Support memtag_heap in SANITIZE_TARGET_DIAG, fix cc_test interation.

cc_test without sanitize:memtag_heap acts as if it has implicit
sanitize{memtag_heap:true, diag:{memtag_heap:true}}. This is unaffected
by SANITIZE_TARGET.

Refactor the test to cover all permutations.

Change memtag include lists to act similar to SANITIZE_TARGET_DIAG: the
the sync include list upgrades async targets to sync, unless diag is
explicitly set to false in the target definition.

Bug: b/135772972
Test: cc_test.go

Change-Id: I6a969f2f5804cd5f47fc4e93a20e3b99ea5fa111
diff --git a/cc/sanitize.go b/cc/sanitize.go
index af17490..8eeb355 100644
--- a/cc/sanitize.go
+++ b/cc/sanitize.go
@@ -267,6 +267,12 @@
 		return
 	}
 
+	// cc_test targets default to SYNC MemTag unless explicitly set to ASYNC (via diag: {memtag_heap}).
+	if ctx.testBinary() && s.Memtag_heap == nil {
+		s.Memtag_heap = boolPtr(true)
+		s.Diag.Memtag_heap = boolPtr(true)
+	}
+
 	var globalSanitizers []string
 	var globalSanitizersDiag []string
 
@@ -358,27 +364,29 @@
 			s.Diag.Cfi = boolPtr(true)
 		}
 
+		if found, globalSanitizersDiag = removeFromList("memtag_heap", globalSanitizersDiag); found &&
+			s.Diag.Memtag_heap == nil && Bool(s.Memtag_heap) {
+			s.Diag.Memtag_heap = boolPtr(true)
+		}
+
 		if len(globalSanitizersDiag) > 0 {
 			ctx.ModuleErrorf("unknown global sanitizer diagnostics option %s", globalSanitizersDiag[0])
 		}
 	}
 
-	// cc_test targets default to SYNC MemTag.
-	if ctx.testBinary() && s.Memtag_heap == nil {
-		if !ctx.Config().MemtagHeapDisabledForPath(ctx.ModuleDir()) {
-			s.Memtag_heap = boolPtr(true)
-			s.Diag.Memtag_heap = boolPtr(true)
-		}
-	}
-
 	// Enable Memtag for all components in the include paths (for Aarch64 only)
-	if s.Memtag_heap == nil && ctx.Arch().ArchType == android.Arm64 {
+	if ctx.Arch().ArchType == android.Arm64 {
 		if ctx.Config().MemtagHeapSyncEnabledForPath(ctx.ModuleDir()) {
-			s.Memtag_heap = boolPtr(true)
-			s.Diag.Memtag_heap = boolPtr(true)
+			if s.Memtag_heap == nil {
+				s.Memtag_heap = boolPtr(true)
+			}
+			if s.Diag.Memtag_heap == nil {
+				s.Diag.Memtag_heap = boolPtr(true)
+			}
 		} else if ctx.Config().MemtagHeapAsyncEnabledForPath(ctx.ModuleDir()) {
-			s.Memtag_heap = boolPtr(true)
-			s.Diag.Memtag_heap = boolPtr(false)
+			if s.Memtag_heap == nil {
+				s.Memtag_heap = boolPtr(true)
+			}
 		}
 	}