Aura impl of Linux Process Singleton Dialog.
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blobc16d5e3de6eca6242112b170073aaf73e888f844
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 <string>
12 #include <vector>
14 #include "base/at_exit.h"
15 #include "base/bind.h"
16 #include "base/command_line.h"
17 #include "base/debug/crash_logging.h"
18 #include "base/debug/debugger.h"
19 #include "base/debug/trace_event.h"
20 #include "base/file_util.h"
21 #include "base/files/file_path.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/path_service.h"
25 #include "base/prefs/json_pref_store.h"
26 #include "base/prefs/pref_registry_simple.h"
27 #include "base/prefs/pref_service.h"
28 #include "base/prefs/pref_value_store.h"
29 #include "base/prefs/scoped_user_pref_update.h"
30 #include "base/process/process_info.h"
31 #include "base/run_loop.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_piece.h"
34 #include "base/strings/string_split.h"
35 #include "base/strings/sys_string_conversions.h"
36 #include "base/strings/utf_string_conversions.h"
37 #include "base/sys_info.h"
38 #include "base/threading/platform_thread.h"
39 #include "base/time/time.h"
40 #include "base/values.h"
41 #include "build/build_config.h"
42 #include "chrome/browser/about_flags.h"
43 #include "chrome/browser/browser_process.h"
44 #include "chrome/browser/browser_process_impl.h"
45 #include "chrome/browser/browser_process_platform_part.h"
46 #include "chrome/browser/browser_shutdown.h"
47 #include "chrome/browser/chrome_browser_main_extra_parts.h"
48 #include "chrome/browser/component_updater/component_updater_service.h"
49 #include "chrome/browser/component_updater/flash_component_installer.h"
50 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
51 #include "chrome/browser/component_updater/recovery_component_installer.h"
52 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
53 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
54 #include "chrome/browser/defaults.h"
55 #include "chrome/browser/extensions/extension_protocols.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_system.h"
58 #include "chrome/browser/extensions/startup_helper.h"
59 #include "chrome/browser/first_run/first_run.h"
60 #include "chrome/browser/first_run/upgrade_util.h"
61 #include "chrome/browser/google/google_search_counter.h"
62 #include "chrome/browser/google/google_util.h"
63 #include "chrome/browser/gpu/gl_string_manager.h"
64 #include "chrome/browser/jankometer.h"
65 #include "chrome/browser/language_usage_metrics.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/nacl_host/nacl_process_host.h"
76 #include "chrome/browser/net/chrome_net_log.h"
77 #include "chrome/browser/net/crl_set_fetcher.h"
78 #include "chrome/browser/notifications/desktop_notification_service.h"
79 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
80 #include "chrome/browser/performance_monitor/performance_monitor.h"
81 #include "chrome/browser/performance_monitor/startup_timer.h"
82 #include "chrome/browser/plugins/plugin_prefs.h"
83 #include "chrome/browser/pref_service_flags_storage.h"
84 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
85 #include "chrome/browser/prefs/command_line_pref_store.h"
86 #include "chrome/browser/prefs/pref_metrics_service.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/shell_integration.h"
94 #include "chrome/browser/three_d_api_observer.h"
95 #include "chrome/browser/translate/translate_manager.h"
96 #include "chrome/browser/ui/app_list/app_list_service.h"
97 #include "chrome/browser/ui/browser.h"
98 #include "chrome/browser/ui/browser_finder.h"
99 #include "chrome/browser/ui/host_desktop.h"
100 #include "chrome/browser/ui/startup/default_browser_prompt.h"
101 #include "chrome/browser/ui/startup/startup_browser_creator.h"
102 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
103 #include "chrome/browser/ui/user_data_dir_dialog.h"
104 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
105 #include "chrome/browser/user_data_dir_extractor.h"
106 #include "chrome/common/chrome_constants.h"
107 #include "chrome/common/chrome_paths.h"
108 #include "chrome/common/chrome_result_codes.h"
109 #include "chrome/common/chrome_switches.h"
110 #include "chrome/common/crash_keys.h"
111 #include "chrome/common/env_vars.h"
112 #include "chrome/common/logging_chrome.h"
113 #include "chrome/common/net/net_resource_provider.h"
114 #include "chrome/common/pref_names.h"
115 #include "chrome/common/profiling.h"
116 #include "chrome/installer/util/google_update_settings.h"
117 #include "components/nacl/browser/nacl_browser.h"
118 #include "components/startup_metric_utils/startup_metric_utils.h"
119 #include "content/public/browser/browser_thread.h"
120 #include "content/public/browser/notification_observer.h"
121 #include "content/public/browser/notification_registrar.h"
122 #include "content/public/browser/notification_service.h"
123 #include "content/public/browser/notification_types.h"
124 #include "content/public/browser/site_instance.h"
125 #include "content/public/common/content_client.h"
126 #include "content/public/common/content_switches.h"
127 #include "content/public/common/main_function_params.h"
128 #include "grit/app_locale_settings.h"
129 #include "grit/browser_resources.h"
130 #include "grit/chromium_strings.h"
131 #include "grit/generated_resources.h"
132 #include "grit/platform_locale_settings.h"
133 #include "net/base/net_module.h"
134 #include "net/base/sdch_manager.h"
135 #include "net/cookies/cookie_monster.h"
136 #include "net/http/http_network_layer.h"
137 #include "net/http/http_stream_factory.h"
138 #include "net/url_request/url_request.h"
139 #include "ui/base/l10n/l10n_util.h"
140 #include "ui/base/layout.h"
141 #include "ui/base/resource/resource_bundle.h"
143 #if !defined(OS_ANDROID)
144 #include "chrome/browser/ui/active_tab_tracker.h"
145 #endif
147 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
148 #include "chrome/browser/first_run/upgrade_util_linux.h"
149 #include "chrome/browser/sxs_linux.h"
150 #endif
152 #if defined(OS_CHROMEOS)
153 #include "chrome/browser/chromeos/settings/cros_settings.h"
154 #include "chromeos/chromeos_switches.h"
155 #include "chromeos/settings/cros_settings_names.h"
156 #endif
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.
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/gfx/win/dpi.h"
179 #endif // defined(OS_WIN)
181 #if defined(OS_MACOSX)
182 #include <Security/Security.h>
184 #include "base/mac/scoped_nsautorelease_pool.h"
185 #include "chrome/browser/mac/keystone_glue.h"
186 #endif
188 #if defined(ENABLE_RLZ)
189 #include "chrome/browser/rlz/rlz.h"
190 #endif
192 #if defined(TOOLKIT_VIEWS)
193 #include "ui/views/focus/accelerator_handler.h"
194 #endif
196 #if defined(USE_AURA)
197 #include "ui/aura/env.h"
198 #endif
200 using content::BrowserThread;
202 namespace {
204 // This function provides some ways to test crash and assertion handling
205 // behavior of the program.
206 void HandleTestParameters(const CommandLine& command_line) {
207 // This parameter causes an assertion.
208 if (command_line.HasSwitch(switches::kBrowserAssertTest)) {
209 DCHECK(false);
212 // This parameter causes a null pointer crash (crash reporter trigger).
213 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
214 int* bad_pointer = NULL;
215 *bad_pointer = 0;
219 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
220 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
221 const std::vector<GURL>& new_tabs) {
222 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
223 it != new_tabs.end(); ++it) {
224 if (it->is_valid())
225 browser_creator->AddFirstRunTab(*it);
228 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
230 // Returns the new local state object, guaranteed non-NULL.
231 // |local_state_task_runner| must be a shutdown-blocking task runner.
232 PrefService* InitializeLocalState(
233 base::SequencedTaskRunner* local_state_task_runner,
234 const CommandLine& parsed_command_line) {
235 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
236 base::FilePath local_state_path;
237 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
238 bool local_state_file_exists = base::PathExists(local_state_path);
240 // Load local state. This includes the application locale so we know which
241 // locale dll to load. This also causes local state prefs to be registered.
242 PrefService* local_state = g_browser_process->local_state();
243 DCHECK(local_state);
245 #if defined(OS_WIN)
246 if (first_run::IsChromeFirstRun()) {
247 // During first run we read the google_update registry key to find what
248 // language the user selected when downloading the installer. This
249 // becomes our default language in the prefs.
250 // Other platforms obey the system locale.
251 std::wstring install_lang;
252 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
253 local_state->SetString(prefs::kApplicationLocale,
254 WideToASCII(install_lang));
257 #endif // defined(OS_WIN)
259 // If the local state file for the current profile doesn't exist and the
260 // parent profile command line flag is present, then we should inherit some
261 // local state from the parent profile.
262 // Checking that the local state file for the current profile doesn't exist
263 // is the most robust way to determine whether we need to inherit or not
264 // since the parent profile command line flag can be present even when the
265 // current profile is not a new one, and in that case we do not want to
266 // inherit and reset the user's setting.
268 // TODO(mnissler): We should probably just instantiate a
269 // JSONPrefStore here instead of an entire PrefService. Once this is
270 // addressed, the call to browser_prefs::RegisterLocalState can move
271 // to chrome_prefs::CreateLocalState.
272 if (!local_state_file_exists &&
273 parsed_command_line.HasSwitch(switches::kParentProfile)) {
274 base::FilePath parent_profile =
275 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
276 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
277 scoped_ptr<PrefService> parent_local_state(
278 chrome_prefs::CreateLocalState(
279 parent_profile,
280 local_state_task_runner,
281 g_browser_process->policy_service(),
282 registry,
283 false));
284 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
285 // Right now, we only inherit the locale setting from the parent profile.
286 local_state->SetString(
287 prefs::kApplicationLocale,
288 parent_local_state->GetString(prefs::kApplicationLocale));
291 #if defined(OS_CHROMEOS)
292 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
293 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
294 // Ensure that we start with owner's locale.
295 if (!owner_locale.empty() &&
296 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
297 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
298 local_state->SetString(prefs::kApplicationLocale, owner_locale);
301 #endif
303 return local_state;
306 // Returns the path that contains the profile that should be loaded
307 // on process startup.
308 base::FilePath GetStartupProfilePath(const base::FilePath& user_data_dir,
309 const CommandLine& command_line) {
310 if (command_line.HasSwitch(switches::kProfileDirectory)) {
311 return user_data_dir.Append(
312 command_line.GetSwitchValuePath(switches::kProfileDirectory));
315 // If we are showing the app list then chrome isn't shown so load the app
316 // list's profile rather than chrome's.
317 if (command_line.HasSwitch(switches::kShowAppList)) {
318 return AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->
319 GetProfilePath(user_data_dir);
322 return g_browser_process->profile_manager()->GetLastUsedProfileDir(
323 user_data_dir);
326 // Initializes the profile, possibly doing some user prompting to pick a
327 // fallback profile. Returns the newly created profile, or NULL if startup
328 // should not continue.
329 Profile* CreateProfile(const content::MainFunctionParams& parameters,
330 const base::FilePath& user_data_dir,
331 const CommandLine& parsed_command_line) {
332 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
333 base::Time start = base::Time::Now();
334 if (profiles::IsMultipleProfilesEnabled() &&
335 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
336 g_browser_process->local_state()->SetString(prefs::kProfileLastUsed,
337 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
338 // Clear kProfilesLastActive since the user only wants to launch a specific
339 // profile.
340 ListPrefUpdate update(g_browser_process->local_state(),
341 prefs::kProfilesLastActive);
342 ListValue* profile_list = update.Get();
343 profile_list->Clear();
346 Profile* profile = NULL;
347 #if defined(OS_CHROMEOS)
348 // TODO(ivankr): http://crbug.com/83792
349 profile = g_browser_process->profile_manager()->GetDefaultProfile(
350 user_data_dir);
351 #else
352 base::FilePath profile_path =
353 GetStartupProfilePath(user_data_dir, parsed_command_line);
354 profile = g_browser_process->profile_manager()->GetProfile(
355 profile_path);
357 // If we're using the --new-profile-management flag and this profile is
358 // signed out, then we should show the user manager instead. By switching
359 // the active profile to the guest profile we ensure that no
360 // browser windows will be opened for the guest profile.
361 if (profiles::IsNewProfileManagementEnabled() && !profile->IsGuestSession()) {
362 ProfileInfoCache& cache =
363 g_browser_process->profile_manager()->GetProfileInfoCache();
364 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
366 if (cache.ProfileIsSigninRequiredAtIndex(profile_index))
367 profile = g_browser_process->profile_manager()->GetProfile(
368 ProfileManager::GetGuestProfilePath());
370 #endif
371 if (profile) {
372 UMA_HISTOGRAM_LONG_TIMES(
373 "Startup.CreateFirstProfile", base::Time::Now() - start);
374 return profile;
377 #if !defined(OS_WIN)
378 // TODO(port): fix this. See comments near the definition of
379 // user_data_dir. It is better to CHECK-fail here than it is to
380 // silently exit because of missing code in the above test.
381 CHECK(profile) << "Cannot get default profile.";
382 #endif
384 return NULL;
387 #if defined(OS_MACOSX)
388 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
389 SecKeychainCallbackInfo* info, void* context) {
390 return noErr;
392 #endif
394 #if !defined(OS_ANDROID)
395 void RegisterComponentsForUpdate(const CommandLine& command_line) {
396 ComponentUpdateService* cus = g_browser_process->component_updater();
398 // Registration can be before or after cus->Start() so it is ok to post
399 // a task to the UI thread to do registration once you done the necessary
400 // file IO to know you existing component version.
401 #if !defined(OS_CHROMEOS)
402 RegisterRecoveryComponent(cus, g_browser_process->local_state());
403 RegisterPepperFlashComponent(cus);
404 RegisterSwiftShaderComponent(cus);
405 #endif
407 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(
408 cus, command_line);
410 #if !defined(OS_CHROMEOS)
411 RegisterWidevineCdmComponent(cus);
413 // CRLSetFetcher attempts to load a CRL set from either the local disk or
414 // network.
415 if (!command_line.HasSwitch(switches::kDisableCRLSets))
416 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus);
417 #endif
419 cus->Start();
422 bool ProcessSingletonNotificationCallback(
423 const CommandLine& command_line,
424 const base::FilePath& current_directory) {
425 // Drop the request if the browser process is already in shutdown path.
426 if (!g_browser_process || g_browser_process->IsShuttingDown())
427 return false;
429 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
430 std::string start_time_string =
431 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
432 int64 remote_start_time;
433 if (base::StringToInt64(start_time_string, &remote_start_time)) {
434 base::TimeDelta elapsed =
435 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
436 if (command_line.HasSwitch(switches::kFastStart)) {
437 UMA_HISTOGRAM_LONG_TIMES(
438 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
439 } else {
440 UMA_HISTOGRAM_LONG_TIMES(
441 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
446 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
447 command_line);
449 // TODO(erikwright): Consider removing this - AFAIK it is no longer used.
450 // Handle the --uninstall-extension startup action. This needs to done here in
451 // the process that is running with the target profile, otherwise the
452 // uninstall will fail to unload and remove all components.
453 if (command_line.HasSwitch(switches::kUninstallExtension)) {
454 // The uninstall extension switch can't be combined with the profile
455 // directory switch.
456 DCHECK(!command_line.HasSwitch(switches::kProfileDirectory));
458 Profile* profile = ProfileManager::GetLastUsedProfile();
459 if (!profile) {
460 // We should never be called before the profile has been created.
461 NOTREACHED();
462 return true;
465 extensions::StartupHelper extension_startup_helper;
466 extension_startup_helper.UninstallExtension(command_line, profile);
467 return true;
470 base::FilePath user_data_dir =
471 g_browser_process->profile_manager()->user_data_dir();
472 base::FilePath startup_profile_dir =
473 GetStartupProfilePath(user_data_dir, command_line);
475 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
476 command_line, current_directory, startup_profile_dir);
477 return true;
479 #endif // !defined(OS_ANDROID)
481 void LaunchDevToolsHandlerIfNeeded(const CommandLine& command_line) {
482 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
483 std::string port_str =
484 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
485 int port;
486 if (base::StringToInt(port_str, &port) && port > 0 && port < 65535) {
487 std::string frontend_str;
488 if (command_line.HasSwitch(::switches::kRemoteDebuggingFrontend)) {
489 frontend_str = command_line.GetSwitchValueASCII(
490 ::switches::kRemoteDebuggingFrontend);
492 g_browser_process->CreateDevToolsHttpProtocolHandler(
493 chrome::HOST_DESKTOP_TYPE_NATIVE,
494 "127.0.0.1",
495 port,
496 frontend_str);
497 } else {
498 DLOG(WARNING) << "Invalid http debugger port number " << port;
503 // Heap allocated class that listens for first page load, kicks off stat
504 // recording and then deletes itself.
505 class LoadCompleteListener : public content::NotificationObserver {
506 public:
507 LoadCompleteListener() {
508 registrar_.Add(this,
509 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
510 content::NotificationService::AllSources());
512 virtual ~LoadCompleteListener() {}
514 // content::NotificationObserver implementation.
515 virtual void Observe(int type,
516 const content::NotificationSource& source,
517 const content::NotificationDetails& details) OVERRIDE {
518 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
519 startup_metric_utils::OnInitialPageLoadComplete();
520 delete this;
523 private:
524 content::NotificationRegistrar registrar_;
525 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
528 } // namespace
530 namespace chrome_browser {
531 // This error message is not localized because we failed to load the
532 // localization data files.
533 const char kMissingLocaleDataTitle[] = "Missing File Error";
534 const char kMissingLocaleDataMessage[] =
535 "Unable to find locale data files. Please reinstall.";
536 } // namespace chrome_browser
538 // BrowserMainParts ------------------------------------------------------------
540 // static
541 bool ChromeBrowserMainParts::disable_enforcing_cookie_policies_for_tests_ =
542 false;
544 ChromeBrowserMainParts::ChromeBrowserMainParts(
545 const content::MainFunctionParams& parameters)
546 : parameters_(parameters),
547 parsed_command_line_(parameters.command_line),
548 result_code_(content::RESULT_CODE_NORMAL_EXIT),
549 startup_watcher_(new StartupTimeBomb()),
550 shutdown_watcher_(new ShutdownWatcherHelper()),
551 startup_timer_(new performance_monitor::StartupTimer()),
552 browser_field_trials_(parameters.command_line),
553 translate_manager_(NULL),
554 profile_(NULL),
555 run_message_loop_(true),
556 notify_result_(ProcessSingleton::PROCESS_NONE),
557 local_state_(NULL),
558 restart_last_session_(false) {
559 // If we're running tests (ui_task is non-null).
560 if (parameters.ui_task)
561 browser_defaults::enable_help_app = false;
563 // Chrome disallows cookies by default. All code paths that want to use
564 // cookies need to go through one of Chrome's URLRequestContexts which have
565 // a ChromeNetworkDelegate attached that selectively allows cookies again.
566 if (!disable_enforcing_cookie_policies_for_tests_)
567 net::URLRequest::SetDefaultCookiePolicyToBlock();
570 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
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();
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)
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()));
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 // 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.";
614 if (command_line->HasSwitch(switches::kForceVariationIds)) {
615 // Create default variation ids which will always be included in the
616 // X-Chrome-Variations request header.
617 chrome_variations::VariationsHttpHeaderProvider* provider =
618 chrome_variations::VariationsHttpHeaderProvider::GetInstance();
619 bool result = provider->SetDefaultVariationIds(
620 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
621 CHECK(result) << "Invalid --" << switches::kForceVariationIds
622 << " list specified.";
624 chrome_variations::VariationsService* variations_service =
625 browser_process_->variations_service();
626 if (variations_service)
627 variations_service->CreateTrialsFromSeed();
629 // This must be called after the local state is initialized.
630 browser_field_trials_.SetupFieldTrials(local_state_);
632 SetupPlatformFieldTrials();
634 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
635 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
636 // Even though base::Bind does AddRef and Release, the object will not be
637 // deleted after the Task is executed.
638 field_trial_synchronizer_ = new FieldTrialSynchronizer();
641 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
643 void ChromeBrowserMainParts::StartMetricsRecording() {
644 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
645 MetricsService* metrics = g_browser_process->metrics_service();
647 // TODO(miu): Metrics reporting is disabled in DEBUG builds until ill-fired
648 // DCHECKs are fixed, and/or we reconsider whether metrics reporting should
649 // really ever be enabled for debug builds. http://crbug.com/156979
650 #if defined(NDEBUG)
651 const bool only_do_metrics_recording =
652 parsed_command_line_.HasSwitch(switches::kMetricsRecordingOnly) ||
653 parsed_command_line_.HasSwitch(switches::kEnableBenchmarking);
654 #else
655 const bool only_do_metrics_recording = true;
656 #endif
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). Not
867 // needed on Android as there aren't experimental flags.
868 // On ChromeOS system level flags are applied from the device settings from
869 // the session manager.
871 TRACE_EVENT0("startup",
872 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
873 about_flags::PrefServiceFlagsStorage flags_storage_(
874 g_browser_process->local_state());
875 about_flags::ConvertFlagsToSwitches(&flags_storage_,
876 CommandLine::ForCurrentProcess(),
877 about_flags::kAddSentinels);
879 #endif
881 local_state_->UpdateCommandLinePrefStore(
882 new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
884 // Reset the command line in the crash report details, since we may have
885 // just changed it to include experiments.
886 crash_keys::SetSwitchesFromCommandLine(CommandLine::ForCurrentProcess());
888 // If we're running tests (ui_task is non-null), then the ResourceBundle
889 // has already been initialized.
890 if (parameters().ui_task &&
891 !local_state_->IsManagedPreference(prefs::kApplicationLocale)) {
892 browser_process_->SetApplicationLocale("en-US");
893 } else {
894 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
895 // needed when loading the MainMenu.nib and the language doesn't depend on
896 // anything since it comes from Cocoa.
897 #if defined(OS_MACOSX)
898 browser_process_->SetApplicationLocale(l10n_util::GetLocaleOverride());
899 #else
900 const std::string locale =
901 local_state_->GetString(prefs::kApplicationLocale);
903 #if defined(OS_WIN)
904 gfx::EnableHighDPISupport();
905 #endif
907 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
908 // method InitSharedInstance is ignored.
910 TRACE_EVENT_BEGIN0("startup",
911 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
912 const std::string loaded_locale =
913 ResourceBundle::InitSharedInstanceWithLocale(locale, NULL);
914 TRACE_EVENT_END0("startup",
915 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
917 if (loaded_locale.empty() &&
918 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
919 ShowMissingLocaleMessageBox();
920 return chrome::RESULT_CODE_MISSING_DATA;
922 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
923 browser_process_->SetApplicationLocale(loaded_locale);
925 base::FilePath resources_pack_path;
926 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
928 TRACE_EVENT0("startup",
929 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
930 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
931 resources_pack_path, ui::SCALE_FACTOR_NONE);
933 #endif // defined(OS_MACOSX)
936 #if defined(TOOLKIT_GTK)
937 g_set_application_name(l10n_util::GetStringUTF8(IDS_PRODUCT_NAME).c_str());
938 #endif
940 // Android does first run in Java instead of native.
941 // Chrome OS has its own out-of-box-experience code.
942 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
943 // On first run, we need to process the predictor preferences before the
944 // browser's profile_manager object is created, but after ResourceBundle
945 // is initialized.
946 if (first_run::IsChromeFirstRun()) {
947 first_run::ProcessMasterPreferencesResult pmp_result =
948 first_run::ProcessMasterPreferences(user_data_dir_,
949 master_prefs_.get());
950 if (pmp_result == first_run::EULA_EXIT_NOW)
951 return chrome::RESULT_CODE_EULA_REFUSED;
953 if (!parsed_command_line().HasSwitch(switches::kApp) &&
954 !parsed_command_line().HasSwitch(switches::kAppId) &&
955 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
956 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
959 // TODO(macourteau): refactor preferences that are copied from
960 // master_preferences into local_state, as a "local_state" section in
961 // master preferences. If possible, a generic solution would be prefered
962 // over a copy one-by-one of specific preferences. Also see related TODO
963 // in first_run.h.
965 // Store the initial VariationsService seed in local state, if it exists
966 // in master prefs.
967 if (!master_prefs_->variations_seed.empty()) {
968 local_state_->SetString(prefs::kVariationsSeed,
969 master_prefs_->variations_seed);
970 // Set the variation seed date to the current system time. If the user's
971 // clock is incorrect, this may cause some field trial expiry checks to
972 // not do the right thing until the next seed update from the server,
973 // when this value will be updated.
974 local_state_->SetInt64(prefs::kVariationsSeedDate,
975 base::Time::Now().ToInternalValue());
978 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
979 local_state_->SetString(
980 prefs::kBrowserSuppressDefaultBrowserPrompt,
981 master_prefs_->suppress_default_browser_prompt_for_version);
984 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->HandleFirstRun();
986 #endif
988 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
989 // Set the product channel for crash reports.
990 base::debug::SetCrashKeyValue(crash_keys::kChannel,
991 chrome::VersionInfo::GetVersionStringModifier());
992 #endif
994 // Initialize tracking synchronizer system.
995 tracking_synchronizer_ = new chrome_browser_metrics::TrackingSynchronizer();
997 // Now that all preferences have been registered, set the install date
998 // for the uninstall metrics if this is our first run. This only actually
999 // gets used if the user has metrics reporting enabled at uninstall time.
1000 int64 install_date = local_state_->GetInt64(prefs::kInstallDate);
1001 if (install_date == 0)
1002 local_state_->SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT());
1004 #if defined(OS_MACOSX)
1005 // Get the Keychain API to register for distributed notifications on the main
1006 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1007 // which doesn't. This ensures those notifications will get delivered
1008 // properly. See issue 37766.
1009 // (Note that the callback mask here is empty. I don't want to register for
1010 // any callbacks, I just want to initialize the mechanism.)
1011 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1012 #endif
1014 #if defined(OS_CHROMEOS)
1015 // Must be done after g_browser_process is constructed, before
1016 // SetupMetricsAndFieldTrials().
1017 chromeos::CrosSettings::Initialize();
1018 #endif
1020 // Now the command line has been mutated based on about:flags, we can setup
1021 // metrics and initialize field trials. The field trials are needed by
1022 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1023 SetupMetricsAndFieldTrials();
1025 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1026 browser_process_->PreCreateThreads();
1028 return content::RESULT_CODE_NORMAL_EXIT;
1031 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1032 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1033 result_code_ = PreMainMessageLoopRunImpl();
1035 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1036 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1039 // PreMainMessageLoopRun calls these extra stages in the following order:
1040 // PreMainMessageLoopRunImpl()
1041 // ... initial setup, including browser_process_ setup.
1042 // PreProfileInit()
1043 // ... additional setup, including CreateProfile()
1044 // PostProfileInit()
1045 // ... additional setup
1046 // PreBrowserStart()
1047 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1048 // PostBrowserStart()
1050 void ChromeBrowserMainParts::PreProfileInit() {
1051 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1053 #if !defined(OS_ANDROID)
1054 ProfileManager* profile_manager = g_browser_process->profile_manager();
1056 // First check if any ephemeral profiles are left behind because of browser
1057 // crash and schedule them for deletion and then proceed with getting the set
1058 // of profiles to open.
1059 ProfileInfoCache& profile_cache = profile_manager->GetProfileInfoCache();
1060 size_t profiles_count = profile_cache.GetNumberOfProfiles();
1061 std::vector<base::FilePath> profiles_to_delete;
1062 for (size_t i = 0;i < profiles_count; ++i) {
1063 if (profile_cache.ProfileIsEphemeralAtIndex(i))
1064 profiles_to_delete.push_back(profile_cache.GetPathOfProfileAtIndex(i));
1067 if (profiles_to_delete.size()) {
1068 for (size_t i = 0;i < profiles_to_delete.size(); ++i) {
1069 profile_manager->ScheduleProfileForDeletion(
1070 profiles_to_delete[i], ProfileManager::CreateCallback());
1072 // Clean up stale profiles immediately after browser start.
1073 BrowserThread::PostTask(
1074 BrowserThread::FILE, FROM_HERE,
1075 base::Bind(&ProfileManager::CleanUpStaleProfiles, profiles_to_delete));
1077 #endif // OS_ANDROID
1079 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1080 chrome_extra_parts_[i]->PreProfileInit();
1083 void ChromeBrowserMainParts::PostProfileInit() {
1084 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1085 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1086 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1087 chrome_extra_parts_[i]->PostProfileInit();
1090 void ChromeBrowserMainParts::PreBrowserStart() {
1091 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1092 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1093 chrome_extra_parts_[i]->PreBrowserStart();
1095 three_d_observer_.reset(new ThreeDAPIObserver());
1098 void ChromeBrowserMainParts::PostBrowserStart() {
1099 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1100 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1101 chrome_extra_parts_[i]->PostBrowserStart();
1102 #if !defined(OS_ANDROID)
1103 // Allow ProcessSingleton to process messages.
1104 process_singleton_->Unlock();
1105 #endif
1108 void ChromeBrowserMainParts::SetupPlatformFieldTrials() {
1109 // Base class implementation of this does nothing.
1112 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1113 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1114 #if !defined(OS_ANDROID)
1115 if (CommandLine::ForCurrentProcess()->HasSwitch(
1116 switches::kTrackActiveVisitTime)) {
1117 active_tab_tracker_.reset(new ActiveTabTracker());
1118 // TODO(sky): nuke this when all ports support ActiveTabTracker.
1119 if (!active_tab_tracker_->is_valid())
1120 active_tab_tracker_.reset();
1122 #endif
1124 // Android updates the metrics service dynamically depending on whether the
1125 // application is in the foreground or not. Do not start here.
1126 #if !defined(OS_ANDROID)
1127 // Now that the file thread has been started, start recording.
1128 StartMetricsRecording();
1129 #endif
1131 // Create watchdog thread after creating all other threads because it will
1132 // watch the other threads and they must be running.
1133 browser_process_->watchdog_thread();
1135 // Do any initializating in the browser process that requires all threads
1136 // running.
1137 browser_process_->PreMainMessageLoopRun();
1139 // Record last shutdown time into a histogram.
1140 browser_shutdown::ReadLastShutdownInfo();
1142 #if defined(OS_WIN)
1143 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1144 // tasks. Those care whether the browser is already running. On Linux/Mac,
1145 // upgrade/uninstall happen separately.
1146 bool already_running = browser_util::IsBrowserAlreadyRunning();
1148 // If the command line specifies 'uninstall' then we need to work here
1149 // unless we detect another chrome browser running.
1150 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1151 return DoUninstallTasks(already_running);
1154 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1155 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1156 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1157 parsed_command_line_);
1159 #endif
1161 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1162 return ShellIntegration::SetAsDefaultBrowser() ?
1163 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1164 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1167 #if defined(USE_AURA)
1168 // Env creates the compositor. Aura widgets need the compositor to be created
1169 // before they can be initialized by the browser.
1170 aura::Env::CreateInstance();
1171 #endif
1173 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1174 #if !defined(OS_ANDROID)
1175 // If the command line specifies --pack-extension, attempt the pack extension
1176 // startup action and exit.
1177 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1178 extensions::StartupHelper extension_startup_helper;
1179 if (extension_startup_helper.PackExtension(parsed_command_line()))
1180 return content::RESULT_CODE_NORMAL_EXIT;
1181 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1184 // If we're being launched just to check the connector policy, we are
1185 // short-lived and don't want to be passing that switch off.
1186 bool pass_command_line = !parsed_command_line().HasSwitch(
1187 switches::kCheckCloudPrintConnectorPolicy);
1189 if (pass_command_line) {
1190 // When another process is running, use that process instead of starting a
1191 // new one. NotifyOtherProcess will currently give the other process up to
1192 // 20 seconds to respond. Note that this needs to be done before we attempt
1193 // to read the profile.
1194 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1195 UMA_HISTOGRAM_ENUMERATION("NotifyOtherProcessOrCreate.Result",
1196 notify_result_,
1197 ProcessSingleton::NUM_NOTIFY_RESULTS);
1198 switch (notify_result_) {
1199 case ProcessSingleton::PROCESS_NONE:
1200 // No process already running, fall through to starting a new one.
1201 break;
1203 case ProcessSingleton::PROCESS_NOTIFIED:
1204 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1205 printf("%s\n", base::SysWideToNativeMB(UTF16ToWide(
1206 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1207 #endif
1208 // Having a differentiated return type for testing allows for tests to
1209 // verify proper handling of some switches. When not testing, stick to
1210 // the standard Unix convention of returning zero when things went as
1211 // expected.
1212 if (parsed_command_line().HasSwitch(switches::kTestType))
1213 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1214 return content::RESULT_CODE_NORMAL_EXIT;
1216 case ProcessSingleton::PROFILE_IN_USE:
1217 return chrome::RESULT_CODE_PROFILE_IN_USE;
1219 case ProcessSingleton::LOCK_ERROR:
1220 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1221 "directory. This means that running multiple instances "
1222 "would start multiple browser processes rather than "
1223 "opening a new window in the existing process. Aborting "
1224 "now to avoid profile corruption.";
1225 return chrome::RESULT_CODE_PROFILE_IN_USE;
1227 default:
1228 NOTREACHED();
1232 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1233 if (sxs_linux::ShouldMigrateUserDataDir())
1234 return sxs_linux::MigrateUserDataDir();
1235 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1237 first_run::CreateSentinelIfNeeded();
1238 #endif // !defined(OS_ANDROID)
1240 // Desktop construction occurs here, (required before profile creation).
1241 PreProfileInit();
1243 std::string try_chrome =
1244 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1245 if (!try_chrome.empty()) {
1246 #if defined(OS_WIN)
1247 // Setup.exe has determined that we need to run a retention experiment
1248 // and has lauched chrome to show the experiment UI. It is guaranteed that
1249 // no other Chrome is currently running as the process singleton was
1250 // sucessfully grabbed above.
1251 int try_chrome_int;
1252 base::StringToInt(try_chrome, &try_chrome_int);
1253 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1254 try_chrome_int,
1255 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1256 base::Unretained(process_singleton_.get())));
1257 if (answer == TryChromeDialogView::NOT_NOW)
1258 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1259 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1260 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1261 // At this point the user is willing to try chrome again.
1262 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1263 // Only set in the unattended case, the interactive case is Windows 8.
1264 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1265 ShellIntegration::SET_DEFAULT_UNATTENDED)
1266 ShellIntegration::SetAsDefaultBrowser();
1268 #else
1269 // We don't support retention experiments on Mac or Linux.
1270 return content::RESULT_CODE_NORMAL_EXIT;
1271 #endif // defined(OS_WIN)
1274 // Profile creation ----------------------------------------------------------
1276 // Called before CreateProfile because creating the profile can trigger
1277 // calls to GetDefaultProfile().
1278 ProfileManager::AllowGetDefaultProfile();
1280 MetricsService::SetExecutionPhase(MetricsService::CREATE_PROFILE);
1281 profile_ = CreateProfile(parameters(), user_data_dir_, parsed_command_line());
1282 if (!profile_)
1283 return content::RESULT_CODE_NORMAL_EXIT;
1285 #if defined(ENABLE_BACKGROUND)
1286 // Autoload any profiles which are running background apps.
1287 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1288 browser_process_->profile_manager()->AutoloadProfiles();
1289 #endif
1290 // Post-profile init ---------------------------------------------------------
1292 #if defined(OS_WIN)
1293 // Do the tasks if chrome has been upgraded while it was last running.
1294 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1295 return content::RESULT_CODE_NORMAL_EXIT;
1297 // Check if there is any machine level Chrome installed on the current
1298 // machine. If yes and the current Chrome process is user level, we do not
1299 // allow the user level Chrome to run. So we notify the user and uninstall
1300 // user level Chrome.
1301 // Note this check should only happen here, after all the checks above
1302 // (uninstall, resource bundle initialization, other chrome browser
1303 // processes etc).
1304 // Do not allow this to occur for Chrome Frame user-to-system handoffs.
1305 if (!parsed_command_line().HasSwitch(switches::kChromeFrame) &&
1306 ChromeBrowserMainPartsWin::CheckMachineLevelInstall()) {
1307 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1309 #endif
1311 // Create the TranslateManager singleton.
1312 translate_manager_ = TranslateManager::GetInstance();
1313 DCHECK(translate_manager_ != NULL);
1315 // Needs to be done before PostProfileInit, since login manager on CrOS is
1316 // called inside PostProfileInit.
1317 content::WebUIControllerFactory::RegisterFactory(
1318 ChromeWebUIControllerFactory::GetInstance());
1320 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1321 // So make sure to create it before that.
1322 #if !defined(DISABLE_NACL)
1323 NaClBrowserDelegateImpl* delegate = new NaClBrowserDelegateImpl(
1324 extensions::ExtensionSystem::Get(profile_)->info_map());
1325 nacl::NaClBrowser::SetDelegate(delegate);
1326 #endif
1328 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1329 // (requires supporting early exit).
1330 PostProfileInit();
1332 // Retrieve cached GL strings from local state and use them for GPU
1333 // blacklist decisions.
1334 if (g_browser_process->gl_string_manager())
1335 g_browser_process->gl_string_manager()->Initialize();
1337 // Create an instance of GpuModeManager to watch gpu mode pref change.
1338 g_browser_process->gpu_mode_manager();
1340 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1341 // Show the First Run UI if this is the first time Chrome has been run on
1342 // this computer, or we're being compelled to do so by a command line flag.
1343 // Note that this be done _after_ the PrefService is initialized and all
1344 // preferences are registered, since some of the code that the importer
1345 // touches reads preferences.
1346 if (first_run::IsChromeFirstRun()) {
1347 first_run::AutoImport(profile_,
1348 master_prefs_->homepage_defined,
1349 master_prefs_->do_import_items,
1350 master_prefs_->dont_import_items,
1351 master_prefs_->import_bookmarks_path);
1353 // Note: this can pop the first run consent dialog on linux.
1354 first_run::DoPostImportTasks(profile_, master_prefs_->make_chrome_default);
1356 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1357 browser_creator_->set_show_main_browser_window(
1358 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1359 } else {
1360 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1363 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1365 #if defined(OS_WIN)
1366 // Sets things up so that if we crash from this point on, a dialog will
1367 // popup asking the user to restart chrome. It is done this late to avoid
1368 // testing against a bunch of special cases that are taken care early on.
1369 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1370 parsed_command_line());
1372 // Registers Chrome with the Windows Restart Manager, which will restore the
1373 // Chrome session when the computer is restarted after a system update.
1374 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1375 // but should run on startup if extended to handle crashes/hangs/patches.
1376 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1377 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1378 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1379 parsed_command_line());
1382 // Verify that the profile is not on a network share and if so prepare to show
1383 // notification to the user.
1384 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1385 content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE,
1386 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1387 profile_->GetPath()));
1389 #endif // OS_WIN
1391 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1392 // Init the RLZ library. This just binds the dll and schedules a task on the
1393 // file thread to be run sometime later. If this is the first run we record
1394 // the installation event.
1395 PrefService* pref_service = profile_->GetPrefs();
1396 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1397 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1398 // Negative ping delay means to send ping immediately after a first search is
1399 // recorded.
1400 RLZTracker::InitRlzFromProfileDelayed(
1401 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1402 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1403 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1405 // Configure modules that need access to resources.
1406 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1408 // In unittest mode, this will do nothing. In normal mode, this will create
1409 // the global IntranetRedirectDetector instance, which will promptly go to
1410 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1411 // to see if it should do anything else.
1413 // A simpler way of doing all this would be to have some function which could
1414 // give the time elapsed since startup, and simply have this object check that
1415 // when asked to initialize itself, but this doesn't seem to exist.
1417 // This can't be created in the BrowserProcessImpl constructor because it
1418 // needs to read prefs that get set after that runs.
1419 browser_process_->intranet_redirect_detector();
1420 GoogleSearchCounter::RegisterForNotifications();
1422 // Disable SDCH filtering if switches::kEnableSdch is 0.
1423 int sdch_enabled = 1;
1424 if (parsed_command_line().HasSwitch(switches::kEnableSdch)) {
1425 base::StringToInt(parsed_command_line().GetSwitchValueASCII(
1426 switches::kEnableSdch), &sdch_enabled);
1427 if (!sdch_enabled)
1428 net::SdchManager::EnableSdchSupport(false);
1431 if (parsed_command_line().HasSwitch(switches::kEnableWatchdog))
1432 InstallJankometer(parsed_command_line());
1434 #if defined(OS_WIN) && !defined(GOOGLE_CHROME_BUILD)
1435 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1436 base::FilePath path =
1437 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1438 printing::PrintedDocument::set_debug_dump_path(path);
1440 #endif
1442 HandleTestParameters(parsed_command_line());
1443 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1444 base::debug::BeingDebugged());
1446 LanguageUsageMetrics::RecordAcceptLanguages(
1447 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1448 LanguageUsageMetrics::RecordApplicationLanguage(
1449 browser_process_->GetApplicationLocale());
1451 // The extension service may be available at this point. If the command line
1452 // specifies --uninstall-extension, attempt the uninstall extension startup
1453 // action.
1454 if (parsed_command_line().HasSwitch(switches::kUninstallExtension)) {
1455 extensions::StartupHelper extension_startup_helper;
1456 if (extension_startup_helper.UninstallExtension(
1457 parsed_command_line(), profile_))
1458 return content::RESULT_CODE_NORMAL_EXIT;
1459 return chrome::RESULT_CODE_UNINSTALL_EXTENSION_ERROR;
1462 // Start watching for hangs during startup. We disarm this hang detector when
1463 // ThreadWatcher takes over or when browser is shutdown or when
1464 // startup_watcher_ is deleted.
1465 MetricsService::SetExecutionPhase(MetricsService::STARTUP_TIMEBOMB_ARM);
1466 startup_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1468 // On mobile, need for clean shutdown arises only when the application comes
1469 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1470 // http://crbug.com/179143
1471 #if !defined(OS_ANDROID)
1472 // Start watching for a hang.
1473 MetricsService::LogNeedForCleanShutdown();
1474 #endif
1476 #if defined(ENABLE_FULL_PRINTING)
1477 // Create the instance of the cloud print proxy service so that it can launch
1478 // the service process if needed. This is needed because the service process
1479 // might have shutdown because an update was available.
1480 // TODO(torne): this should maybe be done with
1481 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1482 // instead?
1483 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1484 #endif
1486 // Start watching all browser threads for responsiveness.
1487 MetricsService::SetExecutionPhase(MetricsService::THREAD_WATCHER_START);
1488 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1490 #if !defined(DISABLE_NACL)
1491 if (parsed_command_line().HasSwitch(switches::kPnaclDir)) {
1492 PathService::Override(chrome::DIR_PNACL_BASE,
1493 parsed_command_line().GetSwitchValuePath(
1494 switches::kPnaclDir));
1497 content::BrowserThread::PostTask(
1498 content::BrowserThread::IO,
1499 FROM_HERE,
1500 base::Bind(NaClProcessHost::EarlyStartup));
1501 #endif
1503 // Make sure initial prefs are recorded
1504 PrefMetricsService::Factory::GetForProfile(profile_);
1506 PreBrowserStart();
1508 // Instantiate the notification UI manager, as this triggers a perf timer
1509 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1510 // triggering the timer and call that explicitly in the approprate place.
1511 // http://crbug.com/105065.
1512 browser_process_->notification_ui_manager();
1514 #if defined(OS_ANDROID)
1515 chrome_variations::VariationsService* variations_service =
1516 browser_process_->variations_service();
1517 if (variations_service)
1518 variations_service->StartRepeatedVariationsSeedFetch();
1519 #else
1520 // Most general initialization is behind us, but opening a
1521 // tab and/or session restore and such is still to be done.
1522 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1524 // We are in regular browser boot sequence. Open initial tabs and enter the
1525 // main message loop.
1526 int result_code;
1527 #if defined(OS_CHROMEOS)
1528 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1529 // them this early as the cryptohome hasn't yet been mounted (which happens
1530 // only once we log in.
1531 std::vector<Profile*> last_opened_profiles;
1532 #else
1533 std::vector<Profile*> last_opened_profiles =
1534 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1535 #endif
1537 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1538 RegisterComponentsForUpdate(parsed_command_line());
1540 if (browser_creator_->Start(parsed_command_line(), base::FilePath(),
1541 profile_, last_opened_profiles, &result_code)) {
1542 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1543 // Initialize autoupdate timer. Timer callback costs basically nothing
1544 // when browser is not in persistent mode, so it's OK to let it ride on
1545 // the main thread. This needs to be done here because we don't want
1546 // to start the timer when Chrome is run inside a test harness.
1547 browser_process_->StartAutoupdateTimer();
1548 #endif
1550 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1551 // On Linux, the running exe will be updated if an upgrade becomes
1552 // available while the browser is running. We need to save the last
1553 // modified time of the exe, so we can compare to determine if there is
1554 // an upgrade while the browser is kept alive by a persistent extension.
1555 upgrade_util::SaveLastModifiedTimeOfExe();
1556 #endif
1558 // Record now as the last successful chrome start.
1559 GoogleUpdateSettings::SetLastRunTime();
1561 #if defined(OS_MACOSX)
1562 // Call Recycle() here as late as possible, before going into the loop
1563 // because Start() will add things to it while creating the main window.
1564 if (parameters().autorelease_pool)
1565 parameters().autorelease_pool->Recycle();
1566 #endif
1568 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1569 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1571 // If we're running tests (ui_task is non-null), then we don't want to
1572 // call FetchLanguageListFromTranslateServer or
1573 // StartRepeatedVariationsSeedFetch.
1574 if (parameters().ui_task == NULL) {
1575 // Request new variations seed information from server.
1576 chrome_variations::VariationsService* variations_service =
1577 browser_process_->variations_service();
1578 if (variations_service) {
1579 variations_service->StartRepeatedVariationsSeedFetch();
1581 #if defined(OS_WIN)
1582 variations_service->StartGoogleUpdateRegistrySync();
1583 #endif
1586 if (translate_manager_ != NULL) {
1587 translate_manager_->FetchLanguageListFromTranslateServer(
1588 profile_->GetPrefs());
1592 run_message_loop_ = true;
1593 } else {
1594 run_message_loop_ = false;
1596 browser_creator_.reset();
1597 #endif // !defined(OS_ANDROID)
1599 performance_monitor::PerformanceMonitor::GetInstance()->Initialize();
1601 PostBrowserStart();
1603 if (parameters().ui_task) {
1604 // We end the startup timer here if we have parameters to run, because we
1605 // never start to run the main loop (where we normally stop the timer).
1606 startup_timer_->SignalStartupComplete(
1607 performance_monitor::StartupTimer::STARTUP_TEST);
1608 parameters().ui_task->Run();
1609 delete parameters().ui_task;
1610 run_message_loop_ = false;
1612 #if defined(OS_ANDROID)
1613 // We never run the C++ main loop on Android, since the UI thread message
1614 // loop is controlled by the OS, so this is as close as we can get to
1615 // the start of the main loop
1616 if (result_code_ <= 0) {
1617 RecordBrowserStartupTime();
1619 #endif
1620 return result_code_;
1623 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1624 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1625 #if defined(OS_ANDROID)
1626 // Chrome on Android does not use default MessageLoop. It has its own
1627 // Android specific MessageLoop
1628 NOTREACHED();
1629 return true;
1630 #else
1631 // Set the result code set in PreMainMessageLoopRun or set above.
1632 *result_code = result_code_;
1633 if (!run_message_loop_)
1634 return true; // Don't run the default message loop.
1636 // These should be invoked as close to the start of the browser's
1637 // UI thread message loop as possible to get a stable measurement
1638 // across versions.
1639 RecordBrowserStartupTime();
1640 startup_timer_->SignalStartupComplete(
1641 performance_monitor::StartupTimer::STARTUP_NORMAL);
1643 DCHECK_EQ(base::MessageLoop::TYPE_UI, base::MessageLoop::current()->type());
1644 #if !defined(USE_AURA) && defined(TOOLKIT_VIEWS)
1645 views::AcceleratorHandler accelerator_handler;
1646 base::RunLoop run_loop(&accelerator_handler);
1647 #else
1648 base::RunLoop run_loop;
1649 #endif
1651 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1653 MetricsService::SetExecutionPhase(MetricsService::MAIN_MESSAGE_LOOP_RUN);
1654 run_loop.Run();
1656 return true;
1657 #endif
1660 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1661 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1662 #if defined(OS_ANDROID)
1663 // Chrome on Android does not use default MessageLoop. It has its own
1664 // Android specific MessageLoop
1665 NOTREACHED();
1666 #else
1668 // Start watching for jank during shutdown. It gets disarmed when
1669 // |shutdown_watcher_| object is destructed.
1670 MetricsService::SetExecutionPhase(MetricsService::SHUTDOWN_TIMEBOMB_ARM);
1671 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1673 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1674 startup_watcher_->Disarm();
1676 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1677 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1679 // Some tests don't set parameters.ui_task, so they started translate
1680 // language fetch that was never completed so we need to cleanup here
1681 // otherwise it will be done by the destructor in a wrong thread.
1682 if (parameters().ui_task == NULL && translate_manager_ != NULL)
1683 translate_manager_->CleanupPendingUlrFetcher();
1685 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1686 process_singleton_->Cleanup();
1688 // Stop all tasks that might run on WatchDogThread.
1689 ThreadWatcherList::StopWatchingAll();
1691 browser_process_->metrics_service()->Stop();
1693 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1694 browser_process_->StartTearDown();
1695 #endif
1698 void ChromeBrowserMainParts::PostDestroyThreads() {
1699 #if defined(OS_ANDROID)
1700 // On Android, there is no quit/exit. So the browser's main message loop will
1701 // not finish.
1702 NOTREACHED();
1703 #else
1704 browser_process_->PostDestroyThreads();
1705 // browser_shutdown takes care of deleting browser_process, so we need to
1706 // release it.
1707 ignore_result(browser_process_.release());
1708 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1709 master_prefs_.reset();
1710 process_singleton_.reset();
1712 // We need to do this check as late as possible, but due to modularity, this
1713 // may be the last point in Chrome. This would be more effective if done at
1714 // a higher level on the stack, so that it is impossible for an early return
1715 // to bypass this code. Perhaps we need a *final* hook that is called on all
1716 // paths from content/browser/browser_main.
1717 CHECK(MetricsService::UmaMetricsProperlyShutdown());
1719 #if defined(OS_CHROMEOS)
1720 chromeos::CrosSettings::Shutdown();
1721 #endif
1722 #endif
1725 // Public members:
1727 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1728 chrome_extra_parts_.push_back(parts);