Add macros to flag-guard te and contexts files

This adds two macros which can be used in te files and contexts files.

* is_flag_enabled(flag_name, codes)
* is_flag_disabled(flag_name, codes)

Also flag-guarding requires to process input files before any
validations. Property contexts test and seapp contexts test are
modified a little to handle that.

Bug: 306563735
Test: build with manual guarding
Change-Id: Ia1c6d00b7aab0da3901c19f16d553153aace018c
diff --git a/build/soong/compat_cil.go b/build/soong/compat_cil.go
index 1f7901b..baad413 100644
--- a/build/soong/compat_cil.go
+++ b/build/soong/compat_cil.go
@@ -129,6 +129,7 @@
 // current policy.
 func compatTestFactory() android.SingletonModule {
 	f := &compatTestModule{}
+	f.AddProperties(&f.properties)
 	android.InitAndroidModule(f)
 	android.AddLoadHook(f, func(ctx android.LoadHookContext) {
 		f.loadHook(ctx)
@@ -138,6 +139,10 @@
 
 type compatTestModule struct {
 	android.SingletonModuleBase
+	properties struct {
+		// Default modules for conf
+		Defaults []string
+	}
 
 	compatTestTimestamp android.ModuleOutPath
 }
@@ -157,6 +162,10 @@
 			":se_build_files{.reqd_mask}",
 		},
 		Installable: proptools.BoolPtr(false),
+	}, &struct {
+		Defaults []string
+	}{
+		Defaults: f.properties.Defaults,
 	})
 
 	ctx.CreateModule(policyCilFactory, &nameProperties{
diff --git a/build/soong/selinux_contexts.go b/build/soong/selinux_contexts.go
index 5f7d525..e542c3a 100644
--- a/build/soong/selinux_contexts.go
+++ b/build/soong/selinux_contexts.go
@@ -17,7 +17,6 @@
 import (
 	"fmt"
 	"io"
-	"os"
 
 	"github.com/google/blueprint"
 	"github.com/google/blueprint/proptools"
@@ -338,7 +337,7 @@
 	return m.buildGeneralContexts(ctx, inputs)
 }
 
-func (m *selinuxContextsModule) checkVendorPropertyNamespace(ctx android.ModuleContext, inputs android.Paths) android.Paths {
+func (m *selinuxContextsModule) checkVendorPropertyNamespace(ctx android.ModuleContext, input android.Path) android.Path {
 	shippingApiLevel := ctx.DeviceConfig().ShippingApiLevel()
 	ApiLevelR := android.ApiLevelOrPanic(ctx, "R")
 
@@ -379,37 +378,33 @@
 		}
 	}
 
-	var ret android.Paths
-	for _, input := range inputs {
-		cmd := rule.Command().
-			BuiltTool("check_prop_prefix").
-			FlagWithInput("--property-contexts ", input).
-			FlagForEachArg("--allowed-property-prefix ", proptools.ShellEscapeList(allowedPropertyPrefixes)). // contains shell special character '$'
-			FlagForEachArg("--allowed-context-prefix ", allowedContextPrefixes)
+	cmd := rule.Command().
+		BuiltTool("check_prop_prefix").
+		FlagWithInput("--property-contexts ", input).
+		FlagForEachArg("--allowed-property-prefix ", proptools.ShellEscapeList(allowedPropertyPrefixes)). // contains shell special character '$'
+		FlagForEachArg("--allowed-context-prefix ", allowedContextPrefixes)
 
-		if !ctx.DeviceConfig().BuildBrokenVendorPropertyNamespace() {
-			cmd.Flag("--strict")
-		}
-
-		out := pathForModuleOut(ctx, "namespace_checked").Join(ctx, input.String())
-		rule.Command().Text("cp -f").Input(input).Output(out)
-		ret = append(ret, out)
+	if !ctx.DeviceConfig().BuildBrokenVendorPropertyNamespace() {
+		cmd.Flag("--strict")
 	}
+
+	out := pathForModuleOut(ctx, "namespace_checked").Join(ctx, input.String())
+	rule.Command().Text("cp -f").Input(input).Output(out)
 	rule.Build("check_namespace", "checking namespace of "+ctx.ModuleName())
-	return ret
+	return out
 }
 
 func (m *selinuxContextsModule) buildPropertyContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
 	// vendor/odm properties are enforced for devices launching with Android Q or later. So, if
 	// vendor/odm, make sure that only vendor/odm properties exist.
+	builtCtxFile := m.buildGeneralContexts(ctx, inputs)
+
 	shippingApiLevel := ctx.DeviceConfig().ShippingApiLevel()
 	ApiLevelQ := android.ApiLevelOrPanic(ctx, "Q")
 	if (ctx.SocSpecific() || ctx.DeviceSpecific()) && shippingApiLevel.GreaterThanOrEqualTo(ApiLevelQ) {
-		inputs = m.checkVendorPropertyNamespace(ctx, inputs)
+		builtCtxFile = m.checkVendorPropertyNamespace(ctx, builtCtxFile)
 	}
 
-	builtCtxFile := m.buildGeneralContexts(ctx, inputs)
-
 	var apiFiles android.Paths
 	ctx.VisitDirectDepsWithTag(syspropLibraryDepTag, func(c android.Module) {
 		i, ok := c.(interface{ CurrentSyspropApiFile() android.OptionalPath })
@@ -458,23 +453,39 @@
 
 func (m *selinuxContextsModule) buildSeappContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
 	neverallowFile := pathForModuleOut(ctx, "neverallow")
-	ret := pathForModuleOut(ctx, m.stem())
+	ret := pathForModuleOut(ctx, "checkseapp", m.stem())
 
+	// Step 1. Generate a M4 processed neverallow file
+	flags := m.getBuildFlags(ctx)
+	m4NeverallowFile := pathForModuleOut(ctx, "neverallow.m4out")
 	rule := android.NewRuleBuilder(pctx, ctx)
-	rule.Command().Text("(grep").
+	rule.Command().
+		Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
+		Flag("--fatal-warnings").
+		FlagForEachArg("-D", ctx.DeviceConfig().SepolicyM4Defs()).
+		Flags(flagsToM4Macros(flags)).
+		Inputs(android.PathsForModuleSrc(ctx, m.seappProperties.Neverallow_files)).
+		FlagWithOutput("> ", m4NeverallowFile)
+
+	rule.Temporary(m4NeverallowFile)
+	rule.Command().
+		Text("( grep").
 		Flag("-ihe").
 		Text("'^neverallow'").
-		Inputs(android.PathsForModuleSrc(ctx, m.seappProperties.Neverallow_files)).
-		Text(os.DevNull). // to make grep happy even when Neverallow_files is empty
+		Input(m4NeverallowFile).
 		Text(">").
 		Output(neverallowFile).
-		Text("|| true)") // to make ninja happy even when result is empty
+		Text("|| true )") // to make ninja happy even when result is empty
 
+	// Step 2. Generate a M4 processed contexts file
+	builtCtx := m.buildGeneralContexts(ctx, inputs)
+
+	// Step 3. checkseapp
 	rule.Temporary(neverallowFile)
 	checkCmd := rule.Command().BuiltTool("checkseapp").
 		FlagWithInput("-p ", android.PathForModuleSrc(ctx, proptools.String(m.seappProperties.Sepolicy))).
 		FlagWithOutput("-o ", ret).
-		Inputs(inputs).
+		Input(builtCtx).
 		Input(neverallowFile)
 
 	if m.shouldCheckCoredomain(ctx) {
diff --git a/build/soong/sepolicy_neverallow.go b/build/soong/sepolicy_neverallow.go
index fc47ab3..6e159e9 100644
--- a/build/soong/sepolicy_neverallow.go
+++ b/build/soong/sepolicy_neverallow.go
@@ -29,6 +29,9 @@
 }
 
 type neverallowTestProperties struct {
+	// Default modules for conf
+	Defaults []string
+
 	// Policy files to be tested.
 	Srcs []string `android:"path"`
 }
@@ -79,6 +82,10 @@
 		Srcs:          n.properties.Srcs,
 		Build_variant: proptools.StringPtr("user"),
 		Installable:   proptools.BoolPtr(false),
+	}, &struct {
+		Defaults []string
+	}{
+		Defaults: n.properties.Defaults,
 	})
 
 	sepolicyAnalyzeConf := n.sepolicyAnalyzeConfModuleName()
@@ -89,6 +96,10 @@
 		Build_variant:      proptools.StringPtr("user"),
 		Exclude_build_test: proptools.BoolPtr(true),
 		Installable:        proptools.BoolPtr(false),
+	}, &struct {
+		Defaults []string
+	}{
+		Defaults: n.properties.Defaults,
 	})
 }