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/extensions/extension_service.h"
53 #include "chrome/browser/extensions/startup_helper.h"
54 #include "chrome/browser/first_run/first_run.h"
55 #include "chrome/browser/first_run/upgrade_util.h"
56 #include "chrome/browser/google/google_search_counter.h"
57 #include "chrome/browser/gpu/gl_string_manager.h"
58 #include "chrome/browser/gpu/three_d_api_observer.h"
59 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
60 #include "chrome/browser/metrics/field_trial_synchronizer.h"
61 #include "chrome/browser/metrics/thread_watcher.h"
62 #include "chrome/browser/metrics/tracking_synchronizer.h"
63 #include "chrome/browser/metrics/variations/variations_service.h"
64 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
65 #include "chrome/browser/net/chrome_net_log.h"
66 #include "chrome/browser/net/crl_set_fetcher.h"
67 #include "chrome/browser/notifications/desktop_notification_service.h"
68 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
69 #include "chrome/browser/performance_monitor/performance_monitor.h"
70 #include "chrome/browser/performance_monitor/startup_timer.h"
71 #include "chrome/browser/plugins/plugin_prefs.h"
72 #include "chrome/browser/power/process_power_collector.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 "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
190 #include "components/nacl/browser/nacl_process_host.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
);
346 profile
= g_browser_process
->profile_manager()->GetProfile(
349 // If we're using the --new-profile-management flag and this profile is
350 // signed out, then we should show the user manager instead. By switching
351 // the active profile to the guest profile we ensure that no
352 // browser windows will be opened for the guest profile.
353 if (switches::IsNewProfileManagement() && !profile
->IsGuestSession()) {
354 ProfileInfoCache
& cache
=
355 g_browser_process
->profile_manager()->GetProfileInfoCache();
356 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
358 if (cache
.ProfileIsSigninRequiredAtIndex(profile_index
))
359 profile
= g_browser_process
->profile_manager()->GetProfile(
360 ProfileManager::GetGuestProfilePath());
364 UMA_HISTOGRAM_LONG_TIMES(
365 "Startup.CreateFirstProfile", base::Time::Now() - start
);
370 // TODO(port): fix this. See comments near the definition of
371 // user_data_dir. It is better to CHECK-fail here than it is to
372 // silently exit because of missing code in the above test.
373 CHECK(profile
) << "Cannot get default profile.";
379 #if defined(OS_MACOSX)
380 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
381 SecKeychainCallbackInfo
* info
, void* context
) {
386 void RegisterComponentsForUpdate() {
387 component_updater::ComponentUpdateService
* cus
=
388 g_browser_process
->component_updater();
390 // Registration can be before or after cus->Start() so it is ok to post
391 // a task to the UI thread to do registration once you done the necessary
392 // file IO to know you existing component version.
393 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
394 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
395 RegisterPepperFlashComponent(cus
);
396 RegisterSwiftShaderComponent(cus
);
397 RegisterWidevineCdmComponent(cus
);
398 #if !defined(DISABLE_NACL)
399 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
403 if (translate::CldDataSource::ShouldRegisterForComponentUpdates()) {
404 RegisterCldComponent(cus
);
408 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
409 #if defined(OS_ANDROID)
410 // The CRLSet component was enabled for some releases. This code attempts to
411 // delete it from the local disk of those how may have downloaded it.
412 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
413 #elif !defined(OS_CHROMEOS)
414 // CRLSetFetcher attempts to load a CRL set from either the local disk or
416 // For Chrome OS this registration is delayed until user login.
417 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
421 #if !defined(OS_ANDROID)
422 // Android does not currently have the EV indicator. No need to get the
423 // EV certs whitelist on Android, then.
424 RegisterEVWhitelistComponent(cus
);
428 ExecutePendingSwReporter(cus
, g_browser_process
->local_state());
434 #if !defined(OS_ANDROID)
435 bool ProcessSingletonNotificationCallback(
436 const CommandLine
& command_line
,
437 const base::FilePath
& current_directory
) {
438 // Drop the request if the browser process is already in shutdown path.
439 if (!g_browser_process
|| g_browser_process
->IsShuttingDown())
442 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
443 std::string start_time_string
=
444 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
445 int64 remote_start_time
;
446 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
447 base::TimeDelta elapsed
=
448 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
449 if (command_line
.HasSwitch(switches::kFastStart
)) {
450 UMA_HISTOGRAM_LONG_TIMES(
451 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
453 UMA_HISTOGRAM_LONG_TIMES(
454 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
459 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
462 base::FilePath user_data_dir
=
463 g_browser_process
->profile_manager()->user_data_dir();
464 base::FilePath startup_profile_dir
=
465 GetStartupProfilePath(user_data_dir
, command_line
);
467 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
468 command_line
, current_directory
, startup_profile_dir
);
471 #endif // !defined(OS_ANDROID)
473 void LaunchDevToolsHandlerIfNeeded(const CommandLine
& command_line
) {
474 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
475 std::string port_str
=
476 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
478 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
479 g_browser_process
->CreateDevToolsHttpProtocolHandler(
480 chrome::HOST_DESKTOP_TYPE_NATIVE
,
484 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
489 // Heap allocated class that listens for first page load, kicks off stat
490 // recording and then deletes itself.
491 class LoadCompleteListener
: public content::NotificationObserver
{
493 LoadCompleteListener() {
495 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
496 content::NotificationService::AllSources());
498 virtual ~LoadCompleteListener() {}
500 // content::NotificationObserver implementation.
501 virtual void Observe(int type
,
502 const content::NotificationSource
& source
,
503 const content::NotificationDetails
& details
) OVERRIDE
{
504 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
505 startup_metric_utils::OnInitialPageLoadComplete();
510 content::NotificationRegistrar registrar_
;
511 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
516 namespace chrome_browser
{
518 // This error message is not localized because we failed to load the
519 // localization data files.
521 const char kMissingLocaleDataTitle
[] = "Missing File Error";
525 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
526 const char kMissingLocaleDataMessage
[] =
527 "Unable to find locale data files. Please reinstall.";
530 } // namespace chrome_browser
532 // BrowserMainParts ------------------------------------------------------------
535 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_
=
538 ChromeBrowserMainParts::ChromeBrowserMainParts(
539 const content::MainFunctionParams
& parameters
)
540 : parameters_(parameters
),
541 parsed_command_line_(parameters
.command_line
),
542 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
543 startup_watcher_(new StartupTimeBomb()),
544 shutdown_watcher_(new ShutdownWatcherHelper()),
545 startup_timer_(new performance_monitor::StartupTimer()),
546 browser_field_trials_(parameters
.command_line
),
548 run_message_loop_(true),
549 notify_result_(ProcessSingleton::PROCESS_NONE
),
551 restart_last_session_(false) {
552 // If we're running tests (ui_task is non-null).
553 if (parameters
.ui_task
)
554 browser_defaults::enable_help_app
= false;
556 // Chrome disallows cookies by default. All code paths that want to use
557 // cookies need to go through one of Chrome's URLRequestContexts which have
558 // a ChromeNetworkDelegate attached that selectively allows cookies again.
559 if (!disable_enforcing_cookie_policies_for_tests_
)
560 net::URLRequest::SetDefaultCookiePolicyToBlock();
563 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
564 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
565 delete chrome_extra_parts_
[i
];
566 chrome_extra_parts_
.clear();
569 // This will be called after the command-line has been mutated by about:flags
570 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
571 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
572 // Must initialize metrics after labs have been converted into switches,
573 // but before field trials are set up (so that client ID is available for
574 // one-time randomized field trials).
576 // Initialize FieldTrialList to support FieldTrials that use one-time
578 metrics::MetricsService
* metrics
= browser_process_
->metrics_service();
579 field_trial_list_
.reset(
580 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
582 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
583 if (command_line
->HasSwitch(switches::kEnableBenchmarking
))
584 base::FieldTrial::EnableBenchmarking();
586 // Ensure any field trials specified on the command line are initialized.
587 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
588 std::set
<std::string
> unforceable_field_trials
;
589 #if defined(OFFICIAL_BUILD)
590 unforceable_field_trials
.insert("SettingsEnforcement");
591 #endif // defined(OFFICIAL_BUILD)
593 // Create field trials without activating them, so that this behaves in a
594 // consistent manner with field trials created from the server.
595 bool result
= base::FieldTrialList::CreateTrialsFromString(
596 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
597 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
598 unforceable_field_trials
);
599 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
600 << " list specified.";
602 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
603 // Create default variation ids which will always be included in the
604 // X-Client-Data request header.
605 variations::VariationsHttpHeaderProvider
* provider
=
606 variations::VariationsHttpHeaderProvider::GetInstance();
607 bool result
= provider
->SetDefaultVariationIds(
608 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
609 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
610 << " list specified.";
612 chrome_variations::VariationsService
* variations_service
=
613 browser_process_
->variations_service();
614 if (variations_service
)
615 variations_service
->CreateTrialsFromSeed();
617 // This must be called after |local_state_| is initialized.
618 browser_field_trials_
.SetupFieldTrials(
619 base::Time::FromTimeT(metrics
->GetInstallDate()), local_state_
);
621 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
622 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
623 // Even though base::Bind does AddRef and Release, the object will not be
624 // deleted after the Task is executed.
625 field_trial_synchronizer_
= new FieldTrialSynchronizer();
627 // Now that field trials have been created, initializes metrics recording.
628 metrics
->InitializeMetricsRecordingState();
631 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
633 void ChromeBrowserMainParts::StartMetricsRecording() {
634 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
635 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
637 const bool only_do_metrics_recording
=
638 parsed_command_line_
.HasSwitch(switches::kMetricsRecordingOnly
) ||
639 parsed_command_line_
.HasSwitch(switches::kEnableBenchmarking
);
640 if (only_do_metrics_recording
) {
641 // If we're testing then we don't care what the user preference is, we turn
642 // on recording, but not reporting, otherwise tests fail.
643 metrics
->StartRecordingForTests();
647 metrics
->CheckForClonedInstall(
648 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
649 const bool metrics_enabled
= metrics
->StartIfMetricsReportingEnabled();
650 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is
651 // currently disabled there. http://crbug.com/370041
652 browser_process_
->rappor_service()->Start(
653 browser_process_
->local_state(),
654 browser_process_
->system_request_context(),
658 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
659 // Don't record any metrics if UI was displayed before this point e.g.
661 if (startup_metric_utils::WasNonBrowserUIDisplayed())
664 #if defined(OS_ANDROID)
665 // On Android the first run is handled in Java code, and the C++ side of
666 // Chrome doesn't know if this is the first run. This will cause some
667 // inaccuracy in the UMA statistics, but this should be minor (first runs are
669 bool is_first_run
= false;
671 bool is_first_run
= first_run::IsChromeFirstRun();
674 // CurrentProcessInfo::CreationTime() is currently only implemented on some
676 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
677 const base::Time process_creation_time
=
678 base::CurrentProcessInfo::CreationTime();
680 if (!is_first_run
&& !process_creation_time
.is_null()) {
681 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
682 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
684 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
686 // Record collected startup metrics.
687 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
690 new LoadCompleteListener();
693 // -----------------------------------------------------------------------------
694 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
697 #define DLLEXPORT __declspec(dllexport)
699 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
701 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
704 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
705 // Need an instance of AtExitManager to handle singleton creations and
706 // deletions. We need this new instance because, the old instance created
707 // in ChromeMain() got destructed when the function returned.
708 base::AtExitManager exit_manager
;
709 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
713 // content::BrowserMainParts implementation ------------------------------------
715 void ChromeBrowserMainParts::PreEarlyInitialization() {
716 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
717 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
718 chrome_extra_parts_
[i
]->PreEarlyInitialization();
721 void ChromeBrowserMainParts::PostEarlyInitialization() {
722 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
723 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
724 chrome_extra_parts_
[i
]->PostEarlyInitialization();
727 void ChromeBrowserMainParts::ToolkitInitialized() {
728 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
729 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
730 chrome_extra_parts_
[i
]->ToolkitInitialized();
733 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
734 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
735 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
736 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
739 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
740 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
741 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
742 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
745 int ChromeBrowserMainParts::PreCreateThreads() {
746 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
747 result_code_
= PreCreateThreadsImpl();
749 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
750 #if !defined(OS_ANDROID)
751 // These members must be initialized before exiting this function normally.
752 DCHECK(master_prefs_
.get());
753 DCHECK(browser_creator_
.get());
755 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
756 chrome_extra_parts_
[i
]->PreCreateThreads();
762 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
763 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
764 run_message_loop_
= false;
765 #if !defined(OS_ANDROID)
766 chrome::MaybeShowInvalidUserDataDirWarningDialog();
768 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
769 return chrome::RESULT_CODE_MISSING_DATA
;
771 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
772 MediaCaptureDevicesDispatcher::GetInstance();
774 // Android's first run is done in Java instead of native.
775 #if !defined(OS_ANDROID)
776 process_singleton_
.reset(new ChromeProcessSingleton(
777 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
779 // Cache first run state early.
780 first_run::IsChromeFirstRun();
783 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
784 JsonPrefStore::GetTaskRunnerForFile(
785 base::FilePath(chrome::kLocalStorePoolName
),
786 BrowserThread::GetBlockingPool());
789 TRACE_EVENT0("startup",
790 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
791 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
792 parsed_command_line()));
795 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
796 TRACE_EVENT0("startup",
797 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
798 // User wants to override default tracking status.
800 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
801 // Default to basic profiling (no parent child support).
802 tracked_objects::ThreadData::Status status
=
803 tracked_objects::ThreadData::PROFILING_ACTIVE
;
804 if (flag
.compare("0") != 0)
805 status
= tracked_objects::ThreadData::DEACTIVATED
;
806 else if (flag
.compare("child") != 0)
807 status
= tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE
;
808 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
811 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile
)) {
812 tracking_objects_
.set_output_file_path(
813 parsed_command_line().GetSwitchValuePath(
814 switches::kProfilingOutputFile
));
817 local_state_
= InitializeLocalState(
818 local_state_task_runner
.get(), parsed_command_line());
820 #if !defined(OS_ANDROID)
821 // These members must be initialized before returning from this function.
822 master_prefs_
.reset(new first_run::MasterPrefs
);
823 // Android doesn't use StartupBrowserCreator.
824 browser_creator_
.reset(new StartupBrowserCreator
);
825 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
826 chrome::UMABrowsingActivityObserver::Init();
829 #if !defined(OS_CHROMEOS)
830 // Convert active labs into switches. This needs to be done before
831 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
832 // affected by experiment flags (--touch-optimized-ui in particular).
833 // On ChromeOS system level flags are applied from the device settings from
834 // the session manager.
836 TRACE_EVENT0("startup",
837 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
838 about_flags::PrefServiceFlagsStorage
flags_storage_(
839 g_browser_process
->local_state());
840 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
841 CommandLine::ForCurrentProcess(),
842 about_flags::kAddSentinels
);
846 local_state_
->UpdateCommandLinePrefStore(
847 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
849 // Reset the command line in the crash report details, since we may have
850 // just changed it to include experiments.
851 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
853 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
854 // needed when loading the MainMenu.nib and the language doesn't depend on
855 // anything since it comes from Cocoa.
856 #if defined(OS_MACOSX)
858 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
859 browser_process_
->SetApplicationLocale(locale
);
861 const std::string locale
=
862 local_state_
->GetString(prefs::kApplicationLocale
);
864 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
865 // method InitSharedInstance is ignored.
867 TRACE_EVENT_BEGIN0("startup",
868 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
869 const std::string loaded_locale
=
870 ui::ResourceBundle::InitSharedInstanceWithLocale(
871 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
872 TRACE_EVENT_END0("startup",
873 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
875 if (loaded_locale
.empty() &&
876 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
877 ShowMissingLocaleMessageBox();
878 return chrome::RESULT_CODE_MISSING_DATA
;
880 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
881 browser_process_
->SetApplicationLocale(loaded_locale
);
883 base::FilePath resources_pack_path
;
884 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
886 TRACE_EVENT0("startup",
887 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
888 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
889 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
891 #endif // defined(OS_MACOSX)
893 // Android does first run in Java instead of native.
894 // Chrome OS has its own out-of-box-experience code.
895 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
896 // On first run, we need to process the predictor preferences before the
897 // browser's profile_manager object is created, but after ResourceBundle
899 if (first_run::IsChromeFirstRun()) {
900 first_run::ProcessMasterPreferencesResult pmp_result
=
901 first_run::ProcessMasterPreferences(user_data_dir_
,
902 master_prefs_
.get());
903 if (pmp_result
== first_run::EULA_EXIT_NOW
)
904 return chrome::RESULT_CODE_EULA_REFUSED
;
906 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
907 !parsed_command_line().HasSwitch(switches::kAppId
) &&
908 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
909 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
912 // TODO(macourteau): refactor preferences that are copied from
913 // master_preferences into local_state, as a "local_state" section in
914 // master preferences. If possible, a generic solution would be preferred
915 // over a copy one-by-one of specific preferences. Also see related TODO
918 // Store the initial VariationsService seed in local state, if it exists
920 if (!master_prefs_
->variations_seed
.empty()) {
921 local_state_
->SetString(prefs::kVariationsSeed
,
922 master_prefs_
->variations_seed
);
923 if (!master_prefs_
->variations_seed_signature
.empty()) {
924 local_state_
->SetString(prefs::kVariationsSeedSignature
,
925 master_prefs_
->variations_seed_signature
);
927 // Set the variation seed date to the current system time. If the user's
928 // clock is incorrect, this may cause some field trial expiry checks to
929 // not do the right thing until the next seed update from the server,
930 // when this value will be updated.
931 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
932 base::Time::Now().ToInternalValue());
935 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
936 local_state_
->SetString(
937 prefs::kBrowserSuppressDefaultBrowserPrompt
,
938 master_prefs_
->suppress_default_browser_prompt_for_version
);
941 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE
)->HandleFirstRun();
945 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
946 // Set the product channel for crash reports.
947 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
948 chrome::VersionInfo::GetVersionStringModifier());
951 // Initialize tracking synchronizer system.
952 tracking_synchronizer_
= new chrome_browser_metrics::TrackingSynchronizer();
954 #if defined(OS_MACOSX)
955 // Get the Keychain API to register for distributed notifications on the main
956 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
957 // which doesn't. This ensures those notifications will get delivered
958 // properly. See issue 37766.
959 // (Note that the callback mask here is empty. I don't want to register for
960 // any callbacks, I just want to initialize the mechanism.)
961 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
964 #if defined(OS_CHROMEOS)
965 // Must be done after g_browser_process is constructed, before
966 // SetupMetricsAndFieldTrials().
967 chromeos::CrosSettings::Initialize();
970 // Now the command line has been mutated based on about:flags, we can setup
971 // metrics and initialize field trials. The field trials are needed by
972 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
973 SetupMetricsAndFieldTrials();
975 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
976 browser_process_
->PreCreateThreads();
978 return content::RESULT_CODE_NORMAL_EXIT
;
981 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
982 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
983 result_code_
= PreMainMessageLoopRunImpl();
985 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
986 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
989 // PreMainMessageLoopRun calls these extra stages in the following order:
990 // PreMainMessageLoopRunImpl()
991 // ... initial setup, including browser_process_ setup.
993 // ... additional setup, including CreateProfile()
995 // ... additional setup
997 // ... browser_creator_->Start (OR parameters().ui_task->Run())
998 // PostBrowserStart()
1000 void ChromeBrowserMainParts::PreProfileInit() {
1001 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1003 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1004 chrome_extra_parts_
[i
]->PreProfileInit();
1006 #if !defined(OS_ANDROID)
1007 // Initialize the feedback uploader so it can setup notifications for profile
1009 feedback::FeedbackProfileObserver::Initialize();
1011 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
1013 // First check if any ephemeral profiles are left behind because of browser
1014 // crash and schedule them for deletion and then proceed with getting the set
1015 // of profiles to open.
1016 ProfileInfoCache
& profile_cache
= profile_manager
->GetProfileInfoCache();
1017 size_t profiles_count
= profile_cache
.GetNumberOfProfiles();
1018 std::vector
<base::FilePath
> profiles_to_delete
;
1019 for (size_t i
= 0; i
< profiles_count
; ++i
) {
1020 if (profile_cache
.ProfileIsEphemeralAtIndex(i
))
1021 profiles_to_delete
.push_back(profile_cache
.GetPathOfProfileAtIndex(i
));
1024 if (profiles_to_delete
.size()) {
1025 for (size_t i
= 0; i
< profiles_to_delete
.size(); ++i
) {
1026 profile_manager
->ScheduleProfileForDeletion(
1027 profiles_to_delete
[i
], ProfileManager::CreateCallback());
1029 // Clean up stale profiles immediately after browser start.
1030 BrowserThread::PostTask(
1031 BrowserThread::FILE, FROM_HERE
,
1032 base::Bind(&ProfileManager::CleanUpStaleProfiles
, profiles_to_delete
));
1034 #endif // OS_ANDROID
1037 void ChromeBrowserMainParts::PostProfileInit() {
1038 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1039 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1040 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1041 chrome_extra_parts_
[i
]->PostProfileInit();
1044 void ChromeBrowserMainParts::PreBrowserStart() {
1045 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1046 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1047 chrome_extra_parts_
[i
]->PreBrowserStart();
1049 three_d_observer_
.reset(new ThreeDAPIObserver());
1052 void ChromeBrowserMainParts::PostBrowserStart() {
1053 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1054 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1055 chrome_extra_parts_
[i
]->PostBrowserStart();
1056 #if !defined(OS_ANDROID)
1057 // Allow ProcessSingleton to process messages.
1058 process_singleton_
->Unlock();
1060 #if defined(ENABLE_WEBRTC)
1061 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1062 // to reduce the impact on startup time.
1063 BrowserThread::PostDelayedTask(
1066 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1067 base::TimeDelta::FromMinutes(1));
1071 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1072 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1073 // Android updates the metrics service dynamically depending on whether the
1074 // application is in the foreground or not. Do not start here.
1075 #if !defined(OS_ANDROID)
1076 // Now that the file thread has been started, start recording.
1077 StartMetricsRecording();
1080 // Create watchdog thread after creating all other threads because it will
1081 // watch the other threads and they must be running.
1082 browser_process_
->watchdog_thread();
1084 // Do any initializating in the browser process that requires all threads
1086 browser_process_
->PreMainMessageLoopRun();
1088 // Record last shutdown time into a histogram.
1089 browser_shutdown::ReadLastShutdownInfo();
1092 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1093 // tasks. Those care whether the browser is already running. On Linux/Mac,
1094 // upgrade/uninstall happen separately.
1095 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1097 // If the command line specifies 'uninstall' then we need to work here
1098 // unless we detect another chrome browser running.
1099 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1100 return DoUninstallTasks(already_running
);
1103 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1104 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1105 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1106 parsed_command_line_
);
1109 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1110 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1113 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1114 return ShellIntegration::SetAsDefaultBrowser() ?
1115 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1116 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1119 #if defined(USE_AURA)
1120 // Make sure aura::Env has been initialized.
1121 CHECK(aura::Env::GetInstance());
1124 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1125 #if !defined(OS_ANDROID)
1126 // If the command line specifies --pack-extension, attempt the pack extension
1127 // startup action and exit.
1128 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1129 extensions::StartupHelper extension_startup_helper
;
1130 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1131 return content::RESULT_CODE_NORMAL_EXIT
;
1132 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1135 // If we're being launched just to check the connector policy, we are
1136 // short-lived and don't want to be passing that switch off.
1137 bool pass_command_line
= !parsed_command_line().HasSwitch(
1138 switches::kCheckCloudPrintConnectorPolicy
);
1140 if (pass_command_line
) {
1141 // When another process is running, use that process instead of starting a
1142 // new one. NotifyOtherProcess will currently give the other process up to
1143 // 20 seconds to respond. Note that this needs to be done before we attempt
1144 // to read the profile.
1145 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1146 switch (notify_result_
) {
1147 case ProcessSingleton::PROCESS_NONE
:
1148 // No process already running, fall through to starting a new one.
1151 case ProcessSingleton::PROCESS_NOTIFIED
:
1152 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1153 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1154 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1156 // Having a differentiated return type for testing allows for tests to
1157 // verify proper handling of some switches. When not testing, stick to
1158 // the standard Unix convention of returning zero when things went as
1160 if (parsed_command_line().HasSwitch(switches::kTestType
))
1161 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1162 return content::RESULT_CODE_NORMAL_EXIT
;
1164 case ProcessSingleton::PROFILE_IN_USE
:
1165 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1167 case ProcessSingleton::LOCK_ERROR
:
1168 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1169 "directory. This means that running multiple instances "
1170 "would start multiple browser processes rather than "
1171 "opening a new window in the existing process. Aborting "
1172 "now to avoid profile corruption.";
1173 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1179 #endif // !defined(OS_ANDROID)
1181 // Handle special early return paths (which couldn't be processed even earlier
1182 // as they require the process singleton to be held) first.
1184 std::string try_chrome
=
1185 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1186 if (!try_chrome
.empty()) {
1188 // Setup.exe has determined that we need to run a retention experiment
1189 // and has lauched chrome to show the experiment UI. It is guaranteed that
1190 // no other Chrome is currently running as the process singleton was
1191 // sucessfully grabbed above.
1193 base::StringToInt(try_chrome
, &try_chrome_int
);
1194 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1196 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1197 base::Unretained(process_singleton_
.get())));
1198 if (answer
== TryChromeDialogView::NOT_NOW
)
1199 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1200 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1201 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1202 // At this point the user is willing to try chrome again.
1203 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1204 // Only set in the unattended case, the interactive case is Windows 8.
1205 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1206 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1207 ShellIntegration::SetAsDefaultBrowser();
1210 // We don't support retention experiments on Mac or Linux.
1211 return content::RESULT_CODE_NORMAL_EXIT
;
1212 #endif // defined(OS_WIN)
1216 // Do the tasks if chrome has been upgraded while it was last running.
1217 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1218 return content::RESULT_CODE_NORMAL_EXIT
;
1220 // Check if there is any machine level Chrome installed on the current
1221 // machine. If yes and the current Chrome process is user level, we do not
1222 // allow the user level Chrome to run. So we notify the user and uninstall
1223 // user level Chrome.
1224 // Note this check needs to happen here (after the process singleton was
1225 // obtained but before potentially creating the first run sentinel).
1226 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1227 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1228 #endif // defined(OS_WIN)
1230 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1231 if (sxs_linux::ShouldMigrateUserDataDir())
1232 return sxs_linux::MigrateUserDataDir();
1233 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1235 // Desktop construction occurs here, (required before profile creation).
1238 // Profile creation ----------------------------------------------------------
1240 metrics::MetricsService::SetExecutionPhase(
1241 metrics::MetricsService::CREATE_PROFILE
,
1242 g_browser_process
->local_state());
1243 profile_
= CreatePrimaryProfile(parameters(),
1245 parsed_command_line());
1247 return content::RESULT_CODE_NORMAL_EXIT
;
1249 #if !defined(OS_ANDROID)
1250 // The first run sentinel must be created after the process singleton was
1251 // grabbed and no early return paths were otherwise hit above.
1252 first_run::CreateSentinelIfNeeded();
1253 #endif // !defined(OS_ANDROID)
1255 #if defined(ENABLE_BACKGROUND)
1256 // Autoload any profiles which are running background apps.
1257 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1258 browser_process_
->profile_manager()->AutoloadProfiles();
1260 // Post-profile init ---------------------------------------------------------
1262 TranslateService::Initialize();
1264 // Needs to be done before PostProfileInit, since login manager on CrOS is
1265 // called inside PostProfileInit.
1266 content::WebUIControllerFactory::RegisterFactory(
1267 ChromeWebUIControllerFactory::GetInstance());
1269 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1270 // So make sure to create it before that.
1271 #if !defined(DISABLE_NACL)
1272 NaClBrowserDelegateImpl
* delegate
=
1273 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1274 nacl::NaClBrowser::SetDelegate(delegate
);
1277 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1278 // (requires supporting early exit).
1281 // Retrieve cached GL strings from local state and use them for GPU
1282 // blacklist decisions.
1283 if (g_browser_process
->gl_string_manager())
1284 g_browser_process
->gl_string_manager()->Initialize();
1286 // Create an instance of GpuModeManager to watch gpu mode pref change.
1287 g_browser_process
->gpu_mode_manager();
1289 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1290 // Show the First Run UI if this is the first time Chrome has been run on
1291 // this computer, or we're being compelled to do so by a command line flag.
1292 // Note that this be done _after_ the PrefService is initialized and all
1293 // preferences are registered, since some of the code that the importer
1294 // touches reads preferences.
1295 if (first_run::IsChromeFirstRun()) {
1296 first_run::AutoImport(profile_
,
1297 master_prefs_
->homepage_defined
,
1298 master_prefs_
->do_import_items
,
1299 master_prefs_
->dont_import_items
,
1300 master_prefs_
->import_bookmarks_path
);
1302 // Note: this can pop the first run consent dialog on linux.
1303 first_run::DoPostImportTasks(profile_
,
1304 master_prefs_
->make_chrome_default_for_user
);
1306 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1307 browser_creator_
->set_show_main_browser_window(
1308 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1310 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1313 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1316 // Sets things up so that if we crash from this point on, a dialog will
1317 // popup asking the user to restart chrome. It is done this late to avoid
1318 // testing against a bunch of special cases that are taken care early on.
1319 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1320 parsed_command_line());
1322 // Registers Chrome with the Windows Restart Manager, which will restore the
1323 // Chrome session when the computer is restarted after a system update.
1324 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1325 // but should run on startup if extended to handle crashes/hangs/patches.
1326 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1327 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1328 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1329 parsed_command_line());
1332 // Verify that the profile is not on a network share and if so prepare to show
1333 // notification to the user.
1334 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1335 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1336 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1337 profile_
->GetPath()));
1341 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1342 // Init the RLZ library. This just binds the dll and schedules a task on the
1343 // file thread to be run sometime later. If this is the first run we record
1344 // the installation event.
1345 PrefService
* pref_service
= profile_
->GetPrefs();
1346 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1347 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1348 // Negative ping delay means to send ping immediately after a first search is
1350 RLZTracker::InitRlzFromProfileDelayed(
1351 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1352 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1353 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1355 // Configure modules that need access to resources.
1356 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1358 // In unittest mode, this will do nothing. In normal mode, this will create
1359 // the global IntranetRedirectDetector instance, which will promptly go to
1360 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1361 // to see if it should do anything else.
1363 // A simpler way of doing all this would be to have some function which could
1364 // give the time elapsed since startup, and simply have this object check that
1365 // when asked to initialize itself, but this doesn't seem to exist.
1367 // This can't be created in the BrowserProcessImpl constructor because it
1368 // needs to read prefs that get set after that runs.
1369 browser_process_
->intranet_redirect_detector();
1370 GoogleSearchCounter::RegisterForNotifications();
1372 if (parsed_command_line().HasSwitch(switches::kEnableSdchOverHttps
)) {
1373 net::SdchManager::EnableSecureSchemeSupport(true);
1375 // Check SDCH field trial.
1376 const char kSdchFieldTrialName
[] = "SDCH";
1377 const char kEnabledAllGroupName
[] = "EnabledAll";
1378 const char kEnabledHttpOnlyGroupName
[] = "EnabledHttpOnly";
1379 const char kDisabledAllGroupName
[] = "DisabledAll";
1381 base::StringPiece sdch_trial_group
=
1382 base::FieldTrialList::FindFullName(kSdchFieldTrialName
);
1383 if (sdch_trial_group
.starts_with(kEnabledAllGroupName
)) {
1384 net::SdchManager::EnableSecureSchemeSupport(true);
1385 net::SdchManager::EnableSdchSupport(true);
1386 } else if (sdch_trial_group
.starts_with(kEnabledHttpOnlyGroupName
)) {
1387 net::SdchManager::EnableSdchSupport(true);
1388 } else if (sdch_trial_group
.starts_with(kDisabledAllGroupName
)) {
1389 net::SdchManager::EnableSdchSupport(false);
1393 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
1394 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1395 base::FilePath path
=
1396 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1397 printing::PrintedDocument::set_debug_dump_path(path
);
1401 HandleTestParameters(parsed_command_line());
1402 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1403 base::debug::BeingDebugged());
1405 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1406 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1407 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1408 browser_process_
->GetApplicationLocale());
1410 // Start watching for hangs during startup. We disarm this hang detector when
1411 // ThreadWatcher takes over or when browser is shutdown or when
1412 // startup_watcher_ is deleted.
1413 metrics::MetricsService::SetExecutionPhase(
1414 metrics::MetricsService::STARTUP_TIMEBOMB_ARM
,
1415 g_browser_process
->local_state());
1416 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1418 // On mobile, need for clean shutdown arises only when the application comes
1419 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1420 // http://crbug.com/179143
1421 #if !defined(OS_ANDROID)
1422 // Start watching for a hang.
1423 metrics::MetricsService::LogNeedForCleanShutdown(
1424 g_browser_process
->local_state());
1427 #if defined(ENABLE_FULL_PRINTING)
1428 // Create the instance of the cloud print proxy service so that it can launch
1429 // the service process if needed. This is needed because the service process
1430 // might have shutdown because an update was available.
1431 // TODO(torne): this should maybe be done with
1432 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1434 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1437 // Start watching all browser threads for responsiveness.
1438 metrics::MetricsService::SetExecutionPhase(
1439 metrics::MetricsService::THREAD_WATCHER_START
,
1440 g_browser_process
->local_state());
1441 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1443 #if defined(OS_ANDROID)
1444 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1447 #if !defined(DISABLE_NACL)
1448 BrowserThread::PostTask(
1451 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1454 // Make sure initial prefs are recorded
1455 PrefMetricsService::Factory::GetForProfile(profile_
);
1459 // Instantiate the notification UI manager, as this triggers a perf timer
1460 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1461 // triggering the timer and call that explicitly in the approprate place.
1462 // http://crbug.com/105065.
1463 browser_process_
->notification_ui_manager();
1465 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1466 RegisterComponentsForUpdate();
1468 #if defined(OS_ANDROID)
1469 chrome_variations::VariationsService
* variations_service
=
1470 browser_process_
->variations_service();
1471 if (variations_service
) {
1472 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1473 variations_service
->StartRepeatedVariationsSeedFetch();
1475 translate::TranslateDownloadManager::RequestLanguageList(
1476 profile_
->GetPrefs());
1479 // Most general initialization is behind us, but opening a
1480 // tab and/or session restore and such is still to be done.
1481 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1483 // We are in regular browser boot sequence. Open initial tabs and enter the
1484 // main message loop.
1486 #if defined(OS_CHROMEOS)
1487 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1488 // them this early as the cryptohome hasn't yet been mounted (which happens
1489 // only once we log in.
1490 std::vector
<Profile
*> last_opened_profiles
;
1492 std::vector
<Profile
*> last_opened_profiles
=
1493 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1496 if (browser_creator_
->Start(parsed_command_line(), base::FilePath(),
1497 profile_
, last_opened_profiles
, &result_code
)) {
1498 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1499 // Initialize autoupdate timer. Timer callback costs basically nothing
1500 // when browser is not in persistent mode, so it's OK to let it ride on
1501 // the main thread. This needs to be done here because we don't want
1502 // to start the timer when Chrome is run inside a test harness.
1503 browser_process_
->StartAutoupdateTimer();
1506 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1507 // On Linux, the running exe will be updated if an upgrade becomes
1508 // available while the browser is running. We need to save the last
1509 // modified time of the exe, so we can compare to determine if there is
1510 // an upgrade while the browser is kept alive by a persistent extension.
1511 upgrade_util::SaveLastModifiedTimeOfExe();
1514 // Record now as the last successful chrome start.
1515 GoogleUpdateSettings::SetLastRunTime();
1517 #if defined(OS_MACOSX)
1518 // Call Recycle() here as late as possible, before going into the loop
1519 // because Start() will add things to it while creating the main window.
1520 if (parameters().autorelease_pool
)
1521 parameters().autorelease_pool
->Recycle();
1524 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1525 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1527 // If we're running tests (ui_task is non-null), then we don't want to
1528 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1529 // RequestLanguageList
1530 if (parameters().ui_task
== NULL
) {
1531 // Request new variations seed information from server.
1532 chrome_variations::VariationsService
* variations_service
=
1533 browser_process_
->variations_service();
1534 if (variations_service
) {
1535 variations_service
->StartRepeatedVariationsSeedFetch();
1538 variations_service
->StartGoogleUpdateRegistrySync();
1542 translate::TranslateDownloadManager::RequestLanguageList(
1543 profile_
->GetPrefs());
1546 run_message_loop_
= true;
1548 run_message_loop_
= false;
1550 browser_creator_
.reset();
1551 #endif // !defined(OS_ANDROID)
1553 performance_monitor::PerformanceMonitor::GetInstance()->Initialize();
1555 #if !defined(OS_ANDROID)
1556 process_power_collector_
.reset(new ProcessPowerCollector
);
1557 process_power_collector_
->Initialize();
1562 if (parameters().ui_task
) {
1563 // We end the startup timer here if we have parameters to run, because we
1564 // never start to run the main loop (where we normally stop the timer).
1565 startup_timer_
->SignalStartupComplete(
1566 performance_monitor::StartupTimer::STARTUP_TEST
);
1567 parameters().ui_task
->Run();
1568 delete parameters().ui_task
;
1569 run_message_loop_
= false;
1571 #if defined(OS_ANDROID)
1572 // We never run the C++ main loop on Android, since the UI thread message
1573 // loop is controlled by the OS, so this is as close as we can get to
1574 // the start of the main loop
1575 if (result_code_
<= 0) {
1576 RecordBrowserStartupTime();
1579 return result_code_
;
1582 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1583 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1584 #if defined(OS_ANDROID)
1585 // Chrome on Android does not use default MessageLoop. It has its own
1586 // Android specific MessageLoop
1590 // Set the result code set in PreMainMessageLoopRun or set above.
1591 *result_code
= result_code_
;
1592 if (!run_message_loop_
)
1593 return true; // Don't run the default message loop.
1595 // These should be invoked as close to the start of the browser's
1596 // UI thread message loop as possible to get a stable measurement
1598 RecordBrowserStartupTime();
1599 startup_timer_
->SignalStartupComplete(
1600 performance_monitor::StartupTimer::STARTUP_NORMAL
);
1602 DCHECK(base::MessageLoopForUI::IsCurrent());
1603 base::RunLoop run_loop
;
1605 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1607 metrics::MetricsService::SetExecutionPhase(
1608 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1609 g_browser_process
->local_state());
1616 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1617 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1618 #if defined(OS_ANDROID)
1619 // Chrome on Android does not use default MessageLoop. It has its own
1620 // Android specific MessageLoop
1624 // Start watching for jank during shutdown. It gets disarmed when
1625 // |shutdown_watcher_| object is destructed.
1626 metrics::MetricsService::SetExecutionPhase(
1627 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1628 g_browser_process
->local_state());
1629 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1631 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1632 startup_watcher_
->Disarm();
1634 // Remove observers attached to D-Bus clients before DbusThreadManager is
1636 process_power_collector_
.reset();
1638 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1639 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1641 // Some tests don't set parameters.ui_task, so they started translate
1642 // language fetch that was never completed so we need to cleanup here
1643 // otherwise it will be done by the destructor in a wrong thread.
1644 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1646 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1647 process_singleton_
->Cleanup();
1649 // Stop all tasks that might run on WatchDogThread.
1650 ThreadWatcherList::StopWatchingAll();
1652 browser_process_
->metrics_service()->Stop();
1654 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1655 browser_process_
->StartTearDown();
1659 void ChromeBrowserMainParts::PostDestroyThreads() {
1660 #if defined(OS_ANDROID)
1661 // On Android, there is no quit/exit. So the browser's main message loop will
1665 browser_process_
->PostDestroyThreads();
1666 // browser_shutdown takes care of deleting browser_process, so we need to
1668 ignore_result(browser_process_
.release());
1669 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1670 master_prefs_
.reset();
1671 process_singleton_
.reset();
1673 // We need to do this check as late as possible, but due to modularity, this
1674 // may be the last point in Chrome. This would be more effective if done at
1675 // a higher level on the stack, so that it is impossible for an early return
1676 // to bypass this code. Perhaps we need a *final* hook that is called on all
1677 // paths from content/browser/browser_main.
1678 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1680 #if defined(OS_CHROMEOS)
1681 chromeos::CrosSettings::Shutdown();
1688 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1689 chrome_extra_parts_
.push_back(parts
);