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/crl_set_fetcher.h"
69 #include "chrome/browser/performance_monitor/performance_monitor.h"
70 #include "chrome/browser/plugins/plugin_prefs.h"
71 #include "chrome/browser/power/process_power_collector.h"
72 #include "chrome/browser/pref_service_flags_storage.h"
73 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
74 #include "chrome/browser/prefs/command_line_pref_store.h"
75 #include "chrome/browser/prefs/incognito_mode_prefs.h"
76 #include "chrome/browser/prefs/pref_metrics_service.h"
77 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
78 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
79 #include "chrome/browser/process_singleton.h"
80 #include "chrome/browser/profiles/profile.h"
81 #include "chrome/browser/profiles/profile_manager.h"
82 #include "chrome/browser/profiles/profiles_state.h"
83 #include "chrome/browser/shell_integration.h"
84 #include "chrome/browser/tracing/navigation_tracing.h"
85 #include "chrome/browser/translate/translate_service.h"
86 #include "chrome/browser/ui/app_list/app_list_service.h"
87 #include "chrome/browser/ui/browser.h"
88 #include "chrome/browser/ui/browser_finder.h"
89 #include "chrome/browser/ui/host_desktop.h"
90 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
91 #include "chrome/browser/ui/startup/default_browser_prompt.h"
92 #include "chrome/browser/ui/startup/startup_browser_creator.h"
93 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
94 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
95 #include "chrome/common/channel_info.h"
96 #include "chrome/common/chrome_constants.h"
97 #include "chrome/common/chrome_paths.h"
98 #include "chrome/common/chrome_result_codes.h"
99 #include "chrome/common/chrome_switches.h"
100 #include "chrome/common/crash_keys.h"
101 #include "chrome/common/env_vars.h"
102 #include "chrome/common/logging_chrome.h"
103 #include "chrome/common/media/media_resource_provider.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 "media/base/media_resources.h"
144 #include "net/base/net_module.h"
145 #include "net/cookies/cookie_monster.h"
146 #include "net/http/http_network_layer.h"
147 #include "net/http/http_stream_factory.h"
148 #include "net/url_request/url_request.h"
149 #include "ui/base/l10n/l10n_util.h"
150 #include "ui/base/layout.h"
151 #include "ui/base/resource/resource_bundle.h"
152 #include "ui/strings/grit/app_locale_settings.h"
154 #if defined(OS_ANDROID)
155 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
156 #include "chrome/browser/metrics/thread_watcher_android.h"
157 #include "ui/base/resource/resource_bundle_android.h"
159 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
160 #include "chrome/browser/feedback/feedback_profile_observer.h"
161 #endif // defined(OS_ANDROID)
163 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
164 #include "chrome/browser/first_run/upgrade_util_linux.h"
165 #include "chrome/browser/sxs_linux.h"
166 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
168 #if defined(OS_CHROMEOS)
169 #include "chrome/browser/chromeos/settings/cros_settings.h"
170 #include "chromeos/chromeos_switches.h"
171 #include "chromeos/settings/cros_settings_names.h"
172 #endif // defined(OS_CHROMEOS)
174 // TODO(port): several win-only methods have been pulled out of this, but
175 // BrowserMain() as a whole needs to be broken apart so that it's usable by
176 // other platforms. For now, it's just a stub. This is a serious work in
177 // progress and should not be taken as an indication of a real refactoring.
180 #include "base/environment.h" // For PreRead experiment.
181 #include "base/trace_event/trace_event_etw_export_win.h"
182 #include "base/win/windows_version.h"
183 #include "chrome/browser/browser_util_win.h"
184 #include "chrome/browser/chrome_browser_main_win.h"
185 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
186 #include "chrome/browser/component_updater/caps_installer_win.h"
187 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
188 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
189 #include "chrome/browser/first_run/upgrade_util_win.h"
190 #include "chrome/browser/ui/network_profile_bubble.h"
191 #include "chrome/installer/util/helper.h"
192 #include "chrome/installer/util/install_util.h"
193 #include "chrome/installer/util/shell_util.h"
194 #include "components/browser_watcher/exit_funnel_win.h"
195 #include "net/base/net_util.h"
196 #include "ui/base/l10n/l10n_util_win.h"
197 #include "ui/gfx/win/dpi.h"
198 #include "ui/shell_dialogs/select_file_dialog.h"
199 #endif // defined(OS_WIN)
201 #if defined(OS_MACOSX)
202 #include <Security/Security.h>
204 #include "base/mac/scoped_nsautorelease_pool.h"
205 #include "chrome/browser/mac/keystone_glue.h"
206 #endif // defined(OS_MACOSX)
209 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
210 #endif // !defined(OS_IOS)
212 #if !defined(DISABLE_NACL)
213 #include "chrome/browser/component_updater/pnacl_component_installer.h"
214 #include "components/nacl/browser/nacl_process_host.h"
215 #endif // !defined(DISABLE_NACL)
217 #if defined(ENABLE_EXTENSIONS)
218 #include "chrome/browser/extensions/startup_helper.h"
219 #include "extensions/browser/extension_protocols.h"
220 #include "extensions/common/features/feature_provider.h"
221 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
222 #endif // defined(ENABLE_EXTENSIONS)
224 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
225 #include "printing/printed_document.h"
226 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
228 #if defined(ENABLE_RLZ)
229 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
230 #include "components/rlz/rlz_tracker.h"
231 #endif // defined(ENABLE_RLZ)
233 #if defined(ENABLE_WEBRTC)
234 #include "chrome/browser/media/webrtc_log_util.h"
235 #endif // defined(ENABLE_WEBRTC)
237 #if defined(USE_AURA)
238 #include "ui/aura/env.h"
239 #endif // defined(USE_AURA)
241 #if !defined(OS_ANDROID) && !defined(OS_IOS)
242 #include "chrome/browser/chrome_webusb_browser_client.h"
243 #include "components/webusb/webusb_detector.h"
246 using content::BrowserThread
;
250 // This function provides some ways to test crash and assertion handling
251 // behavior of the program.
252 void HandleTestParameters(const base::CommandLine
& command_line
) {
253 // This parameter causes a null pointer crash (crash reporter trigger).
254 if (command_line
.HasSwitch(switches::kBrowserCrashTest
)) {
255 int* bad_pointer
= NULL
;
260 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
261 void AddFirstRunNewTabs(StartupBrowserCreator
* browser_creator
,
262 const std::vector
<GURL
>& new_tabs
) {
263 for (std::vector
<GURL
>::const_iterator it
= new_tabs
.begin();
264 it
!= new_tabs
.end(); ++it
) {
266 browser_creator
->AddFirstRunTab(*it
);
269 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
271 // Returns the new local state object, guaranteed non-NULL.
272 // |local_state_task_runner| must be a shutdown-blocking task runner.
273 PrefService
* InitializeLocalState(
274 base::SequencedTaskRunner
* local_state_task_runner
,
275 const base::CommandLine
& parsed_command_line
) {
276 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
278 // Load local state. This includes the application locale so we know which
279 // locale dll to load. This also causes local state prefs to be registered.
280 PrefService
* local_state
= g_browser_process
->local_state();
284 if (first_run::IsChromeFirstRun()) {
285 // During first run we read the google_update registry key to find what
286 // language the user selected when downloading the installer. This
287 // becomes our default language in the prefs.
288 // Other platforms obey the system locale.
289 base::string16 install_lang
;
290 if (GoogleUpdateSettings::GetLanguage(&install_lang
)) {
291 local_state
->SetString(prefs::kApplicationLocale
,
292 base::UTF16ToASCII(install_lang
));
295 #endif // defined(OS_WIN)
297 // If the local state file for the current profile doesn't exist and the
298 // parent profile command line flag is present, then we should inherit some
299 // local state from the parent profile.
300 // Checking that the local state file for the current profile doesn't exist
301 // is the most robust way to determine whether we need to inherit or not
302 // since the parent profile command line flag can be present even when the
303 // current profile is not a new one, and in that case we do not want to
304 // inherit and reset the user's setting.
306 // TODO(mnissler): We should probably just instantiate a
307 // JSONPrefStore here instead of an entire PrefService. Once this is
308 // addressed, the call to browser_prefs::RegisterLocalState can move
309 // to chrome_prefs::CreateLocalState.
310 if (parsed_command_line
.HasSwitch(switches::kParentProfile
)) {
311 base::FilePath local_state_path
;
312 PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
);
313 bool local_state_file_exists
= base::PathExists(local_state_path
);
314 if (!local_state_file_exists
) {
315 base::FilePath parent_profile
=
316 parsed_command_line
.GetSwitchValuePath(switches::kParentProfile
);
317 scoped_refptr
<PrefRegistrySimple
> registry
= new PrefRegistrySimple();
318 scoped_ptr
<PrefService
> parent_local_state(
319 chrome_prefs::CreateLocalState(
321 local_state_task_runner
,
322 g_browser_process
->policy_service(),
325 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
326 // Right now, we only inherit the locale setting from the parent profile.
327 local_state
->SetString(
328 prefs::kApplicationLocale
,
329 parent_local_state
->GetString(prefs::kApplicationLocale
));
333 #if defined(OS_CHROMEOS)
334 if (parsed_command_line
.HasSwitch(chromeos::switches::kLoginManager
)) {
335 std::string owner_locale
= local_state
->GetString(prefs::kOwnerLocale
);
336 // Ensure that we start with owner's locale.
337 if (!owner_locale
.empty() &&
338 local_state
->GetString(prefs::kApplicationLocale
) != owner_locale
&&
339 !local_state
->IsManagedPreference(prefs::kApplicationLocale
)) {
340 local_state
->SetString(prefs::kApplicationLocale
, owner_locale
);
343 #endif // defined(OS_CHROMEOS)
348 // Initializes the primary profile, possibly doing some user prompting to pick
349 // a fallback profile. Returns the newly created profile, or NULL if startup
350 // should not continue.
351 Profile
* CreatePrimaryProfile(const content::MainFunctionParams
& parameters
,
352 const base::FilePath
& user_data_dir
,
353 const base::CommandLine
& parsed_command_line
) {
354 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
356 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
358 base::Time start
= base::Time::Now();
359 if (profiles::IsMultipleProfilesEnabled() &&
360 parsed_command_line
.HasSwitch(switches::kProfileDirectory
)) {
361 profiles::SetLastUsedProfile(
362 parsed_command_line
.GetSwitchValueASCII(switches::kProfileDirectory
));
363 // Clear kProfilesLastActive since the user only wants to launch a specific
365 ListPrefUpdate
update(g_browser_process
->local_state(),
366 prefs::kProfilesLastActive
);
367 base::ListValue
* profile_list
= update
.Get();
368 profile_list
->Clear();
371 Profile
* profile
= NULL
;
372 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
373 // On ChromeOS and Android the ProfileManager will use the same path as the
374 // one we got passed. GetActiveUserProfile will therefore use the correct path
376 DCHECK_EQ(user_data_dir
.value(),
377 g_browser_process
->profile_manager()->user_data_dir().value());
378 profile
= ProfileManager::GetActiveUserProfile();
380 base::FilePath profile_path
=
381 GetStartupProfilePath(user_data_dir
, parsed_command_line
);
383 // Without NewAvatarMenu, replace guest with any existing profile.
384 if (!switches::IsNewAvatarMenu() &&
385 profile_path
== ProfileManager::GetGuestProfilePath()) {
386 profile_path
= g_browser_process
->profile_manager()->GetProfileInfoCache().
387 GetPathOfProfileAtIndex(0);
389 profile
= g_browser_process
->profile_manager()->GetProfile(
392 // If we're using the --new-profile-management flag and this profile is
393 // signed out, then we should show the user manager instead. By switching
394 // the active profile to the guest profile we ensure that no
395 // browser windows will be opened for the guest profile.
396 if (switches::IsNewProfileManagement() &&
398 !profile
->IsGuestSession()) {
399 ProfileInfoCache
& cache
=
400 g_browser_process
->profile_manager()->GetProfileInfoCache();
401 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile_path
);
403 if (profile_index
!= std::string::npos
&&
404 cache
.ProfileIsSigninRequiredAtIndex(profile_index
)) {
405 profile
= g_browser_process
->profile_manager()->GetProfile(
406 ProfileManager::GetGuestProfilePath());
409 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
411 UMA_HISTOGRAM_LONG_TIMES(
412 "Startup.CreateFirstProfile", base::Time::Now() - start
);
417 // TODO(port): fix this. See comments near the definition of
418 // user_data_dir. It is better to CHECK-fail here than it is to
419 // silently exit because of missing code in the above test.
420 CHECK(profile
) << "Cannot get default profile.";
421 #endif // !defined(OS_WIN)
426 #if defined(OS_MACOSX)
427 OSStatus
KeychainCallback(SecKeychainEvent keychain_event
,
428 SecKeychainCallbackInfo
* info
, void* context
) {
431 #endif // defined(OS_MACOSX)
433 void RegisterComponentsForUpdate() {
434 component_updater::ComponentUpdateService
* cus
=
435 g_browser_process
->component_updater();
437 // Registration can be before or after cus->Start() so it is ok to post
438 // a task to the UI thread to do registration once you done the necessary
439 // file IO to know you existing component version.
440 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
441 RegisterRecoveryComponent(cus
, g_browser_process
->local_state());
442 RegisterPepperFlashComponent(cus
);
443 RegisterSwiftShaderComponent(cus
);
444 RegisterWidevineCdmComponent(cus
);
445 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
447 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
448 #if defined(OS_CHROMEOS)
449 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
450 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
451 // installer when running on Linux. See crbug.com/422121 for more details.
452 if (!base::SysInfo::IsRunningOnChromeOS())
453 #endif // defined(OS_CHROMEOS)
454 g_browser_process
->pnacl_component_installer()->RegisterPnaclComponent(cus
);
455 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
457 // Registration of the CLD Component is a no-op unless the CLD data source has
458 // been configured to be the "Component" data source.
459 RegisterCldComponent(cus
);
461 component_updater::SupervisedUserWhitelistInstaller
* whitelist_installer
=
462 g_browser_process
->supervised_user_whitelist_installer();
463 whitelist_installer
->RegisterComponents();
466 if (PathService::Get(chrome::DIR_USER_DATA
, &path
)) {
467 #if defined(OS_ANDROID)
468 // The CRLSet component was enabled for some releases. This code attempts to
469 // delete it from the local disk of those how may have downloaded it.
470 g_browser_process
->crl_set_fetcher()->DeleteFromDisk(path
);
471 #elif !defined(OS_CHROMEOS)
472 // CRLSetFetcher attempts to load a CRL set from either the local disk or
474 // For Chrome OS this registration is delayed until user login.
475 g_browser_process
->crl_set_fetcher()->StartInitialLoad(cus
, path
);
476 // Registration of the EV Whitelist component here is not necessary for:
477 // 1. Android: Because it currently does not have the EV indicator.
478 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
479 RegisterEVWhitelistComponent(cus
, path
);
480 #endif // defined(OS_ANDROID)
484 #if defined(GOOGLE_CHROME_BUILD)
485 RegisterSwReporterComponent(cus
);
486 #endif // defined(GOOGLE_CHROME_BUILD)
487 RegisterCAPSComponent(cus
);
488 #endif // defined(OS_WIN)
491 #if !defined(OS_ANDROID)
492 bool ProcessSingletonNotificationCallback(
493 const base::CommandLine
& command_line
,
494 const base::FilePath
& current_directory
) {
495 // Drop the request if the browser process is already in shutdown path.
496 if (!g_browser_process
|| g_browser_process
->IsShuttingDown()) {
498 browser_watcher::ExitFunnel::RecordSingleEvent(
499 chrome::kBrowserExitCodesRegistryPath
,
500 L
"ProcessSingletonIsShuttingDown");
501 #endif // defined(OS_WIN)
506 if (command_line
.HasSwitch(switches::kOriginalProcessStartTime
)) {
507 std::string start_time_string
=
508 command_line
.GetSwitchValueASCII(switches::kOriginalProcessStartTime
);
509 int64 remote_start_time
;
510 if (base::StringToInt64(start_time_string
, &remote_start_time
)) {
511 base::TimeDelta elapsed
=
512 base::Time::Now() - base::Time::FromInternalValue(remote_start_time
);
513 if (command_line
.HasSwitch(switches::kFastStart
)) {
514 UMA_HISTOGRAM_LONG_TIMES(
515 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed
);
517 UMA_HISTOGRAM_LONG_TIMES(
518 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed
);
523 g_browser_process
->platform_part()->PlatformSpecificCommandLineProcessing(
526 base::FilePath user_data_dir
=
527 g_browser_process
->profile_manager()->user_data_dir();
528 base::FilePath startup_profile_dir
=
529 GetStartupProfilePath(user_data_dir
, command_line
);
531 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
532 command_line
, current_directory
, startup_profile_dir
);
535 #endif // !defined(OS_ANDROID)
537 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine
& command_line
) {
538 if (command_line
.HasSwitch(::switches::kRemoteDebuggingPort
)) {
539 std::string port_str
=
540 command_line
.GetSwitchValueASCII(::switches::kRemoteDebuggingPort
);
542 if (base::StringToInt(port_str
, &port
) && port
>= 0 && port
< 65535) {
543 g_browser_process
->CreateDevToolsHttpProtocolHandler(
544 chrome::HOST_DESKTOP_TYPE_NATIVE
,
546 static_cast<uint16
>(port
));
548 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
555 namespace chrome_browser
{
557 // This error message is not localized because we failed to load the
558 // localization data files.
560 const char kMissingLocaleDataTitle
[] = "Missing File Error";
561 #endif // defined(OS_WIN)
564 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
565 const char kMissingLocaleDataMessage
[] =
566 "Unable to find locale data files. Please reinstall.";
567 #endif // defined(OS_WIN)
569 } // namespace chrome_browser
571 // BrowserMainParts ------------------------------------------------------------
573 ChromeBrowserMainParts::ChromeBrowserMainParts(
574 const content::MainFunctionParams
& parameters
)
575 : parameters_(parameters
),
576 parsed_command_line_(parameters
.command_line
),
577 result_code_(content::RESULT_CODE_NORMAL_EXIT
),
578 startup_watcher_(new StartupTimeBomb()),
579 shutdown_watcher_(new ShutdownWatcherHelper()),
580 browser_field_trials_(parameters
.command_line
),
582 base::PlatformThread::CurrentId(),
583 sampling_profiler_config_
.GetSamplingParams(),
584 metrics::CallStackProfileMetricsProvider::GetProfilerCallback(
585 metrics::CallStackProfileMetricsProvider::Params(
586 metrics::CallStackProfileMetricsProvider::PROCESS_STARTUP
,
589 run_message_loop_(true),
590 notify_result_(ProcessSingleton::PROCESS_NONE
),
592 restart_last_session_(false) {
593 if (sampling_profiler_config_
.IsProfilerEnabled())
594 sampling_profiler_
.Start();
596 // If we're running tests (ui_task is non-null).
597 if (parameters
.ui_task
)
598 browser_defaults::enable_help_app
= false;
600 // Chrome disallows cookies by default. All code paths that want to use
601 // cookies need to go through one of Chrome's URLRequestContexts which have
602 // a ChromeNetworkDelegate attached that selectively allows cookies again.
603 net::URLRequest::SetDefaultCookiePolicyToBlock();
606 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
607 for (int i
= static_cast<int>(chrome_extra_parts_
.size())-1; i
>= 0; --i
)
608 delete chrome_extra_parts_
[i
];
609 chrome_extra_parts_
.clear();
612 // This will be called after the command-line has been mutated by about:flags
613 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
614 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
615 // Must initialize metrics after labs have been converted into switches,
616 // but before field trials are set up (so that client ID is available for
617 // one-time randomized field trials).
619 // Initialize FieldTrialList to support FieldTrials that use one-time
621 metrics::MetricsService
* metrics
= browser_process_
->metrics_service();
622 field_trial_list_
.reset(
623 new base::FieldTrialList(metrics
->CreateEntropyProvider().release()));
625 const base::CommandLine
* command_line
=
626 base::CommandLine::ForCurrentProcess();
627 if (command_line
->HasSwitch(switches::kEnableBenchmarking
) ||
628 command_line
->HasSwitch(cc::switches::kEnableGpuBenchmarking
)) {
629 base::FieldTrial::EnableBenchmarking();
632 if (command_line
->HasSwitch(switches::kForceFieldTrialParams
)) {
633 bool result
= chrome_variations::AssociateParamsFromString(
634 command_line
->GetSwitchValueASCII(switches::kForceFieldTrialParams
));
635 CHECK(result
) << "Invalid --" << switches::kForceFieldTrialParams
636 << " list specified.";
639 // Ensure any field trials specified on the command line are initialized.
640 if (command_line
->HasSwitch(switches::kForceFieldTrials
)) {
641 std::set
<std::string
> unforceable_field_trials
;
642 #if defined(OFFICIAL_BUILD)
643 unforceable_field_trials
.insert("SettingsEnforcement");
644 #endif // defined(OFFICIAL_BUILD)
646 // Create field trials without activating them, so that this behaves in a
647 // consistent manner with field trials created from the server.
648 bool result
= base::FieldTrialList::CreateTrialsFromString(
649 command_line
->GetSwitchValueASCII(switches::kForceFieldTrials
),
650 base::FieldTrialList::DONT_ACTIVATE_TRIALS
,
651 unforceable_field_trials
);
652 CHECK(result
) << "Invalid --" << switches::kForceFieldTrials
653 << " list specified.";
656 #if defined(FIELDTRIAL_TESTING_ENABLED)
657 if (!command_line
->HasSwitch(switches::kDisableFieldTrialTestingConfig
) &&
658 !command_line
->HasSwitch(switches::kForceFieldTrials
) &&
659 !command_line
->HasSwitch(variations::switches::kVariationsServerURL
))
660 chrome_variations::AssociateDefaultFieldTrialConfig();
661 #endif // defined(FIELDTRIAL_TESTING_ENABLED)
663 if (command_line
->HasSwitch(switches::kForceVariationIds
)) {
664 // Create default variation ids which will always be included in the
665 // X-Client-Data request header.
666 variations::VariationsHttpHeaderProvider
* provider
=
667 variations::VariationsHttpHeaderProvider::GetInstance();
668 bool result
= provider
->SetDefaultVariationIds(
669 command_line
->GetSwitchValueASCII(switches::kForceVariationIds
));
670 CHECK(result
) << "Invalid --" << switches::kForceVariationIds
671 << " list specified.";
672 metrics
->AddSyntheticTrialObserver(provider
);
675 scoped_ptr
<base::FeatureList
> feature_list(new base::FeatureList
);
676 feature_list
->InitializeFromCommandLine(
677 command_line
->GetSwitchValueASCII(switches::kEnableFeatures
),
678 command_line
->GetSwitchValueASCII(switches::kDisableFeatures
));
680 variations::VariationsService
* variations_service
=
681 browser_process_
->variations_service();
682 if (variations_service
)
683 variations_service
->CreateTrialsFromSeed();
685 // TODO(asvitkine): Pass |feature_list| to CreateTrialsFromSeed() above.
686 base::FeatureList::SetInstance(feature_list
.Pass());
688 // This must be called after |local_state_| is initialized.
689 browser_field_trials_
.SetupFieldTrials();
691 // Enable Navigation Tracing only if a trace upload url is specified.
692 if (command_line
->HasSwitch(switches::kEnableNavigationTracing
) &&
693 command_line
->HasSwitch(switches::kTraceUploadURL
)) {
694 tracing::SetupNavigationTracing();
697 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
698 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
699 // Even though base::Bind does AddRef and Release, the object will not be
700 // deleted after the Task is executed.
701 field_trial_synchronizer_
= new FieldTrialSynchronizer();
703 // Now that field trials have been created, initializes metrics recording.
704 metrics
->InitializeMetricsRecordingState();
706 const version_info::Channel channel
= chrome::GetChannel();
708 // TODO(dalecurtis): Remove these checks and enable for all channels once we
709 // track down the root causes of crbug.com/422522 and crbug.com/478932.
710 if (channel
== version_info::Channel::UNKNOWN
||
711 channel
== version_info::Channel::CANARY
||
712 channel
== version_info::Channel::DEV
) {
713 media::AudioManager::EnableHangMonitor();
716 // Enable profiler instrumentation depending on the channel.
718 case version_info::Channel::UNKNOWN
:
719 case version_info::Channel::CANARY
:
720 tracked_objects::ScopedTracker::Enable();
723 case version_info::Channel::DEV
:
724 case version_info::Channel::BETA
:
725 case version_info::Channel::STABLE
:
726 // Don't enable instrumentation.
730 // Register a synthetic field trial for the sampling profiler configuration
731 // that was already chosen.
732 sampling_profiler_config_
.RegisterSyntheticFieldTrial();
735 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
737 void ChromeBrowserMainParts::StartMetricsRecording() {
738 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
740 g_browser_process
->metrics_service()->CheckForClonedInstall(
741 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
743 g_browser_process
->GetMetricsServicesManager()->UpdateUploadPermissions(true);
746 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
747 // Don't record any metrics if UI was displayed before this point e.g.
749 if (startup_metric_utils::WasNonBrowserUIDisplayed())
752 bool is_first_run
= false;
753 #if !defined(OS_ANDROID)
754 // On Android, first run is handled in Java code, and the C++ side of Chrome
755 // doesn't know if this is the first run. This will cause some inaccuracy in
756 // the UMA statistics, but this should be minor (first runs are rare).
757 is_first_run
= first_run::IsChromeFirstRun();
758 #endif // defined(OS_ANDROID)
760 // Record collected startup metrics.
761 startup_metric_utils::RecordBrowserMainMessageLoopStart(base::Time::Now(),
765 // -----------------------------------------------------------------------------
766 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
769 #define DLLEXPORT __declspec(dllexport)
771 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
773 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded();
776 DLLEXPORT
void __cdecl
RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
777 // Need an instance of AtExitManager to handle singleton creations and
778 // deletions. We need this new instance because, the old instance created
779 // in ChromeMain() got destructed when the function returned.
780 base::AtExitManager exit_manager
;
781 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
785 // content::BrowserMainParts implementation ------------------------------------
787 void ChromeBrowserMainParts::PreEarlyInitialization() {
788 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
789 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
790 chrome_extra_parts_
[i
]->PreEarlyInitialization();
793 void ChromeBrowserMainParts::PostEarlyInitialization() {
794 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
795 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
796 chrome_extra_parts_
[i
]->PostEarlyInitialization();
799 void ChromeBrowserMainParts::ToolkitInitialized() {
800 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
801 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
802 chrome_extra_parts_
[i
]->ToolkitInitialized();
805 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
806 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
808 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
809 chrome_extra_parts_
[i
]->PreMainMessageLoopStart();
812 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
813 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
815 // device_event_log must be initialized after the message loop. Calls to
816 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
817 // platforms (e.g. chromeos) may have already initialized this.
818 if (!device_event_log::IsInitialized())
819 device_event_log::Initialize(0 /* default max entries */);
821 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
822 chrome_extra_parts_
[i
]->PostMainMessageLoopStart();
825 int ChromeBrowserMainParts::PreCreateThreads() {
826 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
827 result_code_
= PreCreateThreadsImpl();
829 if (result_code_
== content::RESULT_CODE_NORMAL_EXIT
) {
830 #if !defined(OS_ANDROID)
831 // These members must be initialized before exiting this function normally.
832 DCHECK(master_prefs_
.get());
833 DCHECK(browser_creator_
.get());
834 #endif // !defined(OS_ANDROID)
835 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
836 chrome_extra_parts_
[i
]->PreCreateThreads();
842 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
843 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
844 run_message_loop_
= false;
845 #if !defined(OS_ANDROID)
846 chrome::MaybeShowInvalidUserDataDirWarningDialog();
847 #endif // !defined(OS_ANDROID)
848 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir_
))
849 return chrome::RESULT_CODE_MISSING_DATA
;
851 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
852 MediaCaptureDevicesDispatcher::GetInstance();
854 // Android's first run is done in Java instead of native.
855 #if !defined(OS_ANDROID)
856 process_singleton_
.reset(new ChromeProcessSingleton(
857 user_data_dir_
, base::Bind(&ProcessSingletonNotificationCallback
)));
859 // Cache first run state early.
860 first_run::IsChromeFirstRun();
861 #endif // !defined(OS_ANDROID)
863 scoped_refptr
<base::SequencedTaskRunner
> local_state_task_runner
=
864 JsonPrefStore::GetTaskRunnerForFile(
865 base::FilePath(chrome::kLocalStorePoolName
),
866 BrowserThread::GetBlockingPool());
869 TRACE_EVENT0("startup",
870 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
871 browser_process_
.reset(new BrowserProcessImpl(local_state_task_runner
.get(),
872 parsed_command_line()));
875 if (parsed_command_line().HasSwitch(switches::kEnableProfiling
)) {
876 TRACE_EVENT0("startup",
877 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
878 // User wants to override default tracking status.
880 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling
);
881 // Default to basic profiling (no parent child support).
882 tracked_objects::ThreadData::Status status
=
883 tracked_objects::ThreadData::PROFILING_ACTIVE
;
884 if (flag
.compare("0") != 0)
885 status
= tracked_objects::ThreadData::DEACTIVATED
;
886 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status
);
889 local_state_
= InitializeLocalState(
890 local_state_task_runner
.get(), parsed_command_line());
892 #if !defined(OS_ANDROID)
893 // These members must be initialized before returning from this function.
894 master_prefs_
.reset(new first_run::MasterPrefs
);
895 // Android doesn't use StartupBrowserCreator.
896 browser_creator_
.reset(new StartupBrowserCreator
);
897 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
898 chrome::UMABrowsingActivityObserver::Init();
899 #endif // !defined(OS_ANDROID)
901 #if !defined(OS_CHROMEOS)
902 // Convert active labs into switches. This needs to be done before
903 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
904 // affected by experiment flags (--touch-optimized-ui in particular).
905 // On ChromeOS system level flags are applied from the device settings from
906 // the session manager.
908 TRACE_EVENT0("startup",
909 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
910 about_flags::PrefServiceFlagsStorage
flags_storage_(
911 g_browser_process
->local_state());
912 about_flags::ConvertFlagsToSwitches(&flags_storage_
,
913 base::CommandLine::ForCurrentProcess(),
914 about_flags::kAddSentinels
);
916 #endif // !defined(OS_CHROMEOS)
919 // This is needed to enable ETW exporting when requested in about:flags.
920 // Normally, we enable it in ContentMainRunnerImpl::Initialize when the flag
921 // is present on the command line but flags in about:flags are converted only
922 // after this function runs. Note that this starts exporting later which
923 // affects tracing the browser startup. Also, this is only relevant for the
924 // browser process, as other processes will get all the flags on their command
925 // line regardless of the origin (command line or about:flags).
926 if (parsed_command_line().HasSwitch(switches::kTraceExportEventsToETW
))
927 base::trace_event::TraceEventETWExport::EnableETWExport();
930 local_state_
->UpdateCommandLinePrefStore(
931 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
933 // Reset the command line in the crash report details, since we may have
934 // just changed it to include experiments.
935 crash_keys::SetSwitchesFromCommandLine(
936 base::CommandLine::ForCurrentProcess());
938 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
939 // needed when loading the MainMenu.nib and the language doesn't depend on
940 // anything since it comes from Cocoa.
941 #if defined(OS_MACOSX)
943 parameters().ui_task
? "en-US" : l10n_util::GetLocaleOverride();
944 browser_process_
->SetApplicationLocale(locale
);
946 const std::string locale
=
947 local_state_
->GetString(prefs::kApplicationLocale
);
949 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
950 // method InitSharedInstance is ignored.
952 TRACE_EVENT_BEGIN0("startup",
953 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
954 const std::string loaded_locale
=
955 ui::ResourceBundle::InitSharedInstanceWithLocale(
956 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
957 TRACE_EVENT_END0("startup",
958 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
960 if (loaded_locale
.empty() &&
961 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs
)) {
962 ShowMissingLocaleMessageBox();
963 return chrome::RESULT_CODE_MISSING_DATA
;
965 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " << locale
;
966 browser_process_
->SetApplicationLocale(loaded_locale
);
969 TRACE_EVENT0("startup",
970 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
971 base::FilePath resources_pack_path
;
972 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
973 #if defined(OS_ANDROID)
974 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path
);
976 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
977 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
978 #endif // defined(OS_ANDROID)
980 #endif // defined(OS_MACOSX)
982 // Android does first run in Java instead of native.
983 // Chrome OS has its own out-of-box-experience code.
984 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
985 // On first run, we need to process the predictor preferences before the
986 // browser's profile_manager object is created, but after ResourceBundle
988 if (first_run::IsChromeFirstRun()) {
989 first_run::ProcessMasterPreferencesResult pmp_result
=
990 first_run::ProcessMasterPreferences(user_data_dir_
,
991 master_prefs_
.get());
992 if (pmp_result
== first_run::EULA_EXIT_NOW
)
993 return chrome::RESULT_CODE_EULA_REFUSED
;
995 if (!parsed_command_line().HasSwitch(switches::kApp
) &&
996 !parsed_command_line().HasSwitch(switches::kAppId
) &&
997 !parsed_command_line().HasSwitch(switches::kShowAppList
)) {
998 AddFirstRunNewTabs(browser_creator_
.get(), master_prefs_
->new_tabs
);
1001 // TODO(macourteau): refactor preferences that are copied from
1002 // master_preferences into local_state, as a "local_state" section in
1003 // master preferences. If possible, a generic solution would be preferred
1004 // over a copy one-by-one of specific preferences. Also see related TODO
1007 // Store the initial VariationsService seed in local state, if it exists
1009 if (!master_prefs_
->variations_seed
.empty() ||
1010 !master_prefs_
->compressed_variations_seed
.empty()) {
1011 if (!master_prefs_
->variations_seed
.empty()) {
1012 local_state_
->SetString(variations::prefs::kVariationsSeed
,
1013 master_prefs_
->variations_seed
);
1015 if (!master_prefs_
->compressed_variations_seed
.empty()) {
1016 local_state_
->SetString(variations::prefs::kVariationsCompressedSeed
,
1017 master_prefs_
->compressed_variations_seed
);
1019 if (!master_prefs_
->variations_seed_signature
.empty()) {
1020 local_state_
->SetString(variations::prefs::kVariationsSeedSignature
,
1021 master_prefs_
->variations_seed_signature
);
1023 // Set the variation seed date to the current system time. If the user's
1024 // clock is incorrect, this may cause some field trial expiry checks to
1025 // not do the right thing until the next seed update from the server,
1026 // when this value will be updated.
1027 local_state_
->SetInt64(variations::prefs::kVariationsSeedDate
,
1028 base::Time::Now().ToInternalValue());
1031 if (!master_prefs_
->suppress_default_browser_prompt_for_version
.empty()) {
1032 local_state_
->SetString(
1033 prefs::kBrowserSuppressDefaultBrowserPrompt
,
1034 master_prefs_
->suppress_default_browser_prompt_for_version
);
1038 if (!master_prefs_
->welcome_page_on_os_upgrade_enabled
)
1039 local_state_
->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled
, false);
1042 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1044 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1045 // Set the product channel for crash reports.
1046 base::debug::SetCrashKeyValue(crash_keys::kChannel
,
1047 chrome::GetChannelString());
1048 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1050 // Initialize tracking synchronizer system.
1051 tracking_synchronizer_
= new metrics::TrackingSynchronizer(
1052 make_scoped_ptr(new base::DefaultTickClock()));
1054 #if defined(OS_MACOSX)
1055 // Get the Keychain API to register for distributed notifications on the main
1056 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1057 // which doesn't. This ensures those notifications will get delivered
1058 // properly. See issue 37766.
1059 // (Note that the callback mask here is empty. I don't want to register for
1060 // any callbacks, I just want to initialize the mechanism.)
1061 SecKeychainAddCallback(&KeychainCallback
, 0, NULL
);
1062 #endif // defined(OS_MACOSX)
1064 #if defined(OS_CHROMEOS)
1065 // Must be done after g_browser_process is constructed, before
1066 // SetupMetricsAndFieldTrials().
1067 chromeos::CrosSettings::Initialize();
1068 #endif // defined(OS_CHROMEOS)
1070 // Now the command line has been mutated based on about:flags, we can setup
1071 // metrics and initialize field trials. The field trials are needed by
1072 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1073 SetupMetricsAndFieldTrials();
1075 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1076 browser_process_
->PreCreateThreads();
1078 return content::RESULT_CODE_NORMAL_EXIT
;
1081 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1082 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1083 TRACK_SCOPED_REGION(
1084 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1086 result_code_
= PreMainMessageLoopRunImpl();
1088 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1089 chrome_extra_parts_
[i
]->PreMainMessageLoopRun();
1092 // PreMainMessageLoopRun calls these extra stages in the following order:
1093 // PreMainMessageLoopRunImpl()
1094 // ... initial setup, including browser_process_ setup.
1096 // ... additional setup, including CreateProfile()
1097 // PostProfileInit()
1098 // ... additional setup
1099 // PreBrowserStart()
1100 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1101 // PostBrowserStart()
1103 void ChromeBrowserMainParts::PreProfileInit() {
1104 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1106 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1107 chrome_extra_parts_
[i
]->PreProfileInit();
1109 #if !defined(OS_ANDROID)
1110 // Initialize the feedback uploader so it can setup notifications for profile
1112 feedback::FeedbackProfileObserver::Initialize();
1114 // Ephemeral profiles may have been left behind if the browser crashed.
1115 g_browser_process
->profile_manager()->CleanUpEphemeralProfiles();
1116 #endif // !defined(OS_ANDROID)
1118 #if defined(ENABLE_EXTENSIONS)
1119 javascript_dialog_extensions_client::InstallClient();
1120 #endif // defined(ENABLE_EXTENSIONS)
1122 #if !defined(OS_IOS)
1123 InstallChromeJavaScriptNativeDialogFactory();
1124 #endif // !defined(OS_IOS)
1127 void ChromeBrowserMainParts::PostProfileInit() {
1128 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1130 #if defined(OS_ANDROID)
1131 DevToolsDiscoveryProviderAndroid::Install();
1133 ChromeDevToolsDiscoveryProvider::Install();
1134 #endif // defined(OS_ANDROID)
1136 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1137 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1138 chrome_extra_parts_
[i
]->PostProfileInit();
1141 void ChromeBrowserMainParts::PreBrowserStart() {
1142 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1143 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1144 chrome_extra_parts_
[i
]->PreBrowserStart();
1146 three_d_observer_
.reset(new ThreeDAPIObserver());
1148 // Start the out-of-memory priority manager here so that we give the most
1149 // amount of time for the other services to start up before we start
1150 // adjusting the oom priority.
1152 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1154 #if defined(OS_CHROMEOS)
1155 g_browser_process
->GetOomPriorityManager()->Start(false);
1156 #elif defined(OS_WIN) || defined(OS_MACOSX)
1157 const std::string group_name
=
1158 base::FieldTrialList::FindFullName("AutomaticTabDiscarding");
1159 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding
) ||
1160 base::StartsWith(group_name
, "Enabled", base::CompareCase::SENSITIVE
)) {
1161 bool enabled_once
= base::StartsWith(group_name
, "Enabled_Once",
1162 base::CompareCase::SENSITIVE
);
1163 g_browser_process
->GetOomPriorityManager()->Start(enabled_once
);
1168 void ChromeBrowserMainParts::PostBrowserStart() {
1169 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1170 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1171 chrome_extra_parts_
[i
]->PostBrowserStart();
1172 #if !defined(OS_ANDROID)
1173 // Allow ProcessSingleton to process messages.
1174 process_singleton_
->Unlock();
1175 #endif // !defined(OS_ANDROID)
1176 #if defined(ENABLE_WEBRTC)
1177 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1178 // to reduce the impact on startup time.
1179 BrowserThread::PostDelayedTask(
1182 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles
),
1183 base::TimeDelta::FromMinutes(1));
1184 #endif // defined(ENABLE_WEBRTC)
1186 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1187 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1188 switches::kEnableWebUsbNotifications
)) {
1189 webusb_browser_client_
.reset(new ChromeWebUsbBrowserClient());
1190 webusb_detector_
.reset(
1191 new webusb::WebUsbDetector(webusb_browser_client_
.get()));
1195 // At this point, StartupBrowserCreator::Start has run creating initial
1196 // browser windows and tabs, but no progress has been made in loading
1197 // content as the main message loop hasn't started processing tasks yet.
1198 // We setup to observe to the initial page load here to defer running
1199 // task posted via PostAfterStartupTask until its complete.
1200 AfterStartupTaskUtils::StartMonitoringStartup();
1203 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1204 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1205 TRACK_SCOPED_REGION(
1206 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1208 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1209 const base::TimeTicks start_time_step1
= base::TimeTicks::Now();
1212 // Windows parental controls calls can be slow, so we do an early init here
1213 // that calculates this value off of the UI thread.
1214 IncognitoModePrefs::InitializePlatformParentalControls();
1217 #if defined(ENABLE_EXTENSIONS)
1218 if (!variations::GetVariationParamValue(
1219 "LightSpeed", "EarlyInitStartup").empty()) {
1220 // Try to compute this early on another thread so that we don't spend time
1221 // during profile load initializing the extensions APIs.
1222 BrowserThread::PostTask(
1223 BrowserThread::FILE_USER_BLOCKING
,
1226 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures
)));
1230 // Android updates the metrics service dynamically depending on whether the
1231 // application is in the foreground or not. Do not start here.
1232 #if !defined(OS_ANDROID)
1233 // Now that the file thread has been started, start recording.
1234 StartMetricsRecording();
1235 #endif // !defined(OS_ANDROID)
1237 if (!base::debug::BeingDebugged()) {
1238 // Create watchdog thread after creating all other threads because it will
1239 // watch the other threads and they must be running.
1240 browser_process_
->watchdog_thread();
1243 // Do any initializating in the browser process that requires all threads
1245 browser_process_
->PreMainMessageLoopRun();
1247 // Record last shutdown time into a histogram.
1248 browser_shutdown::ReadLastShutdownInfo();
1251 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1252 // tasks. Those care whether the browser is already running. On Linux/Mac,
1253 // upgrade/uninstall happen separately.
1254 bool already_running
= browser_util::IsBrowserAlreadyRunning();
1256 // If the command line specifies 'uninstall' then we need to work here
1257 // unless we detect another chrome browser running.
1258 if (parsed_command_line().HasSwitch(switches::kUninstall
)) {
1259 return DoUninstallTasks(already_running
);
1262 if (parsed_command_line().HasSwitch(switches::kHideIcons
) ||
1263 parsed_command_line().HasSwitch(switches::kShowIcons
)) {
1264 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1265 parsed_command_line_
);
1268 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1269 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
)));
1270 #endif // defined(OS_WIN)
1272 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser
)) {
1273 bool is_managed
= g_browser_process
->local_state()->IsManagedPreference(
1274 prefs::kDefaultBrowserSettingEnabled
);
1275 if (is_managed
&& !g_browser_process
->local_state()->GetBoolean(
1276 prefs::kDefaultBrowserSettingEnabled
)) {
1277 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY
);
1280 return ShellIntegration::SetAsDefaultBrowser() ?
1281 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT
) :
1282 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED
);
1285 #if defined(USE_AURA)
1286 // Make sure aura::Env has been initialized.
1287 CHECK(aura::Env::GetInstance());
1288 #endif // defined(USE_AURA)
1290 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1291 #if !defined(OS_ANDROID)
1292 // If the command line specifies --pack-extension, attempt the pack extension
1293 // startup action and exit.
1294 if (parsed_command_line().HasSwitch(switches::kPackExtension
)) {
1295 extensions::StartupHelper extension_startup_helper
;
1296 if (extension_startup_helper
.PackExtension(parsed_command_line()))
1297 return content::RESULT_CODE_NORMAL_EXIT
;
1298 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR
;
1301 // When another process is running, use that process instead of starting a
1302 // new one. NotifyOtherProcess will currently give the other process up to
1303 // 20 seconds to respond. Note that this needs to be done before we attempt
1304 // to read the profile.
1305 notify_result_
= process_singleton_
->NotifyOtherProcessOrCreate();
1306 switch (notify_result_
) {
1307 case ProcessSingleton::PROCESS_NONE
:
1308 // No process already running, fall through to starting a new one.
1311 case ProcessSingleton::PROCESS_NOTIFIED
:
1312 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1313 // On POSIX systems, print a message notifying the process is running.
1314 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1315 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER
))).c_str());
1316 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1318 // Having a differentiated return type for testing allows for tests to
1319 // verify proper handling of some switches. When not testing, stick to
1320 // the standard Unix convention of returning zero when things went as
1322 if (parsed_command_line().HasSwitch(switches::kTestType
))
1323 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED
;
1324 return content::RESULT_CODE_NORMAL_EXIT
;
1326 case ProcessSingleton::PROFILE_IN_USE
:
1327 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1329 case ProcessSingleton::LOCK_ERROR
:
1330 LOG(ERROR
) << "Failed to create a ProcessSingleton for your profile "
1331 "directory. This means that running multiple instances "
1332 "would start multiple browser processes rather than "
1333 "opening a new window in the existing process. Aborting "
1334 "now to avoid profile corruption.";
1335 return chrome::RESULT_CODE_PROFILE_IN_USE
;
1340 #endif // !defined(OS_ANDROID)
1342 // Handle special early return paths (which couldn't be processed even earlier
1343 // as they require the process singleton to be held) first.
1345 std::string try_chrome
=
1346 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain
);
1347 if (!try_chrome
.empty()) {
1349 // Setup.exe has determined that we need to run a retention experiment
1350 // and has lauched chrome to show the experiment UI. It is guaranteed that
1351 // no other Chrome is currently running as the process singleton was
1352 // sucessfully grabbed above.
1354 base::StringToInt(try_chrome
, &try_chrome_int
);
1355 TryChromeDialogView::Result answer
= TryChromeDialogView::Show(
1357 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog
,
1358 base::Unretained(process_singleton_
.get())));
1359 if (answer
== TryChromeDialogView::NOT_NOW
)
1360 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
;
1361 if (answer
== TryChromeDialogView::UNINSTALL_CHROME
)
1362 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2
;
1363 // At this point the user is willing to try chrome again.
1364 if (answer
== TryChromeDialogView::TRY_CHROME_AS_DEFAULT
) {
1365 // Only set in the unattended case, the interactive case is Windows 8.
1366 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1367 ShellIntegration::SET_DEFAULT_UNATTENDED
)
1368 ShellIntegration::SetAsDefaultBrowser();
1371 // We don't support retention experiments on Mac or Linux.
1372 return content::RESULT_CODE_NORMAL_EXIT
;
1373 #endif // defined(OS_WIN)
1377 // Do the tasks if chrome has been upgraded while it was last running.
1378 if (!already_running
&& upgrade_util::DoUpgradeTasks(parsed_command_line()))
1379 return content::RESULT_CODE_NORMAL_EXIT
;
1381 // Check if there is any machine level Chrome installed on the current
1382 // machine. If yes and the current Chrome process is user level, we do not
1383 // allow the user level Chrome to run. So we notify the user and uninstall
1384 // user level Chrome.
1385 // Note this check needs to happen here (after the process singleton was
1386 // obtained but before potentially creating the first run sentinel).
1387 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1388 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS
;
1389 #endif // defined(OS_WIN)
1391 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1392 if (sxs_linux::ShouldMigrateUserDataDir())
1393 return sxs_linux::MigrateUserDataDir();
1394 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1396 // Desktop construction occurs here, (required before profile creation).
1399 // Profile creation ----------------------------------------------------------
1401 metrics::MetricsService::SetExecutionPhase(
1402 metrics::MetricsService::CREATE_PROFILE
,
1403 g_browser_process
->local_state());
1405 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1406 base::TimeTicks::Now() - start_time_step1
);
1408 // This step is costly and is already measured in Startup.CreateFirstProfile
1409 // and more directly Profile.CreateAndInitializeProfile.
1410 profile_
= CreatePrimaryProfile(parameters(),
1412 parsed_command_line());
1414 return content::RESULT_CODE_NORMAL_EXIT
;
1416 #if !defined(OS_ANDROID)
1417 const base::TimeTicks start_time_step2
= base::TimeTicks::Now();
1418 // The first run sentinel must be created after the process singleton was
1419 // grabbed and no early return paths were otherwise hit above.
1420 first_run::CreateSentinelIfNeeded();
1421 #endif // !defined(OS_ANDROID)
1423 #if defined(ENABLE_BACKGROUND)
1424 // Autoload any profiles which are running background apps.
1425 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1426 browser_process_
->profile_manager()->AutoloadProfiles();
1427 #endif // defined(ENABLE_BACKGROUND)
1428 // Post-profile init ---------------------------------------------------------
1430 TranslateService::Initialize();
1432 // Needs to be done before PostProfileInit, since login manager on CrOS is
1433 // called inside PostProfileInit.
1434 content::WebUIControllerFactory::RegisterFactory(
1435 ChromeWebUIControllerFactory::GetInstance());
1437 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1438 // So make sure to create it before that.
1439 #if !defined(DISABLE_NACL)
1440 NaClBrowserDelegateImpl
* delegate
=
1441 new NaClBrowserDelegateImpl(browser_process_
->profile_manager());
1442 nacl::NaClBrowser::SetDelegate(delegate
);
1443 #endif // !defined(DISABLE_NACL)
1445 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1446 // (requires supporting early exit).
1449 // Retrieve cached GL strings from local state and use them for GPU
1450 // blacklist decisions.
1451 if (g_browser_process
->gl_string_manager())
1452 g_browser_process
->gl_string_manager()->Initialize();
1454 // Create an instance of GpuModeManager to watch gpu mode pref change.
1455 g_browser_process
->gpu_mode_manager();
1457 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1458 // Show the First Run UI if this is the first time Chrome has been run on
1459 // this computer, or we're being compelled to do so by a command line flag.
1460 // Note that this be done _after_ the PrefService is initialized and all
1461 // preferences are registered, since some of the code that the importer
1462 // touches reads preferences.
1463 if (first_run::IsChromeFirstRun()) {
1464 first_run::AutoImport(profile_
,
1465 master_prefs_
->homepage_defined
,
1466 master_prefs_
->do_import_items
,
1467 master_prefs_
->dont_import_items
,
1468 master_prefs_
->import_bookmarks_path
);
1470 // Note: this can pop the first run consent dialog on linux.
1471 first_run::DoPostImportTasks(profile_
,
1472 master_prefs_
->make_chrome_default_for_user
);
1474 if (!master_prefs_
->suppress_first_run_default_browser_prompt
) {
1475 browser_creator_
->set_show_main_browser_window(
1476 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_
));
1478 browser_creator_
->set_is_default_browser_dialog_suppressed(true);
1481 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1484 // Sets things up so that if we crash from this point on, a dialog will
1485 // popup asking the user to restart chrome. It is done this late to avoid
1486 // testing against a bunch of special cases that are taken care early on.
1487 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1488 parsed_command_line());
1490 // Registers Chrome with the Windows Restart Manager, which will restore the
1491 // Chrome session when the computer is restarted after a system update.
1492 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1493 // but should run on startup if extended to handle crashes/hangs/patches.
1494 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1495 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
1496 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1497 parsed_command_line());
1500 // Verify that the profile is not on a network share and if so prepare to show
1501 // notification to the user.
1502 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_
)) {
1503 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
1504 base::Bind(&NetworkProfileBubble::CheckNetworkProfile
,
1505 profile_
->GetPath()));
1507 #endif // defined(OS_WIN)
1509 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1510 // Init the RLZ library. This just binds the dll and schedules a task on the
1511 // file thread to be run sometime later. If this is the first run we record
1512 // the installation event.
1513 PrefService
* pref_service
= profile_
->GetPrefs();
1514 int ping_delay
= first_run::IsChromeFirstRun() ? master_prefs_
->ping_delay
:
1515 pref_service
->GetInteger(first_run::GetPingDelayPrefName().c_str());
1516 // Negative ping delay means to send ping immediately after a first search is
1518 rlz::RLZTracker::SetRlzDelegate(
1519 make_scoped_ptr(new ChromeRLZTrackerDelegate
));
1520 rlz::RLZTracker::InitRlzDelayed(
1521 first_run::IsChromeFirstRun(), ping_delay
< 0,
1522 base::TimeDelta::FromMilliseconds(abs(ping_delay
)),
1523 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_
),
1524 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_
),
1525 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_
));
1526 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1528 // Configure modules that need access to resources.
1529 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
1530 media::SetLocalizedStringProvider(
1531 chrome_common_media::LocalizedStringProvider
);
1533 // In unittest mode, this will do nothing. In normal mode, this will create
1534 // the global IntranetRedirectDetector instance, which will promptly go to
1535 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1536 // to see if it should do anything else.
1538 // A simpler way of doing all this would be to have some function which could
1539 // give the time elapsed since startup, and simply have this object check that
1540 // when asked to initialize itself, but this doesn't seem to exist.
1542 // This can't be created in the BrowserProcessImpl constructor because it
1543 // needs to read prefs that get set after that runs.
1544 browser_process_
->intranet_redirect_detector();
1546 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1547 if (parsed_command_line().HasSwitch(switches::kDebugPrint
)) {
1548 base::FilePath path
=
1549 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint
);
1550 printing::PrintedDocument::set_debug_dump_path(path
);
1552 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1554 HandleTestParameters(parsed_command_line());
1555 browser_process_
->metrics_service()->RecordBreakpadHasDebugger(
1556 base::debug::BeingDebugged());
1558 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1559 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1560 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1561 browser_process_
->GetApplicationLocale());
1563 // Start watching for hangs during startup. We disarm this hang detector when
1564 // ThreadWatcher takes over or when browser is shutdown or when
1565 // startup_watcher_ is deleted.
1566 metrics::MetricsService::SetExecutionPhase(
1567 metrics::MetricsService::STARTUP_TIMEBOMB_ARM
,
1568 g_browser_process
->local_state());
1569 startup_watcher_
->Arm(base::TimeDelta::FromSeconds(600));
1571 // On mobile, need for clean shutdown arises only when the application comes
1572 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1573 // http://crbug.com/179143
1574 #if !defined(OS_ANDROID)
1575 // Start watching for a hang.
1576 browser_process_
->metrics_service()->LogNeedForCleanShutdown();
1577 #endif // !defined(OS_ANDROID)
1579 #if defined(ENABLE_PRINT_PREVIEW)
1580 // Create the instance of the cloud print proxy service so that it can launch
1581 // the service process if needed. This is needed because the service process
1582 // might have shutdown because an update was available.
1583 // TODO(torne): this should maybe be done with
1584 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1586 CloudPrintProxyServiceFactory::GetForProfile(profile_
);
1587 #endif // defined(ENABLE_PRINT_PREVIEW)
1589 // Start watching all browser threads for responsiveness.
1590 metrics::MetricsService::SetExecutionPhase(
1591 metrics::MetricsService::THREAD_WATCHER_START
,
1592 g_browser_process
->local_state());
1593 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1595 #if defined(OS_ANDROID)
1596 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1597 #endif // defined(OS_ANDROID)
1599 #if !defined(DISABLE_NACL)
1600 BrowserThread::PostTask(
1603 base::Bind(nacl::NaClProcessHost::EarlyStartup
));
1604 #endif // !defined(DISABLE_NACL)
1606 // Make sure initial prefs are recorded
1607 PrefMetricsService::Factory::GetForProfile(profile_
);
1611 // Instantiate the notification UI manager, as this triggers a perf timer
1612 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1613 // triggering the timer and call that explicitly in the approprate place.
1614 // http://crbug.com/105065.
1615 browser_process_
->notification_ui_manager();
1617 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1618 // data source is based on the Component Updater.
1619 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1621 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate
))
1622 RegisterComponentsForUpdate();
1624 #if defined(OS_ANDROID)
1625 variations::VariationsService
* variations_service
=
1626 browser_process_
->variations_service();
1627 if (variations_service
) {
1628 // Just initialize the policy prefs service here. Variations seed fetching
1629 // will be initialized when the app enters foreground mode.
1630 variations_service
->set_policy_pref_service(profile_
->GetPrefs());
1632 translate::TranslateDownloadManager::RequestLanguageList(
1633 profile_
->GetPrefs());
1636 // Most general initialization is behind us, but opening a
1637 // tab and/or session restore and such is still to be done.
1638 base::TimeTicks browser_open_start
= base::TimeTicks::Now();
1640 // We are in regular browser boot sequence. Open initial tabs and enter the
1641 // main message loop.
1642 std::vector
<Profile
*> last_opened_profiles
;
1643 #if !defined(OS_CHROMEOS)
1644 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1645 // them this early as the cryptohome hasn't yet been mounted (which happens
1646 // only once we log in).
1647 last_opened_profiles
=
1648 g_browser_process
->profile_manager()->GetLastOpenedProfiles();
1649 #endif // defined(OS_CHROMEOS)
1651 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1652 base::TimeTicks::Now() - start_time_step2
);
1654 // This step is costly and is already measured in
1655 // Startup.StartupBrowserCreator_Start.
1656 const bool started
= browser_creator_
->Start(
1657 parsed_command_line(), base::FilePath(), profile_
, last_opened_profiles
);
1658 const base::TimeTicks start_time_step3
= base::TimeTicks::Now();
1660 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1661 // Initialize autoupdate timer. Timer callback costs basically nothing
1662 // when browser is not in persistent mode, so it's OK to let it ride on
1663 // the main thread. This needs to be done here because we don't want
1664 // to start the timer when Chrome is run inside a test harness.
1665 browser_process_
->StartAutoupdateTimer();
1666 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1668 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1669 // On Linux, the running exe will be updated if an upgrade becomes
1670 // available while the browser is running. We need to save the last
1671 // modified time of the exe, so we can compare to determine if there is
1672 // an upgrade while the browser is kept alive by a persistent extension.
1673 upgrade_util::SaveLastModifiedTimeOfExe();
1674 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1676 // Record now as the last successful chrome start.
1677 GoogleUpdateSettings::SetLastRunTime();
1679 #if defined(OS_MACOSX)
1680 // Call Recycle() here as late as possible, before going into the loop
1681 // because Start() will add things to it while creating the main window.
1682 if (parameters().autorelease_pool
)
1683 parameters().autorelease_pool
->Recycle();
1684 #endif // defined(OS_MACOSX)
1686 const base::TimeDelta delta
= base::TimeTicks::Now() - browser_open_start
;
1687 startup_metric_utils::RecordBrowserOpenTabsDelta(delta
);
1689 // If we're running tests (ui_task is non-null), then we don't want to
1690 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1691 // RequestLanguageList
1692 if (parameters().ui_task
== NULL
) {
1693 // Request new variations seed information from server.
1694 variations::VariationsService
* variations_service
=
1695 browser_process_
->variations_service();
1696 if (variations_service
)
1697 variations_service
->PerformPreMainMessageLoopStartup();
1699 translate::TranslateDownloadManager::RequestLanguageList(
1700 profile_
->GetPrefs());
1703 run_message_loop_
= started
;
1704 browser_creator_
.reset();
1706 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1707 if (g_browser_process
->metrics_service()->reporting_active())
1708 content::StartPowerUsageMonitor();
1709 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1711 process_power_collector_
.reset(new ProcessPowerCollector
);
1712 process_power_collector_
->Initialize();
1713 #endif // !defined(OS_ANDROID)
1717 if (parameters().ui_task
) {
1718 parameters().ui_task
->Run();
1719 delete parameters().ui_task
;
1720 run_message_loop_
= false;
1722 #if defined(OS_ANDROID)
1723 // We never run the C++ main loop on Android, since the UI thread message
1724 // loop is controlled by the OS, so this is as close as we can get to
1725 // the start of the main loop.
1726 if (result_code_
<= 0) {
1727 RecordBrowserStartupTime();
1729 #endif // defined(OS_ANDROID)
1731 #if !defined(OS_ANDROID)
1732 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1733 base::TimeTicks::Now() - start_time_step3
);
1734 #endif // !defined(OS_ANDROID)
1736 return result_code_
;
1739 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code
) {
1740 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1741 #if defined(OS_ANDROID)
1742 // Chrome on Android does not use default MessageLoop. It has its own
1743 // Android specific MessageLoop
1747 // Set the result code set in PreMainMessageLoopRun or set above.
1748 *result_code
= result_code_
;
1749 if (!run_message_loop_
)
1750 return true; // Don't run the default message loop.
1752 // These should be invoked as close to the start of the browser's
1753 // UI thread message loop as possible to get a stable measurement
1755 RecordBrowserStartupTime();
1757 DCHECK(base::MessageLoopForUI::IsCurrent());
1758 base::RunLoop run_loop
;
1760 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1762 metrics::MetricsService::SetExecutionPhase(
1763 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN
,
1764 g_browser_process
->local_state());
1768 #endif // defined(OS_ANDROID)
1771 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1772 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1773 #if defined(OS_ANDROID)
1774 // Chrome on Android does not use default MessageLoop. It has its own
1775 // Android specific MessageLoop
1778 // Start watching for jank during shutdown. It gets disarmed when
1779 // |shutdown_watcher_| object is destructed.
1780 metrics::MetricsService::SetExecutionPhase(
1781 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM
,
1782 g_browser_process
->local_state());
1783 shutdown_watcher_
->Arm(base::TimeDelta::FromSeconds(300));
1785 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1786 startup_watcher_
->Disarm();
1788 // Remove observers attached to D-Bus clients before DbusThreadManager is
1790 process_power_collector_
.reset();
1792 #if !defined(OS_IOS)
1793 webusb_detector_
.reset();
1794 webusb_browser_client_
.reset();
1797 for (size_t i
= 0; i
< chrome_extra_parts_
.size(); ++i
)
1798 chrome_extra_parts_
[i
]->PostMainMessageLoopRun();
1800 // Some tests don't set parameters.ui_task, so they started translate
1801 // language fetch that was never completed so we need to cleanup here
1802 // otherwise it will be done by the destructor in a wrong thread.
1803 TranslateService::Shutdown(parameters().ui_task
== NULL
);
1805 if (notify_result_
== ProcessSingleton::PROCESS_NONE
)
1806 process_singleton_
->Cleanup();
1808 // Stop all tasks that might run on WatchDogThread.
1809 ThreadWatcherList::StopWatchingAll();
1811 browser_process_
->metrics_service()->Stop();
1813 restart_last_session_
= browser_shutdown::ShutdownPreThreadsStop();
1814 browser_process_
->StartTearDown();
1815 #endif // defined(OS_ANDROID)
1818 void ChromeBrowserMainParts::PostDestroyThreads() {
1819 #if defined(OS_ANDROID)
1820 // On Android, there is no quit/exit. So the browser's main message loop will
1824 browser_process_
->PostDestroyThreads();
1825 // browser_shutdown takes care of deleting browser_process, so we need to
1827 ignore_result(browser_process_
.release());
1828 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_
);
1829 master_prefs_
.reset();
1830 process_singleton_
.reset();
1831 device_event_log::Shutdown();
1833 // We need to do this check as late as possible, but due to modularity, this
1834 // may be the last point in Chrome. This would be more effective if done at
1835 // a higher level on the stack, so that it is impossible for an early return
1836 // to bypass this code. Perhaps we need a *final* hook that is called on all
1837 // paths from content/browser/browser_main.
1838 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1840 #if defined(OS_CHROMEOS)
1841 chromeos::CrosSettings::Shutdown();
1842 #endif // defined(OS_CHROMEOS)
1843 #endif // defined(OS_ANDROID)
1848 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts
* parts
) {
1849 chrome_extra_parts_
.push_back(parts
);