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