Merge "Remove patricearruda from OWNERS."
diff --git a/android/apex.go b/android/apex.go
index f6eca86..47d14cc 100644
--- a/android/apex.go
+++ b/android/apex.go
@@ -253,6 +253,12 @@
 	CopyDirectlyInAnyApex()
 }
 
+// Interface that identifies dependencies to skip Apex dependency check
+type SkipApexAllowedDependenciesCheck interface {
+	// Returns true to skip the Apex dependency check, which limits the allowed dependency in build.
+	SkipApexAllowedDependenciesCheck() bool
+}
+
 // ApexModuleBase provides the default implementation for the ApexModule interface. APEX-aware
 // modules are expected to include this struct and call InitApexModule().
 type ApexModuleBase struct {
diff --git a/android/bazel_handler.go b/android/bazel_handler.go
index 357b99f..a00a54d 100644
--- a/android/bazel_handler.go
+++ b/android/bazel_handler.go
@@ -515,6 +515,6 @@
 		// build statement have later timestamps than the outputs.
 		rule.Restat()
 
-		rule.Build(fmt.Sprintf("bazel %s", index), buildStatement.Mnemonic)
+		rule.Build(fmt.Sprintf("bazel %d", index), buildStatement.Mnemonic)
 	}
 }
diff --git a/android/config.go b/android/config.go
index 89467d8..58372ec 100644
--- a/android/config.go
+++ b/android/config.go
@@ -1272,6 +1272,10 @@
 	return Bool(c.productVariables.Flatten_apex)
 }
 
+func (c *config) ForceApexSymlinkOptimization() bool {
+	return Bool(c.productVariables.ForceApexSymlinkOptimization)
+}
+
 func (c *config) CompressedApex() bool {
 	return Bool(c.productVariables.CompressedApex)
 }
@@ -1360,6 +1364,18 @@
 	return Bool(c.config.productVariables.BoardMoveRecoveryResourcesToVendorBoot)
 }
 
+func (c *deviceConfig) PlatformSepolicyVersion() string {
+	return String(c.config.productVariables.PlatformSepolicyVersion)
+}
+
+func (c *deviceConfig) BoardSepolicyVers() string {
+	return String(c.config.productVariables.BoardSepolicyVers)
+}
+
+func (c *deviceConfig) BoardReqdMaskPolicy() []string {
+	return c.config.productVariables.BoardReqdMaskPolicy
+}
+
 // The ConfiguredJarList struct provides methods for handling a list of (apex, jar) pairs.
 // Such lists are used in the build system for things like bootclasspath jars or system server jars.
 // The apex part is either an apex name, or a special names "platform" or "system_ext". Jar is a
diff --git a/android/soongconfig/modules.go b/android/soongconfig/modules.go
index 5a6917e..9f3f804 100644
--- a/android/soongconfig/modules.go
+++ b/android/soongconfig/modules.go
@@ -541,12 +541,15 @@
 }
 
 func (s *valueVariable) PropertiesToApply(config SoongConfig, values reflect.Value) (interface{}, error) {
-	if !config.IsSet(s.variable) {
+	if !config.IsSet(s.variable) || !values.IsValid() {
 		return nil, nil
 	}
 	configValue := config.String(s.variable)
 
 	propStruct := values.Elem().Elem()
+	if !propStruct.IsValid() {
+		return nil, nil
+	}
 	for i := 0; i < propStruct.NumField(); i++ {
 		field := propStruct.Field(i)
 		kind := field.Kind()
diff --git a/android/variable.go b/android/variable.go
index 753ddd7..1455fc2 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -311,18 +311,23 @@
 
 	BoardVendorSepolicyDirs      []string `json:",omitempty"`
 	BoardOdmSepolicyDirs         []string `json:",omitempty"`
+	BoardReqdMaskPolicy          []string `json:",omitempty"`
 	SystemExtPublicSepolicyDirs  []string `json:",omitempty"`
 	SystemExtPrivateSepolicyDirs []string `json:",omitempty"`
 	BoardSepolicyM4Defs          []string `json:",omitempty"`
 
+	BoardSepolicyVers       *string `json:",omitempty"`
+	PlatformSepolicyVersion *string `json:",omitempty"`
+
 	VendorVars map[string]map[string]string `json:",omitempty"`
 
 	Ndk_abis               *bool `json:",omitempty"`
 	Exclude_draft_ndk_apis *bool `json:",omitempty"`
 
-	Flatten_apex   *bool `json:",omitempty"`
-	CompressedApex *bool `json:",omitempty"`
-	Aml_abis       *bool `json:",omitempty"`
+	Flatten_apex                 *bool `json:",omitempty"`
+	ForceApexSymlinkOptimization *bool `json:",omitempty"`
+	CompressedApex               *bool `json:",omitempty"`
+	Aml_abis                     *bool `json:",omitempty"`
 
 	DexpreoptGlobalConfig *string `json:",omitempty"`
 
diff --git a/apex/allowed_deps.txt b/apex/allowed_deps.txt
index c5f2bf8..69bf64f 100644
--- a/apex/allowed_deps.txt
+++ b/apex/allowed_deps.txt
@@ -289,6 +289,7 @@
 libcutils(minSdkVersion:29)
 libcutils_headers(minSdkVersion:29)
 libcutils_sockets(minSdkVersion:29)
+libderive_sdk(minSdkVersion:30)
 libdiagnose_usb(minSdkVersion:(no version))
 libdl(minSdkVersion:(no version))
 libdmabufheap(minSdkVersion:29)
diff --git a/apex/apex.go b/apex/apex.go
index 9fb616d..2182069 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -1913,9 +1913,11 @@
 		a.linkToSystemLib = false
 	}
 
+	forced := ctx.Config().ForceApexSymlinkOptimization()
+
 	// We don't need the optimization for updatable APEXes, as it might give false signal
-	// to the system health when the APEXes are still bundled (b/149805758)
-	if a.Updatable() && a.properties.ApexType == imageApex {
+	// to the system health when the APEXes are still bundled (b/149805758).
+	if !forced && a.Updatable() && a.properties.ApexType == imageApex {
 		a.linkToSystemLib = false
 	}
 
diff --git a/apex/builder.go b/apex/builder.go
index 0e4ba1d..106302b 100644
--- a/apex/builder.go
+++ b/apex/builder.go
@@ -902,6 +902,12 @@
 			return !externalDep
 		}
 
+		depTag := ctx.OtherModuleDependencyTag(to)
+		if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
+			// Check to see if dependency been marked to skip the dependency check
+			return !externalDep
+		}
+
 		if info, exists := depInfos[to.Name()]; exists {
 			if !android.InList(from.Name(), info.From) {
 				info.From = append(info.From, from.Name())
diff --git a/cc/cc.go b/cc/cc.go
index ac6a258..ae11aa1 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -609,6 +609,9 @@
 
 	makeSuffix string
 
+	// Whether or not this dependency should skip the apex dependency check
+	skipApexAllowedDependenciesCheck bool
+
 	// Whether or not this dependency has to be followed for the apex variants
 	excludeInApex bool
 }
@@ -3093,6 +3096,12 @@
 		// We don't track beyond LLNDK or from an implementation library to its stubs.
 		return false
 	}
+	if depTag == staticVariantTag {
+		// This dependency is for optimization (reuse *.o from the static lib). It doesn't
+		// actually mean that the static lib (and its dependencies) are copied into the
+		// APEX.
+		return false
+	}
 	return true
 }
 
diff --git a/cc/sanitize.go b/cc/sanitize.go
index d7df5dc..0e2d01a 100644
--- a/cc/sanitize.go
+++ b/cc/sanitize.go
@@ -204,6 +204,13 @@
 	Properties SanitizeProperties
 }
 
+// Mark this tag with a check to see if apex dependency check should be skipped
+func (t libraryDependencyTag) SkipApexAllowedDependenciesCheck() bool {
+	return t.skipApexAllowedDependenciesCheck
+}
+
+var _ android.SkipApexAllowedDependenciesCheck = (*libraryDependencyTag)(nil)
+
 func init() {
 	android.RegisterMakeVarsProvider(pctx, cfiMakeVarsProvider)
 	android.RegisterMakeVarsProvider(pctx, hwasanMakeVarsProvider)
@@ -1038,9 +1045,18 @@
 						runtimeLibrary = lib
 					}
 				}
-
+				// Skip apex dependency check for sharedLibraryDependency
+				// when sanitizer diags are enabled. Skipping the check will allow
+				// building with diag libraries without having to list the
+				// dependency in Apex's allowed_deps file.
+				diagEnabled := len(diagSanitizers) > 0
 				// dynamic executable and shared libs get shared runtime libs
-				depTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: earlyLibraryDependency}
+				depTag := libraryDependencyTag{
+					Kind:  sharedLibraryDependency,
+					Order: earlyLibraryDependency,
+
+					skipApexAllowedDependenciesCheck: diagEnabled,
+				}
 				variations := append(mctx.Target().Variations(),
 					blueprint.Variation{Mutator: "link", Variation: "shared"})
 				if c.Device() {
diff --git a/java/app.go b/java/app.go
index 249313c..574472c 100755
--- a/java/app.go
+++ b/java/app.go
@@ -905,6 +905,8 @@
 		&module.appProperties,
 		&module.overridableAppProperties)
 
+	module.usesLibrary.enforce = true
+
 	android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
 	android.InitDefaultableModule(module)
 	android.InitOverridableModule(module, &module.appProperties.Overrides)
@@ -1175,6 +1177,9 @@
 // with knowledge of their shared libraries.
 type usesLibrary struct {
 	usesLibraryProperties UsesLibraryProperties
+
+	// Whether to enforce verify_uses_library check.
+	enforce bool
 }
 
 func (u *usesLibrary) addLib(lib string, optional bool) {
@@ -1241,7 +1246,7 @@
 func (u *usesLibrary) enforceUsesLibraries() bool {
 	defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
 		len(u.usesLibraryProperties.Optional_uses_libs) > 0
-	return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, defaultEnforceUsesLibs)
+	return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, u.enforce || defaultEnforceUsesLibs)
 }
 
 // Freeze the value of `enforce_uses_libs` based on the current values of `uses_libs` and `optional_uses_libs`.
diff --git a/java/app_import.go b/java/app_import.go
index 2054785..df940f1 100644
--- a/java/app_import.go
+++ b/java/app_import.go
@@ -430,6 +430,8 @@
 	android.InitDefaultableModule(module)
 	android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
 
+	module.usesLibrary.enforce = true
+
 	return module
 }
 
diff --git a/java/app_import_test.go b/java/app_import_test.go
index 3b55c81..344d23b 100644
--- a/java/app_import_test.go
+++ b/java/app_import_test.go
@@ -182,31 +182,31 @@
 			name:                "no preferred",
 			aaptPreferredConfig: nil,
 			aaptPrebuiltDPI:     []string{},
-			expected:            "prebuilts/apk/app.apk",
+			expected:            "verify_uses_libraries/apk/app.apk",
 		},
 		{
 			name:                "AAPTPreferredConfig matches",
 			aaptPreferredConfig: proptools.StringPtr("xhdpi"),
 			aaptPrebuiltDPI:     []string{"xxhdpi", "ldpi"},
-			expected:            "prebuilts/apk/app_xhdpi.apk",
+			expected:            "verify_uses_libraries/apk/app_xhdpi.apk",
 		},
 		{
 			name:                "AAPTPrebuiltDPI matches",
 			aaptPreferredConfig: proptools.StringPtr("mdpi"),
 			aaptPrebuiltDPI:     []string{"xxhdpi", "xhdpi"},
-			expected:            "prebuilts/apk/app_xxhdpi.apk",
+			expected:            "verify_uses_libraries/apk/app_xxhdpi.apk",
 		},
 		{
 			name:                "non-first AAPTPrebuiltDPI matches",
 			aaptPreferredConfig: proptools.StringPtr("mdpi"),
 			aaptPrebuiltDPI:     []string{"ldpi", "xhdpi"},
-			expected:            "prebuilts/apk/app_xhdpi.apk",
+			expected:            "verify_uses_libraries/apk/app_xhdpi.apk",
 		},
 		{
 			name:                "no matches",
 			aaptPreferredConfig: proptools.StringPtr("mdpi"),
 			aaptPrebuiltDPI:     []string{"ldpi", "xxxhdpi"},
-			expected:            "prebuilts/apk/app.apk",
+			expected:            "verify_uses_libraries/apk/app.apk",
 		},
 	}
 
@@ -225,7 +225,7 @@
 		if len(matches) != 2 {
 			t.Errorf("failed to extract the src apk path from %q", jniRuleCommand)
 		}
-		if test.expected != matches[1] {
+		if strings.HasSuffix(matches[1], test.expected) {
 			t.Errorf("wrong src apk, expected: %q got: %q", test.expected, matches[1])
 		}
 	}
@@ -302,7 +302,7 @@
 					},
 				}
 			`,
-			expected: "prebuilts/apk/app_arm64.apk",
+			expected: "verify_uses_libraries/apk/app_arm64.apk",
 		},
 		{
 			name: "no matching arch",
@@ -321,7 +321,7 @@
 					},
 				}
 			`,
-			expected: "prebuilts/apk/app.apk",
+			expected: "verify_uses_libraries/apk/app.apk",
 		},
 		{
 			name: "no matching arch without default",
@@ -359,7 +359,7 @@
 		if len(matches) != 2 {
 			t.Errorf("failed to extract the src apk path from %q", jniRuleCommand)
 		}
-		if test.expected != matches[1] {
+		if strings.HasSuffix(matches[1], test.expected) {
 			t.Errorf("wrong src apk, expected: %q got: %q", test.expected, matches[1])
 		}
 	}
diff --git a/java/droiddoc.go b/java/droiddoc.go
index cbca12a..c74009e 100644
--- a/java/droiddoc.go
+++ b/java/droiddoc.go
@@ -192,24 +192,6 @@
 
 		Current ApiToCheck
 
-		// The java_sdk_library module generates references to modules (i.e. filegroups)
-		// from which information about the latest API version can be obtained. As those
-		// modules may not exist (e.g. because a previous version has not been released) it
-		// sets ignore_missing_latest_api=true on the droidstubs modules it creates so
-		// that droidstubs can ignore those references if the modules do not yet exist.
-		//
-		// If true then this will ignore module references for modules that do not exist
-		// in properties that supply the previous version of the API.
-		//
-		// There are two sets of those:
-		// * Api_file, Removed_api_file in check_api.last_released
-		// * New_since in check_api.api_lint.new_since
-		//
-		// The first two must be set as a pair, so either they should both exist or neither
-		// should exist - in which case when this property is true they are ignored. If one
-		// exists and the other does not then it is an error.
-		Ignore_missing_latest_api *bool `blueprint:"mutated"`
-
 		Api_lint struct {
 			Enabled *bool
 
@@ -304,25 +286,6 @@
 	return false
 }
 
-func ignoreMissingModules(ctx android.BottomUpMutatorContext, apiToCheck *ApiToCheck) {
-	apiFile := String(apiToCheck.Api_file)
-	removedApiFile := String(apiToCheck.Removed_api_file)
-
-	apiModule := android.SrcIsModule(apiFile)
-	removedApiModule := android.SrcIsModule(removedApiFile)
-
-	if apiModule == "" || removedApiModule == "" {
-		return
-	}
-
-	if ctx.OtherModuleExists(apiModule) || ctx.OtherModuleExists(removedApiModule) {
-		return
-	}
-
-	apiToCheck.Api_file = nil
-	apiToCheck.Removed_api_file = nil
-}
-
 // Used by xsd_config
 type ApiFilePath interface {
 	ApiFilePath() android.Path
@@ -1079,20 +1042,6 @@
 func (d *Droidstubs) DepsMutator(ctx android.BottomUpMutatorContext) {
 	d.Javadoc.addDeps(ctx)
 
-	// If requested clear any properties that provide information about the latest version
-	// of an API and which reference non-existent modules.
-	if Bool(d.properties.Check_api.Ignore_missing_latest_api) {
-		ignoreMissingModules(ctx, &d.properties.Check_api.Last_released)
-
-		// If the new_since references a module, e.g. :module-latest-api and the module
-		// does not exist then clear it.
-		newSinceSrc := d.properties.Check_api.Api_lint.New_since
-		newSinceSrcModule := android.SrcIsModule(proptools.String(newSinceSrc))
-		if newSinceSrcModule != "" && !ctx.OtherModuleExists(newSinceSrcModule) {
-			d.properties.Check_api.Api_lint.New_since = nil
-		}
-	}
-
 	if len(d.properties.Merge_annotations_dirs) != 0 {
 		for _, mergeAnnotationsDir := range d.properties.Merge_annotations_dirs {
 			ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
diff --git a/java/sdk_library.go b/java/sdk_library.go
index f279b95..1a655a6 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -1271,10 +1271,10 @@
 		Merge_annotations_dirs           []string
 		Merge_inclusion_annotations_dirs []string
 		Generate_stubs                   *bool
+		Previous_api                     *string
 		Check_api                        struct {
-			Current                   ApiToCheck
-			Last_released             ApiToCheck
-			Ignore_missing_latest_api *bool
+			Current       ApiToCheck
+			Last_released ApiToCheck
 
 			Api_lint struct {
 				Enabled       *bool
@@ -1357,12 +1357,11 @@
 	// check against the not-yet-release API
 	props.Check_api.Current.Api_file = proptools.StringPtr(currentApiFileName)
 	props.Check_api.Current.Removed_api_file = proptools.StringPtr(removedApiFileName)
-	// TODO(b/176092454): change true to module.sdkLibraryProperties.Unsafe_ignore_missing_latest_api
-	props.Check_api.Ignore_missing_latest_api = proptools.BoolPtr(true)
 
-	if !apiScope.unstable {
+	if !(apiScope.unstable || module.sdkLibraryProperties.Unsafe_ignore_missing_latest_api) {
 		// check against the latest released API
 		latestApiFilegroupName := proptools.StringPtr(module.latestApiFilegroupName(apiScope))
+		props.Previous_api = latestApiFilegroupName
 		props.Check_api.Last_released.Api_file = latestApiFilegroupName
 		props.Check_api.Last_released.Removed_api_file = proptools.StringPtr(
 			module.latestRemovedApiFilegroupName(apiScope))
diff --git a/ui/build/config.go b/ui/build/config.go
index 1152cd7..15da1bc 100644
--- a/ui/build/config.go
+++ b/ui/build/config.go
@@ -56,6 +56,7 @@
 	katiSuffix      string
 	targetDevice    string
 	targetDeviceDir string
+	fullBuild       bool
 
 	// Autodetected
 	totalRAM uint64
@@ -791,6 +792,14 @@
 	c.targetDevice = device
 }
 
+func (c *configImpl) FullBuild() bool {
+	return c.fullBuild
+}
+
+func (c *configImpl) SetFullBuild(fullBuild bool) {
+	c.fullBuild = fullBuild
+}
+
 func (c *configImpl) TargetBuildVariant() string {
 	if v, ok := c.environ.Get("TARGET_BUILD_VARIANT"); ok {
 		return v
diff --git a/ui/build/dumpvars.go b/ui/build/dumpvars.go
index fe0aca9..be6f00a 100644
--- a/ui/build/dumpvars.go
+++ b/ui/build/dumpvars.go
@@ -214,6 +214,9 @@
 		// So that later Kati runs can find BoardConfig.mk faster
 		"TARGET_DEVICE_DIR",
 
+		// To decide whether to skip the old installed cleanup step.
+		"FULL_BUILD",
+
 		// Whether --werror_overriding_commands will work
 		"BUILD_BROKEN_DUP_RULES",
 
@@ -278,6 +281,7 @@
 	config.SetNinjaArgs(strings.Fields(makeVars["NINJA_GOALS"]))
 	config.SetTargetDevice(makeVars["TARGET_DEVICE"])
 	config.SetTargetDeviceDir(makeVars["TARGET_DEVICE_DIR"])
+	config.SetFullBuild(makeVars["FULL_BUILD"] == "true")
 
 	config.SetBuildBrokenDupRules(makeVars["BUILD_BROKEN_DUP_RULES"] == "true")
 	config.SetBuildBrokenUsesNetwork(makeVars["BUILD_BROKEN_USES_NETWORK"] == "true")
diff --git a/ui/build/kati.go b/ui/build/kati.go
index 06ec646..668b20e 100644
--- a/ui/build/kati.go
+++ b/ui/build/kati.go
@@ -229,7 +229,11 @@
 
 	// Cleanup steps.
 	cleanCopyHeaders(ctx, config)
-	cleanOldInstalledFiles(ctx, config)
+	// Skip the old installed file cleanup step for few non-full build goals as we don't create
+	// an installed file list for them.
+	if config.FullBuild() {
+		cleanOldInstalledFiles(ctx, config)
+	}
 }
 
 // Clean out obsolete header files on the disk that were *not copied* during the