AB/Non AB Devices: updates for moving cache

This patchset updates all the places we touch cache on AB devices
and non AB devices so that we can write to the appropriate
location. AB devices removed the cache partition and moved it to
/data/cache.

Change-Id: I485ec205a604f1f07ceb7700ae9c4e720fd55c3e
diff --git a/data.cpp b/data.cpp
index cf8349b..0ece4e7 100755
--- a/data.cpp
+++ b/data.cpp
@@ -1038,33 +1038,38 @@
 	string Path;
 	char version[255];
 
-	if (!PartitionManager.Mount_By_Path("/cache", false)) {
-		LOGINFO("Unable to mount '%s' to write version number.\n", Path.c_str());
-		return;
-	}
-	if (!TWFunc::Path_Exists("/cache/recovery/.")) {
-		LOGINFO("Recreating /cache/recovery folder.\n");
-		if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0) {
-			LOGERR("DataManager::Output_Version -- Unable to make /cache/recovery\n");
+	std::string cacheDir = TWFunc::get_cache_dir();
+	std::string recoveryCacheDir = cacheDir + "recovery/";
+
+	if (cacheDir == NON_AB_CACHE_DIR) {
+		if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
+			LOGINFO("Unable to mount '%s' to write version number.\n", Path.c_str());
 			return;
 		}
 	}
-	Path = "/cache/recovery/.version";
-	if (TWFunc::Path_Exists(Path)) {
-		unlink(Path.c_str());
+	if (!TWFunc::Path_Exists(recoveryCacheDir)) {
+		LOGINFO("Recreating %s folder.\n", recoveryCacheDir.c_str());
+		if (mkdir(recoveryCacheDir.c_str(), S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0) {
+			LOGERR("DataManager::Output_Version -- Unable to make %s: %s\n", recoveryCacheDir.c_str(), strerror(errno));
+			return;
+		}
 	}
-	FILE *fp = fopen(Path.c_str(), "w");
+	std::string verPath = recoveryCacheDir + ".version";
+	if (TWFunc::Path_Exists(verPath)) {
+		unlink(verPath.c_str());
+	}
+	FILE *fp = fopen(verPath.c_str(), "w");
 	if (fp == NULL) {
-		gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Path)(strerror(errno)));
+		gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(verPath)(strerror(errno)));
 		return;
 	}
 	strcpy(version, TW_VERSION_STR);
 	fwrite(version, sizeof(version[0]), strlen(version) / sizeof(version[0]), fp);
 	fclose(fp);
-	TWFunc::copy_file("/etc/recovery.fstab", "/cache/recovery/recovery.fstab", 0644);
+	TWFunc::copy_file("/etc/recovery.fstab", recoveryCacheDir + "recovery.fstab", 0644);
 	PartitionManager.Output_Storage_Fstab();
 	sync();
-	LOGINFO("Version number saved to '%s'\n", Path.c_str());
+	LOGINFO("Version number saved to '%s'\n", verPath.c_str());
 #endif
 }
 
@@ -1077,10 +1082,6 @@
 
 	GetValue(TW_IS_ENCRYPTED, is_enc);
 	GetValue(TW_HAS_DATA_MEDIA, has_data_media);
-	if (is_enc == 1 && has_data_media == 1) {
-		LOGINFO("Cannot load settings -- encrypted.\n");
-		return;
-	}
 
 	memset(mkdir_path, 0, sizeof(mkdir_path));
 	memset(settings_file, 0, sizeof(settings_file));
diff --git a/gui/action.cpp b/gui/action.cpp
index 11d9580..4b644a9 100755
--- a/gui/action.cpp
+++ b/gui/action.cpp
@@ -490,6 +490,8 @@
 	DataManager::SetValue("tw_operation", operation_name);
 	DataManager::SetValue("tw_operation_state", 0);
 	DataManager::SetValue("tw_operation_status", 0);
+	bool tw_ab_device = TWFunc::get_cache_dir() != NON_AB_CACHE_DIR;
+	DataManager::SetValue("tw_ab_device", tw_ab_device);
 }
 
 void GUIAction::operation_end(const int operation_status)
@@ -1059,7 +1061,6 @@
 {
 	operation_start("Format");
 	DataManager::SetValue("tw_partition", arg);
-
 	int ret_val = false;
 
 	if (simulate) {
diff --git a/gui/theme/common/landscape.xml b/gui/theme/common/landscape.xml
index f6f14bc..d1bce16 100755
--- a/gui/theme/common/landscape.xml
+++ b/gui/theme/common/landscape.xml
@@ -527,8 +527,9 @@
 			<template name="console"/>
 
 			<button style="main_button_half_width">
+				<condition var1="tw_ab_device" var2="0"/>
 				<placement x="%col2_x_left%" y="%row15a_y%"/>
-				<text>{@wipe_cache_dalvik_btn=Wipe cache/dalvik}</text>
+				<text>{@wipe_cache_dalvik_btn=Wipe Cache/Dalvik}</text>
 				<actions>
 					<action function="set">tw_back=flash_done</action>
 					<action function="set">tw_action=wipe</action>
@@ -545,6 +546,22 @@
 			</button>
 
 			<button style="main_button_half_width">
+				<condition var1="tw_ab_device" var2="1"/>
+				<placement x="%indent%" y="%row21a_y%"/>
+				<text>{@wipe_dalvik_btn=Wipe Dalvik}</text>
+				<actions>
+					<action function="set">tw_back=flash_done</action>
+					<action function="set">tw_action=wipe</action>
+					<action function="set">tw_action_param=dalvik</action>
+					<action function="set">tw_text1={@wipe_dalvik_confirm=Wipe Dalvik?}</action>
+					<action function="set">tw_action_text1={@wiping_cache_dalvik=Wiping Dalvik...}</action>
+					<action function="set">tw_complete_text1={@wipe_dalvik_complete=Dalvik Wipe Complete}</action>
+					<action function="set">tw_slider_text={@swipe_wipe=Swipe to Wipe}</action>
+					<action function="page">confirm_action</action>
+				</actions>
+			</button>
+
+			<button style="main_button_half_width">
 				<placement x="%center_x%" y="%row15a_y%"/>
 				<text>{@reboot_system_btn=Reboot System}</text>
 				<actions>
diff --git a/gui/theme/common/languages/en.xml b/gui/theme/common/languages/en.xml
index 03d4e08..f8de662 100755
--- a/gui/theme/common/languages/en.xml
+++ b/gui/theme/common/languages/en.xml
@@ -98,7 +98,8 @@
 		<string name="successful">Successful</string>
 		<string name="install_failed">Installation Failed</string>
 		<string name="install_successful">Installation Successful</string>
-		<string name="wipe_cache_dalvik_btn">Wipe cache/dalvik</string>
+		<string name="wipe_cache_dalvik_btn">Wipe Cache/Dalvik</string>
+		<string name="wipe_dalvik_btn">Wipe Dalvik</string>
 		<string name="reboot_system_btn">Reboot System</string>
 		<string name="install_sel_target">Select Target Partition</string>
 		<string name="flash_image_select">Select Partition to Flash Image:</string>
@@ -106,8 +107,11 @@
 		<string name="flashing_image">Flashing Image...</string>
 		<string name="image_flashed">Image Flashed</string>
 		<string name="wipe_cache_dalvik_confirm">Wipe Cache &amp; Dalvik?</string>
+		<string name="wipe_dalvik_confirm">Wipe Dalvik?</string>
 		<string name="wiping_cache_dalvik">Wiping Cache &amp; Dalvik...</string>
+		<string name="wiping_dalvik">Wiping Dalvik...</string>
 		<string name="wipe_cache_dalvik_complete">Cache &amp; Dalvik Wipe Complete</string>
+		<string name="wipe_dalvik_complete">Dalvik Wipe Complete</string>
 		<string name="swipe_wipe">Swipe to Wipe</string>
 		<string name="swipe_wipe_s">   Wipe</string>
 		<string name="no_os1">No OS Installed! Are you</string>
@@ -532,9 +536,10 @@
 		<string name="unable_find_part_path">Unable to find partition for path '{1}'</string>
 		<string name="update_part_details">Updating partition details...</string>
 		<string name="update_part_details_done">...done</string>
-		<string name="wiping_dalvik">Wiping Dalvik Cache Directories...</string>
+		<string name="wiping_dalvik">Wiping Dalvik Directories...</string>
 		<string name="cleaned">Cleaned: {1}...</string>
-		<string name="dalvik_done">-- Dalvik Cache Directories Wipe Complete!</string>
+		<string name="cache_dalvik_done">-- Dalvik Cache Directories Wipe Complete!</string>
+		<string name="dalvik_done">-- Dalvik Directory Wipe Complete!</string>
 		<string name="no_andsec">No android secure partitions found.</string>
 		<string name="unable_to_locate">Unable to locate {1}.</string>
 		<string name="wiping_datamedia">Wiping internal storage -- /data/media...</string>
diff --git a/gui/theme/common/portrait.xml b/gui/theme/common/portrait.xml
index 09b7c6b..1cf4d89 100755
--- a/gui/theme/common/portrait.xml
+++ b/gui/theme/common/portrait.xml
@@ -479,8 +479,9 @@
 			<template name="console"/>
 
 			<button style="main_button_half_height">
+				<condition var1="tw_ab_device" var2="0"/>
 				<placement x="%indent%" y="%row21a_y%"/>
-				<text>{@wipe_cache_dalvik_btn=Wipe cache/dalvik}</text>
+				<text>{@wipe_cache_dalvik_btn=Wipe Cache/Dalvik}</text>
 				<actions>
 					<action function="set">tw_back=flash_done</action>
 					<action function="set">tw_action=wipe</action>
@@ -497,6 +498,22 @@
 			</button>
 
 			<button style="main_button_half_height">
+				<condition var1="tw_ab_device" var2="1"/>
+				<placement x="%indent%" y="%row21a_y%"/>
+				<text>{@wipe_dalvik_btn=Wipe Dalvik}</text>
+				<actions>
+					<action function="set">tw_back=flash_done</action>
+					<action function="set">tw_action=wipe</action>
+					<action function="set">tw_action_param=dalvik</action>
+					<action function="set">tw_text1={@wipe_dalvik_confirm=Wipe Dalvik?}</action>
+					<action function="set">tw_action_text1={@wiping_cache_dalvik=Wiping Dalvik...}</action>
+					<action function="set">tw_complete_text1={@wipe_dalvik_complete=Dalvik Wipe Complete}</action>
+					<action function="set">tw_slider_text={@swipe_wipe=Swipe to Wipe}</action>
+					<action function="page">confirm_action</action>
+				</actions>
+			</button>
+
+			<button style="main_button_half_height">
 				<placement x="%center_x%" y="%row21a_y%"/>
 				<text>{@reboot_system_btn=Reboot System}</text>
 				<actions>
diff --git a/gui/theme/common/watch.xml b/gui/theme/common/watch.xml
index d36bb2d..56bdc55 100755
--- a/gui/theme/common/watch.xml
+++ b/gui/theme/common/watch.xml
@@ -706,6 +706,7 @@
 			<template name="console"/>
 
 			<button style="main_button_half_height">
+				<condition var1="tw_ab_device" var2="0"/>
 				<placement x="%col1_x_left%" y="%row13_y%"/>
 				<text>{@wipe_cache_dalvik_btn=Wipe cache/dalvik}</text>
 				<actions>
@@ -718,7 +719,23 @@
 					<action function="set">tw_text1={@wipe_cache_dalvik_confirm=Wipe Cache &amp; Dalvik?}</action>
 					<action function="set">tw_action_text1={@wiping_cache_dalvik=Wiping Cache &amp; Dalvik...}</action>
 					<action function="set">tw_complete_text1={@wipe_cache_dalvik_complete=Cache &amp; Dalvik Wipe Complete}</action>
-					<action function="set">tw_slider_text={@swipe_wipe_s=   Wipe}</action>
+					<action function="set">tw_slider_text={@swipe_wipe=Swipe to Wipe}</action>
+					<action function="page">confirm_action</action>
+				</actions>
+			</button>
+
+			<button style="main_button_half_height">
+				<condition var1="tw_ab_device" var2="1"/>
+				<placement x="%indent%" y="%row21a_y%"/>
+				<text>{@wipe_dalvik_btn=Wipe Dalvik}</text>
+				<actions>
+					<action function="set">tw_back=flash_done</action>
+					<action function="set">tw_action=wipe</action>
+					<action function="set">tw_action_param=dalvik</action>
+					<action function="set">tw_text1={@wipe_dalvik_confirm=Wipe Dalvik?}</action>
+					<action function="set">tw_action_text1={@wiping_cache_dalvik=Wiping Dalvik...}</action>
+					<action function="set">tw_complete_text1={@wipe_dalvik_complete=Dalvik Wipe Complete}</action>
+					<action function="set">tw_slider_text={@swipe_wipe=Swipe to Wipe}</action>
 					<action function="page">confirm_action</action>
 				</actions>
 			</button>
diff --git a/openrecoveryscript.cpp b/openrecoveryscript.cpp
old mode 100644
new mode 100755
index 86c90a6..d4d4da5
--- a/openrecoveryscript.cpp
+++ b/openrecoveryscript.cpp
@@ -62,17 +62,18 @@
 #define SCRIPT_COMMAND_SIZE 512
 
 int OpenRecoveryScript::check_for_script_file(void) {
-	if (!PartitionManager.Mount_By_Path(SCRIPT_FILE_CACHE, false)) {
-		LOGINFO("Unable to mount /cache for OpenRecoveryScript support.\n");
-		gui_msg(Msg(msg::kError, "unable_to_mount=Unable to mount {1}")(SCRIPT_FILE_CACHE));
+	std::string orsFile = TWFunc::get_cache_dir() + "/recovery/openrecoveryscript";
+	if (!PartitionManager.Mount_By_Path(orsFile, false)) {
+		LOGINFO("Unable to mount %s for OpenRecoveryScript support.\n", TWFunc::get_cache_dir().c_str());
+		gui_msg(Msg(msg::kError, "unable_to_mount=Unable to mount {1}")(TWFunc::get_cache_dir()));
 		return 0;
 	}
-	if (TWFunc::Path_Exists(SCRIPT_FILE_CACHE)) {
-		LOGINFO("Script file found: '%s'\n", SCRIPT_FILE_CACHE);
+	if (TWFunc::Path_Exists(orsFile)) {
+		LOGINFO("Script file found: '%s'\n", orsFile.c_str());
 		// Copy script file to /tmp
-		TWFunc::copy_file(SCRIPT_FILE_CACHE, SCRIPT_FILE_TMP, 0755);
-		// Delete the file from /cache
-		unlink(SCRIPT_FILE_CACHE);
+		TWFunc::copy_file(orsFile, SCRIPT_FILE_TMP, 0755);
+		// Delete the file from cache
+		unlink(orsFile.c_str());
 		return 1;
 	}
 	return 0;
@@ -655,6 +656,10 @@
 		gui_msg("decrypt_cmd=Attempting to decrypt data partition via command line.");
 		if (PartitionManager.Decrypt_Device(pass) == 0) {
 			// set_page_done = 1;  // done by singleaction_page anyway
+			std::string orsFile = TWFunc::get_cache_dir() + "/openrecoveryscript";
+			if (TWFunc::Path_Exists(orsFile)) {
+				Run_OpenRecoveryScript_Action();
+			}
 		}
 	} else if (OpenRecoveryScript::Insert_ORS_Command(command)) {
 		OpenRecoveryScript::run_script_file();
diff --git a/partitionmanager.cpp b/partitionmanager.cpp
old mode 100644
new mode 100755
index 45460d1..b8a95ff
--- a/partitionmanager.cpp
+++ b/partitionmanager.cpp
@@ -1343,9 +1343,14 @@
 		return false;
 
 	dir.push_back("/data/dalvik-cache");
-	if (Mount_By_Path("/cache", false)) {
-		dir.push_back("/cache/dalvik-cache");
-		dir.push_back("/cache/dc");
+
+	std::string cacheDir = TWFunc::get_cache_dir();
+	if (cacheDir == NON_AB_CACHE_DIR) {
+		if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
+			LOGINFO("Unable to mount %s for wiping cache.\n", NON_AB_CACHE_DIR);
+		}
+		dir.push_back(cacheDir + "dalvik-cache");
+		dir.push_back(cacheDir + "/dc");
 	}
 
 	TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
@@ -1357,14 +1362,24 @@
 		}
 	}
 
-	gui_msg("wiping_dalvik=Wiping Dalvik Cache Directories...");
+	if (cacheDir == NON_AB_CACHE_DIR) {
+		gui_msg("wiping_cache_dalvik=Wiping Dalvik Cache Directories...");
+	} else {
+		gui_msg("wiping_dalvik=Wiping Dalvik Directory...");
+	}
 	for (unsigned i = 0; i < dir.size(); ++i) {
 		if (stat(dir.at(i).c_str(), &st) == 0) {
 			TWFunc::removeDir(dir.at(i), false);
 			gui_msg(Msg("cleaned=Cleaned: {1}...")(dir.at(i)));
 		}
 	}
-	gui_msg("dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
+
+	if (cacheDir == NON_AB_CACHE_DIR) {
+		gui_msg("cache_dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
+	} else {
+		gui_msg("dalvik_done=-- Dalvik Directory Wipe Complete!");
+	}
+
 	return true;
 }
 
@@ -2194,10 +2209,12 @@
 	std::vector<TWPartition*>::iterator iter;
 	char storage_partition[255];
 	string Temp;
-	FILE *fp = fopen("/cache/recovery/storage.fstab", "w");
+
+	std::string storageFstab = TWFunc::get_cache_dir() + "recovery/storage.fstab";
+	FILE *fp = fopen(storageFstab.c_str(), "w");
 
 	if (fp == NULL) {
-		gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")("/cache/recovery/storage.fstab"));
+		gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")(storageFstab));
 		return;
 	}
 
diff --git a/twrp-functions.cpp b/twrp-functions.cpp
old mode 100644
new mode 100755
index 00a57a7..37dd0df
--- a/twrp-functions.cpp
+++ b/twrp-functions.cpp
@@ -37,6 +37,7 @@
 #include <sstream>
 #include <cctype>
 #include <algorithm>
+#include <selinux/label.h>
 #include "twrp-functions.hpp"
 #include "twcommon.h"
 #include "gui/gui.hpp"
@@ -58,6 +59,8 @@
 	#include "libcrecovery/common.h"
 }
 
+struct selabel_handle *selinux_handle;
+
 /* Execute a command */
 int TWFunc::Exec_Cmd(const string& cmd, string &result) {
 	FILE* exec;
@@ -520,28 +523,29 @@
 }
 
 void TWFunc::Update_Log_File(void) {
-	// Copy logs to cache so the system can find out what happened.
-	if (PartitionManager.Mount_By_Path("/cache", false)) {
-		if (!TWFunc::Path_Exists("/cache/recovery/.")) {
-			LOGINFO("Recreating /cache/recovery folder.\n");
-			if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
-				LOGINFO("Unable to create /cache/recovery folder.\n");
+	std::string recoveryDir = get_cache_dir() + "recovery/";
+
+	if (get_cache_dir() == NON_AB_CACHE_DIR) {
+		if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
+			LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", NON_AB_CACHE_DIR);
 		}
-		Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
-		copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
-		chown("/cache/recovery/log", 1000, 1000);
-		chmod("/cache/recovery/log", 0600);
-		chmod("/cache/recovery/last_log", 0640);
-	} else if (PartitionManager.Mount_By_Path("/data", false) && TWFunc::Path_Exists("/data/cache/recovery/.")) {
-		Copy_Log(TMP_LOG_FILE, "/data/cache/recovery/log");
-		copy_file("/data/cache/recovery/log", "/data/cache/recovery/last_log", 600);
-		chown("/data/cache/recovery/log", 1000, 1000);
-		chmod("/data/cache/recovery/log", 0600);
-		chmod("/data/cache/recovery/last_log", 0640);
-	} else {
-		LOGINFO("Failed to mount /cache or find /data/cache for TWFunc::Update_Log_File\n");
 	}
 
+	if (!TWFunc::Path_Exists(recoveryDir)) {
+		LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
+		if (mkdir(recoveryDir.c_str(),  S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0) {
+			LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
+		}
+	}
+
+	std::string logCopy = recoveryDir + "log";
+	std::string lastLogCopy = recoveryDir + "last_log";
+	copy_file(logCopy, lastLogCopy, 600);
+	Copy_Log(TMP_LOG_FILE, logCopy);
+	chown(logCopy.c_str(), 1000, 1000);
+	chmod(logCopy.c_str(), 0600);
+	chmod(lastLogCopy.c_str(), 0640);
+
 	// Reset bootloader message
 	TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
 	if (Part != NULL) {
@@ -555,12 +559,13 @@
 		}
 	}
 
-	if (PartitionManager.Mount_By_Path("/cache", false)) {
-		if (unlink("/cache/recovery/command") && errno != ENOENT) {
-			LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
+	if (get_cache_dir() == NON_AB_CACHE_DIR) {
+		if (PartitionManager.Mount_By_Path("/cache", false)) {
+			if (unlink("/cache/recovery/command") && errno != ENOENT) {
+				LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
+			}
 		}
 	}
-
 	sync();
 }
 
@@ -1154,4 +1159,58 @@
 		return -1;
 	return ret;
 }
+
+std::string TWFunc::get_cache_dir() {
+	if (PartitionManager.Find_Partition_By_Path(NON_AB_CACHE_DIR) == NULL) {
+		return AB_CACHE_DIR;
+	}
+	else {
+		return NON_AB_CACHE_DIR;
+	}
+}
+
+void TWFunc::check_selinux_support() {
+	if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
+		if (TWFunc::Path_Exists("/file_contexts")) {
+			printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
+			rename("/file_contexts", "/file_contexts.bak");
+		}
+		printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
+		rename("/prebuilt_file_contexts", "/file_contexts");
+	}
+	struct selinux_opt selinux_options[] = {
+		{ SELABEL_OPT_PATH, "/file_contexts" }
+	};
+	selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
+	if (!selinux_handle)
+		printf("No file contexts for SELinux\n");
+	else
+		printf("SELinux contexts loaded from /file_contexts\n");
+	{ // Check to ensure SELinux can be supported by the kernel
+		char *contexts = NULL;
+		std::string cacheDir = TWFunc::get_cache_dir();
+		std::string se_context_check = cacheDir + "recovery/";
+		int ret = 0;
+
+		if (cacheDir == NON_AB_CACHE_DIR) {
+			PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false);
+		}
+		if (TWFunc::Path_Exists(se_context_check)) {
+			ret = lgetfilecon(se_context_check.c_str(), &contexts);
+			if (ret > 0) {
+				lsetfilecon(se_context_check.c_str(), "test");
+				lgetfilecon(se_context_check.c_str(), &contexts);
+			} else {
+				LOGINFO("Could not check %s SELinux contexts, using /sbin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
+				lgetfilecon("/sbin/teamwin", &contexts);
+			}
+		}
+		if (ret < 0) {
+			gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
+		} else {
+			free(contexts);
+			gui_msg("full_selinux=Full SELinux support is present.");
+		}
+	}
+}
 #endif // ndef BUILD_TWRPTAR_MAIN
diff --git a/twrp-functions.hpp b/twrp-functions.hpp
old mode 100644
new mode 100755
index 0efbdc9..7847aed
--- a/twrp-functions.hpp
+++ b/twrp-functions.hpp
@@ -26,6 +26,9 @@
 
 using namespace std;
 
+#define NON_AB_CACHE_DIR "/cache/"
+#define AB_CACHE_DIR "/data/cache/"
+
 typedef enum
 {
 	rb_current = 0,
@@ -99,6 +102,8 @@
 	static void copy_kernel_log(string curr_storage); // Copy Kernel Log to Current Storage (PSTORE/KMSG)
 	static bool isNumber(string strtocheck); // return true if number, false if not a number
 	static int stream_adb_backup(string &Restore_Name); // Tell ADB Backup to Stream to TWRP from GUI selection
+	static std::string get_cache_dir(); // return the cache partition existence
+	static void check_selinux_support(); // print whether selinux support is enabled to console
 
 private:
 	static void Copy_Log(string Source, string Destination);
diff --git a/twrp.cpp b/twrp.cpp
old mode 100644
new mode 100755
index 2399c0b..6b9cd75
--- a/twrp.cpp
+++ b/twrp.cpp
@@ -54,9 +54,6 @@
 }
 #endif
 
-#include <selinux/label.h>
-struct selabel_handle *selinux_handle;
-
 //extern int adb_server_main(int is_daemon, int server_port, int /* reply_fd */);
 
 TWPartitionManager PartitionManager;
@@ -129,45 +126,6 @@
 	// Load up all the resources
 	gui_loadResources();
 
-	if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
-		if (TWFunc::Path_Exists("/file_contexts")) {
-			printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
-			rename("/file_contexts", "/file_contexts.bak");
-		}
-		printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
-		rename("/prebuilt_file_contexts", "/file_contexts");
-	}
-	struct selinux_opt selinux_options[] = {
-		{ SELABEL_OPT_PATH, "/file_contexts" }
-	};
-	selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
-	if (!selinux_handle)
-		printf("No file contexts for SELinux\n");
-	else
-		printf("SELinux contexts loaded from /file_contexts\n");
-	{ // Check to ensure SELinux can be supported by the kernel
-		char *contexts = NULL;
-
-		if (PartitionManager.Mount_By_Path("/cache", false) && TWFunc::Path_Exists("/cache/recovery")) {
-			lgetfilecon("/cache/recovery", &contexts);
-			if (!contexts) {
-				lsetfilecon("/cache/recovery", "test");
-				lgetfilecon("/cache/recovery", &contexts);
-			}
-		} else {
-			LOGINFO("Could not check /cache/recovery SELinux contexts, using /sbin/teamwin instead which may be inaccurate.\n");
-			lgetfilecon("/sbin/teamwin", &contexts);
-		}
-		if (!contexts) {
-			gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
-		} else {
-			free(contexts);
-			gui_msg("full_selinux=Full SELinux support is present.");
-		}
-	}
-
-	PartitionManager.Mount_By_Path("/cache", false);
-
 	bool Shutdown = false;
 	bool SkipDecryption = false;
 	string Send_Intent = "";
@@ -272,7 +230,6 @@
 	LOGINFO("Backup of TWRP ramdisk done.\n");
 #endif
 
-	TWFunc::Update_Log_File();
 	// Offer to decrypt if the device is encrypted
 	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) != 0) {
 		if (SkipDecryption) {
@@ -283,10 +240,12 @@
 				LOGERR("Failed to start decrypt GUI page.\n");
 			} else {
 				// Check for and load custom theme if present
+				TWFunc::check_selinux_support();
 				gui_loadCustomResources();
 			}
 		}
 	} else if (datamedia) {
+		TWFunc::check_selinux_support();
 		if (tw_get_default_metadata(DataManager::GetSettingsStoragePath().c_str()) != 0) {
 			LOGINFO("Failed to get default contexts and file mode for storage files.\n");
 		} else {
@@ -294,17 +253,20 @@
 		}
 	}
 
-	// Read the settings file
-	DataManager::ReadSettingsFile();
-	PageManager::LoadLanguage(DataManager::GetStrValue("tw_language"));
-	GUIConsole::Translate_Now();
-
 	// Fixup the RTC clock on devices which require it
 	if (crash_counter == 0)
 		TWFunc::Fixup_Time_On_Boot();
 
+	// Read the settings file
+	TWFunc::Update_Log_File();
+	DataManager::ReadSettingsFile();
+	PageManager::LoadLanguage(DataManager::GetStrValue("tw_language"));
+	GUIConsole::Translate_Now();
+
 	// Run any outstanding OpenRecoveryScript
-	if ((DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0 || SkipDecryption) && (TWFunc::Path_Exists(SCRIPT_FILE_TMP) || TWFunc::Path_Exists(SCRIPT_FILE_CACHE))) {
+	std::string cacheDir = TWFunc::get_cache_dir();
+	std::string orsFile = cacheDir + "/recovery/openrecoveryscript";
+	if ((DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0 || SkipDecryption) && (TWFunc::Path_Exists(SCRIPT_FILE_TMP) || TWFunc::Path_Exists(orsFile))) {
 		OpenRecoveryScript::Run_OpenRecoveryScript();
 	}
 
@@ -388,3 +350,4 @@
 
 	return 0;
 }
+
diff --git a/variables.h b/variables.h
index 53529f1..22eb5c9 100644
--- a/variables.h
+++ b/variables.h
@@ -160,8 +160,6 @@
 #define CUSTOM_LUN_FILE "/sys/class/android_usb/android0/f_mass_storage/lun%d/file"
 #endif
 
-// For OpenRecoveryScript
-#define SCRIPT_FILE_CACHE "/cache/recovery/openrecoveryscript"
 #define SCRIPT_FILE_TMP "/tmp/openrecoveryscript"
 #define TMP_LOG_FILE "/tmp/recovery.log"