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