1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main.h"
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/debug/crash_logging.h"
15 #include "base/debug/debugger.h"
16 #include "base/debug/trace_event.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/prefs/json_pref_store.h"
23 #include "base/prefs/pref_registry_simple.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/prefs/pref_value_store.h"
26 #include "base/prefs/scoped_user_pref_update.h"
27 #include "base/process/process_info.h"
28 #include "base/run_loop.h"
29 #include "base/strings/string_number_conversions.h"
30 #include "base/strings/string_piece.h"
31 #include "base/strings/string_split.h"
32 #include "base/strings/sys_string_conversions.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/sys_info.h"
35 #include "base/threading/platform_thread.h"
36 #include "base/time/time.h"
37 #include "base/values.h"
38 #include "build/build_config.h"
39 #include "chrome/browser/about_flags.h"
40 #include "chrome/browser/browser_process.h"
41 #include "chrome/browser/browser_process_impl.h"
42 #include "chrome/browser/browser_process_platform_part.h"
43 #include "chrome/browser/browser_shutdown.h"
44 #include "chrome/browser/chrome_browser_main_extra_parts.h"
45 #include "chrome/browser/component_updater/cld_component_installer.h"
46 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
47 #include "chrome/browser/component_updater/flash_component_installer.h"
48 #include "chrome/browser/component_updater/recovery_component_installer.h"
49 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
50 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
51 #include "chrome/browser/defaults.h"
52 #include "chrome/browser/first_run/first_run.h"
53 #include "chrome/browser/first_run/upgrade_util.h"
54 #include "chrome/browser/google/google_search_counter.h"
55 #include "chrome/browser/gpu/gl_string_manager.h"
56 #include "chrome/browser/gpu/three_d_api_observer.h"
57 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
58 #include "chrome/browser/metrics/field_trial_synchronizer.h"
59 #include "chrome/browser/metrics/thread_watcher.h"
60 #include "chrome/browser/metrics/tracking_synchronizer.h"
61 #include "chrome/browser/metrics/variations/variations_service.h"
62 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
63 #include "chrome/browser/net/chrome_net_log.h"
64 #include "chrome/browser/net/crl_set_fetcher.h"
65 #include "chrome/browser/notifications/desktop_notification_service.h"
66 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
67 #include "chrome/browser/performance_monitor/performance_monitor.h"
68 #include "chrome/browser/plugins/plugin_prefs.h"
69 #include "chrome/browser/power/process_power_collector.h"
70 #include "chrome/browser/pref_service_flags_storage.h"
71 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
72 #include "chrome/browser/prefs/command_line_pref_store.h"
73 #include "chrome/browser/prefs/pref_metrics_service.h"
74 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
75 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
76 #include "chrome/browser/process_singleton.h"
77 #include "chrome/browser/profiles/profile.h"
78 #include "chrome/browser/profiles/profile_manager.h"
79 #include "chrome/browser/profiles/profiles_state.h"
80 #include "chrome/browser/shell_integration.h"
81 #include "chrome/browser/translate/translate_service.h"
82 #include "chrome/browser/ui/app_list/app_list_service.h"
83 #include "chrome/browser/ui/browser.h"
84 #include "chrome/browser/ui/browser_finder.h"
85 #include "chrome/browser/ui/host_desktop.h"
86 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
87 #include "chrome/browser/ui/startup/default_browser_prompt.h"
88 #include "chrome/browser/ui/startup/startup_browser_creator.h"
89 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
90 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
91 #include "chrome/common/chrome_constants.h"
92 #include "chrome/common/chrome_paths.h"
93 #include "chrome/common/chrome_result_codes.h"
94 #include "chrome/common/chrome_switches.h"
95 #include "chrome/common/crash_keys.h"
96 #include "chrome/common/env_vars.h"
97 #include "chrome/common/logging_chrome.h"
98 #include "chrome/common/net/net_resource_provider.h"
99 #include "chrome/common/pref_names.h"
100 #include "chrome/common/profiling.h"
101 #include "chrome/grit/generated_resources.h"
102 #include "chrome/installer/util/google_update_settings.h"
103 #include "components/component_updater/component_updater_service.h"
104 #include "components/google/core/browser/google_util.h"
105 #include "components/language_usage_metrics/language_usage_metrics.h"
106 #include "components/metrics/metrics_service.h"
107 #include "components/nacl/browser/nacl_browser.h"
108 #include "components/rappor/rappor_service.h"
109 #include "components/signin/core/common/profile_management_switches.h"
110 #include "components/startup_metric_utils/startup_metric_utils.h"
111 #include "components/translate/content/common/cld_data_source.h"
112 #include "components/translate/core/browser/translate_download_manager.h"
113 #include "components/variations/variations_http_header_provider.h"
114 #include "content/public/browser/browser_thread.h"
115 #include "content/public/browser/notification_observer.h"
116 #include "content/public/browser/notification_registrar.h"
117 #include "content/public/browser/notification_service.h"
118 #include "content/public/browser/notification_types.h"
119 #include "content/public/browser/site_instance.h"
120 #include "content/public/common/content_client.h"
121 #include "content/public/common/content_switches.h"
122 #include "content/public/common/main_function_params.h"
123 #include "grit/platform_locale_settings.h"
124 #include "net/base/net_module.h"
125 #include "net/base/sdch_manager.h"
126 #include "net/cookies/cookie_monster.h"
127 #include "net/http/http_network_layer.h"
128 #include "net/http/http_stream_factory.h"
129 #include "net/url_request/url_request.h"
130 #include "ui/base/l10n/l10n_util.h"
131 #include "ui/base/layout.h"
132 #include "ui/base/resource/resource_bundle.h"
133 #include "ui/strings/grit/app_locale_settings.h"
135 #if defined(OS_ANDROID)
136 #include "chrome/browser/metrics/thread_watcher_android.h"
138 #include "chrome/browser/feedback/feedback_profile_observer.h"
141 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
142 #include "chrome/browser/first_run/upgrade_util_linux.h"
143 #include "chrome/browser/sxs_linux.h"
146 #if defined(OS_CHROMEOS)
147 #include "chrome/browser/chromeos/settings/cros_settings.h"
148 #include "chromeos/chromeos_switches.h"
149 #include "chromeos/settings/cros_settings_names.h"
152 // TODO(port): several win-only methods have been pulled out of this, but
153 // BrowserMain() as a whole needs to be broken apart so that it's usable by
154 // other platforms. For now, it's just a stub. This is a serious work in
155 // progress and should not be taken as an indication of a real refactoring.
158 #include "base/environment.h" // For PreRead experiment.
159 #include "base/win/windows_version.h"
160 #include "chrome/browser/browser_util_win.h"
161 #include "chrome/browser/chrome_browser_main_win.h"
162 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
163 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
164 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
165 #include "chrome/browser/first_run/upgrade_util_win.h"
166 #include "chrome/browser/ui/network_profile_bubble.h"
167 #include "chrome/installer/util/helper.h"
168 #include "chrome/installer/util/install_util.h"
169 #include "chrome/installer/util/shell_util.h"
170 #include "net/base/net_util.h"
171 #include "ui/base/l10n/l10n_util_win.h"
172 #include "ui/gfx/win/dpi.h"
173 #include "ui/shell_dialogs/select_file_dialog.h"
174 #endif // defined(OS_WIN)
176 #if defined(OS_MACOSX)
177 #include <Security/Security.h>
179 #include "base/mac/scoped_nsautorelease_pool.h"
180 #include "chrome/browser/mac/keystone_glue.h"
183 #if !defined(DISABLE_NACL)
184 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
185 #include "components/nacl/browser/nacl_process_host.h"
188 #if defined(ENABLE_EXTENSIONS)
189 #include "chrome/browser/extensions/startup_helper.h"
190 #include "extensions/browser/extension_protocols.h"
193 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
194 #include "printing/printed_document.h"
197 #if defined(ENABLE_RLZ)
198 #include "chrome/browser/rlz/rlz.h"
201 #if defined(ENABLE_WEBRTC)
202 #include "chrome/browser/media/webrtc_log_util.h"
205 #if defined(USE_AURA)
206 #include "ui/aura/env.h"
209 using content::BrowserThread
;
213 // This function provides some ways to test crash and assertion handling
214 // behavior of the program.
215 void HandleTestParameters(const CommandLine
& command_line
) {
216 // This parameter causes an assertion.
217 if (command_line
.HasSwitch(switches::kBrowserAssertTest
)) {
221 // This parameter causes a null pointer crash (crash reporter trigger).
222 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
223 int* bad_pointer
= NULL
;
228 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
229 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
230 const std::vector
<GURL
>& new_tabs
) {
231 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
232 it
!= new_tabs
.end(); ++it
) {
234 browser_creator
->AddFirstRunTab(*it
);
237 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
239 // Returns the new local state object, guaranteed non-NULL.
240 // |local_state_task_runner| must be a shutdown-blocking task runner.
241 PrefService
* InitializeLocalState(
242 base::SequencedTaskRunner
* local_state_task_runner
,
243 const CommandLine
& parsed_command_line
) {
244 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
245 base::FilePath local_state_path
;
246 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
247 bool local_state_file_exists
= base::PathExists(local_state_path
);
249 // Load local state. This includes the application locale so we know which
250 // locale dll to load. This also causes local state prefs to be registered.
251 PrefService
* local_state
= g_browser_process
->local_state();
255 if (first_run::IsChromeFirstRun()) {
256 // During first run we read the google_update registry key to find what
257 // language the user selected when downloading the installer. This
258 // becomes our default language in the prefs.
259 // Other platforms obey the system locale.
260 base::string16 install_lang
;
261 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
262 local_state
->SetString(prefs::kApplicationLocale
,
263 base::UTF16ToASCII(install_lang
));
266 #endif // defined(OS_WIN)
268 // If the local state file for the current profile doesn't exist and the
269 // parent profile command line flag is present, then we should inherit some
270 // local state from the parent profile.
271 // Checking that the local state file for the current profile doesn't exist
272 // is the most robust way to determine whether we need to inherit or not
273 // since the parent profile command line flag can be present even when the
274 // current profile is not a new one, and in that case we do not want to
275 // inherit and reset the user's setting.
277 // TODO(mnissler): We should probably just instantiate a
278 // JSONPrefStore here instead of an entire PrefService. Once this is
279 // addressed, the call to browser_prefs::RegisterLocalState can move
280 // to chrome_prefs::CreateLocalState.
281 if (!local_state_file_exists
&&
282 parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
283 base::FilePath parent_profile
=
284 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
285 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
286 scoped_ptr
<PrefService
> parent_local_state(
287 chrome_prefs::CreateLocalState(
289 local_state_task_runner
,
290 g_browser_process
->policy_service(),
293 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
294 // Right now, we only inherit the locale setting from the parent profile.
295 local_state
->SetString(
296 prefs::kApplicationLocale
,
297 parent_local_state
->GetString(prefs::kApplicationLocale
));
300 #if defined(OS_CHROMEOS)
301 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
302 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
303 // Ensure that we start with owner's locale.
304 if (!owner_locale
.empty() &&
305 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
306 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
307 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
315 // Initializes the primary profile, possibly doing some user prompting to pick
316 // a fallback profile. Returns the newly created profile, or NULL if startup
317 // should not continue.
318 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
319 const base::FilePath
& user_data_dir
,
320 const CommandLine
& parsed_command_line
) {
321 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
322 base::Time start
= base::Time::Now();
323 if (profiles::IsMultipleProfilesEnabled() &&
324 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
325 g_browser_process
->local_state()->SetString(prefs::kProfileLastUsed
,
326 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
327 // Clear kProfilesLastActive since the user only wants to launch a specific
329 ListPrefUpdate
update(g_browser_process
->local_state(),
330 prefs::kProfilesLastActive
);
331 base::ListValue
* profile_list
= update
.Get();
332 profile_list
->Clear();
335 Profile
* profile
= NULL
;
336 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
337 // On ChromeOS and Android the ProfileManager will use the same path as the
338 // one we got passed. GetActiveUserProfile will therefore use the correct path
340 DCHECK_EQ(user_data_dir
.value(),
341 g_browser_process
->profile_manager()->user_data_dir().value());
342 profile
= ProfileManager::GetActiveUserProfile();
344 base::FilePath profile_path
=
345 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
347 // Without NewAvatarMenu, replace guest with any existing profile.
348 if (!switches::IsNewAvatarMenu() &&
349 profile_path
== ProfileManager::GetGuestProfilePath()) {
350 profile_path
= g_browser_process
->profile_manager()->GetProfileInfoCache().
351 GetPathOfProfileAtIndex(0);
353 profile
= g_browser_process
->profile_manager()->GetProfile(
356 // If we're using the --new-profile-management flag and this profile is
357 // signed out, then we should show the user manager instead. By switching
358 // the active profile to the guest profile we ensure that no
359 // browser windows will be opened for the guest profile.
360 if (switches::IsNewProfileManagement() && !profile
->IsGuestSession()) {
361 ProfileInfoCache
& cache
=
362 g_browser_process
->profile_manager()->GetProfileInfoCache();
363 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
365 if (cache
.ProfileIsSigninRequiredAtIndex(profile_index
))
366 profile
= g_browser_process
->profile_manager()->GetProfile(
367 ProfileManager::GetGuestProfilePath());
371 UMA_HISTOGRAM_LONG_TIMES(
372 "Startup.CreateFirstProfile", base::Time::Now() - start
);
377 // TODO(port): fix this. See comments near the definition of
378 // user_data_dir. It is better to CHECK-fail here than it is to
379 // silently exit because of missing code in the above test.
380 CHECK(profile
) << "Cannot get default profile.";
386 #if defined(OS_MACOSX)
387 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
388 SecKeychainCallbackInfo
* info
, void* context
) {
393 void RegisterComponentsForUpdate() {
394 component_updater::ComponentUpdateService
* cus
=
395 g_browser_process
->component_updater();
397 // Registration can be before or after cus->Start() so it is ok to post
398 // a task to the UI thread to do registration once you done the necessary
399 // file IO to know you existing component version.
400 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
401 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
402 RegisterPepperFlashComponent(cus
);
403 RegisterSwiftShaderComponent(cus
);
404 RegisterWidevineCdmComponent(cus
);
405 #if !defined(DISABLE_NACL)
406 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
410 if (translate::CldDataSource::ShouldRegisterForComponentUpdates()) {
411 RegisterCldComponent(cus
);
415 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
416 #if defined(OS_ANDROID)
417 // The CRLSet component was enabled for some releases. This code attempts to
418 // delete it from the local disk of those how may have downloaded it.
419 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
420 #elif !defined(OS_CHROMEOS)
421 // CRLSetFetcher attempts to load a CRL set from either the local disk or
423 // For Chrome OS this registration is delayed until user login.
424 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
428 #if !defined(OS_ANDROID)
429 // Android does not currently have the EV indicator. No need to get the
430 // EV certs whitelist on Android, then.
431 RegisterEVWhitelistComponent(cus
);
435 RegisterSwReporterComponent(cus
, g_browser_process
->local_state());
441 #if !defined(OS_ANDROID)
442 bool ProcessSingletonNotificationCallback(
443 const CommandLine
& command_line
,
444 const base::FilePath
& current_directory
) {
445 // Drop the request if the browser process is already in shutdown path.
446 if (!g_browser_process
|| g_browser_process
->IsShuttingDown())
449 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
450 std::string start_time_string
=
451 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
452 int64 remote_start_time
;
453 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
454 base::TimeDelta elapsed
=
455 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
456 if (command_line
.HasSwitch(switches::kFastStart
)) {
457 UMA_HISTOGRAM_LONG_TIMES(
458 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
460 UMA_HISTOGRAM_LONG_TIMES(
461 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
466 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
469 base::FilePath user_data_dir
=
470 g_browser_process
->profile_manager()->user_data_dir();
471 base::FilePath startup_profile_dir
=
472 GetStartupProfilePath(user_data_dir
, command_line
);
474 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
475 command_line
, current_directory
, startup_profile_dir
);
478 #endif // !defined(OS_ANDROID)
480 void LaunchDevToolsHandlerIfNeeded(const CommandLine
& command_line
) {
481 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
482 std::string port_str
=
483 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
485 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
486 g_browser_process
->CreateDevToolsHttpProtocolHandler(
487 chrome::HOST_DESKTOP_TYPE_NATIVE
,
491 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
496 // Heap allocated class that listens for first page load, kicks off stat
497 // recording and then deletes itself.
498 class LoadCompleteListener
: public content::NotificationObserver
{
500 LoadCompleteListener() {
502 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
503 content::NotificationService::AllSources());
505 virtual ~LoadCompleteListener() {}
507 // content::NotificationObserver implementation.
508 virtual void Observe(int type
,
509 const content::NotificationSource
& source
,
510 const content::NotificationDetails
& details
) OVERRIDE
{
511 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
512 startup_metric_utils::OnInitialPageLoadComplete();
517 content::NotificationRegistrar registrar_
;
518 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
523 namespace chrome_browser
{
525 // This error message is not localized because we failed to load the
526 // localization data files.
528 const char kMissingLocaleDataTitle
[] = "Missing File Error";
532 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
533 const char kMissingLocaleDataMessage
[] =
534 "Unable to find locale data files. Please reinstall.";
537 } // namespace chrome_browser
539 // BrowserMainParts ------------------------------------------------------------
542 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_
=
545 ChromeBrowserMainParts::ChromeBrowserMainParts(
546 const content::MainFunctionParams
& parameters
)
547 : parameters_(parameters
),
548 parsed_command_line_(parameters
.command_line
),
549 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
550 startup_watcher_(new StartupTimeBomb()),
551 shutdown_watcher_(new ShutdownWatcherHelper()),
552 browser_field_trials_(parameters
.command_line
),
554 run_message_loop_(true),
555 notify_result_(ProcessSingleton::PROCESS_NONE
),
557 restart_last_session_(false) {
558 // If we're running tests (ui_task is non-null).
559 if (parameters
.ui_task
)
560 browser_defaults::enable_help_app
= false;
562 // Chrome disallows cookies by default. All code paths that want to use
563 // cookies need to go through one of Chrome's URLRequestContexts which have
564 // a ChromeNetworkDelegate attached that selectively allows cookies again.
565 if (!disable_enforcing_cookie_policies_for_tests_
)
566 net::URLRequest::SetDefaultCookiePolicyToBlock();
569 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
570 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
571 delete chrome_extra_parts_
[i
];
572 chrome_extra_parts_
.clear();
575 // This will be called after the command-line has been mutated by about:flags
576 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
577 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
578 // Must initialize metrics after labs have been converted into switches,
579 // but before field trials are set up (so that client ID is available for
580 // one-time randomized field trials).
582 // Initialize FieldTrialList to support FieldTrials that use one-time
584 metrics::MetricsService
* metrics
= browser_process_
->metrics_service();
585 field_trial_list_
.reset(
586 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
588 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
589 if (command_line
->HasSwitch(switches::kEnableBenchmarking
))
590 base::FieldTrial::EnableBenchmarking();
592 // Ensure any field trials specified on the command line are initialized.
593 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
594 std::set
<std::string
> unforceable_field_trials
;
595 #if defined(OFFICIAL_BUILD)
596 unforceable_field_trials
.insert("SettingsEnforcement");
597 #endif // defined(OFFICIAL_BUILD)
599 // Create field trials without activating them, so that this behaves in a
600 // consistent manner with field trials created from the server.
601 bool result
= base::FieldTrialList::CreateTrialsFromString(
602 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
603 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
604 unforceable_field_trials
);
605 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
606 << " list specified.";
608 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
609 // Create default variation ids which will always be included in the
610 // X-Client-Data request header.
611 variations::VariationsHttpHeaderProvider
* provider
=
612 variations::VariationsHttpHeaderProvider::GetInstance();
613 bool result
= provider
->SetDefaultVariationIds(
614 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
615 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
616 << " list specified.";
618 chrome_variations::VariationsService
* variations_service
=
619 browser_process_
->variations_service();
620 if (variations_service
)
621 variations_service
->CreateTrialsFromSeed();
623 // This must be called after |local_state_| is initialized.
624 browser_field_trials_
.SetupFieldTrials(
625 base::Time::FromTimeT(metrics
->GetInstallDate()), local_state_
);
627 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
628 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
629 // Even though base::Bind does AddRef and Release, the object will not be
630 // deleted after the Task is executed.
631 field_trial_synchronizer_
= new FieldTrialSynchronizer();
633 // Now that field trials have been created, initializes metrics recording.
634 metrics
->InitializeMetricsRecordingState();
637 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
639 void ChromeBrowserMainParts::StartMetricsRecording() {
640 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
641 metrics::MetricsService
* metrics
= g_browser_process
->metrics_service();
643 const bool only_do_metrics_recording
=
644 parsed_command_line_
.HasSwitch(switches::kMetricsRecordingOnly
) ||
645 parsed_command_line_
.HasSwitch(switches::kEnableBenchmarking
);
646 if (only_do_metrics_recording
) {
647 // If we're testing then we don't care what the user preference is, we turn
648 // on recording, but not reporting, otherwise tests fail.
649 metrics
->StartRecordingForTests();
653 metrics
->CheckForClonedInstall(
654 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
655 const bool metrics_enabled
= metrics
->StartIfMetricsReportingEnabled();
656 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is
657 // currently disabled there. http://crbug.com/370041
658 browser_process_
->rappor_service()->Start(
659 browser_process_
->local_state(),
660 browser_process_
->system_request_context(),
664 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
665 // Don't record any metrics if UI was displayed before this point e.g.
667 if (startup_metric_utils::WasNonBrowserUIDisplayed())
670 #if defined(OS_ANDROID)
671 // On Android the first run is handled in Java code, and the C++ side of
672 // Chrome doesn't know if this is the first run. This will cause some
673 // inaccuracy in the UMA statistics, but this should be minor (first runs are
675 bool is_first_run
= false;
677 bool is_first_run
= first_run::IsChromeFirstRun();
680 // CurrentProcessInfo::CreationTime() is currently only implemented on some
682 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
683 const base::Time process_creation_time
=
684 base::CurrentProcessInfo::CreationTime();
686 if (!is_first_run
&& !process_creation_time
.is_null()) {
687 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
688 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
690 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
692 // Record collected startup metrics.
693 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
696 new LoadCompleteListener();
699 // -----------------------------------------------------------------------------
700 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
703 #define DLLEXPORT __declspec(dllexport)
705 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
707 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
710 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
711 // Need an instance of AtExitManager to handle singleton creations and
712 // deletions. We need this new instance because, the old instance created
713 // in ChromeMain() got destructed when the function returned.
714 base::AtExitManager exit_manager
;
715 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
719 // content::BrowserMainParts implementation ------------------------------------
721 void ChromeBrowserMainParts::PreEarlyInitialization() {
722 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
723 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
724 chrome_extra_parts_
[i
]->PreEarlyInitialization();
727 void ChromeBrowserMainParts::PostEarlyInitialization() {
728 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
729 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
730 chrome_extra_parts_
[i
]->PostEarlyInitialization();
733 void ChromeBrowserMainParts::ToolkitInitialized() {
734 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
735 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
736 chrome_extra_parts_
[i
]->ToolkitInitialized();
739 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
740 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
741 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
742 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
745 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
746 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
747 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
748 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
751 int ChromeBrowserMainParts::PreCreateThreads() {
752 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
753 result_code_
= PreCreateThreadsImpl();
755 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
756 #if !defined(OS_ANDROID)
757 // These members must be initialized before exiting this function normally.
758 DCHECK(master_prefs_
.get());
759 DCHECK(browser_creator_
.get());
761 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
762 chrome_extra_parts_
[i
]->PreCreateThreads();
768 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
769 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
770 run_message_loop_
= false;
771 #if !defined(OS_ANDROID)
772 chrome::MaybeShowInvalidUserDataDirWarningDialog();
774 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
775 return chrome::RESULT_CODE_MISSING_DATA
;
777 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
778 MediaCaptureDevicesDispatcher::GetInstance();
780 // Android's first run is done in Java instead of native.
781 #if !defined(OS_ANDROID)
782 process_singleton_
.reset(new ChromeProcessSingleton(
783 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
785 // Cache first run state early.
786 first_run::IsChromeFirstRun();
789 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
790 JsonPrefStore::GetTaskRunnerForFile(
791 base::FilePath(chrome::kLocalStorePoolName
),
792 BrowserThread::GetBlockingPool());
795 TRACE_EVENT0("startup",
796 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
797 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
798 parsed_command_line()));
801 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
802 TRACE_EVENT0("startup",
803 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
804 // User wants to override default tracking status.
806 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
807 // Default to basic profiling (no parent child support).
808 tracked_objects::ThreadData::Status status
=
809 tracked_objects::ThreadData::PROFILING_ACTIVE
;
810 if (flag
.compare("0") != 0)
811 status
= tracked_objects::ThreadData::DEACTIVATED
;
812 else if (flag
.compare("child") != 0)
813 status
= tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE
;
814 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
817 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile
)) {
818 tracking_objects_
.set_output_file_path(
819 parsed_command_line().GetSwitchValuePath(
820 switches::kProfilingOutputFile
));
823 local_state_
= InitializeLocalState(
824 local_state_task_runner
.get(), parsed_command_line());
826 #if !defined(OS_ANDROID)
827 // These members must be initialized before returning from this function.
828 master_prefs_
.reset(new first_run::MasterPrefs
);
829 // Android doesn't use StartupBrowserCreator.
830 browser_creator_
.reset(new StartupBrowserCreator
);
831 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
832 chrome::UMABrowsingActivityObserver::Init();
835 #if !defined(OS_CHROMEOS)
836 // Convert active labs into switches. This needs to be done before
837 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
838 // affected by experiment flags (--touch-optimized-ui in particular).
839 // On ChromeOS system level flags are applied from the device settings from
840 // the session manager.
842 TRACE_EVENT0("startup",
843 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
844 about_flags::PrefServiceFlagsStorage
flags_storage_(
845 g_browser_process
->local_state());
846 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
847 CommandLine::ForCurrentProcess(),
848 about_flags::kAddSentinels
);
852 local_state_
->UpdateCommandLinePrefStore(
853 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
855 // Reset the command line in the crash report details, since we may have
856 // just changed it to include experiments.
857 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
859 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
860 // needed when loading the MainMenu.nib and the language doesn't depend on
861 // anything since it comes from Cocoa.
862 #if defined(OS_MACOSX)
864 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
865 browser_process_
->SetApplicationLocale(locale
);
867 const std::string locale
=
868 local_state_
->GetString(prefs::kApplicationLocale
);
870 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
871 // method InitSharedInstance is ignored.
873 TRACE_EVENT_BEGIN0("startup",
874 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
875 const std::string loaded_locale
=
876 ui::ResourceBundle::InitSharedInstanceWithLocale(
877 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
878 TRACE_EVENT_END0("startup",
879 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
881 if (loaded_locale
.empty() &&
882 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
883 ShowMissingLocaleMessageBox();
884 return chrome::RESULT_CODE_MISSING_DATA
;
886 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
887 browser_process_
->SetApplicationLocale(loaded_locale
);
889 base::FilePath resources_pack_path
;
890 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
892 TRACE_EVENT0("startup",
893 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
894 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
895 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
897 #endif // defined(OS_MACOSX)
899 // Android does first run in Java instead of native.
900 // Chrome OS has its own out-of-box-experience code.
901 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
902 // On first run, we need to process the predictor preferences before the
903 // browser's profile_manager object is created, but after ResourceBundle
905 if (first_run::IsChromeFirstRun()) {
906 first_run::ProcessMasterPreferencesResult pmp_result
=
907 first_run::ProcessMasterPreferences(user_data_dir_
,
908 master_prefs_
.get());
909 if (pmp_result
== first_run::EULA_EXIT_NOW
)
910 return chrome::RESULT_CODE_EULA_REFUSED
;
912 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
913 !parsed_command_line().HasSwitch(switches::kAppId
) &&
914 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
915 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
918 // TODO(macourteau): refactor preferences that are copied from
919 // master_preferences into local_state, as a "local_state" section in
920 // master preferences. If possible, a generic solution would be preferred
921 // over a copy one-by-one of specific preferences. Also see related TODO
924 // Store the initial VariationsService seed in local state, if it exists
926 if (!master_prefs_
->variations_seed
.empty()) {
927 local_state_
->SetString(prefs::kVariationsSeed
,
928 master_prefs_
->variations_seed
);
929 if (!master_prefs_
->variations_seed_signature
.empty()) {
930 local_state_
->SetString(prefs::kVariationsSeedSignature
,
931 master_prefs_
->variations_seed_signature
);
933 // Set the variation seed date to the current system time. If the user's
934 // clock is incorrect, this may cause some field trial expiry checks to
935 // not do the right thing until the next seed update from the server,
936 // when this value will be updated.
937 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
938 base::Time::Now().ToInternalValue());
941 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
942 local_state_
->SetString(
943 prefs::kBrowserSuppressDefaultBrowserPrompt
,
944 master_prefs_
->suppress_default_browser_prompt_for_version
);
947 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE
)->HandleFirstRun();
951 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
952 // Set the product channel for crash reports.
953 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
954 chrome::VersionInfo::GetVersionStringModifier());
957 // Initialize tracking synchronizer system.
958 tracking_synchronizer_
= new chrome_browser_metrics::TrackingSynchronizer();
960 #if defined(OS_MACOSX)
961 // Get the Keychain API to register for distributed notifications on the main
962 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
963 // which doesn't. This ensures those notifications will get delivered
964 // properly. See issue 37766.
965 // (Note that the callback mask here is empty. I don't want to register for
966 // any callbacks, I just want to initialize the mechanism.)
967 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
970 #if defined(OS_CHROMEOS)
971 // Must be done after g_browser_process is constructed, before
972 // SetupMetricsAndFieldTrials().
973 chromeos::CrosSettings::Initialize();
976 // Now the command line has been mutated based on about:flags, we can setup
977 // metrics and initialize field trials. The field trials are needed by
978 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
979 SetupMetricsAndFieldTrials();
981 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
982 browser_process_
->PreCreateThreads();
984 return content::RESULT_CODE_NORMAL_EXIT
;
987 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
988 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
989 result_code_
= PreMainMessageLoopRunImpl();
991 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
992 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
995 // PreMainMessageLoopRun calls these extra stages in the following order:
996 // PreMainMessageLoopRunImpl()
997 // ... initial setup, including browser_process_ setup.
999 // ... additional setup, including CreateProfile()
1000 // PostProfileInit()
1001 // ... additional setup
1002 // PreBrowserStart()
1003 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1004 // PostBrowserStart()
1006 void ChromeBrowserMainParts::PreProfileInit() {
1007 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1009 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1010 chrome_extra_parts_
[i
]->PreProfileInit();
1012 #if !defined(OS_ANDROID)
1013 // Initialize the feedback uploader so it can setup notifications for profile
1015 feedback::FeedbackProfileObserver::Initialize();
1017 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
1019 // First check if any ephemeral profiles are left behind because of browser
1020 // crash and schedule them for deletion and then proceed with getting the set
1021 // of profiles to open.
1022 ProfileInfoCache
& profile_cache
= profile_manager
->GetProfileInfoCache();
1023 size_t profiles_count
= profile_cache
.GetNumberOfProfiles();
1024 std::vector
<base::FilePath
> profiles_to_delete
;
1025 for (size_t i
= 0; i
< profiles_count
; ++i
) {
1026 if (profile_cache
.ProfileIsEphemeralAtIndex(i
))
1027 profiles_to_delete
.push_back(profile_cache
.GetPathOfProfileAtIndex(i
));
1030 if (profiles_to_delete
.size()) {
1031 for (size_t i
= 0; i
< profiles_to_delete
.size(); ++i
) {
1032 profile_manager
->ScheduleProfileForDeletion(
1033 profiles_to_delete
[i
], ProfileManager::CreateCallback());
1035 // Clean up stale profiles immediately after browser start.
1036 BrowserThread::PostTask(
1037 BrowserThread::FILE, FROM_HERE
,
1038 base::Bind(&ProfileManager::CleanUpStaleProfiles
, profiles_to_delete
));
1040 #endif // OS_ANDROID
1043 void ChromeBrowserMainParts::PostProfileInit() {
1044 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1045 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1046 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1047 chrome_extra_parts_
[i
]->PostProfileInit();
1050 void ChromeBrowserMainParts::PreBrowserStart() {
1051 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1052 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1053 chrome_extra_parts_
[i
]->PreBrowserStart();
1055 three_d_observer_
.reset(new ThreeDAPIObserver());
1058 void ChromeBrowserMainParts::PostBrowserStart() {
1059 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1060 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1061 chrome_extra_parts_
[i
]->PostBrowserStart();
1062 #if !defined(OS_ANDROID)
1063 // Allow ProcessSingleton to process messages.
1064 process_singleton_
->Unlock();
1066 #if defined(ENABLE_WEBRTC)
1067 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1068 // to reduce the impact on startup time.
1069 BrowserThread::PostDelayedTask(
1072 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1073 base::TimeDelta::FromMinutes(1));
1077 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1078 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1079 // Android updates the metrics service dynamically depending on whether the
1080 // application is in the foreground or not. Do not start here.
1081 #if !defined(OS_ANDROID)
1082 // Now that the file thread has been started, start recording.
1083 StartMetricsRecording();
1086 // Create watchdog thread after creating all other threads because it will
1087 // watch the other threads and they must be running.
1088 browser_process_
->watchdog_thread();
1090 // Do any initializating in the browser process that requires all threads
1092 browser_process_
->PreMainMessageLoopRun();
1094 // Record last shutdown time into a histogram.
1095 browser_shutdown::ReadLastShutdownInfo();
1098 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1099 // tasks. Those care whether the browser is already running. On Linux/Mac,
1100 // upgrade/uninstall happen separately.
1101 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1103 // If the command line specifies 'uninstall' then we need to work here
1104 // unless we detect another chrome browser running.
1105 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1106 return DoUninstallTasks(already_running
);
1109 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1110 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1111 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1112 parsed_command_line_
);
1115 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1116 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1119 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1120 return ShellIntegration::SetAsDefaultBrowser() ?
1121 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1122 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1125 #if defined(USE_AURA)
1126 // Make sure aura::Env has been initialized.
1127 CHECK(aura::Env::GetInstance());
1130 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1131 #if !defined(OS_ANDROID)
1132 // If the command line specifies --pack-extension, attempt the pack extension
1133 // startup action and exit.
1134 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1135 extensions::StartupHelper extension_startup_helper
;
1136 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1137 return content::RESULT_CODE_NORMAL_EXIT
;
1138 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1141 // If we're being launched just to check the connector policy, we are
1142 // short-lived and don't want to be passing that switch off.
1143 bool pass_command_line
= !parsed_command_line().HasSwitch(
1144 switches::kCheckCloudPrintConnectorPolicy
);
1146 if (pass_command_line
) {
1147 // When another process is running, use that process instead of starting a
1148 // new one. NotifyOtherProcess will currently give the other process up to
1149 // 20 seconds to respond. Note that this needs to be done before we attempt
1150 // to read the profile.
1151 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1152 switch (notify_result_
) {
1153 case ProcessSingleton::PROCESS_NONE
:
1154 // No process already running, fall through to starting a new one.
1157 case ProcessSingleton::PROCESS_NOTIFIED
:
1158 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1159 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1160 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1162 // Having a differentiated return type for testing allows for tests to
1163 // verify proper handling of some switches. When not testing, stick to
1164 // the standard Unix convention of returning zero when things went as
1166 if (parsed_command_line().HasSwitch(switches::kTestType
))
1167 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1168 return content::RESULT_CODE_NORMAL_EXIT
;
1170 case ProcessSingleton::PROFILE_IN_USE
:
1171 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1173 case ProcessSingleton::LOCK_ERROR
:
1174 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1175 "directory. This means that running multiple instances "
1176 "would start multiple browser processes rather than "
1177 "opening a new window in the existing process. Aborting "
1178 "now to avoid profile corruption.";
1179 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1185 #endif // !defined(OS_ANDROID)
1187 // Handle special early return paths (which couldn't be processed even earlier
1188 // as they require the process singleton to be held) first.
1190 std::string try_chrome
=
1191 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1192 if (!try_chrome
.empty()) {
1194 // Setup.exe has determined that we need to run a retention experiment
1195 // and has lauched chrome to show the experiment UI. It is guaranteed that
1196 // no other Chrome is currently running as the process singleton was
1197 // sucessfully grabbed above.
1199 base::StringToInt(try_chrome
, &try_chrome_int
);
1200 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1202 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1203 base::Unretained(process_singleton_
.get())));
1204 if (answer
== TryChromeDialogView::NOT_NOW
)
1205 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1206 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1207 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1208 // At this point the user is willing to try chrome again.
1209 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1210 // Only set in the unattended case, the interactive case is Windows 8.
1211 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1212 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1213 ShellIntegration::SetAsDefaultBrowser();
1216 // We don't support retention experiments on Mac or Linux.
1217 return content::RESULT_CODE_NORMAL_EXIT
;
1218 #endif // defined(OS_WIN)
1222 // Do the tasks if chrome has been upgraded while it was last running.
1223 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1224 return content::RESULT_CODE_NORMAL_EXIT
;
1226 // Check if there is any machine level Chrome installed on the current
1227 // machine. If yes and the current Chrome process is user level, we do not
1228 // allow the user level Chrome to run. So we notify the user and uninstall
1229 // user level Chrome.
1230 // Note this check needs to happen here (after the process singleton was
1231 // obtained but before potentially creating the first run sentinel).
1232 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1233 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1234 #endif // defined(OS_WIN)
1236 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1237 if (sxs_linux::ShouldMigrateUserDataDir())
1238 return sxs_linux::MigrateUserDataDir();
1239 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1241 // Desktop construction occurs here, (required before profile creation).
1244 // Profile creation ----------------------------------------------------------
1246 metrics::MetricsService::SetExecutionPhase(
1247 metrics::MetricsService::CREATE_PROFILE
,
1248 g_browser_process
->local_state());
1249 profile_
= CreatePrimaryProfile(parameters(),
1251 parsed_command_line());
1253 return content::RESULT_CODE_NORMAL_EXIT
;
1255 #if !defined(OS_ANDROID)
1256 // The first run sentinel must be created after the process singleton was
1257 // grabbed and no early return paths were otherwise hit above.
1258 first_run::CreateSentinelIfNeeded();
1259 #endif // !defined(OS_ANDROID)
1261 #if defined(ENABLE_BACKGROUND)
1262 // Autoload any profiles which are running background apps.
1263 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1264 browser_process_
->profile_manager()->AutoloadProfiles();
1266 // Post-profile init ---------------------------------------------------------
1268 TranslateService::Initialize();
1270 // Needs to be done before PostProfileInit, since login manager on CrOS is
1271 // called inside PostProfileInit.
1272 content::WebUIControllerFactory::RegisterFactory(
1273 ChromeWebUIControllerFactory::GetInstance());
1275 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1276 // So make sure to create it before that.
1277 #if !defined(DISABLE_NACL)
1278 NaClBrowserDelegateImpl
* delegate
=
1279 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1280 nacl::NaClBrowser::SetDelegate(delegate
);
1283 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1284 // (requires supporting early exit).
1287 // Retrieve cached GL strings from local state and use them for GPU
1288 // blacklist decisions.
1289 if (g_browser_process
->gl_string_manager())
1290 g_browser_process
->gl_string_manager()->Initialize();
1292 // Create an instance of GpuModeManager to watch gpu mode pref change.
1293 g_browser_process
->gpu_mode_manager();
1295 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1296 // Show the First Run UI if this is the first time Chrome has been run on
1297 // this computer, or we're being compelled to do so by a command line flag.
1298 // Note that this be done _after_ the PrefService is initialized and all
1299 // preferences are registered, since some of the code that the importer
1300 // touches reads preferences.
1301 if (first_run::IsChromeFirstRun()) {
1302 first_run::AutoImport(profile_
,
1303 master_prefs_
->homepage_defined
,
1304 master_prefs_
->do_import_items
,
1305 master_prefs_
->dont_import_items
,
1306 master_prefs_
->import_bookmarks_path
);
1308 // Note: this can pop the first run consent dialog on linux.
1309 first_run::DoPostImportTasks(profile_
,
1310 master_prefs_
->make_chrome_default_for_user
);
1312 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1313 browser_creator_
->set_show_main_browser_window(
1314 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1316 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1319 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1322 // Sets things up so that if we crash from this point on, a dialog will
1323 // popup asking the user to restart chrome. It is done this late to avoid
1324 // testing against a bunch of special cases that are taken care early on.
1325 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1326 parsed_command_line());
1328 // Registers Chrome with the Windows Restart Manager, which will restore the
1329 // Chrome session when the computer is restarted after a system update.
1330 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1331 // but should run on startup if extended to handle crashes/hangs/patches.
1332 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1333 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1334 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1335 parsed_command_line());
1338 // Verify that the profile is not on a network share and if so prepare to show
1339 // notification to the user.
1340 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1341 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1342 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1343 profile_
->GetPath()));
1347 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1348 // Init the RLZ library. This just binds the dll and schedules a task on the
1349 // file thread to be run sometime later. If this is the first run we record
1350 // the installation event.
1351 PrefService
* pref_service
= profile_
->GetPrefs();
1352 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1353 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1354 // Negative ping delay means to send ping immediately after a first search is
1356 RLZTracker::InitRlzFromProfileDelayed(
1357 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1358 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1359 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1361 // Configure modules that need access to resources.
1362 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1364 // In unittest mode, this will do nothing. In normal mode, this will create
1365 // the global IntranetRedirectDetector instance, which will promptly go to
1366 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1367 // to see if it should do anything else.
1369 // A simpler way of doing all this would be to have some function which could
1370 // give the time elapsed since startup, and simply have this object check that
1371 // when asked to initialize itself, but this doesn't seem to exist.
1373 // This can't be created in the BrowserProcessImpl constructor because it
1374 // needs to read prefs that get set after that runs.
1375 browser_process_
->intranet_redirect_detector();
1376 GoogleSearchCounter::RegisterForNotifications();
1378 if (parsed_command_line().HasSwitch(switches::kEnableSdchOverHttps
)) {
1379 net::SdchManager::EnableSecureSchemeSupport(true);
1381 // Check SDCH field trial.
1382 const char kSdchFieldTrialName
[] = "SDCH";
1383 const char kEnabledAllGroupName
[] = "EnabledAll";
1384 const char kEnabledHttpOnlyGroupName
[] = "EnabledHttpOnly";
1385 const char kDisabledAllGroupName
[] = "DisabledAll";
1387 // Store in a string on return to keep underlying storage for
1388 // StringPiece stable.
1389 std::string sdch_trial_group_string
=
1390 base::FieldTrialList::FindFullName(kSdchFieldTrialName
);
1391 base::StringPiece
sdch_trial_group(sdch_trial_group_string
);
1392 if (sdch_trial_group
.starts_with(kEnabledAllGroupName
)) {
1393 net::SdchManager::EnableSecureSchemeSupport(true);
1394 net::SdchManager::EnableSdchSupport(true);
1395 } else if (sdch_trial_group
.starts_with(kEnabledHttpOnlyGroupName
)) {
1396 net::SdchManager::EnableSdchSupport(true);
1397 } else if (sdch_trial_group
.starts_with(kDisabledAllGroupName
)) {
1398 net::SdchManager::EnableSdchSupport(false);
1402 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
1403 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1404 base::FilePath path
=
1405 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1406 printing::PrintedDocument::set_debug_dump_path(path
);
1410 HandleTestParameters(parsed_command_line());
1411 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1412 base::debug::BeingDebugged());
1414 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1415 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1416 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1417 browser_process_
->GetApplicationLocale());
1419 // Start watching for hangs during startup. We disarm this hang detector when
1420 // ThreadWatcher takes over or when browser is shutdown or when
1421 // startup_watcher_ is deleted.
1422 metrics::MetricsService::SetExecutionPhase(
1423 metrics::MetricsService::STARTUP_TIMEBOMB_ARM
,
1424 g_browser_process
->local_state());
1425 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1427 // On mobile, need for clean shutdown arises only when the application comes
1428 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1429 // http://crbug.com/179143
1430 #if !defined(OS_ANDROID)
1431 // Start watching for a hang.
1432 browser_process_
->metrics_service()->LogNeedForCleanShutdown();
1435 #if defined(ENABLE_FULL_PRINTING)
1436 // Create the instance of the cloud print proxy service so that it can launch
1437 // the service process if needed. This is needed because the service process
1438 // might have shutdown because an update was available.
1439 // TODO(torne): this should maybe be done with
1440 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1442 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1445 // Start watching all browser threads for responsiveness.
1446 metrics::MetricsService::SetExecutionPhase(
1447 metrics::MetricsService::THREAD_WATCHER_START
,
1448 g_browser_process
->local_state());
1449 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1451 #if defined(OS_ANDROID)
1452 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1455 #if !defined(DISABLE_NACL)
1456 BrowserThread::PostTask(
1459 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1462 // Make sure initial prefs are recorded
1463 PrefMetricsService::Factory::GetForProfile(profile_
);
1467 // Instantiate the notification UI manager, as this triggers a perf timer
1468 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1469 // triggering the timer and call that explicitly in the approprate place.
1470 // http://crbug.com/105065.
1471 browser_process_
->notification_ui_manager();
1473 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1474 RegisterComponentsForUpdate();
1476 #if defined(OS_ANDROID)
1477 chrome_variations::VariationsService
* variations_service
=
1478 browser_process_
->variations_service();
1479 if (variations_service
) {
1480 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1481 variations_service
->StartRepeatedVariationsSeedFetch();
1483 translate::TranslateDownloadManager::RequestLanguageList(
1484 profile_
->GetPrefs());
1487 // Most general initialization is behind us, but opening a
1488 // tab and/or session restore and such is still to be done.
1489 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1491 // We are in regular browser boot sequence. Open initial tabs and enter the
1492 // main message loop.
1494 #if defined(OS_CHROMEOS)
1495 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1496 // them this early as the cryptohome hasn't yet been mounted (which happens
1497 // only once we log in.
1498 std::vector
<Profile
*> last_opened_profiles
;
1500 std::vector
<Profile
*> last_opened_profiles
=
1501 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1504 if (browser_creator_
->Start(parsed_command_line(), base::FilePath(),
1505 profile_
, last_opened_profiles
, &result_code
)) {
1506 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1507 // Initialize autoupdate timer. Timer callback costs basically nothing
1508 // when browser is not in persistent mode, so it's OK to let it ride on
1509 // the main thread. This needs to be done here because we don't want
1510 // to start the timer when Chrome is run inside a test harness.
1511 browser_process_
->StartAutoupdateTimer();
1514 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1515 // On Linux, the running exe will be updated if an upgrade becomes
1516 // available while the browser is running. We need to save the last
1517 // modified time of the exe, so we can compare to determine if there is
1518 // an upgrade while the browser is kept alive by a persistent extension.
1519 upgrade_util::SaveLastModifiedTimeOfExe();
1522 // Record now as the last successful chrome start.
1523 GoogleUpdateSettings::SetLastRunTime();
1525 #if defined(OS_MACOSX)
1526 // Call Recycle() here as late as possible, before going into the loop
1527 // because Start() will add things to it while creating the main window.
1528 if (parameters().autorelease_pool
)
1529 parameters().autorelease_pool
->Recycle();
1532 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1533 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1535 // If we're running tests (ui_task is non-null), then we don't want to
1536 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1537 // RequestLanguageList
1538 if (parameters().ui_task
== NULL
) {
1539 // Request new variations seed information from server.
1540 chrome_variations::VariationsService
* variations_service
=
1541 browser_process_
->variations_service();
1542 if (variations_service
) {
1543 variations_service
->StartRepeatedVariationsSeedFetch();
1546 variations_service
->StartGoogleUpdateRegistrySync();
1550 translate::TranslateDownloadManager::RequestLanguageList(
1551 profile_
->GetPrefs());
1554 run_message_loop_
= true;
1556 run_message_loop_
= false;
1558 browser_creator_
.reset();
1559 #endif // !defined(OS_ANDROID)
1561 #if !defined(OS_ANDROID)
1562 process_power_collector_
.reset(new ProcessPowerCollector
);
1563 process_power_collector_
->Initialize();
1568 if (parameters().ui_task
) {
1569 parameters().ui_task
->Run();
1570 delete parameters().ui_task
;
1571 run_message_loop_
= false;
1573 #if defined(OS_ANDROID)
1574 // We never run the C++ main loop on Android, since the UI thread message
1575 // loop is controlled by the OS, so this is as close as we can get to
1576 // the start of the main loop
1577 if (result_code_
<= 0) {
1578 RecordBrowserStartupTime();
1581 return result_code_
;
1584 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1585 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1586 #if defined(OS_ANDROID)
1587 // Chrome on Android does not use default MessageLoop. It has its own
1588 // Android specific MessageLoop
1592 // Set the result code set in PreMainMessageLoopRun or set above.
1593 *result_code
= result_code_
;
1594 if (!run_message_loop_
)
1595 return true; // Don't run the default message loop.
1597 // These should be invoked as close to the start of the browser's
1598 // UI thread message loop as possible to get a stable measurement
1600 RecordBrowserStartupTime();
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
);