Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / extensions / extension_service.cc
index 58c4711..6274bfd 100644 (file)
 #include "base/threading/sequenced_worker_pool.h"
 #include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
-#include "base/values.h"
 #include "base/version.h"
-#include "chrome/browser/app_mode/app_mode_utils.h"
 #include "chrome/browser/browser_process.h"
 #include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/extensions/api/app_runtime/app_runtime_api.h"
-#include "chrome/browser/extensions/api/declarative/rules_registry_service.h"
 #include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
-#include "chrome/browser/extensions/api/profile_keyed_api_factory.h"
-#include "chrome/browser/extensions/api/runtime/runtime_api.h"
-#include "chrome/browser/extensions/api/storage/settings_frontend.h"
 #include "chrome/browser/extensions/component_loader.h"
 #include "chrome/browser/extensions/crx_installer.h"
 #include "chrome/browser/extensions/data_deleter.h"
-#include "chrome/browser/extensions/event_router.h"
 #include "chrome/browser/extensions/extension_disabled_ui.h"
 #include "chrome/browser/extensions/extension_error_reporter.h"
 #include "chrome/browser/extensions/extension_error_ui.h"
-#include "chrome/browser/extensions/extension_host.h"
 #include "chrome/browser/extensions/extension_install_ui.h"
-#include "chrome/browser/extensions/extension_process_manager.h"
-#include "chrome/browser/extensions/extension_sorting.h"
 #include "chrome/browser/extensions/extension_special_storage_policy.h"
 #include "chrome/browser/extensions/extension_sync_service.h"
-#include "chrome/browser/extensions/extension_system.h"
 #include "chrome/browser/extensions/extension_util.h"
 #include "chrome/browser/extensions/external_install_ui.h"
 #include "chrome/browser/extensions/external_provider_impl.h"
-#include "chrome/browser/extensions/external_provider_interface.h"
+#include "chrome/browser/extensions/install_verifier.h"
 #include "chrome/browser/extensions/installed_loader.h"
-#include "chrome/browser/extensions/management_policy.h"
 #include "chrome/browser/extensions/pending_extension_manager.h"
 #include "chrome/browser/extensions/permissions_updater.h"
 #include "chrome/browser/extensions/unpacked_installer.h"
-#include "chrome/browser/extensions/update_observer.h"
+#include "chrome/browser/extensions/updater/extension_cache.h"
 #include "chrome/browser/extensions/updater/extension_updater.h"
 #include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
 #include "chrome/browser/ui/webui/favicon_source.h"
 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
 #include "chrome/browser/ui/webui/theme_source.h"
 #include "chrome/common/chrome_switches.h"
-#include "chrome/common/chrome_version_info.h"
 #include "chrome/common/crash_keys.h"
-#include "chrome/common/extensions/background_info.h"
-#include "chrome/common/extensions/extension.h"
 #include "chrome/common/extensions/extension_constants.h"
 #include "chrome/common/extensions/extension_file_util.h"
-#include "chrome/common/extensions/extension_messages.h"
-#include "chrome/common/extensions/feature_switch.h"
 #include "chrome/common/extensions/features/feature_channel.h"
-#include "chrome/common/extensions/incognito_handler.h"
 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
-#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
-#include "chrome/common/extensions/manifest_handlers/shared_module_info.h"
 #include "chrome/common/extensions/manifest_url_handler.h"
-#include "chrome/common/extensions/permissions/permissions_data.h"
 #include "chrome/common/pref_names.h"
 #include "chrome/common/url_constants.h"
 #include "components/startup_metric_utils/startup_metric_utils.h"
 #include "content/public/browser/notification_service.h"
 #include "content/public/browser/notification_types.h"
 #include "content/public/browser/render_process_host.h"
-#include "content/public/browser/site_instance.h"
 #include "content/public/browser/storage_partition.h"
 #include "content/public/browser/url_data_source.h"
+#include "extensions/browser/app_sorting.h"
+#include "extensions/browser/event_router.h"
+#include "extensions/browser/extension_host.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/browser/extension_system.h"
+#include "extensions/browser/extensions_browser_client.h"
+#include "extensions/browser/external_provider_interface.h"
+#include "extensions/browser/management_policy.h"
+#include "extensions/browser/pref_names.h"
+#include "extensions/browser/process_manager.h"
+#include "extensions/browser/process_map.h"
+#include "extensions/browser/runtime_data.h"
+#include "extensions/browser/update_observer.h"
 #include "extensions/common/constants.h"
 #include "extensions/common/error_utils.h"
+#include "extensions/common/extension.h"
+#include "extensions/common/extension_messages.h"
 #include "extensions/common/extensions_client.h"
+#include "extensions/common/feature_switch.h"
 #include "extensions/common/manifest.h"
 #include "extensions/common/manifest_constants.h"
+#include "extensions/common/manifest_handlers/background_info.h"
+#include "extensions/common/manifest_handlers/incognito_info.h"
+#include "extensions/common/manifest_handlers/shared_module_info.h"
 #include "extensions/common/permissions/permission_message_provider.h"
+#include "extensions/common/permissions/permissions_data.h"
 #include "grit/generated_resources.h"
 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
 #include "ui/base/webui/web_ui_util.h"
@@ -118,7 +115,10 @@ using extensions::CrxInstaller;
 using extensions::Extension;
 using extensions::ExtensionIdSet;
 using extensions::ExtensionInfo;
+using extensions::ExtensionRegistry;
+using extensions::ExtensionSet;
 using extensions::FeatureSwitch;
+using extensions::InstallVerifier;
 using extensions::ManagementPolicy;
 using extensions::Manifest;
 using extensions::PermissionMessage;
@@ -172,12 +172,12 @@ class SharedModuleProvider : public extensions::ManagementPolicy::Provider {
   }
 
   virtual bool UserMayModifySettings(const Extension* extension,
-                                     string16* error) const OVERRIDE {
+                                     base::string16* error) const OVERRIDE {
     return !IsCWSSharedModule(extension);
   }
 
   virtual bool MustRemainEnabled(const Extension* extension,
-                                 string16* error) const OVERRIDE {
+                                 base::string16* error) const OVERRIDE {
     return IsCWSSharedModule(extension);
   }
 
@@ -185,18 +185,8 @@ class SharedModuleProvider : public extensions::ManagementPolicy::Provider {
   DISALLOW_COPY_AND_ASSIGN(SharedModuleProvider);
 };
 
-
 }  // namespace
 
-ExtensionService::ExtensionRuntimeData::ExtensionRuntimeData()
-    : background_page_ready(false),
-      being_upgraded(false),
-      has_used_webrequest(false) {
-}
-
-ExtensionService::ExtensionRuntimeData::~ExtensionRuntimeData() {
-}
-
 // ExtensionService.
 
 void ExtensionService::CheckExternalUninstall(const std::string& id) {
@@ -244,6 +234,7 @@ void ExtensionService::AddProviderForTesting(
 
 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
     const std::string& id,
+    const std::string& install_parameter,
     const GURL& update_url,
     Manifest::Location location,
     int creation_flags,
@@ -251,6 +242,11 @@ bool ExtensionService::OnExternalExtensionUpdateUrlFound(
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   CHECK(Extension::IdIsValid(id));
 
+  if (Manifest::IsExternalLocation(location)) {
+    // All extensions that are not user specific can be cached.
+    extensions::ExtensionCache::GetInstance()->AllowCaching(id);
+  }
+
   const Extension* extension = GetExtensionById(id, true);
   if (extension) {
     // Already installed. Skip this install if the current location has
@@ -266,7 +262,12 @@ bool ExtensionService::OnExternalExtensionUpdateUrlFound(
   // source.  In this case, signal that this extension will not be
   // installed by returning false.
   if (!pending_extension_manager()->AddFromExternalUpdateUrl(
-          id, update_url, location, creation_flags, mark_acknowledged)) {
+          id,
+          install_parameter,
+          update_url,
+          location,
+          creation_flags,
+          mark_acknowledged)) {
     return false;
   }
 
@@ -274,8 +275,13 @@ bool ExtensionService::OnExternalExtensionUpdateUrlFound(
   return true;
 }
 
+const Extension* ExtensionService::GetInstalledExtensionByUrl(
+    const GURL& url) const {
+  return registry_->enabled_extensions().GetExtensionOrAppByURL(url);
+}
+
 const Extension* ExtensionService::GetInstalledApp(const GURL& url) const {
-  const Extension* extension = extensions_.GetExtensionOrAppByURL(url);
+  const Extension* extension = GetInstalledExtensionByUrl(url);
   return (extension && extension->is_app()) ? extension : NULL;
 }
 
@@ -300,7 +306,7 @@ bool ExtensionService::UninstallExtensionHelper(
 
   // The following call to UninstallExtension will not allow an uninstall of a
   // policy-controlled extension.
-  string16 error;
+  base::string16 error;
   if (!extensions_service->UninstallExtension(extension_id, false, &error)) {
     LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
                  << ": " << error;
@@ -323,16 +329,14 @@ ExtensionService::ExtensionService(Profile* profile,
       system_(extensions::ExtensionSystem::Get(profile)),
       extension_prefs_(extension_prefs),
       blacklist_(blacklist),
-      settings_frontend_(extensions::SettingsFrontend::Create(profile)),
       extension_sync_service_(NULL),
-      pending_extension_manager_(*this),
+      registry_(extensions::ExtensionRegistry::Get(profile)),
+      pending_extension_manager_(*this, profile),
       install_directory_(install_directory),
       extensions_enabled_(extensions_enabled),
       show_extensions_prompts_(true),
       install_updates_when_idle_(true),
       ready_(ready),
-      toolbar_model_(this),
-      menu_manager_(profile),
       update_once_all_providers_are_ready_(false),
       browser_terminating_(false),
       installs_delayed_for_gc_(false),
@@ -343,17 +347,14 @@ ExtensionService::ExtensionService(Profile* profile,
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
   // Figure out if extension installation should be enabled.
-  if (command_line->HasSwitch(switches::kDisableExtensions) ||
-      profile->GetPrefs()->GetBoolean(prefs::kDisableExtensions)) {
+  if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
+          *command_line, profile))
     extensions_enabled_ = false;
-  }
 
   registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
                  content::NotificationService::AllBrowserContextsAndSources());
   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
                  content::NotificationService::AllBrowserContextsAndSources());
-  registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED,
-                 content::NotificationService::AllBrowserContextsAndSources());
   registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
                  content::NotificationService::AllBrowserContextsAndSources());
   registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
@@ -362,9 +363,11 @@ ExtensionService::ExtensionService(Profile* profile,
   base::Closure callback =
       base::Bind(&ExtensionService::OnExtensionInstallPrefChanged,
                  base::Unretained(this));
-  pref_change_registrar_.Add(prefs::kExtensionInstallAllowList, callback);
-  pref_change_registrar_.Add(prefs::kExtensionInstallDenyList, callback);
-  pref_change_registrar_.Add(prefs::kExtensionAllowedTypes, callback);
+  pref_change_registrar_.Add(extensions::pref_names::kInstallAllowList,
+                             callback);
+  pref_change_registrar_.Add(extensions::pref_names::kInstallDenyList,
+                             callback);
+  pref_change_registrar_.Add(extensions::pref_names::kAllowedTypes, callback);
 
   // Set up the ExtensionUpdater
   if (autoupdate_enabled) {
@@ -374,25 +377,28 @@ ExtensionService::ExtensionService(Profile* profile,
           switches::kExtensionsUpdateFrequency),
           &update_frequency);
     }
-    updater_.reset(new extensions::ExtensionUpdater(this,
-                                                    extension_prefs,
-                                                    profile->GetPrefs(),
-                                                    profile,
-                                                    update_frequency));
+    updater_.reset(new extensions::ExtensionUpdater(
+        this,
+        extension_prefs,
+        profile->GetPrefs(),
+        profile,
+        update_frequency,
+        extensions::ExtensionCache::GetInstance()));
   }
 
   component_loader_.reset(
       new extensions::ComponentLoader(this,
                                       profile->GetPrefs(),
-                                      g_browser_process->local_state()));
+                                      g_browser_process->local_state(),
+                                      profile));
 
   if (extensions_enabled_) {
     extensions::ExternalProviderImpl::CreateExternalProviders(
         this, profile_, &external_extension_providers_);
   }
 
-  // Set this as the ExtensionService for extension sorting to ensure it
-  // cause syncs if required.
+  // Set this as the ExtensionService for app sorting to ensure it causes syncs
+  // if required.
   is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
 
 #if defined(ENABLE_EXTENSIONS)
@@ -408,35 +414,13 @@ ExtensionService::ExtensionService(Profile* profile,
 }
 
 const ExtensionSet* ExtensionService::extensions() const {
-  return &extensions_;
-}
-
-const ExtensionSet* ExtensionService::disabled_extensions() const {
-  return &disabled_extensions_;
-}
-
-const ExtensionSet* ExtensionService::terminated_extensions() const {
-  return &terminated_extensions_;
-}
-
-const ExtensionSet* ExtensionService::blacklisted_extensions() const {
-  return &blacklisted_extensions_;
+  return &registry_->enabled_extensions();
 }
 
 const ExtensionSet* ExtensionService::delayed_installs() const {
   return &delayed_installs_;
 }
 
-scoped_ptr<const ExtensionSet>
-    ExtensionService::GenerateInstalledExtensionsSet() const {
-  scoped_ptr<ExtensionSet> installed_extensions(new ExtensionSet());
-  installed_extensions->InsertAll(extensions_);
-  installed_extensions->InsertAll(disabled_extensions_);
-  installed_extensions->InsertAll(terminated_extensions_);
-  installed_extensions->InsertAll(blacklisted_extensions_);
-  return installed_extensions.PassAs<const ExtensionSet>();
-}
-
 extensions::PendingExtensionManager*
     ExtensionService::pending_extension_manager() {
   return &pending_extension_manager_;
@@ -461,53 +445,24 @@ void ExtensionService::Shutdown() {
 
 const Extension* ExtensionService::GetExtensionById(
     const std::string& id, bool include_disabled) const {
-  int include_mask = INCLUDE_ENABLED;
+  int include_mask = ExtensionRegistry::ENABLED;
   if (include_disabled) {
     // Include blacklisted extensions here because there are hundreds of
     // callers of this function, and many might assume that this includes those
     // that have been disabled due to blacklisting.
-    include_mask |= INCLUDE_DISABLED | INCLUDE_BLACKLISTED;
+    include_mask |= ExtensionRegistry::DISABLED |
+                    ExtensionRegistry::BLACKLISTED;
   }
-  return GetExtensionById(id, include_mask);
-}
-
-GURL ExtensionService::GetSiteForExtensionId(const std::string& extension_id) {
-  return content::SiteInstance::GetSiteForURL(
-      profile_,
-      Extension::GetBaseURLFromExtensionId(extension_id));
-}
-
-const Extension* ExtensionService::GetExtensionById(
-    const std::string& id, int include_mask) const {
-  std::string lowercase_id = StringToLowerASCII(id);
-  if (include_mask & INCLUDE_ENABLED) {
-    const Extension* extension = extensions_.GetByID(lowercase_id);
-    if (extension)
-      return extension;
-  }
-  if (include_mask & INCLUDE_DISABLED) {
-    const Extension* extension = disabled_extensions_.GetByID(lowercase_id);
-    if (extension)
-      return extension;
-  }
-  if (include_mask & INCLUDE_TERMINATED) {
-    const Extension* extension = terminated_extensions_.GetByID(lowercase_id);
-    if (extension)
-      return extension;
-  }
-  if (include_mask & INCLUDE_BLACKLISTED) {
-    const Extension* extension = blacklisted_extensions_.GetByID(lowercase_id);
-    if (extension)
-      return extension;
-  }
-  return NULL;
+  return registry_->GetExtensionById(id, include_mask);
 }
 
 void ExtensionService::Init() {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
+  base::Time begin_time = base::Time::Now();
+
   DCHECK(!is_ready());  // Can't redo init.
-  DCHECK_EQ(extensions_.size(), 0u);
+  DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
 
   const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
   if (cmd_line->HasSwitch(switches::kInstallFromWebstore) ||
@@ -526,8 +481,9 @@ void ExtensionService::Init() {
 
     // Attempt to re-enable extensions whose only disable reason is reloading.
     std::vector<std::string> extensions_to_enable;
-    for (ExtensionSet::const_iterator iter = disabled_extensions_.begin();
-        iter != disabled_extensions_.end(); ++iter) {
+    const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
+    for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
+        iter != disabled_extensions.end(); ++iter) {
       const Extension* e = iter->get();
       if (extension_prefs_->GetDisableReasons(e->id()) ==
           Extension::DISABLE_RELOAD) {
@@ -573,6 +529,7 @@ void ExtensionService::Init() {
     // rather than running immediately at startup.
     CheckForExternalUpdates();
 
+
     base::MessageLoop::current()->PostDelayedTask(
         FROM_HERE,
         base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
@@ -584,11 +541,32 @@ void ExtensionService::Init() {
     }
     system_->management_policy()->RegisterProvider(
         shared_module_policy_provider_.get());
+
+    LoadGreylistFromPrefs();
+  }
+
+  UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
+                      base::Time::Now() - begin_time);
+}
+
+void ExtensionService::LoadGreylistFromPrefs() {
+  scoped_ptr<ExtensionSet> all_extensions =
+      registry_->GenerateInstalledExtensionsSet();
+
+  for (ExtensionSet::const_iterator it = all_extensions->begin();
+       it != all_extensions->end(); ++it) {
+    extensions::BlacklistState state =
+        extension_prefs_->GetExtensionBlacklistState((*it)->id());
+    if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
+        state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
+        state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
+      greylist_.Insert(*it);
   }
 }
 
 bool ExtensionService::UpdateExtension(const std::string& id,
                                        const base::FilePath& extension_path,
+                                       bool file_ownership_passed,
                                        const GURL& download_url,
                                        CrxInstaller** out_crx_installer) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
@@ -660,9 +638,15 @@ bool ExtensionService::UpdateExtension(const std::string& id,
   if (extension && extension->was_installed_by_default())
     creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
 
+  if (extension && extension->was_installed_by_oem())
+    creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
+
+  if (extension && extension->is_ephemeral())
+    creation_flags |= Extension::IS_EPHEMERAL;
+
   installer->set_creation_flags(creation_flags);
 
-  installer->set_delete_source(true);
+  installer->set_delete_source(file_ownership_passed);
   installer->set_download_url(download_url);
   installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
   installer->InstallCrx(extension_path);
@@ -691,7 +675,7 @@ void ExtensionService::ReloadExtension(const std::string extension_id) {
     // the inspector and hang onto a cookie for it, so that we can reattach
     // later.
     // TODO(yoz): this is not incognito-safe!
-    ExtensionProcessManager* manager = system_->process_manager();
+    extensions::ProcessManager* manager = system_->process_manager();
     extensions::ExtensionHost* host =
         manager->GetBackgroundHostForExtension(extension_id);
     if (host && DevToolsAgentHost::HasFor(host->render_view_host())) {
@@ -704,7 +688,7 @@ void ExtensionService::ReloadExtension(const std::string extension_id) {
 
     path = current_extension->path();
     // BeingUpgraded is set back to false when the extension is added.
-    SetBeingUpgraded(current_extension, true);
+    system_->runtime_data()->SetBeingUpgraded(current_extension, true);
     DisableExtension(extension_id, Extension::DISABLE_RELOAD);
     reloading_extensions_.insert(extension_id);
   } else {
@@ -747,7 +731,7 @@ void ExtensionService::ReloadExtension(const std::string extension_id) {
 bool ExtensionService::UninstallExtension(
     std::string extension_id,
     bool external_uninstall,
-    string16* error) {
+    base::string16* error) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
   scoped_refptr<const Extension> extension(GetInstalledExtension(extension_id));
@@ -774,6 +758,8 @@ bool ExtensionService::UninstallExtension(
         extension.get(), is_ready());
   }
 
+  system_->install_verifier()->Remove(extension->id());
+
   if (IsUnacknowledgedExternalExtension(extension.get())) {
     UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
                               EXTERNAL_EXTENSION_UNINSTALLED,
@@ -808,27 +794,10 @@ bool ExtensionService::UninstallExtension(
       NOTREACHED();
   }
 
-  GURL launch_web_url_origin(
-      extensions::AppLaunchInfo::GetLaunchWebURL(extension.get()).GetOrigin());
-  bool is_storage_isolated =
-      extensions::AppIsolationInfo::HasIsolatedStorage(extension.get());
-
-  if (is_storage_isolated) {
-    BrowserContext::AsyncObliterateStoragePartition(
-        profile_,
-        GetSiteForExtensionId(extension_id),
-        base::Bind(&ExtensionService::OnNeedsToGarbageCollectIsolatedStorage,
-                   AsWeakPtr()));
-  } else {
-    if (extension->is_hosted_app() &&
-        !profile_->GetExtensionSpecialStoragePolicy()->
-            IsStorageProtected(launch_web_url_origin)) {
-      extensions::DataDeleter::StartDeleting(
-          profile_, extension_id, launch_web_url_origin);
-    }
-    extensions::DataDeleter::StartDeleting(profile_, extension_id,
-                                           extension->url());
-  }
+  // Do not remove the data of ephemeral apps. They will be garbage collected by
+  // EphemeralAppService.
+  if (!extension->is_ephemeral())
+    extensions::DataDeleter::StartDeleting(profile_, extension.get());
 
   UntrackTerminatedExtension(extension_id);
 
@@ -858,13 +827,13 @@ bool ExtensionService::UninstallExtension(
 
 bool ExtensionService::IsExtensionEnabled(
     const std::string& extension_id) const {
-  if (extensions_.Contains(extension_id) ||
-      terminated_extensions_.Contains(extension_id)) {
+  if (registry_->enabled_extensions().Contains(extension_id) ||
+      registry_->terminated_extensions().Contains(extension_id)) {
     return true;
   }
 
-  if (disabled_extensions_.Contains(extension_id) ||
-      blacklisted_extensions_.Contains(extension_id)) {
+  if (registry_->disabled_extensions().Contains(extension_id) ||
+      registry_->blacklisted_extensions().Contains(extension_id)) {
     return false;
   }
 
@@ -874,23 +843,13 @@ bool ExtensionService::IsExtensionEnabled(
          !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
 }
 
-bool ExtensionService::IsExternalExtensionUninstalled(
-    const std::string& extension_id) const {
-  return extension_prefs_->IsExternalExtensionUninstalled(extension_id);
-}
-
-bool ExtensionService::IsExtensionEnabledForLauncher(
-    const std::string& extension_id) const {
-  return IsExtensionEnabled(extension_id) &&
-      !GetTerminatedExtension(extension_id);
-}
-
 void ExtensionService::EnableExtension(const std::string& extension_id) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
   if (IsExtensionEnabled(extension_id))
     return;
-  const Extension* extension = disabled_extensions_.GetByID(extension_id);
+  const Extension* extension =
+      registry_->disabled_extensions().GetByID(extension_id);
 
   ManagementPolicy* policy = system_->management_policy();
   if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
@@ -923,8 +882,8 @@ void ExtensionService::EnableExtension(const std::string& extension_id) {
   }
 
   // Move it over to the enabled list.
-  extensions_.Insert(make_scoped_refptr(extension));
-  disabled_extensions_.Remove(extension->id());
+  registry_->AddEnabled(make_scoped_refptr(extension));
+  registry_->RemoveDisabled(extension->id());
 
   NotifyExtensionLoaded(extension);
 
@@ -959,23 +918,24 @@ void ExtensionService::DisableExtension(
   extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
   extension_prefs_->AddDisableReason(extension_id, disable_reason);
 
-  int include_mask = INCLUDE_EVERYTHING & ~INCLUDE_DISABLED;
-  extension = GetExtensionById(extension_id, include_mask);
+  int include_mask =
+      ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
+  extension = registry_->GetExtensionById(extension_id, include_mask);
   if (!extension)
     return;
 
-  // Reset the background_page_ready flag
-  if (extensions::BackgroundInfo::HasBackgroundPage(extension))
-    extension_runtime_data_[extension->id()].background_page_ready = false;
+  // The extension is either enabled or terminated.
+  DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
+         registry_->terminated_extensions().Contains(extension->id()));
 
   // Move it over to the disabled list. Don't send a second unload notification
   // for terminated extensions being disabled.
-  disabled_extensions_.Insert(make_scoped_refptr(extension));
-  if (extensions_.Contains(extension->id())) {
-    extensions_.Remove(extension->id());
+  registry_->AddDisabled(make_scoped_refptr(extension));
+  if (registry_->enabled_extensions().Contains(extension->id())) {
+    registry_->RemoveEnabled(extension->id());
     NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
   } else {
-    terminated_extensions_.Remove(extension->id());
+    registry_->RemoveTerminated(extension->id());
   }
 
   if (extension_sync_service_)
@@ -988,14 +948,19 @@ void ExtensionService::DisableUserExtensions(
       system_->management_policy();
   extensions::ExtensionList to_disable;
 
-  for (ExtensionSet::const_iterator extension = extensions_.begin();
-      extension != extensions_.end(); ++extension) {
-    if (management_policy->UserMayModifySettings(extension->get(), NULL))
+  // TODO(rlp): Clean up this code. crbug.com/353266.
+  const ExtensionSet& enabled_set = registry_->enabled_extensions();
+  for (ExtensionSet::const_iterator extension = enabled_set.begin();
+      extension != enabled_set.end(); ++extension) {
+    if (management_policy->UserMayModifySettings(extension->get(), NULL) &&
+        extension->get()->location() != Manifest::EXTERNAL_COMPONENT)
       to_disable.push_back(*extension);
   }
-  for (ExtensionSet::const_iterator extension = terminated_extensions_.begin();
-      extension != terminated_extensions_.end(); ++extension) {
-    if (management_policy->UserMayModifySettings(extension->get(), NULL))
+  const ExtensionSet& terminated_set = registry_->terminated_extensions();
+  for (ExtensionSet::const_iterator extension = terminated_set.begin();
+      extension != terminated_set.end(); ++extension) {
+    if (management_policy->UserMayModifySettings(extension->get(), NULL) &&
+        extension->get()->location() != Manifest::EXTERNAL_COMPONENT)
       to_disable.push_back(*extension);
   }
 
@@ -1082,19 +1047,23 @@ void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
   //
   // NOTE: It is important that this happen after notifying the renderers about
   // the new extensions so that if we navigate to an extension URL in
-  // NOTIFICATION_EXTENSION_LOADED, the renderer is guaranteed to know about it.
+  // ExtensionRegistryObserver::OnLoaded or NOTIFICATION_EXTENSION_LOADED, the
+  // renderer is guaranteed to know about it.
+  registry_->TriggerOnLoaded(extension);
+
   content::NotificationService::current()->Notify(
       chrome::NOTIFICATION_EXTENSION_LOADED,
       content::Source<Profile>(profile_),
       content::Details<const Extension>(extension));
 
-  // Tell a random-ass collection of other subsystems about the new extension.
-  // TODO(aa): What should we do with all this goop? Can it move into the
-  // relevant objects via EXTENSION_LOADED?
-
+  // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
+  // BrowserContextKeyedService and use ExtensionRegistryObserver.
   profile_->GetExtensionSpecialStoragePolicy()->
       GrantRightsForExtension(extension);
 
+  // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
+  // work properly multi-profile. Besides which, it should be using
+  // ExtensionRegistryObserver. See http://crbug.com/355029.
   UpdateActiveExtensionsInCrashReporter();
 
   // If the extension has permission to load chrome://favicon/ resources we need
@@ -1127,9 +1096,11 @@ void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
 void ExtensionService::NotifyExtensionUnloaded(
     const Extension* extension,
     UnloadedExtensionInfo::Reason reason) {
+  registry_->TriggerOnUnloaded(extension);
+
   UnloadedExtensionInfo details(extension, reason);
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_UNLOADED,
+      chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
       content::Source<Profile>(profile_),
       content::Details<UnloadedExtensionInfo>(&details));
 
@@ -1144,6 +1115,9 @@ void ExtensionService::NotifyExtensionUnloaded(
   }
 
   system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
+
+  // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
+  // BrowserContextKeyedService and use ExtensionRegistryObserver.
   profile_->GetExtensionSpecialStoragePolicy()->
       RevokeRightsForExtension(extension);
 
@@ -1151,8 +1125,8 @@ void ExtensionService::NotifyExtensionUnloaded(
   // Revoke external file access for the extension from its file system context.
   // It is safe to access the extension's storage partition at this point. The
   // storage partition may get destroyed only after the extension gets unloaded.
-  GURL site = extensions::ExtensionSystem::Get(profile_)->extension_service()->
-      GetSiteForExtensionId(extension->id());
+  GURL site =
+      extensions::util::GetSiteForExtensionId(extension->id(), profile_);
   fileapi::FileSystemContext* filesystem_context =
       BrowserContext::GetStoragePartitionForSite(profile_, site)->
           GetFileSystemContext();
@@ -1162,6 +1136,9 @@ void ExtensionService::NotifyExtensionUnloaded(
   }
 #endif
 
+  // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
+  // work properly multi-profile. Besides which, it should be using
+  // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
   UpdateActiveExtensionsInCrashReporter();
 }
 
@@ -1169,20 +1146,10 @@ Profile* ExtensionService::profile() {
   return profile_;
 }
 
-extensions::ExtensionPrefs* ExtensionService::extension_prefs() {
-  return extension_prefs_;
-}
-
-const extensions::ExtensionPrefs* ExtensionService::extension_prefs() const {
-  return extension_prefs_;
-}
-
-extensions::SettingsFrontend* ExtensionService::settings_frontend() {
-  return settings_frontend_.get();
-}
-
-extensions::ContentSettingsStore* ExtensionService::GetContentSettingsStore() {
-  return extension_prefs()->content_settings_store();
+content::BrowserContext* ExtensionService::GetBrowserContext() const {
+  // Implemented in the .cc file to avoid adding a profile.h dependency to
+  // extension_service.h.
+  return profile_;
 }
 
 bool ExtensionService::is_ready() {
@@ -1215,8 +1182,9 @@ void ExtensionService::CheckManagementPolicy() {
 
   // Loop through the extensions list, finding extensions we need to unload or
   // disable.
-  for (ExtensionSet::const_iterator iter = extensions_.begin();
-       iter != extensions_.end(); ++iter) {
+  const ExtensionSet& extensions = registry_->enabled_extensions();
+  for (ExtensionSet::const_iterator iter = extensions.begin();
+       iter != extensions.end(); ++iter) {
     const Extension* extension = (iter->get());
     if (!system_->management_policy()->UserMayLoad(extension, NULL))
       to_unload.push_back(extension->id());
@@ -1249,21 +1217,6 @@ void ExtensionService::CheckForUpdatesSoon() {
   }
 }
 
-void ExtensionService::OnExtensionMoved(
-    const std::string& moved_extension_id,
-    const std::string& predecessor_extension_id,
-    const std::string& successor_extension_id) {
-  extension_prefs_->extension_sorting()->OnExtensionMoved(
-      moved_extension_id,
-      predecessor_extension_id,
-      successor_extension_id);
-
-  const Extension* extension = GetInstalledExtension(moved_extension_id);
-  if (extension_sync_service_ && extension) {
-    extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
-  }
-}
-
 // Some extensions will autoupdate themselves externally from Chrome.  These
 // are typically part of some larger client application package.  To support
 // these, the extension will register its location in the the preferences file
@@ -1326,7 +1279,9 @@ void ExtensionService::OnAllExternalProvidersReady() {
   // Install any pending extensions.
   if (update_once_all_providers_are_ready_ && updater()) {
     update_once_all_providers_are_ready_ = false;
-    updater()->CheckNow(extensions::ExtensionUpdater::CheckParams());
+    extensions::ExtensionUpdater::CheckParams params;
+    params.callback = external_updates_finished_callback_;
+    updater()->CheckNow(params);
   }
 
   // Uninstall all the unclaimed extensions.
@@ -1372,8 +1327,9 @@ bool ExtensionService::PopulateExtensionErrorUI(
   bool needs_alert = false;
 
   // Extensions that are blacklisted.
-  for (ExtensionSet::const_iterator it = blacklisted_extensions_.begin();
-       it != blacklisted_extensions_.end(); ++it) {
+  const ExtensionSet& blacklisted_set = registry_->blacklisted_extensions();
+  for (ExtensionSet::const_iterator it = blacklisted_set.begin();
+       it != blacklisted_set.end(); ++it) {
     std::string id = (*it)->id();
     if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(id)) {
       extension_error_ui->AddBlacklistedExtension(id);
@@ -1381,10 +1337,16 @@ bool ExtensionService::PopulateExtensionErrorUI(
     }
   }
 
-  for (ExtensionSet::const_iterator iter = extensions_.begin();
-       iter != extensions_.end(); ++iter) {
+  const ExtensionSet& enabled_set = registry_->enabled_extensions();
+  for (ExtensionSet::const_iterator iter = enabled_set.begin();
+       iter != enabled_set.end(); ++iter) {
     const Extension* e = iter->get();
 
+    // Skip for extensions that have pending updates. They will be checked again
+    // once the pending update is finished.
+    if (pending_extension_manager()->IsIdPending(e->id()))
+      continue;
+
     // Extensions disabled by policy. Note: this no longer includes blacklisted
     // extensions, though we still show the same UI.
     if (!system_->management_policy()->UserMayLoad(e, NULL)) {
@@ -1429,44 +1391,45 @@ bool ExtensionService::IsUnacknowledgedExternalExtension(
 }
 
 void ExtensionService::ReconcileKnownDisabled() {
-  ExtensionIdSet known_disabled_ids = extension_prefs_->GetKnownDisabled();
-  if (known_disabled_ids.empty()) {
-    if (!disabled_extensions_.is_empty()) {
-      extension_prefs_->SetKnownDisabled(disabled_extensions_.GetIDs());
-      UMA_HISTOGRAM_BOOLEAN("Extensions.KnownDisabledInitialized", true);
-    }
-  } else {
-    // Both |known_disabled_ids| and |extensions_| are ordered (by definition
-    // of std::map and std::set). Iterate forward over both sets in parallel
-    // to find matching IDs and disable the corresponding extensions.
-    ExtensionSet::const_iterator extensions_it = extensions_.begin();
-    ExtensionIdSet::const_iterator known_disabled_ids_it =
-        known_disabled_ids.begin();
-    int known_disabled_count = 0;
-    while (extensions_it != extensions_.end() &&
-           known_disabled_ids_it != known_disabled_ids.end()) {
-      const std::string& extension_id = extensions_it->get()->id();
-      const int comparison = extension_id.compare(*known_disabled_ids_it);
-      if (comparison < 0) {
-        ++extensions_it;
-      } else if (comparison > 0) {
-        ++known_disabled_ids_it;
-      } else {
-        ++known_disabled_count;
-        // Advance |extensions_it| immediately as it will be invalidated upon
-        // disabling the extension it points to.
-        ++extensions_it;
-        ++known_disabled_ids_it;
-        DisableExtension(extension_id, Extension::DISABLE_KNOWN_DISABLED);
-      }
+  ExtensionIdSet known_disabled_ids;
+  if (!extension_prefs_->GetKnownDisabled(&known_disabled_ids)) {
+    extension_prefs_->SetKnownDisabled(
+        registry_->disabled_extensions().GetIDs());
+    UMA_HISTOGRAM_BOOLEAN("Extensions.KnownDisabledInitialized", true);
+    return;
+  }
+
+  // Both |known_disabled_ids| and |extensions| are ordered (by definition
+  // of std::map and std::set). Iterate forward over both sets in parallel
+  // to find matching IDs and disable the corresponding extensions.
+  const ExtensionSet& enabled_set = registry_->enabled_extensions();
+  ExtensionSet::const_iterator extensions_it = enabled_set.begin();
+  ExtensionIdSet::const_iterator known_disabled_ids_it =
+      known_disabled_ids.begin();
+  int known_disabled_count = 0;
+  while (extensions_it != enabled_set.end() &&
+         known_disabled_ids_it != known_disabled_ids.end()) {
+    const std::string& extension_id = extensions_it->get()->id();
+    const int comparison = extension_id.compare(*known_disabled_ids_it);
+    if (comparison < 0) {
+      ++extensions_it;
+    } else if (comparison > 0) {
+      ++known_disabled_ids_it;
+    } else {
+      ++known_disabled_count;
+      // Advance |extensions_it| immediately as it will be invalidated upon
+      // disabling the extension it points to.
+      ++extensions_it;
+      ++known_disabled_ids_it;
+      DisableExtension(extension_id, Extension::DISABLE_KNOWN_DISABLED);
     }
-    UMA_HISTOGRAM_COUNTS_100("Extensions.KnownDisabledReDisabled",
-                             known_disabled_count);
   }
+  UMA_HISTOGRAM_COUNTS_100("Extensions.KnownDisabledReDisabled",
+                           known_disabled_count);
 
   // Update the list of known disabled to reflect every change to
   // |disabled_extensions_| from this point forward.
-  disabled_extensions_.set_modification_callback(
+  registry_->SetDisabledModificationCallback(
       base::Bind(&extensions::ExtensionPrefs::SetKnownDisabled,
                  base::Unretained(extension_prefs_)));
 }
@@ -1484,8 +1447,9 @@ void ExtensionService::UpdateExternalExtensionAlert() {
     return;
 
   const Extension* extension = NULL;
-  for (ExtensionSet::const_iterator iter = disabled_extensions_.begin();
-       iter != disabled_extensions_.end(); ++iter) {
+  const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
+  for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
+       iter != disabled_extensions.end(); ++iter) {
     const Extension* e = iter->get();
     if (IsUnacknowledgedExternalExtension(e)) {
       extension = e;
@@ -1534,9 +1498,10 @@ void ExtensionService::UnloadExtension(
     const std::string& extension_id,
     UnloadedExtensionInfo::Reason reason) {
   // Make sure the extension gets deleted after we return from this function.
-  int include_mask = INCLUDE_EVERYTHING & ~INCLUDE_TERMINATED;
+  int include_mask =
+      ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
   scoped_refptr<const Extension> extension(
-      GetExtensionById(extension_id, include_mask));
+      registry_->GetExtensionById(extension_id, include_mask));
 
   // This method can be called via PostTask, so the extension may have been
   // unloaded by the time this runs.
@@ -1547,11 +1512,6 @@ void ExtensionService::UnloadExtension(
     return;
   }
 
-  // If uninstalling let RuntimeEventRouter know.
-  if (reason == UnloadedExtensionInfo::REASON_UNINSTALL)
-    extensions::RuntimeEventRouter::OnExtensionUninstalled(
-        profile_, extension_id);
-
   // Keep information about the extension so that we can reload it later
   // even if it's not permanently installed.
   unloaded_extension_paths_[extension->id()] = extension->path();
@@ -1559,18 +1519,17 @@ void ExtensionService::UnloadExtension(
   // Clean up if the extension is meant to be enabled after a reload.
   reloading_extensions_.erase(extension->id());
 
-  // Clean up runtime data.
-  extension_runtime_data_.erase(extension_id);
-
-  if (disabled_extensions_.Contains(extension->id())) {
-    disabled_extensions_.Remove(extension->id());
+  if (registry_->disabled_extensions().Contains(extension->id())) {
+    registry_->RemoveDisabled(extension->id());
     // Make sure the profile cleans up its RequestContexts when an already
     // disabled extension is unloaded (since they are also tracking the disabled
     // extensions).
     system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
+    // Don't send the unloaded notification. It was sent when the extension
+    // was disabled.
   } else {
-    // Remove the extension from our list.
-    extensions_.Remove(extension->id());
+    // Remove the extension from the enabled list.
+    registry_->RemoveEnabled(extension->id());
     NotifyExtensionUnloaded(extension.get(), reason);
   }
 
@@ -1591,21 +1550,14 @@ void ExtensionService::RemoveComponentExtension(
       content::Details<const Extension>(extension.get()));
 }
 
-void ExtensionService::UnloadAllExtensions() {
-  profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
-
-  extensions_.Clear();
-  disabled_extensions_.Clear();
-  terminated_extensions_.Clear();
-  extension_runtime_data_.clear();
-
-  // TODO(erikkay) should there be a notification for this?  We can't use
-  // EXTENSION_UNLOADED since that implies that the extension has been disabled
-  // or uninstalled, and UnloadAll is just part of shutdown.
+void ExtensionService::UnloadAllExtensionsForTest() {
+  UnloadAllExtensionsInternal();
 }
 
-void ExtensionService::ReloadExtensions() {
-  UnloadAllExtensions();
+void ExtensionService::ReloadExtensionsForTest() {
+  // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
+  // warning about calling test code in production.
+  UnloadAllExtensionsInternal();
   component_loader_->LoadAll();
   extensions::InstalledLoader(this).LoadAllExtensions();
   // Don't call SetReadyAndNotifyListeners() since tests call this multiple
@@ -1694,7 +1646,7 @@ void ExtensionService::AddExtension(const Extension* extension) {
     if (!Manifest::IsUnpackedLocation(extension->location()))
       CHECK_GE(version_compare_result, 0);
   }
-  SetBeingUpgraded(extension, is_extension_upgrade);
+  system_->runtime_data()->SetBeingUpgraded(extension, is_extension_upgrade);
 
   // The extension is now loaded, remove its data from unloaded extension map.
   unloaded_extension_paths_.erase(extension->id());
@@ -1720,10 +1672,10 @@ void ExtensionService::AddExtension(const Extension* extension) {
     // blacklist before calling into here, e.g. CrxInstaller checks before
     // installation then threads through the install and pending install flow
     // of this class, and we check when loading installed extensions.
-    blacklisted_extensions_.Insert(extension);
+    registry_->AddBlacklisted(extension);
   } else if (!reloading &&
              extension_prefs_->IsExtensionDisabled(extension->id())) {
-    disabled_extensions_.Insert(extension);
+    registry_->AddDisabled(extension);
     if (extension_sync_service_)
       extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
     content::NotificationService::current()->Notify(
@@ -1739,26 +1691,25 @@ void ExtensionService::AddExtension(const Extension* extension) {
     }
   } else if (reloading) {
     // Replace the old extension with the new version.
-    CHECK(!disabled_extensions_.Insert(extension));
+    CHECK(!registry_->AddDisabled(extension));
     EnableExtension(extension->id());
   } else {
     // All apps that are displayed in the launcher are ordered by their ordinals
     // so we must ensure they have valid ordinals.
     if (extension->RequiresSortOrdinal()) {
       if (!extension->ShouldDisplayInNewTabPage()) {
-        extension_prefs_->extension_sorting()->MarkExtensionAsHidden(
-            extension->id());
+        extension_prefs_->app_sorting()->MarkExtensionAsHidden(extension->id());
       }
-      extension_prefs_->extension_sorting()->EnsureValidOrdinals(
+      extension_prefs_->app_sorting()->EnsureValidOrdinals(
           extension->id(), syncer::StringOrdinal());
     }
 
-    extensions_.Insert(extension);
+    registry_->AddEnabled(extension);
     if (extension_sync_service_)
       extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
     NotifyExtensionLoaded(extension);
   }
-  SetBeingUpgraded(extension, false);
+  system_->runtime_data()->SetBeingUpgraded(extension, false);
 }
 
 void ExtensionService::AddComponentExtension(const Extension* extension) {
@@ -1766,6 +1717,7 @@ void ExtensionService::AddComponentExtension(const Extension* extension) {
       extension_prefs_->GetVersionString(extension->id()));
   const Version old_version(old_version_string);
 
+  VLOG(1) << "AddComponentExtension " << extension->name();
   if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
     VLOG(1) << "Component extension " << extension->name() << " ("
         << extension->id() << ") installing/upgrading from '"
@@ -1773,8 +1725,9 @@ void ExtensionService::AddComponentExtension(const Extension* extension) {
 
     AddNewOrUpdatedExtension(extension,
                              Extension::ENABLED_COMPONENT,
-                             extensions::Blacklist::NOT_BLACKLISTED,
-                             syncer::StringOrdinal());
+                             extensions::NOT_BLACKLISTED,
+                             syncer::StringOrdinal(),
+                             std::string());
     return;
   }
 
@@ -1786,7 +1739,7 @@ void ExtensionService::UpdateActivePermissions(const Extension* extension) {
   // custom set of active permissions defined in the extension prefs. Here,
   // we update the extension's active permissions based on the prefs.
   scoped_refptr<PermissionSet> active_permissions =
-      extension_prefs()->GetActivePermissions(extension->id());
+      extension_prefs_->GetActivePermissions(extension->id());
 
   if (active_permissions.get()) {
     // We restrict the active permissions to be within the bounds defined in the
@@ -1842,7 +1795,7 @@ void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
 
   bool auto_grant_permission =
       (!is_extension_installed && extension->was_installed_by_default()) ||
-      chrome::IsRunningInForcedAppMode();
+      extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
   // Silently grant all active permissions to default apps only on install.
   // After install they should behave like other apps.
   // Silently grant all active permissions to apps install in kiosk mode on both
@@ -1915,13 +1868,17 @@ void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
 
 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
   std::set<std::string> extension_ids;
-  for (ExtensionSet::const_iterator iter = extensions_.begin();
-       iter != extensions_.end(); ++iter) {
+  const ExtensionSet& extensions = registry_->enabled_extensions();
+  for (ExtensionSet::const_iterator iter = extensions.begin();
+       iter != extensions.end(); ++iter) {
     const Extension* extension = iter->get();
     if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
       extension_ids.insert(extension->id());
   }
 
+  // TODO(kalman): This is broken. ExtensionService is per-profile.
+  // crash_keys::SetActiveExtensions is per-process. See
+  // http://crbug.com/355029.
   crash_keys::SetActiveExtensions(extension_ids);
 }
 
@@ -1989,9 +1946,9 @@ scoped_ptr<const ExtensionSet>
   scoped_ptr<ExtensionSet> dependents(new ExtensionSet());
   scoped_ptr<ExtensionSet> set_to_check(new ExtensionSet());
   if (SharedModuleInfo::IsSharedModule(extension)) {
-    set_to_check->InsertAll(disabled_extensions_);
+    set_to_check->InsertAll(registry_->disabled_extensions());
     set_to_check->InsertAll(delayed_installs_);
-    set_to_check->InsertAll(extensions_);
+    set_to_check->InsertAll(registry_->enabled_extensions());
     for (ExtensionSet::const_iterator iter = set_to_check->begin();
          iter != set_to_check->end(); ++iter) {
       if (SharedModuleInfo::ImportsExtensionById(iter->get(),
@@ -2027,12 +1984,13 @@ void ExtensionService::OnExtensionInstalled(
     const Extension* extension,
     const syncer::StringOrdinal& page_ordinal,
     bool has_requirement_errors,
-    extensions::Blacklist::BlacklistState blacklist_state,
+    extensions::BlacklistState blacklist_state,
     bool wait_for_idle) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
   const std::string& id = extension->id();
   bool initial_enable = ShouldEnableOnInstall(extension);
+  std::string install_parameter;
   const extensions::PendingExtensionInfo* pending_extension_info = NULL;
   if ((pending_extension_info = pending_extension_manager()->GetById(id))) {
     if (!pending_extension_info->ShouldAllowInstall(extension)) {
@@ -2055,12 +2013,13 @@ void ExtensionService::OnExtensionInstalled(
       return;
     }
 
+    install_parameter = pending_extension_info->install_parameter();
     pending_extension_manager()->Remove(id);
   } else {
     // We explicitly want to re-enable an uninstalled external
     // extension; if we're here, that means the user is manually
     // installing the extension.
-    if (IsExternalExtensionUninstalled(id)) {
+    if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
       initial_enable = true;
     }
   }
@@ -2079,13 +2038,13 @@ void ExtensionService::OnExtensionInstalled(
     extension_prefs_->ClearDisableReasons(id);
   }
 
-  if (blacklist_state == extensions::Blacklist::BLACKLISTED_MALWARE) {
+  if (blacklist_state == extensions::BLACKLISTED_MALWARE) {
     // Installation of a blacklisted extension can happen from sync, policy,
     // etc, where to maintain consistency we need to install it, just never
     // load it (see AddExtension). Usually it should be the job of callers to
     // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
     // showing the install dialogue).
-    extension_prefs()->AcknowledgeBlacklistedExtension(id);
+    extension_prefs_->AcknowledgeBlacklistedExtension(id);
     UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
                               extension->location(),
                               Manifest::NUM_LOCATIONS);
@@ -2107,28 +2066,28 @@ void ExtensionService::OnExtensionInstalled(
 
   // Certain extension locations are specific enough that we can
   // auto-acknowledge any extension that came from one of them.
-  if (Manifest::IsPolicyLocation(extension->location()))
+  if (Manifest::IsPolicyLocation(extension->location()) ||
+      extension->location() == Manifest::EXTERNAL_COMPONENT)
     AcknowledgeExternalExtension(extension->id());
   const Extension::State initial_state =
       initial_enable ? Extension::ENABLED : Extension::DISABLED;
+  const bool blacklisted_for_malware =
+      blacklist_state == extensions::BLACKLISTED_MALWARE;
   if (ShouldDelayExtensionUpdate(id, wait_for_idle)) {
     extension_prefs_->SetDelayedInstallInfo(
         extension,
         initial_state,
-        blacklist_state,
+        blacklisted_for_malware,
         extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
-        page_ordinal);
+        page_ordinal,
+        install_parameter);
 
     // Transfer ownership of |extension|.
     delayed_installs_.Insert(extension);
 
-    // Notify extension of available update.
-    extensions::RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
-        profile_, id, extension->manifest()->value());
-
     // Notify observers that app update is available.
     FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
-                      OnAppUpdateAvailable(extension->id()));
+                      OnAppUpdateAvailable(extension));
     return;
   }
 
@@ -2137,39 +2096,48 @@ void ExtensionService::OnExtensionInstalled(
     extension_prefs_->SetDelayedInstallInfo(
         extension,
         initial_state,
-        blacklist_state,
+        blacklisted_for_malware,
         extensions::ExtensionPrefs::DELAY_REASON_GC,
-        page_ordinal);
+        page_ordinal,
+        install_parameter);
     delayed_installs_.Insert(extension);
   } else if (status != IMPORT_STATUS_OK) {
     if (status == IMPORT_STATUS_UNSATISFIED) {
       extension_prefs_->SetDelayedInstallInfo(
           extension,
           initial_state,
-          blacklist_state,
+          blacklisted_for_malware,
           extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
-          page_ordinal);
+          page_ordinal,
+          install_parameter);
       delayed_installs_.Insert(extension);
     }
   } else {
     AddNewOrUpdatedExtension(extension,
                              initial_state,
                              blacklist_state,
-                             page_ordinal);
+                             page_ordinal,
+                             install_parameter);
   }
 }
 
 void ExtensionService::AddNewOrUpdatedExtension(
     const Extension* extension,
     Extension::State initial_state,
-    extensions::Blacklist::BlacklistState blacklist_state,
-    const syncer::StringOrdinal& page_ordinal) {
+    extensions::BlacklistState blacklist_state,
+    const syncer::StringOrdinal& page_ordinal,
+    const std::string& install_parameter) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+  const bool blacklisted_for_malware =
+      blacklist_state == extensions::BLACKLISTED_MALWARE;
   extension_prefs_->OnExtensionInstalled(extension,
                                          initial_state,
-                                         blacklist_state,
-                                         page_ordinal);
+                                         blacklisted_for_malware,
+                                         page_ordinal,
+                                         install_parameter);
   delayed_installs_.Remove(extension->id());
+  if (InstallVerifier::NeedsVerification(*extension))
+    system_->install_verifier()->VerifyExtension(extension->id());
   FinishInstallation(extension);
 }
 
@@ -2186,7 +2154,7 @@ void ExtensionService::MaybeFinishDelayedInstallation(
   // only used for idle updates.
   if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
        reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
-       is_ready() && !IsExtensionIdle(extension_id))
+       is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
     return;
 
   const Extension* extension = delayed_installs_.GetByID(extension_id);
@@ -2278,16 +2246,17 @@ const Extension* ExtensionService::GetPendingExtensionUpdate(
 }
 
 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
-  if (!terminated_extensions_.Contains(extension->id()))
-    terminated_extensions_.Insert(make_scoped_refptr(extension));
-
+  // No need to check for duplicates; inserting a duplicate is a no-op.
+  registry_->AddTerminated(make_scoped_refptr(extension));
+  extensions_being_terminated_.erase(extension->id());
   UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
 }
 
 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
   std::string lowercase_id = StringToLowerASCII(id);
-  const Extension* extension = terminated_extensions_.GetByID(lowercase_id);
-  terminated_extensions_.Remove(lowercase_id);
+  const Extension* extension =
+      registry_->terminated_extensions().GetByID(lowercase_id);
+  registry_->RemoveTerminated(lowercase_id);
   if (extension) {
     content::NotificationService::current()->Notify(
         chrome::NOTIFICATION_EXTENSION_REMOVED,
@@ -2296,37 +2265,19 @@ void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
   }
 }
 
-const Extension* ExtensionService::GetTerminatedExtension(
-    const std::string& id) const {
-  return GetExtensionById(id, INCLUDE_TERMINATED);
-}
-
 const Extension* ExtensionService::GetInstalledExtension(
     const std::string& id) const {
-  int include_mask = INCLUDE_ENABLED |
-                     INCLUDE_DISABLED |
-                     INCLUDE_TERMINATED |
-                     INCLUDE_BLACKLISTED;
-  return GetExtensionById(id, include_mask);
+  return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
 }
 
 bool ExtensionService::ExtensionBindingsAllowed(const GURL& url) {
   // Allow bindings for all packaged extensions and component hosted apps.
-  const Extension* extension = extensions_.GetExtensionOrAppByURL(url);
+  const Extension* extension =
+      registry_->enabled_extensions().GetExtensionOrAppByURL(url);
   return extension && (!extension->is_hosted_app() ||
                        extension->location() == Manifest::COMPONENT);
 }
 
-bool ExtensionService::ShouldBlockUrlInBrowserTab(GURL* url) {
-  const Extension* extension = extensions_.GetExtensionOrAppByURL(*url);
-  if (extension && extension->is_platform_app()) {
-    *url = GURL(chrome::kExtensionInvalidRequestURL);
-    return true;
-  }
-
-  return false;
-}
-
 bool ExtensionService::OnExternalExtensionFileFound(
          const std::string& id,
          const Version* version,
@@ -2409,11 +2360,23 @@ void ExtensionService::ReportExtensionLoadError(
       content::Source<Profile>(profile_),
       content::Details<const std::string>(&error));
 
-  std::string path_str = UTF16ToUTF8(extension_path.LossyDisplayName());
-  string16 message = UTF8ToUTF16(base::StringPrintf(
-      "Could not load extension from '%s'. %s",
-      path_str.c_str(), error.c_str()));
-  ExtensionErrorReporter::GetInstance()->ReportError(message, be_noisy);
+  std::string path_str = base::UTF16ToUTF8(extension_path.LossyDisplayName());
+  bool retry = false;
+  std::string retry_prompt;
+  if (be_noisy)
+    retry_prompt = "\n\nWould you like to retry?";
+
+  base::string16 message = base::UTF8ToUTF16(
+      base::StringPrintf("Could not load extension from '%s'. %s%s",
+                         path_str.c_str(),
+                         error.c_str(),
+                         retry_prompt.c_str()));
+  ExtensionErrorReporter::GetInstance()->ReportError(message, be_noisy, &retry);
+  std::pair<bool, const base::FilePath&> details(retry, extension_path);
+  content::NotificationService::current()->Notify(
+      chrome::NOTIFICATION_EXTENSION_LOAD_RETRY,
+      content::Source<Profile>(profile_),
+      content::Details<std::pair<bool, const base::FilePath&> >(&details));
 }
 
 void ExtensionService::DidCreateRenderViewForBackgroundPage(
@@ -2446,6 +2409,11 @@ void ExtensionService::Observe(int type,
       extensions::ExtensionHost* host =
           content::Details<extensions::ExtensionHost>(details).ptr();
 
+      // If the extension is already being terminated, there is nothing left to
+      // do.
+      if (!extensions_being_terminated_.insert(host->extension_id()).second)
+        break;
+
       // Mark the extension as terminated and Unload it. We want it to
       // be in a consistent state: either fully working or not loaded
       // at all, but never half-crashed.  We do it in a PostTask so
@@ -2459,48 +2427,6 @@ void ExtensionService::Observe(int type,
               host->extension()));
       break;
     }
-    case content::NOTIFICATION_RENDERER_PROCESS_CREATED: {
-      content::RenderProcessHost* process =
-          content::Source<content::RenderProcessHost>(source).ptr();
-      Profile* host_profile =
-          Profile::FromBrowserContext(process->GetBrowserContext());
-      if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
-          break;
-
-      // Extensions need to know the channel for API restrictions.
-      process->Send(new ExtensionMsg_SetChannel(
-          extensions::GetCurrentChannel()));
-
-      // Platform apps need to know the system font.
-      scoped_ptr<base::DictionaryValue> fonts(new base::DictionaryValue);
-      webui::SetFontAndTextDirection(fonts.get());
-      std::string font_family, font_size;
-      fonts->GetString("fontfamily", &font_family);
-      fonts->GetString("fontsize", &font_size);
-      process->Send(new ExtensionMsg_SetSystemFont(
-          font_family, font_size));
-
-      // Valid extension function names, used to setup bindings in renderer.
-      std::vector<std::string> function_names;
-      ExtensionFunctionDispatcher::GetAllFunctionNames(&function_names);
-      process->Send(new ExtensionMsg_SetFunctionNames(function_names));
-
-      // Scripting whitelist. This is modified by tests and must be communicated
-      // to renderers.
-      process->Send(new ExtensionMsg_SetScriptingWhitelist(
-          extensions::ExtensionsClient::Get()->GetScriptingWhitelist()));
-
-      // Loaded extensions.
-      std::vector<ExtensionMsg_Loaded_Params> loaded_extensions;
-      for (ExtensionSet::const_iterator iter = extensions_.begin();
-           iter != extensions_.end(); ++iter) {
-        // Renderers don't need to know about themes.
-        if (!(*iter)->is_theme())
-          loaded_extensions.push_back(ExtensionMsg_Loaded_Params(iter->get()));
-      }
-      process->Send(new ExtensionMsg_Loaded(loaded_extensions));
-      break;
-    }
     case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
       content::RenderProcessHost* process =
           content::Source<content::RenderProcessHost>(source).ptr();
@@ -2509,11 +2435,13 @@ void ExtensionService::Observe(int type,
       if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
           break;
 
-      if (process_map_.Contains(process->GetID())) {
+      extensions::ProcessMap* process_map =
+          extensions::ProcessMap::Get(profile_);
+      if (process_map->Contains(process->GetID())) {
         // An extension process was terminated, this might have resulted in an
         // app or extension becoming idle.
         std::set<std::string> extension_ids =
-            process_map_.GetExtensionsInProcess(process->GetID());
+            process_map->GetExtensionsInProcess(process->GetID());
         for (std::set<std::string>::const_iterator it = extension_ids.begin();
              it != extension_ids.end(); ++it) {
           if (delayed_installs_.Contains(*it)) {
@@ -2526,19 +2454,16 @@ void ExtensionService::Observe(int type,
         }
       }
 
-      process_map_.RemoveAllFromProcess(process->GetID());
+      process_map->RemoveAllFromProcess(process->GetID());
       BrowserThread::PostTask(
-          BrowserThread::IO, FROM_HERE,
-          base::Bind(&ExtensionInfoMap::UnregisterAllExtensionsInProcess,
+          BrowserThread::IO,
+          FROM_HERE,
+          base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
                      system_->info_map(),
                      process->GetID()));
       break;
     }
     case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
-      // Notify extensions that chrome update is available.
-      extensions::RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(
-          profile_);
-
       // Notify observers that chrome update is available.
       FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
                         OnChromeUpdateAvailable());
@@ -2555,51 +2480,6 @@ void ExtensionService::OnExtensionInstallPrefChanged() {
   CheckManagementPolicy();
 }
 
-bool ExtensionService::HasApps() const {
-  return !GetAppIds().empty();
-}
-
-ExtensionIdSet ExtensionService::GetAppIds() const {
-  ExtensionIdSet result;
-  for (ExtensionSet::const_iterator it = extensions_.begin();
-       it != extensions_.end(); ++it) {
-    if ((*it)->is_app() && (*it)->location() != Manifest::COMPONENT)
-      result.insert((*it)->id());
-  }
-
-  return result;
-}
-
-bool ExtensionService::IsBackgroundPageReady(const Extension* extension) const {
-  if (!extensions::BackgroundInfo::HasPersistentBackgroundPage(extension))
-    return true;
-  ExtensionRuntimeDataMap::const_iterator it =
-      extension_runtime_data_.find(extension->id());
-  return it == extension_runtime_data_.end() ? false :
-                                               it->second.background_page_ready;
-}
-
-void ExtensionService::SetBackgroundPageReady(const Extension* extension) {
-  DCHECK(extensions::BackgroundInfo::HasBackgroundPage(extension));
-  extension_runtime_data_[extension->id()].background_page_ready = true;
-  content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
-      content::Source<const Extension>(extension),
-      content::NotificationService::NoDetails());
-}
-
-bool ExtensionService::IsBeingUpgraded(const Extension* extension) const {
-  ExtensionRuntimeDataMap::const_iterator it =
-      extension_runtime_data_.find(extension->id());
-  return it == extension_runtime_data_.end() ? false :
-                                               it->second.being_upgraded;
-}
-
-void ExtensionService::SetBeingUpgraded(const Extension* extension,
-                                        bool value) {
-  extension_runtime_data_[extension->id()].being_upgraded = value;
-}
-
 bool ExtensionService::IsBeingReloaded(
     const std::string& extension_id) const {
   return ContainsKey(extensions_being_reloaded_, extension_id);
@@ -2613,23 +2493,16 @@ void ExtensionService::SetBeingReloaded(const std::string& extension_id,
     extensions_being_reloaded_.erase(extension_id);
 }
 
-bool ExtensionService::HasUsedWebRequest(const Extension* extension) const {
-  ExtensionRuntimeDataMap::const_iterator it =
-      extension_runtime_data_.find(extension->id());
-  return it == extension_runtime_data_.end() ? false :
-                                               it->second.has_used_webrequest;
-}
-
-void ExtensionService::SetHasUsedWebRequest(const Extension* extension,
-                                            bool value) {
-  extension_runtime_data_[extension->id()].has_used_webrequest = value;
-}
-
 bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
   // Extensions installed by policy can't be disabled. So even if a previous
   // installation disabled the extension, make sure it is now enabled.
-  if (system_->management_policy()->MustRemainEnabled(extension, NULL))
+  // TODO(rlp): Clean up the special case for external components as noted
+  // in crbug.com/353266. For now, EXTERNAL_COMPONENT apps should be
+  // default enabled on install as before.
+  if (system_->management_policy()->MustRemainEnabled(extension, NULL) ||
+      extension->location() == Manifest::EXTERNAL_COMPONENT) {
     return true;
+  }
 
   if (extension_prefs_->IsExtensionDisabled(extension->id()))
     return false;
@@ -2648,23 +2521,6 @@ bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
   return true;
 }
 
-bool ExtensionService::IsExtensionIdle(const std::string& extension_id) const {
-  ExtensionProcessManager* process_manager = system_->process_manager();
-  DCHECK(process_manager);
-  extensions::ExtensionHost* host =
-      process_manager->GetBackgroundHostForExtension(extension_id);
-  if (host)
-    return false;
-
-  content::SiteInstance* site_instance = process_manager->GetSiteInstanceForURL(
-      Extension::GetBaseURLFromExtensionId(extension_id));
-  if (site_instance && site_instance->HasProcess()) {
-    return false;
-  }
-
-  return process_manager->GetRenderViewHostsForExtension(extension_id).empty();
-}
-
 bool ExtensionService::ShouldDelayExtensionUpdate(
     const std::string& extension_id,
     bool wait_for_idle) const {
@@ -2687,18 +2543,35 @@ bool ExtensionService::ShouldDelayExtensionUpdate(
         extension_id, kOnUpdateAvailableEvent);
   } else {
     // Delay installation if the extension is not idle.
-    return !IsExtensionIdle(extension_id);
+    return !extensions::util::IsExtensionIdle(extension_id, profile_);
   }
 }
 
 void ExtensionService::GarbageCollectIsolatedStorage() {
   scoped_ptr<base::hash_set<base::FilePath> > active_paths(
       new base::hash_set<base::FilePath>());
-  for (ExtensionSet::const_iterator it = extensions_.begin();
-       it != extensions_.end(); ++it) {
+  const ExtensionSet& extensions = registry_->enabled_extensions();
+  for (ExtensionSet::const_iterator it = extensions.begin();
+       it != extensions.end(); ++it) {
     if (extensions::AppIsolationInfo::HasIsolatedStorage(it->get())) {
       active_paths->insert(BrowserContext::GetStoragePartitionForSite(
-          profile_, GetSiteForExtensionId((*it)->id()))->GetPath());
+                               profile_,
+                               extensions::util::GetSiteForExtensionId(
+                                   (*it)->id(), profile()))->GetPath());
+    }
+  }
+
+  // The data of ephemeral apps can outlive their cache lifetime. Ensure
+  // they are not garbage collected.
+  scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> evicted_apps_info(
+      extension_prefs_->GetEvictedEphemeralAppsInfo());
+  for (size_t i = 0; i < evicted_apps_info->size(); ++i) {
+    extensions::ExtensionInfo* info = evicted_apps_info->at(i).get();
+    if (extensions::util::HasIsolatedStorage(*info)) {
+      active_paths->insert(BrowserContext::GetStoragePartitionForSite(
+          profile_,
+          extensions::util::GetSiteForExtensionId(
+              info->extension_id, profile()))->GetPath());
     }
   }
 
@@ -2729,35 +2602,79 @@ void ExtensionService::MaybeFinishDelayedInstallations() {
   }
 }
 
-void ExtensionService::OnNeedsToGarbageCollectIsolatedStorage() {
-  extension_prefs_->SetNeedsStorageGarbageCollection(true);
-}
-
 void ExtensionService::OnBlacklistUpdated() {
-  blacklist_->GetMalwareIDs(
-      GenerateInstalledExtensionsSet()->GetIDs(),
+  blacklist_->GetBlacklistedIDs(
+      registry_->GenerateInstalledExtensionsSet()->GetIDs(),
       base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
 }
 
-void ExtensionService::ManageBlacklist(const std::set<std::string>& updated) {
+void ExtensionService::ManageBlacklist(
+    const extensions::Blacklist::BlacklistStateMap& state_map) {
   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
-  std::set<std::string> before = blacklisted_extensions_.GetIDs();
-  std::set<std::string> no_longer_blacklisted =
-      base::STLSetDifference<std::set<std::string> >(before, updated);
-  std::set<std::string> not_yet_blacklisted =
-      base::STLSetDifference<std::set<std::string> >(updated, before);
+  std::set<std::string> blocked;
+  ExtensionIdSet greylist;
+  ExtensionIdSet unchanged;
+  for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
+           state_map.begin();
+       it != state_map.end();
+       ++it) {
+    switch (it->second) {
+      case extensions::NOT_BLACKLISTED:
+        break;
+
+      case extensions::BLACKLISTED_MALWARE:
+        blocked.insert(it->first);
+        break;
+
+      case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
+      case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
+      case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
+        greylist.insert(it->first);
+        break;
+
+      case extensions::BLACKLISTED_UNKNOWN:
+        unchanged.insert(it->first);
+        break;
+    }
+  }
+
+  UpdateBlockedExtensions(blocked, unchanged);
+  UpdateGreylistedExtensions(greylist, unchanged, state_map);
+
+  IdentifyAlertableExtensions();
+}
+
+namespace {
+void Partition(const ExtensionIdSet& before,
+               const ExtensionIdSet& after,
+               const ExtensionIdSet& unchanged,
+               ExtensionIdSet* no_longer,
+               ExtensionIdSet* not_yet) {
+  *not_yet   = base::STLSetDifference<ExtensionIdSet>(after, before);
+  *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
+  *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
+}
+}  // namespace
+
+void ExtensionService::UpdateBlockedExtensions(
+    const ExtensionIdSet& blocked,
+    const ExtensionIdSet& unchanged) {
+  ExtensionIdSet not_yet_blocked, no_longer_blocked;
+  Partition(registry_->blacklisted_extensions().GetIDs(),
+            blocked, unchanged,
+            &no_longer_blocked, &not_yet_blocked);
 
-  for (std::set<std::string>::iterator it = no_longer_blacklisted.begin();
-       it != no_longer_blacklisted.end(); ++it) {
+  for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
+       it != no_longer_blocked.end(); ++it) {
     scoped_refptr<const Extension> extension =
-        blacklisted_extensions_.GetByID(*it);
+        registry_->blacklisted_extensions().GetByID(*it);
     if (!extension.get()) {
-      NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
-                   << "but it was never blacklisted.";
+      NOTREACHED() << "Extension " << *it << " no longer blocked, "
+                   << "but it was never blocked.";
       continue;
     }
-    blacklisted_extensions_.Remove(*it);
+    registry_->RemoveBlacklisted(*it);
     extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
     AddExtension(extension.get());
     UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
@@ -2765,22 +2682,64 @@ void ExtensionService::ManageBlacklist(const std::set<std::string>& updated) {
                               Manifest::NUM_LOCATIONS);
   }
 
-  for (std::set<std::string>::iterator it = not_yet_blacklisted.begin();
-       it != not_yet_blacklisted.end(); ++it) {
+  for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
+       it != not_yet_blocked.end(); ++it) {
     scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
     if (!extension.get()) {
       NOTREACHED() << "Extension " << *it << " needs to be "
                    << "blacklisted, but it's not installed.";
       continue;
     }
-    blacklisted_extensions_.Insert(extension);
-    extension_prefs_->SetExtensionBlacklisted(extension->id(), true);
+    registry_->AddBlacklisted(extension);
+    extension_prefs_->SetExtensionBlacklistState(
+        extension->id(), extensions::BLACKLISTED_MALWARE);
     UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
     UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
                               extension->location(), Manifest::NUM_LOCATIONS);
   }
+}
 
-  IdentifyAlertableExtensions();
+// TODO(oleg): UMA logging
+void ExtensionService::UpdateGreylistedExtensions(
+    const ExtensionIdSet& greylist,
+    const ExtensionIdSet& unchanged,
+    const extensions::Blacklist::BlacklistStateMap& state_map) {
+  ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
+  Partition(greylist_.GetIDs(),
+            greylist, unchanged,
+            &no_longer_greylisted, &not_yet_greylisted);
+
+  for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
+       it != no_longer_greylisted.end(); ++it) {
+    scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
+    if (!extension.get()) {
+      NOTREACHED() << "Extension " << *it << " no longer greylisted, "
+                   << "but it was not marked as greylisted.";
+      continue;
+    }
+
+    greylist_.Remove(*it);
+    extension_prefs_->SetExtensionBlacklistState(extension->id(),
+                                                 extensions::NOT_BLACKLISTED);
+    if (extension_prefs_->GetDisableReasons(extension->id()) &
+        extensions::Extension::DISABLE_GREYLIST)
+      EnableExtension(*it);
+  }
+
+  for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
+       it != not_yet_greylisted.end(); ++it) {
+    scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
+    if (!extension.get()) {
+      NOTREACHED() << "Extension " << *it << " needs to be "
+                   << "disabled, but it's not installed.";
+      continue;
+    }
+    greylist_.Insert(extension);
+    extension_prefs_->SetExtensionBlacklistState(extension->id(),
+                                                 state_map.find(*it)->second);
+    if (registry_->enabled_extensions().Contains(extension->id()))
+      DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
+  }
 }
 
 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
@@ -2791,3 +2750,15 @@ void ExtensionService::RemoveUpdateObserver(
     extensions::UpdateObserver* observer) {
   update_observers_.RemoveObserver(observer);
 }
+
+// Used only by test code.
+void ExtensionService::UnloadAllExtensionsInternal() {
+  profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
+
+  registry_->ClearAll();
+  system_->runtime_data()->ClearAll();
+
+  // TODO(erikkay) should there be a notification for this?  We can't use
+  // EXTENSION_UNLOADED since that implies that the extension has been disabled
+  // or uninstalled.
+}