Merge "[soong] Zero and pattern initialization of heap memory."
diff --git a/apex/vndk.go b/apex/vndk.go
index f948d76..5cc0e2a 100644
--- a/apex/vndk.go
+++ b/apex/vndk.go
@@ -154,10 +154,12 @@
 
 	// TODO(b/124106384): Clean up compat symlinks for ART binaries.
 	if strings.HasPrefix(name, "com.android.art.") {
-		artBinaries := []string{"dalvikvm", "dex2oat"}
-		for _, b := range artBinaries {
-			addSymlink("/apex/com.android.art/bin/"+b, "$(TARGET_OUT)/bin", b)
+		addSymlink("/apex/com.android.art/bin/dalvikvm", "$(TARGET_OUT)/bin", "dalvikvm")
+		dex2oat := "dex2oat32"
+		if ctx.Config().Android64() {
+			dex2oat = "dex2oat64"
 		}
+		addSymlink("/apex/com.android.art/bin/"+dex2oat, "$(TARGET_OUT)/bin", "dex2oat")
 		return
 	}
 	return
diff --git a/cc/config/clang.go b/cc/config/clang.go
index bdd9030..24dc6b9 100644
--- a/cc/config/clang.go
+++ b/cc/config/clang.go
@@ -48,6 +48,8 @@
 	"-Wunused-but-set-parameter",
 	"-Wunused-but-set-variable",
 	"-fdiagnostics-color",
+	// http://b/153759688
+	"-fuse-init-array",
 
 	// arm + arm64
 	"-fgcse-after-reload",
@@ -113,9 +115,6 @@
 		// color codes if it is not running in a terminal.
 		"-fcolor-diagnostics",
 
-		// http://b/68236239 Allow 0/NULL instead of using nullptr everywhere.
-		"-Wno-zero-as-null-pointer-constant",
-
 		// Warnings from clang-7.0
 		"-Wno-sign-compare",
 
@@ -166,6 +165,17 @@
 		"-Wno-int-in-bool-context",          // http://b/148287349
 		"-Wno-sizeof-array-div",             // http://b/148815709
 		"-Wno-tautological-overlap-compare", // http://b/148815696
+		// New warnings to be fixed after clang-r383902.
+		"-Wno-deprecated-copy",                      // http://b/153746672
+		"-Wno-range-loop-construct",                 // http://b/153747076
+		"-Wno-misleading-indentation",               // http://b/153746954
+		"-Wno-zero-as-null-pointer-constant",        // http://b/68236239
+		"-Wno-deprecated-anon-enum-enum-conversion", // http://b/153746485
+		"-Wno-deprecated-enum-enum-conversion",      // http://b/153746563
+		"-Wno-string-compare",                       // http://b/153764102
+		"-Wno-enum-enum-conversion",                 // http://b/154138986
+		"-Wno-enum-float-conversion",                // http://b/154255917
+		"-Wno-pessimizing-move",                     // http://b/154270751
 	}, " "))
 
 	// Extra cflags for external third-party projects to disable warnings that
diff --git a/cc/config/global.go b/cc/config/global.go
index f9255be..923dd29 100644
--- a/cc/config/global.go
+++ b/cc/config/global.go
@@ -128,8 +128,8 @@
 
 	// prebuilts/clang default settings.
 	ClangDefaultBase         = "prebuilts/clang/host"
-	ClangDefaultVersion      = "clang-r377782d"
-	ClangDefaultShortVersion = "10.0.6"
+	ClangDefaultVersion      = "clang-r383902"
+	ClangDefaultShortVersion = "11.0.1"
 
 	// Directories with warnings from Android.bp files.
 	WarningAllowedProjects = []string{
diff --git a/cc/fuzz.go b/cc/fuzz.go
index ebe4252..948595b 100644
--- a/cc/fuzz.go
+++ b/cc/fuzz.go
@@ -126,7 +126,7 @@
 func collectAllSharedDependencies(ctx android.SingletonContext, module android.Module) android.Paths {
 	var fringe []android.Module
 
-	seen := make(map[android.Module]bool)
+	seen := make(map[string]bool)
 
 	// Enumerate the first level of dependencies, as we discard all non-library
 	// modules in the BFS loop below.
@@ -140,15 +140,15 @@
 
 	for i := 0; i < len(fringe); i++ {
 		module := fringe[i]
-		if seen[module] {
+		if seen[module.Name()] {
 			continue
 		}
-		seen[module] = true
+		seen[module.Name()] = true
 
 		ccModule := module.(*Module)
 		sharedLibraries = append(sharedLibraries, ccModule.UnstrippedOutputFile())
 		ctx.VisitDirectDeps(module, func(dep android.Module) {
-			if isValidSharedDependency(dep) && !seen[dep] {
+			if isValidSharedDependency(dep) && !seen[dep.Name()] {
 				fringe = append(fringe, dep)
 			}
 		})
@@ -255,13 +255,13 @@
 	}
 
 	// Grab the list of required shared libraries.
-	seen := make(map[android.Module]bool)
+	seen := make(map[string]bool)
 	var sharedLibraries android.Paths
 	ctx.WalkDeps(func(child, parent android.Module) bool {
-		if seen[child] {
+		if seen[child.Name()] {
 			return false
 		}
-		seen[child] = true
+		seen[child.Name()] = true
 
 		if isValidSharedDependency(child) {
 			sharedLibraries = append(sharedLibraries, child.(*Module).UnstrippedOutputFile())
diff --git a/cc/tidy.go b/cc/tidy.go
index cfb5b68..364e56c 100644
--- a/cc/tidy.go
+++ b/cc/tidy.go
@@ -121,6 +121,12 @@
 	// many local projects enable cert-* checks, which
 	// trigger bugprone-reserved-identifier.
 	tidyChecks = tidyChecks + ",-bugprone-reserved-identifier*,-cert-dcl51-cpp,-cert-dcl37-c"
+	// http://b/153757728
+	tidyChecks = tidyChecks + ",-readability-qualified-auto"
+	// http://b/155034563
+	tidyChecks = tidyChecks + ",-bugprone-signed-char-misuse"
+	// http://b/155034972
+	tidyChecks = tidyChecks + ",-bugprone-branch-clone"
 	flags.TidyFlags = append(flags.TidyFlags, tidyChecks)
 
 	if len(tidy.Properties.Tidy_checks_as_errors) > 0 {
diff --git a/java/app.go b/java/app.go
index 4f4a8d3..d535c5a 100755
--- a/java/app.go
+++ b/java/app.go
@@ -45,6 +45,7 @@
 	ctx.RegisterModuleType("android_app_certificate", AndroidAppCertificateFactory)
 	ctx.RegisterModuleType("override_android_app", OverrideAndroidAppModuleFactory)
 	ctx.RegisterModuleType("override_android_test", OverrideAndroidTestModuleFactory)
+	ctx.RegisterModuleType("override_runtime_resource_overlay", OverrideRuntimeResourceOverlayModuleFactory)
 	ctx.RegisterModuleType("android_app_import", AndroidAppImportFactory)
 	ctx.RegisterModuleType("android_test_import", AndroidTestImportFactory)
 	ctx.RegisterModuleType("runtime_resource_overlay", RuntimeResourceOverlayFactory)
@@ -131,6 +132,15 @@
 	Logging_parent *string
 }
 
+// runtime_resource_overlay properties that can be overridden by override_runtime_resource_overlay
+type OverridableRuntimeResourceOverlayProperties struct {
+	// the package name of this app. The package name in the manifest file is used if one was not given.
+	Package_name *string
+
+	// the target package name of this overlay app. The target package name in the manifest file is used if one was not given.
+	Target_package_name *string
+}
+
 type AndroidApp struct {
 	Library
 	aapt
@@ -570,28 +580,14 @@
 
 	// Build a final signed app package.
 	packageFile := android.PathForModuleOut(ctx, a.installApkName+".apk")
-	v4SigningRequested := Bool(a.Module.deviceProperties.V4_signature)
-	var v4SignatureFile android.WritablePath = nil
-	if v4SigningRequested {
-		v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+".apk.idsig")
-	}
-	CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps, v4SignatureFile)
+	CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps)
 	a.outputFile = packageFile
-	if v4SigningRequested {
-		a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
-	}
 
 	for _, split := range a.aapt.splits {
 		// Sign the split APKs
 		packageFile := android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk")
-		if v4SigningRequested {
-			v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk.idsig")
-		}
-		CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps, v4SignatureFile)
+		CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps)
 		a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
-		if v4SigningRequested {
-			a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
-		}
 	}
 
 	// Build an app bundle.
@@ -753,6 +749,7 @@
 }
 
 type appTestProperties struct {
+	// The name of the android_app module that the tests will run against.
 	Instrumentation_for *string
 
 	// if specified, the instrumentation target package name in the manifest is overwritten by it.
@@ -988,6 +985,27 @@
 	return m
 }
 
+type OverrideRuntimeResourceOverlay struct {
+	android.ModuleBase
+	android.OverrideModuleBase
+}
+
+func (i *OverrideRuntimeResourceOverlay) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	// All the overrides happen in the base module.
+	// TODO(jungjw): Check the base module type.
+}
+
+// override_runtime_resource_overlay is used to create a module based on another
+// runtime_resource_overlay module by overriding some of its properties.
+func OverrideRuntimeResourceOverlayModuleFactory() android.Module {
+	m := &OverrideRuntimeResourceOverlay{}
+	m.AddProperties(&OverridableRuntimeResourceOverlayProperties{})
+
+	android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
+	android.InitOverrideModule(m)
+	return m
+}
+
 type AndroidAppImport struct {
 	android.ModuleBase
 	android.DefaultableModuleBase
@@ -1218,7 +1236,7 @@
 		}
 		a.certificate = certificates[0]
 		signed := android.PathForModuleOut(ctx, "signed", apkFilename)
-		SignAppPackage(ctx, signed, dexOutput, certificates, nil)
+		SignAppPackage(ctx, signed, dexOutput, certificates)
 		a.outputFile = signed
 	} else {
 		alignedApk := android.PathForModuleOut(ctx, "zip-aligned", apkFilename)
@@ -1383,9 +1401,11 @@
 type RuntimeResourceOverlay struct {
 	android.ModuleBase
 	android.DefaultableModuleBase
+	android.OverridableModuleBase
 	aapt
 
-	properties RuntimeResourceOverlayProperties
+	properties            RuntimeResourceOverlayProperties
+	overridableProperties OverridableRuntimeResourceOverlayProperties
 
 	certificate Certificate
 
@@ -1452,13 +1472,27 @@
 	// Compile and link resources
 	r.aapt.hasNoCode = true
 	// Do not remove resources without default values nor dedupe resource configurations with the same value
-	r.aapt.buildActions(ctx, r, "--no-resource-deduping", "--no-resource-removal")
+	aaptLinkFlags := []string{"--no-resource-deduping", "--no-resource-removal"}
+	// Allow the override of "package name" and "overlay target package name"
+	manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
+	if overridden || r.overridableProperties.Package_name != nil {
+		// The product override variable has a priority over the package_name property.
+		if !overridden {
+			manifestPackageName = *r.overridableProperties.Package_name
+		}
+		aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
+	}
+	if r.overridableProperties.Target_package_name != nil {
+		aaptLinkFlags = append(aaptLinkFlags,
+			"--rename-overlay-target-package "+*r.overridableProperties.Target_package_name)
+	}
+	r.aapt.buildActions(ctx, r, aaptLinkFlags...)
 
 	// Sign the built package
 	_, certificates := collectAppDeps(ctx, false, false)
 	certificates = processMainCert(r.ModuleBase, String(r.properties.Certificate), certificates, ctx)
 	signed := android.PathForModuleOut(ctx, "signed", r.Name()+".apk")
-	SignAppPackage(ctx, signed, r.aapt.exportPackage, certificates, nil)
+	SignAppPackage(ctx, signed, r.aapt.exportPackage, certificates)
 	r.certificate = certificates[0]
 
 	r.outputFile = signed
@@ -1503,10 +1537,12 @@
 	module := &RuntimeResourceOverlay{}
 	module.AddProperties(
 		&module.properties,
-		&module.aaptProperties)
+		&module.aaptProperties,
+		&module.overridableProperties)
 
-	InitJavaModule(module, android.DeviceSupported)
-
+	android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
+	android.InitDefaultableModule(module)
+	android.InitOverridableModule(module, &module.properties.Overrides)
 	return module
 }
 
diff --git a/java/app_builder.go b/java/app_builder.go
index b2780bc..5e7fbe6 100644
--- a/java/app_builder.go
+++ b/java/app_builder.go
@@ -45,7 +45,7 @@
 	})
 
 func CreateAndSignAppPackage(ctx android.ModuleContext, outputFile android.WritablePath,
-	packageFile, jniJarFile, dexJarFile android.Path, certificates []Certificate, deps android.Paths, v4SignatureFile android.WritablePath) {
+	packageFile, jniJarFile, dexJarFile android.Path, certificates []Certificate, deps android.Paths) {
 
 	unsignedApkName := strings.TrimSuffix(outputFile.Base(), ".apk") + "-unsigned.apk"
 	unsignedApk := android.PathForModuleOut(ctx, unsignedApkName)
@@ -66,10 +66,10 @@
 		Implicits: deps,
 	})
 
-	SignAppPackage(ctx, outputFile, unsignedApk, certificates, v4SignatureFile)
+	SignAppPackage(ctx, outputFile, unsignedApk, certificates)
 }
 
-func SignAppPackage(ctx android.ModuleContext, signedApk android.WritablePath, unsignedApk android.Path, certificates []Certificate, v4SignatureFile android.WritablePath) {
+func SignAppPackage(ctx android.ModuleContext, signedApk android.WritablePath, unsignedApk android.Path, certificates []Certificate) {
 
 	var certificateArgs []string
 	var deps android.Paths
@@ -78,22 +78,14 @@
 		deps = append(deps, c.Pem, c.Key)
 	}
 
-	outputFiles := android.WritablePaths{signedApk}
-	var flag string = ""
-	if v4SignatureFile != nil {
-		outputFiles = append(outputFiles, v4SignatureFile)
-		flag = "--enable-v4"
-	}
-
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        Signapk,
 		Description: "signapk",
-		Outputs:     outputFiles,
+		Output:      signedApk,
 		Input:       unsignedApk,
 		Implicits:   deps,
 		Args: map[string]string{
 			"certificates": strings.Join(certificateArgs, " "),
-			"flags":        flag,
 		},
 	})
 }
diff --git a/java/app_test.go b/java/app_test.go
index c1a0cdd..998c76a 100644
--- a/java/app_test.go
+++ b/java/app_test.go
@@ -1200,66 +1200,6 @@
 	}
 }
 
-func TestRequestV4SigningFlag(t *testing.T) {
-	testCases := []struct {
-		name     string
-		bp       string
-		expected string
-	}{
-		{
-			name: "default",
-			bp: `
-				android_app {
-					name: "foo",
-					srcs: ["a.java"],
-					sdk_version: "current",
-				}
-			`,
-			expected: "",
-		},
-		{
-			name: "default",
-			bp: `
-				android_app {
-					name: "foo",
-					srcs: ["a.java"],
-					sdk_version: "current",
-					v4_signature: false,
-				}
-			`,
-			expected: "",
-		},
-		{
-			name: "module certificate property",
-			bp: `
-				android_app {
-					name: "foo",
-					srcs: ["a.java"],
-					sdk_version: "current",
-					v4_signature: true,
-				}
-			`,
-			expected: "--enable-v4",
-		},
-	}
-
-	for _, test := range testCases {
-		t.Run(test.name, func(t *testing.T) {
-			config := testAppConfig(nil, test.bp, nil)
-			ctx := testContext()
-
-			run(t, ctx, config)
-			foo := ctx.ModuleForTests("foo", "android_common")
-
-			signapk := foo.Output("foo.apk")
-			signFlags := signapk.Args["flags"]
-			if test.expected != signFlags {
-				t.Errorf("Incorrect signing flags, expected: %q, got: %q", test.expected, signFlags)
-			}
-		})
-	}
-}
-
 func TestPackageNameOverride(t *testing.T) {
 	testCases := []struct {
 		name                string
@@ -2566,3 +2506,137 @@
 		t.Errorf("Unexpected LOCAL_OVERRIDES_PACKAGES value: %v, expected: %v", overrides, expectedOverrides)
 	}
 }
+
+func TestOverrideRuntimeResourceOverlay(t *testing.T) {
+	ctx, _ := testJava(t, `
+		runtime_resource_overlay {
+			name: "foo_overlay",
+			certificate: "platform",
+			product_specific: true,
+			sdk_version: "current",
+		}
+
+		override_runtime_resource_overlay {
+			name: "bar_overlay",
+			base: "foo_overlay",
+			package_name: "com.android.bar.overlay",
+			target_package_name: "com.android.bar",
+		}
+		`)
+
+	expectedVariants := []struct {
+		moduleName        string
+		variantName       string
+		apkPath           string
+		overrides         []string
+		targetVariant     string
+		packageFlag       string
+		targetPackageFlag string
+	}{
+		{
+			variantName:       "android_common",
+			apkPath:           "/target/product/test_device/product/overlay/foo_overlay.apk",
+			overrides:         nil,
+			targetVariant:     "android_common",
+			packageFlag:       "",
+			targetPackageFlag: "",
+		},
+		{
+			variantName:       "android_common_bar_overlay",
+			apkPath:           "/target/product/test_device/product/overlay/bar_overlay.apk",
+			overrides:         []string{"foo_overlay"},
+			targetVariant:     "android_common_bar",
+			packageFlag:       "com.android.bar.overlay",
+			targetPackageFlag: "com.android.bar",
+		},
+	}
+	for _, expected := range expectedVariants {
+		variant := ctx.ModuleForTests("foo_overlay", expected.variantName)
+
+		// Check the final apk name
+		outputs := variant.AllOutputs()
+		expectedApkPath := buildDir + expected.apkPath
+		found := false
+		for _, o := range outputs {
+			if o == expectedApkPath {
+				found = true
+				break
+			}
+		}
+		if !found {
+			t.Errorf("Can't find %q in output files.\nAll outputs:%v", expectedApkPath, outputs)
+		}
+
+		// Check if the overrides field values are correctly aggregated.
+		mod := variant.Module().(*RuntimeResourceOverlay)
+		if !reflect.DeepEqual(expected.overrides, mod.properties.Overrides) {
+			t.Errorf("Incorrect overrides property value, expected: %q, got: %q",
+				expected.overrides, mod.properties.Overrides)
+		}
+
+		// Check aapt2 flags.
+		res := variant.Output("package-res.apk")
+		aapt2Flags := res.Args["flags"]
+		checkAapt2LinkFlag(t, aapt2Flags, "rename-manifest-package", expected.packageFlag)
+		checkAapt2LinkFlag(t, aapt2Flags, "rename-overlay-target-package", expected.targetPackageFlag)
+	}
+}
+
+func TestRuntimeResourceOverlay_JavaDefaults(t *testing.T) {
+	ctx, config := testJava(t, `
+		java_defaults {
+			name: "rro_defaults",
+			theme: "default_theme",
+			product_specific: true,
+			aaptflags: ["--keep-raw-values"],
+		}
+
+		runtime_resource_overlay {
+			name: "foo_with_defaults",
+			defaults: ["rro_defaults"],
+		}
+
+		runtime_resource_overlay {
+			name: "foo_barebones",
+		}
+		`)
+
+	//
+	// RRO module with defaults
+	//
+	m := ctx.ModuleForTests("foo_with_defaults", "android_common")
+
+	// Check AAPT2 link flags.
+	aapt2Flags := strings.Split(m.Output("package-res.apk").Args["flags"], " ")
+	expectedFlags := []string{"--keep-raw-values", "--no-resource-deduping", "--no-resource-removal"}
+	absentFlags := android.RemoveListFromList(expectedFlags, aapt2Flags)
+	if len(absentFlags) > 0 {
+		t.Errorf("expected values, %q are missing in aapt2 link flags, %q", absentFlags, aapt2Flags)
+	}
+
+	// Check device location.
+	path := android.AndroidMkEntriesForTest(t, config, "", m.Module())[0].EntryMap["LOCAL_MODULE_PATH"]
+	expectedPath := []string{"/tmp/target/product/test_device/product/overlay/default_theme"}
+	if !reflect.DeepEqual(path, expectedPath) {
+		t.Errorf("Unexpected LOCAL_MODULE_PATH value: %q, expected: %q", path, expectedPath)
+	}
+
+	//
+	// RRO module without defaults
+	//
+	m = ctx.ModuleForTests("foo_barebones", "android_common")
+
+	// Check AAPT2 link flags.
+	aapt2Flags = strings.Split(m.Output("package-res.apk").Args["flags"], " ")
+	unexpectedFlags := "--keep-raw-values"
+	if inList(unexpectedFlags, aapt2Flags) {
+		t.Errorf("unexpected value, %q is present in aapt2 link flags, %q", unexpectedFlags, aapt2Flags)
+	}
+
+	// Check device location.
+	path = android.AndroidMkEntriesForTest(t, config, "", m.Module())[0].EntryMap["LOCAL_MODULE_PATH"]
+	expectedPath = []string{"/tmp/target/product/test_device/system/overlay"}
+	if !reflect.DeepEqual(path, expectedPath) {
+		t.Errorf("Unexpected LOCAL_MODULE_PATH value: %v, expected: %v", path, expectedPath)
+	}
+}
diff --git a/java/java.go b/java/java.go
index 38f485e..7f3ba98 100644
--- a/java/java.go
+++ b/java/java.go
@@ -337,10 +337,6 @@
 
 	UncompressDex bool `blueprint:"mutated"`
 	IsSDKLibrary  bool `blueprint:"mutated"`
-
-	// If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
-	// Defaults to false.
-	V4_signature *bool
 }
 
 func (me *CompilerDeviceProperties) EffectiveOptimizeEnabled() bool {
@@ -2754,6 +2750,7 @@
 		&sdkLibraryProperties{},
 		&DexImportProperties{},
 		&android.ApexProperties{},
+		&RuntimeResourceOverlayProperties{},
 	)
 
 	android.InitDefaultsModule(module)
diff --git a/java/sdk_library.go b/java/sdk_library.go
index 51e680b..9e3ad5b 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -83,9 +83,6 @@
 	// module name.
 	moduleSuffix string
 
-	// The suffix to add to the make variable that references the location of the api file.
-	apiFileMakeVariableSuffix string
-
 	// SDK version that the stubs library is built against. Note that this is always
 	// *current. Older stubs library built with a numbered SDK version is created from
 	// the prebuilt jar.
@@ -133,20 +130,18 @@
 		sdkVersion: "current",
 	})
 	apiScopeSystem = initApiScope(&apiScope{
-		name:                      "system",
-		apiFilePrefix:             "system-",
-		moduleSuffix:              sdkSystemApiSuffix,
-		apiFileMakeVariableSuffix: "_SYSTEM",
-		sdkVersion:                "system_current",
-		droidstubsArgs:            []string{"-showAnnotation android.annotation.SystemApi"},
+		name:           "system",
+		apiFilePrefix:  "system-",
+		moduleSuffix:   sdkSystemApiSuffix,
+		sdkVersion:     "system_current",
+		droidstubsArgs: []string{"-showAnnotation android.annotation.SystemApi"},
 	})
 	apiScopeTest = initApiScope(&apiScope{
-		name:                      "test",
-		apiFilePrefix:             "test-",
-		moduleSuffix:              sdkTestApiSuffix,
-		apiFileMakeVariableSuffix: "_TEST",
-		sdkVersion:                "test_current",
-		droidstubsArgs:            []string{"-showAnnotation android.annotation.TestApi"},
+		name:           "test",
+		apiFilePrefix:  "test-",
+		moduleSuffix:   sdkTestApiSuffix,
+		sdkVersion:     "test_current",
+		droidstubsArgs: []string{"-showAnnotation android.annotation.TestApi"},
 	})
 	allApiScopes = apiScopes{
 		apiScopePublic,
@@ -503,17 +498,15 @@
 		}
 	}{}
 
-	sdkDep := decodeSdkDep(mctx, sdkContext(&module.Library))
-	// Use the platform API if standard libraries were requested, otherwise use
-	// no default libraries.
-	sdkVersion := ""
-	if !sdkDep.hasStandardLibs() {
-		sdkVersion = "none"
-	}
+	// The stubs source processing uses the same compile time classpath when extracting the
+	// API from the implementation library as it does when compiling it. i.e. the same
+	// * sdk version
+	// * system_modules
+	// * libs (static_libs/libs)
 
 	props.Name = proptools.StringPtr(module.docsName(apiScope))
 	props.Srcs = append(props.Srcs, module.Library.Module.properties.Srcs...)
-	props.Sdk_version = proptools.StringPtr(sdkVersion)
+	props.Sdk_version = module.Library.Module.deviceProperties.Sdk_version
 	props.System_modules = module.Library.Module.deviceProperties.System_modules
 	props.Installable = proptools.BoolPtr(false)
 	// A droiddoc module has only one Libs property and doesn't distinguish between
diff --git a/rust/builder.go b/rust/builder.go
index 27eeec2..2d5e602 100644
--- a/rust/builder.go
+++ b/rust/builder.go
@@ -108,8 +108,8 @@
 	}
 	// TODO once we have static libraries in the host prebuilt .bp, this
 	// should be unconditionally added.
-	if !ctx.Host() {
-		// If we're on a device build, do not use an implicit sysroot
+	if !(ctx.Host() && ctx.TargetPrimary()) {
+		// If we're not targeting the host primary arch, do not use an implicit sysroot
 		rustcFlags = append(rustcFlags, "--sysroot=/dev/null")
 	}
 	// Collect linker flags
diff --git a/rust/compiler.go b/rust/compiler.go
index 81b258c..7499776 100644
--- a/rust/compiler.go
+++ b/rust/compiler.go
@@ -183,8 +183,8 @@
 
 	if !Bool(compiler.Properties.No_stdlibs) {
 		for _, stdlib := range config.Stdlibs {
-			// If we're building for host, use the compiler's stdlibs
-			if ctx.Host() {
+			// If we're building for the primary host target, use the compiler's stdlibs
+			if ctx.Host() && ctx.TargetPrimary() {
 				stdlib = stdlib + "_" + ctx.toolchain().RustTriple()
 			}
 
@@ -192,9 +192,12 @@
 			// static linking is the default, if one of our static
 			// dependencies uses a dynamic library, we need to dynamically
 			// link the stdlib as well.
-			if (len(deps.Dylibs) > 0) || (!ctx.Host()) {
+			if (len(deps.Dylibs) > 0) || ctx.Device() {
 				// Dynamically linked stdlib
 				deps.Dylibs = append(deps.Dylibs, stdlib)
+			} else if ctx.Host() && !ctx.TargetPrimary() {
+				// Otherwise use the static in-tree stdlib for host secondary arch
+				deps.Rlibs = append(deps.Rlibs, stdlib+".static")
 			}
 		}
 	}
diff --git a/rust/compiler_test.go b/rust/compiler_test.go
index bbf9f8d..bcde757 100644
--- a/rust/compiler_test.go
+++ b/rust/compiler_test.go
@@ -74,3 +74,33 @@
 		  host_supported: true,
 		}`)
 }
+
+func TestInstallDir(t *testing.T) {
+	ctx := testRust(t, `
+		rust_library_dylib {
+			name: "libfoo",
+			srcs: ["foo.rs"],
+			crate_name: "foo",
+		}
+		rust_binary {
+			name: "fizzbuzz",
+			srcs: ["foo.rs"],
+		}`)
+
+	install_path_lib64 := ctx.ModuleForTests("libfoo",
+		"android_arm64_armv8-a_dylib").Module().(*Module).compiler.(*libraryDecorator).path.String()
+	install_path_lib32 := ctx.ModuleForTests("libfoo",
+		"android_arm_armv7-a-neon_dylib").Module().(*Module).compiler.(*libraryDecorator).path.String()
+	install_path_bin := ctx.ModuleForTests("fizzbuzz",
+		"android_arm64_armv8-a").Module().(*Module).compiler.(*binaryDecorator).path.String()
+
+	if !strings.HasSuffix(install_path_lib64, "system/lib64/libfoo.dylib.so") {
+		t.Fatalf("unexpected install path for 64-bit library: %#v", install_path_lib64)
+	}
+	if !strings.HasSuffix(install_path_lib32, "system/lib/libfoo.dylib.so") {
+		t.Fatalf("unexpected install path for 32-bit library: %#v", install_path_lib32)
+	}
+	if !strings.HasSuffix(install_path_bin, "system/bin/fizzbuzz") {
+		t.Fatalf("unexpected install path for binary: %#v", install_path_bin)
+	}
+}
diff --git a/rust/config/arm_device.go b/rust/config/arm_device.go
index aedb42b..ac2580b 100644
--- a/rust/config/arm_device.go
+++ b/rust/config/arm_device.go
@@ -50,7 +50,7 @@
 }
 
 type toolchainArm struct {
-	toolchain64Bit
+	toolchain32Bit
 	toolchainRustFlags string
 }
 
diff --git a/rust/library.go b/rust/library.go
index bf863bb..87e816d 100644
--- a/rust/library.go
+++ b/rust/library.go
@@ -281,7 +281,7 @@
 }
 
 func NewRustLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
-	module := newModule(hod, android.MultilibFirst)
+	module := newModule(hod, android.MultilibBoth)
 
 	library := &libraryDecorator{
 		MutatedProperties: LibraryMutatedProperties{
diff --git a/rust/rust_test.go b/rust/rust_test.go
index 02b190f..32eddc1 100644
--- a/rust/rust_test.go
+++ b/rust/rust_test.go
@@ -240,7 +240,7 @@
 		rust_binary {
 			name: "fizz-buzz",
 			srcs: ["foo.rs"],
-                        no_stdlibs: true,
+			no_stdlibs: true,
 		}`)
 	module := ctx.ModuleForTests("fizz-buzz", "android_arm64_armv8-a").Module().(*Module)
 
@@ -248,3 +248,16 @@
 		t.Errorf("no_stdlibs did not suppress dependency on libstd")
 	}
 }
+
+// Test that libraries provide both 32-bit and 64-bit variants.
+func TestMultilib(t *testing.T) {
+	ctx := testRust(t, `
+		rust_library_rlib {
+			name: "libfoo",
+			srcs: ["foo.rs"],
+			crate_name: "foo",
+		}`)
+
+	_ = ctx.ModuleForTests("libfoo", "android_arm64_armv8-a_rlib")
+	_ = ctx.ModuleForTests("libfoo", "android_arm_armv7-a-neon_rlib")
+}
diff --git a/rust/testing.go b/rust/testing.go
index c3a4625..aad4ffe 100644
--- a/rust/testing.go
+++ b/rust/testing.go
@@ -46,24 +46,29 @@
 			crate_name: "std",
 			srcs: ["foo.rs"],
 			no_stdlibs: true,
+			host_supported: true,
 		}
 		rust_library_rlib {
 			name: "libstd.static",
 			crate_name: "std",
 			srcs: ["foo.rs"],
 			no_stdlibs: true,
+			host_supported: true,
 		}
 		rust_library_dylib {
 			name: "libtest",
 			crate_name: "test",
 			srcs: ["foo.rs"],
 			no_stdlibs: true,
+			host_supported: true,
+
 		}
 		rust_library_rlib {
 			name: "libtest.static",
 			crate_name: "test",
 			srcs: ["foo.rs"],
 			no_stdlibs: true,
+			host_supported: true,
 		}
 
 ` + cc.GatherRequiredDepsForTest(android.NoOsType)
diff --git a/scripts/build-aml-prebuilts.sh b/scripts/build-aml-prebuilts.sh
index 7408349..eef6149 100755
--- a/scripts/build-aml-prebuilts.sh
+++ b/scripts/build-aml-prebuilts.sh
@@ -51,13 +51,11 @@
 SOONG_VARS=${SOONG_OUT}/soong.variables
 
 # We enable bionic linux builds as ART also needs prebuilts for it.
-# Enabling bionic linux requires setting allow_missing_dependencies.
 cat > ${SOONG_VARS}.new << EOF
 {
     "Platform_sdk_version": ${PLATFORM_SDK_VERSION},
     "Platform_sdk_codename": "${PLATFORM_VERSION}",
     "Platform_version_active_codenames": ${PLATFORM_VERSION_ALL_CODENAMES},
-    "Allow_missing_dependencies": true,
 
     "DeviceName": "generic_arm64",
     "HostArch": "x86_64",
@@ -78,4 +76,7 @@
   mv ${SOONG_VARS}.new ${SOONG_VARS}
 fi
 
-m --skip-make "$@"
+# We use force building LLVM components flag (even though we actually don't
+# compile them) because we don't have bionic host prebuilts
+# for them.
+FORCE_BUILD_LLVM_COMPONENTS=true m --skip-make "$@"
diff --git a/sdk/java_sdk_test.go b/sdk/java_sdk_test.go
index c0ad35c..788d016 100644
--- a/sdk/java_sdk_test.go
+++ b/sdk/java_sdk_test.go
@@ -46,13 +46,13 @@
 java_import {
 	name: "core.platform.api.stubs",
 }
-java_sdk_library_import {
+java_import {
 	name: "android_stubs_current",
 }
-java_sdk_library_import {
+java_import {
 	name: "android_system_stubs_current",
 }
-java_sdk_library_import {
+java_import {
 	name: "android_test_stubs_current",
 }
 java_import {
diff --git a/ui/build/config.go b/ui/build/config.go
index 437e441..7fcc471 100644
--- a/ui/build/config.go
+++ b/ui/build/config.go
@@ -517,6 +517,9 @@
 				ctx.Fatalln("Unknown option:", arg)
 			}
 		} else if k, v, ok := decodeKeyValue(arg); ok && len(k) > 0 {
+			if k == "OUT_DIR" {
+				ctx.Fatalln("OUT_DIR may only be set in the environment, not as a command line option.")
+			}
 			c.environ.Set(k, v)
 		} else if arg == "dist" {
 			c.dist = true