Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / extensions / extension_service.cc
index 58c4711..3f1b472 100644 (file)
 #include <iterator>
 #include <set>
 
-#include "base/basictypes.h"
-#include "base/bind.h"
-#include "base/callback.h"
 #include "base/command_line.h"
-#include "base/file_util.h"
-#include "base/logging.h"
 #include "base/metrics/histogram.h"
-#include "base/prefs/pref_service.h"
-#include "base/stl_util.h"
 #include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "base/strings/utf_string_conversions.h"
 #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/content_settings/content_settings_custom_extension_provider.h"
+#include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
+#include "chrome/browser/content_settings/host_content_settings_map.h"
+#include "chrome/browser/extensions/api/content_settings/content_settings_service.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_action_storage_manager.h"
+#include "chrome/browser/extensions/extension_assets_manager.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_error_controller.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_install_manager.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/shared_module_service.h"
 #include "chrome/browser/extensions/unpacked_installer.h"
-#include "chrome/browser/extensions/update_observer.h"
+#include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
+#include "chrome/browser/extensions/updater/extension_cache.h"
+#include "chrome/browser/extensions/updater/extension_downloader.h"
 #include "chrome/browser/extensions/updater/extension_updater.h"
+#include "chrome/browser/google/google_brand.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/crx_file/id_util.h"
 #include "components/startup_metric_utils/startup_metric_utils.h"
-#include "content/public/browser/browser_thread.h"
 #include "content/public/browser/devtools_agent_host.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/common/constants.h"
-#include "extensions/common/error_utils.h"
-#include "extensions/common/extensions_client.h"
-#include "extensions/common/manifest.h"
+#include "extensions/browser/event_router.h"
+#include "extensions/browser/extension_host.h"
+#include "extensions/browser/extension_prefs.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/browser/extension_system.h"
+#include "extensions/browser/install_flag.h"
+#include "extensions/browser/runtime_data.h"
+#include "extensions/browser/uninstall_reason.h"
+#include "extensions/browser/update_observer.h"
+#include "extensions/common/extension_messages.h"
+#include "extensions/common/extension_urls.h"
+#include "extensions/common/feature_switch.h"
+#include "extensions/common/file_util.h"
 #include "extensions/common/manifest_constants.h"
+#include "extensions/common/manifest_handlers/background_info.h"
+#include "extensions/common/one_shot_event.h"
 #include "extensions/common/permissions/permission_message_provider.h"
-#include "grit/generated_resources.h"
-#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
-#include "ui/base/webui/web_ui_util.h"
-#include "url/gurl.h"
-#include "webkit/browser/database/database_tracker.h"
-#include "webkit/browser/database/database_util.h"
+#include "extensions/common/permissions/permissions_data.h"
 
 #if defined(OS_CHROMEOS)
 #include "chrome/browser/chromeos/extensions/install_limiter.h"
-#include "webkit/browser/fileapi/file_system_backend.h"
-#include "webkit/browser/fileapi/file_system_context.h"
+#include "storage/browser/fileapi/file_system_backend.h"
+#include "storage/browser/fileapi/file_system_context.h"
 #endif
 
 using content::BrowserContext;
@@ -118,85 +95,28 @@ 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;
 using extensions::PermissionMessages;
 using extensions::PermissionSet;
 using extensions::SharedModuleInfo;
+using extensions::SharedModuleService;
 using extensions::UnloadedExtensionInfo;
 
 namespace errors = extensions::manifest_errors;
 
 namespace {
 
-// Histogram values for logging events related to externally installed
-// extensions.
-enum ExternalExtensionEvent {
-  EXTERNAL_EXTENSION_INSTALLED = 0,
-  EXTERNAL_EXTENSION_IGNORED,
-  EXTERNAL_EXTENSION_REENABLED,
-  EXTERNAL_EXTENSION_UNINSTALLED,
-  EXTERNAL_EXTENSION_BUCKET_BOUNDARY,
-};
-
-// Prompt the user this many times before considering an extension acknowledged.
-static const int kMaxExtensionAcknowledgePromptCount = 3;
-
 // Wait this many seconds after an extensions becomes idle before updating it.
-static const int kUpdateIdleDelay = 5;
-
-// Wait this many seconds before trying to garbage collect extensions again.
-static const int kGarbageCollectRetryDelay = 30;
-
-// Wait this many seconds after startup to see if there are any extensions
-// which can be garbage collected.
-static const int kGarbageCollectStartupDelay = 30;
-
-static bool IsSharedModule(const Extension* extension) {
-  return SharedModuleInfo::IsSharedModule(extension);
-}
-
-static bool IsCWSSharedModule(const Extension* extension) {
-  return extension->from_webstore() && IsSharedModule(extension);
-}
-
-class SharedModuleProvider : public extensions::ManagementPolicy::Provider {
- public:
-  SharedModuleProvider() {}
-  virtual ~SharedModuleProvider() {}
-
-  virtual std::string GetDebugPolicyProviderName() const OVERRIDE {
-    return "SharedModuleProvider";
-  }
-
-  virtual bool UserMayModifySettings(const Extension* extension,
-                                     string16* error) const OVERRIDE {
-    return !IsCWSSharedModule(extension);
-  }
-
-  virtual bool MustRemainEnabled(const Extension* extension,
-                                 string16* error) const OVERRIDE {
-    return IsCWSSharedModule(extension);
-  }
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(SharedModuleProvider);
-};
-
+const int kUpdateIdleDelay = 5;
 
 }  // 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) {
@@ -223,11 +143,14 @@ void ExtensionService::CheckExternalUninstall(const std::string& id) {
                  << "with id: " << id;
     return;
   }
-  UninstallExtension(id, true, NULL);
+  UninstallExtension(id,
+                     extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
+                     base::Bind(&base::DoNothing),
+                     NULL);
 }
 
 void ExtensionService::SetFileTaskRunnerForTesting(
-    base::SequencedTaskRunner* task_runner) {
+    const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
   file_task_runner_ = task_runner;
 }
 
@@ -242,14 +165,28 @@ void ExtensionService::AddProviderForTesting(
       linked_ptr<extensions::ExternalProviderInterface>(test_provider));
 }
 
+void ExtensionService::BlacklistExtensionForTest(
+    const std::string& extension_id) {
+  ExtensionIdSet blocked;
+  ExtensionIdSet unchanged;
+  blocked.insert(extension_id);
+  UpdateBlockedExtensions(blocked, unchanged);
+}
+
 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
     const std::string& id,
+    const std::string& install_parameter,
     const GURL& update_url,
     Manifest::Location location,
     int creation_flags,
     bool mark_acknowledged) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
-  CHECK(Extension::IdIsValid(id));
+  CHECK(crx_file::id_util::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) {
@@ -266,7 +203,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,23 +216,14 @@ bool ExtensionService::OnExternalExtensionUpdateUrlFound(
   return true;
 }
 
-const Extension* ExtensionService::GetInstalledApp(const GURL& url) const {
-  const Extension* extension = extensions_.GetExtensionOrAppByURL(url);
-  return (extension && extension->is_app()) ? extension : NULL;
-}
-
-bool ExtensionService::IsInstalledApp(const GURL& url) const {
-  return !!GetInstalledApp(url);
-}
-
 // static
-// This function is used to implement the command-line switch
-// --uninstall-extension, and to uninstall an extension via sync.  The LOG
-// statements within this function are used to inform the user if the uninstall
-// cannot be done.
+// This function is used to uninstall an extension via sync.  The LOG statements
+// within this function are used to inform the user if the uninstall cannot be
+// done.
 bool ExtensionService::UninstallExtensionHelper(
     ExtensionService* extensions_service,
-    const std::string& extension_id) {
+    const std::string& extension_id,
+    extensions::UninstallReason reason) {
   // We can't call UninstallExtension with an invalid extension ID.
   if (!extensions_service->GetInstalledExtension(extension_id)) {
     LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
@@ -300,8 +233,9 @@ bool ExtensionService::UninstallExtensionHelper(
 
   // The following call to UninstallExtension will not allow an uninstall of a
   // policy-controlled extension.
-  string16 error;
-  if (!extensions_service->UninstallExtension(extension_id, false, &error)) {
+  base::string16 error;
+  if (!extensions_service->UninstallExtension(
+          extension_id, reason, base::Bind(&base::DoNothing), &error)) {
     LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
                  << ": " << error;
     return false;
@@ -323,48 +257,41 @@ 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_(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),
-      is_first_run_(false) {
-#if defined(OS_CHROMEOS)
-  disable_garbage_collection_ = false;
-#endif
+      is_first_run_(false),
+      shared_module_service_(new extensions::SharedModuleService(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,
+  registrar_.Add(this,
+                 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
                  content::NotificationService::AllBrowserContextsAndSources());
   registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
                  content::NotificationService::AllBrowserContextsAndSources());
   registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
                  content::NotificationService::AllBrowserContextsAndSources());
-  pref_change_registrar_.Init(profile->GetPrefs());
-  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);
+  registrar_.Add(this,
+                 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
+                 content::Source<Profile>(profile_));
+
+  extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
+      ->AddObserver(this);
 
   // Set up the ExtensionUpdater
   if (autoupdate_enabled) {
@@ -374,33 +301,39 @@ 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(),
+        base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
+                   profile)));
   }
 
   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)
+  error_controller_.reset(
+      new extensions::ExtensionErrorController(profile_, is_first_run_));
+  external_install_manager_.reset(
+      new extensions::ExternalInstallManager(profile_, is_first_run_));
+
   extension_action_storage_manager_.reset(
       new extensions::ExtensionActionStorageManager(profile_));
-#endif
-
-  shared_module_policy_provider_.reset(new SharedModuleProvider);
 
   // How long is the path to the Extensions directory?
   UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
@@ -408,33 +341,7 @@ 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_;
-}
-
-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>();
+  return &registry_->enabled_extensions();
 }
 
 extensions::PendingExtensionManager*
@@ -455,59 +362,33 @@ ExtensionService::~ExtensionService() {
 }
 
 void ExtensionService::Shutdown() {
+  extensions::ExtensionManagementFactory::GetInstance()
+      ->GetForBrowserContext(profile())
+      ->RemoveObserver(this);
   system_->management_policy()->UnregisterProvider(
       shared_module_policy_provider_.get());
 }
 
 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) ||
@@ -522,12 +403,11 @@ void ExtensionService::Init() {
     component_loader_->LoadAll();
     extensions::InstalledLoader(this).LoadAllExtensions();
 
-    ReconcileKnownDisabled();
-
     // 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,23 +453,31 @@ void ExtensionService::Init() {
     // rather than running immediately at startup.
     CheckForExternalUpdates();
 
-    base::MessageLoop::current()->PostDelayedTask(
-        FROM_HERE,
-        base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
-        base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay));
+    LoadGreylistFromPrefs();
+  }
+
+  UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
+                      base::Time::Now() - begin_time);
+}
 
-    if (extension_prefs_->NeedsStorageGarbageCollection()) {
-      GarbageCollectIsolatedStorage();
-      extension_prefs_->SetNeedsStorageGarbageCollection(false);
-    }
-    system_->management_policy()->RegisterProvider(
-        shared_module_policy_provider_.get());
+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,
-                                       const GURL& download_url,
+                                       bool file_ownership_passed,
                                        CrxInstaller** out_crx_installer) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   if (browser_terminating_) {
@@ -612,7 +500,7 @@ bool ExtensionService::UpdateExtension(const std::string& id,
     if (!GetFileTaskRunner()->PostTask(
             FROM_HERE,
             base::Bind(
-                &extension_file_util::DeleteFile, extension_path, false)))
+                &extensions::file_util::DeleteFile, extension_path, false)))
       NOTREACHED();
 
     return false;
@@ -632,9 +520,11 @@ bool ExtensionService::UpdateExtension(const std::string& id,
     installer->set_install_source(pending_extension_info->install_source());
     if (pending_extension_info->install_silently())
       installer->set_allow_silent_install(true);
+    if (pending_extension_info->remote_install())
+      installer->set_grant_permissions(false);
     creation_flags = pending_extension_info->creation_flags();
     if (pending_extension_info->mark_acknowledged())
-      AcknowledgeExternalExtension(id);
+      external_install_manager_->AcknowledgeExternalExtension(id);
   } else if (extension) {
     installer->set_install_source(extension->location());
   }
@@ -660,10 +550,20 @@ 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->was_installed_by_custodian())
+    creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
+
+  if (extension) {
+    installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
+    installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
+  }
+
   installer->set_creation_flags(creation_flags);
 
-  installer->set_delete_source(true);
-  installer->set_download_url(download_url);
+  installer->set_delete_source(file_ownership_passed);
   installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
   installer->InstallCrx(extension_path);
 
@@ -673,44 +573,66 @@ bool ExtensionService::UpdateExtension(const std::string& id,
   return true;
 }
 
-void ExtensionService::ReloadExtension(const std::string extension_id) {
+void ExtensionService::ReloadExtensionImpl(
+    // "transient" because the process of reloading may cause the reference
+    // to become invalid. Instead, use |extension_id|, a copy.
+    const std::string& transient_extension_id,
+    bool be_noisy) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
   // If the extension is already reloading, don't reload again.
-  if (extension_prefs_->GetDisableReasons(extension_id) &
+  if (extension_prefs_->GetDisableReasons(transient_extension_id) &
       Extension::DISABLE_RELOAD) {
     return;
   }
 
+  // Ignore attempts to reload a blacklisted extension. Sometimes this can
+  // happen in a convoluted reload sequence triggered by the termination of a
+  // blacklisted extension and a naive attempt to reload it. For an example see
+  // http://crbug.com/373842.
+  if (registry_->blacklisted_extensions().Contains(transient_extension_id))
+    return;
+
   base::FilePath path;
-  const Extension* current_extension = GetExtensionById(extension_id, false);
+
+  std::string extension_id = transient_extension_id;
+  const Extension* transient_current_extension =
+      GetExtensionById(extension_id, false);
 
   // Disable the extension if it's loaded. It might not be loaded if it crashed.
-  if (current_extension) {
+  if (transient_current_extension) {
     // If the extension has an inspector open for its background page, detach
     // 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())) {
+    if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
       // Look for an open inspector for the background page.
       scoped_refptr<DevToolsAgentHost> agent_host =
-          DevToolsAgentHost::GetOrCreateFor(host->render_view_host());
-      agent_host->DisconnectRenderViewHost();
+          DevToolsAgentHost::GetOrCreateFor(host->host_contents());
+      agent_host->DisconnectWebContents();
       orphaned_dev_tools_[extension_id] = agent_host;
     }
 
-    path = current_extension->path();
+    path = transient_current_extension->path();
     // BeingUpgraded is set back to false when the extension is added.
-    SetBeingUpgraded(current_extension, true);
+    system_->runtime_data()->SetBeingUpgraded(transient_current_extension,
+                                              true);
     DisableExtension(extension_id, Extension::DISABLE_RELOAD);
     reloading_extensions_.insert(extension_id);
   } else {
+    std::map<std::string, base::FilePath>::const_iterator iter =
+        unloaded_extension_paths_.find(extension_id);
+    if (iter == unloaded_extension_paths_.end()) {
+      return;
+    }
     path = unloaded_extension_paths_[extension_id];
   }
 
+  transient_current_extension = NULL;
+
   if (delayed_installs_.Contains(extension_id)) {
     FinishDelayedInstallation(extension_id);
     return;
@@ -719,15 +641,12 @@ void ExtensionService::ReloadExtension(const std::string extension_id) {
   // If we're reloading a component extension, use the component extension
   // loader's reloader.
   if (component_loader_->Exists(extension_id)) {
-    SetBeingReloaded(extension_id, true);
     component_loader_->Reload(extension_id);
-    SetBeingReloaded(extension_id, false);
     return;
   }
 
   // Check the installed extensions to see if what we're reloading was already
   // installed.
-  SetBeingReloaded(extension_id, true);
   scoped_ptr<ExtensionInfo> installed_extension(
       extension_prefs_->GetInstalledExtensionInfo(extension_id));
   if (installed_extension.get() &&
@@ -738,19 +657,33 @@ void ExtensionService::ReloadExtension(const std::string extension_id) {
     // We should always be able to remember the extension's path. If it's not in
     // the map, someone failed to update |unloaded_extension_paths_|.
     CHECK(!path.empty());
-    extensions::UnpackedInstaller::Create(this)->Load(path);
+    scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
+        extensions::UnpackedInstaller::Create(this);
+    unpacked_installer->set_be_noisy_on_failure(be_noisy);
+    unpacked_installer->Load(path);
   }
-  // When reloading is done, mark this extension as done reloading.
-  SetBeingReloaded(extension_id, false);
+}
+
+void ExtensionService::ReloadExtension(const std::string& extension_id) {
+  ReloadExtensionImpl(extension_id, true); // be_noisy
+}
+
+void ExtensionService::ReloadExtensionWithQuietFailure(
+    const std::string& extension_id) {
+  ReloadExtensionImpl(extension_id, false); // be_noisy
 }
 
 bool ExtensionService::UninstallExtension(
-    std::string extension_id,
-    bool external_uninstall,
-    string16* error) {
+    // "transient" because the process of uninstalling may cause the reference
+    // to become invalid. Instead, use |extenson->id()|.
+    const std::string& transient_extension_id,
+    extensions::UninstallReason reason,
+    const base::Closure& deletion_done_callback,
+    base::string16* error) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
-  scoped_refptr<const Extension> extension(GetInstalledExtension(extension_id));
+  scoped_refptr<const Extension> extension =
+      GetInstalledExtension(transient_extension_id);
 
   // Callers should not send us nonexistent extensions.
   CHECK(extension.get());
@@ -758,97 +691,83 @@ bool ExtensionService::UninstallExtension(
   // Policy change which triggers an uninstall will always set
   // |external_uninstall| to true so this is the only way to uninstall
   // managed extensions.
+  // Shared modules being uninstalled will also set |external_uninstall| to true
+  // so that we can guarantee users don't uninstall a shared module.
+  // (crbug.com/273300)
+  // TODO(rdevlin.cronin): This is probably not right. We should do something
+  // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
+  // we don't do this.
+  bool external_uninstall =
+      (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
+      (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
+      (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
+      (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
+      (reason == extensions::UNINSTALL_REASON_SYNC &&
+           extension->was_installed_by_custodian());
   if (!external_uninstall &&
       !system_->management_policy()->UserMayModifySettings(
         extension.get(), error)) {
     content::NotificationService::current()->Notify(
-        chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
+        extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
         content::Source<Profile>(profile_),
         content::Details<const Extension>(extension.get()));
     return false;
   }
 
   syncer::SyncChange sync_change;
-  if (extension_sync_service_) {
+  // Don't sync the uninstall if we're going to reinstall the extension
+  // momentarily.
+  if (extension_sync_service_ &&
+      reason != extensions::UNINSTALL_REASON_REINSTALL) {
      sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
         extension.get(), is_ready());
   }
 
-  if (IsUnacknowledgedExternalExtension(extension.get())) {
-    UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
-                              EXTERNAL_EXTENSION_UNINSTALLED,
-                              EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    if (extensions::ManifestURL::UpdatesFromGallery(extension.get())) {
-      UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
-                                EXTERNAL_EXTENSION_UNINSTALLED,
-                                EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    } else {
-      UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
-                                EXTERNAL_EXTENSION_UNINSTALLED,
-                                EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    }
-  }
+  system_->install_verifier()->Remove(extension->id());
+
   UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
                             extension->GetType(), 100);
   RecordPermissionMessagesHistogram(extension.get(),
-                                    "Extensions.Permissions_Uninstall");
+                                    "Extensions.Permissions_Uninstall2");
 
   // Unload before doing more cleanup to ensure that nothing is hanging on to
   // any of these resources.
-  UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
+  UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
 
   // Tell the backend to start deleting installed extensions on the file thread.
   if (!Manifest::IsUnpackedLocation(extension->location())) {
     if (!GetFileTaskRunner()->PostTask(
             FROM_HERE,
-            base::Bind(
-                &extension_file_util::UninstallExtension,
-                install_directory_,
-                extension_id)))
+            base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
+                       extension->id(),
+                       profile_,
+                       install_directory_,
+                       extension->path())))
       NOTREACHED();
   }
 
-  GURL launch_web_url_origin(
-      extensions::AppLaunchInfo::GetLaunchWebURL(extension.get()).GetOrigin());
-  bool is_storage_isolated =
-      extensions::AppIsolationInfo::HasIsolatedStorage(extension.get());
+  extensions::DataDeleter::StartDeleting(
+      profile_, extension.get(), deletion_done_callback);
 
-  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());
-  }
-
-  UntrackTerminatedExtension(extension_id);
+  UntrackTerminatedExtension(extension->id());
 
   // Notify interested parties that we've uninstalled this extension.
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
+      extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
       content::Source<Profile>(profile_),
       content::Details<const Extension>(extension.get()));
+  ExtensionRegistry::Get(profile_)
+      ->TriggerOnUninstalled(extension.get(), reason);
 
-  if (extension_sync_service_) {
-    extension_sync_service_->ProcessSyncUninstallExtension(extension_id,
+  if (sync_change.IsValid()) {
+    extension_sync_service_->ProcessSyncUninstallExtension(extension->id(),
                                                            sync_change);
   }
 
-  delayed_installs_.Remove(extension_id);
-
-  PruneSharedModulesOnUninstall(extension.get());
+  delayed_installs_.Remove(extension->id());
 
-  extension_prefs_->OnExtensionUninstalled(extension_id, extension->location(),
-                                           external_uninstall);
+  extension_prefs_->OnExtensionUninstalled(
+      extension->id(), extension->location(), external_uninstall);
 
   // Track the uninstallation.
   UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
@@ -856,41 +775,43 @@ bool ExtensionService::UninstallExtension(
   return true;
 }
 
+// static
+void ExtensionService::UninstallExtensionOnFileThread(
+    const std::string& id,
+    Profile* profile,
+    const base::FilePath& install_dir,
+    const base::FilePath& extension_path) {
+  extensions::ExtensionAssetsManager* assets_manager =
+      extensions::ExtensionAssetsManager::GetInstance();
+  assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
+}
+
 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;
   }
 
   // If the extension hasn't been loaded yet, check the prefs for it. Assume
   // enabled unless otherwise noted.
   return !extension_prefs_->IsExtensionDisabled(extension_id) &&
+         !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
          !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)) {
@@ -906,31 +827,15 @@ void ExtensionService::EnableExtension(const std::string& extension_id) {
   if (!extension)
     return;
 
-  if (IsUnacknowledgedExternalExtension(extension)) {
-    UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
-                              EXTERNAL_EXTENSION_REENABLED,
-                              EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
-      UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
-                                EXTERNAL_EXTENSION_REENABLED,
-                                EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    } else {
-      UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
-                                EXTERNAL_EXTENSION_REENABLED,
-                                EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    }
-    AcknowledgeExternalExtension(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);
 
   // Notify listeners that the extension was enabled.
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_ENABLED,
+      extensions::NOTIFICATION_EXTENSION_ENABLED,
       content::Source<Profile>(profile_),
       content::Details<const Extension>(extension));
 
@@ -943,39 +848,46 @@ void ExtensionService::DisableExtension(
     Extension::DisableReason disable_reason) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
-  // The extension may have been disabled already.
-  if (!IsExtensionEnabled(extension_id))
+  // The extension may have been disabled already. Just add a disable reason.
+  if (!IsExtensionEnabled(extension_id)) {
+    extension_prefs_->AddDisableReason(extension_id, disable_reason);
     return;
+  }
 
   const Extension* extension = GetInstalledExtension(extension_id);
   // |extension| can be NULL if sync disables an extension that is not
   // installed yet.
+  // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
+  // can be uninstalled by the browser if the user sets extension-specific
+  // preferences.
   if (extension &&
       disable_reason != Extension::DISABLE_RELOAD &&
-      !system_->management_policy()->UserMayModifySettings(extension, NULL)) {
+      !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
+      extension->location() != Manifest::EXTERNAL_COMPONENT) {
     return;
   }
 
   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,13 +900,15 @@ void ExtensionService::DisableUserExtensions(
       system_->management_policy();
   extensions::ExtensionList to_disable;
 
-  for (ExtensionSet::const_iterator extension = extensions_.begin();
-      extension != extensions_.end(); ++extension) {
+  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))
       to_disable.push_back(*extension);
   }
-  for (ExtensionSet::const_iterator extension = terminated_extensions_.begin();
-      extension != terminated_extensions_.end(); ++extension) {
+  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))
       to_disable.push_back(*extension);
   }
@@ -1003,7 +917,7 @@ void ExtensionService::DisableUserExtensions(
       extension != to_disable.end(); ++extension) {
     if ((*extension)->was_installed_by_default() &&
         extension_urls::IsWebstoreUpdateUrl(
-            extensions::ManifestURL::GetUpdateURL(*extension)))
+            extensions::ManifestURL::GetUpdateURL(extension->get())))
       continue;
     const std::string& id = (*extension)->id();
     if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
@@ -1014,16 +928,15 @@ void ExtensionService::DisableUserExtensions(
 void ExtensionService::GrantPermissionsAndEnableExtension(
     const Extension* extension) {
   GrantPermissions(extension);
-  RecordPermissionMessagesHistogram(
-      extension, "Extensions.Permissions_ReEnable");
+  RecordPermissionMessagesHistogram(extension,
+                                    "Extensions.Permissions_ReEnable2");
   extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
   EnableExtension(extension->id());
 }
 
 void ExtensionService::GrantPermissions(const Extension* extension) {
   CHECK(extension);
-  extensions::PermissionsUpdater perms_updater(profile());
-  perms_updater.GrantActivePermissions(extension);
+  extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
 }
 
 // static
@@ -1039,7 +952,7 @@ void ExtensionService::RecordPermissionMessagesHistogram(
       base::HistogramBase::kUmaTargetedHistogramFlag);
 
   PermissionMessages permissions =
-      extensions::PermissionsData::GetPermissionMessages(extension);
+      extension->permissions_data()->GetPermissionMessages();
   if (permissions.empty()) {
     counter->Add(PermissionMessage::kNone);
   } else {
@@ -1050,7 +963,7 @@ void ExtensionService::RecordPermissionMessagesHistogram(
 }
 
 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
-  // The ChromeURLRequestContexts need to be first to know that the extension
+  // The URLRequestContexts need to be first to know that the extension
   // was loaded, otherwise a race can arise where a renderer that is created
   // for the extension may try to load an extension URL with an extension id
   // that the request context doesn't yet know about. The profile is responsible
@@ -1082,43 +995,47 @@ 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_DEPRECATED, the
+  // renderer is guaranteed to know about it.
+  registry_->TriggerOnLoaded(extension);
+
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_LOADED,
+      extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
       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();
 
+  const extensions::PermissionsData* permissions_data =
+      extension->permissions_data();
+
   // If the extension has permission to load chrome://favicon/ resources we need
   // to make sure that the FaviconSource is registered with the
   // ChromeURLDataManager.
-  if (extensions::PermissionsData::HasHostPermission(
-          extension, GURL(chrome::kChromeUIFaviconURL))) {
+  if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
     FaviconSource* favicon_source = new FaviconSource(profile_,
                                                       FaviconSource::FAVICON);
     content::URLDataSource::Add(profile_, favicon_source);
   }
 
-#if !defined(OS_ANDROID)
   // Same for chrome://theme/ resources.
-  if (extensions::PermissionsData::HasHostPermission(
-          extension, GURL(chrome::kChromeUIThemeURL))) {
+  if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
     ThemeSource* theme_source = new ThemeSource(profile_);
     content::URLDataSource::Add(profile_, theme_source);
   }
-#endif
 
   // Same for chrome://thumb/ resources.
-  if (extensions::PermissionsData::HasHostPermission(
-          extension, GURL(chrome::kChromeUIThumbnailURL))) {
+  if (permissions_data->HasHostPermission(
+          GURL(chrome::kChromeUIThumbnailURL))) {
     ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
     content::URLDataSource::Add(profile_, thumbnail_source);
   }
@@ -1128,8 +1045,11 @@ void ExtensionService::NotifyExtensionUnloaded(
     const Extension* extension,
     UnloadedExtensionInfo::Reason reason) {
   UnloadedExtensionInfo details(extension, reason);
+
+  registry_->TriggerOnUnloaded(extension, reason);
+
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_UNLOADED,
+      extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
       content::Source<Profile>(profile_),
       content::Details<UnloadedExtensionInfo>(&details));
 
@@ -1144,6 +1064,9 @@ void ExtensionService::NotifyExtensionUnloaded(
   }
 
   system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
+
+  // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
+  // BrowserContextKeyedService and use ExtensionRegistryObserver.
   profile_->GetExtensionSpecialStoragePolicy()->
       RevokeRightsForExtension(extension);
 
@@ -1151,40 +1074,29 @@ 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());
-  fileapi::FileSystemContext* filesystem_context =
-      BrowserContext::GetStoragePartitionForSite(profile_, site)->
-          GetFileSystemContext();
+  GURL site =
+      extensions::util::GetSiteForExtensionId(extension->id(), profile_);
+  storage::FileSystemContext* filesystem_context =
+      BrowserContext::GetStoragePartitionForSite(profile_, site)
+          ->GetFileSystemContext();
   if (filesystem_context && filesystem_context->external_backend()) {
     filesystem_context->external_backend()->
         RevokeAccessForExtension(extension->id());
   }
 #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();
 }
 
-Profile* ExtensionService::profile() {
+content::BrowserContext* ExtensionService::GetBrowserContext() const {
+  // Implemented in the .cc file to avoid adding a profile.h dependency to
+  // extension_service.h.
   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();
-}
-
 bool ExtensionService::is_ready() {
   return ready_->is_signaled();
 }
@@ -1205,18 +1117,15 @@ base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
   return file_task_runner_.get();
 }
 
-extensions::ExtensionUpdater* ExtensionService::updater() {
-  return updater_.get();
-}
-
 void ExtensionService::CheckManagementPolicy() {
   std::vector<std::string> to_unload;
   std::map<std::string, Extension::DisableReason> to_disable;
 
   // 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());
@@ -1235,32 +1144,17 @@ void ExtensionService::CheckManagementPolicy() {
 }
 
 void ExtensionService::CheckForUpdatesSoon() {
-  if (updater()) {
-    if (AreAllExternalProvidersReady()) {
-      updater()->CheckSoon();
-    } else {
-      // Sync can start updating before all the external providers are ready
-      // during startup. Start the update as soon as those providers are ready,
-      // but not before.
-      update_once_all_providers_are_ready_ = true;
-    }
-  } else {
-    LOG(WARNING) << "CheckForUpdatesSoon() called with auto-update turned off";
-  }
-}
-
-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);
+  // This can legitimately happen in unit tests.
+  if (!updater_.get())
+    return;
 
-  const Extension* extension = GetInstalledExtension(moved_extension_id);
-  if (extension_sync_service_ && extension) {
-    extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
+  if (AreAllExternalProvidersReady()) {
+    updater_->CheckSoon();
+  } else {
+    // Sync can start updating before all the external providers are ready
+    // during startup. Start the update as soon as those providers are ready,
+    // but not before.
+    update_once_all_providers_are_ready_ = true;
   }
 }
 
@@ -1292,9 +1186,8 @@ void ExtensionService::CheckForExternalUpdates() {
 
   // Do any required work that we would have done after completion of all
   // providers.
-  if (external_extension_providers_.empty()) {
+  if (external_extension_providers_.empty())
     OnAllExternalProvidersReady();
-  }
 }
 
 void ExtensionService::OnExternalProviderReady(
@@ -1326,7 +1219,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.
@@ -1337,206 +1232,20 @@ void ExtensionService::OnAllExternalProvidersReady() {
     if (Manifest::IsExternalLocation(info->extension_location))
       CheckExternalUninstall(info->extension_id);
   }
-  IdentifyAlertableExtensions();
-}
-
-void ExtensionService::IdentifyAlertableExtensions() {
-  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
-
-  // Build up the lists of extensions that require acknowledgment. If this is
-  // the first time, grandfather extensions that would have caused
-  // notification.
-  extension_error_ui_.reset(ExtensionErrorUI::Create(this));
-
-  bool did_show_alert = false;
-  if (PopulateExtensionErrorUI(extension_error_ui_.get())) {
-    if (!is_first_run_) {
-      CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
-      did_show_alert = extension_error_ui_->ShowErrorInBubbleView();
-    } else {
-      // First run. Just acknowledge all the extensions, silently, by
-      // shortcutting the display of the UI and going straight to the
-      // callback for pressing the Accept button.
-      HandleExtensionAlertAccept();
-    }
-  }
 
-  UpdateExternalExtensionAlert();
+  error_controller_->ShowErrorIfNeeded();
 
-  if (!did_show_alert)
-    extension_error_ui_.reset();
-}
-
-bool ExtensionService::PopulateExtensionErrorUI(
-    ExtensionErrorUI* extension_error_ui) {
-  bool needs_alert = false;
-
-  // Extensions that are blacklisted.
-  for (ExtensionSet::const_iterator it = blacklisted_extensions_.begin();
-       it != blacklisted_extensions_.end(); ++it) {
-    std::string id = (*it)->id();
-    if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(id)) {
-      extension_error_ui->AddBlacklistedExtension(id);
-      needs_alert = true;
-    }
-  }
-
-  for (ExtensionSet::const_iterator iter = extensions_.begin();
-       iter != extensions_.end(); ++iter) {
-    const Extension* e = iter->get();
-
-    // 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)) {
-      if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(e->id())) {
-        extension_error_ui->AddBlacklistedExtension(e->id());
-        needs_alert = true;
-      }
-    }
-  }
-
-  return needs_alert;
-}
-
-void ExtensionService::HandleExtensionAlertClosed() {
-  const ExtensionIdSet* extension_ids =
-      extension_error_ui_->get_blacklisted_extension_ids();
-  for (ExtensionIdSet::const_iterator iter = extension_ids->begin();
-       iter != extension_ids->end(); ++iter) {
-    extension_prefs_->AcknowledgeBlacklistedExtension(*iter);
-  }
-  extension_error_ui_.reset();
-}
-
-void ExtensionService::HandleExtensionAlertAccept() {
-  extension_error_ui_->Close();
-}
-
-void ExtensionService::AcknowledgeExternalExtension(const std::string& id) {
-  extension_prefs_->AcknowledgeExternalExtension(id);
-  UpdateExternalExtensionAlert();
-}
-
-bool ExtensionService::IsUnacknowledgedExternalExtension(
-    const Extension* extension) {
-  if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
-    return false;
-
-  return (Manifest::IsExternalLocation(extension->location()) &&
-          !extension_prefs_->IsExternalExtensionAcknowledged(extension->id()) &&
-          !(extension_prefs_->GetDisableReasons(extension->id()) &
-                Extension::DISABLE_SIDELOAD_WIPEOUT));
-}
-
-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);
-      }
-    }
-    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(
-      base::Bind(&extensions::ExtensionPrefs::SetKnownDisabled,
-                 base::Unretained(extension_prefs_)));
-}
-
-void ExtensionService::HandleExtensionAlertDetails() {
-  extension_error_ui_->ShowExtensions();
-  // ShowExtensions may cause the error UI to close synchronously, e.g. if it
-  // causes a navigation.
-  if (extension_error_ui_)
-    extension_error_ui_->Close();
-}
-
-void ExtensionService::UpdateExternalExtensionAlert() {
-  if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
-    return;
-
-  const Extension* extension = NULL;
-  for (ExtensionSet::const_iterator iter = disabled_extensions_.begin();
-       iter != disabled_extensions_.end(); ++iter) {
-    const Extension* e = iter->get();
-    if (IsUnacknowledgedExternalExtension(e)) {
-      extension = e;
-      break;
-    }
-  }
-
-  if (extension) {
-    if (!extensions::HasExternalInstallError(this)) {
-      if (extension_prefs_->IncrementAcknowledgePromptCount(extension->id()) >
-              kMaxExtensionAcknowledgePromptCount) {
-        // Stop prompting for this extension, and check if there's another
-        // one that needs prompting.
-        extension_prefs_->AcknowledgeExternalExtension(extension->id());
-        UpdateExternalExtensionAlert();
-        UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
-                                  EXTERNAL_EXTENSION_IGNORED,
-                                  EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-        if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
-          UMA_HISTOGRAM_ENUMERATION(
-              "Extensions.ExternalExtensionEventWebstore",
-              EXTERNAL_EXTENSION_IGNORED,
-              EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-        } else {
-          UMA_HISTOGRAM_ENUMERATION(
-              "Extensions.ExternalExtensionEventNonWebstore",
-              EXTERNAL_EXTENSION_IGNORED,
-              EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-        }
-        return;
-      }
-      if (is_first_run_)
-        extension_prefs_->SetExternalInstallFirstRun(extension->id());
-      // first_run is true if the extension was installed during a first run
-      // (even if it's post-first run now).
-      bool first_run = extension_prefs_->IsExternalInstallFirstRun(
-          extension->id());
-      extensions::AddExternalInstallError(this, extension, first_run);
-    }
-  } else {
-    extensions::RemoveExternalInstallError(this);
-  }
+  external_install_manager_->UpdateExternalExtensionAlert();
 }
 
 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 +1256,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,23 +1263,22 @@ 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);
   }
 
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_REMOVED,
+      extensions::NOTIFICATION_EXTENSION_REMOVED,
       content::Source<Profile>(profile_),
       content::Details<const Extension>(extension.get()));
 }
@@ -1585,80 +1288,34 @@ void ExtensionService::RemoveComponentExtension(
   scoped_refptr<const Extension> extension(
       GetExtensionById(extension_id, false));
   UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
-  content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
-      content::Source<Profile>(profile_),
-      content::Details<const Extension>(extension.get()));
+  if (extension.get()) {
+    content::NotificationService::current()->Notify(
+        extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
+        content::Source<Profile>(profile_),
+        content::Details<const Extension>(extension.get()));
+    ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
+        extension.get(), extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT);
+  }
 }
 
-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
   // times.
 }
 
-void ExtensionService::GarbageCollectExtensions() {
-#if defined(OS_CHROMEOS)
-  if (disable_garbage_collection_)
-    return;
-#endif
-
-  if (extension_prefs_->pref_service()->ReadOnly())
-    return;
-
-  if (pending_extension_manager()->HasPendingExtensions()) {
-    // Don't garbage collect while there are pending installations, which may
-    // be using the temporary installation directory. Try to garbage collect
-    // again later.
-    base::MessageLoop::current()->PostDelayedTask(
-        FROM_HERE,
-        base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
-        base::TimeDelta::FromSeconds(kGarbageCollectRetryDelay));
-    return;
-  }
-
-  scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> info(
-      extension_prefs_->GetInstalledExtensionsInfo());
-
-  std::multimap<std::string, base::FilePath> extension_paths;
-  for (size_t i = 0; i < info->size(); ++i)
-    extension_paths.insert(std::make_pair(info->at(i)->extension_id,
-                                          info->at(i)->extension_path));
-
-  info = extension_prefs_->GetAllDelayedInstallInfo();
-  for (size_t i = 0; i < info->size(); ++i)
-    extension_paths.insert(std::make_pair(info->at(i)->extension_id,
-                                          info->at(i)->extension_path));
-
-  if (!GetFileTaskRunner()->PostTask(
-          FROM_HERE,
-          base::Bind(
-              &extension_file_util::GarbageCollectExtensions,
-              install_directory_,
-              extension_paths))) {
-    NOTREACHED();
-  }
-}
-
 void ExtensionService::SetReadyAndNotifyListeners() {
   ready_->Signal();
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSIONS_READY,
+      extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
       content::Source<Profile>(profile_),
       content::NotificationService::NoDetails());
 }
@@ -1694,7 +1351,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,45 +1377,53 @@ 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(
-        chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
+        extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
         content::Source<Profile>(profile_),
         content::Details<const Extension>(extension));
 
-    // Show the extension disabled error if a permissions increase was the
-    // only reason it was disabled.
-    if (extension_prefs_->GetDisableReasons(extension->id()) ==
-        Extension::DISABLE_PERMISSIONS_INCREASE) {
-      extensions::AddExtensionDisabledError(this, extension);
+    // Show the extension disabled error if a permissions increase or a remote
+    // installation is the reason it was disabled, and no other reasons exist.
+    int reasons = extension_prefs_->GetDisableReasons(extension->id());
+    const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
+                            Extension::DISABLE_REMOTE_INSTALL;
+    if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
+      extensions::AddExtensionDisabledError(
+          this,
+          extension,
+          extension_prefs_->HasDisableReason(
+              extension->id(), Extension::DISABLE_REMOTE_INSTALL));
     }
   } 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()->SetExtensionVisible(
+          extension->id(),
+          extension->ShouldDisplayInNewTabPage() &&
+              !extension_prefs_->IsEphemeralApp(extension->id()));
+      if (!extension_prefs_->IsEphemeralApp(extension->id())) {
+        extension_prefs_->app_sorting()->EnsureValidOrdinals(
+            extension->id(), syncer::StringOrdinal());
       }
-      extension_prefs_->extension_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,56 +1431,26 @@ 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 '"
         << old_version_string << "' to " << extension->version()->GetString();
 
     AddNewOrUpdatedExtension(extension,
-                             Extension::ENABLED_COMPONENT,
-                             extensions::Blacklist::NOT_BLACKLISTED,
-                             syncer::StringOrdinal());
+                             Extension::ENABLED,
+                             extensions::kInstallFlagNone,
+                             syncer::StringOrdinal(),
+                             std::string());
     return;
   }
 
   AddExtension(extension);
 }
 
-void ExtensionService::UpdateActivePermissions(const Extension* extension) {
-  // If the extension has used the optional permissions API, it will have a
-  // 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());
-
-  if (active_permissions.get()) {
-    // We restrict the active permissions to be within the bounds defined in the
-    // extension's manifest.
-    //  a) active permissions must be a subset of optional + default permissions
-    //  b) active permissions must contains all default permissions
-    scoped_refptr<PermissionSet> total_permissions =
-        PermissionSet::CreateUnion(
-            extensions::PermissionsData::GetRequiredPermissions(extension),
-            extensions::PermissionsData::GetOptionalPermissions(extension));
-
-    // Make sure the active permissions contain no more than optional + default.
-    scoped_refptr<PermissionSet> adjusted_active =
-        PermissionSet::CreateIntersection(
-            total_permissions.get(), active_permissions.get());
-
-    // Make sure the active permissions contain the default permissions.
-    adjusted_active = PermissionSet::CreateUnion(
-        extensions::PermissionsData::GetRequiredPermissions(extension),
-        adjusted_active.get());
-
-    extensions::PermissionsUpdater perms_updater(profile());
-    perms_updater.UpdateActivePermissions(extension, adjusted_active.get());
-  }
-}
-
 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
                                                 bool is_extension_installed) {
-  UpdateActivePermissions(extension);
+  extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
 
   // We keep track of all permissions the user has granted each extension.
   // This allows extensions to gracefully support backwards compatibility
@@ -1842,7 +1477,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
@@ -1867,9 +1502,9 @@ void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
     // to a version that requires additional privileges.
     is_privilege_increase =
         extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
-                granted_permissions,
-                extension->GetActivePermissions().get(),
-                extension->GetType());
+            granted_permissions.get(),
+            extension->permissions_data()->active_permissions().get(),
+            extension->GetType());
   }
 
   if (is_extension_installed) {
@@ -1896,12 +1531,17 @@ void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
   }
 
   // Extension has changed permissions significantly. Disable it. A
-  // notification should be sent by the caller.
-  if (is_privilege_increase) {
+  // notification should be sent by the caller. If the extension is already
+  // disabled because it was installed remotely, don't add another disable
+  // reason, but instead always set the "did escalate permissions" flag, to
+  // ensure enabling it will always show a warning.
+  if (disable_reasons == Extension::DISABLE_REMOTE_INSTALL) {
+    extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
+  } else if (is_privilege_increase) {
     disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
     if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
-      RecordPermissionMessagesHistogram(
-          extension, "Extensions.Permissions_AutoDisable");
+      RecordPermissionMessagesHistogram(extension,
+                                        "Extensions.Permissions_AutoDisable2");
     }
     extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
     extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
@@ -1915,126 +1555,32 @@ 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);
 }
 
-ExtensionService::ImportStatus ExtensionService::CheckImports(
-    const extensions::Extension* extension,
-    std::list<SharedModuleInfo::ImportInfo>* missing_modules,
-    std::list<SharedModuleInfo::ImportInfo>* outdated_modules) {
-  DCHECK(extension);
-  DCHECK(missing_modules && missing_modules->empty());
-  DCHECK(outdated_modules && outdated_modules->empty());
-  ImportStatus status = IMPORT_STATUS_OK;
-  if (SharedModuleInfo::ImportsModules(extension)) {
-    const std::vector<SharedModuleInfo::ImportInfo>& imports =
-        SharedModuleInfo::GetImports(extension);
-    std::vector<SharedModuleInfo::ImportInfo>::const_iterator i;
-    for (i = imports.begin(); i != imports.end(); ++i) {
-      Version version_required(i->minimum_version);
-      const Extension* imported_module =
-          GetExtensionById(i->extension_id, true);
-      if (!imported_module) {
-        if (extension->from_webstore()) {
-          status = IMPORT_STATUS_UNSATISFIED;
-          missing_modules->push_back(*i);
-        } else {
-          return IMPORT_STATUS_UNRECOVERABLE;
-        }
-      } else if (!SharedModuleInfo::IsSharedModule(imported_module)) {
-        return IMPORT_STATUS_UNRECOVERABLE;
-      } else if (version_required.IsValid() &&
-                 imported_module->version()->CompareTo(version_required) < 0) {
-        if (imported_module->from_webstore()) {
-          outdated_modules->push_back(*i);
-          status = IMPORT_STATUS_UNSATISFIED;
-        } else {
-          return IMPORT_STATUS_UNRECOVERABLE;
-        }
-      }
-    }
-  }
-  return status;
-}
-
-ExtensionService::ImportStatus ExtensionService::SatisfyImports(
-    const Extension* extension) {
-  std::list<SharedModuleInfo::ImportInfo> noinstalled;
-  std::list<SharedModuleInfo::ImportInfo> outdated;
-  ImportStatus status = CheckImports(extension, &noinstalled, &outdated);
-  if (status == IMPORT_STATUS_UNRECOVERABLE)
-    return status;
-  if (status == IMPORT_STATUS_UNSATISFIED) {
-    std::list<SharedModuleInfo::ImportInfo>::const_iterator iter;
-    for (iter = noinstalled.begin(); iter != noinstalled.end(); ++iter) {
-      pending_extension_manager()->AddFromExtensionImport(
-          iter->extension_id,
-          extension_urls::GetWebstoreUpdateUrl(),
-          IsSharedModule);
-    }
-    CheckForUpdatesSoon();
-  }
-  return status;
-}
-
-scoped_ptr<const ExtensionSet>
-    ExtensionService::GetDependentExtensions(const Extension* extension) {
-  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(delayed_installs_);
-    set_to_check->InsertAll(extensions_);
-    for (ExtensionSet::const_iterator iter = set_to_check->begin();
-         iter != set_to_check->end(); ++iter) {
-      if (SharedModuleInfo::ImportsExtensionById(iter->get(),
-                                                 extension->id())) {
-        dependents->Insert(*iter);
-      }
-    }
-  }
-  return dependents.PassAs<const ExtensionSet>();
-}
-
-void ExtensionService::PruneSharedModulesOnUninstall(
-    const Extension* extension) {
-  if (SharedModuleInfo::ImportsModules(extension)) {
-    const std::vector<SharedModuleInfo::ImportInfo>& imports =
-        SharedModuleInfo::GetImports(extension);
-    std::vector<SharedModuleInfo::ImportInfo>::const_iterator i;
-    for (i = imports.begin(); i != imports.end(); ++i) {
-      const Extension* imported_module =
-          GetExtensionById(i->extension_id, true);
-      if (imported_module && imported_module->from_webstore()) {
-        scoped_ptr<const ExtensionSet> dependents =
-            GetDependentExtensions(imported_module);
-        if (dependents->size() == 0) {
-          UninstallExtension(i->extension_id, true, NULL);
-        }
-      }
-    }
-  }
-}
-
 void ExtensionService::OnExtensionInstalled(
     const Extension* extension,
     const syncer::StringOrdinal& page_ordinal,
-    bool has_requirement_errors,
-    extensions::Blacklist::BlacklistState blacklist_state,
-    bool wait_for_idle) {
+    int install_flags) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
 
   const std::string& id = extension->id();
   bool initial_enable = ShouldEnableOnInstall(extension);
-  const extensions::PendingExtensionInfo* pending_extension_info = NULL;
-  if ((pending_extension_info = pending_extension_manager()->GetById(id))) {
+  std::string install_parameter;
+  const extensions::PendingExtensionInfo* pending_extension_info =
+      pending_extension_manager()->GetById(id);
+  if (pending_extension_info) {
     if (!pending_extension_info->ShouldAllowInstall(extension)) {
       pending_extension_manager()->Remove(id);
 
@@ -2048,25 +1594,27 @@ void ExtensionService::OnExtensionInstalled(
       // load it.
       if (!GetFileTaskRunner()->PostTask(
               FROM_HERE,
-              base::Bind(&extension_file_util::DeleteFile,
-                         extension->path(), true))) {
+              base::Bind(&extensions::file_util::DeleteFile,
+                         extension->path(),
+                         true))) {
         NOTREACHED();
       }
       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;
     }
   }
 
   // Unsupported requirements overrides the management policy.
-  if (has_requirement_errors) {
+  if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
     initial_enable = false;
     extension_prefs_->AddDisableReason(
         id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
@@ -2079,13 +1627,13 @@ void ExtensionService::OnExtensionInstalled(
     extension_prefs_->ClearDisableReasons(id);
   }
 
-  if (blacklist_state == extensions::Blacklist::BLACKLISTED_MALWARE) {
+  if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
     // 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);
@@ -2096,81 +1644,93 @@ void ExtensionService::OnExtensionInstalled(
                               extension->GetType(), 100);
     UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
                               extension->location(), Manifest::NUM_LOCATIONS);
-    RecordPermissionMessagesHistogram(
-        extension, "Extensions.Permissions_Install");
+    RecordPermissionMessagesHistogram(extension,
+                                      "Extensions.Permissions_Install2");
   } else {
     UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
                               extension->GetType(), 100);
     UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
                               extension->location(), Manifest::NUM_LOCATIONS);
+
+    // A fully installed app cannot be demoted to an ephemeral app.
+    if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
+        !extension_prefs_->IsEphemeralApp(id)) {
+      install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
+    }
   }
 
-  // Certain extension locations are specific enough that we can
-  // auto-acknowledge any extension that came from one of them.
-  if (Manifest::IsPolicyLocation(extension->location()))
-    AcknowledgeExternalExtension(extension->id());
   const Extension::State initial_state =
       initial_enable ? Extension::ENABLED : Extension::DISABLED;
-  if (ShouldDelayExtensionUpdate(id, wait_for_idle)) {
+  if (ShouldDelayExtensionUpdate(
+          id,
+          !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
     extension_prefs_->SetDelayedInstallInfo(
         extension,
         initial_state,
-        blacklist_state,
+        install_flags,
         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;
   }
 
-  ImportStatus status = SatisfyImports(extension);
-  if (installs_delayed_for_gc()) {
+  extensions::SharedModuleService::ImportStatus status =
+      shared_module_service_->SatisfyImports(extension);
+  if (installs_delayed_for_gc_) {
     extension_prefs_->SetDelayedInstallInfo(
         extension,
         initial_state,
-        blacklist_state,
+        install_flags,
         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) {
+  } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
+    if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
       extension_prefs_->SetDelayedInstallInfo(
           extension,
           initial_state,
-          blacklist_state,
+          install_flags,
           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);
+                             install_flags,
+                             page_ordinal,
+                             install_parameter);
   }
 }
 
+void ExtensionService::OnExtensionManagementSettingsChanged() {
+  error_controller_->ShowErrorIfNeeded();
+  CheckManagementPolicy();
+}
+
 void ExtensionService::AddNewOrUpdatedExtension(
     const Extension* extension,
     Extension::State initial_state,
-    extensions::Blacklist::BlacklistState blacklist_state,
-    const syncer::StringOrdinal& page_ordinal) {
+    int install_flags,
+    const syncer::StringOrdinal& page_ordinal,
+    const std::string& install_parameter) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
-  extension_prefs_->OnExtensionInstalled(extension,
-                                         initial_state,
-                                         blacklist_state,
-                                         page_ordinal);
+  bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
+  extension_prefs_->OnExtensionInstalled(
+      extension, initial_state, page_ordinal, install_flags, install_parameter);
   delayed_installs_.Remove(extension->id());
-  FinishInstallation(extension);
+  if (InstallVerifier::NeedsVerification(*extension))
+    system_->install_verifier()->VerifyExtension(extension->id());
+  FinishInstallation(extension, was_ephemeral);
 }
 
 void ExtensionService::MaybeFinishDelayedInstallation(
@@ -2186,14 +1746,15 @@ 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);
   if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
-    ImportStatus status = SatisfyImports(extension);
-    if (status != IMPORT_STATUS_OK) {
-      if (status == IMPORT_STATUS_UNRECOVERABLE) {
+    extensions::SharedModuleService::ImportStatus status =
+        shared_module_service_->SatisfyImports(extension);
+    if (status != SharedModuleService::IMPORT_STATUS_OK) {
+      if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
         delayed_installs_.Remove(extension_id);
         // Make sure no version of the extension is actually installed, (i.e.,
         // that this delayed install was not an update).
@@ -2214,13 +1775,15 @@ void ExtensionService::FinishDelayedInstallation(
   CHECK(extension.get());
   delayed_installs_.Remove(extension_id);
 
+  bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
   if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
     NOTREACHED();
 
-  FinishInstallation(extension.get());
+  FinishInstallation(extension.get(), was_ephemeral);
 }
 
-void ExtensionService::FinishInstallation(const Extension* extension) {
+void ExtensionService::FinishInstallation(
+    const Extension* extension, bool was_ephemeral) {
   const extensions::Extension* existing_extension =
       GetInstalledExtension(extension->id());
   bool is_update = false;
@@ -2229,13 +1792,17 @@ void ExtensionService::FinishInstallation(const Extension* extension) {
     is_update = true;
     old_name = existing_extension->name();
   }
-  extensions::InstalledExtensionInfo details(extension, is_update, old_name);
+  bool from_ephemeral =
+      was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
+  extensions::InstalledExtensionInfo details(
+      extension, is_update, from_ephemeral, old_name);
   content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_INSTALLED,
+      extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
       content::Source<Profile>(profile_),
       content::Details<const extensions::InstalledExtensionInfo>(&details));
 
-  bool unacknowledged_external = IsUnacknowledgedExternalExtension(extension);
+  registry_->TriggerOnWillBeInstalled(
+      extension, is_update, from_ephemeral, old_name);
 
   // Unpacked extensions default to allowing file access, but if that has been
   // overridden, don't reset the value.
@@ -2246,30 +1813,86 @@ void ExtensionService::FinishInstallation(const Extension* extension) {
 
   AddExtension(extension);
 
-  // If this is a new external extension that was disabled, alert the user
-  // so he can reenable it. We do this last so that it has already been
-  // added to our list of extensions.
-  if (unacknowledged_external && !is_update) {
-    UpdateExternalExtensionAlert();
-    UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
-                              EXTERNAL_EXTENSION_INSTALLED,
-                              EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
-      UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
-                                EXTERNAL_EXTENSION_INSTALLED,
-                                EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    } else {
-      UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
-                                EXTERNAL_EXTENSION_INSTALLED,
-                                EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
-    }
-  }
+  // Notify observers that need to know when an installation is complete.
+  registry_->TriggerOnInstalled(extension, is_update);
 
   // Check extensions that may have been delayed only because this shared module
   // was not available.
-  if (SharedModuleInfo::IsSharedModule(extension)) {
+  if (SharedModuleInfo::IsSharedModule(extension))
     MaybeFinishDelayedInstallations();
+}
+
+void ExtensionService::PromoteEphemeralApp(
+    const extensions::Extension* extension, bool is_from_sync) {
+  DCHECK(GetInstalledExtension(extension->id()) &&
+         extension_prefs_->IsEphemeralApp(extension->id()));
+
+  if (extension->RequiresSortOrdinal()) {
+    extension_prefs_->app_sorting()->SetExtensionVisible(
+        extension->id(), extension->ShouldDisplayInNewTabPage());
+
+    if (!is_from_sync) {
+      // Reset the sort ordinals of the app to ensure it is added to the default
+      // position, like newly installed apps would.
+      extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
+    }
+
+    extension_prefs_->app_sorting()->EnsureValidOrdinals(
+        extension->id(), syncer::StringOrdinal());
+  }
+
+  // Remove the ephemeral flags from the preferences.
+  extension_prefs_->OnEphemeralAppPromoted(extension->id());
+
+  // Fire install-related events to allow observers to handle the promotion
+  // of the ephemeral app.
+  extensions::InstalledExtensionInfo details(
+      extension,
+      true /* is update */,
+      true /* from ephemeral */,
+      extension->name() /* old name */);
+  content::NotificationService::current()->Notify(
+      extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
+      content::Source<Profile>(profile_),
+      content::Details<const extensions::InstalledExtensionInfo>(&details));
+
+  registry_->TriggerOnWillBeInstalled(
+      extension,
+      true /* is update */,
+      true /* from ephemeral */,
+      extension->name() /* old name */);
+
+  if (registry_->enabled_extensions().Contains(extension->id())) {
+    // If the app is already enabled and loaded, fire the load events to allow
+    // observers to handle the promotion of the ephemeral app.
+    content::NotificationService::current()->Notify(
+        extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
+        content::Source<Profile>(profile_),
+        content::Details<const Extension>(extension));
+
+    registry_->TriggerOnLoaded(extension);
+  } else {
+    // Cached ephemeral apps may be updated and disabled due to permissions
+    // increase. The app can be enabled (as long as no other disable reasons
+    // exist) as the install was user-acknowledged.
+    int disable_mask = Extension::DISABLE_NONE;
+    if (!is_from_sync)
+      disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
+
+    int other_disable_reasons =
+        extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
+    if (!other_disable_reasons) {
+      if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
+        GrantPermissionsAndEnableExtension(extension);
+      else
+        EnableExtension(extension->id());
+    }
   }
+
+  registry_->TriggerOnInstalled(extension, true);
+
+  if (!is_from_sync && extension_sync_service_)
+    extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
 }
 
 const Extension* ExtensionService::GetPendingExtensionUpdate(
@@ -2277,54 +1900,50 @@ const Extension* ExtensionService::GetPendingExtensionUpdate(
   return delayed_installs_.GetByID(id);
 }
 
-void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
-  if (!terminated_extensions_.Contains(extension->id()))
-    terminated_extensions_.Insert(make_scoped_refptr(extension));
+void ExtensionService::RegisterContentSettings(
+    HostContentSettingsMap* host_content_settings_map) {
+  host_content_settings_map->RegisterProvider(
+      HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
+      scoped_ptr<content_settings::ObservableProvider>(
+          new content_settings::InternalExtensionProvider(this)));
 
+  host_content_settings_map->RegisterProvider(
+      HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
+      scoped_ptr<content_settings::ObservableProvider>(
+          new content_settings::CustomExtensionProvider(
+              extensions::ContentSettingsService::Get(
+                  profile_)->content_settings_store(),
+              profile_->GetOriginalProfile() != profile_)));
+}
+
+void ExtensionService::TrackTerminatedExtension(const Extension* 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::TerminateExtension(const std::string& extension_id) {
+  const Extension* extension = GetInstalledExtension(extension_id);
+  TrackTerminatedExtension(extension);
+}
+
 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);
+  std::string lowercase_id = base::StringToLowerASCII(id);
+  const Extension* extension =
+      registry_->terminated_extensions().GetByID(lowercase_id);
+  registry_->RemoveTerminated(lowercase_id);
   if (extension) {
     content::NotificationService::current()->Notify(
-        chrome::NOTIFICATION_EXTENSION_REMOVED,
+        extensions::NOTIFICATION_EXTENSION_REMOVED,
         content::Source<Profile>(profile_),
         content::Details<const Extension>(extension));
   }
 }
 
-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);
-}
-
-bool ExtensionService::ExtensionBindingsAllowed(const GURL& url) {
-  // Allow bindings for all packaged extensions and component hosted apps.
-  const Extension* extension = 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;
+  return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
 }
 
 bool ExtensionService::OnExternalExtensionFileFound(
@@ -2335,7 +1954,7 @@ bool ExtensionService::OnExternalExtensionFileFound(
          int creation_flags,
          bool mark_acknowledged) {
   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
-  CHECK(Extension::IdIsValid(id));
+  CHECK(crx_file::id_util::IdIsValid(id));
   if (extension_prefs_->IsExternalExtensionUninstalled(id))
     return false;
 
@@ -2395,27 +2014,11 @@ bool ExtensionService::OnExternalExtensionFileFound(
   // notification on installation. For such extensions, mark them acknowledged
   // now to suppress the notification.
   if (mark_acknowledged)
-    AcknowledgeExternalExtension(id);
+    external_install_manager_->AcknowledgeExternalExtension(id);
 
   return true;
 }
 
-void ExtensionService::ReportExtensionLoadError(
-    const base::FilePath& extension_path,
-    const std::string &error,
-    bool be_noisy) {
-  content::NotificationService::current()->Notify(
-      chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
-      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);
-}
-
 void ExtensionService::DidCreateRenderViewForBackgroundPage(
     extensions::ExtensionHost* host) {
   OrphanedDevTools::iterator iter =
@@ -2423,7 +2026,7 @@ void ExtensionService::DidCreateRenderViewForBackgroundPage(
   if (iter == orphaned_dev_tools_.end())
     return;
 
-  iter->second->ConnectRenderViewHost(host->render_view_host());
+  iter->second->ConnectWebContents(host->host_contents());
   orphaned_dev_tools_.erase(iter);
 }
 
@@ -2437,7 +2040,7 @@ void ExtensionService::Observe(int type,
       // happens too late in browser teardown.)
       browser_terminating_ = true;
       break;
-    case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
+    case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
       if (profile_ !=
           content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
         break;
@@ -2446,6 +2049,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 +2067,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 +2075,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,105 +2094,31 @@ 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());
       break;
     }
+    case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
+      OnProfileDestructionStarted();
+      break;
+    }
 
     default:
       NOTREACHED() << "Unexpected notification type.";
   }
 }
 
-void ExtensionService::OnExtensionInstallPrefChanged() {
-  IdentifyAlertableExtensions();
-  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);
-}
-
-void ExtensionService::SetBeingReloaded(const std::string& extension_id,
-                                        bool isBeingReloaded) {
-  if (isBeingReloaded)
-    extensions_being_reloaded_.insert(extension_id);
-  else
-    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.
@@ -2648,31 +2142,14 @@ 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 {
+    bool install_immediately) const {
   const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
 
   // If delayed updates are globally disabled, or just for this extension,
   // don't delay.
-  if (!install_updates_when_idle_ || !wait_for_idle)
+  if (!install_updates_when_idle_ || install_immediately)
     return false;
 
   const Extension* old = GetInstalledExtension(extension_id);
@@ -2687,31 +2164,18 @@ 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) {
-    if (extensions::AppIsolationInfo::HasIsolatedStorage(it->get())) {
-      active_paths->insert(BrowserContext::GetStoragePartitionForSite(
-          profile_, GetSiteForExtensionId((*it)->id()))->GetPath());
-    }
-  }
-
-  DCHECK(!installs_delayed_for_gc());
-  set_installs_delayed_for_gc(true);
-  BrowserContext::GarbageCollectStoragePartitions(
-      profile_, active_paths.Pass(),
-      base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished,
-                 AsWeakPtr()));
+void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
+  DCHECK(!installs_delayed_for_gc_);
+  installs_delayed_for_gc_ = true;
 }
 
 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
-  set_installs_delayed_for_gc(false);
+  DCHECK(installs_delayed_for_gc_);
+  installs_delayed_for_gc_ = false;
   MaybeFinishDelayedInstallations();
 }
 
@@ -2729,35 +2193,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) {
-  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+void ExtensionService::ManageBlacklist(
+    const extensions::Blacklist::BlacklistStateMap& state_map) {
+  DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+  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);
+
+  error_controller_->ShowErrorIfNeeded();
+}
+
+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
 
-  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);
+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 +2273,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 +2341,24 @@ 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.
+}
+
+void ExtensionService::OnProfileDestructionStarted() {
+  ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
+  for (ExtensionIdSet::iterator it = ids_to_unload.begin();
+       it != ids_to_unload.end();
+       ++it) {
+    UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);
+  }
+}