Merge "go/Android.bp: Clarify sdk_version documentation."
diff --git a/android/apex.go b/android/apex.go
index d3f8d2a..b87ff09 100644
--- a/android/apex.go
+++ b/android/apex.go
@@ -111,6 +111,19 @@
 	return false
 }
 
+// InApexByBaseName tells whether this apex variant of the module is part of the given APEX or not,
+// where the APEX is specified by its canonical base name, i.e. typically beginning with
+// "com.android.". In particular this function doesn't differentiate between source and prebuilt
+// APEXes, where the latter may have "prebuilt_" prefixes.
+func (i ApexInfo) InApexByBaseName(apex string) bool {
+	for _, a := range i.InApexes {
+		if RemoveOptionalPrebuiltPrefix(a) == apex {
+			return true
+		}
+	}
+	return false
+}
+
 // ApexTestForInfo stores the contents of APEXes for which this module is a test - although this
 // module is not part of the APEX - and thus has access to APEX internals.
 type ApexTestForInfo struct {
diff --git a/android/mutator.go b/android/mutator.go
index 2a2be6c..6b19dc5 100644
--- a/android/mutator.go
+++ b/android/mutator.go
@@ -48,6 +48,14 @@
 func RegisterMutatorsForBazelConversion(ctx *blueprint.Context, bp2buildMutators []RegisterMutatorFunc) {
 	mctx := &registerMutatorsContext{}
 
+	sharedMutators := []RegisterMutatorFunc{
+		RegisterDefaultsPreArchMutators,
+	}
+
+	for _, f := range sharedMutators {
+		f(mctx)
+	}
+
 	// Register bp2build mutators
 	for _, f := range bp2buildMutators {
 		f(mctx)
diff --git a/apex/apex.go b/apex/apex.go
index ade8fa9..c897042 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -89,6 +89,9 @@
 
 	Multilib apexMultilibProperties
 
+	// List of boot images that are embedded inside this APEX bundle.
+	Boot_images []string
+
 	// List of java libraries that are embedded inside this APEX bundle.
 	Java_libs []string
 
@@ -544,6 +547,7 @@
 	certificateTag = dependencyTag{name: "certificate"}
 	executableTag  = dependencyTag{name: "executable", payload: true}
 	fsTag          = dependencyTag{name: "filesystem", payload: true}
+	bootImageTag   = dependencyTag{name: "bootImage", payload: true}
 	javaLibTag     = dependencyTag{name: "javaLib", payload: true}
 	jniLibTag      = dependencyTag{name: "jniLib", payload: true}
 	keyTag         = dependencyTag{name: "key"}
@@ -721,6 +725,7 @@
 
 	// Common-arch dependencies come next
 	commonVariation := ctx.Config().AndroidCommonTarget.Variations()
+	ctx.AddFarVariationDependencies(commonVariation, bootImageTag, a.properties.Boot_images...)
 	ctx.AddFarVariationDependencies(commonVariation, javaLibTag, a.properties.Java_libs...)
 	ctx.AddFarVariationDependencies(commonVariation, bpfTag, a.properties.Bpfs...)
 	ctx.AddFarVariationDependencies(commonVariation, fsTag, a.properties.Filesystems...)
@@ -730,10 +735,6 @@
 		if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
 			ctx.AddFarVariationDependencies(commonVariation, javaLibTag, "jacocoagent")
 		}
-		// The ART boot image depends on dex2oat to compile it.
-		if !java.SkipDexpreoptBootJars(ctx) {
-			dexpreopt.RegisterToolDeps(ctx)
-		}
 	}
 
 	// Dependencies for signing
@@ -1648,6 +1649,23 @@
 				} else {
 					ctx.PropertyErrorf("binaries", "%q is neither cc_binary, rust_binary, (embedded) py_binary, (host) blueprint_go_binary, (host) bootstrap_go_binary, nor sh_binary", depName)
 				}
+			case bootImageTag:
+				{
+					if _, ok := child.(*java.BootImageModule); !ok {
+						ctx.PropertyErrorf("boot_images", "%q is not a boot_image module", depName)
+						return false
+					}
+					bootImageInfo := ctx.OtherModuleProvider(child, java.BootImageInfoProvider).(java.BootImageInfo)
+					for arch, files := range bootImageInfo.AndroidBootImageFilesByArchType() {
+						dirInApex := filepath.Join("javalib", arch.String())
+						for _, f := range files {
+							androidMkModuleName := "javalib_" + arch.String() + "_" + filepath.Base(f.String())
+							// TODO(b/177892522) - consider passing in the boot image module here instead of nil
+							af := newApexFile(ctx, f, androidMkModuleName, dirInApex, etc, nil)
+							filesInfo = append(filesInfo, af)
+						}
+					}
+				}
 			case javaLibTag:
 				switch child.(type) {
 				case *java.Library, *java.SdkLibrary, *java.DexImport, *java.SdkLibraryImport, *java.Import:
@@ -1862,25 +1880,6 @@
 		return
 	}
 
-	if a.artApex {
-		// Specific to the ART apex: dexpreopt artifacts for libcore Java libraries. Build rules are
-		// generated by the dexpreopt singleton, and here we access build artifacts via the global
-		// boot image config.
-		for arch, files := range java.DexpreoptedArtApexJars(ctx) {
-			dirInApex := filepath.Join("javalib", arch.String())
-			for _, f := range files {
-				localModule := "javalib_" + arch.String() + "_" + filepath.Base(f.String())
-				af := newApexFile(ctx, f, localModule, dirInApex, etc, nil)
-				filesInfo = append(filesInfo, af)
-			}
-		}
-		// Call GetGlobalSoongConfig to initialize it, which may be necessary if dexpreopt is
-		// disabled for libraries/apps, but boot images are still needed.
-		if !java.SkipDexpreoptBootJars(ctx) {
-			dexpreopt.GetGlobalSoongConfig(ctx)
-		}
-	}
-
 	// Remove duplicates in filesInfo
 	removeDup := func(filesInfo []apexFile) []apexFile {
 		encountered := make(map[string]apexFile)
diff --git a/apex/apex_test.go b/apex/apex_test.go
index cded770..7f5be7e 100644
--- a/apex/apex_test.go
+++ b/apex/apex_test.go
@@ -4398,6 +4398,215 @@
 	})
 }
 
+func TestBootDexJarsFromSourcesAndPrebuilts(t *testing.T) {
+	transform := func(config *dexpreopt.GlobalConfig) {
+		config.BootJars = android.CreateTestConfiguredJarList([]string{"myapex:libfoo"})
+	}
+
+	checkBootDexJarPath := func(ctx *android.TestContext, bootDexJarPath string) {
+		s := ctx.SingletonForTests("dex_bootjars")
+		foundLibfooJar := false
+		for _, output := range s.AllOutputs() {
+			if strings.HasSuffix(output, "/libfoo.jar") {
+				foundLibfooJar = true
+				buildRule := s.Output(output)
+				actual := android.NormalizePathForTesting(buildRule.Input)
+				if actual != bootDexJarPath {
+					t.Errorf("Incorrect boot dex jar path '%s', expected '%s'", actual, bootDexJarPath)
+				}
+			}
+		}
+		if !foundLibfooJar {
+			t.Errorf("Rule for libfoo.jar missing in dex_bootjars singleton outputs")
+		}
+	}
+
+	t.Run("prebuilt only", func(t *testing.T) {
+		bp := `
+		prebuilt_apex {
+			name: "myapex",
+			arch: {
+				arm64: {
+					src: "myapex-arm64.apex",
+				},
+				arm: {
+					src: "myapex-arm.apex",
+				},
+			},
+			exported_java_libs: ["libfoo"],
+		}
+
+		java_import {
+			name: "libfoo",
+			jars: ["libfoo.jar"],
+			apex_available: ["myapex"],
+		}
+	`
+
+		ctx := testDexpreoptWithApexes(t, bp, "", transform)
+		checkBootDexJarPath(ctx, ".intermediates/myapex.deapexer/android_common/deapexer/javalib/libfoo.jar")
+	})
+
+	t.Run("prebuilt with source library preferred", func(t *testing.T) {
+		bp := `
+		prebuilt_apex {
+			name: "myapex",
+			arch: {
+				arm64: {
+					src: "myapex-arm64.apex",
+				},
+				arm: {
+					src: "myapex-arm.apex",
+				},
+			},
+			exported_java_libs: ["libfoo"],
+		}
+
+		java_import {
+			name: "libfoo",
+			jars: ["libfoo.jar"],
+			apex_available: ["myapex"],
+		}
+
+		java_library {
+			name: "libfoo",
+			srcs: ["foo/bar/MyClass.java"],
+			apex_available: ["myapex"],
+		}
+	`
+
+		// In this test the source (java_library) libfoo is active since the
+		// prebuilt (java_import) defaults to prefer:false. However the
+		// prebuilt_apex module always depends on the prebuilt, and so it doesn't
+		// find the dex boot jar in it. We either need to disable the source libfoo
+		// or make the prebuilt libfoo preferred.
+		testDexpreoptWithApexes(t, bp, "failed to find a dex jar path for module 'libfoo'", transform)
+	})
+
+	t.Run("prebuilt library preferred with source", func(t *testing.T) {
+		bp := `
+		prebuilt_apex {
+			name: "myapex",
+			arch: {
+				arm64: {
+					src: "myapex-arm64.apex",
+				},
+				arm: {
+					src: "myapex-arm.apex",
+				},
+			},
+			exported_java_libs: ["libfoo"],
+		}
+
+		java_import {
+			name: "libfoo",
+			prefer: true,
+			jars: ["libfoo.jar"],
+			apex_available: ["myapex"],
+		}
+
+		java_library {
+			name: "libfoo",
+			srcs: ["foo/bar/MyClass.java"],
+			apex_available: ["myapex"],
+		}
+	`
+
+		ctx := testDexpreoptWithApexes(t, bp, "", transform)
+		checkBootDexJarPath(ctx, ".intermediates/myapex.deapexer/android_common/deapexer/javalib/libfoo.jar")
+	})
+
+	t.Run("prebuilt with source apex preferred", func(t *testing.T) {
+		bp := `
+		apex {
+			name: "myapex",
+			key: "myapex.key",
+			java_libs: ["libfoo"],
+		}
+
+		apex_key {
+			name: "myapex.key",
+			public_key: "testkey.avbpubkey",
+			private_key: "testkey.pem",
+		}
+
+		prebuilt_apex {
+			name: "myapex",
+			arch: {
+				arm64: {
+					src: "myapex-arm64.apex",
+				},
+				arm: {
+					src: "myapex-arm.apex",
+				},
+			},
+			exported_java_libs: ["libfoo"],
+		}
+
+		java_import {
+			name: "libfoo",
+			jars: ["libfoo.jar"],
+			apex_available: ["myapex"],
+		}
+
+		java_library {
+			name: "libfoo",
+			srcs: ["foo/bar/MyClass.java"],
+			apex_available: ["myapex"],
+		}
+	`
+
+		ctx := testDexpreoptWithApexes(t, bp, "", transform)
+		checkBootDexJarPath(ctx, ".intermediates/libfoo/android_common_apex10000/aligned/libfoo.jar")
+	})
+
+	t.Run("prebuilt preferred with source apex disabled", func(t *testing.T) {
+		bp := `
+		apex {
+			name: "myapex",
+			enabled: false,
+			key: "myapex.key",
+			java_libs: ["libfoo"],
+		}
+
+		apex_key {
+			name: "myapex.key",
+			public_key: "testkey.avbpubkey",
+			private_key: "testkey.pem",
+		}
+
+		prebuilt_apex {
+			name: "myapex",
+			arch: {
+				arm64: {
+					src: "myapex-arm64.apex",
+				},
+				arm: {
+					src: "myapex-arm.apex",
+				},
+			},
+			exported_java_libs: ["libfoo"],
+		}
+
+		java_import {
+			name: "libfoo",
+			prefer: true,
+			jars: ["libfoo.jar"],
+			apex_available: ["myapex"],
+		}
+
+		java_library {
+			name: "libfoo",
+			srcs: ["foo/bar/MyClass.java"],
+			apex_available: ["myapex"],
+		}
+	`
+
+		ctx := testDexpreoptWithApexes(t, bp, "", transform)
+		checkBootDexJarPath(ctx, ".intermediates/myapex.deapexer/android_common/deapexer/javalib/libfoo.jar")
+	})
+}
+
 func TestApexWithTests(t *testing.T) {
 	ctx, config := testApex(t, `
 		apex_test {
@@ -6002,10 +6211,11 @@
 		"build/make/target/product/security": nil,
 		"apex_manifest.json":                 nil,
 		"AndroidManifest.xml":                nil,
+		"system/sepolicy/apex/myapex-file_contexts":                  nil,
 		"system/sepolicy/apex/some-updatable-apex-file_contexts":     nil,
 		"system/sepolicy/apex/some-non-updatable-apex-file_contexts": nil,
 		"system/sepolicy/apex/com.android.art.debug-file_contexts":   nil,
-		"framework/aidl/a.aidl": nil,
+		"framework/aidl/a.aidl":                                      nil,
 	}
 	cc.GatherRequiredFilesForTest(fs)
 
diff --git a/apex/boot_image_test.go b/apex/boot_image_test.go
index 07feb03..27a1562 100644
--- a/apex/boot_image_test.go
+++ b/apex/boot_image_test.go
@@ -15,6 +15,8 @@
 package apex
 
 import (
+	"reflect"
+	"strings"
 	"testing"
 
 	"android/soong/android"
@@ -69,6 +71,16 @@
 			],
 			srcs: ["b.java"],
 		}
+
+		boot_image {
+			name: "art-boot-image",
+			image_name: "art",
+		}
+
+		boot_image {
+			name: "framework-boot-image",
+			image_name: "boot",
+		}
 `,
 		// Configure some libraries in the art and framework boot images.
 		withArtBootImageJars("com.android.art:baz", "com.android.art:quuz"),
@@ -83,13 +95,39 @@
 	)
 
 	// Make sure that the framework-boot-image is using the correct configuration.
-	checkBootImage(t, ctx, "framework-boot-image", "platform:foo,platform:bar")
+	checkBootImage(t, ctx, "framework-boot-image", "platform:foo,platform:bar", `
+test_device/dex_bootjars/android/system/framework/arm/boot-foo.art
+test_device/dex_bootjars/android/system/framework/arm/boot-foo.oat
+test_device/dex_bootjars/android/system/framework/arm/boot-foo.vdex
+test_device/dex_bootjars/android/system/framework/arm/boot-bar.art
+test_device/dex_bootjars/android/system/framework/arm/boot-bar.oat
+test_device/dex_bootjars/android/system/framework/arm/boot-bar.vdex
+test_device/dex_bootjars/android/system/framework/arm64/boot-foo.art
+test_device/dex_bootjars/android/system/framework/arm64/boot-foo.oat
+test_device/dex_bootjars/android/system/framework/arm64/boot-foo.vdex
+test_device/dex_bootjars/android/system/framework/arm64/boot-bar.art
+test_device/dex_bootjars/android/system/framework/arm64/boot-bar.oat
+test_device/dex_bootjars/android/system/framework/arm64/boot-bar.vdex
+`)
 
 	// Make sure that the art-boot-image is using the correct configuration.
-	checkBootImage(t, ctx, "art-boot-image", "com.android.art:baz,com.android.art:quuz")
+	checkBootImage(t, ctx, "art-boot-image", "com.android.art:baz,com.android.art:quuz", `
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm/boot.art
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm/boot.oat
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm/boot.vdex
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm/boot-quuz.art
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm/boot-quuz.oat
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm/boot-quuz.vdex
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm64/boot.art
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm64/boot.oat
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm64/boot.vdex
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm64/boot-quuz.art
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm64/boot-quuz.oat
+test_device/dex_artjars/android/apex/art_boot_images/javalib/arm64/boot-quuz.vdex
+`)
 }
 
-func checkBootImage(t *testing.T, ctx *android.TestContext, moduleName string, expectedConfiguredModules string) {
+func checkBootImage(t *testing.T, ctx *android.TestContext, moduleName string, expectedConfiguredModules string, expectedBootImageFiles string) {
 	t.Helper()
 
 	bootImage := ctx.ModuleForTests(moduleName, "android_common").Module().(*java.BootImageModule)
@@ -99,6 +137,20 @@
 	if actual := modules.String(); actual != expectedConfiguredModules {
 		t.Errorf("invalid modules for %s: expected %q, actual %q", moduleName, expectedConfiguredModules, actual)
 	}
+
+	// Get a list of all the paths in the boot image sorted by arch type.
+	allPaths := []string{}
+	bootImageFilesByArchType := bootImageInfo.AndroidBootImageFilesByArchType()
+	for _, archType := range android.ArchTypeList() {
+		if paths, ok := bootImageFilesByArchType[archType]; ok {
+			for _, path := range paths {
+				allPaths = append(allPaths, android.NormalizePathForTesting(path))
+			}
+		}
+	}
+	if expected, actual := strings.TrimSpace(expectedBootImageFiles), strings.TrimSpace(strings.Join(allPaths, "\n")); !reflect.DeepEqual(expected, actual) {
+		t.Errorf("invalid paths for %s: expected \n%s, actual \n%s", moduleName, expected, actual)
+	}
 }
 
 func modifyDexpreoptConfig(configModifier func(dexpreoptConfig *dexpreopt.GlobalConfig)) func(fs map[string][]byte, config android.Config) {
@@ -126,3 +178,61 @@
 		dexpreoptConfig.BootJars = android.CreateTestConfiguredJarList(bootJars)
 	})
 }
+
+func TestBootImageInApex(t *testing.T) {
+	ctx, _ := testApex(t, `
+		apex {
+			name: "myapex",
+			key: "myapex.key",
+			boot_images: [
+				"mybootimage",
+			],
+		}
+
+		apex_key {
+			name: "myapex.key",
+			public_key: "testkey.avbpubkey",
+			private_key: "testkey.pem",
+		}
+
+		java_library {
+			name: "foo",
+			srcs: ["b.java"],
+			installable: true,
+		}
+
+		java_library {
+			name: "bar",
+			srcs: ["b.java"],
+			installable: true,
+		}
+
+		boot_image {
+			name: "mybootimage",
+			image_name: "boot",
+			apex_available: [
+				"myapex",
+			],
+		}
+`,
+		// Configure some libraries in the framework boot image.
+		withFrameworkBootImageJars("platform:foo", "platform:bar"),
+	)
+
+	ensureExactContents(t, ctx, "myapex", "android_common_myapex_image", []string{
+		"javalib/arm/boot-bar.art",
+		"javalib/arm/boot-bar.oat",
+		"javalib/arm/boot-bar.vdex",
+		"javalib/arm/boot-foo.art",
+		"javalib/arm/boot-foo.oat",
+		"javalib/arm/boot-foo.vdex",
+		"javalib/arm64/boot-bar.art",
+		"javalib/arm64/boot-bar.oat",
+		"javalib/arm64/boot-bar.vdex",
+		"javalib/arm64/boot-foo.art",
+		"javalib/arm64/boot-foo.oat",
+		"javalib/arm64/boot-foo.vdex",
+	})
+}
+
+// TODO(b/177892522) - add test for host apex.
diff --git a/apex/builder.go b/apex/builder.go
index ee0a410..16ca74c 100644
--- a/apex/builder.go
+++ b/apex/builder.go
@@ -780,7 +780,7 @@
 		ctx.PropertyErrorf("test_only_force_compression", "not available")
 		return
 	}
-	compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.properties.Compressible, true)
+	compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.properties.Compressible, false)
 	if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
 		a.isCompressed = true
 		unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+".capex.unsigned")
diff --git a/bp2build/build_conversion_test.go b/bp2build/build_conversion_test.go
index 66ed42d..a01a7cd 100644
--- a/bp2build/build_conversion_test.go
+++ b/bp2build/build_conversion_test.go
@@ -633,3 +633,201 @@
 		}
 	}
 }
+
+type bp2buildMutator = func(android.TopDownMutatorContext)
+
+func TestBp2BuildInlinesDefaults(t *testing.T) {
+	testCases := []struct {
+		moduleTypesUnderTest      map[string]android.ModuleFactory
+		bp2buildMutatorsUnderTest map[string]bp2buildMutator
+		bp                        string
+		expectedBazelTarget       string
+		description               string
+	}{
+		{
+			moduleTypesUnderTest: map[string]android.ModuleFactory{
+				"genrule":          genrule.GenRuleFactory,
+				"genrule_defaults": func() android.Module { return genrule.DefaultsFactory() },
+			},
+			bp2buildMutatorsUnderTest: map[string]bp2buildMutator{
+				"genrule": genrule.GenruleBp2Build,
+			},
+			bp: `genrule_defaults {
+    name: "gen_defaults",
+    cmd: "do-something $(in) $(out)",
+}
+genrule {
+    name: "gen",
+    out: ["out"],
+    srcs: ["in1"],
+    defaults: ["gen_defaults"],
+}
+`,
+			expectedBazelTarget: `genrule(
+    name = "gen",
+    cmd = "do-something $(SRCS) $(OUTS)",
+    outs = [
+        "out",
+    ],
+    srcs = [
+        "in1",
+    ],
+)`,
+			description: "genrule applies properties from a genrule_defaults dependency if not specified",
+		},
+		{
+			moduleTypesUnderTest: map[string]android.ModuleFactory{
+				"genrule":          genrule.GenRuleFactory,
+				"genrule_defaults": func() android.Module { return genrule.DefaultsFactory() },
+			},
+			bp2buildMutatorsUnderTest: map[string]bp2buildMutator{
+				"genrule": genrule.GenruleBp2Build,
+			},
+			bp: `genrule_defaults {
+    name: "gen_defaults",
+    out: ["out-from-defaults"],
+    srcs: ["in-from-defaults"],
+    cmd: "cmd-from-defaults",
+}
+genrule {
+    name: "gen",
+    out: ["out"],
+    srcs: ["in1"],
+    defaults: ["gen_defaults"],
+    cmd: "do-something $(in) $(out)",
+}
+`,
+			expectedBazelTarget: `genrule(
+    name = "gen",
+    cmd = "do-something $(SRCS) $(OUTS)",
+    outs = [
+        "out-from-defaults",
+        "out",
+    ],
+    srcs = [
+        "in-from-defaults",
+        "in1",
+    ],
+)`,
+			description: "genrule does merges properties from a genrule_defaults dependency, latest-first",
+		},
+		{
+			moduleTypesUnderTest: map[string]android.ModuleFactory{
+				"genrule":          genrule.GenRuleFactory,
+				"genrule_defaults": func() android.Module { return genrule.DefaultsFactory() },
+			},
+			bp2buildMutatorsUnderTest: map[string]bp2buildMutator{
+				"genrule": genrule.GenruleBp2Build,
+			},
+			bp: `genrule_defaults {
+    name: "gen_defaults1",
+    cmd: "cp $(in) $(out)",
+}
+
+genrule_defaults {
+    name: "gen_defaults2",
+    srcs: ["in1"],
+}
+
+genrule {
+    name: "gen",
+    out: ["out"],
+    defaults: ["gen_defaults1", "gen_defaults2"],
+}
+`,
+			expectedBazelTarget: `genrule(
+    name = "gen",
+    cmd = "cp $(SRCS) $(OUTS)",
+    outs = [
+        "out",
+    ],
+    srcs = [
+        "in1",
+    ],
+)`,
+			description: "genrule applies properties from list of genrule_defaults",
+		},
+		{
+			moduleTypesUnderTest: map[string]android.ModuleFactory{
+				"genrule":          genrule.GenRuleFactory,
+				"genrule_defaults": func() android.Module { return genrule.DefaultsFactory() },
+			},
+			bp2buildMutatorsUnderTest: map[string]bp2buildMutator{
+				"genrule": genrule.GenruleBp2Build,
+			},
+			bp: `genrule_defaults {
+    name: "gen_defaults1",
+    defaults: ["gen_defaults2"],
+    cmd: "cmd1 $(in) $(out)", // overrides gen_defaults2's cmd property value.
+}
+
+genrule_defaults {
+    name: "gen_defaults2",
+    defaults: ["gen_defaults3"],
+    cmd: "cmd2 $(in) $(out)",
+    out: ["out-from-2"],
+    srcs: ["in1"],
+}
+
+genrule_defaults {
+    name: "gen_defaults3",
+    out: ["out-from-3"],
+    srcs: ["srcs-from-3"],
+}
+
+genrule {
+    name: "gen",
+    out: ["out"],
+    defaults: ["gen_defaults1"],
+}
+`,
+			expectedBazelTarget: `genrule(
+    name = "gen",
+    cmd = "cmd1 $(SRCS) $(OUTS)",
+    outs = [
+        "out-from-3",
+        "out-from-2",
+        "out",
+    ],
+    srcs = [
+        "srcs-from-3",
+        "in1",
+    ],
+)`,
+			description: "genrule applies properties from genrule_defaults transitively",
+		},
+	}
+
+	dir := "."
+	for _, testCase := range testCases {
+		config := android.TestConfig(buildDir, nil, testCase.bp, nil)
+		ctx := android.NewTestContext(config)
+		for m, factory := range testCase.moduleTypesUnderTest {
+			ctx.RegisterModuleType(m, factory)
+		}
+		for mutator, f := range testCase.bp2buildMutatorsUnderTest {
+			ctx.RegisterBp2BuildMutator(mutator, f)
+		}
+		ctx.RegisterForBazelConversion()
+
+		_, errs := ctx.ParseFileList(dir, []string{"Android.bp"})
+		android.FailIfErrored(t, errs)
+		_, errs = ctx.ResolveDependencies(config)
+		android.FailIfErrored(t, errs)
+
+		bazelTargets := GenerateSoongModuleTargets(ctx.Context.Context, Bp2Build)[dir]
+		if actualCount := len(bazelTargets); actualCount != 1 {
+			t.Fatalf("%s: Expected 1 bazel target, got %d", testCase.description, actualCount)
+		}
+
+		actualBazelTarget := bazelTargets[0]
+		if actualBazelTarget.content != testCase.expectedBazelTarget {
+			t.Errorf(
+				"%s: Expected generated Bazel target to be '%s', got '%s'",
+				testCase.description,
+				testCase.expectedBazelTarget,
+				actualBazelTarget.content,
+			)
+		}
+	}
+}
diff --git a/cc/androidmk.go b/cc/androidmk.go
index 040aa0b..ddb81d9 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -168,7 +168,7 @@
 	}
 }
 
-func androidMkWriteTestData(data []android.DataPath, ctx AndroidMkContext, entries *android.AndroidMkEntries) {
+func AndroidMkWriteTestData(data []android.DataPath, entries *android.AndroidMkEntries) {
 	testFiles := android.AndroidMkDataPaths(data)
 	if len(testFiles) > 0 {
 		entries.ExtraEntries = append(entries.ExtraEntries, func(entries *android.AndroidMkEntries) {
@@ -353,7 +353,7 @@
 	for _, srcPath := range benchmark.data {
 		dataPaths = append(dataPaths, android.DataPath{SrcPath: srcPath})
 	}
-	androidMkWriteTestData(dataPaths, ctx, entries)
+	AndroidMkWriteTestData(dataPaths, entries)
 }
 
 func (test *testBinary) AndroidMkEntries(ctx AndroidMkContext, entries *android.AndroidMkEntries) {
@@ -378,7 +378,7 @@
 		}
 	})
 
-	androidMkWriteTestData(test.data, ctx, entries)
+	AndroidMkWriteTestData(test.data, entries)
 	androidMkWriteExtraTestConfigs(test.extraTestConfigs, entries)
 }
 
@@ -519,7 +519,7 @@
 		entries.SubName += ".cfi"
 	}
 
-	entries.SubName += c.androidMkSuffix
+	entries.SubName += c.baseProperties.Androidmk_suffix
 
 	entries.ExtraEntries = append(entries.ExtraEntries, func(entries *android.AndroidMkEntries) {
 		c.libraryDecorator.androidMkWriteExportedFlags(entries)
@@ -546,7 +546,7 @@
 
 func (c *snapshotBinaryDecorator) AndroidMkEntries(ctx AndroidMkContext, entries *android.AndroidMkEntries) {
 	entries.Class = "EXECUTABLES"
-	entries.SubName = c.androidMkSuffix
+	entries.SubName = c.baseProperties.Androidmk_suffix
 
 	entries.ExtraEntries = append(entries.ExtraEntries, func(entries *android.AndroidMkEntries) {
 		entries.AddStrings("LOCAL_MODULE_SYMLINKS", c.Properties.Symlinks...)
@@ -555,7 +555,7 @@
 
 func (c *snapshotObjectLinker) AndroidMkEntries(ctx AndroidMkContext, entries *android.AndroidMkEntries) {
 	entries.Class = "STATIC_LIBRARIES"
-	entries.SubName = c.androidMkSuffix
+	entries.SubName = c.baseProperties.Androidmk_suffix
 
 	entries.ExtraFooters = append(entries.ExtraFooters,
 		func(w io.Writer, name, prefix, moduleDir string) {
diff --git a/cc/cc.go b/cc/cc.go
index afa6bf9..d282b6e 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -50,10 +50,6 @@
 		ctx.BottomUp("version", versionMutator).Parallel()
 		ctx.BottomUp("begin", BeginMutator).Parallel()
 		ctx.BottomUp("sysprop_cc", SyspropMutator).Parallel()
-		ctx.BottomUp("vendor_snapshot", VendorSnapshotMutator).Parallel()
-		ctx.BottomUp("vendor_snapshot_source", VendorSnapshotSourceMutator).Parallel()
-		ctx.BottomUp("recovery_snapshot", RecoverySnapshotMutator).Parallel()
-		ctx.BottomUp("recovery_snapshot_source", RecoverySnapshotSourceMutator).Parallel()
 	})
 
 	ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
@@ -1237,7 +1233,7 @@
 }
 
 func (c *Module) isSnapshotPrebuilt() bool {
-	if p, ok := c.linker.(interface{ isSnapshotPrebuilt() bool }); ok {
+	if p, ok := c.linker.(snapshotInterface); ok {
 		return p.isSnapshotPrebuilt()
 	}
 	return false
@@ -1937,6 +1933,40 @@
 
 	c.Properties.AndroidMkSystemSharedLibs = deps.SystemSharedLibs
 
+	var snapshotInfo *SnapshotInfo
+	getSnapshot := func() SnapshotInfo {
+		// Only modules with BOARD_VNDK_VERSION uses snapshot.  Others use the zero value of
+		// SnapshotInfo, which provides no mappings.
+		if snapshotInfo == nil {
+			// Only retrieve the snapshot on demand in order to avoid circular dependencies
+			// between the modules in the snapshot and the snapshot itself.
+			var snapshotModule []blueprint.Module
+			if c.InVendor() && c.VndkVersion() == actx.DeviceConfig().VndkVersion() {
+				snapshotModule = ctx.AddVariationDependencies(nil, nil, "vendor_snapshot")
+			} else if recoverySnapshotVersion := actx.DeviceConfig().RecoverySnapshotVersion(); recoverySnapshotVersion != "current" && recoverySnapshotVersion != "" && c.InRecovery() {
+				snapshotModule = ctx.AddVariationDependencies(nil, nil, "recovery_snapshot")
+			}
+			if len(snapshotModule) > 0 {
+				snapshot := ctx.OtherModuleProvider(snapshotModule[0], SnapshotInfoProvider).(SnapshotInfo)
+				snapshotInfo = &snapshot
+				// republish the snapshot for use in later mutators on this module
+				ctx.SetProvider(SnapshotInfoProvider, snapshot)
+			} else {
+				snapshotInfo = &SnapshotInfo{}
+			}
+		}
+
+		return *snapshotInfo
+	}
+
+	rewriteSnapshotLib := func(lib string, snapshotMap map[string]string) string {
+		if snapshot, ok := snapshotMap[lib]; ok {
+			return snapshot
+		}
+
+		return lib
+	}
+
 	variantNdkLibs := []string{}
 	variantLateNdkLibs := []string{}
 	if ctx.Os() == android.Android {
@@ -1956,21 +1986,6 @@
 		// nonvariantLibs
 
 		vendorPublicLibraries := vendorPublicLibraries(actx.Config())
-		vendorSnapshotSharedLibs := vendorSnapshotSharedLibs(actx.Config())
-		recoverySnapshotSharedLibs := recoverySnapshotSharedLibs(actx.Config())
-
-		rewriteVendorLibs := func(lib string) string {
-			// only modules with BOARD_VNDK_VERSION uses snapshot.
-			if c.VndkVersion() != actx.DeviceConfig().VndkVersion() {
-				return lib
-			}
-
-			if snapshot, ok := vendorSnapshotSharedLibs.get(lib, actx.Arch().ArchType); ok {
-				return snapshot
-			}
-
-			return lib
-		}
 
 		rewriteLibs := func(list []string) (nonvariantLibs []string, variantLibs []string) {
 			variantLibs = []string{}
@@ -1979,21 +1994,11 @@
 				// strip #version suffix out
 				name, _ := StubsLibNameAndVersion(entry)
 				if c.InRecovery() {
-					recoverySnapshotVersion :=
-						actx.DeviceConfig().RecoverySnapshotVersion()
-					if recoverySnapshotVersion == "current" ||
-						recoverySnapshotVersion == "" {
-						nonvariantLibs = append(nonvariantLibs, name)
-					} else if snapshot, ok := recoverySnapshotSharedLibs.get(
-						name, actx.Arch().ArchType); ok {
-						nonvariantLibs = append(nonvariantLibs, snapshot)
-					} else {
-						nonvariantLibs = append(nonvariantLibs, name)
-					}
+					nonvariantLibs = append(nonvariantLibs, rewriteSnapshotLib(entry, getSnapshot().SharedLibs))
 				} else if ctx.useSdk() && inList(name, *getNDKKnownLibs(ctx.Config())) {
 					variantLibs = append(variantLibs, name+ndkLibrarySuffix)
 				} else if ctx.useVndk() {
-					nonvariantLibs = append(nonvariantLibs, rewriteVendorLibs(entry))
+					nonvariantLibs = append(nonvariantLibs, rewriteSnapshotLib(entry, getSnapshot().SharedLibs))
 				} else if (ctx.Platform() || ctx.ProductSpecific()) && inList(name, *vendorPublicLibraries) {
 					vendorPublicLib := name + vendorPublicLibrarySuffix
 					if actx.OtherModuleExists(vendorPublicLib) {
@@ -2015,56 +2020,19 @@
 		deps.SharedLibs, variantNdkLibs = rewriteLibs(deps.SharedLibs)
 		deps.LateSharedLibs, variantLateNdkLibs = rewriteLibs(deps.LateSharedLibs)
 		deps.ReexportSharedLibHeaders, _ = rewriteLibs(deps.ReexportSharedLibHeaders)
-		if ctx.useVndk() {
-			for idx, lib := range deps.RuntimeLibs {
-				deps.RuntimeLibs[idx] = rewriteVendorLibs(lib)
-			}
+
+		for idx, lib := range deps.RuntimeLibs {
+			deps.RuntimeLibs[idx] = rewriteSnapshotLib(lib, getSnapshot().SharedLibs)
 		}
 	}
 
-	rewriteSnapshotLibs := func(lib string, snapshotMap *snapshotMap) string {
-		// only modules with BOARD_VNDK_VERSION uses snapshot.
-		if c.VndkVersion() != actx.DeviceConfig().VndkVersion() {
-			return lib
-		}
-
-		if snapshot, ok := snapshotMap.get(lib, actx.Arch().ArchType); ok {
-			return snapshot
-		}
-
-		return lib
-	}
-
-	snapshotHeaderLibs := vendorSnapshotHeaderLibs(actx.Config())
-	snapshotStaticLibs := vendorSnapshotStaticLibs(actx.Config())
-	snapshotObjects := vendorSnapshotObjects(actx.Config())
-
-	if c.InRecovery() {
-		rewriteSnapshotLibs = func(lib string, snapshotMap *snapshotMap) string {
-			recoverySnapshotVersion :=
-				actx.DeviceConfig().RecoverySnapshotVersion()
-			if recoverySnapshotVersion == "current" ||
-				recoverySnapshotVersion == "" {
-				return lib
-			} else if snapshot, ok := snapshotMap.get(lib, actx.Arch().ArchType); ok {
-				return snapshot
-			}
-
-			return lib
-		}
-
-		snapshotHeaderLibs = recoverySnapshotHeaderLibs(actx.Config())
-		snapshotStaticLibs = recoverySnapshotStaticLibs(actx.Config())
-		snapshotObjects = recoverySnapshotObjects(actx.Config())
-	}
-
 	for _, lib := range deps.HeaderLibs {
 		depTag := libraryDependencyTag{Kind: headerLibraryDependency}
 		if inList(lib, deps.ReexportHeaderLibHeaders) {
 			depTag.reexportFlags = true
 		}
 
-		lib = rewriteSnapshotLibs(lib, snapshotHeaderLibs)
+		lib = rewriteSnapshotLib(lib, getSnapshot().HeaderLibs)
 
 		if c.IsStubs() {
 			actx.AddFarVariationDependencies(append(ctx.Target().Variations(), c.ImageVariation()),
@@ -2087,7 +2055,7 @@
 			lib = impl
 		}
 
-		lib = rewriteSnapshotLibs(lib, snapshotStaticLibs)
+		lib = rewriteSnapshotLib(lib, getSnapshot().StaticLibs)
 
 		actx.AddVariationDependencies([]blueprint.Variation{
 			{Mutator: "link", Variation: "static"},
@@ -2107,7 +2075,7 @@
 			lib = impl
 		}
 
-		lib = rewriteSnapshotLibs(lib, snapshotStaticLibs)
+		lib = rewriteSnapshotLib(lib, getSnapshot().StaticLibs)
 
 		actx.AddVariationDependencies([]blueprint.Variation{
 			{Mutator: "link", Variation: "static"},
@@ -2121,14 +2089,14 @@
 		depTag := libraryDependencyTag{Kind: staticLibraryDependency, staticUnwinder: true}
 		actx.AddVariationDependencies([]blueprint.Variation{
 			{Mutator: "link", Variation: "static"},
-		}, depTag, rewriteSnapshotLibs(staticUnwinder(actx), snapshotStaticLibs))
+		}, depTag, rewriteSnapshotLib(staticUnwinder(actx), getSnapshot().StaticLibs))
 	}
 
 	for _, lib := range deps.LateStaticLibs {
 		depTag := libraryDependencyTag{Kind: staticLibraryDependency, Order: lateLibraryDependency}
 		actx.AddVariationDependencies([]blueprint.Variation{
 			{Mutator: "link", Variation: "static"},
-		}, depTag, rewriteSnapshotLibs(lib, snapshotStaticLibs))
+		}, depTag, rewriteSnapshotLib(lib, getSnapshot().StaticLibs))
 	}
 
 	// shared lib names without the #version suffix
@@ -2192,11 +2160,11 @@
 	actx.AddVariationDependencies(crtVariations, objDepTag, deps.ObjFiles...)
 	if deps.CrtBegin != "" {
 		actx.AddVariationDependencies(crtVariations, CrtBeginDepTag,
-			rewriteSnapshotLibs(deps.CrtBegin, snapshotObjects))
+			rewriteSnapshotLib(deps.CrtBegin, getSnapshot().Objects))
 	}
 	if deps.CrtEnd != "" {
 		actx.AddVariationDependencies(crtVariations, CrtEndDepTag,
-			rewriteSnapshotLibs(deps.CrtEnd, snapshotObjects))
+			rewriteSnapshotLib(deps.CrtEnd, getSnapshot().Objects))
 	}
 	if deps.LinkerFlagsFile != "" {
 		actx.AddDependency(c, linkerFlagsDepTag, deps.LinkerFlagsFile)
@@ -2917,8 +2885,6 @@
 }
 
 func (c *Module) makeLibName(ctx android.ModuleContext, ccDep LinkableInterface, depName string) string {
-	vendorSuffixModules := vendorSuffixModules(ctx.Config())
-	recoverySuffixModules := recoverySuffixModules(ctx.Config())
 	vendorPublicLibraries := vendorPublicLibraries(ctx.Config())
 
 	libName := baseLibName(depName)
@@ -2929,20 +2895,10 @@
 
 	if c, ok := ccDep.(*Module); ok {
 		// Use base module name for snapshots when exporting to Makefile.
-		if c.isSnapshotPrebuilt() {
+		if snapshotPrebuilt, ok := c.linker.(snapshotInterface); ok {
 			baseName := c.BaseModuleName()
 
-			if c.IsVndk() {
-				return baseName + ".vendor"
-			}
-
-			if c.InVendor() && vendorSuffixModules[baseName] {
-				return baseName + ".vendor"
-			} else if c.InRecovery() && recoverySuffixModules[baseName] {
-				return baseName + ".recovery"
-			} else {
-				return baseName
-			}
+			return baseName + snapshotPrebuilt.snapshotAndroidMkSuffix()
 		}
 	}
 
diff --git a/cc/image.go b/cc/image.go
index 231da7e..afe6a0e 100644
--- a/cc/image.go
+++ b/cc/image.go
@@ -318,9 +318,7 @@
 	} else if m.isSnapshotPrebuilt() {
 		// Make vendor variants only for the versions in BOARD_VNDK_VERSION and
 		// PRODUCT_EXTRA_VNDK_VERSIONS.
-		if snapshot, ok := m.linker.(interface {
-			version() string
-		}); ok {
+		if snapshot, ok := m.linker.(snapshotInterface); ok {
 			if m.InstallInRecovery() {
 				recoveryVariantNeeded = true
 			} else {
diff --git a/cc/sanitize.go b/cc/sanitize.go
index 8eeb355..8218d97 100644
--- a/cc/sanitize.go
+++ b/cc/sanitize.go
@@ -1149,13 +1149,11 @@
 			// added to libFlags and LOCAL_SHARED_LIBRARIES by cc.Module
 			if c.staticBinary() {
 				deps := append(extraStaticDeps, runtimeLibrary)
-				// If we're using snapshots and in vendor, redirect to snapshot whenever possible
-				if c.VndkVersion() == mctx.DeviceConfig().VndkVersion() {
-					snapshots := vendorSnapshotStaticLibs(mctx.Config())
-					for idx, dep := range deps {
-						if lib, ok := snapshots.get(dep, mctx.Arch().ArchType); ok {
-							deps[idx] = lib
-						}
+				// If we're using snapshots, redirect to snapshot whenever possible
+				snapshot := mctx.Provider(SnapshotInfoProvider).(SnapshotInfo)
+				for idx, dep := range deps {
+					if lib, ok := snapshot.StaticLibs[dep]; ok {
+						deps[idx] = lib
 					}
 				}
 
@@ -1168,13 +1166,12 @@
 				}
 				mctx.AddFarVariationDependencies(variations, depTag, deps...)
 			} else if !c.static() && !c.Header() {
-				// If we're using snapshots and in vendor, redirect to snapshot whenever possible
-				if c.VndkVersion() == mctx.DeviceConfig().VndkVersion() {
-					snapshots := vendorSnapshotSharedLibs(mctx.Config())
-					if lib, ok := snapshots.get(runtimeLibrary, mctx.Arch().ArchType); ok {
-						runtimeLibrary = lib
-					}
+				// If we're using snapshots, redirect to snapshot whenever possible
+				snapshot := mctx.Provider(SnapshotInfoProvider).(SnapshotInfo)
+				if lib, ok := snapshot.SharedLibs[runtimeLibrary]; ok {
+					runtimeLibrary = lib
 				}
+
 				// Skip apex dependency check for sharedLibraryDependency
 				// when sanitizer diags are enabled. Skipping the check will allow
 				// building with diag libraries without having to list the
diff --git a/cc/sdk.go b/cc/sdk.go
index 2c3fec3..aec950b 100644
--- a/cc/sdk.go
+++ b/cc/sdk.go
@@ -75,5 +75,7 @@
 			}
 			ctx.AliasVariation("")
 		}
+	case *snapshot:
+		ctx.CreateVariations("")
 	}
 }
diff --git a/cc/snapshot_prebuilt.go b/cc/snapshot_prebuilt.go
index 2003e03..ffaed8e 100644
--- a/cc/snapshot_prebuilt.go
+++ b/cc/snapshot_prebuilt.go
@@ -19,19 +19,15 @@
 
 import (
 	"strings"
-	"sync"
 
 	"android/soong/android"
 
-	"github.com/google/blueprint/proptools"
+	"github.com/google/blueprint"
 )
 
 // Defines the specifics of different images to which the snapshot process is applicable, e.g.,
 // vendor, recovery, ramdisk.
 type snapshotImage interface {
-	// Used to register callbacks with the build system.
-	init()
-
 	// Returns true if a snapshot should be generated for this image.
 	shouldGenerateSnapshot(ctx android.SingletonContext) bool
 
@@ -61,46 +57,41 @@
 	// exclude_from_recovery_snapshot properties.
 	excludeFromSnapshot(m *Module) bool
 
-	// Returns the snapshotMap to be used for a given module and config, or nil if the
-	// module is not included in this image.
-	getSnapshotMap(m *Module, cfg android.Config) *snapshotMap
-
-	// Returns mutex used for mutual exclusion when updating the snapshot maps.
-	getMutex() *sync.Mutex
-
-	// For a given arch, a maps of which modules are included in this image.
-	suffixModules(config android.Config) map[string]bool
-
-	// Whether to add a given module to the suffix map.
-	shouldBeAddedToSuffixModules(m *Module) bool
-
 	// Returns true if the build is using a snapshot for this image.
 	isUsingSnapshot(cfg android.DeviceConfig) bool
 
-	// Whether to skip the module mutator for a module in a given context.
-	skipModuleMutator(ctx android.BottomUpMutatorContext) bool
-
-	// Whether to skip the source mutator for a given module.
-	skipSourceMutator(ctx android.BottomUpMutatorContext) bool
+	// Returns a version of which the snapshot should be used in this target.
+	// This will only be meaningful when isUsingSnapshot is true.
+	targetSnapshotVersion(cfg android.DeviceConfig) string
 
 	// Whether to exclude a given module from the directed snapshot or not.
 	// If the makefile variable DIRECTED_{IMAGE}_SNAPSHOT is true, directed snapshot is turned on,
 	// and only modules listed in {IMAGE}_SNAPSHOT_MODULES will be captured.
 	excludeFromDirectedSnapshot(cfg android.DeviceConfig, name string) bool
+
+	// The image variant name for this snapshot image.
+	// For example, recovery snapshot image will return "recovery", and vendor snapshot image will
+	// return "vendor." + version.
+	imageVariantName(cfg android.DeviceConfig) string
+
+	// The variant suffix for snapshot modules. For example, vendor snapshot modules will have
+	// ".vendor" as their suffix.
+	moduleNameSuffix() string
 }
 
 type vendorSnapshotImage struct{}
 type recoverySnapshotImage struct{}
 
-func (vendorSnapshotImage) init() {
-	android.RegisterSingletonType("vendor-snapshot", VendorSnapshotSingleton)
-	android.RegisterModuleType("vendor_snapshot_shared", VendorSnapshotSharedFactory)
-	android.RegisterModuleType("vendor_snapshot_static", VendorSnapshotStaticFactory)
-	android.RegisterModuleType("vendor_snapshot_header", VendorSnapshotHeaderFactory)
-	android.RegisterModuleType("vendor_snapshot_binary", VendorSnapshotBinaryFactory)
-	android.RegisterModuleType("vendor_snapshot_object", VendorSnapshotObjectFactory)
+func (vendorSnapshotImage) init(ctx android.RegistrationContext) {
+	ctx.RegisterSingletonType("vendor-snapshot", VendorSnapshotSingleton)
+	ctx.RegisterModuleType("vendor_snapshot", vendorSnapshotFactory)
+	ctx.RegisterModuleType("vendor_snapshot_shared", VendorSnapshotSharedFactory)
+	ctx.RegisterModuleType("vendor_snapshot_static", VendorSnapshotStaticFactory)
+	ctx.RegisterModuleType("vendor_snapshot_header", VendorSnapshotHeaderFactory)
+	ctx.RegisterModuleType("vendor_snapshot_binary", VendorSnapshotBinaryFactory)
+	ctx.RegisterModuleType("vendor_snapshot_object", VendorSnapshotObjectFactory)
 
-	android.RegisterSingletonType("vendor-fake-snapshot", VendorFakeSnapshotSingleton)
+	ctx.RegisterSingletonType("vendor-fake-snapshot", VendorFakeSnapshotSingleton)
 }
 
 func (vendorSnapshotImage) shouldGenerateSnapshot(ctx android.SingletonContext) bool {
@@ -129,73 +120,13 @@
 	return m.ExcludeFromVendorSnapshot()
 }
 
-func (vendorSnapshotImage) getSnapshotMap(m *Module, cfg android.Config) *snapshotMap {
-	if lib, ok := m.linker.(libraryInterface); ok {
-		if lib.static() {
-			return vendorSnapshotStaticLibs(cfg)
-		} else if lib.shared() {
-			return vendorSnapshotSharedLibs(cfg)
-		} else {
-			// header
-			return vendorSnapshotHeaderLibs(cfg)
-		}
-	} else if m.binary() {
-		return vendorSnapshotBinaries(cfg)
-	} else if m.object() {
-		return vendorSnapshotObjects(cfg)
-	} else {
-		return nil
-	}
-}
-
-func (vendorSnapshotImage) getMutex() *sync.Mutex {
-	return &vendorSnapshotsLock
-}
-
-func (vendorSnapshotImage) suffixModules(config android.Config) map[string]bool {
-	return vendorSuffixModules(config)
-}
-
-func (vendorSnapshotImage) shouldBeAddedToSuffixModules(module *Module) bool {
-	// vendor suffix should be added to snapshots if the source module isn't vendor: true.
-	if module.SocSpecific() {
-		return false
-	}
-
-	// But we can't just check SocSpecific() since we already passed the image mutator.
-	// Check ramdisk and recovery to see if we are real "vendor: true" module.
-	ramdiskAvailable := module.InRamdisk() && !module.OnlyInRamdisk()
-	vendorRamdiskAvailable := module.InVendorRamdisk() && !module.OnlyInVendorRamdisk()
-	recoveryAvailable := module.InRecovery() && !module.OnlyInRecovery()
-
-	return !ramdiskAvailable && !recoveryAvailable && !vendorRamdiskAvailable
-}
-
 func (vendorSnapshotImage) isUsingSnapshot(cfg android.DeviceConfig) bool {
 	vndkVersion := cfg.VndkVersion()
 	return vndkVersion != "current" && vndkVersion != ""
 }
 
-func (vendorSnapshotImage) skipModuleMutator(ctx android.BottomUpMutatorContext) bool {
-	vndkVersion := ctx.DeviceConfig().VndkVersion()
-	module, ok := ctx.Module().(*Module)
-	return !ok || module.VndkVersion() != vndkVersion
-}
-
-func (vendorSnapshotImage) skipSourceMutator(ctx android.BottomUpMutatorContext) bool {
-	vndkVersion := ctx.DeviceConfig().VndkVersion()
-	module, ok := ctx.Module().(*Module)
-	if !ok {
-		return true
-	}
-	if module.VndkVersion() != vndkVersion {
-		return true
-	}
-	// .. and also filter out llndk library
-	if module.IsLlndk() {
-		return true
-	}
-	return false
+func (vendorSnapshotImage) targetSnapshotVersion(cfg android.DeviceConfig) string {
+	return cfg.VndkVersion()
 }
 
 // returns true iff a given module SHOULD BE EXCLUDED, false if included
@@ -208,13 +139,22 @@
 	return !cfg.VendorSnapshotModules()[name]
 }
 
-func (recoverySnapshotImage) init() {
-	android.RegisterSingletonType("recovery-snapshot", RecoverySnapshotSingleton)
-	android.RegisterModuleType("recovery_snapshot_shared", RecoverySnapshotSharedFactory)
-	android.RegisterModuleType("recovery_snapshot_static", RecoverySnapshotStaticFactory)
-	android.RegisterModuleType("recovery_snapshot_header", RecoverySnapshotHeaderFactory)
-	android.RegisterModuleType("recovery_snapshot_binary", RecoverySnapshotBinaryFactory)
-	android.RegisterModuleType("recovery_snapshot_object", RecoverySnapshotObjectFactory)
+func (vendorSnapshotImage) imageVariantName(cfg android.DeviceConfig) string {
+	return VendorVariationPrefix + cfg.VndkVersion()
+}
+
+func (vendorSnapshotImage) moduleNameSuffix() string {
+	return vendorSuffix
+}
+
+func (recoverySnapshotImage) init(ctx android.RegistrationContext) {
+	ctx.RegisterSingletonType("recovery-snapshot", RecoverySnapshotSingleton)
+	ctx.RegisterModuleType("recovery_snapshot", recoverySnapshotFactory)
+	ctx.RegisterModuleType("recovery_snapshot_shared", RecoverySnapshotSharedFactory)
+	ctx.RegisterModuleType("recovery_snapshot_static", RecoverySnapshotStaticFactory)
+	ctx.RegisterModuleType("recovery_snapshot_header", RecoverySnapshotHeaderFactory)
+	ctx.RegisterModuleType("recovery_snapshot_binary", RecoverySnapshotBinaryFactory)
+	ctx.RegisterModuleType("recovery_snapshot_object", RecoverySnapshotObjectFactory)
 }
 
 func (recoverySnapshotImage) shouldGenerateSnapshot(ctx android.SingletonContext) bool {
@@ -245,50 +185,13 @@
 	return m.ExcludeFromRecoverySnapshot()
 }
 
-func (recoverySnapshotImage) getSnapshotMap(m *Module, cfg android.Config) *snapshotMap {
-	if lib, ok := m.linker.(libraryInterface); ok {
-		if lib.static() {
-			return recoverySnapshotStaticLibs(cfg)
-		} else if lib.shared() {
-			return recoverySnapshotSharedLibs(cfg)
-		} else {
-			// header
-			return recoverySnapshotHeaderLibs(cfg)
-		}
-	} else if m.binary() {
-		return recoverySnapshotBinaries(cfg)
-	} else if m.object() {
-		return recoverySnapshotObjects(cfg)
-	} else {
-		return nil
-	}
-}
-
-func (recoverySnapshotImage) getMutex() *sync.Mutex {
-	return &recoverySnapshotsLock
-}
-
-func (recoverySnapshotImage) suffixModules(config android.Config) map[string]bool {
-	return recoverySuffixModules(config)
-}
-
-func (recoverySnapshotImage) shouldBeAddedToSuffixModules(module *Module) bool {
-	return proptools.BoolDefault(module.Properties.Recovery_available, false)
-}
-
 func (recoverySnapshotImage) isUsingSnapshot(cfg android.DeviceConfig) bool {
 	recoverySnapshotVersion := cfg.RecoverySnapshotVersion()
 	return recoverySnapshotVersion != "current" && recoverySnapshotVersion != ""
 }
 
-func (recoverySnapshotImage) skipModuleMutator(ctx android.BottomUpMutatorContext) bool {
-	module, ok := ctx.Module().(*Module)
-	return !ok || !module.InRecovery()
-}
-
-func (recoverySnapshotImage) skipSourceMutator(ctx android.BottomUpMutatorContext) bool {
-	module, ok := ctx.Module().(*Module)
-	return !ok || !module.InRecovery()
+func (recoverySnapshotImage) targetSnapshotVersion(cfg android.DeviceConfig) string {
+	return cfg.RecoverySnapshotVersion()
 }
 
 func (recoverySnapshotImage) excludeFromDirectedSnapshot(cfg android.DeviceConfig, name string) bool {
@@ -296,130 +199,160 @@
 	return false
 }
 
+func (recoverySnapshotImage) imageVariantName(cfg android.DeviceConfig) string {
+	return android.RecoveryVariation
+}
+
+func (recoverySnapshotImage) moduleNameSuffix() string {
+	return recoverySuffix
+}
+
 var vendorSnapshotImageSingleton vendorSnapshotImage
 var recoverySnapshotImageSingleton recoverySnapshotImage
 
 func init() {
-	vendorSnapshotImageSingleton.init()
-	recoverySnapshotImageSingleton.init()
+	vendorSnapshotImageSingleton.init(android.InitRegistrationContext)
+	recoverySnapshotImageSingleton.init(android.InitRegistrationContext)
 }
 
 const (
-	vendorSnapshotHeaderSuffix = ".vendor_header."
-	vendorSnapshotSharedSuffix = ".vendor_shared."
-	vendorSnapshotStaticSuffix = ".vendor_static."
-	vendorSnapshotBinarySuffix = ".vendor_binary."
-	vendorSnapshotObjectSuffix = ".vendor_object."
+	snapshotHeaderSuffix = "_header."
+	snapshotSharedSuffix = "_shared."
+	snapshotStaticSuffix = "_static."
+	snapshotBinarySuffix = "_binary."
+	snapshotObjectSuffix = "_object."
 )
 
-const (
-	recoverySnapshotHeaderSuffix = ".recovery_header."
-	recoverySnapshotSharedSuffix = ".recovery_shared."
-	recoverySnapshotStaticSuffix = ".recovery_static."
-	recoverySnapshotBinarySuffix = ".recovery_binary."
-	recoverySnapshotObjectSuffix = ".recovery_object."
-)
-
-var (
-	vendorSnapshotsLock         sync.Mutex
-	vendorSuffixModulesKey      = android.NewOnceKey("vendorSuffixModules")
-	vendorSnapshotHeaderLibsKey = android.NewOnceKey("vendorSnapshotHeaderLibs")
-	vendorSnapshotStaticLibsKey = android.NewOnceKey("vendorSnapshotStaticLibs")
-	vendorSnapshotSharedLibsKey = android.NewOnceKey("vendorSnapshotSharedLibs")
-	vendorSnapshotBinariesKey   = android.NewOnceKey("vendorSnapshotBinaries")
-	vendorSnapshotObjectsKey    = android.NewOnceKey("vendorSnapshotObjects")
-)
-
-var (
-	recoverySnapshotsLock         sync.Mutex
-	recoverySuffixModulesKey      = android.NewOnceKey("recoverySuffixModules")
-	recoverySnapshotHeaderLibsKey = android.NewOnceKey("recoverySnapshotHeaderLibs")
-	recoverySnapshotStaticLibsKey = android.NewOnceKey("recoverySnapshotStaticLibs")
-	recoverySnapshotSharedLibsKey = android.NewOnceKey("recoverySnapshotSharedLibs")
-	recoverySnapshotBinariesKey   = android.NewOnceKey("recoverySnapshotBinaries")
-	recoverySnapshotObjectsKey    = android.NewOnceKey("recoverySnapshotObjects")
-)
-
-// vendorSuffixModules holds names of modules whose vendor variants should have the vendor suffix.
-// This is determined by source modules, and then this will be used when exporting snapshot modules
-// to Makefile.
-//
-// For example, if libbase has "vendor_available: true", the name of core variant will be "libbase"
-// while the name of vendor variant will be "libbase.vendor". In such cases, the vendor snapshot of
-// "libbase" should be exported with the name "libbase.vendor".
-//
-// Refer to VendorSnapshotSourceMutator and makeLibName which use this.
-func vendorSuffixModules(config android.Config) map[string]bool {
-	return config.Once(vendorSuffixModulesKey, func() interface{} {
-		return make(map[string]bool)
-	}).(map[string]bool)
+type SnapshotProperties struct {
+	Header_libs []string `android:"arch_variant"`
+	Static_libs []string `android:"arch_variant"`
+	Shared_libs []string `android:"arch_variant"`
+	Vndk_libs   []string `android:"arch_variant"`
+	Binaries    []string `android:"arch_variant"`
+	Objects     []string `android:"arch_variant"`
 }
 
-// these are vendor snapshot maps holding names of vendor snapshot modules
-func vendorSnapshotHeaderLibs(config android.Config) *snapshotMap {
-	return config.Once(vendorSnapshotHeaderLibsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+type snapshot struct {
+	android.ModuleBase
+
+	properties SnapshotProperties
+
+	baseSnapshot baseSnapshotDecorator
+
+	image snapshotImage
 }
 
-func vendorSnapshotSharedLibs(config android.Config) *snapshotMap {
-	return config.Once(vendorSnapshotSharedLibsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) ImageMutatorBegin(ctx android.BaseModuleContext) {
+	cfg := ctx.DeviceConfig()
+	if !s.image.isUsingSnapshot(cfg) || s.image.targetSnapshotVersion(cfg) != s.baseSnapshot.version() {
+		s.Disable()
+	}
 }
 
-func vendorSnapshotStaticLibs(config android.Config) *snapshotMap {
-	return config.Once(vendorSnapshotStaticLibsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) CoreVariantNeeded(ctx android.BaseModuleContext) bool {
+	return false
 }
 
-func vendorSnapshotBinaries(config android.Config) *snapshotMap {
-	return config.Once(vendorSnapshotBinariesKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) RamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
+	return false
 }
 
-func vendorSnapshotObjects(config android.Config) *snapshotMap {
-	return config.Once(vendorSnapshotObjectsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) VendorRamdiskVariantNeeded(ctx android.BaseModuleContext) bool {
+	return false
 }
 
-func recoverySuffixModules(config android.Config) map[string]bool {
-	return config.Once(recoverySuffixModulesKey, func() interface{} {
-		return make(map[string]bool)
-	}).(map[string]bool)
+func (s *snapshot) RecoveryVariantNeeded(ctx android.BaseModuleContext) bool {
+	return false
 }
 
-func recoverySnapshotHeaderLibs(config android.Config) *snapshotMap {
-	return config.Once(recoverySnapshotHeaderLibsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) ExtraImageVariations(ctx android.BaseModuleContext) []string {
+	return []string{s.image.imageVariantName(ctx.DeviceConfig())}
 }
 
-func recoverySnapshotSharedLibs(config android.Config) *snapshotMap {
-	return config.Once(recoverySnapshotSharedLibsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
 }
 
-func recoverySnapshotStaticLibs(config android.Config) *snapshotMap {
-	return config.Once(recoverySnapshotStaticLibsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	// Nothing, the snapshot module is only used to forward dependency information in DepsMutator.
 }
 
-func recoverySnapshotBinaries(config android.Config) *snapshotMap {
-	return config.Once(recoverySnapshotBinariesKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+func (s *snapshot) DepsMutator(ctx android.BottomUpMutatorContext) {
+	collectSnapshotMap := func(variations []blueprint.Variation, depTag blueprint.DependencyTag,
+		names []string, snapshotSuffix, moduleSuffix string) map[string]string {
+
+		decoratedNames := make([]string, 0, len(names))
+		for _, name := range names {
+			decoratedNames = append(decoratedNames, name+
+				snapshotSuffix+moduleSuffix+
+				s.baseSnapshot.version()+
+				"."+ctx.Arch().ArchType.Name)
+		}
+
+		deps := ctx.AddVariationDependencies(variations, depTag, decoratedNames...)
+		snapshotMap := make(map[string]string)
+		for _, dep := range deps {
+			if dep == nil {
+				continue
+			}
+
+			snapshotMap[dep.(*Module).BaseModuleName()] = ctx.OtherModuleName(dep)
+		}
+		return snapshotMap
+	}
+
+	snapshotSuffix := s.image.moduleNameSuffix()
+	headers := collectSnapshotMap(nil, HeaderDepTag(), s.properties.Header_libs, snapshotSuffix, snapshotHeaderSuffix)
+	binaries := collectSnapshotMap(nil, nil, s.properties.Binaries, snapshotSuffix, snapshotBinarySuffix)
+	objects := collectSnapshotMap(nil, nil, s.properties.Objects, snapshotSuffix, snapshotObjectSuffix)
+
+	staticLibs := collectSnapshotMap([]blueprint.Variation{
+		{Mutator: "link", Variation: "static"},
+	}, StaticDepTag(), s.properties.Static_libs, snapshotSuffix, snapshotStaticSuffix)
+
+	sharedLibs := collectSnapshotMap([]blueprint.Variation{
+		{Mutator: "link", Variation: "shared"},
+	}, SharedDepTag(), s.properties.Shared_libs, snapshotSuffix, snapshotSharedSuffix)
+
+	vndkLibs := collectSnapshotMap([]blueprint.Variation{
+		{Mutator: "link", Variation: "shared"},
+	}, SharedDepTag(), s.properties.Vndk_libs, "", vndkSuffix)
+
+	for k, v := range vndkLibs {
+		sharedLibs[k] = v
+	}
+	ctx.SetProvider(SnapshotInfoProvider, SnapshotInfo{
+		HeaderLibs: headers,
+		Binaries:   binaries,
+		Objects:    objects,
+		StaticLibs: staticLibs,
+		SharedLibs: sharedLibs,
+	})
 }
 
-func recoverySnapshotObjects(config android.Config) *snapshotMap {
-	return config.Once(recoverySnapshotObjectsKey, func() interface{} {
-		return newSnapshotMap()
-	}).(*snapshotMap)
+type SnapshotInfo struct {
+	HeaderLibs, Binaries, Objects, StaticLibs, SharedLibs map[string]string
+}
+
+var SnapshotInfoProvider = blueprint.NewMutatorProvider(SnapshotInfo{}, "deps")
+
+var _ android.ImageInterface = (*snapshot)(nil)
+
+func vendorSnapshotFactory() android.Module {
+	return snapshotFactory(vendorSnapshotImageSingleton)
+}
+
+func recoverySnapshotFactory() android.Module {
+	return snapshotFactory(recoverySnapshotImageSingleton)
+}
+
+func snapshotFactory(image snapshotImage) android.Module {
+	snapshot := &snapshot{}
+	snapshot.image = image
+	snapshot.AddProperties(
+		&snapshot.properties,
+		&snapshot.baseSnapshot.baseProperties)
+	android.InitAndroidArchModule(snapshot, android.DeviceSupported, android.MultilibBoth)
+	return snapshot
 }
 
 type baseSnapshotDecoratorProperties struct {
@@ -429,9 +362,12 @@
 	// Target arch name of the snapshot (e.g. 'arm64' for variant 'aosp_arm64')
 	Target_arch string
 
+	// Suffix to be added to the module name when exporting to Android.mk, e.g. ".vendor".
+	Androidmk_suffix string
+
 	// Suffix to be added to the module name, e.g., vendor_shared,
 	// recovery_shared, etc.
-	Module_suffix string
+	ModuleSuffix string `blueprint:"mutated"`
 }
 
 // baseSnapshotDecorator provides common basic functions for all snapshot modules, such as snapshot
@@ -460,7 +396,7 @@
 		versionSuffix += "." + p.arch()
 	}
 
-	return p.baseProperties.Module_suffix + versionSuffix
+	return p.baseProperties.ModuleSuffix + versionSuffix
 }
 
 func (p *baseSnapshotDecorator) version() string {
@@ -471,18 +407,22 @@
 	return p.baseProperties.Target_arch
 }
 
-func (p *baseSnapshotDecorator) module_suffix() string {
-	return p.baseProperties.Module_suffix
+func (p *baseSnapshotDecorator) moduleSuffix() string {
+	return p.baseProperties.ModuleSuffix
 }
 
 func (p *baseSnapshotDecorator) isSnapshotPrebuilt() bool {
 	return true
 }
 
+func (p *baseSnapshotDecorator) snapshotAndroidMkSuffix() string {
+	return p.baseProperties.Androidmk_suffix
+}
+
 // Call this with a module suffix after creating a snapshot module, such as
 // vendorSnapshotSharedSuffix, recoverySnapshotBinarySuffix, etc.
-func (p *baseSnapshotDecorator) init(m *Module, suffix string) {
-	p.baseProperties.Module_suffix = suffix
+func (p *baseSnapshotDecorator) init(m *Module, snapshotSuffix, moduleSuffix string) {
+	p.baseProperties.ModuleSuffix = snapshotSuffix + moduleSuffix
 	m.AddProperties(&p.baseProperties)
 	android.AddLoadHook(m, func(ctx android.LoadHookContext) {
 		vendorSnapshotLoadHook(ctx, p)
@@ -542,7 +482,6 @@
 		// Library flags for cfi variant.
 		Cfi snapshotLibraryProperties `android:"arch_variant"`
 	}
-	androidMkSuffix string
 }
 
 func (p *snapshotLibraryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
@@ -565,14 +504,6 @@
 // As snapshots are prebuilts, this just returns the prebuilt binary after doing things which are
 // done by normal library decorator, e.g. exporting flags.
 func (p *snapshotLibraryDecorator) link(ctx ModuleContext, flags Flags, deps PathDeps, objs Objects) android.Path {
-	m := ctx.Module().(*Module)
-
-	if m.InVendor() && vendorSuffixModules(ctx.Config())[m.BaseModuleName()] {
-		p.androidMkSuffix = vendorSuffix
-	} else if m.InRecovery() && recoverySuffixModules(ctx.Config())[m.BaseModuleName()] {
-		p.androidMkSuffix = recoverySuffix
-	}
-
 	if p.header() {
 		return p.libraryDecorator.link(ctx, flags, deps, objs)
 	}
@@ -655,7 +586,7 @@
 	}
 }
 
-func snapshotLibraryFactory(suffix string) (*Module, *snapshotLibraryDecorator) {
+func snapshotLibraryFactory(snapshotSuffix, moduleSuffix string) (*Module, *snapshotLibraryDecorator) {
 	module, library := NewLibrary(android.DeviceSupported)
 
 	module.stl = nil
@@ -678,7 +609,7 @@
 	module.linker = prebuilt
 	module.installer = prebuilt
 
-	prebuilt.init(module, suffix)
+	prebuilt.init(module, snapshotSuffix, moduleSuffix)
 	module.AddProperties(
 		&prebuilt.properties,
 		&prebuilt.sanitizerProperties,
@@ -692,7 +623,7 @@
 // overrides the vendor variant of the cc shared library with the same name, if BOARD_VNDK_VERSION
 // is set.
 func VendorSnapshotSharedFactory() android.Module {
-	module, prebuilt := snapshotLibraryFactory(vendorSnapshotSharedSuffix)
+	module, prebuilt := snapshotLibraryFactory(vendorSnapshotImageSingleton.moduleNameSuffix(), snapshotSharedSuffix)
 	prebuilt.libraryDecorator.BuildOnlyShared()
 	return module.Init()
 }
@@ -702,7 +633,7 @@
 // overrides the recovery variant of the cc shared library with the same name, if BOARD_VNDK_VERSION
 // is set.
 func RecoverySnapshotSharedFactory() android.Module {
-	module, prebuilt := snapshotLibraryFactory(recoverySnapshotSharedSuffix)
+	module, prebuilt := snapshotLibraryFactory(recoverySnapshotImageSingleton.moduleNameSuffix(), snapshotSharedSuffix)
 	prebuilt.libraryDecorator.BuildOnlyShared()
 	return module.Init()
 }
@@ -712,7 +643,7 @@
 // overrides the vendor variant of the cc static library with the same name, if BOARD_VNDK_VERSION
 // is set.
 func VendorSnapshotStaticFactory() android.Module {
-	module, prebuilt := snapshotLibraryFactory(vendorSnapshotStaticSuffix)
+	module, prebuilt := snapshotLibraryFactory(vendorSnapshotImageSingleton.moduleNameSuffix(), snapshotStaticSuffix)
 	prebuilt.libraryDecorator.BuildOnlyStatic()
 	return module.Init()
 }
@@ -722,7 +653,7 @@
 // overrides the recovery variant of the cc static library with the same name, if BOARD_VNDK_VERSION
 // is set.
 func RecoverySnapshotStaticFactory() android.Module {
-	module, prebuilt := snapshotLibraryFactory(recoverySnapshotStaticSuffix)
+	module, prebuilt := snapshotLibraryFactory(recoverySnapshotImageSingleton.moduleNameSuffix(), snapshotStaticSuffix)
 	prebuilt.libraryDecorator.BuildOnlyStatic()
 	return module.Init()
 }
@@ -732,7 +663,7 @@
 // overrides the vendor variant of the cc header library with the same name, if BOARD_VNDK_VERSION
 // is set.
 func VendorSnapshotHeaderFactory() android.Module {
-	module, prebuilt := snapshotLibraryFactory(vendorSnapshotHeaderSuffix)
+	module, prebuilt := snapshotLibraryFactory(vendorSnapshotImageSingleton.moduleNameSuffix(), snapshotHeaderSuffix)
 	prebuilt.libraryDecorator.HeaderOnly()
 	return module.Init()
 }
@@ -742,7 +673,7 @@
 // overrides the recovery variant of the cc header library with the same name, if BOARD_VNDK_VERSION
 // is set.
 func RecoverySnapshotHeaderFactory() android.Module {
-	module, prebuilt := snapshotLibraryFactory(recoverySnapshotHeaderSuffix)
+	module, prebuilt := snapshotLibraryFactory(recoverySnapshotImageSingleton.moduleNameSuffix(), snapshotHeaderSuffix)
 	prebuilt.libraryDecorator.HeaderOnly()
 	return module.Init()
 }
@@ -764,8 +695,7 @@
 type snapshotBinaryDecorator struct {
 	baseSnapshotDecorator
 	*binaryDecorator
-	properties      snapshotBinaryProperties
-	androidMkSuffix string
+	properties snapshotBinaryProperties
 }
 
 func (p *snapshotBinaryDecorator) matchesWithDevice(config android.DeviceConfig) bool {
@@ -789,14 +719,6 @@
 	p.unstrippedOutputFile = in
 	binName := in.Base()
 
-	m := ctx.Module().(*Module)
-	if m.InVendor() && vendorSuffixModules(ctx.Config())[m.BaseModuleName()] {
-		p.androidMkSuffix = vendorSuffix
-	} else if m.InRecovery() && recoverySuffixModules(ctx.Config())[m.BaseModuleName()] {
-		p.androidMkSuffix = recoverySuffix
-
-	}
-
 	// use cpExecutable to make it executable
 	outputFile := android.PathForModuleOut(ctx, binName)
 	ctx.Build(pctx, android.BuildParams{
@@ -817,17 +739,17 @@
 // development/vendor_snapshot/update.py. As a part of vendor snapshot, vendor_snapshot_binary
 // overrides the vendor variant of the cc binary with the same name, if BOARD_VNDK_VERSION is set.
 func VendorSnapshotBinaryFactory() android.Module {
-	return snapshotBinaryFactory(vendorSnapshotBinarySuffix)
+	return snapshotBinaryFactory(vendorSnapshotImageSingleton.moduleNameSuffix(), snapshotBinarySuffix)
 }
 
 // recovery_snapshot_binary is a special prebuilt executable binary which is auto-generated by
 // development/vendor_snapshot/update.py. As a part of recovery snapshot, recovery_snapshot_binary
 // overrides the recovery variant of the cc binary with the same name, if BOARD_VNDK_VERSION is set.
 func RecoverySnapshotBinaryFactory() android.Module {
-	return snapshotBinaryFactory(recoverySnapshotBinarySuffix)
+	return snapshotBinaryFactory(recoverySnapshotImageSingleton.moduleNameSuffix(), snapshotBinarySuffix)
 }
 
-func snapshotBinaryFactory(suffix string) android.Module {
+func snapshotBinaryFactory(snapshotSuffix, moduleSuffix string) android.Module {
 	module, binary := NewBinary(android.DeviceSupported)
 	binary.baseLinker.Properties.No_libcrt = BoolPtr(true)
 	binary.baseLinker.Properties.Nocrt = BoolPtr(true)
@@ -846,7 +768,7 @@
 	module.stl = nil
 	module.linker = prebuilt
 
-	prebuilt.init(module, suffix)
+	prebuilt.init(module, snapshotSuffix, moduleSuffix)
 	module.AddProperties(&prebuilt.properties)
 	return module.Init()
 }
@@ -866,8 +788,7 @@
 type snapshotObjectLinker struct {
 	baseSnapshotDecorator
 	objectLinker
-	properties      vendorSnapshotObjectProperties
-	androidMkSuffix string
+	properties vendorSnapshotObjectProperties
 }
 
 func (p *snapshotObjectLinker) matchesWithDevice(config android.DeviceConfig) bool {
@@ -887,14 +808,6 @@
 		return nil
 	}
 
-	m := ctx.Module().(*Module)
-
-	if m.InVendor() && vendorSuffixModules(ctx.Config())[m.BaseModuleName()] {
-		p.androidMkSuffix = vendorSuffix
-	} else if m.InRecovery() && recoverySuffixModules(ctx.Config())[m.BaseModuleName()] {
-		p.androidMkSuffix = recoverySuffix
-	}
-
 	return android.PathForModuleSrc(ctx, *p.properties.Src)
 }
 
@@ -915,7 +828,7 @@
 	}
 	module.linker = prebuilt
 
-	prebuilt.init(module, vendorSnapshotObjectSuffix)
+	prebuilt.init(module, vendorSnapshotImageSingleton.moduleNameSuffix(), snapshotObjectSuffix)
 	module.AddProperties(&prebuilt.properties)
 	return module.Init()
 }
@@ -933,130 +846,19 @@
 	}
 	module.linker = prebuilt
 
-	prebuilt.init(module, recoverySnapshotObjectSuffix)
+	prebuilt.init(module, recoverySnapshotImageSingleton.moduleNameSuffix(), snapshotObjectSuffix)
 	module.AddProperties(&prebuilt.properties)
 	return module.Init()
 }
 
 type snapshotInterface interface {
 	matchesWithDevice(config android.DeviceConfig) bool
+	isSnapshotPrebuilt() bool
+	version() string
+	snapshotAndroidMkSuffix() string
 }
 
 var _ snapshotInterface = (*vndkPrebuiltLibraryDecorator)(nil)
 var _ snapshotInterface = (*snapshotLibraryDecorator)(nil)
 var _ snapshotInterface = (*snapshotBinaryDecorator)(nil)
 var _ snapshotInterface = (*snapshotObjectLinker)(nil)
-
-//
-// Mutators that helps vendor snapshot modules override source modules.
-//
-
-// VendorSnapshotMutator gathers all snapshots for vendor, and disable all snapshots which don't
-// match with device, e.g.
-//   - snapshot version is different with BOARD_VNDK_VERSION
-//   - snapshot arch is different with device's arch (e.g. arm vs x86)
-//
-// This also handles vndk_prebuilt_shared, except for they won't be disabled in any cases, given
-// that any versions of VNDK might be packed into vndk APEX.
-//
-// TODO(b/145966707): remove mutator and utilize android.Prebuilt to override source modules
-func VendorSnapshotMutator(ctx android.BottomUpMutatorContext) {
-	snapshotMutator(ctx, vendorSnapshotImageSingleton)
-}
-
-func RecoverySnapshotMutator(ctx android.BottomUpMutatorContext) {
-	snapshotMutator(ctx, recoverySnapshotImageSingleton)
-}
-
-func snapshotMutator(ctx android.BottomUpMutatorContext, image snapshotImage) {
-	if !image.isUsingSnapshot(ctx.DeviceConfig()) {
-		return
-	}
-	module, ok := ctx.Module().(*Module)
-	if !ok || !module.Enabled() {
-		return
-	}
-	if image.skipModuleMutator(ctx) {
-		return
-	}
-	if !module.isSnapshotPrebuilt() {
-		return
-	}
-
-	// isSnapshotPrebuilt ensures snapshotInterface
-	if !module.linker.(snapshotInterface).matchesWithDevice(ctx.DeviceConfig()) {
-		// Disable unnecessary snapshot module, but do not disable
-		// vndk_prebuilt_shared because they might be packed into vndk APEX
-		if !module.IsVndk() {
-			module.Disable()
-		}
-		return
-	}
-
-	var snapshotMap *snapshotMap = image.getSnapshotMap(module, ctx.Config())
-	if snapshotMap == nil {
-		return
-	}
-
-	mutex := image.getMutex()
-	mutex.Lock()
-	defer mutex.Unlock()
-	snapshotMap.add(module.BaseModuleName(), ctx.Arch().ArchType, ctx.ModuleName())
-}
-
-// VendorSnapshotSourceMutator disables source modules which have corresponding snapshots.
-func VendorSnapshotSourceMutator(ctx android.BottomUpMutatorContext) {
-	snapshotSourceMutator(ctx, vendorSnapshotImageSingleton)
-}
-
-func RecoverySnapshotSourceMutator(ctx android.BottomUpMutatorContext) {
-	snapshotSourceMutator(ctx, recoverySnapshotImageSingleton)
-}
-
-func snapshotSourceMutator(ctx android.BottomUpMutatorContext, image snapshotImage) {
-	if !ctx.Device() {
-		return
-	}
-	if !image.isUsingSnapshot(ctx.DeviceConfig()) {
-		return
-	}
-
-	module, ok := ctx.Module().(*Module)
-	if !ok {
-		return
-	}
-
-	if image.shouldBeAddedToSuffixModules(module) {
-		mutex := image.getMutex()
-		mutex.Lock()
-		defer mutex.Unlock()
-
-		image.suffixModules(ctx.Config())[ctx.ModuleName()] = true
-	}
-
-	if module.isSnapshotPrebuilt() {
-		return
-	}
-	if image.skipSourceMutator(ctx) {
-		return
-	}
-
-	var snapshotMap *snapshotMap = image.getSnapshotMap(module, ctx.Config())
-	if snapshotMap == nil {
-		return
-	}
-
-	if _, ok := snapshotMap.get(ctx.ModuleName(), ctx.Arch().ArchType); !ok {
-		// Corresponding snapshot doesn't exist
-		return
-	}
-
-	// Disables source modules if corresponding snapshot exists.
-	if lib, ok := module.linker.(libraryInterface); ok && lib.buildStatic() && lib.buildShared() {
-		// But do not disable because the shared variant depends on the static variant.
-		module.HideFromMake()
-		module.Properties.HideFromMake = true
-	} else {
-		module.Disable()
-	}
-}
diff --git a/cc/testing.go b/cc/testing.go
index dc9a59d..3a5bd17 100644
--- a/cc/testing.go
+++ b/cc/testing.go
@@ -586,17 +586,13 @@
 	ctx.RegisterModuleType("vendor_public_library", vendorPublicLibraryFactory)
 	ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
 	ctx.RegisterModuleType("vndk_prebuilt_shared", VndkPrebuiltSharedFactory)
-	ctx.RegisterModuleType("vendor_snapshot_shared", VendorSnapshotSharedFactory)
-	ctx.RegisterModuleType("vendor_snapshot_static", VendorSnapshotStaticFactory)
-	ctx.RegisterModuleType("vendor_snapshot_binary", VendorSnapshotBinaryFactory)
+	vendorSnapshotImageSingleton.init(ctx)
+	recoverySnapshotImageSingleton.init(ctx)
 	RegisterVndkLibraryTxtTypes(ctx)
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
 	android.RegisterPrebuiltMutators(ctx)
 	RegisterRequiredBuildComponentsForTest(ctx)
 	ctx.RegisterSingletonType("vndk-snapshot", VndkSnapshotSingleton)
-	ctx.RegisterSingletonType("vendor-snapshot", VendorSnapshotSingleton)
-	ctx.RegisterSingletonType("vendor-fake-snapshot", VendorFakeSnapshotSingleton)
-	ctx.RegisterSingletonType("recovery-snapshot", RecoverySnapshotSingleton)
 
 	return ctx
 }
diff --git a/cc/vendor_snapshot.go b/cc/vendor_snapshot.go
index 7346aac..35fc1c1 100644
--- a/cc/vendor_snapshot.go
+++ b/cc/vendor_snapshot.go
@@ -291,6 +291,7 @@
 type snapshotJsonFlags struct {
 	ModuleName          string `json:",omitempty"`
 	RelativeInstallPath string `json:",omitempty"`
+	AndroidMkSuffix     string `json:",omitempty"`
 
 	// library flags
 	ExportedDirs       []string `json:",omitempty"`
@@ -403,6 +404,7 @@
 		} else {
 			prop.RelativeInstallPath = m.RelativeInstallPath()
 		}
+		prop.AndroidMkSuffix = m.Properties.SubName
 		prop.RuntimeLibs = m.Properties.SnapshotRuntimeLibs
 		prop.Required = m.RequiredModuleNames()
 		for _, path := range m.InitRc() {
diff --git a/cc/vendor_snapshot_test.go b/cc/vendor_snapshot_test.go
index cce28b0..499d7ae 100644
--- a/cc/vendor_snapshot_test.go
+++ b/cc/vendor_snapshot_test.go
@@ -329,6 +329,24 @@
 			},
 		},
 	}
+
+	// old snapshot module which has to be ignored
+	vndk_prebuilt_shared {
+		name: "libvndk",
+		version: "OLD",
+		target_arch: "arm64",
+		vendor_available: true,
+		product_available: true,
+		vndk: {
+			enabled: true,
+		},
+		arch: {
+			arm64: {
+				srcs: ["libvndk.so"],
+				export_include_dirs: ["include/libvndk"],
+			},
+		},
+	}
 `
 
 	vendorProprietaryBp := `
@@ -367,6 +385,27 @@
 		srcs: ["bin.cpp"],
 	}
 
+	vendor_snapshot {
+		name: "vendor_snapshot",
+		compile_multilib: "first",
+		version: "BOARD",
+		vndk_libs: [
+			"libvndk",
+		],
+		static_libs: [
+			"libvendor",
+			"libvendor_available",
+			"libvndk",
+		],
+		shared_libs: [
+			"libvendor",
+			"libvendor_available",
+		],
+		binaries: [
+			"bin",
+		],
+	}
+
 	vendor_snapshot_static {
 		name: "libvndk",
 		version: "BOARD",
@@ -408,6 +447,7 @@
 
 	vendor_snapshot_shared {
 		name: "libvendor_available",
+		androidmk_suffix: ".vendor",
 		version: "BOARD",
 		target_arch: "arm64",
 		vendor: true,
@@ -421,6 +461,7 @@
 
 	vendor_snapshot_static {
 		name: "libvendor_available",
+		androidmk_suffix: ".vendor",
 		version: "BOARD",
 		target_arch: "arm64",
 		vendor: true,
@@ -443,6 +484,19 @@
 			},
 		},
 	}
+
+	// old snapshot module which has to be ignored
+	vendor_snapshot_binary {
+		name: "bin",
+		version: "OLD",
+		target_arch: "arm64",
+		vendor: true,
+		arch: {
+			arm64: {
+				src: "bin",
+			},
+		},
+	}
 `
 	depsBp := GatherRequiredDepsForTest(android.Android)
 
diff --git a/cc/vndk_prebuilt.go b/cc/vndk_prebuilt.go
index 04162cd..71e6427 100644
--- a/cc/vndk_prebuilt.go
+++ b/cc/vndk_prebuilt.go
@@ -107,6 +107,10 @@
 	return "64"
 }
 
+func (p *vndkPrebuiltLibraryDecorator) snapshotAndroidMkSuffix() string {
+	return ".vendor"
+}
+
 func (p *vndkPrebuiltLibraryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
 	p.libraryDecorator.libName = strings.TrimSuffix(ctx.ModuleName(), p.NameSuffix())
 	return p.libraryDecorator.linkerFlags(ctx, flags)
diff --git a/cmd/soong_build/main.go b/cmd/soong_build/main.go
index 8cd4f97..9dcb5f3 100644
--- a/cmd/soong_build/main.go
+++ b/cmd/soong_build/main.go
@@ -19,6 +19,7 @@
 	"fmt"
 	"os"
 	"path/filepath"
+	"strings"
 
 	"github.com/google/blueprint/bootstrap"
 
@@ -166,12 +167,43 @@
 	// conversion for Bazel conversion.
 	bp2buildCtx := android.NewContext(configuration)
 	bp2buildCtx.RegisterForBazelConversion()
+
+	// No need to generate Ninja build rules/statements from Modules and Singletons.
 	configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
 	bp2buildCtx.SetNameInterface(newNameResolver(configuration))
+
+	// Run the loading and analysis pipeline.
 	bootstrap.Main(bp2buildCtx.Context, configuration, extraNinjaDeps...)
 
+	// Run the code-generation phase to convert BazelTargetModules to BUILD files.
 	codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
 	bp2build.Codegen(codegenContext)
+
+	// Workarounds to support running bp2build in a clean AOSP checkout with no
+	// prior builds, and exiting early as soon as the BUILD files get generated,
+	// therefore not creating build.ninja files that soong_ui and callers of
+	// soong_build expects.
+	//
+	// These files are: build.ninja and build.ninja.d. Since Kati hasn't been
+	// ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
+	// target called `nothing`, so we manually create it here.
+	//
+	// Even though outFile (build.ninja) and depFile (build.ninja.d) are values
+	// passed into bootstrap.Main, they are package-private fields in bootstrap.
+	// Short of modifying Blueprint to add an exported getter, inlining them
+	// here is the next-best practical option.
+	ninjaFileName := "build.ninja"
+	ninjaFile := android.PathForOutput(codegenContext, ninjaFileName)
+	ninjaFileD := android.PathForOutput(codegenContext, ninjaFileName+".d")
+	extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
+	// A workaround to create the 'nothing' ninja target so `m nothing` works,
+	// since bp2build runs without Kati, and the 'nothing' target is declared in
+	// a Makefile.
+	android.WriteFileToOutputDir(ninjaFile, []byte("build nothing: phony\n  phony_output = true\n"), 0666)
+	android.WriteFileToOutputDir(
+		ninjaFileD,
+		[]byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFileName, extraNinjaDepsString)),
+		0666)
 }
 
 // shouldPrepareBuildActions reads configuration and flags if build actions
diff --git a/dexpreopt/class_loader_context.go b/dexpreopt/class_loader_context.go
index bf610ef..ec62eb3 100644
--- a/dexpreopt/class_loader_context.go
+++ b/dexpreopt/class_loader_context.go
@@ -534,3 +534,26 @@
 	}
 	return clcs
 }
+
+// Convert Soong CLC map to JSON representation for Make.
+func toJsonClassLoaderContext(clcMap ClassLoaderContextMap) jsonClassLoaderContextMap {
+	jClcMap := make(jsonClassLoaderContextMap)
+	for sdkVer, clcs := range clcMap {
+		sdkVerStr := fmt.Sprintf("%d", sdkVer)
+		jClcMap[sdkVerStr] = toJsonClassLoaderContextRec(clcs)
+	}
+	return jClcMap
+}
+
+// Recursive helper for toJsonClassLoaderContext.
+func toJsonClassLoaderContextRec(clcs []*ClassLoaderContext) map[string]*jsonClassLoaderContext {
+	jClcs := make(map[string]*jsonClassLoaderContext, len(clcs))
+	for _, clc := range clcs {
+		jClcs[clc.Name] = &jsonClassLoaderContext{
+			Host:        clc.Host.String(),
+			Device:      clc.Device,
+			Subcontexts: toJsonClassLoaderContextRec(clc.Subcontexts),
+		}
+	}
+	return jClcs
+}
diff --git a/dexpreopt/config.go b/dexpreopt/config.go
index 867ece6..d55204b 100644
--- a/dexpreopt/config.go
+++ b/dexpreopt/config.go
@@ -114,6 +114,7 @@
 	ProfileBootListing   android.OptionalPath
 
 	EnforceUsesLibraries bool
+	ProvidesUsesLibrary  string // the name of the <uses-library> (usually the same as its module)
 	ClassLoaderContexts  ClassLoaderContextMap
 
 	Archs                   []android.ArchType
@@ -290,6 +291,42 @@
 	return config.ModuleConfig, nil
 }
 
+// WriteSlimModuleConfigForMake serializes a subset of ModuleConfig into a per-module
+// dexpreopt.config JSON file. It is a way to pass dexpreopt information about Soong modules to
+// Make, which is needed when a Make module has a <uses-library> dependency on a Soong module.
+func WriteSlimModuleConfigForMake(ctx android.ModuleContext, config *ModuleConfig, path android.WritablePath) {
+	if path == nil {
+		return
+	}
+
+	// JSON representation of the slim module dexpreopt.config.
+	type slimModuleJSONConfig struct {
+		Name                 string
+		DexLocation          string
+		BuildPath            string
+		EnforceUsesLibraries bool
+		ProvidesUsesLibrary  string
+		ClassLoaderContexts  jsonClassLoaderContextMap
+	}
+
+	jsonConfig := &slimModuleJSONConfig{
+		Name:                 config.Name,
+		DexLocation:          config.DexLocation,
+		BuildPath:            config.BuildPath.String(),
+		EnforceUsesLibraries: config.EnforceUsesLibraries,
+		ProvidesUsesLibrary:  config.ProvidesUsesLibrary,
+		ClassLoaderContexts:  toJsonClassLoaderContext(config.ClassLoaderContexts),
+	}
+
+	data, err := json.MarshalIndent(jsonConfig, "", "    ")
+	if err != nil {
+		ctx.ModuleErrorf("failed to JSON marshal module dexpreopt.config: %v", err)
+		return
+	}
+
+	android.WriteFileRule(ctx, path, string(data))
+}
+
 // dex2oatModuleName returns the name of the module to use for the dex2oat host
 // tool. It should be a binary module with public visibility that is compiled
 // and installed for host.
diff --git a/java/androidmk.go b/java/androidmk.go
index cc454b0..21f3012 100644
--- a/java/androidmk.go
+++ b/java/androidmk.go
@@ -125,6 +125,10 @@
 					entries.SetString("LOCAL_MODULE_STEM", library.Stem())
 
 					entries.SetOptionalPaths("LOCAL_SOONG_LINT_REPORTS", library.linter.reports)
+
+					if library.dexpreopter.configPath != nil {
+						entries.SetPath("LOCAL_SOONG_DEXPREOPT_CONFIG", library.dexpreopter.configPath)
+					}
 				},
 			},
 		})
diff --git a/java/app.go b/java/app.go
index e6c9a2d..ce89e9b 100755
--- a/java/app.go
+++ b/java/app.go
@@ -455,6 +455,7 @@
 
 func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
 	a.dexpreopter.installPath = a.installPath(ctx)
+	a.dexpreopter.isApp = true
 	if a.dexProperties.Uncompress_dex == nil {
 		// If the value was not force-set by the user, use reasonable default based on the module.
 		a.dexProperties.Uncompress_dex = proptools.BoolPtr(a.shouldUncompressDex(ctx))
diff --git a/java/app_import.go b/java/app_import.go
index df940f1..6f21bfb 100644
--- a/java/app_import.go
+++ b/java/app_import.go
@@ -255,6 +255,7 @@
 		installDir = android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
 	}
 
+	a.dexpreopter.isApp = true
 	a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
 	a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
 	a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
diff --git a/java/boot_image.go b/java/boot_image.go
index 07ef0d8..0a525b7 100644
--- a/java/boot_image.go
+++ b/java/boot_image.go
@@ -15,9 +15,11 @@
 package java
 
 import (
+	"fmt"
 	"strings"
 
 	"android/soong/android"
+	"android/soong/dexpreopt"
 	"github.com/google/blueprint"
 )
 
@@ -38,6 +40,7 @@
 
 type BootImageModule struct {
 	android.ModuleBase
+	android.ApexModuleBase
 
 	properties bootImageProperties
 }
@@ -45,7 +48,8 @@
 func bootImageFactory() android.Module {
 	m := &BootImageModule{}
 	m.AddProperties(&m.properties)
-	android.InitAndroidArchModule(m, android.HostAndDeviceDefault, android.MultilibCommon)
+	android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibCommon)
+	android.InitApexModule(m)
 	return m
 }
 
@@ -53,6 +57,9 @@
 
 type BootImageInfo struct {
 	// The image config, internal to this module (and the dex_bootjars singleton).
+	//
+	// Will be nil if the BootImageInfo has not been provided for a specific module. That can occur
+	// when SkipDexpreoptBootJars(ctx) returns true.
 	imageConfig *bootImageConfig
 }
 
@@ -60,12 +67,56 @@
 	return i.imageConfig.modules
 }
 
+// Get a map from ArchType to the associated boot image's contents for Android.
+//
+// Extension boot images only return their own files, not the files of the boot images they extend.
+func (i BootImageInfo) AndroidBootImageFilesByArchType() map[android.ArchType]android.OutputPaths {
+	files := map[android.ArchType]android.OutputPaths{}
+	if i.imageConfig != nil {
+		for _, variant := range i.imageConfig.variants {
+			// We also generate boot images for host (for testing), but we don't need those in the apex.
+			// TODO(b/177892522) - consider changing this to check Os.OsClass = android.Device
+			if variant.target.Os == android.Android {
+				files[variant.target.Arch.ArchType] = variant.imagesDeps
+			}
+		}
+	}
+	return files
+}
+
+func (b *BootImageModule) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
+	tag := ctx.OtherModuleDependencyTag(dep)
+	if tag == dexpreopt.Dex2oatDepTag {
+		// The dex2oat tool is only needed for building and is not required in the apex.
+		return false
+	}
+	panic(fmt.Errorf("boot_image module %q should not have a dependency on %q via tag %s", b, dep, android.PrettyPrintTag(tag)))
+}
+
+func (b *BootImageModule) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
+	return nil
+}
+
+func (b *BootImageModule) DepsMutator(ctx android.BottomUpMutatorContext) {
+	if SkipDexpreoptBootJars(ctx) {
+		return
+	}
+
+	// Add a dependency onto the dex2oat tool which is needed for creating the boot image. The
+	// path is retrieved from the dependency by GetGlobalSoongConfig(ctx).
+	dexpreopt.RegisterToolDeps(ctx)
+}
+
 func (b *BootImageModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	// Nothing to do if skipping the dexpreopt of boot image jars.
 	if SkipDexpreoptBootJars(ctx) {
 		return
 	}
 
+	// Force the GlobalSoongConfig to be created and cached for use by the dex_bootjars
+	// GenerateSingletonBuildActions method as it cannot create it for itself.
+	dexpreopt.GetGlobalSoongConfig(ctx)
+
 	// Get a map of the image configs that are supported.
 	imageConfigs := genBootImageConfigs(ctx)
 
diff --git a/java/boot_jars.go b/java/boot_jars.go
index 823275b..ac8107b 100644
--- a/java/boot_jars.go
+++ b/java/boot_jars.go
@@ -49,14 +49,36 @@
 	return true
 }
 
+// isActiveModule returns true if the given module should be considered for boot
+// jars, i.e. if it's enabled and the preferred one in case of source and
+// prebuilt alternatives.
+func isActiveModule(module android.Module) bool {
+	if !module.Enabled() {
+		return false
+	}
+	if module.IsReplacedByPrebuilt() {
+		// A source module that has been replaced by a prebuilt counterpart.
+		return false
+	}
+	if prebuilt, ok := module.(android.PrebuiltInterface); ok {
+		if p := prebuilt.Prebuilt(); p != nil {
+			return p.UsePrebuilt()
+		}
+	}
+	return true
+}
+
 func (b *bootJarsSingleton) GenerateBuildActions(ctx android.SingletonContext) {
 	config := ctx.Config()
 	if config.SkipBootJarsCheck() {
 		return
 	}
 
-	// Populate a map from module name to APEX from the boot jars. If there is a problem
-	// such as duplicate modules then fail and return immediately.
+	// Populate a map from module name to APEX from the boot jars. If there is a
+	// problem such as duplicate modules then fail and return immediately. Note
+	// that both module and APEX names are tracked by base names here, so we need
+	// to be careful to remove "prebuilt_" prefixes when comparing them with
+	// actual modules and APEX bundles.
 	moduleToApex := make(map[string]string)
 	if !populateMapFromConfiguredJarList(ctx, moduleToApex, config.NonUpdatableBootJars(), "BootJars") ||
 		!populateMapFromConfiguredJarList(ctx, moduleToApex, config.UpdatableBootJars(), "UpdatableBootJars") {
@@ -69,10 +91,14 @@
 	// Scan all the modules looking for the module/apex variants corresponding to the
 	// boot jars.
 	ctx.VisitAllModules(func(module android.Module) {
-		name := ctx.ModuleName(module)
+		if !isActiveModule(module) {
+			return
+		}
+
+		name := android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName(module))
 		if apex, ok := moduleToApex[name]; ok {
 			apexInfo := ctx.ModuleProvider(module, android.ApexInfoProvider).(android.ApexInfo)
-			if (apex == "platform" && apexInfo.IsForPlatform()) || apexInfo.InApex(apex) {
+			if (apex == "platform" && apexInfo.IsForPlatform()) || apexInfo.InApexByBaseName(apex) {
 				// The module name/apex variant should be unique in the system but double check
 				// just in case something has gone wrong.
 				if existing, ok := nameToApexVariant[name]; ok {
diff --git a/java/dexpreopt.go b/java/dexpreopt.go
index b5830c7..ac00592 100644
--- a/java/dexpreopt.go
+++ b/java/dexpreopt.go
@@ -30,6 +30,7 @@
 	installPath         android.InstallPath
 	uncompressedDex     bool
 	isSDKLibrary        bool
+	isApp               bool
 	isTest              bool
 	isPresignedPrebuilt bool
 
@@ -38,6 +39,11 @@
 	classLoaderContexts dexpreopt.ClassLoaderContextMap
 
 	builtInstalled string
+
+	// A path to a dexpreopt.config file generated by Soong for libraries that may be used as a
+	// <uses-library> by Make modules. The path is passed to Make via LOCAL_SOONG_DEXPREOPT_CONFIG
+	// variable. If the path is nil, no config is generated (which is the case for apps and tests).
+	configPath android.WritablePath
 }
 
 type DexpreoptProperties struct {
@@ -117,7 +123,40 @@
 	// the dexpreopter struct hasn't been fully initialized before we're called,
 	// e.g. in aar.go. This keeps the behaviour that dexpreopting is effectively
 	// disabled, even if installable is true.
-	if d.dexpreoptDisabled(ctx) || d.installPath.Base() == "." {
+	if d.installPath.Base() == "." {
+		return
+	}
+
+	dexLocation := android.InstallPathToOnDevicePath(ctx, d.installPath)
+
+	buildPath := android.PathForModuleOut(ctx, "dexpreopt", ctx.ModuleName()+".jar").OutputPath
+
+	providesUsesLib := ctx.ModuleName()
+	if ulib, ok := ctx.Module().(ProvidesUsesLib); ok {
+		name := ulib.ProvidesUsesLib()
+		if name != nil {
+			providesUsesLib = *name
+		}
+	}
+
+	if !d.isApp && !d.isTest {
+		// Slim dexpreopt config is serialized to dexpreopt.config files and used by
+		// dex_preopt_config_merger.py to get information about <uses-library> dependencies.
+		// Note that it might be needed even if dexpreopt is disabled for this module.
+		slimDexpreoptConfig := &dexpreopt.ModuleConfig{
+			Name:                 ctx.ModuleName(),
+			DexLocation:          dexLocation,
+			BuildPath:            buildPath,
+			EnforceUsesLibraries: d.enforceUsesLibs,
+			ProvidesUsesLibrary:  providesUsesLib,
+			ClassLoaderContexts:  d.classLoaderContexts,
+			// The rest of the fields are not needed.
+		}
+		d.configPath = android.PathForModuleOut(ctx, "dexpreopt", "dexpreopt.config")
+		dexpreopt.WriteSlimModuleConfigForMake(ctx, slimDexpreoptConfig, d.configPath)
+	}
+
+	if d.dexpreoptDisabled(ctx) {
 		return
 	}
 
@@ -157,8 +196,6 @@
 	// The image locations for all Android variants are identical.
 	imageLocations := bootImage.getAnyAndroidVariant().imageLocations()
 
-	dexLocation := android.InstallPathToOnDevicePath(ctx, d.installPath)
-
 	var profileClassListing android.OptionalPath
 	var profileBootListing android.OptionalPath
 	profileIsTextListing := false
@@ -177,10 +214,11 @@
 		}
 	}
 
+	// Full dexpreopt config, used to create dexpreopt build rules.
 	dexpreoptConfig := &dexpreopt.ModuleConfig{
 		Name:            ctx.ModuleName(),
 		DexLocation:     dexLocation,
-		BuildPath:       android.PathForModuleOut(ctx, "dexpreopt", ctx.ModuleName()+".jar").OutputPath,
+		BuildPath:       buildPath,
 		DexPath:         dexJarFile,
 		ManifestPath:    d.manifestFile,
 		UncompressedDex: d.uncompressedDex,
@@ -192,6 +230,7 @@
 		ProfileBootListing:   profileBootListing,
 
 		EnforceUsesLibraries: d.enforceUsesLibs,
+		ProvidesUsesLibrary:  providesUsesLib,
 		ClassLoaderContexts:  d.classLoaderContexts,
 
 		Archs:                   archs,
diff --git a/java/dexpreopt_bootjars.go b/java/dexpreopt_bootjars.go
index 78d9d02..2a7eb42 100644
--- a/java/dexpreopt_bootjars.go
+++ b/java/dexpreopt_bootjars.go
@@ -392,22 +392,6 @@
 	dexpreoptConfigForMake android.WritablePath
 }
 
-// Accessor function for the apex package. Returns nil if dexpreopt is disabled.
-func DexpreoptedArtApexJars(ctx android.BuilderContext) map[android.ArchType]android.OutputPaths {
-	if SkipDexpreoptBootJars(ctx) {
-		return nil
-	}
-	// Include dexpreopt files for the primary boot image.
-	files := map[android.ArchType]android.OutputPaths{}
-	for _, variant := range artBootImageConfig(ctx).variants {
-		// We also generate boot images for host (for testing), but we don't need those in the apex.
-		if variant.target.Os == android.Android {
-			files[variant.target.Arch.ArchType] = variant.imagesDeps
-		}
-	}
-	return files
-}
-
 // Provide paths to boot images for use by modules that depend upon them.
 //
 // The build rules are created in GenerateSingletonBuildActions().
@@ -486,7 +470,7 @@
 			// A platform variant is required but this is for an apex so ignore it.
 			return -1, nil
 		}
-	} else if !android.InList(requiredApex, apexInfo.InApexes) {
+	} else if !apexInfo.InApexByBaseName(requiredApex) {
 		// An apex variant for a specific apex is required but this is the wrong apex.
 		return -1, nil
 	}
@@ -496,7 +480,7 @@
 
 	switch image.name {
 	case artBootImageName:
-		if len(apexInfo.InApexes) > 0 && allHavePrefix(apexInfo.InApexes, "com.android.art") {
+		if apexInfo.InApexByBaseName("com.android.art") || apexInfo.InApexByBaseName("com.android.art.debug") || apexInfo.InApexByBaseName("com.android.art,testing") {
 			// ok: found the jar in the ART apex
 		} else if name == "jacocoagent" && ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
 			// exception (skip and continue): Jacoco platform variant for a coverage build
@@ -523,21 +507,17 @@
 	return index, jar.DexJarBuildPath()
 }
 
-func allHavePrefix(list []string, prefix string) bool {
-	for _, s := range list {
-		if s != prefix && !strings.HasPrefix(s, prefix+".") {
-			return false
-		}
-	}
-	return true
-}
-
 // buildBootImage takes a bootImageConfig, creates rules to build it, and returns the image.
 func buildBootImage(ctx android.SingletonContext, image *bootImageConfig) *bootImageConfig {
 	// Collect dex jar paths for the boot image modules.
 	// This logic is tested in the apex package to avoid import cycle apex <-> java.
 	bootDexJars := make(android.Paths, image.modules.Len())
+
 	ctx.VisitAllModules(func(module android.Module) {
+		if !isActiveModule(module) {
+			return
+		}
+
 		if i, j := getBootImageJar(ctx, image, module); i != -1 {
 			if existing := bootDexJars[i]; existing != nil {
 				ctx.Errorf("Multiple dex jars found for %s:%s - %s and %s",
@@ -867,6 +847,9 @@
 		// Collect `permitted_packages` for updatable boot jars.
 		var updatablePackages []string
 		ctx.VisitAllModules(func(module android.Module) {
+			if !isActiveModule(module) {
+				return
+			}
 			if j, ok := module.(PermittedPackagesForUpdatableBootJars); ok {
 				name := ctx.ModuleName(module)
 				if i := android.IndexList(name, updatableModules); i != -1 {
diff --git a/java/dexpreopt_test.go b/java/dexpreopt_test.go
index 5550a4c..a9e0773 100644
--- a/java/dexpreopt_test.go
+++ b/java/dexpreopt_test.go
@@ -148,7 +148,7 @@
 		t.Run(test.name, func(t *testing.T) {
 			ctx, _ := testJava(t, test.bp)
 
-			dexpreopt := ctx.ModuleForTests("foo", "android_common").MaybeDescription("dexpreopt")
+			dexpreopt := ctx.ModuleForTests("foo", "android_common").MaybeRule("dexpreopt")
 			enabled := dexpreopt.Rule != nil
 
 			if enabled != test.enabled {
diff --git a/java/hiddenapi.go b/java/hiddenapi.go
index 71f1e57..2cd025e 100644
--- a/java/hiddenapi.go
+++ b/java/hiddenapi.go
@@ -28,10 +28,40 @@
 }, "outFlag", "stubAPIFlags")
 
 type hiddenAPI struct {
-	bootDexJarPath  android.Path
-	flagsCSVPath    android.Path
-	indexCSVPath    android.Path
+	// The path to the dex jar that is in the boot class path. If this is nil then the associated
+	// module is not a boot jar, but could be one of the <x>-hiddenapi modules that provide additional
+	// annotations for the <x> boot dex jar but which do not actually provide a boot dex jar
+	// themselves.
+	bootDexJarPath android.Path
+
+	// The path to the CSV file that contains mappings from Java signature to various flags derived
+	// from annotations in the source, e.g. whether it is public or the sdk version above which it
+	// can no longer be used.
+	//
+	// It is created by the Class2NonSdkList tool which processes the .class files in the class
+	// implementation jar looking for UnsupportedAppUsage and CovariantReturnType annotations. The
+	// tool also consumes the hiddenAPISingletonPathsStruct.stubFlags file in order to perform
+	// consistency checks on the information in the annotations and to filter out bridge methods
+	// that are already part of the public API.
+	flagsCSVPath android.Path
+
+	// The path to the CSV file that contains mappings from Java signature to the value of properties
+	// specified on UnsupportedAppUsage annotations in the source.
+	//
+	// Like the flagsCSVPath file this is also created by the Class2NonSdkList in the same way.
+	// Although the two files could potentially be created in a single invocation of the
+	// Class2NonSdkList at the moment they are created using their own invocation, with the behavior
+	// being determined by the property that is used.
 	metadataCSVPath android.Path
+
+	// The path to the CSV file that contains mappings from Java signature to source location
+	// information.
+	//
+	// It is created by the merge_csv tool which processes the class implementation jar, extracting
+	// all the files ending in .uau (which are CSV files) and merges them together. The .uau files are
+	// created by the unsupported app usage annotation processor during compilation of the class
+	// implementation jar.
+	indexCSVPath android.Path
 }
 
 func (h *hiddenAPI) flagsCSV() android.Path {
@@ -78,11 +108,9 @@
 		// not on the list then that will cause failures in the CtsHiddenApiBlacklist...
 		// tests.
 		if inList(bootJarName, ctx.Config().BootJars()) {
-			// Derive the greylist from classes jar.
-			flagsCSV := android.PathForModuleOut(ctx, "hiddenapi", "flags.csv")
-			metadataCSV := android.PathForModuleOut(ctx, "hiddenapi", "metadata.csv")
-			indexCSV := android.PathForModuleOut(ctx, "hiddenapi", "index.csv")
-			h.hiddenAPIGenerateCSV(ctx, flagsCSV, metadataCSV, indexCSV, implementationJar)
+			// Create ninja rules to generate various CSV files needed by hiddenapi and store the paths
+			// in the hiddenAPI structure.
+			h.hiddenAPIGenerateCSV(ctx, implementationJar)
 
 			// If this module is actually on the boot jars list and not providing
 			// hiddenapi information for a module on the boot jars list then encode
@@ -106,9 +134,10 @@
 	return dexJar
 }
 
-func (h *hiddenAPI) hiddenAPIGenerateCSV(ctx android.ModuleContext, flagsCSV, metadataCSV, indexCSV android.WritablePath, classesJar android.Path) {
+func (h *hiddenAPI) hiddenAPIGenerateCSV(ctx android.ModuleContext, classesJar android.Path) {
 	stubFlagsCSV := hiddenAPISingletonPaths(ctx).stubFlags
 
+	flagsCSV := android.PathForModuleOut(ctx, "hiddenapi", "flags.csv")
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        hiddenAPIGenerateCSVRule,
 		Description: "hiddenapi flags",
@@ -122,6 +151,7 @@
 	})
 	h.flagsCSVPath = flagsCSV
 
+	metadataCSV := android.PathForModuleOut(ctx, "hiddenapi", "metadata.csv")
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        hiddenAPIGenerateCSVRule,
 		Description: "hiddenapi metadata",
@@ -135,6 +165,7 @@
 	})
 	h.metadataCSVPath = metadataCSV
 
+	indexCSV := android.PathForModuleOut(ctx, "hiddenapi", "index.csv")
 	rule := android.NewRuleBuilder(pctx, ctx)
 	rule.Command().
 		BuiltTool("merge_csv").
diff --git a/java/hiddenapi_singleton.go b/java/hiddenapi_singleton.go
index 4bd255c..ccb8745 100644
--- a/java/hiddenapi_singleton.go
+++ b/java/hiddenapi_singleton.go
@@ -28,9 +28,64 @@
 }
 
 type hiddenAPISingletonPathsStruct struct {
-	flags     android.OutputPath
-	index     android.OutputPath
-	metadata  android.OutputPath
+	// The path to the CSV file that contains the flags that will be encoded into the dex boot jars.
+	//
+	// It is created by the generate_hiddenapi_lists.py tool that is passed the stubFlags along with
+	// a number of additional files that are used to augment the information in the stubFlags with
+	// manually curated data.
+	flags android.OutputPath
+
+	// The path to the CSV index file that contains mappings from Java signature to source location
+	// information for all Java elements annotated with the UnsupportedAppUsage annotation in the
+	// source of all the boot jars.
+	//
+	// It is created by the merge_csv tool which merges all the hiddenAPI.indexCSVPath files that have
+	// been created by the rest of the build. That includes the index files generated for
+	// <x>-hiddenapi modules.
+	index android.OutputPath
+
+	// The path to the CSV metadata file that contains mappings from Java signature to the value of
+	// properties specified on UnsupportedAppUsage annotations in the source of all the boot jars.
+	//
+	// It is created by the merge_csv tool which merges all the hiddenAPI.metadataCSVPath files that
+	// have been created by the rest of the build. That includes the metadata files generated for
+	// <x>-hiddenapi modules.
+	metadata android.OutputPath
+
+	// The path to the CSV metadata file that contains mappings from Java signature to flags obtained
+	// from the public, system and test API stubs.
+	//
+	// This is created by the hiddenapi tool which is given dex files for the public, system and test
+	// API stubs (including product specific stubs) along with dex boot jars, so does not include
+	// <x>-hiddenapi modules. For each API surface (i.e. public, system, test) it records which
+	// members in the dex boot jars match a member in the dex stub jars for that API surface and then
+	// outputs a file containing the signatures of all members in the dex boot jars along with the
+	// flags that indicate which API surface it belongs, if any.
+	//
+	// e.g. a dex member that matches a member in the public dex stubs would have flags
+	// "public-api,system-api,test-api" set (as system and test are both supersets of public). A dex
+	// member that didn't match a member in any of the dex stubs is still output it just has an empty
+	// set of flags.
+	//
+	// The notion of matching is quite complex, it is not restricted to just exact matching but also
+	// follows the Java inheritance rules. e.g. if a method is public then all overriding/implementing
+	// methods are also public. If an interface method is public and a class inherits an
+	// implementation of that method from a super class then that super class method is also public.
+	// That ensures that any method that can be called directly by an App through a public method is
+	// visible to that App.
+	//
+	// Propagating the visibility of members across the inheritance hierarchy at build time will cause
+	// problems when modularizing and unbundling as it that propagation can cross module boundaries.
+	// e.g. Say that a private framework class implements a public interface and inherits an
+	// implementation of one of its methods from a core platform ART class. In that case the ART
+	// implementation method needs to be marked as public which requires the build to have access to
+	// the framework implementation classes at build time. The work to rectify this is being tracked
+	// at http://b/178693149.
+	//
+	// This file (or at least those items marked as being in the public-api) is used by hiddenapi when
+	// creating the metadata and flags for the individual modules in order to perform consistency
+	// checks and filter out bridge methods that are part of the public API. The latter relies on the
+	// propagation of visibility across the inheritance hierarchy.
 	stubFlags android.OutputPath
 }
 
diff --git a/java/testing.go b/java/testing.go
index 31ff47f..5fcf84c 100644
--- a/java/testing.go
+++ b/java/testing.go
@@ -219,16 +219,6 @@
 		dex_bootjars {
 			name: "dex_bootjars",
 		}
-
-		boot_image {
-			name: "art-boot-image",
-			image_name: "art",
-		}
-
-		boot_image {
-			name: "framework-boot-image",
-			image_name: "boot",
-		}
 `
 
 	return bp
diff --git a/rust/androidmk.go b/rust/androidmk.go
index 0307727..1a286f7 100644
--- a/rust/androidmk.go
+++ b/rust/androidmk.go
@@ -18,6 +18,7 @@
 	"path/filepath"
 
 	"android/soong/android"
+	"android/soong/cc"
 )
 
 type AndroidMkContext interface {
@@ -85,7 +86,8 @@
 }
 
 func (test *testDecorator) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkEntries) {
-	test.binaryDecorator.AndroidMk(ctx, ret)
+	ctx.SubAndroidMk(ret, test.binaryDecorator)
+
 	ret.Class = "NATIVE_TESTS"
 	ret.ExtraEntries = append(ret.ExtraEntries, func(entries *android.AndroidMkEntries) {
 		entries.AddCompatibilityTestSuites(test.Properties.Test_suites...)
@@ -95,7 +97,8 @@
 		entries.SetBoolIfTrue("LOCAL_DISABLE_AUTO_GENERATE_TEST_CONFIG", !BoolDefault(test.Properties.Auto_gen_config, true))
 		entries.SetBoolIfTrue("LOCAL_IS_UNIT_TEST", Bool(test.Properties.Test_options.Unit_test))
 	})
-	// TODO(chh): add test data with androidMkWriteTestData(test.data, ctx, ret)
+
+	cc.AndroidMkWriteTestData(test.data, ret)
 }
 
 func (library *libraryDecorator) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkEntries) {
diff --git a/rust/rust_test.go b/rust/rust_test.go
index fc7f47e..abc9af9 100644
--- a/rust/rust_test.go
+++ b/rust/rust_test.go
@@ -116,6 +116,7 @@
 		"foo.proto":       nil,
 		"liby.so":         nil,
 		"libz.so":         nil,
+		"data.txt":        nil,
 	}
 }
 
diff --git a/rust/test.go b/rust/test.go
index 35e04ff..92b4860 100644
--- a/rust/test.go
+++ b/rust/test.go
@@ -43,6 +43,10 @@
 	// installed into.
 	Test_suites []string `android:"arch_variant"`
 
+	// list of files or filegroup modules that provide data that should be installed alongside
+	// the test
+	Data []string `android:"path,arch_variant"`
+
 	// Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
 	// doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
 	// explicitly.
@@ -62,6 +66,12 @@
 	*binaryDecorator
 	Properties TestProperties
 	testConfig android.Path
+
+	data []android.DataPath
+}
+
+func (test *testDecorator) dataPaths() []android.DataPath {
+	return test.data
 }
 
 func (test *testDecorator) nativeCoverage() bool {
@@ -89,7 +99,6 @@
 	}
 
 	module.compiler = test
-	module.AddProperties(&test.Properties)
 	return module, test
 }
 
@@ -105,6 +114,12 @@
 		nil,
 		test.Properties.Auto_gen_config)
 
+	dataSrcPaths := android.PathsForModuleSrc(ctx, test.Properties.Data)
+
+	for _, dataSrcPath := range dataSrcPaths {
+		test.data = append(test.data, android.DataPath{SrcPath: dataSrcPath})
+	}
+
 	// default relative install path is module name
 	if !Bool(test.Properties.No_named_install_directory) {
 		test.baseCompiler.relative = ctx.ModuleName()
diff --git a/rust/test_test.go b/rust/test_test.go
index fea2ad0..892761a 100644
--- a/rust/test_test.go
+++ b/rust/test_test.go
@@ -26,6 +26,7 @@
 		rust_test_host {
 			name: "my_test",
 			srcs: ["foo.rs"],
+			data: ["data.txt"],
 		}`)
 
 	testingModule := ctx.ModuleForTests("my_test", "linux_glibc_x86_64")
@@ -34,6 +35,12 @@
 	if !strings.Contains(outPath, expectedOut) {
 		t.Errorf("wrong output path: %v;  expected: %v", outPath, expectedOut)
 	}
+
+	dataPaths := testingModule.Module().(*Module).compiler.(*testDecorator).dataPaths()
+	if len(dataPaths) != 1 {
+		t.Errorf("expected exactly one test data file. test data files: [%s]", dataPaths)
+		return
+	}
 }
 
 func TestRustTestLinkage(t *testing.T) {
diff --git a/ui/build/build.go b/ui/build/build.go
index 926da31..215a6c8 100644
--- a/ui/build/build.go
+++ b/ui/build/build.go
@@ -252,6 +252,11 @@
 	if what&BuildSoong != 0 {
 		// Run Soong
 		runSoong(ctx, config)
+
+		if config.Environment().IsEnvTrue("GENERATE_BAZEL_FILES") {
+			// Return early, if we're using Soong as the bp2build converter.
+			return
+		}
 	}
 
 	if what&BuildKati != 0 {
diff --git a/ui/build/soong.go b/ui/build/soong.go
index 6a93672..899ab5d 100644
--- a/ui/build/soong.go
+++ b/ui/build/soong.go
@@ -169,8 +169,11 @@
 	// This build generates <builddir>/build.ninja, which is used later by build/soong/ui/build/build.go#Build().
 	ninja("bootstrap", ".bootstrap/build.ninja")
 
-	soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
-	logSoongBuildMetrics(ctx, soongBuildMetrics)
+	var soongBuildMetrics *soong_metrics_proto.SoongBuildMetrics
+	if shouldCollectBuildSoongMetrics(config) {
+		soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
+		logSoongBuildMetrics(ctx, soongBuildMetrics)
+	}
 
 	distGzipFile(ctx, config, config.SoongNinjaFile(), "soong")
 
@@ -179,11 +182,16 @@
 		distGzipFile(ctx, config, config.SoongMakeVarsMk(), "soong")
 	}
 
-	if ctx.Metrics != nil {
+	if shouldCollectBuildSoongMetrics(config) && ctx.Metrics != nil {
 		ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
 	}
 }
 
+func shouldCollectBuildSoongMetrics(config Config) bool {
+	// Do not collect metrics protobuf if the soong_build binary ran as the bp2build converter.
+	return config.Environment().IsFalse("GENERATE_BAZEL_FILES")
+}
+
 func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
 	soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
 	buf, err := ioutil.ReadFile(soongBuildMetricsFile)