Add and install permission file for Android 9+

Without this, installing the twrp app as system app leads to
reboot loops into recovery with log messages like:
java.lang.IllegalStateException: Signature|privileged permissions not in privapp-permissions whitelist: {me.twrp.twrpapp: android.permission.READ_PRECISE_PHONE_STATE, me.twrp.twrpapp: android.permission.BATTERY_STATS, me.twrp.twrpapp: android.permission.PACKAGE_USAGE_STATS}

Change-Id: I6156323ea0d23512b0d7eefbd03aa627f3002ae8
(cherry picked from commit 86a4370e6fe4bb20033b0de3a261aec4bf3573db)
diff --git a/gui/action.cpp b/gui/action.cpp
old mode 100755
new mode 100644
index 585e3c3..350b630
--- a/gui/action.cpp
+++ b/gui/action.cpp
@@ -2041,6 +2041,22 @@
 							LOGERR("setfilecon %s error: %s\n", install_path.c_str(), strerror(errno));
 							goto exit;
 						}
+
+						// System apps require their permissions to be pre-set via an XML file in /etc/permissions
+						string permission_path = base_path + "/etc/permissions/privapp-permissions-twrpapp.xml";
+						if (TWFunc::copy_file("/sbin/privapp-permissions-twrpapp.xml", permission_path, 0644)) {
+							LOGERR("Error copying permission file\n");
+							goto exit;
+						}
+						if (chown(permission_path.c_str(), 1000, 1000)) {
+							LOGERR("chown %s error: %s\n", permission_path.c_str(), strerror(errno));
+							goto exit;
+						}
+						if (setfilecon(permission_path.c_str(), (security_context_t)context.c_str()) < 0) {
+							LOGERR("setfilecon %s error: %s\n", permission_path.c_str(), strerror(errno));
+							goto exit;
+						}
+
 						sync();
 						sync();
 						PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), true);
diff --git a/prebuilt/Android.mk b/prebuilt/Android.mk
index 53c3f85..b97116a 100755
--- a/prebuilt/Android.mk
+++ b/prebuilt/Android.mk
@@ -652,6 +652,15 @@
 LOCAL_SRC_FILES := $(LOCAL_MODULE)
 include $(BUILD_PREBUILT)
 
+#TWRP App permissions for Android 9+
+include $(CLEAR_VARS)
+LOCAL_MODULE := privapp-permissions-twrpapp.xml
+LOCAL_MODULE_TAGS := eng
+LOCAL_MODULE_CLASS := RECOVERY_EXECUTABLES
+LOCAL_MODULE_PATH := $(TARGET_RECOVERY_ROOT_OUT)/sbin
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+
 ifeq ($(TW_INCLUDE_CRYPTO), true)
     ifneq ($(TW_CRYPTO_USE_SYSTEM_VOLD),)
         ifneq ($(shell test $(PLATFORM_SDK_VERSION) -ge 28; echo $$?),0)
diff --git a/prebuilt/privapp-permissions-twrpapp.xml b/prebuilt/privapp-permissions-twrpapp.xml
new file mode 100644
index 0000000..9b294c2
--- /dev/null
+++ b/prebuilt/privapp-permissions-twrpapp.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<permissions>
+    <privapp-permissions package="me.twrp.twrpapp">
+        <permission name="android.permission.BATTERY_STATS"/>
+        <permission name="android.permission.PACKAGE_USAGE_STATS"/>
+        <permission name="android.permission.READ_PRECISE_PHONE_STATE"/>
+    </privapp-permissions>
+</permissions>