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. 4 5 #include "chrome/browser/chrome_browser_main.h" 6 7 #include <set> 8 #include <string> 9 #include <vector> 10 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/debug/trace_event.h" 17 #include "base/file_util.h" 18 #include "base/files/file_path.h" 19 #include "base/metrics/field_trial.h" 20 #include "base/metrics/histogram.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/process/process_info.h" 28 #include "base/run_loop.h" 29 #include "base/strings/string_number_conversions.h" 30 #include "base/strings/string_piece.h" 31 #include "base/strings/string_split.h" 32 #include "base/strings/sys_string_conversions.h" 33 #include "base/strings/utf_string_conversions.h" 34 #include "base/sys_info.h" 35 #include "base/threading/platform_thread.h" 36 #include "base/time/time.h" 37 #include "base/values.h" 38 #include "build/build_config.h" 39 #include "chrome/browser/about_flags.h" 40 #include "chrome/browser/browser_process.h" 41 #include "chrome/browser/browser_process_impl.h" 42 #include "chrome/browser/browser_process_platform_part.h" 43 #include "chrome/browser/browser_shutdown.h" 44 #include "chrome/browser/chrome_browser_main_extra_parts.h" 45 #include "chrome/browser/component_updater/cld_component_installer.h" 46 #include "chrome/browser/component_updater/component_updater_service.h" 47 #include "chrome/browser/component_updater/flash_component_installer.h" 48 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h" 49 #include "chrome/browser/component_updater/recovery_component_installer.h" 50 #include "chrome/browser/component_updater/swiftshader_component_installer.h" 51 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h" 52 #include "chrome/browser/defaults.h" 53 #include "chrome/browser/extensions/extension_service.h" 54 #include "chrome/browser/extensions/startup_helper.h" 55 #include "chrome/browser/first_run/first_run.h" 56 #include "chrome/browser/first_run/upgrade_util.h" 57 #include "chrome/browser/google/google_search_counter.h" 58 #include "chrome/browser/gpu/gl_string_manager.h" 59 #include "chrome/browser/gpu/three_d_api_observer.h" 60 #include "chrome/browser/jankometer.h" 61 #include "chrome/browser/media/media_capture_devices_dispatcher.h" 62 #include "chrome/browser/metrics/field_trial_synchronizer.h" 63 #include "chrome/browser/metrics/thread_watcher.h" 64 #include "chrome/browser/metrics/tracking_synchronizer.h" 65 #include "chrome/browser/metrics/variations/variations_http_header_provider.h" 66 #include "chrome/browser/metrics/variations/variations_service.h" 67 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h" 68 #include "chrome/browser/net/chrome_net_log.h" 69 #include "chrome/browser/net/crl_set_fetcher.h" 70 #include "chrome/browser/notifications/desktop_notification_service.h" 71 #include "chrome/browser/notifications/desktop_notification_service_factory.h" 72 #include "chrome/browser/performance_monitor/performance_monitor.h" 73 #include "chrome/browser/performance_monitor/startup_timer.h" 74 #include "chrome/browser/plugins/plugin_prefs.h" 75 #include "chrome/browser/pref_service_flags_storage.h" 76 #include "chrome/browser/prefs/chrome_pref_service_factory.h" 77 #include "chrome/browser/prefs/command_line_pref_store.h" 78 #include "chrome/browser/prefs/pref_metrics_service.h" 79 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h" 80 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h" 81 #include "chrome/browser/process_singleton.h" 82 #include "chrome/browser/profiles/profile.h" 83 #include "chrome/browser/profiles/profile_manager.h" 84 #include "chrome/browser/profiles/profiles_state.h" 85 #include "chrome/browser/shell_integration.h" 86 #include "chrome/browser/translate/translate_service.h" 87 #include "chrome/browser/ui/app_list/app_list_service.h" 88 #include "chrome/browser/ui/browser.h" 89 #include "chrome/browser/ui/browser_finder.h" 90 #include "chrome/browser/ui/host_desktop.h" 91 #include "chrome/browser/ui/startup/bad_flags_prompt.h" 92 #include "chrome/browser/ui/startup/default_browser_prompt.h" 93 #include "chrome/browser/ui/startup/startup_browser_creator.h" 94 #include "chrome/browser/ui/uma_browsing_activity_observer.h" 95 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" 96 #include "chrome/common/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/installer/util/google_update_settings.h" 107 #include "components/google/core/browser/google_util.h" 108 #include "components/language_usage_metrics/language_usage_metrics.h" 109 #include "components/metrics/metrics_service.h" 110 #include "components/nacl/browser/nacl_browser.h" 111 #include "components/nacl/browser/nacl_process_host.h" 112 #include "components/rappor/rappor_service.h" 113 #include "components/signin/core/common/profile_management_switches.h" 114 #include "components/startup_metric_utils/startup_metric_utils.h" 115 #include "components/translate/core/browser/translate_download_manager.h" 116 #include "content/public/browser/browser_thread.h" 117 #include "content/public/browser/notification_observer.h" 118 #include "content/public/browser/notification_registrar.h" 119 #include "content/public/browser/notification_service.h" 120 #include "content/public/browser/notification_types.h" 121 #include "content/public/browser/site_instance.h" 122 #include "content/public/common/content_client.h" 123 #include "content/public/common/content_switches.h" 124 #include "content/public/common/main_function_params.h" 125 #include "extensions/browser/extension_protocols.h" 126 #include "grit/app_locale_settings.h" 127 #include "grit/browser_resources.h" 128 #include "grit/chromium_strings.h" 129 #include "grit/generated_resources.h" 130 #include "grit/platform_locale_settings.h" 131 #include "net/base/net_module.h" 132 #include "net/base/sdch_manager.h" 133 #include "net/cookies/cookie_monster.h" 134 #include "net/http/http_network_layer.h" 135 #include "net/http/http_stream_factory.h" 136 #include "net/url_request/url_request.h" 137 #include "ui/base/l10n/l10n_util.h" 138 #include "ui/base/layout.h" 139 #include "ui/base/resource/resource_bundle.h" 140 141 #if defined(OS_ANDROID) 142 #include "chrome/browser/metrics/thread_watcher_android.h" 143 #else 144 #include "chrome/browser/feedback/feedback_profile_observer.h" 145 #endif 146 147 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) 148 #include "chrome/browser/first_run/upgrade_util_linux.h" 149 #include "chrome/browser/sxs_linux.h" 150 #endif 151 152 #if defined(OS_CHROMEOS) 153 #include "chrome/browser/chromeos/settings/cros_settings.h" 154 #include "chromeos/chromeos_switches.h" 155 #include "chromeos/settings/cros_settings_names.h" 156 #endif 157 158 // TODO(port): several win-only methods have been pulled out of this, but 159 // BrowserMain() as a whole needs to be broken apart so that it's usable by 160 // other platforms. For now, it's just a stub. This is a serious work in 161 // progress and should not be taken as an indication of a real refactoring. 162 163 #if defined(OS_WIN) 164 #include "base/environment.h" // For PreRead experiment. 165 #include "base/win/windows_version.h" 166 #include "chrome/browser/browser_util_win.h" 167 #include "chrome/browser/chrome_browser_main_win.h" 168 #include "chrome/browser/component_updater/sw_reporter_installer_win.h" 169 #include "chrome/browser/first_run/try_chrome_dialog_view.h" 170 #include "chrome/browser/first_run/upgrade_util_win.h" 171 #include "chrome/browser/ui/network_profile_bubble.h" 172 #include "chrome/installer/util/helper.h" 173 #include "chrome/installer/util/install_util.h" 174 #include "chrome/installer/util/shell_util.h" 175 #include "net/base/net_util.h" 176 #include "ui/base/l10n/l10n_util_win.h" 177 #include "ui/gfx/win/dpi.h" 178 #endif // defined(OS_WIN) 179 180 #if defined(OS_MACOSX) 181 #include <Security/Security.h> 182 183 #include "base/mac/scoped_nsautorelease_pool.h" 184 #include "chrome/browser/mac/keystone_glue.h" 185 #endif 186 187 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD) 188 #include "printing/printed_document.h" 189 #endif 190 191 #if defined(ENABLE_RLZ) 192 #include "chrome/browser/rlz/rlz.h" 193 #endif 194 195 #if defined(ENABLE_WEBRTC) 196 #include "chrome/browser/media/webrtc_log_util.h" 197 #endif 198 199 #if defined(USE_AURA) 200 #include "ui/aura/env.h" 201 #endif 202 203 using content::BrowserThread; 204 205 namespace { 206 207 // This function provides some ways to test crash and assertion handling 208 // behavior of the program. 209 void HandleTestParameters(const CommandLine& command_line) { 210 // This parameter causes an assertion. 211 if (command_line.HasSwitch(switches::kBrowserAssertTest)) { 212 DCHECK(false); 213 } 214 215 // This parameter causes a null pointer crash (crash reporter trigger). 216 if (command_line.HasSwitch(switches::kBrowserCrashTest)) { 217 int* bad_pointer = NULL; 218 *bad_pointer = 0; 219 } 220 } 221 222 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) 223 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator, 224 const std::vector<GURL>& new_tabs) { 225 for (std::vector<GURL>::const_iterator it = new_tabs.begin(); 226 it != new_tabs.end(); ++it) { 227 if (it->is_valid()) 228 browser_creator->AddFirstRunTab(*it); 229 } 230 } 231 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) 232 233 // Returns the new local state object, guaranteed non-NULL. 234 // |local_state_task_runner| must be a shutdown-blocking task runner. 235 PrefService* InitializeLocalState( 236 base::SequencedTaskRunner* local_state_task_runner, 237 const CommandLine& parsed_command_line) { 238 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState") 239 base::FilePath local_state_path; 240 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path); 241 bool local_state_file_exists = base::PathExists(local_state_path); 242 243 // Load local state. This includes the application locale so we know which 244 // locale dll to load. This also causes local state prefs to be registered. 245 PrefService* local_state = g_browser_process->local_state(); 246 DCHECK(local_state); 247 248 #if defined(OS_WIN) 249 if (first_run::IsChromeFirstRun()) { 250 // During first run we read the google_update registry key to find what 251 // language the user selected when downloading the installer. This 252 // becomes our default language in the prefs. 253 // Other platforms obey the system locale. 254 base::string16 install_lang; 255 if (GoogleUpdateSettings::GetLanguage(&install_lang)) { 256 local_state->SetString(prefs::kApplicationLocale, 257 base::UTF16ToASCII(install_lang)); 258 } 259 } 260 #endif // defined(OS_WIN) 261 262 // If the local state file for the current profile doesn't exist and the 263 // parent profile command line flag is present, then we should inherit some 264 // local state from the parent profile. 265 // Checking that the local state file for the current profile doesn't exist 266 // is the most robust way to determine whether we need to inherit or not 267 // since the parent profile command line flag can be present even when the 268 // current profile is not a new one, and in that case we do not want to 269 // inherit and reset the user's setting. 270 // 271 // TODO(mnissler): We should probably just instantiate a 272 // JSONPrefStore here instead of an entire PrefService. Once this is 273 // addressed, the call to browser_prefs::RegisterLocalState can move 274 // to chrome_prefs::CreateLocalState. 275 if (!local_state_file_exists && 276 parsed_command_line.HasSwitch(switches::kParentProfile)) { 277 base::FilePath parent_profile = 278 parsed_command_line.GetSwitchValuePath(switches::kParentProfile); 279 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple(); 280 scoped_ptr<PrefService> parent_local_state( 281 chrome_prefs::CreateLocalState( 282 parent_profile, 283 local_state_task_runner, 284 g_browser_process->policy_service(), 285 registry, 286 false)); 287 registry->RegisterStringPref(prefs::kApplicationLocale, std::string()); 288 // Right now, we only inherit the locale setting from the parent profile. 289 local_state->SetString( 290 prefs::kApplicationLocale, 291 parent_local_state->GetString(prefs::kApplicationLocale)); 292 } 293 294 #if defined(OS_CHROMEOS) 295 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) { 296 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale); 297 // Ensure that we start with owner's locale. 298 if (!owner_locale.empty() && 299 local_state->GetString(prefs::kApplicationLocale) != owner_locale && 300 !local_state->IsManagedPreference(prefs::kApplicationLocale)) { 301 local_state->SetString(prefs::kApplicationLocale, owner_locale); 302 } 303 } 304 #endif 305 306 return local_state; 307 } 308 309 // Initializes the primary profile, possibly doing some user prompting to pick 310 // a fallback profile. Returns the newly created profile, or NULL if startup 311 // should not continue. 312 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters, 313 const base::FilePath& user_data_dir, 314 const CommandLine& parsed_command_line) { 315 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile") 316 base::Time start = base::Time::Now(); 317 if (profiles::IsMultipleProfilesEnabled() && 318 parsed_command_line.HasSwitch(switches::kProfileDirectory)) { 319 g_browser_process->local_state()->SetString(prefs::kProfileLastUsed, 320 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory)); 321 // Clear kProfilesLastActive since the user only wants to launch a specific 322 // profile. 323 ListPrefUpdate update(g_browser_process->local_state(), 324 prefs::kProfilesLastActive); 325 base::ListValue* profile_list = update.Get(); 326 profile_list->Clear(); 327 } 328 329 Profile* profile = NULL; 330 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) 331 // On ChromeOS and Android the ProfileManager will use the same path as the 332 // one we got passed. GetActiveUserProfile will therefore use the correct path 333 // automatically. 334 DCHECK_EQ(user_data_dir.value(), 335 g_browser_process->profile_manager()->user_data_dir().value()); 336 profile = ProfileManager::GetActiveUserProfile(); 337 #else 338 base::FilePath profile_path = 339 GetStartupProfilePath(user_data_dir, parsed_command_line); 340 profile = g_browser_process->profile_manager()->GetProfile( 341 profile_path); 342 343 // If we're using the --new-profile-management flag and this profile is 344 // signed out, then we should show the user manager instead. By switching 345 // the active profile to the guest profile we ensure that no 346 // browser windows will be opened for the guest profile. 347 if (switches::IsNewProfileManagement() && !profile->IsGuestSession()) { 348 ProfileInfoCache& cache = 349 g_browser_process->profile_manager()->GetProfileInfoCache(); 350 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path); 351 352 if (cache.ProfileIsSigninRequiredAtIndex(profile_index)) 353 profile = g_browser_process->profile_manager()->GetProfile( 354 ProfileManager::GetGuestProfilePath()); 355 } 356 #endif 357 if (profile) { 358 UMA_HISTOGRAM_LONG_TIMES( 359 "Startup.CreateFirstProfile", base::Time::Now() - start); 360 return profile; 361 } 362 363 #if !defined(OS_WIN) 364 // TODO(port): fix this. See comments near the definition of 365 // user_data_dir. It is better to CHECK-fail here than it is to 366 // silently exit because of missing code in the above test. 367 CHECK(profile) << "Cannot get default profile."; 368 #endif 369 370 return NULL; 371 } 372 373 #if defined(OS_MACOSX) 374 OSStatus KeychainCallback(SecKeychainEvent keychain_event, 375 SecKeychainCallbackInfo* info, void* context) { 376 return noErr; 377 } 378 #endif 379 380 void RegisterComponentsForUpdate(const CommandLine& command_line) { 381 component_updater::ComponentUpdateService* cus = 382 g_browser_process->component_updater(); 383 384 // Registration can be before or after cus->Start() so it is ok to post 385 // a task to the UI thread to do registration once you done the necessary 386 // file IO to know you existing component version. 387 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) 388 RegisterRecoveryComponent(cus, g_browser_process->local_state()); 389 RegisterPepperFlashComponent(cus); 390 RegisterSwiftShaderComponent(cus); 391 RegisterWidevineCdmComponent(cus); 392 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent( 393 cus, command_line); 394 #endif 395 396 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) 397 // CRLSetFetcher attempts to load a CRL set from either the local disk or 398 // network. 399 if (!command_line.HasSwitch(switches::kDisableCRLSets)) 400 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus); 401 #elif defined(OS_ANDROID) 402 // The CRLSet component was enabled for some releases. This code attempts to 403 // delete it from the local disk of those how may have downloaded it. 404 g_browser_process->crl_set_fetcher()->DeleteFromDisk(); 405 #endif 406 407 #if defined(CLD2_DYNAMIC_MODE) && defined(CLD2_IS_COMPONENT) 408 RegisterCldComponent(cus); 409 #endif 410 411 #if defined(OS_WIN) 412 ExecutePendingSwReporter(cus, g_browser_process->local_state()); 413 #endif 414 415 cus->Start(); 416 } 417 418 #if !defined(OS_ANDROID) 419 bool ProcessSingletonNotificationCallback( 420 const CommandLine& command_line, 421 const base::FilePath& current_directory) { 422 // Drop the request if the browser process is already in shutdown path. 423 if (!g_browser_process || g_browser_process->IsShuttingDown()) 424 return false; 425 426 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) { 427 std::string start_time_string = 428 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime); 429 int64 remote_start_time; 430 if (base::StringToInt64(start_time_string, &remote_start_time)) { 431 base::TimeDelta elapsed = 432 base::Time::Now() - base::Time::FromInternalValue(remote_start_time); 433 if (command_line.HasSwitch(switches::kFastStart)) { 434 UMA_HISTOGRAM_LONG_TIMES( 435 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed); 436 } else { 437 UMA_HISTOGRAM_LONG_TIMES( 438 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed); 439 } 440 } 441 } 442 443 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing( 444 command_line); 445 446 base::FilePath user_data_dir = 447 g_browser_process->profile_manager()->user_data_dir(); 448 base::FilePath startup_profile_dir = 449 GetStartupProfilePath(user_data_dir, command_line); 450 451 StartupBrowserCreator::ProcessCommandLineAlreadyRunning( 452 command_line, current_directory, startup_profile_dir); 453 return true; 454 } 455 #endif // !defined(OS_ANDROID) 456 457 void LaunchDevToolsHandlerIfNeeded(const CommandLine& command_line) { 458 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) { 459 std::string port_str = 460 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort); 461 int port; 462 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) { 463 g_browser_process->CreateDevToolsHttpProtocolHandler( 464 chrome::HOST_DESKTOP_TYPE_NATIVE, 465 "127.0.0.1", 466 port); 467 } else { 468 DLOG(WARNING) << "Invalid http debugger port number " << port; 469 } 470 } 471 } 472 473 // Heap allocated class that listens for first page load, kicks off stat 474 // recording and then deletes itself. 475 class LoadCompleteListener : public content::NotificationObserver { 476 public: 477 LoadCompleteListener() { 478 registrar_.Add(this, 479 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, 480 content::NotificationService::AllSources()); 481 } 482 virtual ~LoadCompleteListener() {} 483 484 // content::NotificationObserver implementation. 485 virtual void Observe(int type, 486 const content::NotificationSource& source, 487 const content::NotificationDetails& details) OVERRIDE { 488 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type); 489 startup_metric_utils::OnInitialPageLoadComplete(); 490 delete this; 491 } 492 493 private: 494 content::NotificationRegistrar registrar_; 495 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener); 496 }; 497 498 } // namespace 499 500 namespace chrome_browser { 501 502 // This error message is not localized because we failed to load the 503 // localization data files. 504 #if defined(OS_WIN) 505 const char kMissingLocaleDataTitle[] = "Missing File Error"; 506 #endif 507 508 #if defined(OS_WIN) 509 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969 510 const char kMissingLocaleDataMessage[] = 511 "Unable to find locale data files. Please reinstall."; 512 #endif 513 514 } // namespace chrome_browser 515 516 // BrowserMainParts ------------------------------------------------------------ 517 518 // static 519 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_ = 520 false; 521 522 ChromeBrowserMainParts::ChromeBrowserMainParts( 523 const content::MainFunctionParams& parameters) 524 : parameters_(parameters), 525 parsed_command_line_(parameters.command_line), 526 result_code_(content::RESULT_CODE_NORMAL_EXIT), 527 startup_watcher_(new StartupTimeBomb()), 528 shutdown_watcher_(new ShutdownWatcherHelper()), 529 startup_timer_(new performance_monitor::StartupTimer()), 530 browser_field_trials_(parameters.command_line), 531 profile_(NULL), 532 run_message_loop_(true), 533 notify_result_(ProcessSingleton::PROCESS_NONE), 534 local_state_(NULL), 535 restart_last_session_(false) { 536 // If we're running tests (ui_task is non-null). 537 if (parameters.ui_task) 538 browser_defaults::enable_help_app = false; 539 540 // Chrome disallows cookies by default. All code paths that want to use 541 // cookies need to go through one of Chrome's URLRequestContexts which have 542 // a ChromeNetworkDelegate attached that selectively allows cookies again. 543 if (!disable_enforcing_cookie_policies_for_tests_) 544 net::URLRequest::SetDefaultCookiePolicyToBlock(); 545 } 546 547 ChromeBrowserMainParts::~ChromeBrowserMainParts() { 548 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i) 549 delete chrome_extra_parts_[i]; 550 chrome_extra_parts_.clear(); 551 } 552 553 // This will be called after the command-line has been mutated by about:flags 554 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() { 555 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials"); 556 // Must initialize metrics after labs have been converted into switches, 557 // but before field trials are set up (so that client ID is available for 558 // one-time randomized field trials). 559 560 // Initialize FieldTrialList to support FieldTrials that use one-time 561 // randomization. 562 MetricsService* metrics = browser_process_->metrics_service(); 563 field_trial_list_.reset( 564 new base::FieldTrialList(metrics->CreateEntropyProvider().release())); 565 566 const CommandLine* command_line = CommandLine::ForCurrentProcess(); 567 if (command_line->HasSwitch(switches::kEnableBenchmarking)) 568 base::FieldTrial::EnableBenchmarking(); 569 570 // Ensure any field trials specified on the command line are initialized. 571 if (command_line->HasSwitch(switches::kForceFieldTrials)) { 572 std::set<std::string> unforceable_field_trials; 573 #if defined(OFFICIAL_BUILD) 574 unforceable_field_trials.insert("SettingsEnforcement"); 575 #endif // defined(OFFICIAL_BUILD) 576 577 // Create field trials without activating them, so that this behaves in a 578 // consistent manner with field trials created from the server. 579 bool result = base::FieldTrialList::CreateTrialsFromString( 580 command_line->GetSwitchValueASCII(switches::kForceFieldTrials), 581 base::FieldTrialList::DONT_ACTIVATE_TRIALS, 582 unforceable_field_trials); 583 CHECK(result) << "Invalid --" << switches::kForceFieldTrials 584 << " list specified."; 585 } 586 if (command_line->HasSwitch(switches::kForceVariationIds)) { 587 // Create default variation ids which will always be included in the 588 // X-Client-Data request header. 589 chrome_variations::VariationsHttpHeaderProvider* provider = 590 chrome_variations::VariationsHttpHeaderProvider::GetInstance(); 591 bool result = provider->SetDefaultVariationIds( 592 command_line->GetSwitchValueASCII(switches::kForceVariationIds)); 593 CHECK(result) << "Invalid --" << switches::kForceVariationIds 594 << " list specified."; 595 } 596 chrome_variations::VariationsService* variations_service = 597 browser_process_->variations_service(); 598 if (variations_service) 599 variations_service->CreateTrialsFromSeed(); 600 601 // This must be called after the local state is initialized. 602 browser_field_trials_.SetupFieldTrials(local_state_); 603 604 // Initialize FieldTrialSynchronizer system. This is a singleton and is used 605 // for posting tasks via base::Bind. Its deleted when it goes out of scope. 606 // Even though base::Bind does AddRef and Release, the object will not be 607 // deleted after the Task is executed. 608 field_trial_synchronizer_ = new FieldTrialSynchronizer(); 609 610 // Now that field trials have been created, initializes metrics recording. 611 metrics->InitializeMetricsRecordingState(); 612 } 613 614 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related -------------- 615 616 void ChromeBrowserMainParts::StartMetricsRecording() { 617 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording"); 618 MetricsService* metrics = g_browser_process->metrics_service(); 619 620 const bool only_do_metrics_recording = 621 parsed_command_line_.HasSwitch(switches::kMetricsRecordingOnly) || 622 parsed_command_line_.HasSwitch(switches::kEnableBenchmarking); 623 if (only_do_metrics_recording) { 624 // If we're testing then we don't care what the user preference is, we turn 625 // on recording, but not reporting, otherwise tests fail. 626 metrics->StartRecordingForTests(); 627 return; 628 } 629 630 metrics->CheckForClonedInstall( 631 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)); 632 const bool metrics_enabled = metrics->StartIfMetricsReportingEnabled(); 633 if (metrics_enabled) { 634 // TODO(asvitkine): Since this function is not run on Android, RAPPOR is 635 // currently disabled there. http://crbug.com/370041 636 browser_process_->rappor_service()->Start( 637 browser_process_->local_state(), 638 browser_process_->system_request_context()); 639 } 640 } 641 642 void ChromeBrowserMainParts::RecordBrowserStartupTime() { 643 // Don't record any metrics if UI was displayed before this point e.g. 644 // warning dialogs. 645 if (startup_metric_utils::WasNonBrowserUIDisplayed()) 646 return; 647 648 #if defined(OS_ANDROID) 649 // On Android the first run is handled in Java code, and the C++ side of 650 // Chrome doesn't know if this is the first run. This will cause some 651 // inaccuracy in the UMA statistics, but this should be minor (first runs are 652 // rare). 653 bool is_first_run = false; 654 #else 655 bool is_first_run = first_run::IsChromeFirstRun(); 656 #endif 657 658 // CurrentProcessInfo::CreationTime() is currently only implemented on some 659 // platforms. 660 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX) 661 const base::Time process_creation_time = 662 base::CurrentProcessInfo::CreationTime(); 663 664 if (!is_first_run && !process_creation_time.is_null()) { 665 base::TimeDelta delay = base::Time::Now() - process_creation_time; 666 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay); 667 } 668 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX) 669 670 // Record collected startup metrics. 671 startup_metric_utils::OnBrowserStartupComplete(is_first_run); 672 673 // Deletes self. 674 new LoadCompleteListener(); 675 } 676 677 // ----------------------------------------------------------------------------- 678 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts. 679 680 #if defined(OS_WIN) 681 #define DLLEXPORT __declspec(dllexport) 682 683 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling. 684 extern "C" { 685 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded(); 686 } 687 688 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() { 689 // Need an instance of AtExitManager to handle singleton creations and 690 // deletions. We need this new instance because, the old instance created 691 // in ChromeMain() got destructed when the function returned. 692 base::AtExitManager exit_manager; 693 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded(); 694 } 695 #endif 696 697 // content::BrowserMainParts implementation ------------------------------------ 698 699 void ChromeBrowserMainParts::PreEarlyInitialization() { 700 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization"); 701 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 702 chrome_extra_parts_[i]->PreEarlyInitialization(); 703 } 704 705 void ChromeBrowserMainParts::PostEarlyInitialization() { 706 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization"); 707 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 708 chrome_extra_parts_[i]->PostEarlyInitialization(); 709 } 710 711 void ChromeBrowserMainParts::ToolkitInitialized() { 712 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized"); 713 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 714 chrome_extra_parts_[i]->ToolkitInitialized(); 715 } 716 717 void ChromeBrowserMainParts::PreMainMessageLoopStart() { 718 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart"); 719 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 720 chrome_extra_parts_[i]->PreMainMessageLoopStart(); 721 } 722 723 void ChromeBrowserMainParts::PostMainMessageLoopStart() { 724 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart"); 725 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 726 chrome_extra_parts_[i]->PostMainMessageLoopStart(); 727 } 728 729 int ChromeBrowserMainParts::PreCreateThreads() { 730 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads"); 731 result_code_ = PreCreateThreadsImpl(); 732 733 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) { 734 #if !defined(OS_ANDROID) 735 // These members must be initialized before exiting this function normally. 736 DCHECK(master_prefs_.get()); 737 DCHECK(browser_creator_.get()); 738 #endif 739 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 740 chrome_extra_parts_[i]->PreCreateThreads(); 741 } 742 743 return result_code_; 744 } 745 746 int ChromeBrowserMainParts::PreCreateThreadsImpl() { 747 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl") 748 run_message_loop_ = false; 749 #if !defined(OS_ANDROID) 750 chrome::MaybeShowInvalidUserDataDirWarningDialog(); 751 #endif 752 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_)) 753 return chrome::RESULT_CODE_MISSING_DATA; 754 755 // Force MediaCaptureDevicesDispatcher to be created on UI thread. 756 MediaCaptureDevicesDispatcher::GetInstance(); 757 758 // Android's first run is done in Java instead of native. 759 #if !defined(OS_ANDROID) 760 process_singleton_.reset(new ChromeProcessSingleton( 761 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback))); 762 763 // Cache first run state early. 764 first_run::IsChromeFirstRun(); 765 #endif 766 767 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner = 768 JsonPrefStore::GetTaskRunnerForFile( 769 base::FilePath(chrome::kLocalStorePoolName), 770 BrowserThread::GetBlockingPool()); 771 772 { 773 TRACE_EVENT0("startup", 774 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl"); 775 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(), 776 parsed_command_line())); 777 } 778 779 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) { 780 TRACE_EVENT0("startup", 781 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling"); 782 // User wants to override default tracking status. 783 std::string flag = 784 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling); 785 // Default to basic profiling (no parent child support). 786 tracked_objects::ThreadData::Status status = 787 tracked_objects::ThreadData::PROFILING_ACTIVE; 788 if (flag.compare("0") != 0) 789 status = tracked_objects::ThreadData::DEACTIVATED; 790 else if (flag.compare("child") != 0) 791 status = tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE; 792 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status); 793 } 794 795 if (parsed_command_line().HasSwitch(switches::kProfilingOutputFile)) { 796 tracking_objects_.set_output_file_path( 797 parsed_command_line().GetSwitchValuePath( 798 switches::kProfilingOutputFile)); 799 } 800 801 local_state_ = InitializeLocalState( 802 local_state_task_runner.get(), parsed_command_line()); 803 804 #if !defined(OS_ANDROID) 805 // These members must be initialized before returning from this function. 806 master_prefs_.reset(new first_run::MasterPrefs); 807 // Android doesn't use StartupBrowserCreator. 808 browser_creator_.reset(new StartupBrowserCreator); 809 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver 810 chrome::UMABrowsingActivityObserver::Init(); 811 #endif 812 813 #if !defined(OS_CHROMEOS) 814 // Convert active labs into switches. This needs to be done before 815 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are 816 // affected by experiment flags (--touch-optimized-ui in particular). 817 // On ChromeOS system level flags are applied from the device settings from 818 // the session manager. 819 { 820 TRACE_EVENT0("startup", 821 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags"); 822 about_flags::PrefServiceFlagsStorage flags_storage_( 823 g_browser_process->local_state()); 824 about_flags::ConvertFlagsToSwitches(&flags_storage_, 825 CommandLine::ForCurrentProcess(), 826 about_flags::kAddSentinels); 827 } 828 #endif 829 830 local_state_->UpdateCommandLinePrefStore( 831 new CommandLinePrefStore(CommandLine::ForCurrentProcess())); 832 833 // Reset the command line in the crash report details, since we may have 834 // just changed it to include experiments. 835 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess()); 836 837 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is 838 // needed when loading the MainMenu.nib and the language doesn't depend on 839 // anything since it comes from Cocoa. 840 #if defined(OS_MACOSX) 841 std::string locale = 842 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride(); 843 browser_process_->SetApplicationLocale(locale); 844 #else 845 const std::string locale = 846 local_state_->GetString(prefs::kApplicationLocale); 847 848 // On a POSIX OS other than ChromeOS, the parameter that is passed to the 849 // method InitSharedInstance is ignored. 850 851 TRACE_EVENT_BEGIN0("startup", 852 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle"); 853 const std::string loaded_locale = 854 ResourceBundle::InitSharedInstanceWithLocale(locale, NULL); 855 TRACE_EVENT_END0("startup", 856 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle"); 857 858 if (loaded_locale.empty() && 859 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) { 860 ShowMissingLocaleMessageBox(); 861 return chrome::RESULT_CODE_MISSING_DATA; 862 } 863 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale; 864 browser_process_->SetApplicationLocale(loaded_locale); 865 866 base::FilePath resources_pack_path; 867 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path); 868 { 869 TRACE_EVENT0("startup", 870 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack"); 871 ResourceBundle::GetSharedInstance().AddDataPackFromPath( 872 resources_pack_path, ui::SCALE_FACTOR_NONE); 873 } 874 #endif // defined(OS_MACOSX) 875 876 // Android does first run in Java instead of native. 877 // Chrome OS has its own out-of-box-experience code. 878 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) 879 // On first run, we need to process the predictor preferences before the 880 // browser's profile_manager object is created, but after ResourceBundle 881 // is initialized. 882 if (first_run::IsChromeFirstRun()) { 883 first_run::ProcessMasterPreferencesResult pmp_result = 884 first_run::ProcessMasterPreferences(user_data_dir_, 885 master_prefs_.get()); 886 if (pmp_result == first_run::EULA_EXIT_NOW) 887 return chrome::RESULT_CODE_EULA_REFUSED; 888 889 if (!parsed_command_line().HasSwitch(switches::kApp) && 890 !parsed_command_line().HasSwitch(switches::kAppId) && 891 !parsed_command_line().HasSwitch(switches::kShowAppList)) { 892 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs); 893 } 894 895 // TODO(macourteau): refactor preferences that are copied from 896 // master_preferences into local_state, as a "local_state" section in 897 // master preferences. If possible, a generic solution would be prefered 898 // over a copy one-by-one of specific preferences. Also see related TODO 899 // in first_run.h. 900 901 // Store the initial VariationsService seed in local state, if it exists 902 // in master prefs. 903 if (!master_prefs_->variations_seed.empty()) { 904 local_state_->SetString(prefs::kVariationsSeed, 905 master_prefs_->variations_seed); 906 if (!master_prefs_->variations_seed_signature.empty()) { 907 local_state_->SetString(prefs::kVariationsSeedSignature, 908 master_prefs_->variations_seed_signature); 909 } 910 // Set the variation seed date to the current system time. If the user's 911 // clock is incorrect, this may cause some field trial expiry checks to 912 // not do the right thing until the next seed update from the server, 913 // when this value will be updated. 914 local_state_->SetInt64(prefs::kVariationsSeedDate, 915 base::Time::Now().ToInternalValue()); 916 } 917 918 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) { 919 local_state_->SetString( 920 prefs::kBrowserSuppressDefaultBrowserPrompt, 921 master_prefs_->suppress_default_browser_prompt_for_version); 922 } 923 924 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->HandleFirstRun(); 925 } 926 #endif 927 928 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX) 929 // Set the product channel for crash reports. 930 base::debug::SetCrashKeyValue(crash_keys::kChannel, 931 chrome::VersionInfo::GetVersionStringModifier()); 932 #endif 933 934 // Initialize tracking synchronizer system. 935 tracking_synchronizer_ = new chrome_browser_metrics::TrackingSynchronizer(); 936 937 // Now that all preferences have been registered, set the install date 938 // for the uninstall metrics if this is our first run. This only actually 939 // gets used if the user has metrics reporting enabled at uninstall time. 940 int64 install_date = local_state_->GetInt64(prefs::kInstallDate); 941 if (install_date == 0) 942 local_state_->SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT()); 943 944 #if defined(OS_MACOSX) 945 // Get the Keychain API to register for distributed notifications on the main 946 // thread, which has a proper CFRunloop, instead of later on the I/O thread, 947 // which doesn't. This ensures those notifications will get delivered 948 // properly. See issue 37766. 949 // (Note that the callback mask here is empty. I don't want to register for 950 // any callbacks, I just want to initialize the mechanism.) 951 SecKeychainAddCallback(&KeychainCallback, 0, NULL); 952 #endif 953 954 #if defined(OS_CHROMEOS) 955 // Must be done after g_browser_process is constructed, before 956 // SetupMetricsAndFieldTrials(). 957 chromeos::CrosSettings::Initialize(); 958 #endif 959 960 // Now the command line has been mutated based on about:flags, we can setup 961 // metrics and initialize field trials. The field trials are needed by 962 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads. 963 SetupMetricsAndFieldTrials(); 964 965 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this. 966 browser_process_->PreCreateThreads(); 967 968 return content::RESULT_CODE_NORMAL_EXIT; 969 } 970 971 void ChromeBrowserMainParts::PreMainMessageLoopRun() { 972 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun"); 973 result_code_ = PreMainMessageLoopRunImpl(); 974 975 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 976 chrome_extra_parts_[i]->PreMainMessageLoopRun(); 977 } 978 979 // PreMainMessageLoopRun calls these extra stages in the following order: 980 // PreMainMessageLoopRunImpl() 981 // ... initial setup, including browser_process_ setup. 982 // PreProfileInit() 983 // ... additional setup, including CreateProfile() 984 // PostProfileInit() 985 // ... additional setup 986 // PreBrowserStart() 987 // ... browser_creator_->Start (OR parameters().ui_task->Run()) 988 // PostBrowserStart() 989 990 void ChromeBrowserMainParts::PreProfileInit() { 991 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit"); 992 993 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 994 chrome_extra_parts_[i]->PreProfileInit(); 995 996 #if !defined(OS_ANDROID) 997 // Initialize the feedback uploader so it can setup notifications for profile 998 // creation. 999 feedback::FeedbackProfileObserver::Initialize(); 1000 1001 ProfileManager* profile_manager = g_browser_process->profile_manager(); 1002 1003 // First check if any ephemeral profiles are left behind because of browser 1004 // crash and schedule them for deletion and then proceed with getting the set 1005 // of profiles to open. 1006 ProfileInfoCache& profile_cache = profile_manager->GetProfileInfoCache(); 1007 size_t profiles_count = profile_cache.GetNumberOfProfiles(); 1008 std::vector<base::FilePath> profiles_to_delete; 1009 for (size_t i = 0; i < profiles_count; ++i) { 1010 if (profile_cache.ProfileIsEphemeralAtIndex(i)) 1011 profiles_to_delete.push_back(profile_cache.GetPathOfProfileAtIndex(i)); 1012 } 1013 1014 if (profiles_to_delete.size()) { 1015 for (size_t i = 0; i < profiles_to_delete.size(); ++i) { 1016 profile_manager->ScheduleProfileForDeletion( 1017 profiles_to_delete[i], ProfileManager::CreateCallback()); 1018 } 1019 // Clean up stale profiles immediately after browser start. 1020 BrowserThread::PostTask( 1021 BrowserThread::FILE, FROM_HERE, 1022 base::Bind(&ProfileManager::CleanUpStaleProfiles, profiles_to_delete)); 1023 } 1024 #endif // OS_ANDROID 1025 } 1026 1027 void ChromeBrowserMainParts::PostProfileInit() { 1028 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit"); 1029 LaunchDevToolsHandlerIfNeeded(parsed_command_line()); 1030 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 1031 chrome_extra_parts_[i]->PostProfileInit(); 1032 } 1033 1034 void ChromeBrowserMainParts::PreBrowserStart() { 1035 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart"); 1036 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 1037 chrome_extra_parts_[i]->PreBrowserStart(); 1038 1039 three_d_observer_.reset(new ThreeDAPIObserver()); 1040 } 1041 1042 void ChromeBrowserMainParts::PostBrowserStart() { 1043 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart"); 1044 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 1045 chrome_extra_parts_[i]->PostBrowserStart(); 1046 #if !defined(OS_ANDROID) 1047 // Allow ProcessSingleton to process messages. 1048 process_singleton_->Unlock(); 1049 #endif 1050 #if defined(ENABLE_WEBRTC) 1051 // Set up a task to delete old WebRTC log files for all profiles. Use a delay 1052 // to reduce the impact on startup time. 1053 BrowserThread::PostDelayedTask( 1054 BrowserThread::UI, 1055 FROM_HERE, 1056 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles), 1057 base::TimeDelta::FromMinutes(1)); 1058 #endif 1059 } 1060 1061 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() { 1062 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl"); 1063 // Android updates the metrics service dynamically depending on whether the 1064 // application is in the foreground or not. Do not start here. 1065 #if !defined(OS_ANDROID) 1066 // Now that the file thread has been started, start recording. 1067 StartMetricsRecording(); 1068 #endif 1069 1070 // Create watchdog thread after creating all other threads because it will 1071 // watch the other threads and they must be running. 1072 browser_process_->watchdog_thread(); 1073 1074 // Do any initializating in the browser process that requires all threads 1075 // running. 1076 browser_process_->PreMainMessageLoopRun(); 1077 1078 // Record last shutdown time into a histogram. 1079 browser_shutdown::ReadLastShutdownInfo(); 1080 1081 #if defined(OS_WIN) 1082 // On Windows, we use our startup as an opportunity to do upgrade/uninstall 1083 // tasks. Those care whether the browser is already running. On Linux/Mac, 1084 // upgrade/uninstall happen separately. 1085 bool already_running = browser_util::IsBrowserAlreadyRunning(); 1086 1087 // If the command line specifies 'uninstall' then we need to work here 1088 // unless we detect another chrome browser running. 1089 if (parsed_command_line().HasSwitch(switches::kUninstall)) { 1090 return DoUninstallTasks(already_running); 1091 } 1092 1093 if (parsed_command_line().HasSwitch(switches::kHideIcons) || 1094 parsed_command_line().HasSwitch(switches::kShowIcons)) { 1095 return ChromeBrowserMainPartsWin::HandleIconsCommands( 1096 parsed_command_line_); 1097 } 1098 #endif 1099 1100 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) { 1101 return ShellIntegration::SetAsDefaultBrowser() ? 1102 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) : 1103 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED); 1104 } 1105 1106 #if defined(USE_AURA) 1107 // Make sure aura::Env has been initialized. 1108 CHECK(aura::Env::GetInstance()); 1109 #endif 1110 1111 // Android doesn't support extensions and doesn't implement ProcessSingleton. 1112 #if !defined(OS_ANDROID) 1113 // If the command line specifies --pack-extension, attempt the pack extension 1114 // startup action and exit. 1115 if (parsed_command_line().HasSwitch(switches::kPackExtension)) { 1116 extensions::StartupHelper extension_startup_helper; 1117 if (extension_startup_helper.PackExtension(parsed_command_line())) 1118 return content::RESULT_CODE_NORMAL_EXIT; 1119 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR; 1120 } 1121 1122 // If we're being launched just to check the connector policy, we are 1123 // short-lived and don't want to be passing that switch off. 1124 bool pass_command_line = !parsed_command_line().HasSwitch( 1125 switches::kCheckCloudPrintConnectorPolicy); 1126 1127 if (pass_command_line) { 1128 // When another process is running, use that process instead of starting a 1129 // new one. NotifyOtherProcess will currently give the other process up to 1130 // 20 seconds to respond. Note that this needs to be done before we attempt 1131 // to read the profile. 1132 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate(); 1133 switch (notify_result_) { 1134 case ProcessSingleton::PROCESS_NONE: 1135 // No process already running, fall through to starting a new one. 1136 break; 1137 1138 case ProcessSingleton::PROCESS_NOTIFIED: 1139 #if defined(OS_POSIX) && !defined(OS_MACOSX) 1140 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide( 1141 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str()); 1142 #endif 1143 // Having a differentiated return type for testing allows for tests to 1144 // verify proper handling of some switches. When not testing, stick to 1145 // the standard Unix convention of returning zero when things went as 1146 // expected. 1147 if (parsed_command_line().HasSwitch(switches::kTestType)) 1148 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED; 1149 return content::RESULT_CODE_NORMAL_EXIT; 1150 1151 case ProcessSingleton::PROFILE_IN_USE: 1152 return chrome::RESULT_CODE_PROFILE_IN_USE; 1153 1154 case ProcessSingleton::LOCK_ERROR: 1155 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile " 1156 "directory. This means that running multiple instances " 1157 "would start multiple browser processes rather than " 1158 "opening a new window in the existing process. Aborting " 1159 "now to avoid profile corruption."; 1160 return chrome::RESULT_CODE_PROFILE_IN_USE; 1161 1162 default: 1163 NOTREACHED(); 1164 } 1165 } 1166 #endif // !defined(OS_ANDROID) 1167 1168 // Handle special early return paths (which couldn't be processed even earlier 1169 // as they require the process singleton to be held) first. 1170 1171 std::string try_chrome = 1172 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain); 1173 if (!try_chrome.empty()) { 1174 #if defined(OS_WIN) 1175 // Setup.exe has determined that we need to run a retention experiment 1176 // and has lauched chrome to show the experiment UI. It is guaranteed that 1177 // no other Chrome is currently running as the process singleton was 1178 // sucessfully grabbed above. 1179 int try_chrome_int; 1180 base::StringToInt(try_chrome, &try_chrome_int); 1181 TryChromeDialogView::Result answer = TryChromeDialogView::Show( 1182 try_chrome_int, 1183 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog, 1184 base::Unretained(process_singleton_.get()))); 1185 if (answer == TryChromeDialogView::NOT_NOW) 1186 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL; 1187 if (answer == TryChromeDialogView::UNINSTALL_CHROME) 1188 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2; 1189 // At this point the user is willing to try chrome again. 1190 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) { 1191 // Only set in the unattended case, the interactive case is Windows 8. 1192 if (ShellIntegration::CanSetAsDefaultBrowser() == 1193 ShellIntegration::SET_DEFAULT_UNATTENDED) 1194 ShellIntegration::SetAsDefaultBrowser(); 1195 } 1196 #else 1197 // We don't support retention experiments on Mac or Linux. 1198 return content::RESULT_CODE_NORMAL_EXIT; 1199 #endif // defined(OS_WIN) 1200 } 1201 1202 #if defined(OS_WIN) 1203 // Do the tasks if chrome has been upgraded while it was last running. 1204 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line())) 1205 return content::RESULT_CODE_NORMAL_EXIT; 1206 1207 // Check if there is any machine level Chrome installed on the current 1208 // machine. If yes and the current Chrome process is user level, we do not 1209 // allow the user level Chrome to run. So we notify the user and uninstall 1210 // user level Chrome. 1211 // Note this check needs to happen here (after the process singleton was 1212 // obtained but before potentially creating the first run sentinel). 1213 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall()) 1214 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS; 1215 #endif // defined(OS_WIN) 1216 1217 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) 1218 if (sxs_linux::ShouldMigrateUserDataDir()) 1219 return sxs_linux::MigrateUserDataDir(); 1220 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) 1221 1222 // Desktop construction occurs here, (required before profile creation). 1223 PreProfileInit(); 1224 1225 // Profile creation ---------------------------------------------------------- 1226 1227 MetricsService::SetExecutionPhase(MetricsService::CREATE_PROFILE, 1228 g_browser_process->local_state()); 1229 profile_ = CreatePrimaryProfile(parameters(), 1230 user_data_dir_, 1231 parsed_command_line()); 1232 if (!profile_) 1233 return content::RESULT_CODE_NORMAL_EXIT; 1234 1235 #if !defined(OS_ANDROID) 1236 // The first run sentinel must be created after the process singleton was 1237 // grabbed and no early return paths were otherwise hit above. 1238 first_run::CreateSentinelIfNeeded(); 1239 #endif // !defined(OS_ANDROID) 1240 1241 #if defined(ENABLE_BACKGROUND) 1242 // Autoload any profiles which are running background apps. 1243 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075. 1244 browser_process_->profile_manager()->AutoloadProfiles(); 1245 #endif 1246 // Post-profile init --------------------------------------------------------- 1247 1248 TranslateService::Initialize(); 1249 1250 // Needs to be done before PostProfileInit, since login manager on CrOS is 1251 // called inside PostProfileInit. 1252 content::WebUIControllerFactory::RegisterFactory( 1253 ChromeWebUIControllerFactory::GetInstance()); 1254 1255 // NaClBrowserDelegateImpl is accessed inside PostProfileInit(). 1256 // So make sure to create it before that. 1257 #if !defined(DISABLE_NACL) 1258 NaClBrowserDelegateImpl* delegate = 1259 new NaClBrowserDelegateImpl(browser_process_->profile_manager()); 1260 nacl::NaClBrowser::SetDelegate(delegate); 1261 #endif 1262 1263 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts. 1264 // (requires supporting early exit). 1265 PostProfileInit(); 1266 1267 // Retrieve cached GL strings from local state and use them for GPU 1268 // blacklist decisions. 1269 if (g_browser_process->gl_string_manager()) 1270 g_browser_process->gl_string_manager()->Initialize(); 1271 1272 // Create an instance of GpuModeManager to watch gpu mode pref change. 1273 g_browser_process->gpu_mode_manager(); 1274 1275 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) 1276 // Show the First Run UI if this is the first time Chrome has been run on 1277 // this computer, or we're being compelled to do so by a command line flag. 1278 // Note that this be done _after_ the PrefService is initialized and all 1279 // preferences are registered, since some of the code that the importer 1280 // touches reads preferences. 1281 if (first_run::IsChromeFirstRun()) { 1282 first_run::AutoImport(profile_, 1283 master_prefs_->homepage_defined, 1284 master_prefs_->do_import_items, 1285 master_prefs_->dont_import_items, 1286 master_prefs_->import_bookmarks_path); 1287 1288 // Note: this can pop the first run consent dialog on linux. 1289 first_run::DoPostImportTasks(profile_, 1290 master_prefs_->make_chrome_default_for_user); 1291 1292 if (!master_prefs_->suppress_first_run_default_browser_prompt) { 1293 browser_creator_->set_show_main_browser_window( 1294 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_)); 1295 } else { 1296 browser_creator_->set_is_default_browser_dialog_suppressed(true); 1297 } 1298 } 1299 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS) 1300 1301 #if defined(OS_WIN) 1302 // Sets things up so that if we crash from this point on, a dialog will 1303 // popup asking the user to restart chrome. It is done this late to avoid 1304 // testing against a bunch of special cases that are taken care early on. 1305 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment( 1306 parsed_command_line()); 1307 1308 // Registers Chrome with the Windows Restart Manager, which will restore the 1309 // Chrome session when the computer is restarted after a system update. 1310 // This could be run as late as WM_QUERYENDSESSION for system update reboots, 1311 // but should run on startup if extended to handle crashes/hangs/patches. 1312 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION. 1313 if (base::win::GetVersion() >= base::win::VERSION_VISTA) { 1314 ChromeBrowserMainPartsWin::RegisterApplicationRestart( 1315 parsed_command_line()); 1316 } 1317 1318 // Verify that the profile is not on a network share and if so prepare to show 1319 // notification to the user. 1320 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) { 1321 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, 1322 base::Bind(&NetworkProfileBubble::CheckNetworkProfile, 1323 profile_->GetPath())); 1324 } 1325 #endif // OS_WIN 1326 1327 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS) 1328 // Init the RLZ library. This just binds the dll and schedules a task on the 1329 // file thread to be run sometime later. If this is the first run we record 1330 // the installation event. 1331 PrefService* pref_service = profile_->GetPrefs(); 1332 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay : 1333 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str()); 1334 // Negative ping delay means to send ping immediately after a first search is 1335 // recorded. 1336 RLZTracker::InitRlzFromProfileDelayed( 1337 profile_, first_run::IsChromeFirstRun(), ping_delay < 0, 1338 base::TimeDelta::FromMilliseconds(abs(ping_delay))); 1339 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS) 1340 1341 // Configure modules that need access to resources. 1342 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider); 1343 1344 // In unittest mode, this will do nothing. In normal mode, this will create 1345 // the global IntranetRedirectDetector instance, which will promptly go to 1346 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards 1347 // to see if it should do anything else. 1348 // 1349 // A simpler way of doing all this would be to have some function which could 1350 // give the time elapsed since startup, and simply have this object check that 1351 // when asked to initialize itself, but this doesn't seem to exist. 1352 // 1353 // This can't be created in the BrowserProcessImpl constructor because it 1354 // needs to read prefs that get set after that runs. 1355 browser_process_->intranet_redirect_detector(); 1356 GoogleSearchCounter::RegisterForNotifications(); 1357 1358 if (parsed_command_line().HasSwitch(switches::kEnableSdchOverHttps)) { 1359 net::SdchManager::EnableSecureSchemeSupport(true); 1360 } else { 1361 // Check SDCH field trial. 1362 const char kSdchFieldTrialName[] = "SDCH"; 1363 const char kEnabledAllGroupName[] = "EnabledAll"; 1364 const char kEnabledHttpOnlyGroupName[] = "EnabledHttpOnly"; 1365 const char kDisabledAllGroupName[] = "DisabledAll"; 1366 1367 base::StringPiece sdch_trial_group = 1368 base::FieldTrialList::FindFullName(kSdchFieldTrialName); 1369 if (sdch_trial_group.starts_with(kEnabledAllGroupName)) { 1370 net::SdchManager::EnableSecureSchemeSupport(true); 1371 net::SdchManager::EnableSdchSupport(true); 1372 } else if (sdch_trial_group.starts_with(kEnabledHttpOnlyGroupName)) { 1373 net::SdchManager::EnableSdchSupport(true); 1374 } else if (sdch_trial_group.starts_with(kDisabledAllGroupName)) { 1375 net::SdchManager::EnableSdchSupport(false); 1376 } 1377 } 1378 1379 if (parsed_command_line().HasSwitch(switches::kEnableWatchdog)) 1380 InstallJankometer(parsed_command_line()); 1381 1382 #if defined(ENABLE_FULL_PRINTING) && !defined(OFFICIAL_BUILD) 1383 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) { 1384 base::FilePath path = 1385 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint); 1386 printing::PrintedDocument::set_debug_dump_path(path); 1387 } 1388 #endif 1389 1390 HandleTestParameters(parsed_command_line()); 1391 browser_process_->metrics_service()->RecordBreakpadHasDebugger( 1392 base::debug::BeingDebugged()); 1393 1394 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages( 1395 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)); 1396 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage( 1397 browser_process_->GetApplicationLocale()); 1398 1399 // Start watching for hangs during startup. We disarm this hang detector when 1400 // ThreadWatcher takes over or when browser is shutdown or when 1401 // startup_watcher_ is deleted. 1402 MetricsService::SetExecutionPhase(MetricsService::STARTUP_TIMEBOMB_ARM, 1403 g_browser_process->local_state()); 1404 startup_watcher_->Arm(base::TimeDelta::FromSeconds(300)); 1405 1406 // On mobile, need for clean shutdown arises only when the application comes 1407 // to foreground (i.e. MetricsService::OnAppEnterForeground is called). 1408 // http://crbug.com/179143 1409 #if !defined(OS_ANDROID) 1410 // Start watching for a hang. 1411 MetricsService::LogNeedForCleanShutdown(g_browser_process->local_state()); 1412 #endif 1413 1414 #if defined(ENABLE_FULL_PRINTING) 1415 // Create the instance of the cloud print proxy service so that it can launch 1416 // the service process if needed. This is needed because the service process 1417 // might have shutdown because an update was available. 1418 // TODO(torne): this should maybe be done with 1419 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext() 1420 // instead? 1421 CloudPrintProxyServiceFactory::GetForProfile(profile_); 1422 #endif 1423 1424 // Start watching all browser threads for responsiveness. 1425 MetricsService::SetExecutionPhase(MetricsService::THREAD_WATCHER_START, 1426 g_browser_process->local_state()); 1427 ThreadWatcherList::StartWatchingAll(parsed_command_line()); 1428 1429 #if defined(OS_ANDROID) 1430 ThreadWatcherAndroid::RegisterApplicationStatusListener(); 1431 #endif 1432 1433 #if !defined(DISABLE_NACL) 1434 BrowserThread::PostTask( 1435 BrowserThread::IO, 1436 FROM_HERE, 1437 base::Bind(nacl::NaClProcessHost::EarlyStartup)); 1438 #endif 1439 1440 // Make sure initial prefs are recorded 1441 PrefMetricsService::Factory::GetForProfile(profile_); 1442 1443 PreBrowserStart(); 1444 1445 // Instantiate the notification UI manager, as this triggers a perf timer 1446 // used to measure startup time. TODO(stevenjb): Figure out what is actually 1447 // triggering the timer and call that explicitly in the approprate place. 1448 // http://crbug.com/105065. 1449 browser_process_->notification_ui_manager(); 1450 1451 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate)) 1452 RegisterComponentsForUpdate(parsed_command_line()); 1453 1454 #if defined(OS_ANDROID) 1455 chrome_variations::VariationsService* variations_service = 1456 browser_process_->variations_service(); 1457 if (variations_service) { 1458 variations_service->set_policy_pref_service(profile_->GetPrefs()); 1459 variations_service->StartRepeatedVariationsSeedFetch(); 1460 } 1461 TranslateDownloadManager::RequestLanguageList(profile_->GetPrefs()); 1462 1463 #else 1464 // Most general initialization is behind us, but opening a 1465 // tab and/or session restore and such is still to be done. 1466 base::TimeTicks browser_open_start = base::TimeTicks::Now(); 1467 1468 // We are in regular browser boot sequence. Open initial tabs and enter the 1469 // main message loop. 1470 int result_code; 1471 #if defined(OS_CHROMEOS) 1472 // On ChromeOS multiple profiles doesn't apply, and will break if we load 1473 // them this early as the cryptohome hasn't yet been mounted (which happens 1474 // only once we log in. 1475 std::vector<Profile*> last_opened_profiles; 1476 #else 1477 std::vector<Profile*> last_opened_profiles = 1478 g_browser_process->profile_manager()->GetLastOpenedProfiles(); 1479 #endif 1480 1481 if (browser_creator_->Start(parsed_command_line(), base::FilePath(), 1482 profile_, last_opened_profiles, &result_code)) { 1483 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) 1484 // Initialize autoupdate timer. Timer callback costs basically nothing 1485 // when browser is not in persistent mode, so it's OK to let it ride on 1486 // the main thread. This needs to be done here because we don't want 1487 // to start the timer when Chrome is run inside a test harness. 1488 browser_process_->StartAutoupdateTimer(); 1489 #endif 1490 1491 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) 1492 // On Linux, the running exe will be updated if an upgrade becomes 1493 // available while the browser is running. We need to save the last 1494 // modified time of the exe, so we can compare to determine if there is 1495 // an upgrade while the browser is kept alive by a persistent extension. 1496 upgrade_util::SaveLastModifiedTimeOfExe(); 1497 #endif 1498 1499 // Record now as the last successful chrome start. 1500 GoogleUpdateSettings::SetLastRunTime(); 1501 1502 #if defined(OS_MACOSX) 1503 // Call Recycle() here as late as possible, before going into the loop 1504 // because Start() will add things to it while creating the main window. 1505 if (parameters().autorelease_pool) 1506 parameters().autorelease_pool->Recycle(); 1507 #endif 1508 1509 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start; 1510 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay); 1511 1512 // If we're running tests (ui_task is non-null), then we don't want to 1513 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or 1514 // RequestLanguageList 1515 if (parameters().ui_task == NULL) { 1516 // Request new variations seed information from server. 1517 chrome_variations::VariationsService* variations_service = 1518 browser_process_->variations_service(); 1519 if (variations_service) { 1520 variations_service->StartRepeatedVariationsSeedFetch(); 1521 1522 #if defined(OS_WIN) 1523 variations_service->StartGoogleUpdateRegistrySync(); 1524 #endif 1525 } 1526 1527 TranslateDownloadManager::RequestLanguageList(profile_->GetPrefs()); 1528 } 1529 1530 run_message_loop_ = true; 1531 } else { 1532 run_message_loop_ = false; 1533 } 1534 browser_creator_.reset(); 1535 #endif // !defined(OS_ANDROID) 1536 1537 performance_monitor::PerformanceMonitor::GetInstance()->Initialize(); 1538 1539 PostBrowserStart(); 1540 1541 if (parameters().ui_task) { 1542 // We end the startup timer here if we have parameters to run, because we 1543 // never start to run the main loop (where we normally stop the timer). 1544 startup_timer_->SignalStartupComplete( 1545 performance_monitor::StartupTimer::STARTUP_TEST); 1546 parameters().ui_task->Run(); 1547 delete parameters().ui_task; 1548 run_message_loop_ = false; 1549 } 1550 #if defined(OS_ANDROID) 1551 // We never run the C++ main loop on Android, since the UI thread message 1552 // loop is controlled by the OS, so this is as close as we can get to 1553 // the start of the main loop 1554 if (result_code_ <= 0) { 1555 RecordBrowserStartupTime(); 1556 } 1557 #endif 1558 return result_code_; 1559 } 1560 1561 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) { 1562 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun"); 1563 #if defined(OS_ANDROID) 1564 // Chrome on Android does not use default MessageLoop. It has its own 1565 // Android specific MessageLoop 1566 NOTREACHED(); 1567 return true; 1568 #else 1569 // Set the result code set in PreMainMessageLoopRun or set above. 1570 *result_code = result_code_; 1571 if (!run_message_loop_) 1572 return true; // Don't run the default message loop. 1573 1574 // These should be invoked as close to the start of the browser's 1575 // UI thread message loop as possible to get a stable measurement 1576 // across versions. 1577 RecordBrowserStartupTime(); 1578 startup_timer_->SignalStartupComplete( 1579 performance_monitor::StartupTimer::STARTUP_NORMAL); 1580 1581 DCHECK(base::MessageLoopForUI::IsCurrent()); 1582 base::RunLoop run_loop; 1583 1584 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle(); 1585 1586 MetricsService::SetExecutionPhase(MetricsService::MAIN_MESSAGE_LOOP_RUN, 1587 g_browser_process->local_state()); 1588 run_loop.Run(); 1589 1590 return true; 1591 #endif 1592 } 1593 1594 void ChromeBrowserMainParts::PostMainMessageLoopRun() { 1595 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun"); 1596 #if defined(OS_ANDROID) 1597 // Chrome on Android does not use default MessageLoop. It has its own 1598 // Android specific MessageLoop 1599 NOTREACHED(); 1600 #else 1601 1602 // Start watching for jank during shutdown. It gets disarmed when 1603 // |shutdown_watcher_| object is destructed. 1604 MetricsService::SetExecutionPhase(MetricsService::SHUTDOWN_TIMEBOMB_ARM, 1605 g_browser_process->local_state()); 1606 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300)); 1607 1608 // Disarm the startup hang detector time bomb if it is still Arm'ed. 1609 startup_watcher_->Disarm(); 1610 1611 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) 1612 chrome_extra_parts_[i]->PostMainMessageLoopRun(); 1613 1614 // Some tests don't set parameters.ui_task, so they started translate 1615 // language fetch that was never completed so we need to cleanup here 1616 // otherwise it will be done by the destructor in a wrong thread. 1617 TranslateService::Shutdown(parameters().ui_task == NULL); 1618 1619 if (notify_result_ == ProcessSingleton::PROCESS_NONE) 1620 process_singleton_->Cleanup(); 1621 1622 // Stop all tasks that might run on WatchDogThread. 1623 ThreadWatcherList::StopWatchingAll(); 1624 1625 browser_process_->metrics_service()->Stop(); 1626 1627 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop(); 1628 browser_process_->StartTearDown(); 1629 #endif 1630 } 1631 1632 void ChromeBrowserMainParts::PostDestroyThreads() { 1633 #if defined(OS_ANDROID) 1634 // On Android, there is no quit/exit. So the browser's main message loop will 1635 // not finish. 1636 NOTREACHED(); 1637 #else 1638 browser_process_->PostDestroyThreads(); 1639 // browser_shutdown takes care of deleting browser_process, so we need to 1640 // release it. 1641 ignore_result(browser_process_.release()); 1642 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_); 1643 master_prefs_.reset(); 1644 process_singleton_.reset(); 1645 1646 // We need to do this check as late as possible, but due to modularity, this 1647 // may be the last point in Chrome. This would be more effective if done at 1648 // a higher level on the stack, so that it is impossible for an early return 1649 // to bypass this code. Perhaps we need a *final* hook that is called on all 1650 // paths from content/browser/browser_main. 1651 CHECK(MetricsService::UmaMetricsProperlyShutdown()); 1652 1653 #if defined(OS_CHROMEOS) 1654 chromeos::CrosSettings::Shutdown(); 1655 #endif 1656 #endif 1657 } 1658 1659 // Public members: 1660 1661 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) { 1662 chrome_extra_parts_.push_back(parts); 1663 } 1664