Merge "Document the ":module{.tag}" syntax in a more visible place."
diff --git a/Android.bp b/Android.bp
index 7259255..0ca11d3 100644
--- a/Android.bp
+++ b/Android.bp
@@ -51,6 +51,7 @@
         "android/expand.go",
         "android/filegroup.go",
         "android/hooks.go",
+        "android/image.go",
         "android/makevars.go",
         "android/module.go",
         "android/mutator.go",
diff --git a/android/androidmk_test.go b/android/androidmk_test.go
index 0bb455b..940e324 100644
--- a/android/androidmk_test.go
+++ b/android/androidmk_test.go
@@ -47,8 +47,8 @@
 	config.inMake = true // Enable androidmk Singleton
 
 	ctx := NewTestContext()
-	ctx.RegisterSingletonType("androidmk", SingletonFactoryAdaptor(AndroidMkSingleton))
-	ctx.RegisterModuleType("custom", ModuleFactoryAdaptor(customModuleFactory))
+	ctx.RegisterSingletonType("androidmk", AndroidMkSingleton)
+	ctx.RegisterModuleType("custom", customModuleFactory)
 	ctx.Register()
 
 	bp := `
diff --git a/android/apex.go b/android/apex.go
index 5118a0a..44387cd 100644
--- a/android/apex.go
+++ b/android/apex.go
@@ -17,8 +17,6 @@
 import (
 	"sort"
 	"sync"
-
-	"github.com/google/blueprint"
 )
 
 // ApexModule is the interface that a module type is expected to implement if
@@ -69,7 +67,7 @@
 
 	// Mutate this module into one or more variants each of which is built
 	// for an APEX marked via BuildForApex().
-	CreateApexVariations(mctx BottomUpMutatorContext) []blueprint.Module
+	CreateApexVariations(mctx BottomUpMutatorContext) []Module
 
 	// Sets the name of the apex variant of this module. Called inside
 	// CreateApexVariations.
@@ -176,7 +174,7 @@
 	}
 }
 
-func (m *ApexModuleBase) CreateApexVariations(mctx BottomUpMutatorContext) []blueprint.Module {
+func (m *ApexModuleBase) CreateApexVariations(mctx BottomUpMutatorContext) []Module {
 	if len(m.apexVariations) > 0 {
 		m.checkApexAvailableProperty(mctx)
 		sort.Strings(m.apexVariations)
diff --git a/android/arch_test.go b/android/arch_test.go
index 52a6684..b41e1ab 100644
--- a/android/arch_test.go
+++ b/android/arch_test.go
@@ -338,7 +338,7 @@
 	for _, tt := range testCases {
 		t.Run(tt.name, func(t *testing.T) {
 			ctx := NewTestArchContext()
-			ctx.RegisterModuleType("module", ModuleFactoryAdaptor(archTestModuleFactory))
+			ctx.RegisterModuleType("module", archTestModuleFactory)
 			ctx.MockFileSystem(mockFS)
 			ctx.Register()
 			config := TestArchConfig(buildDir, nil)
diff --git a/android/csuite_config_test.go b/android/csuite_config_test.go
index e534bb7..5f86bbb 100644
--- a/android/csuite_config_test.go
+++ b/android/csuite_config_test.go
@@ -22,7 +22,7 @@
 	config := TestArchConfig(buildDir, nil)
 
 	ctx := NewTestArchContext()
-	ctx.RegisterModuleType("csuite_config", ModuleFactoryAdaptor(CSuiteConfigFactory))
+	ctx.RegisterModuleType("csuite_config", CSuiteConfigFactory)
 	ctx.Register()
 	mockFiles := map[string][]byte{
 		"Android.bp": []byte(bpFileContents),
diff --git a/android/defaults_test.go b/android/defaults_test.go
index fa26595..80980f7 100644
--- a/android/defaults_test.go
+++ b/android/defaults_test.go
@@ -64,8 +64,8 @@
 	ctx := NewTestContext()
 	ctx.SetAllowMissingDependencies(true)
 
-	ctx.RegisterModuleType("test", ModuleFactoryAdaptor(defaultsTestModuleFactory))
-	ctx.RegisterModuleType("defaults", ModuleFactoryAdaptor(defaultsTestDefaultsFactory))
+	ctx.RegisterModuleType("test", defaultsTestModuleFactory)
+	ctx.RegisterModuleType("defaults", defaultsTestDefaultsFactory)
 
 	ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
 
diff --git a/android/image.go b/android/image.go
new file mode 100644
index 0000000..5ec1b16
--- /dev/null
+++ b/android/image.go
@@ -0,0 +1,83 @@
+// Copyright 2019 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package android
+
+// ImageInterface is implemented by modules that need to be split by the ImageMutator.
+type ImageInterface interface {
+	// ImageMutatorBegin is called before any other method in the ImageInterface.
+	ImageMutatorBegin(ctx BaseModuleContext)
+
+	// CoreVariantNeeded should return true if the module needs a core variant (installed on the system image).
+	CoreVariantNeeded(ctx BaseModuleContext) bool
+
+	// RecoveryVariantNeeded should return true if the module needs a recovery variant (installed on the
+	// recovery partition).
+	RecoveryVariantNeeded(ctx BaseModuleContext) bool
+
+	// ExtraImageVariations should return a list of the additional variations needed for the module.  After the
+	// variants are created the SetImageVariation method will be called on each newly created variant with the
+	// its variation.
+	ExtraImageVariations(ctx BaseModuleContext) []string
+
+	// SetImageVariation will be passed a newly created recovery variant of the module.  ModuleBase implements
+	// SetImageVariation, most module types will not need to override it, and those that do must call the
+	// overridden method.  Implementors of SetImageVariation must be careful to modify the module argument
+	// and not the receiver.
+	SetImageVariation(ctx BaseModuleContext, variation string, module Module)
+}
+
+const (
+	// CoreVariation is the variant used for framework-private libraries, or
+	// SDK libraries. (which framework-private libraries can use), which
+	// will be installed to the system image.
+	CoreVariation string = "core"
+
+	// RecoveryVariation means a module to be installed to recovery image.
+	RecoveryVariation string = "recovery"
+)
+
+// ImageMutator creates variants for modules that implement the ImageInterface that
+// allow them to build differently for each partition (recovery, core, vendor, etc.).
+func ImageMutator(ctx BottomUpMutatorContext) {
+	if ctx.Os() != Android {
+		return
+	}
+
+	if m, ok := ctx.Module().(ImageInterface); ok {
+		m.ImageMutatorBegin(ctx)
+
+		var variations []string
+
+		if m.CoreVariantNeeded(ctx) {
+			variations = append(variations, CoreVariation)
+		}
+		if m.RecoveryVariantNeeded(ctx) {
+			variations = append(variations, RecoveryVariation)
+		}
+
+		extraVariations := m.ExtraImageVariations(ctx)
+		variations = append(variations, extraVariations...)
+
+		if len(variations) == 0 {
+			return
+		}
+
+		mod := ctx.CreateVariations(variations...)
+		for i, v := range variations {
+			mod[i].base().setImageVariation(v)
+			m.SetImageVariation(ctx, v, mod[i])
+		}
+	}
+}
diff --git a/android/module.go b/android/module.go
index 891babc..2ae2961 100644
--- a/android/module.go
+++ b/android/module.go
@@ -431,6 +431,9 @@
 	DebugName       string   `blueprint:"mutated"`
 	DebugMutators   []string `blueprint:"mutated"`
 	DebugVariations []string `blueprint:"mutated"`
+
+	// set by ImageMutator
+	ImageVariation string `blueprint:"mutated"`
 }
 
 type hostAndDeviceProperties struct {
@@ -865,6 +868,21 @@
 	return m.noticeFile
 }
 
+func (m *ModuleBase) setImageVariation(variant string) {
+	m.commonProperties.ImageVariation = variant
+}
+
+func (m *ModuleBase) ImageVariation() blueprint.Variation {
+	return blueprint.Variation{
+		Mutator:   "image",
+		Variation: m.base().commonProperties.ImageVariation,
+	}
+}
+
+func (m *ModuleBase) InRecovery() bool {
+	return m.base().commonProperties.ImageVariation == RecoveryVariation
+}
+
 func (m *ModuleBase) generateModuleTarget(ctx ModuleContext) {
 	allInstalledFiles := Paths{}
 	allCheckbuildFiles := Paths{}
@@ -1515,9 +1533,11 @@
 }
 
 func (m *ModuleBase) MakeAsSystemExt() {
-	if !Bool(m.commonProperties.Vendor) && !Bool(m.commonProperties.Product_specific) {
-		m.commonProperties.System_ext_specific = boolPtr(true)
-	}
+	m.commonProperties.Vendor = boolPtr(false)
+	m.commonProperties.Proprietary = boolPtr(false)
+	m.commonProperties.Soc_specific = boolPtr(false)
+	m.commonProperties.Product_specific = boolPtr(false)
+	m.commonProperties.System_ext_specific = boolPtr(true)
 }
 
 // IsNativeBridgeSupported returns true if "native_bridge_supported" is explicitly set as "true"
diff --git a/android/module_test.go b/android/module_test.go
index 6dca29f..fef1766 100644
--- a/android/module_test.go
+++ b/android/module_test.go
@@ -165,7 +165,7 @@
 
 func TestErrorDependsOnDisabledModule(t *testing.T) {
 	ctx := NewTestContext()
-	ctx.RegisterModuleType("deps", ModuleFactoryAdaptor(depsModuleFactory))
+	ctx.RegisterModuleType("deps", depsModuleFactory)
 
 	bp := `
 		deps {
diff --git a/android/mutator.go b/android/mutator.go
index df68726..0d253eb 100644
--- a/android/mutator.go
+++ b/android/mutator.go
@@ -143,8 +143,8 @@
 
 	AddDependency(module blueprint.Module, tag blueprint.DependencyTag, name ...string)
 	AddReverseDependency(module blueprint.Module, tag blueprint.DependencyTag, name string)
-	CreateVariations(...string) []blueprint.Module
-	CreateLocalVariations(...string) []blueprint.Module
+	CreateVariations(...string) []Module
+	CreateLocalVariations(...string) []Module
 	SetDependencyVariation(string)
 	SetDefaultDependencyVariation(*string)
 	AddVariationDependencies([]blueprint.Variation, blueprint.DependencyTag, ...string)
@@ -285,28 +285,32 @@
 	b.bp.AddReverseDependency(module, tag, name)
 }
 
-func (b *bottomUpMutatorContext) CreateVariations(variations ...string) []blueprint.Module {
+func (b *bottomUpMutatorContext) CreateVariations(variations ...string) []Module {
 	modules := b.bp.CreateVariations(variations...)
 
+	aModules := make([]Module, len(modules))
 	for i := range variations {
-		base := modules[i].(Module).base()
+		aModules[i] = modules[i].(Module)
+		base := aModules[i].base()
 		base.commonProperties.DebugMutators = append(base.commonProperties.DebugMutators, b.MutatorName())
 		base.commonProperties.DebugVariations = append(base.commonProperties.DebugVariations, variations[i])
 	}
 
-	return modules
+	return aModules
 }
 
-func (b *bottomUpMutatorContext) CreateLocalVariations(variations ...string) []blueprint.Module {
+func (b *bottomUpMutatorContext) CreateLocalVariations(variations ...string) []Module {
 	modules := b.bp.CreateLocalVariations(variations...)
 
+	aModules := make([]Module, len(modules))
 	for i := range variations {
-		base := modules[i].(Module).base()
+		aModules[i] = modules[i].(Module)
+		base := aModules[i].base()
 		base.commonProperties.DebugMutators = append(base.commonProperties.DebugMutators, b.MutatorName())
 		base.commonProperties.DebugVariations = append(base.commonProperties.DebugVariations, variations[i])
 	}
 
-	return modules
+	return aModules
 }
 
 func (b *bottomUpMutatorContext) SetDependencyVariation(variation string) {
diff --git a/android/mutator_test.go b/android/mutator_test.go
index 0b23434..2350fdb 100644
--- a/android/mutator_test.go
+++ b/android/mutator_test.go
@@ -62,7 +62,7 @@
 	ctx := NewTestContext()
 	ctx.SetAllowMissingDependencies(true)
 
-	ctx.RegisterModuleType("test", ModuleFactoryAdaptor(mutatorTestModuleFactory))
+	ctx.RegisterModuleType("test", mutatorTestModuleFactory)
 	ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
 		ctx.TopDown("add_missing_dependencies", addMissingDependenciesMutator)
 	})
@@ -131,7 +131,7 @@
 		})
 	})
 
-	ctx.RegisterModuleType("test", ModuleFactoryAdaptor(mutatorTestModuleFactory))
+	ctx.RegisterModuleType("test", mutatorTestModuleFactory)
 
 	bp := `
 		test {
diff --git a/android/namespace_test.go b/android/namespace_test.go
index 20241fe..90058e3 100644
--- a/android/namespace_test.go
+++ b/android/namespace_test.go
@@ -637,9 +637,9 @@
 
 	ctx = NewTestContext()
 	ctx.MockFileSystem(bps)
-	ctx.RegisterModuleType("test_module", ModuleFactoryAdaptor(newTestModule))
-	ctx.RegisterModuleType("soong_namespace", ModuleFactoryAdaptor(NamespaceFactory))
-	ctx.RegisterModuleType("blueprint_test_module", newBlueprintTestModule)
+	ctx.RegisterModuleType("test_module", newTestModule)
+	ctx.RegisterModuleType("soong_namespace", NamespaceFactory)
+	ctx.Context.RegisterModuleType("blueprint_test_module", newBlueprintTestModule)
 	ctx.PreArchMutators(RegisterNamespaceMutator)
 	ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
 		ctx.BottomUp("rename", renameMutator)
diff --git a/android/neverallow_test.go b/android/neverallow_test.go
index b75b5b7..bd94e37 100644
--- a/android/neverallow_test.go
+++ b/android/neverallow_test.go
@@ -269,10 +269,10 @@
 
 func testNeverallow(config Config, fs map[string][]byte) (*TestContext, []error) {
 	ctx := NewTestContext()
-	ctx.RegisterModuleType("cc_library", ModuleFactoryAdaptor(newMockCcLibraryModule))
-	ctx.RegisterModuleType("java_library", ModuleFactoryAdaptor(newMockJavaLibraryModule))
-	ctx.RegisterModuleType("java_library_host", ModuleFactoryAdaptor(newMockJavaLibraryModule))
-	ctx.RegisterModuleType("java_device_for_host", ModuleFactoryAdaptor(newMockJavaLibraryModule))
+	ctx.RegisterModuleType("cc_library", newMockCcLibraryModule)
+	ctx.RegisterModuleType("java_library", newMockJavaLibraryModule)
+	ctx.RegisterModuleType("java_library_host", newMockJavaLibraryModule)
+	ctx.RegisterModuleType("java_device_for_host", newMockJavaLibraryModule)
 	ctx.PostDepsMutators(registerNeverallowMutator)
 	ctx.Register()
 
diff --git a/android/package_test.go b/android/package_test.go
index e5b0556..ae286d6 100644
--- a/android/package_test.go
+++ b/android/package_test.go
@@ -87,7 +87,7 @@
 	config := TestArchConfig(buildDir, nil)
 
 	ctx := NewTestArchContext()
-	ctx.RegisterModuleType("package", ModuleFactoryAdaptor(PackageFactory))
+	ctx.RegisterModuleType("package", PackageFactory)
 	ctx.PreArchMutators(registerPackageRenamer)
 	ctx.Register()
 
diff --git a/android/path_properties_test.go b/android/path_properties_test.go
index 59bfa6c..c859bc5 100644
--- a/android/path_properties_test.go
+++ b/android/path_properties_test.go
@@ -100,8 +100,8 @@
 			config := TestArchConfig(buildDir, nil)
 			ctx := NewTestArchContext()
 
-			ctx.RegisterModuleType("test", ModuleFactoryAdaptor(pathDepsMutatorTestModuleFactory))
-			ctx.RegisterModuleType("filegroup", ModuleFactoryAdaptor(FileGroupFactory))
+			ctx.RegisterModuleType("test", pathDepsMutatorTestModuleFactory)
+			ctx.RegisterModuleType("filegroup", FileGroupFactory)
 
 			bp := test.bp + `
 				filegroup {
diff --git a/android/paths_test.go b/android/paths_test.go
index 2e67272..1d8afa9 100644
--- a/android/paths_test.go
+++ b/android/paths_test.go
@@ -865,9 +865,9 @@
 			config := TestConfig(buildDir, nil)
 			ctx := NewTestContext()
 
-			ctx.RegisterModuleType("test", ModuleFactoryAdaptor(pathForModuleSrcTestModuleFactory))
-			ctx.RegisterModuleType("output_file_provider", ModuleFactoryAdaptor(pathForModuleSrcOutputFileProviderModuleFactory))
-			ctx.RegisterModuleType("filegroup", ModuleFactoryAdaptor(FileGroupFactory))
+			ctx.RegisterModuleType("test", pathForModuleSrcTestModuleFactory)
+			ctx.RegisterModuleType("output_file_provider", pathForModuleSrcOutputFileProviderModuleFactory)
+			ctx.RegisterModuleType("filegroup", FileGroupFactory)
 
 			fgBp := `
 				filegroup {
@@ -1079,7 +1079,7 @@
 	ctx := NewTestContext()
 	ctx.SetAllowMissingDependencies(true)
 
-	ctx.RegisterModuleType("test", ModuleFactoryAdaptor(pathForModuleSrcTestModuleFactory))
+	ctx.RegisterModuleType("test", pathForModuleSrcTestModuleFactory)
 
 	bp := `
 		test {
diff --git a/android/prebuilt_etc.go b/android/prebuilt_etc.go
index 6c80370..2701185 100644
--- a/android/prebuilt_etc.go
+++ b/android/prebuilt_etc.go
@@ -25,10 +25,6 @@
 	RegisterModuleType("prebuilt_usr_share_host", PrebuiltUserShareHostFactory)
 	RegisterModuleType("prebuilt_font", PrebuiltFontFactory)
 	RegisterModuleType("prebuilt_firmware", PrebuiltFirmwareFactory)
-
-	PreDepsMutators(func(ctx RegisterMutatorsContext) {
-		ctx.BottomUp("prebuilt_etc", prebuiltEtcMutator).Parallel()
-	})
 }
 
 type prebuiltEtcProperties struct {
@@ -48,8 +44,6 @@
 	// Make this module available when building for recovery.
 	Recovery_available *bool
 
-	InRecovery bool `blueprint:"mutated"`
-
 	// Whether this module is directly installable to one of the partitions. Default: true.
 	Installable *bool
 }
@@ -76,7 +70,7 @@
 }
 
 func (p *PrebuiltEtc) inRecovery() bool {
-	return p.properties.InRecovery || p.ModuleBase.InstallInRecovery()
+	return p.ModuleBase.InRecovery() || p.ModuleBase.InstallInRecovery()
 }
 
 func (p *PrebuiltEtc) onlyInRecovery() bool {
@@ -87,6 +81,25 @@
 	return p.inRecovery()
 }
 
+var _ ImageInterface = (*PrebuiltEtc)(nil)
+
+func (p *PrebuiltEtc) ImageMutatorBegin(ctx BaseModuleContext) {}
+
+func (p *PrebuiltEtc) CoreVariantNeeded(ctx BaseModuleContext) bool {
+	return !p.ModuleBase.InstallInRecovery()
+}
+
+func (p *PrebuiltEtc) RecoveryVariantNeeded(ctx BaseModuleContext) bool {
+	return Bool(p.properties.Recovery_available) || p.ModuleBase.InstallInRecovery()
+}
+
+func (p *PrebuiltEtc) ExtraImageVariations(ctx BaseModuleContext) []string {
+	return nil
+}
+
+func (p *PrebuiltEtc) SetImageVariation(ctx BaseModuleContext, variation string, module Module) {
+}
+
 func (p *PrebuiltEtc) DepsMutator(ctx BottomUpMutatorContext) {
 	if p.properties.Src == nil {
 		ctx.PropertyErrorf("src", "missing prebuilt source file")
@@ -222,49 +235,6 @@
 	return module
 }
 
-const (
-	// coreMode is the variant for modules to be installed to system.
-	coreMode = "core"
-
-	// recoveryMode means a module to be installed to recovery image.
-	recoveryMode = "recovery"
-)
-
-// prebuiltEtcMutator creates the needed variants to install the module to
-// system or recovery.
-func prebuiltEtcMutator(mctx BottomUpMutatorContext) {
-	m, ok := mctx.Module().(*PrebuiltEtc)
-	if !ok || m.Host() {
-		return
-	}
-
-	var coreVariantNeeded bool = true
-	var recoveryVariantNeeded bool = false
-	if Bool(m.properties.Recovery_available) {
-		recoveryVariantNeeded = true
-	}
-
-	if m.ModuleBase.InstallInRecovery() {
-		recoveryVariantNeeded = true
-		coreVariantNeeded = false
-	}
-
-	var variants []string
-	if coreVariantNeeded {
-		variants = append(variants, coreMode)
-	}
-	if recoveryVariantNeeded {
-		variants = append(variants, recoveryMode)
-	}
-	mod := mctx.CreateVariations(variants...)
-	for i, v := range variants {
-		if v == recoveryMode {
-			m := mod[i].(*PrebuiltEtc)
-			m.properties.InRecovery = true
-		}
-	}
-}
-
 // prebuilt_font installs a font in <partition>/fonts directory.
 func PrebuiltFontFactory() Module {
 	module := &PrebuiltEtc{}
diff --git a/android/prebuilt_etc_test.go b/android/prebuilt_etc_test.go
index f675ea3..3855dac 100644
--- a/android/prebuilt_etc_test.go
+++ b/android/prebuilt_etc_test.go
@@ -23,14 +23,14 @@
 func testPrebuiltEtc(t *testing.T, bp string) (*TestContext, Config) {
 	config := TestArchConfig(buildDir, nil)
 	ctx := NewTestArchContext()
-	ctx.RegisterModuleType("prebuilt_etc", ModuleFactoryAdaptor(PrebuiltEtcFactory))
-	ctx.RegisterModuleType("prebuilt_etc_host", ModuleFactoryAdaptor(PrebuiltEtcHostFactory))
-	ctx.RegisterModuleType("prebuilt_usr_share", ModuleFactoryAdaptor(PrebuiltUserShareFactory))
-	ctx.RegisterModuleType("prebuilt_usr_share_host", ModuleFactoryAdaptor(PrebuiltUserShareHostFactory))
-	ctx.RegisterModuleType("prebuilt_font", ModuleFactoryAdaptor(PrebuiltFontFactory))
-	ctx.RegisterModuleType("prebuilt_firmware", ModuleFactoryAdaptor(PrebuiltFirmwareFactory))
+	ctx.RegisterModuleType("prebuilt_etc", PrebuiltEtcFactory)
+	ctx.RegisterModuleType("prebuilt_etc_host", PrebuiltEtcHostFactory)
+	ctx.RegisterModuleType("prebuilt_usr_share", PrebuiltUserShareFactory)
+	ctx.RegisterModuleType("prebuilt_usr_share_host", PrebuiltUserShareHostFactory)
+	ctx.RegisterModuleType("prebuilt_font", PrebuiltFontFactory)
+	ctx.RegisterModuleType("prebuilt_firmware", PrebuiltFirmwareFactory)
 	ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
-		ctx.BottomUp("prebuilt_etc", prebuiltEtcMutator).Parallel()
+		ctx.BottomUp("prebuilt_etc", ImageMutator).Parallel()
 	})
 	ctx.Register()
 	mockFiles := map[string][]byte{
diff --git a/android/prebuilt_test.go b/android/prebuilt_test.go
index 0a18e2c..81fb278 100644
--- a/android/prebuilt_test.go
+++ b/android/prebuilt_test.go
@@ -132,9 +132,9 @@
 			ctx := NewTestContext()
 			ctx.PreArchMutators(RegisterPrebuiltsPreArchMutators)
 			ctx.PostDepsMutators(RegisterPrebuiltsPostDepsMutators)
-			ctx.RegisterModuleType("filegroup", ModuleFactoryAdaptor(FileGroupFactory))
-			ctx.RegisterModuleType("prebuilt", ModuleFactoryAdaptor(newPrebuiltModule))
-			ctx.RegisterModuleType("source", ModuleFactoryAdaptor(newSourceModule))
+			ctx.RegisterModuleType("filegroup", FileGroupFactory)
+			ctx.RegisterModuleType("prebuilt", newPrebuiltModule)
+			ctx.RegisterModuleType("source", newSourceModule)
 			ctx.Register()
 			ctx.MockFileSystem(map[string][]byte{
 				"prebuilt_file": nil,
diff --git a/android/rule_builder_test.go b/android/rule_builder_test.go
index b484811..52c32df 100644
--- a/android/rule_builder_test.go
+++ b/android/rule_builder_test.go
@@ -465,8 +465,8 @@
 		"bar":        nil,
 		"cp":         nil,
 	})
-	ctx.RegisterModuleType("rule_builder_test", ModuleFactoryAdaptor(testRuleBuilderFactory))
-	ctx.RegisterSingletonType("rule_builder_test", SingletonFactoryAdaptor(testRuleBuilderSingletonFactory))
+	ctx.RegisterModuleType("rule_builder_test", testRuleBuilderFactory)
+	ctx.RegisterSingletonType("rule_builder_test", testRuleBuilderSingletonFactory)
 	ctx.Register()
 
 	_, errs := ctx.ParseFileList(".", []string{"Android.bp"})
diff --git a/android/sdk.go b/android/sdk.go
index d66816d..73cb256 100644
--- a/android/sdk.go
+++ b/android/sdk.go
@@ -164,6 +164,9 @@
 	// to the zip
 	CopyToSnapshot(src Path, dest string)
 
+	// Unzip the supplied zip into the snapshot relative directory destDir.
+	UnzipToSnapshot(zipPath Path, destDir string)
+
 	// Get the AndroidBpFile for the snapshot.
 	AndroidBpFile() GeneratedSnapshotFile
 
diff --git a/android/sh_binary_test.go b/android/sh_binary_test.go
index 9df769c..a138754 100644
--- a/android/sh_binary_test.go
+++ b/android/sh_binary_test.go
@@ -9,8 +9,8 @@
 	config := TestArchConfig(buildDir, nil)
 
 	ctx := NewTestArchContext()
-	ctx.RegisterModuleType("sh_test", ModuleFactoryAdaptor(ShTestFactory))
-	ctx.RegisterModuleType("sh_test_host", ModuleFactoryAdaptor(ShTestHostFactory))
+	ctx.RegisterModuleType("sh_test", ShTestFactory)
+	ctx.RegisterModuleType("sh_test_host", ShTestHostFactory)
 	ctx.Register()
 	mockFiles := map[string][]byte{
 		"Android.bp":         []byte(bp),
diff --git a/android/testing.go b/android/testing.go
index 447ffd6..4b55920 100644
--- a/android/testing.go
+++ b/android/testing.go
@@ -71,7 +71,15 @@
 func (ctx *TestContext) Register() {
 	registerMutators(ctx.Context.Context, ctx.preArch, ctx.preDeps, ctx.postDeps)
 
-	ctx.RegisterSingletonType("env", SingletonFactoryAdaptor(EnvSingleton))
+	ctx.RegisterSingletonType("env", EnvSingleton)
+}
+
+func (ctx *TestContext) RegisterModuleType(name string, factory ModuleFactory) {
+	ctx.Context.RegisterModuleType(name, ModuleFactoryAdaptor(factory))
+}
+
+func (ctx *TestContext) RegisterSingletonType(name string, factory SingletonFactory) {
+	ctx.Context.RegisterSingletonType(name, SingletonFactoryAdaptor(factory))
 }
 
 func (ctx *TestContext) ModuleForTests(name, variant string) TestingModule {
diff --git a/android/variable_test.go b/android/variable_test.go
index c1910fe..1826e39 100644
--- a/android/variable_test.go
+++ b/android/variable_test.go
@@ -159,17 +159,17 @@
 func TestProductVariables(t *testing.T) {
 	ctx := NewTestContext()
 	// A module type that has a srcs property but not a cflags property.
-	ctx.RegisterModuleType("module1", ModuleFactoryAdaptor(testProductVariableModuleFactoryFactory(struct {
+	ctx.RegisterModuleType("module1", testProductVariableModuleFactoryFactory(struct {
 		Srcs []string
-	}{})))
+	}{}))
 	// A module type that has a cflags property but not a srcs property.
-	ctx.RegisterModuleType("module2", ModuleFactoryAdaptor(testProductVariableModuleFactoryFactory(struct {
+	ctx.RegisterModuleType("module2", testProductVariableModuleFactoryFactory(struct {
 		Cflags []string
-	}{})))
+	}{}))
 	// A module type that does not have any properties that match product_variables.
-	ctx.RegisterModuleType("module3", ModuleFactoryAdaptor(testProductVariableModuleFactoryFactory(struct {
+	ctx.RegisterModuleType("module3", testProductVariableModuleFactoryFactory(struct {
 		Foo []string
-	}{})))
+	}{}))
 	ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
 		ctx.BottomUp("variable", variableMutator).Parallel()
 	})
diff --git a/android/visibility_test.go b/android/visibility_test.go
index d13fadf..fd9e98c 100644
--- a/android/visibility_test.go
+++ b/android/visibility_test.go
@@ -871,9 +871,9 @@
 	config := TestArchConfig(buildDir, nil)
 
 	ctx := NewTestArchContext()
-	ctx.RegisterModuleType("package", ModuleFactoryAdaptor(PackageFactory))
-	ctx.RegisterModuleType("mock_library", ModuleFactoryAdaptor(newMockLibraryModule))
-	ctx.RegisterModuleType("mock_defaults", ModuleFactoryAdaptor(defaultsFactory))
+	ctx.RegisterModuleType("package", PackageFactory)
+	ctx.RegisterModuleType("mock_library", newMockLibraryModule)
+	ctx.RegisterModuleType("mock_defaults", defaultsFactory)
 	ctx.PreArchMutators(registerPackageRenamer)
 	ctx.PreArchMutators(registerVisibilityRuleChecker)
 	ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
diff --git a/android/vts_config_test.go b/android/vts_config_test.go
index 142b2f5..162944d 100644
--- a/android/vts_config_test.go
+++ b/android/vts_config_test.go
@@ -22,7 +22,7 @@
 	config := TestArchConfig(buildDir, nil)
 
 	ctx := NewTestArchContext()
-	ctx.RegisterModuleType("vts_config", ModuleFactoryAdaptor(VtsConfigFactory))
+	ctx.RegisterModuleType("vts_config", VtsConfigFactory)
 	ctx.Register()
 	mockFiles := map[string][]byte{
 		"Android.bp": []byte(bpFileContents),
diff --git a/apex/apex.go b/apex/apex.go
index d7f6d53..45184b5 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -178,7 +178,7 @@
 				modules[i].(*apexBundle).properties.ApexType = zipApex
 			case flattenedApexType:
 				modules[i].(*apexBundle).properties.ApexType = flattenedApex
-				if !mctx.Config().FlattenApex() {
+				if !mctx.Config().FlattenApex() && ab.Platform() {
 					modules[i].(*apexBundle).MakeAsSystemExt()
 				}
 			}
@@ -716,12 +716,12 @@
 
 func (a *apexBundle) getImageVariation(config android.DeviceConfig) string {
 	if a.vndkApex {
-		return "vendor." + a.vndkVersion(config)
+		return cc.VendorVariationPrefix + a.vndkVersion(config)
 	}
 	if config.VndkVersion() != "" && proptools.Bool(a.properties.Use_vendor) {
-		return "vendor." + config.PlatformVndkVersion()
+		return cc.VendorVariationPrefix + config.PlatformVndkVersion()
 	} else {
-		return "core"
+		return android.CoreVariation
 	}
 }
 
diff --git a/apex/apex_test.go b/apex/apex_test.go
index 4d7777d..a41f914 100644
--- a/apex/apex_test.go
+++ b/apex/apex_test.go
@@ -101,46 +101,46 @@
 	config.TestProductVariables.Platform_vndk_version = proptools.StringPtr("VER")
 
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("apex", android.ModuleFactoryAdaptor(BundleFactory))
-	ctx.RegisterModuleType("apex_test", android.ModuleFactoryAdaptor(testApexBundleFactory))
-	ctx.RegisterModuleType("apex_vndk", android.ModuleFactoryAdaptor(vndkApexBundleFactory))
-	ctx.RegisterModuleType("apex_key", android.ModuleFactoryAdaptor(ApexKeyFactory))
-	ctx.RegisterModuleType("apex_defaults", android.ModuleFactoryAdaptor(defaultsFactory))
-	ctx.RegisterModuleType("prebuilt_apex", android.ModuleFactoryAdaptor(PrebuiltFactory))
-	ctx.RegisterModuleType("override_apex", android.ModuleFactoryAdaptor(overrideApexFactory))
+	ctx.RegisterModuleType("apex", BundleFactory)
+	ctx.RegisterModuleType("apex_test", testApexBundleFactory)
+	ctx.RegisterModuleType("apex_vndk", vndkApexBundleFactory)
+	ctx.RegisterModuleType("apex_key", ApexKeyFactory)
+	ctx.RegisterModuleType("apex_defaults", defaultsFactory)
+	ctx.RegisterModuleType("prebuilt_apex", PrebuiltFactory)
+	ctx.RegisterModuleType("override_apex", overrideApexFactory)
 
-	ctx.RegisterModuleType("cc_library", android.ModuleFactoryAdaptor(cc.LibraryFactory))
-	ctx.RegisterModuleType("cc_library_shared", android.ModuleFactoryAdaptor(cc.LibrarySharedFactory))
-	ctx.RegisterModuleType("cc_library_headers", android.ModuleFactoryAdaptor(cc.LibraryHeaderFactory))
-	ctx.RegisterModuleType("cc_prebuilt_library_shared", android.ModuleFactoryAdaptor(cc.PrebuiltSharedLibraryFactory))
-	ctx.RegisterModuleType("cc_prebuilt_library_static", android.ModuleFactoryAdaptor(cc.PrebuiltStaticLibraryFactory))
-	ctx.RegisterModuleType("cc_binary", android.ModuleFactoryAdaptor(cc.BinaryFactory))
-	ctx.RegisterModuleType("cc_object", android.ModuleFactoryAdaptor(cc.ObjectFactory))
-	ctx.RegisterModuleType("cc_defaults", android.ModuleFactoryAdaptor(func() android.Module {
+	ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
+	ctx.RegisterModuleType("cc_library_shared", cc.LibrarySharedFactory)
+	ctx.RegisterModuleType("cc_library_headers", cc.LibraryHeaderFactory)
+	ctx.RegisterModuleType("cc_prebuilt_library_shared", cc.PrebuiltSharedLibraryFactory)
+	ctx.RegisterModuleType("cc_prebuilt_library_static", cc.PrebuiltStaticLibraryFactory)
+	ctx.RegisterModuleType("cc_binary", cc.BinaryFactory)
+	ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
+	ctx.RegisterModuleType("cc_defaults", func() android.Module {
 		return cc.DefaultsFactory()
-	}))
-	ctx.RegisterModuleType("cc_test", android.ModuleFactoryAdaptor(cc.TestFactory))
-	ctx.RegisterModuleType("llndk_library", android.ModuleFactoryAdaptor(cc.LlndkLibraryFactory))
-	ctx.RegisterModuleType("vndk_prebuilt_shared", android.ModuleFactoryAdaptor(cc.VndkPrebuiltSharedFactory))
-	ctx.RegisterModuleType("vndk_libraries_txt", android.ModuleFactoryAdaptor(cc.VndkLibrariesTxtFactory))
-	ctx.RegisterModuleType("toolchain_library", android.ModuleFactoryAdaptor(cc.ToolchainLibraryFactory))
-	ctx.RegisterModuleType("prebuilt_etc", android.ModuleFactoryAdaptor(android.PrebuiltEtcFactory))
-	ctx.RegisterModuleType("sh_binary", android.ModuleFactoryAdaptor(android.ShBinaryFactory))
-	ctx.RegisterModuleType("android_app_certificate", android.ModuleFactoryAdaptor(java.AndroidAppCertificateFactory))
-	ctx.RegisterModuleType("filegroup", android.ModuleFactoryAdaptor(android.FileGroupFactory))
-	ctx.RegisterModuleType("java_library", android.ModuleFactoryAdaptor(java.LibraryFactory))
-	ctx.RegisterModuleType("java_import", android.ModuleFactoryAdaptor(java.ImportFactory))
-	ctx.RegisterModuleType("java_system_modules", android.ModuleFactoryAdaptor(java.SystemModulesFactory))
-	ctx.RegisterModuleType("android_app", android.ModuleFactoryAdaptor(java.AndroidAppFactory))
-	ctx.RegisterModuleType("android_app_import", android.ModuleFactoryAdaptor(java.AndroidAppImportFactory))
-	ctx.RegisterModuleType("override_android_app", android.ModuleFactoryAdaptor(java.OverrideAndroidAppModuleFactory))
+	})
+	ctx.RegisterModuleType("cc_test", cc.TestFactory)
+	ctx.RegisterModuleType("llndk_library", cc.LlndkLibraryFactory)
+	ctx.RegisterModuleType("vndk_prebuilt_shared", cc.VndkPrebuiltSharedFactory)
+	ctx.RegisterModuleType("vndk_libraries_txt", cc.VndkLibrariesTxtFactory)
+	ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
+	ctx.RegisterModuleType("prebuilt_etc", android.PrebuiltEtcFactory)
+	ctx.RegisterModuleType("sh_binary", android.ShBinaryFactory)
+	ctx.RegisterModuleType("android_app_certificate", java.AndroidAppCertificateFactory)
+	ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
+	ctx.RegisterModuleType("java_library", java.LibraryFactory)
+	ctx.RegisterModuleType("java_import", java.ImportFactory)
+	ctx.RegisterModuleType("java_system_modules", java.SystemModulesFactory)
+	ctx.RegisterModuleType("android_app", java.AndroidAppFactory)
+	ctx.RegisterModuleType("android_app_import", java.AndroidAppImportFactory)
+	ctx.RegisterModuleType("override_android_app", java.OverrideAndroidAppModuleFactory)
 
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
 	ctx.PreArchMutators(func(ctx android.RegisterMutatorsContext) {
 		ctx.BottomUp("prebuilts", android.PrebuiltMutator).Parallel()
 	})
 	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
-		ctx.BottomUp("image", cc.ImageMutator).Parallel()
+		ctx.BottomUp("image", android.ImageMutator).Parallel()
 		ctx.BottomUp("link", cc.LinkageMutator).Parallel()
 		ctx.BottomUp("vndk", cc.VndkMutator).Parallel()
 		ctx.BottomUp("test_per_src", cc.TestPerSrcMutator).Parallel()
@@ -2144,38 +2144,47 @@
 	ensureContains(t, copyCmds, "image.apex/bin/script/myscript.sh")
 }
 
-func TestApexInProductPartition(t *testing.T) {
-	ctx, _ := testApex(t, `
-		apex {
-			name: "myapex",
-			key: "myapex.key",
-			native_shared_libs: ["mylib"],
-			product_specific: true,
-			file_contexts: "myapex_file_contexts",
-		}
+func TestApexInVariousPartition(t *testing.T) {
+	testcases := []struct {
+		propName, parition, flattenedPartition string
+	}{
+		{"", "system", "system_ext"},
+		{"product_specific: true", "product", "product"},
+		{"soc_specific: true", "vendor", "vendor"},
+		{"proprietary: true", "vendor", "vendor"},
+		{"vendor: true", "vendor", "vendor"},
+		{"system_ext_specific: true", "system_ext", "system_ext"},
+	}
+	for _, tc := range testcases {
+		t.Run(tc.propName+":"+tc.parition, func(t *testing.T) {
+			ctx, _ := testApex(t, `
+				apex {
+					name: "myapex",
+					key: "myapex.key",
+					`+tc.propName+`
+				}
 
-		apex_key {
-			name: "myapex.key",
-			public_key: "testkey.avbpubkey",
-			private_key: "testkey.pem",
-			product_specific: true,
-		}
+				apex_key {
+					name: "myapex.key",
+					public_key: "testkey.avbpubkey",
+					private_key: "testkey.pem",
+				}
+			`)
 
-		cc_library {
-			name: "mylib",
-			srcs: ["mylib.cpp"],
-			system_shared_libs: [],
-			stl: "none",
-		}
-	`, withFiles(map[string][]byte{
-		"myapex_file_contexts": nil,
-	}))
+			apex := ctx.ModuleForTests("myapex", "android_common_myapex_image").Module().(*apexBundle)
+			expected := buildDir + "/target/product/test_device/" + tc.parition + "/apex"
+			actual := apex.installDir.String()
+			if actual != expected {
+				t.Errorf("wrong install path. expected %q. actual %q", expected, actual)
+			}
 
-	apex := ctx.ModuleForTests("myapex", "android_common_myapex_image").Module().(*apexBundle)
-	expected := buildDir + "/target/product/test_device/product/apex"
-	actual := apex.installDir.String()
-	if actual != expected {
-		t.Errorf("wrong install path. expected %q. actual %q", expected, actual)
+			flattened := ctx.ModuleForTests("myapex", "android_common_myapex_flattened").Module().(*apexBundle)
+			expected = buildDir + "/target/product/test_device/" + tc.flattenedPartition + "/apex"
+			actual = flattened.installDir.String()
+			if actual != expected {
+				t.Errorf("wrong install path. expected %q. actual %q", expected, actual)
+			}
+		})
 	}
 }
 
diff --git a/bpf/bpf_test.go b/bpf/bpf_test.go
index cbb251f..73b90ba 100644
--- a/bpf/bpf_test.go
+++ b/bpf/bpf_test.go
@@ -55,7 +55,7 @@
 	}
 
 	ctx := cc.CreateTestContext(bp, mockFS, android.Android)
-	ctx.RegisterModuleType("bpf", android.ModuleFactoryAdaptor(bpfFactory))
+	ctx.RegisterModuleType("bpf", bpfFactory)
 	ctx.Register()
 
 	return ctx
diff --git a/cc/cc.go b/cc/cc.go
index aa656da..f306a00 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -37,7 +37,7 @@
 
 	android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
 		ctx.BottomUp("vndk", VndkMutator).Parallel()
-		ctx.BottomUp("image", ImageMutator).Parallel()
+		ctx.BottomUp("image", android.ImageMutator).Parallel()
 		ctx.BottomUp("link", LinkageMutator).Parallel()
 		ctx.BottomUp("ndk_api", ndkApiMutator).Parallel()
 		ctx.BottomUp("test_per_src", TestPerSrcMutator).Parallel()
@@ -218,7 +218,10 @@
 	// Make this module available when building for recovery
 	Recovery_available *bool
 
-	InRecovery bool `blueprint:"mutated"`
+	// Set by ImageMutator
+	CoreVariantNeeded     bool     `blueprint:"mutated"`
+	RecoveryVariantNeeded bool     `blueprint:"mutated"`
+	VendorVariants        []string `blueprint:"mutated"`
 
 	// Allows this module to use non-APEX version of libraries. Useful
 	// for building binaries that are started before APEXes are activated.
@@ -826,7 +829,7 @@
 }
 
 func (c *Module) InRecovery() bool {
-	return c.Properties.InRecovery || c.ModuleBase.InstallInRecovery()
+	return c.ModuleBase.InRecovery() || c.ModuleBase.InstallInRecovery()
 }
 
 func (c *Module) OnlyInRecovery() bool {
@@ -1588,8 +1591,7 @@
 			depTag = headerExportDepTag
 		}
 		if buildStubs {
-			actx.AddFarVariationDependencies(append(ctx.Target().Variations(),
-				blueprint.Variation{Mutator: "image", Variation: c.imageVariation()}),
+			actx.AddFarVariationDependencies(append(ctx.Target().Variations(), c.ImageVariation()),
 				depTag, lib)
 		} else {
 			actx.AddVariationDependencies(nil, depTag, lib)
@@ -1727,14 +1729,8 @@
 
 	if vndkdep := c.vndkdep; vndkdep != nil {
 		if vndkdep.isVndkExt() {
-			var baseModuleMode string
-			if actx.DeviceConfig().VndkVersion() == "" {
-				baseModuleMode = coreMode
-			} else {
-				baseModuleMode = c.imageVariation()
-			}
 			actx.AddVariationDependencies([]blueprint.Variation{
-				{Mutator: "image", Variation: baseModuleMode},
+				c.ImageVariation(),
 				{Mutator: "link", Variation: "shared"},
 			}, vndkExtDepTag, vndkdep.getVndkExtendsModuleName())
 		}
@@ -2389,15 +2385,6 @@
 	return c.installer != nil && !c.Properties.PreventInstall && c.IsForPlatform() && c.outputFile.Valid()
 }
 
-func (c *Module) imageVariation() string {
-	if c.UseVndk() {
-		return vendorMode + "." + c.Properties.VndkVersion
-	} else if c.InRecovery() {
-		return recoveryMode
-	}
-	return coreMode
-}
-
 func (c *Module) IDEInfo(dpInfo *android.IdeInfo) {
 	outputFiles, err := c.OutputFiles("")
 	if err != nil {
@@ -2481,15 +2468,9 @@
 }
 
 const (
-	// coreMode is the variant used for framework-private libraries, or
-	// SDK libraries. (which framework-private libraries can use)
-	coreMode = "core"
-
-	// vendorMode is the variant prefix used for /vendor code that compiles
+	// VendorVariationPrefix is the variant prefix used for /vendor code that compiles
 	// against the VNDK.
-	vendorMode = "vendor"
-
-	recoveryMode = "recovery"
+	VendorVariationPrefix = "vendor."
 )
 
 func squashVendorSrcs(m *Module) {
@@ -2512,74 +2493,9 @@
 	}
 }
 
-func ImageMutator(mctx android.BottomUpMutatorContext) {
-	if mctx.Os() != android.Android {
-		return
-	}
+var _ android.ImageInterface = (*Module)(nil)
 
-	if g, ok := mctx.Module().(*genrule.Module); ok {
-		if props, ok := g.Extra.(*GenruleExtraProperties); ok {
-			var coreVariantNeeded bool = false
-			var vendorVariantNeeded bool = false
-			var recoveryVariantNeeded bool = false
-			if mctx.DeviceConfig().VndkVersion() == "" {
-				coreVariantNeeded = true
-			} else if Bool(props.Vendor_available) {
-				coreVariantNeeded = true
-				vendorVariantNeeded = true
-			} else if mctx.SocSpecific() || mctx.DeviceSpecific() {
-				vendorVariantNeeded = true
-			} else {
-				coreVariantNeeded = true
-			}
-			if Bool(props.Recovery_available) {
-				recoveryVariantNeeded = true
-			}
-
-			if recoveryVariantNeeded {
-				primaryArch := mctx.Config().DevicePrimaryArchType()
-				moduleArch := g.Target().Arch.ArchType
-				if moduleArch != primaryArch {
-					recoveryVariantNeeded = false
-				}
-			}
-
-			var variants []string
-			if coreVariantNeeded {
-				variants = append(variants, coreMode)
-			}
-			if vendorVariantNeeded {
-				variants = append(variants, vendorMode+"."+mctx.DeviceConfig().PlatformVndkVersion())
-				if vndkVersion := mctx.DeviceConfig().VndkVersion(); vndkVersion != "current" {
-					variants = append(variants, vendorMode+"."+vndkVersion)
-				}
-			}
-			if recoveryVariantNeeded {
-				variants = append(variants, recoveryMode)
-			}
-			mod := mctx.CreateVariations(variants...)
-			for i, v := range variants {
-				if v == recoveryMode {
-					m := mod[i].(*genrule.Module)
-					m.Extra.(*GenruleExtraProperties).InRecovery = true
-				}
-			}
-		}
-	}
-
-	//TODO When LinkableInterface supports VNDK, this should be mctx.Module().(LinkableInterface)
-	m, ok := mctx.Module().(*Module)
-	if !ok {
-		if linkable, ok := mctx.Module().(LinkableInterface); ok {
-			variations := []string{coreMode}
-			if linkable.InRecovery() {
-				variations = append(variations, recoveryMode)
-			}
-			mctx.CreateVariations(variations...)
-		}
-		return
-	}
-
+func (m *Module) ImageMutatorBegin(mctx android.BaseModuleContext) {
 	// Sanity check
 	vendorSpecific := mctx.SocSpecific() || mctx.DeviceSpecific()
 	productSpecific := mctx.ProductSpecific()
@@ -2587,7 +2503,6 @@
 	if m.VendorProperties.Vendor_available != nil && vendorSpecific {
 		mctx.PropertyErrorf("vendor_available",
 			"doesn't make sense at the same time as `vendor: true`, `proprietary: true`, or `device_specific:true`")
-		return
 	}
 
 	if vndkdep := m.vndkdep; vndkdep != nil {
@@ -2595,38 +2510,32 @@
 			if productSpecific {
 				mctx.PropertyErrorf("product_specific",
 					"product_specific must not be true when `vndk: {enabled: true}`")
-				return
 			}
 			if vendorSpecific {
 				if !vndkdep.isVndkExt() {
 					mctx.PropertyErrorf("vndk",
 						"must set `extends: \"...\"` to vndk extension")
-					return
 				}
 			} else {
 				if vndkdep.isVndkExt() {
 					mctx.PropertyErrorf("vndk",
 						"must set `vendor: true` to set `extends: %q`",
 						m.getVndkExtendsModuleName())
-					return
 				}
 				if m.VendorProperties.Vendor_available == nil {
 					mctx.PropertyErrorf("vndk",
 						"vendor_available must be set to either true or false when `vndk: {enabled: true}`")
-					return
 				}
 			}
 		} else {
 			if vndkdep.isVndkSp() {
 				mctx.PropertyErrorf("vndk",
 					"must set `enabled: true` to set `support_system_process: true`")
-				return
 			}
 			if vndkdep.isVndkExt() {
 				mctx.PropertyErrorf("vndk",
 					"must set `enabled: true` to set `extends: %q`",
 					m.getVndkExtendsModuleName())
-				return
 			}
 		}
 	}
@@ -2705,28 +2614,34 @@
 		}
 	}
 
-	var variants []string
-	if coreVariantNeeded {
-		variants = append(variants, coreMode)
-	}
 	for _, variant := range android.FirstUniqueStrings(vendorVariants) {
-		variants = append(variants, vendorMode+"."+variant)
+		m.Properties.VendorVariants = append(m.Properties.VendorVariants, VendorVariationPrefix+variant)
 	}
-	if recoveryVariantNeeded {
-		variants = append(variants, recoveryMode)
-	}
-	mod := mctx.CreateVariations(variants...)
-	for i, v := range variants {
-		if strings.HasPrefix(v, vendorMode+".") {
-			m := mod[i].(*Module)
-			m.Properties.VndkVersion = strings.TrimPrefix(v, vendorMode+".")
-			squashVendorSrcs(m)
-		} else if v == recoveryMode {
-			m := mod[i].(*Module)
-			m.Properties.InRecovery = true
-			m.MakeAsPlatform()
-			squashRecoverySrcs(m)
-		}
+
+	m.Properties.RecoveryVariantNeeded = recoveryVariantNeeded
+	m.Properties.CoreVariantNeeded = coreVariantNeeded
+}
+
+func (c *Module) CoreVariantNeeded(ctx android.BaseModuleContext) bool {
+	return c.Properties.CoreVariantNeeded
+}
+
+func (c *Module) RecoveryVariantNeeded(ctx android.BaseModuleContext) bool {
+	return c.Properties.RecoveryVariantNeeded
+}
+
+func (c *Module) ExtraImageVariations(ctx android.BaseModuleContext) []string {
+	return c.Properties.VendorVariants
+}
+
+func (c *Module) SetImageVariation(ctx android.BaseModuleContext, variant string, module android.Module) {
+	m := module.(*Module)
+	if variant == android.RecoveryVariation {
+		m.MakeAsPlatform()
+		squashRecoverySrcs(m)
+	} else if strings.HasPrefix(variant, VendorVariationPrefix) {
+		m.Properties.VndkVersion = strings.TrimPrefix(variant, VendorVariationPrefix)
+		squashVendorSrcs(m)
 	}
 }
 
diff --git a/cc/config/vndk.go b/cc/config/vndk.go
index 3e8abac..c3cda49 100644
--- a/cc/config/vndk.go
+++ b/cc/config/vndk.go
@@ -165,4 +165,5 @@
 	"libxml2",
 	"libyuv",
 	"libziparchive",
+	"vintf-vibrator-ndk_platform",
 }
diff --git a/cc/genrule.go b/cc/genrule.go
index e594f4b..e74dd4d 100644
--- a/cc/genrule.go
+++ b/cc/genrule.go
@@ -26,9 +26,6 @@
 type GenruleExtraProperties struct {
 	Vendor_available   *bool
 	Recovery_available *bool
-
-	// This genrule is for recovery variant
-	InRecovery bool `blueprint:"mutated"`
 }
 
 // cc_genrule is a genrule that can depend on other cc_* objects.
@@ -37,7 +34,9 @@
 func genRuleFactory() android.Module {
 	module := genrule.NewGenRule()
 
-	module.Extra = &GenruleExtraProperties{}
+	extra := &GenruleExtraProperties{}
+	module.Extra = extra
+	module.ImageInterface = extra
 	module.AddProperties(module.Extra)
 
 	android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibBoth)
@@ -46,3 +45,44 @@
 
 	return module
 }
+
+var _ android.ImageInterface = (*GenruleExtraProperties)(nil)
+
+func (g *GenruleExtraProperties) ImageMutatorBegin(ctx android.BaseModuleContext) {}
+
+func (g *GenruleExtraProperties) CoreVariantNeeded(ctx android.BaseModuleContext) bool {
+	if ctx.DeviceConfig().VndkVersion() == "" {
+		return true
+	}
+
+	return Bool(g.Vendor_available) || !(ctx.SocSpecific() || ctx.DeviceSpecific())
+}
+
+func (g *GenruleExtraProperties) RecoveryVariantNeeded(ctx android.BaseModuleContext) bool {
+	if Bool(g.Recovery_available) {
+		primaryArch := ctx.Config().DevicePrimaryArchType()
+		moduleArch := ctx.Target().Arch.ArchType
+		return moduleArch == primaryArch
+	}
+	return false
+}
+
+func (g *GenruleExtraProperties) ExtraImageVariations(ctx android.BaseModuleContext) []string {
+	if ctx.DeviceConfig().VndkVersion() == "" {
+		return nil
+	}
+
+	if Bool(g.Vendor_available) || ctx.SocSpecific() || ctx.DeviceSpecific() {
+		var variants []string
+		variants = append(variants, VendorVariationPrefix+ctx.DeviceConfig().PlatformVndkVersion())
+		if vndkVersion := ctx.DeviceConfig().VndkVersion(); vndkVersion != "current" {
+			variants = append(variants, VendorVariationPrefix+vndkVersion)
+		}
+		return variants
+	}
+
+	return nil
+}
+
+func (g *GenruleExtraProperties) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
+}
diff --git a/cc/genrule_test.go b/cc/genrule_test.go
index 92024ac..785e3e1 100644
--- a/cc/genrule_test.go
+++ b/cc/genrule_test.go
@@ -25,7 +25,7 @@
 	fs map[string][]byte) *android.TestContext {
 
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("cc_genrule", android.ModuleFactoryAdaptor(genRuleFactory))
+	ctx.RegisterModuleType("cc_genrule", genRuleFactory)
 	ctx.Register()
 
 	mockFS := map[string][]byte{
diff --git a/cc/library.go b/cc/library.go
index b8c4b51..98cae3d 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -1359,9 +1359,11 @@
 		return
 	}
 	if genrule, ok := mctx.Module().(*genrule.Module); ok {
-		if props, ok := genrule.Extra.(*GenruleExtraProperties); ok && !props.InRecovery {
-			mctx.CreateVariations("")
-			return
+		if _, ok := genrule.Extra.(*GenruleExtraProperties); ok {
+			if !genrule.InRecovery() {
+				mctx.CreateVariations("")
+				return
+			}
 		}
 	}
 }
diff --git a/cc/prebuilt_test.go b/cc/prebuilt_test.go
index edcd26e..72f9f4a 100644
--- a/cc/prebuilt_test.go
+++ b/cc/prebuilt_test.go
@@ -72,9 +72,9 @@
 
 	ctx := CreateTestContext(bp, fs, android.Android)
 
-	ctx.RegisterModuleType("cc_prebuilt_library_shared", android.ModuleFactoryAdaptor(PrebuiltSharedLibraryFactory))
-	ctx.RegisterModuleType("cc_prebuilt_library_static", android.ModuleFactoryAdaptor(PrebuiltStaticLibraryFactory))
-	ctx.RegisterModuleType("cc_prebuilt_binary", android.ModuleFactoryAdaptor(prebuiltBinaryFactory))
+	ctx.RegisterModuleType("cc_prebuilt_library_shared", PrebuiltSharedLibraryFactory)
+	ctx.RegisterModuleType("cc_prebuilt_library_static", PrebuiltStaticLibraryFactory)
+	ctx.RegisterModuleType("cc_prebuilt_binary", prebuiltBinaryFactory)
 
 	ctx.PreArchMutators(android.RegisterPrebuiltsPreArchMutators)
 	ctx.PostDepsMutators(android.RegisterPrebuiltsPostDepsMutators)
diff --git a/cc/sanitize.go b/cc/sanitize.go
index 2bf051e..55bdd1c 100644
--- a/cc/sanitize.go
+++ b/cc/sanitize.go
@@ -886,13 +886,13 @@
 				// static executable gets static runtime libs
 				mctx.AddFarVariationDependencies(append(mctx.Target().Variations(), []blueprint.Variation{
 					{Mutator: "link", Variation: "static"},
-					{Mutator: "image", Variation: c.imageVariation()},
+					c.ImageVariation(),
 				}...), StaticDepTag, append([]string{runtimeLibrary}, extraStaticDeps...)...)
 			} else if !c.static() && !c.header() {
 				// dynamic executable and shared libs get shared runtime libs
 				mctx.AddFarVariationDependencies(append(mctx.Target().Variations(), []blueprint.Variation{
 					{Mutator: "link", Variation: "shared"},
-					{Mutator: "image", Variation: c.imageVariation()},
+					c.ImageVariation(),
 				}...), earlySharedDepTag, runtimeLibrary)
 			}
 			// static lib does not have dependency to the runtime library. The
diff --git a/cc/test_data_test.go b/cc/test_data_test.go
index 21ea765..962ff26 100644
--- a/cc/test_data_test.go
+++ b/cc/test_data_test.go
@@ -126,10 +126,8 @@
 				"dir/baz":        nil,
 				"dir/bar/baz":    nil,
 			})
-			ctx.RegisterModuleType("filegroup",
-				android.ModuleFactoryAdaptor(android.FileGroupFactory))
-			ctx.RegisterModuleType("test",
-				android.ModuleFactoryAdaptor(newTest))
+			ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
+			ctx.RegisterModuleType("test", newTest)
 			ctx.Register()
 
 			_, errs := ctx.ParseBlueprintsFiles("Blueprints")
diff --git a/cc/testing.go b/cc/testing.go
index 9ad72d9..3b10f87 100644
--- a/cc/testing.go
+++ b/cc/testing.go
@@ -253,25 +253,25 @@
 	os android.OsType) *android.TestContext {
 
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("cc_defaults", android.ModuleFactoryAdaptor(defaultsFactory))
-	ctx.RegisterModuleType("cc_binary", android.ModuleFactoryAdaptor(BinaryFactory))
-	ctx.RegisterModuleType("cc_binary_host", android.ModuleFactoryAdaptor(binaryHostFactory))
-	ctx.RegisterModuleType("cc_fuzz", android.ModuleFactoryAdaptor(FuzzFactory))
-	ctx.RegisterModuleType("cc_library", android.ModuleFactoryAdaptor(LibraryFactory))
-	ctx.RegisterModuleType("cc_library_shared", android.ModuleFactoryAdaptor(LibrarySharedFactory))
-	ctx.RegisterModuleType("cc_library_static", android.ModuleFactoryAdaptor(LibraryStaticFactory))
-	ctx.RegisterModuleType("cc_library_headers", android.ModuleFactoryAdaptor(LibraryHeaderFactory))
-	ctx.RegisterModuleType("cc_test", android.ModuleFactoryAdaptor(TestFactory))
-	ctx.RegisterModuleType("toolchain_library", android.ModuleFactoryAdaptor(ToolchainLibraryFactory))
-	ctx.RegisterModuleType("llndk_library", android.ModuleFactoryAdaptor(LlndkLibraryFactory))
-	ctx.RegisterModuleType("llndk_headers", android.ModuleFactoryAdaptor(llndkHeadersFactory))
-	ctx.RegisterModuleType("vendor_public_library", android.ModuleFactoryAdaptor(vendorPublicLibraryFactory))
-	ctx.RegisterModuleType("cc_object", android.ModuleFactoryAdaptor(ObjectFactory))
-	ctx.RegisterModuleType("filegroup", android.ModuleFactoryAdaptor(android.FileGroupFactory))
-	ctx.RegisterModuleType("vndk_prebuilt_shared", android.ModuleFactoryAdaptor(VndkPrebuiltSharedFactory))
-	ctx.RegisterModuleType("vndk_libraries_txt", android.ModuleFactoryAdaptor(VndkLibrariesTxtFactory))
+	ctx.RegisterModuleType("cc_defaults", defaultsFactory)
+	ctx.RegisterModuleType("cc_binary", BinaryFactory)
+	ctx.RegisterModuleType("cc_binary_host", binaryHostFactory)
+	ctx.RegisterModuleType("cc_fuzz", FuzzFactory)
+	ctx.RegisterModuleType("cc_library", LibraryFactory)
+	ctx.RegisterModuleType("cc_library_shared", LibrarySharedFactory)
+	ctx.RegisterModuleType("cc_library_static", LibraryStaticFactory)
+	ctx.RegisterModuleType("cc_library_headers", LibraryHeaderFactory)
+	ctx.RegisterModuleType("cc_test", TestFactory)
+	ctx.RegisterModuleType("toolchain_library", ToolchainLibraryFactory)
+	ctx.RegisterModuleType("llndk_library", LlndkLibraryFactory)
+	ctx.RegisterModuleType("llndk_headers", llndkHeadersFactory)
+	ctx.RegisterModuleType("vendor_public_library", vendorPublicLibraryFactory)
+	ctx.RegisterModuleType("cc_object", ObjectFactory)
+	ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
+	ctx.RegisterModuleType("vndk_prebuilt_shared", VndkPrebuiltSharedFactory)
+	ctx.RegisterModuleType("vndk_libraries_txt", VndkLibrariesTxtFactory)
 	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
-		ctx.BottomUp("image", ImageMutator).Parallel()
+		ctx.BottomUp("image", android.ImageMutator).Parallel()
 		ctx.BottomUp("link", LinkageMutator).Parallel()
 		ctx.BottomUp("vndk", VndkMutator).Parallel()
 		ctx.BottomUp("version", VersionMutator).Parallel()
@@ -281,7 +281,7 @@
 		ctx.TopDown("double_loadable", checkDoubleLoadableLibraries).Parallel()
 	})
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
-	ctx.RegisterSingletonType("vndk-snapshot", android.SingletonFactoryAdaptor(VndkSnapshotSingleton))
+	ctx.RegisterSingletonType("vndk-snapshot", VndkSnapshotSingleton)
 
 	// add some modules that are required by the compiler and/or linker
 	bp = bp + GatherRequiredDepsForTest(os)
diff --git a/dexpreopt/dexpreopt.go b/dexpreopt/dexpreopt.go
index 46e0f0a..18a38fb 100644
--- a/dexpreopt/dexpreopt.go
+++ b/dexpreopt/dexpreopt.go
@@ -102,6 +102,13 @@
 		return true
 	}
 
+	// Don't preopt system server jars that are updatable.
+	for _, p := range global.UpdatableSystemServerJars {
+		if _, jar := SplitApexJarPair(p); jar == module.Name {
+			return true
+		}
+	}
+
 	// If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
 	// Also preopt system server jars since selinux prevents system server from loading anything from
 	// /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
@@ -537,6 +544,16 @@
 	}
 }
 
+// Expected format for apexJarValue = <apex name>:<jar name>
+func SplitApexJarPair(apexJarValue string) (string, string) {
+	var apexJarPair []string = strings.SplitN(apexJarValue, ":", 2)
+	if apexJarPair == nil || len(apexJarPair) != 2 {
+		panic(fmt.Errorf("malformed apexJarValue: %q, expected format: <apex>:<jar>",
+			apexJarValue))
+	}
+	return apexJarPair[0], apexJarPair[1]
+}
+
 func contains(l []string, s string) bool {
 	for _, e := range l {
 		if e == s {
diff --git a/genrule/genrule.go b/genrule/genrule.go
index a7c5d65..57ca9bc 100644
--- a/genrule/genrule.go
+++ b/genrule/genrule.go
@@ -118,6 +118,7 @@
 	// For other packages to make their own genrules with extra
 	// properties
 	Extra interface{}
+	android.ImageInterface
 
 	properties generatorProperties
 
@@ -532,9 +533,20 @@
 	module.AddProperties(props...)
 	module.AddProperties(&module.properties)
 
+	module.ImageInterface = noopImageInterface{}
+
 	return module
 }
 
+type noopImageInterface struct{}
+
+func (x noopImageInterface) ImageMutatorBegin(android.BaseModuleContext)                 {}
+func (x noopImageInterface) CoreVariantNeeded(android.BaseModuleContext) bool            { return false }
+func (x noopImageInterface) RecoveryVariantNeeded(android.BaseModuleContext) bool        { return false }
+func (x noopImageInterface) ExtraImageVariations(ctx android.BaseModuleContext) []string { return nil }
+func (x noopImageInterface) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
+}
+
 // replace "out" with "__SBOX_OUT_DIR__/<the value of ${out}>"
 func pathToSandboxOut(path android.Path, genDir android.Path) string {
 	relOut, err := filepath.Rel(genDir.String(), path.String())
diff --git a/genrule/genrule_test.go b/genrule/genrule_test.go
index 5ac0e8c..07de999 100644
--- a/genrule/genrule_test.go
+++ b/genrule/genrule_test.go
@@ -55,11 +55,11 @@
 	fs map[string][]byte) *android.TestContext {
 
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("filegroup", android.ModuleFactoryAdaptor(android.FileGroupFactory))
-	ctx.RegisterModuleType("genrule", android.ModuleFactoryAdaptor(GenRuleFactory))
-	ctx.RegisterModuleType("gensrcs", android.ModuleFactoryAdaptor(GenSrcsFactory))
-	ctx.RegisterModuleType("genrule_defaults", android.ModuleFactoryAdaptor(defaultsFactory))
-	ctx.RegisterModuleType("tool", android.ModuleFactoryAdaptor(toolFactory))
+	ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
+	ctx.RegisterModuleType("genrule", GenRuleFactory)
+	ctx.RegisterModuleType("gensrcs", GenSrcsFactory)
+	ctx.RegisterModuleType("genrule_defaults", defaultsFactory)
+	ctx.RegisterModuleType("tool", toolFactory)
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
 	ctx.Register()
 
diff --git a/java/aar.go b/java/aar.go
index d8db192..e0bea5d 100644
--- a/java/aar.go
+++ b/java/aar.go
@@ -694,6 +694,10 @@
 	return nil
 }
 
+func (d *AARImport) ExportedPlugins() (android.Paths, []string) {
+	return nil, nil
+}
+
 func (a *AARImport) SrcJarArgs() ([]string, android.Paths) {
 	return nil, nil
 }
diff --git a/java/app.go b/java/app.go
old mode 100644
new mode 100755
index c635703..c772e47
--- a/java/app.go
+++ b/java/app.go
@@ -974,7 +974,13 @@
 	jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
 	a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
 
-	installDir := android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
+	var installDir android.InstallPath
+	if Bool(a.properties.Privileged) {
+		installDir = android.PathForModuleInstall(ctx, "priv-app", a.BaseModuleName())
+	} else {
+		installDir = android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
+	}
+
 	a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
 	a.dexpreopter.isInstallable = true
 	a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
diff --git a/java/device_host_converter.go b/java/device_host_converter.go
index 14db521..1524418 100644
--- a/java/device_host_converter.go
+++ b/java/device_host_converter.go
@@ -162,6 +162,10 @@
 	return nil
 }
 
+func (d *DeviceHostConverter) ExportedPlugins() (android.Paths, []string) {
+	return nil, nil
+}
+
 func (d *DeviceHostConverter) SrcJarArgs() ([]string, android.Paths) {
 	return d.srcJarArgs, d.srcJarDeps
 }
diff --git a/java/dexpreopt_bootjars_test.go b/java/dexpreopt_bootjars_test.go
index a684ab2..29a5abe 100644
--- a/java/dexpreopt_bootjars_test.go
+++ b/java/dexpreopt_bootjars_test.go
@@ -53,7 +53,7 @@
 
 	ctx := testContext(bp, nil)
 
-	ctx.RegisterSingletonType("dex_bootjars", android.SingletonFactoryAdaptor(dexpreoptBootJarsFactory))
+	ctx.RegisterSingletonType("dex_bootjars", dexpreoptBootJarsFactory)
 
 	run(t, ctx, config)
 
diff --git a/java/dexpreopt_config.go b/java/dexpreopt_config.go
index 15f11e1..4747c64 100644
--- a/java/dexpreopt_config.go
+++ b/java/dexpreopt_config.go
@@ -15,7 +15,6 @@
 package java
 
 import (
-	"fmt"
 	"path/filepath"
 	"strings"
 
@@ -66,16 +65,6 @@
 var dexpreoptGlobalConfigKey = android.NewOnceKey("DexpreoptGlobalConfig")
 var dexpreoptTestGlobalConfigKey = android.NewOnceKey("TestDexpreoptGlobalConfig")
 
-// Expected format for apexJarValue = <apex name>:<jar name>
-func splitApexJarPair(apexJarValue string) (string, string)  {
-	var apexJarPair []string = strings.SplitN(apexJarValue, ":", 2)
-	if apexJarPair == nil || len(apexJarPair) != 2 {
-		panic(fmt.Errorf("malformed apexJarValue: %q, expected format: <apex>:<jar>",
-			apexJarValue))
-	}
-	return apexJarPair[0], apexJarPair[1]
-}
-
 // systemServerClasspath returns the on-device locations of the modules in the system server classpath.  It is computed
 // once the first time it is called for any ctx.Config(), and returns the same slice for all future calls with the same
 // ctx.Config().
@@ -89,9 +78,9 @@
 				filepath.Join("/system/framework", m+".jar"))
 		}
 		for _, m := range global.UpdatableSystemServerJars {
-			apex, jar := splitApexJarPair(m)
+			apex, jar := dexpreopt.SplitApexJarPair(m)
 			systemServerClasspathLocations = append(systemServerClasspathLocations,
-				filepath.Join("/apex", apex, "javalib", jar + ".jar"))
+				filepath.Join("/apex", apex, "javalib", jar+".jar"))
 		}
 		return systemServerClasspathLocations
 	})
diff --git a/java/droiddoc.go b/java/droiddoc.go
index 54f93fe..83a1ad5 100644
--- a/java/droiddoc.go
+++ b/java/droiddoc.go
@@ -37,6 +37,8 @@
 
 	android.RegisterModuleType("droidstubs", DroidstubsFactory)
 	android.RegisterModuleType("droidstubs_host", DroidstubsHostFactory)
+
+	android.RegisterModuleType("prebuilt_stubs_sources", PrebuiltStubsSourcesFactory)
 }
 
 var (
@@ -1163,6 +1165,7 @@
 //
 type Droidstubs struct {
 	Javadoc
+	android.SdkBase
 
 	properties              DroidstubsProperties
 	apiFile                 android.WritablePath
@@ -1208,6 +1211,7 @@
 		&module.Javadoc.properties)
 
 	InitDroiddocModule(module, android.HostAndDeviceSupported)
+	android.InitSdkAwareModule(module)
 	return module
 }
 
@@ -1913,3 +1917,88 @@
 func zipSyncCleanupCmd(rule *android.RuleBuilder, srcJarDir android.ModuleOutPath) {
 	rule.Command().Text("rm -rf").Text(srcJarDir.String())
 }
+
+var _ android.PrebuiltInterface = (*PrebuiltStubsSources)(nil)
+
+type PrebuiltStubsSourcesProperties struct {
+	Srcs []string `android:"path"`
+}
+
+type PrebuiltStubsSources struct {
+	android.ModuleBase
+	android.DefaultableModuleBase
+	prebuilt android.Prebuilt
+	android.SdkBase
+
+	properties PrebuiltStubsSourcesProperties
+
+	srcs        android.Paths
+	stubsSrcJar android.ModuleOutPath
+}
+
+func (p *PrebuiltStubsSources) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	p.srcs = android.PathsForModuleSrc(ctx, p.properties.Srcs)
+}
+
+func (p *PrebuiltStubsSources) Prebuilt() *android.Prebuilt {
+	return &p.prebuilt
+}
+
+func (p *PrebuiltStubsSources) Name() string {
+	return p.prebuilt.Name(p.ModuleBase.Name())
+}
+
+func (p *PrebuiltStubsSources) Srcs() android.Paths {
+	return append(android.Paths{}, p.srcs...)
+}
+
+// prebuilt_stubs_sources imports a set of java source files as if they were
+// generated by droidstubs.
+//
+// By default, a prebuilt_stubs_sources has a single variant that expects a
+// set of `.java` files generated by droidstubs.
+//
+// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
+// for host modules.
+//
+// Intended only for use by sdk snapshots.
+func PrebuiltStubsSourcesFactory() android.Module {
+	module := &PrebuiltStubsSources{}
+
+	module.AddProperties(&module.properties)
+
+	android.InitPrebuiltModule(module, &module.properties.Srcs)
+	android.InitSdkAwareModule(module)
+	InitDroiddocModule(module, android.HostAndDeviceSupported)
+	return module
+}
+
+func (d *Droidstubs) BuildSnapshot(sdkModuleContext android.ModuleContext, builder android.SnapshotBuilder) {
+	stubsSrcJar := d.stubsSrcJar
+
+	snapshotRelativeDir := filepath.Join("java", d.Name()+"_stubs_sources")
+	builder.UnzipToSnapshot(stubsSrcJar, snapshotRelativeDir)
+
+	name := d.Name()
+	bp := builder.AndroidBpFile()
+	bp.Printfln("prebuilt_stubs_sources {")
+	bp.Indent()
+	bp.Printfln("name: %q,", builder.VersionedSdkMemberName(name))
+	bp.Printfln("sdk_member_name: %q,", name)
+	bp.Printfln("srcs: [%q],", snapshotRelativeDir)
+	bp.Dedent()
+	bp.Printfln("}")
+	bp.Printfln("")
+
+	// This module is for the case when the source tree for the unversioned module
+	// doesn't exist (i.e. building in an unbundled tree). "prefer:" is set to false
+	// so that this module does not eclipse the unversioned module if it exists.
+	bp.Printfln("prebuilt_stubs_sources {")
+	bp.Indent()
+	bp.Printfln("name: %q,", name)
+	bp.Printfln("srcs: [%q],", snapshotRelativeDir)
+	bp.Printfln("prefer: false,")
+	bp.Dedent()
+	bp.Printfln("}")
+	bp.Printfln("")
+}
diff --git a/java/java.go b/java/java.go
index d4f65ba..1c52575 100644
--- a/java/java.go
+++ b/java/java.go
@@ -145,6 +145,9 @@
 	// List of modules to use as annotation processors
 	Plugins []string
 
+	// List of modules to export to libraries that directly depend on this library as annotation processors
+	Exported_plugins []string
+
 	// The number of Java source entries each Javac instance can process
 	Javac_shard_size *int64
 
@@ -360,10 +363,16 @@
 	// manifest file to use instead of properties.Manifest
 	overrideManifest android.OptionalPath
 
-	// list of SDK lib names that this java moudule is exporting
+	// list of SDK lib names that this java module is exporting
 	exportedSdkLibs []string
 
-	// list of source files, collected from srcFiles with uniqie java and all kt files,
+	// list of plugins that this java module is exporting
+	exportedPluginJars android.Paths
+
+	// list of plugins that this java module is exporting
+	exportedPluginClasses []string
+
+	// list of source files, collected from srcFiles with unique java and all kt files,
 	// will be used by android.IDEInfo struct
 	expandIDEInfoCompiledSrcs []string
 
@@ -410,6 +419,7 @@
 	DexJar() android.Path
 	AidlIncludeDirs() android.Paths
 	ExportedSdkLibs() []string
+	ExportedPlugins() (android.Paths, []string)
 	SrcJarArgs() ([]string, android.Paths)
 	BaseModuleName() string
 }
@@ -452,6 +462,7 @@
 	libTag                = dependencyTag{name: "javalib"}
 	java9LibTag           = dependencyTag{name: "java9lib"}
 	pluginTag             = dependencyTag{name: "plugin"}
+	exportedPluginTag     = dependencyTag{name: "exported-plugin"}
 	bootClasspathTag      = dependencyTag{name: "bootclasspath"}
 	systemModulesTag      = dependencyTag{name: "system modules"}
 	frameworkResTag       = dependencyTag{name: "framework-res"}
@@ -561,6 +572,7 @@
 	ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
 
 	ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
+	ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
 
 	android.ProtoDeps(ctx, &j.protoProperties)
 	if j.hasSrcExt(".proto") {
@@ -800,6 +812,8 @@
 				// sdk lib names from dependencies are re-exported
 				j.exportedSdkLibs = append(j.exportedSdkLibs, dep.ExportedSdkLibs()...)
 				deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs()...)
+				pluginJars, pluginClasses := dep.ExportedPlugins()
+				addPlugins(&deps, pluginJars, pluginClasses...)
 			case java9LibTag:
 				deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars()...)
 			case staticLibTag:
@@ -810,16 +824,31 @@
 				// sdk lib names from dependencies are re-exported
 				j.exportedSdkLibs = append(j.exportedSdkLibs, dep.ExportedSdkLibs()...)
 				deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs()...)
+				pluginJars, pluginClasses := dep.ExportedPlugins()
+				addPlugins(&deps, pluginJars, pluginClasses...)
 			case pluginTag:
 				if plugin, ok := dep.(*Plugin); ok {
-					deps.processorPath = append(deps.processorPath, dep.ImplementationAndResourcesJars()...)
 					if plugin.pluginProperties.Processor_class != nil {
-						deps.processorClasses = append(deps.processorClasses, *plugin.pluginProperties.Processor_class)
+						addPlugins(&deps, plugin.ImplementationAndResourcesJars(), *plugin.pluginProperties.Processor_class)
+					} else {
+						addPlugins(&deps, plugin.ImplementationAndResourcesJars())
 					}
 					deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
 				} else {
 					ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
 				}
+			case exportedPluginTag:
+				if plugin, ok := dep.(*Plugin); ok {
+					if plugin.pluginProperties.Generates_api != nil && *plugin.pluginProperties.Generates_api {
+						ctx.PropertyErrorf("exported_plugins", "Cannot export plugins with generates_api = true, found %v", otherName)
+					}
+					j.exportedPluginJars = append(j.exportedPluginJars, plugin.ImplementationAndResourcesJars()...)
+					if plugin.pluginProperties.Processor_class != nil {
+						j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
+					}
+				} else {
+					ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
+				}
 			case frameworkApkTag:
 				if ctx.ModuleName() == "android_stubs_current" ||
 					ctx.ModuleName() == "android_system_stubs_current" ||
@@ -875,6 +904,11 @@
 	return deps
 }
 
+func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
+	deps.processorPath = append(deps.processorPath, pluginJars...)
+	deps.processorClasses = append(deps.processorClasses, pluginClasses...)
+}
+
 func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext sdkContext) javaVersion {
 	v := sdkContext.sdkVersion()
 	// For PDK builds, use the latest SDK version instead of "current"
@@ -1569,6 +1603,10 @@
 	return j.exportedSdkLibs
 }
 
+func (j *Module) ExportedPlugins() (android.Paths, []string) {
+	return j.exportedPluginJars, j.exportedPluginClasses
+}
+
 func (j *Module) SrcJarArgs() ([]string, android.Paths) {
 	return j.srcJarArgs, j.srcJarDeps
 }
@@ -1691,25 +1729,27 @@
 		}
 	}
 
-	name := j.Name()
-	bp := builder.AndroidBpFile()
-	bp.Printfln("java_import {")
-	bp.Indent()
-	bp.Printfln("name: %q,", builder.VersionedSdkMemberName(name))
-	bp.Printfln("sdk_member_name: %q,", name)
-	bp.Printfln("jars: [%q],", snapshotRelativeJavaLibPath)
-	bp.Dedent()
-	bp.Printfln("}")
-	bp.Printfln("")
+	j.generateJavaImport(builder, snapshotRelativeJavaLibPath, true)
 
 	// This module is for the case when the source tree for the unversioned module
 	// doesn't exist (i.e. building in an unbundled tree). "prefer:" is set to false
 	// so that this module does not eclipse the unversioned module if it exists.
+	j.generateJavaImport(builder, snapshotRelativeJavaLibPath, false)
+}
+
+func (j *Library) generateJavaImport(builder android.SnapshotBuilder, snapshotRelativeJavaLibPath string, versioned bool) {
+	bp := builder.AndroidBpFile()
+	name := j.Name()
 	bp.Printfln("java_import {")
 	bp.Indent()
-	bp.Printfln("name: %q,", name)
+	if versioned {
+		bp.Printfln("name: %q,", builder.VersionedSdkMemberName(name))
+		bp.Printfln("sdk_member_name: %q,", name)
+	} else {
+		bp.Printfln("name: %q,", name)
+		bp.Printfln("prefer: false,")
+	}
 	bp.Printfln("jars: [%q],", snapshotRelativeJavaLibPath)
-	bp.Printfln("prefer: false,")
 	bp.Dedent()
 	bp.Printfln("}")
 	bp.Printfln("")
@@ -2143,6 +2183,10 @@
 	return j.exportedSdkLibs
 }
 
+func (j *Import) ExportedPlugins() (android.Paths, []string) {
+	return nil, nil
+}
+
 func (j *Import) SrcJarArgs() ([]string, android.Paths) {
 	return nil, nil
 }
diff --git a/java/java_test.go b/java/java_test.go
index 0f7e6de..dc498a4 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -63,37 +63,38 @@
 func testContext(bp string, fs map[string][]byte) *android.TestContext {
 
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("android_app", android.ModuleFactoryAdaptor(AndroidAppFactory))
-	ctx.RegisterModuleType("android_app_certificate", android.ModuleFactoryAdaptor(AndroidAppCertificateFactory))
-	ctx.RegisterModuleType("android_app_import", android.ModuleFactoryAdaptor(AndroidAppImportFactory))
-	ctx.RegisterModuleType("android_library", android.ModuleFactoryAdaptor(AndroidLibraryFactory))
-	ctx.RegisterModuleType("android_test", android.ModuleFactoryAdaptor(AndroidTestFactory))
-	ctx.RegisterModuleType("android_test_helper_app", android.ModuleFactoryAdaptor(AndroidTestHelperAppFactory))
-	ctx.RegisterModuleType("android_test_import", android.ModuleFactoryAdaptor(AndroidTestImportFactory))
-	ctx.RegisterModuleType("java_binary", android.ModuleFactoryAdaptor(BinaryFactory))
-	ctx.RegisterModuleType("java_binary_host", android.ModuleFactoryAdaptor(BinaryHostFactory))
-	ctx.RegisterModuleType("java_device_for_host", android.ModuleFactoryAdaptor(DeviceForHostFactory))
-	ctx.RegisterModuleType("java_host_for_device", android.ModuleFactoryAdaptor(HostForDeviceFactory))
-	ctx.RegisterModuleType("java_library", android.ModuleFactoryAdaptor(LibraryFactory))
-	ctx.RegisterModuleType("java_library_host", android.ModuleFactoryAdaptor(LibraryHostFactory))
-	ctx.RegisterModuleType("java_test", android.ModuleFactoryAdaptor(TestFactory))
-	ctx.RegisterModuleType("java_import", android.ModuleFactoryAdaptor(ImportFactory))
-	ctx.RegisterModuleType("java_import_host", android.ModuleFactoryAdaptor(ImportFactoryHost))
-	ctx.RegisterModuleType("java_defaults", android.ModuleFactoryAdaptor(defaultsFactory))
-	ctx.RegisterModuleType("java_system_modules", android.ModuleFactoryAdaptor(SystemModulesFactory))
-	ctx.RegisterModuleType("java_genrule", android.ModuleFactoryAdaptor(genRuleFactory))
-	ctx.RegisterModuleType("java_plugin", android.ModuleFactoryAdaptor(PluginFactory))
-	ctx.RegisterModuleType("dex_import", android.ModuleFactoryAdaptor(DexImportFactory))
-	ctx.RegisterModuleType("filegroup", android.ModuleFactoryAdaptor(android.FileGroupFactory))
-	ctx.RegisterModuleType("genrule", android.ModuleFactoryAdaptor(genrule.GenRuleFactory))
-	ctx.RegisterModuleType("droiddoc", android.ModuleFactoryAdaptor(DroiddocFactory))
-	ctx.RegisterModuleType("droiddoc_host", android.ModuleFactoryAdaptor(DroiddocHostFactory))
-	ctx.RegisterModuleType("droiddoc_template", android.ModuleFactoryAdaptor(ExportedDroiddocDirFactory))
-	ctx.RegisterModuleType("java_sdk_library", android.ModuleFactoryAdaptor(SdkLibraryFactory))
-	ctx.RegisterModuleType("java_sdk_library_import", android.ModuleFactoryAdaptor(sdkLibraryImportFactory))
-	ctx.RegisterModuleType("override_android_app", android.ModuleFactoryAdaptor(OverrideAndroidAppModuleFactory))
-	ctx.RegisterModuleType("override_android_test", android.ModuleFactoryAdaptor(OverrideAndroidTestModuleFactory))
-	ctx.RegisterModuleType("prebuilt_apis", android.ModuleFactoryAdaptor(PrebuiltApisFactory))
+	ctx.RegisterModuleType("android_app", AndroidAppFactory)
+	ctx.RegisterModuleType("android_app_certificate", AndroidAppCertificateFactory)
+	ctx.RegisterModuleType("android_app_import", AndroidAppImportFactory)
+	ctx.RegisterModuleType("android_library", AndroidLibraryFactory)
+	ctx.RegisterModuleType("android_test", AndroidTestFactory)
+	ctx.RegisterModuleType("android_test_helper_app", AndroidTestHelperAppFactory)
+	ctx.RegisterModuleType("android_test_import", AndroidTestImportFactory)
+	ctx.RegisterModuleType("java_binary", BinaryFactory)
+	ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
+	ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
+	ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
+	ctx.RegisterModuleType("java_library", LibraryFactory)
+	ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
+	ctx.RegisterModuleType("java_test", TestFactory)
+	ctx.RegisterModuleType("java_import", ImportFactory)
+	ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
+	ctx.RegisterModuleType("java_defaults", defaultsFactory)
+	ctx.RegisterModuleType("java_system_modules", SystemModulesFactory)
+	ctx.RegisterModuleType("java_genrule", genRuleFactory)
+	ctx.RegisterModuleType("java_plugin", PluginFactory)
+	ctx.RegisterModuleType("dex_import", DexImportFactory)
+	ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
+	ctx.RegisterModuleType("genrule", genrule.GenRuleFactory)
+	ctx.RegisterModuleType("droiddoc", DroiddocFactory)
+	ctx.RegisterModuleType("droiddoc_host", DroiddocHostFactory)
+	ctx.RegisterModuleType("droiddoc_template", ExportedDroiddocDirFactory)
+	ctx.RegisterModuleType("prebuilt_stubs_sources", PrebuiltStubsSourcesFactory)
+	ctx.RegisterModuleType("java_sdk_library", SdkLibraryFactory)
+	ctx.RegisterModuleType("java_sdk_library_import", sdkLibraryImportFactory)
+	ctx.RegisterModuleType("override_android_app", OverrideAndroidAppModuleFactory)
+	ctx.RegisterModuleType("override_android_test", OverrideAndroidTestModuleFactory)
+	ctx.RegisterModuleType("prebuilt_apis", PrebuiltApisFactory)
 	ctx.PreArchMutators(android.RegisterPrebuiltsPreArchMutators)
 	ctx.PreArchMutators(android.RegisterPrebuiltsPostDepsMutators)
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
@@ -105,11 +106,11 @@
 	ctx.RegisterPreSingletonType("sdk_versions", android.SingletonFactoryAdaptor(sdkPreSingletonFactory))
 
 	// Register module types and mutators from cc needed for JNI testing
-	ctx.RegisterModuleType("cc_library", android.ModuleFactoryAdaptor(cc.LibraryFactory))
-	ctx.RegisterModuleType("cc_object", android.ModuleFactoryAdaptor(cc.ObjectFactory))
-	ctx.RegisterModuleType("toolchain_library", android.ModuleFactoryAdaptor(cc.ToolchainLibraryFactory))
-	ctx.RegisterModuleType("llndk_library", android.ModuleFactoryAdaptor(cc.LlndkLibraryFactory))
-	ctx.RegisterModuleType("ndk_prebuilt_shared_stl", android.ModuleFactoryAdaptor(cc.NdkPrebuiltSharedStlFactory))
+	ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
+	ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
+	ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
+	ctx.RegisterModuleType("llndk_library", cc.LlndkLibraryFactory)
+	ctx.RegisterModuleType("ndk_prebuilt_shared_stl", cc.NdkPrebuiltSharedStlFactory)
 	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
 		ctx.BottomUp("link", cc.LinkageMutator).Parallel()
 		ctx.BottomUp("begin", cc.BeginMutator).Parallel()
@@ -207,6 +208,9 @@
 		"cert/new_cert.pk8":      nil,
 
 		"testdata/data": nil,
+
+		"stubs-sources/foo/Foo.java": nil,
+		"stubs/sources/foo/Foo.java": nil,
 	}
 
 	for k, v := range fs {
@@ -328,6 +332,89 @@
 	}
 }
 
+func TestExportedPlugins(t *testing.T) {
+	type Result struct {
+		library    string
+		processors string
+	}
+	var tests = []struct {
+		name    string
+		extra   string
+		results []Result
+	}{
+		{
+			name:    "Exported plugin is not a direct plugin",
+			extra:   `java_library { name: "exports", srcs: ["a.java"], exported_plugins: ["plugin"] }`,
+			results: []Result{{library: "exports", processors: "-proc:none"}},
+		},
+		{
+			name: "Exports plugin to dependee",
+			extra: `
+				java_library{name: "exports", exported_plugins: ["plugin"]}
+				java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
+				java_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
+			`,
+			results: []Result{
+				{library: "foo", processors: "-processor com.android.TestPlugin"},
+				{library: "bar", processors: "-processor com.android.TestPlugin"},
+			},
+		},
+		{
+			name: "Exports plugin to android_library",
+			extra: `
+				java_library{name: "exports", exported_plugins: ["plugin"]}
+				android_library{name: "foo", srcs: ["a.java"],  libs: ["exports"]}
+				android_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
+			`,
+			results: []Result{
+				{library: "foo", processors: "-processor com.android.TestPlugin"},
+				{library: "bar", processors: "-processor com.android.TestPlugin"},
+			},
+		},
+		{
+			name: "Exports plugin is not propagated via transitive deps",
+			extra: `
+				java_library{name: "exports", exported_plugins: ["plugin"]}
+				java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
+				java_library{name: "bar", srcs: ["a.java"], static_libs: ["foo"]}
+			`,
+			results: []Result{
+				{library: "foo", processors: "-processor com.android.TestPlugin"},
+				{library: "bar", processors: "-proc:none"},
+			},
+		},
+		{
+			name: "Exports plugin appends to plugins",
+			extra: `
+                java_plugin{name: "plugin2", processor_class: "com.android.TestPlugin2"}
+				java_library{name: "exports", exported_plugins: ["plugin"]}
+				java_library{name: "foo", srcs: ["a.java"], libs: ["exports"], plugins: ["plugin2"]}
+			`,
+			results: []Result{
+				{library: "foo", processors: "-processor com.android.TestPlugin,com.android.TestPlugin2"},
+			},
+		},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			ctx, _ := testJava(t, `
+				java_plugin {
+					name: "plugin",
+					processor_class: "com.android.TestPlugin",
+				}
+			`+test.extra)
+
+			for _, want := range test.results {
+				javac := ctx.ModuleForTests(want.library, "android_common").Rule("javac")
+				if javac.Args["processor"] != want.processors {
+					t.Errorf("For library %v, expected %v, found %v", want.library, want.processors, javac.Args["processor"])
+				}
+			}
+		})
+	}
+}
+
 func TestSdkVersionByPartition(t *testing.T) {
 	testJavaError(t, "sdk_version must have a value when the module is located at vendor or product", `
 		java_library {
@@ -415,7 +502,7 @@
 	ctx, _ := testJava(t, `
 		java_library {
 			name: "foo",
-			srcs: ["a.java"],
+			srcs: ["a.java", ":stubs-source"],
 			libs: ["bar", "sdklib"],
 			static_libs: ["baz"],
 		}
@@ -439,6 +526,11 @@
 			name: "sdklib",
 			jars: ["b.jar"],
 		}
+
+		prebuilt_stubs_sources {
+			name: "stubs-source",
+			srcs: ["stubs/sources/**/*.java"],
+		}
 		`)
 
 	javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
@@ -447,6 +539,19 @@
 	bazJar := ctx.ModuleForTests("baz", "android_common").Rule("combineJar").Output
 	sdklibStubsJar := ctx.ModuleForTests("sdklib.stubs", "android_common").Rule("combineJar").Output
 
+	inputs := []string{}
+	for _, p := range javac.BuildParams.Inputs {
+		inputs = append(inputs, p.String())
+	}
+
+	expected := []string{
+		"a.java",
+		"stubs/sources/foo/Foo.java",
+	}
+	if !reflect.DeepEqual(expected, inputs) {
+		t.Errorf("foo inputs incorrect: expected %q, found %q", expected, inputs)
+	}
+
 	if !strings.Contains(javac.Args["classpath"], barJar.String()) {
 		t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], barJar.String())
 	}
diff --git a/python/python_test.go b/python/python_test.go
index e5fe126..ba5e7fa 100644
--- a/python/python_test.go
+++ b/python/python_test.go
@@ -332,12 +332,9 @@
 			ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
 				ctx.BottomUp("version_split", versionSplitMutator()).Parallel()
 			})
-			ctx.RegisterModuleType("python_library_host",
-				android.ModuleFactoryAdaptor(PythonLibraryHostFactory))
-			ctx.RegisterModuleType("python_binary_host",
-				android.ModuleFactoryAdaptor(PythonBinaryHostFactory))
-			ctx.RegisterModuleType("python_defaults",
-				android.ModuleFactoryAdaptor(defaultsFactory))
+			ctx.RegisterModuleType("python_library_host", PythonLibraryHostFactory)
+			ctx.RegisterModuleType("python_binary_host", PythonBinaryHostFactory)
+			ctx.RegisterModuleType("python_defaults", defaultsFactory)
 			ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
 			ctx.Register()
 			ctx.MockFileSystem(d.mockFiles)
diff --git a/rust/rust.go b/rust/rust.go
index 096f7b6..a3266f7 100644
--- a/rust/rust.go
+++ b/rust/rust.go
@@ -77,6 +77,25 @@
 	outputFile       android.OptionalPath
 }
 
+var _ android.ImageInterface = (*Module)(nil)
+
+func (mod *Module) ImageMutatorBegin(ctx android.BaseModuleContext) {}
+
+func (mod *Module) CoreVariantNeeded(ctx android.BaseModuleContext) bool {
+	return true
+}
+
+func (mod *Module) RecoveryVariantNeeded(android.BaseModuleContext) bool {
+	return mod.InRecovery()
+}
+
+func (mod *Module) ExtraImageVariations(android.BaseModuleContext) []string {
+	return nil
+}
+
+func (c *Module) SetImageVariation(ctx android.BaseModuleContext, variant string, module android.Module) {
+}
+
 func (mod *Module) BuildStubs() bool {
 	return false
 }
@@ -687,7 +706,7 @@
 		blueprint.Variation{Mutator: "version", Variation: ""})
 	if !mod.Host() {
 		commonDepVariations = append(commonDepVariations,
-			blueprint.Variation{Mutator: "image", Variation: "core"})
+			blueprint.Variation{Mutator: "image", Variation: android.CoreVariation})
 	}
 
 	actx.AddVariationDependencies(
diff --git a/rust/testing.go b/rust/testing.go
index 24defa6..45dbbbd 100644
--- a/rust/testing.go
+++ b/rust/testing.go
@@ -164,28 +164,28 @@
 
 func CreateTestContext(bp string) *android.TestContext {
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("cc_library", android.ModuleFactoryAdaptor(cc.LibraryFactory))
-	ctx.RegisterModuleType("cc_object", android.ModuleFactoryAdaptor(cc.ObjectFactory))
-	ctx.RegisterModuleType("rust_binary", android.ModuleFactoryAdaptor(RustBinaryFactory))
-	ctx.RegisterModuleType("rust_binary_host", android.ModuleFactoryAdaptor(RustBinaryHostFactory))
-	ctx.RegisterModuleType("rust_test", android.ModuleFactoryAdaptor(RustTestFactory))
-	ctx.RegisterModuleType("rust_test_host", android.ModuleFactoryAdaptor(RustTestHostFactory))
-	ctx.RegisterModuleType("rust_library", android.ModuleFactoryAdaptor(RustLibraryFactory))
-	ctx.RegisterModuleType("rust_library_host", android.ModuleFactoryAdaptor(RustLibraryHostFactory))
-	ctx.RegisterModuleType("rust_library_host_rlib", android.ModuleFactoryAdaptor(RustLibraryRlibHostFactory))
-	ctx.RegisterModuleType("rust_library_host_dylib", android.ModuleFactoryAdaptor(RustLibraryDylibHostFactory))
-	ctx.RegisterModuleType("rust_library_rlib", android.ModuleFactoryAdaptor(RustLibraryRlibFactory))
-	ctx.RegisterModuleType("rust_library_dylib", android.ModuleFactoryAdaptor(RustLibraryDylibFactory))
-	ctx.RegisterModuleType("rust_library_shared", android.ModuleFactoryAdaptor(RustLibrarySharedFactory))
-	ctx.RegisterModuleType("rust_library_static", android.ModuleFactoryAdaptor(RustLibraryStaticFactory))
-	ctx.RegisterModuleType("rust_library_host_shared", android.ModuleFactoryAdaptor(RustLibrarySharedHostFactory))
-	ctx.RegisterModuleType("rust_library_host_static", android.ModuleFactoryAdaptor(RustLibraryStaticHostFactory))
-	ctx.RegisterModuleType("rust_proc_macro", android.ModuleFactoryAdaptor(ProcMacroFactory))
-	ctx.RegisterModuleType("rust_prebuilt_dylib", android.ModuleFactoryAdaptor(PrebuiltDylibFactory))
-	ctx.RegisterModuleType("toolchain_library", android.ModuleFactoryAdaptor(cc.ToolchainLibraryFactory))
+	ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
+	ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
+	ctx.RegisterModuleType("rust_binary", RustBinaryFactory)
+	ctx.RegisterModuleType("rust_binary_host", RustBinaryHostFactory)
+	ctx.RegisterModuleType("rust_test", RustTestFactory)
+	ctx.RegisterModuleType("rust_test_host", RustTestHostFactory)
+	ctx.RegisterModuleType("rust_library", RustLibraryFactory)
+	ctx.RegisterModuleType("rust_library_host", RustLibraryHostFactory)
+	ctx.RegisterModuleType("rust_library_host_rlib", RustLibraryRlibHostFactory)
+	ctx.RegisterModuleType("rust_library_host_dylib", RustLibraryDylibHostFactory)
+	ctx.RegisterModuleType("rust_library_rlib", RustLibraryRlibFactory)
+	ctx.RegisterModuleType("rust_library_dylib", RustLibraryDylibFactory)
+	ctx.RegisterModuleType("rust_library_shared", RustLibrarySharedFactory)
+	ctx.RegisterModuleType("rust_library_static", RustLibraryStaticFactory)
+	ctx.RegisterModuleType("rust_library_host_shared", RustLibrarySharedHostFactory)
+	ctx.RegisterModuleType("rust_library_host_static", RustLibraryStaticHostFactory)
+	ctx.RegisterModuleType("rust_proc_macro", ProcMacroFactory)
+	ctx.RegisterModuleType("rust_prebuilt_dylib", PrebuiltDylibFactory)
+	ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
 	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
 		// cc mutators
-		ctx.BottomUp("image", cc.ImageMutator).Parallel()
+		ctx.BottomUp("image", android.ImageMutator).Parallel()
 		ctx.BottomUp("link", cc.LinkageMutator).Parallel()
 		ctx.BottomUp("version", cc.VersionMutator).Parallel()
 		ctx.BottomUp("begin", cc.BeginMutator).Parallel()
diff --git a/sdk/sdk.go b/sdk/sdk.go
index 4eb3665..321d5ab 100644
--- a/sdk/sdk.go
+++ b/sdk/sdk.go
@@ -16,6 +16,7 @@
 
 import (
 	"fmt"
+	"io"
 	"strconv"
 
 	"github.com/google/blueprint"
@@ -43,6 +44,9 @@
 	properties sdkProperties
 
 	snapshotFile android.OptionalPath
+
+	// The builder, preserved for testing.
+	builderForTests *snapshotBuilder
 }
 
 type sdkProperties struct {
@@ -50,6 +54,8 @@
 	Java_libs []string
 	// The list of native libraries in this SDK
 	Native_shared_libs []string
+	// The list of stub sources in this SDK
+	Stubs_sources []string
 
 	Snapshot bool `blueprint:"mutated"`
 }
@@ -121,6 +127,13 @@
 		OutputFile: s.snapshotFile,
 		DistFile:   s.snapshotFile,
 		Include:    "$(BUILD_PHONY_PACKAGE)",
+		ExtraFooters: []android.AndroidMkExtraFootersFunc{
+			func(w io.Writer, name, prefix, moduleDir string, entries *android.AndroidMkEntries) {
+				// Allow the sdk to be built by simply passing its name on the command line.
+				fmt.Fprintln(w, ".PHONY:", s.Name())
+				fmt.Fprintln(w, s.Name()+":", s.snapshotFile.String())
+			},
+		},
 	}
 }
 
@@ -167,6 +180,7 @@
 func memberMutator(mctx android.BottomUpMutatorContext) {
 	if m, ok := mctx.Module().(*sdk); ok {
 		mctx.AddVariationDependencies(nil, sdkMemberDepTag, m.properties.Java_libs...)
+		mctx.AddVariationDependencies(nil, sdkMemberDepTag, m.properties.Stubs_sources...)
 
 		targets := mctx.MultiTargets()
 		for _, target := range targets {
@@ -176,7 +190,7 @@
 					version = cc.LatestStubsVersionFor(mctx.Config(), name)
 				}
 				mctx.AddFarVariationDependencies(append(target.Variations(), []blueprint.Variation{
-					{Mutator: "image", Variation: "core"},
+					{Mutator: "image", Variation: android.CoreVariation},
 					{Mutator: "link", Variation: "shared"},
 					{Mutator: "version", Variation: version},
 				}...), sdkMemberDepTag, name)
diff --git a/sdk/sdk_test.go b/sdk/sdk_test.go
index 3471bc9..a4f54ef 100644
--- a/sdk/sdk_test.go
+++ b/sdk/sdk_test.go
@@ -42,20 +42,22 @@
 	})
 
 	// from java package
-	ctx.RegisterModuleType("android_app_certificate", android.ModuleFactoryAdaptor(java.AndroidAppCertificateFactory))
-	ctx.RegisterModuleType("java_library", android.ModuleFactoryAdaptor(java.LibraryFactory))
-	ctx.RegisterModuleType("java_import", android.ModuleFactoryAdaptor(java.ImportFactory))
+	ctx.RegisterModuleType("android_app_certificate", java.AndroidAppCertificateFactory)
+	ctx.RegisterModuleType("java_library", java.LibraryFactory)
+	ctx.RegisterModuleType("java_import", java.ImportFactory)
+	ctx.RegisterModuleType("droidstubs", java.DroidstubsFactory)
+	ctx.RegisterModuleType("prebuilt_stubs_sources", java.PrebuiltStubsSourcesFactory)
 
 	// from cc package
-	ctx.RegisterModuleType("cc_library", android.ModuleFactoryAdaptor(cc.LibraryFactory))
-	ctx.RegisterModuleType("cc_library_shared", android.ModuleFactoryAdaptor(cc.LibrarySharedFactory))
-	ctx.RegisterModuleType("cc_object", android.ModuleFactoryAdaptor(cc.ObjectFactory))
-	ctx.RegisterModuleType("cc_prebuilt_library_shared", android.ModuleFactoryAdaptor(cc.PrebuiltSharedLibraryFactory))
-	ctx.RegisterModuleType("cc_prebuilt_library_static", android.ModuleFactoryAdaptor(cc.PrebuiltStaticLibraryFactory))
-	ctx.RegisterModuleType("llndk_library", android.ModuleFactoryAdaptor(cc.LlndkLibraryFactory))
-	ctx.RegisterModuleType("toolchain_library", android.ModuleFactoryAdaptor(cc.ToolchainLibraryFactory))
+	ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
+	ctx.RegisterModuleType("cc_library_shared", cc.LibrarySharedFactory)
+	ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
+	ctx.RegisterModuleType("cc_prebuilt_library_shared", cc.PrebuiltSharedLibraryFactory)
+	ctx.RegisterModuleType("cc_prebuilt_library_static", cc.PrebuiltStaticLibraryFactory)
+	ctx.RegisterModuleType("llndk_library", cc.LlndkLibraryFactory)
+	ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
 	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
-		ctx.BottomUp("image", cc.ImageMutator).Parallel()
+		ctx.BottomUp("image", android.ImageMutator).Parallel()
 		ctx.BottomUp("link", cc.LinkageMutator).Parallel()
 		ctx.BottomUp("vndk", cc.VndkMutator).Parallel()
 		ctx.BottomUp("test_per_src", cc.TestPerSrcMutator).Parallel()
@@ -64,13 +66,13 @@
 	})
 
 	// from apex package
-	ctx.RegisterModuleType("apex", android.ModuleFactoryAdaptor(apex.BundleFactory))
-	ctx.RegisterModuleType("apex_key", android.ModuleFactoryAdaptor(apex.ApexKeyFactory))
+	ctx.RegisterModuleType("apex", apex.BundleFactory)
+	ctx.RegisterModuleType("apex_key", apex.ApexKeyFactory)
 	ctx.PostDepsMutators(apex.RegisterPostDepsMutators)
 
 	// from this package
-	ctx.RegisterModuleType("sdk", android.ModuleFactoryAdaptor(ModuleFactory))
-	ctx.RegisterModuleType("sdk_snapshot", android.ModuleFactoryAdaptor(SnapshotModuleFactory))
+	ctx.RegisterModuleType("sdk", ModuleFactory)
+	ctx.RegisterModuleType("sdk_snapshot", SnapshotModuleFactory)
 	ctx.PreDepsMutators(RegisterPreDepsMutators)
 	ctx.PostDepsMutators(RegisterPostDepsMutators)
 
@@ -104,6 +106,8 @@
 		"include/Test.h":                             nil,
 		"aidl/foo/bar/Test.aidl":                     nil,
 		"libfoo.so":                                  nil,
+		"stubs-sources/foo/bar/Foo.java":             nil,
+		"foo/bar/Foo.java":                           nil,
 	})
 
 	return ctx, config
@@ -323,6 +327,39 @@
 	ensureListContains(t, pathsToStrings(cpplibForMyApex2.Rule("ld").Implicits), sdkMemberV2.String())
 }
 
+// Note: This test does not verify that a droidstubs can be referenced, either
+// directly or indirectly from an APEX as droidstubs can never be a part of an
+// apex.
+func TestBasicSdkWithDroidstubs(t *testing.T) {
+	testSdk(t, `
+		sdk {
+				name: "mysdk",
+				stubs_sources: ["mystub"],
+		}
+		sdk_snapshot {
+				name: "mysdk@10",
+				stubs_sources: ["mystub_mysdk@10"],
+		}
+		prebuilt_stubs_sources {
+				name: "mystub_mysdk@10",
+				sdk_member_name: "mystub",
+				srcs: ["stubs-sources/foo/bar/Foo.java"],
+		}
+		droidstubs {
+				name: "mystub",
+				srcs: ["foo/bar/Foo.java"],
+				sdk_version: "none",
+				system_modules: "none",
+		}
+		java_library {
+				name: "myjavalib",
+				srcs: [":mystub"],
+				sdk_version: "none",
+				system_modules: "none",
+		}
+	`)
+}
+
 func TestDepNotInRequiredSdks(t *testing.T) {
 	testSdkError(t, `module "myjavalib".*depends on "otherlib".*that isn't part of the required SDKs:.*`, `
 		sdk {
@@ -417,6 +454,7 @@
 			name: "mysdk",
 			java_libs: ["myjavalib"],
 			native_shared_libs: ["mynativelib"],
+			stubs_sources: ["myjavaapistubs"],
 		}
 
 		java_library {
@@ -444,15 +482,115 @@
 			system_shared_libs: [],
 			stl: "none",
 		}
+
+		droidstubs {
+			name: "myjavaapistubs",
+			srcs: ["foo/bar/Foo.java"],
+			system_modules: "none",
+			sdk_version: "none",
+		}
 	`)
 
+	sdk := ctx.ModuleForTests("mysdk", "android_common").Module().(*sdk)
+
+	checkSnapshotAndroidBpContents(t, sdk, `// This is auto-generated. DO NOT EDIT.
+
+java_import {
+    name: "mysdk_myjavalib@current",
+    sdk_member_name: "myjavalib",
+    jars: ["java/myjavalib.jar"],
+}
+
+java_import {
+    name: "myjavalib",
+    prefer: false,
+    jars: ["java/myjavalib.jar"],
+}
+
+prebuilt_stubs_sources {
+    name: "mysdk_myjavaapistubs@current",
+    sdk_member_name: "myjavaapistubs",
+    srcs: ["java/myjavaapistubs_stubs_sources"],
+}
+
+prebuilt_stubs_sources {
+    name: "myjavaapistubs",
+    srcs: ["java/myjavaapistubs_stubs_sources"],
+    prefer: false,
+}
+
+cc_prebuilt_library_shared {
+    name: "mysdk_mynativelib@current",
+    sdk_member_name: "mynativelib",
+    arch: {
+        arm64: {
+            srcs: ["arm64/lib/mynativelib.so"],
+            export_include_dirs: [
+                "arm64/include/include",
+                "arm64/include_gen/mynativelib",
+            ],
+        },
+        arm: {
+            srcs: ["arm/lib/mynativelib.so"],
+            export_include_dirs: [
+                "arm/include/include",
+                "arm/include_gen/mynativelib",
+            ],
+        },
+    },
+    stl: "none",
+    system_shared_libs: [],
+}
+
+cc_prebuilt_library_shared {
+    name: "mynativelib",
+    prefer: false,
+    arch: {
+        arm64: {
+            srcs: ["arm64/lib/mynativelib.so"],
+            export_include_dirs: [
+                "arm64/include/include",
+                "arm64/include_gen/mynativelib",
+            ],
+        },
+        arm: {
+            srcs: ["arm/lib/mynativelib.so"],
+            export_include_dirs: [
+                "arm/include/include",
+                "arm/include_gen/mynativelib",
+            ],
+        },
+    },
+    stl: "none",
+    system_shared_libs: [],
+}
+
+sdk_snapshot {
+    name: "mysdk@current",
+    java_libs: [
+        "mysdk_myjavalib@current",
+    ],
+    stubs_sources: [
+        "mysdk_myjavaapistubs@current",
+    ],
+    native_shared_libs: [
+        "mysdk_mynativelib@current",
+    ],
+}
+
+`)
+
 	var copySrcs []string
 	var copyDests []string
-	buildParams := ctx.ModuleForTests("mysdk", "android_common").Module().BuildParamsForTests()
+	buildParams := sdk.BuildParamsForTests()
+	var zipBp android.BuildParams
 	for _, bp := range buildParams {
-		if bp.Rule.String() == "android/soong/android.Cp" {
+		ruleString := bp.Rule.String()
+		if ruleString == "android/soong/android.Cp" {
 			copySrcs = append(copySrcs, bp.Input.String())
 			copyDests = append(copyDests, bp.Output.Rel()) // rooted at the snapshot root
+		} else if ruleString == "<local rule>:m.mysdk_android_common.snapshot" {
+			zipBp = bp
 		}
 	}
 
@@ -472,6 +610,27 @@
 	ensureListContains(t, copyDests, "arm64/include_gen/mynativelib/aidl/foo/bar/Test.h")
 	ensureListContains(t, copyDests, "java/myjavalib.jar")
 	ensureListContains(t, copyDests, "arm64/lib/mynativelib.so")
+
+	// Ensure that the droidstubs .srcjar as repackaged into a temporary zip file
+	// and then merged together with the intermediate snapshot zip.
+	snapshotCreationInputs := zipBp.Implicits.Strings()
+	ensureListContains(t, snapshotCreationInputs,
+		filepath.Join(buildDir, ".intermediates/mysdk/android_common/tmp/java/myjavaapistubs_stubs_sources.zip"))
+	ensureListContains(t, snapshotCreationInputs,
+		filepath.Join(buildDir, ".intermediates/mysdk/android_common/mysdk-current.unmerged.zip"))
+	actual := zipBp.Output.String()
+	expected := filepath.Join(buildDir, ".intermediates/mysdk/android_common/mysdk-current.zip")
+	if actual != expected {
+		t.Errorf("Expected snapshot output to be %q but was %q", expected, actual)
+	}
+}
+
+func checkSnapshotAndroidBpContents(t *testing.T, s *sdk, expectedContents string) {
+	t.Helper()
+	androidBpContents := strings.NewReplacer("\\n", "\n").Replace(s.GetAndroidBpContentsForTests())
+	if androidBpContents != expectedContents {
+		t.Errorf("Android.bp contents do not match, expected %s, actual %s", expectedContents, androidBpContents)
+	}
 }
 
 var buildDir string
diff --git a/sdk/update.go b/sdk/update.go
index 9fa9e04..e45bd49 100644
--- a/sdk/update.go
+++ b/sdk/update.go
@@ -80,6 +80,16 @@
 	return result
 }
 
+func (s *sdk) stubsSources(ctx android.ModuleContext) []android.SdkAware {
+	result := []android.SdkAware{}
+	ctx.VisitDirectDeps(func(m android.Module) {
+		if j, ok := m.(*java.Droidstubs); ok {
+			result = append(result, j)
+		}
+	})
+	return result
+}
+
 // archSpecificNativeLibInfo represents an arch-specific variant of a native lib
 type archSpecificNativeLibInfo struct {
 	name                      string
@@ -236,9 +246,10 @@
 		ctx:           ctx,
 		version:       "current",
 		snapshotDir:   snapshotDir.OutputPath,
-		androidBpFile: bp,
 		filesToZip:    []android.Path{bp.path},
+		androidBpFile: bp,
 	}
+	s.builderForTests = builder
 
 	// copy exported AIDL files and stub jar files
 	javaLibs := s.javaLibs(ctx)
@@ -246,6 +257,12 @@
 		m.BuildSnapshot(ctx, builder)
 	}
 
+	// copy stubs sources
+	stubsSources := s.stubsSources(ctx)
+	for _, m := range stubsSources {
+		m.BuildSnapshot(ctx, builder)
+	}
+
 	// copy exported header files and stub *.so files
 	nativeLibInfos := s.nativeMemberInfos(ctx)
 	for _, info := range nativeLibInfos {
@@ -266,6 +283,15 @@
 		bp.Dedent()
 		bp.Printfln("],") // java_libs
 	}
+	if len(stubsSources) > 0 {
+		bp.Printfln("stubs_sources: [")
+		bp.Indent()
+		for _, m := range stubsSources {
+			bp.Printfln("%q,", builder.VersionedSdkMemberName(m.Name()))
+		}
+		bp.Dedent()
+		bp.Printfln("],") // stubs_sources
+	}
 	if len(nativeLibInfos) > 0 {
 		bp.Printfln("native_shared_libs: [")
 		bp.Indent()
@@ -284,16 +310,49 @@
 	filesToZip := builder.filesToZip
 
 	// zip them all
-	zipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
+	outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
+	outputRuleName := "snapshot"
+	outputDesc := "Building snapshot for " + ctx.ModuleName()
+
+	// If there are no zips to merge then generate the output zip directly.
+	// Otherwise, generate an intermediate zip file into which other zips can be
+	// merged.
+	var zipFile android.OutputPath
+	var ruleName string
+	var desc string
+	if len(builder.zipsToMerge) == 0 {
+		zipFile = outputZipFile
+		ruleName = outputRuleName
+		desc = outputDesc
+	} else {
+		zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
+		ruleName = "intermediate snapshot"
+		desc = "Building intermediate snapshot for " + ctx.ModuleName()
+	}
+
 	rb := android.NewRuleBuilder()
 	rb.Command().
 		BuiltTool(ctx, "soong_zip").
 		FlagWithArg("-C ", builder.snapshotDir.String()).
 		FlagWithRspFileInputList("-l ", filesToZip).
 		FlagWithOutput("-o ", zipFile)
-	rb.Build(pctx, ctx, "snapshot", "Building snapshot for "+ctx.ModuleName())
+	rb.Build(pctx, ctx, ruleName, desc)
 
-	return zipFile
+	if len(builder.zipsToMerge) != 0 {
+		rb := android.NewRuleBuilder()
+		rb.Command().
+			BuiltTool(ctx, "merge_zips").
+			Output(outputZipFile).
+			Input(zipFile).
+			Inputs(builder.zipsToMerge)
+		rb.Build(pctx, ctx, outputRuleName, outputDesc)
+	}
+
+	return outputZipFile
+}
+
+func (s *sdk) GetAndroidBpContentsForTests() string {
+	return s.builderForTests.androidBpFile.content.String()
 }
 
 func buildSharedNativeLibSnapshot(ctx android.ModuleContext, info *nativeLibInfo, builder android.SnapshotBuilder) {
@@ -347,11 +406,26 @@
 		}
 	}
 
+	info.generatePrebuiltLibrary(ctx, builder, true)
+
+	// This module is for the case when the source tree for the unversioned module
+	// doesn't exist (i.e. building in an unbundled tree). "prefer:" is set to false
+	// so that this module does not eclipse the unversioned module if it exists.
+	info.generatePrebuiltLibrary(ctx, builder, false)
+}
+
+func (info *nativeLibInfo) generatePrebuiltLibrary(ctx android.ModuleContext, builder android.SnapshotBuilder, versioned bool) {
 	bp := builder.AndroidBpFile()
 	bp.Printfln("cc_prebuilt_library_shared {")
 	bp.Indent()
-	bp.Printfln("name: %q,", builder.VersionedSdkMemberName(info.name))
-	bp.Printfln("sdk_member_name: %q,", info.name)
+	name := info.name
+	if versioned {
+		bp.Printfln("name: %q,", builder.VersionedSdkMemberName(name))
+		bp.Printfln("sdk_member_name: %q,", name)
+	} else {
+		bp.Printfln("name: %q,", name)
+		bp.Printfln("prefer: false,")
+	}
 
 	// a function for emitting include dirs
 	printExportedDirsForNativeLibs := func(lib archSpecificNativeLibInfo, systemInclude bool) {
@@ -404,8 +478,9 @@
 	ctx           android.ModuleContext
 	version       string
 	snapshotDir   android.OutputPath
-	filesToZip    android.Paths
 	androidBpFile *generatedFile
+	filesToZip    android.Paths
+	zipsToMerge   android.Paths
 }
 
 func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
@@ -418,6 +493,25 @@
 	s.filesToZip = append(s.filesToZip, path)
 }
 
+func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
+	ctx := s.ctx
+
+	// Repackage the zip file so that the entries are in the destDir directory.
+	// This will allow the zip file to be merged into the snapshot.
+	tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
+	rb := android.NewRuleBuilder()
+	rb.Command().
+		BuiltTool(ctx, "zip2zip").
+		FlagWithInput("-i ", zipPath).
+		FlagWithOutput("-o ", tmpZipPath).
+		Flag("**/*:" + destDir)
+	rb.Build(pctx, ctx, "repackaging "+destDir,
+		"Repackaging zip file "+destDir+" for snapshot "+ctx.ModuleName())
+
+	// Add the repackaged zip file to the files to merge.
+	s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
+}
+
 func (s *snapshotBuilder) AndroidBpFile() android.GeneratedSnapshotFile {
 	return s.androidBpFile
 }
diff --git a/sysprop/sysprop_test.go b/sysprop/sysprop_test.go
index 6b4337a..5e0eb35 100644
--- a/sysprop/sysprop_test.go
+++ b/sysprop/sysprop_test.go
@@ -56,9 +56,9 @@
 	fs map[string][]byte) *android.TestContext {
 
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("android_app", android.ModuleFactoryAdaptor(java.AndroidAppFactory))
-	ctx.RegisterModuleType("java_library", android.ModuleFactoryAdaptor(java.LibraryFactory))
-	ctx.RegisterModuleType("java_system_modules", android.ModuleFactoryAdaptor(java.SystemModulesFactory))
+	ctx.RegisterModuleType("android_app", java.AndroidAppFactory)
+	ctx.RegisterModuleType("java_library", java.LibraryFactory)
+	ctx.RegisterModuleType("java_system_modules", java.SystemModulesFactory)
 	ctx.PreArchMutators(android.RegisterPrebuiltsPreArchMutators)
 	ctx.PreArchMutators(android.RegisterPrebuiltsPostDepsMutators)
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
@@ -66,14 +66,14 @@
 		ctx.BottomUp("sysprop_deps", syspropDepsMutator).Parallel()
 	})
 
-	ctx.RegisterModuleType("cc_library", android.ModuleFactoryAdaptor(cc.LibraryFactory))
-	ctx.RegisterModuleType("cc_library_headers", android.ModuleFactoryAdaptor(cc.LibraryHeaderFactory))
-	ctx.RegisterModuleType("cc_library_static", android.ModuleFactoryAdaptor(cc.LibraryFactory))
-	ctx.RegisterModuleType("cc_object", android.ModuleFactoryAdaptor(cc.ObjectFactory))
-	ctx.RegisterModuleType("llndk_library", android.ModuleFactoryAdaptor(cc.LlndkLibraryFactory))
-	ctx.RegisterModuleType("toolchain_library", android.ModuleFactoryAdaptor(cc.ToolchainLibraryFactory))
+	ctx.RegisterModuleType("cc_library", cc.LibraryFactory)
+	ctx.RegisterModuleType("cc_library_headers", cc.LibraryHeaderFactory)
+	ctx.RegisterModuleType("cc_library_static", cc.LibraryFactory)
+	ctx.RegisterModuleType("cc_object", cc.ObjectFactory)
+	ctx.RegisterModuleType("llndk_library", cc.LlndkLibraryFactory)
+	ctx.RegisterModuleType("toolchain_library", cc.ToolchainLibraryFactory)
 	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
-		ctx.BottomUp("image", cc.ImageMutator).Parallel()
+		ctx.BottomUp("image", android.ImageMutator).Parallel()
 		ctx.BottomUp("link", cc.LinkageMutator).Parallel()
 		ctx.BottomUp("vndk", cc.VndkMutator).Parallel()
 		ctx.BottomUp("version", cc.VersionMutator).Parallel()
@@ -81,7 +81,7 @@
 		ctx.BottomUp("sysprop", cc.SyspropMutator).Parallel()
 	})
 
-	ctx.RegisterModuleType("sysprop_library", android.ModuleFactoryAdaptor(syspropLibraryFactory))
+	ctx.RegisterModuleType("sysprop_library", syspropLibraryFactory)
 
 	ctx.Register()
 
diff --git a/ui/build/cleanbuild.go b/ui/build/cleanbuild.go
index 1dbeb26..0b44b4d 100644
--- a/ui/build/cleanbuild.go
+++ b/ui/build/cleanbuild.go
@@ -97,6 +97,7 @@
 		hostOut("sdk_addon"),
 		hostOut("testcases"),
 		hostOut("vts"),
+		hostOut("vts-core"),
 		productOut("*.img"),
 		productOut("*.zip"),
 		productOut("android-info.txt"),
diff --git a/xml/xml_test.go b/xml/xml_test.go
index f2a440f..0a11566 100644
--- a/xml/xml_test.go
+++ b/xml/xml_test.go
@@ -50,8 +50,8 @@
 func testXml(t *testing.T, bp string) *android.TestContext {
 	config := android.TestArchConfig(buildDir, nil)
 	ctx := android.NewTestArchContext()
-	ctx.RegisterModuleType("prebuilt_etc", android.ModuleFactoryAdaptor(android.PrebuiltEtcFactory))
-	ctx.RegisterModuleType("prebuilt_etc_xml", android.ModuleFactoryAdaptor(PrebuiltEtcXmlFactory))
+	ctx.RegisterModuleType("prebuilt_etc", android.PrebuiltEtcFactory)
+	ctx.RegisterModuleType("prebuilt_etc_xml", PrebuiltEtcXmlFactory)
 	ctx.Register()
 	mockFiles := map[string][]byte{
 		"Android.bp": []byte(bp),