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_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/google/google_search_counter.h"
61 #include "chrome/browser/gpu/gl_string_manager.h"
62 #include "chrome/browser/gpu/three_d_api_observer.h"
63 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
64 #include "chrome/browser/memory/oom_priority_manager.h"
65 #include "chrome/browser/metrics/field_trial_synchronizer.h"
66 #include "chrome/browser/metrics/metrics_services_manager.h"
67 #include "chrome/browser/metrics/thread_watcher.h"
68 #include "chrome/browser/metrics/variations/variations_service.h"
69 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
70 #include "chrome/browser/net/chrome_net_log.h"
71 #include "chrome/browser/net/crl_set_fetcher.h"
72 #include "chrome/browser/notifications/desktop_notification_service.h"
73 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
74 #include "chrome/browser/performance_monitor/performance_monitor.h"
75 #include "chrome/browser/plugins/plugin_prefs.h"
76 #include "chrome/browser/power/process_power_collector.h"
77 #include "chrome/browser/pref_service_flags_storage.h"
78 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
79 #include "chrome/browser/prefs/command_line_pref_store.h"
80 #include "chrome/browser/prefs/incognito_mode_prefs.h"
81 #include "chrome/browser/prefs/pref_metrics_service.h"
82 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
83 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
84 #include "chrome/browser/process_singleton.h"
85 #include "chrome/browser/profiles/profile.h"
86 #include "chrome/browser/profiles/profile_manager.h"
87 #include "chrome/browser/profiles/profiles_state.h"
88 #include "chrome/browser/shell_integration.h"
89 #include "chrome/browser/tracing/navigation_tracing.h"
90 #include "chrome/browser/translate/translate_service.h"
91 #include "chrome/browser/ui/app_list/app_list_service.h"
92 #include "chrome/browser/ui/browser.h"
93 #include "chrome/browser/ui/browser_finder.h"
94 #include "chrome/browser/ui/host_desktop.h"
95 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
96 #include "chrome/browser/ui/startup/default_browser_prompt.h"
97 #include "chrome/browser/ui/startup/startup_browser_creator.h"
98 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
99 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
100 #include "chrome/common/chrome_constants.h"
101 #include "chrome/common/chrome_paths.h"
102 #include "chrome/common/chrome_result_codes.h"
103 #include "chrome/common/chrome_switches.h"
104 #include "chrome/common/chrome_version_info.h"
105 #include "chrome/common/crash_keys.h"
106 #include "chrome/common/env_vars.h"
107 #include "chrome/common/logging_chrome.h"
108 #include "chrome/common/net/net_resource_provider.h"
109 #include "chrome/common/pref_names.h"
110 #include "chrome/common/profiling.h"
111 #include "chrome/common/variations/variations_util.h"
112 #include "chrome/grit/generated_resources.h"
113 #include "chrome/installer/util/google_update_settings.h"
114 #include "components/component_updater/component_updater_service.h"
115 #include "components/device_event_log/device_event_log.h"
116 #include "components/google/core/browser/google_util.h"
117 #include "components/language_usage_metrics/language_usage_metrics.h"
118 #include "components/metrics/call_stack_profile_metrics_provider.h"
119 #include "components/metrics/metrics_service.h"
120 #include "components/metrics/profiler/tracking_synchronizer.h"
121 #include "components/nacl/browser/nacl_browser.h"
122 #include "components/rappor/rappor_service.h"
123 #include "components/signin/core/common/profile_management_switches.h"
124 #include "components/startup_metric_utils/startup_metric_utils.h"
125 #include "components/translate/content/browser/browser_cld_utils.h"
126 #include "components/translate/content/common/cld_data_source.h"
127 #include "components/translate/core/browser/translate_download_manager.h"
128 #include "components/variations/net/variations_http_header_provider.h"
129 #include "components/variations/variations_associated_data.h"
130 #include "content/public/browser/browser_thread.h"
131 #include "content/public/browser/notification_observer.h"
132 #include "content/public/browser/notification_registrar.h"
133 #include "content/public/browser/notification_service.h"
134 #include "content/public/browser/notification_types.h"
135 #include "content/public/browser/power_usage_monitor.h"
136 #include "content/public/browser/site_instance.h"
137 #include "content/public/common/content_client.h"
138 #include "content/public/common/content_switches.h"
139 #include "content/public/common/main_function_params.h"
140 #include "grit/platform_locale_settings.h"
141 #include "media/audio/audio_manager.h"
142 #include "net/base/net_module.h"
143 #include "net/cookies/cookie_monster.h"
144 #include "net/http/http_network_layer.h"
145 #include "net/http/http_stream_factory.h"
146 #include "net/url_request/url_request.h"
147 #include "ui/base/l10n/l10n_util.h"
148 #include "ui/base/layout.h"
149 #include "ui/base/resource/resource_bundle.h"
150 #include "ui/strings/grit/app_locale_settings.h"
152 #if defined(OS_ANDROID)
153 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
154 #include "chrome/browser/metrics/thread_watcher_android.h"
155 #include "ui/base/resource/resource_bundle_android.h"
157 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
158 #include "chrome/browser/feedback/feedback_profile_observer.h"
159 #endif // defined(OS_ANDROID)
161 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
162 #include "chrome/browser/first_run/upgrade_util_linux.h"
163 #include "chrome/browser/sxs_linux.h"
164 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
166 #if defined(OS_CHROMEOS)
167 #include "chrome/browser/chromeos/settings/cros_settings.h"
168 #include "chromeos/chromeos_switches.h"
169 #include "chromeos/settings/cros_settings_names.h"
170 #endif // defined(OS_CHROMEOS)
172 // TODO(port): several win-only methods have been pulled out of this, but
173 // BrowserMain() as a whole needs to be broken apart so that it's usable by
174 // other platforms. For now, it's just a stub. This is a serious work in
175 // progress and should not be taken as an indication of a real refactoring.
178 #include "base/environment.h" // For PreRead experiment.
179 #include "base/win/windows_version.h"
180 #include "chrome/browser/browser_util_win.h"
181 #include "chrome/browser/chrome_browser_main_win.h"
182 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
183 #include "chrome/browser/component_updater/caps_installer_win.h"
184 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
185 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
186 #include "chrome/browser/first_run/upgrade_util_win.h"
187 #include "chrome/browser/ui/network_profile_bubble.h"
188 #include "chrome/installer/util/helper.h"
189 #include "chrome/installer/util/install_util.h"
190 #include "chrome/installer/util/shell_util.h"
191 #include "components/browser_watcher/exit_funnel_win.h"
192 #include "net/base/net_util.h"
193 #include "ui/base/l10n/l10n_util_win.h"
194 #include "ui/gfx/win/dpi.h"
195 #include "ui/shell_dialogs/select_file_dialog.h"
196 #endif // defined(OS_WIN)
198 #if defined(OS_MACOSX)
199 #include <Security/Security.h>
201 #include "base/mac/scoped_nsautorelease_pool.h"
202 #include "chrome/browser/mac/keystone_glue.h"
203 #endif // defined(OS_MACOSX)
206 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
207 #endif // !defined(OS_IOS)
209 #if !defined(DISABLE_NACL)
210 #include "chrome/browser/component_updater/pnacl_component_installer.h"
211 #include "components/nacl/browser/nacl_process_host.h"
212 #endif // !defined(DISABLE_NACL)
214 #if defined(ENABLE_EXTENSIONS)
215 #include "chrome/browser/extensions/startup_helper.h"
216 #include "extensions/browser/extension_protocols.h"
217 #include "extensions/common/features/feature_provider.h"
218 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
219 #endif // defined(ENABLE_EXTENSIONS)
221 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
222 #include "printing/printed_document.h"
223 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
225 #if defined(ENABLE_RLZ)
226 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
227 #include "components/rlz/rlz_tracker.h"
228 #endif // defined(ENABLE_RLZ)
230 #if defined(ENABLE_WEBRTC)
231 #include "chrome/browser/media/webrtc_log_util.h"
232 #endif // defined(ENABLE_WEBRTC)
234 #if defined(USE_AURA)
235 #include "ui/aura/env.h"
236 #endif // defined(USE_AURA)
238 using content::BrowserThread
;
242 // This function provides some ways to test crash and assertion handling
243 // behavior of the program.
244 void HandleTestParameters(const base::CommandLine
& command_line
) {
245 // This parameter causes a null pointer crash (crash reporter trigger).
246 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
247 int* bad_pointer
= NULL
;
252 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
253 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
254 const std::vector
<GURL
>& new_tabs
) {
255 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
256 it
!= new_tabs
.end(); ++it
) {
258 browser_creator
->AddFirstRunTab(*it
);
261 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
263 // Returns the new local state object, guaranteed non-NULL.
264 // |local_state_task_runner| must be a shutdown-blocking task runner.
265 PrefService
* InitializeLocalState(
266 base::SequencedTaskRunner
* local_state_task_runner
,
267 const base::CommandLine
& parsed_command_line
) {
268 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
270 // Load local state. This includes the application locale so we know which
271 // locale dll to load. This also causes local state prefs to be registered.
272 PrefService
* local_state
= g_browser_process
->local_state();
276 if (first_run::IsChromeFirstRun()) {
277 // During first run we read the google_update registry key to find what
278 // language the user selected when downloading the installer. This
279 // becomes our default language in the prefs.
280 // Other platforms obey the system locale.
281 base::string16 install_lang
;
282 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
283 local_state
->SetString(prefs::kApplicationLocale
,
284 base::UTF16ToASCII(install_lang
));
287 #endif // defined(OS_WIN)
289 // If the local state file for the current profile doesn't exist and the
290 // parent profile command line flag is present, then we should inherit some
291 // local state from the parent profile.
292 // Checking that the local state file for the current profile doesn't exist
293 // is the most robust way to determine whether we need to inherit or not
294 // since the parent profile command line flag can be present even when the
295 // current profile is not a new one, and in that case we do not want to
296 // inherit and reset the user's setting.
298 // TODO(mnissler): We should probably just instantiate a
299 // JSONPrefStore here instead of an entire PrefService. Once this is
300 // addressed, the call to browser_prefs::RegisterLocalState can move
301 // to chrome_prefs::CreateLocalState.
302 if (parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
303 base::FilePath local_state_path
;
304 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
305 bool local_state_file_exists
= base::PathExists(local_state_path
);
306 if (!local_state_file_exists
) {
307 base::FilePath parent_profile
=
308 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
309 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
310 scoped_ptr
<PrefService
> parent_local_state(
311 chrome_prefs::CreateLocalState(
313 local_state_task_runner
,
314 g_browser_process
->policy_service(),
317 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
318 // Right now, we only inherit the locale setting from the parent profile.
319 local_state
->SetString(
320 prefs::kApplicationLocale
,
321 parent_local_state
->GetString(prefs::kApplicationLocale
));
325 #if defined(OS_CHROMEOS)
326 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
327 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
328 // Ensure that we start with owner's locale.
329 if (!owner_locale
.empty() &&
330 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
331 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
332 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
335 #endif // defined(OS_CHROMEOS)
340 // Initializes the primary profile, possibly doing some user prompting to pick
341 // a fallback profile. Returns the newly created profile, or NULL if startup
342 // should not continue.
343 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
344 const base::FilePath
& user_data_dir
,
345 const base::CommandLine
& parsed_command_line
) {
346 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
348 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
350 base::Time start
= base::Time::Now();
351 if (profiles::IsMultipleProfilesEnabled() &&
352 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
353 profiles::SetLastUsedProfile(
354 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
355 // Clear kProfilesLastActive since the user only wants to launch a specific
357 ListPrefUpdate
update(g_browser_process
->local_state(),
358 prefs::kProfilesLastActive
);
359 base::ListValue
* profile_list
= update
.Get();
360 profile_list
->Clear();
363 Profile
* profile
= NULL
;
364 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
365 // On ChromeOS and Android the ProfileManager will use the same path as the
366 // one we got passed. GetActiveUserProfile will therefore use the correct path
368 DCHECK_EQ(user_data_dir
.value(),
369 g_browser_process
->profile_manager()->user_data_dir().value());
370 profile
= ProfileManager::GetActiveUserProfile();
372 base::FilePath profile_path
=
373 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
375 // Without NewAvatarMenu, replace guest with any existing profile.
376 if (!switches::IsNewAvatarMenu() &&
377 profile_path
== ProfileManager::GetGuestProfilePath()) {
378 profile_path
= g_browser_process
->profile_manager()->GetProfileInfoCache().
379 GetPathOfProfileAtIndex(0);
381 profile
= g_browser_process
->profile_manager()->GetProfile(
384 // If we're using the --new-profile-management flag and this profile is
385 // signed out, then we should show the user manager instead. By switching
386 // the active profile to the guest profile we ensure that no
387 // browser windows will be opened for the guest profile.
388 if (switches::IsNewProfileManagement() &&
390 !profile
->IsGuestSession()) {
391 ProfileInfoCache
& cache
=
392 g_browser_process
->profile_manager()->GetProfileInfoCache();
393 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
395 if (profile_index
!= std::string::npos
&&
396 cache
.ProfileIsSigninRequiredAtIndex(profile_index
)) {
397 profile
= g_browser_process
->profile_manager()->GetProfile(
398 ProfileManager::GetGuestProfilePath());
401 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
403 UMA_HISTOGRAM_LONG_TIMES(
404 "Startup.CreateFirstProfile", base::Time::Now() - start
);
409 // TODO(port): fix this. See comments near the definition of
410 // user_data_dir. It is better to CHECK-fail here than it is to
411 // silently exit because of missing code in the above test.
412 CHECK(profile
) << "Cannot get default profile.";
413 #endif // !defined(OS_WIN)
418 #if defined(OS_MACOSX)
419 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
420 SecKeychainCallbackInfo
* info
, void* context
) {
423 #endif // defined(OS_MACOSX)
425 void RegisterComponentsForUpdate() {
426 component_updater::ComponentUpdateService
* cus
=
427 g_browser_process
->component_updater();
429 // Registration can be before or after cus->Start() so it is ok to post
430 // a task to the UI thread to do registration once you done the necessary
431 // file IO to know you existing component version.
432 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
433 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
434 RegisterPepperFlashComponent(cus
);
435 RegisterSwiftShaderComponent(cus
);
436 RegisterWidevineCdmComponent(cus
);
437 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
439 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
440 #if defined(OS_CHROMEOS)
441 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
442 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
443 // installer when running on Linux. See crbug.com/422121 for more details.
444 if (!base::SysInfo::IsRunningOnChromeOS())
445 #endif // defined(OS_CHROMEOS)
446 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
447 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
449 // Registration of the CLD Component is a no-op unless the CLD data source has
450 // been configured to be the "Component" data source.
451 RegisterCldComponent(cus
);
453 component_updater::SupervisedUserWhitelistInstaller
* whitelist_installer
=
454 g_browser_process
->supervised_user_whitelist_installer();
455 whitelist_installer
->RegisterComponents();
458 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
459 #if defined(OS_ANDROID)
460 // The CRLSet component was enabled for some releases. This code attempts to
461 // delete it from the local disk of those how may have downloaded it.
462 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
463 #elif !defined(OS_CHROMEOS)
464 // CRLSetFetcher attempts to load a CRL set from either the local disk or
466 // For Chrome OS this registration is delayed until user login.
467 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
468 // Registration of the EV Whitelist component here is not necessary for:
469 // 1. Android: Because it currently does not have the EV indicator.
470 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
471 RegisterEVWhitelistComponent(cus
, path
);
472 #endif // defined(OS_ANDROID)
476 #if defined(GOOGLE_CHROME_BUILD)
477 RegisterSwReporterComponent(cus
);
478 #endif // defined(GOOGLE_CHROME_BUILD)
479 RegisterCAPSComponent(cus
);
480 #endif // defined(OS_WIN)
483 #if !defined(OS_ANDROID)
484 bool ProcessSingletonNotificationCallback(
485 const base::CommandLine
& command_line
,
486 const base::FilePath
& current_directory
) {
487 // Drop the request if the browser process is already in shutdown path.
488 if (!g_browser_process
|| g_browser_process
->IsShuttingDown()) {
490 browser_watcher::ExitFunnel::RecordSingleEvent(
491 chrome::kBrowserExitCodesRegistryPath
,
492 L
"ProcessSingletonIsShuttingDown");
493 #endif // defined(OS_WIN)
498 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
499 std::string start_time_string
=
500 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
501 int64 remote_start_time
;
502 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
503 base::TimeDelta elapsed
=
504 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
505 if (command_line
.HasSwitch(switches::kFastStart
)) {
506 UMA_HISTOGRAM_LONG_TIMES(
507 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
509 UMA_HISTOGRAM_LONG_TIMES(
510 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
515 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
518 base::FilePath user_data_dir
=
519 g_browser_process
->profile_manager()->user_data_dir();
520 base::FilePath startup_profile_dir
=
521 GetStartupProfilePath(user_data_dir
, command_line
);
523 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
524 command_line
, current_directory
, startup_profile_dir
);
527 #endif // !defined(OS_ANDROID)
529 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine
& command_line
) {
530 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
531 std::string port_str
=
532 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
534 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
535 g_browser_process
->CreateDevToolsHttpProtocolHandler(
536 chrome::HOST_DESKTOP_TYPE_NATIVE
,
538 static_cast<uint16
>(port
));
540 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
547 namespace chrome_browser
{
549 // This error message is not localized because we failed to load the
550 // localization data files.
552 const char kMissingLocaleDataTitle
[] = "Missing File Error";
553 #endif // defined(OS_WIN)
556 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
557 const char kMissingLocaleDataMessage
[] =
558 "Unable to find locale data files. Please reinstall.";
559 #endif // defined(OS_WIN)
561 } // namespace chrome_browser
563 // BrowserMainParts ------------------------------------------------------------
565 ChromeBrowserMainParts::ChromeBrowserMainParts(
566 const content::MainFunctionParams
& parameters
)
567 : parameters_(parameters
),
568 parsed_command_line_(parameters
.command_line
),
569 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
570 startup_watcher_(new StartupTimeBomb()),
571 shutdown_watcher_(new ShutdownWatcherHelper()),
572 browser_field_trials_(parameters
.command_line
),
574 run_message_loop_(true),
575 notify_result_(ProcessSingleton::PROCESS_NONE
),
577 restart_last_session_(false) {
578 // If we're running tests (ui_task is non-null).
579 if (parameters
.ui_task
)
580 browser_defaults::enable_help_app
= false;
582 // Chrome disallows cookies by default. All code paths that want to use
583 // cookies need to go through one of Chrome's URLRequestContexts which have
584 // a ChromeNetworkDelegate attached that selectively allows cookies again.
585 net::URLRequest::SetDefaultCookiePolicyToBlock();
588 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
589 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
590 delete chrome_extra_parts_
[i
];
591 chrome_extra_parts_
.clear();
594 // This will be called after the command-line has been mutated by about:flags
595 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
596 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
597 // Must initialize metrics after labs have been converted into switches,
598 // but before field trials are set up (so that client ID is available for
599 // one-time randomized field trials).
601 // Initialize FieldTrialList to support FieldTrials that use one-time
603 metrics::MetricsService
* metrics
= browser_process_
->metrics_service();
604 field_trial_list_
.reset(
605 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
607 const base::CommandLine
* command_line
=
608 base::CommandLine::ForCurrentProcess();
609 if (command_line
->HasSwitch(switches::kEnableBenchmarking
) ||
610 command_line
->HasSwitch(cc::switches::kEnableGpuBenchmarking
)) {
611 base::FieldTrial::EnableBenchmarking();
614 if (command_line
->HasSwitch(switches::kForceFieldTrialParams
)) {
615 bool result
= chrome_variations::AssociateParamsFromString(
616 command_line
->GetSwitchValueASCII(switches::kForceFieldTrialParams
));
617 CHECK(result
) << "Invalid --" << switches::kForceFieldTrialParams
618 << " list specified.";
621 // Ensure any field trials specified on the command line are initialized.
622 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
623 std::set
<std::string
> unforceable_field_trials
;
624 #if defined(OFFICIAL_BUILD)
625 unforceable_field_trials
.insert("SettingsEnforcement");
626 #endif // defined(OFFICIAL_BUILD)
628 // Create field trials without activating them, so that this behaves in a
629 // consistent manner with field trials created from the server.
630 bool result
= base::FieldTrialList::CreateTrialsFromString(
631 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
632 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
633 unforceable_field_trials
);
634 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
635 << " list specified.";
638 #if !defined(GOOGLE_CHROME_BUILD)
639 if (!command_line
->HasSwitch(switches::kDisableFieldTrialTestingConfig
) &&
640 !command_line
->HasSwitch(switches::kForceFieldTrials
) &&
641 !command_line
->HasSwitch(switches::kVariationsServerURL
))
642 chrome_variations::AssociateDefaultFieldTrialConfig();
643 #endif // !defined(GOOGLE_CHROME_BUILD)
645 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
646 // Create default variation ids which will always be included in the
647 // X-Client-Data request header.
648 variations::VariationsHttpHeaderProvider
* provider
=
649 variations::VariationsHttpHeaderProvider::GetInstance();
650 bool result
= provider
->SetDefaultVariationIds(
651 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
652 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
653 << " list specified.";
654 metrics
->AddSyntheticTrialObserver(provider
);
656 chrome_variations::VariationsService
* variations_service
=
657 browser_process_
->variations_service();
658 if (variations_service
)
659 variations_service
->CreateTrialsFromSeed();
661 // This must be called after |local_state_| is initialized.
662 browser_field_trials_
.SetupFieldTrials();
664 // Enable Navigation Tracing only if a trace upload url is specified.
665 if (command_line
->HasSwitch(switches::kEnableNavigationTracing
) &&
666 command_line
->HasSwitch(switches::kTraceUploadURL
)) {
667 tracing::SetupNavigationTracing();
670 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
671 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
672 // Even though base::Bind does AddRef and Release, the object will not be
673 // deleted after the Task is executed.
674 field_trial_synchronizer_
= new FieldTrialSynchronizer();
676 // Now that field trials have been created, initializes metrics recording.
677 metrics
->InitializeMetricsRecordingState();
679 const chrome::VersionInfo::Channel channel
=
680 chrome::VersionInfo::GetChannel();
682 // TODO(dalecurtis): Remove these checks and enable for all channels once we
683 // track down the root causes of crbug.com/422522 and crbug.com/478932.
684 if (channel
== chrome::VersionInfo::CHANNEL_UNKNOWN
||
685 channel
== chrome::VersionInfo::CHANNEL_CANARY
||
686 channel
== chrome::VersionInfo::CHANNEL_DEV
) {
687 media::AudioManager::EnableHangMonitor();
690 // Enable profiler instrumentation depending on the channel.
692 case chrome::VersionInfo::CHANNEL_UNKNOWN
:
693 case chrome::VersionInfo::CHANNEL_CANARY
:
694 tracked_objects::ScopedTracker::Enable();
697 case chrome::VersionInfo::CHANNEL_DEV
:
698 case chrome::VersionInfo::CHANNEL_BETA
:
699 case chrome::VersionInfo::CHANNEL_STABLE
:
700 // Don't enable instrumentation.
705 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
707 void ChromeBrowserMainParts::StartMetricsRecording() {
708 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
710 g_browser_process
->metrics_service()->CheckForClonedInstall(
711 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
713 g_browser_process
->GetMetricsServicesManager()->UpdateUploadPermissions(true);
716 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
717 // Don't record any metrics if UI was displayed before this point e.g.
719 if (startup_metric_utils::WasNonBrowserUIDisplayed())
722 #if defined(OS_ANDROID)
723 // On Android the first run is handled in Java code, and the C++ side of
724 // Chrome doesn't know if this is the first run. This will cause some
725 // inaccuracy in the UMA statistics, but this should be minor (first runs are
727 bool is_first_run
= false;
729 bool is_first_run
= first_run::IsChromeFirstRun();
730 #endif // defined(OS_ANDROID)
732 // CurrentProcessInfo::CreationTime() is currently only implemented on some
734 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
735 const base::Time process_creation_time
=
736 base::CurrentProcessInfo::CreationTime();
738 if (!is_first_run
&& !process_creation_time
.is_null()) {
739 base::TimeDelta delay
= base::Time::Now() - process_creation_time
;
740 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay
);
742 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
744 // Record collected startup metrics.
745 startup_metric_utils::OnBrowserStartupComplete(is_first_run
);
748 // -----------------------------------------------------------------------------
749 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
752 #define DLLEXPORT __declspec(dllexport)
754 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
756 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
759 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
760 // Need an instance of AtExitManager to handle singleton creations and
761 // deletions. We need this new instance because, the old instance created
762 // in ChromeMain() got destructed when the function returned.
763 base::AtExitManager exit_manager
;
764 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
768 // content::BrowserMainParts implementation ------------------------------------
770 void ChromeBrowserMainParts::PreEarlyInitialization() {
771 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
772 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
773 chrome_extra_parts_
[i
]->PreEarlyInitialization();
776 void ChromeBrowserMainParts::PostEarlyInitialization() {
777 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
778 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
779 chrome_extra_parts_
[i
]->PostEarlyInitialization();
782 void ChromeBrowserMainParts::ToolkitInitialized() {
783 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
784 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
785 chrome_extra_parts_
[i
]->ToolkitInitialized();
788 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
789 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
791 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
792 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
795 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
796 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
798 // device_event_log must be initialized after the message loop. Calls to
799 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
800 // platforms (e.g. chromeos) may have already initialized this.
801 if (!device_event_log::IsInitialized())
802 device_event_log::Initialize(0 /* default max entries */);
804 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
805 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
808 int ChromeBrowserMainParts::PreCreateThreads() {
809 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
810 result_code_
= PreCreateThreadsImpl();
812 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
813 #if !defined(OS_ANDROID)
814 // These members must be initialized before exiting this function normally.
815 DCHECK(master_prefs_
.get());
816 DCHECK(browser_creator_
.get());
817 #endif // !defined(OS_ANDROID)
818 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
819 chrome_extra_parts_
[i
]->PreCreateThreads();
825 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
826 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
827 run_message_loop_
= false;
828 #if !defined(OS_ANDROID)
829 chrome::MaybeShowInvalidUserDataDirWarningDialog();
830 #endif // !defined(OS_ANDROID)
831 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
832 return chrome::RESULT_CODE_MISSING_DATA
;
834 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
835 MediaCaptureDevicesDispatcher::GetInstance();
837 // Android's first run is done in Java instead of native.
838 #if !defined(OS_ANDROID)
839 process_singleton_
.reset(new ChromeProcessSingleton(
840 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
842 // Cache first run state early.
843 first_run::IsChromeFirstRun();
844 #endif // !defined(OS_ANDROID)
846 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
847 JsonPrefStore::GetTaskRunnerForFile(
848 base::FilePath(chrome::kLocalStorePoolName
),
849 BrowserThread::GetBlockingPool());
852 TRACE_EVENT0("startup",
853 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
854 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
855 parsed_command_line()));
858 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
859 TRACE_EVENT0("startup",
860 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
861 // User wants to override default tracking status.
863 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
864 // Default to basic profiling (no parent child support).
865 tracked_objects::ThreadData::Status status
=
866 tracked_objects::ThreadData::PROFILING_ACTIVE
;
867 if (flag
.compare("0") != 0)
868 status
= tracked_objects::ThreadData::DEACTIVATED
;
869 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
872 local_state_
= InitializeLocalState(
873 local_state_task_runner
.get(), parsed_command_line());
875 #if !defined(OS_ANDROID)
876 // These members must be initialized before returning from this function.
877 master_prefs_
.reset(new first_run::MasterPrefs
);
878 // Android doesn't use StartupBrowserCreator.
879 browser_creator_
.reset(new StartupBrowserCreator
);
880 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
881 chrome::UMABrowsingActivityObserver::Init();
882 #endif // !defined(OS_ANDROID)
884 #if !defined(OS_CHROMEOS)
885 // Convert active labs into switches. This needs to be done before
886 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
887 // affected by experiment flags (--touch-optimized-ui in particular).
888 // On ChromeOS system level flags are applied from the device settings from
889 // the session manager.
891 TRACE_EVENT0("startup",
892 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
893 about_flags::PrefServiceFlagsStorage
flags_storage_(
894 g_browser_process
->local_state());
895 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
896 base::CommandLine::ForCurrentProcess(),
897 about_flags::kAddSentinels
);
899 #endif // !defined(OS_CHROMEOS)
901 local_state_
->UpdateCommandLinePrefStore(
902 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
904 // Reset the command line in the crash report details, since we may have
905 // just changed it to include experiments.
906 crash_keys::SetSwitchesFromCommandLine(
907 base::CommandLine::ForCurrentProcess());
909 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
910 // needed when loading the MainMenu.nib and the language doesn't depend on
911 // anything since it comes from Cocoa.
912 #if defined(OS_MACOSX)
914 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
915 browser_process_
->SetApplicationLocale(locale
);
917 const std::string locale
=
918 local_state_
->GetString(prefs::kApplicationLocale
);
920 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
921 // method InitSharedInstance is ignored.
923 TRACE_EVENT_BEGIN0("startup",
924 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
925 const std::string loaded_locale
=
926 ui::ResourceBundle::InitSharedInstanceWithLocale(
927 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
928 TRACE_EVENT_END0("startup",
929 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
931 if (loaded_locale
.empty() &&
932 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
933 ShowMissingLocaleMessageBox();
934 return chrome::RESULT_CODE_MISSING_DATA
;
936 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
937 browser_process_
->SetApplicationLocale(loaded_locale
);
940 TRACE_EVENT0("startup",
941 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
942 base::FilePath resources_pack_path
;
943 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
944 #if defined(OS_ANDROID)
945 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path
);
947 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
948 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
949 #endif // defined(OS_ANDROID)
951 #endif // defined(OS_MACOSX)
953 // Android does first run in Java instead of native.
954 // Chrome OS has its own out-of-box-experience code.
955 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
956 // On first run, we need to process the predictor preferences before the
957 // browser's profile_manager object is created, but after ResourceBundle
959 if (first_run::IsChromeFirstRun()) {
960 first_run::ProcessMasterPreferencesResult pmp_result
=
961 first_run::ProcessMasterPreferences(user_data_dir_
,
962 master_prefs_
.get());
963 if (pmp_result
== first_run::EULA_EXIT_NOW
)
964 return chrome::RESULT_CODE_EULA_REFUSED
;
966 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
967 !parsed_command_line().HasSwitch(switches::kAppId
) &&
968 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
969 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
972 // TODO(macourteau): refactor preferences that are copied from
973 // master_preferences into local_state, as a "local_state" section in
974 // master preferences. If possible, a generic solution would be preferred
975 // over a copy one-by-one of specific preferences. Also see related TODO
978 // Store the initial VariationsService seed in local state, if it exists
980 if (!master_prefs_
->variations_seed
.empty() ||
981 !master_prefs_
->compressed_variations_seed
.empty()) {
982 if (!master_prefs_
->variations_seed
.empty()) {
983 local_state_
->SetString(prefs::kVariationsSeed
,
984 master_prefs_
->variations_seed
);
986 if (!master_prefs_
->compressed_variations_seed
.empty()) {
987 local_state_
->SetString(prefs::kVariationsCompressedSeed
,
988 master_prefs_
->compressed_variations_seed
);
990 if (!master_prefs_
->variations_seed_signature
.empty()) {
991 local_state_
->SetString(prefs::kVariationsSeedSignature
,
992 master_prefs_
->variations_seed_signature
);
994 // Set the variation seed date to the current system time. If the user's
995 // clock is incorrect, this may cause some field trial expiry checks to
996 // not do the right thing until the next seed update from the server,
997 // when this value will be updated.
998 local_state_
->SetInt64(prefs::kVariationsSeedDate
,
999 base::Time::Now().ToInternalValue());
1002 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
1003 local_state_
->SetString(
1004 prefs::kBrowserSuppressDefaultBrowserPrompt
,
1005 master_prefs_
->suppress_default_browser_prompt_for_version
);
1009 if (!master_prefs_
->welcome_page_on_os_upgrade_enabled
)
1010 local_state_
->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled
, false);
1013 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1015 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1016 // Set the product channel for crash reports.
1017 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
1018 chrome::VersionInfo::GetVersionStringModifier());
1019 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1021 // Initialize tracking synchronizer system.
1022 tracking_synchronizer_
= new metrics::TrackingSynchronizer(
1023 make_scoped_ptr(new base::DefaultTickClock()));
1025 #if defined(OS_MACOSX)
1026 // Get the Keychain API to register for distributed notifications on the main
1027 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1028 // which doesn't. This ensures those notifications will get delivered
1029 // properly. See issue 37766.
1030 // (Note that the callback mask here is empty. I don't want to register for
1031 // any callbacks, I just want to initialize the mechanism.)
1032 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
1033 #endif // defined(OS_MACOSX)
1035 #if defined(OS_CHROMEOS)
1036 // Must be done after g_browser_process is constructed, before
1037 // SetupMetricsAndFieldTrials().
1038 chromeos::CrosSettings::Initialize();
1039 #endif // defined(OS_CHROMEOS)
1041 // Now the command line has been mutated based on about:flags, we can setup
1042 // metrics and initialize field trials. The field trials are needed by
1043 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1044 SetupMetricsAndFieldTrials();
1046 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1047 browser_process_
->PreCreateThreads();
1049 return content::RESULT_CODE_NORMAL_EXIT
;
1052 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1053 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1054 TRACK_SCOPED_REGION(
1055 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1057 result_code_
= PreMainMessageLoopRunImpl();
1059 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1060 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
1063 // PreMainMessageLoopRun calls these extra stages in the following order:
1064 // PreMainMessageLoopRunImpl()
1065 // ... initial setup, including browser_process_ setup.
1067 // ... additional setup, including CreateProfile()
1068 // PostProfileInit()
1069 // ... additional setup
1070 // PreBrowserStart()
1071 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1072 // PostBrowserStart()
1074 void ChromeBrowserMainParts::PreProfileInit() {
1075 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1077 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1078 chrome_extra_parts_
[i
]->PreProfileInit();
1080 #if !defined(OS_ANDROID)
1081 // Initialize the feedback uploader so it can setup notifications for profile
1083 feedback::FeedbackProfileObserver::Initialize();
1085 // Ephemeral profiles may have been left behind if the browser crashed.
1086 g_browser_process
->profile_manager()->CleanUpEphemeralProfiles();
1087 #endif // !defined(OS_ANDROID)
1089 #if defined(ENABLE_EXTENSIONS)
1090 javascript_dialog_extensions_client::InstallClient();
1091 #endif // defined(ENABLE_EXTENSIONS)
1093 #if !defined(OS_IOS)
1094 InstallChromeJavaScriptNativeDialogFactory();
1095 #endif // !defined(OS_IOS)
1098 void ChromeBrowserMainParts::PostProfileInit() {
1099 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1101 #if defined(OS_ANDROID)
1102 DevToolsDiscoveryProviderAndroid::Install();
1104 ChromeDevToolsDiscoveryProvider::Install();
1105 #endif // defined(OS_ANDROID)
1107 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1108 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1109 chrome_extra_parts_
[i
]->PostProfileInit();
1112 void ChromeBrowserMainParts::PreBrowserStart() {
1113 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1114 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1115 chrome_extra_parts_
[i
]->PreBrowserStart();
1117 three_d_observer_
.reset(new ThreeDAPIObserver());
1119 // Start the out-of-memory priority manager here so that we give the most
1120 // amount of time for the other services to start up before we start
1121 // adjusting the oom priority.
1123 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1125 #if defined(OS_CHROMEOS)
1126 g_browser_process
->GetOomPriorityManager()->Start();
1127 #elif defined(OS_WIN) || defined(OS_MACOSX)
1128 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding
))
1129 g_browser_process
->GetOomPriorityManager()->Start();
1133 void ChromeBrowserMainParts::PostBrowserStart() {
1134 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1135 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1136 chrome_extra_parts_
[i
]->PostBrowserStart();
1137 #if !defined(OS_ANDROID)
1138 // Allow ProcessSingleton to process messages.
1139 process_singleton_
->Unlock();
1140 #endif // !defined(OS_ANDROID)
1141 #if defined(ENABLE_WEBRTC)
1142 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1143 // to reduce the impact on startup time.
1144 BrowserThread::PostDelayedTask(
1147 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1148 base::TimeDelta::FromMinutes(1));
1149 #endif // defined(ENABLE_WEBRTC)
1151 // At this point, StartupBrowserCreator::Start has run creating initial
1152 // browser windows and tabs, but no progress has been made in loading
1153 // content as the main message loop hasn't started processing tasks yet.
1154 // We setup to observe to the initial page load here to defer running
1155 // task posted via PostAfterStartupTask until its complete.
1156 AfterStartupTaskUtils::StartMonitoringStartup();
1159 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1160 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1161 TRACK_SCOPED_REGION(
1162 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1164 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1165 const base::TimeTicks start_time_step1
= base::TimeTicks::Now();
1168 // Windows parental controls calls can be slow, so we do an early init here
1169 // that calculates this value off of the UI thread.
1170 IncognitoModePrefs::InitializePlatformParentalControls();
1173 #if defined(ENABLE_EXTENSIONS)
1174 if (!variations::GetVariationParamValue(
1175 "LightSpeed", "EarlyInitStartup").empty()) {
1176 // Try to compute this early on another thread so that we don't spend time
1177 // during profile load initializing the extensions APIs.
1178 BrowserThread::PostTask(
1179 BrowserThread::FILE_USER_BLOCKING
,
1182 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures
)));
1186 // Android updates the metrics service dynamically depending on whether the
1187 // application is in the foreground or not. Do not start here.
1188 #if !defined(OS_ANDROID)
1189 // Now that the file thread has been started, start recording.
1190 StartMetricsRecording();
1191 #endif // !defined(OS_ANDROID)
1193 if (!base::debug::BeingDebugged()) {
1194 // Create watchdog thread after creating all other threads because it will
1195 // watch the other threads and they must be running.
1196 browser_process_
->watchdog_thread();
1199 // Do any initializating in the browser process that requires all threads
1201 browser_process_
->PreMainMessageLoopRun();
1203 // Record last shutdown time into a histogram.
1204 browser_shutdown::ReadLastShutdownInfo();
1207 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1208 // tasks. Those care whether the browser is already running. On Linux/Mac,
1209 // upgrade/uninstall happen separately.
1210 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1212 // If the command line specifies 'uninstall' then we need to work here
1213 // unless we detect another chrome browser running.
1214 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1215 return DoUninstallTasks(already_running
);
1218 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1219 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1220 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1221 parsed_command_line_
);
1224 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1225 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1226 #endif // defined(OS_WIN)
1228 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1229 bool is_managed
= g_browser_process
->local_state()->IsManagedPreference(
1230 prefs::kDefaultBrowserSettingEnabled
);
1231 if (is_managed
&& !g_browser_process
->local_state()->GetBoolean(
1232 prefs::kDefaultBrowserSettingEnabled
)) {
1233 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY
);
1236 return ShellIntegration::SetAsDefaultBrowser() ?
1237 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1238 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1241 #if defined(USE_AURA)
1242 // Make sure aura::Env has been initialized.
1243 CHECK(aura::Env::GetInstance());
1244 #endif // defined(USE_AURA)
1246 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1247 #if !defined(OS_ANDROID)
1248 // If the command line specifies --pack-extension, attempt the pack extension
1249 // startup action and exit.
1250 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1251 extensions::StartupHelper extension_startup_helper
;
1252 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1253 return content::RESULT_CODE_NORMAL_EXIT
;
1254 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1257 // When another process is running, use that process instead of starting a
1258 // new one. NotifyOtherProcess will currently give the other process up to
1259 // 20 seconds to respond. Note that this needs to be done before we attempt
1260 // to read the profile.
1261 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1262 switch (notify_result_
) {
1263 case ProcessSingleton::PROCESS_NONE
:
1264 // No process already running, fall through to starting a new one.
1267 case ProcessSingleton::PROCESS_NOTIFIED
:
1268 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1269 // On POSIX systems, print a message notifying the process is running.
1270 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1271 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1272 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1274 // Having a differentiated return type for testing allows for tests to
1275 // verify proper handling of some switches. When not testing, stick to
1276 // the standard Unix convention of returning zero when things went as
1278 if (parsed_command_line().HasSwitch(switches::kTestType
))
1279 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1280 return content::RESULT_CODE_NORMAL_EXIT
;
1282 case ProcessSingleton::PROFILE_IN_USE
:
1283 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1285 case ProcessSingleton::LOCK_ERROR
:
1286 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1287 "directory. This means that running multiple instances "
1288 "would start multiple browser processes rather than "
1289 "opening a new window in the existing process. Aborting "
1290 "now to avoid profile corruption.";
1291 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1296 #endif // !defined(OS_ANDROID)
1298 // Handle special early return paths (which couldn't be processed even earlier
1299 // as they require the process singleton to be held) first.
1301 std::string try_chrome
=
1302 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1303 if (!try_chrome
.empty()) {
1305 // Setup.exe has determined that we need to run a retention experiment
1306 // and has lauched chrome to show the experiment UI. It is guaranteed that
1307 // no other Chrome is currently running as the process singleton was
1308 // sucessfully grabbed above.
1310 base::StringToInt(try_chrome
, &try_chrome_int
);
1311 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1313 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1314 base::Unretained(process_singleton_
.get())));
1315 if (answer
== TryChromeDialogView::NOT_NOW
)
1316 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1317 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1318 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1319 // At this point the user is willing to try chrome again.
1320 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1321 // Only set in the unattended case, the interactive case is Windows 8.
1322 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1323 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1324 ShellIntegration::SetAsDefaultBrowser();
1327 // We don't support retention experiments on Mac or Linux.
1328 return content::RESULT_CODE_NORMAL_EXIT
;
1329 #endif // defined(OS_WIN)
1333 // Do the tasks if chrome has been upgraded while it was last running.
1334 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1335 return content::RESULT_CODE_NORMAL_EXIT
;
1337 // Check if there is any machine level Chrome installed on the current
1338 // machine. If yes and the current Chrome process is user level, we do not
1339 // allow the user level Chrome to run. So we notify the user and uninstall
1340 // user level Chrome.
1341 // Note this check needs to happen here (after the process singleton was
1342 // obtained but before potentially creating the first run sentinel).
1343 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1344 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1345 #endif // defined(OS_WIN)
1347 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1348 if (sxs_linux::ShouldMigrateUserDataDir())
1349 return sxs_linux::MigrateUserDataDir();
1350 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1352 // Desktop construction occurs here, (required before profile creation).
1355 // Profile creation ----------------------------------------------------------
1357 metrics::MetricsService::SetExecutionPhase(
1358 metrics::MetricsService::CREATE_PROFILE
,
1359 g_browser_process
->local_state());
1361 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1362 base::TimeTicks::Now() - start_time_step1
);
1364 // This step is costly and is already measured in Startup.CreateFirstProfile
1365 // and more directly Profile.CreateAndInitializeProfile.
1366 profile_
= CreatePrimaryProfile(parameters(),
1368 parsed_command_line());
1370 return content::RESULT_CODE_NORMAL_EXIT
;
1372 #if !defined(OS_ANDROID)
1373 const base::TimeTicks start_time_step2
= base::TimeTicks::Now();
1374 // The first run sentinel must be created after the process singleton was
1375 // grabbed and no early return paths were otherwise hit above.
1376 first_run::CreateSentinelIfNeeded();
1377 #endif // !defined(OS_ANDROID)
1379 #if defined(ENABLE_BACKGROUND)
1380 // Autoload any profiles which are running background apps.
1381 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1382 browser_process_
->profile_manager()->AutoloadProfiles();
1383 #endif // defined(ENABLE_BACKGROUND)
1384 // Post-profile init ---------------------------------------------------------
1386 TranslateService::Initialize();
1388 // Needs to be done before PostProfileInit, since login manager on CrOS is
1389 // called inside PostProfileInit.
1390 content::WebUIControllerFactory::RegisterFactory(
1391 ChromeWebUIControllerFactory::GetInstance());
1393 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1394 // So make sure to create it before that.
1395 #if !defined(DISABLE_NACL)
1396 NaClBrowserDelegateImpl
* delegate
=
1397 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1398 nacl::NaClBrowser::SetDelegate(delegate
);
1399 #endif // !defined(DISABLE_NACL)
1401 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1402 // (requires supporting early exit).
1405 // Retrieve cached GL strings from local state and use them for GPU
1406 // blacklist decisions.
1407 if (g_browser_process
->gl_string_manager())
1408 g_browser_process
->gl_string_manager()->Initialize();
1410 // Create an instance of GpuModeManager to watch gpu mode pref change.
1411 g_browser_process
->gpu_mode_manager();
1413 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1414 // Show the First Run UI if this is the first time Chrome has been run on
1415 // this computer, or we're being compelled to do so by a command line flag.
1416 // Note that this be done _after_ the PrefService is initialized and all
1417 // preferences are registered, since some of the code that the importer
1418 // touches reads preferences.
1419 if (first_run::IsChromeFirstRun()) {
1420 first_run::AutoImport(profile_
,
1421 master_prefs_
->homepage_defined
,
1422 master_prefs_
->do_import_items
,
1423 master_prefs_
->dont_import_items
,
1424 master_prefs_
->import_bookmarks_path
);
1426 // Note: this can pop the first run consent dialog on linux.
1427 first_run::DoPostImportTasks(profile_
,
1428 master_prefs_
->make_chrome_default_for_user
);
1430 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1431 browser_creator_
->set_show_main_browser_window(
1432 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1434 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1437 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1440 // Sets things up so that if we crash from this point on, a dialog will
1441 // popup asking the user to restart chrome. It is done this late to avoid
1442 // testing against a bunch of special cases that are taken care early on.
1443 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1444 parsed_command_line());
1446 // Registers Chrome with the Windows Restart Manager, which will restore the
1447 // Chrome session when the computer is restarted after a system update.
1448 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1449 // but should run on startup if extended to handle crashes/hangs/patches.
1450 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1451 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1452 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1453 parsed_command_line());
1456 // Verify that the profile is not on a network share and if so prepare to show
1457 // notification to the user.
1458 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1459 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1460 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1461 profile_
->GetPath()));
1463 #endif // defined(OS_WIN)
1465 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1466 // Init the RLZ library. This just binds the dll and schedules a task on the
1467 // file thread to be run sometime later. If this is the first run we record
1468 // the installation event.
1469 PrefService
* pref_service
= profile_
->GetPrefs();
1470 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1471 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1472 // Negative ping delay means to send ping immediately after a first search is
1474 rlz::RLZTracker::SetRlzDelegate(
1475 make_scoped_ptr(new ChromeRLZTrackerDelegate
));
1476 rlz::RLZTracker::InitRlzDelayed(
1477 first_run::IsChromeFirstRun(), ping_delay
< 0,
1478 base::TimeDelta::FromMilliseconds(abs(ping_delay
)),
1479 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_
),
1480 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_
),
1481 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_
));
1482 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1484 // Configure modules that need access to resources.
1485 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1487 // In unittest mode, this will do nothing. In normal mode, this will create
1488 // the global IntranetRedirectDetector instance, which will promptly go to
1489 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1490 // to see if it should do anything else.
1492 // A simpler way of doing all this would be to have some function which could
1493 // give the time elapsed since startup, and simply have this object check that
1494 // when asked to initialize itself, but this doesn't seem to exist.
1496 // This can't be created in the BrowserProcessImpl constructor because it
1497 // needs to read prefs that get set after that runs.
1498 browser_process_
->intranet_redirect_detector();
1499 GoogleSearchCounter::RegisterForNotifications();
1501 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1502 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1503 base::FilePath path
=
1504 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1505 printing::PrintedDocument::set_debug_dump_path(path
);
1507 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1509 HandleTestParameters(parsed_command_line());
1510 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1511 base::debug::BeingDebugged());
1513 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1514 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1515 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1516 browser_process_
->GetApplicationLocale());
1518 // Start watching for hangs during startup. We disarm this hang detector when
1519 // ThreadWatcher takes over or when browser is shutdown or when
1520 // startup_watcher_ is deleted.
1521 metrics::MetricsService::SetExecutionPhase(
1522 metrics::MetricsService::STARTUP_TIMEBOMB_ARM
,
1523 g_browser_process
->local_state());
1524 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(600));
1526 // On mobile, need for clean shutdown arises only when the application comes
1527 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1528 // http://crbug.com/179143
1529 #if !defined(OS_ANDROID)
1530 // Start watching for a hang.
1531 browser_process_
->metrics_service()->LogNeedForCleanShutdown();
1532 #endif // !defined(OS_ANDROID)
1534 #if defined(ENABLE_PRINT_PREVIEW)
1535 // Create the instance of the cloud print proxy service so that it can launch
1536 // the service process if needed. This is needed because the service process
1537 // might have shutdown because an update was available.
1538 // TODO(torne): this should maybe be done with
1539 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1541 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1542 #endif // defined(ENABLE_PRINT_PREVIEW)
1544 // Start watching all browser threads for responsiveness.
1545 metrics::MetricsService::SetExecutionPhase(
1546 metrics::MetricsService::THREAD_WATCHER_START
,
1547 g_browser_process
->local_state());
1548 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1550 #if defined(OS_ANDROID)
1551 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1552 #endif // defined(OS_ANDROID)
1554 #if !defined(DISABLE_NACL)
1555 BrowserThread::PostTask(
1558 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1559 #endif // !defined(DISABLE_NACL)
1561 // Make sure initial prefs are recorded
1562 PrefMetricsService::Factory::GetForProfile(profile_
);
1566 // Instantiate the notification UI manager, as this triggers a perf timer
1567 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1568 // triggering the timer and call that explicitly in the approprate place.
1569 // http://crbug.com/105065.
1570 browser_process_
->notification_ui_manager();
1572 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1573 // data source is based on the Component Updater.
1574 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1576 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1577 RegisterComponentsForUpdate();
1579 #if defined(OS_ANDROID)
1580 chrome_variations::VariationsService
* variations_service
=
1581 browser_process_
->variations_service();
1582 if (variations_service
) {
1583 // Just initialize the policy prefs service here. Variations seed fetching
1584 // will be initialized when the app enters foreground mode.
1585 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1587 translate::TranslateDownloadManager::RequestLanguageList(
1588 profile_
->GetPrefs());
1591 // Most general initialization is behind us, but opening a
1592 // tab and/or session restore and such is still to be done.
1593 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1595 // We are in regular browser boot sequence. Open initial tabs and enter the
1596 // main message loop.
1597 #if defined(OS_CHROMEOS)
1598 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1599 // them this early as the cryptohome hasn't yet been mounted (which happens
1600 // only once we log in.
1601 std::vector
<Profile
*> last_opened_profiles
;
1603 std::vector
<Profile
*> last_opened_profiles
=
1604 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1605 #endif // defined(OS_CHROMEOS)
1607 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1608 base::TimeTicks::Now() - start_time_step2
);
1610 // This step is costly and is already measured in
1611 // Startup.StartupBrowserCreator_Start.
1612 bool started
= browser_creator_
->Start(
1613 parsed_command_line(), base::FilePath(), profile_
, last_opened_profiles
);
1614 const base::TimeTicks start_time_step3
= base::TimeTicks::Now();
1616 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1617 // Initialize autoupdate timer. Timer callback costs basically nothing
1618 // when browser is not in persistent mode, so it's OK to let it ride on
1619 // the main thread. This needs to be done here because we don't want
1620 // to start the timer when Chrome is run inside a test harness.
1621 browser_process_
->StartAutoupdateTimer();
1622 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1624 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1625 // On Linux, the running exe will be updated if an upgrade becomes
1626 // available while the browser is running. We need to save the last
1627 // modified time of the exe, so we can compare to determine if there is
1628 // an upgrade while the browser is kept alive by a persistent extension.
1629 upgrade_util::SaveLastModifiedTimeOfExe();
1630 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1632 // Record now as the last successful chrome start.
1633 GoogleUpdateSettings::SetLastRunTime();
1635 #if defined(OS_MACOSX)
1636 // Call Recycle() here as late as possible, before going into the loop
1637 // because Start() will add things to it while creating the main window.
1638 if (parameters().autorelease_pool
)
1639 parameters().autorelease_pool
->Recycle();
1640 #endif // defined(OS_MACOSX)
1642 base::TimeDelta delay
= base::TimeTicks::Now() - browser_open_start
;
1643 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay
);
1645 // If we're running tests (ui_task is non-null), then we don't want to
1646 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1647 // RequestLanguageList
1648 if (parameters().ui_task
== NULL
) {
1649 // Request new variations seed information from server.
1650 chrome_variations::VariationsService
* variations_service
=
1651 browser_process_
->variations_service();
1652 if (variations_service
) {
1653 variations_service
->StartRepeatedVariationsSeedFetch();
1656 variations_service
->StartGoogleUpdateRegistrySync();
1657 #endif // defined(OS_WIN)
1660 translate::TranslateDownloadManager::RequestLanguageList(
1661 profile_
->GetPrefs());
1664 run_message_loop_
= true;
1666 run_message_loop_
= false;
1668 browser_creator_
.reset();
1670 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1671 if (g_browser_process
->metrics_service()->reporting_active())
1672 content::StartPowerUsageMonitor();
1673 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1675 process_power_collector_
.reset(new ProcessPowerCollector
);
1676 process_power_collector_
->Initialize();
1677 #endif // !defined(OS_ANDROID)
1681 if (parameters().ui_task
) {
1682 parameters().ui_task
->Run();
1683 delete parameters().ui_task
;
1684 run_message_loop_
= false;
1686 #if defined(OS_ANDROID)
1687 // We never run the C++ main loop on Android, since the UI thread message
1688 // loop is controlled by the OS, so this is as close as we can get to
1689 // the start of the main loop.
1690 if (result_code_
<= 0) {
1691 RecordBrowserStartupTime();
1693 #endif // defined(OS_ANDROID)
1695 #if !defined(OS_ANDROID)
1696 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1697 base::TimeTicks::Now() - start_time_step3
);
1698 #endif // !defined(OS_ANDROID)
1700 return result_code_
;
1703 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1704 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1705 #if defined(OS_ANDROID)
1706 // Chrome on Android does not use default MessageLoop. It has its own
1707 // Android specific MessageLoop
1711 // Set the result code set in PreMainMessageLoopRun or set above.
1712 *result_code
= result_code_
;
1713 if (!run_message_loop_
)
1714 return true; // Don't run the default message loop.
1716 // These should be invoked as close to the start of the browser's
1717 // UI thread message loop as possible to get a stable measurement
1719 RecordBrowserStartupTime();
1721 DCHECK(base::MessageLoopForUI::IsCurrent());
1722 base::RunLoop run_loop
;
1724 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1726 metrics::MetricsService::SetExecutionPhase(
1727 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1728 g_browser_process
->local_state());
1732 #endif // defined(OS_ANDROID)
1735 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1736 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1737 #if defined(OS_ANDROID)
1738 // Chrome on Android does not use default MessageLoop. It has its own
1739 // Android specific MessageLoop
1742 // Start watching for jank during shutdown. It gets disarmed when
1743 // |shutdown_watcher_| object is destructed.
1744 metrics::MetricsService::SetExecutionPhase(
1745 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1746 g_browser_process
->local_state());
1747 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1749 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1750 startup_watcher_
->Disarm();
1752 // Remove observers attached to D-Bus clients before DbusThreadManager is
1754 process_power_collector_
.reset();
1756 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1757 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1759 // Some tests don't set parameters.ui_task, so they started translate
1760 // language fetch that was never completed so we need to cleanup here
1761 // otherwise it will be done by the destructor in a wrong thread.
1762 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1764 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1765 process_singleton_
->Cleanup();
1767 // Stop all tasks that might run on WatchDogThread.
1768 ThreadWatcherList::StopWatchingAll();
1770 browser_process_
->metrics_service()->Stop();
1772 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1773 browser_process_
->StartTearDown();
1774 #endif // defined(OS_ANDROID)
1777 void ChromeBrowserMainParts::PostDestroyThreads() {
1778 #if defined(OS_ANDROID)
1779 // On Android, there is no quit/exit. So the browser's main message loop will
1783 browser_process_
->PostDestroyThreads();
1784 // browser_shutdown takes care of deleting browser_process, so we need to
1786 ignore_result(browser_process_
.release());
1787 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1788 master_prefs_
.reset();
1789 process_singleton_
.reset();
1790 device_event_log::Shutdown();
1792 // We need to do this check as late as possible, but due to modularity, this
1793 // may be the last point in Chrome. This would be more effective if done at
1794 // a higher level on the stack, so that it is impossible for an early return
1795 // to bypass this code. Perhaps we need a *final* hook that is called on all
1796 // paths from content/browser/browser_main.
1797 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1799 #if defined(OS_CHROMEOS)
1800 chromeos::CrosSettings::Shutdown();
1801 #endif // defined(OS_CHROMEOS)
1802 #endif // defined(OS_ANDROID)
1807 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1808 chrome_extra_parts_
.push_back(parts
);