Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blobe4f88c5bdf463f55b6e3e3be3a09da8a6ef012c1
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/feature_list.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram_macros.h"
21 #include "base/path_service.h"
22 #include "base/prefs/json_pref_store.h"
23 #include "base/prefs/pref_registry_simple.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/prefs/pref_value_store.h"
26 #include "base/prefs/scoped_user_pref_update.h"
27 #include "base/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/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/service/variations_service.h"
129 #include "components/variations/variations_associated_data.h"
130 #include "components/variations/variations_switches.h"
131 #include "components/version_info/version_info.h"
132 #include "content/public/browser/browser_thread.h"
133 #include "content/public/browser/notification_observer.h"
134 #include "content/public/browser/notification_registrar.h"
135 #include "content/public/browser/notification_service.h"
136 #include "content/public/browser/notification_types.h"
137 #include "content/public/browser/power_usage_monitor.h"
138 #include "content/public/browser/site_instance.h"
139 #include "content/public/common/content_client.h"
140 #include "content/public/common/content_switches.h"
141 #include "content/public/common/main_function_params.h"
142 #include "grit/platform_locale_settings.h"
143 #include "media/audio/audio_manager.h"
144 #include "net/base/net_module.h"
145 #include "net/cookies/cookie_monster.h"
146 #include "net/http/http_network_layer.h"
147 #include "net/http/http_stream_factory.h"
148 #include "net/url_request/url_request.h"
149 #include "ui/base/l10n/l10n_util.h"
150 #include "ui/base/layout.h"
151 #include "ui/base/resource/resource_bundle.h"
152 #include "ui/strings/grit/app_locale_settings.h"
154 #if defined(OS_ANDROID)
155 #include "chrome/browser/android/dev_tools_discovery_provider_android.h"
156 #include "chrome/browser/metrics/thread_watcher_android.h"
157 #include "ui/base/resource/resource_bundle_android.h"
158 #else
159 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
160 #include "chrome/browser/feedback/feedback_profile_observer.h"
161 #endif // defined(OS_ANDROID)
163 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
164 #include "chrome/browser/first_run/upgrade_util_linux.h"
165 #include "chrome/browser/sxs_linux.h"
166 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
168 #if defined(OS_CHROMEOS)
169 #include "chrome/browser/chromeos/settings/cros_settings.h"
170 #include "chromeos/chromeos_switches.h"
171 #include "chromeos/settings/cros_settings_names.h"
172 #endif // defined(OS_CHROMEOS)
174 // TODO(port): several win-only methods have been pulled out of this, but
175 // BrowserMain() as a whole needs to be broken apart so that it's usable by
176 // other platforms. For now, it's just a stub. This is a serious work in
177 // progress and should not be taken as an indication of a real refactoring.
179 #if defined(OS_WIN)
180 #include "base/environment.h" // For PreRead experiment.
181 #include "base/trace_event/trace_event_etw_export_win.h"
182 #include "base/win/windows_version.h"
183 #include "chrome/browser/browser_util_win.h"
184 #include "chrome/browser/chrome_browser_main_win.h"
185 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
186 #include "chrome/browser/component_updater/caps_installer_win.h"
187 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
188 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
189 #include "chrome/browser/first_run/upgrade_util_win.h"
190 #include "chrome/browser/ui/network_profile_bubble.h"
191 #include "chrome/installer/util/helper.h"
192 #include "chrome/installer/util/install_util.h"
193 #include "chrome/installer/util/shell_util.h"
194 #include "components/browser_watcher/exit_funnel_win.h"
195 #include "net/base/net_util.h"
196 #include "ui/base/l10n/l10n_util_win.h"
197 #include "ui/gfx/win/dpi.h"
198 #include "ui/shell_dialogs/select_file_dialog.h"
199 #endif // defined(OS_WIN)
201 #if defined(OS_MACOSX)
202 #include <Security/Security.h>
204 #include "base/mac/scoped_nsautorelease_pool.h"
205 #include "chrome/browser/mac/keystone_glue.h"
206 #endif // defined(OS_MACOSX)
208 #if !defined(OS_IOS)
209 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
210 #endif // !defined(OS_IOS)
212 #if !defined(DISABLE_NACL)
213 #include "chrome/browser/component_updater/pnacl_component_installer.h"
214 #include "components/nacl/browser/nacl_process_host.h"
215 #endif // !defined(DISABLE_NACL)
217 #if defined(ENABLE_EXTENSIONS)
218 #include "chrome/browser/extensions/startup_helper.h"
219 #include "extensions/browser/extension_protocols.h"
220 #include "extensions/common/features/feature_provider.h"
221 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
222 #endif // defined(ENABLE_EXTENSIONS)
224 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
225 #include "printing/printed_document.h"
226 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
228 #if defined(ENABLE_RLZ)
229 #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
230 #include "components/rlz/rlz_tracker.h"
231 #endif // defined(ENABLE_RLZ)
233 #if defined(ENABLE_WEBRTC)
234 #include "chrome/browser/media/webrtc_log_util.h"
235 #endif // defined(ENABLE_WEBRTC)
237 #if defined(USE_AURA)
238 #include "ui/aura/env.h"
239 #endif // defined(USE_AURA)
241 #if !defined(OS_ANDROID) && !defined(OS_IOS)
242 #include "chrome/browser/chrome_webusb_browser_client.h"
243 #include "components/webusb/webusb_detector.h"
244 #endif
246 using content::BrowserThread;
248 namespace {
250 // This function provides some ways to test crash and assertion handling
251 // behavior of the program.
252 void HandleTestParameters(const base::CommandLine& command_line) {
253 // This parameter causes a null pointer crash (crash reporter trigger).
254 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
255 int* bad_pointer = NULL;
256 *bad_pointer = 0;
260 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
261 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
262 const std::vector<GURL>& new_tabs) {
263 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
264 it != new_tabs.end(); ++it) {
265 if (it->is_valid())
266 browser_creator->AddFirstRunTab(*it);
269 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
271 // Returns the new local state object, guaranteed non-NULL.
272 // |local_state_task_runner| must be a shutdown-blocking task runner.
273 PrefService* InitializeLocalState(
274 base::SequencedTaskRunner* local_state_task_runner,
275 const base::CommandLine& parsed_command_line) {
276 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
278 // Load local state. This includes the application locale so we know which
279 // locale dll to load. This also causes local state prefs to be registered.
280 PrefService* local_state = g_browser_process->local_state();
281 DCHECK(local_state);
283 #if defined(OS_WIN)
284 if (first_run::IsChromeFirstRun()) {
285 // During first run we read the google_update registry key to find what
286 // language the user selected when downloading the installer. This
287 // becomes our default language in the prefs.
288 // Other platforms obey the system locale.
289 base::string16 install_lang;
290 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
291 local_state->SetString(prefs::kApplicationLocale,
292 base::UTF16ToASCII(install_lang));
295 #endif // defined(OS_WIN)
297 // If the local state file for the current profile doesn't exist and the
298 // parent profile command line flag is present, then we should inherit some
299 // local state from the parent profile.
300 // Checking that the local state file for the current profile doesn't exist
301 // is the most robust way to determine whether we need to inherit or not
302 // since the parent profile command line flag can be present even when the
303 // current profile is not a new one, and in that case we do not want to
304 // inherit and reset the user's setting.
306 // TODO(mnissler): We should probably just instantiate a
307 // JSONPrefStore here instead of an entire PrefService. Once this is
308 // addressed, the call to browser_prefs::RegisterLocalState can move
309 // to chrome_prefs::CreateLocalState.
310 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
311 base::FilePath local_state_path;
312 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
313 bool local_state_file_exists = base::PathExists(local_state_path);
314 if (!local_state_file_exists) {
315 base::FilePath parent_profile =
316 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
317 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
318 scoped_ptr<PrefService> parent_local_state(
319 chrome_prefs::CreateLocalState(
320 parent_profile,
321 local_state_task_runner,
322 g_browser_process->policy_service(),
323 registry,
324 false));
325 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
326 // Right now, we only inherit the locale setting from the parent profile.
327 local_state->SetString(
328 prefs::kApplicationLocale,
329 parent_local_state->GetString(prefs::kApplicationLocale));
333 #if defined(OS_CHROMEOS)
334 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
335 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
336 // Ensure that we start with owner's locale.
337 if (!owner_locale.empty() &&
338 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
339 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
340 local_state->SetString(prefs::kApplicationLocale, owner_locale);
343 #endif // defined(OS_CHROMEOS)
345 return local_state;
348 // Initializes the primary profile, possibly doing some user prompting to pick
349 // a fallback profile. Returns the newly created profile, or NULL if startup
350 // should not continue.
351 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
352 const base::FilePath& user_data_dir,
353 const base::CommandLine& parsed_command_line) {
354 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
355 TRACK_SCOPED_REGION(
356 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
358 base::Time start = base::Time::Now();
359 if (profiles::IsMultipleProfilesEnabled() &&
360 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
361 profiles::SetLastUsedProfile(
362 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
363 // Clear kProfilesLastActive since the user only wants to launch a specific
364 // profile.
365 ListPrefUpdate update(g_browser_process->local_state(),
366 prefs::kProfilesLastActive);
367 base::ListValue* profile_list = update.Get();
368 profile_list->Clear();
371 Profile* profile = NULL;
372 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
373 // On ChromeOS and Android the ProfileManager will use the same path as the
374 // one we got passed. GetActiveUserProfile will therefore use the correct path
375 // automatically.
376 DCHECK_EQ(user_data_dir.value(),
377 g_browser_process->profile_manager()->user_data_dir().value());
378 profile = ProfileManager::GetActiveUserProfile();
379 #else
380 base::FilePath profile_path =
381 GetStartupProfilePath(user_data_dir, parsed_command_line);
383 // Without NewAvatarMenu, replace guest with any existing profile.
384 if (!switches::IsNewAvatarMenu() &&
385 profile_path == ProfileManager::GetGuestProfilePath()) {
386 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
387 GetPathOfProfileAtIndex(0);
389 profile = g_browser_process->profile_manager()->GetProfile(
390 profile_path);
392 // If we're using the --new-profile-management flag and this profile is
393 // signed out, then we should show the user manager instead. By switching
394 // the active profile to the guest profile we ensure that no
395 // browser windows will be opened for the guest profile.
396 if (switches::IsNewProfileManagement() &&
397 profile &&
398 !profile->IsGuestSession()) {
399 ProfileInfoCache& cache =
400 g_browser_process->profile_manager()->GetProfileInfoCache();
401 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
403 if (profile_index != std::string::npos &&
404 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
405 profile = g_browser_process->profile_manager()->GetProfile(
406 ProfileManager::GetGuestProfilePath());
409 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
410 if (profile) {
411 UMA_HISTOGRAM_LONG_TIMES(
412 "Startup.CreateFirstProfile", base::Time::Now() - start);
413 return profile;
416 #if !defined(OS_WIN)
417 // TODO(port): fix this. See comments near the definition of
418 // user_data_dir. It is better to CHECK-fail here than it is to
419 // silently exit because of missing code in the above test.
420 CHECK(profile) << "Cannot get default profile.";
421 #endif // !defined(OS_WIN)
423 return NULL;
426 #if defined(OS_MACOSX)
427 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
428 SecKeychainCallbackInfo* info, void* context) {
429 return noErr;
431 #endif // defined(OS_MACOSX)
433 void RegisterComponentsForUpdate() {
434 component_updater::ComponentUpdateService* cus =
435 g_browser_process->component_updater();
437 // Registration can be before or after cus->Start() so it is ok to post
438 // a task to the UI thread to do registration once you done the necessary
439 // file IO to know you existing component version.
440 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
441 RegisterRecoveryComponent(cus, g_browser_process->local_state());
442 RegisterPepperFlashComponent(cus);
443 RegisterSwiftShaderComponent(cus);
444 RegisterWidevineCdmComponent(cus);
445 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
447 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
448 #if defined(OS_CHROMEOS)
449 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
450 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
451 // installer when running on Linux. See crbug.com/422121 for more details.
452 if (!base::SysInfo::IsRunningOnChromeOS())
453 #endif // defined(OS_CHROMEOS)
454 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
455 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
457 // Registration of the CLD Component is a no-op unless the CLD data source has
458 // been configured to be the "Component" data source.
459 RegisterCldComponent(cus);
461 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
462 g_browser_process->supervised_user_whitelist_installer();
463 whitelist_installer->RegisterComponents();
465 base::FilePath path;
466 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
467 #if defined(OS_ANDROID)
468 // The CRLSet component was enabled for some releases. This code attempts to
469 // delete it from the local disk of those how may have downloaded it.
470 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
471 #elif !defined(OS_CHROMEOS)
472 // CRLSetFetcher attempts to load a CRL set from either the local disk or
473 // network.
474 // For Chrome OS this registration is delayed until user login.
475 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
476 // Registration of the EV Whitelist component here is not necessary for:
477 // 1. Android: Because it currently does not have the EV indicator.
478 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
479 RegisterEVWhitelistComponent(cus, path);
480 #endif // defined(OS_ANDROID)
483 #if defined(OS_WIN)
484 #if defined(GOOGLE_CHROME_BUILD)
485 RegisterSwReporterComponent(cus);
486 #endif // defined(GOOGLE_CHROME_BUILD)
487 RegisterCAPSComponent(cus);
488 #endif // defined(OS_WIN)
491 #if !defined(OS_ANDROID)
492 bool ProcessSingletonNotificationCallback(
493 const base::CommandLine& command_line,
494 const base::FilePath& current_directory) {
495 // Drop the request if the browser process is already in shutdown path.
496 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
497 #if defined(OS_WIN)
498 browser_watcher::ExitFunnel::RecordSingleEvent(
499 chrome::kBrowserExitCodesRegistryPath,
500 L"ProcessSingletonIsShuttingDown");
501 #endif // defined(OS_WIN)
503 return false;
506 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
507 std::string start_time_string =
508 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
509 int64 remote_start_time;
510 if (base::StringToInt64(start_time_string, &remote_start_time)) {
511 base::TimeDelta elapsed =
512 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
513 if (command_line.HasSwitch(switches::kFastStart)) {
514 UMA_HISTOGRAM_LONG_TIMES(
515 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
516 } else {
517 UMA_HISTOGRAM_LONG_TIMES(
518 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
523 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
524 command_line);
526 base::FilePath user_data_dir =
527 g_browser_process->profile_manager()->user_data_dir();
528 base::FilePath startup_profile_dir =
529 GetStartupProfilePath(user_data_dir, command_line);
531 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
532 command_line, current_directory, startup_profile_dir);
533 return true;
535 #endif // !defined(OS_ANDROID)
537 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
538 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
539 std::string port_str =
540 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
541 int port;
542 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
543 g_browser_process->CreateDevToolsHttpProtocolHandler(
544 chrome::HOST_DESKTOP_TYPE_NATIVE,
545 "127.0.0.1",
546 static_cast<uint16>(port));
547 } else {
548 DLOG(WARNING) << "Invalid http debugger port number " << port;
553 base::StackSamplingProfiler::SamplingParams GetStartupSamplingParams() {
554 // Sample at 10Hz for 30 seconds.
555 base::StackSamplingProfiler::SamplingParams params;
556 params.initial_delay = base::TimeDelta::FromMilliseconds(0);
557 params.bursts = 1;
558 params.samples_per_burst = 300;
559 params.sampling_interval = base::TimeDelta::FromMilliseconds(100);
560 return params;
563 } // namespace
565 namespace chrome_browser {
567 // This error message is not localized because we failed to load the
568 // localization data files.
569 #if defined(OS_WIN)
570 const char kMissingLocaleDataTitle[] = "Missing File Error";
571 #endif // defined(OS_WIN)
573 #if defined(OS_WIN)
574 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
575 const char kMissingLocaleDataMessage[] =
576 "Unable to find locale data files. Please reinstall.";
577 #endif // defined(OS_WIN)
579 } // namespace chrome_browser
581 // BrowserMainParts ------------------------------------------------------------
583 ChromeBrowserMainParts::ChromeBrowserMainParts(
584 const content::MainFunctionParams& parameters)
585 : parameters_(parameters),
586 parsed_command_line_(parameters.command_line),
587 result_code_(content::RESULT_CODE_NORMAL_EXIT),
588 startup_watcher_(new StartupTimeBomb()),
589 shutdown_watcher_(new ShutdownWatcherHelper()),
590 browser_field_trials_(parameters.command_line),
591 sampling_profiler_(
592 base::PlatformThread::CurrentId(),
593 GetStartupSamplingParams(),
594 metrics::CallStackProfileMetricsProvider::GetProfilerCallback(
595 metrics::CallStackProfileMetricsProvider::Params(
596 metrics::CallStackProfileMetricsProvider::PROCESS_STARTUP,
597 false))),
598 profile_(NULL),
599 run_message_loop_(true),
600 notify_result_(ProcessSingleton::PROCESS_NONE),
601 local_state_(NULL),
602 restart_last_session_(false) {
603 const version_info::Channel channel = chrome::GetChannel();
604 if (channel == version_info::Channel::UNKNOWN ||
605 channel == version_info::Channel::CANARY ||
606 channel == version_info::Channel::DEV) {
607 sampling_profiler_.Start();
610 // If we're running tests (ui_task is non-null).
611 if (parameters.ui_task)
612 browser_defaults::enable_help_app = false;
614 // Chrome disallows cookies by default. All code paths that want to use
615 // cookies need to go through one of Chrome's URLRequestContexts which have
616 // a ChromeNetworkDelegate attached that selectively allows cookies again.
617 net::URLRequest::SetDefaultCookiePolicyToBlock();
620 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
621 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
622 delete chrome_extra_parts_[i];
623 chrome_extra_parts_.clear();
626 // This will be called after the command-line has been mutated by about:flags
627 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
628 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
629 // Must initialize metrics after labs have been converted into switches,
630 // but before field trials are set up (so that client ID is available for
631 // one-time randomized field trials).
633 // Initialize FieldTrialList to support FieldTrials that use one-time
634 // randomization.
635 metrics::MetricsService* metrics = browser_process_->metrics_service();
636 field_trial_list_.reset(
637 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
639 const base::CommandLine* command_line =
640 base::CommandLine::ForCurrentProcess();
641 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
642 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
643 base::FieldTrial::EnableBenchmarking();
646 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
647 bool result = chrome_variations::AssociateParamsFromString(
648 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
649 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
650 << " list specified.";
653 // Ensure any field trials specified on the command line are initialized.
654 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
655 std::set<std::string> unforceable_field_trials;
656 #if defined(OFFICIAL_BUILD)
657 unforceable_field_trials.insert("SettingsEnforcement");
658 #endif // defined(OFFICIAL_BUILD)
660 // Create field trials without activating them, so that this behaves in a
661 // consistent manner with field trials created from the server.
662 bool result = base::FieldTrialList::CreateTrialsFromString(
663 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
664 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
665 unforceable_field_trials);
666 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
667 << " list specified.";
670 #if defined(FIELDTRIAL_TESTING_ENABLED)
671 if (!command_line->HasSwitch(switches::kDisableFieldTrialTestingConfig) &&
672 !command_line->HasSwitch(switches::kForceFieldTrials) &&
673 !command_line->HasSwitch(variations::switches::kVariationsServerURL))
674 chrome_variations::AssociateDefaultFieldTrialConfig();
675 #endif // defined(FIELDTRIAL_TESTING_ENABLED)
677 if (command_line->HasSwitch(switches::kForceVariationIds)) {
678 // Create default variation ids which will always be included in the
679 // X-Client-Data request header.
680 variations::VariationsHttpHeaderProvider* provider =
681 variations::VariationsHttpHeaderProvider::GetInstance();
682 bool result = provider->SetDefaultVariationIds(
683 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
684 CHECK(result) << "Invalid --" << switches::kForceVariationIds
685 << " list specified.";
686 metrics->AddSyntheticTrialObserver(provider);
689 scoped_ptr<base::FeatureList> feature_list(new base::FeatureList);
690 feature_list->InitializeFromCommandLine(
691 command_line->GetSwitchValueASCII(switches::kEnableFeatures),
692 command_line->GetSwitchValueASCII(switches::kDisableFeatures));
694 variations::VariationsService* variations_service =
695 browser_process_->variations_service();
696 if (variations_service)
697 variations_service->CreateTrialsFromSeed();
699 // TODO(asvitkine): Pass |feature_list| to CreateTrialsFromSeed() above.
700 base::FeatureList::SetInstance(feature_list.Pass());
702 // This must be called after |local_state_| is initialized.
703 browser_field_trials_.SetupFieldTrials();
705 // Enable Navigation Tracing only if a trace upload url is specified.
706 if (command_line->HasSwitch(switches::kEnableNavigationTracing) &&
707 command_line->HasSwitch(switches::kTraceUploadURL)) {
708 tracing::SetupNavigationTracing();
711 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
712 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
713 // Even though base::Bind does AddRef and Release, the object will not be
714 // deleted after the Task is executed.
715 field_trial_synchronizer_ = new FieldTrialSynchronizer();
717 // Now that field trials have been created, initializes metrics recording.
718 metrics->InitializeMetricsRecordingState();
720 const version_info::Channel channel = chrome::GetChannel();
722 // TODO(dalecurtis): Remove these checks and enable for all channels once we
723 // track down the root causes of crbug.com/422522 and crbug.com/478932.
724 if (channel == version_info::Channel::UNKNOWN ||
725 channel == version_info::Channel::CANARY ||
726 channel == version_info::Channel::DEV) {
727 media::AudioManager::EnableHangMonitor();
730 // Enable profiler instrumentation depending on the channel.
731 switch (channel) {
732 case version_info::Channel::UNKNOWN:
733 case version_info::Channel::CANARY:
734 tracked_objects::ScopedTracker::Enable();
735 break;
737 case version_info::Channel::DEV:
738 case version_info::Channel::BETA:
739 case version_info::Channel::STABLE:
740 // Don't enable instrumentation.
741 break;
745 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
747 void ChromeBrowserMainParts::StartMetricsRecording() {
748 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
750 g_browser_process->metrics_service()->CheckForClonedInstall(
751 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
753 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
756 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
757 // Don't record any metrics if UI was displayed before this point e.g.
758 // warning dialogs.
759 if (startup_metric_utils::WasNonBrowserUIDisplayed())
760 return;
762 bool is_first_run = false;
763 #if !defined(OS_ANDROID)
764 // On Android, first run is handled in Java code, and the C++ side of Chrome
765 // doesn't know if this is the first run. This will cause some inaccuracy in
766 // the UMA statistics, but this should be minor (first runs are rare).
767 is_first_run = first_run::IsChromeFirstRun();
768 #endif // defined(OS_ANDROID)
770 // Record collected startup metrics.
771 startup_metric_utils::RecordBrowserMainMessageLoopStart(base::Time::Now(),
772 is_first_run);
775 // -----------------------------------------------------------------------------
776 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
778 #if defined(OS_WIN)
779 #define DLLEXPORT __declspec(dllexport)
781 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
782 extern "C" {
783 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
786 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
787 // Need an instance of AtExitManager to handle singleton creations and
788 // deletions. We need this new instance because, the old instance created
789 // in ChromeMain() got destructed when the function returned.
790 base::AtExitManager exit_manager;
791 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
793 #endif
795 // content::BrowserMainParts implementation ------------------------------------
797 void ChromeBrowserMainParts::PreEarlyInitialization() {
798 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
799 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
800 chrome_extra_parts_[i]->PreEarlyInitialization();
803 void ChromeBrowserMainParts::PostEarlyInitialization() {
804 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
805 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
806 chrome_extra_parts_[i]->PostEarlyInitialization();
809 void ChromeBrowserMainParts::ToolkitInitialized() {
810 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
811 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
812 chrome_extra_parts_[i]->ToolkitInitialized();
815 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
816 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
818 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
819 chrome_extra_parts_[i]->PreMainMessageLoopStart();
822 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
823 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
825 // device_event_log must be initialized after the message loop. Calls to
826 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
827 // platforms (e.g. chromeos) may have already initialized this.
828 if (!device_event_log::IsInitialized())
829 device_event_log::Initialize(0 /* default max entries */);
831 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
832 chrome_extra_parts_[i]->PostMainMessageLoopStart();
835 int ChromeBrowserMainParts::PreCreateThreads() {
836 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
837 result_code_ = PreCreateThreadsImpl();
839 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
840 #if !defined(OS_ANDROID)
841 // These members must be initialized before exiting this function normally.
842 DCHECK(master_prefs_.get());
843 DCHECK(browser_creator_.get());
844 #endif // !defined(OS_ANDROID)
845 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
846 chrome_extra_parts_[i]->PreCreateThreads();
849 return result_code_;
852 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
853 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
854 run_message_loop_ = false;
855 #if !defined(OS_ANDROID)
856 chrome::MaybeShowInvalidUserDataDirWarningDialog();
857 #endif // !defined(OS_ANDROID)
858 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
859 return chrome::RESULT_CODE_MISSING_DATA;
861 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
862 MediaCaptureDevicesDispatcher::GetInstance();
864 // Android's first run is done in Java instead of native.
865 #if !defined(OS_ANDROID)
866 process_singleton_.reset(new ChromeProcessSingleton(
867 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
869 // Cache first run state early.
870 first_run::IsChromeFirstRun();
871 #endif // !defined(OS_ANDROID)
873 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
874 JsonPrefStore::GetTaskRunnerForFile(
875 base::FilePath(chrome::kLocalStorePoolName),
876 BrowserThread::GetBlockingPool());
879 TRACE_EVENT0("startup",
880 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
881 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
882 parsed_command_line()));
885 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
886 TRACE_EVENT0("startup",
887 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
888 // User wants to override default tracking status.
889 std::string flag =
890 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
891 // Default to basic profiling (no parent child support).
892 tracked_objects::ThreadData::Status status =
893 tracked_objects::ThreadData::PROFILING_ACTIVE;
894 if (flag.compare("0") != 0)
895 status = tracked_objects::ThreadData::DEACTIVATED;
896 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
899 local_state_ = InitializeLocalState(
900 local_state_task_runner.get(), parsed_command_line());
902 #if !defined(OS_ANDROID)
903 // These members must be initialized before returning from this function.
904 master_prefs_.reset(new first_run::MasterPrefs);
905 // Android doesn't use StartupBrowserCreator.
906 browser_creator_.reset(new StartupBrowserCreator);
907 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
908 chrome::UMABrowsingActivityObserver::Init();
909 #endif // !defined(OS_ANDROID)
911 #if !defined(OS_CHROMEOS)
912 // Convert active labs into switches. This needs to be done before
913 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
914 // affected by experiment flags (--touch-optimized-ui in particular).
915 // On ChromeOS system level flags are applied from the device settings from
916 // the session manager.
918 TRACE_EVENT0("startup",
919 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
920 about_flags::PrefServiceFlagsStorage flags_storage_(
921 g_browser_process->local_state());
922 about_flags::ConvertFlagsToSwitches(&flags_storage_,
923 base::CommandLine::ForCurrentProcess(),
924 about_flags::kAddSentinels);
926 #endif // !defined(OS_CHROMEOS)
928 #if defined(OS_WIN)
929 // This is needed to enable ETW exporting when requested in about:flags.
930 // Normally, we enable it in ContentMainRunnerImpl::Initialize when the flag
931 // is present on the command line but flags in about:flags are converted only
932 // after this function runs. Note that this starts exporting later which
933 // affects tracing the browser startup. Also, this is only relevant for the
934 // browser process, as other processes will get all the flags on their command
935 // line regardless of the origin (command line or about:flags).
936 if (parsed_command_line().HasSwitch(switches::kTraceExportEventsToETW))
937 base::trace_event::TraceEventETWExport::EnableETWExport();
938 #endif // OS_WIN
940 local_state_->UpdateCommandLinePrefStore(
941 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
943 // Reset the command line in the crash report details, since we may have
944 // just changed it to include experiments.
945 crash_keys::SetSwitchesFromCommandLine(
946 base::CommandLine::ForCurrentProcess());
948 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
949 // needed when loading the MainMenu.nib and the language doesn't depend on
950 // anything since it comes from Cocoa.
951 #if defined(OS_MACOSX)
952 std::string locale =
953 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
954 browser_process_->SetApplicationLocale(locale);
955 #else
956 const std::string locale =
957 local_state_->GetString(prefs::kApplicationLocale);
959 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
960 // method InitSharedInstance is ignored.
962 TRACE_EVENT_BEGIN0("startup",
963 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
964 const std::string loaded_locale =
965 ui::ResourceBundle::InitSharedInstanceWithLocale(
966 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
967 TRACE_EVENT_END0("startup",
968 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
970 if (loaded_locale.empty() &&
971 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
972 ShowMissingLocaleMessageBox();
973 return chrome::RESULT_CODE_MISSING_DATA;
975 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
976 browser_process_->SetApplicationLocale(loaded_locale);
979 TRACE_EVENT0("startup",
980 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
981 base::FilePath resources_pack_path;
982 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
983 #if defined(OS_ANDROID)
984 ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path);
985 #else
986 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
987 resources_pack_path, ui::SCALE_FACTOR_NONE);
988 #endif // defined(OS_ANDROID)
990 #endif // defined(OS_MACOSX)
992 // Android does first run in Java instead of native.
993 // Chrome OS has its own out-of-box-experience code.
994 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
995 // On first run, we need to process the predictor preferences before the
996 // browser's profile_manager object is created, but after ResourceBundle
997 // is initialized.
998 if (first_run::IsChromeFirstRun()) {
999 first_run::ProcessMasterPreferencesResult pmp_result =
1000 first_run::ProcessMasterPreferences(user_data_dir_,
1001 master_prefs_.get());
1002 if (pmp_result == first_run::EULA_EXIT_NOW)
1003 return chrome::RESULT_CODE_EULA_REFUSED;
1005 if (!parsed_command_line().HasSwitch(switches::kApp) &&
1006 !parsed_command_line().HasSwitch(switches::kAppId) &&
1007 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
1008 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
1011 // TODO(macourteau): refactor preferences that are copied from
1012 // master_preferences into local_state, as a "local_state" section in
1013 // master preferences. If possible, a generic solution would be preferred
1014 // over a copy one-by-one of specific preferences. Also see related TODO
1015 // in first_run.h.
1017 // Store the initial VariationsService seed in local state, if it exists
1018 // in master prefs.
1019 if (!master_prefs_->variations_seed.empty() ||
1020 !master_prefs_->compressed_variations_seed.empty()) {
1021 if (!master_prefs_->variations_seed.empty()) {
1022 local_state_->SetString(variations::prefs::kVariationsSeed,
1023 master_prefs_->variations_seed);
1025 if (!master_prefs_->compressed_variations_seed.empty()) {
1026 local_state_->SetString(variations::prefs::kVariationsCompressedSeed,
1027 master_prefs_->compressed_variations_seed);
1029 if (!master_prefs_->variations_seed_signature.empty()) {
1030 local_state_->SetString(variations::prefs::kVariationsSeedSignature,
1031 master_prefs_->variations_seed_signature);
1033 // Set the variation seed date to the current system time. If the user's
1034 // clock is incorrect, this may cause some field trial expiry checks to
1035 // not do the right thing until the next seed update from the server,
1036 // when this value will be updated.
1037 local_state_->SetInt64(variations::prefs::kVariationsSeedDate,
1038 base::Time::Now().ToInternalValue());
1041 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
1042 local_state_->SetString(
1043 prefs::kBrowserSuppressDefaultBrowserPrompt,
1044 master_prefs_->suppress_default_browser_prompt_for_version);
1047 #if defined(OS_WIN)
1048 if (!master_prefs_->welcome_page_on_os_upgrade_enabled)
1049 local_state_->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled, false);
1050 #endif
1052 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1054 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1055 // Set the product channel for crash reports.
1056 base::debug::SetCrashKeyValue(crash_keys::kChannel,
1057 chrome::GetChannelString());
1058 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1060 // Initialize tracking synchronizer system.
1061 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
1062 make_scoped_ptr(new base::DefaultTickClock()));
1064 #if defined(OS_MACOSX)
1065 // Get the Keychain API to register for distributed notifications on the main
1066 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1067 // which doesn't. This ensures those notifications will get delivered
1068 // properly. See issue 37766.
1069 // (Note that the callback mask here is empty. I don't want to register for
1070 // any callbacks, I just want to initialize the mechanism.)
1071 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1072 #endif // defined(OS_MACOSX)
1074 #if defined(OS_CHROMEOS)
1075 // Must be done after g_browser_process is constructed, before
1076 // SetupMetricsAndFieldTrials().
1077 chromeos::CrosSettings::Initialize();
1078 #endif // defined(OS_CHROMEOS)
1080 // Now the command line has been mutated based on about:flags, we can setup
1081 // metrics and initialize field trials. The field trials are needed by
1082 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1083 SetupMetricsAndFieldTrials();
1085 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1086 browser_process_->PreCreateThreads();
1088 return content::RESULT_CODE_NORMAL_EXIT;
1091 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1092 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1093 TRACK_SCOPED_REGION(
1094 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1096 result_code_ = PreMainMessageLoopRunImpl();
1098 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1099 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1102 // PreMainMessageLoopRun calls these extra stages in the following order:
1103 // PreMainMessageLoopRunImpl()
1104 // ... initial setup, including browser_process_ setup.
1105 // PreProfileInit()
1106 // ... additional setup, including CreateProfile()
1107 // PostProfileInit()
1108 // ... additional setup
1109 // PreBrowserStart()
1110 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1111 // PostBrowserStart()
1113 void ChromeBrowserMainParts::PreProfileInit() {
1114 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1116 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1117 chrome_extra_parts_[i]->PreProfileInit();
1119 #if !defined(OS_ANDROID)
1120 // Initialize the feedback uploader so it can setup notifications for profile
1121 // creation.
1122 feedback::FeedbackProfileObserver::Initialize();
1124 // Ephemeral profiles may have been left behind if the browser crashed.
1125 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1126 #endif // !defined(OS_ANDROID)
1128 #if defined(ENABLE_EXTENSIONS)
1129 javascript_dialog_extensions_client::InstallClient();
1130 #endif // defined(ENABLE_EXTENSIONS)
1132 #if !defined(OS_IOS)
1133 InstallChromeJavaScriptNativeDialogFactory();
1134 #endif // !defined(OS_IOS)
1137 void ChromeBrowserMainParts::PostProfileInit() {
1138 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1140 #if defined(OS_ANDROID)
1141 DevToolsDiscoveryProviderAndroid::Install();
1142 #else
1143 ChromeDevToolsDiscoveryProvider::Install();
1144 #endif // defined(OS_ANDROID)
1146 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1147 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1148 chrome_extra_parts_[i]->PostProfileInit();
1151 void ChromeBrowserMainParts::PreBrowserStart() {
1152 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1153 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1154 chrome_extra_parts_[i]->PreBrowserStart();
1156 three_d_observer_.reset(new ThreeDAPIObserver());
1158 // Start the out-of-memory priority manager here so that we give the most
1159 // amount of time for the other services to start up before we start
1160 // adjusting the oom priority.
1162 // On CrOS, it is always enabled. On other platforms, it's behind a flag for
1163 // now.
1164 #if defined(OS_CHROMEOS)
1165 g_browser_process->GetOomPriorityManager()->Start();
1166 #elif defined(OS_WIN) || defined(OS_MACOSX)
1167 const std::string group_name =
1168 base::FieldTrialList::FindFullName("AutomaticTabDiscarding");
1169 if (parsed_command_line().HasSwitch(switches::kEnableTabDiscarding) ||
1170 base::StartsWith(group_name, "Enabled", base::CompareCase::SENSITIVE)) {
1171 g_browser_process->GetOomPriorityManager()->Start();
1173 #endif
1176 void ChromeBrowserMainParts::PostBrowserStart() {
1177 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1178 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1179 chrome_extra_parts_[i]->PostBrowserStart();
1180 #if !defined(OS_ANDROID)
1181 // Allow ProcessSingleton to process messages.
1182 process_singleton_->Unlock();
1183 #endif // !defined(OS_ANDROID)
1184 #if defined(ENABLE_WEBRTC)
1185 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1186 // to reduce the impact on startup time.
1187 BrowserThread::PostDelayedTask(
1188 BrowserThread::UI,
1189 FROM_HERE,
1190 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1191 base::TimeDelta::FromMinutes(1));
1192 #endif // defined(ENABLE_WEBRTC)
1194 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1195 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1196 switches::kEnableWebUsbNotifications)) {
1197 webusb_browser_client_.reset(new ChromeWebUsbBrowserClient());
1198 webusb_detector_.reset(
1199 new webusb::WebUsbDetector(webusb_browser_client_.get()));
1201 #endif
1203 // At this point, StartupBrowserCreator::Start has run creating initial
1204 // browser windows and tabs, but no progress has been made in loading
1205 // content as the main message loop hasn't started processing tasks yet.
1206 // We setup to observe to the initial page load here to defer running
1207 // task posted via PostAfterStartupTask until its complete.
1208 AfterStartupTaskUtils::StartMonitoringStartup();
1211 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1212 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1213 TRACK_SCOPED_REGION(
1214 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1216 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1217 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1219 #if defined(OS_WIN)
1220 // Windows parental controls calls can be slow, so we do an early init here
1221 // that calculates this value off of the UI thread.
1222 IncognitoModePrefs::InitializePlatformParentalControls();
1223 #endif
1225 #if defined(ENABLE_EXTENSIONS)
1226 if (!variations::GetVariationParamValue(
1227 "LightSpeed", "EarlyInitStartup").empty()) {
1228 // Try to compute this early on another thread so that we don't spend time
1229 // during profile load initializing the extensions APIs.
1230 BrowserThread::PostTask(
1231 BrowserThread::FILE_USER_BLOCKING,
1232 FROM_HERE,
1233 base::Bind(
1234 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1236 #endif
1238 // Android updates the metrics service dynamically depending on whether the
1239 // application is in the foreground or not. Do not start here.
1240 #if !defined(OS_ANDROID)
1241 // Now that the file thread has been started, start recording.
1242 StartMetricsRecording();
1243 #endif // !defined(OS_ANDROID)
1245 if (!base::debug::BeingDebugged()) {
1246 // Create watchdog thread after creating all other threads because it will
1247 // watch the other threads and they must be running.
1248 browser_process_->watchdog_thread();
1251 // Do any initializating in the browser process that requires all threads
1252 // running.
1253 browser_process_->PreMainMessageLoopRun();
1255 // Record last shutdown time into a histogram.
1256 browser_shutdown::ReadLastShutdownInfo();
1258 #if defined(OS_WIN)
1259 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1260 // tasks. Those care whether the browser is already running. On Linux/Mac,
1261 // upgrade/uninstall happen separately.
1262 bool already_running = browser_util::IsBrowserAlreadyRunning();
1264 // If the command line specifies 'uninstall' then we need to work here
1265 // unless we detect another chrome browser running.
1266 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1267 return DoUninstallTasks(already_running);
1270 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1271 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1272 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1273 parsed_command_line_);
1276 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1277 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1278 #endif // defined(OS_WIN)
1280 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1281 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1282 prefs::kDefaultBrowserSettingEnabled);
1283 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1284 prefs::kDefaultBrowserSettingEnabled)) {
1285 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1288 return ShellIntegration::SetAsDefaultBrowser() ?
1289 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1290 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1293 #if defined(USE_AURA)
1294 // Make sure aura::Env has been initialized.
1295 CHECK(aura::Env::GetInstance());
1296 #endif // defined(USE_AURA)
1298 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1299 #if !defined(OS_ANDROID)
1300 // If the command line specifies --pack-extension, attempt the pack extension
1301 // startup action and exit.
1302 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1303 extensions::StartupHelper extension_startup_helper;
1304 if (extension_startup_helper.PackExtension(parsed_command_line()))
1305 return content::RESULT_CODE_NORMAL_EXIT;
1306 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1309 // When another process is running, use that process instead of starting a
1310 // new one. NotifyOtherProcess will currently give the other process up to
1311 // 20 seconds to respond. Note that this needs to be done before we attempt
1312 // to read the profile.
1313 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1314 switch (notify_result_) {
1315 case ProcessSingleton::PROCESS_NONE:
1316 // No process already running, fall through to starting a new one.
1317 break;
1319 case ProcessSingleton::PROCESS_NOTIFIED:
1320 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1321 // On POSIX systems, print a message notifying the process is running.
1322 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1323 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1324 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1326 // Having a differentiated return type for testing allows for tests to
1327 // verify proper handling of some switches. When not testing, stick to
1328 // the standard Unix convention of returning zero when things went as
1329 // expected.
1330 if (parsed_command_line().HasSwitch(switches::kTestType))
1331 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1332 return content::RESULT_CODE_NORMAL_EXIT;
1334 case ProcessSingleton::PROFILE_IN_USE:
1335 return chrome::RESULT_CODE_PROFILE_IN_USE;
1337 case ProcessSingleton::LOCK_ERROR:
1338 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1339 "directory. This means that running multiple instances "
1340 "would start multiple browser processes rather than "
1341 "opening a new window in the existing process. Aborting "
1342 "now to avoid profile corruption.";
1343 return chrome::RESULT_CODE_PROFILE_IN_USE;
1345 default:
1346 NOTREACHED();
1348 #endif // !defined(OS_ANDROID)
1350 // Handle special early return paths (which couldn't be processed even earlier
1351 // as they require the process singleton to be held) first.
1353 std::string try_chrome =
1354 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1355 if (!try_chrome.empty()) {
1356 #if defined(OS_WIN)
1357 // Setup.exe has determined that we need to run a retention experiment
1358 // and has lauched chrome to show the experiment UI. It is guaranteed that
1359 // no other Chrome is currently running as the process singleton was
1360 // sucessfully grabbed above.
1361 int try_chrome_int;
1362 base::StringToInt(try_chrome, &try_chrome_int);
1363 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1364 try_chrome_int,
1365 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1366 base::Unretained(process_singleton_.get())));
1367 if (answer == TryChromeDialogView::NOT_NOW)
1368 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1369 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1370 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1371 // At this point the user is willing to try chrome again.
1372 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1373 // Only set in the unattended case, the interactive case is Windows 8.
1374 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1375 ShellIntegration::SET_DEFAULT_UNATTENDED)
1376 ShellIntegration::SetAsDefaultBrowser();
1378 #else
1379 // We don't support retention experiments on Mac or Linux.
1380 return content::RESULT_CODE_NORMAL_EXIT;
1381 #endif // defined(OS_WIN)
1384 #if defined(OS_WIN)
1385 // Do the tasks if chrome has been upgraded while it was last running.
1386 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1387 return content::RESULT_CODE_NORMAL_EXIT;
1389 // Check if there is any machine level Chrome installed on the current
1390 // machine. If yes and the current Chrome process is user level, we do not
1391 // allow the user level Chrome to run. So we notify the user and uninstall
1392 // user level Chrome.
1393 // Note this check needs to happen here (after the process singleton was
1394 // obtained but before potentially creating the first run sentinel).
1395 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1396 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1397 #endif // defined(OS_WIN)
1399 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1400 if (sxs_linux::ShouldMigrateUserDataDir())
1401 return sxs_linux::MigrateUserDataDir();
1402 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1404 // Desktop construction occurs here, (required before profile creation).
1405 PreProfileInit();
1407 // Profile creation ----------------------------------------------------------
1409 metrics::MetricsService::SetExecutionPhase(
1410 metrics::MetricsService::CREATE_PROFILE,
1411 g_browser_process->local_state());
1413 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1414 base::TimeTicks::Now() - start_time_step1);
1416 // This step is costly and is already measured in Startup.CreateFirstProfile
1417 // and more directly Profile.CreateAndInitializeProfile.
1418 profile_ = CreatePrimaryProfile(parameters(),
1419 user_data_dir_,
1420 parsed_command_line());
1421 if (!profile_)
1422 return content::RESULT_CODE_NORMAL_EXIT;
1424 #if !defined(OS_ANDROID)
1425 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1426 // The first run sentinel must be created after the process singleton was
1427 // grabbed and no early return paths were otherwise hit above.
1428 first_run::CreateSentinelIfNeeded();
1429 #endif // !defined(OS_ANDROID)
1431 #if defined(ENABLE_BACKGROUND)
1432 // Autoload any profiles which are running background apps.
1433 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1434 browser_process_->profile_manager()->AutoloadProfiles();
1435 #endif // defined(ENABLE_BACKGROUND)
1436 // Post-profile init ---------------------------------------------------------
1438 TranslateService::Initialize();
1440 // Needs to be done before PostProfileInit, since login manager on CrOS is
1441 // called inside PostProfileInit.
1442 content::WebUIControllerFactory::RegisterFactory(
1443 ChromeWebUIControllerFactory::GetInstance());
1445 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1446 // So make sure to create it before that.
1447 #if !defined(DISABLE_NACL)
1448 NaClBrowserDelegateImpl* delegate =
1449 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1450 nacl::NaClBrowser::SetDelegate(delegate);
1451 #endif // !defined(DISABLE_NACL)
1453 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1454 // (requires supporting early exit).
1455 PostProfileInit();
1457 // Retrieve cached GL strings from local state and use them for GPU
1458 // blacklist decisions.
1459 if (g_browser_process->gl_string_manager())
1460 g_browser_process->gl_string_manager()->Initialize();
1462 // Create an instance of GpuModeManager to watch gpu mode pref change.
1463 g_browser_process->gpu_mode_manager();
1465 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1466 // Show the First Run UI if this is the first time Chrome has been run on
1467 // this computer, or we're being compelled to do so by a command line flag.
1468 // Note that this be done _after_ the PrefService is initialized and all
1469 // preferences are registered, since some of the code that the importer
1470 // touches reads preferences.
1471 if (first_run::IsChromeFirstRun()) {
1472 first_run::AutoImport(profile_,
1473 master_prefs_->homepage_defined,
1474 master_prefs_->do_import_items,
1475 master_prefs_->dont_import_items,
1476 master_prefs_->import_bookmarks_path);
1478 // Note: this can pop the first run consent dialog on linux.
1479 first_run::DoPostImportTasks(profile_,
1480 master_prefs_->make_chrome_default_for_user);
1482 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1483 browser_creator_->set_show_main_browser_window(
1484 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1485 } else {
1486 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1489 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1491 #if defined(OS_WIN)
1492 // Sets things up so that if we crash from this point on, a dialog will
1493 // popup asking the user to restart chrome. It is done this late to avoid
1494 // testing against a bunch of special cases that are taken care early on.
1495 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1496 parsed_command_line());
1498 // Registers Chrome with the Windows Restart Manager, which will restore the
1499 // Chrome session when the computer is restarted after a system update.
1500 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1501 // but should run on startup if extended to handle crashes/hangs/patches.
1502 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1503 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1504 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1505 parsed_command_line());
1508 // Verify that the profile is not on a network share and if so prepare to show
1509 // notification to the user.
1510 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1511 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1512 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1513 profile_->GetPath()));
1515 #endif // defined(OS_WIN)
1517 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1518 // Init the RLZ library. This just binds the dll and schedules a task on the
1519 // file thread to be run sometime later. If this is the first run we record
1520 // the installation event.
1521 PrefService* pref_service = profile_->GetPrefs();
1522 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1523 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1524 // Negative ping delay means to send ping immediately after a first search is
1525 // recorded.
1526 rlz::RLZTracker::SetRlzDelegate(
1527 make_scoped_ptr(new ChromeRLZTrackerDelegate));
1528 rlz::RLZTracker::InitRlzDelayed(
1529 first_run::IsChromeFirstRun(), ping_delay < 0,
1530 base::TimeDelta::FromMilliseconds(abs(ping_delay)),
1531 ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
1532 ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
1533 ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
1534 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1536 // Configure modules that need access to resources.
1537 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1539 // In unittest mode, this will do nothing. In normal mode, this will create
1540 // the global IntranetRedirectDetector instance, which will promptly go to
1541 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1542 // to see if it should do anything else.
1544 // A simpler way of doing all this would be to have some function which could
1545 // give the time elapsed since startup, and simply have this object check that
1546 // when asked to initialize itself, but this doesn't seem to exist.
1548 // This can't be created in the BrowserProcessImpl constructor because it
1549 // needs to read prefs that get set after that runs.
1550 browser_process_->intranet_redirect_detector();
1551 GoogleSearchCounter::RegisterForNotifications();
1553 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1554 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1555 base::FilePath path =
1556 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1557 printing::PrintedDocument::set_debug_dump_path(path);
1559 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1561 HandleTestParameters(parsed_command_line());
1562 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1563 base::debug::BeingDebugged());
1565 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1566 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1567 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1568 browser_process_->GetApplicationLocale());
1570 // Start watching for hangs during startup. We disarm this hang detector when
1571 // ThreadWatcher takes over or when browser is shutdown or when
1572 // startup_watcher_ is deleted.
1573 metrics::MetricsService::SetExecutionPhase(
1574 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1575 g_browser_process->local_state());
1576 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1578 // On mobile, need for clean shutdown arises only when the application comes
1579 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1580 // http://crbug.com/179143
1581 #if !defined(OS_ANDROID)
1582 // Start watching for a hang.
1583 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1584 #endif // !defined(OS_ANDROID)
1586 #if defined(ENABLE_PRINT_PREVIEW)
1587 // Create the instance of the cloud print proxy service so that it can launch
1588 // the service process if needed. This is needed because the service process
1589 // might have shutdown because an update was available.
1590 // TODO(torne): this should maybe be done with
1591 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1592 // instead?
1593 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1594 #endif // defined(ENABLE_PRINT_PREVIEW)
1596 // Start watching all browser threads for responsiveness.
1597 metrics::MetricsService::SetExecutionPhase(
1598 metrics::MetricsService::THREAD_WATCHER_START,
1599 g_browser_process->local_state());
1600 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1602 #if defined(OS_ANDROID)
1603 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1604 #endif // defined(OS_ANDROID)
1606 #if !defined(DISABLE_NACL)
1607 BrowserThread::PostTask(
1608 BrowserThread::IO,
1609 FROM_HERE,
1610 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1611 #endif // !defined(DISABLE_NACL)
1613 // Make sure initial prefs are recorded
1614 PrefMetricsService::Factory::GetForProfile(profile_);
1616 PreBrowserStart();
1618 // Instantiate the notification UI manager, as this triggers a perf timer
1619 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1620 // triggering the timer and call that explicitly in the approprate place.
1621 // http://crbug.com/105065.
1622 browser_process_->notification_ui_manager();
1624 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1625 // data source is based on the Component Updater.
1626 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1628 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1629 RegisterComponentsForUpdate();
1631 #if defined(OS_ANDROID)
1632 variations::VariationsService* variations_service =
1633 browser_process_->variations_service();
1634 if (variations_service) {
1635 // Just initialize the policy prefs service here. Variations seed fetching
1636 // will be initialized when the app enters foreground mode.
1637 variations_service->set_policy_pref_service(profile_->GetPrefs());
1639 translate::TranslateDownloadManager::RequestLanguageList(
1640 profile_->GetPrefs());
1642 #else
1643 // Most general initialization is behind us, but opening a
1644 // tab and/or session restore and such is still to be done.
1645 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1647 // We are in regular browser boot sequence. Open initial tabs and enter the
1648 // main message loop.
1649 std::vector<Profile*> last_opened_profiles;
1650 #if !defined(OS_CHROMEOS)
1651 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1652 // them this early as the cryptohome hasn't yet been mounted (which happens
1653 // only once we log in).
1654 last_opened_profiles =
1655 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1656 #endif // defined(OS_CHROMEOS)
1658 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1659 base::TimeTicks::Now() - start_time_step2);
1661 // This step is costly and is already measured in
1662 // Startup.StartupBrowserCreator_Start.
1663 const bool started = browser_creator_->Start(
1664 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1665 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1666 if (started) {
1667 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1668 // Initialize autoupdate timer. Timer callback costs basically nothing
1669 // when browser is not in persistent mode, so it's OK to let it ride on
1670 // the main thread. This needs to be done here because we don't want
1671 // to start the timer when Chrome is run inside a test harness.
1672 browser_process_->StartAutoupdateTimer();
1673 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1675 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1676 // On Linux, the running exe will be updated if an upgrade becomes
1677 // available while the browser is running. We need to save the last
1678 // modified time of the exe, so we can compare to determine if there is
1679 // an upgrade while the browser is kept alive by a persistent extension.
1680 upgrade_util::SaveLastModifiedTimeOfExe();
1681 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1683 // Record now as the last successful chrome start.
1684 GoogleUpdateSettings::SetLastRunTime();
1686 #if defined(OS_MACOSX)
1687 // Call Recycle() here as late as possible, before going into the loop
1688 // because Start() will add things to it while creating the main window.
1689 if (parameters().autorelease_pool)
1690 parameters().autorelease_pool->Recycle();
1691 #endif // defined(OS_MACOSX)
1693 const base::TimeDelta delta = base::TimeTicks::Now() - browser_open_start;
1694 startup_metric_utils::RecordBrowserOpenTabsDelta(delta);
1696 // If we're running tests (ui_task is non-null), then we don't want to
1697 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1698 // RequestLanguageList
1699 if (parameters().ui_task == NULL) {
1700 // Request new variations seed information from server.
1701 variations::VariationsService* variations_service =
1702 browser_process_->variations_service();
1703 if (variations_service)
1704 variations_service->PerformPreMainMessageLoopStartup();
1706 translate::TranslateDownloadManager::RequestLanguageList(
1707 profile_->GetPrefs());
1710 run_message_loop_ = started;
1711 browser_creator_.reset();
1713 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1714 if (g_browser_process->metrics_service()->reporting_active())
1715 content::StartPowerUsageMonitor();
1716 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1718 process_power_collector_.reset(new ProcessPowerCollector);
1719 process_power_collector_->Initialize();
1720 #endif // !defined(OS_ANDROID)
1722 PostBrowserStart();
1724 if (parameters().ui_task) {
1725 parameters().ui_task->Run();
1726 delete parameters().ui_task;
1727 run_message_loop_ = false;
1729 #if defined(OS_ANDROID)
1730 // We never run the C++ main loop on Android, since the UI thread message
1731 // loop is controlled by the OS, so this is as close as we can get to
1732 // the start of the main loop.
1733 if (result_code_ <= 0) {
1734 RecordBrowserStartupTime();
1736 #endif // defined(OS_ANDROID)
1738 #if !defined(OS_ANDROID)
1739 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1740 base::TimeTicks::Now() - start_time_step3);
1741 #endif // !defined(OS_ANDROID)
1743 return result_code_;
1746 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1747 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1748 #if defined(OS_ANDROID)
1749 // Chrome on Android does not use default MessageLoop. It has its own
1750 // Android specific MessageLoop
1751 NOTREACHED();
1752 return true;
1753 #else
1754 // Set the result code set in PreMainMessageLoopRun or set above.
1755 *result_code = result_code_;
1756 if (!run_message_loop_)
1757 return true; // Don't run the default message loop.
1759 // These should be invoked as close to the start of the browser's
1760 // UI thread message loop as possible to get a stable measurement
1761 // across versions.
1762 RecordBrowserStartupTime();
1764 DCHECK(base::MessageLoopForUI::IsCurrent());
1765 base::RunLoop run_loop;
1767 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1769 metrics::MetricsService::SetExecutionPhase(
1770 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1771 g_browser_process->local_state());
1772 run_loop.Run();
1774 return true;
1775 #endif // defined(OS_ANDROID)
1778 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1779 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1780 #if defined(OS_ANDROID)
1781 // Chrome on Android does not use default MessageLoop. It has its own
1782 // Android specific MessageLoop
1783 NOTREACHED();
1784 #else
1785 // Start watching for jank during shutdown. It gets disarmed when
1786 // |shutdown_watcher_| object is destructed.
1787 metrics::MetricsService::SetExecutionPhase(
1788 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1789 g_browser_process->local_state());
1790 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1792 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1793 startup_watcher_->Disarm();
1795 // Remove observers attached to D-Bus clients before DbusThreadManager is
1796 // shut down.
1797 process_power_collector_.reset();
1799 #if !defined(OS_IOS)
1800 webusb_detector_.reset();
1801 webusb_browser_client_.reset();
1802 #endif
1804 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1805 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1807 // Some tests don't set parameters.ui_task, so they started translate
1808 // language fetch that was never completed so we need to cleanup here
1809 // otherwise it will be done by the destructor in a wrong thread.
1810 TranslateService::Shutdown(parameters().ui_task == NULL);
1812 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1813 process_singleton_->Cleanup();
1815 // Stop all tasks that might run on WatchDogThread.
1816 ThreadWatcherList::StopWatchingAll();
1818 browser_process_->metrics_service()->Stop();
1820 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1821 browser_process_->StartTearDown();
1822 #endif // defined(OS_ANDROID)
1825 void ChromeBrowserMainParts::PostDestroyThreads() {
1826 #if defined(OS_ANDROID)
1827 // On Android, there is no quit/exit. So the browser's main message loop will
1828 // not finish.
1829 NOTREACHED();
1830 #else
1831 browser_process_->PostDestroyThreads();
1832 // browser_shutdown takes care of deleting browser_process, so we need to
1833 // release it.
1834 ignore_result(browser_process_.release());
1835 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1836 master_prefs_.reset();
1837 process_singleton_.reset();
1838 device_event_log::Shutdown();
1840 // We need to do this check as late as possible, but due to modularity, this
1841 // may be the last point in Chrome. This would be more effective if done at
1842 // a higher level on the stack, so that it is impossible for an early return
1843 // to bypass this code. Perhaps we need a *final* hook that is called on all
1844 // paths from content/browser/browser_main.
1845 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1847 #if defined(OS_CHROMEOS)
1848 chromeos::CrosSettings::Shutdown();
1849 #endif // defined(OS_CHROMEOS)
1850 #endif // defined(OS_ANDROID)
1853 // Public members:
1855 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1856 chrome_extra_parts_.push_back(parts);