Merge "Allow betterbug to read profile reports generated by profcollect"
diff --git a/Android.bp b/Android.bp
index aca6e40..780fd69 100644
--- a/Android.bp
+++ b/Android.bp
@@ -493,137 +493,189 @@
     ],
 }
 
-// This is a minimized cil modules to test microdroid.
-// TODO(b/178993690): migrate cil files to Android.bp and remove below
-filegroup {
-    name: "microdroid_sepolicy_build_files",
+se_build_files {
+    name: "se_build_files",
     srcs: [
-        // This order is important. Should be identical to sepolicy_build_files in Android.mk
-        "private/security_classes",
-        "private/initial_sids",
-        "private/access_vectors",
-        "public/global_macros",
-        "public/neverallow_macros",
-        "private/mls_macros",
-        "private/mls_decl",
-        "private/mls",
-        "private/policy_capabilities",
-        "public/te_macros",
-        "public/attributes",
-        "private/attributes",
-        "public/ioctl_defines",
-        "public/ioctl_macros",
-        "public/*.te",
-        "private/*.te",
-        "private/roles_decl",
-        "public/roles",
-        "private/users",
-        "private/initial_sid_contexts",
-        "private/fs_use",
-        "private/genfs_contexts",
-        "private/port_contexts",
+        "security_classes",
+        "initial_sids",
+        "access_vectors",
+        "global_macros",
+        "neverallow_macros",
+        "mls_macros",
+        "mls_decl",
+        "mls",
+        "policy_capabilities",
+        "te_macros",
+        "attributes",
+        "ioctl_defines",
+        "ioctl_macros",
+        "*.te",
+        "roles_decl",
+        "roles",
+        "users",
+        "initial_sid_contexts",
+        "fs_use",
+        "genfs_contexts",
+        "port_contexts",
     ],
 }
 
-filegroup {
-    name: "microdroid_sepolicy_public_and_reqd_mask_build_files",
-    srcs: [
-        // This order is important. Should be identical to sepolicy_build_files in Android.mk
-        "reqd_mask/security_classes",
-        "reqd_mask/initial_sids",
-        "reqd_mask/access_vectors",
-        "public/global_macros",
-        "public/neverallow_macros",
-        "reqd_mask/mls_macros",
-        "reqd_mask/mls_decl",
-        "reqd_mask/mls",
-        "public/te_macros",
-        "public/attributes",
-        "public/ioctl_defines",
-        "public/ioctl_macros",
-        "public/*.te",
-        "reqd_mask/*.te",
-        "reqd_mask/roles_decl",
-        "public/roles",
-        "reqd_mask/roles",
-        "reqd_mask/users",
-        "reqd_mask/initial_sid_contexts",
-    ],
-}
-
-filegroup {
-    name: "microdroid_sepolicy_reqd_mask_build_files",
-    srcs: [
-        // This order is important. Should be identical to sepolicy_build_files in Android.mk
-        "reqd_mask/security_classes",
-        "reqd_mask/initial_sids",
-        "reqd_mask/access_vectors",
-        "reqd_mask/mls_macros",
-        "reqd_mask/mls_decl",
-        "reqd_mask/mls",
-        "reqd_mask/*.te",
-        "reqd_mask/roles_decl",
-        "reqd_mask/roles",
-        "reqd_mask/users",
-        "reqd_mask/initial_sid_contexts",
-    ],
-}
-
-// These variables are based on aosp_cf_x86_64_only_phone-userdebug. Other than target_arch,
-// these configurations should be fine to test microdroid on normal devices with full treble.
-// The exception is target_arch. But as target_arch is meaningful only on mips, and as we are not
-// running microdroid on mips for now, we skip assigning target_arch here. After cil files are fully
-// migrated into Soong, these will have correct values.
-policy_to_conf_flags = "$(location m4) --fatal-warnings " +
-"-D mls_num_sens=1 -D mls_num_cats=1024 " +
-"-D target_build_variant=userdebug " +
-"-D target_with_asan=false " +
-"-D target_with_native_coverage=false " +
-"-D target_full_treble=true " +
-"-D target_compatible_property=true " +
-"-D target_treble_sysprop_neverallow=true " +
-"-D target_enforce_sysprop_owner=true "
-
-genrule {
-    name: "microdroid_plat_sepolicy.cil_gen",
-    srcs: [":microdroid_sepolicy_build_files"],
-    tools: ["m4", "checkpolicy"],
-    out: ["plat_sepolicy.cil"],
-    cmd: policy_to_conf_flags +
-        "-s $(locations :microdroid_sepolicy_build_files) > $(out).conf" +
-        "&& $(location checkpolicy) -M -C -c 30 -o $(out) $(out).conf",
-    visibility: ["//visibility:private"],
-}
-
-prebuilt_etc {
-    name: "microdroid_plat_sepolicy.cil",
-    src: ":microdroid_plat_sepolicy.cil_gen",
-    filename: "plat_sepolicy.cil",
-    relative_install_path: "selinux",
+// reqd_policy_mask - a policy.conf file which contains only the bare minimum
+// policy necessary to use checkpolicy.
+//
+// This bare-minimum policy needs to be present in all policy.conf files, but
+// should not necessarily be exported as part of the public policy.
+//
+// The rules generated by reqd_policy_mask will allow the compilation of public
+// policy and subsequent removal of CIL policy that should not be exported.
+se_policy_conf {
+    name: "reqd_policy_mask.conf",
+    srcs: [":se_build_files{.reqd_mask}"],
     installable: false,
 }
 
-genrule {
-    name: "microdroid_reqd_policy_mask.cil_gen",
-    srcs: [":microdroid_sepolicy_reqd_mask_build_files"],
-    tools: ["m4", "checkpolicy"],
-    out: ["reqd_policy_mask.cil"],
-    cmd: policy_to_conf_flags +
-        "-s $(in) > $(out).conf" +
-        "&& $(location checkpolicy) -C -M -c 30 -o $(out) $(out).conf",
-    visibility: ["//visibility:private"],
+se_policy_cil {
+    name: "reqd_policy_mask.cil",
+    src: ":reqd_policy_mask.conf",
+    secilc_check: false,
+    installable: false,
 }
 
+// pub_policy - policy that will be exported to be a part of non-platform
+// policy corresponding to this platform version.
+//
+// This is a limited subset of policy that would not compile in checkpolicy on
+// its own.
+//
+// To get around this limitation, add only the required files from private
+// policy, which will generate CIL policy that will then be filtered out by the
+// reqd_policy_mask.
+//
+// There are three pub_policy.cil files below:
+//   - pub_policy.cil: exported 'product', 'system_ext' and 'system' policy.
+//   - system_ext_pub_policy.cil: exported 'system_ext' and 'system' policy.
+//   - plat_pub_policy.cil: exported 'system' policy.
+//
+// Those above files will in turn be used to generate the following versioned cil files:
+//   - product_mapping_file: the versioned, exported 'product' policy in product partition.
+//   - system_ext_mapping_file: the versioned, exported 'system_ext' policy in system_ext partition.
+//   - plat_mapping_file: the versioned, exported 'system' policy in system partition.
+//   - plat_pub_versioned.cil: the versioned, exported 'product', 'system_ext' and 'system' policy
+//                             in vendor partition.
+//
+se_policy_conf {
+    name: "pub_policy.conf",
+    srcs: [":se_build_files{.product_public}"], // product_ includes system and system_ext
+    installable: false,
+}
+
+se_policy_cil {
+    name: "pub_policy.cil",
+    src: ":pub_policy.conf",
+    filter_out: [":reqd_policy_mask.cil"],
+    secilc_check: false,
+    installable: false,
+}
+
+se_policy_conf {
+    name: "system_ext_pub_policy.conf",
+    srcs: [":se_build_files{.system_ext_public}"], // system_ext_public includes system
+    installable: false,
+}
+
+se_policy_cil {
+    name: "system_ext_pub_policy.cil",
+    src: ":system_ext_pub_policy.conf",
+    filter_out: [":reqd_policy_mask.cil"],
+    secilc_check: false,
+    installable: false,
+}
+
+se_policy_conf {
+    name: "plat_pub_policy.conf",
+    srcs: [":se_build_files{.plat_public}"],
+    installable: false,
+}
+
+se_policy_cil {
+    name: "plat_pub_policy.cil",
+    src: ":plat_pub_policy.conf",
+    filter_out: [":reqd_policy_mask.cil"],
+    secilc_check: false,
+    installable: false,
+}
+
+// plat_policy.conf - A combination of the private and public platform policy
+// which will ship with the device.
+//
+// The platform will always reflect the most recent platform version and is not
+// currently being attributized.
+se_policy_conf {
+    name: "plat_sepolicy.conf",
+    srcs: [":se_build_files{.plat}"],
+    installable: false,
+}
+
+se_policy_cil {
+    name: "plat_sepolicy.cil",
+    src: ":plat_sepolicy.conf",
+    additional_cil_files: ["private/technical_debt.cil"],
+}
+
+// system_ext_policy.conf - A combination of the private and public system_ext
+// policy which will ship with the device. System_ext policy is not attributized
+se_policy_conf {
+    name: "system_ext_sepolicy.conf",
+    srcs: [":se_build_files{.system_ext}"],
+    installable: false,
+}
+
+se_policy_cil {
+    name: "system_ext_sepolicy.cil",
+    src: ":system_ext_sepolicy.conf",
+    system_ext_specific: true,
+    filter_out: [":plat_sepolicy.cil"],
+    remove_line_marker: true,
+}
+
+// product_policy.conf - A combination of the private and public product policy
+// which will ship with the device. Product policy is not attributized
+se_policy_conf {
+    name: "product_sepolicy.conf",
+    srcs: [":se_build_files{.product}"],
+    installable: false,
+}
+
+se_policy_cil {
+    name: "product_sepolicy.cil",
+    src: ":product_sepolicy.conf",
+    product_specific: true,
+    filter_out: [":plat_sepolicy.cil", ":system_ext_sepolicy.cil"],
+    remove_line_marker: true,
+}
+
+//////////////////////////////////
+// SELinux policy embedded into CTS.
+// CTS checks neverallow rules of this policy against the policy of the device under test.
+//////////////////////////////////
+se_policy_conf {
+    name: "general_sepolicy.conf",
+    srcs: [":se_build_files{.plat}"],
+    build_variant: "user",
+    cts: true,
+    exclude_build_test: true,
+}
+
+//////////////////////////////////
+// modules for microdroid
+// TODO(b/178993690): migrate Android.mk to Android.bp and remove workarounds
+//////////////////////////////////
 genrule {
     name: "microdroid_plat_mapping_file_gen",
-    srcs: [":microdroid_sepolicy_public_and_reqd_mask_build_files", ":microdroid_reqd_policy_mask.cil_gen"],
-    tools: ["m4", "checkpolicy", "build_sepolicy", "version_policy"],
+    srcs: [":plat_pub_policy.cil"],
+    tools: ["version_policy"],
     out: ["10000.0.cil"],
-    cmd: policy_to_conf_flags +
-        "-s $(locations :microdroid_sepolicy_public_and_reqd_mask_build_files) > $(out).conf" +
-        "&& $(location checkpolicy) -M -C -c 30 -o $(out).pub $(out).conf" +
-        "&& $(location build_sepolicy) filter_out -f $(location :microdroid_reqd_policy_mask.cil_gen) -t $(out).pub" +
-        "&& $(location version_policy) -b $(out).pub -m -n 10000.0 -o $(out)",
+    cmd: "$(location version_policy) -b $(location :plat_pub_policy.cil) -m -n 10000.0 -o $(out)",
     visibility: ["//visibility:private"],
 }
 
@@ -635,34 +687,32 @@
     installable: false,
 }
 
-///////////////////////////////////////////////////////////////////
-genrule {
-    name: "microdroid_pub_policy.cil_gen",
-    srcs: [
-        ":microdroid_sepolicy_public_and_reqd_mask_build_files",
-        ":microdroid_reqd_policy_mask.cil_gen",
-    ],
-    tools: ["m4", "checkpolicy", "build_sepolicy"],
-    out: ["pub_policy.cil"],
-    cmd: policy_to_conf_flags + " -s $(locations :microdroid_sepolicy_public_and_reqd_mask_build_files) > $(out).conf && " +
-        "$(location checkpolicy) -C -M -c 30 -o $(out) $(out).conf && " +
-        "$(location build_sepolicy) filter_out -f $(location :microdroid_reqd_policy_mask.cil_gen) -t $(out)",
-    visibility: ["//visibility:private"],
-}
-
+// Normally plat_pub_versioned.cil is built from pub_policy.cil (including system_ext and product).
+// But microdroid only has system, so its plat_pub_versioned.cil uses plat_pub_policy.cil.
 genrule {
     name: "microdroid_plat_pub_versioned.cil_gen",
-    srcs: [":microdroid_pub_policy.cil_gen"],
+    srcs: [":plat_pub_policy.cil"],
     tools: ["version_policy"],
     out: ["plat_pub_versioned.cil"],
     cmd: "$(location version_policy) " +
-        "-b $(location :microdroid_pub_policy.cil_gen) " +
-        "-t $(location :microdroid_pub_policy.cil_gen) " +
+        "-b $(location :plat_pub_policy.cil) " +
+        "-t $(location :plat_pub_policy.cil) " +
         "-n 10000.0 " +
         "-o $(out)",
     visibility: ["//visibility:private"],
 }
 
+prebuilt_etc {
+    name: "microdroid_plat_pub_versioned.cil",
+    src: ":microdroid_plat_pub_versioned.cil_gen",
+    filename: "plat_pub_versioned.cil",
+    relative_install_path: "selinux",
+    installable: false,
+}
+
+// policy files for microdroid vendor
+// This contains a minimal set of policy files for microdroid vendor.
+// TODO(b/178993690): update se_build_files to cover this
 filegroup {
     name: "microdroid_vendor_sepolicy_build_files",
     srcs: [
@@ -689,31 +739,35 @@
     ],
 }
 
+se_policy_conf {
+    name: "microdroid_vendor_sepolicy.conf",
+    srcs: [":microdroid_vendor_sepolicy_build_files"],
+    installable: false,
+}
+
 genrule {
     name: "microdroid_vendor_sepolicy.cil_gen",
     srcs: [
-        ":microdroid_vendor_sepolicy_build_files",
+        ":microdroid_vendor_sepolicy.conf",
         ":microdroid_plat_pub_versioned.cil_gen",
-        ":microdroid_pub_policy.cil_gen",
-        ":microdroid_reqd_policy_mask.cil_gen",
+        ":plat_pub_policy.cil",
+        ":reqd_policy_mask.cil",
     ],
     tools: [
-        "m4",
         "build_sepolicy",
         "checkpolicy",
         "secilc",
         "version_policy",
     ],
     out: ["vendor_sepolicy.cil"],
-    cmd: policy_to_conf_flags + " -s $(locations :microdroid_vendor_sepolicy_build_files) > $(out).conf && " +
-        "$(location build_sepolicy) " +
+    cmd: "$(location build_sepolicy) " +
         "--android_host_path $$(dirname $(location build_sepolicy)) " +
         "build_cil " +
-        "--input_policy_conf $(out).conf " +
+        "--input_policy_conf $(location :microdroid_vendor_sepolicy.conf) " +
         "--checkpolicy_env ASAN_OPTIONS=detect_leaks=0 " +
-        "--base_policy $(location :microdroid_pub_policy.cil_gen) " +
+        "--base_policy $(location :plat_pub_policy.cil) " +
         "--filter_out_files $(location :microdroid_plat_pub_versioned.cil_gen) " +
-        "--reqd_mask $(location :microdroid_reqd_policy_mask.cil_gen) " +
+        "--reqd_mask $(location :reqd_policy_mask.cil) " +
         "--treble_sepolicy_vers 10000.0 " +
         "--policy_vers 30 " +
         "--output_cil $(out)",
@@ -727,38 +781,3 @@
     relative_install_path: "selinux",
     installable: false,
 }
-
-prebuilt_etc {
-    name: "microdroid_plat_pub_versioned.cil",
-    src: ":microdroid_plat_pub_versioned.cil_gen",
-    filename: "plat_pub_versioned.cil",
-    relative_install_path: "selinux",
-    installable: false,
-}
-
-se_build_files {
-    name: "se_build_files",
-    srcs: [
-        "security_classes",
-        "initial_sids",
-        "access_vectors",
-        "global_macros",
-        "neverallow_macros",
-        "mls_macros",
-        "mls_decl",
-        "mls",
-        "policy_capabilities",
-        "te_macros",
-        "attributes",
-        "ioctl_defines",
-        "ioctl_macros",
-        "*.te",
-        "roles_decl",
-        "roles",
-        "users",
-        "initial_sid_contexts",
-        "fs_use",
-        "genfs_contexts",
-        "port_contexts",
-    ],
-}
diff --git a/Android.mk b/Android.mk
index 77513a0..7c4ddbe 100644
--- a/Android.mk
+++ b/Android.mk
@@ -741,209 +741,36 @@
 endif # ifeq ($(mixed_sepolicy_build),true)
 
 ##################################
-# reqd_policy_mask - a policy.conf file which contains only the bare minimum
-# policy necessary to use checkpolicy.  This bare-minimum policy needs to be
-# present in all policy.conf files, but should not necessarily be exported as
-# part of the public policy.  The rules generated by reqd_policy_mask will allow
-# the compilation of public policy and subsequent removal of CIL policy that
-# should not be exported.
-
-policy_files := $(call build_policy, $(sepolicy_build_files), $(REQD_MASK_POLICY))
-reqd_policy_mask.conf := $(intermediates)/reqd_policy_mask.conf
-$(reqd_policy_mask.conf): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(reqd_policy_mask.conf): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(reqd_policy_mask.conf): PRIVATE_TARGET_BUILD_VARIANT := $(TARGET_BUILD_VARIANT)
-$(reqd_policy_mask.conf): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(reqd_policy_mask.conf): PRIVATE_TGT_WITH_ASAN := $(with_asan)
-$(reqd_policy_mask.conf): PRIVATE_TGT_WITH_NATIVE_COVERAGE := $(with_native_coverage)
-$(reqd_policy_mask.conf): PRIVATE_ADDITIONAL_M4DEFS := $(LOCAL_ADDITIONAL_M4DEFS)
-$(reqd_policy_mask.conf): PRIVATE_SEPOLICY_SPLIT := $(PRODUCT_SEPOLICY_SPLIT)
-$(reqd_policy_mask.conf): PRIVATE_COMPATIBLE_PROPERTY := $(PRODUCT_COMPATIBLE_PROPERTY)
-$(reqd_policy_mask.conf): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := $(treble_sysprop_neverallow)
-$(reqd_policy_mask.conf): PRIVATE_ENFORCE_SYSPROP_OWNER := $(enforce_sysprop_owner)
-$(reqd_policy_mask.conf): PRIVATE_POLICY_FILES := $(policy_files)
-$(reqd_policy_mask.conf): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-# b/37755687
-CHECKPOLICY_ASAN_OPTIONS := ASAN_OPTIONS=detect_leaks=0
-
-reqd_policy_mask.cil := $(intermediates)/reqd_policy_mask.cil
-$(reqd_policy_mask.cil): $(reqd_policy_mask.conf) $(HOST_OUT_EXECUTABLES)/checkpolicy
-	@mkdir -p $(dir $@)
-	$(hide) $(CHECKPOLICY_ASAN_OPTIONS) $(HOST_OUT_EXECUTABLES)/checkpolicy -C -M -c \
-		$(POLICYVERS) -o $@ $<
-
-reqd_policy_mask.conf :=
+# plat policy files are now built with Android.bp. Grab them from intermediate.
+# See Android.bp for details of plat policy files.
+#
+reqd_policy_mask.cil := $(call intermediates-dir-for,ETC,reqd_policy_mask.cil)/reqd_policy_mask.cil
 reqd_policy_mask_$(PLATFORM_SEPOLICY_VERSION).cil := $(reqd_policy_mask.cil)
 
-##################################
-# pub_policy - policy that will be exported to be a part of non-platform
-# policy corresponding to this platform version.  This is a limited subset of
-# policy that would not compile in checkpolicy on its own.  To get around this
-# limitation, add only the required files from private policy, which will
-# generate CIL policy that will then be filtered out by the reqd_policy_mask.
-#
-# There are three pub_policy.cil files below:
-#   - pub_policy.cil: exported 'product', 'system_ext' and 'system' policy.
-#   - system_ext_pub_policy.cil: exported 'system_ext' and 'system' policy.
-#   - plat_pub_policy.cil: exported 'system' policy.
-#
-# Those above files will in turn be used to generate the following versioned cil files:
-#   - product_mapping_file: the versioned, exported 'product' policy in product partition.
-#   - system_ext_mapping_file: the versioned, exported 'system_ext' policy in system_ext partition.
-#   - plat_mapping_file: the versioned, exported 'system' policy in system partition.
-#   - plat_pub_versioned.cil: the versioned, exported 'product', 'system_ext' and 'system'
-#                             policy in vendor partition.
-#
-policy_files := $(call build_policy, $(sepolicy_build_files), \
-  $(PLAT_PUBLIC_POLICY) $(SYSTEM_EXT_PUBLIC_POLICY) $(PRODUCT_PUBLIC_POLICY) $(REQD_MASK_POLICY))
-pub_policy.conf := $(intermediates)/pub_policy.conf
-$(pub_policy.conf): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(pub_policy.conf): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(pub_policy.conf): PRIVATE_TARGET_BUILD_VARIANT := $(TARGET_BUILD_VARIANT)
-$(pub_policy.conf): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(pub_policy.conf): PRIVATE_TGT_WITH_ASAN := $(with_asan)
-$(pub_policy.conf): PRIVATE_TGT_WITH_NATIVE_COVERAGE := $(with_native_coverage)
-$(pub_policy.conf): PRIVATE_ADDITIONAL_M4DEFS := $(LOCAL_ADDITIONAL_M4DEFS)
-$(pub_policy.conf): PRIVATE_SEPOLICY_SPLIT := $(PRODUCT_SEPOLICY_SPLIT)
-$(pub_policy.conf): PRIVATE_COMPATIBLE_PROPERTY := $(PRODUCT_COMPATIBLE_PROPERTY)
-$(pub_policy.conf): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := $(treble_sysprop_neverallow)
-$(pub_policy.conf): PRIVATE_ENFORCE_SYSPROP_OWNER := $(enforce_sysprop_owner)
-$(pub_policy.conf): PRIVATE_POLICY_FILES := $(policy_files)
-$(pub_policy.conf): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-pub_policy.cil := $(intermediates)/pub_policy.cil
-$(pub_policy.cil): PRIVATE_POL_CONF := $(pub_policy.conf)
-$(pub_policy.cil): PRIVATE_REQD_MASK := $(reqd_policy_mask.cil)
-$(pub_policy.cil): $(HOST_OUT_EXECUTABLES)/checkpolicy \
-$(HOST_OUT_EXECUTABLES)/build_sepolicy $(pub_policy.conf) $(reqd_policy_mask.cil)
-	@mkdir -p $(dir $@)
-	$(hide) $(CHECKPOLICY_ASAN_OPTIONS) $< -C -M -c $(POLICYVERS) -o $@ $(PRIVATE_POL_CONF)
-	$(hide) $(HOST_OUT_EXECUTABLES)/build_sepolicy -a $(HOST_OUT_EXECUTABLES) filter_out \
-		-f $(PRIVATE_REQD_MASK) -t $@
-
+pub_policy.cil := $(call intermediates-dir-for,ETC,pub_policy.cil)/pub_policy.cil
 pub_policy_$(PLATFORM_SEPOLICY_VERSION).cil := $(pub_policy.cil)
 
-pub_policy.conf :=
-
-##################################
-policy_files := $(call build_policy, $(sepolicy_build_files), \
-  $(PLAT_PUBLIC_POLICY) $(SYSTEM_EXT_PUBLIC_POLICY) $(REQD_MASK_POLICY))
-system_ext_pub_policy.conf := $(intermediates)/system_ext_pub_policy.conf
-$(system_ext_pub_policy.conf): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(system_ext_pub_policy.conf): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(system_ext_pub_policy.conf): PRIVATE_TARGET_BUILD_VARIANT := $(TARGET_BUILD_VARIANT)
-$(system_ext_pub_policy.conf): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(system_ext_pub_policy.conf): PRIVATE_TGT_WITH_ASAN := $(with_asan)
-$(system_ext_pub_policy.conf): PRIVATE_TGT_WITH_NATIVE_COVERAGE := $(with_native_coverage)
-$(system_ext_pub_policy.conf): PRIVATE_ADDITIONAL_M4DEFS := $(LOCAL_ADDITIONAL_M4DEFS)
-$(system_ext_pub_policy.conf): PRIVATE_SEPOLICY_SPLIT := $(PRODUCT_SEPOLICY_SPLIT)
-$(system_ext_pub_policy.conf): PRIVATE_COMPATIBLE_PROPERTY := $(PRODUCT_COMPATIBLE_PROPERTY)
-$(system_ext_pub_policy.conf): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := $(treble_sysprop_neverallow)
-$(system_ext_pub_policy.conf): PRIVATE_ENFORCE_SYSPROP_OWNER := $(enforce_sysprop_owner)
-$(system_ext_pub_policy.conf): PRIVATE_POLICY_FILES := $(policy_files)
-$(system_ext_pub_policy.conf): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-
-system_ext_pub_policy.cil := $(intermediates)/system_ext_pub_policy.cil
-$(system_ext_pub_policy.cil): PRIVATE_POL_CONF := $(system_ext_pub_policy.conf)
-$(system_ext_pub_policy.cil): PRIVATE_REQD_MASK := $(reqd_policy_mask.cil)
-$(system_ext_pub_policy.cil): $(HOST_OUT_EXECUTABLES)/checkpolicy \
-$(HOST_OUT_EXECUTABLES)/build_sepolicy $(system_ext_pub_policy.conf) $(reqd_policy_mask.cil)
-	@mkdir -p $(dir $@)
-	$(hide) $(CHECKPOLICY_ASAN_OPTIONS) $< -C -M -c $(POLICYVERS) -o $@ $(PRIVATE_POL_CONF)
-	$(hide) $(HOST_OUT_EXECUTABLES)/build_sepolicy -a $(HOST_OUT_EXECUTABLES) filter_out \
-		-f $(PRIVATE_REQD_MASK) -t $@
-
+system_ext_pub_policy.cil := $(call intermediates-dir-for,ETC,system_ext_pub_policy.cil)/system_ext_pub_policy.cil
 system_ext_pub_policy_$(PLATFORM_SEPOLICY_VERSION).cil := $(system_ext_pub_policy.cil)
 
-system_ext_pub_policy.conf :=
-
-##################################
-policy_files := $(call build_policy, $(sepolicy_build_files), \
-  $(PLAT_PUBLIC_POLICY) $(REQD_MASK_POLICY))
-plat_pub_policy.conf := $(intermediates)/plat_pub_policy.conf
-$(plat_pub_policy.conf): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(plat_pub_policy.conf): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(plat_pub_policy.conf): PRIVATE_TARGET_BUILD_VARIANT := $(TARGET_BUILD_VARIANT)
-$(plat_pub_policy.conf): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(plat_pub_policy.conf): PRIVATE_TGT_WITH_ASAN := $(with_asan)
-$(plat_pub_policy.conf): PRIVATE_TGT_WITH_NATIVE_COVERAGE := $(with_native_coverage)
-$(plat_pub_policy.conf): PRIVATE_ADDITIONAL_M4DEFS := $(LOCAL_ADDITIONAL_M4DEFS)
-$(plat_pub_policy.conf): PRIVATE_SEPOLICY_SPLIT := $(PRODUCT_SEPOLICY_SPLIT)
-$(plat_pub_policy.conf): PRIVATE_COMPATIBLE_PROPERTY := $(PRODUCT_COMPATIBLE_PROPERTY)
-$(plat_pub_policy.conf): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := $(treble_sysprop_neverallow)
-$(plat_pub_policy.conf): PRIVATE_ENFORCE_SYSPROP_OWNER := $(enforce_sysprop_owner)
-$(plat_pub_policy.conf): PRIVATE_POLICY_FILES := $(policy_files)
-$(plat_pub_policy.conf): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-
-plat_pub_policy.cil := $(intermediates)/plat_pub_policy.cil
-$(plat_pub_policy.cil): PRIVATE_POL_CONF := $(plat_pub_policy.conf)
-$(plat_pub_policy.cil): PRIVATE_REQD_MASK := $(reqd_policy_mask.cil)
-$(plat_pub_policy.cil): $(HOST_OUT_EXECUTABLES)/checkpolicy \
-$(HOST_OUT_EXECUTABLES)/build_sepolicy $(plat_pub_policy.conf) $(reqd_policy_mask.cil)
-	@mkdir -p $(dir $@)
-	$(hide) $(CHECKPOLICY_ASAN_OPTIONS) $< -C -M -c $(POLICYVERS) -o $@ $(PRIVATE_POL_CONF)
-	$(hide) $(HOST_OUT_EXECUTABLES)/build_sepolicy -a $(HOST_OUT_EXECUTABLES) filter_out \
-		-f $(PRIVATE_REQD_MASK) -t $@
-
+plat_pub_policy.cil := $(call intermediates-dir-for,ETC,plat_pub_policy.cil)/plat_pub_policy.cil
 plat_pub_policy_$(PLATFORM_SEPOLICY_VERSION).cil := $(plat_pub_policy.cil)
 
-plat_pub_policy.conf :=
-
-#################################
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := plat_sepolicy.cil
-LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 legacy_unencumbered
-LOCAL_LICENSE_CONDITIONS := notice unencumbered
-LOCAL_NOTICE_FILE := $(LOCAL_PATH)/NOTICE
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE_PATH := $(TARGET_OUT)/etc/selinux
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-# plat_policy.conf - A combination of the private and public platform policy
-# which will ship with the device.  The platform will always reflect the most
-# recent platform version and is not currently being attributized.
-policy_files := $(call build_policy, $(sepolicy_build_files), \
-  $(PLAT_PUBLIC_POLICY) $(PLAT_PRIVATE_POLICY))
-plat_policy.conf := $(intermediates)/plat_policy.conf
-$(plat_policy.conf): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(plat_policy.conf): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(plat_policy.conf): PRIVATE_TARGET_BUILD_VARIANT := $(TARGET_BUILD_VARIANT)
-$(plat_policy.conf): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(plat_policy.conf): PRIVATE_TGT_WITH_ASAN := $(with_asan)
-$(plat_policy.conf): PRIVATE_TGT_WITH_NATIVE_COVERAGE := $(with_native_coverage)
-$(plat_policy.conf): PRIVATE_ADDITIONAL_M4DEFS := $(LOCAL_ADDITIONAL_M4DEFS)
-$(plat_policy.conf): PRIVATE_SEPOLICY_SPLIT := $(PRODUCT_SEPOLICY_SPLIT)
-$(plat_policy.conf): PRIVATE_COMPATIBLE_PROPERTY := $(PRODUCT_COMPATIBLE_PROPERTY)
-$(plat_policy.conf): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := $(treble_sysprop_neverallow)
-$(plat_policy.conf): PRIVATE_ENFORCE_SYSPROP_OWNER := $(enforce_sysprop_owner)
-$(plat_policy.conf): PRIVATE_POLICY_FILES := $(policy_files)
-$(plat_policy.conf): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-	$(hide) sed '/^\s*dontaudit.*;/d' $@ | sed '/^\s*dontaudit/,/;/d' > $@.dontaudit
-
-$(LOCAL_BUILT_MODULE): PRIVATE_ADDITIONAL_CIL_FILES := \
-  $(call build_policy, $(sepolicy_build_cil_workaround_files), $(PLAT_PRIVATE_POLICY))
-$(LOCAL_BUILT_MODULE): PRIVATE_NEVERALLOW_ARG := $(NEVERALLOW_ARG)
-$(LOCAL_BUILT_MODULE): $(plat_policy.conf) $(HOST_OUT_EXECUTABLES)/checkpolicy \
-  $(HOST_OUT_EXECUTABLES)/secilc \
-  $(call build_policy, $(sepolicy_build_cil_workaround_files), $(PLAT_PRIVATE_POLICY)) \
-  $(built_sepolicy_neverallows)
-	@mkdir -p $(dir $@)
-	$(hide) $(CHECKPOLICY_ASAN_OPTIONS) $(HOST_OUT_EXECUTABLES)/checkpolicy -M -C -c \
-		$(POLICYVERS) -o $@.tmp $<
-	$(hide) cat $(PRIVATE_ADDITIONAL_CIL_FILES) >> $@.tmp
-	$(hide) $(HOST_OUT_EXECUTABLES)/secilc -m -M true -G -c $(POLICYVERS) $(PRIVATE_NEVERALLOW_ARG) $@.tmp -o /dev/null -f /dev/null
-	$(hide) mv $@.tmp $@
-
-built_plat_cil := $(LOCAL_BUILT_MODULE)
+built_plat_cil := $(call intermediates-dir-for,ETC,plat_sepolicy.cil)/plat_sepolicy.cil
 built_plat_cil_$(PLATFORM_SEPOLICY_VERSION) := $(built_plat_cil)
-plat_policy.conf :=
+
+ifdef HAS_SYSTEM_EXT_SEPOLICY
+built_system_ext_cil := $(call intermediates-dir-for,ETC,system_ext_sepolicy.cil)/system_ext_sepolicy.cil
+built_system_ext_cil_$(PLATFORM_SEPOLICY_VERSION) := $(built_system_ext_cil)
+endif # ifdef HAS_SYSTEM_EXT_SEPOLICY
+
+ifdef HAS_PRODUCT_SEPOLICY
+built_product_cil := $(call intermediates-dir-for,ETC,product_sepolicy.cil)/product_sepolicy.cil
+built_product_cil_$(PLATFORM_SEPOLICY_VERSION) := $(built_product_cil)
+endif # ifdef HAS_PRODUCT_SEPOLICY
+
+# b/37755687
+CHECKPOLICY_ASAN_OPTIONS := ASAN_OPTIONS=detect_leaks=0
 
 #################################
 include $(CLEAR_VARS)
@@ -997,128 +824,6 @@
 #################################
 include $(CLEAR_VARS)
 
-ifdef HAS_SYSTEM_EXT_SEPOLICY
-LOCAL_MODULE := system_ext_sepolicy.cil
-LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 legacy_unencumbered
-LOCAL_LICENSE_CONDITIONS := notice unencumbered
-LOCAL_NOTICE_FILE := $(LOCAL_PATH)/NOTICE
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE_PATH := $(TARGET_OUT_SYSTEM_EXT)/etc/selinux
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-# system_ext_policy.conf - A combination of the private and public system_ext policy
-# which will ship with the device. System_ext policy is not attributized.
-policy_files := $(call build_policy, $(sepolicy_build_files), \
-  $(PLAT_PUBLIC_POLICY) $(PLAT_PRIVATE_POLICY) \
-  $(SYSTEM_EXT_PUBLIC_POLICY) $(SYSTEM_EXT_PRIVATE_POLICY))
-system_ext_policy.conf := $(intermediates)/system_ext_policy.conf
-$(system_ext_policy.conf): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(system_ext_policy.conf): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(system_ext_policy.conf): PRIVATE_TARGET_BUILD_VARIANT := $(TARGET_BUILD_VARIANT)
-$(system_ext_policy.conf): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(system_ext_policy.conf): PRIVATE_TGT_WITH_ASAN := $(with_asan)
-$(system_ext_policy.conf): PRIVATE_TGT_WITH_NATIVE_COVERAGE := $(with_native_coverage)
-$(system_ext_policy.conf): PRIVATE_ADDITIONAL_M4DEFS := $(LOCAL_ADDITIONAL_M4DEFS)
-$(system_ext_policy.conf): PRIVATE_SEPOLICY_SPLIT := $(PRODUCT_SEPOLICY_SPLIT)
-$(system_ext_policy.conf): PRIVATE_COMPATIBLE_PROPERTY := $(PRODUCT_COMPATIBLE_PROPERTY)
-$(system_ext_policy.conf): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := $(treble_sysprop_neverallow)
-$(system_ext_policy.conf): PRIVATE_ENFORCE_SYSPROP_OWNER := $(enforce_sysprop_owner)
-$(system_ext_policy.conf): PRIVATE_POLICY_FILES := $(policy_files)
-$(system_ext_policy.conf): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-	$(hide) sed '/dontaudit/d' $@ > $@.dontaudit
-
-$(LOCAL_BUILT_MODULE): PRIVATE_NEVERALLOW_ARG := $(NEVERALLOW_ARG)
-$(LOCAL_BUILT_MODULE): PRIVATE_PLAT_CIL := $(built_plat_cil)
-$(LOCAL_BUILT_MODULE): $(system_ext_policy.conf) $(HOST_OUT_EXECUTABLES)/checkpolicy \
-$(HOST_OUT_EXECUTABLES)/build_sepolicy $(HOST_OUT_EXECUTABLES)/secilc $(built_plat_cil)
-	@mkdir -p $(dir $@)
-	$(hide) $(CHECKPOLICY_ASAN_OPTIONS) $(HOST_OUT_EXECUTABLES)/checkpolicy -M -C -c \
-	$(POLICYVERS) -o $@ $<
-	$(hide) $(HOST_OUT_EXECUTABLES)/build_sepolicy -a $(HOST_OUT_EXECUTABLES) filter_out \
-		-f $(PRIVATE_PLAT_CIL) -t $@
-	# Line markers (denoted by ;;) are malformed after above cmd. They are only
-	# used for debugging, so we remove them.
-	$(hide) grep -v ';;' $@ > $@.tmp
-	$(hide) mv $@.tmp $@
-	# Combine plat_sepolicy.cil and system_ext_sepolicy.cil to make sure that the
-	# latter doesn't accidentally depend on vendor/odm policies.
-	$(hide) $(HOST_OUT_EXECUTABLES)/secilc -m -M true -G -c $(POLICYVERS) \
-		$(PRIVATE_NEVERALLOW_ARG) $(PRIVATE_PLAT_CIL) $@ -o /dev/null -f /dev/null
-
-
-built_system_ext_cil := $(LOCAL_BUILT_MODULE)
-built_system_ext_cil_$(PLATFORM_SEPOLICY_VERSION) := $(built_system_ext_cil)
-system_ext_policy.conf :=
-endif # ifdef HAS_SYSTEM_EXT_SEPOLICY
-
-#################################
-include $(CLEAR_VARS)
-
-ifdef HAS_PRODUCT_SEPOLICY
-LOCAL_MODULE := product_sepolicy.cil
-LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 legacy_unencumbered
-LOCAL_LICENSE_CONDITIONS := notice unencumbered
-LOCAL_NOTICE_FILE := $(LOCAL_PATH)/NOTICE
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT)/etc/selinux
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-# product_policy.conf - A combination of the private and public product policy
-# which will ship with the device. Product policy is not attributized.
-policy_files := $(call build_policy, $(sepolicy_build_files), \
-  $(PLAT_PUBLIC_POLICY) $(PLAT_PRIVATE_POLICY) \
-  $(SYSTEM_EXT_PUBLIC_POLICY) $(SYSTEM_EXT_PRIVATE_POLICY) \
-  $(PRODUCT_PUBLIC_POLICY) $(PRODUCT_PRIVATE_POLICY))
-product_policy.conf := $(intermediates)/product_policy.conf
-$(product_policy.conf): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(product_policy.conf): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(product_policy.conf): PRIVATE_TARGET_BUILD_VARIANT := $(TARGET_BUILD_VARIANT)
-$(product_policy.conf): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(product_policy.conf): PRIVATE_TGT_WITH_ASAN := $(with_asan)
-$(product_policy.conf): PRIVATE_TGT_WITH_NATIVE_COVERAGE := $(with_native_coverage)
-$(product_policy.conf): PRIVATE_ADDITIONAL_M4DEFS := $(LOCAL_ADDITIONAL_M4DEFS)
-$(product_policy.conf): PRIVATE_SEPOLICY_SPLIT := $(PRODUCT_SEPOLICY_SPLIT)
-$(product_policy.conf): PRIVATE_COMPATIBLE_PROPERTY := $(PRODUCT_COMPATIBLE_PROPERTY)
-$(product_policy.conf): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := $(treble_sysprop_neverallow)
-$(product_policy.conf): PRIVATE_ENFORCE_SYSPROP_OWNER := $(enforce_sysprop_owner)
-$(product_policy.conf): PRIVATE_POLICY_FILES := $(policy_files)
-$(product_policy.conf): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-	$(hide) sed '/dontaudit/d' $@ > $@.dontaudit
-
-$(LOCAL_BUILT_MODULE): PRIVATE_NEVERALLOW_ARG := $(NEVERALLOW_ARG)
-$(LOCAL_BUILT_MODULE): PRIVATE_PLAT_CIL_FILES := $(built_plat_cil) $(built_system_ext_cil)
-$(LOCAL_BUILT_MODULE): $(product_policy.conf) $(HOST_OUT_EXECUTABLES)/checkpolicy \
-$(HOST_OUT_EXECUTABLES)/build_sepolicy $(HOST_OUT_EXECUTABLES)/secilc \
-$(built_plat_cil) $(built_system_ext_cil)
-	@mkdir -p $(dir $@)
-	$(hide) $(CHECKPOLICY_ASAN_OPTIONS) $(HOST_OUT_EXECUTABLES)/checkpolicy -M -C -c \
-	$(POLICYVERS) -o $@ $<
-	$(hide) $(HOST_OUT_EXECUTABLES)/build_sepolicy -a $(HOST_OUT_EXECUTABLES) filter_out \
-		-f $(PRIVATE_PLAT_CIL_FILES) -t $@
-	# Line markers (denoted by ;;) are malformed after above cmd. They are only
-	# used for debugging, so we remove them.
-	$(hide) grep -v ';;' $@ > $@.tmp
-	$(hide) mv $@.tmp $@
-	# Combine plat_sepolicy.cil, system_ext_sepolicy.cil and product_sepolicy.cil to
-	# make sure that the latter doesn't accidentally depend on vendor/odm policies.
-	$(hide) $(HOST_OUT_EXECUTABLES)/secilc -m -M true -G -c $(POLICYVERS) \
-		$(PRIVATE_NEVERALLOW_ARG) $(PRIVATE_PLAT_CIL_FILES) $@ -o /dev/null -f /dev/null
-
-
-built_product_cil := $(LOCAL_BUILT_MODULE)
-built_product_cil_$(PLATFORM_SEPOLICY_VERSION) := $(built_product_cil)
-product_policy.conf :=
-endif # ifdef HAS_PRODUCT_SEPOLICY
-
-#################################
-include $(CLEAR_VARS)
-
 LOCAL_MODULE := plat_sepolicy_vers.txt
 LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 legacy_unencumbered
 LOCAL_LICENSE_CONDITIONS := notice unencumbered
@@ -1688,38 +1393,6 @@
 sepolicy.recovery.conf :=
 
 ##################################
-# SELinux policy embedded into CTS.
-# CTS checks neverallow rules of this policy against the policy of the device under test.
-##################################
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := general_sepolicy.conf
-LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 legacy_unencumbered
-LOCAL_LICENSE_CONDITIONS := notice unencumbered
-LOCAL_NOTICE_FILE := $(LOCAL_PATH)/NOTICE
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_TAGS := tests
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-policy_files := $(call build_policy, $(sepolicy_build_files), \
-  $(PLAT_PUBLIC_POLICY) $(PLAT_PRIVATE_POLICY))
-$(LOCAL_BUILT_MODULE): PRIVATE_MLS_SENS := $(MLS_SENS)
-$(LOCAL_BUILT_MODULE): PRIVATE_MLS_CATS := $(MLS_CATS)
-$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_BUILD_VARIANT := user
-$(LOCAL_BUILT_MODULE): PRIVATE_TGT_ARCH := $(my_target_arch)
-$(LOCAL_BUILT_MODULE): PRIVATE_WITH_ASAN := false
-$(LOCAL_BUILT_MODULE): PRIVATE_SEPOLICY_SPLIT := cts
-$(LOCAL_BUILT_MODULE): PRIVATE_COMPATIBLE_PROPERTY := cts
-$(LOCAL_BUILT_MODULE): PRIVATE_TREBLE_SYSPROP_NEVERALLOW := cts
-$(LOCAL_BUILT_MODULE): PRIVATE_ENFORCE_SYSPROP_OWNER := cts
-$(LOCAL_BUILT_MODULE): PRIVATE_EXCLUDE_BUILD_TEST := true
-$(LOCAL_BUILT_MODULE): PRIVATE_POLICY_FILES := $(policy_files)
-$(LOCAL_BUILT_MODULE): $(policy_files) $(M4)
-	$(transform-policy-to-conf)
-	$(hide) sed '/^\s*dontaudit.*;/d' $@ | sed '/^\s*dontaudit/,/;/d' > $@.dontaudit
-
-##################################
 # TODO - remove this.   Keep around until we get the filesystem creation stuff taken care of.
 #
 include $(CLEAR_VARS)
diff --git a/build/soong/Android.bp b/build/soong/Android.bp
index 54173e0..4e1d27a 100644
--- a/build/soong/Android.bp
+++ b/build/soong/Android.bp
@@ -34,6 +34,7 @@
         "build_files.go",
         "cil_compat_map.go",
         "filegroup.go",
+        "policy.go",
         "selinux.go",
         "selinux_contexts.go",
     ],
diff --git a/build/soong/policy.go b/build/soong/policy.go
new file mode 100644
index 0000000..caeb6eb
--- /dev/null
+++ b/build/soong/policy.go
@@ -0,0 +1,349 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package selinux
+
+import (
+	"fmt"
+	"os"
+	"strconv"
+
+	"github.com/google/blueprint/proptools"
+
+	"android/soong/android"
+)
+
+const (
+	// TODO: sync with Android.mk
+	MlsSens    = 1
+	MlsCats    = 1024
+	PolicyVers = 30
+)
+
+func init() {
+	android.RegisterModuleType("se_policy_conf", policyConfFactory)
+	android.RegisterModuleType("se_policy_cil", policyCilFactory)
+}
+
+type policyConfProperties struct {
+	// Name of the output. Default is {module_name}
+	Stem *string
+
+	// Policy files to be compiled to cil file.
+	Srcs []string `android:"path"`
+
+	// Target build variant (user / userdebug / eng). Default follows the current lunch target
+	Build_variant *string
+
+	// Whether to exclude build test or not. Default is false
+	Exclude_build_test *bool
+
+	// Whether to include asan specific policies or not. Default follows the current lunch target
+	With_asan *bool
+
+	// Whether to build CTS specific policy or not. Default is false
+	Cts *bool
+
+	// Whether this module is directly installable to one of the partitions. Default is true
+	Installable *bool
+}
+
+type policyConf struct {
+	android.ModuleBase
+
+	properties policyConfProperties
+
+	installSource android.Path
+	installPath   android.InstallPath
+}
+
+// se_policy_conf merges collection of policy files into a policy.conf file to be processed by
+// checkpolicy.
+func policyConfFactory() android.Module {
+	c := &policyConf{}
+	c.AddProperties(&c.properties)
+	android.InitAndroidArchModule(c, android.DeviceSupported, android.MultilibCommon)
+	return c
+}
+
+func (c *policyConf) installable() bool {
+	return proptools.BoolDefault(c.properties.Installable, true)
+}
+
+func (c *policyConf) stem() string {
+	return proptools.StringDefault(c.properties.Stem, c.Name())
+}
+
+func (c *policyConf) buildVariant(ctx android.ModuleContext) string {
+	if variant := proptools.String(c.properties.Build_variant); variant != "" {
+		return variant
+	}
+	if ctx.Config().Eng() {
+		return "eng"
+	}
+	if ctx.Config().Debuggable() {
+		return "userdebug"
+	}
+	return "user"
+}
+
+func (c *policyConf) cts() bool {
+	return proptools.Bool(c.properties.Cts)
+}
+
+func (c *policyConf) withAsan(ctx android.ModuleContext) string {
+	isAsanDevice := android.InList("address", ctx.Config().SanitizeDevice())
+	return strconv.FormatBool(proptools.BoolDefault(c.properties.With_asan, isAsanDevice))
+}
+
+func (c *policyConf) sepolicySplit(ctx android.ModuleContext) string {
+	if c.cts() {
+		return "cts"
+	}
+	return strconv.FormatBool(ctx.DeviceConfig().SepolicySplit())
+}
+
+func (c *policyConf) compatibleProperty(ctx android.ModuleContext) string {
+	if c.cts() {
+		return "cts"
+	}
+	return "true"
+}
+
+func (c *policyConf) trebleSyspropNeverallow(ctx android.ModuleContext) string {
+	if c.cts() {
+		return "cts"
+	}
+	return strconv.FormatBool(!ctx.DeviceConfig().BuildBrokenTrebleSyspropNeverallow())
+}
+
+func (c *policyConf) enforceSyspropOwner(ctx android.ModuleContext) string {
+	if c.cts() {
+		return "cts"
+	}
+	return strconv.FormatBool(!ctx.DeviceConfig().BuildBrokenEnforceSyspropOwner())
+}
+
+func (c *policyConf) transformPolicyToConf(ctx android.ModuleContext) android.OutputPath {
+	conf := android.PathForModuleOut(ctx, "conf").OutputPath
+	rule := android.NewRuleBuilder(pctx, ctx)
+	rule.Command().Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
+		Flag("--fatal-warnings").
+		FlagForEachArg("-D ", ctx.DeviceConfig().SepolicyM4Defs()).
+		FlagWithArg("-D mls_num_sens=", strconv.Itoa(MlsSens)).
+		FlagWithArg("-D mls_num_cats=", strconv.Itoa(MlsCats)).
+		FlagWithArg("-D target_arch=", ctx.DeviceConfig().DeviceArch()).
+		FlagWithArg("-D target_with_asan=", c.withAsan(ctx)).
+		FlagWithArg("-D target_with_native_coverage=", strconv.FormatBool(ctx.DeviceConfig().ClangCoverageEnabled() || ctx.DeviceConfig().GcovCoverageEnabled())).
+		FlagWithArg("-D target_build_variant=", c.buildVariant(ctx)).
+		FlagWithArg("-D target_full_treble=", c.sepolicySplit(ctx)).
+		FlagWithArg("-D target_compatible_property=", c.compatibleProperty(ctx)).
+		FlagWithArg("-D target_treble_sysprop_neverallow=", c.trebleSyspropNeverallow(ctx)).
+		FlagWithArg("-D target_enforce_sysprop_owner=", c.enforceSyspropOwner(ctx)).
+		FlagWithArg("-D target_exclude_build_test=", strconv.FormatBool(proptools.Bool(c.properties.Exclude_build_test))).
+		FlagWithArg("-D target_requires_insecure_execmem_for_swiftshader=", strconv.FormatBool(ctx.DeviceConfig().RequiresInsecureExecmemForSwiftshader())).
+		Flag("-s").
+		Inputs(android.PathsForModuleSrc(ctx, c.properties.Srcs)).
+		Text("> ").Output(conf)
+
+	rule.Build("conf", "Transform policy to conf: "+ctx.ModuleName())
+	return conf
+}
+
+func (c *policyConf) DepsMutator(ctx android.BottomUpMutatorContext) {
+	// do nothing
+}
+
+func (c *policyConf) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	c.installSource = c.transformPolicyToConf(ctx)
+	c.installPath = android.PathForModuleInstall(ctx, "etc")
+	ctx.InstallFile(c.installPath, c.stem(), c.installSource)
+
+	if !c.installable() {
+		c.SkipInstall()
+	}
+}
+
+func (c *policyConf) AndroidMkEntries() []android.AndroidMkEntries {
+	return []android.AndroidMkEntries{android.AndroidMkEntries{
+		OutputFile: android.OptionalPathForPath(c.installSource),
+		Class:      "ETC",
+		ExtraEntries: []android.AndroidMkExtraEntriesFunc{
+			func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
+				entries.SetBool("LOCAL_UNINSTALLABLE_MODULE", !c.installable())
+				entries.SetPath("LOCAL_MODULE_PATH", c.installPath.ToMakePath())
+				entries.SetString("LOCAL_INSTALLED_MODULE_STEM", c.stem())
+			},
+		},
+	}}
+}
+
+func (c *policyConf) OutputFiles(tag string) (android.Paths, error) {
+	if tag == "" {
+		return android.Paths{c.installSource}, nil
+	}
+	return nil, fmt.Errorf("Unknown tag %q", tag)
+}
+
+var _ android.OutputFileProducer = (*policyConf)(nil)
+
+type policyCilProperties struct {
+	// Name of the output. Default is {module_name}
+	Stem *string
+
+	// Policy file to be compiled to cil file.
+	Src *string `android:"path"`
+
+	// Additional cil files to be added in the end of the output. This is to support workarounds
+	// which are not supported by the policy language.
+	Additional_cil_files []string `android:"path"`
+
+	// Cil files to be filtered out by the filter_out tool of "build_sepolicy". Used to build
+	// exported policies
+	Filter_out []string `android:"path"`
+
+	// Whether to remove line markers (denoted by ;;) out of compiled cil files. Defaults to false
+	Remove_line_marker *bool
+
+	// Whether to run secilc to check compiled policy or not. Defaults to true
+	Secilc_check *bool
+
+	// Whether to ignore neverallow when running secilc check. Defaults to
+	// SELINUX_IGNORE_NEVERALLOWS.
+	Ignore_neverallow *bool
+
+	// Whether this module is directly installable to one of the partitions. Default is true
+	Installable *bool
+}
+
+type policyCil struct {
+	android.ModuleBase
+
+	properties policyCilProperties
+
+	installSource android.Path
+	installPath   android.InstallPath
+}
+
+// se_policy_cil compiles a policy.conf file to a cil file with checkpolicy, and optionally runs
+// secilc to check the output cil file. Affected by SELINUX_IGNORE_NEVERALLOWS.
+func policyCilFactory() android.Module {
+	c := &policyCil{}
+	c.AddProperties(&c.properties)
+	android.InitAndroidArchModule(c, android.DeviceSupported, android.MultilibCommon)
+	return c
+}
+
+func (c *policyCil) Installable() bool {
+	return proptools.BoolDefault(c.properties.Installable, true)
+}
+
+func (c *policyCil) stem() string {
+	return proptools.StringDefault(c.properties.Stem, c.Name())
+}
+
+func (c *policyCil) compileConfToCil(ctx android.ModuleContext, conf android.Path) android.OutputPath {
+	cil := android.PathForModuleOut(ctx, c.stem()).OutputPath
+	rule := android.NewRuleBuilder(pctx, ctx)
+	rule.Command().BuiltTool("checkpolicy").
+		Flag("-C"). // Write CIL
+		Flag("-M"). // Enable MLS
+		FlagWithArg("-c ", strconv.Itoa(PolicyVers)).
+		FlagWithOutput("-o ", cil).
+		Input(conf)
+
+	if len(c.properties.Additional_cil_files) > 0 {
+		rule.Command().Text("cat").
+			Inputs(android.PathsForModuleSrc(ctx, c.properties.Additional_cil_files)).
+			Text(">> ").Output(cil)
+	}
+
+	if len(c.properties.Filter_out) > 0 {
+		rule.Command().BuiltTool("build_sepolicy").
+			Text("filter_out").
+			Flag("-f").
+			Inputs(android.PathsForModuleSrc(ctx, c.properties.Filter_out)).
+			FlagWithOutput("-t ", cil)
+	}
+
+	if proptools.Bool(c.properties.Remove_line_marker) {
+		rule.Command().Text("grep -v").
+			Text(proptools.ShellEscape(";;")).
+			Text(cil.String()).
+			Text(">").
+			Text(cil.String() + ".tmp").
+			Text("&& mv").
+			Text(cil.String() + ".tmp").
+			Text(cil.String())
+	}
+
+	if proptools.BoolDefault(c.properties.Secilc_check, true) {
+		secilcCmd := rule.Command().BuiltTool("secilc").
+			Flag("-m").                 // Multiple decls
+			FlagWithArg("-M ", "true"). // Enable MLS
+			Flag("-G").                 // expand and remove auto generated attributes
+			FlagWithArg("-c ", strconv.Itoa(PolicyVers)).
+			Inputs(android.PathsForModuleSrc(ctx, c.properties.Filter_out)). // Also add cil files which are filtered out
+			Text(cil.String()).
+			FlagWithArg("-o ", os.DevNull).
+			FlagWithArg("-f ", os.DevNull)
+
+		if proptools.BoolDefault(c.properties.Ignore_neverallow, ctx.Config().SelinuxIgnoreNeverallows()) {
+			secilcCmd.Flag("-N")
+		}
+	}
+
+	rule.Build("cil", "Building cil for "+ctx.ModuleName())
+	return cil
+}
+
+func (c *policyCil) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	if proptools.String(c.properties.Src) == "" {
+		ctx.PropertyErrorf("src", "must be specified")
+		return
+	}
+	conf := android.PathForModuleSrc(ctx, *c.properties.Src)
+	cil := c.compileConfToCil(ctx, conf)
+
+	c.installPath = android.PathForModuleInstall(ctx, "etc", "selinux")
+	c.installSource = cil
+	ctx.InstallFile(c.installPath, c.stem(), c.installSource)
+
+	if !c.Installable() {
+		c.SkipInstall()
+	}
+}
+
+func (c *policyCil) AndroidMkEntries() []android.AndroidMkEntries {
+	return []android.AndroidMkEntries{android.AndroidMkEntries{
+		OutputFile: android.OptionalPathForPath(c.installSource),
+		Class:      "ETC",
+		ExtraEntries: []android.AndroidMkExtraEntriesFunc{
+			func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
+				entries.SetBool("LOCAL_UNINSTALLABLE_MODULE", !c.Installable())
+				entries.SetPath("LOCAL_MODULE_PATH", c.installPath.ToMakePath())
+				entries.SetString("LOCAL_INSTALLED_MODULE_STEM", c.stem())
+			},
+		},
+	}}
+}
+
+func (c *policyCil) OutputFiles(tag string) (android.Paths, error) {
+	if tag == "" {
+		return android.Paths{c.installSource}, nil
+	}
+	return nil, fmt.Errorf("Unknown tag %q", tag)
+}
+
+var _ android.OutputFileProducer = (*policyCil)(nil)
diff --git a/private/credstore.te b/private/credstore.te
index a1c3263..8d87e2f 100644
--- a/private/credstore.te
+++ b/private/credstore.te
@@ -4,6 +4,3 @@
 
 # talk to Identity Credential
 hal_client_domain(credstore, hal_identity)
-
-# TODO Remove this property when Keystore 2.0 migration is complete b/171563717
-get_prop(credstore, keystore2_enable_prop)
diff --git a/private/init.te b/private/init.te
index c652603..2627add 100644
--- a/private/init.te
+++ b/private/init.te
@@ -38,6 +38,9 @@
 # that userdata is mounted onto.
 allow init sysfs_dm:file read;
 
+# Allow init to write to the drop_caches file.
+allow init proc_drop_caches:file rw_file_perms;
+
 # Allow the BoringSSL self test to request a reboot upon failure
 set_prop(init, powerctl_prop)
 
diff --git a/private/odsign.te b/private/odsign.te
index b35a3ca..0ff3b7b 100644
--- a/private/odsign.te
+++ b/private/odsign.te
@@ -50,6 +50,10 @@
 # Run fsverity_init to add key to fsverity keyring
 domain_auto_trans(odsign, fsverity_init_exec, fsverity_init)
 
+# only odsign can set odsign sysprop
+set_prop(odsign, odsign_prop)
+neverallow { domain -odsign -init } odsign_prop:property_service set;
+
 # Neverallows
 neverallow { domain -odsign -init -fsverity_init } odsign_data_file:dir *;
 neverallow { domain -odsign -init -fsverity_init } odsign_data_file:file *;
diff --git a/private/property.te b/private/property.te
index d9cc93c..2f5fcde 100644
--- a/private/property.te
+++ b/private/property.te
@@ -22,6 +22,8 @@
 system_internal_prop(net_464xlat_fromvendor_prop)
 system_internal_prop(net_connectivity_prop)
 system_internal_prop(netd_stable_secret_prop)
+system_internal_prop(odsign_prop)
+system_internal_prop(perf_drop_caches_prop)
 system_internal_prop(pm_prop)
 system_internal_prop(rollback_test_prop)
 system_internal_prop(setupwizard_prop)
@@ -33,9 +35,6 @@
 system_internal_prop(verity_status_prop)
 system_internal_prop(zygote_wrap_prop)
 
-# TODO Remove this property when Keystore 2.0 migration is complete b/171563717
-system_internal_prop(keystore2_enable_prop)
-
 ###
 ### Neverallow rules
 ###
@@ -540,17 +539,6 @@
   lower_kptr_restrict_prop
 }:property_service set;
 
-# TODO Remove this property when Keystore 2.0 migration is complete b/171563717
-neverallow {
-  domain
-  -init
-  -dumpstate
-  -system_app
-  -system_server
-  -zygote
-  -credstore
-} keystore2_enable_prop:file no_rw_file_perms;
-
 neverallow {
   domain
   -init
@@ -602,15 +590,3 @@
   -init
   -shell
 } rollback_test_prop:property_service set;
-
-# Only init and vendor_init are allowed to set apexd_config_prop
-neverallow { domain -init -vendor_init } apexd_config_prop:property_service set;
-
-# apexd_config properties should only be read by apexd, and dumpstate (to appear in bugreports).
-neverallow {
-  domain
-  -apexd
-  -init
-  -dumpstate
-  -vendor_init
-} apexd_config_prop:file no_rw_file_perms;
diff --git a/private/property_contexts b/private/property_contexts
index 172b656..7fb26fb 100644
--- a/private/property_contexts
+++ b/private/property_contexts
@@ -187,7 +187,7 @@
 ro.dalvik.              u:object_r:dalvik_prop:s0
 
 # qemu_hw_prop is read/written by both system and vendor.
-qemu.hw.mainkeys        u:object_r:qemu_hw_prop:s0
+qemu.hw.mainkeys        u:object_r:qemu_hw_prop:s0 exact string
 
 # qemu_sf_lcd_density_prop is read/written by both system and vendor.
 qemu.sf.lcd_density     u:object_r:qemu_sf_lcd_density_prop:s0 exact int
@@ -260,6 +260,10 @@
 # Property that is set once ueventd finishes cold boot.
 ro.cold_boot_done       u:object_r:cold_boot_done_prop:s0
 
+# Properties that control performance operations.
+# Leave space to later set drop_caches to 1, 2, and 4.
+perf.drop_caches        u:object_r:perf_drop_caches_prop:s0 exact enum 0 3
+
 # Charger properties
 ro.charger.                 u:object_r:charger_prop:s0
 sys.boot_from_charger_mode  u:object_r:charger_status_prop:s0 exact int
@@ -546,6 +550,10 @@
 
 apexd.status u:object_r:apexd_prop:s0 exact enum starting activated ready
 
+odsign.key.done u:object_r:odsign_prop:s0 exact bool
+odsign.verification.done u:object_r:odsign_prop:s0 exact bool
+odsign.verification.success u:object_r:odsign_prop:s0 exact bool
+
 dev.bootcomplete   u:object_r:boot_status_prop:s0 exact bool
 sys.boot_completed u:object_r:boot_status_prop:s0 exact bool
 
@@ -809,6 +817,9 @@
 ro.product.vendor.model        u:object_r:build_vendor_prop:s0 exact string
 ro.product.vendor.name         u:object_r:build_vendor_prop:s0 exact string
 
+# GRF property for the first api level of the vendor partition
+ro.board.first_api_level u:object_r:build_vendor_prop:s0 exact int
+
 # Boot image build props set by /{second_stage_resources/,}boot/etc/build.prop
 ro.bootimage.build.date                        u:object_r:build_bootimage_prop:s0 exact string
 ro.bootimage.build.date.utc                    u:object_r:build_bootimage_prop:s0 exact int
@@ -1081,10 +1092,6 @@
 
 ro.zygote.disable_gl_preload u:object_r:zygote_config_prop:s0 exact bool
 
-# Enable Keystore 2.0.
-# TODO remove this property when Keystore 2.0 migration is complete b/171563717
-persist.android.security.keystore2.enable    u:object_r:keystore2_enable_prop:s0 exact bool
-
 # Broadcast boot stages, which keystore listens to
 keystore.boot_level u:object_r:keystore_listen_prop:s0 exact int
 
diff --git a/private/shell.te b/private/shell.te
index a99ada8..66e2d4d 100644
--- a/private/shell.te
+++ b/private/shell.te
@@ -121,6 +121,7 @@
 set_prop(shell, dumpstate_prop)
 set_prop(shell, exported_dumpstate_prop)
 set_prop(shell, debug_prop)
+set_prop(shell, perf_drop_caches_prop)
 set_prop(shell, powerctl_prop)
 set_prop(shell, log_tag_prop)
 set_prop(shell, wifi_log_prop)
@@ -189,3 +190,7 @@
 
 # Allow shell to read Virtual A/B related properties
 get_prop(shell, virtual_ab_prop)
+
+# Never allow others to set or get the perf.drop_caches property.
+neverallow { domain -shell -init } perf_drop_caches_prop:property_service set;
+neverallow { domain -shell -init -dumpstate } perf_drop_caches_prop:file read;
diff --git a/private/system_app.te b/private/system_app.te
index 36208bf..58322b8 100644
--- a/private/system_app.te
+++ b/private/system_app.te
@@ -172,9 +172,6 @@
 # Settings app reads ro.oem_unlock_supported
 get_prop(system_app, oem_unlock_prop)
 
-# TODO Remove this property when Keystore 2.0 migration is complete b/171563717
-get_prop(system_app, keystore2_enable_prop)
-
 ###
 ### Neverallow rules
 ###
diff --git a/private/system_server.te b/private/system_server.te
index bfb7fef..084ea22 100644
--- a/private/system_server.te
+++ b/private/system_server.te
@@ -1290,9 +1290,6 @@
 # Read/Write /proc/pressure/memory
 allow system_server proc_pressure_mem:file rw_file_perms;
 
-# TODO Remove this property when Keystore 2.0 migration is complete b/171563717
-get_prop(system_server, keystore2_enable_prop)
-
 # dexoptanalyzer is currently used only for secondary dex files which
 # system_server should never access.
 neverallow system_server dexoptanalyzer_exec:file no_x_file_perms;
diff --git a/private/zygote.te b/private/zygote.te
index e78e070..c2c6e89 100644
--- a/private/zygote.te
+++ b/private/zygote.te
@@ -223,9 +223,6 @@
 # Allow zygote to read /apex/apex-info-list.xml
 allow zygote apex_info_file:file r_file_perms;
 
-# TODO Remove this property when Keystore 2.0 migration is complete b/171563717
-get_prop(zygote, keystore2_enable_prop)
-
 ###
 ### neverallow rules
 ###
diff --git a/public/service.te b/public/service.te
index 29d4933..229131c 100644
--- a/public/service.te
+++ b/public/service.te
@@ -99,7 +99,7 @@
 type devicestoragemonitor_service, system_server_service, service_manager_type;
 type diskstats_service, system_api_service, system_server_service, service_manager_type;
 type display_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
-type domain_verification_service, system_api_service, system_server_service, service_manager_type;
+type domain_verification_service, app_api_service, system_server_service, service_manager_type;
 type color_display_service, system_api_service, system_server_service, service_manager_type;
 type external_vibrator_service, system_server_service, service_manager_type;
 type file_integrity_service, app_api_service, system_server_service, service_manager_type;
@@ -135,7 +135,7 @@
 type light_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type location_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type location_time_zone_manager_service, system_server_service, service_manager_type;
-type lock_settings_service, system_api_service, system_server_service, service_manager_type;
+type lock_settings_service, app_api_service, system_api_service, system_server_service, service_manager_type;
 type looper_stats_service, system_server_service, service_manager_type;
 type media_communication_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type media_metrics_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;