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/browser/chrome_browser_main.h"
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/debug/crash_logging.h"
15 #include "base/debug/debugger.h"
16 #include "base/debug/trace_event.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/prefs/json_pref_store.h"
23 #include "base/prefs/pref_registry_simple.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/prefs/pref_value_store.h"
26 #include "base/prefs/scoped_user_pref_update.h"
27 #include "base/process/process_info.h"
28 #include "base/profiler/scoped_tracker.h"
29 #include "base/run_loop.h"
30 #include "base/strings/string_number_conversions.h"
31 #include "base/strings/string_piece.h"
32 #include "base/strings/string_split.h"
33 #include "base/strings/sys_string_conversions.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/sys_info.h"
36 #include "base/threading/platform_thread.h"
37 #include "base/time/time.h"
38 #include "base/values.h"
39 #include "build/build_config.h"
40 #include "chrome/browser/about_flags.h"
41 #include "chrome/browser/browser_process.h"
42 #include "chrome/browser/browser_process_impl.h"
43 #include "chrome/browser/browser_process_platform_part.h"
44 #include "chrome/browser/browser_shutdown.h"
45 #include "chrome/browser/chrome_browser_main_extra_parts.h"
46 #include "chrome/browser/component_updater/cld_component_installer.h"
47 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
48 #include "chrome/browser/component_updater/flash_component_installer.h"
49 #include "chrome/browser/component_updater/recovery_component_installer.h"
50 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
51 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
52 #include "chrome/browser/defaults.h"
53 #include "chrome/browser/first_run/first_run.h"
54 #include "chrome/browser/first_run/upgrade_util.h"
55 #include "chrome/browser/google/google_search_counter.h"
56 #include "chrome/browser/gpu/gl_string_manager.h"
57 #include "chrome/browser/gpu/three_d_api_observer.h"
58 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
59 #include "chrome/browser/metrics/field_trial_synchronizer.h"
60 #include "chrome/browser/metrics/thread_watcher.h"
61 #include "chrome/browser/metrics/variations/variations_service.h"
62 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
63 #include "chrome/browser/net/chrome_net_log.h"
64 #include "chrome/browser/net/crl_set_fetcher.h"
65 #include "chrome/browser/notifications/desktop_notification_service.h"
66 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
67 #include "chrome/browser/performance_monitor/performance_monitor.h"
68 #include "chrome/browser/plugins/plugin_prefs.h"
69 #include "chrome/browser/power/process_power_collector.h"
70 #include "chrome/browser/pref_service_flags_storage.h"
71 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
72 #include "chrome/browser/prefs/command_line_pref_store.h"
73 #include "chrome/browser/prefs/pref_metrics_service.h"
74 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
75 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
76 #include "chrome/browser/process_singleton.h"
77 #include "chrome/browser/profiles/profile.h"
78 #include "chrome/browser/profiles/profile_manager.h"
79 #include "chrome/browser/profiles/profiles_state.h"
80 #include "chrome/browser/shell_integration.h"
81 #include "chrome/browser/translate/translate_service.h"
82 #include "chrome/browser/ui/app_list/app_list_service.h"
83 #include "chrome/browser/ui/browser.h"
84 #include "chrome/browser/ui/browser_finder.h"
85 #include "chrome/browser/ui/host_desktop.h"
86 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
87 #include "chrome/browser/ui/startup/default_browser_prompt.h"
88 #include "chrome/browser/ui/startup/startup_browser_creator.h"
89 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
90 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
91 #include "chrome/common/chrome_constants.h"
92 #include "chrome/common/chrome_paths.h"
93 #include "chrome/common/chrome_result_codes.h"
94 #include "chrome/common/chrome_switches.h"
95 #include "chrome/common/chrome_version_info.h"
96 #include "chrome/common/crash_keys.h"
97 #include "chrome/common/env_vars.h"
98 #include "chrome/common/logging_chrome.h"
99 #include "chrome/common/net/net_resource_provider.h"
100 #include "chrome/common/pref_names.h"
101 #include "chrome/common/profiling.h"
102 #include "chrome/grit/generated_resources.h"
103 #include "chrome/installer/util/google_update_settings.h"
104 #include "components/component_updater/component_updater_service.h"
105 #include "components/google/core/browser/google_util.h"
106 #include "components/language_usage_metrics/language_usage_metrics.h"
107 #include "components/metrics/metrics_service.h"
108 #include "components/metrics/profiler/tracking_synchronizer.h"
109 #include "components/nacl/browser/nacl_browser.h"
110 #include "components/rappor/rappor_service.h"
111 #include "components/signin/core/common/profile_management_switches.h"
112 #include "components/startup_metric_utils/startup_metric_utils.h"
113 #include "components/translate/content/common/cld_data_source.h"
114 #include "components/translate/core/browser/translate_download_manager.h"
115 #include "components/variations/net/variations_http_header_provider.h"
116 #include "content/public/browser/browser_thread.h"
117 #include "content/public/browser/notification_observer.h"
118 #include "content/public/browser/notification_registrar.h"
119 #include "content/public/browser/notification_service.h"
120 #include "content/public/browser/notification_types.h"
121 #include "content/public/browser/site_instance.h"
122 #include "content/public/common/content_client.h"
123 #include "content/public/common/content_switches.h"
124 #include "content/public/common/main_function_params.h"
125 #include "grit/platform_locale_settings.h"
126 #include "net/base/net_module.h"
127 #include "net/base/sdch_manager.h"
128 #include "net/cookies/cookie_monster.h"
129 #include "net/http/http_network_layer.h"
130 #include "net/http/http_stream_factory.h"
131 #include "net/url_request/url_request.h"
132 #include "ui/base/l10n/l10n_util.h"
133 #include "ui/base/layout.h"
134 #include "ui/base/resource/resource_bundle.h"
135 #include "ui/strings/grit/app_locale_settings.h"
137 #if defined(OS_ANDROID)
138 #include "chrome/browser/metrics/thread_watcher_android.h"
140 #include "chrome/browser/feedback/feedback_profile_observer.h"
143 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
144 #include "chrome/browser/first_run/upgrade_util_linux.h"
145 #include "chrome/browser/sxs_linux.h"
148 #if defined(OS_CHROMEOS)
149 #include "chrome/browser/chromeos/settings/cros_settings.h"
150 #include "chromeos/chromeos_switches.h"
151 #include "chromeos/settings/cros_settings_names.h"
154 // TODO(port): several win-only methods have been pulled out of this, but
155 // BrowserMain() as a whole needs to be broken apart so that it's usable by
156 // other platforms. For now, it's just a stub. This is a serious work in
157 // progress and should not be taken as an indication of a real refactoring.
160 #include "base/environment.h" // For PreRead experiment.
161 #include "base/win/windows_version.h"
162 #include "chrome/browser/browser_util_win.h"
163 #include "chrome/browser/chrome_browser_main_win.h"
164 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
165 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
166 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
167 #include "chrome/browser/first_run/upgrade_util_win.h"
168 #include "chrome/browser/ui/network_profile_bubble.h"
169 #include "chrome/installer/util/helper.h"
170 #include "chrome/installer/util/install_util.h"
171 #include "chrome/installer/util/shell_util.h"
172 #include "net/base/net_util.h"
173 #include "ui/base/l10n/l10n_util_win.h"
174 #include "ui/gfx/win/dpi.h"
175 #include "ui/shell_dialogs/select_file_dialog.h"
176 #endif // defined(OS_WIN)
178 #if defined(OS_MACOSX)
179 #include <Security/Security.h>
181 #include "base/mac/scoped_nsautorelease_pool.h"
182 #include "chrome/browser/mac/keystone_glue.h"
186 #include "chrome/browser/ui/app_modal_dialogs/chrome_javascript_native_dialog_factory.h"
189 #if !defined(DISABLE_NACL)
190 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
191 #include "components/nacl/browser/nacl_process_host.h"
194 #if defined(ENABLE_EXTENSIONS)
195 #include "chrome/browser/extensions/startup_helper.h"
196 #include "extensions/browser/extension_protocols.h"
197 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
200 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
201 #include "printing/printed_document.h"
204 #if defined(ENABLE_RLZ)
205 #include "chrome/browser/rlz/rlz.h"
208 #if defined(ENABLE_WEBRTC)
209 #include "chrome/browser/media/webrtc_log_util.h"
212 #if defined(USE_AURA)
213 #include "ui/aura/env.h"
216 using content::BrowserThread;
220 // This function provides some ways to test crash and assertion handling
221 // behavior of the program.
222 void HandleTestParameters(const CommandLine& command_line) {
223 // This parameter causes an assertion.
224 if (command_line.HasSwitch(switches::kBrowserAssertTest)) {
228 // This parameter causes a null pointer crash (crash reporter trigger).
229 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
230 int* bad_pointer = NULL;
235 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
236 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
237 const std::vector<GURL>& new_tabs) {
238 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
239 it != new_tabs.end(); ++it) {
241 browser_creator->AddFirstRunTab(*it);
244 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
246 // Returns the new local state object, guaranteed non-NULL.
247 // |local_state_task_runner| must be a shutdown-blocking task runner.
248 PrefService* InitializeLocalState(
249 base::SequencedTaskRunner* local_state_task_runner,
250 const CommandLine& parsed_command_line) {
251 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
252 base::FilePath local_state_path;
253 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
254 bool local_state_file_exists = base::PathExists(local_state_path);
256 // Load local state. This includes the application locale so we know which
257 // locale dll to load. This also causes local state prefs to be registered.
258 PrefService* local_state = g_browser_process->local_state();
262 if (first_run::IsChromeFirstRun()) {
263 // During first run we read the google_update registry key to find what
264 // language the user selected when downloading the installer. This
265 // becomes our default language in the prefs.
266 // Other platforms obey the system locale.
267 base::string16 install_lang;
268 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
269 local_state->SetString(prefs::kApplicationLocale,
270 base::UTF16ToASCII(install_lang));
273 #endif // defined(OS_WIN)
275 // If the local state file for the current profile doesn't exist and the
276 // parent profile command line flag is present, then we should inherit some
277 // local state from the parent profile.
278 // Checking that the local state file for the current profile doesn't exist
279 // is the most robust way to determine whether we need to inherit or not
280 // since the parent profile command line flag can be present even when the
281 // current profile is not a new one, and in that case we do not want to
282 // inherit and reset the user's setting.
284 // TODO(mnissler): We should probably just instantiate a
285 // JSONPrefStore here instead of an entire PrefService. Once this is
286 // addressed, the call to browser_prefs::RegisterLocalState can move
287 // to chrome_prefs::CreateLocalState.
288 if (!local_state_file_exists &&
289 parsed_command_line.HasSwitch(switches::kParentProfile)) {
290 base::FilePath parent_profile =
291 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
292 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
293 scoped_ptr<PrefService> parent_local_state(
294 chrome_prefs::CreateLocalState(
296 local_state_task_runner,
297 g_browser_process->policy_service(),
300 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
301 // Right now, we only inherit the locale setting from the parent profile.
302 local_state->SetString(
303 prefs::kApplicationLocale,
304 parent_local_state->GetString(prefs::kApplicationLocale));
307 #if defined(OS_CHROMEOS)
308 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
309 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
310 // Ensure that we start with owner's locale.
311 if (!owner_locale.empty() &&
312 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
313 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
314 local_state->SetString(prefs::kApplicationLocale, owner_locale);
322 // Initializes the primary profile, possibly doing some user prompting to pick
323 // a fallback profile. Returns the newly created profile, or NULL if startup
324 // should not continue.
325 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
326 const base::FilePath& user_data_dir,
327 const CommandLine& parsed_command_line) {
328 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
329 base::Time start = base::Time::Now();
330 if (profiles::IsMultipleProfilesEnabled() &&
331 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
332 g_browser_process->local_state()->SetString(prefs::kProfileLastUsed,
333 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
334 // Clear kProfilesLastActive since the user only wants to launch a specific
336 ListPrefUpdate update(g_browser_process->local_state(),
337 prefs::kProfilesLastActive);
338 base::ListValue* profile_list = update.Get();
339 profile_list->Clear();
342 Profile* profile = NULL;
343 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
344 // On ChromeOS and Android the ProfileManager will use the same path as the
345 // one we got passed. GetActiveUserProfile will therefore use the correct path
347 DCHECK_EQ(user_data_dir.value(),
348 g_browser_process->profile_manager()->user_data_dir().value());
349 profile = ProfileManager::GetActiveUserProfile();
351 base::FilePath profile_path =
352 GetStartupProfilePath(user_data_dir, parsed_command_line);
354 // Without NewAvatarMenu, replace guest with any existing profile.
355 if (!switches::IsNewAvatarMenu() &&
356 profile_path == ProfileManager::GetGuestProfilePath()) {
357 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
358 GetPathOfProfileAtIndex(0);
360 profile = g_browser_process->profile_manager()->GetProfile(
363 // If we're using the --new-profile-management flag and this profile is
364 // signed out, then we should show the user manager instead. By switching
365 // the active profile to the guest profile we ensure that no
366 // browser windows will be opened for the guest profile.
367 if (switches::IsNewProfileManagement() && !profile->IsGuestSession()) {
368 ProfileInfoCache& cache =
369 g_browser_process->profile_manager()->GetProfileInfoCache();
370 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
372 if (cache.ProfileIsSigninRequiredAtIndex(profile_index))
373 profile = g_browser_process->profile_manager()->GetProfile(
374 ProfileManager::GetGuestProfilePath());
378 UMA_HISTOGRAM_LONG_TIMES(
379 "Startup.CreateFirstProfile", base::Time::Now() - start);
384 // TODO(port): fix this. See comments near the definition of
385 // user_data_dir. It is better to CHECK-fail here than it is to
386 // silently exit because of missing code in the above test.
387 CHECK(profile) << "Cannot get default profile.";
393 #if defined(OS_MACOSX)
394 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
395 SecKeychainCallbackInfo* info, void* context) {
400 void RegisterComponentsForUpdate() {
401 component_updater::ComponentUpdateService* cus =
402 g_browser_process->component_updater();
404 // Registration can be before or after cus->Start() so it is ok to post
405 // a task to the UI thread to do registration once you done the necessary
406 // file IO to know you existing component version.
407 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
408 RegisterRecoveryComponent(cus, g_browser_process->local_state());
409 RegisterPepperFlashComponent(cus);
410 RegisterSwiftShaderComponent(cus);
411 RegisterWidevineCdmComponent(cus);
414 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
415 #if defined(OS_CHROMEOS)
416 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
417 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
418 // installer when ruining on Linux. See crbug.com/422121 for more details.
419 if (!base::SysInfo::IsRunningOnChromeOS())
421 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
424 if (translate::CldDataSource::ShouldRegisterForComponentUpdates()) {
425 RegisterCldComponent(cus);
429 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
430 #if defined(OS_ANDROID)
431 // The CRLSet component was enabled for some releases. This code attempts to
432 // delete it from the local disk of those how may have downloaded it.
433 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
434 #elif !defined(OS_CHROMEOS)
435 // CRLSetFetcher attempts to load a CRL set from either the local disk or
437 // For Chrome OS this registration is delayed until user login.
438 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
442 #if !defined(OS_ANDROID)
443 // Android does not currently have the EV indicator. No need to get the
444 // EV certs whitelist on Android, then.
445 RegisterEVWhitelistComponent(cus);
449 RegisterSwReporterComponent(cus, g_browser_process->local_state());
455 #if !defined(OS_ANDROID)
456 bool ProcessSingletonNotificationCallback(
457 const CommandLine& command_line,
458 const base::FilePath& current_directory) {
459 // Drop the request if the browser process is already in shutdown path.
460 if (!g_browser_process || g_browser_process->IsShuttingDown())
463 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
464 std::string start_time_string =
465 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
466 int64 remote_start_time;
467 if (base::StringToInt64(start_time_string, &remote_start_time)) {
468 base::TimeDelta elapsed =
469 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
470 if (command_line.HasSwitch(switches::kFastStart)) {
471 UMA_HISTOGRAM_LONG_TIMES(
472 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
474 UMA_HISTOGRAM_LONG_TIMES(
475 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
480 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
483 base::FilePath user_data_dir =
484 g_browser_process->profile_manager()->user_data_dir();
485 base::FilePath startup_profile_dir =
486 GetStartupProfilePath(user_data_dir, command_line);
488 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
489 command_line, current_directory, startup_profile_dir);
492 #endif // !defined(OS_ANDROID)
494 void LaunchDevToolsHandlerIfNeeded(const CommandLine& command_line) {
495 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
496 std::string port_str =
497 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
499 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
500 g_browser_process->CreateDevToolsHttpProtocolHandler(
501 chrome::HOST_DESKTOP_TYPE_NATIVE,
505 DLOG(WARNING) << "Invalid http debugger port number " << port;
510 // Heap allocated class that listens for first page load, kicks off stat
511 // recording and then deletes itself.
512 class LoadCompleteListener : public content::NotificationObserver {
514 LoadCompleteListener() {
516 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
517 content::NotificationService::AllSources());
519 ~LoadCompleteListener() override {}
521 // content::NotificationObserver implementation.
522 void Observe(int type,
523 const content::NotificationSource& source,
524 const content::NotificationDetails& details) override {
525 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
526 startup_metric_utils::OnInitialPageLoadComplete();
531 content::NotificationRegistrar registrar_;
532 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
537 namespace chrome_browser {
539 // This error message is not localized because we failed to load the
540 // localization data files.
542 const char kMissingLocaleDataTitle[] = "Missing File Error";
546 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
547 const char kMissingLocaleDataMessage[] =
548 "Unable to find locale data files. Please reinstall.";
551 } // namespace chrome_browser
553 // BrowserMainParts ------------------------------------------------------------
556 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_ =
559 ChromeBrowserMainParts::ChromeBrowserMainParts(
560 const content::MainFunctionParams& parameters)
561 : parameters_(parameters),
562 parsed_command_line_(parameters.command_line),
563 result_code_(content::RESULT_CODE_NORMAL_EXIT),
564 startup_watcher_(new StartupTimeBomb()),
565 shutdown_watcher_(new ShutdownWatcherHelper()),
566 browser_field_trials_(parameters.command_line),
568 run_message_loop_(true),
569 notify_result_(ProcessSingleton::PROCESS_NONE),
571 restart_last_session_(false) {
572 // If we're running tests (ui_task is non-null).
573 if (parameters.ui_task)
574 browser_defaults::enable_help_app = false;
576 // Chrome disallows cookies by default. All code paths that want to use
577 // cookies need to go through one of Chrome's URLRequestContexts which have
578 // a ChromeNetworkDelegate attached that selectively allows cookies again.
579 if (!disable_enforcing_cookie_policies_for_tests_)
580 net::URLRequest::SetDefaultCookiePolicyToBlock();
583 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
584 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
585 delete chrome_extra_parts_[i];
586 chrome_extra_parts_.clear();
589 // This will be called after the command-line has been mutated by about:flags
590 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
591 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
592 // Must initialize metrics after labs have been converted into switches,
593 // but before field trials are set up (so that client ID is available for
594 // one-time randomized field trials).
596 // Initialize FieldTrialList to support FieldTrials that use one-time
598 metrics::MetricsService* metrics = browser_process_->metrics_service();
599 field_trial_list_.reset(
600 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
602 const CommandLine* command_line = CommandLine::ForCurrentProcess();
603 if (command_line->HasSwitch(switches::kEnableBenchmarking))
604 base::FieldTrial::EnableBenchmarking();
606 // Ensure any field trials specified on the command line are initialized.
607 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
608 std::set<std::string> unforceable_field_trials;
609 #if defined(OFFICIAL_BUILD)
610 unforceable_field_trials.insert("SettingsEnforcement");
611 #endif // defined(OFFICIAL_BUILD)
613 // Create field trials without activating them, so that this behaves in a
614 // consistent manner with field trials created from the server.
615 bool result = base::FieldTrialList::CreateTrialsFromString(
616 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
617 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
618 unforceable_field_trials);
619 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
620 << " list specified.";
622 if (command_line->HasSwitch(switches::kForceVariationIds)) {
623 // Create default variation ids which will always be included in the
624 // X-Client-Data request header.
625 variations::VariationsHttpHeaderProvider* provider =
626 variations::VariationsHttpHeaderProvider::GetInstance();
627 bool result = provider->SetDefaultVariationIds(
628 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
629 CHECK(result) << "Invalid --" << switches::kForceVariationIds
630 << " list specified.";
631 metrics->AddSyntheticTrialObserver(provider);
633 chrome_variations::VariationsService* variations_service =
634 browser_process_->variations_service();
635 if (variations_service)
636 variations_service->CreateTrialsFromSeed();
638 // This must be called after |local_state_| is initialized.
639 browser_field_trials_.SetupFieldTrials(
640 base::Time::FromTimeT(metrics->GetInstallDate()), local_state_);
642 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
643 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
644 // Even though base::Bind does AddRef and Release, the object will not be
645 // deleted after the Task is executed.
646 field_trial_synchronizer_ = new FieldTrialSynchronizer();
648 // Now that field trials have been created, initializes metrics recording.
649 metrics->InitializeMetricsRecordingState();
651 // Enable profiler instrumentation depending on the channel.
652 switch (chrome::VersionInfo::GetChannel()) {
653 case chrome::VersionInfo::CHANNEL_UNKNOWN:
654 case chrome::VersionInfo::CHANNEL_CANARY:
655 tracked_objects::ScopedTracker::Enable();
658 case chrome::VersionInfo::CHANNEL_DEV:
659 case chrome::VersionInfo::CHANNEL_BETA:
660 case chrome::VersionInfo::CHANNEL_STABLE:
661 // Don't enable instrumentation.
666 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
668 void ChromeBrowserMainParts::StartMetricsRecording() {
669 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
670 metrics::MetricsService* metrics = g_browser_process->metrics_service();
672 const bool only_do_metrics_recording =
673 parsed_command_line_.HasSwitch(switches::kMetricsRecordingOnly) ||
674 parsed_command_line_.HasSwitch(switches::kEnableBenchmarking);
675 if (only_do_metrics_recording) {
676 // If we're testing then we don't care what the user preference is, we turn
677 // on recording, but not reporting, otherwise tests fail.
678 metrics->StartRecordingForTests();
682 metrics->CheckForClonedInstall(
683 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
684 const bool metrics_enabled = metrics->StartIfMetricsReportingEnabled();
685 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is
686 // currently disabled there. http://crbug.com/370041
687 browser_process_->rappor_service()->Start(
688 browser_process_->system_request_context(),
692 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
693 // Don't record any metrics if UI was displayed before this point e.g.
695 if (startup_metric_utils::WasNonBrowserUIDisplayed())
698 #if defined(OS_ANDROID)
699 // On Android the first run is handled in Java code, and the C++ side of
700 // Chrome doesn't know if this is the first run. This will cause some
701 // inaccuracy in the UMA statistics, but this should be minor (first runs are
703 bool is_first_run = false;
705 bool is_first_run = first_run::IsChromeFirstRun();
708 // CurrentProcessInfo::CreationTime() is currently only implemented on some
710 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
711 const base::Time process_creation_time =
712 base::CurrentProcessInfo::CreationTime();
714 if (!is_first_run && !process_creation_time.is_null()) {
715 base::TimeDelta delay = base::Time::Now() - process_creation_time;
716 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
718 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
720 // Record collected startup metrics.
721 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
724 new LoadCompleteListener();
727 // -----------------------------------------------------------------------------
728 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
731 #define DLLEXPORT __declspec(dllexport)
733 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
735 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
738 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
739 // Need an instance of AtExitManager to handle singleton creations and
740 // deletions. We need this new instance because, the old instance created
741 // in ChromeMain() got destructed when the function returned.
742 base::AtExitManager exit_manager;
743 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
747 // content::BrowserMainParts implementation ------------------------------------
749 void ChromeBrowserMainParts::PreEarlyInitialization() {
750 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
751 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
752 chrome_extra_parts_[i]->PreEarlyInitialization();
755 void ChromeBrowserMainParts::PostEarlyInitialization() {
756 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
757 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
758 chrome_extra_parts_[i]->PostEarlyInitialization();
761 void ChromeBrowserMainParts::ToolkitInitialized() {
762 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
763 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
764 chrome_extra_parts_[i]->ToolkitInitialized();
767 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
768 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
769 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
770 chrome_extra_parts_[i]->PreMainMessageLoopStart();
773 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
774 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
775 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
776 chrome_extra_parts_[i]->PostMainMessageLoopStart();
779 int ChromeBrowserMainParts::PreCreateThreads() {
780 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
781 result_code_ = PreCreateThreadsImpl();
783 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
784 #if !defined(OS_ANDROID)
785 // These members must be initialized before exiting this function normally.
786 DCHECK(master_prefs_.get());
787 DCHECK(browser_creator_.get());
789 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
790 chrome_extra_parts_[i]->PreCreateThreads();
796 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
797 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
798 run_message_loop_ = false;
799 #if !defined(OS_ANDROID)
800 chrome::MaybeShowInvalidUserDataDirWarningDialog();
802 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
803 return chrome::RESULT_CODE_MISSING_DATA;
805 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
806 MediaCaptureDevicesDispatcher::GetInstance();
808 // Android's first run is done in Java instead of native.
809 #if !defined(OS_ANDROID)
810 process_singleton_.reset(new ChromeProcessSingleton(
811 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
813 // Cache first run state early.
814 first_run::IsChromeFirstRun();
817 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
818 JsonPrefStore::GetTaskRunnerForFile(
819 base::FilePath(chrome::kLocalStorePoolName),
820 BrowserThread::GetBlockingPool());
823 TRACE_EVENT0("startup",
824 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
825 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
826 parsed_command_line()));
829 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
830 TRACE_EVENT0("startup",
831 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
832 // User wants to override default tracking status.
834 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
835 // Default to basic profiling (no parent child support).
836 tracked_objects::ThreadData::Status status =
837 tracked_objects::ThreadData::PROFILING_ACTIVE;
838 if (flag.compare("0") != 0)
839 status = tracked_objects::ThreadData::DEACTIVATED;
840 else if (flag.compare("child") != 0)
841 status = tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE;
842 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
845 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile)) {
846 tracking_objects_.set_output_file_path(
847 parsed_command_line().GetSwitchValuePath(
848 switches::kProfilingOutputFile));
851 local_state_ = InitializeLocalState(
852 local_state_task_runner.get(), parsed_command_line());
854 #if !defined(OS_ANDROID)
855 // These members must be initialized before returning from this function.
856 master_prefs_.reset(new first_run::MasterPrefs);
857 // Android doesn't use StartupBrowserCreator.
858 browser_creator_.reset(new StartupBrowserCreator);
859 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
860 chrome::UMABrowsingActivityObserver::Init();
863 #if !defined(OS_CHROMEOS)
864 // Convert active labs into switches. This needs to be done before
865 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
866 // affected by experiment flags (--touch-optimized-ui in particular).
867 // On ChromeOS system level flags are applied from the device settings from
868 // the session manager.
870 TRACE_EVENT0("startup",
871 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
872 about_flags::PrefServiceFlagsStorage flags_storage_(
873 g_browser_process->local_state());
874 about_flags::ConvertFlagsToSwitches(&flags_storage_,
875 CommandLine::ForCurrentProcess(),
876 about_flags::kAddSentinels);
880 local_state_->UpdateCommandLinePrefStore(
881 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
883 // Reset the command line in the crash report details, since we may have
884 // just changed it to include experiments.
885 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
887 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
888 // needed when loading the MainMenu.nib and the language doesn't depend on
889 // anything since it comes from Cocoa.
890 #if defined(OS_MACOSX)
892 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
893 browser_process_->SetApplicationLocale(locale);
895 const std::string locale =
896 local_state_->GetString(prefs::kApplicationLocale);
898 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
899 // method InitSharedInstance is ignored.
901 TRACE_EVENT_BEGIN0("startup",
902 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
903 const std::string loaded_locale =
904 ui::ResourceBundle::InitSharedInstanceWithLocale(
905 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
906 TRACE_EVENT_END0("startup",
907 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
909 if (loaded_locale.empty() &&
910 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
911 ShowMissingLocaleMessageBox();
912 return chrome::RESULT_CODE_MISSING_DATA;
914 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
915 browser_process_->SetApplicationLocale(loaded_locale);
917 base::FilePath resources_pack_path;
918 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
920 TRACE_EVENT0("startup",
921 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
922 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
923 resources_pack_path, ui::SCALE_FACTOR_NONE);
925 #endif // defined(OS_MACOSX)
927 // Android does first run in Java instead of native.
928 // Chrome OS has its own out-of-box-experience code.
929 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
930 // On first run, we need to process the predictor preferences before the
931 // browser's profile_manager object is created, but after ResourceBundle
933 if (first_run::IsChromeFirstRun()) {
934 first_run::ProcessMasterPreferencesResult pmp_result =
935 first_run::ProcessMasterPreferences(user_data_dir_,
936 master_prefs_.get());
937 if (pmp_result == first_run::EULA_EXIT_NOW)
938 return chrome::RESULT_CODE_EULA_REFUSED;
940 if (!parsed_command_line().HasSwitch(switches::kApp) &&
941 !parsed_command_line().HasSwitch(switches::kAppId) &&
942 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
943 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
946 // TODO(macourteau): refactor preferences that are copied from
947 // master_preferences into local_state, as a "local_state" section in
948 // master preferences. If possible, a generic solution would be preferred
949 // over a copy one-by-one of specific preferences. Also see related TODO
952 // Store the initial VariationsService seed in local state, if it exists
954 if (!master_prefs_->variations_seed.empty()) {
955 local_state_->SetString(prefs::kVariationsSeed,
956 master_prefs_->variations_seed);
957 if (!master_prefs_->variations_seed_signature.empty()) {
958 local_state_->SetString(prefs::kVariationsSeedSignature,
959 master_prefs_->variations_seed_signature);
961 // Set the variation seed date to the current system time. If the user's
962 // clock is incorrect, this may cause some field trial expiry checks to
963 // not do the right thing until the next seed update from the server,
964 // when this value will be updated.
965 local_state_->SetInt64(prefs::kVariationsSeedDate,
966 base::Time::Now().ToInternalValue());
969 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
970 local_state_->SetString(
971 prefs::kBrowserSuppressDefaultBrowserPrompt,
972 master_prefs_->suppress_default_browser_prompt_for_version);
975 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->HandleFirstRun();
979 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
980 // Set the product channel for crash reports.
981 base::debug::SetCrashKeyValue(crash_keys::kChannel,
982 chrome::VersionInfo::GetVersionStringModifier());
985 // Initialize tracking synchronizer system.
986 tracking_synchronizer_ = new metrics::TrackingSynchronizer();
988 #if defined(OS_MACOSX)
989 // Get the Keychain API to register for distributed notifications on the main
990 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
991 // which doesn't. This ensures those notifications will get delivered
992 // properly. See issue 37766.
993 // (Note that the callback mask here is empty. I don't want to register for
994 // any callbacks, I just want to initialize the mechanism.)
995 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
998 #if defined(OS_CHROMEOS)
999 // Must be done after g_browser_process is constructed, before
1000 // SetupMetricsAndFieldTrials().
1001 chromeos::CrosSettings::Initialize();
1004 // Now the command line has been mutated based on about:flags, we can setup
1005 // metrics and initialize field trials. The field trials are needed by
1006 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1007 SetupMetricsAndFieldTrials();
1009 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1010 browser_process_->PreCreateThreads();
1012 return content::RESULT_CODE_NORMAL_EXIT;
1015 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1016 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1017 result_code_ = PreMainMessageLoopRunImpl();
1019 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1020 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1023 // PreMainMessageLoopRun calls these extra stages in the following order:
1024 // PreMainMessageLoopRunImpl()
1025 // ... initial setup, including browser_process_ setup.
1027 // ... additional setup, including CreateProfile()
1028 // PostProfileInit()
1029 // ... additional setup
1030 // PreBrowserStart()
1031 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1032 // PostBrowserStart()
1034 void ChromeBrowserMainParts::PreProfileInit() {
1035 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1037 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1038 chrome_extra_parts_[i]->PreProfileInit();
1040 #if !defined(OS_ANDROID)
1041 // Initialize the feedback uploader so it can setup notifications for profile
1043 feedback::FeedbackProfileObserver::Initialize();
1045 ProfileManager* profile_manager = g_browser_process->profile_manager();
1047 // First check if any ephemeral profiles are left behind because of browser
1048 // crash and schedule them for deletion and then proceed with getting the set
1049 // of profiles to open.
1050 ProfileInfoCache& profile_cache = profile_manager->GetProfileInfoCache();
1051 size_t profiles_count = profile_cache.GetNumberOfProfiles();
1052 std::vector<base::FilePath> profiles_to_delete;
1053 for (size_t i = 0; i < profiles_count; ++i) {
1054 if (profile_cache.ProfileIsEphemeralAtIndex(i))
1055 profiles_to_delete.push_back(profile_cache.GetPathOfProfileAtIndex(i));
1058 if (profiles_to_delete.size()) {
1059 for (size_t i = 0; i < profiles_to_delete.size(); ++i) {
1060 profile_manager->ScheduleProfileForDeletion(
1061 profiles_to_delete[i], ProfileManager::CreateCallback());
1063 // Clean up stale profiles immediately after browser start.
1064 BrowserThread::PostTask(
1065 BrowserThread::FILE, FROM_HERE,
1066 base::Bind(&ProfileManager::CleanUpStaleProfiles, profiles_to_delete));
1068 #endif // OS_ANDROID
1070 #if defined(ENABLE_EXTENSIONS)
1071 InstallJavaScriptDialogExtensionsClient();
1074 #if !defined(OS_IOS)
1075 InstallChromeJavaScriptNativeDialogFactory();
1079 void ChromeBrowserMainParts::PostProfileInit() {
1080 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1081 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1082 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1083 chrome_extra_parts_[i]->PostProfileInit();
1086 void ChromeBrowserMainParts::PreBrowserStart() {
1087 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1088 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1089 chrome_extra_parts_[i]->PreBrowserStart();
1091 three_d_observer_.reset(new ThreeDAPIObserver());
1094 void ChromeBrowserMainParts::PostBrowserStart() {
1095 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1096 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1097 chrome_extra_parts_[i]->PostBrowserStart();
1098 #if !defined(OS_ANDROID)
1099 // Allow ProcessSingleton to process messages.
1100 process_singleton_->Unlock();
1102 #if defined(ENABLE_WEBRTC)
1103 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1104 // to reduce the impact on startup time.
1105 BrowserThread::PostDelayedTask(
1108 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1109 base::TimeDelta::FromMinutes(1));
1113 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1114 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1115 // Android updates the metrics service dynamically depending on whether the
1116 // application is in the foreground or not. Do not start here.
1117 #if !defined(OS_ANDROID)
1118 // Now that the file thread has been started, start recording.
1119 StartMetricsRecording();
1122 if (!base::debug::BeingDebugged()) {
1123 // Create watchdog thread after creating all other threads because it will
1124 // watch the other threads and they must be running.
1125 browser_process_->watchdog_thread();
1128 // Do any initializating in the browser process that requires all threads
1130 browser_process_->PreMainMessageLoopRun();
1132 // Record last shutdown time into a histogram.
1133 browser_shutdown::ReadLastShutdownInfo();
1136 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1137 // tasks. Those care whether the browser is already running. On Linux/Mac,
1138 // upgrade/uninstall happen separately.
1139 bool already_running = browser_util::IsBrowserAlreadyRunning();
1141 // If the command line specifies 'uninstall' then we need to work here
1142 // unless we detect another chrome browser running.
1143 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1144 return DoUninstallTasks(already_running);
1147 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1148 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1149 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1150 parsed_command_line_);
1153 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1154 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1157 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1158 return ShellIntegration::SetAsDefaultBrowser() ?
1159 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1160 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1163 #if defined(USE_AURA)
1164 // Make sure aura::Env has been initialized.
1165 CHECK(aura::Env::GetInstance());
1168 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1169 #if !defined(OS_ANDROID)
1170 // If the command line specifies --pack-extension, attempt the pack extension
1171 // startup action and exit.
1172 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1173 extensions::StartupHelper extension_startup_helper;
1174 if (extension_startup_helper.PackExtension(parsed_command_line()))
1175 return content::RESULT_CODE_NORMAL_EXIT;
1176 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1179 // If we're being launched just to check the connector policy, we are
1180 // short-lived and don't want to be passing that switch off.
1181 bool pass_command_line = !parsed_command_line().HasSwitch(
1182 switches::kCheckCloudPrintConnectorPolicy);
1184 if (pass_command_line) {
1185 // When another process is running, use that process instead of starting a
1186 // new one. NotifyOtherProcess will currently give the other process up to
1187 // 20 seconds to respond. Note that this needs to be done before we attempt
1188 // to read the profile.
1189 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1190 switch (notify_result_) {
1191 case ProcessSingleton::PROCESS_NONE:
1192 // No process already running, fall through to starting a new one.
1195 case ProcessSingleton::PROCESS_NOTIFIED:
1196 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1197 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1198 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1200 // Having a differentiated return type for testing allows for tests to
1201 // verify proper handling of some switches. When not testing, stick to
1202 // the standard Unix convention of returning zero when things went as
1204 if (parsed_command_line().HasSwitch(switches::kTestType))
1205 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1206 return content::RESULT_CODE_NORMAL_EXIT;
1208 case ProcessSingleton::PROFILE_IN_USE:
1209 return chrome::RESULT_CODE_PROFILE_IN_USE;
1211 case ProcessSingleton::LOCK_ERROR:
1212 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1213 "directory. This means that running multiple instances "
1214 "would start multiple browser processes rather than "
1215 "opening a new window in the existing process. Aborting "
1216 "now to avoid profile corruption.";
1217 return chrome::RESULT_CODE_PROFILE_IN_USE;
1223 #endif // !defined(OS_ANDROID)
1225 // Handle special early return paths (which couldn't be processed even earlier
1226 // as they require the process singleton to be held) first.
1228 std::string try_chrome =
1229 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1230 if (!try_chrome.empty()) {
1232 // Setup.exe has determined that we need to run a retention experiment
1233 // and has lauched chrome to show the experiment UI. It is guaranteed that
1234 // no other Chrome is currently running as the process singleton was
1235 // sucessfully grabbed above.
1237 base::StringToInt(try_chrome, &try_chrome_int);
1238 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1240 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1241 base::Unretained(process_singleton_.get())));
1242 if (answer == TryChromeDialogView::NOT_NOW)
1243 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1244 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1245 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1246 // At this point the user is willing to try chrome again.
1247 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1248 // Only set in the unattended case, the interactive case is Windows 8.
1249 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1250 ShellIntegration::SET_DEFAULT_UNATTENDED)
1251 ShellIntegration::SetAsDefaultBrowser();
1254 // We don't support retention experiments on Mac or Linux.
1255 return content::RESULT_CODE_NORMAL_EXIT;
1256 #endif // defined(OS_WIN)
1260 // Do the tasks if chrome has been upgraded while it was last running.
1261 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1262 return content::RESULT_CODE_NORMAL_EXIT;
1264 // Check if there is any machine level Chrome installed on the current
1265 // machine. If yes and the current Chrome process is user level, we do not
1266 // allow the user level Chrome to run. So we notify the user and uninstall
1267 // user level Chrome.
1268 // Note this check needs to happen here (after the process singleton was
1269 // obtained but before potentially creating the first run sentinel).
1270 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1271 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1272 #endif // defined(OS_WIN)
1274 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1275 if (sxs_linux::ShouldMigrateUserDataDir())
1276 return sxs_linux::MigrateUserDataDir();
1277 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1279 // Desktop construction occurs here, (required before profile creation).
1282 // Profile creation ----------------------------------------------------------
1284 metrics::MetricsService::SetExecutionPhase(
1285 metrics::MetricsService::CREATE_PROFILE,
1286 g_browser_process->local_state());
1287 profile_ = CreatePrimaryProfile(parameters(),
1289 parsed_command_line());
1291 return content::RESULT_CODE_NORMAL_EXIT;
1293 #if !defined(OS_ANDROID)
1294 // The first run sentinel must be created after the process singleton was
1295 // grabbed and no early return paths were otherwise hit above.
1296 first_run::CreateSentinelIfNeeded();
1297 #endif // !defined(OS_ANDROID)
1299 #if defined(ENABLE_BACKGROUND)
1300 // Autoload any profiles which are running background apps.
1301 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1302 browser_process_->profile_manager()->AutoloadProfiles();
1304 // Post-profile init ---------------------------------------------------------
1306 TranslateService::Initialize();
1308 // Needs to be done before PostProfileInit, since login manager on CrOS is
1309 // called inside PostProfileInit.
1310 content::WebUIControllerFactory::RegisterFactory(
1311 ChromeWebUIControllerFactory::GetInstance());
1313 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1314 // So make sure to create it before that.
1315 #if !defined(DISABLE_NACL)
1316 NaClBrowserDelegateImpl* delegate =
1317 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1318 nacl::NaClBrowser::SetDelegate(delegate);
1321 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1322 // (requires supporting early exit).
1325 // Retrieve cached GL strings from local state and use them for GPU
1326 // blacklist decisions.
1327 if (g_browser_process->gl_string_manager())
1328 g_browser_process->gl_string_manager()->Initialize();
1330 // Create an instance of GpuModeManager to watch gpu mode pref change.
1331 g_browser_process->gpu_mode_manager();
1333 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1334 // Show the First Run UI if this is the first time Chrome has been run on
1335 // this computer, or we're being compelled to do so by a command line flag.
1336 // Note that this be done _after_ the PrefService is initialized and all
1337 // preferences are registered, since some of the code that the importer
1338 // touches reads preferences.
1339 if (first_run::IsChromeFirstRun()) {
1340 first_run::AutoImport(profile_,
1341 master_prefs_->homepage_defined,
1342 master_prefs_->do_import_items,
1343 master_prefs_->dont_import_items,
1344 master_prefs_->import_bookmarks_path);
1346 // Note: this can pop the first run consent dialog on linux.
1347 first_run::DoPostImportTasks(profile_,
1348 master_prefs_->make_chrome_default_for_user);
1350 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1351 browser_creator_->set_show_main_browser_window(
1352 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1354 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1357 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1360 // Sets things up so that if we crash from this point on, a dialog will
1361 // popup asking the user to restart chrome. It is done this late to avoid
1362 // testing against a bunch of special cases that are taken care early on.
1363 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1364 parsed_command_line());
1366 // Registers Chrome with the Windows Restart Manager, which will restore the
1367 // Chrome session when the computer is restarted after a system update.
1368 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1369 // but should run on startup if extended to handle crashes/hangs/patches.
1370 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1371 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1372 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1373 parsed_command_line());
1376 // Verify that the profile is not on a network share and if so prepare to show
1377 // notification to the user.
1378 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1379 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1380 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1381 profile_->GetPath()));
1385 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1386 // Init the RLZ library. This just binds the dll and schedules a task on the
1387 // file thread to be run sometime later. If this is the first run we record
1388 // the installation event.
1389 PrefService* pref_service = profile_->GetPrefs();
1390 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1391 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1392 // Negative ping delay means to send ping immediately after a first search is
1394 RLZTracker::InitRlzFromProfileDelayed(
1395 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1396 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1397 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1399 // Configure modules that need access to resources.
1400 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1402 // In unittest mode, this will do nothing. In normal mode, this will create
1403 // the global IntranetRedirectDetector instance, which will promptly go to
1404 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1405 // to see if it should do anything else.
1407 // A simpler way of doing all this would be to have some function which could
1408 // give the time elapsed since startup, and simply have this object check that
1409 // when asked to initialize itself, but this doesn't seem to exist.
1411 // This can't be created in the BrowserProcessImpl constructor because it
1412 // needs to read prefs that get set after that runs.
1413 browser_process_->intranet_redirect_detector();
1414 GoogleSearchCounter::RegisterForNotifications();
1416 // Check SDCH field trial. Default is now that everything is enabled,
1417 // so provide options for disabling HTTPS or all of SDCH.
1418 const char kSdchFieldTrialName[] = "SDCH";
1419 const char kEnabledHttpOnlyGroupName[] = "EnabledHttpOnly";
1420 const char kDisabledAllGroupName[] = "DisabledAll";
1422 // Store in a string on return to keep underlying storage for
1423 // StringPiece stable.
1424 std::string sdch_trial_group_string =
1425 base::FieldTrialList::FindFullName(kSdchFieldTrialName);
1426 base::StringPiece sdch_trial_group(sdch_trial_group_string);
1427 if (sdch_trial_group.starts_with(kEnabledHttpOnlyGroupName)) {
1428 net::SdchManager::EnableSdchSupport(true);
1429 net::SdchManager::EnableSecureSchemeSupport(false);
1430 } else if (sdch_trial_group.starts_with(kDisabledAllGroupName)) {
1431 net::SdchManager::EnableSdchSupport(false);
1434 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1435 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1436 base::FilePath path =
1437 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1438 printing::PrintedDocument::set_debug_dump_path(path);
1442 HandleTestParameters(parsed_command_line());
1443 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1444 base::debug::BeingDebugged());
1446 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1447 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1448 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1449 browser_process_->GetApplicationLocale());
1451 // Start watching for hangs during startup. We disarm this hang detector when
1452 // ThreadWatcher takes over or when browser is shutdown or when
1453 // startup_watcher_ is deleted.
1454 metrics::MetricsService::SetExecutionPhase(
1455 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1456 g_browser_process->local_state());
1457 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1459 // On mobile, need for clean shutdown arises only when the application comes
1460 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1461 // http://crbug.com/179143
1462 #if !defined(OS_ANDROID)
1463 // Start watching for a hang.
1464 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1467 #if defined(ENABLE_PRINT_PREVIEW)
1468 // Create the instance of the cloud print proxy service so that it can launch
1469 // the service process if needed. This is needed because the service process
1470 // might have shutdown because an update was available.
1471 // TODO(torne): this should maybe be done with
1472 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1474 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1477 // Start watching all browser threads for responsiveness.
1478 metrics::MetricsService::SetExecutionPhase(
1479 metrics::MetricsService::THREAD_WATCHER_START,
1480 g_browser_process->local_state());
1481 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1483 #if defined(OS_ANDROID)
1484 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1487 #if !defined(DISABLE_NACL)
1488 BrowserThread::PostTask(
1491 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1494 // Make sure initial prefs are recorded
1495 PrefMetricsService::Factory::GetForProfile(profile_);
1499 // Instantiate the notification UI manager, as this triggers a perf timer
1500 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1501 // triggering the timer and call that explicitly in the approprate place.
1502 // http://crbug.com/105065.
1503 browser_process_->notification_ui_manager();
1505 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1506 RegisterComponentsForUpdate();
1508 #if defined(OS_ANDROID)
1509 chrome_variations::VariationsService* variations_service =
1510 browser_process_->variations_service();
1511 if (variations_service) {
1512 variations_service->set_policy_pref_service(profile_->GetPrefs());
1513 variations_service->StartRepeatedVariationsSeedFetch();
1515 translate::TranslateDownloadManager::RequestLanguageList(
1516 profile_->GetPrefs());
1519 // Most general initialization is behind us, but opening a
1520 // tab and/or session restore and such is still to be done.
1521 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1523 // We are in regular browser boot sequence. Open initial tabs and enter the
1524 // main message loop.
1526 #if defined(OS_CHROMEOS)
1527 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1528 // them this early as the cryptohome hasn't yet been mounted (which happens
1529 // only once we log in.
1530 std::vector<Profile*> last_opened_profiles;
1532 std::vector<Profile*> last_opened_profiles =
1533 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1536 if (browser_creator_->Start(parsed_command_line(), base::FilePath(),
1537 profile_, last_opened_profiles, &result_code)) {
1538 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1539 // Initialize autoupdate timer. Timer callback costs basically nothing
1540 // when browser is not in persistent mode, so it's OK to let it ride on
1541 // the main thread. This needs to be done here because we don't want
1542 // to start the timer when Chrome is run inside a test harness.
1543 browser_process_->StartAutoupdateTimer();
1546 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1547 // On Linux, the running exe will be updated if an upgrade becomes
1548 // available while the browser is running. We need to save the last
1549 // modified time of the exe, so we can compare to determine if there is
1550 // an upgrade while the browser is kept alive by a persistent extension.
1551 upgrade_util::SaveLastModifiedTimeOfExe();
1554 // Record now as the last successful chrome start.
1555 GoogleUpdateSettings::SetLastRunTime();
1557 #if defined(OS_MACOSX)
1558 // Call Recycle() here as late as possible, before going into the loop
1559 // because Start() will add things to it while creating the main window.
1560 if (parameters().autorelease_pool)
1561 parameters().autorelease_pool->Recycle();
1564 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1565 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1567 // If we're running tests (ui_task is non-null), then we don't want to
1568 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1569 // RequestLanguageList
1570 if (parameters().ui_task == NULL) {
1571 // Request new variations seed information from server.
1572 chrome_variations::VariationsService* variations_service =
1573 browser_process_->variations_service();
1574 if (variations_service) {
1575 variations_service->StartRepeatedVariationsSeedFetch();
1578 variations_service->StartGoogleUpdateRegistrySync();
1582 translate::TranslateDownloadManager::RequestLanguageList(
1583 profile_->GetPrefs());
1586 run_message_loop_ = true;
1588 run_message_loop_ = false;
1590 browser_creator_.reset();
1592 process_power_collector_.reset(new ProcessPowerCollector);
1593 process_power_collector_->Initialize();
1594 #endif // !defined(OS_ANDROID)
1598 if (parameters().ui_task) {
1599 parameters().ui_task->Run();
1600 delete parameters().ui_task;
1601 run_message_loop_ = false;
1603 #if defined(OS_ANDROID)
1604 // We never run the C++ main loop on Android, since the UI thread message
1605 // loop is controlled by the OS, so this is as close as we can get to
1606 // the start of the main loop
1607 if (result_code_ <= 0) {
1608 RecordBrowserStartupTime();
1611 return result_code_;
1614 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1615 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1616 #if defined(OS_ANDROID)
1617 // Chrome on Android does not use default MessageLoop. It has its own
1618 // Android specific MessageLoop
1622 // Set the result code set in PreMainMessageLoopRun or set above.
1623 *result_code = result_code_;
1624 if (!run_message_loop_)
1625 return true; // Don't run the default message loop.
1627 // These should be invoked as close to the start of the browser's
1628 // UI thread message loop as possible to get a stable measurement
1630 RecordBrowserStartupTime();
1632 DCHECK(base::MessageLoopForUI::IsCurrent());
1633 base::RunLoop run_loop;
1635 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1637 metrics::MetricsService::SetExecutionPhase(
1638 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1639 g_browser_process->local_state());
1646 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1647 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1648 #if defined(OS_ANDROID)
1649 // Chrome on Android does not use default MessageLoop. It has its own
1650 // Android specific MessageLoop
1654 // Start watching for jank during shutdown. It gets disarmed when
1655 // |shutdown_watcher_| object is destructed.
1656 metrics::MetricsService::SetExecutionPhase(
1657 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1658 g_browser_process->local_state());
1659 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1661 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1662 startup_watcher_->Disarm();
1664 // Remove observers attached to D-Bus clients before DbusThreadManager is
1666 process_power_collector_.reset();
1668 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1669 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1671 // Some tests don't set parameters.ui_task, so they started translate
1672 // language fetch that was never completed so we need to cleanup here
1673 // otherwise it will be done by the destructor in a wrong thread.
1674 TranslateService::Shutdown(parameters().ui_task == NULL);
1676 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1677 process_singleton_->Cleanup();
1679 // Stop all tasks that might run on WatchDogThread.
1680 ThreadWatcherList::StopWatchingAll();
1682 browser_process_->metrics_service()->Stop();
1684 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1685 browser_process_->StartTearDown();
1689 void ChromeBrowserMainParts::PostDestroyThreads() {
1690 #if defined(OS_ANDROID)
1691 // On Android, there is no quit/exit. So the browser's main message loop will
1695 browser_process_->PostDestroyThreads();
1696 // browser_shutdown takes care of deleting browser_process, so we need to
1698 ignore_result(browser_process_.release());
1699 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1700 master_prefs_.reset();
1701 process_singleton_.reset();
1703 // We need to do this check as late as possible, but due to modularity, this
1704 // may be the last point in Chrome. This would be more effective if done at
1705 // a higher level on the stack, so that it is impossible for an early return
1706 // to bypass this code. Perhaps we need a *final* hook that is called on all
1707 // paths from content/browser/browser_main.
1708 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1710 #if defined(OS_CHROMEOS)
1711 chromeos::CrosSettings::Shutdown();
1718 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1719 chrome_extra_parts_.push_back(parts);