Merge "Clean up android/module.go"
diff --git a/android/allowlists/allowlists.go b/android/allowlists/allowlists.go
index 79d4910..b668042 100644
--- a/android/allowlists/allowlists.go
+++ b/android/allowlists/allowlists.go
@@ -146,6 +146,7 @@
 		"external/scudo":                                         Bp2BuildDefaultTrueRecursively,
 		"external/selinux/libselinux":                            Bp2BuildDefaultTrueRecursively,
 		"external/selinux/libsepol":                              Bp2BuildDefaultTrueRecursively,
+		"external/toybox":                                        Bp2BuildDefaultTrueRecursively,
 		"external/zlib":                                          Bp2BuildDefaultTrueRecursively,
 		"external/zopfli":                                        Bp2BuildDefaultTrueRecursively,
 		"external/zstd":                                          Bp2BuildDefaultTrueRecursively,
@@ -335,6 +336,13 @@
 		"server_configurable_flags",
 		"tensorflow_headers",
 
+		// fastboot
+		"bootimg_headers",
+		"fastboot",
+		"libfastboot",
+		"liblp",
+		"libstorage_literals_headers",
+
 		//external/avb
 		"avbtool",
 		"libavb",
@@ -485,6 +493,9 @@
 		// b/215723302; awaiting tz{data,_version} to then rename targets conflicting with srcs
 		"tzdata",
 		"tz_version",
+
+		// '//bionic/libc:libc_bp2build_cc_library_static' is duplicated in the 'deps' attribute of rule
+		"toybox-static",
 	}
 
 	Bp2buildCcLibraryStaticOnlyList = []string{}
diff --git a/android/config.go b/android/config.go
index 8c01bee..84c17de 100644
--- a/android/config.go
+++ b/android/config.go
@@ -18,6 +18,7 @@
 // product variables necessary for soong_build's operation.
 
 import (
+	"bytes"
 	"encoding/json"
 	"errors"
 	"fmt"
@@ -305,6 +306,9 @@
 	if err != nil {
 		return fmt.Errorf("cannot marshal config data: %s", err.Error())
 	}
+	// The backslashes need to be escaped because this text is going to be put
+	// inside a Starlark string literal.
+	configJson = bytes.ReplaceAll(configJson, []byte("\\"), []byte("\\\\"))
 
 	bzl := []string{
 		bazel.GeneratedBazelFileWarning,
@@ -317,11 +321,11 @@
 arch_variant_product_var_constraints = _arch_variant_product_var_constraints
 `,
 	}
-	err = ioutil.WriteFile(filepath.Join(dir, "product_variables.bzl"), []byte(strings.Join(bzl, "\n")), 0644)
+	err = os.WriteFile(filepath.Join(dir, "product_variables.bzl"), []byte(strings.Join(bzl, "\n")), 0644)
 	if err != nil {
 		return fmt.Errorf("Could not write .bzl config file %s", err)
 	}
-	err = ioutil.WriteFile(filepath.Join(dir, "BUILD"), []byte(bazel.GeneratedBazelFileWarning), 0644)
+	err = os.WriteFile(filepath.Join(dir, "BUILD"), []byte(bazel.GeneratedBazelFileWarning), 0644)
 	if err != nil {
 		return fmt.Errorf("Could not write BUILD config file %s", err)
 	}
diff --git a/apex/apex.go b/apex/apex.go
index 09a5784..e9b0815 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -2701,7 +2701,7 @@
 
 var _ android.ModuleWithMinSdkVersionCheck = (*apexBundle)(nil)
 
-// Entures that min_sdk_version of the included modules are equal or less than the min_sdk_version
+// Ensures that min_sdk_version of the included modules are equal or less than the min_sdk_version
 // of this apexBundle.
 func (a *apexBundle) CheckMinSdkVersion(ctx android.ModuleContext) {
 	if a.testApex || a.vndkApex {
diff --git a/java/android_manifest.go b/java/android_manifest.go
index 83cb171..522b664 100644
--- a/java/android_manifest.go
+++ b/java/android_manifest.go
@@ -45,7 +45,11 @@
 // This enables release builds (that run with TARGET_BUILD_APPS=[val...]) to target APIs that have not yet been finalized as part of an SDK
 func targetSdkVersionForManifestFixer(ctx android.ModuleContext, sdkContext android.SdkContext) string {
 	targetSdkVersionSpec := sdkContext.TargetSdkVersion(ctx)
-	if ctx.Config().UnbundledBuildApps() && targetSdkVersionSpec.ApiLevel.IsPreview() {
+	// Return 10000 for modules targeting "current" if either
+	// 1. The module is built in unbundled mode (TARGET_BUILD_APPS not empty)
+	// 2. The module is run as part of MTS, and should be testable on stable branches
+	// TODO(b/240294501): Determine the rules for handling test apexes
+	if targetSdkVersionSpec.ApiLevel.IsPreview() && (ctx.Config().UnbundledBuildApps() || includedInMts(ctx.Module())) {
 		return strconv.Itoa(android.FutureApiLevel.FinalOrFutureInt())
 	}
 	targetSdkVersion, err := targetSdkVersionSpec.EffectiveVersionString(ctx)
@@ -55,6 +59,15 @@
 	return targetSdkVersion
 }
 
+// Helper function that casts android.Module to java.androidTestApp
+// If this type conversion is possible, it queries whether the test app is included in an MTS suite
+func includedInMts(module android.Module) bool {
+	if test, ok := module.(androidTestApp); ok {
+		return test.includedInTestSuite("mts")
+	}
+	return false
+}
+
 type ManifestFixerParams struct {
 	SdkContext             android.SdkContext
 	ClassLoaderContexts    dexpreopt.ClassLoaderContextMap
diff --git a/java/app.go b/java/app.go
index 5185959..c369978 100755
--- a/java/app.go
+++ b/java/app.go
@@ -962,6 +962,18 @@
 	return true
 }
 
+type androidTestApp interface {
+	includedInTestSuite(searchPrefix string) bool
+}
+
+func (a *AndroidTest) includedInTestSuite(searchPrefix string) bool {
+	return android.PrefixInList(a.testProperties.Test_suites, searchPrefix)
+}
+
+func (a *AndroidTestHelperApp) includedInTestSuite(searchPrefix string) bool {
+	return android.PrefixInList(a.appTestHelperAppProperties.Test_suites, searchPrefix)
+}
+
 func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	var configs []tradefed.Config
 	if a.appTestProperties.Instrumentation_target_package != nil {
diff --git a/java/app_test.go b/java/app_test.go
index bb44803..0f973ba 100644
--- a/java/app_test.go
+++ b/java/app_test.go
@@ -3160,3 +3160,65 @@
 		})
 	}
 }
+
+func TestTargetSdkVersionMtsTests(t *testing.T) {
+	platformSdkCodename := "Tiramisu"
+	android_test := "android_test"
+	android_test_helper_app := "android_test_helper_app"
+	bpTemplate := `
+	%v {
+		name: "mytest",
+		target_sdk_version: "%v",
+		test_suites: ["othersuite", "%v"],
+	}
+	`
+	testCases := []struct {
+		desc                     string
+		moduleType               string
+		targetSdkVersionInBp     string
+		targetSdkVersionExpected string
+		testSuites               string
+	}{
+		{
+			desc:                     "Non-MTS android_test_apps targeting current should not be upgraded to 10000",
+			moduleType:               android_test,
+			targetSdkVersionInBp:     "current",
+			targetSdkVersionExpected: platformSdkCodename,
+			testSuites:               "non-mts-suite",
+		},
+		{
+			desc:                     "MTS android_test_apps targeting released sdks should not be upgraded to 10000",
+			moduleType:               android_test,
+			targetSdkVersionInBp:     "29",
+			targetSdkVersionExpected: "29",
+			testSuites:               "mts-suite",
+		},
+		{
+			desc:                     "MTS android_test_apps targeting current should be upgraded to 10000",
+			moduleType:               android_test,
+			targetSdkVersionInBp:     "current",
+			targetSdkVersionExpected: "10000",
+			testSuites:               "mts-suite",
+		},
+		{
+			desc:                     "MTS android_test_helper_apps targeting current should be upgraded to 10000",
+			moduleType:               android_test_helper_app,
+			targetSdkVersionInBp:     "current",
+			targetSdkVersionExpected: "10000",
+			testSuites:               "mts-suite",
+		},
+	}
+	fixture := android.GroupFixturePreparers(
+		prepareForJavaTest,
+		android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
+			variables.Platform_sdk_codename = &platformSdkCodename
+			variables.Platform_version_active_codenames = []string{platformSdkCodename}
+		}),
+	)
+	for _, testCase := range testCases {
+		result := fixture.RunTestWithBp(t, fmt.Sprintf(bpTemplate, testCase.moduleType, testCase.targetSdkVersionInBp, testCase.testSuites))
+		mytest := result.ModuleForTests("mytest", "android_common")
+		manifestFixerArgs := mytest.Output("manifest_fixer/AndroidManifest.xml").Args["args"]
+		android.AssertStringDoesContain(t, testCase.desc, manifestFixerArgs, "--targetSdkVersion  "+testCase.targetSdkVersionExpected)
+	}
+}
diff --git a/java/dex.go b/java/dex.go
index c943938..a44d792 100644
--- a/java/dex.go
+++ b/java/dex.go
@@ -42,6 +42,9 @@
 		// True if the module containing this has it set by default.
 		EnabledByDefault bool `blueprint:"mutated"`
 
+		// Whether to continue building even if warnings are emitted.  Defaults to true.
+		Ignore_warnings *bool
+
 		// If true, runs R8 in Proguard compatibility mode (default).
 		// Otherwise, runs R8 in full mode.
 		Proguard_compatibility *bool
@@ -293,7 +296,10 @@
 	}
 
 	// TODO(b/180878971): missing classes should be added to the relevant builds.
-	r8Flags = append(r8Flags, "-ignorewarnings")
+	// TODO(b/229727645): do not use true as default for Android platform builds.
+	if proptools.BoolDefault(opt.Ignore_warnings, true) {
+		r8Flags = append(r8Flags, "-ignorewarnings")
+	}
 
 	return r8Flags, r8Deps
 }
diff --git a/java/dex_test.go b/java/dex_test.go
index fbdccb6..a3e2ded 100644
--- a/java/dex_test.go
+++ b/java/dex_test.go
@@ -59,6 +59,36 @@
 		appR8.Args["r8Flags"], libHeader.String())
 	android.AssertStringDoesNotContain(t, "expected no  static_lib header jar in app javac classpath",
 		appR8.Args["r8Flags"], staticLibHeader.String())
+	android.AssertStringDoesContain(t, "expected -ignorewarnings in app r8 flags",
+		appR8.Args["r8Flags"], "-ignorewarnings")
+}
+
+func TestR8Flags(t *testing.T) {
+	result := PrepareForTestWithJavaDefaultModulesWithoutFakeDex2oatd.RunTestWithBp(t, `
+		android_app {
+			name: "app",
+			srcs: ["foo.java"],
+			platform_apis: true,
+			optimize: {
+				shrink: false,
+				optimize: false,
+				obfuscate: false,
+				ignore_warnings: false,
+			},
+		}
+	`)
+
+	app := result.ModuleForTests("app", "android_common")
+	appR8 := app.Rule("r8")
+	android.AssertStringDoesContain(t, "expected -dontshrink in app r8 flags",
+		appR8.Args["r8Flags"], "-dontshrink")
+	android.AssertStringDoesContain(t, "expected -dontoptimize in app r8 flags",
+		appR8.Args["r8Flags"], "-dontoptimize")
+	android.AssertStringDoesContain(t, "expected -dontobfuscate in app r8 flags",
+		appR8.Args["r8Flags"], "-dontobfuscate")
+	android.AssertStringDoesNotContain(t, "expected no -ignorewarnings in app r8 flags",
+		appR8.Args["r8Flags"], "-ignorewarnings")
+
 }
 
 func TestD8(t *testing.T) {