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