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