1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main.h"
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/debug/crash_logging.h"
15 #include "base/debug/debugger.h"
16 #include "base/debug/trace_event.h"
17 #include "base/file_util.h"
18 #include "base/files/file_path.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/prefs/json_pref_store.h"
23 #include "base/prefs/pref_registry_simple.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/prefs/pref_value_store.h"
26 #include "base/prefs/scoped_user_pref_update.h"
27 #include "base/process/process_info.h"
28 #include "base/run_loop.h"
29 #include "base/strings/string_number_conversions.h"
30 #include "base/strings/string_piece.h"
31 #include "base/strings/string_split.h"
32 #include "base/strings/sys_string_conversions.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/sys_info.h"
35 #include "base/threading/platform_thread.h"
36 #include "base/time/time.h"
37 #include "base/values.h"
38 #include "build/build_config.h"
39 #include "chrome/browser/about_flags.h"
40 #include "chrome/browser/browser_process.h"
41 #include "chrome/browser/browser_process_impl.h"
42 #include "chrome/browser/browser_process_platform_part.h"
43 #include "chrome/browser/browser_shutdown.h"
44 #include "chrome/browser/chrome_browser_main_extra_parts.h"
45 #include "chrome/browser/component_updater/component_updater_service.h"
46 #include "chrome/browser/component_updater/flash_component_installer.h"
47 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
48 #include "chrome/browser/component_updater/recovery_component_installer.h"
49 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
50 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
51 #include "chrome/browser/defaults.h"
52 #include "chrome/browser/extensions/extension_service.h"
53 #include "chrome/browser/extensions/startup_helper.h"
54 #include "chrome/browser/first_run/first_run.h"
55 #include "chrome/browser/first_run/upgrade_util.h"
56 #include "chrome/browser/google/google_search_counter.h"
57 #include "chrome/browser/gpu/gl_string_manager.h"
58 #include "chrome/browser/gpu/three_d_api_observer.h"
59 #include "chrome/browser/jankometer.h"
60 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
61 #include "chrome/browser/metrics/field_trial_synchronizer.h"
62 #include "chrome/browser/metrics/thread_watcher.h"
63 #include "chrome/browser/metrics/tracking_synchronizer.h"
64 #include "chrome/browser/metrics/variations/variations_service.h"
65 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
66 #include "chrome/browser/net/chrome_net_log.h"
67 #include "chrome/browser/net/crl_set_fetcher.h"
68 #include "chrome/browser/notifications/desktop_notification_service.h"
69 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
70 #include "chrome/browser/performance_monitor/performance_monitor.h"
71 #include "chrome/browser/performance_monitor/startup_timer.h"
72 #include "chrome/browser/plugins/plugin_prefs.h"
73 #include "chrome/browser/pref_service_flags_storage.h"
74 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
75 #include "chrome/browser/prefs/command_line_pref_store.h"
76 #include "chrome/browser/prefs/pref_metrics_service.h"
77 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
78 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
79 #include "chrome/browser/process_singleton.h"
80 #include "chrome/browser/profiles/profile.h"
81 #include "chrome/browser/profiles/profile_manager.h"
82 #include "chrome/browser/profiles/profiles_state.h"
83 #include "chrome/browser/shell_integration.h"
84 #include "chrome/browser/translate/translate_service.h"
85 #include "chrome/browser/ui/app_list/app_list_service.h"
86 #include "chrome/browser/ui/browser.h"
87 #include "chrome/browser/ui/browser_finder.h"
88 #include "chrome/browser/ui/host_desktop.h"
89 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
90 #include "chrome/browser/ui/startup/default_browser_prompt.h"
91 #include "chrome/browser/ui/startup/startup_browser_creator.h"
92 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
93 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
94 #include "chrome/common/chrome_constants.h"
95 #include "chrome/common/chrome_paths.h"
96 #include "chrome/common/chrome_result_codes.h"
97 #include "chrome/common/chrome_switches.h"
98 #include "chrome/common/crash_keys.h"
99 #include "chrome/common/env_vars.h"
100 #include "chrome/common/logging_chrome.h"
101 #include "chrome/common/net/net_resource_provider.h"
102 #include "chrome/common/pref_names.h"
103 #include "chrome/common/profiling.h"
104 #include "chrome/installer/util/google_update_settings.h"
105 #include "components/google/core/browser/google_util.h"
106 #include "components/language_usage_metrics/language_usage_metrics.h"
107 #include "components/metrics/metrics_service.h"
108 #include "components/nacl/browser/nacl_browser.h"
109 #include "components/nacl/browser/nacl_process_host.h"
110 #include "components/rappor/rappor_service.h"
111 #include "components/signin/core/common/profile_management_switches.h"
112 #include "components/startup_metric_utils/startup_metric_utils.h"
113 #include "components/translate/core/browser/translate_download_manager.h"
114 #include "components/variations/variations_http_header_provider.h"
115 #include "content/public/browser/browser_thread.h"
116 #include "content/public/browser/notification_observer.h"
117 #include "content/public/browser/notification_registrar.h"
118 #include "content/public/browser/notification_service.h"
119 #include "content/public/browser/notification_types.h"
120 #include "content/public/browser/site_instance.h"
121 #include "content/public/common/content_client.h"
122 #include "content/public/common/content_switches.h"
123 #include "content/public/common/main_function_params.h"
124 #include "extensions/browser/extension_protocols.h"
125 #include "grit/app_locale_settings.h"
126 #include "grit/browser_resources.h"
127 #include "grit/chromium_strings.h"
128 #include "grit/generated_resources.h"
129 #include "grit/platform_locale_settings.h"
130 #include "net/base/net_module.h"
131 #include "net/base/sdch_manager.h"
132 #include "net/cookies/cookie_monster.h"
133 #include "net/http/http_network_layer.h"
134 #include "net/http/http_stream_factory.h"
135 #include "net/url_request/url_request.h"
136 #include "ui/base/l10n/l10n_util.h"
137 #include "ui/base/layout.h"
138 #include "ui/base/resource/resource_bundle.h"
140 #if defined(OS_ANDROID)
141 #include "chrome/browser/metrics/thread_watcher_android.h"
143 #include "chrome/browser/feedback/feedback_profile_observer.h"
146 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
147 #include "chrome/browser/first_run/upgrade_util_linux.h"
148 #include "chrome/browser/sxs_linux.h"
151 #if defined(OS_CHROMEOS)
152 #include "chrome/browser/chromeos/settings/cros_settings.h"
153 #include "chromeos/chromeos_switches.h"
154 #include "chromeos/settings/cros_settings_names.h"
157 // TODO(port): several win-only methods have been pulled out of this, but
158 // BrowserMain() as a whole needs to be broken apart so that it's usable by
159 // other platforms. For now, it's just a stub. This is a serious work in
160 // progress and should not be taken as an indication of a real refactoring.
163 #include "base/environment.h" // For PreRead experiment.
164 #include "base/win/windows_version.h"
165 #include "chrome/browser/browser_util_win.h"
166 #include "chrome/browser/chrome_browser_main_win.h"
167 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
168 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
169 #include "chrome/browser/first_run/upgrade_util_win.h"
170 #include "chrome/browser/ui/network_profile_bubble.h"
171 #include "chrome/installer/util/helper.h"
172 #include "chrome/installer/util/install_util.h"
173 #include "chrome/installer/util/shell_util.h"
174 #include "net/base/net_util.h"
175 #include "ui/base/l10n/l10n_util_win.h"
176 #include "ui/gfx/win/dpi.h"
177 #endif // defined(OS_WIN)
179 #if defined(OS_MACOSX)
180 #include <Security/Security.h>
182 #include "base/mac/scoped_nsautorelease_pool.h"
183 #include "chrome/browser/mac/keystone_glue.h"
186 #if defined(CLD_DATA_FROM_COMPONENT)
187 #include "chrome/browser/component_updater/cld_component_installer.h"
190 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
191 #include "printing/printed_document.h"
194 #if defined(ENABLE_RLZ)
195 #include "chrome/browser/rlz/rlz.h"
198 #if defined(ENABLE_WEBRTC)
199 #include "chrome/browser/media/webrtc_log_util.h"
202 #if defined(USE_AURA)
203 #include "ui/aura/env.h"
206 using content::BrowserThread
;
210 // This function provides some ways to test crash and assertion handling
211 // behavior of the program.
212 void HandleTestParameters(const CommandLine
& command_line
) {
213 // This parameter causes an assertion.
214 if (command_line
.HasSwitch(switches::kBrowserAssertTest
)) {
218 // This parameter causes a null pointer crash (crash reporter trigger).
219 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
220 int* bad_pointer
= NULL
;
225 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
226 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
227 const std::vector
<GURL
>& new_tabs
) {
228 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
229 it
!= new_tabs
.end(); ++it
) {
231 browser_creator
->AddFirstRunTab(*it
);
234 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
236 // Returns the new local state object, guaranteed non-NULL.
237 // |local_state_task_runner| must be a shutdown-blocking task runner.
238 PrefService
* InitializeLocalState(
239 base::SequencedTaskRunner
* local_state_task_runner
,
240 const CommandLine
& parsed_command_line
) {
241 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
242 base::FilePath local_state_path
;
243 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
244 bool local_state_file_exists
= base::PathExists(local_state_path
);
246 // Load local state. This includes the application locale so we know which
247 // locale dll to load. This also causes local state prefs to be registered.
248 PrefService
* local_state
= g_browser_process
->local_state();
252 if (first_run::IsChromeFirstRun()) {
253 // During first run we read the google_update registry key to find what
254 // language the user selected when downloading the installer. This
255 // becomes our default language in the prefs.
256 // Other platforms obey the system locale.
257 base::string16 install_lang
;
258 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
259 local_state
->SetString(prefs::kApplicationLocale
,
260 base::UTF16ToASCII(install_lang
));
263 #endif // defined(OS_WIN)
265 // If the local state file for the current profile doesn't exist and the
266 // parent profile command line flag is present, then we should inherit some
267 // local state from the parent profile.
268 // Checking that the local state file for the current profile doesn't exist
269 // is the most robust way to determine whether we need to inherit or not
270 // since the parent profile command line flag can be present even when the
271 // current profile is not a new one, and in that case we do not want to
272 // inherit and reset the user's setting.
274 // TODO(mnissler): We should probably just instantiate a
275 // JSONPrefStore here instead of an entire PrefService. Once this is
276 // addressed, the call to browser_prefs::RegisterLocalState can move
277 // to chrome_prefs::CreateLocalState.
278 if (!local_state_file_exists
&&
279 parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
280 base::FilePath parent_profile
=
281 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
282 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
283 scoped_ptr
<PrefService
> parent_local_state(
284 chrome_prefs::CreateLocalState(
286 local_state_task_runner
,
287 g_browser_process
->policy_service(),
290 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
291 // Right now, we only inherit the locale setting from the parent profile.
292 local_state
->SetString(
293 prefs::kApplicationLocale
,
294 parent_local_state
->GetString(prefs::kApplicationLocale
));
297 #if defined(OS_CHROMEOS)
298 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
299 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
300 // Ensure that we start with owner's locale.
301 if (!owner_locale
.empty() &&
302 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
303 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
304 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
312 // Initializes the primary profile, possibly doing some user prompting to pick
313 // a fallback profile. Returns the newly created profile, or NULL if startup
314 // should not continue.
315 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
316 const base::FilePath
& user_data_dir
,
317 const CommandLine
& parsed_command_line
) {
318 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
319 base::Time start
= base::Time::Now();
320 if (profiles::IsMultipleProfilesEnabled() &&
321 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
322 g_browser_process
->local_state()->SetString(prefs::kProfileLastUsed
,
323 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
324 // Clear kProfilesLastActive since the user only wants to launch a specific
326 ListPrefUpdate
update(g_browser_process
->local_state(),
327 prefs::kProfilesLastActive
);
328 base::ListValue
* profile_list
= update
.Get();
329 profile_list
->Clear();
332 Profile
* profile
= NULL
;
333 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
334 // On ChromeOS and Android the ProfileManager will use the same path as the
335 // one we got passed. GetActiveUserProfile will therefore use the correct path
337 DCHECK_EQ(user_data_dir
.value(),
338 g_browser_process
->profile_manager()->user_data_dir().value());
339 profile
= ProfileManager::GetActiveUserProfile();
341 base::FilePath profile_path
=
342 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
343 profile
= g_browser_process
->profile_manager()->GetProfile(
346 // If we're using the --new-profile-management flag and this profile is
347 // signed out, then we should show the user manager instead. By switching
348 // the active profile to the guest profile we ensure that no
349 // browser windows will be opened for the guest profile.
350 if (switches::IsNewProfileManagement() && !profile
->IsGuestSession()) {
351 ProfileInfoCache
& cache
=
352 g_browser_process
->profile_manager()->GetProfileInfoCache();
353 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
355 if (cache
.ProfileIsSigninRequiredAtIndex(profile_index
))
356 profile
= g_browser_process
->profile_manager()->GetProfile(
357 ProfileManager::GetGuestProfilePath());
361 UMA_HISTOGRAM_LONG_TIMES(
362 "Startup.CreateFirstProfile", base::Time::Now() - start
);
367 // TODO(port): fix this. See comments near the definition of
368 // user_data_dir. It is better to CHECK-fail here than it is to
369 // silently exit because of missing code in the above test.
370 CHECK(profile
) << "Cannot get default profile.";
376 #if defined(OS_MACOSX)
377 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
378 SecKeychainCallbackInfo
* info
, void* context
) {
383 void RegisterComponentsForUpdate() {
384 component_updater::ComponentUpdateService
* cus
=
385 g_browser_process
->component_updater();
387 // Registration can be before or after cus->Start() so it is ok to post
388 // a task to the UI thread to do registration once you done the necessary
389 // file IO to know you existing component version.
390 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
391 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
392 RegisterPepperFlashComponent(cus
);
393 RegisterSwiftShaderComponent(cus
);
394 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
395 RegisterWidevineCdmComponent(cus
);
398 #if defined(CLD_DATA_FROM_COMPONENT)
399 RegisterCldComponent(cus
);
402 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
403 // CRLSetFetcher attempts to load a CRL set from either the local disk or
405 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
);
406 #elif defined(OS_ANDROID)
407 // The CRLSet component was enabled for some releases. This code attempts to
408 // delete it from the local disk of those how may have downloaded it.
409 g_browser_process
->crl_set_fetcher()->DeleteFromDisk();
413 ExecutePendingSwReporter(cus
, g_browser_process
->local_state());
419 #if !defined(OS_ANDROID)
420 bool ProcessSingletonNotificationCallback(
421 const CommandLine
& command_line
,
422 const base::FilePath
& current_directory
) {
423 // Drop the request if the browser process is already in shutdown path.
424 if (!g_browser_process
|| g_browser_process
->IsShuttingDown())
427 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
428 std::string start_time_string
=
429 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
430 int64 remote_start_time
;
431 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
432 base::TimeDelta elapsed
=
433 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
434 if (command_line
.HasSwitch(switches::kFastStart
)) {
435 UMA_HISTOGRAM_LONG_TIMES(
436 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
438 UMA_HISTOGRAM_LONG_TIMES(
439 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
444 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
447 base::FilePath user_data_dir
=
448 g_browser_process
->profile_manager()->user_data_dir();
449 base::FilePath startup_profile_dir
=
450 GetStartupProfilePath(user_data_dir
, command_line
);
452 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
453 command_line
, current_directory
, startup_profile_dir
);
456 #endif // !defined(OS_ANDROID)
458 void LaunchDevToolsHandlerIfNeeded(const CommandLine
& command_line
) {
459 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
460 std::string port_str
=
461 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
463 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
464 g_browser_process
->CreateDevToolsHttpProtocolHandler(
465 chrome::HOST_DESKTOP_TYPE_NATIVE
,
469 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
474 // Heap allocated class that listens for first page load, kicks off stat
475 // recording and then deletes itself.
476 class LoadCompleteListener
: public content::NotificationObserver
{
478 LoadCompleteListener() {
480 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
481 content::NotificationService::AllSources());
483 virtual ~LoadCompleteListener() {}
485 // content::NotificationObserver implementation.
486 virtual void Observe(int type
,
487 const content::NotificationSource
& source
,
488 const content::NotificationDetails
& details
) OVERRIDE
{
489 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
490 startup_metric_utils::OnInitialPageLoadComplete();
495 content::NotificationRegistrar registrar_
;
496 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
501 namespace chrome_browser
{
503 // This error message is not localized because we failed to load the
504 // localization data files.
506 const char kMissingLocaleDataTitle
[] = "Missing File Error";
510 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
511 const char kMissingLocaleDataMessage
[] =
512 "Unable to find locale data files. Please reinstall.";
515 } // namespace chrome_browser
517 // BrowserMainParts ------------------------------------------------------------
520 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_
=
523 ChromeBrowserMainParts::ChromeBrowserMainParts(
524 const content::MainFunctionParams
& parameters
)
525 : parameters_(parameters
),
526 parsed_command_line_(parameters
.command_line
),
527 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
528 startup_watcher_(new StartupTimeBomb()),
529 shutdown_watcher_(new ShutdownWatcherHelper()),
530 startup_timer_(new performance_monitor::StartupTimer()),
531 browser_field_trials_(parameters
.command_line
),
533 run_message_loop_(true),
534 notify_result_(ProcessSingleton::PROCESS_NONE
),
536 restart_last_session_(false) {
537 // If we're running tests (ui_task is non-null).
538 if (parameters
.ui_task
)
539 browser_defaults::enable_help_app
= false;
541 // Chrome disallows cookies by default. All code paths that want to use
542 // cookies need to go through one of Chrome's URLRequestContexts which have
543 // a ChromeNetworkDelegate attached that selectively allows cookies again.
544 if (!disable_enforcing_cookie_policies_for_tests_
)
545 net::URLRequest::SetDefaultCookiePolicyToBlock();
548 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
549 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
550 delete chrome_extra_parts_
[i
];
551 chrome_extra_parts_
.clear();
554 // This will be called after the command-line has been mutated by about:flags
555 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
556 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
557 // Must initialize metrics after labs have been converted into switches,
558 // but before field trials are set up (so that client ID is available for
559 // one-time randomized field trials).
561 // Initialize FieldTrialList to support FieldTrials that use one-time
563 MetricsService
* metrics
= browser_process_
->metrics_service();
564 field_trial_list_
.reset(
565 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
567 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
568 if (command_line
->HasSwitch(switches::kEnableBenchmarking
))
569 base::FieldTrial::EnableBenchmarking();
571 // Ensure any field trials specified on the command line are initialized.
572 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
573 std::set
<std::string
> unforceable_field_trials
;
574 #if defined(OFFICIAL_BUILD)
575 unforceable_field_trials
.insert("SettingsEnforcement");
576 #endif // defined(OFFICIAL_BUILD)
578 // Create field trials without activating them, so that this behaves in a
579 // consistent manner with field trials created from the server.
580 bool result
= base::FieldTrialList::CreateTrialsFromString(
581 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
582 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
583 unforceable_field_trials
);
584 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
585 << " list specified.";
587 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
588 // Create default variation ids which will always be included in the
589 // X-Client-Data request header.
590 variations::VariationsHttpHeaderProvider
* provider
=
591 variations::VariationsHttpHeaderProvider::GetInstance();
592 bool result
= provider
->SetDefaultVariationIds(
593 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
594 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
595 << " list specified.";
597 chrome_variations::VariationsService
* variations_service
=
598 browser_process_
->variations_service();
599 if (variations_service
)
600 variations_service
->CreateTrialsFromSeed();
602 // This must be called after |local_state_| is initialized.
603 browser_field_trials_
.SetupFieldTrials(
604 base::Time::FromTimeT(metrics
->GetInstallDate()), local_state_
);
606 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
607 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
608 // Even though base::Bind does AddRef and Release, the object will not be
609 // deleted after the Task is executed.
610 field_trial_synchronizer_
= new FieldTrialSynchronizer();
612 // Now that field trials have been created, initializes metrics recording.
613 metrics
->InitializeMetricsRecordingState();
616 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
618 void ChromeBrowserMainParts::StartMetricsRecording() {
619 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
620 MetricsService
* metrics
= g_browser_process
->metrics_service();
622 const bool only_do_metrics_recording
=
623 parsed_command_line_
.HasSwitch(switches::kMetricsRecordingOnly
) ||
624 parsed_command_line_
.HasSwitch(switches::kEnableBenchmarking
);
625 if (only_do_metrics_recording
) {
626 // If we're testing then we don't care what the user preference is, we turn
627 // on recording, but not reporting, otherwise tests fail.
628 metrics
->StartRecordingForTests();
632 metrics
->CheckForClonedInstall(
633 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
634 const bool metrics_enabled
= metrics
->StartIfMetricsReportingEnabled();
635 if (metrics_enabled
) {
636 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is
637 // currently disabled there. http://crbug.com/370041
638 browser_process_
->rappor_service()->Start(
639 browser_process_
->local_state(),
640 browser_process_
->system_request_context());
644 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
645 // Don't record any metrics if UI was displayed before this point e.g.
647 if (startup_metric_utils::WasNonBrowserUIDisplayed())
650 #if defined(OS_ANDROID)
651 // On Android the first run is handled in Java code, and the C++ side of
652 // Chrome doesn't know if this is the first run. This will cause some
653 // inaccuracy in the UMA statistics, but this should be minor (first runs are
655 bool is_first_run
= false;
657 bool is_first_run
= first_run::IsChromeFirstRun();
660 // CurrentProcessInfo::CreationTime() is currently only implemented on some
662 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
663 const base::Time process_creation_time
=
664 base::CurrentProcessInfo::CreationTime();
666 if (!is_first_run
&& !process_creation_time
.is_null()) {
667 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
668 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
670 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
672 // Record collected startup metrics.
673 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
676 new LoadCompleteListener();
679 // -----------------------------------------------------------------------------
680 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
683 #define DLLEXPORT __declspec(dllexport)
685 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
687 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
690 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
691 // Need an instance of AtExitManager to handle singleton creations and
692 // deletions. We need this new instance because, the old instance created
693 // in ChromeMain() got destructed when the function returned.
694 base::AtExitManager exit_manager
;
695 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
699 // content::BrowserMainParts implementation ------------------------------------
701 void ChromeBrowserMainParts::PreEarlyInitialization() {
702 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
703 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
704 chrome_extra_parts_
[i
]->PreEarlyInitialization();
707 void ChromeBrowserMainParts::PostEarlyInitialization() {
708 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
709 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
710 chrome_extra_parts_
[i
]->PostEarlyInitialization();
713 void ChromeBrowserMainParts::ToolkitInitialized() {
714 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
715 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
716 chrome_extra_parts_
[i
]->ToolkitInitialized();
719 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
720 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
721 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
722 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
725 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
726 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
727 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
728 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
731 int ChromeBrowserMainParts::PreCreateThreads() {
732 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
733 result_code_
= PreCreateThreadsImpl();
735 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
736 #if !defined(OS_ANDROID)
737 // These members must be initialized before exiting this function normally.
738 DCHECK(master_prefs_
.get());
739 DCHECK(browser_creator_
.get());
741 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
742 chrome_extra_parts_
[i
]->PreCreateThreads();
748 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
749 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
750 run_message_loop_
= false;
751 #if !defined(OS_ANDROID)
752 chrome::MaybeShowInvalidUserDataDirWarningDialog();
754 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
755 return chrome::RESULT_CODE_MISSING_DATA
;
757 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
758 MediaCaptureDevicesDispatcher::GetInstance();
760 // Android's first run is done in Java instead of native.
761 #if !defined(OS_ANDROID)
762 process_singleton_
.reset(new ChromeProcessSingleton(
763 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
765 // Cache first run state early.
766 first_run::IsChromeFirstRun();
769 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
770 JsonPrefStore::GetTaskRunnerForFile(
771 base::FilePath(chrome::kLocalStorePoolName
),
772 BrowserThread::GetBlockingPool());
775 TRACE_EVENT0("startup",
776 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
777 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
778 parsed_command_line()));
781 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
782 TRACE_EVENT0("startup",
783 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
784 // User wants to override default tracking status.
786 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
787 // Default to basic profiling (no parent child support).
788 tracked_objects::ThreadData::Status status
=
789 tracked_objects::ThreadData::PROFILING_ACTIVE
;
790 if (flag
.compare("0") != 0)
791 status
= tracked_objects::ThreadData::DEACTIVATED
;
792 else if (flag
.compare("child") != 0)
793 status
= tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE
;
794 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
797 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile
)) {
798 tracking_objects_
.set_output_file_path(
799 parsed_command_line().GetSwitchValuePath(
800 switches::kProfilingOutputFile
));
803 local_state_
= InitializeLocalState(
804 local_state_task_runner
.get(), parsed_command_line());
806 #if !defined(OS_ANDROID)
807 // These members must be initialized before returning from this function.
808 master_prefs_
.reset(new first_run::MasterPrefs
);
809 // Android doesn't use StartupBrowserCreator.
810 browser_creator_
.reset(new StartupBrowserCreator
);
811 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
812 chrome::UMABrowsingActivityObserver::Init();
815 #if !defined(OS_CHROMEOS)
816 // Convert active labs into switches. This needs to be done before
817 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
818 // affected by experiment flags (--touch-optimized-ui in particular).
819 // On ChromeOS system level flags are applied from the device settings from
820 // the session manager.
822 TRACE_EVENT0("startup",
823 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
824 about_flags::PrefServiceFlagsStorage
flags_storage_(
825 g_browser_process
->local_state());
826 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
827 CommandLine::ForCurrentProcess(),
828 about_flags::kAddSentinels
);
832 local_state_
->UpdateCommandLinePrefStore(
833 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
835 // Reset the command line in the crash report details, since we may have
836 // just changed it to include experiments.
837 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
839 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
840 // needed when loading the MainMenu.nib and the language doesn't depend on
841 // anything since it comes from Cocoa.
842 #if defined(OS_MACOSX)
844 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
845 browser_process_
->SetApplicationLocale(locale
);
847 const std::string locale
=
848 local_state_
->GetString(prefs::kApplicationLocale
);
850 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
851 // method InitSharedInstance is ignored.
853 TRACE_EVENT_BEGIN0("startup",
854 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
855 const std::string loaded_locale
=
856 ResourceBundle::InitSharedInstanceWithLocale(locale
, NULL
);
857 TRACE_EVENT_END0("startup",
858 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
860 if (loaded_locale
.empty() &&
861 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
862 ShowMissingLocaleMessageBox();
863 return chrome::RESULT_CODE_MISSING_DATA
;
865 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
866 browser_process_
->SetApplicationLocale(loaded_locale
);
868 base::FilePath resources_pack_path
;
869 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
871 TRACE_EVENT0("startup",
872 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
873 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
874 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
876 #endif // defined(OS_MACOSX)
878 // Android does first run in Java instead of native.
879 // Chrome OS has its own out-of-box-experience code.
880 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
881 // On first run, we need to process the predictor preferences before the
882 // browser's profile_manager object is created, but after ResourceBundle
884 if (first_run::IsChromeFirstRun()) {
885 first_run::ProcessMasterPreferencesResult pmp_result
=
886 first_run::ProcessMasterPreferences(user_data_dir_
,
887 master_prefs_
.get());
888 if (pmp_result
== first_run::EULA_EXIT_NOW
)
889 return chrome::RESULT_CODE_EULA_REFUSED
;
891 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
892 !parsed_command_line().HasSwitch(switches::kAppId
) &&
893 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
894 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
897 // TODO(macourteau): refactor preferences that are copied from
898 // master_preferences into local_state, as a "local_state" section in
899 // master preferences. If possible, a generic solution would be preferred
900 // over a copy one-by-one of specific preferences. Also see related TODO
903 // Store the initial VariationsService seed in local state, if it exists
905 if (!master_prefs_
->variations_seed
.empty()) {
906 local_state_
->SetString(prefs::kVariationsSeed
,
907 master_prefs_
->variations_seed
);
908 if (!master_prefs_
->variations_seed_signature
.empty()) {
909 local_state_
->SetString(prefs::kVariationsSeedSignature
,
910 master_prefs_
->variations_seed_signature
);
912 // Set the variation seed date to the current system time. If the user's
913 // clock is incorrect, this may cause some field trial expiry checks to
914 // not do the right thing until the next seed update from the server,
915 // when this value will be updated.
916 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
917 base::Time::Now().ToInternalValue());
920 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
921 local_state_
->SetString(
922 prefs::kBrowserSuppressDefaultBrowserPrompt
,
923 master_prefs_
->suppress_default_browser_prompt_for_version
);
926 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE
)->HandleFirstRun();
930 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
931 // Set the product channel for crash reports.
932 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
933 chrome::VersionInfo::GetVersionStringModifier());
936 // Initialize tracking synchronizer system.
937 tracking_synchronizer_
= new chrome_browser_metrics::TrackingSynchronizer();
939 #if defined(OS_MACOSX)
940 // Get the Keychain API to register for distributed notifications on the main
941 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
942 // which doesn't. This ensures those notifications will get delivered
943 // properly. See issue 37766.
944 // (Note that the callback mask here is empty. I don't want to register for
945 // any callbacks, I just want to initialize the mechanism.)
946 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
949 #if defined(OS_CHROMEOS)
950 // Must be done after g_browser_process is constructed, before
951 // SetupMetricsAndFieldTrials().
952 chromeos::CrosSettings::Initialize();
955 // Now the command line has been mutated based on about:flags, we can setup
956 // metrics and initialize field trials. The field trials are needed by
957 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
958 SetupMetricsAndFieldTrials();
960 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
961 browser_process_
->PreCreateThreads();
963 return content::RESULT_CODE_NORMAL_EXIT
;
966 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
967 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
968 result_code_
= PreMainMessageLoopRunImpl();
970 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
971 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
974 // PreMainMessageLoopRun calls these extra stages in the following order:
975 // PreMainMessageLoopRunImpl()
976 // ... initial setup, including browser_process_ setup.
978 // ... additional setup, including CreateProfile()
980 // ... additional setup
982 // ... browser_creator_->Start (OR parameters().ui_task->Run())
983 // PostBrowserStart()
985 void ChromeBrowserMainParts::PreProfileInit() {
986 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
988 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
989 chrome_extra_parts_
[i
]->PreProfileInit();
991 #if !defined(OS_ANDROID)
992 // Initialize the feedback uploader so it can setup notifications for profile
994 feedback::FeedbackProfileObserver::Initialize();
996 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
998 // First check if any ephemeral profiles are left behind because of browser
999 // crash and schedule them for deletion and then proceed with getting the set
1000 // of profiles to open.
1001 ProfileInfoCache
& profile_cache
= profile_manager
->GetProfileInfoCache();
1002 size_t profiles_count
= profile_cache
.GetNumberOfProfiles();
1003 std::vector
<base::FilePath
> profiles_to_delete
;
1004 for (size_t i
= 0; i
< profiles_count
; ++i
) {
1005 if (profile_cache
.ProfileIsEphemeralAtIndex(i
))
1006 profiles_to_delete
.push_back(profile_cache
.GetPathOfProfileAtIndex(i
));
1009 if (profiles_to_delete
.size()) {
1010 for (size_t i
= 0; i
< profiles_to_delete
.size(); ++i
) {
1011 profile_manager
->ScheduleProfileForDeletion(
1012 profiles_to_delete
[i
], ProfileManager::CreateCallback());
1014 // Clean up stale profiles immediately after browser start.
1015 BrowserThread::PostTask(
1016 BrowserThread::FILE, FROM_HERE
,
1017 base::Bind(&ProfileManager::CleanUpStaleProfiles
, profiles_to_delete
));
1019 #endif // OS_ANDROID
1022 void ChromeBrowserMainParts::PostProfileInit() {
1023 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1024 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1025 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1026 chrome_extra_parts_
[i
]->PostProfileInit();
1029 void ChromeBrowserMainParts::PreBrowserStart() {
1030 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1031 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1032 chrome_extra_parts_
[i
]->PreBrowserStart();
1034 three_d_observer_
.reset(new ThreeDAPIObserver());
1037 void ChromeBrowserMainParts::PostBrowserStart() {
1038 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1039 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1040 chrome_extra_parts_
[i
]->PostBrowserStart();
1041 #if !defined(OS_ANDROID)
1042 // Allow ProcessSingleton to process messages.
1043 process_singleton_
->Unlock();
1045 #if defined(ENABLE_WEBRTC)
1046 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1047 // to reduce the impact on startup time.
1048 BrowserThread::PostDelayedTask(
1051 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1052 base::TimeDelta::FromMinutes(1));
1056 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1057 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1058 // Android updates the metrics service dynamically depending on whether the
1059 // application is in the foreground or not. Do not start here.
1060 #if !defined(OS_ANDROID)
1061 // Now that the file thread has been started, start recording.
1062 StartMetricsRecording();
1065 // Create watchdog thread after creating all other threads because it will
1066 // watch the other threads and they must be running.
1067 browser_process_
->watchdog_thread();
1069 // Do any initializating in the browser process that requires all threads
1071 browser_process_
->PreMainMessageLoopRun();
1073 // Record last shutdown time into a histogram.
1074 browser_shutdown::ReadLastShutdownInfo();
1077 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1078 // tasks. Those care whether the browser is already running. On Linux/Mac,
1079 // upgrade/uninstall happen separately.
1080 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1082 // If the command line specifies 'uninstall' then we need to work here
1083 // unless we detect another chrome browser running.
1084 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1085 return DoUninstallTasks(already_running
);
1088 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1089 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1090 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1091 parsed_command_line_
);
1095 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1096 return ShellIntegration::SetAsDefaultBrowser() ?
1097 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1098 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1101 #if defined(USE_AURA)
1102 // Make sure aura::Env has been initialized.
1103 CHECK(aura::Env::GetInstance());
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 switch (notify_result_
) {
1129 case ProcessSingleton::PROCESS_NONE
:
1130 // No process already running, fall through to starting a new one.
1133 case ProcessSingleton::PROCESS_NOTIFIED
:
1134 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1135 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1136 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1138 // Having a differentiated return type for testing allows for tests to
1139 // verify proper handling of some switches. When not testing, stick to
1140 // the standard Unix convention of returning zero when things went as
1142 if (parsed_command_line().HasSwitch(switches::kTestType
))
1143 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1144 return content::RESULT_CODE_NORMAL_EXIT
;
1146 case ProcessSingleton::PROFILE_IN_USE
:
1147 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1149 case ProcessSingleton::LOCK_ERROR
:
1150 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1151 "directory. This means that running multiple instances "
1152 "would start multiple browser processes rather than "
1153 "opening a new window in the existing process. Aborting "
1154 "now to avoid profile corruption.";
1155 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1161 #endif // !defined(OS_ANDROID)
1163 // Handle special early return paths (which couldn't be processed even earlier
1164 // as they require the process singleton to be held) first.
1166 std::string try_chrome
=
1167 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1168 if (!try_chrome
.empty()) {
1170 // Setup.exe has determined that we need to run a retention experiment
1171 // and has lauched chrome to show the experiment UI. It is guaranteed that
1172 // no other Chrome is currently running as the process singleton was
1173 // sucessfully grabbed above.
1175 base::StringToInt(try_chrome
, &try_chrome_int
);
1176 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1178 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1179 base::Unretained(process_singleton_
.get())));
1180 if (answer
== TryChromeDialogView::NOT_NOW
)
1181 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1182 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1183 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1184 // At this point the user is willing to try chrome again.
1185 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1186 // Only set in the unattended case, the interactive case is Windows 8.
1187 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1188 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1189 ShellIntegration::SetAsDefaultBrowser();
1192 // We don't support retention experiments on Mac or Linux.
1193 return content::RESULT_CODE_NORMAL_EXIT
;
1194 #endif // defined(OS_WIN)
1198 // Do the tasks if chrome has been upgraded while it was last running.
1199 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1200 return content::RESULT_CODE_NORMAL_EXIT
;
1202 // Check if there is any machine level Chrome installed on the current
1203 // machine. If yes and the current Chrome process is user level, we do not
1204 // allow the user level Chrome to run. So we notify the user and uninstall
1205 // user level Chrome.
1206 // Note this check needs to happen here (after the process singleton was
1207 // obtained but before potentially creating the first run sentinel).
1208 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1209 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1210 #endif // defined(OS_WIN)
1212 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1213 if (sxs_linux::ShouldMigrateUserDataDir())
1214 return sxs_linux::MigrateUserDataDir();
1215 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1217 // Desktop construction occurs here, (required before profile creation).
1220 // Profile creation ----------------------------------------------------------
1222 MetricsService::SetExecutionPhase(MetricsService::CREATE_PROFILE
,
1223 g_browser_process
->local_state());
1224 profile_
= CreatePrimaryProfile(parameters(),
1226 parsed_command_line());
1228 return content::RESULT_CODE_NORMAL_EXIT
;
1230 #if !defined(OS_ANDROID)
1231 // The first run sentinel must be created after the process singleton was
1232 // grabbed and no early return paths were otherwise hit above.
1233 first_run::CreateSentinelIfNeeded();
1234 #endif // !defined(OS_ANDROID)
1236 #if defined(ENABLE_BACKGROUND)
1237 // Autoload any profiles which are running background apps.
1238 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1239 browser_process_
->profile_manager()->AutoloadProfiles();
1241 // Post-profile init ---------------------------------------------------------
1243 TranslateService::Initialize();
1245 // Needs to be done before PostProfileInit, since login manager on CrOS is
1246 // called inside PostProfileInit.
1247 content::WebUIControllerFactory::RegisterFactory(
1248 ChromeWebUIControllerFactory::GetInstance());
1250 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1251 // So make sure to create it before that.
1252 #if !defined(DISABLE_NACL)
1253 NaClBrowserDelegateImpl
* delegate
=
1254 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1255 nacl::NaClBrowser::SetDelegate(delegate
);
1258 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1259 // (requires supporting early exit).
1262 // Retrieve cached GL strings from local state and use them for GPU
1263 // blacklist decisions.
1264 if (g_browser_process
->gl_string_manager())
1265 g_browser_process
->gl_string_manager()->Initialize();
1267 // Create an instance of GpuModeManager to watch gpu mode pref change.
1268 g_browser_process
->gpu_mode_manager();
1270 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1271 // Show the First Run UI if this is the first time Chrome has been run on
1272 // this computer, or we're being compelled to do so by a command line flag.
1273 // Note that this be done _after_ the PrefService is initialized and all
1274 // preferences are registered, since some of the code that the importer
1275 // touches reads preferences.
1276 if (first_run::IsChromeFirstRun()) {
1277 first_run::AutoImport(profile_
,
1278 master_prefs_
->homepage_defined
,
1279 master_prefs_
->do_import_items
,
1280 master_prefs_
->dont_import_items
,
1281 master_prefs_
->import_bookmarks_path
);
1283 // Note: this can pop the first run consent dialog on linux.
1284 first_run::DoPostImportTasks(profile_
,
1285 master_prefs_
->make_chrome_default_for_user
);
1287 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1288 browser_creator_
->set_show_main_browser_window(
1289 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1291 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1294 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1297 // Sets things up so that if we crash from this point on, a dialog will
1298 // popup asking the user to restart chrome. It is done this late to avoid
1299 // testing against a bunch of special cases that are taken care early on.
1300 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1301 parsed_command_line());
1303 // Registers Chrome with the Windows Restart Manager, which will restore the
1304 // Chrome session when the computer is restarted after a system update.
1305 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1306 // but should run on startup if extended to handle crashes/hangs/patches.
1307 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1308 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1309 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1310 parsed_command_line());
1313 // Verify that the profile is not on a network share and if so prepare to show
1314 // notification to the user.
1315 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1316 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1317 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1318 profile_
->GetPath()));
1322 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1323 // Init the RLZ library. This just binds the dll and schedules a task on the
1324 // file thread to be run sometime later. If this is the first run we record
1325 // the installation event.
1326 PrefService
* pref_service
= profile_
->GetPrefs();
1327 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1328 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1329 // Negative ping delay means to send ping immediately after a first search is
1331 RLZTracker::InitRlzFromProfileDelayed(
1332 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1333 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1334 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1336 // Configure modules that need access to resources.
1337 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1339 // In unittest mode, this will do nothing. In normal mode, this will create
1340 // the global IntranetRedirectDetector instance, which will promptly go to
1341 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1342 // to see if it should do anything else.
1344 // A simpler way of doing all this would be to have some function which could
1345 // give the time elapsed since startup, and simply have this object check that
1346 // when asked to initialize itself, but this doesn't seem to exist.
1348 // This can't be created in the BrowserProcessImpl constructor because it
1349 // needs to read prefs that get set after that runs.
1350 browser_process_
->intranet_redirect_detector();
1351 GoogleSearchCounter::RegisterForNotifications();
1353 if (parsed_command_line().HasSwitch(switches::kEnableSdchOverHttps
)) {
1354 net::SdchManager::EnableSecureSchemeSupport(true);
1356 // Check SDCH field trial.
1357 const char kSdchFieldTrialName
[] = "SDCH";
1358 const char kEnabledAllGroupName
[] = "EnabledAll";
1359 const char kEnabledHttpOnlyGroupName
[] = "EnabledHttpOnly";
1360 const char kDisabledAllGroupName
[] = "DisabledAll";
1362 base::StringPiece sdch_trial_group
=
1363 base::FieldTrialList::FindFullName(kSdchFieldTrialName
);
1364 if (sdch_trial_group
.starts_with(kEnabledAllGroupName
)) {
1365 net::SdchManager::EnableSecureSchemeSupport(true);
1366 net::SdchManager::EnableSdchSupport(true);
1367 } else if (sdch_trial_group
.starts_with(kEnabledHttpOnlyGroupName
)) {
1368 net::SdchManager::EnableSdchSupport(true);
1369 } else if (sdch_trial_group
.starts_with(kDisabledAllGroupName
)) {
1370 net::SdchManager::EnableSdchSupport(false);
1374 if (parsed_command_line().HasSwitch(switches::kEnableWatchdog
))
1375 InstallJankometer(parsed_command_line());
1377 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
1378 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1379 base::FilePath path
=
1380 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1381 printing::PrintedDocument::set_debug_dump_path(path
);
1385 HandleTestParameters(parsed_command_line());
1386 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1387 base::debug::BeingDebugged());
1389 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1390 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1391 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1392 browser_process_
->GetApplicationLocale());
1394 // Start watching for hangs during startup. We disarm this hang detector when
1395 // ThreadWatcher takes over or when browser is shutdown or when
1396 // startup_watcher_ is deleted.
1397 MetricsService::SetExecutionPhase(MetricsService::STARTUP_TIMEBOMB_ARM
,
1398 g_browser_process
->local_state());
1399 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1401 // On mobile, need for clean shutdown arises only when the application comes
1402 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1403 // http://crbug.com/179143
1404 #if !defined(OS_ANDROID)
1405 // Start watching for a hang.
1406 MetricsService::LogNeedForCleanShutdown(g_browser_process
->local_state());
1409 #if defined(ENABLE_FULL_PRINTING)
1410 // Create the instance of the cloud print proxy service so that it can launch
1411 // the service process if needed. This is needed because the service process
1412 // might have shutdown because an update was available.
1413 // TODO(torne): this should maybe be done with
1414 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1416 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1419 // Start watching all browser threads for responsiveness.
1420 MetricsService::SetExecutionPhase(MetricsService::THREAD_WATCHER_START
,
1421 g_browser_process
->local_state());
1422 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1424 #if defined(OS_ANDROID)
1425 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1428 #if !defined(DISABLE_NACL)
1429 BrowserThread::PostTask(
1432 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1435 // Make sure initial prefs are recorded
1436 PrefMetricsService::Factory::GetForProfile(profile_
);
1440 // Instantiate the notification UI manager, as this triggers a perf timer
1441 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1442 // triggering the timer and call that explicitly in the approprate place.
1443 // http://crbug.com/105065.
1444 browser_process_
->notification_ui_manager();
1446 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1447 RegisterComponentsForUpdate();
1449 #if defined(OS_ANDROID)
1450 chrome_variations::VariationsService
* variations_service
=
1451 browser_process_
->variations_service();
1452 if (variations_service
) {
1453 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1454 variations_service
->StartRepeatedVariationsSeedFetch();
1456 TranslateDownloadManager::RequestLanguageList(profile_
->GetPrefs());
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 RequestLanguageList or StartRepeatedVariationsSeedFetch or
1509 // RequestLanguageList
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 TranslateDownloadManager::RequestLanguageList(profile_
->GetPrefs());
1525 run_message_loop_
= true;
1527 run_message_loop_
= false;
1529 browser_creator_
.reset();
1530 #endif // !defined(OS_ANDROID)
1532 performance_monitor::PerformanceMonitor::GetInstance()->Initialize();
1536 if (parameters().ui_task
) {
1537 // We end the startup timer here if we have parameters to run, because we
1538 // never start to run the main loop (where we normally stop the timer).
1539 startup_timer_
->SignalStartupComplete(
1540 performance_monitor::StartupTimer::STARTUP_TEST
);
1541 parameters().ui_task
->Run();
1542 delete parameters().ui_task
;
1543 run_message_loop_
= false;
1545 #if defined(OS_ANDROID)
1546 // We never run the C++ main loop on Android, since the UI thread message
1547 // loop is controlled by the OS, so this is as close as we can get to
1548 // the start of the main loop
1549 if (result_code_
<= 0) {
1550 RecordBrowserStartupTime();
1553 return result_code_
;
1556 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1557 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1558 #if defined(OS_ANDROID)
1559 // Chrome on Android does not use default MessageLoop. It has its own
1560 // Android specific MessageLoop
1564 // Set the result code set in PreMainMessageLoopRun or set above.
1565 *result_code
= result_code_
;
1566 if (!run_message_loop_
)
1567 return true; // Don't run the default message loop.
1569 // These should be invoked as close to the start of the browser's
1570 // UI thread message loop as possible to get a stable measurement
1572 RecordBrowserStartupTime();
1573 startup_timer_
->SignalStartupComplete(
1574 performance_monitor::StartupTimer::STARTUP_NORMAL
);
1576 DCHECK(base::MessageLoopForUI::IsCurrent());
1577 base::RunLoop run_loop
;
1579 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1581 MetricsService::SetExecutionPhase(MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1582 g_browser_process
->local_state());
1589 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1590 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1591 #if defined(OS_ANDROID)
1592 // Chrome on Android does not use default MessageLoop. It has its own
1593 // Android specific MessageLoop
1597 // Start watching for jank during shutdown. It gets disarmed when
1598 // |shutdown_watcher_| object is destructed.
1599 MetricsService::SetExecutionPhase(MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1600 g_browser_process
->local_state());
1601 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1603 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1604 startup_watcher_
->Disarm();
1606 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1607 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1609 // Some tests don't set parameters.ui_task, so they started translate
1610 // language fetch that was never completed so we need to cleanup here
1611 // otherwise it will be done by the destructor in a wrong thread.
1612 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1614 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1615 process_singleton_
->Cleanup();
1617 // Stop all tasks that might run on WatchDogThread.
1618 ThreadWatcherList::StopWatchingAll();
1620 browser_process_
->metrics_service()->Stop();
1622 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1623 browser_process_
->StartTearDown();
1627 void ChromeBrowserMainParts::PostDestroyThreads() {
1628 #if defined(OS_ANDROID)
1629 // On Android, there is no quit/exit. So the browser's main message loop will
1633 browser_process_
->PostDestroyThreads();
1634 // browser_shutdown takes care of deleting browser_process, so we need to
1636 ignore_result(browser_process_
.release());
1637 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1638 master_prefs_
.reset();
1639 process_singleton_
.reset();
1641 // We need to do this check as late as possible, but due to modularity, this
1642 // may be the last point in Chrome. This would be more effective if done at
1643 // a higher level on the stack, so that it is impossible for an early return
1644 // to bypass this code. Perhaps we need a *final* hook that is called on all
1645 // paths from content/browser/browser_main.
1646 CHECK(MetricsService::UmaMetricsProperlyShutdown());
1648 #if defined(OS_CHROMEOS)
1649 chromeos::CrosSettings::Shutdown();
1656 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1657 chrome_extra_parts_
.push_back(parts
);