Merge "Allow mediaprovider to search /mnt/media_rw"
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..26102c9
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,41 @@
+// Copyright (C) 2018 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.
+
+se_filegroup {
+    name: "26.0.board.compat.map",
+    srcs: [
+        "compat/26.0/26.0.cil",
+    ],
+}
+
+se_filegroup {
+    name: "27.0.board.compat.map",
+    srcs: [
+        "compat/27.0/27.0.cil",
+    ],
+}
+
+se_cil_compat_map {
+    name: "26.0.cil",
+    srcs: [
+        ":26.0.board.compat.map",
+    ],
+}
+
+se_cil_compat_map {
+    name: "27.0.cil",
+    srcs: [
+        ":27.0.board.compat.map",
+    ],
+}
diff --git a/Android.mk b/Android.mk
index e155177..ffdc5c4 100644
--- a/Android.mk
+++ b/Android.mk
@@ -476,26 +476,6 @@
 #################################
 include $(CLEAR_VARS)
 
-LOCAL_MODULE := 27.0.cil
-LOCAL_SRC_FILES := private/compat/27.0/27.0.cil
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE_PATH := $(TARGET_OUT)/etc/selinux/mapping
-
-include $(BUILD_PREBUILT)
-#################################
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := 26.0.cil
-LOCAL_SRC_FILES := private/compat/26.0/26.0.cil
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE_PATH := $(TARGET_OUT)/etc/selinux/mapping
-
-include $(BUILD_PREBUILT)
-#################################
-include $(CLEAR_VARS)
-
 LOCAL_MODULE := plat_and_mapping_sepolicy.cil.sha256
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_TAGS := optional
diff --git a/build/soong/Android.bp b/build/soong/Android.bp
new file mode 100644
index 0000000..bcd33b3
--- /dev/null
+++ b/build/soong/Android.bp
@@ -0,0 +1,29 @@
+// Copyright (C) 2018 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.
+
+bootstrap_go_package {
+    name: "soong-selinux",
+    pkgPath: "android/soong/selinux",
+    deps: [
+        "blueprint",
+        "soong",
+        "soong-android",
+        "soong-genrule",
+    ],
+    srcs: [
+        "cil_compat_map.go",
+        "filegroup.go"
+    ],
+    pluginFor: ["soong_build"],
+}
diff --git a/build/soong/cil_compat_map.go b/build/soong/cil_compat_map.go
new file mode 100644
index 0000000..8f55797
--- /dev/null
+++ b/build/soong/cil_compat_map.go
@@ -0,0 +1,113 @@
+// Copyright (C) 2018 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
+
+// This file contains "se_cil_compat_map" module type used to build and install
+// sepolicy backwards compatibility mapping files.
+
+import (
+	"android/soong/android"
+	"fmt"
+	"io"
+)
+
+var (
+	pctx = android.NewPackageContext("android/soong/selinux")
+)
+
+func init() {
+	android.RegisterModuleType("se_cil_compat_map", cilCompatMapFactory)
+	pctx.Import("android/soong/common")
+}
+
+func cilCompatMapFactory() android.Module {
+	c := &cilCompatMap{}
+	c.AddProperties(&c.properties)
+	android.InitAndroidModule(c)
+	return c
+}
+
+type cilCompatMapProperties struct {
+	// list of source (.cil) files used to build an sepolicy compatibility mapping
+	// file. srcs may reference the outputs of other modules that produce source
+	// files like genrule or filegroup using the syntax ":module". srcs has to be
+	// non-empty.
+	Srcs []string
+}
+
+type cilCompatMap struct {
+	android.ModuleBase
+	properties cilCompatMapProperties
+	// (.intermediate) module output path as installation source.
+	installSource android.OptionalPath
+}
+
+func expandSeSources(ctx android.ModuleContext, srcFiles []string) android.Paths {
+	expandedSrcFiles := make(android.Paths, 0, len(srcFiles))
+	for _, s := range srcFiles {
+		if m := android.SrcIsModule(s); m != "" {
+			module := ctx.GetDirectDepWithTag(m, android.SourceDepTag)
+			if module == nil {
+				// Error will have been handled by ExtractSourcesDeps
+				continue
+			}
+			if fg, ok := module.(*fileGroup); ok {
+				// Core compatibility mapping files are under system/sepolicy/private.
+				expandedSrcFiles = append(expandedSrcFiles, fg.SystemPrivateSrcs()...)
+				// Partner extensions to the compatibility mapping in must be located in
+				// BOARD_PLAT_PRIVATE_SEPOLICY_DIR
+				expandedSrcFiles = append(expandedSrcFiles, fg.SystemExtPrivateSrcs()...)
+			} else {
+				ctx.ModuleErrorf("srcs dependency %q is not an selinux filegroup", m)
+			}
+		} else {
+			p := android.PathForModuleSrc(ctx, s)
+			expandedSrcFiles = append(expandedSrcFiles, p)
+		}
+	}
+	return expandedSrcFiles
+}
+
+func (c *cilCompatMap) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	srcFiles := expandSeSources(ctx, c.properties.Srcs)
+	for _, src := range srcFiles {
+		if src.Ext() != ".cil" {
+			ctx.PropertyErrorf("srcs", "%s has to be a .cil file.", src.String())
+		}
+	}
+
+	out := android.PathForModuleGen(ctx, c.Name())
+	ctx.Build(pctx, android.BuildParams{
+		Rule:   android.Cat,
+		Output: out,
+		Inputs: srcFiles,
+	})
+	c.installSource = android.OptionalPathForPath(out)
+}
+
+func (c *cilCompatMap) DepsMutator(ctx android.BottomUpMutatorContext) {
+	android.ExtractSourcesDeps(ctx, c.properties.Srcs)
+}
+
+func (c *cilCompatMap) AndroidMk() android.AndroidMkData {
+	ret := android.AndroidMkData{
+		OutputFile: c.installSource,
+		Class:      "ETC",
+	}
+	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
+		fmt.Fprintln(w, "LOCAL_MODULE_PATH := $(TARGET_OUT)/etc/selinux/mapping")
+	})
+	return ret
+}
diff --git a/build/soong/filegroup.go b/build/soong/filegroup.go
new file mode 100644
index 0000000..7441834
--- /dev/null
+++ b/build/soong/filegroup.go
@@ -0,0 +1,130 @@
+// Copyright 2018 Google Inc. All rights reserved.
+//
+// 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 (
+	"android/soong/android"
+	"path/filepath"
+)
+
+func init() {
+	android.RegisterModuleType("se_filegroup", FileGroupFactory)
+}
+
+func FileGroupFactory() android.Module {
+	module := &fileGroup{}
+	module.AddProperties(&module.properties)
+	android.InitAndroidModule(module)
+	return module
+}
+
+type fileGroupProperties struct {
+	// list of source file suffixes used to collect selinux policy files.
+	// Source files will be looked up in the following local directories:
+	// system/sepolicy/{public, private, vendor, reqd_mask}
+	// and directories specified by following config variables:
+	// BOARD_SEPOLICY_DIRS, BOARD_ODM_SEPOLICY_DIRS
+	// BOARD_PLAT_PUBLIC_SEPOLICY_DIR, BOARD_PLAT_PRIVATE_SEPOLICY_DIR
+	Srcs []string
+}
+
+type fileGroup struct {
+	android.ModuleBase
+	properties fileGroupProperties
+
+	systemPublicSrcs   android.Paths
+	systemPrivateSrcs  android.Paths
+	systemVendorSrcs   android.Paths
+	systemReqdMaskSrcs android.Paths
+
+	systemExtPublicSrcs  android.Paths
+	systemExtPrivateSrcs android.Paths
+
+	vendorSrcs android.Paths
+	odmSrcs    android.Paths
+}
+
+// Source files from system/sepolicy/public
+func (fg *fileGroup) SystemPublicSrcs() android.Paths {
+	return fg.systemPublicSrcs
+}
+
+// Source files from system/sepolicy/private
+func (fg *fileGroup) SystemPrivateSrcs() android.Paths {
+	return fg.systemPrivateSrcs
+}
+
+// Source files from system/sepolicy/vendor
+func (fg *fileGroup) SystemVendorSrcs() android.Paths {
+	return fg.systemVendorSrcs
+}
+
+// Source files from system/sepolicy/reqd_mask
+func (fg *fileGroup) SystemReqdMaskSrcs() android.Paths {
+	return fg.systemReqdMaskSrcs
+}
+
+// Source files from BOARD_PLAT_PUBLIC_SEPOLICY_DIR
+func (fg *fileGroup) SystemExtPublicSrcs() android.Paths {
+	return fg.systemExtPublicSrcs
+}
+
+// Source files from BOARD_PLAT_PRIVATE_SEPOLICY_DIR
+func (fg *fileGroup) SystemExtPrivateSrcs() android.Paths {
+	return fg.systemExtPrivateSrcs
+}
+
+// Source files from BOARD_SEPOLICY_DIRS
+func (fg *fileGroup) VendorSrcs() android.Paths {
+	return fg.vendorSrcs
+}
+
+// Source files from BOARD_ODM_SEPOLICY_DIRS
+func (fg *fileGroup) OdmSrcs() android.Paths {
+	return fg.odmSrcs
+}
+
+func (fg *fileGroup) findSrcsInDirs(ctx android.ModuleContext, dirs []string) android.Paths {
+	result := android.Paths{}
+	for _, f := range fg.properties.Srcs {
+		for _, d := range dirs {
+			path := filepath.Join(d, f)
+			files, _ := ctx.GlobWithDeps(path, nil)
+			for _, f := range files {
+				result = append(result, android.PathForSource(ctx, f))
+			}
+		}
+	}
+	return result
+}
+
+func (fg *fileGroup) findSrcsInDir(ctx android.ModuleContext, dir string) android.Paths {
+	return fg.findSrcsInDirs(ctx, []string{dir})
+}
+
+func (fg *fileGroup) DepsMutator(ctx android.BottomUpMutatorContext) {}
+
+func (fg *fileGroup) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	fg.systemPublicSrcs = fg.findSrcsInDir(ctx, filepath.Join(ctx.ModuleDir(), "public"))
+	fg.systemPrivateSrcs = fg.findSrcsInDir(ctx, filepath.Join(ctx.ModuleDir(), "private"))
+	fg.systemVendorSrcs = fg.findSrcsInDir(ctx, filepath.Join(ctx.ModuleDir(), "vendor"))
+	fg.systemReqdMaskSrcs = fg.findSrcsInDir(ctx, filepath.Join(ctx.ModuleDir(), "reqd_mask"))
+
+	fg.systemExtPublicSrcs = fg.findSrcsInDir(ctx, ctx.DeviceConfig().PlatPublicSepolicyDir())
+	fg.systemExtPrivateSrcs = fg.findSrcsInDir(ctx, ctx.DeviceConfig().PlatPrivateSepolicyDir())
+
+	fg.vendorSrcs = fg.findSrcsInDirs(ctx, ctx.DeviceConfig().VendorSepolicyDirs())
+	fg.odmSrcs = fg.findSrcsInDirs(ctx, ctx.DeviceConfig().OdmSepolicyDirs())
+}
diff --git a/private/compat/26.0/26.0.ignore.cil b/private/compat/26.0/26.0.ignore.cil
index 12f8d7b..b0b5f19 100644
--- a/private/compat/26.0/26.0.ignore.cil
+++ b/private/compat/26.0/26.0.ignore.cil
@@ -62,6 +62,9 @@
     incident_helper
     incident_helper_exec
     kmsg_debug_device
+    llkd
+    llkd_exec
+    llkd_tmpfs
     last_boot_reason_prop
     mediaprovider_tmpfs
     netd_stable_secret_prop
@@ -137,6 +140,9 @@
     vold_prepare_subdirs
     vold_prepare_subdirs_exec
     vold_service
+    wait_for_keymaster
+    wait_for_keymaster_exec
+    wait_for_keymaster_tmpfs
     wpantund
     wpantund_exec
     wpantund_service
diff --git a/private/compat/27.0/27.0.ignore.cil b/private/compat/27.0/27.0.ignore.cil
index 7d6476a..d2ab474 100644
--- a/private/compat/27.0/27.0.ignore.cil
+++ b/private/compat/27.0/27.0.ignore.cil
@@ -54,6 +54,9 @@
     incident_helper
     incident_helper_exec
     last_boot_reason_prop
+    llkd
+    llkd_exec
+    llkd_tmpfs
     lowpan_device
     lowpan_prop
     lowpan_service
@@ -113,6 +116,9 @@
     vold_prepare_subdirs
     vold_prepare_subdirs_exec
     vold_service
+    wait_for_keymaster
+    wait_for_keymaster_exec
+    wait_for_keymaster_tmpfs
     wm_trace_data_file
     wpantund
     wpantund_exec
diff --git a/private/file_contexts b/private/file_contexts
index 3488787..b55fb9d 100644
--- a/private/file_contexts
+++ b/private/file_contexts
@@ -249,6 +249,7 @@
 /system/bin/dnsmasq     u:object_r:dnsmasq_exec:s0
 /system/bin/healthd     u:object_r:healthd_exec:s0
 /system/bin/clatd	u:object_r:clatd_exec:s0
+/system/bin/llkd        u:object_r:llkd_exec:s0
 /system/bin/lmkd        u:object_r:lmkd_exec:s0
 /system/bin/usbd   u:object_r:usbd_exec:s0
 /system/bin/inputflinger u:object_r:inputflinger_exec:s0
@@ -294,6 +295,7 @@
 /system/bin/stats                u:object_r:stats_exec:s0
 /system/bin/statsd               u:object_r:statsd_exec:s0
 /system/bin/bpfloader            u:object_r:bpfloader_exec:s0
+/system/bin/wait_for_keymaster   u:object_r:wait_for_keymaster_exec:s0
 
 #############################
 # Vendor files
diff --git a/private/genfs_contexts b/private/genfs_contexts
index eca489c..c076918 100644
--- a/private/genfs_contexts
+++ b/private/genfs_contexts
@@ -38,7 +38,7 @@
 genfscon proc /sys/kernel/dmesg_restrict u:object_r:proc_security:s0
 genfscon proc /sys/kernel/hostname u:object_r:proc_hostname:s0
 genfscon proc /sys/kernel/hotplug u:object_r:usermodehelper:s0
-genfscon proc /sys/kernel/hung_task_timeout_secs u:object_r:proc_hung_task:s0
+genfscon proc /sys/kernel/hung_task_ u:object_r:proc_hung_task:s0
 genfscon proc /sys/kernel/kptr_restrict u:object_r:proc_security:s0
 genfscon proc /sys/kernel/modprobe u:object_r:usermodehelper:s0
 genfscon proc /sys/kernel/modules_disabled u:object_r:proc_security:s0
diff --git a/private/hwservicemanager.te b/private/hwservicemanager.te
index f56e0c6..45b62d0 100644
--- a/private/hwservicemanager.te
+++ b/private/hwservicemanager.te
@@ -6,3 +6,4 @@
 add_hwservice(hwservicemanager, hidl_token_hwservice)
 
 set_prop(hwservicemanager, ctl_default_prop)
+set_prop(hwservicemanager, ctl_dumpstate_prop)
diff --git a/private/llkd.te b/private/llkd.te
new file mode 100644
index 0000000..54c6d04
--- /dev/null
+++ b/private/llkd.te
@@ -0,0 +1,32 @@
+# llkd Live LocK Daemon
+typeattribute llkd coredomain;
+
+init_daemon_domain(llkd)
+
+allow llkd self:global_capability_class_set kill;
+
+# llkd optionally locks itself in memory, to prevent it from being
+# swapped out and unable to discover a kernel in live-lock state.
+allow llkd self:global_capability_class_set ipc_lock;
+
+# Send kill signals to _anyone_ suffering from Live Lock
+allow llkd domain:process sigkill;
+
+# live lock watchdog process allowed to look through /proc/
+allow llkd domain:dir r_dir_perms;
+allow llkd domain:file r_file_perms;
+allow llkd domain:lnk_file read;
+# Set /proc/sys/kernel/hung_task_*
+allow llkd proc_hung_task:file rw_file_perms;
+
+# live lock watchdog process allowed to dump process trace and
+# reboot because orderly shutdown may not be possible.
+allow llkd proc_sysrq:file w_file_perms;
+allow llkd kmsg_device:chr_file w_file_perms;
+
+### neverallow rules
+
+neverallow { domain -init } llkd:process { dyntransition transition };
+
+# never honor LD_PRELOAD
+neverallow * llkd:process noatsecure;
diff --git a/private/statsd.te b/private/statsd.te
index 74b89c2..834fb8b 100644
--- a/private/statsd.te
+++ b/private/statsd.te
@@ -50,6 +50,9 @@
 allow statsd {
   app_api_service
   incident_service
+  userdebug_or_eng(`
+    perfprofd_service
+  ')
   statscompanion_service
   system_api_service
 }:service_manager find;
diff --git a/private/system_server.te b/private/system_server.te
index 48ec634..aab37fc 100644
--- a/private/system_server.te
+++ b/private/system_server.te
@@ -389,7 +389,7 @@
 
 # Allow dropbox to read /data/misc/perfprofd. Only the fd is sent over binder.
 userdebug_or_eng(`
-  allow system_server perfprofd_data_file:file read;
+  allow system_server perfprofd_data_file:file { getattr read };
   allow system_server perfprofd:fd use;
 ')
 
@@ -778,6 +778,11 @@
 allow system_server user_profile_data_file:dir { getattr search };
 allow system_server user_profile_data_file:file { getattr open read };
 
+# System server may dump profile data for debuggable apps in the /data/misc/profman.
+# As such it needs to be able create files but it should never read from them.
+allow system_server profman_dump_data_file:file { create getattr setattr w_file_perms};
+allow system_server profman_dump_data_file:dir w_dir_perms;
+
 # On userdebug build we may profile system server. Allow it to write and create its own profile.
 userdebug_or_eng(`
   allow system_server user_profile_data_file:file create_file_perms;
diff --git a/private/wait_for_keymaster.te b/private/wait_for_keymaster.te
new file mode 100644
index 0000000..8b8dd29
--- /dev/null
+++ b/private/wait_for_keymaster.te
@@ -0,0 +1,9 @@
+# wait_for_keymaster service
+type wait_for_keymaster, domain, coredomain;
+type wait_for_keymaster_exec, exec_type, file_type;
+
+init_daemon_domain(wait_for_keymaster)
+
+hal_client_domain(wait_for_keymaster, hal_keymaster)
+
+allow wait_for_keymaster kmsg_device:chr_file w_file_perms;
diff --git a/public/init.te b/public/init.te
index 51a991b..24dfb1d 100644
--- a/public/init.te
+++ b/public/init.te
@@ -254,6 +254,7 @@
   -dm_device
   -hwbinder_device
   -hw_random_device
+  -input_device
   -keychord_device
   -kmem_device
   -kmsg_device
@@ -453,6 +454,8 @@
 # keychord configuration
 allow init self:global_capability_class_set sys_tty_config;
 allow init keychord_device:chr_file rw_file_perms;
+allow init input_device:dir r_dir_perms;
+allow init input_device:chr_file rw_file_perms;
 
 # Access device mapper for setting up dm-verity
 allow init dm_device:chr_file rw_file_perms;
diff --git a/public/llkd.te b/public/llkd.te
new file mode 100644
index 0000000..afc508d
--- /dev/null
+++ b/public/llkd.te
@@ -0,0 +1,3 @@
+# llkd Live LocK Daemon
+type llkd, domain, mlstrustedsubject;
+type llkd_exec, exec_type, file_type;
diff --git a/public/mediaextractor.te b/public/mediaextractor.te
index 44387fd..b055462 100644
--- a/public/mediaextractor.te
+++ b/public/mediaextractor.te
@@ -22,10 +22,8 @@
 
 crash_dump_fallback(mediaextractor)
 
-# Suppress denials from sdcardfs (b/67454004)
-dontaudit mediaextractor sdcardfs:file read;
-
 # allow mediaextractor read permissions for file sources
+allow mediaextractor sdcardfs:file { getattr read };
 allow mediaextractor media_rw_data_file:file { getattr read };
 allow mediaextractor app_data_file:file { getattr read };
 
diff --git a/public/shell.te b/public/shell.te
index 2be6da6..4293f52 100644
--- a/public/shell.te
+++ b/public/shell.te
@@ -30,8 +30,8 @@
 allow shell trace_data_file:dir { r_dir_perms remove_name write };
 
 # Access /data/misc/profman.
-allow shell profman_dump_data_file:dir { search getattr write remove_name };
-allow shell profman_dump_data_file:file { getattr unlink };
+allow shell profman_dump_data_file:dir { write remove_name r_dir_perms };
+allow shell profman_dump_data_file:file { unlink r_file_perms };
 
 # Read/execute files in /data/nativetest
 userdebug_or_eng(`
diff --git a/tools/Android.bp b/tools/Android.bp
index 8184302..2809c9d 100644
--- a/tools/Android.bp
+++ b/tools/Android.bp
@@ -22,7 +22,6 @@
     ],
     static_libs: ["libsepol"],
     stl: "none",
-    tags: ["optional"],
 }
 
 cc_binary_host {
@@ -55,6 +54,5 @@
 cc_prebuilt_binary {
     name: "insertkeys.py",
     srcs: ["insertkeys.py"],
-    tags: ["optional"],
     host_supported: true,
 }
diff --git a/tools/fc_sort/Android.bp b/tools/fc_sort/Android.bp
index acecc97..d0a391b 100644
--- a/tools/fc_sort/Android.bp
+++ b/tools/fc_sort/Android.bp
@@ -18,7 +18,6 @@
     name: "fc_sort",
     srcs: ["fc_sort.c"],
     stl: "none",
-    tags: ["optional"],
     cflags: [
         "-Wall",
         "-Werror",