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