Merge "Remove global variables from Blueprint."
diff --git a/android/Android.bp b/android/Android.bp
index 588ad5e..9f6ae02 100644
--- a/android/Android.bp
+++ b/android/Android.bp
@@ -12,6 +12,7 @@
         "soong",
         "soong-android-soongconfig",
         "soong-bazel",
+        "soong-cquery",
         "soong-shared",
         "soong-ui-metrics_proto",
     ],
diff --git a/android/bazel.go b/android/bazel.go
index 9939bd5..683495b 100644
--- a/android/bazel.go
+++ b/android/bazel.go
@@ -14,19 +14,49 @@
 
 package android
 
-import "android/soong/bazel"
+import (
+	"fmt"
+	"io/ioutil"
+	"path/filepath"
+	"strings"
+
+	"github.com/google/blueprint"
+	"github.com/google/blueprint/proptools"
+)
+
+type bazelModuleProperties struct {
+	// The label of the Bazel target replacing this Soong module. When run in conversion mode, this
+	// will import the handcrafted build target into the autogenerated file. Note: this may result in
+	// a conflict due to duplicate targets if bp2build_available is also set.
+	Label *string
+
+	// If true, bp2build will generate the converted Bazel target for this module. Note: this may
+	// cause a conflict due to the duplicate targets if label is also set.
+	Bp2build_available bool
+}
+
+// Properties contains common module properties for Bazel migration purposes.
+type properties struct {
+	// In USE_BAZEL_ANALYSIS=1 mode, this represents the Bazel target replacing
+	// this Soong module.
+	Bazel_module bazelModuleProperties
+}
 
 // BazelModuleBase contains the property structs with metadata for modules which can be converted to
 // Bazel.
 type BazelModuleBase struct {
-	bazelProperties bazel.Properties
+	bazelProperties properties
 }
 
 // Bazelable is specifies the interface for modules that can be converted to Bazel.
 type Bazelable interface {
-	bazelProps() *bazel.Properties
-	GetBazelLabel() string
+	bazelProps() *properties
+	HasHandcraftedLabel() bool
+	HandcraftedLabel() string
+	GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string
 	ConvertWithBp2build() bool
+	GetBazelBuildFileContents(c Config, path, name string) (string, error)
+	ConvertedToBazel() bool
 }
 
 // BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
@@ -42,16 +72,60 @@
 }
 
 // bazelProps returns the Bazel properties for the given BazelModuleBase.
-func (b *BazelModuleBase) bazelProps() *bazel.Properties {
+func (b *BazelModuleBase) bazelProps() *properties {
 	return &b.bazelProperties
 }
 
+// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
+func (b *BazelModuleBase) HasHandcraftedLabel() bool {
+	return b.bazelProperties.Bazel_module.Label != nil
+}
+
+// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
+func (b *BazelModuleBase) HandcraftedLabel() string {
+	return proptools.String(b.bazelProperties.Bazel_module.Label)
+}
+
 // GetBazelLabel returns the Bazel label for the given BazelModuleBase.
-func (b *BazelModuleBase) GetBazelLabel() string {
-	return b.bazelProperties.Bazel_module.Label
+func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
+	if b.HasHandcraftedLabel() {
+		return b.HandcraftedLabel()
+	}
+	if b.ConvertWithBp2build() {
+		return bp2buildModuleLabel(ctx, module)
+	}
+	return "" // no label for unconverted module
 }
 
 // ConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build.
 func (b *BazelModuleBase) ConvertWithBp2build() bool {
 	return b.bazelProperties.Bazel_module.Bp2build_available
 }
+
+// GetBazelBuildFileContents returns the file contents of a hand-crafted BUILD file if available or
+// an error if there are errors reading the file.
+// TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
+// something more targeted based on the rule type and target.
+func (b *BazelModuleBase) GetBazelBuildFileContents(c Config, path, name string) (string, error) {
+	if !strings.Contains(b.HandcraftedLabel(), path) {
+		return "", fmt.Errorf("%q not found in bazel_module.label %q", path, b.HandcraftedLabel())
+	}
+	name = filepath.Join(path, name)
+	f, err := c.fs.Open(name)
+	if err != nil {
+		return "", err
+	}
+	defer f.Close()
+
+	data, err := ioutil.ReadAll(f)
+	if err != nil {
+		return "", err
+	}
+	return string(data[:]), nil
+}
+
+// ConvertedToBazel returns whether this module has been converted to Bazel, whether automatically
+// or manually
+func (b *BazelModuleBase) ConvertedToBazel() bool {
+	return b.ConvertWithBp2build() || b.HasHandcraftedLabel()
+}
diff --git a/android/bazel_handler.go b/android/bazel_handler.go
index 6675840..bbec389 100644
--- a/android/bazel_handler.go
+++ b/android/bazel_handler.go
@@ -26,6 +26,7 @@
 	"strings"
 	"sync"
 
+	"android/soong/bazel/cquery"
 	"github.com/google/blueprint/bootstrap"
 
 	"android/soong/bazel"
@@ -43,7 +44,7 @@
 // Map key to describe bazel cquery requests.
 type cqueryKey struct {
 	label       string
-	requestType CqueryRequestType
+	requestType cquery.RequestType
 	archType    ArchType
 }
 
@@ -53,14 +54,15 @@
 	// has been queued to be run later.
 
 	// Returns result files built by building the given bazel target label.
-	GetAllFiles(label string, archType ArchType) ([]string, bool)
+	GetOutputFiles(label string, archType ArchType) ([]string, bool)
 
 	// Returns object files produced by compiling the given cc-related target.
 	// Retrieves these files from Bazel's CcInfo provider.
 	GetCcObjectFiles(label string, archType ArchType) ([]string, bool)
 
-	// Returns the results of GetAllFiles and GetCcObjectFiles in a single query (in that order).
-	GetAllFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool)
+	// TODO(cparsons): Other cquery-related methods should be added here.
+	// Returns the results of GetOutputFiles and GetCcObjectFiles in a single query (in that order).
+	GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool)
 
 	// ** End cquery methods
 
@@ -109,7 +111,7 @@
 	AllFiles map[string][]string
 }
 
-func (m MockBazelContext) GetAllFiles(label string, archType ArchType) ([]string, bool) {
+func (m MockBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
 	result, ok := m.AllFiles[label]
 	return result, ok
 }
@@ -119,7 +121,7 @@
 	return result, ok
 }
 
-func (m MockBazelContext) GetAllFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
+func (m MockBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
 	result, ok := m.AllFiles[label]
 	return result, result, ok
 }
@@ -142,43 +144,42 @@
 
 var _ BazelContext = MockBazelContext{}
 
-func (bazelCtx *bazelContext) GetAllFiles(label string, archType ArchType) ([]string, bool) {
-	result, ok := bazelCtx.cquery(label, getAllFiles, archType)
+func (bazelCtx *bazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
+	rawString, ok := bazelCtx.cquery(label, cquery.GetOutputFiles, archType)
+	var ret []string
 	if ok {
-		bazelOutput := strings.TrimSpace(result)
-		return strings.Split(bazelOutput, ", "), true
-	} else {
-		return nil, false
+		bazelOutput := strings.TrimSpace(rawString)
+		ret = cquery.GetOutputFiles.ParseResult(bazelOutput).([]string)
 	}
+	return ret, ok
 }
 
 func (bazelCtx *bazelContext) GetCcObjectFiles(label string, archType ArchType) ([]string, bool) {
-	result, ok := bazelCtx.cquery(label, getCcObjectFiles, archType)
+	rawString, ok := bazelCtx.cquery(label, cquery.GetCcObjectFiles, archType)
+	var returnResult []string
 	if ok {
-		bazelOutput := strings.TrimSpace(result)
-		return strings.Split(bazelOutput, ", "), true
-	} else {
-		return nil, false
+		bazelOutput := strings.TrimSpace(rawString)
+		returnResult = cquery.GetCcObjectFiles.ParseResult(bazelOutput).([]string)
 	}
+	return returnResult, ok
 }
 
-func (bazelCtx *bazelContext) GetAllFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
-	var allFiles []string
+func (bazelCtx *bazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
+	var outputFiles []string
 	var ccObjects []string
 
-	result, ok := bazelCtx.cquery(label, getAllFilesAndCcObjectFiles, archType)
+	result, ok := bazelCtx.cquery(label, cquery.GetOutputFilesAndCcObjectFiles, archType)
 	if ok {
 		bazelOutput := strings.TrimSpace(result)
-		splitString := strings.Split(bazelOutput, "|")
-		allFilesString := splitString[0]
-		ccObjectsString := splitString[1]
-		allFiles = strings.Split(allFilesString, ", ")
-		ccObjects = strings.Split(ccObjectsString, ", ")
+		returnResult := cquery.GetOutputFilesAndCcObjectFiles.ParseResult(bazelOutput).(cquery.GetOutputFilesAndCcObjectFiles_Result)
+		outputFiles = returnResult.OutputFiles
+		ccObjects = returnResult.CcObjectFiles
 	}
-	return allFiles, ccObjects, ok
+
+	return outputFiles, ccObjects, ok
 }
 
-func (n noopBazelContext) GetAllFiles(label string, archType ArchType) ([]string, bool) {
+func (n noopBazelContext) GetOutputFiles(label string, archType ArchType) ([]string, bool) {
 	panic("unimplemented")
 }
 
@@ -186,7 +187,7 @@
 	panic("unimplemented")
 }
 
-func (n noopBazelContext) GetAllFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
+func (n noopBazelContext) GetOutputFilesAndCcObjectFiles(label string, archType ArchType) ([]string, []string, bool) {
 	panic("unimplemented")
 }
 
@@ -260,7 +261,7 @@
 // If the given request was already made (and the results are available), then
 // returns (result, true). If the request is queued but no results are available,
 // then returns ("", false).
-func (context *bazelContext) cquery(label string, requestType CqueryRequestType,
+func (context *bazelContext) cquery(label string, requestType cquery.RequestType,
 	archType ArchType) (string, bool) {
 	key := cqueryKey{label, requestType, archType}
 	if result, ok := context.results[key]; ok {
@@ -485,38 +486,66 @@
 		strings.Join(deps_arm, ",\n            ")))
 }
 
+func indent(original string) string {
+	result := ""
+	for _, line := range strings.Split(original, "\n") {
+		result += "  " + line + "\n"
+	}
+	return result
+}
+
 // Returns the file contents of the buildroot.cquery file that should be used for the cquery
 // expression in order to obtain information about buildroot and its dependencies.
 // The contents of this file depend on the bazelContext's requests; requests are enumerated
 // and grouped by their request type. The data retrieved for each label depends on its
 // request type.
 func (context *bazelContext) cqueryStarlarkFileContents() []byte {
+	requestTypeToCqueryIdEntries := map[cquery.RequestType][]string{}
+	for val, _ := range context.requests {
+		cqueryId := getCqueryId(val)
+		mapEntryString := fmt.Sprintf("%q : True", cqueryId)
+		requestTypeToCqueryIdEntries[val.requestType] =
+			append(requestTypeToCqueryIdEntries[val.requestType], mapEntryString)
+	}
+	labelRegistrationMapSection := ""
+	functionDefSection := ""
+	mainSwitchSection := ""
+
+	mapDeclarationFormatString := `
+%s = {
+  %s
+}
+`
+	functionDefFormatString := `
+def %s(target):
+%s
+`
+	mainSwitchSectionFormatString := `
+  if id_string in %s:
+    return id_string + ">>" + %s(target)
+`
+
+	for _, requestType := range cquery.RequestTypes {
+		labelMapName := requestType.Name() + "_Labels"
+		functionName := requestType.Name() + "_Fn"
+		labelRegistrationMapSection += fmt.Sprintf(mapDeclarationFormatString,
+			labelMapName,
+			strings.Join(requestTypeToCqueryIdEntries[requestType], ",\n  "))
+		functionDefSection += fmt.Sprintf(functionDefFormatString,
+			functionName,
+			indent(requestType.StarlarkFunctionBody()))
+		mainSwitchSection += fmt.Sprintf(mainSwitchSectionFormatString,
+			labelMapName, functionName)
+	}
+
 	formatString := `
 # This file is generated by soong_build. Do not edit.
-getAllFilesLabels = {
-  %s
-}
 
-getCcObjectFilesLabels = {
-  %s
-}
+# Label Map Section
+%s
 
-getAllFilesAndCcObjectFilesLabels = {
-  %s
-}
-
-def get_all_files(target):
-  return [f.path for f in target.files.to_list()]
-
-def get_cc_object_files(target):
-  result = []
-  linker_inputs = providers(target)["CcInfo"].linking_context.linker_inputs.to_list()
-
-  for linker_input in linker_inputs:
-    for library in linker_input.libraries:
-      for object in library.objects:
-        result += [object.path]
-  return result
+# Function Def Section
+%s
 
 def get_arch(target):
   buildoptions = build_options(target)
@@ -536,39 +565,16 @@
 
 def format(target):
   id_string = str(target.label) + "|" + get_arch(target)
-  if id_string in getAllFilesLabels:
-    return id_string + ">>" + ', '.join(get_all_files(target))
-  elif id_string in getCcObjectFilesLabels:
-    return id_string + ">>" + ', '.join(get_cc_object_files(target))
-  elif id_string in getAllFilesAndCcObjectFilesLabels:
-    return id_string + ">>" + ', '.join(get_all_files(target)) + "|" + ', '.join(get_cc_object_files(target))
-  else:
-    # This target was not requested via cquery, and thus must be a dependency
-    # of a requested target.
-    return id_string + ">>NONE"
+
+  # Main switch section
+  %s
+  # This target was not requested via cquery, and thus must be a dependency
+  # of a requested target.
+  return id_string + ">>NONE"
 `
-	var getAllFilesDeps []string = nil
-	var getCcObjectFilesDeps []string = nil
-	var getAllFilesAndCcObjectFilesDeps []string = nil
 
-	for val, _ := range context.requests {
-		labelWithArch := getCqueryId(val)
-		mapEntryString := fmt.Sprintf("%q : True", labelWithArch)
-		switch val.requestType {
-		case getAllFiles:
-			getAllFilesDeps = append(getAllFilesDeps, mapEntryString)
-		case getCcObjectFiles:
-			getCcObjectFilesDeps = append(getCcObjectFilesDeps, mapEntryString)
-		case getAllFilesAndCcObjectFiles:
-			getAllFilesAndCcObjectFilesDeps = append(getAllFilesAndCcObjectFilesDeps, mapEntryString)
-		}
-	}
-	getAllFilesDepsString := strings.Join(getAllFilesDeps, ",\n  ")
-	getCcObjectFilesDepsString := strings.Join(getCcObjectFilesDeps, ",\n  ")
-	getAllFilesAndCcObjectFilesDepsString := strings.Join(getAllFilesAndCcObjectFilesDeps, ",\n  ")
-
-	return []byte(fmt.Sprintf(formatString, getAllFilesDepsString, getCcObjectFilesDepsString,
-		getAllFilesAndCcObjectFilesDepsString))
+	return []byte(fmt.Sprintf(formatString, labelRegistrationMapSection, functionDefSection,
+		mainSwitchSection))
 }
 
 // Returns a workspace-relative path containing build-related metadata required
diff --git a/android/config.go b/android/config.go
index 3869a76..cae419b 100644
--- a/android/config.go
+++ b/android/config.go
@@ -1419,6 +1419,62 @@
 	return c.config.productVariables.RecoverySnapshotModules
 }
 
+func createDirsMap(previous map[string]bool, dirs []string) (map[string]bool, error) {
+	var ret = make(map[string]bool)
+	for _, dir := range dirs {
+		clean := filepath.Clean(dir)
+		if previous[clean] || ret[clean] {
+			return nil, fmt.Errorf("Duplicate entry %s", dir)
+		}
+		ret[clean] = true
+	}
+	return ret, nil
+}
+
+func (c *deviceConfig) createDirsMapOnce(onceKey OnceKey, previous map[string]bool, dirs []string) map[string]bool {
+	dirMap := c.Once(onceKey, func() interface{} {
+		ret, err := createDirsMap(previous, dirs)
+		if err != nil {
+			panic(fmt.Errorf("%s: %w", onceKey.key, err))
+		}
+		return ret
+	})
+	if dirMap == nil {
+		return nil
+	}
+	return dirMap.(map[string]bool)
+}
+
+var vendorSnapshotDirsExcludedKey = NewOnceKey("VendorSnapshotDirsExcludedMap")
+
+func (c *deviceConfig) VendorSnapshotDirsExcludedMap() map[string]bool {
+	return c.createDirsMapOnce(vendorSnapshotDirsExcludedKey, nil,
+		c.config.productVariables.VendorSnapshotDirsExcluded)
+}
+
+var vendorSnapshotDirsIncludedKey = NewOnceKey("VendorSnapshotDirsIncludedMap")
+
+func (c *deviceConfig) VendorSnapshotDirsIncludedMap() map[string]bool {
+	excludedMap := c.VendorSnapshotDirsExcludedMap()
+	return c.createDirsMapOnce(vendorSnapshotDirsIncludedKey, excludedMap,
+		c.config.productVariables.VendorSnapshotDirsIncluded)
+}
+
+var recoverySnapshotDirsExcludedKey = NewOnceKey("RecoverySnapshotDirsExcludedMap")
+
+func (c *deviceConfig) RecoverySnapshotDirsExcludedMap() map[string]bool {
+	return c.createDirsMapOnce(recoverySnapshotDirsExcludedKey, nil,
+		c.config.productVariables.RecoverySnapshotDirsExcluded)
+}
+
+var recoverySnapshotDirsIncludedKey = NewOnceKey("RecoverySnapshotDirsIncludedMap")
+
+func (c *deviceConfig) RecoverySnapshotDirsIncludedMap() map[string]bool {
+	excludedMap := c.RecoverySnapshotDirsExcludedMap()
+	return c.createDirsMapOnce(recoverySnapshotDirsIncludedKey, excludedMap,
+		c.config.productVariables.RecoverySnapshotDirsIncluded)
+}
+
 func (c *deviceConfig) ShippingApiLevel() ApiLevel {
 	if c.config.productVariables.ShippingApiLevel == nil {
 		return NoneApiLevel
diff --git a/android/fixture.go b/android/fixture.go
index d8893f7..928967d 100644
--- a/android/fixture.go
+++ b/android/fixture.go
@@ -221,7 +221,8 @@
 //
 // The buildDirSupplier is a pointer to the package level buildDir variable that is initialized by
 // the package level setUp method. It has to be a pointer to the variable as the variable will not
-// have been initialized at the time the factory is created.
+// have been initialized at the time the factory is created. If it is nil then a test specific
+// temporary directory will be created instead.
 func NewFixtureFactory(buildDirSupplier *string, preparers ...FixturePreparer) FixtureFactory {
 	return &fixtureFactory{
 		buildDirSupplier: buildDirSupplier,
@@ -585,7 +586,16 @@
 }
 
 func (f *fixtureFactory) Fixture(t *testing.T, preparers ...FixturePreparer) Fixture {
-	config := TestConfig(*f.buildDirSupplier, nil, "", nil)
+	var buildDir string
+	if f.buildDirSupplier == nil {
+		// Create a new temporary directory for this run. It will be automatically cleaned up when the
+		// test finishes.
+		buildDir = t.TempDir()
+	} else {
+		// Retrieve the buildDir from the supplier.
+		buildDir = *f.buildDirSupplier
+	}
+	config := TestConfig(buildDir, nil, "", nil)
 	ctx := NewTestContext(config)
 	fixture := &fixture{
 		factory:      f,
diff --git a/android/paths.go b/android/paths.go
index 3f4d3f2..f648c55 100644
--- a/android/paths.go
+++ b/android/paths.go
@@ -339,6 +339,7 @@
 	EarlyModulePathContext
 
 	GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
+	Module() Module
 	OtherModuleName(m blueprint.Module) string
 	OtherModuleDir(m blueprint.Module) string
 }
@@ -434,15 +435,45 @@
 // already be resolved by either deps mutator or path deps mutator.
 func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
 	m, _ := ctx.GetDirectDep(dep)
-	// TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
-	otherModuleName := ctx.OtherModuleName(m)
-	var label bazel.Label
-	if otherDir, dir := ctx.OtherModuleDir(m), ctx.ModuleDir(); otherDir != dir {
-		label.Label = fmt.Sprintf("//%s:%s", otherDir, otherModuleName)
-	} else {
-		label.Label = fmt.Sprintf(":%s", otherModuleName)
+	otherLabel := bazelModuleLabel(ctx, m, tag)
+	label := bazelModuleLabel(ctx, ctx.Module(), "")
+	if samePackage(label, otherLabel) {
+		otherLabel = bazelShortLabel(otherLabel)
 	}
-	return label
+
+	return bazel.Label{
+		Label: otherLabel,
+	}
+}
+
+func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
+	// TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
+	b, ok := module.(Bazelable)
+	// TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
+	if !ok || !b.ConvertedToBazel() {
+		return bp2buildModuleLabel(ctx, module)
+	}
+	return b.GetBazelLabel(ctx, module)
+}
+
+func bazelShortLabel(label string) string {
+	i := strings.Index(label, ":")
+	return label[i:]
+}
+
+func bazelPackage(label string) string {
+	i := strings.Index(label, ":")
+	return label[0:i]
+}
+
+func samePackage(label1, label2 string) bool {
+	return bazelPackage(label1) == bazelPackage(label2)
+}
+
+func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
+	moduleName := ctx.OtherModuleName(module)
+	moduleDir := ctx.OtherModuleDir(module)
+	return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
 }
 
 // OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
diff --git a/android/paths_test.go b/android/paths_test.go
index 14a4773..3734ed2 100644
--- a/android/paths_test.go
+++ b/android/paths_test.go
@@ -1261,6 +1261,52 @@
 	}
 }
 
+func TestPathRelativeToTop(t *testing.T) {
+	testConfig := pathTestConfig("/tmp/build/top")
+	deviceTarget := Target{Os: Android, Arch: Arch{ArchType: Arm64}}
+
+	ctx := &testModuleInstallPathContext{
+		baseModuleContext: baseModuleContext{
+			os:     deviceTarget.Os,
+			target: deviceTarget,
+		},
+	}
+	ctx.baseModuleContext.config = testConfig
+
+	t.Run("install for soong", func(t *testing.T) {
+		p := PathForModuleInstall(ctx, "install/path")
+		AssertPathRelativeToTopEquals(t, "install path for soong", "out/soong/target/product/test_device/system/install/path", p)
+	})
+	t.Run("install for make", func(t *testing.T) {
+		p := PathForModuleInstall(ctx, "install/path").ToMakePath()
+		AssertPathRelativeToTopEquals(t, "install path for make", "out/target/product/test_device/system/install/path", p)
+	})
+	t.Run("output", func(t *testing.T) {
+		p := PathForOutput(ctx, "output/path")
+		AssertPathRelativeToTopEquals(t, "output path", "out/soong/output/path", p)
+	})
+	t.Run("source", func(t *testing.T) {
+		p := PathForSource(ctx, "source/path")
+		AssertPathRelativeToTopEquals(t, "source path", "source/path", p)
+	})
+	t.Run("mixture", func(t *testing.T) {
+		paths := Paths{
+			PathForModuleInstall(ctx, "install/path"),
+			PathForModuleInstall(ctx, "install/path").ToMakePath(),
+			PathForOutput(ctx, "output/path"),
+			PathForSource(ctx, "source/path"),
+		}
+
+		expected := []string{
+			"out/soong/target/product/test_device/system/install/path",
+			"out/target/product/test_device/system/install/path",
+			"out/soong/output/path",
+			"source/path",
+		}
+		AssertPathsRelativeToTopEquals(t, "mixture", expected, paths)
+	})
+}
+
 func ExampleOutputPath_ReplaceExtension() {
 	ctx := &configErrorWrapper{
 		config: TestConfig("out", nil, "", nil),
diff --git a/android/test_asserts.go b/android/test_asserts.go
index d0de523..5100abb 100644
--- a/android/test_asserts.go
+++ b/android/test_asserts.go
@@ -40,6 +40,34 @@
 	}
 }
 
+// AssertPathRelativeToTopEquals checks if the expected value is equal to the result of calling
+// PathRelativeToTop on the actual Path.
+func AssertPathRelativeToTopEquals(t *testing.T, message string, expected string, actual Path) {
+	t.Helper()
+	AssertStringEquals(t, message, expected, PathRelativeToTop(actual))
+}
+
+// AssertPathsRelativeToTopEquals checks if the expected value is equal to the result of calling
+// PathsRelativeToTop on the actual Paths.
+func AssertPathsRelativeToTopEquals(t *testing.T, message string, expected []string, actual Paths) {
+	t.Helper()
+	AssertDeepEquals(t, message, expected, PathsRelativeToTop(actual))
+}
+
+// AssertStringPathRelativeToTopEquals checks if the expected value is equal to the result of calling
+// StringPathRelativeToTop on the actual string path.
+func AssertStringPathRelativeToTopEquals(t *testing.T, message string, config Config, expected string, actual string) {
+	t.Helper()
+	AssertStringEquals(t, message, expected, StringPathRelativeToTop(config.buildDir, actual))
+}
+
+// AssertStringPathsRelativeToTopEquals checks if the expected value is equal to the result of
+// calling StringPathsRelativeToTop on the actual string paths.
+func AssertStringPathsRelativeToTopEquals(t *testing.T, message string, config Config, expected []string, actual []string) {
+	t.Helper()
+	AssertDeepEquals(t, message, expected, StringPathsRelativeToTop(config.buildDir, actual))
+}
+
 // AssertErrorMessageEquals checks if the error is not nil and has the expected message. If it does
 // not then this reports an error prefixed with the supplied message and including a reason for why
 // it failed.
diff --git a/android/testing.go b/android/testing.go
index dd3d607..af360fa 100644
--- a/android/testing.go
+++ b/android/testing.go
@@ -813,6 +813,9 @@
 // that is relative to the root of the source tree.
 //
 // The build and source paths should be distinguishable based on their contents.
+//
+// deprecated: use PathRelativeToTop instead as it handles make install paths and differentiates
+// between output and source properly.
 func NormalizePathForTesting(path Path) string {
 	if path == nil {
 		return "<nil path>"
@@ -828,6 +831,11 @@
 	return p
 }
 
+// NormalizePathsForTesting creates a slice of strings where each string is the result of applying
+// NormalizePathForTesting to the corresponding Path in the input slice.
+//
+// deprecated: use PathsRelativeToTop instead as it handles make install paths and differentiates
+// between output and source properly.
 func NormalizePathsForTesting(paths Paths) []string {
 	var result []string
 	for _, path := range paths {
@@ -836,3 +844,100 @@
 	}
 	return result
 }
+
+// PathRelativeToTop returns a string representation of the path relative to a notional top
+// directory.
+//
+// For a WritablePath it applies StringPathRelativeToTop to it, using the buildDir returned from the
+// WritablePath's buildDir() method. For all other paths, i.e. source paths, that are already
+// relative to the top it just returns their string representation.
+func PathRelativeToTop(path Path) string {
+	if path == nil {
+		return "<nil path>"
+	}
+	p := path.String()
+	if w, ok := path.(WritablePath); ok {
+		buildDir := w.buildDir()
+		return StringPathRelativeToTop(buildDir, p)
+	}
+	return p
+}
+
+// PathsRelativeToTop creates a slice of strings where each string is the result of applying
+// PathRelativeToTop to the corresponding Path in the input slice.
+func PathsRelativeToTop(paths Paths) []string {
+	var result []string
+	for _, path := range paths {
+		relative := PathRelativeToTop(path)
+		result = append(result, relative)
+	}
+	return result
+}
+
+// StringPathRelativeToTop returns a string representation of the path relative to a notional top
+// directory.
+//
+// A standard build has the following structure:
+//   ../top/
+//          out/ - make install files go here.
+//          out/soong - this is the buildDir passed to NewTestConfig()
+//          ... - the source files
+//
+// This function converts a path so that it appears relative to the ../top/ directory, i.e.
+// * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
+//   relative path "out/<path>"
+// * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
+//   converted into the top relative path "out/soong/<path>".
+// * Source paths are already relative to the top.
+//
+// This is provided for processing paths that have already been converted into a string, e.g. paths
+// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
+// which it can try and relativize paths. PathRelativeToTop must be used for process Path objects.
+func StringPathRelativeToTop(soongOutDir string, path string) string {
+
+	// A relative path must be a source path so leave it as it is.
+	if !filepath.IsAbs(path) {
+		return path
+	}
+
+	// Check to see if the path is relative to the soong out dir.
+	rel, isRel, err := maybeRelErr(soongOutDir, path)
+	if err != nil {
+		panic(err)
+	}
+
+	if isRel {
+		// The path is in the soong out dir so indicate that in the relative path.
+		return filepath.Join("out/soong", rel)
+	}
+
+	// Check to see if the path is relative to the top level out dir.
+	outDir := filepath.Dir(soongOutDir)
+	rel, isRel, err = maybeRelErr(outDir, path)
+	if err != nil {
+		panic(err)
+	}
+
+	if isRel {
+		// The path is in the out dir so indicate that in the relative path.
+		return filepath.Join("out", rel)
+	}
+
+	// This should never happen.
+	panic(fmt.Errorf("internal error: absolute path %s is not relative to the out dir %s", path, outDir))
+}
+
+// StringPathsRelativeToTop creates a slice of strings where each string is the result of applying
+// StringPathRelativeToTop to the corresponding string path in the input slice.
+//
+// This is provided for processing paths that have already been converted into a string, e.g. paths
+// in AndroidMkEntries structures. As a result it needs to be supplied the soong output dir against
+// which it can try and relativize paths. PathsRelativeToTop must be used for process Paths objects.
+func StringPathsRelativeToTop(soongOutDir string, paths []string) []string {
+	var result []string
+	for _, path := range paths {
+		relative := StringPathRelativeToTop(soongOutDir, path)
+		result = append(result, relative)
+	}
+	return result
+}
diff --git a/android/variable.go b/android/variable.go
index be12a0a..a5e9ab4 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -314,6 +314,11 @@
 	DirectedRecoverySnapshot bool            `json:",omitempty"`
 	RecoverySnapshotModules  map[string]bool `json:",omitempty"`
 
+	VendorSnapshotDirsIncluded   []string `json:",omitempty"`
+	VendorSnapshotDirsExcluded   []string `json:",omitempty"`
+	RecoverySnapshotDirsExcluded []string `json:",omitempty"`
+	RecoverySnapshotDirsIncluded []string `json:",omitempty"`
+
 	BoardVendorSepolicyDirs      []string `json:",omitempty"`
 	BoardOdmSepolicyDirs         []string `json:",omitempty"`
 	BoardReqdMaskPolicy          []string `json:",omitempty"`
diff --git a/apex/apex.go b/apex/apex.go
index f66da1d..3db20f4 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -735,19 +735,13 @@
 		{Mutator: "arch", Variation: archForPrebuiltEtc.String()},
 	}, prebuiltTag, a.properties.Prebuilts...)
 
-	// Add dependency on platform_compat_configs.
-	// TODO(b/182816033) - make this common-arch once all usages have been migrated.
-	ctx.AddFarVariationDependencies([]blueprint.Variation{
-		{Mutator: "os", Variation: ctx.Os().String()},
-		{Mutator: "arch", Variation: archForPrebuiltEtc.String()},
-	}, compatConfigsTag, a.properties.Compat_configs...)
-
 	// 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...)
+	ctx.AddFarVariationDependencies(commonVariation, compatConfigsTag, a.properties.Compat_configs...)
 
 	if a.artApex {
 		// With EMMA_INSTRUMENT_FRAMEWORK=true the ART boot image includes jacoco library.
@@ -1746,10 +1740,8 @@
 			case prebuiltTag:
 				if prebuilt, ok := child.(prebuilt_etc.PrebuiltEtcModule); ok {
 					filesInfo = append(filesInfo, apexFileForPrebuiltEtc(ctx, prebuilt, depName))
-				} else if prebuilt, ok := child.(java.PlatformCompatConfigIntf); ok {
-					filesInfo = append(filesInfo, apexFileForCompatConfig(ctx, prebuilt, depName))
 				} else {
-					ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc and not a platform_compat_config module", depName)
+					ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
 				}
 			case compatConfigsTag:
 				if compatConfig, ok := child.(java.PlatformCompatConfigIntf); ok {
diff --git a/bazel/cquery/Android.bp b/bazel/cquery/Android.bp
new file mode 100644
index 0000000..3a71e9c
--- /dev/null
+++ b/bazel/cquery/Android.bp
@@ -0,0 +1,14 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+bootstrap_go_package {
+    name: "soong-cquery",
+    pkgPath: "android/soong/bazel/cquery",
+    srcs: [
+        "request_type.go",
+    ],
+    pluginFor: [
+        "soong_build",
+    ],
+}
diff --git a/bazel/cquery/request_type.go b/bazel/cquery/request_type.go
new file mode 100644
index 0000000..864db3d
--- /dev/null
+++ b/bazel/cquery/request_type.go
@@ -0,0 +1,110 @@
+package cquery
+
+import (
+	"strings"
+)
+
+var (
+	GetOutputFiles                 RequestType = &getOutputFilesRequestType{}
+	GetCcObjectFiles               RequestType = &getCcObjectFilesRequestType{}
+	GetOutputFilesAndCcObjectFiles RequestType = &getOutputFilesAndCcObjectFilesType{}
+)
+
+type GetOutputFilesAndCcObjectFiles_Result struct {
+	OutputFiles   []string
+	CcObjectFiles []string
+}
+
+var RequestTypes []RequestType = []RequestType{
+	GetOutputFiles, GetCcObjectFiles, 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.
+	Name() string
+
+	// StarlarkFunctionBody returns a straark function body to process this request type.
+	// The returned string is the body of a Starlark function which obtains
+	// all request-relevant information about a target and returns a string containing
+	// this information.
+	// The function should have the following properties:
+	//   - `target` is the only parameter to this function (a configured target).
+	//   - The return value must be a string.
+	//   - The function body should not be indented outside of its own scope.
+	StarlarkFunctionBody() string
+
+	// ParseResult returns a value obtained by parsing the result of the request's Starlark function.
+	// The given rawString must correspond to the string output which was created by evaluating the
+	// Starlark given in StarlarkFunctionBody.
+	// The type of this value depends on the request type; it is up to the caller to
+	// cast to the correct type.
+	ParseResult(rawString string) interface{}
+}
+
+type getOutputFilesRequestType struct{}
+
+func (g getOutputFilesRequestType) Name() string {
+	return "getOutputFiles"
+}
+
+func (g getOutputFilesRequestType) StarlarkFunctionBody() string {
+	return "return ', '.join([f.path for f in target.files.to_list()])"
+}
+
+func (g getOutputFilesRequestType) ParseResult(rawString string) interface{} {
+	return strings.Split(rawString, ", ")
+}
+
+type getCcObjectFilesRequestType struct{}
+
+func (g getCcObjectFilesRequestType) Name() string {
+	return "getCcObjectFiles"
+}
+
+func (g getCcObjectFilesRequestType) StarlarkFunctionBody() string {
+	return `
+result = []
+linker_inputs = providers(target)["CcInfo"].linking_context.linker_inputs.to_list()
+
+for linker_input in linker_inputs:
+  for library in linker_input.libraries:
+    for object in library.objects:
+      result += [object.path]
+return ', '.join(result)`
+}
+
+func (g getCcObjectFilesRequestType) ParseResult(rawString string) interface{} {
+	return strings.Split(rawString, ", ")
+}
+
+type getOutputFilesAndCcObjectFilesType struct{}
+
+func (g getOutputFilesAndCcObjectFilesType) Name() string {
+	return "getOutputFilesAndCcObjectFiles"
+}
+
+func (g getOutputFilesAndCcObjectFilesType) StarlarkFunctionBody() string {
+	return `
+outputFiles = [f.path for f in target.files.to_list()]
+
+ccObjectFiles = []
+linker_inputs = providers(target)["CcInfo"].linking_context.linker_inputs.to_list()
+
+for linker_input in linker_inputs:
+  for library in linker_input.libraries:
+    for object in library.objects:
+      ccObjectFiles += [object.path]
+return ', '.join(outputFiles) + "|" + ', '.join(ccObjectFiles)`
+}
+
+func (g getOutputFilesAndCcObjectFilesType) ParseResult(rawString string) interface{} {
+	var outputFiles []string
+	var ccObjects []string
+
+	splitString := strings.Split(rawString, "|")
+	outputFilesString := splitString[0]
+	ccObjectsString := splitString[1]
+	outputFiles = strings.Split(outputFilesString, ", ")
+	ccObjects = strings.Split(ccObjectsString, ", ")
+	return GetOutputFilesAndCcObjectFiles_Result{outputFiles, ccObjects}
+}
diff --git a/bazel/properties.go b/bazel/properties.go
index cb47758..abdc107 100644
--- a/bazel/properties.go
+++ b/bazel/properties.go
@@ -19,21 +19,6 @@
 	"sort"
 )
 
-type bazelModuleProperties struct {
-	// The label of the Bazel target replacing this Soong module.
-	Label string
-
-	// If true, bp2build will generate the converted Bazel target for this module.
-	Bp2build_available bool
-}
-
-// Properties contains common module properties for Bazel migration purposes.
-type Properties struct {
-	// In USE_BAZEL_ANALYSIS=1 mode, this represents the Bazel target replacing
-	// this Soong module.
-	Bazel_module bazelModuleProperties
-}
-
 // BazelTargetModuleProperties contain properties and metadata used for
 // Blueprint to BUILD file conversion.
 type BazelTargetModuleProperties struct {
diff --git a/bp2build/Android.bp b/bp2build/Android.bp
index 99d706c..c74f902 100644
--- a/bp2build/Android.bp
+++ b/bp2build/Android.bp
@@ -11,6 +11,7 @@
         "build_conversion.go",
         "bzl_conversion.go",
         "configurability.go",
+        "constants.go",
         "conversion.go",
         "metrics.go",
     ],
diff --git a/bp2build/bp2build.go b/bp2build/bp2build.go
index 7169d7e..97a5137 100644
--- a/bp2build/bp2build.go
+++ b/bp2build/bp2build.go
@@ -22,7 +22,7 @@
 
 // The Bazel bp2build code generator is responsible for writing .bzl files that are equivalent to
 // Android.bp files that are capable of being built with Bazel.
-func Codegen(ctx CodegenContext) CodegenMetrics {
+func Codegen(ctx *CodegenContext) CodegenMetrics {
 	outputDir := android.PathForOutput(ctx, "bp2build")
 	android.RemoveAllOutputDir(outputDir)
 
diff --git a/bp2build/build_conversion.go b/bp2build/build_conversion.go
index 7fa4996..9c98c76 100644
--- a/bp2build/build_conversion.go
+++ b/bp2build/build_conversion.go
@@ -99,9 +99,10 @@
 }
 
 type CodegenContext struct {
-	config  android.Config
-	context android.Context
-	mode    CodegenMode
+	config         android.Config
+	context        android.Context
+	mode           CodegenMode
+	additionalDeps []string
 }
 
 func (c *CodegenContext) Mode() CodegenMode {
@@ -137,14 +138,26 @@
 	}
 }
 
-func (ctx CodegenContext) AddNinjaFileDeps(...string) {}
-func (ctx CodegenContext) Config() android.Config     { return ctx.config }
-func (ctx CodegenContext) Context() android.Context   { return ctx.context }
+// AddNinjaFileDeps adds dependencies on the specified files to be added to the ninja manifest. The
+// primary builder will be rerun whenever the specified files are modified. Allows us to fulfill the
+// PathContext interface in order to add dependencies on hand-crafted BUILD files. Note: must also
+// call AdditionalNinjaDeps and add them manually to the ninja file.
+func (ctx *CodegenContext) AddNinjaFileDeps(deps ...string) {
+	ctx.additionalDeps = append(ctx.additionalDeps, deps...)
+}
+
+// AdditionalNinjaDeps returns additional ninja deps added by CodegenContext
+func (ctx *CodegenContext) AdditionalNinjaDeps() []string {
+	return ctx.additionalDeps
+}
+
+func (ctx *CodegenContext) Config() android.Config   { return ctx.config }
+func (ctx *CodegenContext) Context() android.Context { return ctx.context }
 
 // NewCodegenContext creates a wrapper context that conforms to PathContext for
 // writing BUILD files in the output directory.
-func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) CodegenContext {
-	return CodegenContext{
+func NewCodegenContext(config android.Config, context android.Context, mode CodegenMode) *CodegenContext {
+	return &CodegenContext{
 		context: context,
 		config:  config,
 		mode:    mode,
@@ -163,12 +176,14 @@
 	return attributes
 }
 
-func GenerateBazelTargets(ctx CodegenContext) (map[string]BazelTargets, CodegenMetrics) {
+func GenerateBazelTargets(ctx *CodegenContext) (map[string]BazelTargets, CodegenMetrics) {
 	buildFileToTargets := make(map[string]BazelTargets)
+	buildFileToAppend := make(map[string]bool)
 
 	// Simple metrics tracking for bp2build
-	totalModuleCount := 0
-	ruleClassCount := make(map[string]int)
+	metrics := CodegenMetrics{
+		RuleClassCount: make(map[string]int),
+	}
 
 	bpCtx := ctx.Context()
 	bpCtx.VisitAllModules(func(m blueprint.Module) {
@@ -177,13 +192,29 @@
 
 		switch ctx.Mode() {
 		case Bp2Build:
-			if b, ok := m.(android.BazelTargetModule); !ok {
-				// Only include regular Soong modules (non-BazelTargetModules) into the total count.
-				totalModuleCount += 1
-				return
+			if b, ok := m.(android.Bazelable); ok && b.HasHandcraftedLabel() {
+				metrics.handCraftedTargetCount += 1
+				metrics.TotalModuleCount += 1
+				pathToBuildFile := getBazelPackagePath(b)
+				// We are using the entire contents of handcrafted build file, so if multiple targets within
+				// a package have handcrafted targets, we only want to include the contents one time.
+				if _, exists := buildFileToAppend[pathToBuildFile]; exists {
+					return
+				}
+				var err error
+				t, err = getHandcraftedBuildContent(ctx, b, pathToBuildFile)
+				if err != nil {
+					panic(fmt.Errorf("Error converting %s: %s", bpCtx.ModuleName(m), err))
+				}
+				// TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
+				// something more targeted based on the rule type and target
+				buildFileToAppend[pathToBuildFile] = true
+			} else if btm, ok := m.(android.BazelTargetModule); ok {
+				t = generateBazelTarget(bpCtx, m, btm)
+				metrics.RuleClassCount[t.ruleClass] += 1
 			} else {
-				t = generateBazelTarget(bpCtx, m, b)
-				ruleClassCount[t.ruleClass] += 1
+				metrics.TotalModuleCount += 1
+				return
 			}
 		case QueryView:
 			// Blocklist certain module types from being generated.
@@ -200,17 +231,34 @@
 		buildFileToTargets[dir] = append(buildFileToTargets[dir], t)
 	})
 
-	metrics := CodegenMetrics{
-		TotalModuleCount: totalModuleCount,
-		RuleClassCount:   ruleClassCount,
-	}
-
 	return buildFileToTargets, metrics
 }
 
-func generateBazelTarget(ctx bpToBuildContext, m blueprint.Module, b android.BazelTargetModule) BazelTarget {
-	ruleClass := b.RuleClass()
-	bzlLoadLocation := b.BzlLoadLocation()
+func getBazelPackagePath(b android.Bazelable) string {
+	label := b.HandcraftedLabel()
+	pathToBuildFile := strings.TrimPrefix(label, "//")
+	pathToBuildFile = strings.Split(pathToBuildFile, ":")[0]
+	return pathToBuildFile
+}
+
+func getHandcraftedBuildContent(ctx *CodegenContext, b android.Bazelable, pathToBuildFile string) (BazelTarget, error) {
+	p := android.ExistentPathForSource(ctx, pathToBuildFile, HandcraftedBuildFileName)
+	if !p.Valid() {
+		return BazelTarget{}, fmt.Errorf("Could not find file %q for handcrafted target.", pathToBuildFile)
+	}
+	c, err := b.GetBazelBuildFileContents(ctx.Config(), pathToBuildFile, HandcraftedBuildFileName)
+	if err != nil {
+		return BazelTarget{}, err
+	}
+	// TODO(b/181575318): once this is more targeted, we need to include name, rule class, etc
+	return BazelTarget{
+		content: c,
+	}, nil
+}
+
+func generateBazelTarget(ctx bpToBuildContext, m blueprint.Module, btm android.BazelTargetModule) BazelTarget {
+	ruleClass := btm.RuleClass()
+	bzlLoadLocation := btm.BzlLoadLocation()
 
 	// extract the bazel attributes from the module.
 	props := getBuildProperties(ctx, m)
diff --git a/bp2build/build_conversion_test.go b/bp2build/build_conversion_test.go
index aa4fc1d..89acbe9 100644
--- a/bp2build/build_conversion_test.go
+++ b/bp2build/build_conversion_test.go
@@ -1221,3 +1221,157 @@
 		}
 	}
 }
+
+func TestCombineBuildFilesBp2buildTargets(t *testing.T) {
+	testCases := []struct {
+		description                        string
+		moduleTypeUnderTest                string
+		moduleTypeUnderTestFactory         android.ModuleFactory
+		moduleTypeUnderTestBp2BuildMutator func(android.TopDownMutatorContext)
+		preArchMutators                    []android.RegisterMutatorFunc
+		depsMutators                       []android.RegisterMutatorFunc
+		bp                                 string
+		expectedBazelTargets               []string
+		fs                                 map[string]string
+		dir                                string
+	}{
+		{
+			description:                        "filegroup bazel_module.label",
+			moduleTypeUnderTest:                "filegroup",
+			moduleTypeUnderTestFactory:         android.FileGroupFactory,
+			moduleTypeUnderTestBp2BuildMutator: android.FilegroupBp2Build,
+			bp: `filegroup {
+    name: "fg_foo",
+    bazel_module: { label: "//other:fg_foo" },
+}`,
+			expectedBazelTargets: []string{
+				`// BUILD file`,
+			},
+			fs: map[string]string{
+				"other/BUILD.bazel": `// BUILD file`,
+			},
+		},
+		{
+			description:                        "multiple bazel_module.label same BUILD",
+			moduleTypeUnderTest:                "filegroup",
+			moduleTypeUnderTestFactory:         android.FileGroupFactory,
+			moduleTypeUnderTestBp2BuildMutator: android.FilegroupBp2Build,
+			bp: `filegroup {
+    name: "fg_foo",
+    bazel_module: { label: "//other:fg_foo" },
+}
+
+filegroup {
+    name: "foo",
+    bazel_module: { label: "//other:foo" },
+}`,
+			expectedBazelTargets: []string{
+				`// BUILD file`,
+			},
+			fs: map[string]string{
+				"other/BUILD.bazel": `// BUILD file`,
+			},
+		},
+		{
+			description:                        "filegroup bazel_module.label and bp2build",
+			moduleTypeUnderTest:                "filegroup",
+			moduleTypeUnderTestFactory:         android.FileGroupFactory,
+			moduleTypeUnderTestBp2BuildMutator: android.FilegroupBp2Build,
+			bp: `filegroup {
+    name: "fg_foo",
+    bazel_module: {
+      label: "//other:fg_foo",
+      bp2build_available: true,
+    },
+}`,
+			expectedBazelTargets: []string{
+				`filegroup(
+    name = "fg_foo",
+)`,
+				`// BUILD file`,
+			},
+			fs: map[string]string{
+				"other/BUILD.bazel": `// BUILD file`,
+			},
+		},
+		{
+			description:                        "filegroup bazel_module.label and filegroup bp2build",
+			moduleTypeUnderTest:                "filegroup",
+			moduleTypeUnderTestFactory:         android.FileGroupFactory,
+			moduleTypeUnderTestBp2BuildMutator: android.FilegroupBp2Build,
+			bp: `filegroup {
+    name: "fg_foo",
+    bazel_module: {
+      label: "//other:fg_foo",
+    },
+}
+
+filegroup {
+    name: "fg_bar",
+    bazel_module: {
+      bp2build_available: true,
+    },
+}`,
+			expectedBazelTargets: []string{
+				`filegroup(
+    name = "fg_bar",
+)`,
+				`// BUILD file`,
+			},
+			fs: map[string]string{
+				"other/BUILD.bazel": `// BUILD file`,
+			},
+		},
+	}
+
+	dir := "."
+	for _, testCase := range testCases {
+		fs := make(map[string][]byte)
+		toParse := []string{
+			"Android.bp",
+		}
+		for f, content := range testCase.fs {
+			if strings.HasSuffix(f, "Android.bp") {
+				toParse = append(toParse, f)
+			}
+			fs[f] = []byte(content)
+		}
+		config := android.TestConfig(buildDir, nil, testCase.bp, fs)
+		ctx := android.NewTestContext(config)
+		ctx.RegisterModuleType(testCase.moduleTypeUnderTest, testCase.moduleTypeUnderTestFactory)
+		for _, m := range testCase.depsMutators {
+			ctx.DepsBp2BuildMutators(m)
+		}
+		ctx.RegisterBp2BuildMutator(testCase.moduleTypeUnderTest, testCase.moduleTypeUnderTestBp2BuildMutator)
+		ctx.RegisterForBazelConversion()
+
+		_, errs := ctx.ParseFileList(dir, toParse)
+		if Errored(t, testCase.description, errs) {
+			continue
+		}
+		_, errs = ctx.ResolveDependencies(config)
+		if Errored(t, testCase.description, errs) {
+			continue
+		}
+
+		checkDir := dir
+		if testCase.dir != "" {
+			checkDir = testCase.dir
+		}
+		bazelTargets := generateBazelTargetsForDir(NewCodegenContext(config, *ctx.Context, Bp2Build), checkDir)
+		if actualCount, expectedCount := len(bazelTargets), len(testCase.expectedBazelTargets); actualCount != expectedCount {
+			t.Errorf("%s: Expected %d bazel target, got %d\n%s", testCase.description, expectedCount, actualCount, bazelTargets)
+		} else {
+			for i, target := range bazelTargets {
+				if w, g := testCase.expectedBazelTargets[i], target.content; w != g {
+					t.Errorf(
+						"%s: Expected generated Bazel target to be '%s', got '%s'",
+						testCase.description,
+						w,
+						g,
+					)
+				}
+			}
+		}
+	}
+}
diff --git a/bp2build/constants.go b/bp2build/constants.go
new file mode 100644
index 0000000..23bca83
--- /dev/null
+++ b/bp2build/constants.go
@@ -0,0 +1,25 @@
+// Copyright 2020 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package bp2build
+
+var (
+	// When both a BUILD and BUILD.bazel file are exist in the same package, the BUILD.bazel file will
+	// be preferred for use within a Bazel build.
+
+	// The file name used for automatically generated files. Files with this name are ignored by git.
+	GeneratedBuildFileName = "BUILD"
+	// The file name used for hand-crafted build targets.
+	HandcraftedBuildFileName = "BUILD.bazel"
+)
diff --git a/bp2build/conversion.go b/bp2build/conversion.go
index 1225f2b..7877bb8 100644
--- a/bp2build/conversion.go
+++ b/bp2build/conversion.go
@@ -24,9 +24,9 @@
 	// Write top level files: WORKSPACE and BUILD. These files are empty.
 	files = append(files, newFile("", "WORKSPACE", ""))
 	// Used to denote that the top level directory is a package.
-	files = append(files, newFile("", "BUILD", ""))
+	files = append(files, newFile("", GeneratedBuildFileName, ""))
 
-	files = append(files, newFile(bazelRulesSubDir, "BUILD", ""))
+	files = append(files, newFile(bazelRulesSubDir, GeneratedBuildFileName, ""))
 
 	if mode == QueryView {
 		// These files are only used for queryview.
@@ -47,7 +47,14 @@
 	files := make([]BazelFile, 0, len(buildToTargets))
 	for _, dir := range android.SortedStringKeys(buildToTargets) {
 		targets := buildToTargets[dir]
-		sort.Slice(targets, func(i, j int) bool { return targets[i].name < targets[j].name })
+		sort.Slice(targets, func(i, j int) bool {
+			// this will cover all bp2build generated targets
+			if targets[i].name < targets[j].name {
+				return true
+			}
+			// give a strict ordering to content from hand-crafted targets
+			return targets[i].content < targets[j].content
+		})
 		content := soongModuleLoad
 		if mode == Bp2Build {
 			content = `# This file was automatically generated by bp2build for the Bazel migration project.
@@ -62,7 +69,7 @@
 			content += "\n\n"
 		}
 		content += targets.String()
-		files = append(files, newFile(dir, "BUILD", content))
+		files = append(files, newFile(dir, GeneratedBuildFileName, content))
 	}
 	return files
 }
diff --git a/bp2build/metrics.go b/bp2build/metrics.go
index 916129f..65b06c6 100644
--- a/bp2build/metrics.go
+++ b/bp2build/metrics.go
@@ -13,6 +13,9 @@
 
 	// Counts of generated Bazel targets per Bazel rule class
 	RuleClassCount map[string]int
+
+	// Total number of handcrafted targets
+	handCraftedTargetCount int
 }
 
 // Print the codegen metrics to stdout.
@@ -24,7 +27,8 @@
 		generatedTargetCount += count
 	}
 	fmt.Printf(
-		"[bp2build] Generated %d total BUILD targets from %d Android.bp modules.\n",
+		"[bp2build] Generated %d total BUILD targets and included %d handcrafted BUILD targets from %d Android.bp modules.\n",
 		generatedTargetCount,
+		metrics.handCraftedTargetCount,
 		metrics.TotalModuleCount)
 }
diff --git a/bp2build/testing.go b/bp2build/testing.go
index bd75a8f..a15a4a5 100644
--- a/bp2build/testing.go
+++ b/bp2build/testing.go
@@ -175,7 +175,7 @@
 }
 
 // Helper method for tests to easily access the targets in a dir.
-func generateBazelTargetsForDir(codegenCtx CodegenContext, dir string) BazelTargets {
+func generateBazelTargetsForDir(codegenCtx *CodegenContext, dir string) BazelTargets {
 	buildFileToTargets, _ := GenerateBazelTargets(codegenCtx)
 	return buildFileToTargets[dir]
 }
diff --git a/cc/cc.go b/cc/cc.go
index c335dac..cab7459 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -1605,7 +1605,7 @@
 
 // Returns true if Bazel was successfully used for the analysis of this module.
 func (c *Module) maybeGenerateBazelActions(actx android.ModuleContext) bool {
-	bazelModuleLabel := c.GetBazelLabel()
+	bazelModuleLabel := c.GetBazelLabel(actx, c)
 	bazelActionsUsed := false
 	if c.bazelHandler != nil && actx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
 		bazelActionsUsed = c.bazelHandler.generateBazelBuildActions(actx, bazelModuleLabel)
diff --git a/cc/library.go b/cc/library.go
index 6a3b876..22a36c6 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -415,38 +415,39 @@
 
 func (handler *staticLibraryBazelHandler) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
 	bazelCtx := ctx.Config().BazelContext
-	outputPaths, objPaths, ok := bazelCtx.GetAllFilesAndCcObjectFiles(label, ctx.Arch().ArchType)
-	if ok {
-		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)
-			return false
-		}
-		outputFilePath := android.PathForBazelOut(ctx, outputPaths[0])
-		handler.module.outputFile = android.OptionalPathForPath(outputFilePath)
-
-		objFiles := make(android.Paths, len(objPaths))
-		for i, objPath := range objPaths {
-			objFiles[i] = android.PathForBazelOut(ctx, objPath)
-		}
-		objects := Objects{
-			objFiles: objFiles,
-		}
-
-		ctx.SetProvider(StaticLibraryInfoProvider, StaticLibraryInfo{
-			StaticLibrary: outputFilePath,
-			ReuseObjects:  objects,
-			Objects:       objects,
-
-			// TODO(cparsons): Include transitive static libraries in this provider to support
-			// static libraries with deps.
-			TransitiveStaticLibrariesForOrdering: android.NewDepSetBuilder(android.TOPOLOGICAL).
-				Direct(outputFilePath).
-				Build(),
-		})
-		handler.module.outputFile = android.OptionalPathForPath(android.PathForBazelOut(ctx, objPaths[0]))
+	outputPaths, objPaths, ok := bazelCtx.GetOutputFilesAndCcObjectFiles(label, ctx.Arch().ArchType)
+	if !ok {
+		return ok
 	}
+	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)
+		return false
+	}
+	outputFilePath := android.PathForBazelOut(ctx, outputPaths[0])
+	handler.module.outputFile = android.OptionalPathForPath(outputFilePath)
+
+	objFiles := make(android.Paths, len(objPaths))
+	for i, objPath := range objPaths {
+		objFiles[i] = android.PathForBazelOut(ctx, objPath)
+	}
+	objects := Objects{
+		objFiles: objFiles,
+	}
+
+	ctx.SetProvider(StaticLibraryInfoProvider, StaticLibraryInfo{
+		StaticLibrary: outputFilePath,
+		ReuseObjects:  objects,
+		Objects:       objects,
+
+		// TODO(cparsons): Include transitive static libraries in this provider to support
+		// static libraries with deps.
+		TransitiveStaticLibrariesForOrdering: android.NewDepSetBuilder(android.TOPOLOGICAL).
+			Direct(outputFilePath).
+			Build(),
+	})
+	handler.module.outputFile = android.OptionalPathForPath(android.PathForBazelOut(ctx, objPaths[0]))
 	return ok
 }
 
diff --git a/cc/object.go b/cc/object.go
index 126bd65..f9e6d2d 100644
--- a/cc/object.go
+++ b/cc/object.go
@@ -53,17 +53,8 @@
 }
 
 func (handler *objectBazelHandler) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
-	bazelCtx := ctx.Config().BazelContext
-	objPaths, ok := bazelCtx.GetCcObjectFiles(label, ctx.Arch().ArchType)
-	if ok {
-		if len(objPaths) != 1 {
-			ctx.ModuleErrorf("expected exactly one object file for '%s', but got %s", label, objPaths)
-			return false
-		}
-
-		handler.module.outputFile = android.OptionalPathForPath(android.PathForBazelOut(ctx, objPaths[0]))
-	}
-	return ok
+	// TODO(b/181794963): restore mixed builds once cc_object incompatibility resolved
+	return false
 }
 
 type ObjectLinkerProperties struct {
diff --git a/cc/snapshot_prebuilt.go b/cc/snapshot_prebuilt.go
index f9aea0c..bbb8896 100644
--- a/cc/snapshot_prebuilt.go
+++ b/cc/snapshot_prebuilt.go
@@ -18,6 +18,7 @@
 // snapshot mutators and snapshot information maps which are also defined in this file.
 
 import (
+	"path/filepath"
 	"strings"
 
 	"android/soong/android"
@@ -45,9 +46,9 @@
 	// directory, such as device/, vendor/, etc.
 	//
 	// For a given snapshot (e.g., vendor, recovery, etc.) if
-	// isProprietaryPath(dir) returns true, then the module in dir will be
-	// built from sources.
-	isProprietaryPath(dir string) bool
+	// isProprietaryPath(dir, deviceConfig) returns true, then the module in dir
+	// will be built from sources.
+	isProprietaryPath(dir string, deviceConfig android.DeviceConfig) bool
 
 	// Whether to include VNDK in the snapshot for this image.
 	includeVndk() bool
@@ -82,6 +83,31 @@
 type vendorSnapshotImage struct{}
 type recoverySnapshotImage struct{}
 
+type directoryMap map[string]bool
+
+var (
+	// Modules under following directories are ignored. They are OEM's and vendor's
+	// proprietary modules(device/, kernel/, vendor/, and hardware/).
+	defaultDirectoryExcludedMap = directoryMap{
+		"device":   true,
+		"hardware": true,
+		"kernel":   true,
+		"vendor":   true,
+	}
+
+	// Modules under following directories are included as they are in AOSP,
+	// although hardware/ and kernel/ are normally for vendor's own.
+	defaultDirectoryIncludedMap = directoryMap{
+		"kernel/configs":              true,
+		"kernel/prebuilts":            true,
+		"kernel/tests":                true,
+		"hardware/interfaces":         true,
+		"hardware/libhardware":        true,
+		"hardware/libhardware_legacy": true,
+		"hardware/ril":                true,
+	}
+)
+
 func (vendorSnapshotImage) init(ctx android.RegistrationContext) {
 	ctx.RegisterSingletonType("vendor-snapshot", VendorSnapshotSingleton)
 	ctx.RegisterModuleType("vendor_snapshot", vendorSnapshotFactory)
@@ -107,8 +133,25 @@
 	return m.IsVndkPrivate()
 }
 
-func (vendorSnapshotImage) isProprietaryPath(dir string) bool {
-	return isVendorProprietaryPath(dir)
+func isDirectoryExcluded(dir string, excludedMap directoryMap, includedMap directoryMap) bool {
+	if dir == "." || dir == "/" {
+		return false
+	}
+	if includedMap[dir] {
+		return false
+	} else if excludedMap[dir] {
+		return true
+	} else if defaultDirectoryIncludedMap[dir] {
+		return false
+	} else if defaultDirectoryExcludedMap[dir] {
+		return true
+	} else {
+		return isDirectoryExcluded(filepath.Dir(dir), excludedMap, includedMap)
+	}
+}
+
+func (vendorSnapshotImage) isProprietaryPath(dir string, deviceConfig android.DeviceConfig) bool {
+	return isDirectoryExcluded(dir, deviceConfig.VendorSnapshotDirsExcludedMap(), deviceConfig.VendorSnapshotDirsIncludedMap())
 }
 
 // vendor snapshot includes static/header libraries with vndk: {enabled: true}.
@@ -172,8 +215,8 @@
 	return false
 }
 
-func (recoverySnapshotImage) isProprietaryPath(dir string) bool {
-	return isRecoveryProprietaryPath(dir)
+func (recoverySnapshotImage) isProprietaryPath(dir string, deviceConfig android.DeviceConfig) bool {
+	return isDirectoryExcluded(dir, deviceConfig.RecoverySnapshotDirsExcludedMap(), deviceConfig.RecoverySnapshotDirsIncludedMap())
 }
 
 // recovery snapshot does NOT treat vndk specially.
diff --git a/cc/snapshot_utils.go b/cc/snapshot_utils.go
index c50ef45..c32fa36 100644
--- a/cc/snapshot_utils.go
+++ b/cc/snapshot_utils.go
@@ -80,7 +80,7 @@
 	}
 
 	for _, image := range []snapshotImage{vendorSnapshotImageSingleton, recoverySnapshotImageSingleton} {
-		if isSnapshotAware(ctx.DeviceConfig(), m, image.isProprietaryPath(ctx.ModuleDir()), apexInfo, image) {
+		if isSnapshotAware(ctx.DeviceConfig(), m, image.isProprietaryPath(ctx.ModuleDir(), ctx.DeviceConfig()), apexInfo, image) {
 			return true
 		}
 	}
diff --git a/cc/vendor_snapshot.go b/cc/vendor_snapshot.go
index 7077b71..fdd1fec 100644
--- a/cc/vendor_snapshot.go
+++ b/cc/vendor_snapshot.go
@@ -90,73 +90,24 @@
 	fake bool
 }
 
-var (
-	// Modules under following directories are ignored. They are OEM's and vendor's
-	// proprietary modules(device/, kernel/, vendor/, and hardware/).
-	vendorProprietaryDirs = []string{
-		"device",
-		"kernel",
-		"vendor",
-		"hardware",
-	}
-
-	// Modules under following directories are ignored. They are OEM's and vendor's
-	// proprietary modules(device/, kernel/, vendor/, and hardware/).
-	recoveryProprietaryDirs = []string{
-		"device",
-		"hardware",
-		"kernel",
-		"vendor",
-	}
-
-	// Modules under following directories are included as they are in AOSP,
-	// although hardware/ and kernel/ are normally for vendor's own.
-	aospDirsUnderProprietary = []string{
-		"kernel/configs",
-		"kernel/prebuilts",
-		"kernel/tests",
-		"hardware/interfaces",
-		"hardware/libhardware",
-		"hardware/libhardware_legacy",
-		"hardware/ril",
-	}
-)
-
-// Determine if a dir under source tree is an SoC-owned proprietary directory, such as
-// device/, vendor/, etc.
-func isVendorProprietaryPath(dir string) bool {
-	return isProprietaryPath(dir, vendorProprietaryDirs)
+// Determine if a dir under source tree is an SoC-owned proprietary directory based
+// on vendor snapshot configuration
+// Examples: device/, vendor/
+func isVendorProprietaryPath(dir string, deviceConfig android.DeviceConfig) bool {
+	return VendorSnapshotSingleton().(*snapshotSingleton).image.isProprietaryPath(dir, deviceConfig)
 }
 
-func isRecoveryProprietaryPath(dir string) bool {
-	return isProprietaryPath(dir, recoveryProprietaryDirs)
-}
-
-// Determine if a dir under source tree is an SoC-owned proprietary directory, such as
-// device/, vendor/, etc.
-func isProprietaryPath(dir string, proprietaryDirs []string) bool {
-	for _, p := range proprietaryDirs {
-		if strings.HasPrefix(dir, p) {
-			// filter out AOSP defined directories, e.g. hardware/interfaces/
-			aosp := false
-			for _, p := range aospDirsUnderProprietary {
-				if strings.HasPrefix(dir, p) {
-					aosp = true
-					break
-				}
-			}
-			if !aosp {
-				return true
-			}
-		}
-	}
-	return false
+// Determine if a dir under source tree is an SoC-owned proprietary directory based
+// on recovery snapshot configuration
+// Examples: device/, vendor/
+func isRecoveryProprietaryPath(dir string, deviceConfig android.DeviceConfig) bool {
+	return RecoverySnapshotSingleton().(*snapshotSingleton).image.isProprietaryPath(dir, deviceConfig)
 }
 
 func isVendorProprietaryModule(ctx android.BaseModuleContext) bool {
 	// Any module in a vendor proprietary path is a vendor proprietary
 	// module.
-	if isVendorProprietaryPath(ctx.ModuleDir()) {
+	if isVendorProprietaryPath(ctx.ModuleDir(), ctx.DeviceConfig()) {
 		return true
 	}
 
@@ -177,7 +128,7 @@
 
 	// Any module in a recovery proprietary path is a recovery proprietary
 	// module.
-	if isRecoveryProprietaryPath(ctx.ModuleDir()) {
+	if isRecoveryProprietaryPath(ctx.ModuleDir(), ctx.DeviceConfig()) {
 		return true
 	}
 
@@ -513,7 +464,7 @@
 		}
 
 		moduleDir := ctx.ModuleDir(module)
-		inProprietaryPath := c.image.isProprietaryPath(moduleDir)
+		inProprietaryPath := c.image.isProprietaryPath(moduleDir, ctx.DeviceConfig())
 		apexInfo := ctx.ModuleProvider(module, android.ApexInfoProvider).(android.ApexInfo)
 
 		if c.image.excludeFromSnapshot(m) {
diff --git a/cmd/soong_build/main.go b/cmd/soong_build/main.go
index 0c80605..d96abd9 100644
--- a/cmd/soong_build/main.go
+++ b/cmd/soong_build/main.go
@@ -198,7 +198,6 @@
 	if err != nil {
 		panic(err)
 	}
-	extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
 
 	// Run the loading and analysis pipeline to prepare the graph of regular
 	// Modules parsed from Android.bp files, and the BazelTargetModules mapped
@@ -215,6 +214,9 @@
 	// 1:1 mapping for each module.
 	metrics.Print()
 
+	extraNinjaDeps = append(extraNinjaDeps, codegenContext.AdditionalNinjaDeps()...)
+	extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
+
 	// 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
diff --git a/cmd/soong_build/queryview.go b/cmd/soong_build/queryview.go
index 0a77d67..edc8a42 100644
--- a/cmd/soong_build/queryview.go
+++ b/cmd/soong_build/queryview.go
@@ -22,7 +22,7 @@
 	"path/filepath"
 )
 
-func createBazelQueryView(ctx bp2build.CodegenContext, bazelQueryViewDir string) error {
+func createBazelQueryView(ctx *bp2build.CodegenContext, bazelQueryViewDir string) error {
 	ruleShims := bp2build.CreateRuleShims(android.ModuleTypeFactories())
 
 	// Ignore metrics reporting for queryview, since queryview is already a full-repo
diff --git a/dexpreopt/dexpreopt.go b/dexpreopt/dexpreopt.go
index fdb00bd..4999bc7 100644
--- a/dexpreopt/dexpreopt.go
+++ b/dexpreopt/dexpreopt.go
@@ -261,21 +261,17 @@
 
 	} else if module.EnforceUsesLibraries {
 		// Generate command that saves target SDK version in a shell variable.
-		if module.ManifestPath != nil {
-			rule.Command().Text(`target_sdk_version="$(`).
-				Tool(globalSoong.ManifestCheck).
-				Flag("--extract-target-sdk-version").
-				Input(module.ManifestPath).
-				Text(`)"`)
-		} else {
-			// No manifest to extract targetSdkVersion from, hope that DexJar is an APK
-			rule.Command().Text(`target_sdk_version="$(`).
-				Tool(globalSoong.Aapt).
-				Flag("dump badging").
-				Input(module.DexPath).
-				Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`).
-				Text(`)"`)
+		manifestOrApk := module.ManifestPath
+		if manifestOrApk == nil {
+			// No manifest to extract targetSdkVersion from, hope that dexjar is an APK.
+			manifestOrApk = module.DexPath
 		}
+		rule.Command().Text(`target_sdk_version="$(`).
+			Tool(globalSoong.ManifestCheck).
+			Flag("--extract-target-sdk-version").
+			Input(manifestOrApk).
+			FlagWithInput("--aapt ", ctx.Config().HostToolPath(ctx, "aapt")).
+			Text(`)"`)
 
 		// Generate command that saves host and target class loader context in shell variables.
 		clc, paths := ComputeClassLoaderContext(module.ClassLoaderContexts)
diff --git a/etc/prebuilt_etc_test.go b/etc/prebuilt_etc_test.go
index 09f2e8c..f800c48 100644
--- a/etc/prebuilt_etc_test.go
+++ b/etc/prebuilt_etc_test.go
@@ -15,7 +15,6 @@
 package etc
 
 import (
-	"io/ioutil"
 	"os"
 	"path/filepath"
 	"testing"
@@ -23,33 +22,12 @@
 	"android/soong/android"
 )
 
-var buildDir string
-
-func setUp() {
-	var err error
-	buildDir, err = ioutil.TempDir("", "soong_etc_test")
-	if err != nil {
-		panic(err)
-	}
-}
-
-func tearDown() {
-	os.RemoveAll(buildDir)
-}
-
 func TestMain(m *testing.M) {
-	run := func() int {
-		setUp()
-		defer tearDown()
-
-		return m.Run()
-	}
-
-	os.Exit(run())
+	os.Exit(m.Run())
 }
 
 var prebuiltEtcFixtureFactory = android.NewFixtureFactory(
-	&buildDir,
+	nil,
 	android.PrepareForTestWithArchMutator,
 	PrepareForTestWithPrebuiltEtc,
 	android.FixtureMergeMockFs(android.MockFS{
@@ -170,8 +148,8 @@
 	`)
 
 	p := result.Module("foo.conf", "android_arm64_armv8-a").(*PrebuiltEtc)
-	expected := buildDir + "/target/product/test_device/system/etc/bar"
-	android.AssertStringEquals(t, "install dir", expected, p.installDirPath.String())
+	expected := "out/soong/target/product/test_device/system/etc/bar"
+	android.AssertPathRelativeToTopEquals(t, "install dir", expected, p.installDirPath)
 }
 
 func TestPrebuiltEtcCannotSetRelativeInstallPathAndSubDir(t *testing.T) {
@@ -212,8 +190,8 @@
 	`)
 
 	p := result.Module("foo.conf", "android_arm64_armv8-a").(*PrebuiltEtc)
-	expected := buildDir + "/target/product/test_device/system/usr/share/bar"
-	android.AssertStringEquals(t, "install dir", expected, p.installDirPath.String())
+	expected := "out/soong/target/product/test_device/system/usr/share/bar"
+	android.AssertPathRelativeToTopEquals(t, "install dir", expected, p.installDirPath)
 }
 
 func TestPrebuiltUserShareHostInstallDirPath(t *testing.T) {
@@ -227,8 +205,8 @@
 
 	buildOS := android.BuildOs.String()
 	p := result.Module("foo.conf", buildOS+"_common").(*PrebuiltEtc)
-	expected := filepath.Join(buildDir, "host", result.Config.PrebuiltOS(), "usr", "share", "bar")
-	android.AssertStringEquals(t, "install dir", expected, p.installDirPath.String())
+	expected := filepath.Join("out/soong/host", result.Config.PrebuiltOS(), "usr", "share", "bar")
+	android.AssertPathRelativeToTopEquals(t, "install dir", expected, p.installDirPath)
 }
 
 func TestPrebuiltFontInstallDirPath(t *testing.T) {
@@ -240,12 +218,12 @@
 	`)
 
 	p := result.Module("foo.conf", "android_arm64_armv8-a").(*PrebuiltEtc)
-	expected := buildDir + "/target/product/test_device/system/fonts"
-	android.AssertStringEquals(t, "install dir", expected, p.installDirPath.String())
+	expected := "out/soong/target/product/test_device/system/fonts"
+	android.AssertPathRelativeToTopEquals(t, "install dir", expected, p.installDirPath)
 }
 
 func TestPrebuiltFirmwareDirPath(t *testing.T) {
-	targetPath := buildDir + "/target/product/test_device"
+	targetPath := "out/soong/target/product/test_device"
 	tests := []struct {
 		description  string
 		config       string
@@ -273,13 +251,13 @@
 		t.Run(tt.description, func(t *testing.T) {
 			result := prebuiltEtcFixtureFactory.RunTestWithBp(t, tt.config)
 			p := result.Module("foo.conf", "android_arm64_armv8-a").(*PrebuiltEtc)
-			android.AssertStringEquals(t, "install dir", tt.expectedPath, p.installDirPath.String())
+			android.AssertPathRelativeToTopEquals(t, "install dir", tt.expectedPath, p.installDirPath)
 		})
 	}
 }
 
 func TestPrebuiltDSPDirPath(t *testing.T) {
-	targetPath := filepath.Join(buildDir, "/target/product/test_device")
+	targetPath := "out/soong/target/product/test_device"
 	tests := []struct {
 		description  string
 		config       string
@@ -307,7 +285,7 @@
 		t.Run(tt.description, func(t *testing.T) {
 			result := prebuiltEtcFixtureFactory.RunTestWithBp(t, tt.config)
 			p := result.Module("foo.conf", "android_arm64_armv8-a").(*PrebuiltEtc)
-			android.AssertStringEquals(t, "install dir", tt.expectedPath, p.installDirPath.String())
+			android.AssertPathRelativeToTopEquals(t, "install dir", tt.expectedPath, p.installDirPath)
 		})
 	}
 }
diff --git a/genrule/genrule.go b/genrule/genrule.go
index 5349906..fc6a44f 100644
--- a/genrule/genrule.go
+++ b/genrule/genrule.go
@@ -227,7 +227,7 @@
 // Returns true if information was available from Bazel, false if bazel invocation still needs to occur.
 func (c *Module) generateBazelBuildActions(ctx android.ModuleContext, label string) bool {
 	bazelCtx := ctx.Config().BazelContext
-	filePaths, ok := bazelCtx.GetAllFiles(label, ctx.Arch().ArchType)
+	filePaths, ok := bazelCtx.GetOutputFiles(label, ctx.Arch().ArchType)
 	if ok {
 		var bazelOutputFiles android.Paths
 		for _, bazelOutputFile := range filePaths {
@@ -538,7 +538,7 @@
 
 	g.outputFiles = outputFiles.Paths()
 
-	bazelModuleLabel := g.GetBazelLabel()
+	bazelModuleLabel := g.GetBazelLabel(ctx, g)
 	bazelActionsUsed := false
 	if ctx.Config().BazelContext.BazelEnabled() && len(bazelModuleLabel) > 0 {
 		bazelActionsUsed = g.generateBazelBuildActions(ctx, bazelModuleLabel)
diff --git a/genrule/genrule_test.go b/genrule/genrule_test.go
index 690277c..d131e94 100644
--- a/genrule/genrule_test.go
+++ b/genrule/genrule_test.go
@@ -15,7 +15,6 @@
 package genrule
 
 import (
-	"io/ioutil"
 	"os"
 	"regexp"
 	"testing"
@@ -25,33 +24,12 @@
 	"github.com/google/blueprint/proptools"
 )
 
-var buildDir string
-
-func setUp() {
-	var err error
-	buildDir, err = ioutil.TempDir("", "genrule_test")
-	if err != nil {
-		panic(err)
-	}
-}
-
-func tearDown() {
-	os.RemoveAll(buildDir)
-}
-
 func TestMain(m *testing.M) {
-	run := func() int {
-		setUp()
-		defer tearDown()
-
-		return m.Run()
-	}
-
-	os.Exit(run())
+	os.Exit(m.Run())
 }
 
 var genruleFixtureFactory = android.NewFixtureFactory(
-	&buildDir,
+	nil,
 	android.PrepareForTestWithArchMutator,
 	android.PrepareForTestWithDefaults,
 
@@ -572,8 +550,14 @@
 			cmds: []string{
 				"bash -c '__SBOX_SANDBOX_DIR__/tools/out/bin/tool in1.txt > __SBOX_SANDBOX_DIR__/out/in1.h' && bash -c '__SBOX_SANDBOX_DIR__/tools/out/bin/tool in2.txt > __SBOX_SANDBOX_DIR__/out/in2.h'",
 			},
-			deps:  []string{buildDir + "/.intermediates/gen/gen/gensrcs/in1.h", buildDir + "/.intermediates/gen/gen/gensrcs/in2.h"},
-			files: []string{buildDir + "/.intermediates/gen/gen/gensrcs/in1.h", buildDir + "/.intermediates/gen/gen/gensrcs/in2.h"},
+			deps: []string{
+				"out/soong/.intermediates/gen/gen/gensrcs/in1.h",
+				"out/soong/.intermediates/gen/gen/gensrcs/in2.h",
+			},
+			files: []string{
+				"out/soong/.intermediates/gen/gen/gensrcs/in1.h",
+				"out/soong/.intermediates/gen/gen/gensrcs/in2.h",
+			},
 		},
 		{
 			name: "shards",
@@ -587,8 +571,16 @@
 				"bash -c '__SBOX_SANDBOX_DIR__/tools/out/bin/tool in1.txt > __SBOX_SANDBOX_DIR__/out/in1.h' && bash -c '__SBOX_SANDBOX_DIR__/tools/out/bin/tool in2.txt > __SBOX_SANDBOX_DIR__/out/in2.h'",
 				"bash -c '__SBOX_SANDBOX_DIR__/tools/out/bin/tool in3.txt > __SBOX_SANDBOX_DIR__/out/in3.h'",
 			},
-			deps:  []string{buildDir + "/.intermediates/gen/gen/gensrcs/in1.h", buildDir + "/.intermediates/gen/gen/gensrcs/in2.h", buildDir + "/.intermediates/gen/gen/gensrcs/in3.h"},
-			files: []string{buildDir + "/.intermediates/gen/gen/gensrcs/in1.h", buildDir + "/.intermediates/gen/gen/gensrcs/in2.h", buildDir + "/.intermediates/gen/gen/gensrcs/in3.h"},
+			deps: []string{
+				"out/soong/.intermediates/gen/gen/gensrcs/in1.h",
+				"out/soong/.intermediates/gen/gen/gensrcs/in2.h",
+				"out/soong/.intermediates/gen/gen/gensrcs/in3.h",
+			},
+			files: []string{
+				"out/soong/.intermediates/gen/gen/gensrcs/in1.h",
+				"out/soong/.intermediates/gen/gen/gensrcs/in2.h",
+				"out/soong/.intermediates/gen/gen/gensrcs/in3.h",
+			},
 		},
 	}
 
@@ -616,9 +608,9 @@
 			gen := result.Module("gen", "").(*Module)
 			android.AssertDeepEquals(t, "cmd", test.cmds, gen.rawCommands)
 
-			android.AssertDeepEquals(t, "deps", test.deps, gen.outputDeps.Strings())
+			android.AssertPathsRelativeToTopEquals(t, "deps", test.deps, gen.outputDeps)
 
-			android.AssertDeepEquals(t, "files", test.files, gen.outputFiles.Strings())
+			android.AssertPathsRelativeToTopEquals(t, "files", test.files, gen.outputFiles)
 		})
 	}
 }
diff --git a/java/androidmk_test.go b/java/androidmk_test.go
index e758a92..3477956 100644
--- a/java/androidmk_test.go
+++ b/java/androidmk_test.go
@@ -135,7 +135,10 @@
 }
 
 func TestJavaSdkLibrary_RequireXmlPermissionFile(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo-shared_library", "foo-no_shared_library"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo-shared_library",
 			srcs: ["a.java"],
@@ -148,7 +151,7 @@
 		`)
 
 	// Verify the existence of internal modules
-	ctx.ModuleForTests("foo-shared_library.xml", "android_common")
+	result.ModuleForTests("foo-shared_library.xml", "android_common")
 
 	testCases := []struct {
 		moduleName string
@@ -158,8 +161,8 @@
 		{"foo-no_shared_library", nil},
 	}
 	for _, tc := range testCases {
-		mod := ctx.ModuleForTests(tc.moduleName, "android_common").Module()
-		entries := android.AndroidMkEntriesForTest(t, ctx, mod)[0]
+		mod := result.ModuleForTests(tc.moduleName, "android_common").Module()
+		entries := android.AndroidMkEntriesForTest(t, result.TestContext, mod)[0]
 		actual := entries.EntryMap["LOCAL_REQUIRED_MODULES"]
 		if !reflect.DeepEqual(tc.expected, actual) {
 			t.Errorf("Unexpected required modules - expected: %q, actual: %q", tc.expected, actual)
diff --git a/java/app.go b/java/app.go
index eef627c..1b6e0e3 100755
--- a/java/app.go
+++ b/java/app.go
@@ -302,7 +302,7 @@
 // This check is enforced for "updatable" APKs (including APK-in-APEX).
 // b/155209650: until min_sdk_version is properly supported, use sdk_version instead.
 // because, sdk_version is overridden by min_sdk_version (if set as smaller)
-// and linkType is checked with dependencies so we can be sure that the whole dependency tree
+// and sdkLinkType is checked with dependencies so we can be sure that the whole dependency tree
 // will meet the requirements.
 func (a *AndroidApp) checkJniLibsSdkVersion(ctx android.ModuleContext, minSdkVersion sdkVersion) {
 	// It's enough to check direct JNI deps' sdk_version because all transitive deps from JNI deps are checked in cc.checkLinkType()
@@ -1281,10 +1281,13 @@
 	u.usesLibraryProperties.Enforce_uses_libs = &enforce
 }
 
-// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against the ones specified
-// in the uses_libs and optional_uses_libs properties.  It returns the path to a copy of the manifest.
-func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
-	outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
+// verifyUsesLibraries checks the <uses-library> tags in the manifest against the ones specified
+// in the `uses_libs`/`optional_uses_libs` properties. The input can be either an XML manifest, or
+// an APK with the manifest embedded in it (manifest_check will know which one it is by the file
+// extension: APKs are supposed to end with '.apk').
+func (u *usesLibrary) verifyUsesLibraries(ctx android.ModuleContext, inputFile android.Path,
+	outputFile android.WritablePath) android.Path {
+
 	statusFile := dexpreopt.UsesLibrariesStatusFile(ctx)
 
 	// Disable verify_uses_libraries check if dexpreopt is globally disabled. Without dexpreopt the
@@ -1292,15 +1295,19 @@
 	// non-linux build platforms where dexpreopt is generally disabled (the check may fail due to
 	// various unrelated reasons, such as a failure to get manifest from an APK).
 	if dexpreopt.GetGlobalConfig(ctx).DisablePreopt {
-		return manifest
+		return inputFile
 	}
 
 	rule := android.NewRuleBuilder(pctx, ctx)
 	cmd := rule.Command().BuiltTool("manifest_check").
 		Flag("--enforce-uses-libraries").
-		Input(manifest).
+		Input(inputFile).
 		FlagWithOutput("--enforce-uses-libraries-status ", statusFile).
-		FlagWithOutput("-o ", outputFile)
+		FlagWithInput("--aapt ", ctx.Config().HostToolPath(ctx, "aapt"))
+
+	if outputFile != nil {
+		cmd.FlagWithOutput("-o ", outputFile)
+	}
 
 	if dexpreopt.GetGlobalConfig(ctx).RelaxUsesLibraryCheck {
 		cmd.Flag("--enforce-uses-libraries-relax")
@@ -1315,35 +1322,20 @@
 	}
 
 	rule.Build("verify_uses_libraries", "verify <uses-library>")
-
 	return outputFile
 }
 
-// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the ones specified
-// in the uses_libs and optional_uses_libs properties.  It returns the path to a copy of the APK.
+// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against
+// the build system and returns the path to a copy of the manifest.
+func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
+	outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
+	return u.verifyUsesLibraries(ctx, manifest, outputFile)
+}
+
+// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the build
+// system and returns the path to a copy of the APK.
 func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
+	u.verifyUsesLibraries(ctx, apk, nil) // for APKs manifest_check does not write output file
 	outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
-	statusFile := dexpreopt.UsesLibrariesStatusFile(ctx)
-
-	// Disable verify_uses_libraries check if dexpreopt is globally disabled. Without dexpreopt the
-	// check is not necessary, and although it is good to have, it is difficult to maintain on
-	// non-linux build platforms where dexpreopt is generally disabled (the check may fail due to
-	// various unrelated reasons, such as a failure to get manifest from an APK).
-	if dexpreopt.GetGlobalConfig(ctx).DisablePreopt {
-		return apk
-	}
-
-	rule := android.NewRuleBuilder(pctx, ctx)
-	aapt := ctx.Config().HostToolPath(ctx, "aapt")
-	rule.Command().
-		Textf("aapt_binary=%s", aapt.String()).Implicit(aapt).
-		Textf(`uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Uses_libs, " ")).
-		Textf(`optional_uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Optional_uses_libs, " ")).
-		Textf(`relax_check="%t"`, dexpreopt.GetGlobalConfig(ctx).RelaxUsesLibraryCheck).
-		Tool(android.PathForSource(ctx, "build/make/core/verify_uses_libraries.sh")).Input(apk).Output(statusFile)
-	rule.Command().Text("cp -f").Input(apk).Output(outputFile)
-
-	rule.Build("verify_uses_libraries", "verify <uses-library>")
-
 	return outputFile
 }
diff --git a/java/app_test.go b/java/app_test.go
index 3b37473..c189ee5 100644
--- a/java/app_test.go
+++ b/java/app_test.go
@@ -2400,13 +2400,13 @@
 
 	// Test that all libraries are verified for an APK (library order matters).
 	verifyApkCmd := prebuilt.Rule("verify_uses_libraries").RuleParams.Command
-	verifyApkReqLibs := `uses_library_names="foo com.non.sdk.lib android.test.runner"`
-	verifyApkOptLibs := `optional_uses_library_names="bar baz"`
-	if !strings.Contains(verifyApkCmd, verifyApkReqLibs) {
-		t.Errorf("wanted %q in %q", verifyApkReqLibs, verifyApkCmd)
-	}
-	if !strings.Contains(verifyApkCmd, verifyApkOptLibs) {
-		t.Errorf("wanted %q in %q", verifyApkOptLibs, verifyApkCmd)
+	verifyApkArgs := `--uses-library foo ` +
+		`--uses-library com.non.sdk.lib ` +
+		`--uses-library android.test.runner ` +
+		`--optional-uses-library bar ` +
+		`--optional-uses-library baz `
+	if !strings.Contains(verifyApkCmd, verifyApkArgs) {
+		t.Errorf("wanted %q in %q", verifyApkArgs, verifyApkCmd)
 	}
 
 	// Test that all present libraries are preopted, including implicit SDK dependencies, possibly stubs
diff --git a/java/hiddenapi_singleton.go b/java/hiddenapi_singleton.go
index 82e8b3f..6ad4ff3 100644
--- a/java/hiddenapi_singleton.go
+++ b/java/hiddenapi_singleton.go
@@ -31,6 +31,8 @@
 	ctx.RegisterModuleType("hiddenapi_flags", hiddenAPIFlagsFactory)
 }
 
+var PrepareForTestWithHiddenApiBuildComponents = android.FixtureRegisterWithContext(RegisterHiddenApiSingletonComponents)
+
 type hiddenAPISingletonPathsStruct struct {
 	// The path to the CSV file that contains the flags that will be encoded into the dex boot jars.
 	//
diff --git a/java/hiddenapi_singleton_test.go b/java/hiddenapi_singleton_test.go
index fb63820..f17d436 100644
--- a/java/hiddenapi_singleton_test.go
+++ b/java/hiddenapi_singleton_test.go
@@ -16,68 +16,50 @@
 
 import (
 	"fmt"
-	"strings"
+	"path/filepath"
 	"testing"
 
 	"android/soong/android"
-
 	"github.com/google/blueprint/proptools"
 )
 
-func testConfigWithBootJars(bp string, bootJars []string, prebuiltHiddenApiDir *string) android.Config {
-	config := testConfig(nil, bp, nil)
-	config.TestProductVariables.BootJars = android.CreateTestConfiguredJarList(bootJars)
-	config.TestProductVariables.PrebuiltHiddenApiDir = prebuiltHiddenApiDir
-	return config
+func fixtureSetBootJarsProductVariable(bootJars ...string) android.FixturePreparer {
+	return android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
+		variables.BootJars = android.CreateTestConfiguredJarList(bootJars)
+	})
 }
 
-func testContextWithHiddenAPI(config android.Config) *android.TestContext {
-	ctx := testContext(config)
-	RegisterHiddenApiSingletonComponents(ctx)
-	return ctx
+func fixtureSetPrebuiltHiddenApiDirProductVariable(prebuiltHiddenApiDir *string) android.FixturePreparer {
+	return android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
+		variables.PrebuiltHiddenApiDir = prebuiltHiddenApiDir
+	})
 }
 
-func testHiddenAPIWithConfig(t *testing.T, config android.Config) *android.TestContext {
-	t.Helper()
-
-	ctx := testContextWithHiddenAPI(config)
-
-	run(t, ctx, config)
-	return ctx
-}
-
-func testHiddenAPIBootJars(t *testing.T, bp string, bootJars []string, prebuiltHiddenApiDir *string) (*android.TestContext, android.Config) {
-	config := testConfigWithBootJars(bp, bootJars, prebuiltHiddenApiDir)
-
-	return testHiddenAPIWithConfig(t, config), config
-}
-
-func testHiddenAPIUnbundled(t *testing.T, unbundled bool) (*android.TestContext, android.Config) {
-	config := testConfig(nil, ``, nil)
-	config.TestProductVariables.Always_use_prebuilt_sdks = proptools.BoolPtr(unbundled)
-
-	return testHiddenAPIWithConfig(t, config), config
-}
+var hiddenApiFixtureFactory = javaFixtureFactory.Extend(PrepareForTestWithHiddenApiBuildComponents)
 
 func TestHiddenAPISingleton(t *testing.T) {
-	ctx, _ := testHiddenAPIBootJars(t, `
+	result := hiddenApiFixtureFactory.Extend(
+		fixtureSetBootJarsProductVariable("platform:foo"),
+	).RunTestWithBp(t, `
 		java_library {
 			name: "foo",
 			srcs: ["a.java"],
 			compile_dex: true,
 		}
-	`, []string{"platform:foo"}, nil)
+	`)
 
-	hiddenAPI := ctx.SingletonForTests("hiddenapi")
+	hiddenAPI := result.SingletonForTests("hiddenapi")
 	hiddenapiRule := hiddenAPI.Rule("hiddenapi")
 	want := "--boot-dex=" + buildDir + "/.intermediates/foo/android_common/aligned/foo.jar"
-	if !strings.Contains(hiddenapiRule.RuleParams.Command, want) {
-		t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", want, hiddenapiRule.RuleParams.Command)
-	}
+	android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, want)
 }
 
 func TestHiddenAPIIndexSingleton(t *testing.T) {
-	ctx, _ := testHiddenAPIBootJars(t, `
+	result := hiddenApiFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("bar"),
+		fixtureSetBootJarsProductVariable("platform:foo", "platform:bar"),
+	).RunTestWithBp(t, `
 		java_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -106,9 +88,9 @@
 			srcs: ["a.java"],
 			compile_dex: true,
 		}
-	`, []string{"platform:foo", "platform:bar"}, nil)
+	`)
 
-	hiddenAPIIndex := ctx.SingletonForTests("hiddenapi_index")
+	hiddenAPIIndex := result.SingletonForTests("hiddenapi_index")
 	indexRule := hiddenAPIIndex.Rule("singleton-merged-hiddenapi-index")
 	CheckHiddenAPIRuleInputs(t, `
 .intermediates/bar/android_common/hiddenapi/index.csv
@@ -118,7 +100,7 @@
 
 	// Make sure that the foo-hiddenapi-annotations.jar is included in the inputs to the rules that
 	// creates the index.csv file.
-	foo := ctx.ModuleForTests("foo", "android_common")
+	foo := result.ModuleForTests("foo", "android_common")
 	indexParams := foo.Output("hiddenapi/index.csv")
 	CheckHiddenAPIRuleInputs(t, `
 .intermediates/foo-hiddenapi-annotations/android_common/javac/foo-hiddenapi-annotations.jar
@@ -127,7 +109,15 @@
 }
 
 func TestHiddenAPISingletonWithSourceAndPrebuiltPreferredButNoDex(t *testing.T) {
-	config := testConfigWithBootJars(`
+	expectedErrorMessage :=
+		"hiddenapi has determined that the source module \"foo\" should be ignored as it has been" +
+			" replaced by the prebuilt module \"prebuilt_foo\" but unfortunately it does not provide a" +
+			" suitable boot dex jar"
+
+	hiddenApiFixtureFactory.Extend(
+		fixtureSetBootJarsProductVariable("platform:foo"),
+	).ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(expectedErrorMessage)).
+		RunTestWithBp(t, `
 		java_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -139,35 +129,30 @@
 			jars: ["a.jar"],
 			prefer: true,
 		}
-	`, []string{"platform:foo"}, nil)
-
-	ctx := testContextWithHiddenAPI(config)
-
-	runWithErrors(t, ctx, config,
-		"hiddenapi has determined that the source module \"foo\" should be ignored as it has been"+
-			" replaced by the prebuilt module \"prebuilt_foo\" but unfortunately it does not provide a"+
-			" suitable boot dex jar")
+	`)
 }
 
 func TestHiddenAPISingletonWithPrebuilt(t *testing.T) {
-	ctx, _ := testHiddenAPIBootJars(t, `
+	result := hiddenApiFixtureFactory.Extend(
+		fixtureSetBootJarsProductVariable("platform:foo"),
+	).RunTestWithBp(t, `
 		java_import {
 			name: "foo",
 			jars: ["a.jar"],
 			compile_dex: true,
 	}
-	`, []string{"platform:foo"}, nil)
+	`)
 
-	hiddenAPI := ctx.SingletonForTests("hiddenapi")
+	hiddenAPI := result.SingletonForTests("hiddenapi")
 	hiddenapiRule := hiddenAPI.Rule("hiddenapi")
 	want := "--boot-dex=" + buildDir + "/.intermediates/foo/android_common/aligned/foo.jar"
-	if !strings.Contains(hiddenapiRule.RuleParams.Command, want) {
-		t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", want, hiddenapiRule.RuleParams.Command)
-	}
+	android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, want)
 }
 
 func TestHiddenAPISingletonWithPrebuiltUseSource(t *testing.T) {
-	ctx, _ := testHiddenAPIBootJars(t, `
+	result := hiddenApiFixtureFactory.Extend(
+		fixtureSetBootJarsProductVariable("platform:foo"),
+	).RunTestWithBp(t, `
 		java_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -180,23 +165,21 @@
 			compile_dex: true,
 			prefer: false,
 		}
-	`, []string{"platform:foo"}, nil)
+	`)
 
-	hiddenAPI := ctx.SingletonForTests("hiddenapi")
+	hiddenAPI := result.SingletonForTests("hiddenapi")
 	hiddenapiRule := hiddenAPI.Rule("hiddenapi")
 	fromSourceJarArg := "--boot-dex=" + buildDir + "/.intermediates/foo/android_common/aligned/foo.jar"
-	if !strings.Contains(hiddenapiRule.RuleParams.Command, fromSourceJarArg) {
-		t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", fromSourceJarArg, hiddenapiRule.RuleParams.Command)
-	}
+	android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, fromSourceJarArg)
 
 	prebuiltJarArg := "--boot-dex=" + buildDir + "/.intermediates/foo/android_common/dex/foo.jar"
-	if strings.Contains(hiddenapiRule.RuleParams.Command, prebuiltJarArg) {
-		t.Errorf("Did not expect %s in hiddenapi command, but it was present: %s", prebuiltJarArg, hiddenapiRule.RuleParams.Command)
-	}
+	android.AssertStringDoesNotContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, prebuiltJarArg)
 }
 
 func TestHiddenAPISingletonWithPrebuiltOverrideSource(t *testing.T) {
-	ctx, _ := testHiddenAPIBootJars(t, `
+	result := hiddenApiFixtureFactory.Extend(
+		fixtureSetBootJarsProductVariable("platform:foo"),
+	).RunTestWithBp(t, `
 		java_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -209,19 +192,15 @@
 			compile_dex: true,
 			prefer: true,
 		}
-	`, []string{"platform:foo"}, nil)
+	`)
 
-	hiddenAPI := ctx.SingletonForTests("hiddenapi")
+	hiddenAPI := result.SingletonForTests("hiddenapi")
 	hiddenapiRule := hiddenAPI.Rule("hiddenapi")
 	prebuiltJarArg := "--boot-dex=" + buildDir + "/.intermediates/prebuilt_foo/android_common/dex/foo.jar"
-	if !strings.Contains(hiddenapiRule.RuleParams.Command, prebuiltJarArg) {
-		t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", prebuiltJarArg, hiddenapiRule.RuleParams.Command)
-	}
+	android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, prebuiltJarArg)
 
 	fromSourceJarArg := "--boot-dex=" + buildDir + "/.intermediates/foo/android_common/aligned/foo.jar"
-	if strings.Contains(hiddenapiRule.RuleParams.Command, fromSourceJarArg) {
-		t.Errorf("Did not expect %s in hiddenapi command, but it was present: %s", fromSourceJarArg, hiddenapiRule.RuleParams.Command)
-	}
+	android.AssertStringDoesNotContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, fromSourceJarArg)
 }
 
 func TestHiddenAPISingletonSdks(t *testing.T) {
@@ -232,6 +211,9 @@
 		systemStub       string
 		testStub         string
 		corePlatformStub string
+
+		// Additional test preparer
+		preparer android.FixturePreparer
 	}{
 		{
 			name:             "testBundled",
@@ -240,6 +222,7 @@
 			systemStub:       "android_system_stubs_current",
 			testStub:         "android_test_stubs_current",
 			corePlatformStub: "legacy.core.platform.api.stubs",
+			preparer:         android.GroupFixturePreparers(),
 		}, {
 			name:             "testUnbundled",
 			unbundledBuild:   true,
@@ -247,33 +230,31 @@
 			systemStub:       "sdk_system_current_android",
 			testStub:         "sdk_test_current_android",
 			corePlatformStub: "legacy.core.platform.api.stubs",
+			preparer:         PrepareForTestWithPrebuiltsOfCurrentApi,
 		},
 	}
 	for _, tc := range testCases {
 		t.Run(tc.name, func(t *testing.T) {
-			ctx, _ := testHiddenAPIUnbundled(t, tc.unbundledBuild)
+			result := hiddenApiFixtureFactory.Extend(
+				tc.preparer,
+				android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
+					variables.Always_use_prebuilt_sdks = proptools.BoolPtr(tc.unbundledBuild)
+				}),
+			).RunTest(t)
 
-			hiddenAPI := ctx.SingletonForTests("hiddenapi")
+			hiddenAPI := result.SingletonForTests("hiddenapi")
 			hiddenapiRule := hiddenAPI.Rule("hiddenapi")
 			wantPublicStubs := "--public-stub-classpath=" + generateSdkDexPath(tc.publicStub, tc.unbundledBuild)
-			if !strings.Contains(hiddenapiRule.RuleParams.Command, wantPublicStubs) {
-				t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", wantPublicStubs, hiddenapiRule.RuleParams.Command)
-			}
+			android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, wantPublicStubs)
 
 			wantSystemStubs := "--system-stub-classpath=" + generateSdkDexPath(tc.systemStub, tc.unbundledBuild)
-			if !strings.Contains(hiddenapiRule.RuleParams.Command, wantSystemStubs) {
-				t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", wantSystemStubs, hiddenapiRule.RuleParams.Command)
-			}
+			android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, wantSystemStubs)
 
 			wantTestStubs := "--test-stub-classpath=" + generateSdkDexPath(tc.testStub, tc.unbundledBuild)
-			if !strings.Contains(hiddenapiRule.RuleParams.Command, wantTestStubs) {
-				t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", wantTestStubs, hiddenapiRule.RuleParams.Command)
-			}
+			android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, wantTestStubs)
 
-			wantCorePlatformStubs := "--core-platform-stub-classpath=" + generateDexPath(tc.corePlatformStub)
-			if !strings.Contains(hiddenapiRule.RuleParams.Command, wantCorePlatformStubs) {
-				t.Errorf("Expected %s in hiddenapi command, but it was not present: %s", wantCorePlatformStubs, hiddenapiRule.RuleParams.Command)
-			}
+			wantCorePlatformStubs := "--core-platform-stub-classpath=" + generateDexPath(defaultJavaDir, tc.corePlatformStub)
+			android.AssertStringDoesContain(t, "hiddenapi command", hiddenapiRule.RuleParams.Command, wantCorePlatformStubs)
 		})
 	}
 }
@@ -282,15 +263,15 @@
 	return fmt.Sprintf("%s/.intermediates/%s/android_common/%s/%s.jar", buildDir, subDir, dex, module)
 }
 
-func generateDexPath(module string) string {
-	return generateDexedPath(module, "dex", module)
+func generateDexPath(moduleDir string, module string) string {
+	return generateDexedPath(filepath.Join(moduleDir, module), "dex", module)
 }
 
 func generateSdkDexPath(module string, unbundled bool) string {
 	if unbundled {
 		return generateDexedPath("prebuilts/sdk/"+module, "dex", module)
 	}
-	return generateDexPath(module)
+	return generateDexPath(defaultJavaDir, module)
 }
 
 func TestHiddenAPISingletonWithPrebuiltCsvFile(t *testing.T) {
@@ -304,36 +285,33 @@
 	// Where to find the prebuilt hiddenapi files:
 	prebuiltHiddenApiDir := "path/to/prebuilt/hiddenapi"
 
-	ctx, _ := testHiddenAPIBootJars(t, `
+	result := hiddenApiFixtureFactory.Extend(
+		fixtureSetBootJarsProductVariable("platform:foo"),
+		fixtureSetPrebuiltHiddenApiDirProductVariable(&prebuiltHiddenApiDir),
+	).RunTestWithBp(t, `
 		java_import {
 			name: "foo",
 			jars: ["a.jar"],
 			compile_dex: true,
 	}
-	`, []string{"platform:foo"}, &prebuiltHiddenApiDir)
+	`)
 
 	expectedCpInput := prebuiltHiddenApiDir + "/hiddenapi-flags.csv"
 	expectedCpOutput := buildDir + "/hiddenapi/hiddenapi-flags.csv"
 	expectedFlagsCsv := buildDir + "/hiddenapi/hiddenapi-flags.csv"
 
-	foo := ctx.ModuleForTests("foo", "android_common")
+	foo := result.ModuleForTests("foo", "android_common")
 
-	hiddenAPI := ctx.SingletonForTests("hiddenapi")
+	hiddenAPI := result.SingletonForTests("hiddenapi")
 	cpRule := hiddenAPI.Rule("Cp")
 	actualCpInput := cpRule.BuildParams.Input
 	actualCpOutput := cpRule.BuildParams.Output
 	encodeDexRule := foo.Rule("hiddenAPIEncodeDex")
 	actualFlagsCsv := encodeDexRule.BuildParams.Args["flagsCsv"]
 
-	if actualCpInput.String() != expectedCpInput {
-		t.Errorf("Prebuilt hiddenapi cp rule input mismatch, actual: %s, expected: %s", actualCpInput, expectedCpInput)
-	}
+	android.AssertStringEquals(t, "hiddenapi cp rule input", expectedCpInput, actualCpInput.String())
 
-	if actualCpOutput.String() != expectedCpOutput {
-		t.Errorf("Prebuilt hiddenapi cp rule output mismatch, actual: %s, expected: %s", actualCpOutput, expectedCpOutput)
-	}
+	android.AssertStringEquals(t, "hiddenapi cp rule output", expectedCpOutput, actualCpOutput.String())
 
-	if actualFlagsCsv != expectedFlagsCsv {
-		t.Errorf("Prebuilt hiddenapi encode dex rule flags csv mismatch, actual: %s, expected: %s", actualFlagsCsv, expectedFlagsCsv)
-	}
+	android.AssertStringEquals(t, "hiddenapi encode dex rule flags csv", expectedFlagsCsv, actualFlagsCsv)
 }
diff --git a/java/java.go b/java/java.go
index 036c7af..8c714ee 100644
--- a/java/java.go
+++ b/java/java.go
@@ -37,6 +37,36 @@
 func init() {
 	RegisterJavaBuildComponents(android.InitRegistrationContext)
 
+	RegisterJavaSdkMemberTypes()
+}
+
+func RegisterJavaBuildComponents(ctx android.RegistrationContext) {
+	ctx.RegisterModuleType("java_defaults", DefaultsFactory)
+
+	ctx.RegisterModuleType("java_library", LibraryFactory)
+	ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
+	ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
+	ctx.RegisterModuleType("java_binary", BinaryFactory)
+	ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
+	ctx.RegisterModuleType("java_test", TestFactory)
+	ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
+	ctx.RegisterModuleType("java_test_host", TestHostFactory)
+	ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
+	ctx.RegisterModuleType("java_import", ImportFactory)
+	ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
+	ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
+	ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
+	ctx.RegisterModuleType("dex_import", DexImportFactory)
+
+	ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
+		ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
+	})
+
+	ctx.RegisterSingletonType("logtags", LogtagsSingleton)
+	ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
+}
+
+func RegisterJavaSdkMemberTypes() {
 	// Register sdk member types.
 	android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
 
@@ -89,85 +119,7 @@
 			PropertyName: "java_tests",
 		},
 	})
-}
 
-func RegisterJavaBuildComponents(ctx android.RegistrationContext) {
-	ctx.RegisterModuleType("java_defaults", DefaultsFactory)
-
-	ctx.RegisterModuleType("java_library", LibraryFactory)
-	ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
-	ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
-	ctx.RegisterModuleType("java_binary", BinaryFactory)
-	ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
-	ctx.RegisterModuleType("java_test", TestFactory)
-	ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
-	ctx.RegisterModuleType("java_test_host", TestHostFactory)
-	ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
-	ctx.RegisterModuleType("java_import", ImportFactory)
-	ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
-	ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
-	ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
-	ctx.RegisterModuleType("dex_import", DexImportFactory)
-
-	ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
-		ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
-	})
-
-	ctx.RegisterSingletonType("logtags", LogtagsSingleton)
-	ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
-}
-
-func (j *Module) CheckStableSdkVersion() error {
-	sdkVersion := j.sdkVersion()
-	if sdkVersion.stable() {
-		return nil
-	}
-	if sdkVersion.kind == sdkCorePlatform {
-		if useLegacyCorePlatformApiByName(j.BaseModuleName()) {
-			return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
-		} else {
-			// Treat stable core platform as stable.
-			return nil
-		}
-	} else {
-		return fmt.Errorf("non stable SDK %v", sdkVersion)
-	}
-}
-
-func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
-	if j.RequiresStableAPIs(ctx) {
-		if sc, ok := ctx.Module().(sdkContext); ok {
-			if !sc.sdkVersion().specified() {
-				ctx.PropertyErrorf("sdk_version",
-					"sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
-			}
-		}
-	}
-
-	ctx.VisitDirectDeps(func(module android.Module) {
-		tag := ctx.OtherModuleDependencyTag(module)
-		switch module.(type) {
-		// TODO(satayev): cover other types as well, e.g. imports
-		case *Library, *AndroidLibrary:
-			switch tag {
-			case bootClasspathTag, libTag, staticLibTag, java9LibTag:
-				checkLinkType(ctx, j, module.(linkTypeContext), tag.(dependencyTag))
-			}
-		}
-	})
-}
-
-func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
-	if sc, ok := ctx.Module().(sdkContext); ok {
-		usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
-		sdkVersionSpecified := sc.sdkVersion().specified()
-		if usePlatformAPI && sdkVersionSpecified {
-			ctx.PropertyErrorf("platform_apis", "platform_apis must be false when sdk_version is not empty.")
-		} else if !usePlatformAPI && !sdkVersionSpecified {
-			ctx.PropertyErrorf("platform_apis", "platform_apis must be true when sdk_version is empty.")
-		}
-
-	}
 }
 
 // TODO:
@@ -179,7 +131,8 @@
 // DroidDoc
 // Findbugs
 
-type CompilerProperties struct {
+// Properties that are common to most Java modules, i.e. whether it's a host or device module.
+type CommonProperties struct {
 	// list of source files used to compile the Java module.  May be .java, .kt, .logtags, .proto,
 	// or .aidl files.
 	Srcs []string `android:"path,arch_variant"`
@@ -312,7 +265,9 @@
 	Hiddenapi_additional_annotations []string
 }
 
-type CompilerDeviceProperties struct {
+// Properties that are specific to device modules. Host module factories should not add these when
+// constructing a new module.
+type DeviceProperties struct {
 	// if not blank, set to the version of the sdk to compile against.
 	// Defaults to compiling against the current platform.
 	Sdk_version *string
@@ -421,9 +376,9 @@
 	// Functionality common to Module and Import.
 	embeddableInModuleAndImport
 
-	properties       CompilerProperties
+	properties       CommonProperties
 	protoProperties  android.ProtoProperties
-	deviceProperties CompilerDeviceProperties
+	deviceProperties DeviceProperties
 
 	// jar file containing header classes including static library dependencies, suitable for
 	// inserting into the bootclasspath/classpath of another compile
@@ -508,6 +463,62 @@
 	hideApexVariantFromMake bool
 }
 
+func (j *Module) CheckStableSdkVersion() error {
+	sdkVersion := j.sdkVersion()
+	if sdkVersion.stable() {
+		return nil
+	}
+	if sdkVersion.kind == sdkCorePlatform {
+		if useLegacyCorePlatformApiByName(j.BaseModuleName()) {
+			return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
+		} else {
+			// Treat stable core platform as stable.
+			return nil
+		}
+	} else {
+		return fmt.Errorf("non stable SDK %v", sdkVersion)
+	}
+}
+
+// checkSdkVersions enforces restrictions around SDK dependencies.
+func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
+	if j.RequiresStableAPIs(ctx) {
+		if sc, ok := ctx.Module().(sdkContext); ok {
+			if !sc.sdkVersion().specified() {
+				ctx.PropertyErrorf("sdk_version",
+					"sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
+			}
+		}
+	}
+
+	// Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
+	// See rank() for details.
+	ctx.VisitDirectDeps(func(module android.Module) {
+		tag := ctx.OtherModuleDependencyTag(module)
+		switch module.(type) {
+		// TODO(satayev): cover other types as well, e.g. imports
+		case *Library, *AndroidLibrary:
+			switch tag {
+			case bootClasspathTag, libTag, staticLibTag, java9LibTag:
+				j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
+			}
+		}
+	})
+}
+
+func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
+	if sc, ok := ctx.Module().(sdkContext); ok {
+		usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
+		sdkVersionSpecified := sc.sdkVersion().specified()
+		if usePlatformAPI && sdkVersionSpecified {
+			ctx.PropertyErrorf("platform_apis", "platform_apis must be false when sdk_version is not empty.")
+		} else if !usePlatformAPI && !sdkVersionSpecified {
+			ctx.PropertyErrorf("platform_apis", "platform_apis must be true when sdk_version is empty.")
+		}
+
+	}
+}
+
 func (j *Module) addHostProperties() {
 	j.AddProperties(
 		&j.properties,
@@ -1008,13 +1019,13 @@
 	}
 }
 
-type linkType int
+type sdkLinkType int
 
 const (
 	// TODO(jiyong) rename these for better readability. Make the allowed
 	// and disallowed link types explicit
 	// order is important here. See rank()
-	javaCore linkType = iota
+	javaCore sdkLinkType = iota
 	javaSdk
 	javaSystem
 	javaModule
@@ -1022,7 +1033,7 @@
 	javaPlatform
 )
 
-func (lt linkType) String() string {
+func (lt sdkLinkType) String() string {
 	switch lt {
 	case javaCore:
 		return "core Java API"
@@ -1041,18 +1052,19 @@
 	}
 }
 
-// rank determins the total order among linkTypes. A link type of rank A can link to another link
-// type of rank B only when B <= A
-func (lt linkType) rank() int {
+// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
+// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
+// can't statically depend on modules that use Platform API.
+func (lt sdkLinkType) rank() int {
 	return int(lt)
 }
 
-type linkTypeContext interface {
+type moduleWithSdkDep interface {
 	android.Module
-	getLinkType(name string) (ret linkType, stubs bool)
+	getSdkLinkType(name string) (ret sdkLinkType, stubs bool)
 }
 
-func (m *Module) getLinkType(name string) (ret linkType, stubs bool) {
+func (m *Module) getSdkLinkType(name string) (ret sdkLinkType, stubs bool) {
 	switch name {
 	case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
 		"stub-annotations", "private-stub-annotations-jar",
@@ -1096,23 +1108,26 @@
 	return javaSdk, false
 }
 
-func checkLinkType(ctx android.ModuleContext, from *Module, to linkTypeContext, tag dependencyTag) {
+// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
+// this module's. See the comment on rank() for details and an example.
+func (j *Module) checkSdkLinkType(
+	ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
 	if ctx.Host() {
 		return
 	}
 
-	myLinkType, stubs := from.getLinkType(ctx.ModuleName())
+	myLinkType, stubs := j.getSdkLinkType(ctx.ModuleName())
 	if stubs {
 		return
 	}
-	otherLinkType, _ := to.getLinkType(ctx.OtherModuleName(to))
+	depLinkType, _ := dep.getSdkLinkType(ctx.OtherModuleName(dep))
 
-	if myLinkType.rank() < otherLinkType.rank() {
+	if myLinkType.rank() < depLinkType.rank() {
 		ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
 			"In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
 			"property of the source or target module so that target module is built "+
 			"with the same or smaller API set when compared to the source.",
-			myLinkType, ctx.OtherModuleName(to), otherLinkType)
+			myLinkType, ctx.OtherModuleName(dep), depLinkType)
 	}
 }
 
@@ -1133,7 +1148,7 @@
 		}
 	}
 
-	linkType, _ := j.getLinkType(ctx.ModuleName())
+	sdkLinkType, _ := j.getSdkLinkType(ctx.ModuleName())
 
 	ctx.VisitDirectDeps(func(module android.Module) {
 		otherName := ctx.OtherModuleName(module)
@@ -1157,7 +1172,7 @@
 			}
 		} else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
 			dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
-			if linkType != javaPlatform &&
+			if sdkLinkType != javaPlatform &&
 				ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
 				// dep is a sysprop implementation library, but this module is not linking against
 				// the platform, so it gets the sysprop public stubs library instead.  Replace
@@ -2505,6 +2520,10 @@
 	j.deps(ctx)
 }
 
+func (j *TestHost) AddExtraResource(p android.Path) {
+	j.extraResources = append(j.extraResources, p)
+}
+
 func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
 		// TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
@@ -2668,13 +2687,23 @@
 	module.AddProperties(&module.testProperties)
 	module.AddProperties(&module.testHostProperties)
 
-	module.Module.properties.Installable = proptools.BoolPtr(true)
+	InitTestHost(
+		module,
+		proptools.BoolPtr(true),
+		nil,
+		nil)
 
 	InitJavaModuleMultiTargets(module, android.HostSupported)
 
 	return module
 }
 
+func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
+	th.properties.Installable = installable
+	th.testProperties.Auto_gen_config = autoGenConfig
+	th.testProperties.Test_suites = testSuites
+}
+
 //
 // Java Binaries (.jar file plus wrapper script)
 //
@@ -3332,8 +3361,8 @@
 	module := &Defaults{}
 
 	module.AddProperties(
-		&CompilerProperties{},
-		&CompilerDeviceProperties{},
+		&CommonProperties{},
+		&DeviceProperties{},
 		&DexProperties{},
 		&DexpreoptProperties{},
 		&android.ProtoProperties{},
diff --git a/java/java_test.go b/java/java_test.go
index 9ef23e9..2eb7241 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -369,13 +369,9 @@
 	barTurbine := filepath.Join(buildDir, ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
 	bazTurbine := filepath.Join(buildDir, ".intermediates", "baz", "android_common", "turbine-combined", "baz.jar")
 
-	if !strings.Contains(javac.Args["classpath"], barTurbine) {
-		t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], barTurbine)
-	}
+	android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], barTurbine)
 
-	if !strings.Contains(javac.Args["classpath"], bazTurbine) {
-		t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], bazTurbine)
-	}
+	android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], bazTurbine)
 
 	if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != baz {
 		t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, baz)
@@ -745,7 +741,7 @@
 }
 
 func TestJavaSdkLibraryImport(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.RunTestWithBp(t, `
 		java_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -783,16 +779,14 @@
 		`)
 
 	for _, scope := range []string{"", ".system", ".test"} {
-		fooModule := ctx.ModuleForTests("foo"+scope, "android_common")
+		fooModule := result.ModuleForTests("foo"+scope, "android_common")
 		javac := fooModule.Rule("javac")
 
-		sdklibStubsJar := ctx.ModuleForTests("sdklib.stubs"+scope, "android_common").Rule("combineJar").Output
-		if !strings.Contains(javac.Args["classpath"], sdklibStubsJar.String()) {
-			t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], sdklibStubsJar.String())
-		}
+		sdklibStubsJar := result.ModuleForTests("sdklib.stubs"+scope, "android_common").Rule("combineJar").Output
+		android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], sdklibStubsJar.String())
 	}
 
-	CheckModuleDependencies(t, ctx, "sdklib", "android_common", []string{
+	CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
 		`prebuilt_sdklib.stubs`,
 		`prebuilt_sdklib.stubs.source.test`,
 		`prebuilt_sdklib.stubs.system`,
@@ -801,7 +795,10 @@
 }
 
 func TestJavaSdkLibraryImport_WithSource(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("sdklib"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "sdklib",
 			srcs: ["a.java"],
@@ -820,7 +817,7 @@
 		}
 		`)
 
-	CheckModuleDependencies(t, ctx, "sdklib", "android_common", []string{
+	CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
 		`dex2oatd`,
 		`prebuilt_sdklib`,
 		`sdklib.impl`,
@@ -829,7 +826,7 @@
 		`sdklib.xml`,
 	})
 
-	CheckModuleDependencies(t, ctx, "prebuilt_sdklib", "android_common", []string{
+	CheckModuleDependencies(t, result.TestContext, "prebuilt_sdklib", "android_common", []string{
 		`prebuilt_sdklib.stubs`,
 		`sdklib.impl`,
 		// This should be prebuilt_sdklib.stubs but is set to sdklib.stubs because the
@@ -840,7 +837,10 @@
 }
 
 func TestJavaSdkLibraryImport_Preferred(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("sdklib"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "sdklib",
 			srcs: ["a.java"],
@@ -860,7 +860,7 @@
 		}
 		`)
 
-	CheckModuleDependencies(t, ctx, "sdklib", "android_common", []string{
+	CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
 		`dex2oatd`,
 		`prebuilt_sdklib`,
 		`sdklib.impl`,
@@ -869,7 +869,7 @@
 		`sdklib.xml`,
 	})
 
-	CheckModuleDependencies(t, ctx, "prebuilt_sdklib", "android_common", []string{
+	CheckModuleDependencies(t, result.TestContext, "prebuilt_sdklib", "android_common", []string{
 		`prebuilt_sdklib.stubs`,
 		`sdklib.impl`,
 		`sdklib.xml`,
@@ -924,6 +924,8 @@
 			partitionToBpOption(info.toPartition))
 
 		return android.GroupFixturePreparers(
+			PrepareForTestWithJavaSdkLibraryFiles,
+			FixtureWithLastReleaseApis("bar"),
 			android.FixtureWithRootAndroidBp(bpFile),
 			android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
 				variables.EnforceProductPartitionInterface = proptools.BoolPtr(info.enforceProductInterface)
@@ -1844,7 +1846,14 @@
 }
 
 func TestJavaSdkLibrary(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithPrebuiltApis(map[string][]string{
+			"28": {"foo"},
+			"29": {"foo"},
+			"30": {"bar", "barney", "baz", "betty", "foo", "fred", "quuz", "wilma"},
+		}),
+	).RunTestWithBp(t, `
 		droiddoc_exported_dir {
 			name: "droiddoc-templates-sdk",
 			path: ".",
@@ -1921,68 +1930,51 @@
 		`)
 
 	// check the existence of the internal modules
-	ctx.ModuleForTests("foo", "android_common")
-	ctx.ModuleForTests(apiScopePublic.stubsLibraryModuleName("foo"), "android_common")
-	ctx.ModuleForTests(apiScopeSystem.stubsLibraryModuleName("foo"), "android_common")
-	ctx.ModuleForTests(apiScopeTest.stubsLibraryModuleName("foo"), "android_common")
-	ctx.ModuleForTests(apiScopePublic.stubsSourceModuleName("foo"), "android_common")
-	ctx.ModuleForTests(apiScopeSystem.stubsSourceModuleName("foo"), "android_common")
-	ctx.ModuleForTests(apiScopeTest.stubsSourceModuleName("foo"), "android_common")
-	ctx.ModuleForTests("foo"+sdkXmlFileSuffix, "android_common")
-	ctx.ModuleForTests("foo.api.public.28", "")
-	ctx.ModuleForTests("foo.api.system.28", "")
-	ctx.ModuleForTests("foo.api.test.28", "")
+	result.ModuleForTests("foo", "android_common")
+	result.ModuleForTests(apiScopePublic.stubsLibraryModuleName("foo"), "android_common")
+	result.ModuleForTests(apiScopeSystem.stubsLibraryModuleName("foo"), "android_common")
+	result.ModuleForTests(apiScopeTest.stubsLibraryModuleName("foo"), "android_common")
+	result.ModuleForTests(apiScopePublic.stubsSourceModuleName("foo"), "android_common")
+	result.ModuleForTests(apiScopeSystem.stubsSourceModuleName("foo"), "android_common")
+	result.ModuleForTests(apiScopeTest.stubsSourceModuleName("foo"), "android_common")
+	result.ModuleForTests("foo"+sdkXmlFileSuffix, "android_common")
+	result.ModuleForTests("foo.api.public.28", "")
+	result.ModuleForTests("foo.api.system.28", "")
+	result.ModuleForTests("foo.api.test.28", "")
 
-	bazJavac := ctx.ModuleForTests("baz", "android_common").Rule("javac")
+	bazJavac := result.ModuleForTests("baz", "android_common").Rule("javac")
 	// tests if baz is actually linked to the stubs lib
-	if !strings.Contains(bazJavac.Args["classpath"], "foo.stubs.system.jar") {
-		t.Errorf("baz javac classpath %v does not contain %q", bazJavac.Args["classpath"],
-			"foo.stubs.system.jar")
-	}
+	android.AssertStringDoesContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.stubs.system.jar")
 	// ... and not to the impl lib
-	if strings.Contains(bazJavac.Args["classpath"], "foo.jar") {
-		t.Errorf("baz javac classpath %v should not contain %q", bazJavac.Args["classpath"],
-			"foo.jar")
-	}
+	android.AssertStringDoesNotContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.jar")
 	// test if baz is not linked to the system variant of foo
-	if strings.Contains(bazJavac.Args["classpath"], "foo.stubs.jar") {
-		t.Errorf("baz javac classpath %v should not contain %q", bazJavac.Args["classpath"],
-			"foo.stubs.jar")
-	}
+	android.AssertStringDoesNotContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.stubs.jar")
 
-	bazTestJavac := ctx.ModuleForTests("baz-test", "android_common").Rule("javac")
+	bazTestJavac := result.ModuleForTests("baz-test", "android_common").Rule("javac")
 	// tests if baz-test is actually linked to the test stubs lib
-	if !strings.Contains(bazTestJavac.Args["classpath"], "foo.stubs.test.jar") {
-		t.Errorf("baz-test javac classpath %v does not contain %q", bazTestJavac.Args["classpath"],
-			"foo.stubs.test.jar")
-	}
+	android.AssertStringDoesContain(t, "baz-test javac classpath", bazTestJavac.Args["classpath"], "foo.stubs.test.jar")
 
-	baz29Javac := ctx.ModuleForTests("baz-29", "android_common").Rule("javac")
+	baz29Javac := result.ModuleForTests("baz-29", "android_common").Rule("javac")
 	// tests if baz-29 is actually linked to the system 29 stubs lib
-	if !strings.Contains(baz29Javac.Args["classpath"], "prebuilts/sdk/29/system/foo.jar") {
-		t.Errorf("baz-29 javac classpath %v does not contain %q", baz29Javac.Args["classpath"],
-			"prebuilts/sdk/29/system/foo.jar")
-	}
+	android.AssertStringDoesContain(t, "baz-29 javac classpath", baz29Javac.Args["classpath"], "prebuilts/sdk/29/system/foo.jar")
 
-	bazModule30Javac := ctx.ModuleForTests("baz-module-30", "android_common").Rule("javac")
+	bazModule30Javac := result.ModuleForTests("baz-module-30", "android_common").Rule("javac")
 	// tests if "baz-module-30" is actually linked to the module 30 stubs lib
-	if !strings.Contains(bazModule30Javac.Args["classpath"], "prebuilts/sdk/30/module-lib/foo.jar") {
-		t.Errorf("baz-module-30 javac classpath %v does not contain %q", bazModule30Javac.Args["classpath"],
-			"prebuilts/sdk/30/module-lib/foo.jar")
-	}
+	android.AssertStringDoesContain(t, "baz-module-30 javac classpath", bazModule30Javac.Args["classpath"], "prebuilts/sdk/30/module-lib/foo.jar")
 
 	// test if baz has exported SDK lib names foo and bar to qux
-	qux := ctx.ModuleForTests("qux", "android_common")
+	qux := result.ModuleForTests("qux", "android_common")
 	if quxLib, ok := qux.Module().(*Library); ok {
 		sdkLibs := quxLib.ClassLoaderContexts().UsesLibs()
-		if w := []string{"foo", "bar", "fred", "quuz"}; !reflect.DeepEqual(w, sdkLibs) {
-			t.Errorf("qux should export %q but exports %q", w, sdkLibs)
-		}
+		android.AssertDeepEquals(t, "qux exports", []string{"foo", "bar", "fred", "quuz"}, sdkLibs)
 	}
 }
 
 func TestJavaSdkLibrary_StubOrImplOnlyLibs(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("sdklib"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "sdklib",
 			srcs: ["a.java"],
@@ -2002,20 +1994,23 @@
 		`)
 
 	for _, implName := range []string{"sdklib", "sdklib.impl"} {
-		implJavacCp := ctx.ModuleForTests(implName, "android_common").Rule("javac").Args["classpath"]
+		implJavacCp := result.ModuleForTests(implName, "android_common").Rule("javac").Args["classpath"]
 		if !strings.Contains(implJavacCp, "/foo.jar") || strings.Contains(implJavacCp, "/bar.jar") {
 			t.Errorf("%v javac classpath %v does not contain foo and not bar", implName, implJavacCp)
 		}
 	}
 	stubName := apiScopePublic.stubsLibraryModuleName("sdklib")
-	stubsJavacCp := ctx.ModuleForTests(stubName, "android_common").Rule("javac").Args["classpath"]
+	stubsJavacCp := result.ModuleForTests(stubName, "android_common").Rule("javac").Args["classpath"]
 	if strings.Contains(stubsJavacCp, "/foo.jar") || !strings.Contains(stubsJavacCp, "/bar.jar") {
 		t.Errorf("stubs javac classpath %v does not contain bar and not foo", stubsJavacCp)
 	}
 }
 
 func TestJavaSdkLibrary_DoNotAccessImplWhenItIsNotBuilt(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -2033,14 +2028,17 @@
 		`)
 
 	// The bar library should depend on the stubs jar.
-	barLibrary := ctx.ModuleForTests("bar", "android_common").Rule("javac")
+	barLibrary := result.ModuleForTests("bar", "android_common").Rule("javac")
 	if expected, actual := `^-classpath .*:/[^:]*/turbine-combined/foo\.stubs\.jar$`, barLibrary.Args["classpath"]; !regexp.MustCompile(expected).MatchString(actual) {
 		t.Errorf("expected %q, found %#q", expected, actual)
 	}
 }
 
 func TestJavaSdkLibrary_UseSourcesFromAnotherSdkLibrary(t *testing.T) {
-	testJava(t, `
+	javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -2058,7 +2056,13 @@
 }
 
 func TestJavaSdkLibrary_AccessOutputFiles_MissingScope(t *testing.T) {
-	testJavaError(t, `"foo" does not provide api scope system`, `
+	javaFixtureFactory.
+		Extend(
+			PrepareForTestWithJavaSdkLibraryFiles,
+			FixtureWithLastReleaseApis("foo"),
+		).
+		ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`"foo" does not provide api scope system`)).
+		RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -2076,7 +2080,10 @@
 }
 
 func TestJavaSdkLibrary_Deps(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("sdklib"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "sdklib",
 			srcs: ["a.java"],
@@ -2088,7 +2095,7 @@
 		}
 		`)
 
-	CheckModuleDependencies(t, ctx, "sdklib", "android_common", []string{
+	CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
 		`dex2oatd`,
 		`sdklib.impl`,
 		`sdklib.stubs`,
@@ -2098,7 +2105,7 @@
 }
 
 func TestJavaSdkLibraryImport_AccessOutputFiles(t *testing.T) {
-	testJava(t, `
+	javaFixtureFactory.RunTestWithBp(t, `
 		java_sdk_library_import {
 			name: "foo",
 			public: {
@@ -2131,63 +2138,74 @@
 		`
 
 	t.Run("stubs.source", func(t *testing.T) {
-		testJavaError(t, `stubs.source not available for api scope public`, bp+`
-		java_library {
-			name: "bar",
-			srcs: [":foo{.public.stubs.source}"],
-			java_resources: [
-				":foo{.public.api.txt}",
-				":foo{.public.removed-api.txt}",
-			],
-		}
-		`)
+		javaFixtureFactory.
+			ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`stubs.source not available for api scope public`)).
+			RunTestWithBp(t, bp+`
+				java_library {
+					name: "bar",
+					srcs: [":foo{.public.stubs.source}"],
+					java_resources: [
+						":foo{.public.api.txt}",
+						":foo{.public.removed-api.txt}",
+					],
+				}
+			`)
 	})
 
 	t.Run("api.txt", func(t *testing.T) {
-		testJavaError(t, `api.txt not available for api scope public`, bp+`
-		java_library {
-			name: "bar",
-			srcs: ["a.java"],
-			java_resources: [
-				":foo{.public.api.txt}",
-			],
-		}
-		`)
+		javaFixtureFactory.
+			ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`api.txt not available for api scope public`)).
+			RunTestWithBp(t, bp+`
+				java_library {
+					name: "bar",
+					srcs: ["a.java"],
+					java_resources: [
+						":foo{.public.api.txt}",
+					],
+				}
+			`)
 	})
 
 	t.Run("removed-api.txt", func(t *testing.T) {
-		testJavaError(t, `removed-api.txt not available for api scope public`, bp+`
-		java_library {
-			name: "bar",
-			srcs: ["a.java"],
-			java_resources: [
-				":foo{.public.removed-api.txt}",
-			],
-		}
-		`)
+		javaFixtureFactory.
+			ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`removed-api.txt not available for api scope public`)).
+			RunTestWithBp(t, bp+`
+				java_library {
+					name: "bar",
+					srcs: ["a.java"],
+					java_resources: [
+						":foo{.public.removed-api.txt}",
+					],
+				}
+			`)
 	})
 }
 
 func TestJavaSdkLibrary_InvalidScopes(t *testing.T) {
-	testJavaError(t, `module "foo": enabled api scope "system" depends on disabled scope "public"`, `
-		java_sdk_library {
-			name: "foo",
-			srcs: ["a.java", "b.java"],
-			api_packages: ["foo"],
-			// Explicitly disable public to test the check that ensures the set of enabled
-			// scopes is consistent.
-			public: {
-				enabled: false,
-			},
-			system: {
-				enabled: true,
-			},
-		}
+	javaFixtureFactory.
+		ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`module "foo": enabled api scope "system" depends on disabled scope "public"`)).
+		RunTestWithBp(t, `
+			java_sdk_library {
+				name: "foo",
+				srcs: ["a.java", "b.java"],
+				api_packages: ["foo"],
+				// Explicitly disable public to test the check that ensures the set of enabled
+				// scopes is consistent.
+				public: {
+					enabled: false,
+				},
+				system: {
+					enabled: true,
+				},
+			}
 		`)
 }
 
 func TestJavaSdkLibrary_SdkVersion_ForScope(t *testing.T) {
-	testJava(t, `
+	javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java", "b.java"],
@@ -2201,7 +2219,10 @@
 }
 
 func TestJavaSdkLibrary_ModuleLib(t *testing.T) {
-	testJava(t, `
+	javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java", "b.java"],
@@ -2217,7 +2238,10 @@
 }
 
 func TestJavaSdkLibrary_SystemServer(t *testing.T) {
-	testJava(t, `
+	javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java", "b.java"],
@@ -2233,26 +2257,31 @@
 }
 
 func TestJavaSdkLibrary_MissingScope(t *testing.T) {
-	testJavaError(t, `requires api scope module-lib from foo but it only has \[\] available`, `
-		java_sdk_library {
-			name: "foo",
-			srcs: ["a.java"],
-			public: {
-				enabled: false,
-			},
-		}
+	javaFixtureFactory.
+		ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`requires api scope module-lib from foo but it only has \[\] available`)).
+		RunTestWithBp(t, `
+			java_sdk_library {
+				name: "foo",
+				srcs: ["a.java"],
+				public: {
+					enabled: false,
+				},
+			}
 
-		java_library {
-			name: "baz",
-			srcs: ["a.java"],
-			libs: ["foo"],
-			sdk_version: "module_current",
-		}
+			java_library {
+				name: "baz",
+				srcs: ["a.java"],
+				libs: ["foo"],
+				sdk_version: "module_current",
+			}
 		`)
 }
 
 func TestJavaSdkLibrary_FallbackScope(t *testing.T) {
-	testJava(t, `
+	javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -2272,7 +2301,10 @@
 }
 
 func TestJavaSdkLibrary_DefaultToStubs(t *testing.T) {
-	ctx, _ := testJava(t, `
+	result := javaFixtureFactory.Extend(
+		PrepareForTestWithJavaSdkLibraryFiles,
+		FixtureWithLastReleaseApis("foo"),
+	).RunTestWithBp(t, `
 		java_sdk_library {
 			name: "foo",
 			srcs: ["a.java"],
@@ -2292,7 +2324,7 @@
 		}
 		`)
 	// The baz library should depend on the system stubs jar.
-	bazLibrary := ctx.ModuleForTests("baz", "android_common").Rule("javac")
+	bazLibrary := result.ModuleForTests("baz", "android_common").Rule("javac")
 	if expected, actual := `^-classpath .*:/[^:]*/turbine-combined/foo\.stubs.system\.jar$`, bazLibrary.Args["classpath"]; !regexp.MustCompile(expected).MatchString(actual) {
 		t.Errorf("expected %q, found %#q", expected, actual)
 	}
@@ -2569,3 +2601,16 @@
 		t.Errorf("Unexpected test data - expected: %q, actual: %q", expected, actual)
 	}
 }
+
+func TestDefaultInstallable(t *testing.T) {
+	ctx, _ := testJava(t, `
+		java_test_host {
+			name: "foo"
+		}
+	`)
+
+	buildOS := android.BuildOs.String()
+	module := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
+	assertDeepEquals(t, "Default installable value should be true.", proptools.BoolPtr(true),
+		module.properties.Installable)
+}
diff --git a/java/legacy_core_platform_api_usage.go b/java/legacy_core_platform_api_usage.go
index cae9dc5..5949edd 100644
--- a/java/legacy_core_platform_api_usage.go
+++ b/java/legacy_core_platform_api_usage.go
@@ -83,6 +83,7 @@
 	"FrameworksNetTests",
 	"FrameworksServicesRoboTests",
 	"FrameworksServicesTests",
+	"FrameworksMockingServicesTests",
 	"FrameworksUtilTests",
 	"FrameworksWifiTests",
 	"hid",
diff --git a/java/platform_compat_config.go b/java/platform_compat_config.go
index 218154e..4bfd4e2 100644
--- a/java/platform_compat_config.go
+++ b/java/platform_compat_config.go
@@ -152,7 +152,7 @@
 func PlatformCompatConfigFactory() android.Module {
 	module := &platformCompatConfig{}
 	module.AddProperties(&module.properties)
-	android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibFirst)
+	android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
 	return module
 }
 
diff --git a/java/proto.go b/java/proto.go
index 652a4da..8731822 100644
--- a/java/proto.go
+++ b/java/proto.go
@@ -94,7 +94,7 @@
 	}
 }
 
-func protoFlags(ctx android.ModuleContext, j *CompilerProperties, p *android.ProtoProperties,
+func protoFlags(ctx android.ModuleContext, j *CommonProperties, p *android.ProtoProperties,
 	flags javaBuilderFlags) javaBuilderFlags {
 
 	flags.proto = android.GetProtoFlags(ctx, p)
diff --git a/java/sdk_library.go b/java/sdk_library.go
index b03f90c..e1ca77d 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -1681,7 +1681,7 @@
 
 var _ sdkLibraryComponentNamingScheme = (*defaultNamingScheme)(nil)
 
-func moduleStubLinkType(name string) (stub bool, ret linkType) {
+func moduleStubLinkType(name string) (stub bool, ret sdkLinkType) {
 	// This suffix-based approach is fragile and could potentially mis-trigger.
 	// TODO(b/155164730): Clean this up when modules no longer reference sdk_lib stubs directly.
 	if strings.HasSuffix(name, ".stubs.public") || strings.HasSuffix(name, "-stubs-publicapi") {
diff --git a/scripts/manifest_check.py b/scripts/manifest_check.py
index 0eb1b76..973a675 100755
--- a/scripts/manifest_check.py
+++ b/scripts/manifest_check.py
@@ -19,6 +19,8 @@
 from __future__ import print_function
 
 import argparse
+import re
+import subprocess
 import sys
 from xml.dom import minidom
 
@@ -59,64 +61,44 @@
                       dest='extract_target_sdk_version',
                       action='store_true',
                       help='print the targetSdkVersion from the manifest')
+  parser.add_argument('--aapt',
+                      dest='aapt',
+                      help='path to aapt executable')
   parser.add_argument('--output', '-o', dest='output', help='output AndroidManifest.xml file')
   parser.add_argument('input', help='input AndroidManifest.xml file')
   return parser.parse_args()
 
 
-def enforce_uses_libraries(doc, uses_libraries, optional_uses_libraries, relax):
-  """Verify that the <uses-library> tags in the manifest match those provided by the build system.
+def enforce_uses_libraries(manifest, required, optional, relax, is_apk = False):
+  """Verify that the <uses-library> tags in the manifest match those provided
+  by the build system.
 
   Args:
-    doc: The XML document.
-    uses_libraries: The names of <uses-library> tags known to the build system
-    optional_uses_libraries: The names of <uses-library> tags with required:fals
-      known to the build system
-  Raises:
-    RuntimeError: Invalid manifest
-    ManifestMismatchError: Manifest does not match
+    manifest: manifest (either parsed XML or aapt dump of APK)
+    required: required libs known to the build system
+    optional: optional libs known to the build system
+    relax:    if true, suppress error on mismatch and just write it to file
+    is_apk:   if the manifest comes from an APK or an XML file
   """
+  if is_apk:
+    manifest_required, manifest_optional = extract_uses_libs_apk(manifest)
+  else:
+    manifest_required, manifest_optional = extract_uses_libs_xml(manifest)
 
-  manifest = parse_manifest(doc)
-  elems = get_children_with_tag(manifest, 'application')
-  application = elems[0] if len(elems) == 1 else None
-  if len(elems) > 1:
-    raise RuntimeError('found multiple <application> tags')
-  elif not elems:
-    if uses_libraries or optional_uses_libraries:
-      raise ManifestMismatchError('no <application> tag found')
-    return
+  if required is None:
+    required = []
 
-  return verify_uses_library(application, uses_libraries, optional_uses_libraries, relax)
-
-
-def verify_uses_library(application, uses_libraries, optional_uses_libraries, relax):
-  """Verify that the uses-library values known to the build system match the manifest.
-
-  Args:
-    application: the <application> tag in the manifest.
-    uses_libraries: the names of expected <uses-library> tags.
-    optional_uses_libraries: the names of expected <uses-library> tags with required="false".
-  Raises:
-    ManifestMismatchError: Manifest does not match
-  """
-
-  if uses_libraries is None:
-    uses_libraries = []
-
-  if optional_uses_libraries is None:
-    optional_uses_libraries = []
-
-  manifest_uses_libraries, manifest_optional_uses_libraries = parse_uses_library(application)
+  if optional is None:
+    optional = []
 
   err = []
-  if manifest_uses_libraries != uses_libraries:
+  if manifest_required != required:
     err.append('Expected required <uses-library> tags "%s", got "%s"' %
-               (', '.join(uses_libraries), ', '.join(manifest_uses_libraries)))
+               (', '.join(required), ', '.join(manifest_required)))
 
-  if manifest_optional_uses_libraries != optional_uses_libraries:
+  if manifest_optional != optional:
     err.append('Expected optional <uses-library> tags "%s", got "%s"' %
-               (', '.join(optional_uses_libraries), ', '.join(manifest_optional_uses_libraries)))
+               (', '.join(optional), ', '.join(manifest_optional)))
 
   if err:
     errmsg = '\n'.join(err)
@@ -126,19 +108,43 @@
 
   return None
 
-def parse_uses_library(application):
-  """Extract uses-library tags from the manifest.
 
-  Args:
-    application: the <application> tag in the manifest.
-  """
+def extract_uses_libs_apk(badging):
+  """Extract <uses-library> tags from the manifest of an APK."""
+
+  pattern = re.compile("^uses-library(-not-required)?:'(.*)'$", re.MULTILINE)
+
+  required = []
+  optional = []
+  for match in re.finditer(pattern, badging):
+    libname = match.group(2)
+    if match.group(1) == None:
+      required.append(libname)
+    else:
+      optional.append(libname)
+
+  return first_unique_elements(required), first_unique_elements(optional)
+
+
+def extract_uses_libs_xml(xml):
+  """Extract <uses-library> tags from the manifest."""
+
+  manifest = parse_manifest(xml)
+  elems = get_children_with_tag(manifest, 'application')
+  application = elems[0] if len(elems) == 1 else None
+  if len(elems) > 1:
+    raise RuntimeError('found multiple <application> tags')
+  elif not elems:
+    if uses_libraries or optional_uses_libraries:
+      raise ManifestMismatchError('no <application> tag found')
+    return
 
   libs = get_children_with_tag(application, 'uses-library')
 
-  uses_libraries = [uses_library_name(x) for x in libs if uses_library_required(x)]
-  optional_uses_libraries = [uses_library_name(x) for x in libs if not uses_library_required(x)]
+  required = [uses_library_name(x) for x in libs if uses_library_required(x)]
+  optional = [uses_library_name(x) for x in libs if not uses_library_required(x)]
 
-  return first_unique_elements(uses_libraries), first_unique_elements(optional_uses_libraries)
+  return first_unique_elements(required), first_unique_elements(optional)
 
 
 def first_unique_elements(l):
@@ -167,16 +173,34 @@
   return (required.value == 'true') if required is not None else True
 
 
-def extract_target_sdk_version(doc):
+def extract_target_sdk_version(manifest, is_apk = False):
   """Returns the targetSdkVersion from the manifest.
 
   Args:
-    doc: The XML document.
-  Raises:
-    RuntimeError: invalid manifest
+    manifest: manifest (either parsed XML or aapt dump of APK)
+    is_apk:   if the manifest comes from an APK or an XML file
   """
+  if is_apk:
+    return extract_target_sdk_version_apk(manifest)
+  else:
+    return extract_target_sdk_version_xml(manifest)
 
-  manifest = parse_manifest(doc)
+
+def extract_target_sdk_version_apk(badging):
+  """Extract targetSdkVersion tags from the manifest of an APK."""
+
+  pattern = re.compile("^targetSdkVersion?:'(.*)'$", re.MULTILINE)
+
+  for match in re.finditer(pattern, badging):
+    return match.group(1)
+
+  raise RuntimeError('cannot find targetSdkVersion in the manifest')
+
+
+def extract_target_sdk_version_xml(xml):
+  """Extract targetSdkVersion tags from the manifest."""
+
+  manifest = parse_manifest(xml)
 
   # Get or insert the uses-sdk element
   uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
@@ -203,14 +227,22 @@
   try:
     args = parse_args()
 
-    doc = minidom.parse(args.input)
+    # The input can be either an XML manifest or an APK, they are parsed and
+    # processed in different ways.
+    is_apk = args.input.endswith('.apk')
+    if is_apk:
+      aapt = args.aapt if args.aapt != None else "aapt"
+      manifest = subprocess.check_output([aapt, "dump", "badging", args.input])
+    else:
+      manifest = minidom.parse(args.input)
 
     if args.enforce_uses_libraries:
       # Check if the <uses-library> lists in the build system agree with those
       # in the manifest. Raise an exception on mismatch, unless the script was
       # passed a special parameter to suppress exceptions.
-      errmsg = enforce_uses_libraries(doc, args.uses_libraries,
-        args.optional_uses_libraries, args.enforce_uses_libraries_relax)
+      errmsg = enforce_uses_libraries(manifest, args.uses_libraries,
+        args.optional_uses_libraries, args.enforce_uses_libraries_relax,
+        is_apk)
 
       # Create a status file that is empty on success, or contains an error
       # message on failure. When exceptions are suppressed, dexpreopt command
@@ -221,11 +253,16 @@
             f.write("%s\n" % errmsg)
 
     if args.extract_target_sdk_version:
-      print(extract_target_sdk_version(doc))
+      print(extract_target_sdk_version(manifest, is_apk))
 
     if args.output:
+      # XML output is supposed to be written only when this script is invoked
+      # with XML input manifest, not with an APK.
+      if is_apk:
+        raise RuntimeError('cannot save APK manifest as XML')
+
       with open(args.output, 'wb') as f:
-        write_xml(f, doc)
+        write_xml(f, manifest)
 
   # pylint: disable=broad-except
   except Exception as err:
diff --git a/scripts/manifest_check_test.py b/scripts/manifest_check_test.py
index 56c2d9e..635ba9d 100755
--- a/scripts/manifest_check_test.py
+++ b/scripts/manifest_check_test.py
@@ -25,28 +25,38 @@
 sys.dont_write_bytecode = True
 
 
-def uses_library(name, attr=''):
+def uses_library_xml(name, attr=''):
   return '<uses-library android:name="%s"%s />' % (name, attr)
 
 
-def required(value):
+def required_xml(value):
   return ' android:required="%s"' % ('true' if value else 'false')
 
 
+def uses_library_apk(name, sfx=''):
+  return "uses-library%s:'%s'" % (sfx, name)
+
+
+def required_apk(value):
+  return '' if value else '-not-required'
+
+
 class EnforceUsesLibrariesTest(unittest.TestCase):
   """Unit tests for add_extract_native_libs function."""
 
-  def run_test(self, input_manifest, uses_libraries=None, optional_uses_libraries=None):
-    doc = minidom.parseString(input_manifest)
+  def run_test(self, xml, apk, uses_libraries=[], optional_uses_libraries=[]):
+    doc = minidom.parseString(xml)
     try:
       relax = False
       manifest_check.enforce_uses_libraries(doc, uses_libraries,
-        optional_uses_libraries, relax)
+        optional_uses_libraries, relax, is_apk=False)
+      manifest_check.enforce_uses_libraries(apk, uses_libraries,
+        optional_uses_libraries, relax, is_apk=True)
       return True
     except manifest_check.ManifestMismatchError:
       return False
 
-  manifest_tmpl = (
+  xml_tmpl = (
       '<?xml version="1.0" encoding="utf-8"?>\n'
       '<manifest xmlns:android="http://schemas.android.com/apk/res/android">\n'
       '    <application>\n'
@@ -54,115 +64,155 @@
       '    </application>\n'
       '</manifest>\n')
 
+  apk_tmpl = (
+      "package: name='com.google.android.something' versionCode='100'\n"
+      "sdkVersion:'29'\n"
+      "targetSdkVersion:'29'\n"
+      "uses-permission: name='android.permission.ACCESS_NETWORK_STATE'\n"
+      "%s\n"
+      "densities: '160' '240' '320' '480' '640' '65534")
+
   def test_uses_library(self):
-    manifest_input = self.manifest_tmpl % (uses_library('foo'))
-    matches = self.run_test(manifest_input, uses_libraries=['foo'])
+    xml = self.xml_tmpl % (uses_library_xml('foo'))
+    apk = self.apk_tmpl % (uses_library_apk('foo'))
+    matches = self.run_test(xml, apk, uses_libraries=['foo'])
     self.assertTrue(matches)
 
   def test_uses_library_required(self):
-    manifest_input = self.manifest_tmpl % (uses_library('foo', required(True)))
-    matches = self.run_test(manifest_input, uses_libraries=['foo'])
+    xml = self.xml_tmpl % (uses_library_xml('foo', required_xml(True)))
+    apk = self.apk_tmpl % (uses_library_apk('foo', required_apk(True)))
+    matches = self.run_test(xml, apk, uses_libraries=['foo'])
     self.assertTrue(matches)
 
   def test_optional_uses_library(self):
-    manifest_input = self.manifest_tmpl % (uses_library('foo', required(False)))
-    matches = self.run_test(manifest_input, optional_uses_libraries=['foo'])
+    xml = self.xml_tmpl % (uses_library_xml('foo', required_xml(False)))
+    apk = self.apk_tmpl % (uses_library_apk('foo', required_apk(False)))
+    matches = self.run_test(xml, apk, optional_uses_libraries=['foo'])
     self.assertTrue(matches)
 
   def test_expected_uses_library(self):
-    manifest_input = self.manifest_tmpl % (uses_library('foo', required(False)))
-    matches = self.run_test(manifest_input, uses_libraries=['foo'])
+    xml = self.xml_tmpl % (uses_library_xml('foo', required_xml(False)))
+    apk = self.apk_tmpl % (uses_library_apk('foo', required_apk(False)))
+    matches = self.run_test(xml, apk, uses_libraries=['foo'])
     self.assertFalse(matches)
 
   def test_expected_optional_uses_library(self):
-    manifest_input = self.manifest_tmpl % (uses_library('foo'))
-    matches = self.run_test(manifest_input, optional_uses_libraries=['foo'])
+    xml = self.xml_tmpl % (uses_library_xml('foo'))
+    apk = self.apk_tmpl % (uses_library_apk('foo'))
+    matches = self.run_test(xml, apk, optional_uses_libraries=['foo'])
     self.assertFalse(matches)
 
   def test_missing_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('')
-    matches = self.run_test(manifest_input, uses_libraries=['foo'])
+    xml = self.xml_tmpl % ('')
+    apk = self.apk_tmpl % ('')
+    matches = self.run_test(xml, apk, uses_libraries=['foo'])
     self.assertFalse(matches)
 
   def test_missing_optional_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('')
-    matches = self.run_test(manifest_input, optional_uses_libraries=['foo'])
+    xml = self.xml_tmpl % ('')
+    apk = self.apk_tmpl % ('')
+    matches = self.run_test(xml, apk, optional_uses_libraries=['foo'])
     self.assertFalse(matches)
 
   def test_extra_uses_library(self):
-    manifest_input = self.manifest_tmpl % (uses_library('foo'))
-    matches = self.run_test(manifest_input)
+    xml = self.xml_tmpl % (uses_library_xml('foo'))
+    apk = self.apk_tmpl % (uses_library_xml('foo'))
+    matches = self.run_test(xml, apk)
     self.assertFalse(matches)
 
   def test_extra_optional_uses_library(self):
-    manifest_input = self.manifest_tmpl % (uses_library('foo', required(False)))
-    matches = self.run_test(manifest_input)
+    xml = self.xml_tmpl % (uses_library_xml('foo', required_xml(False)))
+    apk = self.apk_tmpl % (uses_library_apk('foo', required_apk(False)))
+    matches = self.run_test(xml, apk)
     self.assertFalse(matches)
 
   def test_multiple_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('\n'.join([uses_library('foo'),
-                                                      uses_library('bar')]))
-    matches = self.run_test(manifest_input, uses_libraries=['foo', 'bar'])
+    xml = self.xml_tmpl % ('\n'.join([uses_library_xml('foo'),
+                                      uses_library_xml('bar')]))
+    apk = self.apk_tmpl % ('\n'.join([uses_library_apk('foo'),
+                                      uses_library_apk('bar')]))
+    matches = self.run_test(xml, apk, uses_libraries=['foo', 'bar'])
     self.assertTrue(matches)
 
   def test_multiple_optional_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('\n'.join([uses_library('foo', required(False)),
-                                                      uses_library('bar', required(False))]))
-    matches = self.run_test(manifest_input, optional_uses_libraries=['foo', 'bar'])
+    xml = self.xml_tmpl % ('\n'.join([uses_library_xml('foo', required_xml(False)),
+                                      uses_library_xml('bar', required_xml(False))]))
+    apk = self.apk_tmpl % ('\n'.join([uses_library_apk('foo', required_apk(False)),
+                                      uses_library_apk('bar', required_apk(False))]))
+    matches = self.run_test(xml, apk, optional_uses_libraries=['foo', 'bar'])
     self.assertTrue(matches)
 
   def test_order_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('\n'.join([uses_library('foo'),
-                                                      uses_library('bar')]))
-    matches = self.run_test(manifest_input, uses_libraries=['bar', 'foo'])
+    xml = self.xml_tmpl % ('\n'.join([uses_library_xml('foo'),
+                                      uses_library_xml('bar')]))
+    apk = self.apk_tmpl % ('\n'.join([uses_library_apk('foo'),
+                                      uses_library_apk('bar')]))
+    matches = self.run_test(xml, apk, uses_libraries=['bar', 'foo'])
     self.assertFalse(matches)
 
   def test_order_optional_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('\n'.join([uses_library('foo', required(False)),
-                                                      uses_library('bar', required(False))]))
-    matches = self.run_test(manifest_input, optional_uses_libraries=['bar', 'foo'])
+    xml = self.xml_tmpl % ('\n'.join([uses_library_xml('foo', required_xml(False)),
+                                      uses_library_xml('bar', required_xml(False))]))
+    apk = self.apk_tmpl % ('\n'.join([uses_library_apk('foo', required_apk(False)),
+                                      uses_library_apk('bar', required_apk(False))]))
+    matches = self.run_test(xml, apk, optional_uses_libraries=['bar', 'foo'])
     self.assertFalse(matches)
 
   def test_duplicate_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('\n'.join([uses_library('foo'),
-                                                      uses_library('foo')]))
-    matches = self.run_test(manifest_input, uses_libraries=['foo'])
+    xml = self.xml_tmpl % ('\n'.join([uses_library_xml('foo'),
+                                      uses_library_xml('foo')]))
+    apk = self.apk_tmpl % ('\n'.join([uses_library_apk('foo'),
+                                      uses_library_apk('foo')]))
+    matches = self.run_test(xml, apk, uses_libraries=['foo'])
     self.assertTrue(matches)
 
   def test_duplicate_optional_uses_library(self):
-    manifest_input = self.manifest_tmpl % ('\n'.join([uses_library('foo', required(False)),
-                                                      uses_library('foo', required(False))]))
-    matches = self.run_test(manifest_input, optional_uses_libraries=['foo'])
+    xml = self.xml_tmpl % ('\n'.join([uses_library_xml('foo', required_xml(False)),
+                                      uses_library_xml('foo', required_xml(False))]))
+    apk = self.apk_tmpl % ('\n'.join([uses_library_apk('foo', required_apk(False)),
+                                      uses_library_apk('foo', required_apk(False))]))
+    matches = self.run_test(xml, apk, optional_uses_libraries=['foo'])
     self.assertTrue(matches)
 
   def test_mixed(self):
-    manifest_input = self.manifest_tmpl % ('\n'.join([uses_library('foo'),
-                                                      uses_library('bar', required(False))]))
-    matches = self.run_test(manifest_input, uses_libraries=['foo'],
+    xml = self.xml_tmpl % ('\n'.join([uses_library_xml('foo'),
+                                      uses_library_xml('bar', required_xml(False))]))
+    apk = self.apk_tmpl % ('\n'.join([uses_library_apk('foo'),
+                                      uses_library_apk('bar', required_apk(False))]))
+    matches = self.run_test(xml, apk, uses_libraries=['foo'],
                             optional_uses_libraries=['bar'])
     self.assertTrue(matches)
 
 
 class ExtractTargetSdkVersionTest(unittest.TestCase):
-  def test_target_sdk_version(self):
-    manifest = (
-      '<?xml version="1.0" encoding="utf-8"?>\n'
-      '<manifest xmlns:android="http://schemas.android.com/apk/res/android">\n'
-      '    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="29" />\n'
-      '</manifest>\n')
-    doc = minidom.parseString(manifest)
-    target_sdk_version = manifest_check.extract_target_sdk_version(doc)
-    self.assertEqual(target_sdk_version, '29')
+  def run_test(self, xml, apk, version):
+    doc = minidom.parseString(xml)
+    v = manifest_check.extract_target_sdk_version(doc, is_apk=False)
+    self.assertEqual(v, version)
+    v = manifest_check.extract_target_sdk_version(apk, is_apk=True)
+    self.assertEqual(v, version)
 
-  def test_min_sdk_version(self):
-    manifest = (
+  xml_tmpl = (
       '<?xml version="1.0" encoding="utf-8"?>\n'
       '<manifest xmlns:android="http://schemas.android.com/apk/res/android">\n'
-      '    <uses-sdk android:minSdkVersion="28" />\n'
+      '    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="%s" />\n'
       '</manifest>\n')
-    doc = minidom.parseString(manifest)
-    target_sdk_version = manifest_check.extract_target_sdk_version(doc)
-    self.assertEqual(target_sdk_version, '28')
+
+  apk_tmpl = (
+      "package: name='com.google.android.something' versionCode='100'\n"
+      "sdkVersion:'28'\n"
+      "targetSdkVersion:'%s'\n"
+      "uses-permission: name='android.permission.ACCESS_NETWORK_STATE'\n")
+
+  def test_targert_sdk_version_28(self):
+    xml = self.xml_tmpl % "28"
+    apk = self.apk_tmpl % "28"
+    self.run_test(xml, apk, "28")
+
+  def test_targert_sdk_version_29(self):
+    xml = self.xml_tmpl % "29"
+    apk = self.apk_tmpl % "29"
+    self.run_test(xml, apk, "29")
 
 if __name__ == '__main__':
   unittest.main(verbosity=2)
diff --git a/sh/sh_binary_test.go b/sh/sh_binary_test.go
index 7a24168..5887b56 100644
--- a/sh/sh_binary_test.go
+++ b/sh/sh_binary_test.go
@@ -1,44 +1,20 @@
 package sh
 
 import (
-	"io/ioutil"
 	"os"
-	"path"
 	"path/filepath"
-	"reflect"
 	"testing"
 
 	"android/soong/android"
 	"android/soong/cc"
 )
 
-var buildDir string
-
-func setUp() {
-	var err error
-	buildDir, err = ioutil.TempDir("", "soong_sh_test")
-	if err != nil {
-		panic(err)
-	}
-}
-
-func tearDown() {
-	os.RemoveAll(buildDir)
-}
-
 func TestMain(m *testing.M) {
-	run := func() int {
-		setUp()
-		defer tearDown()
-
-		return m.Run()
-	}
-
-	os.Exit(run())
+	os.Exit(m.Run())
 }
 
 var shFixtureFactory = android.NewFixtureFactory(
-	&buildDir,
+	nil,
 	cc.PrepareForTestWithCcBuildComponents,
 	PrepareForTestWithShBuildComponents,
 	android.FixtureMergeMockFs(android.MockFS{
@@ -66,7 +42,7 @@
 }
 
 func TestShTestSubDir(t *testing.T) {
-	ctx, _ := testShBinary(t, `
+	ctx, config := testShBinary(t, `
 		sh_test {
 			name: "foo",
 			src: "test.sh",
@@ -78,16 +54,13 @@
 
 	entries := android.AndroidMkEntriesForTest(t, ctx, mod)[0]
 
-	expectedPath := path.Join(buildDir,
-		"../target/product/test_device/data/nativetest64/foo_test")
+	expectedPath := "out/target/product/test_device/data/nativetest64/foo_test"
 	actualPath := entries.EntryMap["LOCAL_MODULE_PATH"][0]
-	if expectedPath != actualPath {
-		t.Errorf("Unexpected LOCAL_MODULE_PATH expected: %q, actual: %q", expectedPath, actualPath)
-	}
+	android.AssertStringPathRelativeToTopEquals(t, "LOCAL_MODULE_PATH[0]", config, expectedPath, actualPath)
 }
 
 func TestShTest(t *testing.T) {
-	ctx, _ := testShBinary(t, `
+	ctx, config := testShBinary(t, `
 		sh_test {
 			name: "foo",
 			src: "test.sh",
@@ -103,22 +76,17 @@
 
 	entries := android.AndroidMkEntriesForTest(t, ctx, mod)[0]
 
-	expectedPath := path.Join(buildDir,
-		"../target/product/test_device/data/nativetest64/foo")
+	expectedPath := "out/target/product/test_device/data/nativetest64/foo"
 	actualPath := entries.EntryMap["LOCAL_MODULE_PATH"][0]
-	if expectedPath != actualPath {
-		t.Errorf("Unexpected LOCAL_MODULE_PATH expected: %q, actual: %q", expectedPath, actualPath)
-	}
+	android.AssertStringPathRelativeToTopEquals(t, "LOCAL_MODULE_PATH[0]", config, expectedPath, actualPath)
 
 	expectedData := []string{":testdata/data1", ":testdata/sub/data2"}
 	actualData := entries.EntryMap["LOCAL_TEST_DATA"]
-	if !reflect.DeepEqual(expectedData, actualData) {
-		t.Errorf("Unexpected test data expected: %q, actual: %q", expectedData, actualData)
-	}
+	android.AssertDeepEquals(t, "LOCAL_TEST_DATA", expectedData, actualData)
 }
 
 func TestShTest_dataModules(t *testing.T) {
-	ctx, _ := testShBinary(t, `
+	ctx, config := testShBinary(t, `
 		sh_test {
 			name: "foo",
 			src: "test.sh",
@@ -157,22 +125,17 @@
 			libExt = ".dylib"
 		}
 		relocated := variant.Output("relocated/lib64/libbar" + libExt)
-		expectedInput := filepath.Join(buildDir, ".intermediates/libbar/"+arch+"_shared/libbar"+libExt)
-		if relocated.Input.String() != expectedInput {
-			t.Errorf("Unexpected relocation input, expected: %q, actual: %q",
-				expectedInput, relocated.Input.String())
-		}
+		expectedInput := "out/soong/.intermediates/libbar/" + arch + "_shared/libbar" + libExt
+		android.AssertPathRelativeToTopEquals(t, "relocation input", expectedInput, relocated.Input)
 
 		mod := variant.Module().(*ShTest)
 		entries := android.AndroidMkEntriesForTest(t, ctx, mod)[0]
 		expectedData := []string{
-			filepath.Join(buildDir, ".intermediates/bar", arch, ":bar"),
-			filepath.Join(buildDir, ".intermediates/foo", arch, "relocated/:lib64/libbar"+libExt),
+			filepath.Join("out/soong/.intermediates/bar", arch, ":bar"),
+			filepath.Join("out/soong/.intermediates/foo", arch, "relocated/:lib64/libbar"+libExt),
 		}
 		actualData := entries.EntryMap["LOCAL_TEST_DATA"]
-		if !reflect.DeepEqual(expectedData, actualData) {
-			t.Errorf("Unexpected test data, expected: %q, actual: %q", expectedData, actualData)
-		}
+		android.AssertStringPathsRelativeToTopEquals(t, "LOCAL_TEST_DATA", config, expectedData, actualData)
 	}
 }
 
@@ -197,7 +160,7 @@
 }
 
 func TestShTestHost_dataDeviceModules(t *testing.T) {
-	ctx, _ := testShBinary(t, `
+	ctx, config := testShBinary(t, `
 		sh_test_host {
 			name: "foo",
 			src: "test.sh",
@@ -227,21 +190,16 @@
 	variant := ctx.ModuleForTests("foo", buildOS+"_x86_64")
 
 	relocated := variant.Output("relocated/lib64/libbar.so")
-	expectedInput := filepath.Join(buildDir, ".intermediates/libbar/android_arm64_armv8-a_shared/libbar.so")
-	if relocated.Input.String() != expectedInput {
-		t.Errorf("Unexpected relocation input, expected: %q, actual: %q",
-			expectedInput, relocated.Input.String())
-	}
+	expectedInput := "out/soong/.intermediates/libbar/android_arm64_armv8-a_shared/libbar.so"
+	android.AssertPathRelativeToTopEquals(t, "relocation input", expectedInput, relocated.Input)
 
 	mod := variant.Module().(*ShTest)
 	entries := android.AndroidMkEntriesForTest(t, ctx, mod)[0]
 	expectedData := []string{
-		filepath.Join(buildDir, ".intermediates/bar/android_arm64_armv8-a/:bar"),
+		"out/soong/.intermediates/bar/android_arm64_armv8-a/:bar",
 		// libbar has been relocated, and so has a variant that matches the host arch.
-		filepath.Join(buildDir, ".intermediates/foo/"+buildOS+"_x86_64/relocated/:lib64/libbar.so"),
+		"out/soong/.intermediates/foo/" + buildOS + "_x86_64/relocated/:lib64/libbar.so",
 	}
 	actualData := entries.EntryMap["LOCAL_TEST_DATA"]
-	if !reflect.DeepEqual(expectedData, actualData) {
-		t.Errorf("Unexpected test data, expected: %q, actual: %q", expectedData, actualData)
-	}
+	android.AssertStringPathsRelativeToTopEquals(t, "LOCAL_TEST_DATA", config, expectedData, actualData)
 }
diff --git a/zip/zip.go b/zip/zip.go
index f731329..088ed0d 100644
--- a/zip/zip.go
+++ b/zip/zip.go
@@ -406,6 +406,8 @@
 	buf := &bytes.Buffer{}
 	var out io.Writer = buf
 
+	var zipErr error
+
 	if !args.WriteIfChanged {
 		f, err := os.Create(args.OutputFilePath)
 		if err != nil {
@@ -414,7 +416,7 @@
 
 		defer f.Close()
 		defer func() {
-			if err != nil {
+			if zipErr != nil {
 				os.Remove(args.OutputFilePath)
 			}
 		}()
@@ -422,9 +424,9 @@
 		out = f
 	}
 
-	err := zipTo(args, out)
-	if err != nil {
-		return err
+	zipErr = zipTo(args, out)
+	if zipErr != nil {
+		return zipErr
 	}
 
 	if args.WriteIfChanged {