1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main.h"
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/debug/crash_logging.h"
15 #include "base/debug/debugger.h"
16 #include "base/debug/trace_event.h"
17 #include "base/file_util.h"
18 #include "base/files/file_path.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/prefs/json_pref_store.h"
23 #include "base/prefs/pref_registry_simple.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/prefs/pref_value_store.h"
26 #include "base/prefs/scoped_user_pref_update.h"
27 #include "base/process/process_info.h"
28 #include "base/run_loop.h"
29 #include "base/strings/string_number_conversions.h"
30 #include "base/strings/string_piece.h"
31 #include "base/strings/string_split.h"
32 #include "base/strings/sys_string_conversions.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/sys_info.h"
35 #include "base/threading/platform_thread.h"
36 #include "base/time/time.h"
37 #include "base/values.h"
38 #include "build/build_config.h"
39 #include "chrome/browser/about_flags.h"
40 #include "chrome/browser/browser_process.h"
41 #include "chrome/browser/browser_process_impl.h"
42 #include "chrome/browser/browser_process_platform_part.h"
43 #include "chrome/browser/browser_shutdown.h"
44 #include "chrome/browser/chrome_browser_main_extra_parts.h"
45 #include "chrome/browser/component_updater/cld_component_installer.h"
46 #include "chrome/browser/component_updater/component_updater_service.h"
47 #include "chrome/browser/component_updater/flash_component_installer.h"
48 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
49 #include "chrome/browser/component_updater/recovery_component_installer.h"
50 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
51 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
52 #include "chrome/browser/defaults.h"
53 #include "chrome/browser/extensions/extension_service.h"
54 #include "chrome/browser/extensions/startup_helper.h"
55 #include "chrome/browser/feedback/feedback_profile_observer.h"
56 #include "chrome/browser/first_run/first_run.h"
57 #include "chrome/browser/first_run/upgrade_util.h"
58 #include "chrome/browser/google/google_search_counter.h"
59 #include "chrome/browser/google/google_util.h"
60 #include "chrome/browser/gpu/gl_string_manager.h"
61 #include "chrome/browser/jankometer.h"
62 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
63 #include "chrome/browser/metrics/field_trial_synchronizer.h"
64 #include "chrome/browser/metrics/metrics_log.h"
65 #include "chrome/browser/metrics/metrics_service.h"
66 #include "chrome/browser/metrics/thread_watcher.h"
67 #include "chrome/browser/metrics/tracking_synchronizer.h"
68 #include "chrome/browser/metrics/variations/variations_http_header_provider.h"
69 #include "chrome/browser/metrics/variations/variations_service.h"
70 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
71 #include "chrome/browser/net/chrome_net_log.h"
72 #include "chrome/browser/net/crl_set_fetcher.h"
73 #include "chrome/browser/notifications/desktop_notification_service.h"
74 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
75 #include "chrome/browser/performance_monitor/performance_monitor.h"
76 #include "chrome/browser/performance_monitor/startup_timer.h"
77 #include "chrome/browser/plugins/plugin_prefs.h"
78 #include "chrome/browser/pref_service_flags_storage.h"
79 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
80 #include "chrome/browser/prefs/command_line_pref_store.h"
81 #include "chrome/browser/prefs/pref_metrics_service.h"
82 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
83 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
84 #include "chrome/browser/process_singleton.h"
85 #include "chrome/browser/profiles/profile.h"
86 #include "chrome/browser/profiles/profile_manager.h"
87 #include "chrome/browser/profiles/profiles_state.h"
88 #include "chrome/browser/shell_integration.h"
89 #include "chrome/browser/three_d_api_observer.h"
90 #include "chrome/browser/translate/translate_service.h"
91 #include "chrome/browser/ui/app_list/app_list_service.h"
92 #include "chrome/browser/ui/browser.h"
93 #include "chrome/browser/ui/browser_finder.h"
94 #include "chrome/browser/ui/host_desktop.h"
95 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
96 #include "chrome/browser/ui/startup/default_browser_prompt.h"
97 #include "chrome/browser/ui/startup/startup_browser_creator.h"
98 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
99 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
100 #include "chrome/common/chrome_constants.h"
101 #include "chrome/common/chrome_paths.h"
102 #include "chrome/common/chrome_result_codes.h"
103 #include "chrome/common/chrome_switches.h"
104 #include "chrome/common/crash_keys.h"
105 #include "chrome/common/env_vars.h"
106 #include "chrome/common/logging_chrome.h"
107 #include "chrome/common/net/net_resource_provider.h"
108 #include "chrome/common/pref_names.h"
109 #include "chrome/common/profiling.h"
110 #include "chrome/installer/util/google_update_settings.h"
111 #include "components/language_usage_metrics/language_usage_metrics.h"
112 #include "components/nacl/browser/nacl_browser.h"
113 #include "components/nacl/browser/nacl_process_host.h"
114 #include "components/rappor/rappor_service.h"
115 #include "components/signin/core/common/profile_management_switches.h"
116 #include "components/startup_metric_utils/startup_metric_utils.h"
117 #include "components/translate/core/browser/translate_download_manager.h"
118 #include "content/public/browser/browser_thread.h"
119 #include "content/public/browser/notification_observer.h"
120 #include "content/public/browser/notification_registrar.h"
121 #include "content/public/browser/notification_service.h"
122 #include "content/public/browser/notification_types.h"
123 #include "content/public/browser/site_instance.h"
124 #include "content/public/common/content_client.h"
125 #include "content/public/common/content_switches.h"
126 #include "content/public/common/main_function_params.h"
127 #include "extensions/browser/extension_protocols.h"
128 #include "extensions/browser/extension_system.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_ANDROID)
145 #include "chrome/browser/metrics/thread_watcher_android.h"
148 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
149 #include "chrome/browser/first_run/upgrade_util_linux.h"
150 #include "chrome/browser/sxs_linux.h"
153 #if defined(OS_CHROMEOS)
154 #include "chrome/browser/chromeos/settings/cros_settings.h"
155 #include "chromeos/chromeos_switches.h"
156 #include "chromeos/settings/cros_settings_names.h"
159 // TODO(port): several win-only methods have been pulled out of this, but
160 // BrowserMain() as a whole needs to be broken apart so that it's usable by
161 // other platforms. For now, it's just a stub. This is a serious work in
162 // progress and should not be taken as an indication of a real refactoring.
165 #include "base/environment.h" // For PreRead experiment.
166 #include "base/win/windows_version.h"
167 #include "chrome/browser/browser_util_win.h"
168 #include "chrome/browser/chrome_browser_main_win.h"
169 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
170 #include "chrome/browser/first_run/upgrade_util_win.h"
171 #include "chrome/browser/ui/network_profile_bubble.h"
172 #include "chrome/common/net/url_fixer_upper.h"
173 #include "chrome/installer/util/helper.h"
174 #include "chrome/installer/util/install_util.h"
175 #include "chrome/installer/util/shell_util.h"
176 #include "net/base/net_util.h"
177 #include "ui/base/l10n/l10n_util_win.h"
178 #include "ui/gfx/win/dpi.h"
179 #endif // defined(OS_WIN)
181 #if defined(OS_MACOSX)
182 #include <Security/Security.h>
184 #include "base/mac/scoped_nsautorelease_pool.h"
185 #include "chrome/browser/mac/keystone_glue.h"
188 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
189 #include "printing/printed_document.h"
192 #if defined(ENABLE_RLZ)
193 #include "chrome/browser/rlz/rlz.h"
196 #if defined(ENABLE_WEBRTC)
197 #include "chrome/browser/media/webrtc_log_util.h"
200 #if defined(USE_AURA)
201 #include "ui/aura/env.h"
204 using content::BrowserThread
;
208 // This function provides some ways to test crash and assertion handling
209 // behavior of the program.
210 void HandleTestParameters(const CommandLine
& command_line
) {
211 // This parameter causes an assertion.
212 if (command_line
.HasSwitch(switches::kBrowserAssertTest
)) {
216 // This parameter causes a null pointer crash (crash reporter trigger).
217 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
218 int* bad_pointer
= NULL
;
223 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
224 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
225 const std::vector
<GURL
>& new_tabs
) {
226 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
227 it
!= new_tabs
.end(); ++it
) {
229 browser_creator
->AddFirstRunTab(*it
);
232 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
234 // Returns the new local state object, guaranteed non-NULL.
235 // |local_state_task_runner| must be a shutdown-blocking task runner.
236 PrefService
* InitializeLocalState(
237 base::SequencedTaskRunner
* local_state_task_runner
,
238 const CommandLine
& parsed_command_line
) {
239 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
240 base::FilePath local_state_path
;
241 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
242 bool local_state_file_exists
= base::PathExists(local_state_path
);
244 // Load local state. This includes the application locale so we know which
245 // locale dll to load. This also causes local state prefs to be registered.
246 PrefService
* local_state
= g_browser_process
->local_state();
250 if (first_run::IsChromeFirstRun()) {
251 // During first run we read the google_update registry key to find what
252 // language the user selected when downloading the installer. This
253 // becomes our default language in the prefs.
254 // Other platforms obey the system locale.
255 base::string16 install_lang
;
256 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
257 local_state
->SetString(prefs::kApplicationLocale
,
258 base::UTF16ToASCII(install_lang
));
261 #endif // defined(OS_WIN)
263 // If the local state file for the current profile doesn't exist and the
264 // parent profile command line flag is present, then we should inherit some
265 // local state from the parent profile.
266 // Checking that the local state file for the current profile doesn't exist
267 // is the most robust way to determine whether we need to inherit or not
268 // since the parent profile command line flag can be present even when the
269 // current profile is not a new one, and in that case we do not want to
270 // inherit and reset the user's setting.
272 // TODO(mnissler): We should probably just instantiate a
273 // JSONPrefStore here instead of an entire PrefService. Once this is
274 // addressed, the call to browser_prefs::RegisterLocalState can move
275 // to chrome_prefs::CreateLocalState.
276 if (!local_state_file_exists
&&
277 parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
278 base::FilePath parent_profile
=
279 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
280 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
281 scoped_ptr
<PrefService
> parent_local_state(
282 chrome_prefs::CreateLocalState(
284 local_state_task_runner
,
285 g_browser_process
->policy_service(),
288 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
289 // Right now, we only inherit the locale setting from the parent profile.
290 local_state
->SetString(
291 prefs::kApplicationLocale
,
292 parent_local_state
->GetString(prefs::kApplicationLocale
));
295 #if defined(OS_CHROMEOS)
296 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
297 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
298 // Ensure that we start with owner's locale.
299 if (!owner_locale
.empty() &&
300 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
301 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
302 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
310 // Initializes the primary profile, possibly doing some user prompting to pick
311 // a fallback profile. Returns the newly created profile, or NULL if startup
312 // should not continue.
313 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
314 const base::FilePath
& user_data_dir
,
315 const CommandLine
& parsed_command_line
) {
316 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
317 base::Time start
= base::Time::Now();
318 if (profiles::IsMultipleProfilesEnabled() &&
319 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
320 g_browser_process
->local_state()->SetString(prefs::kProfileLastUsed
,
321 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
322 // Clear kProfilesLastActive since the user only wants to launch a specific
324 ListPrefUpdate
update(g_browser_process
->local_state(),
325 prefs::kProfilesLastActive
);
326 base::ListValue
* profile_list
= update
.Get();
327 profile_list
->Clear();
330 Profile
* profile
= NULL
;
331 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
332 // On ChromeOS and Android the ProfileManager will use the same path as the
333 // one we got passed. GetActiveUserProfile will therefore use the correct path
335 DCHECK_EQ(user_data_dir
.value(),
336 g_browser_process
->profile_manager()->user_data_dir().value());
337 profile
= ProfileManager::GetActiveUserProfile();
339 base::FilePath profile_path
=
340 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
341 profile
= g_browser_process
->profile_manager()->GetProfile(
344 // If we're using the --new-profile-management flag and this profile is
345 // signed out, then we should show the user manager instead. By switching
346 // the active profile to the guest profile we ensure that no
347 // browser windows will be opened for the guest profile.
348 if (switches::IsNewProfileManagement() && !profile
->IsGuestSession()) {
349 ProfileInfoCache
& cache
=
350 g_browser_process
->profile_manager()->GetProfileInfoCache();
351 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
353 if (cache
.ProfileIsSigninRequiredAtIndex(profile_index
))
354 profile
= g_browser_process
->profile_manager()->GetProfile(
355 ProfileManager::GetGuestProfilePath());
359 UMA_HISTOGRAM_LONG_TIMES(
360 "Startup.CreateFirstProfile", base::Time::Now() - start
);
365 // TODO(port): fix this. See comments near the definition of
366 // user_data_dir. It is better to CHECK-fail here than it is to
367 // silently exit because of missing code in the above test.
368 CHECK(profile
) << "Cannot get default profile.";
374 #if defined(OS_MACOSX)
375 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
376 SecKeychainCallbackInfo
* info
, void* context
) {
381 void RegisterComponentsForUpdate(const CommandLine
& command_line
) {
382 component_updater::ComponentUpdateService
* cus
=
383 g_browser_process
->component_updater();
385 // Registration can be before or after cus->Start() so it is ok to post
386 // a task to the UI thread to do registration once you done the necessary
387 // file IO to know you existing component version.
388 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
389 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
390 RegisterPepperFlashComponent(cus
);
391 RegisterSwiftShaderComponent(cus
);
394 #if !defined(OS_ANDROID)
395 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(
399 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
400 RegisterWidevineCdmComponent(cus
);
403 #if !defined(OS_CHROMEOS)
404 // CRLSetFetcher attempts to load a CRL set from either the local disk or
406 if (!command_line
.HasSwitch(switches::kDisableCRLSets
))
407 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
);
410 #if defined(CLD2_DYNAMIC_MODE) && defined(CLD2_IS_COMPONENT)
411 RegisterCldComponent(cus
);
417 #if !defined(OS_ANDROID)
418 bool ProcessSingletonNotificationCallback(
419 const CommandLine
& command_line
,
420 const base::FilePath
& current_directory
) {
421 // Drop the request if the browser process is already in shutdown path.
422 if (!g_browser_process
|| g_browser_process
->IsShuttingDown())
425 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
426 std::string start_time_string
=
427 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
428 int64 remote_start_time
;
429 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
430 base::TimeDelta elapsed
=
431 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
432 if (command_line
.HasSwitch(switches::kFastStart
)) {
433 UMA_HISTOGRAM_LONG_TIMES(
434 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
436 UMA_HISTOGRAM_LONG_TIMES(
437 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
442 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
445 base::FilePath user_data_dir
=
446 g_browser_process
->profile_manager()->user_data_dir();
447 base::FilePath startup_profile_dir
=
448 GetStartupProfilePath(user_data_dir
, command_line
);
450 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
451 command_line
, current_directory
, startup_profile_dir
);
454 #endif // !defined(OS_ANDROID)
456 void LaunchDevToolsHandlerIfNeeded(const CommandLine
& command_line
) {
457 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
458 std::string port_str
=
459 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
461 if (base::StringToInt(port_str
, &port
) && port
> 0 && port
< 65535) {
462 g_browser_process
->CreateDevToolsHttpProtocolHandler(
463 chrome::HOST_DESKTOP_TYPE_NATIVE
,
467 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
472 // Heap allocated class that listens for first page load, kicks off stat
473 // recording and then deletes itself.
474 class LoadCompleteListener
: public content::NotificationObserver
{
476 LoadCompleteListener() {
478 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
479 content::NotificationService::AllSources());
481 virtual ~LoadCompleteListener() {}
483 // content::NotificationObserver implementation.
484 virtual void Observe(int type
,
485 const content::NotificationSource
& source
,
486 const content::NotificationDetails
& details
) OVERRIDE
{
487 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
488 startup_metric_utils::OnInitialPageLoadComplete();
493 content::NotificationRegistrar registrar_
;
494 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
499 namespace chrome_browser
{
501 // This error message is not localized because we failed to load the
502 // localization data files.
504 const char kMissingLocaleDataTitle
[] = "Missing File Error";
508 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
509 const char kMissingLocaleDataMessage
[] =
510 "Unable to find locale data files. Please reinstall.";
513 } // namespace chrome_browser
515 // BrowserMainParts ------------------------------------------------------------
518 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_
=
521 ChromeBrowserMainParts::ChromeBrowserMainParts(
522 const content::MainFunctionParams
& parameters
)
523 : parameters_(parameters
),
524 parsed_command_line_(parameters
.command_line
),
525 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
526 startup_watcher_(new StartupTimeBomb()),
527 shutdown_watcher_(new ShutdownWatcherHelper()),
528 startup_timer_(new performance_monitor::StartupTimer()),
529 browser_field_trials_(parameters
.command_line
),
531 run_message_loop_(true),
532 notify_result_(ProcessSingleton::PROCESS_NONE
),
534 restart_last_session_(false) {
535 // If we're running tests (ui_task is non-null).
536 if (parameters
.ui_task
)
537 browser_defaults::enable_help_app
= false;
539 // Chrome disallows cookies by default. All code paths that want to use
540 // cookies need to go through one of Chrome's URLRequestContexts which have
541 // a ChromeNetworkDelegate attached that selectively allows cookies again.
542 if (!disable_enforcing_cookie_policies_for_tests_
)
543 net::URLRequest::SetDefaultCookiePolicyToBlock();
546 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
547 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
548 delete chrome_extra_parts_
[i
];
549 chrome_extra_parts_
.clear();
552 // This will be called after the command-line has been mutated by about:flags
553 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
554 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
555 // Must initialize metrics after labs have been converted into switches,
556 // but before field trials are set up (so that client ID is available for
557 // one-time randomized field trials).
558 #if defined(ARCH_CPU_64_BITS)
559 MetricsLog::set_version_extension("-64");
560 #endif // defined(ARCH_CPU_64_BITS)
562 // Initialize FieldTrialList to support FieldTrials that use one-time
564 MetricsService
* metrics
= browser_process_
->metrics_service();
565 field_trial_list_
.reset(
566 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
568 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
569 if (command_line
->HasSwitch(switches::kEnableBenchmarking
))
570 base::FieldTrial::EnableBenchmarking();
572 // Ensure any field trials specified on the command line are initialized.
573 // Also stop the metrics service so that we don't pollute UMA.
574 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
575 std::set
<std::string
> unforceable_field_trials
;
576 #if defined(OFFICIAL_BUILD)
577 unforceable_field_trials
.insert("SettingsEnforcement");
578 #endif // defined(OFFICIAL_BUILD)
580 // Create field trials without activating them, so that this behaves in a
581 // consistent manner with field trials created from the server.
582 bool result
= base::FieldTrialList::CreateTrialsFromString(
583 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
584 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
585 unforceable_field_trials
);
586 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
587 << " list specified.";
589 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
590 // Create default variation ids which will always be included in the
591 // X-Client-Data request header.
592 chrome_variations::VariationsHttpHeaderProvider
* provider
=
593 chrome_variations::VariationsHttpHeaderProvider::GetInstance();
594 bool result
= provider
->SetDefaultVariationIds(
595 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
596 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
597 << " list specified.";
599 chrome_variations::VariationsService
* variations_service
=
600 browser_process_
->variations_service();
601 if (variations_service
)
602 variations_service
->CreateTrialsFromSeed();
604 // This must be called after the local state is initialized.
605 browser_field_trials_
.SetupFieldTrials(local_state_
);
607 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
608 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
609 // Even though base::Bind does AddRef and Release, the object will not be
610 // deleted after the Task is executed.
611 field_trial_synchronizer_
= new FieldTrialSynchronizer();
613 // Now that field trials have been created, initializes metrics recording.
614 metrics
->InitializeMetricsRecordingState();
617 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
619 void ChromeBrowserMainParts::StartMetricsRecording() {
620 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
621 MetricsService
* metrics
= g_browser_process
->metrics_service();
623 const bool only_do_metrics_recording
=
624 parsed_command_line_
.HasSwitch(switches::kMetricsRecordingOnly
) ||
625 parsed_command_line_
.HasSwitch(switches::kEnableBenchmarking
);
626 if (only_do_metrics_recording
) {
627 // If we're testing then we don't care what the user preference is, we turn
628 // on recording, but not reporting, otherwise tests fail.
629 metrics
->StartRecordingForTests();
633 metrics
->CheckForClonedInstall();
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 prefered
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 // Now that all preferences have been registered, set the install date
940 // for the uninstall metrics if this is our first run. This only actually
941 // gets used if the user has metrics reporting enabled at uninstall time.
942 int64 install_date
= local_state_
->GetInt64(prefs::kInstallDate
);
943 if (install_date
== 0)
944 local_state_
->SetInt64(prefs::kInstallDate
, base::Time::Now().ToTimeT());
946 #if defined(OS_MACOSX)
947 // Get the Keychain API to register for distributed notifications on the main
948 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
949 // which doesn't. This ensures those notifications will get delivered
950 // properly. See issue 37766.
951 // (Note that the callback mask here is empty. I don't want to register for
952 // any callbacks, I just want to initialize the mechanism.)
953 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
956 #if defined(OS_CHROMEOS)
957 // Must be done after g_browser_process is constructed, before
958 // SetupMetricsAndFieldTrials().
959 chromeos::CrosSettings::Initialize();
962 // Now the command line has been mutated based on about:flags, we can setup
963 // metrics and initialize field trials. The field trials are needed by
964 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
965 SetupMetricsAndFieldTrials();
967 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
968 browser_process_
->PreCreateThreads();
970 return content::RESULT_CODE_NORMAL_EXIT
;
973 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
974 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
975 result_code_
= PreMainMessageLoopRunImpl();
977 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
978 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
981 // PreMainMessageLoopRun calls these extra stages in the following order:
982 // PreMainMessageLoopRunImpl()
983 // ... initial setup, including browser_process_ setup.
985 // ... additional setup, including CreateProfile()
987 // ... additional setup
989 // ... browser_creator_->Start (OR parameters().ui_task->Run())
990 // PostBrowserStart()
992 void ChromeBrowserMainParts::PreProfileInit() {
993 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
995 // Initialize the feedback uploader so it can setup notifications for profile
997 feedback::FeedbackProfileObserver::Initialize();
999 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1000 chrome_extra_parts_
[i
]->PreProfileInit();
1002 #if !defined(OS_ANDROID)
1003 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
1005 // First check if any ephemeral profiles are left behind because of browser
1006 // crash and schedule them for deletion and then proceed with getting the set
1007 // of profiles to open.
1008 ProfileInfoCache
& profile_cache
= profile_manager
->GetProfileInfoCache();
1009 size_t profiles_count
= profile_cache
.GetNumberOfProfiles();
1010 std::vector
<base::FilePath
> profiles_to_delete
;
1011 for (size_t i
= 0; i
< profiles_count
; ++i
) {
1012 if (profile_cache
.ProfileIsEphemeralAtIndex(i
))
1013 profiles_to_delete
.push_back(profile_cache
.GetPathOfProfileAtIndex(i
));
1016 if (profiles_to_delete
.size()) {
1017 for (size_t i
= 0; i
< profiles_to_delete
.size(); ++i
) {
1018 profile_manager
->ScheduleProfileForDeletion(
1019 profiles_to_delete
[i
], ProfileManager::CreateCallback());
1021 // Clean up stale profiles immediately after browser start.
1022 BrowserThread::PostTask(
1023 BrowserThread::FILE, FROM_HERE
,
1024 base::Bind(&ProfileManager::CleanUpStaleProfiles
, profiles_to_delete
));
1026 #endif // OS_ANDROID
1029 void ChromeBrowserMainParts::PostProfileInit() {
1030 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1031 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1032 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1033 chrome_extra_parts_
[i
]->PostProfileInit();
1036 void ChromeBrowserMainParts::PreBrowserStart() {
1037 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1038 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1039 chrome_extra_parts_
[i
]->PreBrowserStart();
1041 three_d_observer_
.reset(new ThreeDAPIObserver());
1044 void ChromeBrowserMainParts::PostBrowserStart() {
1045 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1046 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1047 chrome_extra_parts_
[i
]->PostBrowserStart();
1048 #if !defined(OS_ANDROID)
1049 // Allow ProcessSingleton to process messages.
1050 process_singleton_
->Unlock();
1052 #if defined(ENABLE_WEBRTC)
1053 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1054 // to reduce the impact on startup time.
1055 BrowserThread::PostDelayedTask(
1058 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1059 base::TimeDelta::FromMinutes(1));
1063 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1064 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1065 // Android updates the metrics service dynamically depending on whether the
1066 // application is in the foreground or not. Do not start here.
1067 #if !defined(OS_ANDROID)
1068 // Now that the file thread has been started, start recording.
1069 StartMetricsRecording();
1072 // Create watchdog thread after creating all other threads because it will
1073 // watch the other threads and they must be running.
1074 browser_process_
->watchdog_thread();
1076 // Do any initializating in the browser process that requires all threads
1078 browser_process_
->PreMainMessageLoopRun();
1080 // Record last shutdown time into a histogram.
1081 browser_shutdown::ReadLastShutdownInfo();
1084 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1085 // tasks. Those care whether the browser is already running. On Linux/Mac,
1086 // upgrade/uninstall happen separately.
1087 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1089 // If the command line specifies 'uninstall' then we need to work here
1090 // unless we detect another chrome browser running.
1091 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1092 return DoUninstallTasks(already_running
);
1095 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1096 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1097 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1098 parsed_command_line_
);
1102 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1103 return ShellIntegration::SetAsDefaultBrowser() ?
1104 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1105 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1108 #if defined(USE_AURA)
1109 // Make sure aura::Env has been initialized.
1110 CHECK(aura::Env::GetInstance());
1113 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1114 #if !defined(OS_ANDROID)
1115 // If the command line specifies --pack-extension, attempt the pack extension
1116 // startup action and exit.
1117 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1118 extensions::StartupHelper extension_startup_helper
;
1119 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1120 return content::RESULT_CODE_NORMAL_EXIT
;
1121 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1124 // If we're being launched just to check the connector policy, we are
1125 // short-lived and don't want to be passing that switch off.
1126 bool pass_command_line
= !parsed_command_line().HasSwitch(
1127 switches::kCheckCloudPrintConnectorPolicy
);
1129 if (pass_command_line
) {
1130 // When another process is running, use that process instead of starting a
1131 // new one. NotifyOtherProcess will currently give the other process up to
1132 // 20 seconds to respond. Note that this needs to be done before we attempt
1133 // to read the profile.
1134 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1135 switch (notify_result_
) {
1136 case ProcessSingleton::PROCESS_NONE
:
1137 // No process already running, fall through to starting a new one.
1140 case ProcessSingleton::PROCESS_NOTIFIED
:
1141 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1142 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1143 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1145 // Having a differentiated return type for testing allows for tests to
1146 // verify proper handling of some switches. When not testing, stick to
1147 // the standard Unix convention of returning zero when things went as
1149 if (parsed_command_line().HasSwitch(switches::kTestType
))
1150 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1151 return content::RESULT_CODE_NORMAL_EXIT
;
1153 case ProcessSingleton::PROFILE_IN_USE
:
1154 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1156 case ProcessSingleton::LOCK_ERROR
:
1157 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1158 "directory. This means that running multiple instances "
1159 "would start multiple browser processes rather than "
1160 "opening a new window in the existing process. Aborting "
1161 "now to avoid profile corruption.";
1162 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1168 #endif // !defined(OS_ANDROID)
1170 // Handle special early return paths (which couldn't be processed even earlier
1171 // as they require the process singleton to be held) first.
1173 std::string try_chrome
=
1174 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1175 if (!try_chrome
.empty()) {
1177 // Setup.exe has determined that we need to run a retention experiment
1178 // and has lauched chrome to show the experiment UI. It is guaranteed that
1179 // no other Chrome is currently running as the process singleton was
1180 // sucessfully grabbed above.
1182 base::StringToInt(try_chrome
, &try_chrome_int
);
1183 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1185 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1186 base::Unretained(process_singleton_
.get())));
1187 if (answer
== TryChromeDialogView::NOT_NOW
)
1188 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1189 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1190 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1191 // At this point the user is willing to try chrome again.
1192 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1193 // Only set in the unattended case, the interactive case is Windows 8.
1194 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1195 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1196 ShellIntegration::SetAsDefaultBrowser();
1199 // We don't support retention experiments on Mac or Linux.
1200 return content::RESULT_CODE_NORMAL_EXIT
;
1201 #endif // defined(OS_WIN)
1205 // Do the tasks if chrome has been upgraded while it was last running.
1206 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1207 return content::RESULT_CODE_NORMAL_EXIT
;
1209 // Check if there is any machine level Chrome installed on the current
1210 // machine. If yes and the current Chrome process is user level, we do not
1211 // allow the user level Chrome to run. So we notify the user and uninstall
1212 // user level Chrome.
1213 // Note this check needs to happen here (after the process singleton was
1214 // obtained but before potentially creating the first run sentinel).
1215 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1216 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1217 #endif // defined(OS_WIN)
1219 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1220 if (sxs_linux::ShouldMigrateUserDataDir())
1221 return sxs_linux::MigrateUserDataDir();
1222 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1224 // Desktop construction occurs here, (required before profile creation).
1227 // Profile creation ----------------------------------------------------------
1229 MetricsService::SetExecutionPhase(MetricsService::CREATE_PROFILE
);
1230 profile_
= CreatePrimaryProfile(parameters(),
1232 parsed_command_line());
1234 return content::RESULT_CODE_NORMAL_EXIT
;
1236 #if !defined(OS_ANDROID)
1237 // The first run sentinel must be created after the process singleton was
1238 // grabbed and no early return paths were otherwise hit above.
1239 first_run::CreateSentinelIfNeeded();
1240 #endif // !defined(OS_ANDROID)
1242 #if defined(ENABLE_BACKGROUND)
1243 // Autoload any profiles which are running background apps.
1244 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1245 browser_process_
->profile_manager()->AutoloadProfiles();
1247 // Post-profile init ---------------------------------------------------------
1249 TranslateService::Initialize();
1251 // Needs to be done before PostProfileInit, since login manager on CrOS is
1252 // called inside PostProfileInit.
1253 content::WebUIControllerFactory::RegisterFactory(
1254 ChromeWebUIControllerFactory::GetInstance());
1256 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1257 // So make sure to create it before that.
1258 #if !defined(DISABLE_NACL)
1259 NaClBrowserDelegateImpl
* delegate
= new NaClBrowserDelegateImpl(
1260 extensions::ExtensionSystem::Get(profile_
)->info_map());
1261 nacl::NaClBrowser::SetDelegate(delegate
);
1264 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1265 // (requires supporting early exit).
1268 // Retrieve cached GL strings from local state and use them for GPU
1269 // blacklist decisions.
1270 if (g_browser_process
->gl_string_manager())
1271 g_browser_process
->gl_string_manager()->Initialize();
1273 // Create an instance of GpuModeManager to watch gpu mode pref change.
1274 g_browser_process
->gpu_mode_manager();
1276 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1277 // Show the First Run UI if this is the first time Chrome has been run on
1278 // this computer, or we're being compelled to do so by a command line flag.
1279 // Note that this be done _after_ the PrefService is initialized and all
1280 // preferences are registered, since some of the code that the importer
1281 // touches reads preferences.
1282 if (first_run::IsChromeFirstRun()) {
1283 first_run::AutoImport(profile_
,
1284 master_prefs_
->homepage_defined
,
1285 master_prefs_
->do_import_items
,
1286 master_prefs_
->dont_import_items
,
1287 master_prefs_
->import_bookmarks_path
);
1289 // Note: this can pop the first run consent dialog on linux.
1290 first_run::DoPostImportTasks(profile_
,
1291 master_prefs_
->make_chrome_default_for_user
);
1293 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1294 browser_creator_
->set_show_main_browser_window(
1295 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1297 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1300 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1303 // Sets things up so that if we crash from this point on, a dialog will
1304 // popup asking the user to restart chrome. It is done this late to avoid
1305 // testing against a bunch of special cases that are taken care early on.
1306 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1307 parsed_command_line());
1309 // Registers Chrome with the Windows Restart Manager, which will restore the
1310 // Chrome session when the computer is restarted after a system update.
1311 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1312 // but should run on startup if extended to handle crashes/hangs/patches.
1313 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1314 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1315 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1316 parsed_command_line());
1319 // Verify that the profile is not on a network share and if so prepare to show
1320 // notification to the user.
1321 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1322 content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE
,
1323 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1324 profile_
->GetPath()));
1328 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1329 // Init the RLZ library. This just binds the dll and schedules a task on the
1330 // file thread to be run sometime later. If this is the first run we record
1331 // the installation event.
1332 PrefService
* pref_service
= profile_
->GetPrefs();
1333 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1334 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1335 // Negative ping delay means to send ping immediately after a first search is
1337 RLZTracker::InitRlzFromProfileDelayed(
1338 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1339 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1340 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1342 // Configure modules that need access to resources.
1343 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1345 // In unittest mode, this will do nothing. In normal mode, this will create
1346 // the global IntranetRedirectDetector instance, which will promptly go to
1347 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1348 // to see if it should do anything else.
1350 // A simpler way of doing all this would be to have some function which could
1351 // give the time elapsed since startup, and simply have this object check that
1352 // when asked to initialize itself, but this doesn't seem to exist.
1354 // This can't be created in the BrowserProcessImpl constructor because it
1355 // needs to read prefs that get set after that runs.
1356 browser_process_
->intranet_redirect_detector();
1357 GoogleSearchCounter::RegisterForNotifications();
1359 if (parsed_command_line().HasSwitch(switches::kEnableSdchOverHttps
)) {
1360 net::SdchManager::EnableSecureSchemeSupport(true);
1362 // Check SDCH field trial.
1363 const char kSdchFieldTrialName
[] = "SDCH";
1364 const char kEnabledAllGroupName
[] = "EnabledAll";
1365 const char kEnabledHttpOnlyGroupName
[] = "EnabledHttpOnly";
1366 const char kDisabledAllGroupName
[] = "DisabledAll";
1368 base::StringPiece sdch_trial_group
=
1369 base::FieldTrialList::FindFullName(kSdchFieldTrialName
);
1370 if (sdch_trial_group
.starts_with(kEnabledAllGroupName
)) {
1371 net::SdchManager::EnableSecureSchemeSupport(true);
1372 net::SdchManager::EnableSdchSupport(true);
1373 } else if (sdch_trial_group
.starts_with(kEnabledHttpOnlyGroupName
)) {
1374 net::SdchManager::EnableSdchSupport(true);
1375 } else if (sdch_trial_group
.starts_with(kDisabledAllGroupName
)) {
1376 net::SdchManager::EnableSdchSupport(false);
1380 if (parsed_command_line().HasSwitch(switches::kEnableWatchdog
))
1381 InstallJankometer(parsed_command_line());
1383 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD)
1384 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1385 base::FilePath path
=
1386 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1387 printing::PrintedDocument::set_debug_dump_path(path
);
1391 HandleTestParameters(parsed_command_line());
1392 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1393 base::debug::BeingDebugged());
1395 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1396 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1397 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1398 browser_process_
->GetApplicationLocale());
1400 // Start watching for hangs during startup. We disarm this hang detector when
1401 // ThreadWatcher takes over or when browser is shutdown or when
1402 // startup_watcher_ is deleted.
1403 MetricsService::SetExecutionPhase(MetricsService::STARTUP_TIMEBOMB_ARM
);
1404 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1406 // On mobile, need for clean shutdown arises only when the application comes
1407 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1408 // http://crbug.com/179143
1409 #if !defined(OS_ANDROID)
1410 // Start watching for a hang.
1411 MetricsService::LogNeedForCleanShutdown();
1414 #if defined(ENABLE_FULL_PRINTING)
1415 // Create the instance of the cloud print proxy service so that it can launch
1416 // the service process if needed. This is needed because the service process
1417 // might have shutdown because an update was available.
1418 // TODO(torne): this should maybe be done with
1419 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1421 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1424 // Start watching all browser threads for responsiveness.
1425 MetricsService::SetExecutionPhase(MetricsService::THREAD_WATCHER_START
);
1426 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1428 #if defined(OS_ANDROID)
1429 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1432 #if !defined(DISABLE_NACL)
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
->set_policy_pref_service(profile_
->GetPrefs());
1458 variations_service
->StartRepeatedVariationsSeedFetch();
1460 TranslateDownloadManager::RequestLanguageList(profile_
->GetPrefs());
1463 // Most general initialization is behind us, but opening a
1464 // tab and/or session restore and such is still to be done.
1465 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1467 // We are in regular browser boot sequence. Open initial tabs and enter the
1468 // main message loop.
1470 #if defined(OS_CHROMEOS)
1471 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1472 // them this early as the cryptohome hasn't yet been mounted (which happens
1473 // only once we log in.
1474 std::vector
<Profile
*> last_opened_profiles
;
1476 std::vector
<Profile
*> last_opened_profiles
=
1477 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1480 if (browser_creator_
->Start(parsed_command_line(), base::FilePath(),
1481 profile_
, last_opened_profiles
, &result_code
)) {
1482 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1483 // Initialize autoupdate timer. Timer callback costs basically nothing
1484 // when browser is not in persistent mode, so it's OK to let it ride on
1485 // the main thread. This needs to be done here because we don't want
1486 // to start the timer when Chrome is run inside a test harness.
1487 browser_process_
->StartAutoupdateTimer();
1490 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1491 // On Linux, the running exe will be updated if an upgrade becomes
1492 // available while the browser is running. We need to save the last
1493 // modified time of the exe, so we can compare to determine if there is
1494 // an upgrade while the browser is kept alive by a persistent extension.
1495 upgrade_util::SaveLastModifiedTimeOfExe();
1498 // Record now as the last successful chrome start.
1499 GoogleUpdateSettings::SetLastRunTime();
1501 #if defined(OS_MACOSX)
1502 // Call Recycle() here as late as possible, before going into the loop
1503 // because Start() will add things to it while creating the main window.
1504 if (parameters().autorelease_pool
)
1505 parameters().autorelease_pool
->Recycle();
1508 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1509 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1511 // If we're running tests (ui_task is non-null), then we don't want to
1512 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1513 // RequestLanguageList
1514 if (parameters().ui_task
== NULL
) {
1515 // Request new variations seed information from server.
1516 chrome_variations::VariationsService
* variations_service
=
1517 browser_process_
->variations_service();
1518 if (variations_service
) {
1519 variations_service
->StartRepeatedVariationsSeedFetch();
1522 variations_service
->StartGoogleUpdateRegistrySync();
1526 TranslateDownloadManager::RequestLanguageList(profile_
->GetPrefs());
1529 run_message_loop_
= true;
1531 run_message_loop_
= false;
1533 browser_creator_
.reset();
1534 #endif // !defined(OS_ANDROID)
1536 performance_monitor::PerformanceMonitor::GetInstance()->Initialize();
1540 chrome_prefs::SchedulePrefHashStoresUpdateCheck(profile_
->GetPath());
1542 if (parameters().ui_task
) {
1543 // We end the startup timer here if we have parameters to run, because we
1544 // never start to run the main loop (where we normally stop the timer).
1545 startup_timer_
->SignalStartupComplete(
1546 performance_monitor::StartupTimer::STARTUP_TEST
);
1547 parameters().ui_task
->Run();
1548 delete parameters().ui_task
;
1549 run_message_loop_
= false;
1551 #if defined(OS_ANDROID)
1552 // We never run the C++ main loop on Android, since the UI thread message
1553 // loop is controlled by the OS, so this is as close as we can get to
1554 // the start of the main loop
1555 if (result_code_
<= 0) {
1556 RecordBrowserStartupTime();
1559 return result_code_
;
1562 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1563 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1564 #if defined(OS_ANDROID)
1565 // Chrome on Android does not use default MessageLoop. It has its own
1566 // Android specific MessageLoop
1570 // Set the result code set in PreMainMessageLoopRun or set above.
1571 *result_code
= result_code_
;
1572 if (!run_message_loop_
)
1573 return true; // Don't run the default message loop.
1575 // These should be invoked as close to the start of the browser's
1576 // UI thread message loop as possible to get a stable measurement
1578 RecordBrowserStartupTime();
1579 startup_timer_
->SignalStartupComplete(
1580 performance_monitor::StartupTimer::STARTUP_NORMAL
);
1582 DCHECK(base::MessageLoopForUI::IsCurrent());
1583 base::RunLoop run_loop
;
1585 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1587 MetricsService::SetExecutionPhase(MetricsService::MAIN_MESSAGE_LOOP_RUN
);
1594 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1595 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1596 #if defined(OS_ANDROID)
1597 // Chrome on Android does not use default MessageLoop. It has its own
1598 // Android specific MessageLoop
1602 // Start watching for jank during shutdown. It gets disarmed when
1603 // |shutdown_watcher_| object is destructed.
1604 MetricsService::SetExecutionPhase(MetricsService::SHUTDOWN_TIMEBOMB_ARM
);
1605 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1607 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1608 startup_watcher_
->Disarm();
1610 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1611 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1613 // Some tests don't set parameters.ui_task, so they started translate
1614 // language fetch that was never completed so we need to cleanup here
1615 // otherwise it will be done by the destructor in a wrong thread.
1616 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1618 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1619 process_singleton_
->Cleanup();
1621 // Stop all tasks that might run on WatchDogThread.
1622 ThreadWatcherList::StopWatchingAll();
1624 browser_process_
->metrics_service()->Stop();
1626 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1627 browser_process_
->StartTearDown();
1631 void ChromeBrowserMainParts::PostDestroyThreads() {
1632 #if defined(OS_ANDROID)
1633 // On Android, there is no quit/exit. So the browser's main message loop will
1637 browser_process_
->PostDestroyThreads();
1638 // browser_shutdown takes care of deleting browser_process, so we need to
1640 ignore_result(browser_process_
.release());
1641 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1642 master_prefs_
.reset();
1643 process_singleton_
.reset();
1645 // We need to do this check as late as possible, but due to modularity, this
1646 // may be the last point in Chrome. This would be more effective if done at
1647 // a higher level on the stack, so that it is impossible for an early return
1648 // to bypass this code. Perhaps we need a *final* hook that is called on all
1649 // paths from content/browser/browser_main.
1650 CHECK(MetricsService::UmaMetricsProperlyShutdown());
1652 #if defined(OS_CHROMEOS)
1653 chromeos::CrosSettings::Shutdown();
1660 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1661 chrome_extra_parts_
.push_back(parts
);