Merge "Fix the lib directory being used for fetching libraries."
diff --git a/android/config.go b/android/config.go
index aeed81d..3387706 100644
--- a/android/config.go
+++ b/android/config.go
@@ -1271,3 +1271,7 @@
 func (c *deviceConfig) BoardUsesRecoveryAsBoot() bool {
 	return Bool(c.config.productVariables.BoardUsesRecoveryAsBoot)
 }
+
+func (c *deviceConfig) BoardKernelBinaries() []string {
+	return c.config.productVariables.BoardKernelBinaries
+}
diff --git a/android/module.go b/android/module.go
index 2062a4d..a12cd9b 100644
--- a/android/module.go
+++ b/android/module.go
@@ -548,6 +548,9 @@
 
 	SkipInstall bool `blueprint:"mutated"`
 
+	// Disabled by mutators. If set to true, it overrides Enabled property.
+	ForcedDisabled bool `blueprint:"mutated"`
+
 	NamespaceExportedToMake bool `blueprint:"mutated"`
 
 	MissingDeps []string `blueprint:"mutated"`
@@ -1022,6 +1025,9 @@
 }
 
 func (m *ModuleBase) Enabled() bool {
+	if m.commonProperties.ForcedDisabled {
+		return false
+	}
 	if m.commonProperties.Enabled == nil {
 		return !m.Os().DefaultDisabled
 	}
@@ -1029,7 +1035,7 @@
 }
 
 func (m *ModuleBase) Disable() {
-	m.commonProperties.Enabled = proptools.BoolPtr(false)
+	m.commonProperties.ForcedDisabled = true
 }
 
 func (m *ModuleBase) SkipInstall() {
diff --git a/android/variable.go b/android/variable.go
index 5826138..c1e1b42 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -344,6 +344,8 @@
 	InstallExtraFlattenedApexes *bool `json:",omitempty"`
 
 	BoardUsesRecoveryAsBoot *bool `json:",omitempty"`
+
+	BoardKernelBinaries []string `json:",omitempty"`
 }
 
 func boolPtr(v bool) *bool {
diff --git a/apex/androidmk.go b/apex/androidmk.go
index 082aa60..5c6d6cc 100644
--- a/apex/androidmk.go
+++ b/apex/androidmk.go
@@ -214,7 +214,7 @@
 			if !ok {
 				panic(fmt.Sprintf("Expected %s to be AndroidAppSet", fi.module))
 			}
-			fmt.Fprintln(w, "LOCAL_APK_SET_MASTER_FILE :=", as.MasterFile())
+			fmt.Fprintln(w, "LOCAL_APK_SET_INSTALL_FILE :=", as.InstallFile())
 			fmt.Fprintln(w, "LOCAL_APKCERTS_FILE :=", as.APKCertsFile().String())
 			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_android_app_set.mk")
 		case nativeSharedLib, nativeExecutable, nativeTest:
diff --git a/apex/apex_test.go b/apex/apex_test.go
index 0959a49..bfd7dfe 100644
--- a/apex/apex_test.go
+++ b/apex/apex_test.go
@@ -236,13 +236,15 @@
 	ctx.PreArchMutators(android.RegisterComponentsMutator)
 	ctx.PostDepsMutators(android.RegisterOverridePostDepsMutators)
 
-	cc.RegisterRequiredBuildComponentsForTest(ctx)
+	android.RegisterPrebuiltMutators(ctx)
 
-	// Register this after the prebuilt mutators have been registered (in
-	// cc.RegisterRequiredBuildComponentsForTest) to match what happens at runtime.
+	// Register these after the prebuilt mutators have been registered to match what
+	// happens at runtime.
 	ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
 	ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
 
+	cc.RegisterRequiredBuildComponentsForTest(ctx)
+
 	ctx.RegisterModuleType("cc_test", cc.TestFactory)
 	ctx.RegisterModuleType("vndk_prebuilt_shared", cc.VndkPrebuiltSharedFactory)
 	ctx.RegisterModuleType("vndk_libraries_txt", cc.VndkLibrariesTxtFactory)
@@ -5542,6 +5544,7 @@
 	ctx.RegisterModuleType("apex_key", ApexKeyFactory)
 	ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
+	android.RegisterPrebuiltMutators(ctx)
 	cc.RegisterRequiredBuildComponentsForTest(ctx)
 	java.RegisterJavaBuildComponents(ctx)
 	java.RegisterSystemModulesBuildComponents(ctx)
diff --git a/cc/testing.go b/cc/testing.go
index 4d0b28b..c2353d8 100644
--- a/cc/testing.go
+++ b/cc/testing.go
@@ -20,8 +20,6 @@
 
 func RegisterRequiredBuildComponentsForTest(ctx android.RegistrationContext) {
 	RegisterPrebuiltBuildComponents(ctx)
-	android.RegisterPrebuiltMutators(ctx)
-
 	RegisterCCBuildComponents(ctx)
 	RegisterBinaryBuildComponents(ctx)
 	RegisterLibraryBuildComponents(ctx)
@@ -570,6 +568,7 @@
 	ctx.RegisterModuleType("vndk_prebuilt_shared", VndkPrebuiltSharedFactory)
 	ctx.RegisterModuleType("vndk_libraries_txt", VndkLibrariesTxtFactory)
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
+	android.RegisterPrebuiltMutators(ctx)
 	RegisterRequiredBuildComponentsForTest(ctx)
 	ctx.RegisterSingletonType("vndk-snapshot", VndkSnapshotSingleton)
 	ctx.RegisterSingletonType("vendor-snapshot", VendorSnapshotSingleton)
diff --git a/cc/vendor_snapshot.go b/cc/vendor_snapshot.go
index fec0c8b..0af2258 100644
--- a/cc/vendor_snapshot.go
+++ b/cc/vendor_snapshot.go
@@ -552,6 +552,13 @@
 	if _, ok := m.linker.(*kernelHeadersDecorator); ok {
 		return false
 	}
+	// skip llndk_library and llndk_headers which are backward compatible
+	if _, ok := m.linker.(*llndkStubDecorator); ok {
+		return false
+	}
+	if _, ok := m.linker.(*llndkHeadersDecorator); ok {
+		return false
+	}
 
 	// Libraries
 	if l, ok := m.linker.(snapshotLibraryInterface); ok {
diff --git a/cmd/diff_target_files/Android.bp b/cmd/diff_target_files/Android.bp
index 5397f4b..bc6b068 100644
--- a/cmd/diff_target_files/Android.bp
+++ b/cmd/diff_target_files/Android.bp
@@ -5,12 +5,12 @@
         "diff_target_files.go",
         "glob.go",
         "target_files.go",
-        "whitelist.go",
+        "allow_list.go",
         "zip_artifact.go",
     ],
     testSrcs: [
         "compare_test.go",
         "glob_test.go",
-        "whitelist_test.go",
+        "allow_list_test.go",
     ],
 }
diff --git a/cmd/diff_target_files/whitelist.go b/cmd/diff_target_files/allow_list.go
similarity index 77%
rename from cmd/diff_target_files/whitelist.go
rename to cmd/diff_target_files/allow_list.go
index f00fc1e..ca55b43 100644
--- a/cmd/diff_target_files/whitelist.go
+++ b/cmd/diff_target_files/allow_list.go
@@ -25,18 +25,13 @@
 	"unicode"
 )
 
-type jsonWhitelist struct {
-	Paths               []string
-	IgnoreMatchingLines []string
-}
-
-type whitelist struct {
+type allowList struct {
 	path                string
 	ignoreMatchingLines []string
 }
 
-func parseWhitelists(whitelists []string, whitelistFiles []string) ([]whitelist, error) {
-	var ret []whitelist
+func parseAllowLists(allowLists []string, allowListFiles []string) ([]allowList, error) {
+	var ret []allowList
 
 	add := func(path string, ignoreMatchingLines []string) {
 		for _, x := range ret {
@@ -46,24 +41,24 @@
 			}
 		}
 
-		ret = append(ret, whitelist{
+		ret = append(ret, allowList{
 			path:                path,
 			ignoreMatchingLines: ignoreMatchingLines,
 		})
 	}
 
-	for _, file := range whitelistFiles {
-		newWhitelists, err := parseWhitelistFile(file)
+	for _, file := range allowListFiles {
+		newAllowlists, err := parseAllowListFile(file)
 		if err != nil {
 			return nil, err
 		}
 
-		for _, w := range newWhitelists {
+		for _, w := range newAllowlists {
 			add(w.path, w.ignoreMatchingLines)
 		}
 	}
 
-	for _, s := range whitelists {
+	for _, s := range allowLists {
 		colon := strings.IndexRune(s, ':')
 		var ignoreMatchingLines []string
 		if colon >= 0 {
@@ -75,7 +70,7 @@
 	return ret, nil
 }
 
-func parseWhitelistFile(file string) ([]whitelist, error) {
+func parseAllowListFile(file string) ([]allowList, error) {
 	r, err := os.Open(file)
 	if err != nil {
 		return nil, err
@@ -84,27 +79,32 @@
 
 	d := json.NewDecoder(newJSONCommentStripper(r))
 
-	var jsonWhitelists []jsonWhitelist
+	var jsonAllowLists []struct {
+		Paths               []string
+		IgnoreMatchingLines []string
+	}
 
-	err = d.Decode(&jsonWhitelists)
+	if err := d.Decode(&jsonAllowLists); err != nil {
+		return nil, err
+	}
 
-	var whitelists []whitelist
-	for _, w := range jsonWhitelists {
+	var allowLists []allowList
+	for _, w := range jsonAllowLists {
 		for _, p := range w.Paths {
-			whitelists = append(whitelists, whitelist{
+			allowLists = append(allowLists, allowList{
 				path:                p,
 				ignoreMatchingLines: w.IgnoreMatchingLines,
 			})
 		}
 	}
 
-	return whitelists, err
+	return allowLists, err
 }
 
-func filterModifiedPaths(l [][2]*ZipArtifactFile, whitelists []whitelist) ([][2]*ZipArtifactFile, error) {
+func filterModifiedPaths(l [][2]*ZipArtifactFile, allowLists []allowList) ([][2]*ZipArtifactFile, error) {
 outer:
 	for i := 0; i < len(l); i++ {
-		for _, w := range whitelists {
+		for _, w := range allowLists {
 			if match, err := Match(w.path, l[i][0].Name); err != nil {
 				return l, err
 			} else if match {
@@ -126,10 +126,10 @@
 	return l, nil
 }
 
-func filterNewPaths(l []*ZipArtifactFile, whitelists []whitelist) ([]*ZipArtifactFile, error) {
+func filterNewPaths(l []*ZipArtifactFile, allowLists []allowList) ([]*ZipArtifactFile, error) {
 outer:
 	for i := 0; i < len(l); i++ {
-		for _, w := range whitelists {
+		for _, w := range allowLists {
 			if match, err := Match(w.path, l[i].Name); err != nil {
 				return l, err
 			} else if match && len(w.ignoreMatchingLines) == 0 {
@@ -192,18 +192,18 @@
 	return bytes.Compare(bufA, bufB) == 0, nil
 }
 
-func applyWhitelists(diff zipDiff, whitelists []whitelist) (zipDiff, error) {
+func applyAllowLists(diff zipDiff, allowLists []allowList) (zipDiff, error) {
 	var err error
 
-	diff.modified, err = filterModifiedPaths(diff.modified, whitelists)
+	diff.modified, err = filterModifiedPaths(diff.modified, allowLists)
 	if err != nil {
 		return diff, err
 	}
-	diff.onlyInA, err = filterNewPaths(diff.onlyInA, whitelists)
+	diff.onlyInA, err = filterNewPaths(diff.onlyInA, allowLists)
 	if err != nil {
 		return diff, err
 	}
-	diff.onlyInB, err = filterNewPaths(diff.onlyInB, whitelists)
+	diff.onlyInB, err = filterNewPaths(diff.onlyInB, allowLists)
 	if err != nil {
 		return diff, err
 	}
diff --git a/cmd/diff_target_files/whitelist_test.go b/cmd/diff_target_files/allow_list_test.go
similarity index 82%
rename from cmd/diff_target_files/whitelist_test.go
rename to cmd/diff_target_files/allow_list_test.go
index 4b19fdd..8410e5a 100644
--- a/cmd/diff_target_files/whitelist_test.go
+++ b/cmd/diff_target_files/allow_list_test.go
@@ -57,10 +57,10 @@
 
 var f2 = bytesToZipArtifactFile("dir/f2", nil)
 
-func Test_applyWhitelists(t *testing.T) {
+func Test_applyAllowLists(t *testing.T) {
 	type args struct {
 		diff       zipDiff
-		whitelists []whitelist
+		allowLists []allowList
 	}
 	tests := []struct {
 		name    string
@@ -74,7 +74,7 @@
 				diff: zipDiff{
 					onlyInA: []*ZipArtifactFile{f1a, f2},
 				},
-				whitelists: []whitelist{{path: "dir/f1"}},
+				allowLists: []allowList{{path: "dir/f1"}},
 			},
 			want: zipDiff{
 				onlyInA: []*ZipArtifactFile{f2},
@@ -86,7 +86,7 @@
 				diff: zipDiff{
 					onlyInA: []*ZipArtifactFile{f1a, f2},
 				},
-				whitelists: []whitelist{{path: "dir/*"}},
+				allowLists: []allowList{{path: "dir/*"}},
 			},
 			want: zipDiff{},
 		},
@@ -96,7 +96,7 @@
 				diff: zipDiff{
 					modified: [][2]*ZipArtifactFile{{f1a, f1b}},
 				},
-				whitelists: []whitelist{{path: "dir/*"}},
+				allowLists: []allowList{{path: "dir/*"}},
 			},
 			want: zipDiff{},
 		},
@@ -106,20 +106,20 @@
 				diff: zipDiff{
 					modified: [][2]*ZipArtifactFile{{f1a, f1b}},
 				},
-				whitelists: []whitelist{{path: "dir/*", ignoreMatchingLines: []string{"foo: .*"}}},
+				allowLists: []allowList{{path: "dir/*", ignoreMatchingLines: []string{"foo: .*"}}},
 			},
 			want: zipDiff{},
 		},
 	}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
-			got, err := applyWhitelists(tt.args.diff, tt.args.whitelists)
+			got, err := applyAllowLists(tt.args.diff, tt.args.allowLists)
 			if (err != nil) != tt.wantErr {
-				t.Errorf("applyWhitelists() error = %v, wantErr %v", err, tt.wantErr)
+				t.Errorf("Test_applyAllowLists() error = %v, wantErr %v", err, tt.wantErr)
 				return
 			}
 			if !reflect.DeepEqual(got, tt.want) {
-				t.Errorf("applyWhitelists() = %v, want %v", got, tt.want)
+				t.Errorf("Test_applyAllowLists() = %v, want %v", got, tt.want)
 			}
 		})
 	}
diff --git a/cmd/diff_target_files/compare.go b/cmd/diff_target_files/compare.go
index 00cd9ca..45b6d6b 100644
--- a/cmd/diff_target_files/compare.go
+++ b/cmd/diff_target_files/compare.go
@@ -21,7 +21,7 @@
 
 // compareTargetFiles takes two ZipArtifacts and compares the files they contain by examining
 // the path, size, and CRC of each file.
-func compareTargetFiles(priZip, refZip ZipArtifact, artifact string, whitelists []whitelist, filters []string) (zipDiff, error) {
+func compareTargetFiles(priZip, refZip ZipArtifact, artifact string, allowLists []allowList, filters []string) (zipDiff, error) {
 	priZipFiles, err := priZip.Files()
 	if err != nil {
 		return zipDiff{}, fmt.Errorf("error fetching target file lists from primary zip %v", err)
@@ -45,7 +45,7 @@
 	// Compare the file lists from both builds
 	diff := diffTargetFilesLists(refZipFiles, priZipFiles)
 
-	return applyWhitelists(diff, whitelists)
+	return applyAllowLists(diff, allowLists)
 }
 
 // zipDiff contains the list of files that differ between two zip files.
diff --git a/cmd/diff_target_files/diff_target_files.go b/cmd/diff_target_files/diff_target_files.go
index 75bc8ee..634565b 100644
--- a/cmd/diff_target_files/diff_target_files.go
+++ b/cmd/diff_target_files/diff_target_files.go
@@ -22,8 +22,8 @@
 )
 
 var (
-	whitelists     = newMultiString("whitelist", "whitelist patterns in the form <pattern>[:<regex of line to ignore>]")
-	whitelistFiles = newMultiString("whitelist_file", "files containing whitelist definitions")
+	allowLists     = newMultiString("allowlist", "allowlist patterns in the form <pattern>[:<regex of line to ignore>]")
+	allowListFiles = newMultiString("allowlist_file", "files containing allowlist definitions")
 
 	filters = newMultiString("filter", "filter patterns to apply to files in target-files.zip before comparing")
 )
@@ -47,9 +47,9 @@
 		os.Exit(1)
 	}
 
-	whitelists, err := parseWhitelists(*whitelists, *whitelistFiles)
+	allowLists, err := parseAllowLists(*allowLists, *allowListFiles)
 	if err != nil {
-		fmt.Fprintf(os.Stderr, "Error parsing whitelists: %v\n", err)
+		fmt.Fprintf(os.Stderr, "Error parsing allowlists: %v\n", err)
 		os.Exit(1)
 	}
 
@@ -67,7 +67,7 @@
 	}
 	defer refZip.Close()
 
-	diff, err := compareTargetFiles(priZip, refZip, targetFilesPattern, whitelists, *filters)
+	diff, err := compareTargetFiles(priZip, refZip, targetFilesPattern, allowLists, *filters)
 	if err != nil {
 		fmt.Fprintf(os.Stderr, "Error comparing zip files: %v\n", err)
 		os.Exit(1)
diff --git a/java/androidmk.go b/java/androidmk.go
index 25dd329..081fcb2 100644
--- a/java/androidmk.go
+++ b/java/androidmk.go
@@ -728,7 +728,7 @@
 			ExtraEntries: []android.AndroidMkExtraEntriesFunc{
 				func(entries *android.AndroidMkEntries) {
 					entries.SetBoolIfTrue("LOCAL_PRIVILEGED_MODULE", apkSet.Privileged())
-					entries.SetString("LOCAL_APK_SET_MASTER_FILE", apkSet.masterFile)
+					entries.SetString("LOCAL_APK_SET_INSTALL_FILE", apkSet.InstallFile())
 					entries.SetPath("LOCAL_APKCERTS_FILE", apkSet.apkcertsFile)
 					entries.AddStrings("LOCAL_OVERRIDES_PACKAGES", apkSet.properties.Overrides...)
 				},
diff --git a/java/app.go b/java/app.go
index 4031cfe..1ede34e 100755
--- a/java/app.go
+++ b/java/app.go
@@ -78,7 +78,7 @@
 
 	properties   AndroidAppSetProperties
 	packedOutput android.WritablePath
-	masterFile   string
+	installFile  string
 	apkcertsFile android.ModuleOutPath
 }
 
@@ -102,8 +102,8 @@
 	return as.packedOutput
 }
 
-func (as *AndroidAppSet) MasterFile() string {
-	return as.masterFile
+func (as *AndroidAppSet) InstallFile() string {
+	return as.installFile
 }
 
 func (as *AndroidAppSet) APKCertsFile() android.Path {
@@ -136,10 +136,10 @@
 func (as *AndroidAppSet) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	as.packedOutput = android.PathForModuleOut(ctx, ctx.ModuleName()+".zip")
 	as.apkcertsFile = android.PathForModuleOut(ctx, "apkcerts.txt")
-	// We are assuming here that the master file in the APK
+	// We are assuming here that the install file in the APK
 	// set has `.apk` suffix. If it doesn't the build will fail.
 	// APK sets containing APEX files are handled elsewhere.
-	as.masterFile = as.BaseModuleName() + ".apk"
+	as.installFile = as.BaseModuleName() + ".apk"
 	screenDensities := "all"
 	if dpis := ctx.Config().ProductAAPTPrebuiltDPI(); len(dpis) > 0 {
 		screenDensities = strings.ToUpper(strings.Join(dpis, ","))
@@ -167,7 +167,7 @@
 
 // android_app_set extracts a set of APKs based on the target device
 // configuration and installs this set as "split APKs".
-// The extracted set always contains 'master' APK whose name is
+// The extracted set always contains an APK whose name is
 // _module_name_.apk and every split APK matching target device.
 // The extraction of the density-specific splits depends on
 // PRODUCT_AAPT_PREBUILT_DPI variable. If present (its value should
diff --git a/java/app_test.go b/java/app_test.go
index d4323bb..efb4fd2 100644
--- a/java/app_test.go
+++ b/java/app_test.go
@@ -161,11 +161,11 @@
 		t.Errorf("wrong partition value: '%s', expected 'system'", s)
 	}
 	mkEntries := android.AndroidMkEntriesForTest(t, config, "", module.Module())[0]
-	actualMaster := mkEntries.EntryMap["LOCAL_APK_SET_MASTER_FILE"]
-	expectedMaster := []string{"foo.apk"}
-	if !reflect.DeepEqual(actualMaster, expectedMaster) {
-		t.Errorf("Unexpected LOCAL_APK_SET_MASTER_FILE value: '%s', expected: '%s',",
-			actualMaster, expectedMaster)
+	actualInstallFile := mkEntries.EntryMap["LOCAL_APK_SET_INSTALL_FILE"]
+	expectedInstallFile := []string{"foo.apk"}
+	if !reflect.DeepEqual(actualInstallFile, expectedInstallFile) {
+		t.Errorf("Unexpected LOCAL_APK_SET_INSTALL_FILE value: '%s', expected: '%s',",
+			actualInstallFile, expectedInstallFile)
 	}
 }
 
diff --git a/java/droiddoc.go b/java/droiddoc.go
index 935b839..d2f8d83 100644
--- a/java/droiddoc.go
+++ b/java/droiddoc.go
@@ -198,7 +198,7 @@
 	// the generated removed Dex API filename by Doclava.
 	Removed_dex_api_filename *string
 
-	// if set to false, don't allow droiddoc to generate stubs source files. Defaults to true.
+	// if set to false, don't allow droiddoc to generate stubs source files. Defaults to false.
 	Create_stubs *bool
 
 	Check_api struct {
@@ -870,6 +870,10 @@
 	}
 }
 
+func (d *Droiddoc) createStubs() bool {
+	return BoolDefault(d.properties.Create_stubs, false)
+}
+
 func (d *Droiddoc) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.WritablePath) {
 	if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
 		apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") ||
@@ -892,7 +896,7 @@
 		cmd.FlagWithOutput("-removedDexApi ", d.removedDexApiFile)
 	}
 
-	if BoolDefault(d.properties.Create_stubs, true) {
+	if d.createStubs() {
 		cmd.FlagWithArg("-stubs ", stubsDir.String())
 	}
 
diff --git a/java/java_test.go b/java/java_test.go
index 582ebe9..a3c7854 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -96,6 +96,8 @@
 	ctx.RegisterPreSingletonType("overlay", android.SingletonFactoryAdaptor(OverlaySingletonFactory))
 	ctx.RegisterPreSingletonType("sdk_versions", android.SingletonFactoryAdaptor(sdkPreSingletonFactory))
 
+	android.RegisterPrebuiltMutators(ctx)
+
 	// Register module types and mutators from cc needed for JNI testing
 	cc.RegisterRequiredBuildComponentsForTest(ctx)
 
@@ -1107,8 +1109,13 @@
 			"bar-doc/a.java": nil,
 			"bar-doc/b.java": nil,
 		})
+	barDocModule := ctx.ModuleForTests("bar-doc", "android_common")
+	barDoc := barDocModule.Rule("javadoc")
+	notExpected := " -stubs "
+	if strings.Contains(barDoc.RuleParams.Command, notExpected) {
+		t.Errorf("bar-doc command contains flag %q to create stubs, but should not", notExpected)
+	}
 
-	barDoc := ctx.ModuleForTests("bar-doc", "android_common").Rule("javadoc")
 	var javaSrcs []string
 	for _, i := range barDoc.Inputs {
 		javaSrcs = append(javaSrcs, i.Base())
@@ -1117,7 +1124,7 @@
 		t.Errorf("inputs of bar-doc must be []string{\"a.java\"}, but was %#v.", javaSrcs)
 	}
 
-	aidl := ctx.ModuleForTests("bar-doc", "android_common").Rule("aidl")
+	aidl := barDocModule.Rule("aidl")
 	if g, w := barDoc.Implicits.Strings(), aidl.Output.String(); !inList(w, g) {
 		t.Errorf("implicits of bar-doc must contain %q, but was %q.", w, g)
 	}
diff --git a/rust/library.go b/rust/library.go
index 4c6da9d..6d5eca0 100644
--- a/rust/library.go
+++ b/rust/library.go
@@ -454,25 +454,19 @@
 	if m, ok := mctx.Module().(*Module); ok && m.compiler != nil {
 		switch library := m.compiler.(type) {
 		case libraryInterface:
+			if library.buildRlib() && library.buildDylib() {
+				modules := mctx.CreateLocalVariations("rlib", "dylib")
+				rlib := modules[0].(*Module)
+				dylib := modules[1].(*Module)
 
-			// We only build the rust library variants here. This assumes that
-			// LinkageMutator runs first and there's an empty variant
-			// if rust variants are required.
-			if !library.static() && !library.shared() {
-				if library.buildRlib() && library.buildDylib() {
-					modules := mctx.CreateLocalVariations("rlib", "dylib")
-					rlib := modules[0].(*Module)
-					dylib := modules[1].(*Module)
-
-					rlib.compiler.(libraryInterface).setRlib()
-					dylib.compiler.(libraryInterface).setDylib()
-				} else if library.buildRlib() {
-					modules := mctx.CreateLocalVariations("rlib")
-					modules[0].(*Module).compiler.(libraryInterface).setRlib()
-				} else if library.buildDylib() {
-					modules := mctx.CreateLocalVariations("dylib")
-					modules[0].(*Module).compiler.(libraryInterface).setDylib()
-				}
+				rlib.compiler.(libraryInterface).setRlib()
+				dylib.compiler.(libraryInterface).setDylib()
+			} else if library.buildRlib() {
+				modules := mctx.CreateLocalVariations("rlib")
+				modules[0].(*Module).compiler.(libraryInterface).setRlib()
+			} else if library.buildDylib() {
+				modules := mctx.CreateLocalVariations("dylib")
+				modules[0].(*Module).compiler.(libraryInterface).setDylib()
 			}
 		}
 	}
diff --git a/rust/rust.go b/rust/rust.go
index 78bf7ad..5d383e1 100644
--- a/rust/rust.go
+++ b/rust/rust.go
@@ -141,12 +141,8 @@
 
 func (mod *Module) NonCcVariants() bool {
 	if mod.compiler != nil {
-		if library, ok := mod.compiler.(libraryInterface); ok {
-			if library.buildRlib() || library.buildDylib() {
-				return true
-			} else {
-				return false
-			}
+		if _, ok := mod.compiler.(libraryInterface); ok {
+			return false
 		}
 	}
 	panic(fmt.Errorf("NonCcVariants called on non-library module: %q", mod.BaseModuleName()))
@@ -162,16 +158,16 @@
 			return library.static()
 		}
 	}
-	panic(fmt.Errorf("Static called on non-library module: %q", mod.BaseModuleName()))
+	return false
 }
 
 func (mod *Module) Shared() bool {
 	if mod.compiler != nil {
 		if library, ok := mod.compiler.(libraryInterface); ok {
-			return library.static()
+			return library.shared()
 		}
 	}
-	panic(fmt.Errorf("Shared called on non-library module: %q", mod.BaseModuleName()))
+	return false
 }
 
 func (mod *Module) Toc() android.OptionalPath {
@@ -399,7 +395,9 @@
 
 func (mod *Module) CcLibraryInterface() bool {
 	if mod.compiler != nil {
-		if _, ok := mod.compiler.(libraryInterface); ok {
+		// use build{Static,Shared}() instead of {static,shared}() here because this might be called before
+		// VariantIs{Static,Shared} is set.
+		if lib, ok := mod.compiler.(libraryInterface); ok && (lib.buildShared() || lib.buildStatic()) {
 			return true
 		}
 	}
@@ -754,7 +752,7 @@
 	ctx.VisitDirectDeps(func(dep android.Module) {
 		depName := ctx.OtherModuleName(dep)
 		depTag := ctx.OtherModuleDependencyTag(dep)
-		if rustDep, ok := dep.(*Module); ok {
+		if rustDep, ok := dep.(*Module); ok && !rustDep.CcLibraryInterface() {
 			//Handle Rust Modules
 
 			linkFile := rustDep.outputFile
@@ -816,17 +814,7 @@
 				}
 			}
 
-		}
-
-		if srcDep, ok := dep.(android.SourceFileProducer); ok {
-			switch depTag {
-			case android.SourceDepTag:
-				// These are usually genrules which don't have per-target variants.
-				directSrcDeps = append(directSrcDeps, srcDep)
-			}
-		}
-
-		if ccDep, ok := dep.(cc.LinkableInterface); ok {
+		} else if ccDep, ok := dep.(cc.LinkableInterface); ok {
 			//Handle C dependencies
 			if _, ok := ccDep.(*Module); !ok {
 				if ccDep.Module().Target().Os != ctx.Os() {
@@ -886,6 +874,14 @@
 				lib.exportDepFlags(depFlag)
 			}
 		}
+
+		if srcDep, ok := dep.(android.SourceFileProducer); ok {
+			switch depTag {
+			case android.SourceDepTag:
+				// These are usually genrules which don't have per-target variants.
+				directSrcDeps = append(directSrcDeps, srcDep)
+			}
+		}
 	})
 
 	var rlibDepFiles RustLibraries
@@ -974,21 +970,18 @@
 	}
 	actx.AddVariationDependencies(
 		append(commonDepVariations, []blueprint.Variation{
-			{Mutator: "rust_libraries", Variation: "rlib"},
-			{Mutator: "link", Variation: ""}}...),
+			{Mutator: "rust_libraries", Variation: "rlib"}}...),
 		rlibDepTag, deps.Rlibs...)
 	actx.AddVariationDependencies(
 		append(commonDepVariations, []blueprint.Variation{
-			{Mutator: "rust_libraries", Variation: "dylib"},
-			{Mutator: "link", Variation: ""}}...),
+			{Mutator: "rust_libraries", Variation: "dylib"}}...),
 		dylibDepTag, deps.Dylibs...)
 
 	if deps.Rustlibs != nil {
 		autoDep := mod.compiler.(autoDeppable).autoDep()
 		actx.AddVariationDependencies(
 			append(commonDepVariations, []blueprint.Variation{
-				{Mutator: "rust_libraries", Variation: autoDep.variation},
-				{Mutator: "link", Variation: ""}}...),
+				{Mutator: "rust_libraries", Variation: autoDep.variation}}...),
 			autoDep.depTag, deps.Rustlibs...)
 	}
 
diff --git a/rust/testing.go b/rust/testing.go
index f2d4c5e..83b2828 100644
--- a/rust/testing.go
+++ b/rust/testing.go
@@ -77,6 +77,7 @@
 
 func CreateTestContext() *android.TestContext {
 	ctx := android.NewTestArchContext()
+	android.RegisterPrebuiltMutators(ctx)
 	cc.RegisterRequiredBuildComponentsForTest(ctx)
 	ctx.RegisterModuleType("genrule", genrule.GenRuleFactory)
 	ctx.RegisterModuleType("rust_binary", RustBinaryFactory)
diff --git a/sdk/testing.go b/sdk/testing.go
index 34ea8f0..b53558d 100644
--- a/sdk/testing.go
+++ b/sdk/testing.go
@@ -97,6 +97,11 @@
 	ctx.PreArchMutators(android.RegisterVisibilityRuleChecker)
 	ctx.PreArchMutators(android.RegisterDefaultsPreArchMutators)
 	ctx.PreArchMutators(android.RegisterComponentsMutator)
+
+	android.RegisterPrebuiltMutators(ctx)
+
+	// Register these after the prebuilt mutators have been registered to match what
+	// happens at runtime.
 	ctx.PreArchMutators(android.RegisterVisibilityRuleGatherer)
 	ctx.PostDepsMutators(android.RegisterVisibilityRuleEnforcer)
 
diff --git a/sysprop/sysprop_test.go b/sysprop/sysprop_test.go
index 8503386..711129c 100644
--- a/sysprop/sysprop_test.go
+++ b/sysprop/sysprop_test.go
@@ -67,6 +67,8 @@
 		ctx.BottomUp("sysprop_deps", syspropDepsMutator).Parallel()
 	})
 
+	android.RegisterPrebuiltMutators(ctx)
+
 	cc.RegisterRequiredBuildComponentsForTest(ctx)
 	ctx.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
 		ctx.BottomUp("sysprop_java", java.SyspropMutator).Parallel()
diff --git a/ui/build/rbe_test.go b/ui/build/rbe_test.go
index 2c4995b..23a53b4 100644
--- a/ui/build/rbe_test.go
+++ b/ui/build/rbe_test.go
@@ -94,12 +94,12 @@
 	}, {
 		description:         "stopRBE failed",
 		rbeOutputDirDefined: true,
-		bootstrapProgram:    "#!/bin/bash\nexit 1",
+		bootstrapProgram:    "#!/bin/bash\nexit 1\n",
 		expectedErr:         "shutdown failed",
 	}, {
 		description:         "failed to copy metrics file",
 		rbeOutputDirDefined: true,
-		bootstrapProgram:    "#!/bin/bash",
+		bootstrapProgram:    "#!/bin/bash\n",
 		expectedErr:         "failed to copy",
 	}}
 
@@ -139,4 +139,4 @@
 	}
 }
 
-var rbeBootstrapProgram = fmt.Sprintf("#!/bin/bash\necho 1 > $RBE_output_dir/%s", rbeMetricsPBFilename)
+var rbeBootstrapProgram = fmt.Sprintf("#!/bin/bash\necho 1 > $RBE_output_dir/%s\n", rbeMetricsPBFilename)