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/run_loop.h"
29 #include "base/strings/string_number_conversions.h"
30 #include "base/strings/string_piece.h"
31 #include "base/strings/string_split.h"
32 #include "base/strings/sys_string_conversions.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/sys_info.h"
35 #include "base/threading/platform_thread.h"
36 #include "base/time/time.h"
37 #include "base/values.h"
38 #include "build/build_config.h"
39 #include "chrome/browser/about_flags.h"
40 #include "chrome/browser/browser_process.h"
41 #include "chrome/browser/browser_process_impl.h"
42 #include "chrome/browser/browser_process_platform_part.h"
43 #include "chrome/browser/browser_shutdown.h"
44 #include "chrome/browser/chrome_browser_main_extra_parts.h"
45 #include "chrome/browser/component_updater/cld_component_installer.h"
46 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
47 #include "chrome/browser/component_updater/flash_component_installer.h"
48 #include "chrome/browser/component_updater/recovery_component_installer.h"
49 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
50 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
51 #include "chrome/browser/defaults.h"
52 #include "chrome/browser/first_run/first_run.h"
53 #include "chrome/browser/first_run/upgrade_util.h"
54 #include "chrome/browser/google/google_search_counter.h"
55 #include "chrome/browser/gpu/gl_string_manager.h"
56 #include "chrome/browser/gpu/three_d_api_observer.h"
57 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
58 #include "chrome/browser/metrics/field_trial_synchronizer.h"
59 #include "chrome/browser/metrics/thread_watcher.h"
60 #include "chrome/browser/metrics/variations/variations_service.h"
61 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
62 #include "chrome/browser/net/chrome_net_log.h"
63 #include "chrome/browser/net/crl_set_fetcher.h"
64 #include "chrome/browser/notifications/desktop_notification_service.h"
65 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
66 #include "chrome/browser/performance_monitor/performance_monitor.h"
67 #include "chrome/browser/plugins/plugin_prefs.h"
68 #include "chrome/browser/power/process_power_collector.h"
69 #include "chrome/browser/pref_service_flags_storage.h"
70 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
71 #include "chrome/browser/prefs/command_line_pref_store.h"
72 #include "chrome/browser/prefs/pref_metrics_service.h"
73 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
74 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
75 #include "chrome/browser/process_singleton.h"
76 #include "chrome/browser/profiles/profile.h"
77 #include "chrome/browser/profiles/profile_manager.h"
78 #include "chrome/browser/profiles/profiles_state.h"
79 #include "chrome/browser/shell_integration.h"
80 #include "chrome/browser/translate/translate_service.h"
81 #include "chrome/browser/ui/app_list/app_list_service.h"
82 #include "chrome/browser/ui/browser.h"
83 #include "chrome/browser/ui/browser_finder.h"
84 #include "chrome/browser/ui/host_desktop.h"
85 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
86 #include "chrome/browser/ui/startup/default_browser_prompt.h"
87 #include "chrome/browser/ui/startup/startup_browser_creator.h"
88 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
89 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
90 #include "chrome/common/chrome_constants.h"
91 #include "chrome/common/chrome_paths.h"
92 #include "chrome/common/chrome_result_codes.h"
93 #include "chrome/common/chrome_switches.h"
94 #include "chrome/common/crash_keys.h"
95 #include "chrome/common/env_vars.h"
96 #include "chrome/common/logging_chrome.h"
97 #include "chrome/common/net/net_resource_provider.h"
98 #include "chrome/common/pref_names.h"
99 #include "chrome/common/profiling.h"
100 #include "chrome/grit/generated_resources.h"
101 #include "chrome/installer/util/google_update_settings.h"
102 #include "components/component_updater/component_updater_service.h"
103 #include "components/google/core/browser/google_util.h"
104 #include "components/language_usage_metrics/language_usage_metrics.h"
105 #include "components/metrics/metrics_service.h"
106 #include "components/metrics/profiler/tracking_synchronizer.h"
107 #include "components/nacl/browser/nacl_browser.h"
108 #include "components/rappor/rappor_service.h"
109 #include "components/signin/core/common/profile_management_switches.h"
110 #include "components/startup_metric_utils/startup_metric_utils.h"
111 #include "components/translate/content/common/cld_data_source.h"
112 #include "components/translate/core/browser/translate_download_manager.h"
113 #include "components/variations/net/variations_http_header_provider.h"
114 #include "content/public/browser/browser_thread.h"
115 #include "content/public/browser/notification_observer.h"
116 #include "content/public/browser/notification_registrar.h"
117 #include "content/public/browser/notification_service.h"
118 #include "content/public/browser/notification_types.h"
119 #include "content/public/browser/site_instance.h"
120 #include "content/public/common/content_client.h"
121 #include "content/public/common/content_switches.h"
122 #include "content/public/common/main_function_params.h"
123 #include "grit/platform_locale_settings.h"
124 #include "net/base/net_module.h"
125 #include "net/base/sdch_manager.h"
126 #include "net/cookies/cookie_monster.h"
127 #include "net/http/http_network_layer.h"
128 #include "net/http/http_stream_factory.h"
129 #include "net/url_request/url_request.h"
130 #include "ui/base/l10n/l10n_util.h"
131 #include "ui/base/layout.h"
132 #include "ui/base/resource/resource_bundle.h"
133 #include "ui/strings/grit/app_locale_settings.h"
135 #if defined(OS_ANDROID)
136 #include "chrome/browser/metrics/thread_watcher_android.h"
138 #include "chrome/browser/feedback/feedback_profile_observer.h"
141 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
142 #include "chrome/browser/first_run/upgrade_util_linux.h"
143 #include "chrome/browser/sxs_linux.h"
146 #if defined(OS_CHROMEOS)
147 #include "chrome/browser/chromeos/settings/cros_settings.h"
148 #include "chromeos/chromeos_switches.h"
149 #include "chromeos/settings/cros_settings_names.h"
152 // TODO(port): several win-only methods have been pulled out of this, but
153 // BrowserMain() as a whole needs to be broken apart so that it's usable by
154 // other platforms. For now, it's just a stub. This is a serious work in
155 // progress and should not be taken as an indication of a real refactoring.
158 #include "base/environment.h" // For PreRead experiment.
159 #include "base/win/windows_version.h"
160 #include "chrome/browser/browser_util_win.h"
161 #include "chrome/browser/chrome_browser_main_win.h"
162 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
163 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
164 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
165 #include "chrome/browser/first_run/upgrade_util_win.h"
166 #include "chrome/browser/ui/network_profile_bubble.h"
167 #include "chrome/installer/util/helper.h"
168 #include "chrome/installer/util/install_util.h"
169 #include "chrome/installer/util/shell_util.h"
170 #include "net/base/net_util.h"
171 #include "ui/base/l10n/l10n_util_win.h"
172 #include "ui/gfx/win/dpi.h"
173 #include "ui/shell_dialogs/select_file_dialog.h"
174 #endif // defined(OS_WIN)
176 #if defined(OS_MACOSX)
177 #include <Security/Security.h>
179 #include "base/mac/scoped_nsautorelease_pool.h"
180 #include "chrome/browser/mac/keystone_glue.h"
183 #if !defined(DISABLE_NACL)
184 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
185 #include "components/nacl/browser/nacl_process_host.h"
188 #if defined(ENABLE_EXTENSIONS)
189 #include "chrome/browser/extensions/startup_helper.h"
190 #include "extensions/browser/extension_protocols.h"
193 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
194 #include "printing/printed_document.h"
197 #if defined(ENABLE_RLZ)
198 #include "chrome/browser/rlz/rlz.h"
201 #if defined(ENABLE_WEBRTC)
202 #include "chrome/browser/media/webrtc_log_util.h"
205 #if defined(USE_AURA)
206 #include "ui/aura/env.h"
209 using content::BrowserThread
;
213 // This function provides some ways to test crash and assertion handling
214 // behavior of the program.
215 void HandleTestParameters(const CommandLine
& command_line
) {
216 // This parameter causes an assertion.
217 if (command_line
.HasSwitch(switches::kBrowserAssertTest
)) {
221 // This parameter causes a null pointer crash (crash reporter trigger).
222 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
223 int* bad_pointer
= NULL
;
228 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
229 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
230 const std::vector
<GURL
>& new_tabs
) {
231 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
232 it
!= new_tabs
.end(); ++it
) {
234 browser_creator
->AddFirstRunTab(*it
);
237 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
239 // Returns the new local state object, guaranteed non-NULL.
240 // |local_state_task_runner| must be a shutdown-blocking task runner.
241 PrefService
* InitializeLocalState(
242 base::SequencedTaskRunner
* local_state_task_runner
,
243 const CommandLine
& parsed_command_line
) {
244 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
245 base::FilePath local_state_path
;
246 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
247 bool local_state_file_exists
= base::PathExists(local_state_path
);
249 // Load local state. This includes the application locale so we know which
250 // locale dll to load. This also causes local state prefs to be registered.
251 PrefService
* local_state
= g_browser_process
->local_state();
255 if (first_run::IsChromeFirstRun()) {
256 // During first run we read the google_update registry key to find what
257 // language the user selected when downloading the installer. This
258 // becomes our default language in the prefs.
259 // Other platforms obey the system locale.
260 base::string16 install_lang
;
261 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
262 local_state
->SetString(prefs::kApplicationLocale
,
263 base::UTF16ToASCII(install_lang
));
266 #endif // defined(OS_WIN)
268 // If the local state file for the current profile doesn't exist and the
269 // parent profile command line flag is present, then we should inherit some
270 // local state from the parent profile.
271 // Checking that the local state file for the current profile doesn't exist
272 // is the most robust way to determine whether we need to inherit or not
273 // since the parent profile command line flag can be present even when the
274 // current profile is not a new one, and in that case we do not want to
275 // inherit and reset the user's setting.
277 // TODO(mnissler): We should probably just instantiate a
278 // JSONPrefStore here instead of an entire PrefService. Once this is
279 // addressed, the call to browser_prefs::RegisterLocalState can move
280 // to chrome_prefs::CreateLocalState.
281 if (!local_state_file_exists
&&
282 parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
283 base::FilePath parent_profile
=
284 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
285 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
286 scoped_ptr
<PrefService
> parent_local_state(
287 chrome_prefs::CreateLocalState(
289 local_state_task_runner
,
290 g_browser_process
->policy_service(),
293 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
294 // Right now, we only inherit the locale setting from the parent profile.
295 local_state
->SetString(
296 prefs::kApplicationLocale
,
297 parent_local_state
->GetString(prefs::kApplicationLocale
));
300 #if defined(OS_CHROMEOS)
301 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
302 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
303 // Ensure that we start with owner's locale.
304 if (!owner_locale
.empty() &&
305 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
306 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
307 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
315 // Initializes the primary profile, possibly doing some user prompting to pick
316 // a fallback profile. Returns the newly created profile, or NULL if startup
317 // should not continue.
318 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
319 const base::FilePath
& user_data_dir
,
320 const CommandLine
& parsed_command_line
) {
321 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
322 base::Time start
= base::Time::Now();
323 if (profiles::IsMultipleProfilesEnabled() &&
324 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
325 g_browser_process
->local_state()->SetString(prefs::kProfileLastUsed
,
326 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
327 // Clear kProfilesLastActive since the user only wants to launch a specific
329 ListPrefUpdate
update(g_browser_process
->local_state(),
330 prefs::kProfilesLastActive
);
331 base::ListValue
* profile_list
= update
.Get();
332 profile_list
->Clear();
335 Profile
* profile
= NULL
;
336 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
337 // On ChromeOS and Android the ProfileManager will use the same path as the
338 // one we got passed. GetActiveUserProfile will therefore use the correct path
340 DCHECK_EQ(user_data_dir
.value(),
341 g_browser_process
->profile_manager()->user_data_dir().value());
342 profile
= ProfileManager::GetActiveUserProfile();
344 base::FilePath profile_path
=
345 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
347 // Without NewAvatarMenu, replace guest with any existing profile.
348 if (!switches::IsNewAvatarMenu() &&
349 profile_path
== ProfileManager::GetGuestProfilePath()) {
350 profile_path
= g_browser_process
->profile_manager()->GetProfileInfoCache().
351 GetPathOfProfileAtIndex(0);
353 profile
= g_browser_process
->profile_manager()->GetProfile(
356 // If we're using the --new-profile-management flag and this profile is
357 // signed out, then we should show the user manager instead. By switching
358 // the active profile to the guest profile we ensure that no
359 // browser windows will be opened for the guest profile.
360 if (switches::IsNewProfileManagement() && !profile
->IsGuestSession()) {
361 ProfileInfoCache
& cache
=
362 g_browser_process
->profile_manager()->GetProfileInfoCache();
363 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
365 if (cache
.ProfileIsSigninRequiredAtIndex(profile_index
))
366 profile
= g_browser_process
->profile_manager()->GetProfile(
367 ProfileManager::GetGuestProfilePath());
371 UMA_HISTOGRAM_LONG_TIMES(
372 "Startup.CreateFirstProfile", base::Time::Now() - start
);
377 // TODO(port): fix this. See comments near the definition of
378 // user_data_dir. It is better to CHECK-fail here than it is to
379 // silently exit because of missing code in the above test.
380 CHECK(profile
) << "Cannot get default profile.";
386 #if defined(OS_MACOSX)
387 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
388 SecKeychainCallbackInfo
* info
, void* context
) {
393 void RegisterComponentsForUpdate() {
394 component_updater::ComponentUpdateService
* cus
=
395 g_browser_process
->component_updater();
397 // Registration can be before or after cus->Start() so it is ok to post
398 // a task to the UI thread to do registration once you done the necessary
399 // file IO to know you existing component version.
400 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
401 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
402 RegisterPepperFlashComponent(cus
);
403 RegisterSwiftShaderComponent(cus
);
404 RegisterWidevineCdmComponent(cus
);
407 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
408 #if defined(OS_CHROMEOS)
409 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
410 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
411 // installer when ruining on Linux. See crbug.com/422121 for more details.
412 if (!base::SysInfo::IsRunningOnChromeOS())
414 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
417 if (translate::CldDataSource::ShouldRegisterForComponentUpdates()) {
418 RegisterCldComponent(cus
);
422 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
423 #if defined(OS_ANDROID)
424 // The CRLSet component was enabled for some releases. This code attempts to
425 // delete it from the local disk of those how may have downloaded it.
426 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
427 #elif !defined(OS_CHROMEOS)
428 // CRLSetFetcher attempts to load a CRL set from either the local disk or
430 // For Chrome OS this registration is delayed until user login.
431 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
435 #if !defined(OS_ANDROID)
436 // Android does not currently have the EV indicator. No need to get the
437 // EV certs whitelist on Android, then.
438 RegisterEVWhitelistComponent(cus
);
442 RegisterSwReporterComponent(cus
, g_browser_process
->local_state());
448 #if !defined(OS_ANDROID)
449 bool ProcessSingletonNotificationCallback(
450 const CommandLine
& command_line
,
451 const base::FilePath
& current_directory
) {
452 // Drop the request if the browser process is already in shutdown path.
453 if (!g_browser_process
|| g_browser_process
->IsShuttingDown())
456 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
457 std::string start_time_string
=
458 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
459 int64 remote_start_time
;
460 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
461 base::TimeDelta elapsed
=
462 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
463 if (command_line
.HasSwitch(switches::kFastStart
)) {
464 UMA_HISTOGRAM_LONG_TIMES(
465 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
467 UMA_HISTOGRAM_LONG_TIMES(
468 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
473 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
476 base::FilePath user_data_dir
=
477 g_browser_process
->profile_manager()->user_data_dir();
478 base::FilePath startup_profile_dir
=
479 GetStartupProfilePath(user_data_dir
, command_line
);
481 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
482 command_line
, current_directory
, startup_profile_dir
);
485 #endif // !defined(OS_ANDROID)
487 void LaunchDevToolsHandlerIfNeeded(const CommandLine
& command_line
) {
488 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
489 std::string port_str
=
490 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
492 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
493 g_browser_process
->CreateDevToolsHttpProtocolHandler(
494 chrome::HOST_DESKTOP_TYPE_NATIVE
,
498 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
503 // Heap allocated class that listens for first page load, kicks off stat
504 // recording and then deletes itself.
505 class LoadCompleteListener
: public content::NotificationObserver
{
507 LoadCompleteListener() {
509 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
510 content::NotificationService::AllSources());
512 ~LoadCompleteListener() override
{}
514 // content::NotificationObserver implementation.
515 void Observe(int type
,
516 const content::NotificationSource
& source
,
517 const content::NotificationDetails
& details
) override
{
518 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
519 startup_metric_utils::OnInitialPageLoadComplete();
524 content::NotificationRegistrar registrar_
;
525 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
530 namespace chrome_browser
{
532 // This error message is not localized because we failed to load the
533 // localization data files.
535 const char kMissingLocaleDataTitle
[] = "Missing File Error";
539 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
540 const char kMissingLocaleDataMessage
[] =
541 "Unable to find locale data files. Please reinstall.";
544 } // namespace chrome_browser
546 // BrowserMainParts ------------------------------------------------------------
549 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_
=
552 ChromeBrowserMainParts::ChromeBrowserMainParts(
553 const content::MainFunctionParams
& parameters
)
554 : parameters_(parameters
),
555 parsed_command_line_(parameters
.command_line
),
556 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
557 startup_watcher_(new StartupTimeBomb()),
558 shutdown_watcher_(new ShutdownWatcherHelper()),
559 browser_field_trials_(parameters
.command_line
),
561 run_message_loop_(true),
562 notify_result_(ProcessSingleton::PROCESS_NONE
),
564 restart_last_session_(false) {
565 // If we're running tests (ui_task is non-null).
566 if (parameters
.ui_task
)
567 browser_defaults::enable_help_app
= false;
569 // Chrome disallows cookies by default. All code paths that want to use
570 // cookies need to go through one of Chrome's URLRequestContexts which have
571 // a ChromeNetworkDelegate attached that selectively allows cookies again.
572 if (!disable_enforcing_cookie_policies_for_tests_
)
573 net::URLRequest::SetDefaultCookiePolicyToBlock();
576 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
577 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
578 delete chrome_extra_parts_
[i
];
579 chrome_extra_parts_
.clear();
582 // This will be called after the command-line has been mutated by about:flags
583 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
584 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
585 // Must initialize metrics after labs have been converted into switches,
586 // but before field trials are set up (so that client ID is available for
587 // one-time randomized field trials).
589 // Initialize FieldTrialList to support FieldTrials that use one-time
591 metrics::MetricsService
* metrics
= browser_process_
->metrics_service();
592 field_trial_list_
.reset(
593 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
595 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
596 if (command_line
->HasSwitch(switches::kEnableBenchmarking
))
597 base::FieldTrial::EnableBenchmarking();
599 // Ensure any field trials specified on the command line are initialized.
600 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
601 std::set
<std::string
> unforceable_field_trials
;
602 #if defined(OFFICIAL_BUILD)
603 unforceable_field_trials
.insert("SettingsEnforcement");
604 #endif // defined(OFFICIAL_BUILD)
606 // Create field trials without activating them, so that this behaves in a
607 // consistent manner with field trials created from the server.
608 bool result
= base::FieldTrialList::CreateTrialsFromString(
609 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
610 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
611 unforceable_field_trials
);
612 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
613 << " list specified.";
615 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
616 // Create default variation ids which will always be included in the
617 // X-Client-Data request header.
618 variations::VariationsHttpHeaderProvider
* provider
=
619 variations::VariationsHttpHeaderProvider::GetInstance();
620 bool result
= provider
->SetDefaultVariationIds(
621 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
622 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
623 << " list specified.";
625 chrome_variations::VariationsService
* variations_service
=
626 browser_process_
->variations_service();
627 if (variations_service
)
628 variations_service
->CreateTrialsFromSeed();
630 // This must be called after |local_state_| is initialized.
631 browser_field_trials_
.SetupFieldTrials(
632 base::Time::FromTimeT(metrics
->GetInstallDate()), local_state_
);
634 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
635 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
636 // Even though base::Bind does AddRef and Release, the object will not be
637 // deleted after the Task is executed.
638 field_trial_synchronizer_
= new FieldTrialSynchronizer();
640 // Now that field trials have been created, initializes metrics recording.
641 metrics
->InitializeMetricsRecordingState();
644 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
646 void ChromeBrowserMainParts::StartMetricsRecording() {
647 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
648 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
650 const bool only_do_metrics_recording
=
651 parsed_command_line_
.HasSwitch(switches::kMetricsRecordingOnly
) ||
652 parsed_command_line_
.HasSwitch(switches::kEnableBenchmarking
);
653 if (only_do_metrics_recording
) {
654 // If we're testing then we don't care what the user preference is, we turn
655 // on recording, but not reporting, otherwise tests fail.
656 metrics
->StartRecordingForTests();
660 metrics
->CheckForClonedInstall(
661 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
662 const bool metrics_enabled
= metrics
->StartIfMetricsReportingEnabled();
663 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is
664 // currently disabled there. http://crbug.com/370041
665 browser_process_
->rappor_service()->Start(
666 browser_process_
->system_request_context(),
670 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
671 // Don't record any metrics if UI was displayed before this point e.g.
673 if (startup_metric_utils::WasNonBrowserUIDisplayed())
676 #if defined(OS_ANDROID)
677 // On Android the first run is handled in Java code, and the C++ side of
678 // Chrome doesn't know if this is the first run. This will cause some
679 // inaccuracy in the UMA statistics, but this should be minor (first runs are
681 bool is_first_run
= false;
683 bool is_first_run
= first_run::IsChromeFirstRun();
686 // CurrentProcessInfo::CreationTime() is currently only implemented on some
688 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
689 const base::Time process_creation_time
=
690 base::CurrentProcessInfo::CreationTime();
692 if (!is_first_run
&& !process_creation_time
.is_null()) {
693 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
694 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
696 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
698 // Record collected startup metrics.
699 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
702 new LoadCompleteListener();
705 // -----------------------------------------------------------------------------
706 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
709 #define DLLEXPORT __declspec(dllexport)
711 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
713 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
716 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
717 // Need an instance of AtExitManager to handle singleton creations and
718 // deletions. We need this new instance because, the old instance created
719 // in ChromeMain() got destructed when the function returned.
720 base::AtExitManager exit_manager
;
721 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
725 // content::BrowserMainParts implementation ------------------------------------
727 void ChromeBrowserMainParts::PreEarlyInitialization() {
728 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
729 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
730 chrome_extra_parts_
[i
]->PreEarlyInitialization();
733 void ChromeBrowserMainParts::PostEarlyInitialization() {
734 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
735 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
736 chrome_extra_parts_
[i
]->PostEarlyInitialization();
739 void ChromeBrowserMainParts::ToolkitInitialized() {
740 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
741 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
742 chrome_extra_parts_
[i
]->ToolkitInitialized();
745 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
746 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
747 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
748 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
751 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
752 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
753 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
754 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
757 int ChromeBrowserMainParts::PreCreateThreads() {
758 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
759 result_code_
= PreCreateThreadsImpl();
761 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
762 #if !defined(OS_ANDROID)
763 // These members must be initialized before exiting this function normally.
764 DCHECK(master_prefs_
.get());
765 DCHECK(browser_creator_
.get());
767 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
768 chrome_extra_parts_
[i
]->PreCreateThreads();
774 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
775 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
776 run_message_loop_
= false;
777 #if !defined(OS_ANDROID)
778 chrome::MaybeShowInvalidUserDataDirWarningDialog();
780 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
781 return chrome::RESULT_CODE_MISSING_DATA
;
783 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
784 MediaCaptureDevicesDispatcher::GetInstance();
786 // Android's first run is done in Java instead of native.
787 #if !defined(OS_ANDROID)
788 process_singleton_
.reset(new ChromeProcessSingleton(
789 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
791 // Cache first run state early.
792 first_run::IsChromeFirstRun();
795 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
796 JsonPrefStore::GetTaskRunnerForFile(
797 base::FilePath(chrome::kLocalStorePoolName
),
798 BrowserThread::GetBlockingPool());
801 TRACE_EVENT0("startup",
802 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
803 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
804 parsed_command_line()));
807 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
808 TRACE_EVENT0("startup",
809 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
810 // User wants to override default tracking status.
812 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
813 // Default to basic profiling (no parent child support).
814 tracked_objects::ThreadData::Status status
=
815 tracked_objects::ThreadData::PROFILING_ACTIVE
;
816 if (flag
.compare("0") != 0)
817 status
= tracked_objects::ThreadData::DEACTIVATED
;
818 else if (flag
.compare("child") != 0)
819 status
= tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE
;
820 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
823 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile
)) {
824 tracking_objects_
.set_output_file_path(
825 parsed_command_line().GetSwitchValuePath(
826 switches::kProfilingOutputFile
));
829 local_state_
= InitializeLocalState(
830 local_state_task_runner
.get(), parsed_command_line());
832 #if !defined(OS_ANDROID)
833 // These members must be initialized before returning from this function.
834 master_prefs_
.reset(new first_run::MasterPrefs
);
835 // Android doesn't use StartupBrowserCreator.
836 browser_creator_
.reset(new StartupBrowserCreator
);
837 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
838 chrome::UMABrowsingActivityObserver::Init();
841 #if !defined(OS_CHROMEOS)
842 // Convert active labs into switches. This needs to be done before
843 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
844 // affected by experiment flags (--touch-optimized-ui in particular).
845 // On ChromeOS system level flags are applied from the device settings from
846 // the session manager.
848 TRACE_EVENT0("startup",
849 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
850 about_flags::PrefServiceFlagsStorage
flags_storage_(
851 g_browser_process
->local_state());
852 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
853 CommandLine::ForCurrentProcess(),
854 about_flags::kAddSentinels
);
858 local_state_
->UpdateCommandLinePrefStore(
859 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
861 // Reset the command line in the crash report details, since we may have
862 // just changed it to include experiments.
863 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
865 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
866 // needed when loading the MainMenu.nib and the language doesn't depend on
867 // anything since it comes from Cocoa.
868 #if defined(OS_MACOSX)
870 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
871 browser_process_
->SetApplicationLocale(locale
);
873 const std::string locale
=
874 local_state_
->GetString(prefs::kApplicationLocale
);
876 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
877 // method InitSharedInstance is ignored.
879 TRACE_EVENT_BEGIN0("startup",
880 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
881 const std::string loaded_locale
=
882 ui::ResourceBundle::InitSharedInstanceWithLocale(
883 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
884 TRACE_EVENT_END0("startup",
885 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
887 if (loaded_locale
.empty() &&
888 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
889 ShowMissingLocaleMessageBox();
890 return chrome::RESULT_CODE_MISSING_DATA
;
892 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
893 browser_process_
->SetApplicationLocale(loaded_locale
);
895 base::FilePath resources_pack_path
;
896 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
898 TRACE_EVENT0("startup",
899 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
900 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
901 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
903 #endif // defined(OS_MACOSX)
905 // Android does first run in Java instead of native.
906 // Chrome OS has its own out-of-box-experience code.
907 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
908 // On first run, we need to process the predictor preferences before the
909 // browser's profile_manager object is created, but after ResourceBundle
911 if (first_run::IsChromeFirstRun()) {
912 first_run::ProcessMasterPreferencesResult pmp_result
=
913 first_run::ProcessMasterPreferences(user_data_dir_
,
914 master_prefs_
.get());
915 if (pmp_result
== first_run::EULA_EXIT_NOW
)
916 return chrome::RESULT_CODE_EULA_REFUSED
;
918 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
919 !parsed_command_line().HasSwitch(switches::kAppId
) &&
920 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
921 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
924 // TODO(macourteau): refactor preferences that are copied from
925 // master_preferences into local_state, as a "local_state" section in
926 // master preferences. If possible, a generic solution would be preferred
927 // over a copy one-by-one of specific preferences. Also see related TODO
930 // Store the initial VariationsService seed in local state, if it exists
932 if (!master_prefs_
->variations_seed
.empty()) {
933 local_state_
->SetString(prefs::kVariationsSeed
,
934 master_prefs_
->variations_seed
);
935 if (!master_prefs_
->variations_seed_signature
.empty()) {
936 local_state_
->SetString(prefs::kVariationsSeedSignature
,
937 master_prefs_
->variations_seed_signature
);
939 // Set the variation seed date to the current system time. If the user's
940 // clock is incorrect, this may cause some field trial expiry checks to
941 // not do the right thing until the next seed update from the server,
942 // when this value will be updated.
943 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
944 base::Time::Now().ToInternalValue());
947 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
948 local_state_
->SetString(
949 prefs::kBrowserSuppressDefaultBrowserPrompt
,
950 master_prefs_
->suppress_default_browser_prompt_for_version
);
953 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE
)->HandleFirstRun();
957 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
958 // Set the product channel for crash reports.
959 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
960 chrome::VersionInfo::GetVersionStringModifier());
963 // Initialize tracking synchronizer system.
964 tracking_synchronizer_
= new metrics::TrackingSynchronizer();
966 #if defined(OS_MACOSX)
967 // Get the Keychain API to register for distributed notifications on the main
968 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
969 // which doesn't. This ensures those notifications will get delivered
970 // properly. See issue 37766.
971 // (Note that the callback mask here is empty. I don't want to register for
972 // any callbacks, I just want to initialize the mechanism.)
973 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
976 #if defined(OS_CHROMEOS)
977 // Must be done after g_browser_process is constructed, before
978 // SetupMetricsAndFieldTrials().
979 chromeos::CrosSettings::Initialize();
982 // Now the command line has been mutated based on about:flags, we can setup
983 // metrics and initialize field trials. The field trials are needed by
984 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
985 SetupMetricsAndFieldTrials();
987 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
988 browser_process_
->PreCreateThreads();
990 return content::RESULT_CODE_NORMAL_EXIT
;
993 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
994 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
995 result_code_
= PreMainMessageLoopRunImpl();
997 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
998 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
1001 // PreMainMessageLoopRun calls these extra stages in the following order:
1002 // PreMainMessageLoopRunImpl()
1003 // ... initial setup, including browser_process_ setup.
1005 // ... additional setup, including CreateProfile()
1006 // PostProfileInit()
1007 // ... additional setup
1008 // PreBrowserStart()
1009 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1010 // PostBrowserStart()
1012 void ChromeBrowserMainParts::PreProfileInit() {
1013 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1015 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1016 chrome_extra_parts_
[i
]->PreProfileInit();
1018 #if !defined(OS_ANDROID)
1019 // Initialize the feedback uploader so it can setup notifications for profile
1021 feedback::FeedbackProfileObserver::Initialize();
1023 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
1025 // First check if any ephemeral profiles are left behind because of browser
1026 // crash and schedule them for deletion and then proceed with getting the set
1027 // of profiles to open.
1028 ProfileInfoCache
& profile_cache
= profile_manager
->GetProfileInfoCache();
1029 size_t profiles_count
= profile_cache
.GetNumberOfProfiles();
1030 std::vector
<base::FilePath
> profiles_to_delete
;
1031 for (size_t i
= 0; i
< profiles_count
; ++i
) {
1032 if (profile_cache
.ProfileIsEphemeralAtIndex(i
))
1033 profiles_to_delete
.push_back(profile_cache
.GetPathOfProfileAtIndex(i
));
1036 if (profiles_to_delete
.size()) {
1037 for (size_t i
= 0; i
< profiles_to_delete
.size(); ++i
) {
1038 profile_manager
->ScheduleProfileForDeletion(
1039 profiles_to_delete
[i
], ProfileManager::CreateCallback());
1041 // Clean up stale profiles immediately after browser start.
1042 BrowserThread::PostTask(
1043 BrowserThread::FILE, FROM_HERE
,
1044 base::Bind(&ProfileManager::CleanUpStaleProfiles
, profiles_to_delete
));
1046 #endif // OS_ANDROID
1049 void ChromeBrowserMainParts::PostProfileInit() {
1050 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1051 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1052 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1053 chrome_extra_parts_
[i
]->PostProfileInit();
1056 void ChromeBrowserMainParts::PreBrowserStart() {
1057 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1058 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1059 chrome_extra_parts_
[i
]->PreBrowserStart();
1061 three_d_observer_
.reset(new ThreeDAPIObserver());
1064 void ChromeBrowserMainParts::PostBrowserStart() {
1065 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1066 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1067 chrome_extra_parts_
[i
]->PostBrowserStart();
1068 #if !defined(OS_ANDROID)
1069 // Allow ProcessSingleton to process messages.
1070 process_singleton_
->Unlock();
1072 #if defined(ENABLE_WEBRTC)
1073 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1074 // to reduce the impact on startup time.
1075 BrowserThread::PostDelayedTask(
1078 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1079 base::TimeDelta::FromMinutes(1));
1083 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1084 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1085 // Android updates the metrics service dynamically depending on whether the
1086 // application is in the foreground or not. Do not start here.
1087 #if !defined(OS_ANDROID)
1088 // Now that the file thread has been started, start recording.
1089 StartMetricsRecording();
1092 if (!base::debug::BeingDebugged()) {
1093 // Create watchdog thread after creating all other threads because it will
1094 // watch the other threads and they must be running.
1095 browser_process_
->watchdog_thread();
1098 // Do any initializating in the browser process that requires all threads
1100 browser_process_
->PreMainMessageLoopRun();
1102 // Record last shutdown time into a histogram.
1103 browser_shutdown::ReadLastShutdownInfo();
1106 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1107 // tasks. Those care whether the browser is already running. On Linux/Mac,
1108 // upgrade/uninstall happen separately.
1109 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1111 // If the command line specifies 'uninstall' then we need to work here
1112 // unless we detect another chrome browser running.
1113 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1114 return DoUninstallTasks(already_running
);
1117 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1118 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1119 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1120 parsed_command_line_
);
1123 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1124 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1127 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1128 return ShellIntegration::SetAsDefaultBrowser() ?
1129 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1130 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1133 #if defined(USE_AURA)
1134 // Make sure aura::Env has been initialized.
1135 CHECK(aura::Env::GetInstance());
1138 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1139 #if !defined(OS_ANDROID)
1140 // If the command line specifies --pack-extension, attempt the pack extension
1141 // startup action and exit.
1142 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1143 extensions::StartupHelper extension_startup_helper
;
1144 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1145 return content::RESULT_CODE_NORMAL_EXIT
;
1146 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1149 // If we're being launched just to check the connector policy, we are
1150 // short-lived and don't want to be passing that switch off.
1151 bool pass_command_line
= !parsed_command_line().HasSwitch(
1152 switches::kCheckCloudPrintConnectorPolicy
);
1154 if (pass_command_line
) {
1155 // When another process is running, use that process instead of starting a
1156 // new one. NotifyOtherProcess will currently give the other process up to
1157 // 20 seconds to respond. Note that this needs to be done before we attempt
1158 // to read the profile.
1159 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1160 switch (notify_result_
) {
1161 case ProcessSingleton::PROCESS_NONE
:
1162 // No process already running, fall through to starting a new one.
1165 case ProcessSingleton::PROCESS_NOTIFIED
:
1166 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1167 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1168 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1170 // Having a differentiated return type for testing allows for tests to
1171 // verify proper handling of some switches. When not testing, stick to
1172 // the standard Unix convention of returning zero when things went as
1174 if (parsed_command_line().HasSwitch(switches::kTestType
))
1175 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1176 return content::RESULT_CODE_NORMAL_EXIT
;
1178 case ProcessSingleton::PROFILE_IN_USE
:
1179 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1181 case ProcessSingleton::LOCK_ERROR
:
1182 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1183 "directory. This means that running multiple instances "
1184 "would start multiple browser processes rather than "
1185 "opening a new window in the existing process. Aborting "
1186 "now to avoid profile corruption.";
1187 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1193 #endif // !defined(OS_ANDROID)
1195 // Handle special early return paths (which couldn't be processed even earlier
1196 // as they require the process singleton to be held) first.
1198 std::string try_chrome
=
1199 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1200 if (!try_chrome
.empty()) {
1202 // Setup.exe has determined that we need to run a retention experiment
1203 // and has lauched chrome to show the experiment UI. It is guaranteed that
1204 // no other Chrome is currently running as the process singleton was
1205 // sucessfully grabbed above.
1207 base::StringToInt(try_chrome
, &try_chrome_int
);
1208 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1210 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1211 base::Unretained(process_singleton_
.get())));
1212 if (answer
== TryChromeDialogView::NOT_NOW
)
1213 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1214 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1215 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1216 // At this point the user is willing to try chrome again.
1217 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1218 // Only set in the unattended case, the interactive case is Windows 8.
1219 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1220 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1221 ShellIntegration::SetAsDefaultBrowser();
1224 // We don't support retention experiments on Mac or Linux.
1225 return content::RESULT_CODE_NORMAL_EXIT
;
1226 #endif // defined(OS_WIN)
1230 // Do the tasks if chrome has been upgraded while it was last running.
1231 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1232 return content::RESULT_CODE_NORMAL_EXIT
;
1234 // Check if there is any machine level Chrome installed on the current
1235 // machine. If yes and the current Chrome process is user level, we do not
1236 // allow the user level Chrome to run. So we notify the user and uninstall
1237 // user level Chrome.
1238 // Note this check needs to happen here (after the process singleton was
1239 // obtained but before potentially creating the first run sentinel).
1240 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1241 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1242 #endif // defined(OS_WIN)
1244 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1245 if (sxs_linux::ShouldMigrateUserDataDir())
1246 return sxs_linux::MigrateUserDataDir();
1247 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1249 // Desktop construction occurs here, (required before profile creation).
1252 // Profile creation ----------------------------------------------------------
1254 metrics::MetricsService::SetExecutionPhase(
1255 metrics::MetricsService::CREATE_PROFILE
,
1256 g_browser_process
->local_state());
1257 profile_
= CreatePrimaryProfile(parameters(),
1259 parsed_command_line());
1261 return content::RESULT_CODE_NORMAL_EXIT
;
1263 #if !defined(OS_ANDROID)
1264 // The first run sentinel must be created after the process singleton was
1265 // grabbed and no early return paths were otherwise hit above.
1266 first_run::CreateSentinelIfNeeded();
1267 #endif // !defined(OS_ANDROID)
1269 #if defined(ENABLE_BACKGROUND)
1270 // Autoload any profiles which are running background apps.
1271 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1272 browser_process_
->profile_manager()->AutoloadProfiles();
1274 // Post-profile init ---------------------------------------------------------
1276 TranslateService::Initialize();
1278 // Needs to be done before PostProfileInit, since login manager on CrOS is
1279 // called inside PostProfileInit.
1280 content::WebUIControllerFactory::RegisterFactory(
1281 ChromeWebUIControllerFactory::GetInstance());
1283 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1284 // So make sure to create it before that.
1285 #if !defined(DISABLE_NACL)
1286 NaClBrowserDelegateImpl
* delegate
=
1287 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1288 nacl::NaClBrowser::SetDelegate(delegate
);
1291 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1292 // (requires supporting early exit).
1295 // Retrieve cached GL strings from local state and use them for GPU
1296 // blacklist decisions.
1297 if (g_browser_process
->gl_string_manager())
1298 g_browser_process
->gl_string_manager()->Initialize();
1300 // Create an instance of GpuModeManager to watch gpu mode pref change.
1301 g_browser_process
->gpu_mode_manager();
1303 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1304 // Show the First Run UI if this is the first time Chrome has been run on
1305 // this computer, or we're being compelled to do so by a command line flag.
1306 // Note that this be done _after_ the PrefService is initialized and all
1307 // preferences are registered, since some of the code that the importer
1308 // touches reads preferences.
1309 if (first_run::IsChromeFirstRun()) {
1310 first_run::AutoImport(profile_
,
1311 master_prefs_
->homepage_defined
,
1312 master_prefs_
->do_import_items
,
1313 master_prefs_
->dont_import_items
,
1314 master_prefs_
->import_bookmarks_path
);
1316 // Note: this can pop the first run consent dialog on linux.
1317 first_run::DoPostImportTasks(profile_
,
1318 master_prefs_
->make_chrome_default_for_user
);
1320 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1321 browser_creator_
->set_show_main_browser_window(
1322 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1324 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1327 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1330 // Sets things up so that if we crash from this point on, a dialog will
1331 // popup asking the user to restart chrome. It is done this late to avoid
1332 // testing against a bunch of special cases that are taken care early on.
1333 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1334 parsed_command_line());
1336 // Registers Chrome with the Windows Restart Manager, which will restore the
1337 // Chrome session when the computer is restarted after a system update.
1338 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1339 // but should run on startup if extended to handle crashes/hangs/patches.
1340 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1341 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1342 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1343 parsed_command_line());
1346 // Verify that the profile is not on a network share and if so prepare to show
1347 // notification to the user.
1348 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1349 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1350 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1351 profile_
->GetPath()));
1355 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1356 // Init the RLZ library. This just binds the dll and schedules a task on the
1357 // file thread to be run sometime later. If this is the first run we record
1358 // the installation event.
1359 PrefService
* pref_service
= profile_
->GetPrefs();
1360 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1361 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1362 // Negative ping delay means to send ping immediately after a first search is
1364 RLZTracker::InitRlzFromProfileDelayed(
1365 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1366 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1367 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1369 // Configure modules that need access to resources.
1370 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1372 // In unittest mode, this will do nothing. In normal mode, this will create
1373 // the global IntranetRedirectDetector instance, which will promptly go to
1374 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1375 // to see if it should do anything else.
1377 // A simpler way of doing all this would be to have some function which could
1378 // give the time elapsed since startup, and simply have this object check that
1379 // when asked to initialize itself, but this doesn't seem to exist.
1381 // This can't be created in the BrowserProcessImpl constructor because it
1382 // needs to read prefs that get set after that runs.
1383 browser_process_
->intranet_redirect_detector();
1384 GoogleSearchCounter::RegisterForNotifications();
1386 // Check SDCH field trial. Default is now that everything is enabled,
1387 // so provide options for disabling HTTPS or all of SDCH.
1388 const char kSdchFieldTrialName
[] = "SDCH";
1389 const char kEnabledHttpOnlyGroupName
[] = "EnabledHttpOnly";
1390 const char kDisabledAllGroupName
[] = "DisabledAll";
1392 // Store in a string on return to keep underlying storage for
1393 // StringPiece stable.
1394 std::string sdch_trial_group_string
=
1395 base::FieldTrialList::FindFullName(kSdchFieldTrialName
);
1396 base::StringPiece
sdch_trial_group(sdch_trial_group_string
);
1397 if (sdch_trial_group
.starts_with(kEnabledHttpOnlyGroupName
)) {
1398 net::SdchManager::EnableSdchSupport(true);
1399 net::SdchManager::EnableSecureSchemeSupport(false);
1400 } else if (sdch_trial_group
.starts_with(kDisabledAllGroupName
)) {
1401 net::SdchManager::EnableSdchSupport(false);
1404 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
1405 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1406 base::FilePath path
=
1407 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1408 printing::PrintedDocument::set_debug_dump_path(path
);
1412 HandleTestParameters(parsed_command_line());
1413 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1414 base::debug::BeingDebugged());
1416 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1417 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1418 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1419 browser_process_
->GetApplicationLocale());
1421 // Start watching for hangs during startup. We disarm this hang detector when
1422 // ThreadWatcher takes over or when browser is shutdown or when
1423 // startup_watcher_ is deleted.
1424 metrics::MetricsService::SetExecutionPhase(
1425 metrics::MetricsService::STARTUP_TIMEBOMB_ARM
,
1426 g_browser_process
->local_state());
1427 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(600));
1429 // On mobile, need for clean shutdown arises only when the application comes
1430 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1431 // http://crbug.com/179143
1432 #if !defined(OS_ANDROID)
1433 // Start watching for a hang.
1434 browser_process_
->metrics_service()->LogNeedForCleanShutdown();
1437 #if defined(ENABLE_FULL_PRINTING)
1438 // Create the instance of the cloud print proxy service so that it can launch
1439 // the service process if needed. This is needed because the service process
1440 // might have shutdown because an update was available.
1441 // TODO(torne): this should maybe be done with
1442 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1444 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1447 // Start watching all browser threads for responsiveness.
1448 metrics::MetricsService::SetExecutionPhase(
1449 metrics::MetricsService::THREAD_WATCHER_START
,
1450 g_browser_process
->local_state());
1451 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1453 #if defined(OS_ANDROID)
1454 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1457 #if !defined(DISABLE_NACL)
1458 BrowserThread::PostTask(
1461 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1464 // Make sure initial prefs are recorded
1465 PrefMetricsService::Factory::GetForProfile(profile_
);
1469 // Instantiate the notification UI manager, as this triggers a perf timer
1470 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1471 // triggering the timer and call that explicitly in the approprate place.
1472 // http://crbug.com/105065.
1473 browser_process_
->notification_ui_manager();
1475 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1476 RegisterComponentsForUpdate();
1478 #if defined(OS_ANDROID)
1479 chrome_variations::VariationsService
* variations_service
=
1480 browser_process_
->variations_service();
1481 if (variations_service
) {
1482 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1483 variations_service
->StartRepeatedVariationsSeedFetch();
1485 translate::TranslateDownloadManager::RequestLanguageList(
1486 profile_
->GetPrefs());
1489 // Most general initialization is behind us, but opening a
1490 // tab and/or session restore and such is still to be done.
1491 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1493 // We are in regular browser boot sequence. Open initial tabs and enter the
1494 // main message loop.
1496 #if defined(OS_CHROMEOS)
1497 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1498 // them this early as the cryptohome hasn't yet been mounted (which happens
1499 // only once we log in.
1500 std::vector
<Profile
*> last_opened_profiles
;
1502 std::vector
<Profile
*> last_opened_profiles
=
1503 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1506 if (browser_creator_
->Start(parsed_command_line(), base::FilePath(),
1507 profile_
, last_opened_profiles
, &result_code
)) {
1508 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1509 // Initialize autoupdate timer. Timer callback costs basically nothing
1510 // when browser is not in persistent mode, so it's OK to let it ride on
1511 // the main thread. This needs to be done here because we don't want
1512 // to start the timer when Chrome is run inside a test harness.
1513 browser_process_
->StartAutoupdateTimer();
1516 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1517 // On Linux, the running exe will be updated if an upgrade becomes
1518 // available while the browser is running. We need to save the last
1519 // modified time of the exe, so we can compare to determine if there is
1520 // an upgrade while the browser is kept alive by a persistent extension.
1521 upgrade_util::SaveLastModifiedTimeOfExe();
1524 // Record now as the last successful chrome start.
1525 GoogleUpdateSettings::SetLastRunTime();
1527 #if defined(OS_MACOSX)
1528 // Call Recycle() here as late as possible, before going into the loop
1529 // because Start() will add things to it while creating the main window.
1530 if (parameters().autorelease_pool
)
1531 parameters().autorelease_pool
->Recycle();
1534 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1535 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1537 // If we're running tests (ui_task is non-null), then we don't want to
1538 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1539 // RequestLanguageList
1540 if (parameters().ui_task
== NULL
) {
1541 // Request new variations seed information from server.
1542 chrome_variations::VariationsService
* variations_service
=
1543 browser_process_
->variations_service();
1544 if (variations_service
) {
1545 variations_service
->StartRepeatedVariationsSeedFetch();
1548 variations_service
->StartGoogleUpdateRegistrySync();
1552 translate::TranslateDownloadManager::RequestLanguageList(
1553 profile_
->GetPrefs());
1556 run_message_loop_
= true;
1558 run_message_loop_
= false;
1560 browser_creator_
.reset();
1561 #endif // !defined(OS_ANDROID)
1563 #if !defined(OS_ANDROID)
1564 process_power_collector_
.reset(new ProcessPowerCollector
);
1565 process_power_collector_
->Initialize();
1570 if (parameters().ui_task
) {
1571 parameters().ui_task
->Run();
1572 delete parameters().ui_task
;
1573 run_message_loop_
= false;
1575 #if defined(OS_ANDROID)
1576 // We never run the C++ main loop on Android, since the UI thread message
1577 // loop is controlled by the OS, so this is as close as we can get to
1578 // the start of the main loop
1579 if (result_code_
<= 0) {
1580 RecordBrowserStartupTime();
1583 return result_code_
;
1586 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1587 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1588 #if defined(OS_ANDROID)
1589 // Chrome on Android does not use default MessageLoop. It has its own
1590 // Android specific MessageLoop
1594 // Set the result code set in PreMainMessageLoopRun or set above.
1595 *result_code
= result_code_
;
1596 if (!run_message_loop_
)
1597 return true; // Don't run the default message loop.
1599 // These should be invoked as close to the start of the browser's
1600 // UI thread message loop as possible to get a stable measurement
1602 RecordBrowserStartupTime();
1604 DCHECK(base::MessageLoopForUI::IsCurrent());
1605 base::RunLoop run_loop
;
1607 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1609 metrics::MetricsService::SetExecutionPhase(
1610 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1611 g_browser_process
->local_state());
1618 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1619 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1620 #if defined(OS_ANDROID)
1621 // Chrome on Android does not use default MessageLoop. It has its own
1622 // Android specific MessageLoop
1626 // Start watching for jank during shutdown. It gets disarmed when
1627 // |shutdown_watcher_| object is destructed.
1628 metrics::MetricsService::SetExecutionPhase(
1629 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1630 g_browser_process
->local_state());
1631 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1633 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1634 startup_watcher_
->Disarm();
1636 // Remove observers attached to D-Bus clients before DbusThreadManager is
1638 process_power_collector_
.reset();
1640 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1641 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1643 // Some tests don't set parameters.ui_task, so they started translate
1644 // language fetch that was never completed so we need to cleanup here
1645 // otherwise it will be done by the destructor in a wrong thread.
1646 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1648 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1649 process_singleton_
->Cleanup();
1651 // Stop all tasks that might run on WatchDogThread.
1652 ThreadWatcherList::StopWatchingAll();
1654 browser_process_
->metrics_service()->Stop();
1656 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1657 browser_process_
->StartTearDown();
1661 void ChromeBrowserMainParts::PostDestroyThreads() {
1662 #if defined(OS_ANDROID)
1663 // On Android, there is no quit/exit. So the browser's main message loop will
1667 browser_process_
->PostDestroyThreads();
1668 // browser_shutdown takes care of deleting browser_process, so we need to
1670 ignore_result(browser_process_
.release());
1671 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1672 master_prefs_
.reset();
1673 process_singleton_
.reset();
1675 // We need to do this check as late as possible, but due to modularity, this
1676 // may be the last point in Chrome. This would be more effective if done at
1677 // a higher level on the stack, so that it is impossible for an early return
1678 // to bypass this code. Perhaps we need a *final* hook that is called on all
1679 // paths from content/browser/browser_main.
1680 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1682 #if defined(OS_CHROMEOS)
1683 chromeos::CrosSettings::Shutdown();
1690 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1691 chrome_extra_parts_
.push_back(parts
);