Merge "Revert "Revert "More neverallow rules"""
diff --git a/Android.bp b/Android.bp
index 9a13c9c..d22010c 100644
--- a/Android.bp
+++ b/Android.bp
@@ -661,6 +661,14 @@
     ],
 }
 
+reqd_mask_policy          = [":se_build_files{.reqd_mask}"]
+plat_public_policy        = [":se_build_files{.plat_public}"]
+plat_private_policy       = [":se_build_files{.plat_private}"]
+system_ext_public_policy  = [":se_build_files{.system_ext_public}"]
+system_ext_private_policy = [":se_build_files{.system_ext_private}"]
+product_public_policy     = [":se_build_files{.product_public}"]
+product_private_policy    = [":se_build_files{.product_private}"]
+
 // reqd_policy_mask - a policy.conf file which contains only the bare minimum
 // policy necessary to use checkpolicy.
 //
@@ -671,7 +679,7 @@
 // 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}"],
+    srcs: reqd_mask_policy,
     installable: false,
 }
 
@@ -706,7 +714,10 @@
 //
 se_policy_conf {
     name: "pub_policy.conf",
-    srcs: [":se_build_files{.product_public}"], // product_ includes system and system_ext
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        product_public_policy +
+        reqd_mask_policy,
     installable: false,
 }
 
@@ -720,7 +731,9 @@
 
 se_policy_conf {
     name: "system_ext_pub_policy.conf",
-    srcs: [":se_build_files{.system_ext_public}"], // system_ext_public includes system
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        reqd_mask_policy,
     installable: false,
 }
 
@@ -734,7 +747,8 @@
 
 se_policy_conf {
     name: "plat_pub_policy.conf",
-    srcs: [":se_build_files{.plat_public}"],
+    srcs: plat_public_policy +
+        reqd_mask_policy,
     installable: false,
 }
 
@@ -753,7 +767,8 @@
 // currently being attributized.
 se_policy_conf {
     name: "plat_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     installable: false,
 }
 
@@ -766,7 +781,8 @@
 // userdebug_plat_policy.conf - the userdebug version plat_sepolicy.cil
 se_policy_conf {
     name: "userdebug_plat_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     build_variant: "userdebug",
     installable: false,
 }
@@ -815,7 +831,10 @@
 // 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}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy,
     installable: false,
 }
 
@@ -831,7 +850,12 @@
 // which will ship with the device. Product policy is not attributized
 se_policy_conf {
     name: "product_sepolicy.conf",
-    srcs: [":se_build_files{.product}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy +
+        product_public_policy +
+        product_private_policy,
     installable: false,
 }
 
@@ -1017,7 +1041,8 @@
 //////////////////////////////////
 se_policy_conf {
     name: "general_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     build_variant: "user",
     cts: true,
     exclude_build_test: true,
@@ -1032,7 +1057,8 @@
 //////////////////////////////////
 se_policy_conf {
     name: "base_plat_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1053,7 +1079,10 @@
 
 se_policy_conf {
     name: "base_system_ext_sepolicy.conf",
-    srcs: [":se_build_files{.system_ext}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1076,7 +1105,12 @@
 
 se_policy_conf {
     name: "base_product_sepolicy.conf",
-    srcs: [":se_build_files{.product}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy +
+        product_public_policy +
+        product_private_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1099,7 +1133,8 @@
 
 se_policy_conf {
     name: "base_plat_pub_policy.conf",
-    srcs: [":se_build_files{.plat_public}"],
+    srcs: plat_public_policy +
+        reqd_mask_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1114,7 +1149,9 @@
 
 se_policy_conf {
     name: "base_system_ext_pub_policy.conf",
-    srcs: [":se_build_files{.system_ext_public}"], // system_ext_public includes system
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        reqd_mask_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1129,7 +1166,10 @@
 
 se_policy_conf {
     name: "base_product_pub_policy.conf",
-    srcs: [":se_build_files{.product_public}"], // product_ includes system and system_ext
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        product_public_policy +
+        reqd_mask_policy,
     build_variant: "user",
     installable: false,
 }
diff --git a/build/soong/build_files.go b/build/soong/build_files.go
index 5de6122..8f77e4f 100644
--- a/build/soong/build_files.go
+++ b/build/soong/build_files.go
@@ -17,7 +17,6 @@
 import (
 	"fmt"
 	"path/filepath"
-	"sort"
 	"strings"
 
 	"android/soong/android"
@@ -29,8 +28,8 @@
 
 // se_build_files gathers policy files from sepolicy dirs, and acts like a filegroup. A tag with
 // partition(plat, system_ext, product) and scope(public, private) is used to select directories.
-// Supported tags are: "plat", "plat_public", "system_ext", "system_ext_public", "product",
-// "product_public", and "reqd_mask".
+// Supported tags are: "plat_public", "plat_private", "system_ext_public", "system_ext_private",
+// "product_public", "product_private", and "reqd_mask".
 func buildFilesFactory() android.Module {
 	module := &buildFiles{}
 	module.AddProperties(&module.properties)
@@ -86,114 +85,18 @@
 
 var _ android.OutputFileProducer = (*buildFiles)(nil)
 
-type partition int
-
-const (
-	system partition = iota
-	system_ext
-	product
-)
-
-type scope int
-
-const (
-	public scope = iota
-	private
-)
-
 type sepolicyDir struct {
-	partition partition
-	scope     scope
-	paths     []string
-}
-
-func (p partition) String() string {
-	switch p {
-	case system:
-		return "plat"
-	case system_ext:
-		return "system_ext"
-	case product:
-		return "product"
-	default:
-		panic(fmt.Sprintf("Unknown partition %#v", p))
-	}
+	tag   string
+	paths []string
 }
 
 func (b *buildFiles) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-	// Sepolicy directories should be included in the following order.
-	//   - system_public
-	//   - system_private
-	//   - system_ext_public
-	//   - system_ext_private
-	//   - product_public
-	//   - product_private
-	dirs := []sepolicyDir{
-		sepolicyDir{partition: system, scope: public, paths: []string{filepath.Join(ctx.ModuleDir(), "public")}},
-		sepolicyDir{partition: system, scope: private, paths: []string{filepath.Join(ctx.ModuleDir(), "private")}},
-		sepolicyDir{partition: system_ext, scope: public, paths: ctx.DeviceConfig().SystemExtPublicSepolicyDirs()},
-		sepolicyDir{partition: system_ext, scope: private, paths: ctx.DeviceConfig().SystemExtPrivateSepolicyDirs()},
-		sepolicyDir{partition: product, scope: public, paths: ctx.Config().ProductPublicSepolicyDirs()},
-		sepolicyDir{partition: product, scope: private, paths: ctx.Config().ProductPrivateSepolicyDirs()},
-	}
-
-	if !sort.SliceIsSorted(dirs, func(i, j int) bool {
-		if dirs[i].partition != dirs[j].partition {
-			return dirs[i].partition < dirs[j].partition
-		}
-
-		return dirs[i].scope < dirs[j].scope
-	}) {
-		panic("dirs is not sorted")
-	}
-
-	// Exported cil policy files are built with the following policies.
-	//
-	//   - plat_pub_policy.cil: exported 'system'
-	//   - system_ext_pub_policy.cil: exported 'system' and 'system_ext'
-	//   - pub_policy.cil: exported 'system', 'system_ext', and 'product'
-	//
-	// cil policy files are built with the following policies.
-	//
-	//   - plat_policy.cil: 'system', including private
-	//   - system_ext_policy.cil: 'system_ext', including private
-	//   - product_sepolicy.cil: 'product', including private
-	//
-	// gatherDirsFor collects all needed directories for given partition and scope. For example,
-	//
-	//   - gatherDirsFor(system_ext, private) will return system + system_ext (including private)
-	//   - gatherDirsFor(product, public) will return system + system_ext + product (public only)
-	//
-	// "dirs" should be sorted before calling this.
-	gatherDirsFor := func(p partition, s scope) []string {
-		var ret []string
-
-		for _, d := range dirs {
-			if d.partition <= p && d.scope <= s {
-				ret = append(ret, d.paths...)
-			}
-		}
-
-		return ret
-	}
-
-	reqdMaskDir := filepath.Join(ctx.ModuleDir(), "reqd_mask")
-
 	b.srcs = make(map[string]android.Paths)
-	b.srcs[".reqd_mask"] = b.findSrcsInDirs(ctx, reqdMaskDir)
-
-	for _, p := range []partition{system, system_ext, product} {
-		b.srcs["."+p.String()] = b.findSrcsInDirs(ctx, gatherDirsFor(p, private)...)
-
-		// reqd_mask is needed for public policies
-		b.srcs["."+p.String()+"_public"] = b.findSrcsInDirs(ctx, append(gatherDirsFor(p, public), reqdMaskDir)...)
-	}
-
-	// A special tag, "plat_vendor", includes minimized vendor policies required to boot.
-	//   - system/sepolicy/public
-	//   - system/sepolicy/reqd_mask
-	//   - system/sepolicy/vendor
-	// This is for minimized vendor partition, e.g. microdroid's vendor
-	platVendorDir := filepath.Join(ctx.ModuleDir(), "vendor")
-	b.srcs[".plat_vendor"] = b.findSrcsInDirs(ctx, append(gatherDirsFor(system, public), reqdMaskDir, platVendorDir)...)
+	b.srcs[".reqd_mask"] = b.findSrcsInDirs(ctx, filepath.Join(ctx.ModuleDir(), "reqd_mask"))
+	b.srcs[".plat_public"] = b.findSrcsInDirs(ctx, filepath.Join(ctx.ModuleDir(), "public"))
+	b.srcs[".plat_private"] = b.findSrcsInDirs(ctx, filepath.Join(ctx.ModuleDir(), "private"))
+	b.srcs[".system_ext_public"] = b.findSrcsInDirs(ctx, ctx.DeviceConfig().SystemExtPublicSepolicyDirs()...)
+	b.srcs[".system_ext_private"] = b.findSrcsInDirs(ctx, ctx.DeviceConfig().SystemExtPrivateSepolicyDirs()...)
+	b.srcs[".product_public"] = b.findSrcsInDirs(ctx, ctx.Config().ProductPublicSepolicyDirs()...)
+	b.srcs[".product_private"] = b.findSrcsInDirs(ctx, ctx.Config().ProductPrivateSepolicyDirs()...)
 }
diff --git a/build/soong/policy.go b/build/soong/policy.go
index 82fabe3..8d0e1a4 100644
--- a/build/soong/policy.go
+++ b/build/soong/policy.go
@@ -17,7 +17,9 @@
 import (
 	"fmt"
 	"os"
+	"sort"
 	"strconv"
+	"strings"
 
 	"github.com/google/blueprint/proptools"
 
@@ -31,6 +33,31 @@
 	PolicyVers = 30
 )
 
+// This order should be kept. checkpolicy syntax requires it.
+var policyConfOrder = []string{
+	"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",
+}
+
 func init() {
 	android.RegisterModuleType("se_policy_conf", policyConfFactory)
 	android.RegisterModuleType("se_policy_cil", policyCilFactory)
@@ -143,9 +170,25 @@
 	return strconv.FormatBool(ctx.DeviceConfig().BuildDebugfsRestrictionsEnabled())
 }
 
+func findPolicyConfOrder(name string) int {
+	for idx, pattern := range policyConfOrder {
+		if pattern == name || (pattern == "*.te" && strings.HasSuffix(name, ".te")) {
+			return idx
+		}
+	}
+	// name is not matched
+	return len(policyConfOrder)
+}
+
 func (c *policyConf) transformPolicyToConf(ctx android.ModuleContext) android.OutputPath {
 	conf := android.PathForModuleOut(ctx, "conf").OutputPath
 	rule := android.NewRuleBuilder(pctx, ctx)
+
+	srcs := android.PathsForModuleSrc(ctx, c.properties.Srcs)
+	sort.SliceStable(srcs, func(x, y int) bool {
+		return findPolicyConfOrder(srcs[x].Base()) < findPolicyConfOrder(srcs[y].Base())
+	})
+
 	rule.Command().Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
 		Flag("--fatal-warnings").
 		FlagForEachArg("-D ", ctx.DeviceConfig().SepolicyM4Defs()).
@@ -164,7 +207,7 @@
 		FlagWithArg("-D target_requires_insecure_execmem_for_swiftshader=", strconv.FormatBool(ctx.DeviceConfig().RequiresInsecureExecmemForSwiftshader())).
 		FlagWithArg("-D target_enforce_debugfs_restriction=", c.enforceDebugfsRestrictions(ctx)).
 		Flag("-s").
-		Inputs(android.PathsForModuleSrc(ctx, c.properties.Srcs)).
+		Inputs(srcs).
 		Text("> ").Output(conf)
 
 	rule.Build("conf", "Transform policy to conf: "+ctx.ModuleName())
diff --git a/microdroid/TEST_MAPPING b/microdroid/TEST_MAPPING
new file mode 100644
index 0000000..f6e1c4f
--- /dev/null
+++ b/microdroid/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "imports": [
+    {
+      "path": "packages/modules/Virtualization"
+    }
+  ]
+}
diff --git a/microdroid/system/private/apkdmverity.te b/microdroid/system/private/apkdmverity.te
index c3f718b..84e1575 100644
--- a/microdroid/system/private/apkdmverity.te
+++ b/microdroid/system/private/apkdmverity.te
@@ -36,7 +36,6 @@
 allow apkdmverity kmsg_device:chr_file w_file_perms;
 
 # apkdmverity is forked from microdroid_manager
-# TODO(inseob): remove this
 allow apkdmverity microdroid_manager:fd use;
 
 # Only microdroid_manager can run apkdmverity
diff --git a/microdroid/system/private/odrefresh.te b/microdroid/system/private/odrefresh.te
index 3dd2d2c..c281896 100644
--- a/microdroid/system/private/odrefresh.te
+++ b/microdroid/system/private/odrefresh.te
@@ -19,5 +19,11 @@
 # the current APEXes.
 allow odrefresh apex_info_file:file r_file_perms;
 
+# Minijail uses pipe for the parent process to signal the child (as a fallback
+# mechanism, since Android does not support minijail's preload).
+# TODO(196109647): We can probably remove this once the minijail preload is
+# supported on Android.
+allow odrefresh compos:fifo_file read;
+
 # Do not audit unused resources from parent processes.
 dontaudit odrefresh compos:fd use;
diff --git a/microdroid/system/private/zipfuse.te b/microdroid/system/private/zipfuse.te
index b88c014..da0cd0f 100644
--- a/microdroid/system/private/zipfuse.te
+++ b/microdroid/system/private/zipfuse.te
@@ -42,7 +42,6 @@
 allow zipfuse extra_apk_file:dir mounton;
 
 # zipfuse is forked from microdroid_manager
-# TODO(inseob): remove this
 allow zipfuse microdroid_manager:fd use;
 
 # Only microdroid_manager can run zipfuse
diff --git a/private/charger_type.te b/private/charger_type.te
index cb699de..3647496 100644
--- a/private/charger_type.te
+++ b/private/charger_type.te
@@ -15,18 +15,18 @@
     -vendor_init
 } charger_config_prop:property_service set;
 
-# charger_status_prop: Only init, vendor_init, charger, and hal_health_server
+# charger_status_prop: Only init, vendor_init, charger, and charger_vendor
 # are allowed to set it
 neverallow {
     domain
     -init
     -vendor_init
     -charger
-    -hal_health_server
+    -charger_vendor
 } charger_status_prop:property_service set;
 
 # Both charger_config_prop and charger_status_prop:
-# Only init, vendor_init, dumpstate, charger, and hal_health_server
+# Only init, vendor_init, dumpstate, charger, and charger_vendor
 # are allowed to read it
 neverallow {
     domain
@@ -34,5 +34,5 @@
     -dumpstate
     -vendor_init
     -charger
-    -hal_health_server
+    -charger_vendor
 } { charger_config_prop charger_status_prop }:file no_rw_file_perms;
diff --git a/private/compat/32.0/32.0.ignore.cil b/private/compat/32.0/32.0.ignore.cil
index 6eb9e46..dce2649 100644
--- a/private/compat/32.0/32.0.ignore.cil
+++ b/private/compat/32.0/32.0.ignore.cil
@@ -8,6 +8,7 @@
     apexd_select_prop
     artd_service
     attestation_verification_service
+    charger_vendor
     device_config_nnapi_native_prop
     dice_maintenance_service
     dice_node_service
@@ -37,6 +38,7 @@
     locale_service
     proc_watermark_boost_factor
     proc_watermark_scale_factor
+    selection_toolbar_service
     snapuserd_proxy_socket
     supplemental_process_service
     sysfs_fs_fuse_bpf
diff --git a/private/netd.te b/private/netd.te
index 670a4bf..d87b9a6 100644
--- a/private/netd.te
+++ b/private/netd.te
@@ -9,6 +9,9 @@
 domain_auto_trans(netd, clatd_exec, clatd)
 allow netd clatd:process signal;
 
+# Allow netd to setup packet socket and pass to clatd
+allow netd self:packet_socket { bind create setopt };
+
 # give netd permission to setup iptables rule with xt_bpf, attach program to cgroup, and read/write
 # the map created by bpfloader
 allow netd bpfloader:bpf { prog_run map_read map_write };
diff --git a/private/service_contexts b/private/service_contexts
index 327b4f7..c378aec 100644
--- a/private/service_contexts
+++ b/private/service_contexts
@@ -274,6 +274,7 @@
 search_ui                                 u:object_r:search_ui_service:s0
 secure_element                            u:object_r:secure_element_service:s0
 sec_key_att_app_id_provider               u:object_r:sec_key_att_app_id_provider_service:s0
+selection_toolbar                         u:object_r:selection_toolbar_service:s0
 sensorservice                             u:object_r:sensorservice_service:s0
 sensor_privacy                            u:object_r:sensor_privacy_service:s0
 serial                                    u:object_r:serial_service:s0
diff --git a/public/charger_vendor.te b/public/charger_vendor.te
new file mode 100644
index 0000000..2dd106f
--- /dev/null
+++ b/public/charger_vendor.te
@@ -0,0 +1,4 @@
+# Context when health HAL runs charger mode
+
+type charger_vendor, charger_type, domain;
+hal_server_domain(charger_vendor, hal_health)
diff --git a/public/hal_nlinterceptor.te b/public/hal_nlinterceptor.te
index 2076de8..1a738a5 100644
--- a/public/hal_nlinterceptor.te
+++ b/public/hal_nlinterceptor.te
@@ -5,4 +5,4 @@
 
 allow hal_nlinterceptor self:global_capability_class_set net_admin;
 allow hal_nlinterceptor self:netlink_generic_socket create_socket_perms_no_ioctl;
-allow hal_nlinterceptor self:netlink_route_socket { nlmsg_readpriv nlmsg_write };
+allow hal_nlinterceptor self:netlink_route_socket { create_socket_perms_no_ioctl nlmsg_readpriv nlmsg_write };
diff --git a/public/service.te b/public/service.te
index 9fb8df3..e4cdc13 100644
--- a/public/service.te
+++ b/public/service.te
@@ -193,6 +193,7 @@
 type search_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type search_ui_service, app_api_service, system_server_service, service_manager_type;
 type sec_key_att_app_id_provider_service, app_api_service, system_server_service, service_manager_type;
+type selection_toolbar_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type sensorservice_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type sensor_privacy_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type serial_service, system_api_service, system_server_service, service_manager_type;
diff --git a/vendor/hal_health_default.te b/vendor/hal_health_default.te
index 9b2b921..a48c7b8 100644
--- a/vendor/hal_health_default.te
+++ b/vendor/hal_health_default.te
@@ -4,3 +4,7 @@
 
 type hal_health_default_exec, exec_type, vendor_file_type, file_type;
 init_daemon_domain(hal_health_default)
+
+# When executing the service in offline-charging mode,
+# allow to transition to charger_vendor domain.
+domain_trans(init, hal_health_default_exec, charger_vendor)