Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob5e3d4ef4a03d488e7d00295f6fd821e787cfb0e1
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/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram_macros.h"
20 #include "base/path_service.h"
21 #include "base/prefs/json_pref_store.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/prefs/pref_value_store.h"
25 #include "base/prefs/scoped_user_pref_update.h"
26 #include "base/process/process_info.h"
27 #include "base/profiler/scoped_tracker.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/trace_event/trace_event.h"
38 #include "base/values.h"
39 #include "build/build_config.h"
40 #include "cc/base/switches.h"
41 #include "chrome/browser/about_flags.h"
42 #include "chrome/browser/browser_process.h"
43 #include "chrome/browser/browser_process_impl.h"
44 #include "chrome/browser/browser_process_platform_part.h"
45 #include "chrome/browser/browser_shutdown.h"
46 #include "chrome/browser/chrome_browser_main_extra_parts.h"
47 #include "chrome/browser/component_updater/cld_component_installer.h"
48 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
49 #include "chrome/browser/component_updater/flash_component_installer.h"
50 #include "chrome/browser/component_updater/recovery_component_installer.h"
51 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
52 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
53 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
54 #include "chrome/browser/defaults.h"
55 #include "chrome/browser/first_run/first_run.h"
56 #include "chrome/browser/first_run/upgrade_util.h"
57 #include "chrome/browser/google/google_search_counter.h"
58 #include "chrome/browser/gpu/gl_string_manager.h"
59 #include "chrome/browser/gpu/three_d_api_observer.h"
60 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
61 #include "chrome/browser/metrics/field_trial_synchronizer.h"
62 #include "chrome/browser/metrics/metrics_services_manager.h"
63 #include "chrome/browser/metrics/thread_watcher.h"
64 #include "chrome/browser/metrics/variations/variations_service.h"
65 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
66 #include "chrome/browser/net/chrome_net_log.h"
67 #include "chrome/browser/net/crl_set_fetcher.h"
68 #include "chrome/browser/notifications/desktop_notification_service.h"
69 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
70 #include "chrome/browser/performance_monitor/performance_monitor.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/chrome_version_info.h"
99 #include "chrome/common/crash_keys.h"
100 #include "chrome/common/env_vars.h"
101 #include "chrome/common/logging_chrome.h"
102 #include "chrome/common/net/net_resource_provider.h"
103 #include "chrome/common/pref_names.h"
104 #include "chrome/common/profiling.h"
105 #include "chrome/grit/generated_resources.h"
106 #include "chrome/installer/util/google_update_settings.h"
107 #include "components/component_updater/component_updater_service.h"
108 #include "components/device_event_log/device_event_log.h"
109 #include "components/google/core/browser/google_util.h"
110 #include "components/language_usage_metrics/language_usage_metrics.h"
111 #include "components/metrics/metrics_service.h"
112 #include "components/metrics/profiler/tracking_synchronizer.h"
113 #include "components/nacl/browser/nacl_browser.h"
114 #include "components/rappor/rappor_service.h"
115 #include "components/signin/core/common/profile_management_switches.h"
116 #include "components/startup_metric_utils/startup_metric_utils.h"
117 #include "components/translate/content/browser/browser_cld_utils.h"
118 #include "components/translate/content/common/cld_data_source.h"
119 #include "components/translate/core/browser/translate_download_manager.h"
120 #include "components/variations/net/variations_http_header_provider.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/power_usage_monitor.h"
127 #include "content/public/browser/site_instance.h"
128 #include "content/public/common/content_client.h"
129 #include "content/public/common/content_switches.h"
130 #include "content/public/common/main_function_params.h"
131 #include "grit/platform_locale_settings.h"
132 #include "net/base/net_module.h"
133 #include "net/cookies/cookie_monster.h"
134 #include "net/http/http_network_layer.h"
135 #include "net/http/http_stream_factory.h"
136 #include "net/url_request/url_request.h"
137 #include "ui/base/l10n/l10n_util.h"
138 #include "ui/base/layout.h"
139 #include "ui/base/resource/resource_bundle.h"
140 #include "ui/strings/grit/app_locale_settings.h"
142 #if defined(OS_ANDROID)
143 #include "chrome/browser/metrics/thread_watcher_android.h"
144 #else
145 #include "chrome/browser/feedback/feedback_profile_observer.h"
146 #endif // defined(OS_ANDROID)
148 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
149 #include "chrome/browser/first_run/upgrade_util_linux.h"
150 #include "chrome/browser/sxs_linux.h"
151 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
153 #if defined(OS_CHROMEOS)
154 #include "chrome/browser/chromeos/settings/cros_settings.h"
155 #include "chromeos/chromeos_switches.h"
156 #include "chromeos/settings/cros_settings_names.h"
157 #endif // defined(OS_CHROMEOS)
159 // TODO(port): several win-only methods have been pulled out of this, but
160 // BrowserMain() as a whole needs to be broken apart so that it's usable by
161 // other platforms. For now, it's just a stub. This is a serious work in
162 // progress and should not be taken as an indication of a real refactoring.
164 #if defined(OS_WIN)
165 #include "base/environment.h" // For PreRead experiment.
166 #include "base/win/windows_version.h"
167 #include "chrome/browser/browser_util_win.h"
168 #include "chrome/browser/chrome_browser_main_win.h"
169 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
170 #include "chrome/browser/component_updater/caps_installer_win.h"
171 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
172 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
173 #include "chrome/browser/first_run/upgrade_util_win.h"
174 #include "chrome/browser/ui/network_profile_bubble.h"
175 #include "chrome/installer/util/helper.h"
176 #include "chrome/installer/util/install_util.h"
177 #include "chrome/installer/util/shell_util.h"
178 #include "components/browser_watcher/exit_funnel_win.h"
179 #include "net/base/net_util.h"
180 #include "ui/base/l10n/l10n_util_win.h"
181 #include "ui/gfx/win/dpi.h"
182 #include "ui/shell_dialogs/select_file_dialog.h"
183 #endif // defined(OS_WIN)
185 #if defined(OS_MACOSX)
186 #include <Security/Security.h>
188 #include "base/mac/scoped_nsautorelease_pool.h"
189 #include "chrome/browser/mac/keystone_glue.h"
190 #endif // defined(OS_MACOSX)
192 #if !defined(OS_IOS)
193 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
194 #endif // !defined(OS_IOS)
196 #if !defined(DISABLE_NACL)
197 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
198 #include "components/nacl/browser/nacl_process_host.h"
199 #endif // !defined(DISABLE_NACL)
201 #if defined(ENABLE_EXTENSIONS)
202 #include "chrome/browser/extensions/startup_helper.h"
203 #include "extensions/browser/extension_protocols.h"
204 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
205 #endif // defined(ENABLE_EXTENSIONS)
207 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
208 #include "printing/printed_document.h"
209 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
211 #if defined(ENABLE_RLZ)
212 #include "chrome/browser/rlz/rlz.h"
213 #endif // defined(ENABLE_RLZ)
215 #if defined(ENABLE_WEBRTC)
216 #include "chrome/browser/media/webrtc_log_util.h"
217 #endif // defined(ENABLE_WEBRTC)
219 #if defined(USE_AURA)
220 #include "ui/aura/env.h"
221 #endif // defined(USE_AURA)
223 using content::BrowserThread;
225 namespace {
227 // This function provides some ways to test crash and assertion handling
228 // behavior of the program.
229 void HandleTestParameters(const base::CommandLine& command_line) {
230 // This parameter causes a null pointer crash (crash reporter trigger).
231 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
232 int* bad_pointer = NULL;
233 *bad_pointer = 0;
237 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
238 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
239 const std::vector<GURL>& new_tabs) {
240 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
241 it != new_tabs.end(); ++it) {
242 if (it->is_valid())
243 browser_creator->AddFirstRunTab(*it);
246 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
248 // Returns the new local state object, guaranteed non-NULL.
249 // |local_state_task_runner| must be a shutdown-blocking task runner.
250 PrefService* InitializeLocalState(
251 base::SequencedTaskRunner* local_state_task_runner,
252 const base::CommandLine& parsed_command_line) {
253 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
255 // Load local state. This includes the application locale so we know which
256 // locale dll to load. This also causes local state prefs to be registered.
257 PrefService* local_state = g_browser_process->local_state();
258 DCHECK(local_state);
260 #if defined(OS_WIN)
261 if (first_run::IsChromeFirstRun()) {
262 // During first run we read the google_update registry key to find what
263 // language the user selected when downloading the installer. This
264 // becomes our default language in the prefs.
265 // Other platforms obey the system locale.
266 base::string16 install_lang;
267 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
268 local_state->SetString(prefs::kApplicationLocale,
269 base::UTF16ToASCII(install_lang));
272 #endif // defined(OS_WIN)
274 // If the local state file for the current profile doesn't exist and the
275 // parent profile command line flag is present, then we should inherit some
276 // local state from the parent profile.
277 // Checking that the local state file for the current profile doesn't exist
278 // is the most robust way to determine whether we need to inherit or not
279 // since the parent profile command line flag can be present even when the
280 // current profile is not a new one, and in that case we do not want to
281 // inherit and reset the user's setting.
283 // TODO(mnissler): We should probably just instantiate a
284 // JSONPrefStore here instead of an entire PrefService. Once this is
285 // addressed, the call to browser_prefs::RegisterLocalState can move
286 // to chrome_prefs::CreateLocalState.
287 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
288 base::FilePath local_state_path;
289 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
290 bool local_state_file_exists = base::PathExists(local_state_path);
291 if (!local_state_file_exists) {
292 base::FilePath parent_profile =
293 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
294 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
295 scoped_ptr<PrefService> parent_local_state(
296 chrome_prefs::CreateLocalState(
297 parent_profile,
298 local_state_task_runner,
299 g_browser_process->policy_service(),
300 registry,
301 false));
302 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
303 // Right now, we only inherit the locale setting from the parent profile.
304 local_state->SetString(
305 prefs::kApplicationLocale,
306 parent_local_state->GetString(prefs::kApplicationLocale));
310 #if defined(OS_CHROMEOS)
311 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
312 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
313 // Ensure that we start with owner's locale.
314 if (!owner_locale.empty() &&
315 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
316 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
317 local_state->SetString(prefs::kApplicationLocale, owner_locale);
320 #endif // defined(OS_CHROMEOS)
322 return local_state;
325 // Initializes the primary profile, possibly doing some user prompting to pick
326 // a fallback profile. Returns the newly created profile, or NULL if startup
327 // should not continue.
328 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
329 const base::FilePath& user_data_dir,
330 const base::CommandLine& parsed_command_line) {
331 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
332 base::Time start = base::Time::Now();
333 if (profiles::IsMultipleProfilesEnabled() &&
334 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
335 g_browser_process->local_state()->SetString(prefs::kProfileLastUsed,
336 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
337 // Clear kProfilesLastActive since the user only wants to launch a specific
338 // profile.
339 ListPrefUpdate update(g_browser_process->local_state(),
340 prefs::kProfilesLastActive);
341 base::ListValue* profile_list = update.Get();
342 profile_list->Clear();
345 Profile* profile = NULL;
346 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
347 // On ChromeOS and Android the ProfileManager will use the same path as the
348 // one we got passed. GetActiveUserProfile will therefore use the correct path
349 // automatically.
350 DCHECK_EQ(user_data_dir.value(),
351 g_browser_process->profile_manager()->user_data_dir().value());
352 profile = ProfileManager::GetActiveUserProfile();
353 #else
354 base::FilePath profile_path =
355 GetStartupProfilePath(user_data_dir, parsed_command_line);
357 // Without NewAvatarMenu, replace guest with any existing profile.
358 if (!switches::IsNewAvatarMenu() &&
359 profile_path == ProfileManager::GetGuestProfilePath()) {
360 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
361 GetPathOfProfileAtIndex(0);
363 profile = g_browser_process->profile_manager()->GetProfile(
364 profile_path);
366 // If we're using the --new-profile-management flag and this profile is
367 // signed out, then we should show the user manager instead. By switching
368 // the active profile to the guest profile we ensure that no
369 // browser windows will be opened for the guest profile.
370 if (switches::IsNewProfileManagement() &&
371 profile &&
372 !profile->IsGuestSession()) {
373 ProfileInfoCache& cache =
374 g_browser_process->profile_manager()->GetProfileInfoCache();
375 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
377 if (profile_index != std::string::npos &&
378 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
379 profile = g_browser_process->profile_manager()->GetProfile(
380 ProfileManager::GetGuestProfilePath());
383 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
384 if (profile) {
385 UMA_HISTOGRAM_LONG_TIMES(
386 "Startup.CreateFirstProfile", base::Time::Now() - start);
387 return profile;
390 #if !defined(OS_WIN)
391 // TODO(port): fix this. See comments near the definition of
392 // user_data_dir. It is better to CHECK-fail here than it is to
393 // silently exit because of missing code in the above test.
394 CHECK(profile) << "Cannot get default profile.";
395 #endif // !defined(OS_WIN)
397 return NULL;
400 #if defined(OS_MACOSX)
401 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
402 SecKeychainCallbackInfo* info, void* context) {
403 return noErr;
405 #endif // defined(OS_MACOSX)
407 void RegisterComponentsForUpdate() {
408 component_updater::ComponentUpdateService* cus =
409 g_browser_process->component_updater();
411 // Registration can be before or after cus->Start() so it is ok to post
412 // a task to the UI thread to do registration once you done the necessary
413 // file IO to know you existing component version.
414 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
415 RegisterRecoveryComponent(cus, g_browser_process->local_state());
416 RegisterPepperFlashComponent(cus);
417 RegisterSwiftShaderComponent(cus);
418 RegisterWidevineCdmComponent(cus);
419 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
421 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
422 #if defined(OS_CHROMEOS)
423 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
424 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
425 // installer when running on Linux. See crbug.com/422121 for more details.
426 if (!base::SysInfo::IsRunningOnChromeOS())
427 #endif // defined(OS_CHROMEOS)
428 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
429 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
431 // Registration of the CLD Component is a no-op unless the CLD data source has
432 // been configured to be the "Component" data source.
433 RegisterCldComponent(cus);
435 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
436 g_browser_process->supervised_user_whitelist_installer();
437 whitelist_installer->RegisterComponents();
439 base::FilePath path;
440 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
441 #if defined(OS_ANDROID)
442 // The CRLSet component was enabled for some releases. This code attempts to
443 // delete it from the local disk of those how may have downloaded it.
444 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
445 #elif !defined(OS_CHROMEOS)
446 // CRLSetFetcher attempts to load a CRL set from either the local disk or
447 // network.
448 // For Chrome OS this registration is delayed until user login.
449 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
450 // Registration of the EV Whitelist component here is not necessary for:
451 // 1. Android: Because it currently does not have the EV indicator.
452 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
453 RegisterEVWhitelistComponent(cus, path);
454 #endif // defined(OS_ANDROID)
457 #if defined(OS_WIN)
458 RegisterSwReporterComponent(cus, g_browser_process->local_state());
459 RegisterCAPSComponent(cus);
460 #endif // defined(OS_WIN)
462 cus->Start();
465 #if !defined(OS_ANDROID)
466 bool ProcessSingletonNotificationCallback(
467 const base::CommandLine& command_line,
468 const base::FilePath& current_directory) {
469 // Drop the request if the browser process is already in shutdown path.
470 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
471 #if defined(OS_WIN)
472 browser_watcher::ExitFunnel::RecordSingleEvent(
473 chrome::kBrowserExitCodesRegistryPath,
474 L"ProcessSingletonIsShuttingDown");
475 #endif // defined(OS_WIN)
477 return false;
480 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
481 std::string start_time_string =
482 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
483 int64 remote_start_time;
484 if (base::StringToInt64(start_time_string, &remote_start_time)) {
485 base::TimeDelta elapsed =
486 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
487 if (command_line.HasSwitch(switches::kFastStart)) {
488 UMA_HISTOGRAM_LONG_TIMES(
489 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
490 } else {
491 UMA_HISTOGRAM_LONG_TIMES(
492 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
497 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
498 command_line);
500 base::FilePath user_data_dir =
501 g_browser_process->profile_manager()->user_data_dir();
502 base::FilePath startup_profile_dir =
503 GetStartupProfilePath(user_data_dir, command_line);
505 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
506 command_line, current_directory, startup_profile_dir);
507 return true;
509 #endif // !defined(OS_ANDROID)
511 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
512 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
513 std::string port_str =
514 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
515 int port;
516 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
517 g_browser_process->CreateDevToolsHttpProtocolHandler(
518 chrome::HOST_DESKTOP_TYPE_NATIVE,
519 "127.0.0.1",
520 static_cast<uint16>(port));
521 } else {
522 DLOG(WARNING) << "Invalid http debugger port number " << port;
527 // Heap allocated class that listens for first page load, kicks off stat
528 // recording and then deletes itself.
529 class LoadCompleteListener : public content::NotificationObserver {
530 public:
531 LoadCompleteListener() {
532 registrar_.Add(this,
533 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
534 content::NotificationService::AllSources());
536 ~LoadCompleteListener() override {}
538 // content::NotificationObserver implementation.
539 void Observe(int type,
540 const content::NotificationSource& source,
541 const content::NotificationDetails& details) override {
542 DCHECK_EQ(content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, type);
543 startup_metric_utils::OnInitialPageLoadComplete();
544 delete this;
547 private:
548 content::NotificationRegistrar registrar_;
549 DISALLOW_COPY_AND_ASSIGN(LoadCompleteListener);
552 } // namespace
554 namespace chrome_browser {
556 // This error message is not localized because we failed to load the
557 // localization data files.
558 #if defined(OS_WIN)
559 const char kMissingLocaleDataTitle[] = "Missing File Error";
560 #endif // defined(OS_WIN)
562 #if defined(OS_WIN)
563 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
564 const char kMissingLocaleDataMessage[] =
565 "Unable to find locale data files. Please reinstall.";
566 #endif // defined(OS_WIN)
568 } // namespace chrome_browser
570 // BrowserMainParts ------------------------------------------------------------
572 ChromeBrowserMainParts::ChromeBrowserMainParts(
573 const content::MainFunctionParams& parameters)
574 : parameters_(parameters),
575 parsed_command_line_(parameters.command_line),
576 result_code_(content::RESULT_CODE_NORMAL_EXIT),
577 startup_watcher_(new StartupTimeBomb()),
578 shutdown_watcher_(new ShutdownWatcherHelper()),
579 browser_field_trials_(parameters.command_line),
580 sampling_profiler_(base::PlatformThread::CurrentId(),
581 GetStartupSamplingParams()),
582 profile_(NULL),
583 run_message_loop_(true),
584 notify_result_(ProcessSingleton::PROCESS_NONE),
585 local_state_(NULL),
586 restart_last_session_(false) {
587 sampling_profiler_.Start();
588 // If we're running tests (ui_task is non-null).
589 if (parameters.ui_task)
590 browser_defaults::enable_help_app = false;
592 // Chrome disallows cookies by default. All code paths that want to use
593 // cookies need to go through one of Chrome's URLRequestContexts which have
594 // a ChromeNetworkDelegate attached that selectively allows cookies again.
595 net::URLRequest::SetDefaultCookiePolicyToBlock();
598 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
599 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
600 delete chrome_extra_parts_[i];
601 chrome_extra_parts_.clear();
604 // This will be called after the command-line has been mutated by about:flags
605 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
606 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
607 // Must initialize metrics after labs have been converted into switches,
608 // but before field trials are set up (so that client ID is available for
609 // one-time randomized field trials).
611 // Initialize FieldTrialList to support FieldTrials that use one-time
612 // randomization.
613 metrics::MetricsService* metrics = browser_process_->metrics_service();
614 field_trial_list_.reset(
615 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
617 const base::CommandLine* command_line =
618 base::CommandLine::ForCurrentProcess();
619 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
620 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
621 base::FieldTrial::EnableBenchmarking();
624 // Ensure any field trials specified on the command line are initialized.
625 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
626 std::set<std::string> unforceable_field_trials;
627 #if defined(OFFICIAL_BUILD)
628 unforceable_field_trials.insert("SettingsEnforcement");
629 #endif // defined(OFFICIAL_BUILD)
631 // Create field trials without activating them, so that this behaves in a
632 // consistent manner with field trials created from the server.
633 bool result = base::FieldTrialList::CreateTrialsFromString(
634 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
635 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
636 unforceable_field_trials);
637 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
638 << " list specified.";
640 if (command_line->HasSwitch(switches::kForceVariationIds)) {
641 // Create default variation ids which will always be included in the
642 // X-Client-Data request header.
643 variations::VariationsHttpHeaderProvider* provider =
644 variations::VariationsHttpHeaderProvider::GetInstance();
645 bool result = provider->SetDefaultVariationIds(
646 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
647 CHECK(result) << "Invalid --" << switches::kForceVariationIds
648 << " list specified.";
649 metrics->AddSyntheticTrialObserver(provider);
651 chrome_variations::VariationsService* variations_service =
652 browser_process_->variations_service();
653 if (variations_service)
654 variations_service->CreateTrialsFromSeed();
656 // This must be called after |local_state_| is initialized.
657 browser_field_trials_.SetupFieldTrials();
659 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
660 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
661 // Even though base::Bind does AddRef and Release, the object will not be
662 // deleted after the Task is executed.
663 field_trial_synchronizer_ = new FieldTrialSynchronizer();
665 // Now that field trials have been created, initializes metrics recording.
666 metrics->InitializeMetricsRecordingState();
668 // Enable profiler instrumentation depending on the channel.
669 switch (chrome::VersionInfo::GetChannel()) {
670 case chrome::VersionInfo::CHANNEL_UNKNOWN:
671 case chrome::VersionInfo::CHANNEL_CANARY:
672 tracked_objects::ScopedTracker::Enable();
673 break;
675 case chrome::VersionInfo::CHANNEL_DEV:
676 case chrome::VersionInfo::CHANNEL_BETA:
677 case chrome::VersionInfo::CHANNEL_STABLE:
678 // Don't enable instrumentation.
679 break;
683 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
685 void ChromeBrowserMainParts::StartMetricsRecording() {
686 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
688 g_browser_process->metrics_service()->CheckForClonedInstall(
689 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
691 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
694 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
695 // Don't record any metrics if UI was displayed before this point e.g.
696 // warning dialogs.
697 if (startup_metric_utils::WasNonBrowserUIDisplayed())
698 return;
700 #if defined(OS_ANDROID)
701 // On Android the first run is handled in Java code, and the C++ side of
702 // Chrome doesn't know if this is the first run. This will cause some
703 // inaccuracy in the UMA statistics, but this should be minor (first runs are
704 // rare).
705 bool is_first_run = false;
706 #else
707 bool is_first_run = first_run::IsChromeFirstRun();
708 #endif // defined(OS_ANDROID)
710 // CurrentProcessInfo::CreationTime() is currently only implemented on some
711 // platforms.
712 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
713 const base::Time process_creation_time =
714 base::CurrentProcessInfo::CreationTime();
716 if (!is_first_run && !process_creation_time.is_null()) {
717 base::TimeDelta delay = base::Time::Now() - process_creation_time;
718 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
720 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
722 // Record collected startup metrics.
723 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
725 // Deletes self.
726 new LoadCompleteListener();
729 // static
730 base::StackSamplingProfiler::SamplingParams
731 ChromeBrowserMainParts::GetStartupSamplingParams() {
732 // Sample at 10Hz for 30 seconds.
733 base::StackSamplingProfiler::SamplingParams params;
734 params.initial_delay = base::TimeDelta::FromMilliseconds(0);
735 params.bursts = 1;
736 params.samples_per_burst = 300;
737 params.sampling_interval = base::TimeDelta::FromMilliseconds(100);
738 params.preserve_sample_ordering = false;
739 return params;
742 // -----------------------------------------------------------------------------
743 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
745 #if defined(OS_WIN)
746 #define DLLEXPORT __declspec(dllexport)
748 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
749 extern "C" {
750 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
753 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
754 // Need an instance of AtExitManager to handle singleton creations and
755 // deletions. We need this new instance because, the old instance created
756 // in ChromeMain() got destructed when the function returned.
757 base::AtExitManager exit_manager;
758 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
760 #endif
762 // content::BrowserMainParts implementation ------------------------------------
764 void ChromeBrowserMainParts::PreEarlyInitialization() {
765 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
766 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
767 chrome_extra_parts_[i]->PreEarlyInitialization();
770 void ChromeBrowserMainParts::PostEarlyInitialization() {
771 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
772 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
773 chrome_extra_parts_[i]->PostEarlyInitialization();
776 void ChromeBrowserMainParts::ToolkitInitialized() {
777 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
778 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
779 chrome_extra_parts_[i]->ToolkitInitialized();
782 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
783 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
785 device_event_log::Initialize(0 /* default max entries */);
787 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
788 chrome_extra_parts_[i]->PreMainMessageLoopStart();
791 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
792 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
793 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
794 chrome_extra_parts_[i]->PostMainMessageLoopStart();
797 int ChromeBrowserMainParts::PreCreateThreads() {
798 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
799 result_code_ = PreCreateThreadsImpl();
801 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
802 #if !defined(OS_ANDROID)
803 // These members must be initialized before exiting this function normally.
804 DCHECK(master_prefs_.get());
805 DCHECK(browser_creator_.get());
806 #endif // !defined(OS_ANDROID)
807 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
808 chrome_extra_parts_[i]->PreCreateThreads();
811 return result_code_;
814 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
815 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
816 run_message_loop_ = false;
817 #if !defined(OS_ANDROID)
818 chrome::MaybeShowInvalidUserDataDirWarningDialog();
819 #endif // !defined(OS_ANDROID)
820 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
821 return chrome::RESULT_CODE_MISSING_DATA;
823 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
824 MediaCaptureDevicesDispatcher::GetInstance();
826 // Android's first run is done in Java instead of native.
827 #if !defined(OS_ANDROID)
828 process_singleton_.reset(new ChromeProcessSingleton(
829 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
831 // Cache first run state early.
832 first_run::IsChromeFirstRun();
833 #endif // !defined(OS_ANDROID)
835 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
836 JsonPrefStore::GetTaskRunnerForFile(
837 base::FilePath(chrome::kLocalStorePoolName),
838 BrowserThread::GetBlockingPool());
841 TRACE_EVENT0("startup",
842 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
843 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
844 parsed_command_line()));
847 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
848 TRACE_EVENT0("startup",
849 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
850 // User wants to override default tracking status.
851 std::string flag =
852 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
853 // Default to basic profiling (no parent child support).
854 tracked_objects::ThreadData::Status status =
855 tracked_objects::ThreadData::PROFILING_ACTIVE;
856 if (flag.compare("0") != 0)
857 status = tracked_objects::ThreadData::DEACTIVATED;
858 else if (flag.compare("child") != 0)
859 status = tracked_objects::ThreadData::PROFILING_CHILDREN_ACTIVE;
860 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
863 local_state_ = InitializeLocalState(
864 local_state_task_runner.get(), parsed_command_line());
866 #if !defined(OS_ANDROID)
867 // These members must be initialized before returning from this function.
868 master_prefs_.reset(new first_run::MasterPrefs);
869 // Android doesn't use StartupBrowserCreator.
870 browser_creator_.reset(new StartupBrowserCreator);
871 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
872 chrome::UMABrowsingActivityObserver::Init();
873 #endif // !defined(OS_ANDROID)
875 #if !defined(OS_CHROMEOS)
876 // Convert active labs into switches. This needs to be done before
877 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
878 // affected by experiment flags (--touch-optimized-ui in particular).
879 // On ChromeOS system level flags are applied from the device settings from
880 // the session manager.
882 TRACE_EVENT0("startup",
883 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
884 about_flags::PrefServiceFlagsStorage flags_storage_(
885 g_browser_process->local_state());
886 about_flags::ConvertFlagsToSwitches(&flags_storage_,
887 base::CommandLine::ForCurrentProcess(),
888 about_flags::kAddSentinels);
890 #endif // !defined(OS_CHROMEOS)
892 local_state_->UpdateCommandLinePrefStore(
893 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
895 // Reset the command line in the crash report details, since we may have
896 // just changed it to include experiments.
897 crash_keys::SetSwitchesFromCommandLine(
898 base::CommandLine::ForCurrentProcess());
900 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
901 // needed when loading the MainMenu.nib and the language doesn't depend on
902 // anything since it comes from Cocoa.
903 #if defined(OS_MACOSX)
904 std::string locale =
905 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
906 browser_process_->SetApplicationLocale(locale);
907 #else
908 const std::string locale =
909 local_state_->GetString(prefs::kApplicationLocale);
911 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
912 // method InitSharedInstance is ignored.
914 TRACE_EVENT_BEGIN0("startup",
915 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
916 const std::string loaded_locale =
917 ui::ResourceBundle::InitSharedInstanceWithLocale(
918 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
919 TRACE_EVENT_END0("startup",
920 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
922 if (loaded_locale.empty() &&
923 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
924 ShowMissingLocaleMessageBox();
925 return chrome::RESULT_CODE_MISSING_DATA;
927 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
928 browser_process_->SetApplicationLocale(loaded_locale);
930 base::FilePath resources_pack_path;
931 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
933 TRACE_EVENT0("startup",
934 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
935 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
936 resources_pack_path, ui::SCALE_FACTOR_NONE);
938 #endif // defined(OS_MACOSX)
940 // Android does first run in Java instead of native.
941 // Chrome OS has its own out-of-box-experience code.
942 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
943 // On first run, we need to process the predictor preferences before the
944 // browser's profile_manager object is created, but after ResourceBundle
945 // is initialized.
946 if (first_run::IsChromeFirstRun()) {
947 first_run::ProcessMasterPreferencesResult pmp_result =
948 first_run::ProcessMasterPreferences(user_data_dir_,
949 master_prefs_.get());
950 if (pmp_result == first_run::EULA_EXIT_NOW)
951 return chrome::RESULT_CODE_EULA_REFUSED;
953 if (!parsed_command_line().HasSwitch(switches::kApp) &&
954 !parsed_command_line().HasSwitch(switches::kAppId) &&
955 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
956 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
959 // TODO(macourteau): refactor preferences that are copied from
960 // master_preferences into local_state, as a "local_state" section in
961 // master preferences. If possible, a generic solution would be preferred
962 // over a copy one-by-one of specific preferences. Also see related TODO
963 // in first_run.h.
965 // Store the initial VariationsService seed in local state, if it exists
966 // in master prefs.
967 if (!master_prefs_->variations_seed.empty() ||
968 !master_prefs_->compressed_variations_seed.empty()) {
969 if (!master_prefs_->variations_seed.empty()) {
970 local_state_->SetString(prefs::kVariationsSeed,
971 master_prefs_->variations_seed);
973 if (!master_prefs_->compressed_variations_seed.empty()) {
974 local_state_->SetString(prefs::kVariationsCompressedSeed,
975 master_prefs_->compressed_variations_seed);
977 if (!master_prefs_->variations_seed_signature.empty()) {
978 local_state_->SetString(prefs::kVariationsSeedSignature,
979 master_prefs_->variations_seed_signature);
981 // Set the variation seed date to the current system time. If the user's
982 // clock is incorrect, this may cause some field trial expiry checks to
983 // not do the right thing until the next seed update from the server,
984 // when this value will be updated.
985 local_state_->SetInt64(prefs::kVariationsSeedDate,
986 base::Time::Now().ToInternalValue());
989 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
990 local_state_->SetString(
991 prefs::kBrowserSuppressDefaultBrowserPrompt,
992 master_prefs_->suppress_default_browser_prompt_for_version);
995 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
997 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
998 // Set the product channel for crash reports.
999 base::debug::SetCrashKeyValue(crash_keys::kChannel,
1000 chrome::VersionInfo::GetVersionStringModifier());
1001 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1003 // Initialize tracking synchronizer system.
1004 tracking_synchronizer_ =
1005 new metrics::TrackingSynchronizer(base::TimeTicks::Now());
1007 #if defined(OS_MACOSX)
1008 // Get the Keychain API to register for distributed notifications on the main
1009 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1010 // which doesn't. This ensures those notifications will get delivered
1011 // properly. See issue 37766.
1012 // (Note that the callback mask here is empty. I don't want to register for
1013 // any callbacks, I just want to initialize the mechanism.)
1014 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1015 #endif // defined(OS_MACOSX)
1017 #if defined(OS_CHROMEOS)
1018 // Must be done after g_browser_process is constructed, before
1019 // SetupMetricsAndFieldTrials().
1020 chromeos::CrosSettings::Initialize();
1021 #endif // defined(OS_CHROMEOS)
1023 // Now the command line has been mutated based on about:flags, we can setup
1024 // metrics and initialize field trials. The field trials are needed by
1025 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1026 SetupMetricsAndFieldTrials();
1028 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1029 browser_process_->PreCreateThreads();
1031 return content::RESULT_CODE_NORMAL_EXIT;
1034 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1035 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1036 result_code_ = PreMainMessageLoopRunImpl();
1038 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1039 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1042 // PreMainMessageLoopRun calls these extra stages in the following order:
1043 // PreMainMessageLoopRunImpl()
1044 // ... initial setup, including browser_process_ setup.
1045 // PreProfileInit()
1046 // ... additional setup, including CreateProfile()
1047 // PostProfileInit()
1048 // ... additional setup
1049 // PreBrowserStart()
1050 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1051 // PostBrowserStart()
1053 void ChromeBrowserMainParts::PreProfileInit() {
1054 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1056 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1057 chrome_extra_parts_[i]->PreProfileInit();
1059 #if !defined(OS_ANDROID)
1060 // Initialize the feedback uploader so it can setup notifications for profile
1061 // creation.
1062 feedback::FeedbackProfileObserver::Initialize();
1064 ProfileManager* profile_manager = g_browser_process->profile_manager();
1066 // First check if any ephemeral profiles are left behind because of browser
1067 // crash and schedule them for deletion and then proceed with getting the set
1068 // of profiles to open.
1069 ProfileInfoCache& profile_cache = profile_manager->GetProfileInfoCache();
1070 size_t profiles_count = profile_cache.GetNumberOfProfiles();
1071 std::vector<base::FilePath> profiles_to_delete;
1072 for (size_t i = 0; i < profiles_count; ++i) {
1073 if (profile_cache.ProfileIsEphemeralAtIndex(i))
1074 profiles_to_delete.push_back(profile_cache.GetPathOfProfileAtIndex(i));
1077 if (profiles_to_delete.size()) {
1078 for (size_t i = 0; i < profiles_to_delete.size(); ++i) {
1079 profile_manager->ScheduleProfileForDeletion(
1080 profiles_to_delete[i], ProfileManager::CreateCallback());
1082 // Clean up stale profiles immediately after browser start.
1083 BrowserThread::PostTask(
1084 BrowserThread::FILE, FROM_HERE,
1085 base::Bind(&ProfileManager::CleanUpStaleProfiles, profiles_to_delete));
1087 #endif // !defined(OS_ANDROID)
1089 #if defined(ENABLE_EXTENSIONS)
1090 javascript_dialog_extensions_client::InstallClient();
1091 #endif // defined(ENABLE_EXTENSIONS)
1093 #if !defined(OS_IOS)
1094 InstallChromeJavaScriptNativeDialogFactory();
1095 #endif // !defined(OS_IOS)
1098 void ChromeBrowserMainParts::PostProfileInit() {
1099 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1100 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1101 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1102 chrome_extra_parts_[i]->PostProfileInit();
1105 void ChromeBrowserMainParts::PreBrowserStart() {
1106 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1107 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1108 chrome_extra_parts_[i]->PreBrowserStart();
1110 three_d_observer_.reset(new ThreeDAPIObserver());
1113 void ChromeBrowserMainParts::PostBrowserStart() {
1114 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1115 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1116 chrome_extra_parts_[i]->PostBrowserStart();
1117 #if !defined(OS_ANDROID)
1118 // Allow ProcessSingleton to process messages.
1119 process_singleton_->Unlock();
1120 #endif // !defined(OS_ANDROID)
1121 #if defined(ENABLE_WEBRTC)
1122 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1123 // to reduce the impact on startup time.
1124 BrowserThread::PostDelayedTask(
1125 BrowserThread::UI,
1126 FROM_HERE,
1127 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1128 base::TimeDelta::FromMinutes(1));
1129 #endif // defined(ENABLE_WEBRTC)
1132 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1133 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1134 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1135 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1136 // Android updates the metrics service dynamically depending on whether the
1137 // application is in the foreground or not. Do not start here.
1138 #if !defined(OS_ANDROID)
1139 // Now that the file thread has been started, start recording.
1140 StartMetricsRecording();
1141 #endif // !defined(OS_ANDROID)
1143 if (!base::debug::BeingDebugged()) {
1144 // Create watchdog thread after creating all other threads because it will
1145 // watch the other threads and they must be running.
1146 browser_process_->watchdog_thread();
1149 // Do any initializating in the browser process that requires all threads
1150 // running.
1151 browser_process_->PreMainMessageLoopRun();
1153 // Record last shutdown time into a histogram.
1154 browser_shutdown::ReadLastShutdownInfo();
1156 #if defined(OS_WIN)
1157 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1158 // tasks. Those care whether the browser is already running. On Linux/Mac,
1159 // upgrade/uninstall happen separately.
1160 bool already_running = browser_util::IsBrowserAlreadyRunning();
1162 // If the command line specifies 'uninstall' then we need to work here
1163 // unless we detect another chrome browser running.
1164 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1165 return DoUninstallTasks(already_running);
1168 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1169 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1170 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1171 parsed_command_line_);
1174 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1175 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1176 #endif // defined(OS_WIN)
1178 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1179 return ShellIntegration::SetAsDefaultBrowser() ?
1180 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1181 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1184 #if defined(USE_AURA)
1185 // Make sure aura::Env has been initialized.
1186 CHECK(aura::Env::GetInstance());
1187 #endif // defined(USE_AURA)
1189 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1190 #if !defined(OS_ANDROID)
1191 // If the command line specifies --pack-extension, attempt the pack extension
1192 // startup action and exit.
1193 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1194 extensions::StartupHelper extension_startup_helper;
1195 if (extension_startup_helper.PackExtension(parsed_command_line()))
1196 return content::RESULT_CODE_NORMAL_EXIT;
1197 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1200 // If we're being launched just to check the connector policy, we are
1201 // short-lived and don't want to be passing that switch off.
1202 bool pass_command_line = !parsed_command_line().HasSwitch(
1203 switches::kCheckCloudPrintConnectorPolicy);
1205 if (pass_command_line) {
1206 // When another process is running, use that process instead of starting a
1207 // new one. NotifyOtherProcess will currently give the other process up to
1208 // 20 seconds to respond. Note that this needs to be done before we attempt
1209 // to read the profile.
1210 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1211 switch (notify_result_) {
1212 case ProcessSingleton::PROCESS_NONE:
1213 // No process already running, fall through to starting a new one.
1214 break;
1216 case ProcessSingleton::PROCESS_NOTIFIED:
1217 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1218 // On POSIX systems, print a message notifying the process is running.
1219 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1220 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1221 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1223 // Having a differentiated return type for testing allows for tests to
1224 // verify proper handling of some switches. When not testing, stick to
1225 // the standard Unix convention of returning zero when things went as
1226 // expected.
1227 if (parsed_command_line().HasSwitch(switches::kTestType))
1228 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1229 return content::RESULT_CODE_NORMAL_EXIT;
1231 case ProcessSingleton::PROFILE_IN_USE:
1232 return chrome::RESULT_CODE_PROFILE_IN_USE;
1234 case ProcessSingleton::LOCK_ERROR:
1235 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1236 "directory. This means that running multiple instances "
1237 "would start multiple browser processes rather than "
1238 "opening a new window in the existing process. Aborting "
1239 "now to avoid profile corruption.";
1240 return chrome::RESULT_CODE_PROFILE_IN_USE;
1242 default:
1243 NOTREACHED();
1246 #endif // !defined(OS_ANDROID)
1248 // Handle special early return paths (which couldn't be processed even earlier
1249 // as they require the process singleton to be held) first.
1251 std::string try_chrome =
1252 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1253 if (!try_chrome.empty()) {
1254 #if defined(OS_WIN)
1255 // Setup.exe has determined that we need to run a retention experiment
1256 // and has lauched chrome to show the experiment UI. It is guaranteed that
1257 // no other Chrome is currently running as the process singleton was
1258 // sucessfully grabbed above.
1259 int try_chrome_int;
1260 base::StringToInt(try_chrome, &try_chrome_int);
1261 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1262 try_chrome_int,
1263 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1264 base::Unretained(process_singleton_.get())));
1265 if (answer == TryChromeDialogView::NOT_NOW)
1266 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1267 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1268 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1269 // At this point the user is willing to try chrome again.
1270 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1271 // Only set in the unattended case, the interactive case is Windows 8.
1272 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1273 ShellIntegration::SET_DEFAULT_UNATTENDED)
1274 ShellIntegration::SetAsDefaultBrowser();
1276 #else
1277 // We don't support retention experiments on Mac or Linux.
1278 return content::RESULT_CODE_NORMAL_EXIT;
1279 #endif // defined(OS_WIN)
1282 #if defined(OS_WIN)
1283 // Do the tasks if chrome has been upgraded while it was last running.
1284 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1285 return content::RESULT_CODE_NORMAL_EXIT;
1287 // Check if there is any machine level Chrome installed on the current
1288 // machine. If yes and the current Chrome process is user level, we do not
1289 // allow the user level Chrome to run. So we notify the user and uninstall
1290 // user level Chrome.
1291 // Note this check needs to happen here (after the process singleton was
1292 // obtained but before potentially creating the first run sentinel).
1293 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1294 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1295 #endif // defined(OS_WIN)
1297 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1298 if (sxs_linux::ShouldMigrateUserDataDir())
1299 return sxs_linux::MigrateUserDataDir();
1300 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1302 // Desktop construction occurs here, (required before profile creation).
1303 PreProfileInit();
1305 // Profile creation ----------------------------------------------------------
1307 metrics::MetricsService::SetExecutionPhase(
1308 metrics::MetricsService::CREATE_PROFILE,
1309 g_browser_process->local_state());
1311 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1312 base::TimeTicks::Now() - start_time_step1);
1314 // This step is costly and is already measured in Startup.CreateFirstProfile
1315 // and more directly Profile.CreateAndInitializeProfile.
1316 profile_ = CreatePrimaryProfile(parameters(),
1317 user_data_dir_,
1318 parsed_command_line());
1319 if (!profile_)
1320 return content::RESULT_CODE_NORMAL_EXIT;
1322 #if !defined(OS_ANDROID)
1323 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1324 // The first run sentinel must be created after the process singleton was
1325 // grabbed and no early return paths were otherwise hit above.
1326 first_run::CreateSentinelIfNeeded();
1327 #endif // !defined(OS_ANDROID)
1329 #if defined(ENABLE_BACKGROUND)
1330 // Autoload any profiles which are running background apps.
1331 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1332 browser_process_->profile_manager()->AutoloadProfiles();
1333 #endif // defined(ENABLE_BACKGROUND)
1334 // Post-profile init ---------------------------------------------------------
1336 TranslateService::Initialize();
1338 // Needs to be done before PostProfileInit, since login manager on CrOS is
1339 // called inside PostProfileInit.
1340 content::WebUIControllerFactory::RegisterFactory(
1341 ChromeWebUIControllerFactory::GetInstance());
1343 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1344 // So make sure to create it before that.
1345 #if !defined(DISABLE_NACL)
1346 NaClBrowserDelegateImpl* delegate =
1347 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1348 nacl::NaClBrowser::SetDelegate(delegate);
1349 #endif // !defined(DISABLE_NACL)
1351 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1352 // (requires supporting early exit).
1353 PostProfileInit();
1355 // Retrieve cached GL strings from local state and use them for GPU
1356 // blacklist decisions.
1357 if (g_browser_process->gl_string_manager())
1358 g_browser_process->gl_string_manager()->Initialize();
1360 // Create an instance of GpuModeManager to watch gpu mode pref change.
1361 g_browser_process->gpu_mode_manager();
1363 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1364 // Show the First Run UI if this is the first time Chrome has been run on
1365 // this computer, or we're being compelled to do so by a command line flag.
1366 // Note that this be done _after_ the PrefService is initialized and all
1367 // preferences are registered, since some of the code that the importer
1368 // touches reads preferences.
1369 if (first_run::IsChromeFirstRun()) {
1370 first_run::AutoImport(profile_,
1371 master_prefs_->homepage_defined,
1372 master_prefs_->do_import_items,
1373 master_prefs_->dont_import_items,
1374 master_prefs_->import_bookmarks_path);
1376 // Note: this can pop the first run consent dialog on linux.
1377 first_run::DoPostImportTasks(profile_,
1378 master_prefs_->make_chrome_default_for_user);
1380 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1381 browser_creator_->set_show_main_browser_window(
1382 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1383 } else {
1384 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1387 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1389 #if defined(OS_WIN)
1390 // Sets things up so that if we crash from this point on, a dialog will
1391 // popup asking the user to restart chrome. It is done this late to avoid
1392 // testing against a bunch of special cases that are taken care early on.
1393 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1394 parsed_command_line());
1396 // Registers Chrome with the Windows Restart Manager, which will restore the
1397 // Chrome session when the computer is restarted after a system update.
1398 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1399 // but should run on startup if extended to handle crashes/hangs/patches.
1400 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1401 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1402 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1403 parsed_command_line());
1406 // Verify that the profile is not on a network share and if so prepare to show
1407 // notification to the user.
1408 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1409 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1410 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1411 profile_->GetPath()));
1413 #endif // defined(OS_WIN)
1415 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1416 // Init the RLZ library. This just binds the dll and schedules a task on the
1417 // file thread to be run sometime later. If this is the first run we record
1418 // the installation event.
1419 PrefService* pref_service = profile_->GetPrefs();
1420 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1421 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1422 // Negative ping delay means to send ping immediately after a first search is
1423 // recorded.
1424 RLZTracker::InitRlzFromProfileDelayed(
1425 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1426 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1427 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1429 // Configure modules that need access to resources.
1430 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1432 // In unittest mode, this will do nothing. In normal mode, this will create
1433 // the global IntranetRedirectDetector instance, which will promptly go to
1434 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1435 // to see if it should do anything else.
1437 // A simpler way of doing all this would be to have some function which could
1438 // give the time elapsed since startup, and simply have this object check that
1439 // when asked to initialize itself, but this doesn't seem to exist.
1441 // This can't be created in the BrowserProcessImpl constructor because it
1442 // needs to read prefs that get set after that runs.
1443 browser_process_->intranet_redirect_detector();
1444 GoogleSearchCounter::RegisterForNotifications();
1446 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1447 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1448 base::FilePath path =
1449 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1450 printing::PrintedDocument::set_debug_dump_path(path);
1452 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1454 HandleTestParameters(parsed_command_line());
1455 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1456 base::debug::BeingDebugged());
1458 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1459 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1460 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1461 browser_process_->GetApplicationLocale());
1463 // Start watching for hangs during startup. We disarm this hang detector when
1464 // ThreadWatcher takes over or when browser is shutdown or when
1465 // startup_watcher_ is deleted.
1466 metrics::MetricsService::SetExecutionPhase(
1467 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1468 g_browser_process->local_state());
1469 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1471 // On mobile, need for clean shutdown arises only when the application comes
1472 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1473 // http://crbug.com/179143
1474 #if !defined(OS_ANDROID)
1475 // Start watching for a hang.
1476 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1477 #endif // !defined(OS_ANDROID)
1479 #if defined(ENABLE_PRINT_PREVIEW)
1480 // Create the instance of the cloud print proxy service so that it can launch
1481 // the service process if needed. This is needed because the service process
1482 // might have shutdown because an update was available.
1483 // TODO(torne): this should maybe be done with
1484 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1485 // instead?
1486 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1487 #endif // defined(ENABLE_PRINT_PREVIEW)
1489 // Start watching all browser threads for responsiveness.
1490 metrics::MetricsService::SetExecutionPhase(
1491 metrics::MetricsService::THREAD_WATCHER_START,
1492 g_browser_process->local_state());
1493 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1495 #if defined(OS_ANDROID)
1496 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1497 #endif // defined(OS_ANDROID)
1499 #if !defined(DISABLE_NACL)
1500 BrowserThread::PostTask(
1501 BrowserThread::IO,
1502 FROM_HERE,
1503 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1504 #endif // !defined(DISABLE_NACL)
1506 // Make sure initial prefs are recorded
1507 PrefMetricsService::Factory::GetForProfile(profile_);
1509 PreBrowserStart();
1511 // Instantiate the notification UI manager, as this triggers a perf timer
1512 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1513 // triggering the timer and call that explicitly in the approprate place.
1514 // http://crbug.com/105065.
1515 browser_process_->notification_ui_manager();
1517 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1518 // data source is based on the Component Updater.
1519 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1521 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1522 RegisterComponentsForUpdate();
1524 #if defined(OS_ANDROID)
1525 chrome_variations::VariationsService* variations_service =
1526 browser_process_->variations_service();
1527 if (variations_service) {
1528 // Just initialize the policy prefs service here. Variations seed fetching
1529 // will be initialized when the app enters foreground mode.
1530 variations_service->set_policy_pref_service(profile_->GetPrefs());
1532 translate::TranslateDownloadManager::RequestLanguageList(
1533 profile_->GetPrefs());
1535 #else
1536 // Most general initialization is behind us, but opening a
1537 // tab and/or session restore and such is still to be done.
1538 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1540 // We are in regular browser boot sequence. Open initial tabs and enter the
1541 // main message loop.
1542 #if defined(OS_CHROMEOS)
1543 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1544 // them this early as the cryptohome hasn't yet been mounted (which happens
1545 // only once we log in.
1546 std::vector<Profile*> last_opened_profiles;
1547 #else
1548 std::vector<Profile*> last_opened_profiles =
1549 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1550 #endif // defined(OS_CHROMEOS)
1552 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1553 base::TimeTicks::Now() - start_time_step2);
1555 // This step is costly and is already measured in
1556 // Startup.StartupBrowserCreator_Start.
1557 bool started = browser_creator_->Start(
1558 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1559 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1560 if (started) {
1561 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1562 // Initialize autoupdate timer. Timer callback costs basically nothing
1563 // when browser is not in persistent mode, so it's OK to let it ride on
1564 // the main thread. This needs to be done here because we don't want
1565 // to start the timer when Chrome is run inside a test harness.
1566 browser_process_->StartAutoupdateTimer();
1567 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1569 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1570 // On Linux, the running exe will be updated if an upgrade becomes
1571 // available while the browser is running. We need to save the last
1572 // modified time of the exe, so we can compare to determine if there is
1573 // an upgrade while the browser is kept alive by a persistent extension.
1574 upgrade_util::SaveLastModifiedTimeOfExe();
1575 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1577 // Record now as the last successful chrome start.
1578 GoogleUpdateSettings::SetLastRunTime();
1580 #if defined(OS_MACOSX)
1581 // Call Recycle() here as late as possible, before going into the loop
1582 // because Start() will add things to it while creating the main window.
1583 if (parameters().autorelease_pool)
1584 parameters().autorelease_pool->Recycle();
1585 #endif // defined(OS_MACOSX)
1587 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1588 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1590 // If we're running tests (ui_task is non-null), then we don't want to
1591 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1592 // RequestLanguageList
1593 if (parameters().ui_task == NULL) {
1594 // Request new variations seed information from server.
1595 chrome_variations::VariationsService* variations_service =
1596 browser_process_->variations_service();
1597 if (variations_service) {
1598 variations_service->StartRepeatedVariationsSeedFetch();
1600 #if defined(OS_WIN)
1601 variations_service->StartGoogleUpdateRegistrySync();
1602 #endif // defined(OS_WIN)
1605 translate::TranslateDownloadManager::RequestLanguageList(
1606 profile_->GetPrefs());
1609 run_message_loop_ = true;
1610 } else {
1611 run_message_loop_ = false;
1613 browser_creator_.reset();
1615 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1616 if (g_browser_process->metrics_service()->reporting_active())
1617 content::StartPowerUsageMonitor();
1618 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1620 process_power_collector_.reset(new ProcessPowerCollector);
1621 process_power_collector_->Initialize();
1622 #endif // !defined(OS_ANDROID)
1624 PostBrowserStart();
1626 if (parameters().ui_task) {
1627 parameters().ui_task->Run();
1628 delete parameters().ui_task;
1629 run_message_loop_ = false;
1631 #if defined(OS_ANDROID)
1632 // We never run the C++ main loop on Android, since the UI thread message
1633 // loop is controlled by the OS, so this is as close as we can get to
1634 // the start of the main loop.
1635 if (result_code_ <= 0) {
1636 RecordBrowserStartupTime();
1638 #endif // defined(OS_ANDROID)
1640 #if !defined(OS_ANDROID)
1641 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1642 base::TimeTicks::Now() - start_time_step3);
1643 #endif // !defined(OS_ANDROID)
1645 return result_code_;
1648 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1649 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1650 #if defined(OS_ANDROID)
1651 // Chrome on Android does not use default MessageLoop. It has its own
1652 // Android specific MessageLoop
1653 NOTREACHED();
1654 return true;
1655 #else
1656 // Set the result code set in PreMainMessageLoopRun or set above.
1657 *result_code = result_code_;
1658 if (!run_message_loop_)
1659 return true; // Don't run the default message loop.
1661 // These should be invoked as close to the start of the browser's
1662 // UI thread message loop as possible to get a stable measurement
1663 // across versions.
1664 RecordBrowserStartupTime();
1666 DCHECK(base::MessageLoopForUI::IsCurrent());
1667 base::RunLoop run_loop;
1669 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1671 metrics::MetricsService::SetExecutionPhase(
1672 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1673 g_browser_process->local_state());
1674 run_loop.Run();
1676 return true;
1677 #endif // defined(OS_ANDROID)
1680 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1681 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1682 #if defined(OS_ANDROID)
1683 // Chrome on Android does not use default MessageLoop. It has its own
1684 // Android specific MessageLoop
1685 NOTREACHED();
1686 #else
1688 // Start watching for jank during shutdown. It gets disarmed when
1689 // |shutdown_watcher_| object is destructed.
1690 metrics::MetricsService::SetExecutionPhase(
1691 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1692 g_browser_process->local_state());
1693 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1695 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1696 startup_watcher_->Disarm();
1698 // Remove observers attached to D-Bus clients before DbusThreadManager is
1699 // shut down.
1700 process_power_collector_.reset();
1702 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1703 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1705 // Some tests don't set parameters.ui_task, so they started translate
1706 // language fetch that was never completed so we need to cleanup here
1707 // otherwise it will be done by the destructor in a wrong thread.
1708 TranslateService::Shutdown(parameters().ui_task == NULL);
1710 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1711 process_singleton_->Cleanup();
1713 // Stop all tasks that might run on WatchDogThread.
1714 ThreadWatcherList::StopWatchingAll();
1716 browser_process_->metrics_service()->Stop();
1718 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1719 browser_process_->StartTearDown();
1720 #endif // defined(OS_ANDROID)
1723 void ChromeBrowserMainParts::PostDestroyThreads() {
1724 #if defined(OS_ANDROID)
1725 // On Android, there is no quit/exit. So the browser's main message loop will
1726 // not finish.
1727 NOTREACHED();
1728 #else
1729 browser_process_->PostDestroyThreads();
1730 // browser_shutdown takes care of deleting browser_process, so we need to
1731 // release it.
1732 ignore_result(browser_process_.release());
1733 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1734 master_prefs_.reset();
1735 process_singleton_.reset();
1736 device_event_log::Shutdown();
1738 // We need to do this check as late as possible, but due to modularity, this
1739 // may be the last point in Chrome. This would be more effective if done at
1740 // a higher level on the stack, so that it is impossible for an early return
1741 // to bypass this code. Perhaps we need a *final* hook that is called on all
1742 // paths from content/browser/browser_main.
1743 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1745 #if defined(OS_CHROMEOS)
1746 chromeos::CrosSettings::Shutdown();
1747 #endif // defined(OS_CHROMEOS)
1748 #endif // defined(OS_ANDROID)
1751 // Public members:
1753 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1754 chrome_extra_parts_.push_back(parts);