Merge "Update build to new location of hiddenapi config files"
diff --git a/Android.bp b/Android.bp
index 9d5b07d..8f7f3e2 100644
--- a/Android.bp
+++ b/Android.bp
@@ -47,101 +47,6 @@
 //
 
 toolchain_library {
-    name: "libatomic",
-    defaults: ["linux_bionic_supported"],
-    vendor_available: true,
-    product_available: true,
-    ramdisk_available: true,
-    vendor_ramdisk_available: true,
-    recovery_available: true,
-    native_bridge_supported: true,
-
-    arch: {
-        arm: {
-            src: "prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.9/arm-linux-androideabi/lib/libatomic.a",
-        },
-        arm64: {
-            src: "prebuilts/gcc/linux-x86/aarch64/aarch64-linux-android-4.9/aarch64-linux-android/lib64/libatomic.a",
-        },
-        x86: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/x86_64-linux-android/lib/libatomic.a",
-        },
-        x86_64: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/x86_64-linux-android/lib64/libatomic.a",
-        },
-    },
-}
-
-toolchain_library {
-    name: "libgcc",
-    defaults: ["linux_bionic_supported"],
-    vendor_available: true,
-    product_available: true,
-    recovery_available: true,
-    native_bridge_supported: true,
-    apex_available: [
-        "//apex_available:platform",
-        "//apex_available:anyapex",
-    ],
-
-    arch: {
-        arm: {
-            src: "prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.9/lib/gcc/arm-linux-androideabi/4.9.x/libgcc.a",
-        },
-        arm64: {
-            src: "prebuilts/gcc/linux-x86/aarch64/aarch64-linux-android-4.9/lib/gcc/aarch64-linux-android/4.9.x/libgcc.a",
-        },
-        x86: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/lib/gcc/x86_64-linux-android/4.9.x/32/libgcc.a",
-        },
-        x86_64: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/lib/gcc/x86_64-linux-android/4.9.x/libgcc.a",
-        },
-    },
-}
-
-toolchain_library {
-    name: "libgcc_stripped",
-    defaults: ["linux_bionic_supported"],
-    vendor_available: true,
-    product_available: true,
-    ramdisk_available: true,
-    vendor_ramdisk_available: true,
-    recovery_available: true,
-    native_bridge_supported: true,
-    sdk_version: "current",
-
-    arch: {
-        arm: {
-            src: "prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.9/lib/gcc/arm-linux-androideabi/4.9.x/libgcc.a",
-            repack_objects_to_keep: [],
-            enabled: false,
-        },
-        arm64: {
-            src: "prebuilts/gcc/linux-x86/aarch64/aarch64-linux-android-4.9/lib/gcc/aarch64-linux-android/4.9.x/libgcc.a",
-            repack_objects_to_keep: [
-                "unwind-dw2.o",
-                "unwind-dw2-fde-dip.o",
-            ],
-        },
-        x86: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/lib/gcc/x86_64-linux-android/4.9.x/32/libgcc.a",
-            repack_objects_to_keep: [
-                "unwind-dw2.o",
-                "unwind-dw2-fde-dip.o",
-            ],
-        },
-        x86_64: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/lib/gcc/x86_64-linux-android/4.9.x/libgcc.a",
-            repack_objects_to_keep: [
-                "unwind-dw2.o",
-                "unwind-dw2-fde-dip.o",
-            ],
-        },
-    },
-}
-
-toolchain_library {
     name: "libwinpthread",
     host_supported: true,
     enabled: false,
@@ -159,26 +64,6 @@
     notice: ":mingw-libwinpthread-notice",
 }
 
-toolchain_library {
-    name: "libgcov",
-    defaults: ["linux_bionic_supported"],
-
-    arch: {
-        arm: {
-            src: "prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.9/lib/gcc/arm-linux-androideabi/4.9.x/libgcov.a",
-        },
-        arm64: {
-            src: "prebuilts/gcc/linux-x86/aarch64/aarch64-linux-android-4.9/lib/gcc/aarch64-linux-android/4.9.x/libgcov.a",
-        },
-        x86: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/lib/gcc/x86_64-linux-android/4.9.x/32/libgcov.a",
-        },
-        x86_64: {
-            src: "prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/lib/gcc/x86_64-linux-android/4.9.x/libgcov.a",
-        },
-    },
-}
-
 kernel_headers {
     name: "device_kernel_headers",
     vendor: true,
diff --git a/android/arch.go b/android/arch.go
index 3eff5d5..6826f3b 100644
--- a/android/arch.go
+++ b/android/arch.go
@@ -167,7 +167,8 @@
 	return archType
 }
 
-// ArchTypeList returns the 4 supported ArchTypes for arm, arm64, x86 and x86_64.
+// ArchTypeList returns the a slice copy of the 4 supported ArchTypes for arm,
+// arm64, x86 and x86_64.
 func ArchTypeList() []ArchType {
 	return append([]ArchType(nil), archTypeList...)
 }
@@ -266,7 +267,7 @@
 
 		DefaultDisabled: defDisabled,
 	}
-	OsTypeList = append(OsTypeList, os)
+	osTypeList = append(osTypeList, os)
 
 	if _, found := commonTargetMap[name]; found {
 		panic(fmt.Errorf("Found Os type duplicate during OsType registration: %q", name))
@@ -280,7 +281,7 @@
 
 // osByName returns the OsType that has the given name, or NoOsType if none match.
 func osByName(name string) OsType {
-	for _, os := range OsTypeList {
+	for _, os := range osTypeList {
 		if os.Name == name {
 			return os
 		}
@@ -312,9 +313,9 @@
 }()
 
 var (
-	// OsTypeList contains a list of all the supported OsTypes, including ones not supported
+	// osTypeList contains a list of all the supported OsTypes, including ones not supported
 	// by the current build host or the target device.
-	OsTypeList []OsType
+	osTypeList []OsType
 	// commonTargetMap maps names of OsTypes to the corresponding common Target, i.e. the
 	// Target with the same OsType and the common ArchType.
 	commonTargetMap = make(map[string]Target)
@@ -347,6 +348,11 @@
 	CommonArch = Arch{ArchType: Common}
 )
 
+// OsTypeList returns a slice copy of the supported OsTypes.
+func OsTypeList() []OsType {
+	return append([]OsType(nil), osTypeList...)
+}
+
 // Target specifies the OS and architecture that a module is being compiled for.
 type Target struct {
 	// Os the OS that the module is being compiled for (e.g. "linux_glibc", "android").
@@ -448,7 +454,7 @@
 	// Collect a list of OSTypes supported by this module based on the HostOrDevice value
 	// passed to InitAndroidArchModule and the device_supported and host_supported properties.
 	var moduleOSList []OsType
-	for _, os := range OsTypeList {
+	for _, os := range osTypeList {
 		for _, t := range mctx.Config().Targets[os] {
 			if base.supportsTarget(t) {
 				moduleOSList = append(moduleOSList, os)
@@ -838,7 +844,7 @@
 			"Arm_on_x86_64",
 			"Native_bridge",
 		}
-		for _, os := range OsTypeList {
+		for _, os := range osTypeList {
 			// Add all the OSes.
 			targets = append(targets, os.Field)
 
@@ -1742,7 +1748,7 @@
 		}
 
 		// Iterate over the supported OS types
-		for _, os := range OsTypeList {
+		for _, os := range osTypeList {
 			// e.g android, linux_bionic
 			field := os.Field
 
diff --git a/android/bazel.go b/android/bazel.go
index a08da0e..b2170be 100644
--- a/android/bazel.go
+++ b/android/bazel.go
@@ -174,8 +174,6 @@
 		"liblinker_debuggerd_stub",      // ruperts@, cc_library_static, depends on //system/libbase
 		"libbionic_tests_headers_posix", // ruperts@, cc_library_static
 		"libc_dns",                      // ruperts@, cc_library_static
-		"note_memtag_heap_async",        // cparsons@, cc_library_static
-		"note_memtag_heap_sync",         // cparsons@, cc_library_static
 	}
 
 	// Used for quicker lookups
diff --git a/android/bazel_handler.go b/android/bazel_handler.go
index 04b70d6..5b9d3bf 100644
--- a/android/bazel_handler.go
+++ b/android/bazel_handler.go
@@ -34,13 +34,6 @@
 	"android/soong/shared"
 )
 
-type CqueryRequestType int
-
-const (
-	getAllFiles CqueryRequestType = iota
-	getAllFilesAndCcObjectFiles
-)
-
 // Map key to describe bazel cquery requests.
 type cqueryKey struct {
 	label       string
@@ -481,7 +474,7 @@
     return id_string + ">>" + %s(target)
 `
 
-	for _, requestType := range cquery.RequestTypes {
+	for requestType, _ := range requestTypeToCqueryIdEntries {
 		labelMapName := requestType.Name() + "_Labels"
 		functionName := requestType.Name() + "_Fn"
 		labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
@@ -688,7 +681,7 @@
 	// Register bazel-owned build statements (obtained from the aquery invocation).
 	for index, buildStatement := range ctx.Config().BazelContext.BuildStatementsToRegister() {
 		if len(buildStatement.Command) < 1 {
-			panic(fmt.Sprintf("unhandled build statement: %s", buildStatement))
+			panic(fmt.Sprintf("unhandled build statement: %v", buildStatement))
 		}
 		rule := NewRuleBuilder(pctx, ctx)
 		cmd := rule.Command()
diff --git a/android/prebuilt.go b/android/prebuilt.go
index ebccaa7..8176299 100644
--- a/android/prebuilt.go
+++ b/android/prebuilt.go
@@ -82,6 +82,12 @@
 }
 
 func (p *Prebuilt) Name(name string) string {
+	return PrebuiltNameFromSource(name)
+}
+
+// PrebuiltNameFromSource returns the result of prepending the "prebuilt_" prefix to the supplied
+// name.
+func PrebuiltNameFromSource(name string) string {
 	return "prebuilt_" + name
 }
 
@@ -213,6 +219,26 @@
 	Prebuilt() *Prebuilt
 }
 
+// IsModulePreferred returns true if the given module is preferred.
+//
+// A source module is preferred if there is no corresponding prebuilt module or the prebuilt module
+// does not have "prefer: true".
+//
+// A prebuilt module is preferred if there is no corresponding source module or the prebuilt module
+// has "prefer: true".
+func IsModulePreferred(module Module) bool {
+	if module.IsReplacedByPrebuilt() {
+		// A source module that has been replaced by a prebuilt counterpart.
+		return false
+	}
+	if prebuilt, ok := module.(PrebuiltInterface); ok {
+		if p := prebuilt.Prebuilt(); p != nil {
+			return p.UsePrebuilt()
+		}
+	}
+	return true
+}
+
 func RegisterPrebuiltsPreArchMutators(ctx RegisterMutatorsContext) {
 	ctx.BottomUp("prebuilt_rename", PrebuiltRenameMutator).Parallel()
 }
diff --git a/apex/apex.go b/apex/apex.go
index 9d06e1c..bad382a 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -1049,6 +1049,16 @@
 	if a, ok := mctx.Module().(*apexBundle); ok && !a.vndkApex {
 		apexBundleName := mctx.ModuleName()
 		mctx.CreateVariations(apexBundleName)
+		if strings.HasPrefix(apexBundleName, "com.android.art") {
+			// Create an alias from the platform variant. This is done to make
+			// test_for dependencies work for modules that are split by the APEX
+			// mutator, since test_for dependencies always go to the platform variant.
+			// This doesn't happen for normal APEXes that are disjunct, so only do
+			// this for the overlapping ART APEXes.
+			// TODO(b/183882457): Remove this if the test_for functionality is
+			// refactored to depend on the proper APEX variants instead of platform.
+			mctx.CreateAliasVariation("", apexBundleName)
+		}
 	} else if o, ok := mctx.Module().(*OverrideApex); ok {
 		apexBundleName := o.GetOverriddenModuleName()
 		if apexBundleName == "" {
@@ -1056,6 +1066,10 @@
 			return
 		}
 		mctx.CreateVariations(apexBundleName)
+		if strings.HasPrefix(apexBundleName, "com.android.art") {
+			// TODO(b/183882457): See note for CreateAliasVariation above.
+			mctx.CreateAliasVariation("", apexBundleName)
+		}
 	}
 }
 
@@ -2925,9 +2939,7 @@
 		"com.google.android.material_material",
 		"com.google.android.material_material-nodeps",
 
-		"libatomic",
 		"libclang_rt",
-		"libgcc_stripped",
 		"libprofile-clang-extras",
 		"libprofile-clang-extras_ndk",
 		"libprofile-extras",
diff --git a/apex/apex_test.go b/apex/apex_test.go
index e47bd1e..87d551b 100644
--- a/apex/apex_test.go
+++ b/apex/apex_test.go
@@ -6947,6 +6947,56 @@
 	ensureLinkedLibIs("myprivlib", "android_arm64_armv8-a_shared", "out/soong/.intermediates/mylib/", "android_arm64_armv8-a_shared/mylib.so")
 }
 
+func TestTestForForLibInOtherApex(t *testing.T) {
+	// This case is only allowed for known overlapping APEXes, i.e. the ART APEXes.
+	_ = testApex(t, `
+		apex {
+			name: "com.android.art",
+			key: "myapex.key",
+			native_shared_libs: ["mylib"],
+			updatable: false,
+		}
+
+		apex {
+			name: "com.android.art.debug",
+			key: "myapex.key",
+			native_shared_libs: ["mylib", "mytestlib"],
+			updatable: false,
+		}
+
+		apex_key {
+			name: "myapex.key",
+			public_key: "testkey.avbpubkey",
+			private_key: "testkey.pem",
+		}
+
+		cc_library {
+			name: "mylib",
+			srcs: ["mylib.cpp"],
+			system_shared_libs: [],
+			stl: "none",
+			stubs: {
+				versions: ["1"],
+			},
+			apex_available: ["com.android.art", "com.android.art.debug"],
+		}
+
+		cc_library {
+			name: "mytestlib",
+			srcs: ["mylib.cpp"],
+			system_shared_libs: [],
+			shared_libs: ["mylib"],
+			stl: "none",
+			apex_available: ["com.android.art.debug"],
+			test_for: ["com.android.art"],
+		}
+	`,
+		android.MockFS{
+			"system/sepolicy/apex/com.android.art-file_contexts":       nil,
+			"system/sepolicy/apex/com.android.art.debug-file_contexts": nil,
+		}.AddToFixture())
+}
+
 // TODO(jungjw): Move this to proptools
 func intPtr(i int) *int {
 	return &i
diff --git a/apex/prebuilt.go b/apex/prebuilt.go
index 3280cd8..68f2859 100644
--- a/apex/prebuilt.go
+++ b/apex/prebuilt.go
@@ -250,7 +250,7 @@
 	// the unprefixed name is the one to use. If the unprefixed one turns out to be a source module
 	// and not a renamed prebuilt module then that will be detected and reported as an error when
 	// processing the dependency in ApexInfoMutator().
-	prebuiltName := "prebuilt_" + name
+	prebuiltName := android.PrebuiltNameFromSource(name)
 	if ctx.OtherModuleExists(prebuiltName) {
 		name = prebuiltName
 	}
diff --git a/bazel/cquery/request_type.go b/bazel/cquery/request_type.go
index bd1ece1..affb5ce 100644
--- a/bazel/cquery/request_type.go
+++ b/bazel/cquery/request_type.go
@@ -14,11 +14,6 @@
 	CcObjectFiles []string
 }
 
-var RequestTypes []RequestType = []RequestType{
-	GetOutputFiles,
-	GetOutputFilesAndCcObjectFiles,
-}
-
 type RequestType interface {
 	// Name returns a string name for this request type. Such request type names must be unique,
 	// and must only consist of alphanumeric characters.
@@ -83,7 +78,17 @@
 	splitString := strings.Split(rawString, "|")
 	outputFilesString := splitString[0]
 	ccObjectsString := splitString[1]
-	outputFiles = strings.Split(outputFilesString, ", ")
-	ccObjects = strings.Split(ccObjectsString, ", ")
+	outputFiles = splitOrEmpty(outputFilesString, ", ")
+	ccObjects = splitOrEmpty(ccObjectsString, ", ")
 	return GetOutputFilesAndCcObjectFiles_Result{outputFiles, ccObjects}
 }
+
+// splitOrEmpty is a modification of strings.Split() that returns an empty list
+// if the given string is empty.
+func splitOrEmpty(s string, sep string) []string {
+	if len(s) < 1 {
+		return []string{}
+	} else {
+		return strings.Split(s, sep)
+	}
+}
diff --git a/bp2build/cc_library_headers_conversion_test.go b/bp2build/cc_library_headers_conversion_test.go
index d828168..dbea37a 100644
--- a/bp2build/cc_library_headers_conversion_test.go
+++ b/bp2build/cc_library_headers_conversion_test.go
@@ -37,17 +37,6 @@
 	recovery_available: true,
 	native_bridge_supported: true,
 	src: "",
-}
-
-toolchain_library {
-	name: "libatomic",
-	defaults: ["linux_bionic_supported"],
-	vendor_available: true,
-	vendor_ramdisk_available: true,
-	product_available: true,
-	recovery_available: true,
-	native_bridge_supported: true,
-	src: "",
 }`
 )
 
diff --git a/bp2build/cc_library_static_conversion_test.go b/bp2build/cc_library_static_conversion_test.go
index 7bf5fd3..467b0b2 100644
--- a/bp2build/cc_library_static_conversion_test.go
+++ b/bp2build/cc_library_static_conversion_test.go
@@ -37,17 +37,6 @@
 	recovery_available: true,
 	native_bridge_supported: true,
 	src: "",
-}
-
-toolchain_library {
-	name: "libatomic",
-	defaults: ["linux_bionic_supported"],
-	vendor_available: true,
-	vendor_ramdisk_available: true,
-	product_available: true,
-	recovery_available: true,
-	native_bridge_supported: true,
-	src: "",
 }`
 )
 
diff --git a/cc/cc.go b/cc/cc.go
index 0f9a556..1ce83a9 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -1646,12 +1646,12 @@
 		c.hideApexVariantFromMake = true
 	}
 
+	c.makeLinkType = GetMakeLinkType(actx, c)
+
 	if c.maybeGenerateBazelActions(actx) {
 		return
 	}
 
-	c.makeLinkType = GetMakeLinkType(actx, c)
-
 	ctx := &moduleContext{
 		ModuleContext: actx,
 		moduleContextImpl: moduleContextImpl{
diff --git a/cc/cc_test.go b/cc/cc_test.go
index 235232e..465283d 100644
--- a/cc/cc_test.go
+++ b/cc/cc_test.go
@@ -2912,13 +2912,13 @@
 	// Check the shared version of lib2.
 	variant := "android_arm64_armv8-a_shared"
 	module := ctx.ModuleForTests("lib2", variant).Module().(*Module)
-	checkStaticLibs(t, []string{"lib1", "libc++demangle", "libclang_rt.builtins-aarch64-android", "libatomic"}, module)
+	checkStaticLibs(t, []string{"lib1", "libc++demangle", "libclang_rt.builtins-aarch64-android"}, module)
 
 	// Check the static version of lib2.
 	variant = "android_arm64_armv8-a_static"
 	module = ctx.ModuleForTests("lib2", variant).Module().(*Module)
 	// libc++_static is linked additionally.
-	checkStaticLibs(t, []string{"lib1", "libc++_static", "libc++demangle", "libclang_rt.builtins-aarch64-android", "libatomic"}, module)
+	checkStaticLibs(t, []string{"lib1", "libc++_static", "libc++demangle", "libclang_rt.builtins-aarch64-android"}, module)
 }
 
 var compilerFlagsTestCases = []struct {
diff --git a/cc/library.go b/cc/library.go
index 50fff7f..11b6737 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -425,11 +425,14 @@
 	if !ok {
 		return ok
 	}
-	if len(outputPaths) != 1 {
+	if len(outputPaths) > 1 {
 		// TODO(cparsons): This is actually expected behavior for static libraries with no srcs.
 		// We should support this.
-		ctx.ModuleErrorf("expected exactly one output file for '%s', but got %s", label, objPaths)
+		ctx.ModuleErrorf("expected at most one output file for '%s', but got %s", label, objPaths)
 		return false
+	} else if len(outputPaths) == 0 {
+		handler.module.outputFile = android.OptionalPath{}
+		return true
 	}
 	outputFilePath := android.PathForBazelOut(ctx, outputPaths[0])
 	handler.module.outputFile = android.OptionalPathForPath(outputFilePath)
@@ -453,7 +456,15 @@
 			Direct(outputFilePath).
 			Build(),
 	})
-	handler.module.outputFile = android.OptionalPathForPath(android.PathForBazelOut(ctx, objPaths[0]))
+	if i, ok := handler.module.linker.(snapshotLibraryInterface); ok {
+		// Dependencies on this library will expect collectedSnapshotHeaders to
+		// be set, otherwise validation will fail. For now, set this to an empty
+		// list.
+		// TODO(cparsons): More closely mirror the collectHeadersForSnapshot
+		// implementation.
+		i.(*libraryDecorator).collectedSnapshotHeaders = android.Paths{}
+	}
+
 	return ok
 }
 
diff --git a/cc/linker.go b/cc/linker.go
index 21281d2..ae33356 100644
--- a/cc/linker.go
+++ b/cc/linker.go
@@ -321,10 +321,9 @@
 	}
 
 	if ctx.toolchain().Bionic() {
-		// libclang_rt.builtins and libatomic have to be last on the command line
+		// libclang_rt.builtins has to be last on the command line
 		if !Bool(linker.Properties.No_libcrt) {
 			deps.LateStaticLibs = append(deps.LateStaticLibs, config.BuiltinsRuntimeLibrary(ctx.toolchain()))
-			deps.LateStaticLibs = append(deps.LateStaticLibs, "libatomic")
 		}
 
 		deps.SystemSharedLibs = linker.Properties.System_shared_libs
diff --git a/cc/testing.go b/cc/testing.go
index 6e35655..ff32bff 100644
--- a/cc/testing.go
+++ b/cc/testing.go
@@ -63,17 +63,6 @@
 func commonDefaultModules() string {
 	return `
 		toolchain_library {
-			name: "libatomic",
-			defaults: ["linux_bionic_supported"],
-			vendor_available: true,
-			vendor_ramdisk_available: true,
-			product_available: true,
-			recovery_available: true,
-			native_bridge_supported: true,
-			src: "",
-		}
-
-		toolchain_library {
 			name: "libcompiler_rt-extras",
 			vendor_available: true,
 			vendor_ramdisk_available: true,
@@ -200,29 +189,6 @@
 			srcs: [""],
 		}
 
-		toolchain_library {
-			name: "libgcc",
-			defaults: ["linux_bionic_supported"],
-			vendor_available: true,
-			product_available: true,
-			recovery_available: true,
-			src: "",
-			apex_available: [
-				"//apex_available:platform",
-				"//apex_available:anyapex",
-			],
-		}
-
-		toolchain_library {
-			name: "libgcc_stripped",
-			defaults: ["linux_bionic_supported"],
-			vendor_available: true,
-			product_available: true,
-			recovery_available: true,
-			sdk_version: "current",
-			src: "",
-		}
-
 		cc_library {
 			name: "libc",
 			defaults: ["linux_bionic_supported"],
@@ -398,16 +364,6 @@
 				"//apex_available:anyapex",
 			],
 		}
-		cc_library {
-			name: "libunwind_llvm",
-			no_libcrt: true,
-			nocrt: true,
-			system_shared_libs: [],
-			stl: "none",
-			vendor_available: true,
-			product_available: true,
-			recovery_available: true,
-		}
 
 		cc_defaults {
 			name: "crt_defaults",
diff --git a/cmd/pom2bp/pom2bp.go b/cmd/pom2bp/pom2bp.go
index d9116b0..d31489e 100644
--- a/cmd/pom2bp/pom2bp.go
+++ b/cmd/pom2bp/pom2bp.go
@@ -401,6 +401,8 @@
         {{- end}}
     ],
     {{- end}}
+    {{- else if not .IsHostOnly}}
+    min_sdk_version: "{{.DefaultMinSdkVersion}}",
     {{- end}}
 }
 `))
@@ -442,6 +444,8 @@
         {{- end}}
     ],
     {{- end}}
+    {{- else if not .IsHostOnly}}
+    min_sdk_version: "{{.DefaultMinSdkVersion}}",
     {{- end}}
 }
 
diff --git a/java/app.go b/java/app.go
index dcb3bc6..04406e7 100755
--- a/java/app.go
+++ b/java/app.go
@@ -380,7 +380,11 @@
 }
 
 func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
-	a.aapt.usesNonSdkApis = Bool(a.Module.deviceProperties.Platform_apis)
+	usePlatformAPI := proptools.Bool(a.Module.deviceProperties.Platform_apis)
+	if ctx.Module().(android.SdkContext).SdkVersion().Kind == android.SdkModule {
+		usePlatformAPI = true
+	}
+	a.aapt.usesNonSdkApis = usePlatformAPI
 
 	// Ask manifest_fixer to add or update the application element indicating this app has no code.
 	a.aapt.hasNoCode = !a.hasCode(ctx)
diff --git a/java/boot_jars.go b/java/boot_jars.go
index ac8107b..1fb3deb 100644
--- a/java/boot_jars.go
+++ b/java/boot_jars.go
@@ -56,16 +56,7 @@
 	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
+	return android.IsModulePreferred(module)
 }
 
 func (b *bootJarsSingleton) GenerateBuildActions(ctx android.SingletonContext) {
diff --git a/java/hiddenapi_singleton.go b/java/hiddenapi_singleton.go
index 9c51649..7e9477b 100644
--- a/java/hiddenapi_singleton.go
+++ b/java/hiddenapi_singleton.go
@@ -186,17 +186,6 @@
 	// We do not have prebuilts of the core platform api yet
 	corePlatformStubModules = append(corePlatformStubModules, "legacy.core.platform.api.stubs")
 
-	// Add the android.test.base to the set of stubs only if the android.test.base module is on
-	// the boot jars list as the runtime will only enforce hiddenapi access against modules on
-	// that list.
-	if inList("android.test.base", ctx.Config().BootJars()) {
-		if ctx.Config().AlwaysUsePrebuiltSdks() {
-			publicStubModules = append(publicStubModules, "sdk_public_current_android.test.base")
-		} else {
-			publicStubModules = append(publicStubModules, "android.test.base.stubs")
-		}
-	}
-
 	// Allow products to define their own stubs for custom product jars that apps can use.
 	publicStubModules = append(publicStubModules, ctx.Config().ProductHiddenAPIStubs()...)
 	systemStubModules = append(systemStubModules, ctx.Config().ProductHiddenAPIStubsSystem()...)
diff --git a/java/lint.go b/java/lint.go
index 475e8dc..30843dc 100644
--- a/java/lint.go
+++ b/java/lint.go
@@ -347,7 +347,7 @@
 
 	cmd := rule.Command()
 
-	cmd.Flag("JAVA_OPTS=-Xmx3072m").
+	cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
 		FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
 		FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
 		FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
@@ -392,6 +392,9 @@
 
 	rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
 
+	// The HTML output contains a date, remove it to make the output deterministic.
+	rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
+
 	rule.Build("lint", "lint")
 
 	l.outputs = lintOutputs{
diff --git a/java/lint_defaults.txt b/java/lint_defaults.txt
index 0786b7c..2de05b0 100644
--- a/java/lint_defaults.txt
+++ b/java/lint_defaults.txt
@@ -76,3 +76,5 @@
 
 # TODO(b/158390965): remove this when lint doesn't crash
 --disable_check HardcodedDebugMode
+
+--warning_check QueryAllPackagesPermission
diff --git a/java/platform_compat_config.go b/java/platform_compat_config.go
index c3d13ae..edfa146 100644
--- a/java/platform_compat_config.go
+++ b/java/platform_compat_config.go
@@ -232,15 +232,7 @@
 		}
 	}
 
-	// A prebuilt module should only be used when it is preferred.
-	if pi, ok := module.(android.PrebuiltInterface); ok {
-		if p := pi.Prebuilt(); p != nil {
-			return p.UsePrebuilt()
-		}
-	}
-
-	// Otherwise, a module should only be used if it has not been replaced by a prebuilt.
-	return !module.IsReplacedByPrebuilt()
+	return android.IsModulePreferred(module)
 }
 
 func (p *platformCompatConfigSingleton) GenerateBuildActions(ctx android.SingletonContext) {
diff --git a/java/sdk_library.go b/java/sdk_library.go
index 37b8d9f..eb9ba9b 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -1945,11 +1945,11 @@
 		}
 
 		// Add dependencies to the prebuilt stubs library
-		ctx.AddVariationDependencies(nil, apiScope.stubsTag, "prebuilt_"+module.stubsLibraryModuleName(apiScope))
+		ctx.AddVariationDependencies(nil, apiScope.stubsTag, android.PrebuiltNameFromSource(module.stubsLibraryModuleName(apiScope)))
 
 		if len(scopeProperties.Stub_srcs) > 0 {
 			// Add dependencies to the prebuilt stubs source library
-			ctx.AddVariationDependencies(nil, apiScope.stubsSourceTag, "prebuilt_"+module.stubsSourceModuleName(apiScope))
+			ctx.AddVariationDependencies(nil, apiScope.stubsSourceTag, android.PrebuiltNameFromSource(module.stubsSourceModuleName(apiScope)))
 		}
 	}
 }
diff --git a/java/system_modules.go b/java/system_modules.go
index 8c69051..320a2bb 100644
--- a/java/system_modules.go
+++ b/java/system_modules.go
@@ -236,7 +236,7 @@
 // modules.
 func (system *systemModulesImport) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
 	for _, lib := range system.properties.Libs {
-		ctx.AddVariationDependencies(nil, systemModulesLibsTag, "prebuilt_"+lib)
+		ctx.AddVariationDependencies(nil, systemModulesLibsTag, android.PrebuiltNameFromSource(lib))
 	}
 }
 
diff --git a/scripts/Android.bp b/scripts/Android.bp
index 9e8a602..c54b2bc 100644
--- a/scripts/Android.bp
+++ b/scripts/Android.bp
@@ -254,3 +254,22 @@
         "linker_config_proto",
     ],
 }
+
+python_binary_host {
+    name: "conv_classpaths_proto",
+    srcs: [
+        "conv_classpaths_proto.py",
+    ],
+    version: {
+        py2: {
+            enabled: false,
+        },
+        py3: {
+            enabled: true,
+            embedded_launcher: true,
+        },
+    },
+    libs: [
+        "classpaths_proto_python",
+    ],
+}
diff --git a/scripts/conv_classpaths_proto.py b/scripts/conv_classpaths_proto.py
new file mode 100644
index 0000000..f49fbbb
--- /dev/null
+++ b/scripts/conv_classpaths_proto.py
@@ -0,0 +1,76 @@
+#  Copyright (C) 2021 The Android Open Source Project
+#
+#  Licensed under the Apache License, Version 2.0 (the "License");
+#  you may not use this file except in compliance with the License.
+#  You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+import argparse
+
+import classpaths_pb2
+
+import google.protobuf.json_format as json_format
+import google.protobuf.text_format as text_format
+
+
+def encode(args):
+    pb = classpaths_pb2.ExportedClasspathsJars()
+    if args.format == 'json':
+        json_format.Parse(args.input.read(), pb)
+    else:
+        text_format.Parse(args.input.read(), pb)
+    args.output.write(pb.SerializeToString())
+    args.input.close()
+    args.output.close()
+
+
+def decode(args):
+    pb = classpaths_pb2.ExportedClasspathsJars()
+    pb.ParseFromString(args.input.read())
+    if args.format == 'json':
+        args.output.write(json_format.MessageToJson(pb))
+    else:
+        args.output.write(text_format.MessageToString(pb).encode('utf_8'))
+    args.input.close()
+    args.output.close()
+
+
+def main():
+    parser = argparse.ArgumentParser('Convert classpaths.proto messages between binary and '
+                                     'human-readable formats.')
+    parser.add_argument('-f', '--format', default='textproto',
+                        help='human-readable format, either json or text(proto), '
+                             'defaults to textproto')
+    parser.add_argument('-i', '--input',
+                        nargs='?', type=argparse.FileType('rb'), default=sys.stdin.buffer)
+    parser.add_argument('-o', '--output',
+                        nargs='?', type=argparse.FileType('wb'),
+                        default=sys.stdout.buffer)
+
+    subparsers = parser.add_subparsers()
+
+    parser_encode = subparsers.add_parser('encode',
+                                          help='convert classpaths protobuf message from '
+                                               'JSON to binary format',
+                                          parents=[parser], add_help=False)
+
+    parser_encode.set_defaults(func=encode)
+
+    parser_decode = subparsers.add_parser('decode',
+                                          help='print classpaths config in JSON format',
+                                          parents=[parser], add_help=False)
+    parser_decode.set_defaults(func=decode)
+
+    args = parser.parse_args()
+    args.func(args)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/sdk/update.go b/sdk/update.go
index 828c7b6..522a888 100644
--- a/sdk/update.go
+++ b/sdk/update.go
@@ -1350,7 +1350,7 @@
 // Compute the list of possible os types that this sdk could support.
 func (s *sdk) getPossibleOsTypes() []android.OsType {
 	var osTypes []android.OsType
-	for _, osType := range android.OsTypeList {
+	for _, osType := range android.OsTypeList() {
 		if s.DeviceSupported() {
 			if osType.Class == android.Device && osType != android.Fuchsia {
 				osTypes = append(osTypes, osType)