Popular sites on the NTP: re-download popular suggestions once per Chrome run
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blobf23f18542f51ede9de4c8bd49ec8c346e414c4a1
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"
7 #include <set>
8 #include <string>
9 #include <vector>
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/net/net_resource_provider.h"
104 #include "chrome/common/pref_names.h"
105 #include "chrome/common/profiling.h"
106 #include "chrome/common/variations/variations_util.h"
107 #include "chrome/grit/generated_resources.h"
108 #include "chrome/installer/util/google_update_settings.h"
109 #include "components/component_updater/component_updater_service.h"
110 #include "components/device_event_log/device_event_log.h"
111 #include "components/google/core/browser/google_util.h"
112 #include "components/language_usage_metrics/language_usage_metrics.h"
113 #include "components/metrics/call_stack_profile_metrics_provider.h"
114 #include "components/metrics/metrics_service.h"
115 #include "components/metrics/profiler/tracking_synchronizer.h"
116 #include "components/nacl/browser/nacl_browser.h"
117 #include "components/rappor/rappor_service.h"
118 #include "components/signin/core/common/profile_management_switches.h"
119 #include "components/startup_metric_utils/startup_metric_utils.h"
120 #include "components/tracing/tracing_switches.h"
121 #include "components/translate/content/browser/browser_cld_utils.h"
122 #include "components/translate/content/common/cld_data_source.h"
123 #include "components/translate/core/browser/translate_download_manager.h"
124 #include "components/variations/net/variations_http_header_provider.h"
125 #include "components/variations/pref_names.h"
126 #include "components/variations/service/variations_service.h"
127 #include "components/variations/variations_associated_data.h"
128 #include "components/variations/variations_switches.h"
129 #include "components/version_info/version_info.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"
156 #else
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.
177 #if defined(OS_WIN)
178 #include "base/environment.h" // For PreRead experiment.
179 #include "base/trace_event/trace_event_etw_export_win.h"
180 #include "base/win/windows_version.h"
181 #include "chrome/browser/browser_util_win.h"
182 #include "chrome/browser/chrome_browser_main_win.h"
183 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
184 #include "chrome/browser/component_updater/caps_installer_win.h"
185 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
186 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
187 #include "chrome/browser/first_run/upgrade_util_win.h"
188 #include "chrome/browser/ui/network_profile_bubble.h"
189 #include "chrome/installer/util/helper.h"
190 #include "chrome/installer/util/install_util.h"
191 #include "chrome/installer/util/shell_util.h"
192 #include "components/browser_watcher/exit_funnel_win.h"
193 #include "net/base/net_util.h"
194 #include "ui/base/l10n/l10n_util_win.h"
195 #include "ui/gfx/win/dpi.h"
196 #include "ui/shell_dialogs/select_file_dialog.h"
197 #endif // defined(OS_WIN)
199 #if defined(OS_MACOSX)
200 #include <Security/Security.h>
202 #include "base/mac/scoped_nsautorelease_pool.h"
203 #include "chrome/browser/mac/keystone_glue.h"
204 #endif // defined(OS_MACOSX)
206 #if !defined(OS_IOS)
207 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
208 #endif // !defined(OS_IOS)
210 #if !defined(DISABLE_NACL)
211 #include "chrome/browser/component_updater/pnacl_component_installer.h"
212 #include "components/nacl/browser/nacl_process_host.h"
213 #endif // !defined(DISABLE_NACL)
215 #if defined(ENABLE_EXTENSIONS)
216 #include "chrome/browser/extensions/startup_helper.h"
217 #include "extensions/browser/extension_protocols.h"
218 #include "extensions/common/features/feature_provider.h"
219 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
220 #endif // defined(ENABLE_EXTENSIONS)
222 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
223 #include "printing/printed_document.h"
224 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
226 #if defined(ENABLE_RLZ)
227 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
228 #include "components/rlz/rlz_tracker.h"
229 #endif // defined(ENABLE_RLZ)
231 #if defined(ENABLE_WEBRTC)
232 #include "chrome/browser/media/webrtc_log_util.h"
233 #endif // defined(ENABLE_WEBRTC)
235 #if defined(USE_AURA)
236 #include "ui/aura/env.h"
237 #endif // defined(USE_AURA)
239 #if !defined(OS_ANDROID) && !defined(OS_IOS)
240 #include "chrome/browser/chrome_webusb_browser_client.h"
241 #include "components/webusb/webusb_detector.h"
242 #endif
244 using content::BrowserThread;
246 namespace {
248 // This function provides some ways to test crash and assertion handling
249 // behavior of the program.
250 void HandleTestParameters(const base::CommandLine& command_line) {
251 // This parameter causes a null pointer crash (crash reporter trigger).
252 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
253 int* bad_pointer = NULL;
254 *bad_pointer = 0;
258 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
259 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
260 const std::vector<GURL>& new_tabs) {
261 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
262 it != new_tabs.end(); ++it) {
263 if (it->is_valid())
264 browser_creator->AddFirstRunTab(*it);
267 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
269 // Returns the new local state object, guaranteed non-NULL.
270 // |local_state_task_runner| must be a shutdown-blocking task runner.
271 PrefService* InitializeLocalState(
272 base::SequencedTaskRunner* local_state_task_runner,
273 const base::CommandLine& parsed_command_line) {
274 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
276 // Load local state. This includes the application locale so we know which
277 // locale dll to load. This also causes local state prefs to be registered.
278 PrefService* local_state = g_browser_process->local_state();
279 DCHECK(local_state);
281 #if defined(OS_WIN)
282 if (first_run::IsChromeFirstRun()) {
283 // During first run we read the google_update registry key to find what
284 // language the user selected when downloading the installer. This
285 // becomes our default language in the prefs.
286 // Other platforms obey the system locale.
287 base::string16 install_lang;
288 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
289 local_state->SetString(prefs::kApplicationLocale,
290 base::UTF16ToASCII(install_lang));
293 #endif // defined(OS_WIN)
295 // If the local state file for the current profile doesn't exist and the
296 // parent profile command line flag is present, then we should inherit some
297 // local state from the parent profile.
298 // Checking that the local state file for the current profile doesn't exist
299 // is the most robust way to determine whether we need to inherit or not
300 // since the parent profile command line flag can be present even when the
301 // current profile is not a new one, and in that case we do not want to
302 // inherit and reset the user's setting.
304 // TODO(mnissler): We should probably just instantiate a
305 // JSONPrefStore here instead of an entire PrefService. Once this is
306 // addressed, the call to browser_prefs::RegisterLocalState can move
307 // to chrome_prefs::CreateLocalState.
308 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
309 base::FilePath local_state_path;
310 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
311 bool local_state_file_exists = base::PathExists(local_state_path);
312 if (!local_state_file_exists) {
313 base::FilePath parent_profile =
314 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
315 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
316 scoped_ptr<PrefService> parent_local_state(
317 chrome_prefs::CreateLocalState(
318 parent_profile,
319 local_state_task_runner,
320 g_browser_process->policy_service(),
321 registry,
322 false));
323 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
324 // Right now, we only inherit the locale setting from the parent profile.
325 local_state->SetString(
326 prefs::kApplicationLocale,
327 parent_local_state->GetString(prefs::kApplicationLocale));
331 #if defined(OS_CHROMEOS)
332 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
333 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
334 // Ensure that we start with owner's locale.
335 if (!owner_locale.empty() &&
336 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
337 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
338 local_state->SetString(prefs::kApplicationLocale, owner_locale);
341 #endif // defined(OS_CHROMEOS)
343 return local_state;
346 // Initializes the primary profile, possibly doing some user prompting to pick
347 // a fallback profile. Returns the newly created profile, or NULL if startup
348 // should not continue.
349 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
350 const base::FilePath& user_data_dir,
351 const base::CommandLine& parsed_command_line) {
352 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
353 TRACK_SCOPED_REGION(
354 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
356 base::Time start = base::Time::Now();
357 if (profiles::IsMultipleProfilesEnabled() &&
358 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
359 profiles::SetLastUsedProfile(
360 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
361 // Clear kProfilesLastActive since the user only wants to launch a specific
362 // profile.
363 ListPrefUpdate update(g_browser_process->local_state(),
364 prefs::kProfilesLastActive);
365 base::ListValue* profile_list = update.Get();
366 profile_list->Clear();
369 Profile* profile = NULL;
370 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
371 // On ChromeOS and Android the ProfileManager will use the same path as the
372 // one we got passed. GetActiveUserProfile will therefore use the correct path
373 // automatically.
374 DCHECK_EQ(user_data_dir.value(),
375 g_browser_process->profile_manager()->user_data_dir().value());
376 profile = ProfileManager::GetActiveUserProfile();
377 #else
378 base::FilePath profile_path =
379 GetStartupProfilePath(user_data_dir, parsed_command_line);
381 // Without NewAvatarMenu, replace guest with any existing profile.
382 if (!switches::IsNewAvatarMenu() &&
383 profile_path == ProfileManager::GetGuestProfilePath()) {
384 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
385 GetPathOfProfileAtIndex(0);
387 profile = g_browser_process->profile_manager()->GetProfile(
388 profile_path);
390 // If we're using the --new-profile-management flag and this profile is
391 // signed out, then we should show the user manager instead. By switching
392 // the active profile to the guest profile we ensure that no
393 // browser windows will be opened for the guest profile.
394 if (switches::IsNewProfileManagement() &&
395 profile &&
396 !profile->IsGuestSession()) {
397 ProfileInfoCache& cache =
398 g_browser_process->profile_manager()->GetProfileInfoCache();
399 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
401 if (profile_index != std::string::npos &&
402 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
403 profile = g_browser_process->profile_manager()->GetProfile(
404 ProfileManager::GetGuestProfilePath());
407 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
408 if (profile) {
409 UMA_HISTOGRAM_LONG_TIMES(
410 "Startup.CreateFirstProfile", base::Time::Now() - start);
411 return profile;
414 #if !defined(OS_WIN)
415 // TODO(port): fix this. See comments near the definition of
416 // user_data_dir. It is better to CHECK-fail here than it is to
417 // silently exit because of missing code in the above test.
418 CHECK(profile) << "Cannot get default profile.";
419 #endif // !defined(OS_WIN)
421 return NULL;
424 #if defined(OS_MACOSX)
425 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
426 SecKeychainCallbackInfo* info, void* context) {
427 return noErr;
429 #endif // defined(OS_MACOSX)
431 void RegisterComponentsForUpdate() {
432 component_updater::ComponentUpdateService* cus =
433 g_browser_process->component_updater();
435 // Registration can be before or after cus->Start() so it is ok to post
436 // a task to the UI thread to do registration once you done the necessary
437 // file IO to know you existing component version.
438 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
439 RegisterRecoveryComponent(cus, g_browser_process->local_state());
440 RegisterPepperFlashComponent(cus);
441 RegisterSwiftShaderComponent(cus);
442 RegisterWidevineCdmComponent(cus);
443 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
445 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
446 #if defined(OS_CHROMEOS)
447 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
448 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
449 // installer when running on Linux. See crbug.com/422121 for more details.
450 if (!base::SysInfo::IsRunningOnChromeOS())
451 #endif // defined(OS_CHROMEOS)
452 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
453 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
455 // Registration of the CLD Component is a no-op unless the CLD data source has
456 // been configured to be the "Component" data source.
457 RegisterCldComponent(cus);
459 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
460 g_browser_process->supervised_user_whitelist_installer();
461 whitelist_installer->RegisterComponents();
463 base::FilePath path;
464 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
465 #if defined(OS_ANDROID)
466 // The CRLSet component was enabled for some releases. This code attempts to
467 // delete it from the local disk of those how may have downloaded it.
468 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
469 #elif !defined(OS_CHROMEOS)
470 // CRLSetFetcher attempts to load a CRL set from either the local disk or
471 // network.
472 // For Chrome OS this registration is delayed until user login.
473 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
474 // Registration of the EV Whitelist component here is not necessary for:
475 // 1. Android: Because it currently does not have the EV indicator.
476 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
477 RegisterEVWhitelistComponent(cus, path);
478 #endif // defined(OS_ANDROID)
481 #if defined(OS_WIN)
482 #if defined(GOOGLE_CHROME_BUILD)
483 RegisterSwReporterComponent(cus);
484 #endif // defined(GOOGLE_CHROME_BUILD)
485 RegisterCAPSComponent(cus);
486 #endif // defined(OS_WIN)
489 #if !defined(OS_ANDROID)
490 bool ProcessSingletonNotificationCallback(
491 const base::CommandLine& command_line,
492 const base::FilePath& current_directory) {
493 // Drop the request if the browser process is already in shutdown path.
494 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
495 #if defined(OS_WIN)
496 browser_watcher::ExitFunnel::RecordSingleEvent(
497 chrome::kBrowserExitCodesRegistryPath,
498 L"ProcessSingletonIsShuttingDown");
499 #endif // defined(OS_WIN)
501 return false;
504 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
505 std::string start_time_string =
506 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
507 int64 remote_start_time;
508 if (base::StringToInt64(start_time_string, &remote_start_time)) {
509 base::TimeDelta elapsed =
510 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
511 if (command_line.HasSwitch(switches::kFastStart)) {
512 UMA_HISTOGRAM_LONG_TIMES(
513 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
514 } else {
515 UMA_HISTOGRAM_LONG_TIMES(
516 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
521 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
522 command_line);
524 base::FilePath user_data_dir =
525 g_browser_process->profile_manager()->user_data_dir();
526 base::FilePath startup_profile_dir =
527 GetStartupProfilePath(user_data_dir, command_line);
529 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
530 command_line, current_directory, startup_profile_dir);
531 return true;
533 #endif // !defined(OS_ANDROID)
535 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
536 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
537 std::string port_str =
538 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
539 int port;
540 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
541 g_browser_process->CreateDevToolsHttpProtocolHandler(
542 chrome::HOST_DESKTOP_TYPE_NATIVE,
543 "127.0.0.1",
544 static_cast<uint16>(port));
545 } else {
546 DLOG(WARNING) << "Invalid http debugger port number " << port;
551 } // namespace
553 namespace chrome_browser {
555 // This error message is not localized because we failed to load the
556 // localization data files.
557 #if defined(OS_WIN)
558 const char kMissingLocaleDataTitle[] = "Missing File Error";
559 #endif // defined(OS_WIN)
561 #if defined(OS_WIN)
562 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
563 const char kMissingLocaleDataMessage[] =
564 "Unable to find locale data files. Please reinstall.";
565 #endif // defined(OS_WIN)
567 } // namespace chrome_browser
569 // BrowserMainParts ------------------------------------------------------------
571 ChromeBrowserMainParts::ChromeBrowserMainParts(
572 const content::MainFunctionParams& parameters)
573 : parameters_(parameters),
574 parsed_command_line_(parameters.command_line),
575 result_code_(content::RESULT_CODE_NORMAL_EXIT),
576 startup_watcher_(new StartupTimeBomb()),
577 shutdown_watcher_(new ShutdownWatcherHelper()),
578 browser_field_trials_(parameters.command_line),
579 sampling_profiler_(
580 base::PlatformThread::CurrentId(),
581 sampling_profiler_config_.GetSamplingParams(),
582 metrics::CallStackProfileMetricsProvider::GetProfilerCallback(
583 metrics::CallStackProfileMetricsProvider::Params(
584 metrics::CallStackProfileMetricsProvider::PROCESS_STARTUP,
585 false))),
586 profile_(NULL),
587 run_message_loop_(true),
588 notify_result_(ProcessSingleton::PROCESS_NONE),
589 local_state_(NULL),
590 restart_last_session_(false) {
591 if (sampling_profiler_config_.IsProfilerEnabled())
592 sampling_profiler_.Start();
594 // If we're running tests (ui_task is non-null).
595 if (parameters.ui_task)
596 browser_defaults::enable_help_app = false;
598 // Chrome disallows cookies by default. All code paths that want to use
599 // cookies need to go through one of Chrome's URLRequestContexts which have
600 // a ChromeNetworkDelegate attached that selectively allows cookies again.
601 net::URLRequest::SetDefaultCookiePolicyToBlock();
604 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
605 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
606 delete chrome_extra_parts_[i];
607 chrome_extra_parts_.clear();
610 // This will be called after the command-line has been mutated by about:flags
611 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
612 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
613 // Must initialize metrics after labs have been converted into switches,
614 // but before field trials are set up (so that client ID is available for
615 // one-time randomized field trials).
617 // Initialize FieldTrialList to support FieldTrials that use one-time
618 // randomization.
619 metrics::MetricsService* metrics = browser_process_->metrics_service();
620 field_trial_list_.reset(
621 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
623 const base::CommandLine* command_line =
624 base::CommandLine::ForCurrentProcess();
625 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
626 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
627 base::FieldTrial::EnableBenchmarking();
630 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
631 bool result = chrome_variations::AssociateParamsFromString(
632 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
633 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
634 << " list specified.";
637 // Ensure any field trials specified on the command line are initialized.
638 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
639 std::set<std::string> unforceable_field_trials;
640 #if defined(OFFICIAL_BUILD)
641 unforceable_field_trials.insert("SettingsEnforcement");
642 #endif // defined(OFFICIAL_BUILD)
644 // Create field trials without activating them, so that this behaves in a
645 // consistent manner with field trials created from the server.
646 bool result = base::FieldTrialList::CreateTrialsFromString(
647 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
648 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
649 unforceable_field_trials);
650 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
651 << " list specified.";
654 #if defined(FIELDTRIAL_TESTING_ENABLED)
655 if (!command_line->HasSwitch(switches::kDisableFieldTrialTestingConfig) &&
656 !command_line->HasSwitch(switches::kForceFieldTrials) &&
657 !command_line->HasSwitch(variations::switches::kVariationsServerURL))
658 chrome_variations::AssociateDefaultFieldTrialConfig();
659 #endif // defined(FIELDTRIAL_TESTING_ENABLED)
661 if (command_line->HasSwitch(switches::kForceVariationIds)) {
662 // Create default variation ids which will always be included in the
663 // X-Client-Data request header.
664 variations::VariationsHttpHeaderProvider* provider =
665 variations::VariationsHttpHeaderProvider::GetInstance();
666 bool result = provider->SetDefaultVariationIds(
667 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
668 CHECK(result) << "Invalid --" << switches::kForceVariationIds
669 << " list specified.";
670 metrics->AddSyntheticTrialObserver(provider);
673 scoped_ptr<base::FeatureList> feature_list(new base::FeatureList);
674 feature_list->InitializeFromCommandLine(
675 command_line->GetSwitchValueASCII(switches::kEnableFeatures),
676 command_line->GetSwitchValueASCII(switches::kDisableFeatures));
678 variations::VariationsService* variations_service =
679 browser_process_->variations_service();
680 if (variations_service)
681 variations_service->CreateTrialsFromSeed();
683 // TODO(asvitkine): Pass |feature_list| to CreateTrialsFromSeed() above.
684 base::FeatureList::SetInstance(feature_list.Pass());
686 // This must be called after |local_state_| is initialized.
687 browser_field_trials_.SetupFieldTrials();
689 // Enable Navigation Tracing only if a trace upload url is specified.
690 if (command_line->HasSwitch(switches::kEnableNavigationTracing) &&
691 command_line->HasSwitch(switches::kTraceUploadURL)) {
692 tracing::SetupNavigationTracing();
695 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
696 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
697 // Even though base::Bind does AddRef and Release, the object will not be
698 // deleted after the Task is executed.
699 field_trial_synchronizer_ = new FieldTrialSynchronizer();
701 // Now that field trials have been created, initializes metrics recording.
702 metrics->InitializeMetricsRecordingState();
704 const version_info::Channel channel = chrome::GetChannel();
706 // TODO(dalecurtis): Remove these checks and enable for all channels once we
707 // track down the root causes of crbug.com/422522 and crbug.com/478932.
708 if (channel == version_info::Channel::UNKNOWN ||
709 channel == version_info::Channel::CANARY ||
710 channel == version_info::Channel::DEV) {
711 media::AudioManager::EnableHangMonitor();
714 // Enable profiler instrumentation depending on the channel.
715 switch (channel) {
716 case version_info::Channel::UNKNOWN:
717 case version_info::Channel::CANARY:
718 tracked_objects::ScopedTracker::Enable();
719 break;
721 case version_info::Channel::DEV:
722 case version_info::Channel::BETA:
723 case version_info::Channel::STABLE:
724 // Don't enable instrumentation.
725 break;
728 // Register a synthetic field trial for the sampling profiler configuration
729 // that was already chosen.
730 sampling_profiler_config_.RegisterSyntheticFieldTrial();
733 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
735 void ChromeBrowserMainParts::StartMetricsRecording() {
736 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
738 g_browser_process->metrics_service()->CheckForClonedInstall(
739 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
741 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
744 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
745 // Don't record any metrics if UI was displayed before this point e.g.
746 // warning dialogs.
747 if (startup_metric_utils::WasNonBrowserUIDisplayed())
748 return;
750 bool is_first_run = false;
751 #if !defined(OS_ANDROID)
752 // On Android, first run is handled in Java code, and the C++ side of Chrome
753 // doesn't know if this is the first run. This will cause some inaccuracy in
754 // the UMA statistics, but this should be minor (first runs are rare).
755 is_first_run = first_run::IsChromeFirstRun();
756 #endif // defined(OS_ANDROID)
758 // Record collected startup metrics.
759 startup_metric_utils::RecordBrowserMainMessageLoopStart(base::Time::Now(),
760 is_first_run);
763 // -----------------------------------------------------------------------------
764 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
766 #if defined(OS_WIN)
767 #define DLLEXPORT __declspec(dllexport)
769 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
770 extern "C" {
771 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
774 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
775 // Need an instance of AtExitManager to handle singleton creations and
776 // deletions. We need this new instance because, the old instance created
777 // in ChromeMain() got destructed when the function returned.
778 base::AtExitManager exit_manager;
779 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
781 #endif
783 // content::BrowserMainParts implementation ------------------------------------
785 void ChromeBrowserMainParts::PreEarlyInitialization() {
786 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
787 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
788 chrome_extra_parts_[i]->PreEarlyInitialization();
791 void ChromeBrowserMainParts::PostEarlyInitialization() {
792 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
793 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
794 chrome_extra_parts_[i]->PostEarlyInitialization();
797 void ChromeBrowserMainParts::ToolkitInitialized() {
798 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
799 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
800 chrome_extra_parts_[i]->ToolkitInitialized();
803 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
804 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
806 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
807 chrome_extra_parts_[i]->PreMainMessageLoopStart();
810 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
811 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
813 // device_event_log must be initialized after the message loop. Calls to
814 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
815 // platforms (e.g. chromeos) may have already initialized this.
816 if (!device_event_log::IsInitialized())
817 device_event_log::Initialize(0 /* default max entries */);
819 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
820 chrome_extra_parts_[i]->PostMainMessageLoopStart();
823 int ChromeBrowserMainParts::PreCreateThreads() {
824 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
825 result_code_ = PreCreateThreadsImpl();
827 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
828 #if !defined(OS_ANDROID)
829 // These members must be initialized before exiting this function normally.
830 DCHECK(master_prefs_.get());
831 DCHECK(browser_creator_.get());
832 #endif // !defined(OS_ANDROID)
833 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
834 chrome_extra_parts_[i]->PreCreateThreads();
837 return result_code_;
840 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
841 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
842 run_message_loop_ = false;
843 #if !defined(OS_ANDROID)
844 chrome::MaybeShowInvalidUserDataDirWarningDialog();
845 #endif // !defined(OS_ANDROID)
846 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
847 return chrome::RESULT_CODE_MISSING_DATA;
849 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
850 MediaCaptureDevicesDispatcher::GetInstance();
852 // Android's first run is done in Java instead of native.
853 #if !defined(OS_ANDROID)
854 process_singleton_.reset(new ChromeProcessSingleton(
855 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
857 // Cache first run state early.
858 first_run::IsChromeFirstRun();
859 #endif // !defined(OS_ANDROID)
861 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
862 JsonPrefStore::GetTaskRunnerForFile(
863 base::FilePath(chrome::kLocalStorePoolName),
864 BrowserThread::GetBlockingPool());
867 TRACE_EVENT0("startup",
868 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
869 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
870 parsed_command_line()));
873 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
874 TRACE_EVENT0("startup",
875 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
876 // User wants to override default tracking status.
877 std::string flag =
878 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
879 // Default to basic profiling (no parent child support).
880 tracked_objects::ThreadData::Status status =
881 tracked_objects::ThreadData::PROFILING_ACTIVE;
882 if (flag.compare("0") != 0)
883 status = tracked_objects::ThreadData::DEACTIVATED;
884 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
887 local_state_ = InitializeLocalState(
888 local_state_task_runner.get(), parsed_command_line());
890 #if !defined(OS_ANDROID)
891 // These members must be initialized before returning from this function.
892 master_prefs_.reset(new first_run::MasterPrefs);
893 // Android doesn't use StartupBrowserCreator.
894 browser_creator_.reset(new StartupBrowserCreator);
895 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
896 chrome::UMABrowsingActivityObserver::Init();
897 #endif // !defined(OS_ANDROID)
899 #if !defined(OS_CHROMEOS)
900 // Convert active labs into switches. This needs to be done before
901 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
902 // affected by experiment flags (--touch-optimized-ui in particular).
903 // On ChromeOS system level flags are applied from the device settings from
904 // the session manager.
906 TRACE_EVENT0("startup",
907 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
908 about_flags::PrefServiceFlagsStorage flags_storage_(
909 g_browser_process->local_state());
910 about_flags::ConvertFlagsToSwitches(&flags_storage_,
911 base::CommandLine::ForCurrentProcess(),
912 about_flags::kAddSentinels);
914 #endif // !defined(OS_CHROMEOS)
916 #if defined(OS_WIN)
917 // This is needed to enable ETW exporting when requested in about:flags.
918 // Normally, we enable it in ContentMainRunnerImpl::Initialize when the flag
919 // is present on the command line but flags in about:flags are converted only
920 // after this function runs. Note that this starts exporting later which
921 // affects tracing the browser startup. Also, this is only relevant for the
922 // browser process, as other processes will get all the flags on their command
923 // line regardless of the origin (command line or about:flags).
924 if (parsed_command_line().HasSwitch(switches::kTraceExportEventsToETW))
925 base::trace_event::TraceEventETWExport::EnableETWExport();
926 #endif // OS_WIN
928 local_state_->UpdateCommandLinePrefStore(
929 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
931 // Reset the command line in the crash report details, since we may have
932 // just changed it to include experiments.
933 crash_keys::SetSwitchesFromCommandLine(
934 base::CommandLine::ForCurrentProcess());
936 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
937 // needed when loading the MainMenu.nib and the language doesn't depend on
938 // anything since it comes from Cocoa.
939 #if defined(OS_MACOSX)
940 std::string locale =
941 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
942 browser_process_->SetApplicationLocale(locale);
943 #else
944 const std::string locale =
945 local_state_->GetString(prefs::kApplicationLocale);
947 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
948 // method InitSharedInstance is ignored.
950 TRACE_EVENT_BEGIN0("startup",
951 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
952 const std::string loaded_locale =
953 ui::ResourceBundle::InitSharedInstanceWithLocale(
954 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
955 TRACE_EVENT_END0("startup",
956 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
958 if (loaded_locale.empty() &&
959 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
960 ShowMissingLocaleMessageBox();
961 return chrome::RESULT_CODE_MISSING_DATA;
963 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
964 browser_process_->SetApplicationLocale(loaded_locale);
967 TRACE_EVENT0("startup",
968 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
969 base::FilePath resources_pack_path;
970 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
971 #if defined(OS_ANDROID)
972 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path);
973 #else
974 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
975 resources_pack_path, ui::SCALE_FACTOR_NONE);
976 #endif // defined(OS_ANDROID)
978 #endif // defined(OS_MACOSX)
980 // Android does first run in Java instead of native.
981 // Chrome OS has its own out-of-box-experience code.
982 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
983 // On first run, we need to process the predictor preferences before the
984 // browser's profile_manager object is created, but after ResourceBundle
985 // is initialized.
986 if (first_run::IsChromeFirstRun()) {
987 first_run::ProcessMasterPreferencesResult pmp_result =
988 first_run::ProcessMasterPreferences(user_data_dir_,
989 master_prefs_.get());
990 if (pmp_result == first_run::EULA_EXIT_NOW)
991 return chrome::RESULT_CODE_EULA_REFUSED;
993 if (!parsed_command_line().HasSwitch(switches::kApp) &&
994 !parsed_command_line().HasSwitch(switches::kAppId) &&
995 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
996 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
999 // TODO(macourteau): refactor preferences that are copied from
1000 // master_preferences into local_state, as a "local_state" section in
1001 // master preferences. If possible, a generic solution would be preferred
1002 // over a copy one-by-one of specific preferences. Also see related TODO
1003 // in first_run.h.
1005 // Store the initial VariationsService seed in local state, if it exists
1006 // in master prefs.
1007 if (!master_prefs_->variations_seed.empty() ||
1008 !master_prefs_->compressed_variations_seed.empty()) {
1009 if (!master_prefs_->variations_seed.empty()) {
1010 local_state_->SetString(variations::prefs::kVariationsSeed,
1011 master_prefs_->variations_seed);
1013 if (!master_prefs_->compressed_variations_seed.empty()) {
1014 local_state_->SetString(variations::prefs::kVariationsCompressedSeed,
1015 master_prefs_->compressed_variations_seed);
1017 if (!master_prefs_->variations_seed_signature.empty()) {
1018 local_state_->SetString(variations::prefs::kVariationsSeedSignature,
1019 master_prefs_->variations_seed_signature);
1021 // Set the variation seed date to the current system time. If the user's
1022 // clock is incorrect, this may cause some field trial expiry checks to
1023 // not do the right thing until the next seed update from the server,
1024 // when this value will be updated.
1025 local_state_->SetInt64(variations::prefs::kVariationsSeedDate,
1026 base::Time::Now().ToInternalValue());
1029 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
1030 local_state_->SetString(
1031 prefs::kBrowserSuppressDefaultBrowserPrompt,
1032 master_prefs_->suppress_default_browser_prompt_for_version);
1035 #if defined(OS_WIN)
1036 if (!master_prefs_->welcome_page_on_os_upgrade_enabled)
1037 local_state_->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled, false);
1038 #endif
1040 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1042 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1043 // Set the product channel for crash reports.
1044 base::debug::SetCrashKeyValue(crash_keys::kChannel,
1045 chrome::GetChannelString());
1046 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1048 // Initialize tracking synchronizer system.
1049 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
1050 make_scoped_ptr(new base::DefaultTickClock()));
1052 #if defined(OS_MACOSX)
1053 // Get the Keychain API to register for distributed notifications on the main
1054 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1055 // which doesn't. This ensures those notifications will get delivered
1056 // properly. See issue 37766.
1057 // (Note that the callback mask here is empty. I don't want to register for
1058 // any callbacks, I just want to initialize the mechanism.)
1059 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1060 #endif // defined(OS_MACOSX)
1062 #if defined(OS_CHROMEOS)
1063 // Must be done after g_browser_process is constructed, before
1064 // SetupMetricsAndFieldTrials().
1065 chromeos::CrosSettings::Initialize();
1066 #endif // defined(OS_CHROMEOS)
1068 // Now the command line has been mutated based on about:flags, we can setup
1069 // metrics and initialize field trials. The field trials are needed by
1070 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1071 SetupMetricsAndFieldTrials();
1073 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1074 browser_process_->PreCreateThreads();
1076 return content::RESULT_CODE_NORMAL_EXIT;
1079 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1080 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1081 TRACK_SCOPED_REGION(
1082 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1084 result_code_ = PreMainMessageLoopRunImpl();
1086 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1087 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1090 // PreMainMessageLoopRun calls these extra stages in the following order:
1091 // PreMainMessageLoopRunImpl()
1092 // ... initial setup, including browser_process_ setup.
1093 // PreProfileInit()
1094 // ... additional setup, including CreateProfile()
1095 // PostProfileInit()
1096 // ... additional setup
1097 // PreBrowserStart()
1098 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1099 // PostBrowserStart()
1101 void ChromeBrowserMainParts::PreProfileInit() {
1102 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1104 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1105 chrome_extra_parts_[i]->PreProfileInit();
1107 #if !defined(OS_ANDROID)
1108 // Initialize the feedback uploader so it can setup notifications for profile
1109 // creation.
1110 feedback::FeedbackProfileObserver::Initialize();
1112 // Ephemeral profiles may have been left behind if the browser crashed.
1113 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1114 #endif // !defined(OS_ANDROID)
1116 #if defined(ENABLE_EXTENSIONS)
1117 javascript_dialog_extensions_client::InstallClient();
1118 #endif // defined(ENABLE_EXTENSIONS)
1120 #if !defined(OS_IOS)
1121 InstallChromeJavaScriptNativeDialogFactory();
1122 #endif // !defined(OS_IOS)
1125 void ChromeBrowserMainParts::PostProfileInit() {
1126 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1128 #if defined(OS_ANDROID)
1129 DevToolsDiscoveryProviderAndroid::Install();
1130 #else
1131 ChromeDevToolsDiscoveryProvider::Install();
1132 #endif // defined(OS_ANDROID)
1134 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1135 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1136 chrome_extra_parts_[i]->PostProfileInit();
1139 void ChromeBrowserMainParts::PreBrowserStart() {
1140 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1141 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1142 chrome_extra_parts_[i]->PreBrowserStart();
1144 three_d_observer_.reset(new ThreeDAPIObserver());
1146 // Start the out-of-memory priority manager here so that we give the most
1147 // amount of time for the other services to start up before we start
1148 // adjusting the oom priority.
1150 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1151 // now.
1152 #if defined(OS_CHROMEOS)
1153 g_browser_process->GetOomPriorityManager()->Start(false);
1154 #elif defined(OS_WIN) || defined(OS_MACOSX)
1155 const std::string group_name =
1156 base::FieldTrialList::FindFullName("AutomaticTabDiscarding");
1157 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding) ||
1158 base::StartsWith(group_name, "Enabled", base::CompareCase::SENSITIVE)) {
1159 bool enabled_once = base::StartsWith(group_name, "Enabled_Once",
1160 base::CompareCase::SENSITIVE);
1161 g_browser_process->GetOomPriorityManager()->Start(enabled_once);
1163 #endif
1166 void ChromeBrowserMainParts::PostBrowserStart() {
1167 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1168 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1169 chrome_extra_parts_[i]->PostBrowserStart();
1170 #if !defined(OS_ANDROID)
1171 // Allow ProcessSingleton to process messages.
1172 process_singleton_->Unlock();
1173 #endif // !defined(OS_ANDROID)
1174 #if defined(ENABLE_WEBRTC)
1175 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1176 // to reduce the impact on startup time.
1177 BrowserThread::PostDelayedTask(
1178 BrowserThread::UI,
1179 FROM_HERE,
1180 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1181 base::TimeDelta::FromMinutes(1));
1182 #endif // defined(ENABLE_WEBRTC)
1184 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1185 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1186 switches::kEnableWebUsbNotifications)) {
1187 webusb_browser_client_.reset(new ChromeWebUsbBrowserClient());
1188 webusb_detector_.reset(
1189 new webusb::WebUsbDetector(webusb_browser_client_.get()));
1191 #endif
1193 // At this point, StartupBrowserCreator::Start has run creating initial
1194 // browser windows and tabs, but no progress has been made in loading
1195 // content as the main message loop hasn't started processing tasks yet.
1196 // We setup to observe to the initial page load here to defer running
1197 // task posted via PostAfterStartupTask until its complete.
1198 AfterStartupTaskUtils::StartMonitoringStartup();
1201 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1202 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1203 TRACK_SCOPED_REGION(
1204 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1206 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1207 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1209 #if defined(OS_WIN)
1210 // Windows parental controls calls can be slow, so we do an early init here
1211 // that calculates this value off of the UI thread.
1212 IncognitoModePrefs::InitializePlatformParentalControls();
1213 #endif
1215 #if defined(ENABLE_EXTENSIONS)
1216 if (!variations::GetVariationParamValue(
1217 "LightSpeed", "EarlyInitStartup").empty()) {
1218 // Try to compute this early on another thread so that we don't spend time
1219 // during profile load initializing the extensions APIs.
1220 BrowserThread::PostTask(
1221 BrowserThread::FILE_USER_BLOCKING,
1222 FROM_HERE,
1223 base::Bind(
1224 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1226 #endif
1228 // Android updates the metrics service dynamically depending on whether the
1229 // application is in the foreground or not. Do not start here.
1230 #if !defined(OS_ANDROID)
1231 // Now that the file thread has been started, start recording.
1232 StartMetricsRecording();
1233 #endif // !defined(OS_ANDROID)
1235 if (!base::debug::BeingDebugged()) {
1236 // Create watchdog thread after creating all other threads because it will
1237 // watch the other threads and they must be running.
1238 browser_process_->watchdog_thread();
1241 // Do any initializating in the browser process that requires all threads
1242 // running.
1243 browser_process_->PreMainMessageLoopRun();
1245 // Record last shutdown time into a histogram.
1246 browser_shutdown::ReadLastShutdownInfo();
1248 #if defined(OS_WIN)
1249 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1250 // tasks. Those care whether the browser is already running. On Linux/Mac,
1251 // upgrade/uninstall happen separately.
1252 bool already_running = browser_util::IsBrowserAlreadyRunning();
1254 // If the command line specifies 'uninstall' then we need to work here
1255 // unless we detect another chrome browser running.
1256 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1257 return DoUninstallTasks(already_running);
1260 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1261 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1262 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1263 parsed_command_line_);
1266 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1267 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1268 #endif // defined(OS_WIN)
1270 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1271 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1272 prefs::kDefaultBrowserSettingEnabled);
1273 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1274 prefs::kDefaultBrowserSettingEnabled)) {
1275 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1278 return ShellIntegration::SetAsDefaultBrowser() ?
1279 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1280 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1283 #if defined(USE_AURA)
1284 // Make sure aura::Env has been initialized.
1285 CHECK(aura::Env::GetInstance());
1286 #endif // defined(USE_AURA)
1288 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1289 #if !defined(OS_ANDROID)
1290 // If the command line specifies --pack-extension, attempt the pack extension
1291 // startup action and exit.
1292 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1293 extensions::StartupHelper extension_startup_helper;
1294 if (extension_startup_helper.PackExtension(parsed_command_line()))
1295 return content::RESULT_CODE_NORMAL_EXIT;
1296 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1299 // When another process is running, use that process instead of starting a
1300 // new one. NotifyOtherProcess will currently give the other process up to
1301 // 20 seconds to respond. Note that this needs to be done before we attempt
1302 // to read the profile.
1303 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1304 switch (notify_result_) {
1305 case ProcessSingleton::PROCESS_NONE:
1306 // No process already running, fall through to starting a new one.
1307 break;
1309 case ProcessSingleton::PROCESS_NOTIFIED:
1310 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1311 // On POSIX systems, print a message notifying the process is running.
1312 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1313 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1314 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1316 // Having a differentiated return type for testing allows for tests to
1317 // verify proper handling of some switches. When not testing, stick to
1318 // the standard Unix convention of returning zero when things went as
1319 // expected.
1320 if (parsed_command_line().HasSwitch(switches::kTestType))
1321 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1322 return content::RESULT_CODE_NORMAL_EXIT;
1324 case ProcessSingleton::PROFILE_IN_USE:
1325 return chrome::RESULT_CODE_PROFILE_IN_USE;
1327 case ProcessSingleton::LOCK_ERROR:
1328 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1329 "directory. This means that running multiple instances "
1330 "would start multiple browser processes rather than "
1331 "opening a new window in the existing process. Aborting "
1332 "now to avoid profile corruption.";
1333 return chrome::RESULT_CODE_PROFILE_IN_USE;
1335 default:
1336 NOTREACHED();
1338 #endif // !defined(OS_ANDROID)
1340 // Handle special early return paths (which couldn't be processed even earlier
1341 // as they require the process singleton to be held) first.
1343 std::string try_chrome =
1344 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1345 if (!try_chrome.empty()) {
1346 #if defined(OS_WIN)
1347 // Setup.exe has determined that we need to run a retention experiment
1348 // and has lauched chrome to show the experiment UI. It is guaranteed that
1349 // no other Chrome is currently running as the process singleton was
1350 // sucessfully grabbed above.
1351 int try_chrome_int;
1352 base::StringToInt(try_chrome, &try_chrome_int);
1353 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1354 try_chrome_int,
1355 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1356 base::Unretained(process_singleton_.get())));
1357 if (answer == TryChromeDialogView::NOT_NOW)
1358 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1359 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1360 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1361 // At this point the user is willing to try chrome again.
1362 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1363 // Only set in the unattended case, the interactive case is Windows 8.
1364 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1365 ShellIntegration::SET_DEFAULT_UNATTENDED)
1366 ShellIntegration::SetAsDefaultBrowser();
1368 #else
1369 // We don't support retention experiments on Mac or Linux.
1370 return content::RESULT_CODE_NORMAL_EXIT;
1371 #endif // defined(OS_WIN)
1374 #if defined(OS_WIN)
1375 // Do the tasks if chrome has been upgraded while it was last running.
1376 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1377 return content::RESULT_CODE_NORMAL_EXIT;
1379 // Check if there is any machine level Chrome installed on the current
1380 // machine. If yes and the current Chrome process is user level, we do not
1381 // allow the user level Chrome to run. So we notify the user and uninstall
1382 // user level Chrome.
1383 // Note this check needs to happen here (after the process singleton was
1384 // obtained but before potentially creating the first run sentinel).
1385 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1386 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1387 #endif // defined(OS_WIN)
1389 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1390 if (sxs_linux::ShouldMigrateUserDataDir())
1391 return sxs_linux::MigrateUserDataDir();
1392 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1394 // Desktop construction occurs here, (required before profile creation).
1395 PreProfileInit();
1397 // Profile creation ----------------------------------------------------------
1399 metrics::MetricsService::SetExecutionPhase(
1400 metrics::MetricsService::CREATE_PROFILE,
1401 g_browser_process->local_state());
1403 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1404 base::TimeTicks::Now() - start_time_step1);
1406 // This step is costly and is already measured in Startup.CreateFirstProfile
1407 // and more directly Profile.CreateAndInitializeProfile.
1408 profile_ = CreatePrimaryProfile(parameters(),
1409 user_data_dir_,
1410 parsed_command_line());
1411 if (!profile_)
1412 return content::RESULT_CODE_NORMAL_EXIT;
1414 #if !defined(OS_ANDROID)
1415 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1416 // The first run sentinel must be created after the process singleton was
1417 // grabbed and no early return paths were otherwise hit above.
1418 first_run::CreateSentinelIfNeeded();
1419 #endif // !defined(OS_ANDROID)
1421 #if defined(ENABLE_BACKGROUND)
1422 // Autoload any profiles which are running background apps.
1423 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1424 browser_process_->profile_manager()->AutoloadProfiles();
1425 #endif // defined(ENABLE_BACKGROUND)
1426 // Post-profile init ---------------------------------------------------------
1428 TranslateService::Initialize();
1430 // Needs to be done before PostProfileInit, since login manager on CrOS is
1431 // called inside PostProfileInit.
1432 content::WebUIControllerFactory::RegisterFactory(
1433 ChromeWebUIControllerFactory::GetInstance());
1435 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1436 // So make sure to create it before that.
1437 #if !defined(DISABLE_NACL)
1438 NaClBrowserDelegateImpl* delegate =
1439 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1440 nacl::NaClBrowser::SetDelegate(delegate);
1441 #endif // !defined(DISABLE_NACL)
1443 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1444 // (requires supporting early exit).
1445 PostProfileInit();
1447 // Retrieve cached GL strings from local state and use them for GPU
1448 // blacklist decisions.
1449 if (g_browser_process->gl_string_manager())
1450 g_browser_process->gl_string_manager()->Initialize();
1452 // Create an instance of GpuModeManager to watch gpu mode pref change.
1453 g_browser_process->gpu_mode_manager();
1455 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1456 // Show the First Run UI if this is the first time Chrome has been run on
1457 // this computer, or we're being compelled to do so by a command line flag.
1458 // Note that this be done _after_ the PrefService is initialized and all
1459 // preferences are registered, since some of the code that the importer
1460 // touches reads preferences.
1461 if (first_run::IsChromeFirstRun()) {
1462 first_run::AutoImport(profile_,
1463 master_prefs_->homepage_defined,
1464 master_prefs_->do_import_items,
1465 master_prefs_->dont_import_items,
1466 master_prefs_->import_bookmarks_path);
1468 // Note: this can pop the first run consent dialog on linux.
1469 first_run::DoPostImportTasks(profile_,
1470 master_prefs_->make_chrome_default_for_user);
1472 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1473 browser_creator_->set_show_main_browser_window(
1474 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1475 } else {
1476 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1479 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1481 #if defined(OS_WIN)
1482 // Sets things up so that if we crash from this point on, a dialog will
1483 // popup asking the user to restart chrome. It is done this late to avoid
1484 // testing against a bunch of special cases that are taken care early on.
1485 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1486 parsed_command_line());
1488 // Registers Chrome with the Windows Restart Manager, which will restore the
1489 // Chrome session when the computer is restarted after a system update.
1490 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1491 // but should run on startup if extended to handle crashes/hangs/patches.
1492 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1493 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1494 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1495 parsed_command_line());
1498 // Verify that the profile is not on a network share and if so prepare to show
1499 // notification to the user.
1500 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1501 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1502 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1503 profile_->GetPath()));
1505 #endif // defined(OS_WIN)
1507 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1508 // Init the RLZ library. This just binds the dll and schedules a task on the
1509 // file thread to be run sometime later. If this is the first run we record
1510 // the installation event.
1511 PrefService* pref_service = profile_->GetPrefs();
1512 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1513 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1514 // Negative ping delay means to send ping immediately after a first search is
1515 // recorded.
1516 rlz::RLZTracker::SetRlzDelegate(
1517 make_scoped_ptr(new ChromeRLZTrackerDelegate));
1518 rlz::RLZTracker::InitRlzDelayed(
1519 first_run::IsChromeFirstRun(), ping_delay < 0,
1520 base::TimeDelta::FromMilliseconds(abs(ping_delay)),
1521 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
1522 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
1523 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
1524 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1526 // Configure modules that need access to resources.
1527 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1529 // In unittest mode, this will do nothing. In normal mode, this will create
1530 // the global IntranetRedirectDetector instance, which will promptly go to
1531 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1532 // to see if it should do anything else.
1534 // A simpler way of doing all this would be to have some function which could
1535 // give the time elapsed since startup, and simply have this object check that
1536 // when asked to initialize itself, but this doesn't seem to exist.
1538 // This can't be created in the BrowserProcessImpl constructor because it
1539 // needs to read prefs that get set after that runs.
1540 browser_process_->intranet_redirect_detector();
1542 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1543 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1544 base::FilePath path =
1545 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1546 printing::PrintedDocument::set_debug_dump_path(path);
1548 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1550 HandleTestParameters(parsed_command_line());
1551 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1552 base::debug::BeingDebugged());
1554 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1555 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1556 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1557 browser_process_->GetApplicationLocale());
1559 // Start watching for hangs during startup. We disarm this hang detector when
1560 // ThreadWatcher takes over or when browser is shutdown or when
1561 // startup_watcher_ is deleted.
1562 metrics::MetricsService::SetExecutionPhase(
1563 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1564 g_browser_process->local_state());
1565 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1567 // On mobile, need for clean shutdown arises only when the application comes
1568 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1569 // http://crbug.com/179143
1570 #if !defined(OS_ANDROID)
1571 // Start watching for a hang.
1572 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1573 #endif // !defined(OS_ANDROID)
1575 #if defined(ENABLE_PRINT_PREVIEW)
1576 // Create the instance of the cloud print proxy service so that it can launch
1577 // the service process if needed. This is needed because the service process
1578 // might have shutdown because an update was available.
1579 // TODO(torne): this should maybe be done with
1580 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1581 // instead?
1582 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1583 #endif // defined(ENABLE_PRINT_PREVIEW)
1585 // Start watching all browser threads for responsiveness.
1586 metrics::MetricsService::SetExecutionPhase(
1587 metrics::MetricsService::THREAD_WATCHER_START,
1588 g_browser_process->local_state());
1589 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1591 #if defined(OS_ANDROID)
1592 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1593 #endif // defined(OS_ANDROID)
1595 #if !defined(DISABLE_NACL)
1596 BrowserThread::PostTask(
1597 BrowserThread::IO,
1598 FROM_HERE,
1599 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1600 #endif // !defined(DISABLE_NACL)
1602 // Make sure initial prefs are recorded
1603 PrefMetricsService::Factory::GetForProfile(profile_);
1605 PreBrowserStart();
1607 // Instantiate the notification UI manager, as this triggers a perf timer
1608 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1609 // triggering the timer and call that explicitly in the approprate place.
1610 // http://crbug.com/105065.
1611 browser_process_->notification_ui_manager();
1613 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1614 // data source is based on the Component Updater.
1615 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1617 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1618 RegisterComponentsForUpdate();
1620 #if defined(OS_ANDROID)
1621 variations::VariationsService* variations_service =
1622 browser_process_->variations_service();
1623 if (variations_service) {
1624 // Just initialize the policy prefs service here. Variations seed fetching
1625 // will be initialized when the app enters foreground mode.
1626 variations_service->set_policy_pref_service(profile_->GetPrefs());
1628 translate::TranslateDownloadManager::RequestLanguageList(
1629 profile_->GetPrefs());
1631 #else
1632 // Most general initialization is behind us, but opening a
1633 // tab and/or session restore and such is still to be done.
1634 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1636 // We are in regular browser boot sequence. Open initial tabs and enter the
1637 // main message loop.
1638 std::vector<Profile*> last_opened_profiles;
1639 #if !defined(OS_CHROMEOS)
1640 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1641 // them this early as the cryptohome hasn't yet been mounted (which happens
1642 // only once we log in).
1643 last_opened_profiles =
1644 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1645 #endif // defined(OS_CHROMEOS)
1647 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1648 base::TimeTicks::Now() - start_time_step2);
1650 // This step is costly and is already measured in
1651 // Startup.StartupBrowserCreator_Start.
1652 const bool started = browser_creator_->Start(
1653 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1654 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1655 if (started) {
1656 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1657 // Initialize autoupdate timer. Timer callback costs basically nothing
1658 // when browser is not in persistent mode, so it's OK to let it ride on
1659 // the main thread. This needs to be done here because we don't want
1660 // to start the timer when Chrome is run inside a test harness.
1661 browser_process_->StartAutoupdateTimer();
1662 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1664 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1665 // On Linux, the running exe will be updated if an upgrade becomes
1666 // available while the browser is running. We need to save the last
1667 // modified time of the exe, so we can compare to determine if there is
1668 // an upgrade while the browser is kept alive by a persistent extension.
1669 upgrade_util::SaveLastModifiedTimeOfExe();
1670 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1672 // Record now as the last successful chrome start.
1673 GoogleUpdateSettings::SetLastRunTime();
1675 #if defined(OS_MACOSX)
1676 // Call Recycle() here as late as possible, before going into the loop
1677 // because Start() will add things to it while creating the main window.
1678 if (parameters().autorelease_pool)
1679 parameters().autorelease_pool->Recycle();
1680 #endif // defined(OS_MACOSX)
1682 const base::TimeDelta delta = base::TimeTicks::Now() - browser_open_start;
1683 startup_metric_utils::RecordBrowserOpenTabsDelta(delta);
1685 // If we're running tests (ui_task is non-null), then we don't want to
1686 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1687 // RequestLanguageList
1688 if (parameters().ui_task == NULL) {
1689 // Request new variations seed information from server.
1690 variations::VariationsService* variations_service =
1691 browser_process_->variations_service();
1692 if (variations_service)
1693 variations_service->PerformPreMainMessageLoopStartup();
1695 translate::TranslateDownloadManager::RequestLanguageList(
1696 profile_->GetPrefs());
1699 run_message_loop_ = started;
1700 browser_creator_.reset();
1702 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1703 if (g_browser_process->metrics_service()->reporting_active())
1704 content::StartPowerUsageMonitor();
1705 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1707 process_power_collector_.reset(new ProcessPowerCollector);
1708 process_power_collector_->Initialize();
1709 #endif // !defined(OS_ANDROID)
1711 PostBrowserStart();
1713 if (parameters().ui_task) {
1714 parameters().ui_task->Run();
1715 delete parameters().ui_task;
1716 run_message_loop_ = false;
1718 #if defined(OS_ANDROID)
1719 // We never run the C++ main loop on Android, since the UI thread message
1720 // loop is controlled by the OS, so this is as close as we can get to
1721 // the start of the main loop.
1722 if (result_code_ <= 0) {
1723 RecordBrowserStartupTime();
1725 #endif // defined(OS_ANDROID)
1727 #if !defined(OS_ANDROID)
1728 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1729 base::TimeTicks::Now() - start_time_step3);
1730 #endif // !defined(OS_ANDROID)
1732 return result_code_;
1735 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1736 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1737 #if defined(OS_ANDROID)
1738 // Chrome on Android does not use default MessageLoop. It has its own
1739 // Android specific MessageLoop
1740 NOTREACHED();
1741 return true;
1742 #else
1743 // Set the result code set in PreMainMessageLoopRun or set above.
1744 *result_code = result_code_;
1745 if (!run_message_loop_)
1746 return true; // Don't run the default message loop.
1748 // These should be invoked as close to the start of the browser's
1749 // UI thread message loop as possible to get a stable measurement
1750 // across versions.
1751 RecordBrowserStartupTime();
1753 DCHECK(base::MessageLoopForUI::IsCurrent());
1754 base::RunLoop run_loop;
1756 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1758 metrics::MetricsService::SetExecutionPhase(
1759 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1760 g_browser_process->local_state());
1761 run_loop.Run();
1763 return true;
1764 #endif // defined(OS_ANDROID)
1767 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1768 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1769 #if defined(OS_ANDROID)
1770 // Chrome on Android does not use default MessageLoop. It has its own
1771 // Android specific MessageLoop
1772 NOTREACHED();
1773 #else
1774 // Start watching for jank during shutdown. It gets disarmed when
1775 // |shutdown_watcher_| object is destructed.
1776 metrics::MetricsService::SetExecutionPhase(
1777 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1778 g_browser_process->local_state());
1779 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1781 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1782 startup_watcher_->Disarm();
1784 // Remove observers attached to D-Bus clients before DbusThreadManager is
1785 // shut down.
1786 process_power_collector_.reset();
1788 #if !defined(OS_IOS)
1789 webusb_detector_.reset();
1790 webusb_browser_client_.reset();
1791 #endif
1793 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1794 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1796 // Some tests don't set parameters.ui_task, so they started translate
1797 // language fetch that was never completed so we need to cleanup here
1798 // otherwise it will be done by the destructor in a wrong thread.
1799 TranslateService::Shutdown(parameters().ui_task == NULL);
1801 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1802 process_singleton_->Cleanup();
1804 // Stop all tasks that might run on WatchDogThread.
1805 ThreadWatcherList::StopWatchingAll();
1807 browser_process_->metrics_service()->Stop();
1809 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1810 browser_process_->StartTearDown();
1811 #endif // defined(OS_ANDROID)
1814 void ChromeBrowserMainParts::PostDestroyThreads() {
1815 #if defined(OS_ANDROID)
1816 // On Android, there is no quit/exit. So the browser's main message loop will
1817 // not finish.
1818 NOTREACHED();
1819 #else
1820 browser_process_->PostDestroyThreads();
1821 // browser_shutdown takes care of deleting browser_process, so we need to
1822 // release it.
1823 ignore_result(browser_process_.release());
1824 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1825 master_prefs_.reset();
1826 process_singleton_.reset();
1827 device_event_log::Shutdown();
1829 // We need to do this check as late as possible, but due to modularity, this
1830 // may be the last point in Chrome. This would be more effective if done at
1831 // a higher level on the stack, so that it is impossible for an early return
1832 // to bypass this code. Perhaps we need a *final* hook that is called on all
1833 // paths from content/browser/browser_main.
1834 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1836 #if defined(OS_CHROMEOS)
1837 chromeos::CrosSettings::Shutdown();
1838 #endif // defined(OS_CHROMEOS)
1839 #endif // defined(OS_ANDROID)
1842 // Public members:
1844 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1845 chrome_extra_parts_.push_back(parts);