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"
7 #if defined(TOOLKIT_GTK)
14 #include "base/at_exit.h"
15 #include "base/bind.h"
16 #include "base/command_line.h"
17 #include "base/debug/crash_logging.h"
18 #include "base/debug/debugger.h"
19 #include "base/debug/trace_event.h"
20 #include "base/file_util.h"
21 #include "base/files/file_path.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/path_service.h"
25 #include "base/prefs/json_pref_store.h"
26 #include "base/prefs/pref_registry_simple.h"
27 #include "base/prefs/pref_service.h"
28 #include "base/prefs/pref_value_store.h"
29 #include "base/prefs/scoped_user_pref_update.h"
30 #include "base/process/process_info.h"
31 #include "base/run_loop.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_piece.h"
34 #include "base/strings/string_split.h"
35 #include "base/strings/sys_string_conversions.h"
36 #include "base/strings/utf_string_conversions.h"
37 #include "base/sys_info.h"
38 #include "base/threading/platform_thread.h"
39 #include "base/time/time.h"
40 #include "base/values.h"
41 #include "build/build_config.h"
42 #include "chrome/browser/about_flags.h"
43 #include "chrome/browser/browser_process.h"
44 #include "chrome/browser/browser_process_impl.h"
45 #include "chrome/browser/browser_process_platform_part.h"
46 #include "chrome/browser/browser_shutdown.h"
47 #include "chrome/browser/chrome_browser_main_extra_parts.h"
48 #include "chrome/browser/component_updater/component_updater_service.h"
49 #include "chrome/browser/component_updater/flash_component_installer.h"
50 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
51 #include "chrome/browser/component_updater/recovery_component_installer.h"
52 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
53 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
54 #include "chrome/browser/defaults.h"
55 #include "chrome/browser/extensions/extension_protocols.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_system.h"
58 #include "chrome/browser/extensions/startup_helper.h"
59 #include "chrome/browser/first_run/first_run.h"
60 #include "chrome/browser/first_run/upgrade_util.h"
61 #include "chrome/browser/google/google_search_counter.h"
62 #include "chrome/browser/google/google_util.h"
63 #include "chrome/browser/gpu/gl_string_manager.h"
64 #include "chrome/browser/jankometer.h"
65 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
66 #include "chrome/browser/metrics/field_trial_synchronizer.h"
67 #include "chrome/browser/metrics/metrics_log.h"
68 #include "chrome/browser/metrics/metrics_service.h"
69 #include "chrome/browser/metrics/thread_watcher.h"
70 #include "chrome/browser/metrics/tracking_synchronizer.h"
71 #include "chrome/browser/metrics/variations/variations_http_header_provider.h"
72 #include "chrome/browser/metrics/variations/variations_service.h"
73 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
74 #include "chrome/browser/net/chrome_net_log.h"
75 #include "chrome/browser/net/crl_set_fetcher.h"
76 #include "chrome/browser/notifications/desktop_notification_service.h"
77 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
78 #include "chrome/browser/performance_monitor/performance_monitor.h"
79 #include "chrome/browser/performance_monitor/startup_timer.h"
80 #include "chrome/browser/plugins/plugin_prefs.h"
81 #include "chrome/browser/pref_service_flags_storage.h"
82 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
83 #include "chrome/browser/prefs/command_line_pref_store.h"
84 #include "chrome/browser/prefs/pref_metrics_service.h"
85 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
86 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
87 #include "chrome/browser/process_singleton.h"
88 #include "chrome/browser/profiles/profile.h"
89 #include "chrome/browser/profiles/profile_manager.h"
90 #include "chrome/browser/profiles/profiles_state.h"
91 #include "chrome/browser/shell_integration.h"
92 #include "chrome/browser/three_d_api_observer.h"
93 #include "chrome/browser/translate/translate_manager.h"
94 #include "chrome/browser/ui/app_list/app_list_service.h"
95 #include "chrome/browser/ui/browser.h"
96 #include "chrome/browser/ui/browser_finder.h"
97 #include "chrome/browser/ui/host_desktop.h"
98 #include "chrome/browser/ui/startup/default_browser_prompt.h"
99 #include "chrome/browser/ui/startup/startup_browser_creator.h"
100 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
101 #include "chrome/browser/ui/user_data_dir_dialog.h"
102 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
103 #include "chrome/browser/user_data_dir_extractor.h"
104 #include "chrome/common/chrome_constants.h"
105 #include "chrome/common/chrome_paths.h"
106 #include "chrome/common/chrome_result_codes.h"
107 #include "chrome/common/chrome_switches.h"
108 #include "chrome/common/crash_keys.h"
109 #include "chrome/common/env_vars.h"
110 #include "chrome/common/logging_chrome.h"
111 #include "chrome/common/net/net_resource_provider.h"
112 #include "chrome/common/pref_names.h"
113 #include "chrome/common/profile_management_switches.h"
114 #include "chrome/common/profiling.h"
115 #include "chrome/installer/util/google_update_settings.h"
116 #include "components/language_usage_metrics/language_usage_metrics.h"
117 #include "components/nacl/browser/nacl_browser.h"
118 #include "components/nacl/browser/nacl_process_host.h"
119 #include "components/startup_metric_utils/startup_metric_utils.h"
120 #include "content/public/browser/browser_thread.h"
121 #include "content/public/browser/notification_observer.h"
122 #include "content/public/browser/notification_registrar.h"
123 #include "content/public/browser/notification_service.h"
124 #include "content/public/browser/notification_types.h"
125 #include "content/public/browser/site_instance.h"
126 #include "content/public/common/content_client.h"
127 #include "content/public/common/content_switches.h"
128 #include "content/public/common/main_function_params.h"
129 #include "grit/app_locale_settings.h"
130 #include "grit/browser_resources.h"
131 #include "grit/chromium_strings.h"
132 #include "grit/generated_resources.h"
133 #include "grit/platform_locale_settings.h"
134 #include "net/base/net_module.h"
135 #include "net/base/sdch_manager.h"
136 #include "net/cookies/cookie_monster.h"
137 #include "net/http/http_network_layer.h"
138 #include "net/http/http_stream_factory.h"
139 #include "net/url_request/url_request.h"
140 #include "ui/base/l10n/l10n_util.h"
141 #include "ui/base/layout.h"
142 #include "ui/base/resource/resource_bundle.h"
144 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
145 #include "chrome/browser/first_run/upgrade_util_linux.h"
146 #include "chrome/browser/sxs_linux.h"
149 #if defined(OS_CHROMEOS)
150 #include "chrome/browser/chromeos/settings/cros_settings.h"
151 #include "chromeos/chromeos_switches.h"
152 #include "chromeos/settings/cros_settings_names.h"
155 // TODO(port): several win-only methods have been pulled out of this, but
156 // BrowserMain() as a whole needs to be broken apart so that it's usable by
157 // other platforms. For now, it's just a stub. This is a serious work in
158 // progress and should not be taken as an indication of a real refactoring.
161 #include "base/environment.h" // For PreRead experiment.
162 #include "base/win/windows_version.h"
163 #include "chrome/browser/browser_util_win.h"
164 #include "chrome/browser/chrome_browser_main_win.h"
165 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
166 #include "chrome/browser/first_run/upgrade_util_win.h"
167 #include "chrome/browser/ui/network_profile_bubble.h"
168 #include "chrome/common/net/url_fixer_upper.h"
169 #include "chrome/installer/util/helper.h"
170 #include "chrome/installer/util/install_util.h"
171 #include "chrome/installer/util/shell_util.h"
172 #include "net/base/net_util.h"
173 #include "printing/printed_document.h"
174 #include "ui/base/l10n/l10n_util_win.h"
175 #include "ui/gfx/win/dpi.h"
176 #endif // defined(OS_WIN)
178 #if defined(OS_MACOSX)
179 #include <Security/Security.h>
181 #include "base/mac/scoped_nsautorelease_pool.h"
182 #include "chrome/browser/mac/keystone_glue.h"
185 #if defined(ENABLE_RLZ)
186 #include "chrome/browser/rlz/rlz.h"
189 #if defined(TOOLKIT_VIEWS)
190 #include "ui/views/focus/accelerator_handler.h"
193 #if defined(USE_AURA)
194 #include "ui/aura/env.h"
197 using content::BrowserThread
;
201 // This function provides some ways to test crash and assertion handling
202 // behavior of the program.
203 void HandleTestParameters(const CommandLine
& command_line
) {
204 // This parameter causes an assertion.
205 if (command_line
.HasSwitch(switches::kBrowserAssertTest
)) {
209 // This parameter causes a null pointer crash (crash reporter trigger).
210 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
211 int* bad_pointer
= NULL
;
216 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
217 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
218 const std::vector
<GURL
>& new_tabs
) {
219 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
220 it
!= new_tabs
.end(); ++it
) {
222 browser_creator
->AddFirstRunTab(*it
);
225 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
227 // Returns the new local state object, guaranteed non-NULL.
228 // |local_state_task_runner| must be a shutdown-blocking task runner.
229 PrefService
* InitializeLocalState(
230 base::SequencedTaskRunner
* local_state_task_runner
,
231 const CommandLine
& parsed_command_line
) {
232 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
233 base::FilePath local_state_path
;
234 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
235 bool local_state_file_exists
= base::PathExists(local_state_path
);
237 // Load local state. This includes the application locale so we know which
238 // locale dll to load. This also causes local state prefs to be registered.
239 PrefService
* local_state
= g_browser_process
->local_state();
243 if (first_run::IsChromeFirstRun()) {
244 // During first run we read the google_update registry key to find what
245 // language the user selected when downloading the installer. This
246 // becomes our default language in the prefs.
247 // Other platforms obey the system locale.
248 std::wstring install_lang
;
249 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
250 local_state
->SetString(prefs::kApplicationLocale
,
251 WideToASCII(install_lang
));
254 #endif // defined(OS_WIN)
256 // If the local state file for the current profile doesn't exist and the
257 // parent profile command line flag is present, then we should inherit some
258 // local state from the parent profile.
259 // Checking that the local state file for the current profile doesn't exist
260 // is the most robust way to determine whether we need to inherit or not
261 // since the parent profile command line flag can be present even when the
262 // current profile is not a new one, and in that case we do not want to
263 // inherit and reset the user's setting.
265 // TODO(mnissler): We should probably just instantiate a
266 // JSONPrefStore here instead of an entire PrefService. Once this is
267 // addressed, the call to browser_prefs::RegisterLocalState can move
268 // to chrome_prefs::CreateLocalState.
269 if (!local_state_file_exists
&&
270 parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
271 base::FilePath parent_profile
=
272 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
273 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
274 scoped_ptr
<PrefService
> parent_local_state(
275 chrome_prefs::CreateLocalState(
277 local_state_task_runner
,
278 g_browser_process
->policy_service(),
281 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
282 // Right now, we only inherit the locale setting from the parent profile.
283 local_state
->SetString(
284 prefs::kApplicationLocale
,
285 parent_local_state
->GetString(prefs::kApplicationLocale
));
288 #if defined(OS_CHROMEOS)
289 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
290 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
291 // Ensure that we start with owner's locale.
292 if (!owner_locale
.empty() &&
293 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
294 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
295 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
303 // Initializes the primary profile, possibly doing some user prompting to pick
304 // a fallback profile. Returns the newly created profile, or NULL if startup
305 // should not continue.
306 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
307 const base::FilePath
& user_data_dir
,
308 const CommandLine
& parsed_command_line
) {
309 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
310 base::Time start
= base::Time::Now();
311 if (profiles::IsMultipleProfilesEnabled() &&
312 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
313 g_browser_process
->local_state()->SetString(prefs::kProfileLastUsed
,
314 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
315 // Clear kProfilesLastActive since the user only wants to launch a specific
317 ListPrefUpdate
update(g_browser_process
->local_state(),
318 prefs::kProfilesLastActive
);
319 base::ListValue
* profile_list
= update
.Get();
320 profile_list
->Clear();
323 Profile
* profile
= NULL
;
324 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
325 // On ChromeOS and Android the ProfileManager will use the same path as the
326 // one we got passed. GetActiveUserProfile will therefore use the correct path
328 DCHECK_EQ(user_data_dir
.value(),
329 g_browser_process
->profile_manager()->user_data_dir().value());
330 profile
= ProfileManager::GetActiveUserProfile();
332 base::FilePath profile_path
=
333 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
334 profile
= g_browser_process
->profile_manager()->GetProfile(
337 // If we're using the --new-profile-management flag and this profile is
338 // signed out, then we should show the user manager instead. By switching
339 // the active profile to the guest profile we ensure that no
340 // browser windows will be opened for the guest profile.
341 if (switches::IsNewProfileManagement() && !profile
->IsGuestSession()) {
342 ProfileInfoCache
& cache
=
343 g_browser_process
->profile_manager()->GetProfileInfoCache();
344 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
346 if (cache
.ProfileIsSigninRequiredAtIndex(profile_index
))
347 profile
= g_browser_process
->profile_manager()->GetProfile(
348 ProfileManager::GetGuestProfilePath());
352 UMA_HISTOGRAM_LONG_TIMES(
353 "Startup.CreateFirstProfile", base::Time::Now() - start
);
358 // TODO(port): fix this. See comments near the definition of
359 // user_data_dir. It is better to CHECK-fail here than it is to
360 // silently exit because of missing code in the above test.
361 CHECK(profile
) << "Cannot get default profile.";
367 #if defined(OS_MACOSX)
368 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
369 SecKeychainCallbackInfo
* info
, void* context
) {
374 void RegisterComponentsForUpdate(const CommandLine
& command_line
) {
375 component_updater::ComponentUpdateService
* cus
=
376 g_browser_process
->component_updater();
378 // Registration can be before or after cus->Start() so it is ok to post
379 // a task to the UI thread to do registration once you done the necessary
380 // file IO to know you existing component version.
381 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
382 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
383 RegisterPepperFlashComponent(cus
);
384 RegisterSwiftShaderComponent(cus
);
387 #if !defined(OS_ANDROID)
388 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(
392 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
393 RegisterWidevineCdmComponent(cus
);
396 #if !defined(OS_CHROMEOS)
397 // CRLSetFetcher attempts to load a CRL set from either the local disk or
399 if (!command_line
.HasSwitch(switches::kDisableCRLSets
))
400 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
);
406 #if !defined(OS_ANDROID)
407 bool ProcessSingletonNotificationCallback(
408 const CommandLine
& command_line
,
409 const base::FilePath
& current_directory
) {
410 // Drop the request if the browser process is already in shutdown path.
411 if (!g_browser_process
|| g_browser_process
->IsShuttingDown())
414 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
415 std::string start_time_string
=
416 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
417 int64 remote_start_time
;
418 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
419 base::TimeDelta elapsed
=
420 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
421 if (command_line
.HasSwitch(switches::kFastStart
)) {
422 UMA_HISTOGRAM_LONG_TIMES(
423 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
425 UMA_HISTOGRAM_LONG_TIMES(
426 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
431 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
434 // TODO(erikwright): Consider removing this - AFAIK it is no longer used.
435 // Handle the --uninstall-extension startup action. This needs to done here in
436 // the process that is running with the target profile, otherwise the
437 // uninstall will fail to unload and remove all components.
438 if (command_line
.HasSwitch(switches::kUninstallExtension
)) {
439 // The uninstall extension switch can't be combined with the profile
441 DCHECK(!command_line
.HasSwitch(switches::kProfileDirectory
));
443 Profile
* profile
= ProfileManager::GetLastUsedProfile();
445 // We should never be called before the profile has been created.
450 extensions::StartupHelper extension_startup_helper
;
451 extension_startup_helper
.UninstallExtension(command_line
, profile
);
455 base::FilePath user_data_dir
=
456 g_browser_process
->profile_manager()->user_data_dir();
457 base::FilePath startup_profile_dir
=
458 GetStartupProfilePath(user_data_dir
, command_line
);
460 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
461 command_line
, current_directory
, startup_profile_dir
);
464 #endif // !defined(OS_ANDROID)
466 void LaunchDevToolsHandlerIfNeeded(const CommandLine
& command_line
) {
467 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
468 std::string port_str
=
469 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
471 if (base::StringToInt(port_str
, &port
) && port
> 0 && port
< 65535) {
472 std::string frontend_str
;
473 if (command_line
.HasSwitch(::switches::kRemoteDebuggingFrontend
)) {
474 frontend_str
= command_line
.GetSwitchValueASCII(
475 ::switches::kRemoteDebuggingFrontend
);
477 g_browser_process
->CreateDevToolsHttpProtocolHandler(
478 chrome::HOST_DESKTOP_TYPE_NATIVE
,
483 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
488 // Heap allocated class that listens for first page load, kicks off stat
489 // recording and then deletes itself.
490 class LoadCompleteListener
: public content::NotificationObserver
{
492 LoadCompleteListener() {
494 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
495 content::NotificationService::AllSources());
497 virtual ~LoadCompleteListener() {}
499 // content::NotificationObserver implementation.
500 virtual void Observe(int type
,
501 const content::NotificationSource
& source
,
502 const content::NotificationDetails
& details
) OVERRIDE
{
503 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
504 startup_metric_utils::OnInitialPageLoadComplete();
509 content::NotificationRegistrar registrar_
;
510 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
515 namespace chrome_browser
{
516 // This error message is not localized because we failed to load the
517 // localization data files.
518 const char kMissingLocaleDataTitle
[] = "Missing File Error";
519 const char kMissingLocaleDataMessage
[] =
520 "Unable to find locale data files. Please reinstall.";
521 } // namespace chrome_browser
523 // BrowserMainParts ------------------------------------------------------------
526 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_
=
529 ChromeBrowserMainParts::ChromeBrowserMainParts(
530 const content::MainFunctionParams
& parameters
)
531 : parameters_(parameters
),
532 parsed_command_line_(parameters
.command_line
),
533 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
534 startup_watcher_(new StartupTimeBomb()),
535 shutdown_watcher_(new ShutdownWatcherHelper()),
536 startup_timer_(new performance_monitor::StartupTimer()),
537 browser_field_trials_(parameters
.command_line
),
538 translate_manager_(NULL
),
540 run_message_loop_(true),
541 notify_result_(ProcessSingleton::PROCESS_NONE
),
543 restart_last_session_(false) {
544 // If we're running tests (ui_task is non-null).
545 if (parameters
.ui_task
)
546 browser_defaults::enable_help_app
= false;
548 // Chrome disallows cookies by default. All code paths that want to use
549 // cookies need to go through one of Chrome's URLRequestContexts which have
550 // a ChromeNetworkDelegate attached that selectively allows cookies again.
551 if (!disable_enforcing_cookie_policies_for_tests_
)
552 net::URLRequest::SetDefaultCookiePolicyToBlock();
555 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
556 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
557 delete chrome_extra_parts_
[i
];
558 chrome_extra_parts_
.clear();
561 // This will be called after the command-line has been mutated by about:flags
562 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
563 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
564 // Must initialize metrics after labs have been converted into switches,
565 // but before field trials are set up (so that client ID is available for
566 // one-time randomized field trials).
567 #if defined(ARCH_CPU_64_BITS)
568 MetricsLog::set_version_extension("-64");
569 #endif // defined(ARCH_CPU_64_BITS)
571 // Initialize FieldTrialList to support FieldTrials that use one-time
573 MetricsService
* metrics
= browser_process_
->metrics_service();
574 MetricsService::ReportingState reporting_state
=
575 IsMetricsReportingEnabled() ? MetricsService::REPORTING_ENABLED
:
576 MetricsService::REPORTING_DISABLED
;
577 if (reporting_state
== MetricsService::REPORTING_ENABLED
)
578 metrics
->ForceClientIdCreation(); // Needed below.
579 field_trial_list_
.reset(
580 new base::FieldTrialList(
581 metrics
->CreateEntropyProvider(reporting_state
).release()));
583 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
584 if (command_line
->HasSwitch(switches::kEnableBenchmarking
))
585 base::FieldTrial::EnableBenchmarking();
587 // Ensure any field trials specified on the command line are initialized.
588 // Also stop the metrics service so that we don't pollute UMA.
589 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
590 // Create field trials without activating them, so that this behaves in a
591 // consistent manner with field trials created from the server.
592 bool result
= base::FieldTrialList::CreateTrialsFromString(
593 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
594 base::FieldTrialList::DONT_ACTIVATE_TRIALS
);
595 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
596 << " list specified.";
598 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
599 // Create default variation ids which will always be included in the
600 // X-Client-Data request header.
601 chrome_variations::VariationsHttpHeaderProvider
* provider
=
602 chrome_variations::VariationsHttpHeaderProvider::GetInstance();
603 bool result
= provider
->SetDefaultVariationIds(
604 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
605 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
606 << " list specified.";
608 chrome_variations::VariationsService
* variations_service
=
609 browser_process_
->variations_service();
610 if (variations_service
)
611 variations_service
->CreateTrialsFromSeed();
613 // This must be called after the local state is initialized.
614 browser_field_trials_
.SetupFieldTrials(local_state_
);
616 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
617 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
618 // Even though base::Bind does AddRef and Release, the object will not be
619 // deleted after the Task is executed.
620 field_trial_synchronizer_
= new FieldTrialSynchronizer();
622 // Now that field trials have been created, initializes metrics recording.
623 metrics
->InitializeMetricsRecordingState(reporting_state
);
626 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
628 void ChromeBrowserMainParts::StartMetricsRecording() {
629 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
630 MetricsService
* metrics
= g_browser_process
->metrics_service();
632 const bool only_do_metrics_recording
=
633 parsed_command_line_
.HasSwitch(switches::kMetricsRecordingOnly
) ||
634 parsed_command_line_
.HasSwitch(switches::kEnableBenchmarking
);
635 if (only_do_metrics_recording
) {
636 // If we're testing then we don't care what the user preference is, we turn
637 // on recording, but not reporting, otherwise tests fail.
638 metrics
->StartRecordingForTests();
642 if (IsMetricsReportingEnabled())
646 bool ChromeBrowserMainParts::IsMetricsReportingEnabled() {
647 // If the user permits metrics reporting with the checkbox in the
648 // prefs, we turn on recording. We disable metrics completely for
649 // non-official builds. This can be forced with a flag.
650 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
651 if (command_line
->HasSwitch(switches::kEnableMetricsReportingForTesting
))
654 bool enabled
= false;
655 // The debug build doesn't send UMA logs when FieldTrials are forced.
656 if (command_line
->HasSwitch(switches::kForceFieldTrials
))
659 #if defined(GOOGLE_CHROME_BUILD)
660 #if defined(OS_CHROMEOS)
661 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref
,
664 enabled
= local_state_
->GetBoolean(prefs::kMetricsReportingEnabled
);
665 #endif // #if defined(OS_CHROMEOS)
666 #endif // defined(GOOGLE_CHROME_BUILD)
670 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
671 // Don't record any metrics if UI was displayed before this point e.g.
673 if (startup_metric_utils::WasNonBrowserUIDisplayed())
676 #if defined(OS_ANDROID)
677 // On Android the first run is handled in Java code, and the C++ side of
678 // Chrome doesn't know if this is the first run. This will cause some
679 // inaccuracy in the UMA statistics, but this should be minor (first runs are
681 bool is_first_run
= false;
683 bool is_first_run
= first_run::IsChromeFirstRun();
686 // CurrentProcessInfo::CreationTime() is currently only implemented on some
688 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
689 const base::Time process_creation_time
=
690 base::CurrentProcessInfo::CreationTime();
692 if (!is_first_run
&& !process_creation_time
.is_null()) {
693 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
694 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
696 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
698 // Record collected startup metrics.
699 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
702 new LoadCompleteListener();
705 // -----------------------------------------------------------------------------
706 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
709 #define DLLEXPORT __declspec(dllexport)
711 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
713 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
716 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
717 // Need an instance of AtExitManager to handle singleton creations and
718 // deletions. We need this new instance because, the old instance created
719 // in ChromeMain() got destructed when the function returned.
720 base::AtExitManager exit_manager
;
721 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
725 // content::BrowserMainParts implementation ------------------------------------
727 void ChromeBrowserMainParts::PreEarlyInitialization() {
728 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
729 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
730 chrome_extra_parts_
[i
]->PreEarlyInitialization();
733 void ChromeBrowserMainParts::PostEarlyInitialization() {
734 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
735 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
736 chrome_extra_parts_
[i
]->PostEarlyInitialization();
739 void ChromeBrowserMainParts::ToolkitInitialized() {
740 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
741 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
742 chrome_extra_parts_
[i
]->ToolkitInitialized();
745 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
746 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
747 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
748 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
751 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
752 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
753 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
754 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
757 int ChromeBrowserMainParts::PreCreateThreads() {
758 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
759 result_code_
= PreCreateThreadsImpl();
760 // These members must be initialized before returning from this function.
761 #if !defined(OS_ANDROID)
762 DCHECK(master_prefs_
.get());
763 DCHECK(browser_creator_
.get());
766 if (result_code_
== 0) {
767 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
768 chrome_extra_parts_
[i
]->PreCreateThreads();
774 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
775 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
776 run_message_loop_
= false;
778 TRACE_EVENT0("startup",
779 "ChromeBrowserMainParts::PreCreateThreadsImpl:GetUserDataDir");
780 user_data_dir_
= chrome::GetUserDataDir(parameters());
783 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
784 MediaCaptureDevicesDispatcher::GetInstance();
786 // Android's first run is done in Java instead of native.
787 #if !defined(OS_ANDROID)
788 process_singleton_
.reset(new ChromeProcessSingleton(
789 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
791 // Cache first run state early.
792 first_run::IsChromeFirstRun();
795 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
796 JsonPrefStore::GetTaskRunnerForFile(
797 base::FilePath(chrome::kLocalStorePoolName
),
798 BrowserThread::GetBlockingPool());
801 TRACE_EVENT0("startup",
802 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
803 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
804 parsed_command_line()));
807 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
808 TRACE_EVENT0("startup",
809 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
810 // User wants to override default tracking status.
812 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
813 // Default to basic profiling (no parent child support).
814 tracked_objects::ThreadData::Status status
=
815 tracked_objects::ThreadData::PROFILING_ACTIVE
;
816 if (flag
.compare("0") != 0)
817 status
= tracked_objects::ThreadData::DEACTIVATED
;
818 else if (flag
.compare("child") != 0)
819 status
= tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE
;
820 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
823 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile
)) {
824 tracking_objects_
.set_output_file_path(
825 parsed_command_line().GetSwitchValuePath(
826 switches::kProfilingOutputFile
));
829 local_state_
= InitializeLocalState(
830 local_state_task_runner
.get(), parsed_command_line());
832 #if !defined(OS_ANDROID)
833 // These members must be initialized before returning from this function.
834 master_prefs_
.reset(new first_run::MasterPrefs
);
835 // Android doesn't use StartupBrowserCreator.
836 browser_creator_
.reset(new StartupBrowserCreator
);
837 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
838 chrome::UMABrowsingActivityObserver::Init();
841 #if !defined(OS_CHROMEOS)
842 // Convert active labs into switches. This needs to be done before
843 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
844 // affected by experiment flags (--touch-optimized-ui in particular).
845 // On ChromeOS system level flags are applied from the device settings from
846 // the session manager.
848 TRACE_EVENT0("startup",
849 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
850 about_flags::PrefServiceFlagsStorage
flags_storage_(
851 g_browser_process
->local_state());
852 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
853 CommandLine::ForCurrentProcess(),
854 about_flags::kAddSentinels
);
858 local_state_
->UpdateCommandLinePrefStore(
859 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
861 // Reset the command line in the crash report details, since we may have
862 // just changed it to include experiments.
863 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
865 // If we're running tests (ui_task is non-null), then the ResourceBundle
866 // has already been initialized.
867 if (parameters().ui_task
&&
868 !local_state_
->IsManagedPreference(prefs::kApplicationLocale
)) {
869 browser_process_
->SetApplicationLocale("en-US");
871 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
872 // needed when loading the MainMenu.nib and the language doesn't depend on
873 // anything since it comes from Cocoa.
874 #if defined(OS_MACOSX)
875 browser_process_
->SetApplicationLocale(l10n_util::GetLocaleOverride());
877 const std::string locale
=
878 local_state_
->GetString(prefs::kApplicationLocale
);
880 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
881 // method InitSharedInstance is ignored.
883 TRACE_EVENT_BEGIN0("startup",
884 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
885 const std::string loaded_locale
=
886 ResourceBundle::InitSharedInstanceWithLocale(locale
, NULL
);
887 TRACE_EVENT_END0("startup",
888 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
890 if (loaded_locale
.empty() &&
891 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
892 ShowMissingLocaleMessageBox();
893 return chrome::RESULT_CODE_MISSING_DATA
;
895 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
896 browser_process_
->SetApplicationLocale(loaded_locale
);
898 base::FilePath resources_pack_path
;
899 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
901 TRACE_EVENT0("startup",
902 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
903 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
904 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
906 #endif // defined(OS_MACOSX)
909 #if defined(TOOLKIT_GTK)
910 g_set_application_name(l10n_util::GetStringUTF8(IDS_PRODUCT_NAME
).c_str());
913 // Android does first run in Java instead of native.
914 // Chrome OS has its own out-of-box-experience code.
915 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
916 // On first run, we need to process the predictor preferences before the
917 // browser's profile_manager object is created, but after ResourceBundle
919 if (first_run::IsChromeFirstRun()) {
920 first_run::ProcessMasterPreferencesResult pmp_result
=
921 first_run::ProcessMasterPreferences(user_data_dir_
,
922 master_prefs_
.get());
923 if (pmp_result
== first_run::EULA_EXIT_NOW
)
924 return chrome::RESULT_CODE_EULA_REFUSED
;
926 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
927 !parsed_command_line().HasSwitch(switches::kAppId
) &&
928 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
929 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
932 // TODO(macourteau): refactor preferences that are copied from
933 // master_preferences into local_state, as a "local_state" section in
934 // master preferences. If possible, a generic solution would be prefered
935 // over a copy one-by-one of specific preferences. Also see related TODO
938 // Store the initial VariationsService seed in local state, if it exists
940 if (!master_prefs_
->variations_seed
.empty()) {
941 local_state_
->SetString(prefs::kVariationsSeed
,
942 master_prefs_
->variations_seed
);
943 // Set the variation seed date to the current system time. If the user's
944 // clock is incorrect, this may cause some field trial expiry checks to
945 // not do the right thing until the next seed update from the server,
946 // when this value will be updated.
947 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
948 base::Time::Now().ToInternalValue());
951 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
952 local_state_
->SetString(
953 prefs::kBrowserSuppressDefaultBrowserPrompt
,
954 master_prefs_
->suppress_default_browser_prompt_for_version
);
957 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE
)->HandleFirstRun();
961 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
962 // Set the product channel for crash reports.
963 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
964 chrome::VersionInfo::GetVersionStringModifier());
967 // Initialize tracking synchronizer system.
968 tracking_synchronizer_
= new chrome_browser_metrics::TrackingSynchronizer();
970 // Now that all preferences have been registered, set the install date
971 // for the uninstall metrics if this is our first run. This only actually
972 // gets used if the user has metrics reporting enabled at uninstall time.
973 int64 install_date
= local_state_
->GetInt64(prefs::kInstallDate
);
974 if (install_date
== 0)
975 local_state_
->SetInt64(prefs::kInstallDate
, base::Time::Now().ToTimeT());
977 #if defined(OS_MACOSX)
978 // Get the Keychain API to register for distributed notifications on the main
979 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
980 // which doesn't. This ensures those notifications will get delivered
981 // properly. See issue 37766.
982 // (Note that the callback mask here is empty. I don't want to register for
983 // any callbacks, I just want to initialize the mechanism.)
984 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
987 #if defined(OS_CHROMEOS)
988 // Must be done after g_browser_process is constructed, before
989 // SetupMetricsAndFieldTrials().
990 chromeos::CrosSettings::Initialize();
993 // Now the command line has been mutated based on about:flags, we can setup
994 // metrics and initialize field trials. The field trials are needed by
995 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
996 SetupMetricsAndFieldTrials();
998 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
999 browser_process_
->PreCreateThreads();
1001 return content::RESULT_CODE_NORMAL_EXIT
;
1004 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1005 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1006 result_code_
= PreMainMessageLoopRunImpl();
1008 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1009 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
1012 // PreMainMessageLoopRun calls these extra stages in the following order:
1013 // PreMainMessageLoopRunImpl()
1014 // ... initial setup, including browser_process_ setup.
1016 // ... additional setup, including CreateProfile()
1017 // PostProfileInit()
1018 // ... additional setup
1019 // PreBrowserStart()
1020 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1021 // PostBrowserStart()
1023 void ChromeBrowserMainParts::PreProfileInit() {
1024 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1026 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1027 chrome_extra_parts_
[i
]->PreProfileInit();
1030 void ChromeBrowserMainParts::PostProfileInit() {
1031 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1032 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1033 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1034 chrome_extra_parts_
[i
]->PostProfileInit();
1037 void ChromeBrowserMainParts::PreBrowserStart() {
1038 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1039 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1040 chrome_extra_parts_
[i
]->PreBrowserStart();
1042 three_d_observer_
.reset(new ThreeDAPIObserver());
1045 void ChromeBrowserMainParts::PostBrowserStart() {
1046 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1047 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1048 chrome_extra_parts_
[i
]->PostBrowserStart();
1049 #if !defined(OS_ANDROID)
1050 // Allow ProcessSingleton to process messages.
1051 process_singleton_
->Unlock();
1055 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1056 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1057 // Android updates the metrics service dynamically depending on whether the
1058 // application is in the foreground or not. Do not start here.
1059 #if !defined(OS_ANDROID)
1060 // Now that the file thread has been started, start recording.
1061 StartMetricsRecording();
1064 // Create watchdog thread after creating all other threads because it will
1065 // watch the other threads and they must be running.
1066 browser_process_
->watchdog_thread();
1068 // Do any initializating in the browser process that requires all threads
1070 browser_process_
->PreMainMessageLoopRun();
1072 // Record last shutdown time into a histogram.
1073 browser_shutdown::ReadLastShutdownInfo();
1076 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1077 // tasks. Those care whether the browser is already running. On Linux/Mac,
1078 // upgrade/uninstall happen separately.
1079 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1081 // If the command line specifies 'uninstall' then we need to work here
1082 // unless we detect another chrome browser running.
1083 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1084 return DoUninstallTasks(already_running
);
1087 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1088 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1089 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1090 parsed_command_line_
);
1094 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1095 return ShellIntegration::SetAsDefaultBrowser() ?
1096 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1097 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1100 #if defined(USE_AURA)
1101 // Env creates the compositor. Aura widgets need the compositor to be created
1102 // before they can be initialized by the browser.
1103 aura::Env::CreateInstance();
1106 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1107 #if !defined(OS_ANDROID)
1108 // If the command line specifies --pack-extension, attempt the pack extension
1109 // startup action and exit.
1110 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1111 extensions::StartupHelper extension_startup_helper
;
1112 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1113 return content::RESULT_CODE_NORMAL_EXIT
;
1114 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1117 // If we're being launched just to check the connector policy, we are
1118 // short-lived and don't want to be passing that switch off.
1119 bool pass_command_line
= !parsed_command_line().HasSwitch(
1120 switches::kCheckCloudPrintConnectorPolicy
);
1122 if (pass_command_line
) {
1123 // When another process is running, use that process instead of starting a
1124 // new one. NotifyOtherProcess will currently give the other process up to
1125 // 20 seconds to respond. Note that this needs to be done before we attempt
1126 // to read the profile.
1127 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1128 UMA_HISTOGRAM_ENUMERATION("NotifyOtherProcessOrCreate.Result",
1130 ProcessSingleton::NUM_NOTIFY_RESULTS
);
1131 switch (notify_result_
) {
1132 case ProcessSingleton::PROCESS_NONE
:
1133 // No process already running, fall through to starting a new one.
1136 case ProcessSingleton::PROCESS_NOTIFIED
:
1137 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1138 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1139 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1141 // Having a differentiated return type for testing allows for tests to
1142 // verify proper handling of some switches. When not testing, stick to
1143 // the standard Unix convention of returning zero when things went as
1145 if (parsed_command_line().HasSwitch(switches::kTestType
))
1146 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1147 return content::RESULT_CODE_NORMAL_EXIT
;
1149 case ProcessSingleton::PROFILE_IN_USE
:
1150 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1152 case ProcessSingleton::LOCK_ERROR
:
1153 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1154 "directory. This means that running multiple instances "
1155 "would start multiple browser processes rather than "
1156 "opening a new window in the existing process. Aborting "
1157 "now to avoid profile corruption.";
1158 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1165 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1166 if (sxs_linux::ShouldMigrateUserDataDir())
1167 return sxs_linux::MigrateUserDataDir();
1168 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1170 first_run::CreateSentinelIfNeeded();
1171 #endif // !defined(OS_ANDROID)
1173 // Desktop construction occurs here, (required before profile creation).
1176 std::string try_chrome
=
1177 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1178 if (!try_chrome
.empty()) {
1180 // Setup.exe has determined that we need to run a retention experiment
1181 // and has lauched chrome to show the experiment UI. It is guaranteed that
1182 // no other Chrome is currently running as the process singleton was
1183 // sucessfully grabbed above.
1185 base::StringToInt(try_chrome
, &try_chrome_int
);
1186 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1188 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1189 base::Unretained(process_singleton_
.get())));
1190 if (answer
== TryChromeDialogView::NOT_NOW
)
1191 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1192 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1193 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1194 // At this point the user is willing to try chrome again.
1195 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1196 // Only set in the unattended case, the interactive case is Windows 8.
1197 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1198 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1199 ShellIntegration::SetAsDefaultBrowser();
1202 // We don't support retention experiments on Mac or Linux.
1203 return content::RESULT_CODE_NORMAL_EXIT
;
1204 #endif // defined(OS_WIN)
1207 // Profile creation ----------------------------------------------------------
1209 MetricsService::SetExecutionPhase(MetricsService::CREATE_PROFILE
);
1210 profile_
= CreatePrimaryProfile(parameters(),
1212 parsed_command_line());
1214 return content::RESULT_CODE_NORMAL_EXIT
;
1216 #if defined(ENABLE_BACKGROUND)
1217 // Autoload any profiles which are running background apps.
1218 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1219 browser_process_
->profile_manager()->AutoloadProfiles();
1221 // Post-profile init ---------------------------------------------------------
1224 // Do the tasks if chrome has been upgraded while it was last running.
1225 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1226 return content::RESULT_CODE_NORMAL_EXIT
;
1228 // Check if there is any machine level Chrome installed on the current
1229 // machine. If yes and the current Chrome process is user level, we do not
1230 // allow the user level Chrome to run. So we notify the user and uninstall
1231 // user level Chrome.
1232 // Note this check should only happen here, after all the checks above
1233 // (uninstall, resource bundle initialization, other chrome browser
1235 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1236 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1239 // Create the TranslateManager singleton.
1240 translate_manager_
= TranslateManager::GetInstance();
1241 DCHECK(translate_manager_
!= NULL
);
1243 // Needs to be done before PostProfileInit, since login manager on CrOS is
1244 // called inside PostProfileInit.
1245 content::WebUIControllerFactory::RegisterFactory(
1246 ChromeWebUIControllerFactory::GetInstance());
1248 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1249 // So make sure to create it before that.
1250 #if !defined(DISABLE_NACL)
1251 NaClBrowserDelegateImpl
* delegate
= new NaClBrowserDelegateImpl(
1252 extensions::ExtensionSystem::Get(profile_
)->info_map());
1253 nacl::NaClBrowser::SetDelegate(delegate
);
1256 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1257 // (requires supporting early exit).
1260 // Retrieve cached GL strings from local state and use them for GPU
1261 // blacklist decisions.
1262 if (g_browser_process
->gl_string_manager())
1263 g_browser_process
->gl_string_manager()->Initialize();
1265 // Create an instance of GpuModeManager to watch gpu mode pref change.
1266 g_browser_process
->gpu_mode_manager();
1268 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1269 // Show the First Run UI if this is the first time Chrome has been run on
1270 // this computer, or we're being compelled to do so by a command line flag.
1271 // Note that this be done _after_ the PrefService is initialized and all
1272 // preferences are registered, since some of the code that the importer
1273 // touches reads preferences.
1274 if (first_run::IsChromeFirstRun()) {
1275 first_run::AutoImport(profile_
,
1276 master_prefs_
->homepage_defined
,
1277 master_prefs_
->do_import_items
,
1278 master_prefs_
->dont_import_items
,
1279 master_prefs_
->import_bookmarks_path
);
1281 // Note: this can pop the first run consent dialog on linux.
1282 first_run::DoPostImportTasks(profile_
,
1283 master_prefs_
->make_chrome_default_for_user
);
1285 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1286 browser_creator_
->set_show_main_browser_window(
1287 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1289 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1292 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1295 // Sets things up so that if we crash from this point on, a dialog will
1296 // popup asking the user to restart chrome. It is done this late to avoid
1297 // testing against a bunch of special cases that are taken care early on.
1298 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1299 parsed_command_line());
1301 // Registers Chrome with the Windows Restart Manager, which will restore the
1302 // Chrome session when the computer is restarted after a system update.
1303 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1304 // but should run on startup if extended to handle crashes/hangs/patches.
1305 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1306 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1307 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1308 parsed_command_line());
1311 // Verify that the profile is not on a network share and if so prepare to show
1312 // notification to the user.
1313 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1314 content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE
,
1315 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1316 profile_
->GetPath()));
1320 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1321 // Init the RLZ library. This just binds the dll and schedules a task on the
1322 // file thread to be run sometime later. If this is the first run we record
1323 // the installation event.
1324 PrefService
* pref_service
= profile_
->GetPrefs();
1325 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1326 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1327 // Negative ping delay means to send ping immediately after a first search is
1329 RLZTracker::InitRlzFromProfileDelayed(
1330 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1331 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1332 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1334 // Configure modules that need access to resources.
1335 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1337 // In unittest mode, this will do nothing. In normal mode, this will create
1338 // the global IntranetRedirectDetector instance, which will promptly go to
1339 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1340 // to see if it should do anything else.
1342 // A simpler way of doing all this would be to have some function which could
1343 // give the time elapsed since startup, and simply have this object check that
1344 // when asked to initialize itself, but this doesn't seem to exist.
1346 // This can't be created in the BrowserProcessImpl constructor because it
1347 // needs to read prefs that get set after that runs.
1348 browser_process_
->intranet_redirect_detector();
1349 GoogleSearchCounter::RegisterForNotifications();
1351 if (parsed_command_line().HasSwitch(switches::kEnableSdch
)) {
1352 // SDCH options via switches::kEnableSdch include:
1353 const int kSdchDisabled
= 0;
1354 const int kSdchOverHttpEnabled
= 1;
1355 const int kSdchOverBothHttpAndHttpsEnabled
= 2;
1356 int sdch_enabled
= kSdchOverHttpEnabled
;
1357 if (base::StringToInt(parsed_command_line().GetSwitchValueASCII(
1358 switches::kEnableSdch
), &sdch_enabled
)) {
1359 if (sdch_enabled
== kSdchDisabled
) {
1360 net::SdchManager::EnableSdchSupport(false);
1361 } else if (sdch_enabled
== kSdchOverBothHttpAndHttpsEnabled
) {
1362 net::SdchManager::EnableSecureSchemeSupport(true);
1367 if (parsed_command_line().HasSwitch(switches::kEnableWatchdog
))
1368 InstallJankometer(parsed_command_line());
1370 #if defined(OS_WIN) && !defined(GOOGLE_CHROME_BUILD)
1371 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1372 base::FilePath path
=
1373 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1374 printing::PrintedDocument::set_debug_dump_path(path
);
1378 HandleTestParameters(parsed_command_line());
1379 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1380 base::debug::BeingDebugged());
1382 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1383 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1384 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1385 browser_process_
->GetApplicationLocale());
1387 // The extension service may be available at this point. If the command line
1388 // specifies --uninstall-extension, attempt the uninstall extension startup
1390 if (parsed_command_line().HasSwitch(switches::kUninstallExtension
)) {
1391 extensions::StartupHelper extension_startup_helper
;
1392 if (extension_startup_helper
.UninstallExtension(
1393 parsed_command_line(), profile_
))
1394 return content::RESULT_CODE_NORMAL_EXIT
;
1395 return chrome::RESULT_CODE_UNINSTALL_EXTENSION_ERROR
;
1398 // Start watching for hangs during startup. We disarm this hang detector when
1399 // ThreadWatcher takes over or when browser is shutdown or when
1400 // startup_watcher_ is deleted.
1401 MetricsService::SetExecutionPhase(MetricsService::STARTUP_TIMEBOMB_ARM
);
1402 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1404 // On mobile, need for clean shutdown arises only when the application comes
1405 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1406 // http://crbug.com/179143
1407 #if !defined(OS_ANDROID)
1408 // Start watching for a hang.
1409 MetricsService::LogNeedForCleanShutdown();
1412 #if defined(ENABLE_FULL_PRINTING)
1413 // Create the instance of the cloud print proxy service so that it can launch
1414 // the service process if needed. This is needed because the service process
1415 // might have shutdown because an update was available.
1416 // TODO(torne): this should maybe be done with
1417 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1419 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1422 // Start watching all browser threads for responsiveness.
1423 MetricsService::SetExecutionPhase(MetricsService::THREAD_WATCHER_START
);
1424 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1426 #if !defined(DISABLE_NACL)
1427 if (parsed_command_line().HasSwitch(switches::kPnaclDir
)) {
1428 PathService::Override(chrome::DIR_PNACL_BASE
,
1429 parsed_command_line().GetSwitchValuePath(
1430 switches::kPnaclDir
));
1433 content::BrowserThread::PostTask(
1434 content::BrowserThread::IO
,
1436 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1439 // Make sure initial prefs are recorded
1440 PrefMetricsService::Factory::GetForProfile(profile_
);
1444 // Instantiate the notification UI manager, as this triggers a perf timer
1445 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1446 // triggering the timer and call that explicitly in the approprate place.
1447 // http://crbug.com/105065.
1448 browser_process_
->notification_ui_manager();
1450 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1451 RegisterComponentsForUpdate(parsed_command_line());
1453 #if defined(OS_ANDROID)
1454 chrome_variations::VariationsService
* variations_service
=
1455 browser_process_
->variations_service();
1456 if (variations_service
)
1457 variations_service
->StartRepeatedVariationsSeedFetch();
1459 // Most general initialization is behind us, but opening a
1460 // tab and/or session restore and such is still to be done.
1461 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1463 // We are in regular browser boot sequence. Open initial tabs and enter the
1464 // main message loop.
1466 #if defined(OS_CHROMEOS)
1467 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1468 // them this early as the cryptohome hasn't yet been mounted (which happens
1469 // only once we log in.
1470 std::vector
<Profile
*> last_opened_profiles
;
1472 std::vector
<Profile
*> last_opened_profiles
=
1473 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1476 if (browser_creator_
->Start(parsed_command_line(), base::FilePath(),
1477 profile_
, last_opened_profiles
, &result_code
)) {
1478 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1479 // Initialize autoupdate timer. Timer callback costs basically nothing
1480 // when browser is not in persistent mode, so it's OK to let it ride on
1481 // the main thread. This needs to be done here because we don't want
1482 // to start the timer when Chrome is run inside a test harness.
1483 browser_process_
->StartAutoupdateTimer();
1486 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1487 // On Linux, the running exe will be updated if an upgrade becomes
1488 // available while the browser is running. We need to save the last
1489 // modified time of the exe, so we can compare to determine if there is
1490 // an upgrade while the browser is kept alive by a persistent extension.
1491 upgrade_util::SaveLastModifiedTimeOfExe();
1494 // Record now as the last successful chrome start.
1495 GoogleUpdateSettings::SetLastRunTime();
1497 #if defined(OS_MACOSX)
1498 // Call Recycle() here as late as possible, before going into the loop
1499 // because Start() will add things to it while creating the main window.
1500 if (parameters().autorelease_pool
)
1501 parameters().autorelease_pool
->Recycle();
1504 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1505 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1507 // If we're running tests (ui_task is non-null), then we don't want to
1508 // call FetchLanguageListFromTranslateServer or
1509 // StartRepeatedVariationsSeedFetch.
1510 if (parameters().ui_task
== NULL
) {
1511 // Request new variations seed information from server.
1512 chrome_variations::VariationsService
* variations_service
=
1513 browser_process_
->variations_service();
1514 if (variations_service
) {
1515 variations_service
->StartRepeatedVariationsSeedFetch();
1518 variations_service
->StartGoogleUpdateRegistrySync();
1522 if (translate_manager_
!= NULL
) {
1523 translate_manager_
->FetchLanguageListFromTranslateServer(
1524 profile_
->GetPrefs());
1528 run_message_loop_
= true;
1530 run_message_loop_
= false;
1532 browser_creator_
.reset();
1533 #endif // !defined(OS_ANDROID)
1535 performance_monitor::PerformanceMonitor::GetInstance()->Initialize();
1539 if (parameters().ui_task
) {
1540 // We end the startup timer here if we have parameters to run, because we
1541 // never start to run the main loop (where we normally stop the timer).
1542 startup_timer_
->SignalStartupComplete(
1543 performance_monitor::StartupTimer::STARTUP_TEST
);
1544 parameters().ui_task
->Run();
1545 delete parameters().ui_task
;
1546 run_message_loop_
= false;
1548 #if defined(OS_ANDROID)
1549 // We never run the C++ main loop on Android, since the UI thread message
1550 // loop is controlled by the OS, so this is as close as we can get to
1551 // the start of the main loop
1552 if (result_code_
<= 0) {
1553 RecordBrowserStartupTime();
1556 return result_code_
;
1559 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1560 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1561 #if defined(OS_ANDROID)
1562 // Chrome on Android does not use default MessageLoop. It has its own
1563 // Android specific MessageLoop
1567 // Set the result code set in PreMainMessageLoopRun or set above.
1568 *result_code
= result_code_
;
1569 if (!run_message_loop_
)
1570 return true; // Don't run the default message loop.
1572 // These should be invoked as close to the start of the browser's
1573 // UI thread message loop as possible to get a stable measurement
1575 RecordBrowserStartupTime();
1576 startup_timer_
->SignalStartupComplete(
1577 performance_monitor::StartupTimer::STARTUP_NORMAL
);
1579 DCHECK(base::MessageLoopForUI::IsCurrent());
1580 #if !defined(USE_AURA) && defined(TOOLKIT_VIEWS)
1581 views::AcceleratorHandler accelerator_handler
;
1582 base::RunLoop
run_loop(&accelerator_handler
);
1584 base::RunLoop run_loop
;
1587 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1589 MetricsService::SetExecutionPhase(MetricsService::MAIN_MESSAGE_LOOP_RUN
);
1596 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1597 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1598 #if defined(OS_ANDROID)
1599 // Chrome on Android does not use default MessageLoop. It has its own
1600 // Android specific MessageLoop
1604 // Start watching for jank during shutdown. It gets disarmed when
1605 // |shutdown_watcher_| object is destructed.
1606 MetricsService::SetExecutionPhase(MetricsService::SHUTDOWN_TIMEBOMB_ARM
);
1607 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1609 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1610 startup_watcher_
->Disarm();
1612 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1613 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1615 // Some tests don't set parameters.ui_task, so they started translate
1616 // language fetch that was never completed so we need to cleanup here
1617 // otherwise it will be done by the destructor in a wrong thread.
1618 if (parameters().ui_task
== NULL
&& translate_manager_
!= NULL
)
1619 translate_manager_
->CleanupPendingUlrFetcher();
1621 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1622 process_singleton_
->Cleanup();
1624 // Stop all tasks that might run on WatchDogThread.
1625 ThreadWatcherList::StopWatchingAll();
1627 browser_process_
->metrics_service()->Stop();
1629 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1630 browser_process_
->StartTearDown();
1634 void ChromeBrowserMainParts::PostDestroyThreads() {
1635 #if defined(OS_ANDROID)
1636 // On Android, there is no quit/exit. So the browser's main message loop will
1640 browser_process_
->PostDestroyThreads();
1641 // browser_shutdown takes care of deleting browser_process, so we need to
1643 ignore_result(browser_process_
.release());
1644 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1645 master_prefs_
.reset();
1646 process_singleton_
.reset();
1648 // We need to do this check as late as possible, but due to modularity, this
1649 // may be the last point in Chrome. This would be more effective if done at
1650 // a higher level on the stack, so that it is impossible for an early return
1651 // to bypass this code. Perhaps we need a *final* hook that is called on all
1652 // paths from content/browser/browser_main.
1653 CHECK(MetricsService::UmaMetricsProperlyShutdown());
1655 #if defined(OS_CHROMEOS)
1656 chromeos::CrosSettings::Shutdown();
1663 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1664 chrome_extra_parts_
.push_back(parts
);