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/file_util.h"
18 #include "base/files/file_path.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/pnacl/pnacl_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/extensions/extension_service.h"
54 #include "chrome/browser/extensions/startup_helper.h"
55 #include "chrome/browser/first_run/first_run.h"
56 #include "chrome/browser/first_run/upgrade_util.h"
57 #include "chrome/browser/google/google_search_counter.h"
58 #include "chrome/browser/gpu/gl_string_manager.h"
59 #include "chrome/browser/gpu/three_d_api_observer.h"
60 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
61 #include "chrome/browser/metrics/field_trial_synchronizer.h"
62 #include "chrome/browser/metrics/thread_watcher.h"
63 #include "chrome/browser/metrics/tracking_synchronizer.h"
64 #include "chrome/browser/metrics/variations/variations_service.h"
65 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
66 #include "chrome/browser/net/chrome_net_log.h"
67 #include "chrome/browser/net/crl_set_fetcher.h"
68 #include "chrome/browser/notifications/desktop_notification_service.h"
69 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
70 #include "chrome/browser/performance_monitor/performance_monitor.h"
71 #include "chrome/browser/performance_monitor/startup_timer.h"
72 #include "chrome/browser/plugins/plugin_prefs.h"
73 #include "chrome/browser/pref_service_flags_storage.h"
74 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
75 #include "chrome/browser/prefs/command_line_pref_store.h"
76 #include "chrome/browser/prefs/pref_metrics_service.h"
77 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
78 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
79 #include "chrome/browser/process_singleton.h"
80 #include "chrome/browser/profiles/profile.h"
81 #include "chrome/browser/profiles/profile_manager.h"
82 #include "chrome/browser/profiles/profiles_state.h"
83 #include "chrome/browser/shell_integration.h"
84 #include "chrome/browser/translate/translate_service.h"
85 #include "chrome/browser/ui/app_list/app_list_service.h"
86 #include "chrome/browser/ui/browser.h"
87 #include "chrome/browser/ui/browser_finder.h"
88 #include "chrome/browser/ui/host_desktop.h"
89 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
90 #include "chrome/browser/ui/startup/default_browser_prompt.h"
91 #include "chrome/browser/ui/startup/startup_browser_creator.h"
92 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
93 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
94 #include "chrome/common/chrome_constants.h"
95 #include "chrome/common/chrome_paths.h"
96 #include "chrome/common/chrome_result_codes.h"
97 #include "chrome/common/chrome_switches.h"
98 #include "chrome/common/crash_keys.h"
99 #include "chrome/common/env_vars.h"
100 #include "chrome/common/logging_chrome.h"
101 #include "chrome/common/net/net_resource_provider.h"
102 #include "chrome/common/pref_names.h"
103 #include "chrome/common/profiling.h"
104 #include "chrome/grit/generated_resources.h"
105 #include "chrome/installer/util/google_update_settings.h"
106 #include "components/component_updater/component_updater_service.h"
107 #include "components/google/core/browser/google_util.h"
108 #include "components/language_usage_metrics/language_usage_metrics.h"
109 #include "components/metrics/metrics_service.h"
110 #include "components/nacl/browser/nacl_browser.h"
111 #include "components/rappor/rappor_service.h"
112 #include "components/signin/core/common/profile_management_switches.h"
113 #include "components/startup_metric_utils/startup_metric_utils.h"
114 #include "components/translate/content/common/cld_data_source.h"
115 #include "components/translate/core/browser/translate_download_manager.h"
116 #include "components/variations/variations_http_header_provider.h"
117 #include "content/public/browser/browser_thread.h"
118 #include "content/public/browser/notification_observer.h"
119 #include "content/public/browser/notification_registrar.h"
120 #include "content/public/browser/notification_service.h"
121 #include "content/public/browser/notification_types.h"
122 #include "content/public/browser/site_instance.h"
123 #include "content/public/common/content_client.h"
124 #include "content/public/common/content_switches.h"
125 #include "content/public/common/main_function_params.h"
126 #include "extensions/browser/extension_protocols.h"
127 #include "grit/app_locale_settings.h"
128 #include "grit/browser_resources.h"
129 #include "grit/platform_locale_settings.h"
130 #include "net/base/net_module.h"
131 #include "net/base/sdch_manager.h"
132 #include "net/cookies/cookie_monster.h"
133 #include "net/http/http_network_layer.h"
134 #include "net/http/http_stream_factory.h"
135 #include "net/url_request/url_request.h"
136 #include "ui/base/l10n/l10n_util.h"
137 #include "ui/base/layout.h"
138 #include "ui/base/resource/resource_bundle.h"
140 #if defined(OS_ANDROID)
141 #include "chrome/browser/metrics/thread_watcher_android.h"
143 #include "chrome/browser/feedback/feedback_profile_observer.h"
146 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
147 #include "chrome/browser/first_run/upgrade_util_linux.h"
148 #include "chrome/browser/sxs_linux.h"
151 #if defined(OS_CHROMEOS)
152 #include "chrome/browser/chromeos/settings/cros_settings.h"
153 #include "chromeos/chromeos_switches.h"
154 #include "chromeos/settings/cros_settings_names.h"
157 // TODO(port): several win-only methods have been pulled out of this, but
158 // BrowserMain() as a whole needs to be broken apart so that it's usable by
159 // other platforms. For now, it's just a stub. This is a serious work in
160 // progress and should not be taken as an indication of a real refactoring.
163 #include "base/environment.h" // For PreRead experiment.
164 #include "base/win/windows_version.h"
165 #include "chrome/browser/browser_util_win.h"
166 #include "chrome/browser/chrome_browser_main_win.h"
167 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
168 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
169 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
170 #include "chrome/browser/first_run/upgrade_util_win.h"
171 #include "chrome/browser/ui/network_profile_bubble.h"
172 #include "chrome/installer/util/helper.h"
173 #include "chrome/installer/util/install_util.h"
174 #include "chrome/installer/util/shell_util.h"
175 #include "net/base/net_util.h"
176 #include "ui/base/l10n/l10n_util_win.h"
177 #include "ui/gfx/win/dpi.h"
178 #include "ui/shell_dialogs/select_file_dialog.h"
179 #endif // defined(OS_WIN)
181 #if defined(OS_MACOSX)
182 #include <Security/Security.h>
184 #include "base/mac/scoped_nsautorelease_pool.h"
185 #include "chrome/browser/mac/keystone_glue.h"
188 #if !defined(DISABLE_NACL)
189 #include "components/nacl/browser/nacl_process_host.h"
192 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
193 #include "printing/printed_document.h"
196 #if defined(ENABLE_RLZ)
197 #include "chrome/browser/rlz/rlz.h"
200 #if defined(ENABLE_WEBRTC)
201 #include "chrome/browser/media/webrtc_log_util.h"
204 #if defined(USE_AURA)
205 #include "ui/aura/env.h"
208 using content::BrowserThread
;
212 // This function provides some ways to test crash and assertion handling
213 // behavior of the program.
214 void HandleTestParameters(const CommandLine
& command_line
) {
215 // This parameter causes an assertion.
216 if (command_line
.HasSwitch(switches::kBrowserAssertTest
)) {
220 // This parameter causes a null pointer crash (crash reporter trigger).
221 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
222 int* bad_pointer
= NULL
;
227 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
228 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
229 const std::vector
<GURL
>& new_tabs
) {
230 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
231 it
!= new_tabs
.end(); ++it
) {
233 browser_creator
->AddFirstRunTab(*it
);
236 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
238 // Returns the new local state object, guaranteed non-NULL.
239 // |local_state_task_runner| must be a shutdown-blocking task runner.
240 PrefService
* InitializeLocalState(
241 base::SequencedTaskRunner
* local_state_task_runner
,
242 const CommandLine
& parsed_command_line
) {
243 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
244 base::FilePath local_state_path
;
245 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
246 bool local_state_file_exists
= base::PathExists(local_state_path
);
248 // Load local state. This includes the application locale so we know which
249 // locale dll to load. This also causes local state prefs to be registered.
250 PrefService
* local_state
= g_browser_process
->local_state();
254 if (first_run::IsChromeFirstRun()) {
255 // During first run we read the google_update registry key to find what
256 // language the user selected when downloading the installer. This
257 // becomes our default language in the prefs.
258 // Other platforms obey the system locale.
259 base::string16 install_lang
;
260 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
261 local_state
->SetString(prefs::kApplicationLocale
,
262 base::UTF16ToASCII(install_lang
));
265 #endif // defined(OS_WIN)
267 // If the local state file for the current profile doesn't exist and the
268 // parent profile command line flag is present, then we should inherit some
269 // local state from the parent profile.
270 // Checking that the local state file for the current profile doesn't exist
271 // is the most robust way to determine whether we need to inherit or not
272 // since the parent profile command line flag can be present even when the
273 // current profile is not a new one, and in that case we do not want to
274 // inherit and reset the user's setting.
276 // TODO(mnissler): We should probably just instantiate a
277 // JSONPrefStore here instead of an entire PrefService. Once this is
278 // addressed, the call to browser_prefs::RegisterLocalState can move
279 // to chrome_prefs::CreateLocalState.
280 if (!local_state_file_exists
&&
281 parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
282 base::FilePath parent_profile
=
283 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
284 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
285 scoped_ptr
<PrefService
> parent_local_state(
286 chrome_prefs::CreateLocalState(
288 local_state_task_runner
,
289 g_browser_process
->policy_service(),
292 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
293 // Right now, we only inherit the locale setting from the parent profile.
294 local_state
->SetString(
295 prefs::kApplicationLocale
,
296 parent_local_state
->GetString(prefs::kApplicationLocale
));
299 #if defined(OS_CHROMEOS)
300 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
301 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
302 // Ensure that we start with owner's locale.
303 if (!owner_locale
.empty() &&
304 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
305 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
306 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
314 // Initializes the primary profile, possibly doing some user prompting to pick
315 // a fallback profile. Returns the newly created profile, or NULL if startup
316 // should not continue.
317 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
318 const base::FilePath
& user_data_dir
,
319 const CommandLine
& parsed_command_line
) {
320 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
321 base::Time start
= base::Time::Now();
322 if (profiles::IsMultipleProfilesEnabled() &&
323 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
324 g_browser_process
->local_state()->SetString(prefs::kProfileLastUsed
,
325 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
326 // Clear kProfilesLastActive since the user only wants to launch a specific
328 ListPrefUpdate
update(g_browser_process
->local_state(),
329 prefs::kProfilesLastActive
);
330 base::ListValue
* profile_list
= update
.Get();
331 profile_list
->Clear();
334 Profile
* profile
= NULL
;
335 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
336 // On ChromeOS and Android the ProfileManager will use the same path as the
337 // one we got passed. GetActiveUserProfile will therefore use the correct path
339 DCHECK_EQ(user_data_dir
.value(),
340 g_browser_process
->profile_manager()->user_data_dir().value());
341 profile
= ProfileManager::GetActiveUserProfile();
343 base::FilePath profile_path
=
344 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
345 profile
= g_browser_process
->profile_manager()->GetProfile(
348 // If we're using the --new-profile-management flag and this profile is
349 // signed out, then we should show the user manager instead. By switching
350 // the active profile to the guest profile we ensure that no
351 // browser windows will be opened for the guest profile.
352 if (switches::IsNewProfileManagement() && !profile
->IsGuestSession()) {
353 ProfileInfoCache
& cache
=
354 g_browser_process
->profile_manager()->GetProfileInfoCache();
355 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
357 if (cache
.ProfileIsSigninRequiredAtIndex(profile_index
))
358 profile
= g_browser_process
->profile_manager()->GetProfile(
359 ProfileManager::GetGuestProfilePath());
363 UMA_HISTOGRAM_LONG_TIMES(
364 "Startup.CreateFirstProfile", base::Time::Now() - start
);
369 // TODO(port): fix this. See comments near the definition of
370 // user_data_dir. It is better to CHECK-fail here than it is to
371 // silently exit because of missing code in the above test.
372 CHECK(profile
) << "Cannot get default profile.";
378 #if defined(OS_MACOSX)
379 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
380 SecKeychainCallbackInfo
* info
, void* context
) {
385 void RegisterComponentsForUpdate() {
386 component_updater::ComponentUpdateService
* cus
=
387 g_browser_process
->component_updater();
389 // Registration can be before or after cus->Start() so it is ok to post
390 // a task to the UI thread to do registration once you done the necessary
391 // file IO to know you existing component version.
392 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
393 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
394 RegisterPepperFlashComponent(cus
);
395 RegisterSwiftShaderComponent(cus
);
396 RegisterWidevineCdmComponent(cus
);
397 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
400 if (translate::CldDataSource::ShouldRegisterForComponentUpdates()) {
401 RegisterCldComponent(cus
);
405 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
406 #if defined(OS_ANDROID)
407 // The CRLSet component was enabled for some releases. This code attempts to
408 // delete it from the local disk of those how may have downloaded it.
409 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
410 #elif !defined(OS_CHROMEOS)
411 // CRLSetFetcher attempts to load a CRL set from either the local disk or
413 // For Chrome OS this registration is delayed until user login.
414 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
418 #if !defined(OS_ANDROID)
419 // Android does not currently have the EV indicator. No need to get the
420 // EV certs whitelist on Android, then.
421 RegisterEVWhitelistComponent(cus
);
425 ExecutePendingSwReporter(cus
, g_browser_process
->local_state());
431 #if !defined(OS_ANDROID)
432 bool ProcessSingletonNotificationCallback(
433 const CommandLine
& command_line
,
434 const base::FilePath
& current_directory
) {
435 // Drop the request if the browser process is already in shutdown path.
436 if (!g_browser_process
|| g_browser_process
->IsShuttingDown())
439 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
440 std::string start_time_string
=
441 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
442 int64 remote_start_time
;
443 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
444 base::TimeDelta elapsed
=
445 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
446 if (command_line
.HasSwitch(switches::kFastStart
)) {
447 UMA_HISTOGRAM_LONG_TIMES(
448 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
450 UMA_HISTOGRAM_LONG_TIMES(
451 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
456 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
459 base::FilePath user_data_dir
=
460 g_browser_process
->profile_manager()->user_data_dir();
461 base::FilePath startup_profile_dir
=
462 GetStartupProfilePath(user_data_dir
, command_line
);
464 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
465 command_line
, current_directory
, startup_profile_dir
);
468 #endif // !defined(OS_ANDROID)
470 void LaunchDevToolsHandlerIfNeeded(const CommandLine
& command_line
) {
471 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
472 std::string port_str
=
473 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
475 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
476 g_browser_process
->CreateDevToolsHttpProtocolHandler(
477 chrome::HOST_DESKTOP_TYPE_NATIVE
,
481 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
486 // Heap allocated class that listens for first page load, kicks off stat
487 // recording and then deletes itself.
488 class LoadCompleteListener
: public content::NotificationObserver
{
490 LoadCompleteListener() {
492 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
493 content::NotificationService::AllSources());
495 virtual ~LoadCompleteListener() {}
497 // content::NotificationObserver implementation.
498 virtual void Observe(int type
,
499 const content::NotificationSource
& source
,
500 const content::NotificationDetails
& details
) OVERRIDE
{
501 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
502 startup_metric_utils::OnInitialPageLoadComplete();
507 content::NotificationRegistrar registrar_
;
508 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
513 namespace chrome_browser
{
515 // This error message is not localized because we failed to load the
516 // localization data files.
518 const char kMissingLocaleDataTitle
[] = "Missing File Error";
522 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
523 const char kMissingLocaleDataMessage
[] =
524 "Unable to find locale data files. Please reinstall.";
527 } // namespace chrome_browser
529 // BrowserMainParts ------------------------------------------------------------
532 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_
=
535 ChromeBrowserMainParts::ChromeBrowserMainParts(
536 const content::MainFunctionParams
& parameters
)
537 : parameters_(parameters
),
538 parsed_command_line_(parameters
.command_line
),
539 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
540 startup_watcher_(new StartupTimeBomb()),
541 shutdown_watcher_(new ShutdownWatcherHelper()),
542 startup_timer_(new performance_monitor::StartupTimer()),
543 browser_field_trials_(parameters
.command_line
),
545 run_message_loop_(true),
546 notify_result_(ProcessSingleton::PROCESS_NONE
),
548 restart_last_session_(false) {
549 // If we're running tests (ui_task is non-null).
550 if (parameters
.ui_task
)
551 browser_defaults::enable_help_app
= false;
553 // Chrome disallows cookies by default. All code paths that want to use
554 // cookies need to go through one of Chrome's URLRequestContexts which have
555 // a ChromeNetworkDelegate attached that selectively allows cookies again.
556 if (!disable_enforcing_cookie_policies_for_tests_
)
557 net::URLRequest::SetDefaultCookiePolicyToBlock();
560 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
561 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
562 delete chrome_extra_parts_
[i
];
563 chrome_extra_parts_
.clear();
566 // This will be called after the command-line has been mutated by about:flags
567 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
568 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
569 // Must initialize metrics after labs have been converted into switches,
570 // but before field trials are set up (so that client ID is available for
571 // one-time randomized field trials).
573 // Initialize FieldTrialList to support FieldTrials that use one-time
575 MetricsService
* metrics
= browser_process_
->metrics_service();
576 field_trial_list_
.reset(
577 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
579 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
580 if (command_line
->HasSwitch(switches::kEnableBenchmarking
))
581 base::FieldTrial::EnableBenchmarking();
583 // Ensure any field trials specified on the command line are initialized.
584 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
585 std::set
<std::string
> unforceable_field_trials
;
586 #if defined(OFFICIAL_BUILD)
587 unforceable_field_trials
.insert("SettingsEnforcement");
588 #endif // defined(OFFICIAL_BUILD)
590 // Create field trials without activating them, so that this behaves in a
591 // consistent manner with field trials created from the server.
592 bool result
= base::FieldTrialList::CreateTrialsFromString(
593 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
594 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
595 unforceable_field_trials
);
596 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
597 << " list specified.";
599 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
600 // Create default variation ids which will always be included in the
601 // X-Client-Data request header.
602 variations::VariationsHttpHeaderProvider
* provider
=
603 variations::VariationsHttpHeaderProvider::GetInstance();
604 bool result
= provider
->SetDefaultVariationIds(
605 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
606 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
607 << " list specified.";
609 chrome_variations::VariationsService
* variations_service
=
610 browser_process_
->variations_service();
611 if (variations_service
)
612 variations_service
->CreateTrialsFromSeed();
614 // This must be called after |local_state_| is initialized.
615 browser_field_trials_
.SetupFieldTrials(
616 base::Time::FromTimeT(metrics
->GetInstallDate()), local_state_
);
618 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
619 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
620 // Even though base::Bind does AddRef and Release, the object will not be
621 // deleted after the Task is executed.
622 field_trial_synchronizer_
= new FieldTrialSynchronizer();
624 // Now that field trials have been created, initializes metrics recording.
625 metrics
->InitializeMetricsRecordingState();
628 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
630 void ChromeBrowserMainParts::StartMetricsRecording() {
631 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
632 MetricsService
* metrics
= g_browser_process
->metrics_service();
634 const bool only_do_metrics_recording
=
635 parsed_command_line_
.HasSwitch(switches::kMetricsRecordingOnly
) ||
636 parsed_command_line_
.HasSwitch(switches::kEnableBenchmarking
);
637 if (only_do_metrics_recording
) {
638 // If we're testing then we don't care what the user preference is, we turn
639 // on recording, but not reporting, otherwise tests fail.
640 metrics
->StartRecordingForTests();
644 metrics
->CheckForClonedInstall(
645 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
646 const bool metrics_enabled
= metrics
->StartIfMetricsReportingEnabled();
647 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is
648 // currently disabled there. http://crbug.com/370041
649 browser_process_
->rappor_service()->Start(
650 browser_process_
->local_state(),
651 browser_process_
->system_request_context(),
655 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
656 // Don't record any metrics if UI was displayed before this point e.g.
658 if (startup_metric_utils::WasNonBrowserUIDisplayed())
661 #if defined(OS_ANDROID)
662 // On Android the first run is handled in Java code, and the C++ side of
663 // Chrome doesn't know if this is the first run. This will cause some
664 // inaccuracy in the UMA statistics, but this should be minor (first runs are
666 bool is_first_run
= false;
668 bool is_first_run
= first_run::IsChromeFirstRun();
671 // CurrentProcessInfo::CreationTime() is currently only implemented on some
673 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
674 const base::Time process_creation_time
=
675 base::CurrentProcessInfo::CreationTime();
677 if (!is_first_run
&& !process_creation_time
.is_null()) {
678 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
679 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
681 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
683 // Record collected startup metrics.
684 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
687 new LoadCompleteListener();
690 // -----------------------------------------------------------------------------
691 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
694 #define DLLEXPORT __declspec(dllexport)
696 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
698 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
701 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
702 // Need an instance of AtExitManager to handle singleton creations and
703 // deletions. We need this new instance because, the old instance created
704 // in ChromeMain() got destructed when the function returned.
705 base::AtExitManager exit_manager
;
706 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
710 // content::BrowserMainParts implementation ------------------------------------
712 void ChromeBrowserMainParts::PreEarlyInitialization() {
713 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
714 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
715 chrome_extra_parts_
[i
]->PreEarlyInitialization();
718 void ChromeBrowserMainParts::PostEarlyInitialization() {
719 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
720 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
721 chrome_extra_parts_
[i
]->PostEarlyInitialization();
724 void ChromeBrowserMainParts::ToolkitInitialized() {
725 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
726 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
727 chrome_extra_parts_
[i
]->ToolkitInitialized();
730 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
731 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
732 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
733 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
736 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
737 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
738 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
739 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
742 int ChromeBrowserMainParts::PreCreateThreads() {
743 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
744 result_code_
= PreCreateThreadsImpl();
746 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
747 #if !defined(OS_ANDROID)
748 // These members must be initialized before exiting this function normally.
749 DCHECK(master_prefs_
.get());
750 DCHECK(browser_creator_
.get());
752 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
753 chrome_extra_parts_
[i
]->PreCreateThreads();
759 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
760 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
761 run_message_loop_
= false;
762 #if !defined(OS_ANDROID)
763 chrome::MaybeShowInvalidUserDataDirWarningDialog();
765 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
766 return chrome::RESULT_CODE_MISSING_DATA
;
768 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
769 MediaCaptureDevicesDispatcher::GetInstance();
771 // Android's first run is done in Java instead of native.
772 #if !defined(OS_ANDROID)
773 process_singleton_
.reset(new ChromeProcessSingleton(
774 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
776 // Cache first run state early.
777 first_run::IsChromeFirstRun();
780 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
781 JsonPrefStore::GetTaskRunnerForFile(
782 base::FilePath(chrome::kLocalStorePoolName
),
783 BrowserThread::GetBlockingPool());
786 TRACE_EVENT0("startup",
787 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
788 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
789 parsed_command_line()));
792 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
793 TRACE_EVENT0("startup",
794 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
795 // User wants to override default tracking status.
797 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
798 // Default to basic profiling (no parent child support).
799 tracked_objects::ThreadData::Status status
=
800 tracked_objects::ThreadData::PROFILING_ACTIVE
;
801 if (flag
.compare("0") != 0)
802 status
= tracked_objects::ThreadData::DEACTIVATED
;
803 else if (flag
.compare("child") != 0)
804 status
= tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE
;
805 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
808 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile
)) {
809 tracking_objects_
.set_output_file_path(
810 parsed_command_line().GetSwitchValuePath(
811 switches::kProfilingOutputFile
));
814 local_state_
= InitializeLocalState(
815 local_state_task_runner
.get(), parsed_command_line());
817 #if !defined(OS_ANDROID)
818 // These members must be initialized before returning from this function.
819 master_prefs_
.reset(new first_run::MasterPrefs
);
820 // Android doesn't use StartupBrowserCreator.
821 browser_creator_
.reset(new StartupBrowserCreator
);
822 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
823 chrome::UMABrowsingActivityObserver::Init();
826 #if !defined(OS_CHROMEOS)
827 // Convert active labs into switches. This needs to be done before
828 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
829 // affected by experiment flags (--touch-optimized-ui in particular).
830 // On ChromeOS system level flags are applied from the device settings from
831 // the session manager.
833 TRACE_EVENT0("startup",
834 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
835 about_flags::PrefServiceFlagsStorage
flags_storage_(
836 g_browser_process
->local_state());
837 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
838 CommandLine::ForCurrentProcess(),
839 about_flags::kAddSentinels
);
843 local_state_
->UpdateCommandLinePrefStore(
844 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
846 // Reset the command line in the crash report details, since we may have
847 // just changed it to include experiments.
848 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
850 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
851 // needed when loading the MainMenu.nib and the language doesn't depend on
852 // anything since it comes from Cocoa.
853 #if defined(OS_MACOSX)
855 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
856 browser_process_
->SetApplicationLocale(locale
);
858 const std::string locale
=
859 local_state_
->GetString(prefs::kApplicationLocale
);
861 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
862 // method InitSharedInstance is ignored.
864 TRACE_EVENT_BEGIN0("startup",
865 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
866 const std::string loaded_locale
=
867 ui::ResourceBundle::InitSharedInstanceWithLocale(
868 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
869 TRACE_EVENT_END0("startup",
870 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
872 if (loaded_locale
.empty() &&
873 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
874 ShowMissingLocaleMessageBox();
875 return chrome::RESULT_CODE_MISSING_DATA
;
877 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
878 browser_process_
->SetApplicationLocale(loaded_locale
);
880 base::FilePath resources_pack_path
;
881 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
883 TRACE_EVENT0("startup",
884 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
885 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
886 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
888 #endif // defined(OS_MACOSX)
890 // Android does first run in Java instead of native.
891 // Chrome OS has its own out-of-box-experience code.
892 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
893 // On first run, we need to process the predictor preferences before the
894 // browser's profile_manager object is created, but after ResourceBundle
896 if (first_run::IsChromeFirstRun()) {
897 first_run::ProcessMasterPreferencesResult pmp_result
=
898 first_run::ProcessMasterPreferences(user_data_dir_
,
899 master_prefs_
.get());
900 if (pmp_result
== first_run::EULA_EXIT_NOW
)
901 return chrome::RESULT_CODE_EULA_REFUSED
;
903 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
904 !parsed_command_line().HasSwitch(switches::kAppId
) &&
905 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
906 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
909 // TODO(macourteau): refactor preferences that are copied from
910 // master_preferences into local_state, as a "local_state" section in
911 // master preferences. If possible, a generic solution would be preferred
912 // over a copy one-by-one of specific preferences. Also see related TODO
915 // Store the initial VariationsService seed in local state, if it exists
917 if (!master_prefs_
->variations_seed
.empty()) {
918 local_state_
->SetString(prefs::kVariationsSeed
,
919 master_prefs_
->variations_seed
);
920 if (!master_prefs_
->variations_seed_signature
.empty()) {
921 local_state_
->SetString(prefs::kVariationsSeedSignature
,
922 master_prefs_
->variations_seed_signature
);
924 // Set the variation seed date to the current system time. If the user's
925 // clock is incorrect, this may cause some field trial expiry checks to
926 // not do the right thing until the next seed update from the server,
927 // when this value will be updated.
928 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
929 base::Time::Now().ToInternalValue());
932 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
933 local_state_
->SetString(
934 prefs::kBrowserSuppressDefaultBrowserPrompt
,
935 master_prefs_
->suppress_default_browser_prompt_for_version
);
938 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE
)->HandleFirstRun();
942 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
943 // Set the product channel for crash reports.
944 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
945 chrome::VersionInfo::GetVersionStringModifier());
948 // Initialize tracking synchronizer system.
949 tracking_synchronizer_
= new chrome_browser_metrics::TrackingSynchronizer();
951 #if defined(OS_MACOSX)
952 // Get the Keychain API to register for distributed notifications on the main
953 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
954 // which doesn't. This ensures those notifications will get delivered
955 // properly. See issue 37766.
956 // (Note that the callback mask here is empty. I don't want to register for
957 // any callbacks, I just want to initialize the mechanism.)
958 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
961 #if defined(OS_CHROMEOS)
962 // Must be done after g_browser_process is constructed, before
963 // SetupMetricsAndFieldTrials().
964 chromeos::CrosSettings::Initialize();
967 // Now the command line has been mutated based on about:flags, we can setup
968 // metrics and initialize field trials. The field trials are needed by
969 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
970 SetupMetricsAndFieldTrials();
972 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
973 browser_process_
->PreCreateThreads();
975 return content::RESULT_CODE_NORMAL_EXIT
;
978 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
979 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
980 result_code_
= PreMainMessageLoopRunImpl();
982 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
983 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
986 // PreMainMessageLoopRun calls these extra stages in the following order:
987 // PreMainMessageLoopRunImpl()
988 // ... initial setup, including browser_process_ setup.
990 // ... additional setup, including CreateProfile()
992 // ... additional setup
994 // ... browser_creator_->Start (OR parameters().ui_task->Run())
995 // PostBrowserStart()
997 void ChromeBrowserMainParts::PreProfileInit() {
998 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1000 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1001 chrome_extra_parts_
[i
]->PreProfileInit();
1003 #if !defined(OS_ANDROID)
1004 // Initialize the feedback uploader so it can setup notifications for profile
1006 feedback::FeedbackProfileObserver::Initialize();
1008 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
1010 // First check if any ephemeral profiles are left behind because of browser
1011 // crash and schedule them for deletion and then proceed with getting the set
1012 // of profiles to open.
1013 ProfileInfoCache
& profile_cache
= profile_manager
->GetProfileInfoCache();
1014 size_t profiles_count
= profile_cache
.GetNumberOfProfiles();
1015 std::vector
<base::FilePath
> profiles_to_delete
;
1016 for (size_t i
= 0; i
< profiles_count
; ++i
) {
1017 if (profile_cache
.ProfileIsEphemeralAtIndex(i
))
1018 profiles_to_delete
.push_back(profile_cache
.GetPathOfProfileAtIndex(i
));
1021 if (profiles_to_delete
.size()) {
1022 for (size_t i
= 0; i
< profiles_to_delete
.size(); ++i
) {
1023 profile_manager
->ScheduleProfileForDeletion(
1024 profiles_to_delete
[i
], ProfileManager::CreateCallback());
1026 // Clean up stale profiles immediately after browser start.
1027 BrowserThread::PostTask(
1028 BrowserThread::FILE, FROM_HERE
,
1029 base::Bind(&ProfileManager::CleanUpStaleProfiles
, profiles_to_delete
));
1031 #endif // OS_ANDROID
1034 void ChromeBrowserMainParts::PostProfileInit() {
1035 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1036 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1037 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1038 chrome_extra_parts_
[i
]->PostProfileInit();
1041 void ChromeBrowserMainParts::PreBrowserStart() {
1042 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1043 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1044 chrome_extra_parts_
[i
]->PreBrowserStart();
1046 three_d_observer_
.reset(new ThreeDAPIObserver());
1049 void ChromeBrowserMainParts::PostBrowserStart() {
1050 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1051 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1052 chrome_extra_parts_
[i
]->PostBrowserStart();
1053 #if !defined(OS_ANDROID)
1054 // Allow ProcessSingleton to process messages.
1055 process_singleton_
->Unlock();
1057 #if defined(ENABLE_WEBRTC)
1058 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1059 // to reduce the impact on startup time.
1060 BrowserThread::PostDelayedTask(
1063 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1064 base::TimeDelta::FromMinutes(1));
1068 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1069 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1070 // Android updates the metrics service dynamically depending on whether the
1071 // application is in the foreground or not. Do not start here.
1072 #if !defined(OS_ANDROID)
1073 // Now that the file thread has been started, start recording.
1074 StartMetricsRecording();
1077 // Create watchdog thread after creating all other threads because it will
1078 // watch the other threads and they must be running.
1079 browser_process_
->watchdog_thread();
1081 // Do any initializating in the browser process that requires all threads
1083 browser_process_
->PreMainMessageLoopRun();
1085 // Record last shutdown time into a histogram.
1086 browser_shutdown::ReadLastShutdownInfo();
1089 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1090 // tasks. Those care whether the browser is already running. On Linux/Mac,
1091 // upgrade/uninstall happen separately.
1092 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1094 // If the command line specifies 'uninstall' then we need to work here
1095 // unless we detect another chrome browser running.
1096 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1097 return DoUninstallTasks(already_running
);
1100 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1101 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1102 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1103 parsed_command_line_
);
1106 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1107 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1110 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1111 return ShellIntegration::SetAsDefaultBrowser() ?
1112 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1113 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1116 #if defined(USE_AURA)
1117 // Make sure aura::Env has been initialized.
1118 CHECK(aura::Env::GetInstance());
1121 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1122 #if !defined(OS_ANDROID)
1123 // If the command line specifies --pack-extension, attempt the pack extension
1124 // startup action and exit.
1125 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1126 extensions::StartupHelper extension_startup_helper
;
1127 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1128 return content::RESULT_CODE_NORMAL_EXIT
;
1129 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1132 // If we're being launched just to check the connector policy, we are
1133 // short-lived and don't want to be passing that switch off.
1134 bool pass_command_line
= !parsed_command_line().HasSwitch(
1135 switches::kCheckCloudPrintConnectorPolicy
);
1137 if (pass_command_line
) {
1138 // When another process is running, use that process instead of starting a
1139 // new one. NotifyOtherProcess will currently give the other process up to
1140 // 20 seconds to respond. Note that this needs to be done before we attempt
1141 // to read the profile.
1142 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1143 switch (notify_result_
) {
1144 case ProcessSingleton::PROCESS_NONE
:
1145 // No process already running, fall through to starting a new one.
1148 case ProcessSingleton::PROCESS_NOTIFIED
:
1149 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1150 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1151 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1153 // Having a differentiated return type for testing allows for tests to
1154 // verify proper handling of some switches. When not testing, stick to
1155 // the standard Unix convention of returning zero when things went as
1157 if (parsed_command_line().HasSwitch(switches::kTestType
))
1158 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1159 return content::RESULT_CODE_NORMAL_EXIT
;
1161 case ProcessSingleton::PROFILE_IN_USE
:
1162 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1164 case ProcessSingleton::LOCK_ERROR
:
1165 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1166 "directory. This means that running multiple instances "
1167 "would start multiple browser processes rather than "
1168 "opening a new window in the existing process. Aborting "
1169 "now to avoid profile corruption.";
1170 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1176 #endif // !defined(OS_ANDROID)
1178 // Handle special early return paths (which couldn't be processed even earlier
1179 // as they require the process singleton to be held) first.
1181 std::string try_chrome
=
1182 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1183 if (!try_chrome
.empty()) {
1185 // Setup.exe has determined that we need to run a retention experiment
1186 // and has lauched chrome to show the experiment UI. It is guaranteed that
1187 // no other Chrome is currently running as the process singleton was
1188 // sucessfully grabbed above.
1190 base::StringToInt(try_chrome
, &try_chrome_int
);
1191 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1193 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1194 base::Unretained(process_singleton_
.get())));
1195 if (answer
== TryChromeDialogView::NOT_NOW
)
1196 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1197 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1198 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1199 // At this point the user is willing to try chrome again.
1200 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1201 // Only set in the unattended case, the interactive case is Windows 8.
1202 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1203 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1204 ShellIntegration::SetAsDefaultBrowser();
1207 // We don't support retention experiments on Mac or Linux.
1208 return content::RESULT_CODE_NORMAL_EXIT
;
1209 #endif // defined(OS_WIN)
1213 // Do the tasks if chrome has been upgraded while it was last running.
1214 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1215 return content::RESULT_CODE_NORMAL_EXIT
;
1217 // Check if there is any machine level Chrome installed on the current
1218 // machine. If yes and the current Chrome process is user level, we do not
1219 // allow the user level Chrome to run. So we notify the user and uninstall
1220 // user level Chrome.
1221 // Note this check needs to happen here (after the process singleton was
1222 // obtained but before potentially creating the first run sentinel).
1223 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1224 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1225 #endif // defined(OS_WIN)
1227 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1228 if (sxs_linux::ShouldMigrateUserDataDir())
1229 return sxs_linux::MigrateUserDataDir();
1230 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1232 // Desktop construction occurs here, (required before profile creation).
1235 // Profile creation ----------------------------------------------------------
1237 MetricsService::SetExecutionPhase(MetricsService::CREATE_PROFILE
,
1238 g_browser_process
->local_state());
1239 profile_
= CreatePrimaryProfile(parameters(),
1241 parsed_command_line());
1243 return content::RESULT_CODE_NORMAL_EXIT
;
1245 #if !defined(OS_ANDROID)
1246 // The first run sentinel must be created after the process singleton was
1247 // grabbed and no early return paths were otherwise hit above.
1248 first_run::CreateSentinelIfNeeded();
1249 #endif // !defined(OS_ANDROID)
1251 #if defined(ENABLE_BACKGROUND)
1252 // Autoload any profiles which are running background apps.
1253 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1254 browser_process_
->profile_manager()->AutoloadProfiles();
1256 // Post-profile init ---------------------------------------------------------
1258 TranslateService::Initialize();
1260 // Needs to be done before PostProfileInit, since login manager on CrOS is
1261 // called inside PostProfileInit.
1262 content::WebUIControllerFactory::RegisterFactory(
1263 ChromeWebUIControllerFactory::GetInstance());
1265 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1266 // So make sure to create it before that.
1267 #if !defined(DISABLE_NACL)
1268 NaClBrowserDelegateImpl
* delegate
=
1269 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1270 nacl::NaClBrowser::SetDelegate(delegate
);
1273 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1274 // (requires supporting early exit).
1277 // Retrieve cached GL strings from local state and use them for GPU
1278 // blacklist decisions.
1279 if (g_browser_process
->gl_string_manager())
1280 g_browser_process
->gl_string_manager()->Initialize();
1282 // Create an instance of GpuModeManager to watch gpu mode pref change.
1283 g_browser_process
->gpu_mode_manager();
1285 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1286 // Show the First Run UI if this is the first time Chrome has been run on
1287 // this computer, or we're being compelled to do so by a command line flag.
1288 // Note that this be done _after_ the PrefService is initialized and all
1289 // preferences are registered, since some of the code that the importer
1290 // touches reads preferences.
1291 if (first_run::IsChromeFirstRun()) {
1292 first_run::AutoImport(profile_
,
1293 master_prefs_
->homepage_defined
,
1294 master_prefs_
->do_import_items
,
1295 master_prefs_
->dont_import_items
,
1296 master_prefs_
->import_bookmarks_path
);
1298 // Note: this can pop the first run consent dialog on linux.
1299 first_run::DoPostImportTasks(profile_
,
1300 master_prefs_
->make_chrome_default_for_user
);
1302 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1303 browser_creator_
->set_show_main_browser_window(
1304 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1306 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1309 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1312 // Sets things up so that if we crash from this point on, a dialog will
1313 // popup asking the user to restart chrome. It is done this late to avoid
1314 // testing against a bunch of special cases that are taken care early on.
1315 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1316 parsed_command_line());
1318 // Registers Chrome with the Windows Restart Manager, which will restore the
1319 // Chrome session when the computer is restarted after a system update.
1320 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1321 // but should run on startup if extended to handle crashes/hangs/patches.
1322 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1323 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1324 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1325 parsed_command_line());
1328 // Verify that the profile is not on a network share and if so prepare to show
1329 // notification to the user.
1330 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1331 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1332 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1333 profile_
->GetPath()));
1337 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1338 // Init the RLZ library. This just binds the dll and schedules a task on the
1339 // file thread to be run sometime later. If this is the first run we record
1340 // the installation event.
1341 PrefService
* pref_service
= profile_
->GetPrefs();
1342 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1343 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1344 // Negative ping delay means to send ping immediately after a first search is
1346 RLZTracker::InitRlzFromProfileDelayed(
1347 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1348 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1349 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1351 // Configure modules that need access to resources.
1352 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1354 // In unittest mode, this will do nothing. In normal mode, this will create
1355 // the global IntranetRedirectDetector instance, which will promptly go to
1356 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1357 // to see if it should do anything else.
1359 // A simpler way of doing all this would be to have some function which could
1360 // give the time elapsed since startup, and simply have this object check that
1361 // when asked to initialize itself, but this doesn't seem to exist.
1363 // This can't be created in the BrowserProcessImpl constructor because it
1364 // needs to read prefs that get set after that runs.
1365 browser_process_
->intranet_redirect_detector();
1366 GoogleSearchCounter::RegisterForNotifications();
1368 if (parsed_command_line().HasSwitch(switches::kEnableSdchOverHttps
)) {
1369 net::SdchManager::EnableSecureSchemeSupport(true);
1371 // Check SDCH field trial.
1372 const char kSdchFieldTrialName
[] = "SDCH";
1373 const char kEnabledAllGroupName
[] = "EnabledAll";
1374 const char kEnabledHttpOnlyGroupName
[] = "EnabledHttpOnly";
1375 const char kDisabledAllGroupName
[] = "DisabledAll";
1377 base::StringPiece sdch_trial_group
=
1378 base::FieldTrialList::FindFullName(kSdchFieldTrialName
);
1379 if (sdch_trial_group
.starts_with(kEnabledAllGroupName
)) {
1380 net::SdchManager::EnableSecureSchemeSupport(true);
1381 net::SdchManager::EnableSdchSupport(true);
1382 } else if (sdch_trial_group
.starts_with(kEnabledHttpOnlyGroupName
)) {
1383 net::SdchManager::EnableSdchSupport(true);
1384 } else if (sdch_trial_group
.starts_with(kDisabledAllGroupName
)) {
1385 net::SdchManager::EnableSdchSupport(false);
1389 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
1390 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1391 base::FilePath path
=
1392 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1393 printing::PrintedDocument::set_debug_dump_path(path
);
1397 HandleTestParameters(parsed_command_line());
1398 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1399 base::debug::BeingDebugged());
1401 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1402 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1403 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1404 browser_process_
->GetApplicationLocale());
1406 // Start watching for hangs during startup. We disarm this hang detector when
1407 // ThreadWatcher takes over or when browser is shutdown or when
1408 // startup_watcher_ is deleted.
1409 MetricsService::SetExecutionPhase(MetricsService::STARTUP_TIMEBOMB_ARM
,
1410 g_browser_process
->local_state());
1411 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1413 // On mobile, need for clean shutdown arises only when the application comes
1414 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1415 // http://crbug.com/179143
1416 #if !defined(OS_ANDROID)
1417 // Start watching for a hang.
1418 MetricsService::LogNeedForCleanShutdown(g_browser_process
->local_state());
1421 #if defined(ENABLE_FULL_PRINTING)
1422 // Create the instance of the cloud print proxy service so that it can launch
1423 // the service process if needed. This is needed because the service process
1424 // might have shutdown because an update was available.
1425 // TODO(torne): this should maybe be done with
1426 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1428 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1431 // Start watching all browser threads for responsiveness.
1432 MetricsService::SetExecutionPhase(MetricsService::THREAD_WATCHER_START
,
1433 g_browser_process
->local_state());
1434 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1436 #if defined(OS_ANDROID)
1437 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1440 #if !defined(DISABLE_NACL)
1441 BrowserThread::PostTask(
1444 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1447 // Make sure initial prefs are recorded
1448 PrefMetricsService::Factory::GetForProfile(profile_
);
1452 // Instantiate the notification UI manager, as this triggers a perf timer
1453 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1454 // triggering the timer and call that explicitly in the approprate place.
1455 // http://crbug.com/105065.
1456 browser_process_
->notification_ui_manager();
1458 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1459 RegisterComponentsForUpdate();
1461 #if defined(OS_ANDROID)
1462 chrome_variations::VariationsService
* variations_service
=
1463 browser_process_
->variations_service();
1464 if (variations_service
) {
1465 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1466 variations_service
->StartRepeatedVariationsSeedFetch();
1468 translate::TranslateDownloadManager::RequestLanguageList(
1469 profile_
->GetPrefs());
1472 // Most general initialization is behind us, but opening a
1473 // tab and/or session restore and such is still to be done.
1474 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1476 // We are in regular browser boot sequence. Open initial tabs and enter the
1477 // main message loop.
1479 #if defined(OS_CHROMEOS)
1480 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1481 // them this early as the cryptohome hasn't yet been mounted (which happens
1482 // only once we log in.
1483 std::vector
<Profile
*> last_opened_profiles
;
1485 std::vector
<Profile
*> last_opened_profiles
=
1486 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1489 if (browser_creator_
->Start(parsed_command_line(), base::FilePath(),
1490 profile_
, last_opened_profiles
, &result_code
)) {
1491 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1492 // Initialize autoupdate timer. Timer callback costs basically nothing
1493 // when browser is not in persistent mode, so it's OK to let it ride on
1494 // the main thread. This needs to be done here because we don't want
1495 // to start the timer when Chrome is run inside a test harness.
1496 browser_process_
->StartAutoupdateTimer();
1499 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1500 // On Linux, the running exe will be updated if an upgrade becomes
1501 // available while the browser is running. We need to save the last
1502 // modified time of the exe, so we can compare to determine if there is
1503 // an upgrade while the browser is kept alive by a persistent extension.
1504 upgrade_util::SaveLastModifiedTimeOfExe();
1507 // Record now as the last successful chrome start.
1508 GoogleUpdateSettings::SetLastRunTime();
1510 #if defined(OS_MACOSX)
1511 // Call Recycle() here as late as possible, before going into the loop
1512 // because Start() will add things to it while creating the main window.
1513 if (parameters().autorelease_pool
)
1514 parameters().autorelease_pool
->Recycle();
1517 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1518 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1520 // If we're running tests (ui_task is non-null), then we don't want to
1521 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1522 // RequestLanguageList
1523 if (parameters().ui_task
== NULL
) {
1524 // Request new variations seed information from server.
1525 chrome_variations::VariationsService
* variations_service
=
1526 browser_process_
->variations_service();
1527 if (variations_service
) {
1528 variations_service
->StartRepeatedVariationsSeedFetch();
1531 variations_service
->StartGoogleUpdateRegistrySync();
1535 translate::TranslateDownloadManager::RequestLanguageList(
1536 profile_
->GetPrefs());
1539 run_message_loop_
= true;
1541 run_message_loop_
= false;
1543 browser_creator_
.reset();
1544 #endif // !defined(OS_ANDROID)
1546 performance_monitor::PerformanceMonitor::GetInstance()->Initialize();
1550 if (parameters().ui_task
) {
1551 // We end the startup timer here if we have parameters to run, because we
1552 // never start to run the main loop (where we normally stop the timer).
1553 startup_timer_
->SignalStartupComplete(
1554 performance_monitor::StartupTimer::STARTUP_TEST
);
1555 parameters().ui_task
->Run();
1556 delete parameters().ui_task
;
1557 run_message_loop_
= false;
1559 #if defined(OS_ANDROID)
1560 // We never run the C++ main loop on Android, since the UI thread message
1561 // loop is controlled by the OS, so this is as close as we can get to
1562 // the start of the main loop
1563 if (result_code_
<= 0) {
1564 RecordBrowserStartupTime();
1567 return result_code_
;
1570 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1571 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1572 #if defined(OS_ANDROID)
1573 // Chrome on Android does not use default MessageLoop. It has its own
1574 // Android specific MessageLoop
1578 // Set the result code set in PreMainMessageLoopRun or set above.
1579 *result_code
= result_code_
;
1580 if (!run_message_loop_
)
1581 return true; // Don't run the default message loop.
1583 // These should be invoked as close to the start of the browser's
1584 // UI thread message loop as possible to get a stable measurement
1586 RecordBrowserStartupTime();
1587 startup_timer_
->SignalStartupComplete(
1588 performance_monitor::StartupTimer::STARTUP_NORMAL
);
1590 DCHECK(base::MessageLoopForUI::IsCurrent());
1591 base::RunLoop run_loop
;
1593 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1595 MetricsService::SetExecutionPhase(MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1596 g_browser_process
->local_state());
1603 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1604 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1605 #if defined(OS_ANDROID)
1606 // Chrome on Android does not use default MessageLoop. It has its own
1607 // Android specific MessageLoop
1611 // Start watching for jank during shutdown. It gets disarmed when
1612 // |shutdown_watcher_| object is destructed.
1613 MetricsService::SetExecutionPhase(MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1614 g_browser_process
->local_state());
1615 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1617 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1618 startup_watcher_
->Disarm();
1620 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1621 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1623 // Some tests don't set parameters.ui_task, so they started translate
1624 // language fetch that was never completed so we need to cleanup here
1625 // otherwise it will be done by the destructor in a wrong thread.
1626 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1628 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1629 process_singleton_
->Cleanup();
1631 // Stop all tasks that might run on WatchDogThread.
1632 ThreadWatcherList::StopWatchingAll();
1634 browser_process_
->metrics_service()->Stop();
1636 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1637 browser_process_
->StartTearDown();
1641 void ChromeBrowserMainParts::PostDestroyThreads() {
1642 #if defined(OS_ANDROID)
1643 // On Android, there is no quit/exit. So the browser's main message loop will
1647 browser_process_
->PostDestroyThreads();
1648 // browser_shutdown takes care of deleting browser_process, so we need to
1650 ignore_result(browser_process_
.release());
1651 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1652 master_prefs_
.reset();
1653 process_singleton_
.reset();
1655 // We need to do this check as late as possible, but due to modularity, this
1656 // may be the last point in Chrome. This would be more effective if done at
1657 // a higher level on the stack, so that it is impossible for an early return
1658 // to bypass this code. Perhaps we need a *final* hook that is called on all
1659 // paths from content/browser/browser_main.
1660 CHECK(MetricsService::UmaMetricsProperlyShutdown());
1662 #if defined(OS_CHROMEOS)
1663 chromeos::CrosSettings::Shutdown();
1670 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1671 chrome_extra_parts_
.push_back(parts
);