Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob89733288609659f236749b4ac5df8f9f6604c5d3
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/profiler/scoped_profile.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/default_tick_clock.h"
37 #include "base/time/time.h"
38 #include "base/trace_event/trace_event.h"
39 #include "base/values.h"
40 #include "build/build_config.h"
41 #include "cc/base/switches.h"
42 #include "chrome/browser/about_flags.h"
43 #include "chrome/browser/after_startup_task_utils.h"
44 #include "chrome/browser/browser_process.h"
45 #include "chrome/browser/browser_process_impl.h"
46 #include "chrome/browser/browser_process_platform_part.h"
47 #include "chrome/browser/browser_shutdown.h"
48 #include "chrome/browser/chrome_browser_main_extra_parts.h"
49 #include "chrome/browser/component_updater/cld_component_installer.h"
50 #include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
51 #include "chrome/browser/component_updater/flash_component_installer.h"
52 #include "chrome/browser/component_updater/recovery_component_installer.h"
53 #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
54 #include "chrome/browser/component_updater/swiftshader_component_installer.h"
55 #include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
56 #include "chrome/browser/defaults.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/gpu/gl_string_manager.h"
61 #include "chrome/browser/gpu/three_d_api_observer.h"
62 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
63 #include "chrome/browser/memory/oom_priority_manager.h"
64 #include "chrome/browser/metrics/field_trial_synchronizer.h"
65 #include "chrome/browser/metrics/metrics_services_manager.h"
66 #include "chrome/browser/metrics/thread_watcher.h"
67 #include "chrome/browser/metrics/variations/variations_service.h"
68 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
69 #include "chrome/browser/net/chrome_net_log.h"
70 #include "chrome/browser/net/crl_set_fetcher.h"
71 #include "chrome/browser/performance_monitor/performance_monitor.h"
72 #include "chrome/browser/plugins/plugin_prefs.h"
73 #include "chrome/browser/power/process_power_collector.h"
74 #include "chrome/browser/pref_service_flags_storage.h"
75 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
76 #include "chrome/browser/prefs/command_line_pref_store.h"
77 #include "chrome/browser/prefs/incognito_mode_prefs.h"
78 #include "chrome/browser/prefs/pref_metrics_service.h"
79 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
80 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
81 #include "chrome/browser/process_singleton.h"
82 #include "chrome/browser/profiles/profile.h"
83 #include "chrome/browser/profiles/profile_manager.h"
84 #include "chrome/browser/profiles/profiles_state.h"
85 #include "chrome/browser/shell_integration.h"
86 #include "chrome/browser/tracing/navigation_tracing.h"
87 #include "chrome/browser/translate/translate_service.h"
88 #include "chrome/browser/ui/app_list/app_list_service.h"
89 #include "chrome/browser/ui/browser.h"
90 #include "chrome/browser/ui/browser_finder.h"
91 #include "chrome/browser/ui/host_desktop.h"
92 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
93 #include "chrome/browser/ui/startup/default_browser_prompt.h"
94 #include "chrome/browser/ui/startup/startup_browser_creator.h"
95 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
96 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
97 #include "chrome/common/channel_info.h"
98 #include "chrome/common/chrome_constants.h"
99 #include "chrome/common/chrome_paths.h"
100 #include "chrome/common/chrome_result_codes.h"
101 #include "chrome/common/chrome_switches.h"
102 #include "chrome/common/crash_keys.h"
103 #include "chrome/common/env_vars.h"
104 #include "chrome/common/logging_chrome.h"
105 #include "chrome/common/net/net_resource_provider.h"
106 #include "chrome/common/pref_names.h"
107 #include "chrome/common/profiling.h"
108 #include "chrome/common/variations/variations_util.h"
109 #include "chrome/grit/generated_resources.h"
110 #include "chrome/installer/util/google_update_settings.h"
111 #include "components/component_updater/component_updater_service.h"
112 #include "components/device_event_log/device_event_log.h"
113 #include "components/google/core/browser/google_util.h"
114 #include "components/language_usage_metrics/language_usage_metrics.h"
115 #include "components/metrics/call_stack_profile_metrics_provider.h"
116 #include "components/metrics/metrics_service.h"
117 #include "components/metrics/profiler/tracking_synchronizer.h"
118 #include "components/nacl/browser/nacl_browser.h"
119 #include "components/rappor/rappor_service.h"
120 #include "components/signin/core/common/profile_management_switches.h"
121 #include "components/startup_metric_utils/startup_metric_utils.h"
122 #include "components/tracing/tracing_switches.h"
123 #include "components/translate/content/browser/browser_cld_utils.h"
124 #include "components/translate/content/common/cld_data_source.h"
125 #include "components/translate/core/browser/translate_download_manager.h"
126 #include "components/variations/net/variations_http_header_provider.h"
127 #include "components/variations/pref_names.h"
128 #include "components/variations/variations_associated_data.h"
129 #include "components/version_info/version_info.h"
130 #include "content/public/browser/browser_thread.h"
131 #include "content/public/browser/notification_observer.h"
132 #include "content/public/browser/notification_registrar.h"
133 #include "content/public/browser/notification_service.h"
134 #include "content/public/browser/notification_types.h"
135 #include "content/public/browser/power_usage_monitor.h"
136 #include "content/public/browser/site_instance.h"
137 #include "content/public/common/content_client.h"
138 #include "content/public/common/content_switches.h"
139 #include "content/public/common/main_function_params.h"
140 #include "grit/platform_locale_settings.h"
141 #include "media/audio/audio_manager.h"
142 #include "net/base/net_module.h"
143 #include "net/cookies/cookie_monster.h"
144 #include "net/http/http_network_layer.h"
145 #include "net/http/http_stream_factory.h"
146 #include "net/url_request/url_request.h"
147 #include "ui/base/l10n/l10n_util.h"
148 #include "ui/base/layout.h"
149 #include "ui/base/resource/resource_bundle.h"
150 #include "ui/strings/grit/app_locale_settings.h"
152 #if defined(OS_ANDROID)
153 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
154 #include "chrome/browser/metrics/thread_watcher_android.h"
155 #include "ui/base/resource/resource_bundle_android.h"
156 #else
157 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
158 #include "chrome/browser/feedback/feedback_profile_observer.h"
159 #endif // defined(OS_ANDROID)
161 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
162 #include "chrome/browser/first_run/upgrade_util_linux.h"
163 #include "chrome/browser/sxs_linux.h"
164 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
166 #if defined(OS_CHROMEOS)
167 #include "chrome/browser/chromeos/settings/cros_settings.h"
168 #include "chromeos/chromeos_switches.h"
169 #include "chromeos/settings/cros_settings_names.h"
170 #endif // defined(OS_CHROMEOS)
172 // TODO(port): several win-only methods have been pulled out of this, but
173 // BrowserMain() as a whole needs to be broken apart so that it's usable by
174 // other platforms. For now, it's just a stub. This is a serious work in
175 // progress and should not be taken as an indication of a real refactoring.
177 #if defined(OS_WIN)
178 #include "base/environment.h" // For PreRead experiment.
179 #include "base/win/windows_version.h"
180 #include "chrome/browser/browser_util_win.h"
181 #include "chrome/browser/chrome_browser_main_win.h"
182 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
183 #include "chrome/browser/component_updater/caps_installer_win.h"
184 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
185 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
186 #include "chrome/browser/first_run/upgrade_util_win.h"
187 #include "chrome/browser/ui/network_profile_bubble.h"
188 #include "chrome/installer/util/helper.h"
189 #include "chrome/installer/util/install_util.h"
190 #include "chrome/installer/util/shell_util.h"
191 #include "components/browser_watcher/exit_funnel_win.h"
192 #include "net/base/net_util.h"
193 #include "ui/base/l10n/l10n_util_win.h"
194 #include "ui/gfx/win/dpi.h"
195 #include "ui/shell_dialogs/select_file_dialog.h"
196 #endif // defined(OS_WIN)
198 #if defined(OS_MACOSX)
199 #include <Security/Security.h>
201 #include "base/mac/scoped_nsautorelease_pool.h"
202 #include "chrome/browser/mac/keystone_glue.h"
203 #endif // defined(OS_MACOSX)
205 #if !defined(OS_IOS)
206 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
207 #endif // !defined(OS_IOS)
209 #if !defined(DISABLE_NACL)
210 #include "chrome/browser/component_updater/pnacl_component_installer.h"
211 #include "components/nacl/browser/nacl_process_host.h"
212 #endif // !defined(DISABLE_NACL)
214 #if defined(ENABLE_EXTENSIONS)
215 #include "chrome/browser/extensions/startup_helper.h"
216 #include "extensions/browser/extension_protocols.h"
217 #include "extensions/common/features/feature_provider.h"
218 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
219 #endif // defined(ENABLE_EXTENSIONS)
221 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
222 #include "printing/printed_document.h"
223 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
225 #if defined(ENABLE_RLZ)
226 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
227 #include "components/rlz/rlz_tracker.h"
228 #endif // defined(ENABLE_RLZ)
230 #if defined(ENABLE_WEBRTC)
231 #include "chrome/browser/media/webrtc_log_util.h"
232 #endif // defined(ENABLE_WEBRTC)
234 #if defined(USE_AURA)
235 #include "ui/aura/env.h"
236 #endif // defined(USE_AURA)
238 using content::BrowserThread;
240 namespace {
242 // This function provides some ways to test crash and assertion handling
243 // behavior of the program.
244 void HandleTestParameters(const base::CommandLine& command_line) {
245 // This parameter causes a null pointer crash (crash reporter trigger).
246 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
247 int* bad_pointer = NULL;
248 *bad_pointer = 0;
252 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
253 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
254 const std::vector<GURL>& new_tabs) {
255 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
256 it != new_tabs.end(); ++it) {
257 if (it->is_valid())
258 browser_creator->AddFirstRunTab(*it);
261 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
263 // Returns the new local state object, guaranteed non-NULL.
264 // |local_state_task_runner| must be a shutdown-blocking task runner.
265 PrefService* InitializeLocalState(
266 base::SequencedTaskRunner* local_state_task_runner,
267 const base::CommandLine& parsed_command_line) {
268 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
270 // Load local state. This includes the application locale so we know which
271 // locale dll to load. This also causes local state prefs to be registered.
272 PrefService* local_state = g_browser_process->local_state();
273 DCHECK(local_state);
275 #if defined(OS_WIN)
276 if (first_run::IsChromeFirstRun()) {
277 // During first run we read the google_update registry key to find what
278 // language the user selected when downloading the installer. This
279 // becomes our default language in the prefs.
280 // Other platforms obey the system locale.
281 base::string16 install_lang;
282 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
283 local_state->SetString(prefs::kApplicationLocale,
284 base::UTF16ToASCII(install_lang));
287 #endif // defined(OS_WIN)
289 // If the local state file for the current profile doesn't exist and the
290 // parent profile command line flag is present, then we should inherit some
291 // local state from the parent profile.
292 // Checking that the local state file for the current profile doesn't exist
293 // is the most robust way to determine whether we need to inherit or not
294 // since the parent profile command line flag can be present even when the
295 // current profile is not a new one, and in that case we do not want to
296 // inherit and reset the user's setting.
298 // TODO(mnissler): We should probably just instantiate a
299 // JSONPrefStore here instead of an entire PrefService. Once this is
300 // addressed, the call to browser_prefs::RegisterLocalState can move
301 // to chrome_prefs::CreateLocalState.
302 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
303 base::FilePath local_state_path;
304 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
305 bool local_state_file_exists = base::PathExists(local_state_path);
306 if (!local_state_file_exists) {
307 base::FilePath parent_profile =
308 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
309 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
310 scoped_ptr<PrefService> parent_local_state(
311 chrome_prefs::CreateLocalState(
312 parent_profile,
313 local_state_task_runner,
314 g_browser_process->policy_service(),
315 registry,
316 false));
317 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
318 // Right now, we only inherit the locale setting from the parent profile.
319 local_state->SetString(
320 prefs::kApplicationLocale,
321 parent_local_state->GetString(prefs::kApplicationLocale));
325 #if defined(OS_CHROMEOS)
326 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
327 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
328 // Ensure that we start with owner's locale.
329 if (!owner_locale.empty() &&
330 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
331 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
332 local_state->SetString(prefs::kApplicationLocale, owner_locale);
335 #endif // defined(OS_CHROMEOS)
337 return local_state;
340 // Initializes the primary profile, possibly doing some user prompting to pick
341 // a fallback profile. Returns the newly created profile, or NULL if startup
342 // should not continue.
343 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
344 const base::FilePath& user_data_dir,
345 const base::CommandLine& parsed_command_line) {
346 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
347 TRACK_SCOPED_REGION(
348 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
350 base::Time start = base::Time::Now();
351 if (profiles::IsMultipleProfilesEnabled() &&
352 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
353 profiles::SetLastUsedProfile(
354 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
355 // Clear kProfilesLastActive since the user only wants to launch a specific
356 // profile.
357 ListPrefUpdate update(g_browser_process->local_state(),
358 prefs::kProfilesLastActive);
359 base::ListValue* profile_list = update.Get();
360 profile_list->Clear();
363 Profile* profile = NULL;
364 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
365 // On ChromeOS and Android the ProfileManager will use the same path as the
366 // one we got passed. GetActiveUserProfile will therefore use the correct path
367 // automatically.
368 DCHECK_EQ(user_data_dir.value(),
369 g_browser_process->profile_manager()->user_data_dir().value());
370 profile = ProfileManager::GetActiveUserProfile();
371 #else
372 base::FilePath profile_path =
373 GetStartupProfilePath(user_data_dir, parsed_command_line);
375 // Without NewAvatarMenu, replace guest with any existing profile.
376 if (!switches::IsNewAvatarMenu() &&
377 profile_path == ProfileManager::GetGuestProfilePath()) {
378 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
379 GetPathOfProfileAtIndex(0);
381 profile = g_browser_process->profile_manager()->GetProfile(
382 profile_path);
384 // If we're using the --new-profile-management flag and this profile is
385 // signed out, then we should show the user manager instead. By switching
386 // the active profile to the guest profile we ensure that no
387 // browser windows will be opened for the guest profile.
388 if (switches::IsNewProfileManagement() &&
389 profile &&
390 !profile->IsGuestSession()) {
391 ProfileInfoCache& cache =
392 g_browser_process->profile_manager()->GetProfileInfoCache();
393 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
395 if (profile_index != std::string::npos &&
396 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
397 profile = g_browser_process->profile_manager()->GetProfile(
398 ProfileManager::GetGuestProfilePath());
401 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
402 if (profile) {
403 UMA_HISTOGRAM_LONG_TIMES(
404 "Startup.CreateFirstProfile", base::Time::Now() - start);
405 return profile;
408 #if !defined(OS_WIN)
409 // TODO(port): fix this. See comments near the definition of
410 // user_data_dir. It is better to CHECK-fail here than it is to
411 // silently exit because of missing code in the above test.
412 CHECK(profile) << "Cannot get default profile.";
413 #endif // !defined(OS_WIN)
415 return NULL;
418 #if defined(OS_MACOSX)
419 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
420 SecKeychainCallbackInfo* info, void* context) {
421 return noErr;
423 #endif // defined(OS_MACOSX)
425 void RegisterComponentsForUpdate() {
426 component_updater::ComponentUpdateService* cus =
427 g_browser_process->component_updater();
429 // Registration can be before or after cus->Start() so it is ok to post
430 // a task to the UI thread to do registration once you done the necessary
431 // file IO to know you existing component version.
432 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
433 RegisterRecoveryComponent(cus, g_browser_process->local_state());
434 RegisterPepperFlashComponent(cus);
435 RegisterSwiftShaderComponent(cus);
436 RegisterWidevineCdmComponent(cus);
437 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
439 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
440 #if defined(OS_CHROMEOS)
441 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
442 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
443 // installer when running on Linux. See crbug.com/422121 for more details.
444 if (!base::SysInfo::IsRunningOnChromeOS())
445 #endif // defined(OS_CHROMEOS)
446 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
447 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
449 // Registration of the CLD Component is a no-op unless the CLD data source has
450 // been configured to be the "Component" data source.
451 RegisterCldComponent(cus);
453 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
454 g_browser_process->supervised_user_whitelist_installer();
455 whitelist_installer->RegisterComponents();
457 base::FilePath path;
458 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
459 #if defined(OS_ANDROID)
460 // The CRLSet component was enabled for some releases. This code attempts to
461 // delete it from the local disk of those how may have downloaded it.
462 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
463 #elif !defined(OS_CHROMEOS)
464 // CRLSetFetcher attempts to load a CRL set from either the local disk or
465 // network.
466 // For Chrome OS this registration is delayed until user login.
467 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
468 // Registration of the EV Whitelist component here is not necessary for:
469 // 1. Android: Because it currently does not have the EV indicator.
470 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
471 RegisterEVWhitelistComponent(cus, path);
472 #endif // defined(OS_ANDROID)
475 #if defined(OS_WIN)
476 #if defined(GOOGLE_CHROME_BUILD)
477 RegisterSwReporterComponent(cus);
478 #endif // defined(GOOGLE_CHROME_BUILD)
479 RegisterCAPSComponent(cus);
480 #endif // defined(OS_WIN)
483 #if !defined(OS_ANDROID)
484 bool ProcessSingletonNotificationCallback(
485 const base::CommandLine& command_line,
486 const base::FilePath& current_directory) {
487 // Drop the request if the browser process is already in shutdown path.
488 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
489 #if defined(OS_WIN)
490 browser_watcher::ExitFunnel::RecordSingleEvent(
491 chrome::kBrowserExitCodesRegistryPath,
492 L"ProcessSingletonIsShuttingDown");
493 #endif // defined(OS_WIN)
495 return false;
498 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
499 std::string start_time_string =
500 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
501 int64 remote_start_time;
502 if (base::StringToInt64(start_time_string, &remote_start_time)) {
503 base::TimeDelta elapsed =
504 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
505 if (command_line.HasSwitch(switches::kFastStart)) {
506 UMA_HISTOGRAM_LONG_TIMES(
507 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
508 } else {
509 UMA_HISTOGRAM_LONG_TIMES(
510 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
515 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
516 command_line);
518 base::FilePath user_data_dir =
519 g_browser_process->profile_manager()->user_data_dir();
520 base::FilePath startup_profile_dir =
521 GetStartupProfilePath(user_data_dir, command_line);
523 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
524 command_line, current_directory, startup_profile_dir);
525 return true;
527 #endif // !defined(OS_ANDROID)
529 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
530 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
531 std::string port_str =
532 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
533 int port;
534 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
535 g_browser_process->CreateDevToolsHttpProtocolHandler(
536 chrome::HOST_DESKTOP_TYPE_NATIVE,
537 "127.0.0.1",
538 static_cast<uint16>(port));
539 } else {
540 DLOG(WARNING) << "Invalid http debugger port number " << port;
545 } // namespace
547 namespace chrome_browser {
549 // This error message is not localized because we failed to load the
550 // localization data files.
551 #if defined(OS_WIN)
552 const char kMissingLocaleDataTitle[] = "Missing File Error";
553 #endif // defined(OS_WIN)
555 #if defined(OS_WIN)
556 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
557 const char kMissingLocaleDataMessage[] =
558 "Unable to find locale data files. Please reinstall.";
559 #endif // defined(OS_WIN)
561 } // namespace chrome_browser
563 // BrowserMainParts ------------------------------------------------------------
565 ChromeBrowserMainParts::ChromeBrowserMainParts(
566 const content::MainFunctionParams& parameters)
567 : parameters_(parameters),
568 parsed_command_line_(parameters.command_line),
569 result_code_(content::RESULT_CODE_NORMAL_EXIT),
570 startup_watcher_(new StartupTimeBomb()),
571 shutdown_watcher_(new ShutdownWatcherHelper()),
572 browser_field_trials_(parameters.command_line),
573 profile_(NULL),
574 run_message_loop_(true),
575 notify_result_(ProcessSingleton::PROCESS_NONE),
576 local_state_(NULL),
577 restart_last_session_(false) {
578 // If we're running tests (ui_task is non-null).
579 if (parameters.ui_task)
580 browser_defaults::enable_help_app = false;
582 // Chrome disallows cookies by default. All code paths that want to use
583 // cookies need to go through one of Chrome's URLRequestContexts which have
584 // a ChromeNetworkDelegate attached that selectively allows cookies again.
585 net::URLRequest::SetDefaultCookiePolicyToBlock();
588 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
589 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
590 delete chrome_extra_parts_[i];
591 chrome_extra_parts_.clear();
594 // This will be called after the command-line has been mutated by about:flags
595 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
596 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
597 // Must initialize metrics after labs have been converted into switches,
598 // but before field trials are set up (so that client ID is available for
599 // one-time randomized field trials).
601 // Initialize FieldTrialList to support FieldTrials that use one-time
602 // randomization.
603 metrics::MetricsService* metrics = browser_process_->metrics_service();
604 field_trial_list_.reset(
605 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
607 const base::CommandLine* command_line =
608 base::CommandLine::ForCurrentProcess();
609 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
610 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
611 base::FieldTrial::EnableBenchmarking();
614 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
615 bool result = chrome_variations::AssociateParamsFromString(
616 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
617 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
618 << " list specified.";
621 // Ensure any field trials specified on the command line are initialized.
622 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
623 std::set<std::string> unforceable_field_trials;
624 #if defined(OFFICIAL_BUILD)
625 unforceable_field_trials.insert("SettingsEnforcement");
626 #endif // defined(OFFICIAL_BUILD)
628 // Create field trials without activating them, so that this behaves in a
629 // consistent manner with field trials created from the server.
630 bool result = base::FieldTrialList::CreateTrialsFromString(
631 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
632 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
633 unforceable_field_trials);
634 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
635 << " list specified.";
638 #if defined(FIELDTRIAL_TESTING_ENABLED)
639 if (!command_line->HasSwitch(switches::kDisableFieldTrialTestingConfig) &&
640 !command_line->HasSwitch(switches::kForceFieldTrials) &&
641 !command_line->HasSwitch(switches::kVariationsServerURL))
642 chrome_variations::AssociateDefaultFieldTrialConfig();
643 #endif // defined(FIELDTRIAL_TESTING_ENABLED)
645 if (command_line->HasSwitch(switches::kForceVariationIds)) {
646 // Create default variation ids which will always be included in the
647 // X-Client-Data request header.
648 variations::VariationsHttpHeaderProvider* provider =
649 variations::VariationsHttpHeaderProvider::GetInstance();
650 bool result = provider->SetDefaultVariationIds(
651 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
652 CHECK(result) << "Invalid --" << switches::kForceVariationIds
653 << " list specified.";
654 metrics->AddSyntheticTrialObserver(provider);
656 chrome_variations::VariationsService* variations_service =
657 browser_process_->variations_service();
658 if (variations_service)
659 variations_service->CreateTrialsFromSeed();
661 // This must be called after |local_state_| is initialized.
662 browser_field_trials_.SetupFieldTrials();
664 // Enable Navigation Tracing only if a trace upload url is specified.
665 if (command_line->HasSwitch(switches::kEnableNavigationTracing) &&
666 command_line->HasSwitch(switches::kTraceUploadURL)) {
667 tracing::SetupNavigationTracing();
670 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
671 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
672 // Even though base::Bind does AddRef and Release, the object will not be
673 // deleted after the Task is executed.
674 field_trial_synchronizer_ = new FieldTrialSynchronizer();
676 // Now that field trials have been created, initializes metrics recording.
677 metrics->InitializeMetricsRecordingState();
679 const version_info::Channel channel = chrome::GetChannel();
681 // TODO(dalecurtis): Remove these checks and enable for all channels once we
682 // track down the root causes of crbug.com/422522 and crbug.com/478932.
683 if (channel == version_info::Channel::UNKNOWN ||
684 channel == version_info::Channel::CANARY ||
685 channel == version_info::Channel::DEV) {
686 media::AudioManager::EnableHangMonitor();
689 // Enable profiler instrumentation depending on the channel.
690 switch (channel) {
691 case version_info::Channel::UNKNOWN:
692 case version_info::Channel::CANARY:
693 tracked_objects::ScopedTracker::Enable();
694 break;
696 case version_info::Channel::DEV:
697 case version_info::Channel::BETA:
698 case version_info::Channel::STABLE:
699 // Don't enable instrumentation.
700 break;
704 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
706 void ChromeBrowserMainParts::StartMetricsRecording() {
707 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
709 g_browser_process->metrics_service()->CheckForClonedInstall(
710 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
712 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
715 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
716 // Don't record any metrics if UI was displayed before this point e.g.
717 // warning dialogs.
718 if (startup_metric_utils::WasNonBrowserUIDisplayed())
719 return;
721 bool is_first_run = false;
722 #if !defined(OS_ANDROID)
723 // On Android, first run is handled in Java code, and the C++ side of Chrome
724 // doesn't know if this is the first run. This will cause some inaccuracy in
725 // the UMA statistics, but this should be minor (first runs are rare).
726 is_first_run = first_run::IsChromeFirstRun();
727 #endif // defined(OS_ANDROID)
729 // Record collected startup metrics.
730 startup_metric_utils::RecordBrowserMainMessageLoopStart(base::Time::Now(),
731 is_first_run);
734 // -----------------------------------------------------------------------------
735 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
737 #if defined(OS_WIN)
738 #define DLLEXPORT __declspec(dllexport)
740 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
741 extern "C" {
742 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
745 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
746 // Need an instance of AtExitManager to handle singleton creations and
747 // deletions. We need this new instance because, the old instance created
748 // in ChromeMain() got destructed when the function returned.
749 base::AtExitManager exit_manager;
750 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
752 #endif
754 // content::BrowserMainParts implementation ------------------------------------
756 void ChromeBrowserMainParts::PreEarlyInitialization() {
757 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
758 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
759 chrome_extra_parts_[i]->PreEarlyInitialization();
762 void ChromeBrowserMainParts::PostEarlyInitialization() {
763 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
764 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
765 chrome_extra_parts_[i]->PostEarlyInitialization();
768 void ChromeBrowserMainParts::ToolkitInitialized() {
769 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
770 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
771 chrome_extra_parts_[i]->ToolkitInitialized();
774 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
775 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
777 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
778 chrome_extra_parts_[i]->PreMainMessageLoopStart();
781 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
782 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
784 // device_event_log must be initialized after the message loop. Calls to
785 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
786 // platforms (e.g. chromeos) may have already initialized this.
787 if (!device_event_log::IsInitialized())
788 device_event_log::Initialize(0 /* default max entries */);
790 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
791 chrome_extra_parts_[i]->PostMainMessageLoopStart();
794 int ChromeBrowserMainParts::PreCreateThreads() {
795 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
796 result_code_ = PreCreateThreadsImpl();
798 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
799 #if !defined(OS_ANDROID)
800 // These members must be initialized before exiting this function normally.
801 DCHECK(master_prefs_.get());
802 DCHECK(browser_creator_.get());
803 #endif // !defined(OS_ANDROID)
804 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
805 chrome_extra_parts_[i]->PreCreateThreads();
808 return result_code_;
811 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
812 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
813 run_message_loop_ = false;
814 #if !defined(OS_ANDROID)
815 chrome::MaybeShowInvalidUserDataDirWarningDialog();
816 #endif // !defined(OS_ANDROID)
817 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
818 return chrome::RESULT_CODE_MISSING_DATA;
820 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
821 MediaCaptureDevicesDispatcher::GetInstance();
823 // Android's first run is done in Java instead of native.
824 #if !defined(OS_ANDROID)
825 process_singleton_.reset(new ChromeProcessSingleton(
826 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
828 // Cache first run state early.
829 first_run::IsChromeFirstRun();
830 #endif // !defined(OS_ANDROID)
832 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
833 JsonPrefStore::GetTaskRunnerForFile(
834 base::FilePath(chrome::kLocalStorePoolName),
835 BrowserThread::GetBlockingPool());
838 TRACE_EVENT0("startup",
839 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
840 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
841 parsed_command_line()));
844 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
845 TRACE_EVENT0("startup",
846 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
847 // User wants to override default tracking status.
848 std::string flag =
849 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
850 // Default to basic profiling (no parent child support).
851 tracked_objects::ThreadData::Status status =
852 tracked_objects::ThreadData::PROFILING_ACTIVE;
853 if (flag.compare("0") != 0)
854 status = tracked_objects::ThreadData::DEACTIVATED;
855 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
858 local_state_ = InitializeLocalState(
859 local_state_task_runner.get(), parsed_command_line());
861 #if !defined(OS_ANDROID)
862 // These members must be initialized before returning from this function.
863 master_prefs_.reset(new first_run::MasterPrefs);
864 // Android doesn't use StartupBrowserCreator.
865 browser_creator_.reset(new StartupBrowserCreator);
866 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
867 chrome::UMABrowsingActivityObserver::Init();
868 #endif // !defined(OS_ANDROID)
870 #if !defined(OS_CHROMEOS)
871 // Convert active labs into switches. This needs to be done before
872 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
873 // affected by experiment flags (--touch-optimized-ui in particular).
874 // On ChromeOS system level flags are applied from the device settings from
875 // the session manager.
877 TRACE_EVENT0("startup",
878 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
879 about_flags::PrefServiceFlagsStorage flags_storage_(
880 g_browser_process->local_state());
881 about_flags::ConvertFlagsToSwitches(&flags_storage_,
882 base::CommandLine::ForCurrentProcess(),
883 about_flags::kAddSentinels);
885 #endif // !defined(OS_CHROMEOS)
887 local_state_->UpdateCommandLinePrefStore(
888 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
890 // Reset the command line in the crash report details, since we may have
891 // just changed it to include experiments.
892 crash_keys::SetSwitchesFromCommandLine(
893 base::CommandLine::ForCurrentProcess());
895 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
896 // needed when loading the MainMenu.nib and the language doesn't depend on
897 // anything since it comes from Cocoa.
898 #if defined(OS_MACOSX)
899 std::string locale =
900 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
901 browser_process_->SetApplicationLocale(locale);
902 #else
903 const std::string locale =
904 local_state_->GetString(prefs::kApplicationLocale);
906 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
907 // method InitSharedInstance is ignored.
909 TRACE_EVENT_BEGIN0("startup",
910 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
911 const std::string loaded_locale =
912 ui::ResourceBundle::InitSharedInstanceWithLocale(
913 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
914 TRACE_EVENT_END0("startup",
915 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
917 if (loaded_locale.empty() &&
918 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
919 ShowMissingLocaleMessageBox();
920 return chrome::RESULT_CODE_MISSING_DATA;
922 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
923 browser_process_->SetApplicationLocale(loaded_locale);
926 TRACE_EVENT0("startup",
927 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
928 base::FilePath resources_pack_path;
929 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
930 #if defined(OS_ANDROID)
931 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path);
932 #else
933 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
934 resources_pack_path, ui::SCALE_FACTOR_NONE);
935 #endif // defined(OS_ANDROID)
937 #endif // defined(OS_MACOSX)
939 // Android does first run in Java instead of native.
940 // Chrome OS has its own out-of-box-experience code.
941 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
942 // On first run, we need to process the predictor preferences before the
943 // browser's profile_manager object is created, but after ResourceBundle
944 // is initialized.
945 if (first_run::IsChromeFirstRun()) {
946 first_run::ProcessMasterPreferencesResult pmp_result =
947 first_run::ProcessMasterPreferences(user_data_dir_,
948 master_prefs_.get());
949 if (pmp_result == first_run::EULA_EXIT_NOW)
950 return chrome::RESULT_CODE_EULA_REFUSED;
952 if (!parsed_command_line().HasSwitch(switches::kApp) &&
953 !parsed_command_line().HasSwitch(switches::kAppId) &&
954 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
955 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
958 // TODO(macourteau): refactor preferences that are copied from
959 // master_preferences into local_state, as a "local_state" section in
960 // master preferences. If possible, a generic solution would be preferred
961 // over a copy one-by-one of specific preferences. Also see related TODO
962 // in first_run.h.
964 // Store the initial VariationsService seed in local state, if it exists
965 // in master prefs.
966 if (!master_prefs_->variations_seed.empty() ||
967 !master_prefs_->compressed_variations_seed.empty()) {
968 if (!master_prefs_->variations_seed.empty()) {
969 local_state_->SetString(chrome_variations::prefs::kVariationsSeed,
970 master_prefs_->variations_seed);
972 if (!master_prefs_->compressed_variations_seed.empty()) {
973 local_state_->SetString(
974 chrome_variations::prefs::kVariationsCompressedSeed,
975 master_prefs_->compressed_variations_seed);
977 if (!master_prefs_->variations_seed_signature.empty()) {
978 local_state_->SetString(
979 chrome_variations::prefs::kVariationsSeedSignature,
980 master_prefs_->variations_seed_signature);
982 // Set the variation seed date to the current system time. If the user's
983 // clock is incorrect, this may cause some field trial expiry checks to
984 // not do the right thing until the next seed update from the server,
985 // when this value will be updated.
986 local_state_->SetInt64(chrome_variations::prefs::kVariationsSeedDate,
987 base::Time::Now().ToInternalValue());
990 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
991 local_state_->SetString(
992 prefs::kBrowserSuppressDefaultBrowserPrompt,
993 master_prefs_->suppress_default_browser_prompt_for_version);
996 #if defined(OS_WIN)
997 if (!master_prefs_->welcome_page_on_os_upgrade_enabled)
998 local_state_->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled, false);
999 #endif
1001 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1003 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1004 // Set the product channel for crash reports.
1005 base::debug::SetCrashKeyValue(crash_keys::kChannel,
1006 chrome::GetChannelString());
1007 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1009 // Initialize tracking synchronizer system.
1010 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
1011 make_scoped_ptr(new base::DefaultTickClock()));
1013 #if defined(OS_MACOSX)
1014 // Get the Keychain API to register for distributed notifications on the main
1015 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1016 // which doesn't. This ensures those notifications will get delivered
1017 // properly. See issue 37766.
1018 // (Note that the callback mask here is empty. I don't want to register for
1019 // any callbacks, I just want to initialize the mechanism.)
1020 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1021 #endif // defined(OS_MACOSX)
1023 #if defined(OS_CHROMEOS)
1024 // Must be done after g_browser_process is constructed, before
1025 // SetupMetricsAndFieldTrials().
1026 chromeos::CrosSettings::Initialize();
1027 #endif // defined(OS_CHROMEOS)
1029 // Now the command line has been mutated based on about:flags, we can setup
1030 // metrics and initialize field trials. The field trials are needed by
1031 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1032 SetupMetricsAndFieldTrials();
1034 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1035 browser_process_->PreCreateThreads();
1037 return content::RESULT_CODE_NORMAL_EXIT;
1040 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1041 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1042 TRACK_SCOPED_REGION(
1043 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1045 result_code_ = PreMainMessageLoopRunImpl();
1047 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1048 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1051 // PreMainMessageLoopRun calls these extra stages in the following order:
1052 // PreMainMessageLoopRunImpl()
1053 // ... initial setup, including browser_process_ setup.
1054 // PreProfileInit()
1055 // ... additional setup, including CreateProfile()
1056 // PostProfileInit()
1057 // ... additional setup
1058 // PreBrowserStart()
1059 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1060 // PostBrowserStart()
1062 void ChromeBrowserMainParts::PreProfileInit() {
1063 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1065 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1066 chrome_extra_parts_[i]->PreProfileInit();
1068 #if !defined(OS_ANDROID)
1069 // Initialize the feedback uploader so it can setup notifications for profile
1070 // creation.
1071 feedback::FeedbackProfileObserver::Initialize();
1073 // Ephemeral profiles may have been left behind if the browser crashed.
1074 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1075 #endif // !defined(OS_ANDROID)
1077 #if defined(ENABLE_EXTENSIONS)
1078 javascript_dialog_extensions_client::InstallClient();
1079 #endif // defined(ENABLE_EXTENSIONS)
1081 #if !defined(OS_IOS)
1082 InstallChromeJavaScriptNativeDialogFactory();
1083 #endif // !defined(OS_IOS)
1086 void ChromeBrowserMainParts::PostProfileInit() {
1087 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1089 #if defined(OS_ANDROID)
1090 DevToolsDiscoveryProviderAndroid::Install();
1091 #else
1092 ChromeDevToolsDiscoveryProvider::Install();
1093 #endif // defined(OS_ANDROID)
1095 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1096 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1097 chrome_extra_parts_[i]->PostProfileInit();
1100 void ChromeBrowserMainParts::PreBrowserStart() {
1101 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1102 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1103 chrome_extra_parts_[i]->PreBrowserStart();
1105 three_d_observer_.reset(new ThreeDAPIObserver());
1107 // Start the out-of-memory priority manager here so that we give the most
1108 // amount of time for the other services to start up before we start
1109 // adjusting the oom priority.
1111 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1112 // now.
1113 #if defined(OS_CHROMEOS)
1114 g_browser_process->GetOomPriorityManager()->Start();
1115 #elif defined(OS_WIN) || defined(OS_MACOSX)
1116 const std::string group_name =
1117 base::FieldTrialList::FindFullName("AutomaticTabDiscarding");
1118 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding) ||
1119 base::StartsWith(group_name, "Enabled", base::CompareCase::SENSITIVE)) {
1120 g_browser_process->GetOomPriorityManager()->Start();
1122 #endif
1125 void ChromeBrowserMainParts::PostBrowserStart() {
1126 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1127 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1128 chrome_extra_parts_[i]->PostBrowserStart();
1129 #if !defined(OS_ANDROID)
1130 // Allow ProcessSingleton to process messages.
1131 process_singleton_->Unlock();
1132 #endif // !defined(OS_ANDROID)
1133 #if defined(ENABLE_WEBRTC)
1134 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1135 // to reduce the impact on startup time.
1136 BrowserThread::PostDelayedTask(
1137 BrowserThread::UI,
1138 FROM_HERE,
1139 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1140 base::TimeDelta::FromMinutes(1));
1141 #endif // defined(ENABLE_WEBRTC)
1143 // At this point, StartupBrowserCreator::Start has run creating initial
1144 // browser windows and tabs, but no progress has been made in loading
1145 // content as the main message loop hasn't started processing tasks yet.
1146 // We setup to observe to the initial page load here to defer running
1147 // task posted via PostAfterStartupTask until its complete.
1148 AfterStartupTaskUtils::StartMonitoringStartup();
1151 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1152 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1153 TRACK_SCOPED_REGION(
1154 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1156 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1157 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1159 #if defined(OS_WIN)
1160 // Windows parental controls calls can be slow, so we do an early init here
1161 // that calculates this value off of the UI thread.
1162 IncognitoModePrefs::InitializePlatformParentalControls();
1163 #endif
1165 #if defined(ENABLE_EXTENSIONS)
1166 if (!variations::GetVariationParamValue(
1167 "LightSpeed", "EarlyInitStartup").empty()) {
1168 // Try to compute this early on another thread so that we don't spend time
1169 // during profile load initializing the extensions APIs.
1170 BrowserThread::PostTask(
1171 BrowserThread::FILE_USER_BLOCKING,
1172 FROM_HERE,
1173 base::Bind(
1174 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1176 #endif
1178 // Android updates the metrics service dynamically depending on whether the
1179 // application is in the foreground or not. Do not start here.
1180 #if !defined(OS_ANDROID)
1181 // Now that the file thread has been started, start recording.
1182 StartMetricsRecording();
1183 #endif // !defined(OS_ANDROID)
1185 if (!base::debug::BeingDebugged()) {
1186 // Create watchdog thread after creating all other threads because it will
1187 // watch the other threads and they must be running.
1188 browser_process_->watchdog_thread();
1191 // Do any initializating in the browser process that requires all threads
1192 // running.
1193 browser_process_->PreMainMessageLoopRun();
1195 // Record last shutdown time into a histogram.
1196 browser_shutdown::ReadLastShutdownInfo();
1198 #if defined(OS_WIN)
1199 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1200 // tasks. Those care whether the browser is already running. On Linux/Mac,
1201 // upgrade/uninstall happen separately.
1202 bool already_running = browser_util::IsBrowserAlreadyRunning();
1204 // If the command line specifies 'uninstall' then we need to work here
1205 // unless we detect another chrome browser running.
1206 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1207 return DoUninstallTasks(already_running);
1210 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1211 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1212 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1213 parsed_command_line_);
1216 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1217 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1218 #endif // defined(OS_WIN)
1220 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1221 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1222 prefs::kDefaultBrowserSettingEnabled);
1223 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1224 prefs::kDefaultBrowserSettingEnabled)) {
1225 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1228 return ShellIntegration::SetAsDefaultBrowser() ?
1229 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1230 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1233 #if defined(USE_AURA)
1234 // Make sure aura::Env has been initialized.
1235 CHECK(aura::Env::GetInstance());
1236 #endif // defined(USE_AURA)
1238 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1239 #if !defined(OS_ANDROID)
1240 // If the command line specifies --pack-extension, attempt the pack extension
1241 // startup action and exit.
1242 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1243 extensions::StartupHelper extension_startup_helper;
1244 if (extension_startup_helper.PackExtension(parsed_command_line()))
1245 return content::RESULT_CODE_NORMAL_EXIT;
1246 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1249 // When another process is running, use that process instead of starting a
1250 // new one. NotifyOtherProcess will currently give the other process up to
1251 // 20 seconds to respond. Note that this needs to be done before we attempt
1252 // to read the profile.
1253 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1254 switch (notify_result_) {
1255 case ProcessSingleton::PROCESS_NONE:
1256 // No process already running, fall through to starting a new one.
1257 break;
1259 case ProcessSingleton::PROCESS_NOTIFIED:
1260 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1261 // On POSIX systems, print a message notifying the process is running.
1262 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1263 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1264 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1266 // Having a differentiated return type for testing allows for tests to
1267 // verify proper handling of some switches. When not testing, stick to
1268 // the standard Unix convention of returning zero when things went as
1269 // expected.
1270 if (parsed_command_line().HasSwitch(switches::kTestType))
1271 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1272 return content::RESULT_CODE_NORMAL_EXIT;
1274 case ProcessSingleton::PROFILE_IN_USE:
1275 return chrome::RESULT_CODE_PROFILE_IN_USE;
1277 case ProcessSingleton::LOCK_ERROR:
1278 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1279 "directory. This means that running multiple instances "
1280 "would start multiple browser processes rather than "
1281 "opening a new window in the existing process. Aborting "
1282 "now to avoid profile corruption.";
1283 return chrome::RESULT_CODE_PROFILE_IN_USE;
1285 default:
1286 NOTREACHED();
1288 #endif // !defined(OS_ANDROID)
1290 // Handle special early return paths (which couldn't be processed even earlier
1291 // as they require the process singleton to be held) first.
1293 std::string try_chrome =
1294 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1295 if (!try_chrome.empty()) {
1296 #if defined(OS_WIN)
1297 // Setup.exe has determined that we need to run a retention experiment
1298 // and has lauched chrome to show the experiment UI. It is guaranteed that
1299 // no other Chrome is currently running as the process singleton was
1300 // sucessfully grabbed above.
1301 int try_chrome_int;
1302 base::StringToInt(try_chrome, &try_chrome_int);
1303 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1304 try_chrome_int,
1305 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1306 base::Unretained(process_singleton_.get())));
1307 if (answer == TryChromeDialogView::NOT_NOW)
1308 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1309 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1310 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1311 // At this point the user is willing to try chrome again.
1312 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1313 // Only set in the unattended case, the interactive case is Windows 8.
1314 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1315 ShellIntegration::SET_DEFAULT_UNATTENDED)
1316 ShellIntegration::SetAsDefaultBrowser();
1318 #else
1319 // We don't support retention experiments on Mac or Linux.
1320 return content::RESULT_CODE_NORMAL_EXIT;
1321 #endif // defined(OS_WIN)
1324 #if defined(OS_WIN)
1325 // Do the tasks if chrome has been upgraded while it was last running.
1326 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1327 return content::RESULT_CODE_NORMAL_EXIT;
1329 // Check if there is any machine level Chrome installed on the current
1330 // machine. If yes and the current Chrome process is user level, we do not
1331 // allow the user level Chrome to run. So we notify the user and uninstall
1332 // user level Chrome.
1333 // Note this check needs to happen here (after the process singleton was
1334 // obtained but before potentially creating the first run sentinel).
1335 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1336 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1337 #endif // defined(OS_WIN)
1339 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1340 if (sxs_linux::ShouldMigrateUserDataDir())
1341 return sxs_linux::MigrateUserDataDir();
1342 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1344 // Desktop construction occurs here, (required before profile creation).
1345 PreProfileInit();
1347 // Profile creation ----------------------------------------------------------
1349 metrics::MetricsService::SetExecutionPhase(
1350 metrics::MetricsService::CREATE_PROFILE,
1351 g_browser_process->local_state());
1353 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1354 base::TimeTicks::Now() - start_time_step1);
1356 // This step is costly and is already measured in Startup.CreateFirstProfile
1357 // and more directly Profile.CreateAndInitializeProfile.
1358 profile_ = CreatePrimaryProfile(parameters(),
1359 user_data_dir_,
1360 parsed_command_line());
1361 if (!profile_)
1362 return content::RESULT_CODE_NORMAL_EXIT;
1364 #if !defined(OS_ANDROID)
1365 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1366 // The first run sentinel must be created after the process singleton was
1367 // grabbed and no early return paths were otherwise hit above.
1368 first_run::CreateSentinelIfNeeded();
1369 #endif // !defined(OS_ANDROID)
1371 #if defined(ENABLE_BACKGROUND)
1372 // Autoload any profiles which are running background apps.
1373 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1374 browser_process_->profile_manager()->AutoloadProfiles();
1375 #endif // defined(ENABLE_BACKGROUND)
1376 // Post-profile init ---------------------------------------------------------
1378 TranslateService::Initialize();
1380 // Needs to be done before PostProfileInit, since login manager on CrOS is
1381 // called inside PostProfileInit.
1382 content::WebUIControllerFactory::RegisterFactory(
1383 ChromeWebUIControllerFactory::GetInstance());
1385 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1386 // So make sure to create it before that.
1387 #if !defined(DISABLE_NACL)
1388 NaClBrowserDelegateImpl* delegate =
1389 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1390 nacl::NaClBrowser::SetDelegate(delegate);
1391 #endif // !defined(DISABLE_NACL)
1393 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1394 // (requires supporting early exit).
1395 PostProfileInit();
1397 // Retrieve cached GL strings from local state and use them for GPU
1398 // blacklist decisions.
1399 if (g_browser_process->gl_string_manager())
1400 g_browser_process->gl_string_manager()->Initialize();
1402 // Create an instance of GpuModeManager to watch gpu mode pref change.
1403 g_browser_process->gpu_mode_manager();
1405 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1406 // Show the First Run UI if this is the first time Chrome has been run on
1407 // this computer, or we're being compelled to do so by a command line flag.
1408 // Note that this be done _after_ the PrefService is initialized and all
1409 // preferences are registered, since some of the code that the importer
1410 // touches reads preferences.
1411 if (first_run::IsChromeFirstRun()) {
1412 first_run::AutoImport(profile_,
1413 master_prefs_->homepage_defined,
1414 master_prefs_->do_import_items,
1415 master_prefs_->dont_import_items,
1416 master_prefs_->import_bookmarks_path);
1418 // Note: this can pop the first run consent dialog on linux.
1419 first_run::DoPostImportTasks(profile_,
1420 master_prefs_->make_chrome_default_for_user);
1422 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1423 browser_creator_->set_show_main_browser_window(
1424 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1425 } else {
1426 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1429 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1431 #if defined(OS_WIN)
1432 // Sets things up so that if we crash from this point on, a dialog will
1433 // popup asking the user to restart chrome. It is done this late to avoid
1434 // testing against a bunch of special cases that are taken care early on.
1435 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1436 parsed_command_line());
1438 // Registers Chrome with the Windows Restart Manager, which will restore the
1439 // Chrome session when the computer is restarted after a system update.
1440 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1441 // but should run on startup if extended to handle crashes/hangs/patches.
1442 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1443 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1444 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1445 parsed_command_line());
1448 // Verify that the profile is not on a network share and if so prepare to show
1449 // notification to the user.
1450 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1451 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1452 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1453 profile_->GetPath()));
1455 #endif // defined(OS_WIN)
1457 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1458 // Init the RLZ library. This just binds the dll and schedules a task on the
1459 // file thread to be run sometime later. If this is the first run we record
1460 // the installation event.
1461 PrefService* pref_service = profile_->GetPrefs();
1462 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1463 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1464 // Negative ping delay means to send ping immediately after a first search is
1465 // recorded.
1466 rlz::RLZTracker::SetRlzDelegate(
1467 make_scoped_ptr(new ChromeRLZTrackerDelegate));
1468 rlz::RLZTracker::InitRlzDelayed(
1469 first_run::IsChromeFirstRun(), ping_delay < 0,
1470 base::TimeDelta::FromMilliseconds(abs(ping_delay)),
1471 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
1472 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
1473 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
1474 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1476 // Configure modules that need access to resources.
1477 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1479 // In unittest mode, this will do nothing. In normal mode, this will create
1480 // the global IntranetRedirectDetector instance, which will promptly go to
1481 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1482 // to see if it should do anything else.
1484 // A simpler way of doing all this would be to have some function which could
1485 // give the time elapsed since startup, and simply have this object check that
1486 // when asked to initialize itself, but this doesn't seem to exist.
1488 // This can't be created in the BrowserProcessImpl constructor because it
1489 // needs to read prefs that get set after that runs.
1490 browser_process_->intranet_redirect_detector();
1491 GoogleSearchCounter::RegisterForNotifications();
1493 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1494 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1495 base::FilePath path =
1496 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1497 printing::PrintedDocument::set_debug_dump_path(path);
1499 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1501 HandleTestParameters(parsed_command_line());
1502 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1503 base::debug::BeingDebugged());
1505 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1506 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1507 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1508 browser_process_->GetApplicationLocale());
1510 // Start watching for hangs during startup. We disarm this hang detector when
1511 // ThreadWatcher takes over or when browser is shutdown or when
1512 // startup_watcher_ is deleted.
1513 metrics::MetricsService::SetExecutionPhase(
1514 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1515 g_browser_process->local_state());
1516 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1518 // On mobile, need for clean shutdown arises only when the application comes
1519 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1520 // http://crbug.com/179143
1521 #if !defined(OS_ANDROID)
1522 // Start watching for a hang.
1523 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1524 #endif // !defined(OS_ANDROID)
1526 #if defined(ENABLE_PRINT_PREVIEW)
1527 // Create the instance of the cloud print proxy service so that it can launch
1528 // the service process if needed. This is needed because the service process
1529 // might have shutdown because an update was available.
1530 // TODO(torne): this should maybe be done with
1531 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1532 // instead?
1533 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1534 #endif // defined(ENABLE_PRINT_PREVIEW)
1536 // Start watching all browser threads for responsiveness.
1537 metrics::MetricsService::SetExecutionPhase(
1538 metrics::MetricsService::THREAD_WATCHER_START,
1539 g_browser_process->local_state());
1540 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1542 #if defined(OS_ANDROID)
1543 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1544 #endif // defined(OS_ANDROID)
1546 #if !defined(DISABLE_NACL)
1547 BrowserThread::PostTask(
1548 BrowserThread::IO,
1549 FROM_HERE,
1550 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1551 #endif // !defined(DISABLE_NACL)
1553 // Make sure initial prefs are recorded
1554 PrefMetricsService::Factory::GetForProfile(profile_);
1556 PreBrowserStart();
1558 // Instantiate the notification UI manager, as this triggers a perf timer
1559 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1560 // triggering the timer and call that explicitly in the approprate place.
1561 // http://crbug.com/105065.
1562 browser_process_->notification_ui_manager();
1564 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1565 // data source is based on the Component Updater.
1566 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1568 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1569 RegisterComponentsForUpdate();
1571 #if defined(OS_ANDROID)
1572 chrome_variations::VariationsService* variations_service =
1573 browser_process_->variations_service();
1574 if (variations_service) {
1575 // Just initialize the policy prefs service here. Variations seed fetching
1576 // will be initialized when the app enters foreground mode.
1577 variations_service->set_policy_pref_service(profile_->GetPrefs());
1579 translate::TranslateDownloadManager::RequestLanguageList(
1580 profile_->GetPrefs());
1582 #else
1583 // Most general initialization is behind us, but opening a
1584 // tab and/or session restore and such is still to be done.
1585 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1587 // We are in regular browser boot sequence. Open initial tabs and enter the
1588 // main message loop.
1589 #if defined(OS_CHROMEOS)
1590 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1591 // them this early as the cryptohome hasn't yet been mounted (which happens
1592 // only once we log in.
1593 std::vector<Profile*> last_opened_profiles;
1594 #else
1595 std::vector<Profile*> last_opened_profiles =
1596 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1597 #endif // defined(OS_CHROMEOS)
1599 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1600 base::TimeTicks::Now() - start_time_step2);
1602 // This step is costly and is already measured in
1603 // Startup.StartupBrowserCreator_Start.
1604 bool started = browser_creator_->Start(
1605 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1606 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1607 if (started) {
1608 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1609 // Initialize autoupdate timer. Timer callback costs basically nothing
1610 // when browser is not in persistent mode, so it's OK to let it ride on
1611 // the main thread. This needs to be done here because we don't want
1612 // to start the timer when Chrome is run inside a test harness.
1613 browser_process_->StartAutoupdateTimer();
1614 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1616 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1617 // On Linux, the running exe will be updated if an upgrade becomes
1618 // available while the browser is running. We need to save the last
1619 // modified time of the exe, so we can compare to determine if there is
1620 // an upgrade while the browser is kept alive by a persistent extension.
1621 upgrade_util::SaveLastModifiedTimeOfExe();
1622 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1624 // Record now as the last successful chrome start.
1625 GoogleUpdateSettings::SetLastRunTime();
1627 #if defined(OS_MACOSX)
1628 // Call Recycle() here as late as possible, before going into the loop
1629 // because Start() will add things to it while creating the main window.
1630 if (parameters().autorelease_pool)
1631 parameters().autorelease_pool->Recycle();
1632 #endif // defined(OS_MACOSX)
1634 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1635 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1637 // If we're running tests (ui_task is non-null), then we don't want to
1638 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1639 // RequestLanguageList
1640 if (parameters().ui_task == NULL) {
1641 // Request new variations seed information from server.
1642 chrome_variations::VariationsService* variations_service =
1643 browser_process_->variations_service();
1644 if (variations_service) {
1645 variations_service->StartRepeatedVariationsSeedFetch();
1647 #if defined(OS_WIN)
1648 variations_service->StartGoogleUpdateRegistrySync();
1649 #endif // defined(OS_WIN)
1652 translate::TranslateDownloadManager::RequestLanguageList(
1653 profile_->GetPrefs());
1656 run_message_loop_ = true;
1657 } else {
1658 run_message_loop_ = false;
1660 browser_creator_.reset();
1662 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1663 if (g_browser_process->metrics_service()->reporting_active())
1664 content::StartPowerUsageMonitor();
1665 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1667 process_power_collector_.reset(new ProcessPowerCollector);
1668 process_power_collector_->Initialize();
1669 #endif // !defined(OS_ANDROID)
1671 PostBrowserStart();
1673 if (parameters().ui_task) {
1674 parameters().ui_task->Run();
1675 delete parameters().ui_task;
1676 run_message_loop_ = false;
1678 #if defined(OS_ANDROID)
1679 // We never run the C++ main loop on Android, since the UI thread message
1680 // loop is controlled by the OS, so this is as close as we can get to
1681 // the start of the main loop.
1682 if (result_code_ <= 0) {
1683 RecordBrowserStartupTime();
1685 #endif // defined(OS_ANDROID)
1687 #if !defined(OS_ANDROID)
1688 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1689 base::TimeTicks::Now() - start_time_step3);
1690 #endif // !defined(OS_ANDROID)
1692 return result_code_;
1695 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1696 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1697 #if defined(OS_ANDROID)
1698 // Chrome on Android does not use default MessageLoop. It has its own
1699 // Android specific MessageLoop
1700 NOTREACHED();
1701 return true;
1702 #else
1703 // Set the result code set in PreMainMessageLoopRun or set above.
1704 *result_code = result_code_;
1705 if (!run_message_loop_)
1706 return true; // Don't run the default message loop.
1708 // These should be invoked as close to the start of the browser's
1709 // UI thread message loop as possible to get a stable measurement
1710 // across versions.
1711 RecordBrowserStartupTime();
1713 DCHECK(base::MessageLoopForUI::IsCurrent());
1714 base::RunLoop run_loop;
1716 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1718 metrics::MetricsService::SetExecutionPhase(
1719 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1720 g_browser_process->local_state());
1721 run_loop.Run();
1723 return true;
1724 #endif // defined(OS_ANDROID)
1727 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1728 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1729 #if defined(OS_ANDROID)
1730 // Chrome on Android does not use default MessageLoop. It has its own
1731 // Android specific MessageLoop
1732 NOTREACHED();
1733 #else
1734 // Start watching for jank during shutdown. It gets disarmed when
1735 // |shutdown_watcher_| object is destructed.
1736 metrics::MetricsService::SetExecutionPhase(
1737 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1738 g_browser_process->local_state());
1739 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1741 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1742 startup_watcher_->Disarm();
1744 // Remove observers attached to D-Bus clients before DbusThreadManager is
1745 // shut down.
1746 process_power_collector_.reset();
1748 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1749 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1751 // Some tests don't set parameters.ui_task, so they started translate
1752 // language fetch that was never completed so we need to cleanup here
1753 // otherwise it will be done by the destructor in a wrong thread.
1754 TranslateService::Shutdown(parameters().ui_task == NULL);
1756 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1757 process_singleton_->Cleanup();
1759 // Stop all tasks that might run on WatchDogThread.
1760 ThreadWatcherList::StopWatchingAll();
1762 browser_process_->metrics_service()->Stop();
1764 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1765 browser_process_->StartTearDown();
1766 #endif // defined(OS_ANDROID)
1769 void ChromeBrowserMainParts::PostDestroyThreads() {
1770 #if defined(OS_ANDROID)
1771 // On Android, there is no quit/exit. So the browser's main message loop will
1772 // not finish.
1773 NOTREACHED();
1774 #else
1775 browser_process_->PostDestroyThreads();
1776 // browser_shutdown takes care of deleting browser_process, so we need to
1777 // release it.
1778 ignore_result(browser_process_.release());
1779 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1780 master_prefs_.reset();
1781 process_singleton_.reset();
1782 device_event_log::Shutdown();
1784 // We need to do this check as late as possible, but due to modularity, this
1785 // may be the last point in Chrome. This would be more effective if done at
1786 // a higher level on the stack, so that it is impossible for an early return
1787 // to bypass this code. Perhaps we need a *final* hook that is called on all
1788 // paths from content/browser/browser_main.
1789 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1791 #if defined(OS_CHROMEOS)
1792 chromeos::CrosSettings::Shutdown();
1793 #endif // defined(OS_CHROMEOS)
1794 #endif // defined(OS_ANDROID)
1797 // Public members:
1799 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1800 chrome_extra_parts_.push_back(parts);