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/feature_list.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram_macros.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/profiler/scoped_profile.h"
28 #include "base/profiler/scoped_tracker.h"
29 #include "base/run_loop.h"
30 #include "base/strings/string_number_conversions.h"
31 #include "base/strings/string_piece.h"
32 #include "base/strings/string_split.h"
33 #include "base/strings/sys_string_conversions.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/sys_info.h"
36 #include "base/threading/platform_thread.h"
37 #include "base/time/default_tick_clock.h"
38 #include "base/time/time.h"
39 #include "base/trace_event/trace_event.h"
40 #include "base/values.h"
41 #include "build/build_config.h"
42 #include "cc/base/switches.h"
43 #include "chrome/browser/about_flags.h"
44 #include "chrome/browser/after_startup_task_utils.h"
45 #include "chrome/browser/browser_process.h"
46 #include "chrome/browser/browser_process_impl.h"
47 #include "chrome/browser/browser_process_platform_part.h"
48 #include "chrome/browser/browser_shutdown.h"
49 #include "chrome/browser/chrome_browser_main_extra_parts.h"
50 #include "chrome/browser/component_updater/cld_component_installer.h"
51 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
52 #include "chrome/browser/component_updater/flash_component_installer.h"
53 #include "chrome/browser/component_updater/recovery_component_installer.h"
54 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
55 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
56 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
57 #include "chrome/browser/defaults.h"
58 #include "chrome/browser/first_run/first_run.h"
59 #include "chrome/browser/first_run/upgrade_util.h"
60 #include "chrome/browser/gpu/gl_string_manager.h"
61 #include "chrome/browser/gpu/three_d_api_observer.h"
62 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
63 #include "chrome/browser/memory/oom_priority_manager.h"
64 #include "chrome/browser/metrics/field_trial_synchronizer.h"
65 #include "chrome/browser/metrics/metrics_services_manager.h"
66 #include "chrome/browser/metrics/thread_watcher.h"
67 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
68 #include "chrome/browser/net/chrome_net_log.h"
69 #include "chrome/browser/net/crl_set_fetcher.h"
70 #include "chrome/browser/performance_monitor/performance_monitor.h"
71 #include "chrome/browser/plugins/plugin_prefs.h"
72 #include "chrome/browser/power/process_power_collector.h"
73 #include "chrome/browser/pref_service_flags_storage.h"
74 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
75 #include "chrome/browser/prefs/command_line_pref_store.h"
76 #include "chrome/browser/prefs/incognito_mode_prefs.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/tracing/navigation_tracing.h"
86 #include "chrome/browser/translate/translate_service.h"
87 #include "chrome/browser/ui/app_list/app_list_service.h"
88 #include "chrome/browser/ui/browser.h"
89 #include "chrome/browser/ui/browser_finder.h"
90 #include "chrome/browser/ui/host_desktop.h"
91 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
92 #include "chrome/browser/ui/startup/default_browser_prompt.h"
93 #include "chrome/browser/ui/startup/startup_browser_creator.h"
94 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
95 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
96 #include "chrome/common/channel_info.h"
97 #include "chrome/common/chrome_constants.h"
98 #include "chrome/common/chrome_paths.h"
99 #include "chrome/common/chrome_result_codes.h"
100 #include "chrome/common/chrome_switches.h"
101 #include "chrome/common/crash_keys.h"
102 #include "chrome/common/env_vars.h"
103 #include "chrome/common/logging_chrome.h"
104 #include "chrome/common/net/net_resource_provider.h"
105 #include "chrome/common/pref_names.h"
106 #include "chrome/common/profiling.h"
107 #include "chrome/common/variations/variations_util.h"
108 #include "chrome/grit/generated_resources.h"
109 #include "chrome/installer/util/google_update_settings.h"
110 #include "components/component_updater/component_updater_service.h"
111 #include "components/device_event_log/device_event_log.h"
112 #include "components/google/core/browser/google_util.h"
113 #include "components/language_usage_metrics/language_usage_metrics.h"
114 #include "components/metrics/call_stack_profile_metrics_provider.h"
115 #include "components/metrics/metrics_service.h"
116 #include "components/metrics/profiler/tracking_synchronizer.h"
117 #include "components/nacl/browser/nacl_browser.h"
118 #include "components/rappor/rappor_service.h"
119 #include "components/signin/core/common/profile_management_switches.h"
120 #include "components/startup_metric_utils/startup_metric_utils.h"
121 #include "components/tracing/tracing_switches.h"
122 #include "components/translate/content/browser/browser_cld_utils.h"
123 #include "components/translate/content/common/cld_data_source.h"
124 #include "components/translate/core/browser/translate_download_manager.h"
125 #include "components/variations/net/variations_http_header_provider.h"
126 #include "components/variations/pref_names.h"
127 #include "components/variations/service/variations_service.h"
128 #include "components/variations/variations_associated_data.h"
129 #include "components/variations/variations_switches.h"
130 #include "components/version_info/version_info.h"
131 #include "content/public/browser/browser_thread.h"
132 #include "content/public/browser/notification_observer.h"
133 #include "content/public/browser/notification_registrar.h"
134 #include "content/public/browser/notification_service.h"
135 #include "content/public/browser/notification_types.h"
136 #include "content/public/browser/power_usage_monitor.h"
137 #include "content/public/browser/site_instance.h"
138 #include "content/public/common/content_client.h"
139 #include "content/public/common/content_switches.h"
140 #include "content/public/common/main_function_params.h"
141 #include "grit/platform_locale_settings.h"
142 #include "media/audio/audio_manager.h"
143 #include "net/base/net_module.h"
144 #include "net/cookies/cookie_monster.h"
145 #include "net/http/http_network_layer.h"
146 #include "net/http/http_stream_factory.h"
147 #include "net/url_request/url_request.h"
148 #include "ui/base/l10n/l10n_util.h"
149 #include "ui/base/layout.h"
150 #include "ui/base/resource/resource_bundle.h"
151 #include "ui/strings/grit/app_locale_settings.h"
153 #if defined(OS_ANDROID)
154 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
155 #include "chrome/browser/metrics/thread_watcher_android.h"
156 #include "ui/base/resource/resource_bundle_android.h"
158 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
159 #include "chrome/browser/feedback/feedback_profile_observer.h"
160 #endif // defined(OS_ANDROID)
162 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
163 #include "chrome/browser/first_run/upgrade_util_linux.h"
164 #include "chrome/browser/sxs_linux.h"
165 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
167 #if defined(OS_CHROMEOS)
168 #include "chrome/browser/chromeos/settings/cros_settings.h"
169 #include "chromeos/chromeos_switches.h"
170 #include "chromeos/settings/cros_settings_names.h"
171 #endif // defined(OS_CHROMEOS)
173 // TODO(port): several win-only methods have been pulled out of this, but
174 // BrowserMain() as a whole needs to be broken apart so that it's usable by
175 // other platforms. For now, it's just a stub. This is a serious work in
176 // progress and should not be taken as an indication of a real refactoring.
179 #include "base/environment.h" // For PreRead experiment.
180 #include "base/trace_event/trace_event_etw_export_win.h"
181 #include "base/win/windows_version.h"
182 #include "chrome/browser/browser_util_win.h"
183 #include "chrome/browser/chrome_browser_main_win.h"
184 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
185 #include "chrome/browser/component_updater/caps_installer_win.h"
186 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
187 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
188 #include "chrome/browser/first_run/upgrade_util_win.h"
189 #include "chrome/browser/ui/network_profile_bubble.h"
190 #include "chrome/installer/util/helper.h"
191 #include "chrome/installer/util/install_util.h"
192 #include "chrome/installer/util/shell_util.h"
193 #include "components/browser_watcher/exit_funnel_win.h"
194 #include "net/base/net_util.h"
195 #include "ui/base/l10n/l10n_util_win.h"
196 #include "ui/gfx/win/dpi.h"
197 #include "ui/shell_dialogs/select_file_dialog.h"
198 #endif // defined(OS_WIN)
200 #if defined(OS_MACOSX)
201 #include <Security/Security.h>
203 #include "base/mac/scoped_nsautorelease_pool.h"
204 #include "chrome/browser/mac/keystone_glue.h"
205 #endif // defined(OS_MACOSX)
208 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
209 #endif // !defined(OS_IOS)
211 #if !defined(DISABLE_NACL)
212 #include "chrome/browser/component_updater/pnacl_component_installer.h"
213 #include "components/nacl/browser/nacl_process_host.h"
214 #endif // !defined(DISABLE_NACL)
216 #if defined(ENABLE_EXTENSIONS)
217 #include "chrome/browser/extensions/startup_helper.h"
218 #include "extensions/browser/extension_protocols.h"
219 #include "extensions/common/features/feature_provider.h"
220 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
221 #endif // defined(ENABLE_EXTENSIONS)
223 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
224 #include "printing/printed_document.h"
225 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
227 #if defined(ENABLE_RLZ)
228 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
229 #include "components/rlz/rlz_tracker.h"
230 #endif // defined(ENABLE_RLZ)
232 #if defined(ENABLE_WEBRTC)
233 #include "chrome/browser/media/webrtc_log_util.h"
234 #endif // defined(ENABLE_WEBRTC)
236 #if defined(USE_AURA)
237 #include "ui/aura/env.h"
238 #endif // defined(USE_AURA)
240 #if !defined(OS_ANDROID) && !defined(OS_IOS)
241 #include "chrome/browser/chrome_webusb_browser_client.h"
242 #include "components/webusb/webusb_detector.h"
245 using content::BrowserThread
;
249 // This function provides some ways to test crash and assertion handling
250 // behavior of the program.
251 void HandleTestParameters(const base::CommandLine
& command_line
) {
252 // This parameter causes a null pointer crash (crash reporter trigger).
253 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
254 int* bad_pointer
= NULL
;
259 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
260 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
261 const std::vector
<GURL
>& new_tabs
) {
262 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
263 it
!= new_tabs
.end(); ++it
) {
265 browser_creator
->AddFirstRunTab(*it
);
268 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
270 // Returns the new local state object, guaranteed non-NULL.
271 // |local_state_task_runner| must be a shutdown-blocking task runner.
272 PrefService
* InitializeLocalState(
273 base::SequencedTaskRunner
* local_state_task_runner
,
274 const base::CommandLine
& parsed_command_line
) {
275 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
277 // Load local state. This includes the application locale so we know which
278 // locale dll to load. This also causes local state prefs to be registered.
279 PrefService
* local_state
= g_browser_process
->local_state();
283 if (first_run::IsChromeFirstRun()) {
284 // During first run we read the google_update registry key to find what
285 // language the user selected when downloading the installer. This
286 // becomes our default language in the prefs.
287 // Other platforms obey the system locale.
288 base::string16 install_lang
;
289 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
290 local_state
->SetString(prefs::kApplicationLocale
,
291 base::UTF16ToASCII(install_lang
));
294 #endif // defined(OS_WIN)
296 // If the local state file for the current profile doesn't exist and the
297 // parent profile command line flag is present, then we should inherit some
298 // local state from the parent profile.
299 // Checking that the local state file for the current profile doesn't exist
300 // is the most robust way to determine whether we need to inherit or not
301 // since the parent profile command line flag can be present even when the
302 // current profile is not a new one, and in that case we do not want to
303 // inherit and reset the user's setting.
305 // TODO(mnissler): We should probably just instantiate a
306 // JSONPrefStore here instead of an entire PrefService. Once this is
307 // addressed, the call to browser_prefs::RegisterLocalState can move
308 // to chrome_prefs::CreateLocalState.
309 if (parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
310 base::FilePath local_state_path
;
311 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
312 bool local_state_file_exists
= base::PathExists(local_state_path
);
313 if (!local_state_file_exists
) {
314 base::FilePath parent_profile
=
315 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
316 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
317 scoped_ptr
<PrefService
> parent_local_state(
318 chrome_prefs::CreateLocalState(
320 local_state_task_runner
,
321 g_browser_process
->policy_service(),
324 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
325 // Right now, we only inherit the locale setting from the parent profile.
326 local_state
->SetString(
327 prefs::kApplicationLocale
,
328 parent_local_state
->GetString(prefs::kApplicationLocale
));
332 #if defined(OS_CHROMEOS)
333 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
334 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
335 // Ensure that we start with owner's locale.
336 if (!owner_locale
.empty() &&
337 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
338 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
339 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
342 #endif // defined(OS_CHROMEOS)
347 // Initializes the primary profile, possibly doing some user prompting to pick
348 // a fallback profile. Returns the newly created profile, or NULL if startup
349 // should not continue.
350 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
351 const base::FilePath
& user_data_dir
,
352 const base::CommandLine
& parsed_command_line
) {
353 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
355 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
357 base::Time start
= base::Time::Now();
358 if (profiles::IsMultipleProfilesEnabled() &&
359 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
360 profiles::SetLastUsedProfile(
361 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
362 // Clear kProfilesLastActive since the user only wants to launch a specific
364 ListPrefUpdate
update(g_browser_process
->local_state(),
365 prefs::kProfilesLastActive
);
366 base::ListValue
* profile_list
= update
.Get();
367 profile_list
->Clear();
370 Profile
* profile
= NULL
;
371 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
372 // On ChromeOS and Android the ProfileManager will use the same path as the
373 // one we got passed. GetActiveUserProfile will therefore use the correct path
375 DCHECK_EQ(user_data_dir
.value(),
376 g_browser_process
->profile_manager()->user_data_dir().value());
377 profile
= ProfileManager::GetActiveUserProfile();
379 base::FilePath profile_path
=
380 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
382 // Without NewAvatarMenu, replace guest with any existing profile.
383 if (!switches::IsNewAvatarMenu() &&
384 profile_path
== ProfileManager::GetGuestProfilePath()) {
385 profile_path
= g_browser_process
->profile_manager()->GetProfileInfoCache().
386 GetPathOfProfileAtIndex(0);
388 profile
= g_browser_process
->profile_manager()->GetProfile(
391 // If we're using the --new-profile-management flag and this profile is
392 // signed out, then we should show the user manager instead. By switching
393 // the active profile to the guest profile we ensure that no
394 // browser windows will be opened for the guest profile.
395 if (switches::IsNewProfileManagement() &&
397 !profile
->IsGuestSession()) {
398 ProfileInfoCache
& cache
=
399 g_browser_process
->profile_manager()->GetProfileInfoCache();
400 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
402 if (profile_index
!= std::string::npos
&&
403 cache
.ProfileIsSigninRequiredAtIndex(profile_index
)) {
404 profile
= g_browser_process
->profile_manager()->GetProfile(
405 ProfileManager::GetGuestProfilePath());
408 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
410 UMA_HISTOGRAM_LONG_TIMES(
411 "Startup.CreateFirstProfile", base::Time::Now() - start
);
416 // TODO(port): fix this. See comments near the definition of
417 // user_data_dir. It is better to CHECK-fail here than it is to
418 // silently exit because of missing code in the above test.
419 CHECK(profile
) << "Cannot get default profile.";
420 #endif // !defined(OS_WIN)
425 #if defined(OS_MACOSX)
426 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
427 SecKeychainCallbackInfo
* info
, void* context
) {
430 #endif // defined(OS_MACOSX)
432 void RegisterComponentsForUpdate() {
433 component_updater::ComponentUpdateService
* cus
=
434 g_browser_process
->component_updater();
436 // Registration can be before or after cus->Start() so it is ok to post
437 // a task to the UI thread to do registration once you done the necessary
438 // file IO to know you existing component version.
439 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
440 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
441 RegisterPepperFlashComponent(cus
);
442 RegisterSwiftShaderComponent(cus
);
443 RegisterWidevineCdmComponent(cus
);
444 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
446 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
447 #if defined(OS_CHROMEOS)
448 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
449 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
450 // installer when running on Linux. See crbug.com/422121 for more details.
451 if (!base::SysInfo::IsRunningOnChromeOS())
452 #endif // defined(OS_CHROMEOS)
453 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
454 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
456 // Registration of the CLD Component is a no-op unless the CLD data source has
457 // been configured to be the "Component" data source.
458 RegisterCldComponent(cus
);
460 component_updater::SupervisedUserWhitelistInstaller
* whitelist_installer
=
461 g_browser_process
->supervised_user_whitelist_installer();
462 whitelist_installer
->RegisterComponents();
465 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
466 #if defined(OS_ANDROID)
467 // The CRLSet component was enabled for some releases. This code attempts to
468 // delete it from the local disk of those how may have downloaded it.
469 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
470 #elif !defined(OS_CHROMEOS)
471 // CRLSetFetcher attempts to load a CRL set from either the local disk or
473 // For Chrome OS this registration is delayed until user login.
474 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
475 // Registration of the EV Whitelist component here is not necessary for:
476 // 1. Android: Because it currently does not have the EV indicator.
477 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
478 RegisterEVWhitelistComponent(cus
, path
);
479 #endif // defined(OS_ANDROID)
483 #if defined(GOOGLE_CHROME_BUILD)
484 RegisterSwReporterComponent(cus
);
485 #endif // defined(GOOGLE_CHROME_BUILD)
486 RegisterCAPSComponent(cus
);
487 #endif // defined(OS_WIN)
490 #if !defined(OS_ANDROID)
491 bool ProcessSingletonNotificationCallback(
492 const base::CommandLine
& command_line
,
493 const base::FilePath
& current_directory
) {
494 // Drop the request if the browser process is already in shutdown path.
495 if (!g_browser_process
|| g_browser_process
->IsShuttingDown()) {
497 browser_watcher::ExitFunnel::RecordSingleEvent(
498 chrome::kBrowserExitCodesRegistryPath
,
499 L
"ProcessSingletonIsShuttingDown");
500 #endif // defined(OS_WIN)
505 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
506 std::string start_time_string
=
507 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
508 int64 remote_start_time
;
509 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
510 base::TimeDelta elapsed
=
511 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
512 if (command_line
.HasSwitch(switches::kFastStart
)) {
513 UMA_HISTOGRAM_LONG_TIMES(
514 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
516 UMA_HISTOGRAM_LONG_TIMES(
517 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
522 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
525 base::FilePath user_data_dir
=
526 g_browser_process
->profile_manager()->user_data_dir();
527 base::FilePath startup_profile_dir
=
528 GetStartupProfilePath(user_data_dir
, command_line
);
530 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
531 command_line
, current_directory
, startup_profile_dir
);
534 #endif // !defined(OS_ANDROID)
536 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine
& command_line
) {
537 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
538 std::string port_str
=
539 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
541 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
542 g_browser_process
->CreateDevToolsHttpProtocolHandler(
543 chrome::HOST_DESKTOP_TYPE_NATIVE
,
545 static_cast<uint16
>(port
));
547 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
554 namespace chrome_browser
{
556 // This error message is not localized because we failed to load the
557 // localization data files.
559 const char kMissingLocaleDataTitle
[] = "Missing File Error";
560 #endif // defined(OS_WIN)
563 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
564 const char kMissingLocaleDataMessage
[] =
565 "Unable to find locale data files. Please reinstall.";
566 #endif // defined(OS_WIN)
568 } // namespace chrome_browser
570 // BrowserMainParts ------------------------------------------------------------
572 ChromeBrowserMainParts::ChromeBrowserMainParts(
573 const content::MainFunctionParams
& parameters
)
574 : parameters_(parameters
),
575 parsed_command_line_(parameters
.command_line
),
576 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
577 startup_watcher_(new StartupTimeBomb()),
578 shutdown_watcher_(new ShutdownWatcherHelper()),
579 browser_field_trials_(parameters
.command_line
),
581 base::PlatformThread::CurrentId(),
582 sampling_profiler_config_
.GetSamplingParams(),
583 metrics::CallStackProfileMetricsProvider::GetProfilerCallback(
584 metrics::CallStackProfileMetricsProvider::Params(
585 metrics::CallStackProfileMetricsProvider::PROCESS_STARTUP
,
588 run_message_loop_(true),
589 notify_result_(ProcessSingleton::PROCESS_NONE
),
591 restart_last_session_(false) {
592 if (sampling_profiler_config_
.IsProfilerEnabled())
593 sampling_profiler_
.Start();
595 // If we're running tests (ui_task is non-null).
596 if (parameters
.ui_task
)
597 browser_defaults::enable_help_app
= false;
599 // Chrome disallows cookies by default. All code paths that want to use
600 // cookies need to go through one of Chrome's URLRequestContexts which have
601 // a ChromeNetworkDelegate attached that selectively allows cookies again.
602 net::URLRequest::SetDefaultCookiePolicyToBlock();
605 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
606 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
607 delete chrome_extra_parts_
[i
];
608 chrome_extra_parts_
.clear();
611 // This will be called after the command-line has been mutated by about:flags
612 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
613 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
614 // Must initialize metrics after labs have been converted into switches,
615 // but before field trials are set up (so that client ID is available for
616 // one-time randomized field trials).
618 // Initialize FieldTrialList to support FieldTrials that use one-time
620 metrics::MetricsService
* metrics
= browser_process_
->metrics_service();
621 field_trial_list_
.reset(
622 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
624 const base::CommandLine
* command_line
=
625 base::CommandLine::ForCurrentProcess();
626 if (command_line
->HasSwitch(switches::kEnableBenchmarking
) ||
627 command_line
->HasSwitch(cc::switches::kEnableGpuBenchmarking
)) {
628 base::FieldTrial::EnableBenchmarking();
631 if (command_line
->HasSwitch(switches::kForceFieldTrialParams
)) {
632 bool result
= chrome_variations::AssociateParamsFromString(
633 command_line
->GetSwitchValueASCII(switches::kForceFieldTrialParams
));
634 CHECK(result
) << "Invalid --" << switches::kForceFieldTrialParams
635 << " list specified.";
638 // Ensure any field trials specified on the command line are initialized.
639 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
640 std::set
<std::string
> unforceable_field_trials
;
641 #if defined(OFFICIAL_BUILD)
642 unforceable_field_trials
.insert("SettingsEnforcement");
643 #endif // defined(OFFICIAL_BUILD)
645 // Create field trials without activating them, so that this behaves in a
646 // consistent manner with field trials created from the server.
647 bool result
= base::FieldTrialList::CreateTrialsFromString(
648 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
649 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
650 unforceable_field_trials
);
651 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
652 << " list specified.";
655 #if defined(FIELDTRIAL_TESTING_ENABLED)
656 if (!command_line
->HasSwitch(switches::kDisableFieldTrialTestingConfig
) &&
657 !command_line
->HasSwitch(switches::kForceFieldTrials
) &&
658 !command_line
->HasSwitch(variations::switches::kVariationsServerURL
))
659 chrome_variations::AssociateDefaultFieldTrialConfig();
660 #endif // defined(FIELDTRIAL_TESTING_ENABLED)
662 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
663 // Create default variation ids which will always be included in the
664 // X-Client-Data request header.
665 variations::VariationsHttpHeaderProvider
* provider
=
666 variations::VariationsHttpHeaderProvider::GetInstance();
667 bool result
= provider
->SetDefaultVariationIds(
668 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
669 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
670 << " list specified.";
671 metrics
->AddSyntheticTrialObserver(provider
);
674 scoped_ptr
<base::FeatureList
> feature_list(new base::FeatureList
);
675 feature_list
->InitializeFromCommandLine(
676 command_line
->GetSwitchValueASCII(switches::kEnableFeatures
),
677 command_line
->GetSwitchValueASCII(switches::kDisableFeatures
));
679 variations::VariationsService
* variations_service
=
680 browser_process_
->variations_service();
681 if (variations_service
)
682 variations_service
->CreateTrialsFromSeed();
684 // TODO(asvitkine): Pass |feature_list| to CreateTrialsFromSeed() above.
685 base::FeatureList::SetInstance(feature_list
.Pass());
687 // This must be called after |local_state_| is initialized.
688 browser_field_trials_
.SetupFieldTrials();
690 // Enable Navigation Tracing only if a trace upload url is specified.
691 if (command_line
->HasSwitch(switches::kEnableNavigationTracing
) &&
692 command_line
->HasSwitch(switches::kTraceUploadURL
)) {
693 tracing::SetupNavigationTracing();
696 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
697 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
698 // Even though base::Bind does AddRef and Release, the object will not be
699 // deleted after the Task is executed.
700 field_trial_synchronizer_
= new FieldTrialSynchronizer();
702 // Now that field trials have been created, initializes metrics recording.
703 metrics
->InitializeMetricsRecordingState();
705 const version_info::Channel channel
= chrome::GetChannel();
707 // TODO(dalecurtis): Remove these checks and enable for all channels once we
708 // track down the root causes of crbug.com/422522 and crbug.com/478932.
709 if (channel
== version_info::Channel::UNKNOWN
||
710 channel
== version_info::Channel::CANARY
||
711 channel
== version_info::Channel::DEV
) {
712 media::AudioManager::EnableHangMonitor();
715 // Enable profiler instrumentation depending on the channel.
717 case version_info::Channel::UNKNOWN
:
718 case version_info::Channel::CANARY
:
719 tracked_objects::ScopedTracker::Enable();
722 case version_info::Channel::DEV
:
723 case version_info::Channel::BETA
:
724 case version_info::Channel::STABLE
:
725 // Don't enable instrumentation.
729 // Register a synthetic field trial for the sampling profiler configuration
730 // that was already chosen.
731 sampling_profiler_config_
.RegisterSyntheticFieldTrial();
734 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
736 void ChromeBrowserMainParts::StartMetricsRecording() {
737 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
739 g_browser_process
->metrics_service()->CheckForClonedInstall(
740 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
742 g_browser_process
->GetMetricsServicesManager()->UpdateUploadPermissions(true);
745 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
746 // Don't record any metrics if UI was displayed before this point e.g.
748 if (startup_metric_utils::WasNonBrowserUIDisplayed())
751 bool is_first_run
= false;
752 #if !defined(OS_ANDROID)
753 // On Android, first run is handled in Java code, and the C++ side of Chrome
754 // doesn't know if this is the first run. This will cause some inaccuracy in
755 // the UMA statistics, but this should be minor (first runs are rare).
756 is_first_run
= first_run::IsChromeFirstRun();
757 #endif // defined(OS_ANDROID)
759 // Record collected startup metrics.
760 startup_metric_utils::RecordBrowserMainMessageLoopStart(base::Time::Now(),
764 // -----------------------------------------------------------------------------
765 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
768 #define DLLEXPORT __declspec(dllexport)
770 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
772 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
775 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
776 // Need an instance of AtExitManager to handle singleton creations and
777 // deletions. We need this new instance because, the old instance created
778 // in ChromeMain() got destructed when the function returned.
779 base::AtExitManager exit_manager
;
780 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
784 // content::BrowserMainParts implementation ------------------------------------
786 void ChromeBrowserMainParts::PreEarlyInitialization() {
787 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
788 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
789 chrome_extra_parts_
[i
]->PreEarlyInitialization();
792 void ChromeBrowserMainParts::PostEarlyInitialization() {
793 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
794 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
795 chrome_extra_parts_
[i
]->PostEarlyInitialization();
798 void ChromeBrowserMainParts::ToolkitInitialized() {
799 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
800 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
801 chrome_extra_parts_
[i
]->ToolkitInitialized();
804 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
805 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
807 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
808 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
811 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
812 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
814 // device_event_log must be initialized after the message loop. Calls to
815 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
816 // platforms (e.g. chromeos) may have already initialized this.
817 if (!device_event_log::IsInitialized())
818 device_event_log::Initialize(0 /* default max entries */);
820 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
821 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
824 int ChromeBrowserMainParts::PreCreateThreads() {
825 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
826 result_code_
= PreCreateThreadsImpl();
828 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
829 #if !defined(OS_ANDROID)
830 // These members must be initialized before exiting this function normally.
831 DCHECK(master_prefs_
.get());
832 DCHECK(browser_creator_
.get());
833 #endif // !defined(OS_ANDROID)
834 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
835 chrome_extra_parts_
[i
]->PreCreateThreads();
841 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
842 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
843 run_message_loop_
= false;
844 #if !defined(OS_ANDROID)
845 chrome::MaybeShowInvalidUserDataDirWarningDialog();
846 #endif // !defined(OS_ANDROID)
847 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
848 return chrome::RESULT_CODE_MISSING_DATA
;
850 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
851 MediaCaptureDevicesDispatcher::GetInstance();
853 // Android's first run is done in Java instead of native.
854 #if !defined(OS_ANDROID)
855 process_singleton_
.reset(new ChromeProcessSingleton(
856 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
858 // Cache first run state early.
859 first_run::IsChromeFirstRun();
860 #endif // !defined(OS_ANDROID)
862 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
863 JsonPrefStore::GetTaskRunnerForFile(
864 base::FilePath(chrome::kLocalStorePoolName
),
865 BrowserThread::GetBlockingPool());
868 TRACE_EVENT0("startup",
869 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
870 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
871 parsed_command_line()));
874 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
875 TRACE_EVENT0("startup",
876 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
877 // User wants to override default tracking status.
879 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
880 // Default to basic profiling (no parent child support).
881 tracked_objects::ThreadData::Status status
=
882 tracked_objects::ThreadData::PROFILING_ACTIVE
;
883 if (flag
.compare("0") != 0)
884 status
= tracked_objects::ThreadData::DEACTIVATED
;
885 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
888 local_state_
= InitializeLocalState(
889 local_state_task_runner
.get(), parsed_command_line());
891 #if !defined(OS_ANDROID)
892 // These members must be initialized before returning from this function.
893 master_prefs_
.reset(new first_run::MasterPrefs
);
894 // Android doesn't use StartupBrowserCreator.
895 browser_creator_
.reset(new StartupBrowserCreator
);
896 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
897 chrome::UMABrowsingActivityObserver::Init();
898 #endif // !defined(OS_ANDROID)
900 #if !defined(OS_CHROMEOS)
901 // Convert active labs into switches. This needs to be done before
902 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
903 // affected by experiment flags (--touch-optimized-ui in particular).
904 // On ChromeOS system level flags are applied from the device settings from
905 // the session manager.
907 TRACE_EVENT0("startup",
908 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
909 about_flags::PrefServiceFlagsStorage
flags_storage_(
910 g_browser_process
->local_state());
911 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
912 base::CommandLine::ForCurrentProcess(),
913 about_flags::kAddSentinels
);
915 #endif // !defined(OS_CHROMEOS)
918 // This is needed to enable ETW exporting when requested in about:flags.
919 // Normally, we enable it in ContentMainRunnerImpl::Initialize when the flag
920 // is present on the command line but flags in about:flags are converted only
921 // after this function runs. Note that this starts exporting later which
922 // affects tracing the browser startup. Also, this is only relevant for the
923 // browser process, as other processes will get all the flags on their command
924 // line regardless of the origin (command line or about:flags).
925 if (parsed_command_line().HasSwitch(switches::kTraceExportEventsToETW
))
926 base::trace_event::TraceEventETWExport::EnableETWExport();
929 local_state_
->UpdateCommandLinePrefStore(
930 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
932 // Reset the command line in the crash report details, since we may have
933 // just changed it to include experiments.
934 crash_keys::SetSwitchesFromCommandLine(
935 base::CommandLine::ForCurrentProcess());
937 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
938 // needed when loading the MainMenu.nib and the language doesn't depend on
939 // anything since it comes from Cocoa.
940 #if defined(OS_MACOSX)
942 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
943 browser_process_
->SetApplicationLocale(locale
);
945 const std::string locale
=
946 local_state_
->GetString(prefs::kApplicationLocale
);
948 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
949 // method InitSharedInstance is ignored.
951 TRACE_EVENT_BEGIN0("startup",
952 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
953 const std::string loaded_locale
=
954 ui::ResourceBundle::InitSharedInstanceWithLocale(
955 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
956 TRACE_EVENT_END0("startup",
957 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
959 if (loaded_locale
.empty() &&
960 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
961 ShowMissingLocaleMessageBox();
962 return chrome::RESULT_CODE_MISSING_DATA
;
964 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
965 browser_process_
->SetApplicationLocale(loaded_locale
);
968 TRACE_EVENT0("startup",
969 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
970 base::FilePath resources_pack_path
;
971 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
972 #if defined(OS_ANDROID)
973 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path
);
975 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
976 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
977 #endif // defined(OS_ANDROID)
979 #endif // defined(OS_MACOSX)
981 // Android does first run in Java instead of native.
982 // Chrome OS has its own out-of-box-experience code.
983 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
984 // On first run, we need to process the predictor preferences before the
985 // browser's profile_manager object is created, but after ResourceBundle
987 if (first_run::IsChromeFirstRun()) {
988 first_run::ProcessMasterPreferencesResult pmp_result
=
989 first_run::ProcessMasterPreferences(user_data_dir_
,
990 master_prefs_
.get());
991 if (pmp_result
== first_run::EULA_EXIT_NOW
)
992 return chrome::RESULT_CODE_EULA_REFUSED
;
994 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
995 !parsed_command_line().HasSwitch(switches::kAppId
) &&
996 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
997 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
1000 // TODO(macourteau): refactor preferences that are copied from
1001 // master_preferences into local_state, as a "local_state" section in
1002 // master preferences. If possible, a generic solution would be preferred
1003 // over a copy one-by-one of specific preferences. Also see related TODO
1006 // Store the initial VariationsService seed in local state, if it exists
1008 if (!master_prefs_
->variations_seed
.empty() ||
1009 !master_prefs_
->compressed_variations_seed
.empty()) {
1010 if (!master_prefs_
->variations_seed
.empty()) {
1011 local_state_
->SetString(variations::prefs::kVariationsSeed
,
1012 master_prefs_
->variations_seed
);
1014 if (!master_prefs_
->compressed_variations_seed
.empty()) {
1015 local_state_
->SetString(variations::prefs::kVariationsCompressedSeed
,
1016 master_prefs_
->compressed_variations_seed
);
1018 if (!master_prefs_
->variations_seed_signature
.empty()) {
1019 local_state_
->SetString(variations::prefs::kVariationsSeedSignature
,
1020 master_prefs_
->variations_seed_signature
);
1022 // Set the variation seed date to the current system time. If the user's
1023 // clock is incorrect, this may cause some field trial expiry checks to
1024 // not do the right thing until the next seed update from the server,
1025 // when this value will be updated.
1026 local_state_
->SetInt64(variations::prefs::kVariationsSeedDate
,
1027 base::Time::Now().ToInternalValue());
1030 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
1031 local_state_
->SetString(
1032 prefs::kBrowserSuppressDefaultBrowserPrompt
,
1033 master_prefs_
->suppress_default_browser_prompt_for_version
);
1037 if (!master_prefs_
->welcome_page_on_os_upgrade_enabled
)
1038 local_state_
->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled
, false);
1041 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1043 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1044 // Set the product channel for crash reports.
1045 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
1046 chrome::GetChannelString());
1047 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1049 // Initialize tracking synchronizer system.
1050 tracking_synchronizer_
= new metrics::TrackingSynchronizer(
1051 make_scoped_ptr(new base::DefaultTickClock()));
1053 #if defined(OS_MACOSX)
1054 // Get the Keychain API to register for distributed notifications on the main
1055 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1056 // which doesn't. This ensures those notifications will get delivered
1057 // properly. See issue 37766.
1058 // (Note that the callback mask here is empty. I don't want to register for
1059 // any callbacks, I just want to initialize the mechanism.)
1060 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
1061 #endif // defined(OS_MACOSX)
1063 #if defined(OS_CHROMEOS)
1064 // Must be done after g_browser_process is constructed, before
1065 // SetupMetricsAndFieldTrials().
1066 chromeos::CrosSettings::Initialize();
1067 #endif // defined(OS_CHROMEOS)
1069 // Now the command line has been mutated based on about:flags, we can setup
1070 // metrics and initialize field trials. The field trials are needed by
1071 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1072 SetupMetricsAndFieldTrials();
1074 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1075 browser_process_
->PreCreateThreads();
1077 return content::RESULT_CODE_NORMAL_EXIT
;
1080 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1081 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1082 TRACK_SCOPED_REGION(
1083 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1085 result_code_
= PreMainMessageLoopRunImpl();
1087 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1088 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
1091 // PreMainMessageLoopRun calls these extra stages in the following order:
1092 // PreMainMessageLoopRunImpl()
1093 // ... initial setup, including browser_process_ setup.
1095 // ... additional setup, including CreateProfile()
1096 // PostProfileInit()
1097 // ... additional setup
1098 // PreBrowserStart()
1099 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1100 // PostBrowserStart()
1102 void ChromeBrowserMainParts::PreProfileInit() {
1103 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1105 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1106 chrome_extra_parts_
[i
]->PreProfileInit();
1108 #if !defined(OS_ANDROID)
1109 // Initialize the feedback uploader so it can setup notifications for profile
1111 feedback::FeedbackProfileObserver::Initialize();
1113 // Ephemeral profiles may have been left behind if the browser crashed.
1114 g_browser_process
->profile_manager()->CleanUpEphemeralProfiles();
1115 #endif // !defined(OS_ANDROID)
1117 #if defined(ENABLE_EXTENSIONS)
1118 javascript_dialog_extensions_client::InstallClient();
1119 #endif // defined(ENABLE_EXTENSIONS)
1121 #if !defined(OS_IOS)
1122 InstallChromeJavaScriptNativeDialogFactory();
1123 #endif // !defined(OS_IOS)
1126 void ChromeBrowserMainParts::PostProfileInit() {
1127 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1129 #if defined(OS_ANDROID)
1130 DevToolsDiscoveryProviderAndroid::Install();
1132 ChromeDevToolsDiscoveryProvider::Install();
1133 #endif // defined(OS_ANDROID)
1135 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1136 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1137 chrome_extra_parts_
[i
]->PostProfileInit();
1140 void ChromeBrowserMainParts::PreBrowserStart() {
1141 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1142 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1143 chrome_extra_parts_
[i
]->PreBrowserStart();
1145 three_d_observer_
.reset(new ThreeDAPIObserver());
1147 // Start the out-of-memory priority manager here so that we give the most
1148 // amount of time for the other services to start up before we start
1149 // adjusting the oom priority.
1151 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1153 #if defined(OS_CHROMEOS)
1154 g_browser_process
->GetOomPriorityManager()->Start(false);
1155 #elif defined(OS_WIN) || defined(OS_MACOSX)
1156 const std::string group_name
=
1157 base::FieldTrialList::FindFullName("AutomaticTabDiscarding");
1158 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding
) ||
1159 base::StartsWith(group_name
, "Enabled", base::CompareCase::SENSITIVE
)) {
1160 bool enabled_once
= base::StartsWith(group_name
, "Enabled_Once",
1161 base::CompareCase::SENSITIVE
);
1162 g_browser_process
->GetOomPriorityManager()->Start(enabled_once
);
1167 void ChromeBrowserMainParts::PostBrowserStart() {
1168 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1169 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1170 chrome_extra_parts_
[i
]->PostBrowserStart();
1171 #if !defined(OS_ANDROID)
1172 // Allow ProcessSingleton to process messages.
1173 process_singleton_
->Unlock();
1174 #endif // !defined(OS_ANDROID)
1175 #if defined(ENABLE_WEBRTC)
1176 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1177 // to reduce the impact on startup time.
1178 BrowserThread::PostDelayedTask(
1181 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1182 base::TimeDelta::FromMinutes(1));
1183 #endif // defined(ENABLE_WEBRTC)
1185 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1186 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1187 switches::kEnableWebUsbNotifications
)) {
1188 webusb_browser_client_
.reset(new ChromeWebUsbBrowserClient());
1189 webusb_detector_
.reset(
1190 new webusb::WebUsbDetector(webusb_browser_client_
.get()));
1194 // At this point, StartupBrowserCreator::Start has run creating initial
1195 // browser windows and tabs, but no progress has been made in loading
1196 // content as the main message loop hasn't started processing tasks yet.
1197 // We setup to observe to the initial page load here to defer running
1198 // task posted via PostAfterStartupTask until its complete.
1199 AfterStartupTaskUtils::StartMonitoringStartup();
1202 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1203 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1204 TRACK_SCOPED_REGION(
1205 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1207 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1208 const base::TimeTicks start_time_step1
= base::TimeTicks::Now();
1211 // Windows parental controls calls can be slow, so we do an early init here
1212 // that calculates this value off of the UI thread.
1213 IncognitoModePrefs::InitializePlatformParentalControls();
1216 #if defined(ENABLE_EXTENSIONS)
1217 if (!variations::GetVariationParamValue(
1218 "LightSpeed", "EarlyInitStartup").empty()) {
1219 // Try to compute this early on another thread so that we don't spend time
1220 // during profile load initializing the extensions APIs.
1221 BrowserThread::PostTask(
1222 BrowserThread::FILE_USER_BLOCKING
,
1225 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures
)));
1229 // Android updates the metrics service dynamically depending on whether the
1230 // application is in the foreground or not. Do not start here.
1231 #if !defined(OS_ANDROID)
1232 // Now that the file thread has been started, start recording.
1233 StartMetricsRecording();
1234 #endif // !defined(OS_ANDROID)
1236 if (!base::debug::BeingDebugged()) {
1237 // Create watchdog thread after creating all other threads because it will
1238 // watch the other threads and they must be running.
1239 browser_process_
->watchdog_thread();
1242 // Do any initializating in the browser process that requires all threads
1244 browser_process_
->PreMainMessageLoopRun();
1246 // Record last shutdown time into a histogram.
1247 browser_shutdown::ReadLastShutdownInfo();
1250 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1251 // tasks. Those care whether the browser is already running. On Linux/Mac,
1252 // upgrade/uninstall happen separately.
1253 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1255 // If the command line specifies 'uninstall' then we need to work here
1256 // unless we detect another chrome browser running.
1257 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1258 return DoUninstallTasks(already_running
);
1261 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1262 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1263 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1264 parsed_command_line_
);
1267 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1268 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1269 #endif // defined(OS_WIN)
1271 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1272 bool is_managed
= g_browser_process
->local_state()->IsManagedPreference(
1273 prefs::kDefaultBrowserSettingEnabled
);
1274 if (is_managed
&& !g_browser_process
->local_state()->GetBoolean(
1275 prefs::kDefaultBrowserSettingEnabled
)) {
1276 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY
);
1279 return ShellIntegration::SetAsDefaultBrowser() ?
1280 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1281 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1284 #if defined(USE_AURA)
1285 // Make sure aura::Env has been initialized.
1286 CHECK(aura::Env::GetInstance());
1287 #endif // defined(USE_AURA)
1289 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1290 #if !defined(OS_ANDROID)
1291 // If the command line specifies --pack-extension, attempt the pack extension
1292 // startup action and exit.
1293 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1294 extensions::StartupHelper extension_startup_helper
;
1295 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1296 return content::RESULT_CODE_NORMAL_EXIT
;
1297 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1300 // When another process is running, use that process instead of starting a
1301 // new one. NotifyOtherProcess will currently give the other process up to
1302 // 20 seconds to respond. Note that this needs to be done before we attempt
1303 // to read the profile.
1304 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1305 switch (notify_result_
) {
1306 case ProcessSingleton::PROCESS_NONE
:
1307 // No process already running, fall through to starting a new one.
1310 case ProcessSingleton::PROCESS_NOTIFIED
:
1311 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1312 // On POSIX systems, print a message notifying the process is running.
1313 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1314 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1315 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1317 // Having a differentiated return type for testing allows for tests to
1318 // verify proper handling of some switches. When not testing, stick to
1319 // the standard Unix convention of returning zero when things went as
1321 if (parsed_command_line().HasSwitch(switches::kTestType
))
1322 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1323 return content::RESULT_CODE_NORMAL_EXIT
;
1325 case ProcessSingleton::PROFILE_IN_USE
:
1326 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1328 case ProcessSingleton::LOCK_ERROR
:
1329 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1330 "directory. This means that running multiple instances "
1331 "would start multiple browser processes rather than "
1332 "opening a new window in the existing process. Aborting "
1333 "now to avoid profile corruption.";
1334 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1339 #endif // !defined(OS_ANDROID)
1341 // Handle special early return paths (which couldn't be processed even earlier
1342 // as they require the process singleton to be held) first.
1344 std::string try_chrome
=
1345 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1346 if (!try_chrome
.empty()) {
1348 // Setup.exe has determined that we need to run a retention experiment
1349 // and has lauched chrome to show the experiment UI. It is guaranteed that
1350 // no other Chrome is currently running as the process singleton was
1351 // sucessfully grabbed above.
1353 base::StringToInt(try_chrome
, &try_chrome_int
);
1354 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1356 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1357 base::Unretained(process_singleton_
.get())));
1358 if (answer
== TryChromeDialogView::NOT_NOW
)
1359 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1360 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1361 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1362 // At this point the user is willing to try chrome again.
1363 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1364 // Only set in the unattended case, the interactive case is Windows 8.
1365 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1366 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1367 ShellIntegration::SetAsDefaultBrowser();
1370 // We don't support retention experiments on Mac or Linux.
1371 return content::RESULT_CODE_NORMAL_EXIT
;
1372 #endif // defined(OS_WIN)
1376 // Do the tasks if chrome has been upgraded while it was last running.
1377 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1378 return content::RESULT_CODE_NORMAL_EXIT
;
1380 // Check if there is any machine level Chrome installed on the current
1381 // machine. If yes and the current Chrome process is user level, we do not
1382 // allow the user level Chrome to run. So we notify the user and uninstall
1383 // user level Chrome.
1384 // Note this check needs to happen here (after the process singleton was
1385 // obtained but before potentially creating the first run sentinel).
1386 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1387 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1388 #endif // defined(OS_WIN)
1390 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1391 if (sxs_linux::ShouldMigrateUserDataDir())
1392 return sxs_linux::MigrateUserDataDir();
1393 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1395 // Desktop construction occurs here, (required before profile creation).
1398 // Profile creation ----------------------------------------------------------
1400 metrics::MetricsService::SetExecutionPhase(
1401 metrics::MetricsService::CREATE_PROFILE
,
1402 g_browser_process
->local_state());
1404 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1405 base::TimeTicks::Now() - start_time_step1
);
1407 // This step is costly and is already measured in Startup.CreateFirstProfile
1408 // and more directly Profile.CreateAndInitializeProfile.
1409 profile_
= CreatePrimaryProfile(parameters(),
1411 parsed_command_line());
1413 return content::RESULT_CODE_NORMAL_EXIT
;
1415 #if !defined(OS_ANDROID)
1416 const base::TimeTicks start_time_step2
= base::TimeTicks::Now();
1417 // The first run sentinel must be created after the process singleton was
1418 // grabbed and no early return paths were otherwise hit above.
1419 first_run::CreateSentinelIfNeeded();
1420 #endif // !defined(OS_ANDROID)
1422 #if defined(ENABLE_BACKGROUND)
1423 // Autoload any profiles which are running background apps.
1424 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1425 browser_process_
->profile_manager()->AutoloadProfiles();
1426 #endif // defined(ENABLE_BACKGROUND)
1427 // Post-profile init ---------------------------------------------------------
1429 TranslateService::Initialize();
1431 // Needs to be done before PostProfileInit, since login manager on CrOS is
1432 // called inside PostProfileInit.
1433 content::WebUIControllerFactory::RegisterFactory(
1434 ChromeWebUIControllerFactory::GetInstance());
1436 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1437 // So make sure to create it before that.
1438 #if !defined(DISABLE_NACL)
1439 NaClBrowserDelegateImpl
* delegate
=
1440 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1441 nacl::NaClBrowser::SetDelegate(delegate
);
1442 #endif // !defined(DISABLE_NACL)
1444 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1445 // (requires supporting early exit).
1448 // Retrieve cached GL strings from local state and use them for GPU
1449 // blacklist decisions.
1450 if (g_browser_process
->gl_string_manager())
1451 g_browser_process
->gl_string_manager()->Initialize();
1453 // Create an instance of GpuModeManager to watch gpu mode pref change.
1454 g_browser_process
->gpu_mode_manager();
1456 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1457 // Show the First Run UI if this is the first time Chrome has been run on
1458 // this computer, or we're being compelled to do so by a command line flag.
1459 // Note that this be done _after_ the PrefService is initialized and all
1460 // preferences are registered, since some of the code that the importer
1461 // touches reads preferences.
1462 if (first_run::IsChromeFirstRun()) {
1463 first_run::AutoImport(profile_
,
1464 master_prefs_
->homepage_defined
,
1465 master_prefs_
->do_import_items
,
1466 master_prefs_
->dont_import_items
,
1467 master_prefs_
->import_bookmarks_path
);
1469 // Note: this can pop the first run consent dialog on linux.
1470 first_run::DoPostImportTasks(profile_
,
1471 master_prefs_
->make_chrome_default_for_user
);
1473 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1474 browser_creator_
->set_show_main_browser_window(
1475 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1477 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1480 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1483 // Sets things up so that if we crash from this point on, a dialog will
1484 // popup asking the user to restart chrome. It is done this late to avoid
1485 // testing against a bunch of special cases that are taken care early on.
1486 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1487 parsed_command_line());
1489 // Registers Chrome with the Windows Restart Manager, which will restore the
1490 // Chrome session when the computer is restarted after a system update.
1491 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1492 // but should run on startup if extended to handle crashes/hangs/patches.
1493 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1494 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1495 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1496 parsed_command_line());
1499 // Verify that the profile is not on a network share and if so prepare to show
1500 // notification to the user.
1501 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1502 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1503 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1504 profile_
->GetPath()));
1506 #endif // defined(OS_WIN)
1508 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1509 // Init the RLZ library. This just binds the dll and schedules a task on the
1510 // file thread to be run sometime later. If this is the first run we record
1511 // the installation event.
1512 PrefService
* pref_service
= profile_
->GetPrefs();
1513 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1514 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1515 // Negative ping delay means to send ping immediately after a first search is
1517 rlz::RLZTracker::SetRlzDelegate(
1518 make_scoped_ptr(new ChromeRLZTrackerDelegate
));
1519 rlz::RLZTracker::InitRlzDelayed(
1520 first_run::IsChromeFirstRun(), ping_delay
< 0,
1521 base::TimeDelta::FromMilliseconds(abs(ping_delay
)),
1522 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_
),
1523 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_
),
1524 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_
));
1525 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1527 // Configure modules that need access to resources.
1528 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1530 // In unittest mode, this will do nothing. In normal mode, this will create
1531 // the global IntranetRedirectDetector instance, which will promptly go to
1532 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1533 // to see if it should do anything else.
1535 // A simpler way of doing all this would be to have some function which could
1536 // give the time elapsed since startup, and simply have this object check that
1537 // when asked to initialize itself, but this doesn't seem to exist.
1539 // This can't be created in the BrowserProcessImpl constructor because it
1540 // needs to read prefs that get set after that runs.
1541 browser_process_
->intranet_redirect_detector();
1543 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1544 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1545 base::FilePath path
=
1546 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1547 printing::PrintedDocument::set_debug_dump_path(path
);
1549 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1551 HandleTestParameters(parsed_command_line());
1552 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1553 base::debug::BeingDebugged());
1555 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1556 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1557 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1558 browser_process_
->GetApplicationLocale());
1560 // Start watching for hangs during startup. We disarm this hang detector when
1561 // ThreadWatcher takes over or when browser is shutdown or when
1562 // startup_watcher_ is deleted.
1563 metrics::MetricsService::SetExecutionPhase(
1564 metrics::MetricsService::STARTUP_TIMEBOMB_ARM
,
1565 g_browser_process
->local_state());
1566 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(600));
1568 // On mobile, need for clean shutdown arises only when the application comes
1569 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1570 // http://crbug.com/179143
1571 #if !defined(OS_ANDROID)
1572 // Start watching for a hang.
1573 browser_process_
->metrics_service()->LogNeedForCleanShutdown();
1574 #endif // !defined(OS_ANDROID)
1576 #if defined(ENABLE_PRINT_PREVIEW)
1577 // Create the instance of the cloud print proxy service so that it can launch
1578 // the service process if needed. This is needed because the service process
1579 // might have shutdown because an update was available.
1580 // TODO(torne): this should maybe be done with
1581 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1583 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1584 #endif // defined(ENABLE_PRINT_PREVIEW)
1586 // Start watching all browser threads for responsiveness.
1587 metrics::MetricsService::SetExecutionPhase(
1588 metrics::MetricsService::THREAD_WATCHER_START
,
1589 g_browser_process
->local_state());
1590 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1592 #if defined(OS_ANDROID)
1593 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1594 #endif // defined(OS_ANDROID)
1596 #if !defined(DISABLE_NACL)
1597 BrowserThread::PostTask(
1600 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1601 #endif // !defined(DISABLE_NACL)
1603 // Make sure initial prefs are recorded
1604 PrefMetricsService::Factory::GetForProfile(profile_
);
1608 // Instantiate the notification UI manager, as this triggers a perf timer
1609 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1610 // triggering the timer and call that explicitly in the approprate place.
1611 // http://crbug.com/105065.
1612 browser_process_
->notification_ui_manager();
1614 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1615 // data source is based on the Component Updater.
1616 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1618 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1619 RegisterComponentsForUpdate();
1621 #if defined(OS_ANDROID)
1622 variations::VariationsService
* variations_service
=
1623 browser_process_
->variations_service();
1624 if (variations_service
) {
1625 // Just initialize the policy prefs service here. Variations seed fetching
1626 // will be initialized when the app enters foreground mode.
1627 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1629 translate::TranslateDownloadManager::RequestLanguageList(
1630 profile_
->GetPrefs());
1633 // Most general initialization is behind us, but opening a
1634 // tab and/or session restore and such is still to be done.
1635 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1637 // We are in regular browser boot sequence. Open initial tabs and enter the
1638 // main message loop.
1639 std::vector
<Profile
*> last_opened_profiles
;
1640 #if !defined(OS_CHROMEOS)
1641 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1642 // them this early as the cryptohome hasn't yet been mounted (which happens
1643 // only once we log in).
1644 last_opened_profiles
=
1645 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1646 #endif // defined(OS_CHROMEOS)
1648 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1649 base::TimeTicks::Now() - start_time_step2
);
1651 // This step is costly and is already measured in
1652 // Startup.StartupBrowserCreator_Start.
1653 const bool started
= browser_creator_
->Start(
1654 parsed_command_line(), base::FilePath(), profile_
, last_opened_profiles
);
1655 const base::TimeTicks start_time_step3
= base::TimeTicks::Now();
1657 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1658 // Initialize autoupdate timer. Timer callback costs basically nothing
1659 // when browser is not in persistent mode, so it's OK to let it ride on
1660 // the main thread. This needs to be done here because we don't want
1661 // to start the timer when Chrome is run inside a test harness.
1662 browser_process_
->StartAutoupdateTimer();
1663 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1665 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1666 // On Linux, the running exe will be updated if an upgrade becomes
1667 // available while the browser is running. We need to save the last
1668 // modified time of the exe, so we can compare to determine if there is
1669 // an upgrade while the browser is kept alive by a persistent extension.
1670 upgrade_util::SaveLastModifiedTimeOfExe();
1671 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1673 // Record now as the last successful chrome start.
1674 GoogleUpdateSettings::SetLastRunTime();
1676 #if defined(OS_MACOSX)
1677 // Call Recycle() here as late as possible, before going into the loop
1678 // because Start() will add things to it while creating the main window.
1679 if (parameters().autorelease_pool
)
1680 parameters().autorelease_pool
->Recycle();
1681 #endif // defined(OS_MACOSX)
1683 const base::TimeDelta delta
= base::TimeTicks::Now() - browser_open_start
;
1684 startup_metric_utils::RecordBrowserOpenTabsDelta(delta
);
1686 // If we're running tests (ui_task is non-null), then we don't want to
1687 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1688 // RequestLanguageList
1689 if (parameters().ui_task
== NULL
) {
1690 // Request new variations seed information from server.
1691 variations::VariationsService
* variations_service
=
1692 browser_process_
->variations_service();
1693 if (variations_service
)
1694 variations_service
->PerformPreMainMessageLoopStartup();
1696 translate::TranslateDownloadManager::RequestLanguageList(
1697 profile_
->GetPrefs());
1700 run_message_loop_
= started
;
1701 browser_creator_
.reset();
1703 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1704 if (g_browser_process
->metrics_service()->reporting_active())
1705 content::StartPowerUsageMonitor();
1706 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1708 process_power_collector_
.reset(new ProcessPowerCollector
);
1709 process_power_collector_
->Initialize();
1710 #endif // !defined(OS_ANDROID)
1714 if (parameters().ui_task
) {
1715 parameters().ui_task
->Run();
1716 delete parameters().ui_task
;
1717 run_message_loop_
= false;
1719 #if defined(OS_ANDROID)
1720 // We never run the C++ main loop on Android, since the UI thread message
1721 // loop is controlled by the OS, so this is as close as we can get to
1722 // the start of the main loop.
1723 if (result_code_
<= 0) {
1724 RecordBrowserStartupTime();
1726 #endif // defined(OS_ANDROID)
1728 #if !defined(OS_ANDROID)
1729 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1730 base::TimeTicks::Now() - start_time_step3
);
1731 #endif // !defined(OS_ANDROID)
1733 return result_code_
;
1736 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1737 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1738 #if defined(OS_ANDROID)
1739 // Chrome on Android does not use default MessageLoop. It has its own
1740 // Android specific MessageLoop
1744 // Set the result code set in PreMainMessageLoopRun or set above.
1745 *result_code
= result_code_
;
1746 if (!run_message_loop_
)
1747 return true; // Don't run the default message loop.
1749 // These should be invoked as close to the start of the browser's
1750 // UI thread message loop as possible to get a stable measurement
1752 RecordBrowserStartupTime();
1754 DCHECK(base::MessageLoopForUI::IsCurrent());
1755 base::RunLoop run_loop
;
1757 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1759 metrics::MetricsService::SetExecutionPhase(
1760 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1761 g_browser_process
->local_state());
1765 #endif // defined(OS_ANDROID)
1768 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1769 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1770 #if defined(OS_ANDROID)
1771 // Chrome on Android does not use default MessageLoop. It has its own
1772 // Android specific MessageLoop
1775 // Start watching for jank during shutdown. It gets disarmed when
1776 // |shutdown_watcher_| object is destructed.
1777 metrics::MetricsService::SetExecutionPhase(
1778 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1779 g_browser_process
->local_state());
1780 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1782 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1783 startup_watcher_
->Disarm();
1785 // Remove observers attached to D-Bus clients before DbusThreadManager is
1787 process_power_collector_
.reset();
1789 #if !defined(OS_IOS)
1790 webusb_detector_
.reset();
1791 webusb_browser_client_
.reset();
1794 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1795 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1797 // Some tests don't set parameters.ui_task, so they started translate
1798 // language fetch that was never completed so we need to cleanup here
1799 // otherwise it will be done by the destructor in a wrong thread.
1800 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1802 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1803 process_singleton_
->Cleanup();
1805 // Stop all tasks that might run on WatchDogThread.
1806 ThreadWatcherList::StopWatchingAll();
1808 browser_process_
->metrics_service()->Stop();
1810 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1811 browser_process_
->StartTearDown();
1812 #endif // defined(OS_ANDROID)
1815 void ChromeBrowserMainParts::PostDestroyThreads() {
1816 #if defined(OS_ANDROID)
1817 // On Android, there is no quit/exit. So the browser's main message loop will
1821 browser_process_
->PostDestroyThreads();
1822 // browser_shutdown takes care of deleting browser_process, so we need to
1824 ignore_result(browser_process_
.release());
1825 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1826 master_prefs_
.reset();
1827 process_singleton_
.reset();
1828 device_event_log::Shutdown();
1830 // We need to do this check as late as possible, but due to modularity, this
1831 // may be the last point in Chrome. This would be more effective if done at
1832 // a higher level on the stack, so that it is impossible for an early return
1833 // to bypass this code. Perhaps we need a *final* hook that is called on all
1834 // paths from content/browser/browser_main.
1835 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1837 #if defined(OS_CHROMEOS)
1838 chromeos::CrosSettings::Shutdown();
1839 #endif // defined(OS_CHROMEOS)
1840 #endif // defined(OS_ANDROID)
1845 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1846 chrome_extra_parts_
.push_back(parts
);