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/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram_macros.h"
20 #include "base/path_service.h"
21 #include "base/prefs/json_pref_store.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/prefs/pref_value_store.h"
25 #include "base/prefs/scoped_user_pref_update.h"
26 #include "base/process/process_info.h"
27 #include "base/profiler/scoped_tracker.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/trace_event/trace_event.h"
38 #include "base/values.h"
39 #include "build/build_config.h"
40 #include "cc/base/switches.h"
41 #include "chrome/browser/about_flags.h"
42 #include "chrome/browser/after_startup_task_utils.h"
43 #include "chrome/browser/browser_process.h"
44 #include "chrome/browser/browser_process_impl.h"
45 #include "chrome/browser/browser_process_platform_part.h"
46 #include "chrome/browser/browser_shutdown.h"
47 #include "chrome/browser/chrome_browser_main_extra_parts.h"
48 #include "chrome/browser/component_updater/cld_component_installer.h"
49 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
50 #include "chrome/browser/component_updater/flash_component_installer.h"
51 #include "chrome/browser/component_updater/recovery_component_installer.h"
52 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
53 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
54 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
55 #include "chrome/browser/defaults.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/gpu/gl_string_manager.h"
60 #include "chrome/browser/gpu/three_d_api_observer.h"
61 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
62 #include "chrome/browser/metrics/field_trial_synchronizer.h"
63 #include "chrome/browser/metrics/metrics_services_manager.h"
64 #include "chrome/browser/metrics/thread_watcher.h"
65 #include "chrome/browser/metrics/variations/variations_service.h"
66 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
67 #include "chrome/browser/net/chrome_net_log.h"
68 #include "chrome/browser/net/crl_set_fetcher.h"
69 #include "chrome/browser/notifications/desktop_notification_service.h"
70 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
71 #include "chrome/browser/performance_monitor/performance_monitor.h"
72 #include "chrome/browser/plugins/plugin_prefs.h"
73 #include "chrome/browser/power/process_power_collector.h"
74 #include "chrome/browser/pref_service_flags_storage.h"
75 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
76 #include "chrome/browser/prefs/command_line_pref_store.h"
77 #include "chrome/browser/prefs/pref_metrics_service.h"
78 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
79 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
80 #include "chrome/browser/process_singleton.h"
81 #include "chrome/browser/profiles/profile.h"
82 #include "chrome/browser/profiles/profile_manager.h"
83 #include "chrome/browser/profiles/profiles_state.h"
84 #include "chrome/browser/shell_integration.h"
85 #include "chrome/browser/translate/translate_service.h"
86 #include "chrome/browser/ui/app_list/app_list_service.h"
87 #include "chrome/browser/ui/browser.h"
88 #include "chrome/browser/ui/browser_finder.h"
89 #include "chrome/browser/ui/host_desktop.h"
90 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
91 #include "chrome/browser/ui/startup/default_browser_prompt.h"
92 #include "chrome/browser/ui/startup/startup_browser_creator.h"
93 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
94 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
95 #include "chrome/common/chrome_constants.h"
96 #include "chrome/common/chrome_paths.h"
97 #include "chrome/common/chrome_result_codes.h"
98 #include "chrome/common/chrome_switches.h"
99 #include "chrome/common/chrome_version_info.h"
100 #include "chrome/common/crash_keys.h"
101 #include "chrome/common/env_vars.h"
102 #include "chrome/common/logging_chrome.h"
103 #include "chrome/common/net/net_resource_provider.h"
104 #include "chrome/common/pref_names.h"
105 #include "chrome/common/profiling.h"
106 #include "chrome/grit/generated_resources.h"
107 #include "chrome/installer/util/google_update_settings.h"
108 #include "components/component_updater/component_updater_service.h"
109 #include "components/device_event_log/device_event_log.h"
110 #include "components/google/core/browser/google_util.h"
111 #include "components/language_usage_metrics/language_usage_metrics.h"
112 #include "components/metrics/call_stack_profile_metrics_provider.h"
113 #include "components/metrics/metrics_service.h"
114 #include "components/metrics/profiler/tracking_synchronizer.h"
115 #include "components/nacl/browser/nacl_browser.h"
116 #include "components/rappor/rappor_service.h"
117 #include "components/signin/core/common/profile_management_switches.h"
118 #include "components/startup_metric_utils/startup_metric_utils.h"
119 #include "components/translate/content/browser/browser_cld_utils.h"
120 #include "components/translate/content/common/cld_data_source.h"
121 #include "components/translate/core/browser/translate_download_manager.h"
122 #include "components/variations/net/variations_http_header_provider.h"
123 #include "components/variations/variations_associated_data.h"
124 #include "content/public/browser/browser_thread.h"
125 #include "content/public/browser/notification_observer.h"
126 #include "content/public/browser/notification_registrar.h"
127 #include "content/public/browser/notification_service.h"
128 #include "content/public/browser/notification_types.h"
129 #include "content/public/browser/power_usage_monitor.h"
130 #include "content/public/browser/site_instance.h"
131 #include "content/public/common/content_client.h"
132 #include "content/public/common/content_switches.h"
133 #include "content/public/common/main_function_params.h"
134 #include "grit/platform_locale_settings.h"
135 #include "net/base/net_module.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"
143 #include "ui/strings/grit/app_locale_settings.h"
145 #if defined(OS_ANDROID)
146 #include "chrome/browser/metrics/thread_watcher_android.h"
148 #include "chrome/browser/feedback/feedback_profile_observer.h"
149 #endif // defined(OS_ANDROID)
151 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
152 #include "chrome/browser/first_run/upgrade_util_linux.h"
153 #include "chrome/browser/sxs_linux.h"
154 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
156 #if defined(OS_CHROMEOS)
157 #include "chrome/browser/chromeos/settings/cros_settings.h"
158 #include "chromeos/chromeos_switches.h"
159 #include "chromeos/settings/cros_settings_names.h"
160 #endif // defined(OS_CHROMEOS)
162 // TODO(port): several win-only methods have been pulled out of this, but
163 // BrowserMain() as a whole needs to be broken apart so that it's usable by
164 // other platforms. For now, it's just a stub. This is a serious work in
165 // progress and should not be taken as an indication of a real refactoring.
168 #include "base/environment.h" // For PreRead experiment.
169 #include "base/win/windows_version.h"
170 #include "chrome/browser/browser_util_win.h"
171 #include "chrome/browser/chrome_browser_main_win.h"
172 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
173 #include "chrome/browser/component_updater/caps_installer_win.h"
174 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
175 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
176 #include "chrome/browser/first_run/upgrade_util_win.h"
177 #include "chrome/browser/ui/network_profile_bubble.h"
178 #include "chrome/installer/util/helper.h"
179 #include "chrome/installer/util/install_util.h"
180 #include "chrome/installer/util/shell_util.h"
181 #include "components/browser_watcher/exit_funnel_win.h"
182 #include "net/base/net_util.h"
183 #include "ui/base/l10n/l10n_util_win.h"
184 #include "ui/gfx/win/dpi.h"
185 #include "ui/shell_dialogs/select_file_dialog.h"
186 #endif // defined(OS_WIN)
188 #if defined(OS_MACOSX)
189 #include <Security/Security.h>
191 #include "base/mac/scoped_nsautorelease_pool.h"
192 #include "chrome/browser/mac/keystone_glue.h"
193 #endif // defined(OS_MACOSX)
196 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
197 #endif // !defined(OS_IOS)
199 #if !defined(DISABLE_NACL)
200 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
201 #include "components/nacl/browser/nacl_process_host.h"
202 #endif // !defined(DISABLE_NACL)
204 #if defined(ENABLE_EXTENSIONS)
205 #include "chrome/browser/extensions/startup_helper.h"
206 #include "extensions/browser/extension_protocols.h"
207 #include "extensions/common/features/feature_provider.h"
208 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
209 #endif // defined(ENABLE_EXTENSIONS)
211 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
212 #include "printing/printed_document.h"
213 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
215 #if defined(ENABLE_RLZ)
216 #include "chrome/browser/rlz/rlz.h"
217 #endif // defined(ENABLE_RLZ)
219 #if defined(ENABLE_WEBRTC)
220 #include "chrome/browser/media/webrtc_log_util.h"
221 #endif // defined(ENABLE_WEBRTC)
223 #if defined(USE_AURA)
224 #include "ui/aura/env.h"
225 #endif // defined(USE_AURA)
227 using content::BrowserThread
;
231 // This function provides some ways to test crash and assertion handling
232 // behavior of the program.
233 void HandleTestParameters(const base::CommandLine
& command_line
) {
234 // This parameter causes a null pointer crash (crash reporter trigger).
235 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
236 int* bad_pointer
= NULL
;
241 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
242 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
243 const std::vector
<GURL
>& new_tabs
) {
244 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
245 it
!= new_tabs
.end(); ++it
) {
247 browser_creator
->AddFirstRunTab(*it
);
250 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
252 // Returns the new local state object, guaranteed non-NULL.
253 // |local_state_task_runner| must be a shutdown-blocking task runner.
254 PrefService
* InitializeLocalState(
255 base::SequencedTaskRunner
* local_state_task_runner
,
256 const base::CommandLine
& parsed_command_line
) {
257 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
259 // Load local state. This includes the application locale so we know which
260 // locale dll to load. This also causes local state prefs to be registered.
261 PrefService
* local_state
= g_browser_process
->local_state();
265 if (first_run::IsChromeFirstRun()) {
266 // During first run we read the google_update registry key to find what
267 // language the user selected when downloading the installer. This
268 // becomes our default language in the prefs.
269 // Other platforms obey the system locale.
270 base::string16 install_lang
;
271 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
272 local_state
->SetString(prefs::kApplicationLocale
,
273 base::UTF16ToASCII(install_lang
));
276 #endif // defined(OS_WIN)
278 // If the local state file for the current profile doesn't exist and the
279 // parent profile command line flag is present, then we should inherit some
280 // local state from the parent profile.
281 // Checking that the local state file for the current profile doesn't exist
282 // is the most robust way to determine whether we need to inherit or not
283 // since the parent profile command line flag can be present even when the
284 // current profile is not a new one, and in that case we do not want to
285 // inherit and reset the user's setting.
287 // TODO(mnissler): We should probably just instantiate a
288 // JSONPrefStore here instead of an entire PrefService. Once this is
289 // addressed, the call to browser_prefs::RegisterLocalState can move
290 // to chrome_prefs::CreateLocalState.
291 if (parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
292 base::FilePath local_state_path
;
293 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
294 bool local_state_file_exists
= base::PathExists(local_state_path
);
295 if (!local_state_file_exists
) {
296 base::FilePath parent_profile
=
297 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
298 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
299 scoped_ptr
<PrefService
> parent_local_state(
300 chrome_prefs::CreateLocalState(
302 local_state_task_runner
,
303 g_browser_process
->policy_service(),
306 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
307 // Right now, we only inherit the locale setting from the parent profile.
308 local_state
->SetString(
309 prefs::kApplicationLocale
,
310 parent_local_state
->GetString(prefs::kApplicationLocale
));
314 #if defined(OS_CHROMEOS)
315 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
316 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
317 // Ensure that we start with owner's locale.
318 if (!owner_locale
.empty() &&
319 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
320 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
321 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
324 #endif // defined(OS_CHROMEOS)
329 // Initializes the primary profile, possibly doing some user prompting to pick
330 // a fallback profile. Returns the newly created profile, or NULL if startup
331 // should not continue.
332 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
333 const base::FilePath
& user_data_dir
,
334 const base::CommandLine
& parsed_command_line
) {
335 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
336 base::Time start
= base::Time::Now();
337 if (profiles::IsMultipleProfilesEnabled() &&
338 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
339 g_browser_process
->local_state()->SetString(prefs::kProfileLastUsed
,
340 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
341 // Clear kProfilesLastActive since the user only wants to launch a specific
343 ListPrefUpdate
update(g_browser_process
->local_state(),
344 prefs::kProfilesLastActive
);
345 base::ListValue
* profile_list
= update
.Get();
346 profile_list
->Clear();
349 Profile
* profile
= NULL
;
350 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
351 // On ChromeOS and Android the ProfileManager will use the same path as the
352 // one we got passed. GetActiveUserProfile will therefore use the correct path
354 DCHECK_EQ(user_data_dir
.value(),
355 g_browser_process
->profile_manager()->user_data_dir().value());
356 profile
= ProfileManager::GetActiveUserProfile();
358 base::FilePath profile_path
=
359 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
361 // Without NewAvatarMenu, replace guest with any existing profile.
362 if (!switches::IsNewAvatarMenu() &&
363 profile_path
== ProfileManager::GetGuestProfilePath()) {
364 profile_path
= g_browser_process
->profile_manager()->GetProfileInfoCache().
365 GetPathOfProfileAtIndex(0);
367 profile
= g_browser_process
->profile_manager()->GetProfile(
370 // If we're using the --new-profile-management flag and this profile is
371 // signed out, then we should show the user manager instead. By switching
372 // the active profile to the guest profile we ensure that no
373 // browser windows will be opened for the guest profile.
374 if (switches::IsNewProfileManagement() &&
376 !profile
->IsGuestSession()) {
377 ProfileInfoCache
& cache
=
378 g_browser_process
->profile_manager()->GetProfileInfoCache();
379 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
381 if (profile_index
!= std::string::npos
&&
382 cache
.ProfileIsSigninRequiredAtIndex(profile_index
)) {
383 profile
= g_browser_process
->profile_manager()->GetProfile(
384 ProfileManager::GetGuestProfilePath());
387 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
389 UMA_HISTOGRAM_LONG_TIMES(
390 "Startup.CreateFirstProfile", base::Time::Now() - start
);
395 // TODO(port): fix this. See comments near the definition of
396 // user_data_dir. It is better to CHECK-fail here than it is to
397 // silently exit because of missing code in the above test.
398 CHECK(profile
) << "Cannot get default profile.";
399 #endif // !defined(OS_WIN)
404 #if defined(OS_MACOSX)
405 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
406 SecKeychainCallbackInfo
* info
, void* context
) {
409 #endif // defined(OS_MACOSX)
411 void RegisterComponentsForUpdate() {
412 component_updater::ComponentUpdateService
* cus
=
413 g_browser_process
->component_updater();
415 // Registration can be before or after cus->Start() so it is ok to post
416 // a task to the UI thread to do registration once you done the necessary
417 // file IO to know you existing component version.
418 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
419 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
420 RegisterPepperFlashComponent(cus
);
421 RegisterSwiftShaderComponent(cus
);
422 RegisterWidevineCdmComponent(cus
);
423 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
425 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
426 #if defined(OS_CHROMEOS)
427 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
428 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
429 // installer when running on Linux. See crbug.com/422121 for more details.
430 if (!base::SysInfo::IsRunningOnChromeOS())
431 #endif // defined(OS_CHROMEOS)
432 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
433 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
435 // Registration of the CLD Component is a no-op unless the CLD data source has
436 // been configured to be the "Component" data source.
437 RegisterCldComponent(cus
);
439 component_updater::SupervisedUserWhitelistInstaller
* whitelist_installer
=
440 g_browser_process
->supervised_user_whitelist_installer();
441 whitelist_installer
->RegisterComponents();
444 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
445 #if defined(OS_ANDROID)
446 // The CRLSet component was enabled for some releases. This code attempts to
447 // delete it from the local disk of those how may have downloaded it.
448 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
449 #elif !defined(OS_CHROMEOS)
450 // CRLSetFetcher attempts to load a CRL set from either the local disk or
452 // For Chrome OS this registration is delayed until user login.
453 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
454 // Registration of the EV Whitelist component here is not necessary for:
455 // 1. Android: Because it currently does not have the EV indicator.
456 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
457 RegisterEVWhitelistComponent(cus
, path
);
458 #endif // defined(OS_ANDROID)
462 RegisterSwReporterComponent(cus
, g_browser_process
->local_state());
463 RegisterCAPSComponent(cus
);
464 #endif // defined(OS_WIN)
469 #if !defined(OS_ANDROID)
470 bool ProcessSingletonNotificationCallback(
471 const base::CommandLine
& command_line
,
472 const base::FilePath
& current_directory
) {
473 // Drop the request if the browser process is already in shutdown path.
474 if (!g_browser_process
|| g_browser_process
->IsShuttingDown()) {
476 browser_watcher::ExitFunnel::RecordSingleEvent(
477 chrome::kBrowserExitCodesRegistryPath
,
478 L
"ProcessSingletonIsShuttingDown");
479 #endif // defined(OS_WIN)
484 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
485 std::string start_time_string
=
486 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
487 int64 remote_start_time
;
488 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
489 base::TimeDelta elapsed
=
490 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
491 if (command_line
.HasSwitch(switches::kFastStart
)) {
492 UMA_HISTOGRAM_LONG_TIMES(
493 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
495 UMA_HISTOGRAM_LONG_TIMES(
496 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
501 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
504 base::FilePath user_data_dir
=
505 g_browser_process
->profile_manager()->user_data_dir();
506 base::FilePath startup_profile_dir
=
507 GetStartupProfilePath(user_data_dir
, command_line
);
509 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
510 command_line
, current_directory
, startup_profile_dir
);
513 #endif // !defined(OS_ANDROID)
515 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine
& command_line
) {
516 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
517 std::string port_str
=
518 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
520 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
521 g_browser_process
->CreateDevToolsHttpProtocolHandler(
522 chrome::HOST_DESKTOP_TYPE_NATIVE
,
524 static_cast<uint16
>(port
));
526 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
531 // Heap allocated class that listens for first page load, kicks off stat
532 // recording and then deletes itself.
533 class LoadCompleteListener
: public content::NotificationObserver
{
535 LoadCompleteListener() {
537 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
538 content::NotificationService::AllSources());
540 ~LoadCompleteListener() override
{}
542 // content::NotificationObserver implementation.
543 void Observe(int type
,
544 const content::NotificationSource
& source
,
545 const content::NotificationDetails
& details
) override
{
546 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
, type
);
547 startup_metric_utils::OnInitialPageLoadComplete();
552 content::NotificationRegistrar registrar_
;
553 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener
);
558 namespace chrome_browser
{
560 // This error message is not localized because we failed to load the
561 // localization data files.
563 const char kMissingLocaleDataTitle
[] = "Missing File Error";
564 #endif // defined(OS_WIN)
567 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
568 const char kMissingLocaleDataMessage
[] =
569 "Unable to find locale data files. Please reinstall.";
570 #endif // defined(OS_WIN)
572 } // namespace chrome_browser
574 // BrowserMainParts ------------------------------------------------------------
576 ChromeBrowserMainParts::ChromeBrowserMainParts(
577 const content::MainFunctionParams
& parameters
)
578 : parameters_(parameters
),
579 parsed_command_line_(parameters
.command_line
),
580 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
581 startup_watcher_(new StartupTimeBomb()),
582 shutdown_watcher_(new ShutdownWatcherHelper()),
583 browser_field_trials_(parameters
.command_line
),
585 run_message_loop_(true),
586 notify_result_(ProcessSingleton::PROCESS_NONE
),
588 restart_last_session_(false) {
589 // If we're running tests (ui_task is non-null).
590 if (parameters
.ui_task
)
591 browser_defaults::enable_help_app
= false;
593 // Chrome disallows cookies by default. All code paths that want to use
594 // cookies need to go through one of Chrome's URLRequestContexts which have
595 // a ChromeNetworkDelegate attached that selectively allows cookies again.
596 net::URLRequest::SetDefaultCookiePolicyToBlock();
599 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
600 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
601 delete chrome_extra_parts_
[i
];
602 chrome_extra_parts_
.clear();
605 // This will be called after the command-line has been mutated by about:flags
606 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
607 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
608 // Must initialize metrics after labs have been converted into switches,
609 // but before field trials are set up (so that client ID is available for
610 // one-time randomized field trials).
612 // Initialize FieldTrialList to support FieldTrials that use one-time
614 metrics::MetricsService
* metrics
= browser_process_
->metrics_service();
615 field_trial_list_
.reset(
616 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
618 const base::CommandLine
* command_line
=
619 base::CommandLine::ForCurrentProcess();
620 if (command_line
->HasSwitch(switches::kEnableBenchmarking
) ||
621 command_line
->HasSwitch(cc::switches::kEnableGpuBenchmarking
)) {
622 base::FieldTrial::EnableBenchmarking();
625 // Ensure any field trials specified on the command line are initialized.
626 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
627 std::set
<std::string
> unforceable_field_trials
;
628 #if defined(OFFICIAL_BUILD)
629 unforceable_field_trials
.insert("SettingsEnforcement");
630 #endif // defined(OFFICIAL_BUILD)
632 // Create field trials without activating them, so that this behaves in a
633 // consistent manner with field trials created from the server.
634 bool result
= base::FieldTrialList::CreateTrialsFromString(
635 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
636 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
637 unforceable_field_trials
);
638 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
639 << " list specified.";
641 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
642 // Create default variation ids which will always be included in the
643 // X-Client-Data request header.
644 variations::VariationsHttpHeaderProvider
* provider
=
645 variations::VariationsHttpHeaderProvider::GetInstance();
646 bool result
= provider
->SetDefaultVariationIds(
647 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
648 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
649 << " list specified.";
650 metrics
->AddSyntheticTrialObserver(provider
);
652 chrome_variations::VariationsService
* variations_service
=
653 browser_process_
->variations_service();
654 if (variations_service
)
655 variations_service
->CreateTrialsFromSeed();
657 // This must be called after |local_state_| is initialized.
658 browser_field_trials_
.SetupFieldTrials();
660 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
661 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
662 // Even though base::Bind does AddRef and Release, the object will not be
663 // deleted after the Task is executed.
664 field_trial_synchronizer_
= new FieldTrialSynchronizer();
666 // Now that field trials have been created, initializes metrics recording.
667 metrics
->InitializeMetricsRecordingState();
669 // Enable profiler instrumentation depending on the channel.
670 switch (chrome::VersionInfo::GetChannel()) {
671 case chrome::VersionInfo::CHANNEL_UNKNOWN
:
672 case chrome::VersionInfo::CHANNEL_CANARY
:
673 tracked_objects::ScopedTracker::Enable();
676 case chrome::VersionInfo::CHANNEL_DEV
:
677 case chrome::VersionInfo::CHANNEL_BETA
:
678 case chrome::VersionInfo::CHANNEL_STABLE
:
679 // Don't enable instrumentation.
684 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
686 void ChromeBrowserMainParts::StartMetricsRecording() {
687 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
689 g_browser_process
->metrics_service()->CheckForClonedInstall(
690 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
692 g_browser_process
->GetMetricsServicesManager()->UpdateUploadPermissions(true);
695 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
696 // Don't record any metrics if UI was displayed before this point e.g.
698 if (startup_metric_utils::WasNonBrowserUIDisplayed())
701 #if defined(OS_ANDROID)
702 // On Android the first run is handled in Java code, and the C++ side of
703 // Chrome doesn't know if this is the first run. This will cause some
704 // inaccuracy in the UMA statistics, but this should be minor (first runs are
706 bool is_first_run
= false;
708 bool is_first_run
= first_run::IsChromeFirstRun();
709 #endif // defined(OS_ANDROID)
711 // CurrentProcessInfo::CreationTime() is currently only implemented on some
713 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
714 const base::Time process_creation_time
=
715 base::CurrentProcessInfo::CreationTime();
717 if (!is_first_run
&& !process_creation_time
.is_null()) {
718 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
719 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
721 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
723 // Record collected startup metrics.
724 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
727 new LoadCompleteListener();
730 // -----------------------------------------------------------------------------
731 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
734 #define DLLEXPORT __declspec(dllexport)
736 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
738 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
741 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
742 // Need an instance of AtExitManager to handle singleton creations and
743 // deletions. We need this new instance because, the old instance created
744 // in ChromeMain() got destructed when the function returned.
745 base::AtExitManager exit_manager
;
746 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
750 // content::BrowserMainParts implementation ------------------------------------
752 void ChromeBrowserMainParts::PreEarlyInitialization() {
753 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
754 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
755 chrome_extra_parts_
[i
]->PreEarlyInitialization();
758 void ChromeBrowserMainParts::PostEarlyInitialization() {
759 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
760 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
761 chrome_extra_parts_
[i
]->PostEarlyInitialization();
764 void ChromeBrowserMainParts::ToolkitInitialized() {
765 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
766 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
767 chrome_extra_parts_
[i
]->ToolkitInitialized();
770 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
771 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
773 device_event_log::Initialize(0 /* default max entries */);
775 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
776 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
779 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
780 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
781 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
782 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
785 int ChromeBrowserMainParts::PreCreateThreads() {
786 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
787 result_code_
= PreCreateThreadsImpl();
789 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
790 #if !defined(OS_ANDROID)
791 // These members must be initialized before exiting this function normally.
792 DCHECK(master_prefs_
.get());
793 DCHECK(browser_creator_
.get());
794 #endif // !defined(OS_ANDROID)
795 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
796 chrome_extra_parts_
[i
]->PreCreateThreads();
802 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
803 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
804 run_message_loop_
= false;
805 #if !defined(OS_ANDROID)
806 chrome::MaybeShowInvalidUserDataDirWarningDialog();
807 #endif // !defined(OS_ANDROID)
808 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
809 return chrome::RESULT_CODE_MISSING_DATA
;
811 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
812 MediaCaptureDevicesDispatcher::GetInstance();
814 // Android's first run is done in Java instead of native.
815 #if !defined(OS_ANDROID)
816 process_singleton_
.reset(new ChromeProcessSingleton(
817 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
819 // Cache first run state early.
820 first_run::IsChromeFirstRun();
821 #endif // !defined(OS_ANDROID)
823 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
824 JsonPrefStore::GetTaskRunnerForFile(
825 base::FilePath(chrome::kLocalStorePoolName
),
826 BrowserThread::GetBlockingPool());
829 TRACE_EVENT0("startup",
830 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
831 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
832 parsed_command_line()));
835 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
836 TRACE_EVENT0("startup",
837 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
838 // User wants to override default tracking status.
840 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
841 // Default to basic profiling (no parent child support).
842 tracked_objects::ThreadData::Status status
=
843 tracked_objects::ThreadData::PROFILING_ACTIVE
;
844 if (flag
.compare("0") != 0)
845 status
= tracked_objects::ThreadData::DEACTIVATED
;
846 else if (flag
.compare("child") != 0)
847 status
= tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE
;
848 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
851 local_state_
= InitializeLocalState(
852 local_state_task_runner
.get(), parsed_command_line());
854 #if !defined(OS_ANDROID)
855 // These members must be initialized before returning from this function.
856 master_prefs_
.reset(new first_run::MasterPrefs
);
857 // Android doesn't use StartupBrowserCreator.
858 browser_creator_
.reset(new StartupBrowserCreator
);
859 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
860 chrome::UMABrowsingActivityObserver::Init();
861 #endif // !defined(OS_ANDROID)
863 #if !defined(OS_CHROMEOS)
864 // Convert active labs into switches. This needs to be done before
865 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
866 // affected by experiment flags (--touch-optimized-ui in particular).
867 // On ChromeOS system level flags are applied from the device settings from
868 // the session manager.
870 TRACE_EVENT0("startup",
871 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
872 about_flags::PrefServiceFlagsStorage
flags_storage_(
873 g_browser_process
->local_state());
874 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
875 base::CommandLine::ForCurrentProcess(),
876 about_flags::kAddSentinels
);
878 #endif // !defined(OS_CHROMEOS)
880 local_state_
->UpdateCommandLinePrefStore(
881 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
883 // Reset the command line in the crash report details, since we may have
884 // just changed it to include experiments.
885 crash_keys::SetSwitchesFromCommandLine(
886 base::CommandLine::ForCurrentProcess());
888 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
889 // needed when loading the MainMenu.nib and the language doesn't depend on
890 // anything since it comes from Cocoa.
891 #if defined(OS_MACOSX)
893 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
894 browser_process_
->SetApplicationLocale(locale
);
896 const std::string locale
=
897 local_state_
->GetString(prefs::kApplicationLocale
);
899 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
900 // method InitSharedInstance is ignored.
902 TRACE_EVENT_BEGIN0("startup",
903 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
904 const std::string loaded_locale
=
905 ui::ResourceBundle::InitSharedInstanceWithLocale(
906 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
907 TRACE_EVENT_END0("startup",
908 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
910 if (loaded_locale
.empty() &&
911 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
912 ShowMissingLocaleMessageBox();
913 return chrome::RESULT_CODE_MISSING_DATA
;
915 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
916 browser_process_
->SetApplicationLocale(loaded_locale
);
918 base::FilePath resources_pack_path
;
919 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
921 TRACE_EVENT0("startup",
922 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
923 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
924 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
926 #endif // defined(OS_MACOSX)
928 // Android does first run in Java instead of native.
929 // Chrome OS has its own out-of-box-experience code.
930 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
931 // On first run, we need to process the predictor preferences before the
932 // browser's profile_manager object is created, but after ResourceBundle
934 if (first_run::IsChromeFirstRun()) {
935 first_run::ProcessMasterPreferencesResult pmp_result
=
936 first_run::ProcessMasterPreferences(user_data_dir_
,
937 master_prefs_
.get());
938 if (pmp_result
== first_run::EULA_EXIT_NOW
)
939 return chrome::RESULT_CODE_EULA_REFUSED
;
941 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
942 !parsed_command_line().HasSwitch(switches::kAppId
) &&
943 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
944 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
947 // TODO(macourteau): refactor preferences that are copied from
948 // master_preferences into local_state, as a "local_state" section in
949 // master preferences. If possible, a generic solution would be preferred
950 // over a copy one-by-one of specific preferences. Also see related TODO
953 // Store the initial VariationsService seed in local state, if it exists
955 if (!master_prefs_
->variations_seed
.empty() ||
956 !master_prefs_
->compressed_variations_seed
.empty()) {
957 if (!master_prefs_
->variations_seed
.empty()) {
958 local_state_
->SetString(prefs::kVariationsSeed
,
959 master_prefs_
->variations_seed
);
961 if (!master_prefs_
->compressed_variations_seed
.empty()) {
962 local_state_
->SetString(prefs::kVariationsCompressedSeed
,
963 master_prefs_
->compressed_variations_seed
);
965 if (!master_prefs_
->variations_seed_signature
.empty()) {
966 local_state_
->SetString(prefs::kVariationsSeedSignature
,
967 master_prefs_
->variations_seed_signature
);
969 // Set the variation seed date to the current system time. If the user's
970 // clock is incorrect, this may cause some field trial expiry checks to
971 // not do the right thing until the next seed update from the server,
972 // when this value will be updated.
973 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
974 base::Time::Now().ToInternalValue());
977 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
978 local_state_
->SetString(
979 prefs::kBrowserSuppressDefaultBrowserPrompt
,
980 master_prefs_
->suppress_default_browser_prompt_for_version
);
983 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
985 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
986 // Set the product channel for crash reports.
987 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
988 chrome::VersionInfo::GetVersionStringModifier());
989 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
991 // Initialize tracking synchronizer system.
992 tracking_synchronizer_
=
993 new metrics::TrackingSynchronizer(base::TimeTicks::Now());
995 #if defined(OS_MACOSX)
996 // Get the Keychain API to register for distributed notifications on the main
997 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
998 // which doesn't. This ensures those notifications will get delivered
999 // properly. See issue 37766.
1000 // (Note that the callback mask here is empty. I don't want to register for
1001 // any callbacks, I just want to initialize the mechanism.)
1002 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
1003 #endif // defined(OS_MACOSX)
1005 #if defined(OS_CHROMEOS)
1006 // Must be done after g_browser_process is constructed, before
1007 // SetupMetricsAndFieldTrials().
1008 chromeos::CrosSettings::Initialize();
1009 #endif // defined(OS_CHROMEOS)
1011 // Now the command line has been mutated based on about:flags, we can setup
1012 // metrics and initialize field trials. The field trials are needed by
1013 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1014 SetupMetricsAndFieldTrials();
1016 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1017 browser_process_
->PreCreateThreads();
1019 return content::RESULT_CODE_NORMAL_EXIT
;
1022 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1023 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1024 result_code_
= PreMainMessageLoopRunImpl();
1026 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1027 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
1030 // PreMainMessageLoopRun calls these extra stages in the following order:
1031 // PreMainMessageLoopRunImpl()
1032 // ... initial setup, including browser_process_ setup.
1034 // ... additional setup, including CreateProfile()
1035 // PostProfileInit()
1036 // ... additional setup
1037 // PreBrowserStart()
1038 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1039 // PostBrowserStart()
1041 void ChromeBrowserMainParts::PreProfileInit() {
1042 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1044 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1045 chrome_extra_parts_
[i
]->PreProfileInit();
1047 #if !defined(OS_ANDROID)
1048 // Initialize the feedback uploader so it can setup notifications for profile
1050 feedback::FeedbackProfileObserver::Initialize();
1052 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
1054 // First check if any ephemeral profiles are left behind because of browser
1055 // crash and schedule them for deletion and then proceed with getting the set
1056 // of profiles to open.
1057 ProfileInfoCache
& profile_cache
= profile_manager
->GetProfileInfoCache();
1058 size_t profiles_count
= profile_cache
.GetNumberOfProfiles();
1059 std::vector
<base::FilePath
> profiles_to_delete
;
1060 for (size_t i
= 0; i
< profiles_count
; ++i
) {
1061 if (profile_cache
.ProfileIsEphemeralAtIndex(i
))
1062 profiles_to_delete
.push_back(profile_cache
.GetPathOfProfileAtIndex(i
));
1065 if (profiles_to_delete
.size()) {
1066 for (size_t i
= 0; i
< profiles_to_delete
.size(); ++i
) {
1067 profile_manager
->ScheduleProfileForDeletion(
1068 profiles_to_delete
[i
], ProfileManager::CreateCallback());
1070 // Clean up stale profiles immediately after browser start.
1071 BrowserThread::PostTask(
1072 BrowserThread::FILE, FROM_HERE
,
1073 base::Bind(&ProfileManager::CleanUpStaleProfiles
, profiles_to_delete
));
1075 #endif // !defined(OS_ANDROID)
1077 #if defined(ENABLE_EXTENSIONS)
1078 javascript_dialog_extensions_client::InstallClient();
1079 #endif // defined(ENABLE_EXTENSIONS)
1081 #if !defined(OS_IOS)
1082 InstallChromeJavaScriptNativeDialogFactory();
1083 #endif // !defined(OS_IOS)
1086 void ChromeBrowserMainParts::PostProfileInit() {
1087 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1088 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1089 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1090 chrome_extra_parts_
[i
]->PostProfileInit();
1093 void ChromeBrowserMainParts::PreBrowserStart() {
1094 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1095 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1096 chrome_extra_parts_
[i
]->PreBrowserStart();
1098 three_d_observer_
.reset(new ThreeDAPIObserver());
1101 void ChromeBrowserMainParts::PostBrowserStart() {
1102 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1103 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1104 chrome_extra_parts_
[i
]->PostBrowserStart();
1105 #if !defined(OS_ANDROID)
1106 // Allow ProcessSingleton to process messages.
1107 process_singleton_
->Unlock();
1108 #endif // !defined(OS_ANDROID)
1109 #if defined(ENABLE_WEBRTC)
1110 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1111 // to reduce the impact on startup time.
1112 BrowserThread::PostDelayedTask(
1115 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1116 base::TimeDelta::FromMinutes(1));
1117 #endif // defined(ENABLE_WEBRTC)
1119 // At this point, StartupBrowserCreator::Start has run creating initial
1120 // browser windows and tabs, but no progress has been made in loading
1121 // content as the main message loop hasn't started processing tasks yet.
1122 // We setup to observe to the initial page load here to defer running
1123 // task posted via PostAfterStartupTask until its complete.
1124 AfterStartupTaskUtils::StartMonitoringStartup();
1127 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1128 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1129 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1130 const base::TimeTicks start_time_step1
= base::TimeTicks::Now();
1132 #if defined(ENABLE_EXTENSIONS)
1133 if (!variations::GetVariationParamValue(
1134 "LightSpeed", "EarlyInitStartup").empty()) {
1135 // Try to compute this early on another thread so that we don't spend time
1136 // during profile load initializing the extensions APIs.
1137 BrowserThread::PostTask(
1138 BrowserThread::FILE_USER_BLOCKING
,
1141 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures
)));
1145 // Android updates the metrics service dynamically depending on whether the
1146 // application is in the foreground or not. Do not start here.
1147 #if !defined(OS_ANDROID)
1148 // Now that the file thread has been started, start recording.
1149 StartMetricsRecording();
1150 #endif // !defined(OS_ANDROID)
1152 if (!base::debug::BeingDebugged()) {
1153 // Create watchdog thread after creating all other threads because it will
1154 // watch the other threads and they must be running.
1155 browser_process_
->watchdog_thread();
1158 // Do any initializating in the browser process that requires all threads
1160 browser_process_
->PreMainMessageLoopRun();
1162 // Record last shutdown time into a histogram.
1163 browser_shutdown::ReadLastShutdownInfo();
1166 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1167 // tasks. Those care whether the browser is already running. On Linux/Mac,
1168 // upgrade/uninstall happen separately.
1169 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1171 // If the command line specifies 'uninstall' then we need to work here
1172 // unless we detect another chrome browser running.
1173 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1174 return DoUninstallTasks(already_running
);
1177 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1178 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1179 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1180 parsed_command_line_
);
1183 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1184 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1185 #endif // defined(OS_WIN)
1187 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1188 bool is_managed
= g_browser_process
->local_state()->IsManagedPreference(
1189 prefs::kDefaultBrowserSettingEnabled
);
1190 if (is_managed
&& !g_browser_process
->local_state()->GetBoolean(
1191 prefs::kDefaultBrowserSettingEnabled
)) {
1192 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY
);
1195 return ShellIntegration::SetAsDefaultBrowser() ?
1196 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1197 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1200 #if defined(USE_AURA)
1201 // Make sure aura::Env has been initialized.
1202 CHECK(aura::Env::GetInstance());
1203 #endif // defined(USE_AURA)
1205 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1206 #if !defined(OS_ANDROID)
1207 // If the command line specifies --pack-extension, attempt the pack extension
1208 // startup action and exit.
1209 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1210 extensions::StartupHelper extension_startup_helper
;
1211 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1212 return content::RESULT_CODE_NORMAL_EXIT
;
1213 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1216 // When another process is running, use that process instead of starting a
1217 // new one. NotifyOtherProcess will currently give the other process up to
1218 // 20 seconds to respond. Note that this needs to be done before we attempt
1219 // to read the profile.
1220 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1221 switch (notify_result_
) {
1222 case ProcessSingleton::PROCESS_NONE
:
1223 // No process already running, fall through to starting a new one.
1226 case ProcessSingleton::PROCESS_NOTIFIED
:
1227 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1228 // On POSIX systems, print a message notifying the process is running.
1229 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1230 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1231 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1233 // Having a differentiated return type for testing allows for tests to
1234 // verify proper handling of some switches. When not testing, stick to
1235 // the standard Unix convention of returning zero when things went as
1237 if (parsed_command_line().HasSwitch(switches::kTestType
))
1238 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1239 return content::RESULT_CODE_NORMAL_EXIT
;
1241 case ProcessSingleton::PROFILE_IN_USE
:
1242 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1244 case ProcessSingleton::LOCK_ERROR
:
1245 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1246 "directory. This means that running multiple instances "
1247 "would start multiple browser processes rather than "
1248 "opening a new window in the existing process. Aborting "
1249 "now to avoid profile corruption.";
1250 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1255 #endif // !defined(OS_ANDROID)
1257 // Handle special early return paths (which couldn't be processed even earlier
1258 // as they require the process singleton to be held) first.
1260 std::string try_chrome
=
1261 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1262 if (!try_chrome
.empty()) {
1264 // Setup.exe has determined that we need to run a retention experiment
1265 // and has lauched chrome to show the experiment UI. It is guaranteed that
1266 // no other Chrome is currently running as the process singleton was
1267 // sucessfully grabbed above.
1269 base::StringToInt(try_chrome
, &try_chrome_int
);
1270 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1272 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1273 base::Unretained(process_singleton_
.get())));
1274 if (answer
== TryChromeDialogView::NOT_NOW
)
1275 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1276 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1277 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1278 // At this point the user is willing to try chrome again.
1279 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1280 // Only set in the unattended case, the interactive case is Windows 8.
1281 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1282 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1283 ShellIntegration::SetAsDefaultBrowser();
1286 // We don't support retention experiments on Mac or Linux.
1287 return content::RESULT_CODE_NORMAL_EXIT
;
1288 #endif // defined(OS_WIN)
1292 // Do the tasks if chrome has been upgraded while it was last running.
1293 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1294 return content::RESULT_CODE_NORMAL_EXIT
;
1296 // Check if there is any machine level Chrome installed on the current
1297 // machine. If yes and the current Chrome process is user level, we do not
1298 // allow the user level Chrome to run. So we notify the user and uninstall
1299 // user level Chrome.
1300 // Note this check needs to happen here (after the process singleton was
1301 // obtained but before potentially creating the first run sentinel).
1302 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1303 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1304 #endif // defined(OS_WIN)
1306 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1307 if (sxs_linux::ShouldMigrateUserDataDir())
1308 return sxs_linux::MigrateUserDataDir();
1309 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1311 // Desktop construction occurs here, (required before profile creation).
1314 // Profile creation ----------------------------------------------------------
1316 metrics::MetricsService::SetExecutionPhase(
1317 metrics::MetricsService::CREATE_PROFILE
,
1318 g_browser_process
->local_state());
1320 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1321 base::TimeTicks::Now() - start_time_step1
);
1323 // This step is costly and is already measured in Startup.CreateFirstProfile
1324 // and more directly Profile.CreateAndInitializeProfile.
1325 profile_
= CreatePrimaryProfile(parameters(),
1327 parsed_command_line());
1329 return content::RESULT_CODE_NORMAL_EXIT
;
1331 #if !defined(OS_ANDROID)
1332 const base::TimeTicks start_time_step2
= base::TimeTicks::Now();
1333 // The first run sentinel must be created after the process singleton was
1334 // grabbed and no early return paths were otherwise hit above.
1335 first_run::CreateSentinelIfNeeded();
1336 #endif // !defined(OS_ANDROID)
1338 #if defined(ENABLE_BACKGROUND)
1339 // Autoload any profiles which are running background apps.
1340 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1341 browser_process_
->profile_manager()->AutoloadProfiles();
1342 #endif // defined(ENABLE_BACKGROUND)
1343 // Post-profile init ---------------------------------------------------------
1345 TranslateService::Initialize();
1347 // Needs to be done before PostProfileInit, since login manager on CrOS is
1348 // called inside PostProfileInit.
1349 content::WebUIControllerFactory::RegisterFactory(
1350 ChromeWebUIControllerFactory::GetInstance());
1352 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1353 // So make sure to create it before that.
1354 #if !defined(DISABLE_NACL)
1355 NaClBrowserDelegateImpl
* delegate
=
1356 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1357 nacl::NaClBrowser::SetDelegate(delegate
);
1358 #endif // !defined(DISABLE_NACL)
1360 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1361 // (requires supporting early exit).
1364 // Retrieve cached GL strings from local state and use them for GPU
1365 // blacklist decisions.
1366 if (g_browser_process
->gl_string_manager())
1367 g_browser_process
->gl_string_manager()->Initialize();
1369 // Create an instance of GpuModeManager to watch gpu mode pref change.
1370 g_browser_process
->gpu_mode_manager();
1372 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1373 // Show the First Run UI if this is the first time Chrome has been run on
1374 // this computer, or we're being compelled to do so by a command line flag.
1375 // Note that this be done _after_ the PrefService is initialized and all
1376 // preferences are registered, since some of the code that the importer
1377 // touches reads preferences.
1378 if (first_run::IsChromeFirstRun()) {
1379 first_run::AutoImport(profile_
,
1380 master_prefs_
->homepage_defined
,
1381 master_prefs_
->do_import_items
,
1382 master_prefs_
->dont_import_items
,
1383 master_prefs_
->import_bookmarks_path
);
1385 // Note: this can pop the first run consent dialog on linux.
1386 first_run::DoPostImportTasks(profile_
,
1387 master_prefs_
->make_chrome_default_for_user
);
1389 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1390 browser_creator_
->set_show_main_browser_window(
1391 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1393 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1396 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1399 // Sets things up so that if we crash from this point on, a dialog will
1400 // popup asking the user to restart chrome. It is done this late to avoid
1401 // testing against a bunch of special cases that are taken care early on.
1402 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1403 parsed_command_line());
1405 // Registers Chrome with the Windows Restart Manager, which will restore the
1406 // Chrome session when the computer is restarted after a system update.
1407 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1408 // but should run on startup if extended to handle crashes/hangs/patches.
1409 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1410 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1411 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1412 parsed_command_line());
1415 // Verify that the profile is not on a network share and if so prepare to show
1416 // notification to the user.
1417 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1418 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1419 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1420 profile_
->GetPath()));
1422 #endif // defined(OS_WIN)
1424 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1425 // Init the RLZ library. This just binds the dll and schedules a task on the
1426 // file thread to be run sometime later. If this is the first run we record
1427 // the installation event.
1428 PrefService
* pref_service
= profile_
->GetPrefs();
1429 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1430 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1431 // Negative ping delay means to send ping immediately after a first search is
1433 RLZTracker::InitRlzFromProfileDelayed(
1434 profile_
, first_run::IsChromeFirstRun(), ping_delay
< 0,
1435 base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
1436 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1438 // Configure modules that need access to resources.
1439 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1441 // In unittest mode, this will do nothing. In normal mode, this will create
1442 // the global IntranetRedirectDetector instance, which will promptly go to
1443 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1444 // to see if it should do anything else.
1446 // A simpler way of doing all this would be to have some function which could
1447 // give the time elapsed since startup, and simply have this object check that
1448 // when asked to initialize itself, but this doesn't seem to exist.
1450 // This can't be created in the BrowserProcessImpl constructor because it
1451 // needs to read prefs that get set after that runs.
1452 browser_process_
->intranet_redirect_detector();
1453 GoogleSearchCounter::RegisterForNotifications();
1455 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1456 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1457 base::FilePath path
=
1458 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1459 printing::PrintedDocument::set_debug_dump_path(path
);
1461 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1463 HandleTestParameters(parsed_command_line());
1464 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1465 base::debug::BeingDebugged());
1467 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1468 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1469 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1470 browser_process_
->GetApplicationLocale());
1472 // Start watching for hangs during startup. We disarm this hang detector when
1473 // ThreadWatcher takes over or when browser is shutdown or when
1474 // startup_watcher_ is deleted.
1475 metrics::MetricsService::SetExecutionPhase(
1476 metrics::MetricsService::STARTUP_TIMEBOMB_ARM
,
1477 g_browser_process
->local_state());
1478 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(600));
1480 // On mobile, need for clean shutdown arises only when the application comes
1481 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1482 // http://crbug.com/179143
1483 #if !defined(OS_ANDROID)
1484 // Start watching for a hang.
1485 browser_process_
->metrics_service()->LogNeedForCleanShutdown();
1486 #endif // !defined(OS_ANDROID)
1488 #if defined(ENABLE_PRINT_PREVIEW)
1489 // Create the instance of the cloud print proxy service so that it can launch
1490 // the service process if needed. This is needed because the service process
1491 // might have shutdown because an update was available.
1492 // TODO(torne): this should maybe be done with
1493 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1495 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1496 #endif // defined(ENABLE_PRINT_PREVIEW)
1498 // Start watching all browser threads for responsiveness.
1499 metrics::MetricsService::SetExecutionPhase(
1500 metrics::MetricsService::THREAD_WATCHER_START
,
1501 g_browser_process
->local_state());
1502 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1504 #if defined(OS_ANDROID)
1505 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1506 #endif // defined(OS_ANDROID)
1508 #if !defined(DISABLE_NACL)
1509 BrowserThread::PostTask(
1512 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1513 #endif // !defined(DISABLE_NACL)
1515 // Make sure initial prefs are recorded
1516 PrefMetricsService::Factory::GetForProfile(profile_
);
1520 // Instantiate the notification UI manager, as this triggers a perf timer
1521 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1522 // triggering the timer and call that explicitly in the approprate place.
1523 // http://crbug.com/105065.
1524 browser_process_
->notification_ui_manager();
1526 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1527 // data source is based on the Component Updater.
1528 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1530 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1531 RegisterComponentsForUpdate();
1533 #if defined(OS_ANDROID)
1534 chrome_variations::VariationsService
* variations_service
=
1535 browser_process_
->variations_service();
1536 if (variations_service
) {
1537 // Just initialize the policy prefs service here. Variations seed fetching
1538 // will be initialized when the app enters foreground mode.
1539 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1541 translate::TranslateDownloadManager::RequestLanguageList(
1542 profile_
->GetPrefs());
1545 // Most general initialization is behind us, but opening a
1546 // tab and/or session restore and such is still to be done.
1547 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1549 // We are in regular browser boot sequence. Open initial tabs and enter the
1550 // main message loop.
1551 #if defined(OS_CHROMEOS)
1552 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1553 // them this early as the cryptohome hasn't yet been mounted (which happens
1554 // only once we log in.
1555 std::vector
<Profile
*> last_opened_profiles
;
1557 std::vector
<Profile
*> last_opened_profiles
=
1558 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1559 #endif // defined(OS_CHROMEOS)
1561 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1562 base::TimeTicks::Now() - start_time_step2
);
1564 // This step is costly and is already measured in
1565 // Startup.StartupBrowserCreator_Start.
1566 bool started
= browser_creator_
->Start(
1567 parsed_command_line(), base::FilePath(), profile_
, last_opened_profiles
);
1568 const base::TimeTicks start_time_step3
= base::TimeTicks::Now();
1570 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1571 // Initialize autoupdate timer. Timer callback costs basically nothing
1572 // when browser is not in persistent mode, so it's OK to let it ride on
1573 // the main thread. This needs to be done here because we don't want
1574 // to start the timer when Chrome is run inside a test harness.
1575 browser_process_
->StartAutoupdateTimer();
1576 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1578 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1579 // On Linux, the running exe will be updated if an upgrade becomes
1580 // available while the browser is running. We need to save the last
1581 // modified time of the exe, so we can compare to determine if there is
1582 // an upgrade while the browser is kept alive by a persistent extension.
1583 upgrade_util::SaveLastModifiedTimeOfExe();
1584 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1586 // Record now as the last successful chrome start.
1587 GoogleUpdateSettings::SetLastRunTime();
1589 #if defined(OS_MACOSX)
1590 // Call Recycle() here as late as possible, before going into the loop
1591 // because Start() will add things to it while creating the main window.
1592 if (parameters().autorelease_pool
)
1593 parameters().autorelease_pool
->Recycle();
1594 #endif // defined(OS_MACOSX)
1596 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1597 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1599 // If we're running tests (ui_task is non-null), then we don't want to
1600 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1601 // RequestLanguageList
1602 if (parameters().ui_task
== NULL
) {
1603 // Request new variations seed information from server.
1604 chrome_variations::VariationsService
* variations_service
=
1605 browser_process_
->variations_service();
1606 if (variations_service
) {
1607 variations_service
->StartRepeatedVariationsSeedFetch();
1610 variations_service
->StartGoogleUpdateRegistrySync();
1611 #endif // defined(OS_WIN)
1614 translate::TranslateDownloadManager::RequestLanguageList(
1615 profile_
->GetPrefs());
1618 run_message_loop_
= true;
1620 run_message_loop_
= false;
1622 browser_creator_
.reset();
1624 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1625 if (g_browser_process
->metrics_service()->reporting_active())
1626 content::StartPowerUsageMonitor();
1627 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1629 process_power_collector_
.reset(new ProcessPowerCollector
);
1630 process_power_collector_
->Initialize();
1631 #endif // !defined(OS_ANDROID)
1635 if (parameters().ui_task
) {
1636 parameters().ui_task
->Run();
1637 delete parameters().ui_task
;
1638 run_message_loop_
= false;
1640 #if defined(OS_ANDROID)
1641 // We never run the C++ main loop on Android, since the UI thread message
1642 // loop is controlled by the OS, so this is as close as we can get to
1643 // the start of the main loop.
1644 if (result_code_
<= 0) {
1645 RecordBrowserStartupTime();
1647 #endif // defined(OS_ANDROID)
1649 #if !defined(OS_ANDROID)
1650 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1651 base::TimeTicks::Now() - start_time_step3
);
1652 #endif // !defined(OS_ANDROID)
1654 return result_code_
;
1657 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1658 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1659 #if defined(OS_ANDROID)
1660 // Chrome on Android does not use default MessageLoop. It has its own
1661 // Android specific MessageLoop
1665 // Set the result code set in PreMainMessageLoopRun or set above.
1666 *result_code
= result_code_
;
1667 if (!run_message_loop_
)
1668 return true; // Don't run the default message loop.
1670 // These should be invoked as close to the start of the browser's
1671 // UI thread message loop as possible to get a stable measurement
1673 RecordBrowserStartupTime();
1675 DCHECK(base::MessageLoopForUI::IsCurrent());
1676 base::RunLoop run_loop
;
1678 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1680 metrics::MetricsService::SetExecutionPhase(
1681 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1682 g_browser_process
->local_state());
1686 #endif // defined(OS_ANDROID)
1689 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1690 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1691 #if defined(OS_ANDROID)
1692 // Chrome on Android does not use default MessageLoop. It has its own
1693 // Android specific MessageLoop
1697 // Start watching for jank during shutdown. It gets disarmed when
1698 // |shutdown_watcher_| object is destructed.
1699 metrics::MetricsService::SetExecutionPhase(
1700 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1701 g_browser_process
->local_state());
1702 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1704 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1705 startup_watcher_
->Disarm();
1707 // Remove observers attached to D-Bus clients before DbusThreadManager is
1709 process_power_collector_
.reset();
1711 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1712 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1714 // Some tests don't set parameters.ui_task, so they started translate
1715 // language fetch that was never completed so we need to cleanup here
1716 // otherwise it will be done by the destructor in a wrong thread.
1717 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1719 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1720 process_singleton_
->Cleanup();
1722 // Stop all tasks that might run on WatchDogThread.
1723 ThreadWatcherList::StopWatchingAll();
1725 browser_process_
->metrics_service()->Stop();
1727 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1728 browser_process_
->StartTearDown();
1729 #endif // defined(OS_ANDROID)
1732 void ChromeBrowserMainParts::PostDestroyThreads() {
1733 #if defined(OS_ANDROID)
1734 // On Android, there is no quit/exit. So the browser's main message loop will
1738 browser_process_
->PostDestroyThreads();
1739 // browser_shutdown takes care of deleting browser_process, so we need to
1741 ignore_result(browser_process_
.release());
1742 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1743 master_prefs_
.reset();
1744 process_singleton_
.reset();
1745 device_event_log::Shutdown();
1747 // We need to do this check as late as possible, but due to modularity, this
1748 // may be the last point in Chrome. This would be more effective if done at
1749 // a higher level on the stack, so that it is impossible for an early return
1750 // to bypass this code. Perhaps we need a *final* hook that is called on all
1751 // paths from content/browser/browser_main.
1752 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1754 #if defined(OS_CHROMEOS)
1755 chromeos::CrosSettings::Shutdown();
1756 #endif // defined(OS_CHROMEOS)
1757 #endif // defined(OS_ANDROID)
1762 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1763 chrome_extra_parts_
.push_back(parts
);