Add a webstorePrivate API to show a permission prompt for delegated bundle installs
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main.cc
blob985781d1ab4d3803b6937aaecb8f102f89c30d66
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/metrics/field_trial_synchronizer.h"
65 #include "chrome/browser/metrics/metrics_services_manager.h"
66 #include "chrome/browser/metrics/thread_watcher.h"
67 #include "chrome/browser/metrics/variations/variations_service.h"
68 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
69 #include "chrome/browser/net/chrome_net_log.h"
70 #include "chrome/browser/net/crl_set_fetcher.h"
71 #include "chrome/browser/notifications/desktop_notification_service.h"
72 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
73 #include "chrome/browser/performance_monitor/performance_monitor.h"
74 #include "chrome/browser/plugins/plugin_prefs.h"
75 #include "chrome/browser/power/process_power_collector.h"
76 #include "chrome/browser/pref_service_flags_storage.h"
77 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
78 #include "chrome/browser/prefs/command_line_pref_store.h"
79 #include "chrome/browser/prefs/incognito_mode_prefs.h"
80 #include "chrome/browser/prefs/pref_metrics_service.h"
81 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
82 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
83 #include "chrome/browser/process_singleton.h"
84 #include "chrome/browser/profiles/profile.h"
85 #include "chrome/browser/profiles/profile_manager.h"
86 #include "chrome/browser/profiles/profiles_state.h"
87 #include "chrome/browser/shell_integration.h"
88 #include "chrome/browser/tracing/navigation_tracing.h"
89 #include "chrome/browser/translate/translate_service.h"
90 #include "chrome/browser/ui/app_list/app_list_service.h"
91 #include "chrome/browser/ui/browser.h"
92 #include "chrome/browser/ui/browser_finder.h"
93 #include "chrome/browser/ui/host_desktop.h"
94 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
95 #include "chrome/browser/ui/startup/default_browser_prompt.h"
96 #include "chrome/browser/ui/startup/startup_browser_creator.h"
97 #include "chrome/browser/ui/uma_browsing_activity_observer.h"
98 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.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/chrome_version_info.h"
104 #include "chrome/common/crash_keys.h"
105 #include "chrome/common/env_vars.h"
106 #include "chrome/common/logging_chrome.h"
107 #include "chrome/common/net/net_resource_provider.h"
108 #include "chrome/common/pref_names.h"
109 #include "chrome/common/profiling.h"
110 #include "chrome/common/variations/variations_util.h"
111 #include "chrome/grit/generated_resources.h"
112 #include "chrome/installer/util/google_update_settings.h"
113 #include "components/component_updater/component_updater_service.h"
114 #include "components/device_event_log/device_event_log.h"
115 #include "components/google/core/browser/google_util.h"
116 #include "components/language_usage_metrics/language_usage_metrics.h"
117 #include "components/metrics/call_stack_profile_metrics_provider.h"
118 #include "components/metrics/metrics_service.h"
119 #include "components/metrics/profiler/tracking_synchronizer.h"
120 #include "components/nacl/browser/nacl_browser.h"
121 #include "components/rappor/rappor_service.h"
122 #include "components/signin/core/common/profile_management_switches.h"
123 #include "components/startup_metric_utils/startup_metric_utils.h"
124 #include "components/translate/content/browser/browser_cld_utils.h"
125 #include "components/translate/content/common/cld_data_source.h"
126 #include "components/translate/core/browser/translate_download_manager.h"
127 #include "components/variations/net/variations_http_header_provider.h"
128 #include "components/variations/variations_associated_data.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 #else
155 #include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
156 #include "chrome/browser/feedback/feedback_profile_observer.h"
157 #endif // defined(OS_ANDROID)
159 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
160 #include "chrome/browser/first_run/upgrade_util_linux.h"
161 #include "chrome/browser/sxs_linux.h"
162 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
164 #if defined(OS_CHROMEOS)
165 #include "chrome/browser/chromeos/settings/cros_settings.h"
166 #include "chromeos/chromeos_switches.h"
167 #include "chromeos/settings/cros_settings_names.h"
168 #endif // defined(OS_CHROMEOS)
170 // TODO(port): several win-only methods have been pulled out of this, but
171 // BrowserMain() as a whole needs to be broken apart so that it's usable by
172 // other platforms. For now, it's just a stub. This is a serious work in
173 // progress and should not be taken as an indication of a real refactoring.
175 #if defined(OS_WIN)
176 #include "base/environment.h" // For PreRead experiment.
177 #include "base/win/windows_version.h"
178 #include "chrome/browser/browser_util_win.h"
179 #include "chrome/browser/chrome_browser_main_win.h"
180 #include "chrome/browser/chrome_select_file_dialog_factory_win.h"
181 #include "chrome/browser/component_updater/caps_installer_win.h"
182 #include "chrome/browser/component_updater/sw_reporter_installer_win.h"
183 #include "chrome/browser/first_run/try_chrome_dialog_view.h"
184 #include "chrome/browser/first_run/upgrade_util_win.h"
185 #include "chrome/browser/ui/network_profile_bubble.h"
186 #include "chrome/installer/util/helper.h"
187 #include "chrome/installer/util/install_util.h"
188 #include "chrome/installer/util/shell_util.h"
189 #include "components/browser_watcher/exit_funnel_win.h"
190 #include "net/base/net_util.h"
191 #include "ui/base/l10n/l10n_util_win.h"
192 #include "ui/gfx/win/dpi.h"
193 #include "ui/shell_dialogs/select_file_dialog.h"
194 #endif // defined(OS_WIN)
196 #if defined(OS_MACOSX)
197 #include <Security/Security.h>
199 #include "base/mac/scoped_nsautorelease_pool.h"
200 #include "chrome/browser/mac/keystone_glue.h"
201 #endif // defined(OS_MACOSX)
203 #if !defined(OS_IOS)
204 #include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
205 #endif // !defined(OS_IOS)
207 #if !defined(DISABLE_NACL)
208 #include "chrome/browser/component_updater/pnacl_component_installer.h"
209 #include "components/nacl/browser/nacl_process_host.h"
210 #endif // !defined(DISABLE_NACL)
212 #if defined(ENABLE_EXTENSIONS)
213 #include "chrome/browser/extensions/startup_helper.h"
214 #include "extensions/browser/extension_protocols.h"
215 #include "extensions/common/features/feature_provider.h"
216 #include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
217 #endif // defined(ENABLE_EXTENSIONS)
219 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
220 #include "printing/printed_document.h"
221 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
223 #if defined(ENABLE_RLZ)
224 #include "chrome/browser/rlz/rlz.h"
225 #endif // defined(ENABLE_RLZ)
227 #if defined(ENABLE_WEBRTC)
228 #include "chrome/browser/media/webrtc_log_util.h"
229 #endif // defined(ENABLE_WEBRTC)
231 #if defined(USE_AURA)
232 #include "ui/aura/env.h"
233 #endif // defined(USE_AURA)
235 using content::BrowserThread;
237 namespace {
239 // This function provides some ways to test crash and assertion handling
240 // behavior of the program.
241 void HandleTestParameters(const base::CommandLine& command_line) {
242 // This parameter causes a null pointer crash (crash reporter trigger).
243 if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
244 int* bad_pointer = NULL;
245 *bad_pointer = 0;
249 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
250 void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
251 const std::vector<GURL>& new_tabs) {
252 for (std::vector<GURL>::const_iterator it = new_tabs.begin();
253 it != new_tabs.end(); ++it) {
254 if (it->is_valid())
255 browser_creator->AddFirstRunTab(*it);
258 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
260 // Returns the new local state object, guaranteed non-NULL.
261 // |local_state_task_runner| must be a shutdown-blocking task runner.
262 PrefService* InitializeLocalState(
263 base::SequencedTaskRunner* local_state_task_runner,
264 const base::CommandLine& parsed_command_line) {
265 TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
267 // Load local state. This includes the application locale so we know which
268 // locale dll to load. This also causes local state prefs to be registered.
269 PrefService* local_state = g_browser_process->local_state();
270 DCHECK(local_state);
272 #if defined(OS_WIN)
273 if (first_run::IsChromeFirstRun()) {
274 // During first run we read the google_update registry key to find what
275 // language the user selected when downloading the installer. This
276 // becomes our default language in the prefs.
277 // Other platforms obey the system locale.
278 base::string16 install_lang;
279 if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
280 local_state->SetString(prefs::kApplicationLocale,
281 base::UTF16ToASCII(install_lang));
284 #endif // defined(OS_WIN)
286 // If the local state file for the current profile doesn't exist and the
287 // parent profile command line flag is present, then we should inherit some
288 // local state from the parent profile.
289 // Checking that the local state file for the current profile doesn't exist
290 // is the most robust way to determine whether we need to inherit or not
291 // since the parent profile command line flag can be present even when the
292 // current profile is not a new one, and in that case we do not want to
293 // inherit and reset the user's setting.
295 // TODO(mnissler): We should probably just instantiate a
296 // JSONPrefStore here instead of an entire PrefService. Once this is
297 // addressed, the call to browser_prefs::RegisterLocalState can move
298 // to chrome_prefs::CreateLocalState.
299 if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
300 base::FilePath local_state_path;
301 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
302 bool local_state_file_exists = base::PathExists(local_state_path);
303 if (!local_state_file_exists) {
304 base::FilePath parent_profile =
305 parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
306 scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
307 scoped_ptr<PrefService> parent_local_state(
308 chrome_prefs::CreateLocalState(
309 parent_profile,
310 local_state_task_runner,
311 g_browser_process->policy_service(),
312 registry,
313 false));
314 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
315 // Right now, we only inherit the locale setting from the parent profile.
316 local_state->SetString(
317 prefs::kApplicationLocale,
318 parent_local_state->GetString(prefs::kApplicationLocale));
322 #if defined(OS_CHROMEOS)
323 if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
324 std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
325 // Ensure that we start with owner's locale.
326 if (!owner_locale.empty() &&
327 local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
328 !local_state->IsManagedPreference(prefs::kApplicationLocale)) {
329 local_state->SetString(prefs::kApplicationLocale, owner_locale);
332 #endif // defined(OS_CHROMEOS)
334 return local_state;
337 // Initializes the primary profile, possibly doing some user prompting to pick
338 // a fallback profile. Returns the newly created profile, or NULL if startup
339 // should not continue.
340 Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
341 const base::FilePath& user_data_dir,
342 const base::CommandLine& parsed_command_line) {
343 TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
344 TRACK_SCOPED_REGION(
345 "Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
347 base::Time start = base::Time::Now();
348 if (profiles::IsMultipleProfilesEnabled() &&
349 parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
350 profiles::SetLastUsedProfile(
351 parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
352 // Clear kProfilesLastActive since the user only wants to launch a specific
353 // profile.
354 ListPrefUpdate update(g_browser_process->local_state(),
355 prefs::kProfilesLastActive);
356 base::ListValue* profile_list = update.Get();
357 profile_list->Clear();
360 Profile* profile = NULL;
361 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
362 // On ChromeOS and Android the ProfileManager will use the same path as the
363 // one we got passed. GetActiveUserProfile will therefore use the correct path
364 // automatically.
365 DCHECK_EQ(user_data_dir.value(),
366 g_browser_process->profile_manager()->user_data_dir().value());
367 profile = ProfileManager::GetActiveUserProfile();
368 #else
369 base::FilePath profile_path =
370 GetStartupProfilePath(user_data_dir, parsed_command_line);
372 // Without NewAvatarMenu, replace guest with any existing profile.
373 if (!switches::IsNewAvatarMenu() &&
374 profile_path == ProfileManager::GetGuestProfilePath()) {
375 profile_path = g_browser_process->profile_manager()->GetProfileInfoCache().
376 GetPathOfProfileAtIndex(0);
378 profile = g_browser_process->profile_manager()->GetProfile(
379 profile_path);
381 // If we're using the --new-profile-management flag and this profile is
382 // signed out, then we should show the user manager instead. By switching
383 // the active profile to the guest profile we ensure that no
384 // browser windows will be opened for the guest profile.
385 if (switches::IsNewProfileManagement() &&
386 profile &&
387 !profile->IsGuestSession()) {
388 ProfileInfoCache& cache =
389 g_browser_process->profile_manager()->GetProfileInfoCache();
390 size_t profile_index = cache.GetIndexOfProfileWithPath(profile_path);
392 if (profile_index != std::string::npos &&
393 cache.ProfileIsSigninRequiredAtIndex(profile_index)) {
394 profile = g_browser_process->profile_manager()->GetProfile(
395 ProfileManager::GetGuestProfilePath());
398 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
399 if (profile) {
400 UMA_HISTOGRAM_LONG_TIMES(
401 "Startup.CreateFirstProfile", base::Time::Now() - start);
402 return profile;
405 #if !defined(OS_WIN)
406 // TODO(port): fix this. See comments near the definition of
407 // user_data_dir. It is better to CHECK-fail here than it is to
408 // silently exit because of missing code in the above test.
409 CHECK(profile) << "Cannot get default profile.";
410 #endif // !defined(OS_WIN)
412 return NULL;
415 #if defined(OS_MACOSX)
416 OSStatus KeychainCallback(SecKeychainEvent keychain_event,
417 SecKeychainCallbackInfo* info, void* context) {
418 return noErr;
420 #endif // defined(OS_MACOSX)
422 void RegisterComponentsForUpdate() {
423 component_updater::ComponentUpdateService* cus =
424 g_browser_process->component_updater();
426 // Registration can be before or after cus->Start() so it is ok to post
427 // a task to the UI thread to do registration once you done the necessary
428 // file IO to know you existing component version.
429 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
430 RegisterRecoveryComponent(cus, g_browser_process->local_state());
431 RegisterPepperFlashComponent(cus);
432 RegisterSwiftShaderComponent(cus);
433 RegisterWidevineCdmComponent(cus);
434 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
436 #if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
437 #if defined(OS_CHROMEOS)
438 // PNaCl on Chrome OS is on rootfs and there is no need to download it. But
439 // Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
440 // installer when running on Linux. See crbug.com/422121 for more details.
441 if (!base::SysInfo::IsRunningOnChromeOS())
442 #endif // defined(OS_CHROMEOS)
443 g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
444 #endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
446 // Registration of the CLD Component is a no-op unless the CLD data source has
447 // been configured to be the "Component" data source.
448 RegisterCldComponent(cus);
450 component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
451 g_browser_process->supervised_user_whitelist_installer();
452 whitelist_installer->RegisterComponents();
454 base::FilePath path;
455 if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
456 #if defined(OS_ANDROID)
457 // The CRLSet component was enabled for some releases. This code attempts to
458 // delete it from the local disk of those how may have downloaded it.
459 g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
460 #elif !defined(OS_CHROMEOS)
461 // CRLSetFetcher attempts to load a CRL set from either the local disk or
462 // network.
463 // For Chrome OS this registration is delayed until user login.
464 g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
465 // Registration of the EV Whitelist component here is not necessary for:
466 // 1. Android: Because it currently does not have the EV indicator.
467 // 2. Chrome OS: On Chrome OS this registration is delayed until user login.
468 RegisterEVWhitelistComponent(cus, path);
469 #endif // defined(OS_ANDROID)
472 #if defined(OS_WIN)
473 #if defined(GOOGLE_CHROME_BUILD)
474 RegisterSwReporterComponent(cus, g_browser_process->local_state());
475 #endif // defined(GOOGLE_CHROME_BUILD)
476 RegisterCAPSComponent(cus);
477 #endif // defined(OS_WIN)
480 #if !defined(OS_ANDROID)
481 bool ProcessSingletonNotificationCallback(
482 const base::CommandLine& command_line,
483 const base::FilePath& current_directory) {
484 // Drop the request if the browser process is already in shutdown path.
485 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
486 #if defined(OS_WIN)
487 browser_watcher::ExitFunnel::RecordSingleEvent(
488 chrome::kBrowserExitCodesRegistryPath,
489 L"ProcessSingletonIsShuttingDown");
490 #endif // defined(OS_WIN)
492 return false;
495 if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
496 std::string start_time_string =
497 command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
498 int64 remote_start_time;
499 if (base::StringToInt64(start_time_string, &remote_start_time)) {
500 base::TimeDelta elapsed =
501 base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
502 if (command_line.HasSwitch(switches::kFastStart)) {
503 UMA_HISTOGRAM_LONG_TIMES(
504 "Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
505 } else {
506 UMA_HISTOGRAM_LONG_TIMES(
507 "Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
512 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
513 command_line);
515 base::FilePath user_data_dir =
516 g_browser_process->profile_manager()->user_data_dir();
517 base::FilePath startup_profile_dir =
518 GetStartupProfilePath(user_data_dir, command_line);
520 StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
521 command_line, current_directory, startup_profile_dir);
522 return true;
524 #endif // !defined(OS_ANDROID)
526 void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
527 if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
528 std::string port_str =
529 command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
530 int port;
531 if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
532 g_browser_process->CreateDevToolsHttpProtocolHandler(
533 chrome::HOST_DESKTOP_TYPE_NATIVE,
534 "127.0.0.1",
535 static_cast<uint16>(port));
536 } else {
537 DLOG(WARNING) << "Invalid http debugger port number " << port;
542 } // namespace
544 namespace chrome_browser {
546 // This error message is not localized because we failed to load the
547 // localization data files.
548 #if defined(OS_WIN)
549 const char kMissingLocaleDataTitle[] = "Missing File Error";
550 #endif // defined(OS_WIN)
552 #if defined(OS_WIN)
553 // TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
554 const char kMissingLocaleDataMessage[] =
555 "Unable to find locale data files. Please reinstall.";
556 #endif // defined(OS_WIN)
558 } // namespace chrome_browser
560 // BrowserMainParts ------------------------------------------------------------
562 ChromeBrowserMainParts::ChromeBrowserMainParts(
563 const content::MainFunctionParams& parameters)
564 : parameters_(parameters),
565 parsed_command_line_(parameters.command_line),
566 result_code_(content::RESULT_CODE_NORMAL_EXIT),
567 startup_watcher_(new StartupTimeBomb()),
568 shutdown_watcher_(new ShutdownWatcherHelper()),
569 browser_field_trials_(parameters.command_line),
570 profile_(NULL),
571 run_message_loop_(true),
572 notify_result_(ProcessSingleton::PROCESS_NONE),
573 local_state_(NULL),
574 restart_last_session_(false) {
575 // If we're running tests (ui_task is non-null).
576 if (parameters.ui_task)
577 browser_defaults::enable_help_app = false;
579 // Chrome disallows cookies by default. All code paths that want to use
580 // cookies need to go through one of Chrome's URLRequestContexts which have
581 // a ChromeNetworkDelegate attached that selectively allows cookies again.
582 net::URLRequest::SetDefaultCookiePolicyToBlock();
585 ChromeBrowserMainParts::~ChromeBrowserMainParts() {
586 for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
587 delete chrome_extra_parts_[i];
588 chrome_extra_parts_.clear();
591 // This will be called after the command-line has been mutated by about:flags
592 void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
593 TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
594 // Must initialize metrics after labs have been converted into switches,
595 // but before field trials are set up (so that client ID is available for
596 // one-time randomized field trials).
598 // Initialize FieldTrialList to support FieldTrials that use one-time
599 // randomization.
600 metrics::MetricsService* metrics = browser_process_->metrics_service();
601 field_trial_list_.reset(
602 new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
604 const base::CommandLine* command_line =
605 base::CommandLine::ForCurrentProcess();
606 if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
607 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
608 base::FieldTrial::EnableBenchmarking();
611 if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
612 bool result = chrome_variations::AssociateParamsFromString(
613 command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
614 CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
615 << " list specified.";
618 // Ensure any field trials specified on the command line are initialized.
619 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
620 std::set<std::string> unforceable_field_trials;
621 #if defined(OFFICIAL_BUILD)
622 unforceable_field_trials.insert("SettingsEnforcement");
623 #endif // defined(OFFICIAL_BUILD)
625 // Create field trials without activating them, so that this behaves in a
626 // consistent manner with field trials created from the server.
627 bool result = base::FieldTrialList::CreateTrialsFromString(
628 command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
629 base::FieldTrialList::DONT_ACTIVATE_TRIALS,
630 unforceable_field_trials);
631 CHECK(result) << "Invalid --" << switches::kForceFieldTrials
632 << " list specified.";
634 if (command_line->HasSwitch(switches::kForceVariationIds)) {
635 // Create default variation ids which will always be included in the
636 // X-Client-Data request header.
637 variations::VariationsHttpHeaderProvider* provider =
638 variations::VariationsHttpHeaderProvider::GetInstance();
639 bool result = provider->SetDefaultVariationIds(
640 command_line->GetSwitchValueASCII(switches::kForceVariationIds));
641 CHECK(result) << "Invalid --" << switches::kForceVariationIds
642 << " list specified.";
643 metrics->AddSyntheticTrialObserver(provider);
645 chrome_variations::VariationsService* variations_service =
646 browser_process_->variations_service();
647 if (variations_service)
648 variations_service->CreateTrialsFromSeed();
650 // This must be called after |local_state_| is initialized.
651 browser_field_trials_.SetupFieldTrials();
653 // Enable Navigation Tracing only if a trace upload url is specified.
654 if (command_line->HasSwitch(switches::kEnableNavigationTracing) &&
655 command_line->HasSwitch(switches::kTraceUploadURL)) {
656 tracing::SetupNavigationTracing();
659 // Initialize FieldTrialSynchronizer system. This is a singleton and is used
660 // for posting tasks via base::Bind. Its deleted when it goes out of scope.
661 // Even though base::Bind does AddRef and Release, the object will not be
662 // deleted after the Task is executed.
663 field_trial_synchronizer_ = new FieldTrialSynchronizer();
665 // Now that field trials have been created, initializes metrics recording.
666 metrics->InitializeMetricsRecordingState();
668 const chrome::VersionInfo::Channel channel =
669 chrome::VersionInfo::GetChannel();
671 // TODO(dalecurtis): Remove these checks and enable for all channels once we
672 // track down the root causes of crbug.com/422522 and crbug.com/478932.
673 if (channel == chrome::VersionInfo::CHANNEL_UNKNOWN ||
674 channel == chrome::VersionInfo::CHANNEL_CANARY ||
675 channel == chrome::VersionInfo::CHANNEL_DEV) {
676 media::AudioManager::EnableHangMonitor();
679 // Enable profiler instrumentation depending on the channel.
680 switch (channel) {
681 case chrome::VersionInfo::CHANNEL_UNKNOWN:
682 case chrome::VersionInfo::CHANNEL_CANARY:
683 tracked_objects::ScopedTracker::Enable();
684 break;
686 case chrome::VersionInfo::CHANNEL_DEV:
687 case chrome::VersionInfo::CHANNEL_BETA:
688 case chrome::VersionInfo::CHANNEL_STABLE:
689 // Don't enable instrumentation.
690 break;
694 // ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
696 void ChromeBrowserMainParts::StartMetricsRecording() {
697 TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
699 g_browser_process->metrics_service()->CheckForClonedInstall(
700 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
702 g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
705 void ChromeBrowserMainParts::RecordBrowserStartupTime() {
706 // Don't record any metrics if UI was displayed before this point e.g.
707 // warning dialogs.
708 if (startup_metric_utils::WasNonBrowserUIDisplayed())
709 return;
711 #if defined(OS_ANDROID)
712 // On Android the first run is handled in Java code, and the C++ side of
713 // Chrome doesn't know if this is the first run. This will cause some
714 // inaccuracy in the UMA statistics, but this should be minor (first runs are
715 // rare).
716 bool is_first_run = false;
717 #else
718 bool is_first_run = first_run::IsChromeFirstRun();
719 #endif // defined(OS_ANDROID)
721 // CurrentProcessInfo::CreationTime() is currently only implemented on some
722 // platforms.
723 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
724 const base::Time process_creation_time =
725 base::CurrentProcessInfo::CreationTime();
727 if (!is_first_run && !process_creation_time.is_null()) {
728 base::TimeDelta delay = base::Time::Now() - process_creation_time;
729 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserMessageLoopStartTime", delay);
731 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
733 // Record collected startup metrics.
734 startup_metric_utils::OnBrowserStartupComplete(is_first_run);
737 // -----------------------------------------------------------------------------
738 // TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
740 #if defined(OS_WIN)
741 #define DLLEXPORT __declspec(dllexport)
743 // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
744 extern "C" {
745 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
748 DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
749 // Need an instance of AtExitManager to handle singleton creations and
750 // deletions. We need this new instance because, the old instance created
751 // in ChromeMain() got destructed when the function returned.
752 base::AtExitManager exit_manager;
753 upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
755 #endif
757 // content::BrowserMainParts implementation ------------------------------------
759 void ChromeBrowserMainParts::PreEarlyInitialization() {
760 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
761 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
762 chrome_extra_parts_[i]->PreEarlyInitialization();
765 void ChromeBrowserMainParts::PostEarlyInitialization() {
766 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
767 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
768 chrome_extra_parts_[i]->PostEarlyInitialization();
771 void ChromeBrowserMainParts::ToolkitInitialized() {
772 TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
773 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
774 chrome_extra_parts_[i]->ToolkitInitialized();
777 void ChromeBrowserMainParts::PreMainMessageLoopStart() {
778 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
780 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
781 chrome_extra_parts_[i]->PreMainMessageLoopStart();
784 void ChromeBrowserMainParts::PostMainMessageLoopStart() {
785 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
787 // device_event_log must be initialized after the message loop. Calls to
788 // {DEVICE}_LOG prior to here will only be logged with VLOG. Some
789 // platforms (e.g. chromeos) may have already initialized this.
790 if (!device_event_log::IsInitialized())
791 device_event_log::Initialize(0 /* default max entries */);
793 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
794 chrome_extra_parts_[i]->PostMainMessageLoopStart();
797 int ChromeBrowserMainParts::PreCreateThreads() {
798 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
799 result_code_ = PreCreateThreadsImpl();
801 if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
802 #if !defined(OS_ANDROID)
803 // These members must be initialized before exiting this function normally.
804 DCHECK(master_prefs_.get());
805 DCHECK(browser_creator_.get());
806 #endif // !defined(OS_ANDROID)
807 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
808 chrome_extra_parts_[i]->PreCreateThreads();
811 return result_code_;
814 int ChromeBrowserMainParts::PreCreateThreadsImpl() {
815 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
816 run_message_loop_ = false;
817 #if !defined(OS_ANDROID)
818 chrome::MaybeShowInvalidUserDataDirWarningDialog();
819 #endif // !defined(OS_ANDROID)
820 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
821 return chrome::RESULT_CODE_MISSING_DATA;
823 // Force MediaCaptureDevicesDispatcher to be created on UI thread.
824 MediaCaptureDevicesDispatcher::GetInstance();
826 // Android's first run is done in Java instead of native.
827 #if !defined(OS_ANDROID)
828 process_singleton_.reset(new ChromeProcessSingleton(
829 user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
831 // Cache first run state early.
832 first_run::IsChromeFirstRun();
833 #endif // !defined(OS_ANDROID)
835 scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
836 JsonPrefStore::GetTaskRunnerForFile(
837 base::FilePath(chrome::kLocalStorePoolName),
838 BrowserThread::GetBlockingPool());
841 TRACE_EVENT0("startup",
842 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
843 browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
844 parsed_command_line()));
847 if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
848 TRACE_EVENT0("startup",
849 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
850 // User wants to override default tracking status.
851 std::string flag =
852 parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
853 // Default to basic profiling (no parent child support).
854 tracked_objects::ThreadData::Status status =
855 tracked_objects::ThreadData::PROFILING_ACTIVE;
856 if (flag.compare("0") != 0)
857 status = tracked_objects::ThreadData::DEACTIVATED;
858 tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
861 local_state_ = InitializeLocalState(
862 local_state_task_runner.get(), parsed_command_line());
864 #if !defined(OS_ANDROID)
865 // These members must be initialized before returning from this function.
866 master_prefs_.reset(new first_run::MasterPrefs);
867 // Android doesn't use StartupBrowserCreator.
868 browser_creator_.reset(new StartupBrowserCreator);
869 // TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
870 chrome::UMABrowsingActivityObserver::Init();
871 #endif // !defined(OS_ANDROID)
873 #if !defined(OS_CHROMEOS)
874 // Convert active labs into switches. This needs to be done before
875 // ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
876 // affected by experiment flags (--touch-optimized-ui in particular).
877 // On ChromeOS system level flags are applied from the device settings from
878 // the session manager.
880 TRACE_EVENT0("startup",
881 "ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
882 about_flags::PrefServiceFlagsStorage flags_storage_(
883 g_browser_process->local_state());
884 about_flags::ConvertFlagsToSwitches(&flags_storage_,
885 base::CommandLine::ForCurrentProcess(),
886 about_flags::kAddSentinels);
888 #endif // !defined(OS_CHROMEOS)
890 local_state_->UpdateCommandLinePrefStore(
891 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
893 // Reset the command line in the crash report details, since we may have
894 // just changed it to include experiments.
895 crash_keys::SetSwitchesFromCommandLine(
896 base::CommandLine::ForCurrentProcess());
898 // Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
899 // needed when loading the MainMenu.nib and the language doesn't depend on
900 // anything since it comes from Cocoa.
901 #if defined(OS_MACOSX)
902 std::string locale =
903 parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
904 browser_process_->SetApplicationLocale(locale);
905 #else
906 const std::string locale =
907 local_state_->GetString(prefs::kApplicationLocale);
909 // On a POSIX OS other than ChromeOS, the parameter that is passed to the
910 // method InitSharedInstance is ignored.
912 TRACE_EVENT_BEGIN0("startup",
913 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
914 const std::string loaded_locale =
915 ui::ResourceBundle::InitSharedInstanceWithLocale(
916 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
917 TRACE_EVENT_END0("startup",
918 "ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
920 if (loaded_locale.empty() &&
921 !parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
922 ShowMissingLocaleMessageBox();
923 return chrome::RESULT_CODE_MISSING_DATA;
925 CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
926 browser_process_->SetApplicationLocale(loaded_locale);
928 base::FilePath resources_pack_path;
929 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
931 TRACE_EVENT0("startup",
932 "ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
933 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
934 resources_pack_path, ui::SCALE_FACTOR_NONE);
936 #endif // defined(OS_MACOSX)
938 // Android does first run in Java instead of native.
939 // Chrome OS has its own out-of-box-experience code.
940 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
941 // On first run, we need to process the predictor preferences before the
942 // browser's profile_manager object is created, but after ResourceBundle
943 // is initialized.
944 if (first_run::IsChromeFirstRun()) {
945 first_run::ProcessMasterPreferencesResult pmp_result =
946 first_run::ProcessMasterPreferences(user_data_dir_,
947 master_prefs_.get());
948 if (pmp_result == first_run::EULA_EXIT_NOW)
949 return chrome::RESULT_CODE_EULA_REFUSED;
951 if (!parsed_command_line().HasSwitch(switches::kApp) &&
952 !parsed_command_line().HasSwitch(switches::kAppId) &&
953 !parsed_command_line().HasSwitch(switches::kShowAppList)) {
954 AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
957 // TODO(macourteau): refactor preferences that are copied from
958 // master_preferences into local_state, as a "local_state" section in
959 // master preferences. If possible, a generic solution would be preferred
960 // over a copy one-by-one of specific preferences. Also see related TODO
961 // in first_run.h.
963 // Store the initial VariationsService seed in local state, if it exists
964 // in master prefs.
965 if (!master_prefs_->variations_seed.empty() ||
966 !master_prefs_->compressed_variations_seed.empty()) {
967 if (!master_prefs_->variations_seed.empty()) {
968 local_state_->SetString(prefs::kVariationsSeed,
969 master_prefs_->variations_seed);
971 if (!master_prefs_->compressed_variations_seed.empty()) {
972 local_state_->SetString(prefs::kVariationsCompressedSeed,
973 master_prefs_->compressed_variations_seed);
975 if (!master_prefs_->variations_seed_signature.empty()) {
976 local_state_->SetString(prefs::kVariationsSeedSignature,
977 master_prefs_->variations_seed_signature);
979 // Set the variation seed date to the current system time. If the user's
980 // clock is incorrect, this may cause some field trial expiry checks to
981 // not do the right thing until the next seed update from the server,
982 // when this value will be updated.
983 local_state_->SetInt64(prefs::kVariationsSeedDate,
984 base::Time::Now().ToInternalValue());
987 if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
988 local_state_->SetString(
989 prefs::kBrowserSuppressDefaultBrowserPrompt,
990 master_prefs_->suppress_default_browser_prompt_for_version);
993 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
995 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
996 // Set the product channel for crash reports.
997 base::debug::SetCrashKeyValue(crash_keys::kChannel,
998 chrome::VersionInfo::GetVersionStringModifier());
999 #endif // defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_MACOSX)
1001 // Initialize tracking synchronizer system.
1002 tracking_synchronizer_ = new metrics::TrackingSynchronizer(
1003 make_scoped_ptr(new base::DefaultTickClock()));
1005 #if defined(OS_MACOSX)
1006 // Get the Keychain API to register for distributed notifications on the main
1007 // thread, which has a proper CFRunloop, instead of later on the I/O thread,
1008 // which doesn't. This ensures those notifications will get delivered
1009 // properly. See issue 37766.
1010 // (Note that the callback mask here is empty. I don't want to register for
1011 // any callbacks, I just want to initialize the mechanism.)
1012 SecKeychainAddCallback(&KeychainCallback, 0, NULL);
1013 #endif // defined(OS_MACOSX)
1015 #if defined(OS_CHROMEOS)
1016 // Must be done after g_browser_process is constructed, before
1017 // SetupMetricsAndFieldTrials().
1018 chromeos::CrosSettings::Initialize();
1019 #endif // defined(OS_CHROMEOS)
1021 // Now the command line has been mutated based on about:flags, we can setup
1022 // metrics and initialize field trials. The field trials are needed by
1023 // IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
1024 SetupMetricsAndFieldTrials();
1026 // ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
1027 browser_process_->PreCreateThreads();
1029 return content::RESULT_CODE_NORMAL_EXIT;
1032 void ChromeBrowserMainParts::PreMainMessageLoopRun() {
1033 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1034 TRACK_SCOPED_REGION(
1035 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
1037 result_code_ = PreMainMessageLoopRunImpl();
1039 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1040 chrome_extra_parts_[i]->PreMainMessageLoopRun();
1043 // PreMainMessageLoopRun calls these extra stages in the following order:
1044 // PreMainMessageLoopRunImpl()
1045 // ... initial setup, including browser_process_ setup.
1046 // PreProfileInit()
1047 // ... additional setup, including CreateProfile()
1048 // PostProfileInit()
1049 // ... additional setup
1050 // PreBrowserStart()
1051 // ... browser_creator_->Start (OR parameters().ui_task->Run())
1052 // PostBrowserStart()
1054 void ChromeBrowserMainParts::PreProfileInit() {
1055 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
1057 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1058 chrome_extra_parts_[i]->PreProfileInit();
1060 #if !defined(OS_ANDROID)
1061 // Initialize the feedback uploader so it can setup notifications for profile
1062 // creation.
1063 feedback::FeedbackProfileObserver::Initialize();
1065 // Ephemeral profiles may have been left behind if the browser crashed.
1066 g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
1067 #endif // !defined(OS_ANDROID)
1069 #if defined(ENABLE_EXTENSIONS)
1070 javascript_dialog_extensions_client::InstallClient();
1071 #endif // defined(ENABLE_EXTENSIONS)
1073 #if !defined(OS_IOS)
1074 InstallChromeJavaScriptNativeDialogFactory();
1075 #endif // !defined(OS_IOS)
1078 void ChromeBrowserMainParts::PostProfileInit() {
1079 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
1081 #if defined(OS_ANDROID)
1082 DevToolsDiscoveryProviderAndroid::Install();
1083 #else
1084 ChromeDevToolsDiscoveryProvider::Install();
1085 #endif // defined(OS_ANDROID)
1087 LaunchDevToolsHandlerIfNeeded(parsed_command_line());
1088 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1089 chrome_extra_parts_[i]->PostProfileInit();
1092 void ChromeBrowserMainParts::PreBrowserStart() {
1093 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
1094 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1095 chrome_extra_parts_[i]->PreBrowserStart();
1097 three_d_observer_.reset(new ThreeDAPIObserver());
1100 void ChromeBrowserMainParts::PostBrowserStart() {
1101 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
1102 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1103 chrome_extra_parts_[i]->PostBrowserStart();
1104 #if !defined(OS_ANDROID)
1105 // Allow ProcessSingleton to process messages.
1106 process_singleton_->Unlock();
1107 #endif // !defined(OS_ANDROID)
1108 #if defined(ENABLE_WEBRTC)
1109 // Set up a task to delete old WebRTC log files for all profiles. Use a delay
1110 // to reduce the impact on startup time.
1111 BrowserThread::PostDelayedTask(
1112 BrowserThread::UI,
1113 FROM_HERE,
1114 base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
1115 base::TimeDelta::FromMinutes(1));
1116 #endif // defined(ENABLE_WEBRTC)
1118 // At this point, StartupBrowserCreator::Start has run creating initial
1119 // browser windows and tabs, but no progress has been made in loading
1120 // content as the main message loop hasn't started processing tasks yet.
1121 // We setup to observe to the initial page load here to defer running
1122 // task posted via PostAfterStartupTask until its complete.
1123 AfterStartupTaskUtils::StartMonitoringStartup();
1126 int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
1127 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1128 TRACK_SCOPED_REGION(
1129 "Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
1131 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
1132 const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
1134 #if defined(OS_WIN)
1135 // Windows parental controls calls can be slow, so we do an early init here
1136 // that calculates this value off of the UI thread.
1137 IncognitoModePrefs::InitializePlatformParentalControls();
1138 #endif
1140 #if defined(ENABLE_EXTENSIONS)
1141 if (!variations::GetVariationParamValue(
1142 "LightSpeed", "EarlyInitStartup").empty()) {
1143 // Try to compute this early on another thread so that we don't spend time
1144 // during profile load initializing the extensions APIs.
1145 BrowserThread::PostTask(
1146 BrowserThread::FILE_USER_BLOCKING,
1147 FROM_HERE,
1148 base::Bind(
1149 base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
1151 #endif
1153 // Android updates the metrics service dynamically depending on whether the
1154 // application is in the foreground or not. Do not start here.
1155 #if !defined(OS_ANDROID)
1156 // Now that the file thread has been started, start recording.
1157 StartMetricsRecording();
1158 #endif // !defined(OS_ANDROID)
1160 if (!base::debug::BeingDebugged()) {
1161 // Create watchdog thread after creating all other threads because it will
1162 // watch the other threads and they must be running.
1163 browser_process_->watchdog_thread();
1166 // Do any initializating in the browser process that requires all threads
1167 // running.
1168 browser_process_->PreMainMessageLoopRun();
1170 // Record last shutdown time into a histogram.
1171 browser_shutdown::ReadLastShutdownInfo();
1173 #if defined(OS_WIN)
1174 // On Windows, we use our startup as an opportunity to do upgrade/uninstall
1175 // tasks. Those care whether the browser is already running. On Linux/Mac,
1176 // upgrade/uninstall happen separately.
1177 bool already_running = browser_util::IsBrowserAlreadyRunning();
1179 // If the command line specifies 'uninstall' then we need to work here
1180 // unless we detect another chrome browser running.
1181 if (parsed_command_line().HasSwitch(switches::kUninstall)) {
1182 return DoUninstallTasks(already_running);
1185 if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
1186 parsed_command_line().HasSwitch(switches::kShowIcons)) {
1187 return ChromeBrowserMainPartsWin::HandleIconsCommands(
1188 parsed_command_line_);
1191 ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
1192 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1193 #endif // defined(OS_WIN)
1195 if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
1196 bool is_managed = g_browser_process->local_state()->IsManagedPreference(
1197 prefs::kDefaultBrowserSettingEnabled);
1198 if (is_managed && !g_browser_process->local_state()->GetBoolean(
1199 prefs::kDefaultBrowserSettingEnabled)) {
1200 return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
1203 return ShellIntegration::SetAsDefaultBrowser() ?
1204 static_cast<int>(content::RESULT_CODE_NORMAL_EXIT) :
1205 static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
1208 #if defined(USE_AURA)
1209 // Make sure aura::Env has been initialized.
1210 CHECK(aura::Env::GetInstance());
1211 #endif // defined(USE_AURA)
1213 // Android doesn't support extensions and doesn't implement ProcessSingleton.
1214 #if !defined(OS_ANDROID)
1215 // If the command line specifies --pack-extension, attempt the pack extension
1216 // startup action and exit.
1217 if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
1218 extensions::StartupHelper extension_startup_helper;
1219 if (extension_startup_helper.PackExtension(parsed_command_line()))
1220 return content::RESULT_CODE_NORMAL_EXIT;
1221 return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
1224 // When another process is running, use that process instead of starting a
1225 // new one. NotifyOtherProcess will currently give the other process up to
1226 // 20 seconds to respond. Note that this needs to be done before we attempt
1227 // to read the profile.
1228 notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
1229 switch (notify_result_) {
1230 case ProcessSingleton::PROCESS_NONE:
1231 // No process already running, fall through to starting a new one.
1232 break;
1234 case ProcessSingleton::PROCESS_NOTIFIED:
1235 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1236 // On POSIX systems, print a message notifying the process is running.
1237 printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
1238 l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
1239 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1241 // Having a differentiated return type for testing allows for tests to
1242 // verify proper handling of some switches. When not testing, stick to
1243 // the standard Unix convention of returning zero when things went as
1244 // expected.
1245 if (parsed_command_line().HasSwitch(switches::kTestType))
1246 return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
1247 return content::RESULT_CODE_NORMAL_EXIT;
1249 case ProcessSingleton::PROFILE_IN_USE:
1250 return chrome::RESULT_CODE_PROFILE_IN_USE;
1252 case ProcessSingleton::LOCK_ERROR:
1253 LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
1254 "directory. This means that running multiple instances "
1255 "would start multiple browser processes rather than "
1256 "opening a new window in the existing process. Aborting "
1257 "now to avoid profile corruption.";
1258 return chrome::RESULT_CODE_PROFILE_IN_USE;
1260 default:
1261 NOTREACHED();
1263 #endif // !defined(OS_ANDROID)
1265 // Handle special early return paths (which couldn't be processed even earlier
1266 // as they require the process singleton to be held) first.
1268 std::string try_chrome =
1269 parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
1270 if (!try_chrome.empty()) {
1271 #if defined(OS_WIN)
1272 // Setup.exe has determined that we need to run a retention experiment
1273 // and has lauched chrome to show the experiment UI. It is guaranteed that
1274 // no other Chrome is currently running as the process singleton was
1275 // sucessfully grabbed above.
1276 int try_chrome_int;
1277 base::StringToInt(try_chrome, &try_chrome_int);
1278 TryChromeDialogView::Result answer = TryChromeDialogView::Show(
1279 try_chrome_int,
1280 base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
1281 base::Unretained(process_singleton_.get())));
1282 if (answer == TryChromeDialogView::NOT_NOW)
1283 return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
1284 if (answer == TryChromeDialogView::UNINSTALL_CHROME)
1285 return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
1286 // At this point the user is willing to try chrome again.
1287 if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
1288 // Only set in the unattended case, the interactive case is Windows 8.
1289 if (ShellIntegration::CanSetAsDefaultBrowser() ==
1290 ShellIntegration::SET_DEFAULT_UNATTENDED)
1291 ShellIntegration::SetAsDefaultBrowser();
1293 #else
1294 // We don't support retention experiments on Mac or Linux.
1295 return content::RESULT_CODE_NORMAL_EXIT;
1296 #endif // defined(OS_WIN)
1299 #if defined(OS_WIN)
1300 // Do the tasks if chrome has been upgraded while it was last running.
1301 if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
1302 return content::RESULT_CODE_NORMAL_EXIT;
1304 // Check if there is any machine level Chrome installed on the current
1305 // machine. If yes and the current Chrome process is user level, we do not
1306 // allow the user level Chrome to run. So we notify the user and uninstall
1307 // user level Chrome.
1308 // Note this check needs to happen here (after the process singleton was
1309 // obtained but before potentially creating the first run sentinel).
1310 if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
1311 return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
1312 #endif // defined(OS_WIN)
1314 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1315 if (sxs_linux::ShouldMigrateUserDataDir())
1316 return sxs_linux::MigrateUserDataDir();
1317 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1319 // Desktop construction occurs here, (required before profile creation).
1320 PreProfileInit();
1322 // Profile creation ----------------------------------------------------------
1324 metrics::MetricsService::SetExecutionPhase(
1325 metrics::MetricsService::CREATE_PROFILE,
1326 g_browser_process->local_state());
1328 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
1329 base::TimeTicks::Now() - start_time_step1);
1331 // This step is costly and is already measured in Startup.CreateFirstProfile
1332 // and more directly Profile.CreateAndInitializeProfile.
1333 profile_ = CreatePrimaryProfile(parameters(),
1334 user_data_dir_,
1335 parsed_command_line());
1336 if (!profile_)
1337 return content::RESULT_CODE_NORMAL_EXIT;
1339 #if !defined(OS_ANDROID)
1340 const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
1341 // The first run sentinel must be created after the process singleton was
1342 // grabbed and no early return paths were otherwise hit above.
1343 first_run::CreateSentinelIfNeeded();
1344 #endif // !defined(OS_ANDROID)
1346 #if defined(ENABLE_BACKGROUND)
1347 // Autoload any profiles which are running background apps.
1348 // TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
1349 browser_process_->profile_manager()->AutoloadProfiles();
1350 #endif // defined(ENABLE_BACKGROUND)
1351 // Post-profile init ---------------------------------------------------------
1353 TranslateService::Initialize();
1355 // Needs to be done before PostProfileInit, since login manager on CrOS is
1356 // called inside PostProfileInit.
1357 content::WebUIControllerFactory::RegisterFactory(
1358 ChromeWebUIControllerFactory::GetInstance());
1360 // NaClBrowserDelegateImpl is accessed inside PostProfileInit().
1361 // So make sure to create it before that.
1362 #if !defined(DISABLE_NACL)
1363 NaClBrowserDelegateImpl* delegate =
1364 new NaClBrowserDelegateImpl(browser_process_->profile_manager());
1365 nacl::NaClBrowser::SetDelegate(delegate);
1366 #endif // !defined(DISABLE_NACL)
1368 // TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
1369 // (requires supporting early exit).
1370 PostProfileInit();
1372 // Retrieve cached GL strings from local state and use them for GPU
1373 // blacklist decisions.
1374 if (g_browser_process->gl_string_manager())
1375 g_browser_process->gl_string_manager()->Initialize();
1377 // Create an instance of GpuModeManager to watch gpu mode pref change.
1378 g_browser_process->gpu_mode_manager();
1380 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1381 // Show the First Run UI if this is the first time Chrome has been run on
1382 // this computer, or we're being compelled to do so by a command line flag.
1383 // Note that this be done _after_ the PrefService is initialized and all
1384 // preferences are registered, since some of the code that the importer
1385 // touches reads preferences.
1386 if (first_run::IsChromeFirstRun()) {
1387 first_run::AutoImport(profile_,
1388 master_prefs_->homepage_defined,
1389 master_prefs_->do_import_items,
1390 master_prefs_->dont_import_items,
1391 master_prefs_->import_bookmarks_path);
1393 // Note: this can pop the first run consent dialog on linux.
1394 first_run::DoPostImportTasks(profile_,
1395 master_prefs_->make_chrome_default_for_user);
1397 if (!master_prefs_->suppress_first_run_default_browser_prompt) {
1398 browser_creator_->set_show_main_browser_window(
1399 !chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
1400 } else {
1401 browser_creator_->set_is_default_browser_dialog_suppressed(true);
1404 #endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1406 #if defined(OS_WIN)
1407 // Sets things up so that if we crash from this point on, a dialog will
1408 // popup asking the user to restart chrome. It is done this late to avoid
1409 // testing against a bunch of special cases that are taken care early on.
1410 ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
1411 parsed_command_line());
1413 // Registers Chrome with the Windows Restart Manager, which will restore the
1414 // Chrome session when the computer is restarted after a system update.
1415 // This could be run as late as WM_QUERYENDSESSION for system update reboots,
1416 // but should run on startup if extended to handle crashes/hangs/patches.
1417 // Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
1418 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
1419 ChromeBrowserMainPartsWin::RegisterApplicationRestart(
1420 parsed_command_line());
1423 // Verify that the profile is not on a network share and if so prepare to show
1424 // notification to the user.
1425 if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
1426 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
1427 base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
1428 profile_->GetPath()));
1430 #endif // defined(OS_WIN)
1432 #if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1433 // Init the RLZ library. This just binds the dll and schedules a task on the
1434 // file thread to be run sometime later. If this is the first run we record
1435 // the installation event.
1436 PrefService* pref_service = profile_->GetPrefs();
1437 int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
1438 pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
1439 // Negative ping delay means to send ping immediately after a first search is
1440 // recorded.
1441 RLZTracker::InitRlzFromProfileDelayed(
1442 profile_, first_run::IsChromeFirstRun(), ping_delay < 0,
1443 base::TimeDelta::FromMilliseconds(abs(ping_delay)));
1444 #endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
1446 // Configure modules that need access to resources.
1447 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
1449 // In unittest mode, this will do nothing. In normal mode, this will create
1450 // the global IntranetRedirectDetector instance, which will promptly go to
1451 // sleep for seven seconds (to avoid slowing startup), and wake up afterwards
1452 // to see if it should do anything else.
1454 // A simpler way of doing all this would be to have some function which could
1455 // give the time elapsed since startup, and simply have this object check that
1456 // when asked to initialize itself, but this doesn't seem to exist.
1458 // This can't be created in the BrowserProcessImpl constructor because it
1459 // needs to read prefs that get set after that runs.
1460 browser_process_->intranet_redirect_detector();
1461 GoogleSearchCounter::RegisterForNotifications();
1463 #if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1464 if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
1465 base::FilePath path =
1466 parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
1467 printing::PrintedDocument::set_debug_dump_path(path);
1469 #endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
1471 HandleTestParameters(parsed_command_line());
1472 browser_process_->metrics_service()->RecordBreakpadHasDebugger(
1473 base::debug::BeingDebugged());
1475 language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
1476 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1477 language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
1478 browser_process_->GetApplicationLocale());
1480 // Start watching for hangs during startup. We disarm this hang detector when
1481 // ThreadWatcher takes over or when browser is shutdown or when
1482 // startup_watcher_ is deleted.
1483 metrics::MetricsService::SetExecutionPhase(
1484 metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
1485 g_browser_process->local_state());
1486 startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
1488 // On mobile, need for clean shutdown arises only when the application comes
1489 // to foreground (i.e. MetricsService::OnAppEnterForeground is called).
1490 // http://crbug.com/179143
1491 #if !defined(OS_ANDROID)
1492 // Start watching for a hang.
1493 browser_process_->metrics_service()->LogNeedForCleanShutdown();
1494 #endif // !defined(OS_ANDROID)
1496 #if defined(ENABLE_PRINT_PREVIEW)
1497 // Create the instance of the cloud print proxy service so that it can launch
1498 // the service process if needed. This is needed because the service process
1499 // might have shutdown because an update was available.
1500 // TODO(torne): this should maybe be done with
1501 // BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
1502 // instead?
1503 CloudPrintProxyServiceFactory::GetForProfile(profile_);
1504 #endif // defined(ENABLE_PRINT_PREVIEW)
1506 // Start watching all browser threads for responsiveness.
1507 metrics::MetricsService::SetExecutionPhase(
1508 metrics::MetricsService::THREAD_WATCHER_START,
1509 g_browser_process->local_state());
1510 ThreadWatcherList::StartWatchingAll(parsed_command_line());
1512 #if defined(OS_ANDROID)
1513 ThreadWatcherAndroid::RegisterApplicationStatusListener();
1514 #endif // defined(OS_ANDROID)
1516 #if !defined(DISABLE_NACL)
1517 BrowserThread::PostTask(
1518 BrowserThread::IO,
1519 FROM_HERE,
1520 base::Bind(nacl::NaClProcessHost::EarlyStartup));
1521 #endif // !defined(DISABLE_NACL)
1523 // Make sure initial prefs are recorded
1524 PrefMetricsService::Factory::GetForProfile(profile_);
1526 PreBrowserStart();
1528 // Instantiate the notification UI manager, as this triggers a perf timer
1529 // used to measure startup time. TODO(stevenjb): Figure out what is actually
1530 // triggering the timer and call that explicitly in the approprate place.
1531 // http://crbug.com/105065.
1532 browser_process_->notification_ui_manager();
1534 // This must be called prior to RegisterComponentsForUpdate, in case the CLD
1535 // data source is based on the Component Updater.
1536 translate::BrowserCldUtils::ConfigureDefaultDataProvider();
1538 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
1539 RegisterComponentsForUpdate();
1541 #if defined(OS_ANDROID)
1542 chrome_variations::VariationsService* variations_service =
1543 browser_process_->variations_service();
1544 if (variations_service) {
1545 // Just initialize the policy prefs service here. Variations seed fetching
1546 // will be initialized when the app enters foreground mode.
1547 variations_service->set_policy_pref_service(profile_->GetPrefs());
1549 translate::TranslateDownloadManager::RequestLanguageList(
1550 profile_->GetPrefs());
1552 #else
1553 // Most general initialization is behind us, but opening a
1554 // tab and/or session restore and such is still to be done.
1555 base::TimeTicks browser_open_start = base::TimeTicks::Now();
1557 // We are in regular browser boot sequence. Open initial tabs and enter the
1558 // main message loop.
1559 #if defined(OS_CHROMEOS)
1560 // On ChromeOS multiple profiles doesn't apply, and will break if we load
1561 // them this early as the cryptohome hasn't yet been mounted (which happens
1562 // only once we log in.
1563 std::vector<Profile*> last_opened_profiles;
1564 #else
1565 std::vector<Profile*> last_opened_profiles =
1566 g_browser_process->profile_manager()->GetLastOpenedProfiles();
1567 #endif // defined(OS_CHROMEOS)
1569 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
1570 base::TimeTicks::Now() - start_time_step2);
1572 // This step is costly and is already measured in
1573 // Startup.StartupBrowserCreator_Start.
1574 bool started = browser_creator_->Start(
1575 parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
1576 const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
1577 if (started) {
1578 #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1579 // Initialize autoupdate timer. Timer callback costs basically nothing
1580 // when browser is not in persistent mode, so it's OK to let it ride on
1581 // the main thread. This needs to be done here because we don't want
1582 // to start the timer when Chrome is run inside a test harness.
1583 browser_process_->StartAutoupdateTimer();
1584 #endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
1586 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1587 // On Linux, the running exe will be updated if an upgrade becomes
1588 // available while the browser is running. We need to save the last
1589 // modified time of the exe, so we can compare to determine if there is
1590 // an upgrade while the browser is kept alive by a persistent extension.
1591 upgrade_util::SaveLastModifiedTimeOfExe();
1592 #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
1594 // Record now as the last successful chrome start.
1595 GoogleUpdateSettings::SetLastRunTime();
1597 #if defined(OS_MACOSX)
1598 // Call Recycle() here as late as possible, before going into the loop
1599 // because Start() will add things to it while creating the main window.
1600 if (parameters().autorelease_pool)
1601 parameters().autorelease_pool->Recycle();
1602 #endif // defined(OS_MACOSX)
1604 base::TimeDelta delay = base::TimeTicks::Now() - browser_open_start;
1605 UMA_HISTOGRAM_LONG_TIMES_100("Startup.BrowserOpenTabs", delay);
1607 // If we're running tests (ui_task is non-null), then we don't want to
1608 // call RequestLanguageList or StartRepeatedVariationsSeedFetch or
1609 // RequestLanguageList
1610 if (parameters().ui_task == NULL) {
1611 // Request new variations seed information from server.
1612 chrome_variations::VariationsService* variations_service =
1613 browser_process_->variations_service();
1614 if (variations_service) {
1615 variations_service->StartRepeatedVariationsSeedFetch();
1617 #if defined(OS_WIN)
1618 variations_service->StartGoogleUpdateRegistrySync();
1619 #endif // defined(OS_WIN)
1622 translate::TranslateDownloadManager::RequestLanguageList(
1623 profile_->GetPrefs());
1626 run_message_loop_ = true;
1627 } else {
1628 run_message_loop_ = false;
1630 browser_creator_.reset();
1632 #if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
1633 if (g_browser_process->metrics_service()->reporting_active())
1634 content::StartPowerUsageMonitor();
1635 #endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
1637 process_power_collector_.reset(new ProcessPowerCollector);
1638 process_power_collector_->Initialize();
1639 #endif // !defined(OS_ANDROID)
1641 PostBrowserStart();
1643 if (parameters().ui_task) {
1644 parameters().ui_task->Run();
1645 delete parameters().ui_task;
1646 run_message_loop_ = false;
1648 #if defined(OS_ANDROID)
1649 // We never run the C++ main loop on Android, since the UI thread message
1650 // loop is controlled by the OS, so this is as close as we can get to
1651 // the start of the main loop.
1652 if (result_code_ <= 0) {
1653 RecordBrowserStartupTime();
1655 #endif // defined(OS_ANDROID)
1657 #if !defined(OS_ANDROID)
1658 UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
1659 base::TimeTicks::Now() - start_time_step3);
1660 #endif // !defined(OS_ANDROID)
1662 return result_code_;
1665 bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
1666 TRACE_EVENT0("startup", "ChromeBrowserMainParts::MainMessageLoopRun");
1667 #if defined(OS_ANDROID)
1668 // Chrome on Android does not use default MessageLoop. It has its own
1669 // Android specific MessageLoop
1670 NOTREACHED();
1671 return true;
1672 #else
1673 // Set the result code set in PreMainMessageLoopRun or set above.
1674 *result_code = result_code_;
1675 if (!run_message_loop_)
1676 return true; // Don't run the default message loop.
1678 // These should be invoked as close to the start of the browser's
1679 // UI thread message loop as possible to get a stable measurement
1680 // across versions.
1681 RecordBrowserStartupTime();
1683 DCHECK(base::MessageLoopForUI::IsCurrent());
1684 base::RunLoop run_loop;
1686 performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
1688 metrics::MetricsService::SetExecutionPhase(
1689 metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
1690 g_browser_process->local_state());
1691 run_loop.Run();
1693 return true;
1694 #endif // defined(OS_ANDROID)
1697 void ChromeBrowserMainParts::PostMainMessageLoopRun() {
1698 TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
1699 #if defined(OS_ANDROID)
1700 // Chrome on Android does not use default MessageLoop. It has its own
1701 // Android specific MessageLoop
1702 NOTREACHED();
1703 #else
1705 // Start watching for jank during shutdown. It gets disarmed when
1706 // |shutdown_watcher_| object is destructed.
1707 metrics::MetricsService::SetExecutionPhase(
1708 metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
1709 g_browser_process->local_state());
1710 shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
1712 // Disarm the startup hang detector time bomb if it is still Arm'ed.
1713 startup_watcher_->Disarm();
1715 // Remove observers attached to D-Bus clients before DbusThreadManager is
1716 // shut down.
1717 process_power_collector_.reset();
1719 for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
1720 chrome_extra_parts_[i]->PostMainMessageLoopRun();
1722 // Some tests don't set parameters.ui_task, so they started translate
1723 // language fetch that was never completed so we need to cleanup here
1724 // otherwise it will be done by the destructor in a wrong thread.
1725 TranslateService::Shutdown(parameters().ui_task == NULL);
1727 if (notify_result_ == ProcessSingleton::PROCESS_NONE)
1728 process_singleton_->Cleanup();
1730 // Stop all tasks that might run on WatchDogThread.
1731 ThreadWatcherList::StopWatchingAll();
1733 browser_process_->metrics_service()->Stop();
1735 restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
1736 browser_process_->StartTearDown();
1737 #endif // defined(OS_ANDROID)
1740 void ChromeBrowserMainParts::PostDestroyThreads() {
1741 #if defined(OS_ANDROID)
1742 // On Android, there is no quit/exit. So the browser's main message loop will
1743 // not finish.
1744 NOTREACHED();
1745 #else
1746 browser_process_->PostDestroyThreads();
1747 // browser_shutdown takes care of deleting browser_process, so we need to
1748 // release it.
1749 ignore_result(browser_process_.release());
1750 browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
1751 master_prefs_.reset();
1752 process_singleton_.reset();
1753 device_event_log::Shutdown();
1755 // We need to do this check as late as possible, but due to modularity, this
1756 // may be the last point in Chrome. This would be more effective if done at
1757 // a higher level on the stack, so that it is impossible for an early return
1758 // to bypass this code. Perhaps we need a *final* hook that is called on all
1759 // paths from content/browser/browser_main.
1760 CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
1762 #if defined(OS_CHROMEOS)
1763 chromeos::CrosSettings::Shutdown();
1764 #endif // defined(OS_CHROMEOS)
1765 #endif // defined(OS_ANDROID)
1768 // Public members:
1770 void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
1771 chrome_extra_parts_.push_back(parts);