Patches as of 2018-03-06 release
diff --git a/patches/platform_build/0001-Add-PRODUCT_SYSTEM_DEFAULT_PROPERTIES.patch b/patches/platform_build/0001-Add-PRODUCT_SYSTEM_DEFAULT_PROPERTIES.patch
new file mode 100644
index 0000000..893c807
--- /dev/null
+++ b/patches/platform_build/0001-Add-PRODUCT_SYSTEM_DEFAULT_PROPERTIES.patch
@@ -0,0 +1,80 @@
+From cd16437f867940eeeea039e40e4cb926b493a48e Mon Sep 17 00:00:00 2001
+From: Jaekyun Seok <jaekyun@google.com>
+Date: Fri, 3 Nov 2017 15:18:55 +0900
+Subject: [PATCH 1/3] Add PRODUCT_SYSTEM_DEFAULT_PROPERTIES
+
+PRODUCT_SYSTEM_DEFAULT_PROPERTIES will be used to define system default
+properties which should be installed in system partition.
+
+Bug: 64661857
+Test: confirmed that ART default properties are stored in
+/system/etc/prop.default when they were defined in
+PRODUCT_SYSTEM_DEFAULT_PROPERTIES.
+
+Change-Id: Ia08c25d0c5805381c6e3fe63dd1d171e8d195b90
+---
+ core/Makefile          | 3 ++-
+ core/product-graph.mk  | 1 +
+ core/product.mk        | 1 +
+ core/product_config.mk | 7 +++++++
+ 4 files changed, 11 insertions(+), 1 deletion(-)
+
+diff --git a/core/Makefile b/core/Makefile
+index 618e98317..77a817cd5 100644
+--- a/core/Makefile
++++ b/core/Makefile
+@@ -90,7 +90,8 @@ INSTALLED_DEFAULT_PROP_TARGET := $(TARGET_ROOT_OUT)/default.prop
+ endif
+ ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_DEFAULT_PROP_TARGET)
+ FINAL_DEFAULT_PROPERTIES := \
+-    $(call collapse-pairs, $(ADDITIONAL_DEFAULT_PROPERTIES))
++    $(call collapse-pairs, $(ADDITIONAL_DEFAULT_PROPERTIES)) \
++    $(call collapse-pairs, $(PRODUCT_SYSTEM_DEFAULT_PROPERTIES))
+ ifndef property_overrides_split_enabled
+   FINAL_DEFAULT_PROPERTIES += \
+       $(call collapse-pairs, $(PRODUCT_DEFAULT_PROPERTY_OVERRIDES))
+diff --git a/core/product-graph.mk b/core/product-graph.mk
+index 36e903723..dc9a29646 100644
+--- a/core/product-graph.mk
++++ b/core/product-graph.mk
+@@ -103,6 +103,7 @@ $(OUT_DIR)/products/$(strip $(1)).txt: $(this_makefile)
+ 	$(hide) echo 'PRODUCT_MANUFACTURER=$$(PRODUCTS.$(strip $(1)).PRODUCT_MANUFACTURER)' >> $$@
+ 	$(hide) echo 'PRODUCT_PROPERTY_OVERRIDES=$$(PRODUCTS.$(strip $(1)).PRODUCT_PROPERTY_OVERRIDES)' >> $$@
+ 	$(hide) echo 'PRODUCT_DEFAULT_PROPERTY_OVERRIDES=$$(PRODUCTS.$(strip $(1)).PRODUCT_DEFAULT_PROPERTY_OVERRIDES)' >> $$@
++	$(hide) echo 'PRODUCT_SYSTEM_DEFAULT_PROPERTIES=$$(PRODUCTS.$(strip $(1)).PRODUCT_SYSTEM_DEFAULT_PROPERTIES)' >> $$@
+ 	$(hide) echo 'PRODUCT_CHARACTERISTICS=$$(PRODUCTS.$(strip $(1)).PRODUCT_CHARACTERISTICS)' >> $$@
+ 	$(hide) echo 'PRODUCT_COPY_FILES=$$(PRODUCTS.$(strip $(1)).PRODUCT_COPY_FILES)' >> $$@
+ 	$(hide) echo 'PRODUCT_OTA_PUBLIC_KEYS=$$(PRODUCTS.$(strip $(1)).PRODUCT_OTA_PUBLIC_KEYS)' >> $$@
+diff --git a/core/product.mk b/core/product.mk
+index 4682dac99..ea6cd30fa 100644
+--- a/core/product.mk
++++ b/core/product.mk
+@@ -112,6 +112,7 @@ _product_var_list := \
+     PRODUCT_SUPPORTS_VERITY \
+     PRODUCT_SUPPORTS_VERITY_FEC \
+     PRODUCT_OEM_PROPERTIES \
++    PRODUCT_SYSTEM_DEFAULT_PROPERTIES \
+     PRODUCT_SYSTEM_PROPERTY_BLACKLIST \
+     PRODUCT_SYSTEM_SERVER_APPS \
+     PRODUCT_SYSTEM_SERVER_JARS \
+diff --git a/core/product_config.mk b/core/product_config.mk
+index f7ae834fb..330497f5b 100644
+--- a/core/product_config.mk
++++ b/core/product_config.mk
+@@ -359,6 +359,13 @@ PRODUCT_DEFAULT_PROPERTY_OVERRIDES := \
+     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEFAULT_PROPERTY_OVERRIDES))
+ .KATI_READONLY := PRODUCT_DEFAULT_PROPERTY_OVERRIDES
+ 
++# A list of property assignments, like "key = value", with zero or more
++# whitespace characters on either side of the '='.
++# used for adding properties to default.prop of system partition
++PRODUCT_SYSTEM_DEFAULT_PROPERTIES := \
++    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_DEFAULT_PROPERTIES))
++.KATI_READONLY := PRODUCT_SYSTEM_DEFAULT_PROPERTIES
++
+ # Should we use the default resources or add any product specific overlays
+ PRODUCT_PACKAGE_OVERLAYS := \
+     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGE_OVERLAYS))
+-- 
+2.15.1
+
diff --git a/patches/platform_build/0002-Move-ART-default-properties-into-system-partition.patch b/patches/platform_build/0002-Move-ART-default-properties-into-system-partition.patch
new file mode 100644
index 0000000..5695ad4
--- /dev/null
+++ b/patches/platform_build/0002-Move-ART-default-properties-into-system-partition.patch
@@ -0,0 +1,67 @@
+From 84e5d0e45c211c4e5e22acfea523ede244d34911 Mon Sep 17 00:00:00 2001
+From: Jaekyun Seok <jaekyun@google.com>
+Date: Fri, 3 Nov 2017 15:33:10 +0900
+Subject: [PATCH 2/3] Move ART default properties into system partition
+
+Bug: 64661857
+Bug: 68755013
+Test: confirmed that ART default properties were stored in
+/system/etc/prop.default on sailfish device
+
+Change-Id: Ie07d3049de5ac395cfb9105e208fe7825080fa15
+---
+ core/dex_preopt_libart.mk        | 4 +++-
+ target/product/runtime_libart.mk | 8 ++++----
+ 2 files changed, 7 insertions(+), 5 deletions(-)
+
+diff --git a/core/dex_preopt_libart.mk b/core/dex_preopt_libart.mk
+index 96160367b..15cb221b6 100644
+--- a/core/dex_preopt_libart.mk
++++ b/core/dex_preopt_libart.mk
+@@ -30,7 +30,9 @@ DIRTY_IMAGE_OBJECTS := $(call word-colon,1,$(firstword \
+     $(filter %system/etc/dirty-image-objects,$(PRODUCT_COPY_FILES))))
+ 
+ define get-product-default-property
+-$(strip $(patsubst $(1)=%,%,$(filter $(1)=%,$(PRODUCT_DEFAULT_PROPERTY_OVERRIDES))))
++$(strip \
++  $(eval _prop := $(patsubst $(1)=%,%,$(filter $(1)=%,$(PRODUCT_DEFAULT_PROPERTY_OVERRIDES))))\
++  $(if $(_prop),$(_prop),$(patsubst $(1)=%,%,$(filter $(1)=%,$(PRODUCT_SYSTEM_DEFAULT_PROPERTIES)))))
+ endef
+ 
+ DEX2OAT_IMAGE_XMS := $(call get-product-default-property,dalvik.vm.image-dex2oat-Xms)
+diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
+index 8aedee79c..f1b8f4596 100644
+--- a/target/product/runtime_libart.mk
++++ b/target/product/runtime_libart.mk
+@@ -56,7 +56,7 @@ PRODUCT_PACKAGES += art-tools
+ PRODUCT_PACKAGES += \
+     cacerts \
+ 
+-PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
++PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+     dalvik.vm.image-dex2oat-Xms=64m \
+     dalvik.vm.image-dex2oat-Xmx=64m \
+     dalvik.vm.dex2oat-Xms=64m \
+@@ -70,16 +70,16 @@ PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
+ # Different dexopt types for different package update/install times.
+ # On eng builds, make "boot" reasons only extract for faster turnaround.
+ ifeq (eng,$(TARGET_BUILD_VARIANT))
+-    PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
++    PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+         pm.dexopt.first-boot=extract \
+         pm.dexopt.boot=extract
+ else
+-    PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
++    PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+         pm.dexopt.first-boot=quicken \
+         pm.dexopt.boot=verify
+ endif
+ 
+-PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
++PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+     pm.dexopt.install=quicken \
+     pm.dexopt.bg-dexopt=speed-profile \
+     pm.dexopt.ab-ota=speed-profile \
+-- 
+2.15.1
+
diff --git a/patches/platform_build/0003-Set-ro.build.fingerprint-in-system-etc-prop.default.patch b/patches/platform_build/0003-Set-ro.build.fingerprint-in-system-etc-prop.default.patch
new file mode 100644
index 0000000..090ac53
--- /dev/null
+++ b/patches/platform_build/0003-Set-ro.build.fingerprint-in-system-etc-prop.default.patch
@@ -0,0 +1,24 @@
+From 98a31a76008d682563273b8196668b57c1b6ff14 Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@phh.me>
+Date: Mon, 5 Mar 2018 22:27:50 +0100
+Subject: [PATCH 3/3] Set ro.build.fingerprint in system/etc/prop.default
+
+---
+ core/Makefile | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/core/Makefile b/core/Makefile
+index 77a817cd5..e0f0e9145 100644
+--- a/core/Makefile
++++ b/core/Makefile
+@@ -116,6 +116,7 @@ $(INSTALLED_DEFAULT_PROP_TARGET): $(intermediate_system_build_prop)
+ 	$(hide) echo ro.bootimage.build.date=`$(DATE_FROM_FILE)`>>$@
+ 	$(hide) echo ro.bootimage.build.date.utc=`$(DATE_FROM_FILE) +%s`>>$@
+ 	$(hide) echo ro.bootimage.build.fingerprint="$(BUILD_FINGERPRINT_FROM_FILE)">>$@
++	$(hide) echo ro.build.fingerprint="$(BUILD_FINGERPRINT_FROM_FILE)">>$@
+ 	$(hide) build/tools/post_process_props.py $@
+ ifdef property_overrides_split_enabled
+ 	$(hide) mkdir -p $(TARGET_ROOT_OUT)
+-- 
+2.15.1
+
diff --git a/patches/platform_external_selinux/0001-libsepol-cil-Add-ability-to-redeclare-types-attribut.patch b/patches/platform_external_selinux/0001-libsepol-cil-Add-ability-to-redeclare-types-attribut.patch
new file mode 100644
index 0000000..d38aec2
--- /dev/null
+++ b/patches/platform_external_selinux/0001-libsepol-cil-Add-ability-to-redeclare-types-attribut.patch
@@ -0,0 +1,208 @@
+From be352c253dffb5c0d952fbeef905c3269853b7e0 Mon Sep 17 00:00:00 2001
+From: Dan Cashman <dcashman@android.com>
+Date: Tue, 29 Aug 2017 09:32:05 -0700
+Subject: [PATCH 1/5] libsepol: cil: Add ability to redeclare types[attributes]
+
+Modify cil_gen_node() to check to see if the cil_db supports multiple
+declarations, and if so, to check whether or not the
+repeated symbol is eligible to share the existing, already-stored datum. The
+only types considered so far are CIL_TYPE and CIL_TYPEATTRIBUTE, both of
+which intall empty datums during AST building, so they automatically return
+true.
+
+Test: Build policy with multilpe type and attribute declarations, and
+without. Policies are binary-identical.
+
+Signed-off-by: Dan Cashman <dcashman@android.com>
+Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
+---
+ libsepol/cil/include/cil/cil.h   |  1 +
+ libsepol/cil/src/cil.c           |  5 +++++
+ libsepol/cil/src/cil_build_ast.c | 48 ++++++++++++++++++++++++++++++++++------
+ libsepol/cil/src/cil_internal.h  |  1 +
+ libsepol/src/libsepol.map.in     |  1 +
+ secilc/secilc.c                  |  9 +++++++-
+ 6 files changed, 57 insertions(+), 8 deletions(-)
+
+diff --git a/libsepol/cil/include/cil/cil.h b/libsepol/cil/include/cil/cil.h
+index 4507892c..4df646a0 100644
+--- a/libsepol/cil/include/cil/cil.h
++++ b/libsepol/cil/include/cil/cil.h
+@@ -46,6 +46,7 @@ extern int cil_userprefixes_to_string(cil_db_t *db, char **out, size_t *size);
+ extern int cil_selinuxusers_to_string(cil_db_t *db, char **out, size_t *size);
+ extern int cil_filecons_to_string(cil_db_t *db, char **out, size_t *size);
+ extern void cil_set_disable_dontaudit(cil_db_t *db, int disable_dontaudit);
++extern void cil_set_multiple_decls(cil_db_t *db, int multiple_decls);
+ extern void cil_set_disable_neverallow(cil_db_t *db, int disable_neverallow);
+ extern void cil_set_preserve_tunables(cil_db_t *db, int preserve_tunables);
+ extern int cil_set_handle_unknown(cil_db_t *db, int handle_unknown);
+diff --git a/libsepol/cil/src/cil.c b/libsepol/cil/src/cil.c
+index 9b9ccc36..e8bbbfdf 100644
+--- a/libsepol/cil/src/cil.c
++++ b/libsepol/cil/src/cil.c
+@@ -1675,6 +1675,11 @@ void cil_set_mls(struct cil_db *db, int mls)
+ 	db->mls = mls;
+ }
+ 
++void cil_set_multiple_decls(struct cil_db *db, int multiple_decls)
++{
++	db->multiple_decls = multiple_decls;
++}
++
+ void cil_set_target_platform(struct cil_db *db, int target_platform)
+ {
+ 	db->target_platform = target_platform;
+diff --git a/libsepol/cil/src/cil_build_ast.c b/libsepol/cil/src/cil_build_ast.c
+index 36cc6735..9a10e7ab 100644
+--- a/libsepol/cil/src/cil_build_ast.c
++++ b/libsepol/cil/src/cil_build_ast.c
+@@ -82,10 +82,33 @@ exit:
+ 	return rc;
+ }
+ 
++/*
++ * Determine whether or not multiple declarations of the same key can share a
++ * datum, given the new datum and the one already present in a given symtab.
++ */
++int cil_is_datum_multiple_decl(__attribute__((unused)) struct cil_symtab_datum *cur,
++                               __attribute__((unused)) struct cil_symtab_datum *old,
++                               enum cil_flavor f)
++{
++	int rc = CIL_FALSE;
++
++	switch (f) {
++	case CIL_TYPE:
++	case CIL_TYPEATTRIBUTE:
++		/* type and typeattribute statements insert empty datums, ret true */
++		rc = CIL_TRUE;
++		break;
++	default:
++		break;
++	}
++	return rc;
++}
++
+ int cil_gen_node(__attribute__((unused)) struct cil_db *db, struct cil_tree_node *ast_node, struct cil_symtab_datum *datum, hashtab_key_t key, enum cil_sym_index sflavor, enum cil_flavor nflavor)
+ {
+ 	int rc = SEPOL_ERR;
+ 	symtab_t *symtab = NULL;
++	struct cil_symtab_datum *prev;
+ 
+ 	rc = __cil_verify_name((const char*)key);
+ 	if (rc != SEPOL_OK) {
+@@ -103,15 +126,26 @@ int cil_gen_node(__attribute__((unused)) struct cil_db *db, struct cil_tree_node
+ 	if (symtab != NULL) {
+ 		rc = cil_symtab_insert(symtab, (hashtab_key_t)key, datum, ast_node);
+ 		if (rc == SEPOL_EEXIST) {
+-			cil_log(CIL_ERR, "Re-declaration of %s %s\n", 
+-				cil_node_to_string(ast_node), key);
+-			if (cil_symtab_get_datum(symtab, key, &datum) == SEPOL_OK) {
+-				if (sflavor == CIL_SYM_BLOCKS) {
+-					struct cil_tree_node *node = datum->nodes->head->data;
+-					cil_tree_log(node, CIL_ERR, "Previous declaration");
++			if (!db->multiple_decls ||
++			    cil_symtab_get_datum(symtab, (hashtab_key_t)key, &prev) != SEPOL_OK ||
++			    !cil_is_datum_multiple_decl(datum, prev, nflavor)) {
++
++				/* multiple_decls not ok, ret error */
++				cil_log(CIL_ERR, "Re-declaration of %s %s\n",
++					cil_node_to_string(ast_node), key);
++				if (cil_symtab_get_datum(symtab, key, &datum) == SEPOL_OK) {
++					if (sflavor == CIL_SYM_BLOCKS) {
++						struct cil_tree_node *node = datum->nodes->head->data;
++						cil_tree_log(node, CIL_ERR, "Previous declaration");
++					}
+ 				}
++				goto exit;
+ 			}
+-			goto exit;
++			/* multiple_decls is enabled and works for this datum type, add node */
++			cil_list_append(prev->nodes, CIL_NODE, ast_node);
++			ast_node->data = prev;
++			cil_symtab_datum_destroy(datum);
++			free(datum);
+ 		}
+ 	}
+ 
+diff --git a/libsepol/cil/src/cil_internal.h b/libsepol/cil/src/cil_internal.h
+index aee3f00c..abfacd8d 100644
+--- a/libsepol/cil/src/cil_internal.h
++++ b/libsepol/cil/src/cil_internal.h
+@@ -312,6 +312,7 @@ struct cil_db {
+ 	int preserve_tunables;
+ 	int handle_unknown;
+ 	int mls;
++	int multiple_decls;
+ 	int target_platform;
+ 	int policy_version;
+ };
+diff --git a/libsepol/src/libsepol.map.in b/libsepol/src/libsepol.map.in
+index 40426408..edd98d5a 100644
+--- a/libsepol/src/libsepol.map.in
++++ b/libsepol/src/libsepol.map.in
+@@ -47,6 +47,7 @@ LIBSEPOL_1.1 {
+ 	cil_set_mls;
+ 	cil_set_attrs_expand_generated;
+ 	cil_set_attrs_expand_size;
++	cil_set_multiple_decls;
+ 	cil_write_policy_conf;
+ 	sepol_ppfile_to_module_package;
+ 	sepol_module_package_to_cil;
+diff --git a/secilc/secilc.c b/secilc/secilc.c
+index f2232e72..0be6975b 100644
+--- a/secilc/secilc.c
++++ b/secilc/secilc.c
+@@ -63,6 +63,7 @@ static __attribute__((__noreturn__)) void usage(const char *prog)
+ 	printf("                                 statement if present in the policy\n");
+ 	printf("  -D, --disable-dontaudit        do not add dontaudit rules to the binary policy\n");
+ 	printf("  -P, --preserve-tunables        treat tunables as booleans\n");
++	printf("  -m, --multiple-decls           allow some statements to be re-declared\n");
+ 	printf("  -N, --disable-neverallow       do not check neverallow rules\n");
+ 	printf("  -G, --expand-generated         Expand and remove auto-generated attributes\n");
+ 	printf("  -X, --expand-size <SIZE>       Expand type attributes with fewer than <SIZE>\n");
+@@ -89,6 +90,7 @@ int main(int argc, char *argv[])
+ 	int target = SEPOL_TARGET_SELINUX;
+ 	int mls = -1;
+ 	int disable_dontaudit = 0;
++	int multiple_decls = 0;
+ 	int disable_neverallow = 0;
+ 	int preserve_tunables = 0;
+ 	int handle_unknown = -1;
+@@ -108,6 +110,7 @@ int main(int argc, char *argv[])
+ 		{"policyversion", required_argument, 0, 'c'},
+ 		{"handle-unknown", required_argument, 0, 'U'},
+ 		{"disable-dontaudit", no_argument, 0, 'D'},
++		{"multiple-decls", no_argument, 0, 'm'},
+ 		{"disable-neverallow", no_argument, 0, 'N'},
+ 		{"preserve-tunables", no_argument, 0, 'P'},
+ 		{"output", required_argument, 0, 'o'},
+@@ -119,7 +122,7 @@ int main(int argc, char *argv[])
+ 	int i;
+ 
+ 	while (1) {
+-		opt_char = getopt_long(argc, argv, "o:f:U:hvt:M:PDNc:GX:", long_opts, &opt_index);
++		opt_char = getopt_long(argc, argv, "o:f:U:hvt:M:PDmNc:GX:", long_opts, &opt_index);
+ 		if (opt_char == -1) {
+ 			break;
+ 		}
+@@ -175,6 +178,9 @@ int main(int argc, char *argv[])
+ 			case 'D':
+ 				disable_dontaudit = 1;
+ 				break;
++			case 'm':
++				multiple_decls = 1;
++				break;
+ 			case 'N':
+ 				disable_neverallow = 1;
+ 				break;
+@@ -223,6 +229,7 @@ int main(int argc, char *argv[])
+ 
+ 	cil_db_init(&db);
+ 	cil_set_disable_dontaudit(db, disable_dontaudit);
++	cil_set_multiple_decls(db, multiple_decls);
+ 	cil_set_disable_neverallow(db, disable_neverallow);
+ 	cil_set_preserve_tunables(db, preserve_tunables);
+ 	if (handle_unknown != -1) {
+-- 
+2.15.1
+
diff --git a/patches/platform_external_selinux/0002-libsepol-cil-Keep-type-attribute-declarations-when-a.patch b/patches/platform_external_selinux/0002-libsepol-cil-Keep-type-attribute-declarations-when-a.patch
new file mode 100644
index 0000000..f88b855
--- /dev/null
+++ b/patches/platform_external_selinux/0002-libsepol-cil-Keep-type-attribute-declarations-when-a.patch
@@ -0,0 +1,89 @@
+From 0a0c8e77b3a55c70ef55cd78aa5c2a4bce5b0862 Mon Sep 17 00:00:00 2001
+From: Dan Cashman <dcashman@google.com>
+Date: Wed, 11 Oct 2017 12:59:43 -0700
+Subject: [PATCH 2/5] libsepol: cil: Keep type[attribute] declarations when
+ attributizing.
+
+cil_android_attributize() uses a source policy to identify types and
+attributes to be versioned according to the given version number, and
+then proceeds to modify the provided target policy to provide this
+versioning.  Previously, the versioned policy relied on a base policy
+for the declarations of these type[attribute]s, but with multiple_decl
+support added, the declarations can be made in both places.  This will
+make the policy more robust and allow for greater flexibility and the
+types of base policy used.
+
+Bug: 37915794
+Test: Builds 'n' boots.  non_plat_sepolicy.cil now contains the public
+type[attribute] declarations.
+
+Change-Id: Iaa084211a9e2774a7ed391888fb21c4c0cf955db
+---
+ libsepol/cil/include/cil/android.h |  2 ++
+ libsepol/cil/src/android.c         | 17 ++++++++---------
+ 2 files changed, 10 insertions(+), 9 deletions(-)
+
+diff --git a/libsepol/cil/include/cil/android.h b/libsepol/cil/include/cil/android.h
+index 082d7fd2..5aceda62 100644
+--- a/libsepol/cil/include/cil/android.h
++++ b/libsepol/cil/include/cil/android.h
+@@ -21,6 +21,8 @@ int cil_android_attrib_mapping(struct cil_db **mdb, struct cil_db *srcdb, const
+ /*
+  * cil_android_attributize - extract attributizable elements of the policy in
+  * srcdb and convert all usage of those elements in tgtdb to versioned attributes.
++ * Keep the attributes and type definitions so that tgtdb policy is more robust
++ * against future changes to the public policy.
+  *   tgtdb - initialized and parsed cil_db reference to modify.
+  *   srcdb - initialized and parsed cil_db reference to source public policy
+  *           from which to extract attributizable elements.
+diff --git a/libsepol/cil/src/android.c b/libsepol/cil/src/android.c
+index 1d80046b..53df4187 100644
+--- a/libsepol/cil/src/android.c
++++ b/libsepol/cil/src/android.c
+@@ -200,23 +200,27 @@ static char *__cil_attrib_get_versname(char *old, const char *vers)
+ 
+ /*
+  * Change type to attribute - create new versioned name based on old, create
+- * typeattribute node and replace existing type node.
++ * typeattribute node add to the existing type node.
+  */
+ static int __cil_attrib_convert_type(struct cil_tree_node *node, struct version_args *args)
+ {
+ 	int rc = SEPOL_ERR;
+ 	struct cil_type *type = (struct cil_type *)node->data;
+ 	struct cil_typeattribute *typeattr = NULL;
++	struct cil_tree_node *new_ast_node = NULL;
+ 	char *new_key;
+ 
+ 	cil_typeattribute_init(&typeattr);
+ 
+ 	new_key = __cil_attrib_get_versname(type->datum.name, args->num);
+ 
+-	cil_symtab_datum_remove_node(&type->datum, node);
+-	cil_destroy_type(type);
++	/* create new tree node to contain typeattribute and add to tree */
++	cil_tree_node_init(&new_ast_node);
++	new_ast_node->parent = node->parent;
++	new_ast_node->next = node->next;
++	node->next = new_ast_node;
+ 
+-	rc = cil_gen_node(args->db, node, (struct cil_symtab_datum *) typeattr,
++	rc = cil_gen_node(args->db, new_ast_node, (struct cil_symtab_datum *) typeattr,
+ 			  new_key, CIL_SYM_TYPES, CIL_TYPEATTRIBUTE);
+ 	if (rc != SEPOL_OK) {
+ 		goto exit;
+@@ -422,11 +426,6 @@ static int cil_attrib_typeattribute(struct cil_tree_node *node, struct version_a
+ 		if (rc != SEPOL_OK) {
+ 			goto exit;
+ 		}
+-	} else if (__cil_get_plat_flavor(args->vers_map, key) == PLAT_ATTRIB) {
+-		// platform attribute declaration to be provided by platform policy
+-		cil_symtab_datum_remove_node(&typeattr->datum, node);
+-		cil_destroy_typeattribute(typeattr);
+-		node->flavor = CIL_NONE; // traversal relies on this node sticking around, empty it.
+ 	}
+ 
+ 	return SEPOL_OK;
+-- 
+2.15.1
+
diff --git a/patches/platform_external_selinux/0003-libsepol-cil-Create-new-keep-field-for-type-attribut.patch b/patches/platform_external_selinux/0003-libsepol-cil-Create-new-keep-field-for-type-attribut.patch
new file mode 100644
index 0000000..86f94f1
--- /dev/null
+++ b/patches/platform_external_selinux/0003-libsepol-cil-Create-new-keep-field-for-type-attribut.patch
@@ -0,0 +1,138 @@
+From 92fac49b74a4d83bd07b086e35f3e7dfe84fd429 Mon Sep 17 00:00:00 2001
+From: James Carter <jwcart2@tycho.nsa.gov>
+Date: Fri, 17 Nov 2017 08:09:52 -0500
+Subject: [PATCH 3/5] libsepol/cil: Create new keep field for type attribute
+ sets
+
+Daniel Cashman <dcashman@android.com> discovered the following:
+When using cil_db multiple_decls, the different cil_attribute nodes
+all point to the same underlying cil_attribute struct.  This leads
+to problems, though, when modifying the used value in the struct.
+__cil_post_db_attr() changes the value of the field to based on
+the output of cil_typeattribute_used(), for use later in
+cil_typeattribute_to_policydb and cil_typeattribute_to_bitmap, but
+due to the multiple declarations, cil_typeattribute_used() could be
+called again by a second node.  In this second call, the value used
+is the modifed value of CIL_TRUE or CIL_FALSE, not the flags actually
+needed. This could result in the field being reset again, to an
+incorrect CIL_FALSE value.
+
+Add the field "keep" to struct cil_typeattributeset, set its value
+using cil_typeattribute_used(), and use it when determining whether
+the attribute is to be kept or if it should be expanded.
+
+Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
+---
+ libsepol/cil/src/cil.c           | 1 +
+ libsepol/cil/src/cil_binary.c    | 8 ++++----
+ libsepol/cil/src/cil_internal.h  | 1 +
+ libsepol/cil/src/cil_policy.c    | 2 +-
+ libsepol/cil/src/cil_post.c      | 2 +-
+ libsepol/cil/src/cil_reset_ast.c | 1 +
+ 6 files changed, 9 insertions(+), 6 deletions(-)
+
+diff --git a/libsepol/cil/src/cil.c b/libsepol/cil/src/cil.c
+index e8bbbfdf..a5a3e263 100644
+--- a/libsepol/cil/src/cil.c
++++ b/libsepol/cil/src/cil.c
+@@ -2038,6 +2038,7 @@ void cil_typeattribute_init(struct cil_typeattribute **attr)
+ 	(*attr)->expr_list = NULL;
+ 	(*attr)->types = NULL;
+ 	(*attr)->used = CIL_FALSE;
++	(*attr)->keep = CIL_FALSE;
+ }
+ 
+ void cil_typeattributeset_init(struct cil_typeattributeset **attrset)
+diff --git a/libsepol/cil/src/cil_binary.c b/libsepol/cil/src/cil_binary.c
+index e1481a43..1818ffa9 100644
+--- a/libsepol/cil/src/cil_binary.c
++++ b/libsepol/cil/src/cil_binary.c
+@@ -567,7 +567,7 @@ int cil_typeattribute_to_policydb(policydb_t *pdb, struct cil_typeattribute *cil
+ 	char *key = NULL;
+ 	type_datum_t *sepol_attr = NULL;
+ 
+-	if (!cil_attr->used) {
++	if (!cil_attr->keep) {
+ 		return SEPOL_OK;		
+ 	}
+ 
+@@ -632,7 +632,7 @@ int cil_typeattribute_to_bitmap(policydb_t *pdb, const struct cil_db *db, struct
+ 	ebitmap_node_t *tnode;
+ 	unsigned int i;
+ 
+-	if (!cil_attr->used) {
++	if (!cil_attr->keep) {
+ 		return SEPOL_OK;
+ 	}
+ 
+@@ -1442,7 +1442,7 @@ static int __cil_should_expand_attribute( const struct cil_db *db, struct cil_sy
+ 
+ 	attr = (struct cil_typeattribute *)datum;
+ 
+-	return !attr->used || (ebitmap_cardinality(attr->types) < db->attrs_expand_size);
++	return !attr->keep || (ebitmap_cardinality(attr->types) < db->attrs_expand_size);
+ }
+ 
+ int __cil_avrule_to_avtab(policydb_t *pdb, const struct cil_db *db, struct cil_avrule *cil_avrule, cond_node_t *cond_node, enum cil_flavor cond_flavor)
+@@ -2525,7 +2525,7 @@ int __cil_constrain_expr_datum_to_sepol_expr(policydb_t *pdb, const struct cil_d
+ 			if (rc != SEPOL_OK) {
+ 				if (FLAVOR(item->data) == CIL_TYPEATTRIBUTE) {
+ 					struct cil_typeattribute *attr = item->data;
+-					if (!attr->used) {
++					if (!attr->keep) {
+ 						rc = 0;
+ 					}
+ 				}
+diff --git a/libsepol/cil/src/cil_internal.h b/libsepol/cil/src/cil_internal.h
+index abfacd8d..942b28f0 100644
+--- a/libsepol/cil/src/cil_internal.h
++++ b/libsepol/cil/src/cil_internal.h
+@@ -527,6 +527,7 @@ struct cil_typeattribute {
+ 	struct cil_list *expr_list;
+ 	ebitmap_t *types;
+ 	int used;	// whether or not this attribute was used in a binary policy rule
++	int keep;
+ };
+ 
+ struct cil_typeattributeset {
+diff --git a/libsepol/cil/src/cil_policy.c b/libsepol/cil/src/cil_policy.c
+index 77179e63..3e511330 100644
+--- a/libsepol/cil/src/cil_policy.c
++++ b/libsepol/cil/src/cil_policy.c
+@@ -1085,7 +1085,7 @@ static void cil_typeattributes_to_policy(FILE *out, struct cil_list *types, stru
+ 		type = i1->data;
+ 		cil_list_for_each(i2, attributes) {
+ 			attribute = i2->data;
+-			if (!attribute->used)
++			if (!attribute->keep)
+ 				continue;
+ 			if (ebitmap_get_bit(attribute->types, type->value)) {
+ 				if (first) {
+diff --git a/libsepol/cil/src/cil_post.c b/libsepol/cil/src/cil_post.c
+index 1941fab3..a30de0e1 100644
+--- a/libsepol/cil/src/cil_post.c
++++ b/libsepol/cil/src/cil_post.c
+@@ -1250,7 +1250,7 @@ static int __cil_post_db_attr_helper(struct cil_tree_node *node, uint32_t *finis
+ 			rc = __evaluate_type_expression(attr, db);
+ 			if (rc != SEPOL_OK) goto exit;
+ 		}
+-		attr->used = cil_typeattribute_used(attr, db);
++		attr->keep = cil_typeattribute_used(attr, db);
+ 		break;
+ 	}
+ 	case CIL_ROLEATTRIBUTE: {
+diff --git a/libsepol/cil/src/cil_reset_ast.c b/libsepol/cil/src/cil_reset_ast.c
+index 676e156e..142179ee 100644
+--- a/libsepol/cil/src/cil_reset_ast.c
++++ b/libsepol/cil/src/cil_reset_ast.c
+@@ -186,6 +186,7 @@ static void cil_reset_typeattr(struct cil_typeattribute *attr)
+ 		attr->expr_list = NULL;
+ 	}
+ 	attr->used = CIL_FALSE;
++	attr->keep = CIL_FALSE;
+ }
+ 
+ static void cil_reset_typeattributeset(struct cil_typeattributeset *tas)
+-- 
+2.15.1
+
diff --git a/patches/platform_external_selinux/0004-Enable-multipl_decls-by-default.-This-is-needed-beca.patch b/patches/platform_external_selinux/0004-Enable-multipl_decls-by-default.-This-is-needed-beca.patch
new file mode 100644
index 0000000..edf02fa
--- /dev/null
+++ b/patches/platform_external_selinux/0004-Enable-multipl_decls-by-default.-This-is-needed-beca.patch
@@ -0,0 +1,27 @@
+From 6afcaac2da4ea0fad2e3aea4b579eddd02523e73 Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@phh.me>
+Date: Fri, 2 Mar 2018 22:49:55 +0100
+Subject: [PATCH 4/5] Enable multipl_decls by default. This is needed because
+ 8.0 init doesn't add -m
+
+Change-Id: I43dc661d519f7b8576d72a828d8cbd444592bf5e
+---
+ secilc/secilc.c | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/secilc/secilc.c b/secilc/secilc.c
+index 0be6975b..e30572e5 100644
+--- a/secilc/secilc.c
++++ b/secilc/secilc.c
+@@ -90,7 +90,7 @@ int main(int argc, char *argv[])
+ 	int target = SEPOL_TARGET_SELINUX;
+ 	int mls = -1;
+ 	int disable_dontaudit = 0;
+-	int multiple_decls = 0;
++	int multiple_decls = 1;
+ 	int disable_neverallow = 0;
+ 	int preserve_tunables = 0;
+ 	int handle_unknown = -1;
+-- 
+2.15.1
+
diff --git a/patches/platform_external_selinux/0005-Delete-identical-genfscon-s.patch b/patches/platform_external_selinux/0005-Delete-identical-genfscon-s.patch
new file mode 100644
index 0000000..bf664e1
--- /dev/null
+++ b/patches/platform_external_selinux/0005-Delete-identical-genfscon-s.patch
@@ -0,0 +1,42 @@
+From c334f823d0eccac2656ceceb707367680cca32f2 Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@phh.me>
+Date: Sat, 3 Mar 2018 19:02:29 +0100
+Subject: [PATCH 5/5] Delete identical genfscon-s
+
+Change-Id: I9775187b9da3568390ab66ebd59cb774b1283ad1
+---
+ libsepol/cil/src/cil_post.c | 11 +++++++++++
+ 1 file changed, 11 insertions(+)
+
+diff --git a/libsepol/cil/src/cil_post.c b/libsepol/cil/src/cil_post.c
+index a30de0e1..605847d1 100644
+--- a/libsepol/cil/src/cil_post.c
++++ b/libsepol/cil/src/cil_post.c
+@@ -53,6 +53,16 @@
+ static int __cil_expr_to_bitmap(struct cil_list *expr, ebitmap_t *out, int max, struct cil_db *db);
+ static int __cil_expr_list_to_bitmap(struct cil_list *expr_list, ebitmap_t *out, int max, struct cil_db *db);
+ 
++static int compact(void* array, int count, int len, int (*compar)(const void *, const void *)) {
++	char *a = (char*)array;
++	int j = 0;
++	for(int i=1; i<count; i++) {
++		if(compar(a+i*len, a+j*len) != 0) j++;
++		if(i != j) memcpy(a+j*len, a+i*len, len);
++	}
++	return j;
++}
++
+ static int cil_verify_is_list(struct cil_list *list, enum cil_flavor flavor)
+ {
+ 	struct cil_list_item *curr;
+@@ -1977,6 +1987,7 @@ static int cil_post_db(struct cil_db *db)
+ 
+ 	qsort(db->netifcon->array, db->netifcon->count, sizeof(db->netifcon->array), cil_post_netifcon_compare);
+ 	qsort(db->genfscon->array, db->genfscon->count, sizeof(db->genfscon->array), cil_post_genfscon_compare);
++	db->genfscon->count = compact(db->genfscon->array, db->genfscon->count, sizeof(db->genfscon->array), cil_post_genfscon_compare);
+ 	qsort(db->portcon->array, db->portcon->count, sizeof(db->portcon->array), cil_post_portcon_compare);
+ 	qsort(db->nodecon->array, db->nodecon->count, sizeof(db->nodecon->array), cil_post_nodecon_compare);
+ 	qsort(db->fsuse->array, db->fsuse->count, sizeof(db->fsuse->array), cil_post_fsuse_compare);
+-- 
+2.15.1
+
diff --git a/patches/platform_frameworks_base/0001-renderthread-relax-error-handling-for-wide-gamut-EGL.patch b/patches/platform_frameworks_base/0001-renderthread-relax-error-handling-for-wide-gamut-EGL.patch
new file mode 100644
index 0000000..73d2590
--- /dev/null
+++ b/patches/platform_frameworks_base/0001-renderthread-relax-error-handling-for-wide-gamut-EGL.patch
@@ -0,0 +1,36 @@
+From 8aff32ec3106530d1ea81ba536cd548760bd4ded Mon Sep 17 00:00:00 2001
+From: Rob Herring <robh@kernel.org>
+Date: Wed, 29 Nov 2017 09:26:31 -0600
+Subject: [PATCH 1/3] renderthread: relax error handling for wide gamut EGL
+ configs
+
+It is valid to advertise EGL_EXT_pixel_format_float, but not have a
+the requested EGL config. Instead of aborting, fallback to the default
+behavior.
+
+Change-Id: I6c602233b627dc2070364434fece57d3d0aab435
+Cc: Romain Guy <romainguy@google.com>
+Signed-off-by: Rob Herring <robh@kernel.org>
+---
+ libs/hwui/renderthread/EglManager.cpp | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/libs/hwui/renderthread/EglManager.cpp b/libs/hwui/renderthread/EglManager.cpp
+index 16d77364942..bd4708da562 100644
+--- a/libs/hwui/renderthread/EglManager.cpp
++++ b/libs/hwui/renderthread/EglManager.cpp
+@@ -223,9 +223,9 @@ void EglManager::loadConfigs() {
+         numConfigs = 1;
+         if (!eglChooseConfig(mEglDisplay, attribs16F, &mEglConfigWideGamut, numConfigs, &numConfigs)
+                 || numConfigs != 1) {
+-            LOG_ALWAYS_FATAL(
+-                    "Device claims wide gamut support, cannot find matching config, error = %s",
++            ALOGE("Device claims wide gamut support, cannot find matching config, error = %s",
+                     eglErrorString());
++            EglExtensions.pixelFormatFloat = false;
+         }
+     }
+ }
+-- 
+2.15.1
+
diff --git a/patches/platform_frameworks_base/0002-Reintroduce-button-backlight-and-respective-inactivi.patch b/patches/platform_frameworks_base/0002-Reintroduce-button-backlight-and-respective-inactivi.patch
new file mode 100644
index 0000000..e4afc1d
--- /dev/null
+++ b/patches/platform_frameworks_base/0002-Reintroduce-button-backlight-and-respective-inactivi.patch
@@ -0,0 +1,108 @@
+From d1cd1dbf69b4cb6c0046255c8015c58b10a90165 Mon Sep 17 00:00:00 2001
+From: Ricardo Cerqueira <cyanogenmod@cerqueira.org>
+Date: Fri, 23 Nov 2012 14:23:16 +0000
+Subject: [PATCH 2/3] Reintroduce button-backlight (and respective inactivity
+ timeout)
+
+The power manager rewrite from Change I1d7a52e98f0449f76d70bf421f6a7f245957d1d7
+completely removed support for control of the button backlights, which makes
+all capacitive buttons out there stay dark. The commit message in that change
+mentions it hasn't been implemented _yet_, so this fix should be temporary
+until upstream does their own implementation
+
+[RC: Updated to 5.0]
+
+Change-Id: I6094c446e0b8c23f57d30652a3cbd35dee5e821a
+---
+ .../com/android/server/display/DisplayPowerController.java    | 11 +++++++++++
+ .../java/com/android/server/power/PowerManagerService.java    | 10 ++++++++++
+ 2 files changed, 21 insertions(+)
+
+diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
+index f8e58362e7a..80bdf1ffade 100644
+--- a/services/core/java/com/android/server/display/DisplayPowerController.java
++++ b/services/core/java/com/android/server/display/DisplayPowerController.java
+@@ -20,6 +20,7 @@ import android.app.ActivityManager;
+ import com.android.internal.app.IBatteryStats;
+ import com.android.server.LocalServices;
+ import com.android.server.am.BatteryStatsService;
++import com.android.server.lights.LightsManager;
+ 
+ import android.animation.Animator;
+ import android.animation.ObjectAnimator;
+@@ -129,6 +130,9 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
+     // Battery stats.
+     private final IBatteryStats mBatteryStats;
+ 
++    // The lights service.
++    private final LightsManager mLights;
++
+     // The sensor manager.
+     private final SensorManager mSensorManager;
+ 
+@@ -300,6 +304,7 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
+         mCallbacks = callbacks;
+ 
+         mBatteryStats = BatteryStatsService.getService();
++        mLights = LocalServices.getService(LightsManager.class);
+         mSensorManager = sensorManager;
+         mWindowManagerPolicy = LocalServices.getService(WindowManagerPolicy.class);
+         mBlanker = blanker;
+@@ -678,6 +683,12 @@ final class DisplayPowerController implements AutomaticBrightnessController.Call
+         // Use zero brightness when screen is off.
+         if (state == Display.STATE_OFF) {
+             brightness = PowerManager.BRIGHTNESS_OFF;
++            mLights.getLight(LightsManager.LIGHT_ID_BUTTONS).setBrightness(brightness);
++        }
++
++        // Disable button lights when dozing
++        if (state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND) {
++            mLights.getLight(LightsManager.LIGHT_ID_BUTTONS).setBrightness(PowerManager.BRIGHTNESS_OFF);
+         }
+ 
+         // Configure auto-brightness.
+diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
+index f84b20c0570..1ced53fe840 100644
+--- a/services/core/java/com/android/server/power/PowerManagerService.java
++++ b/services/core/java/com/android/server/power/PowerManagerService.java
+@@ -220,6 +220,8 @@ public final class PowerManagerService extends SystemService
+     private static final int HALT_MODE_REBOOT = 1;
+     private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
+ 
++    private static final int BUTTON_ON_DURATION = 5 * 1000;
++
+     // File location for last reboot reason
+     private static final String LAST_REBOOT_LOCATION = "/data/misc/reboot/last_reboot_reason";
+ 
+@@ -240,6 +242,7 @@ public final class PowerManagerService extends SystemService
+     private SettingsObserver mSettingsObserver;
+     private DreamManagerInternal mDreamManager;
+     private Light mAttentionLight;
++    private Light mButtonsLight;
+ 
+     private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
+ 
+@@ -747,6 +750,7 @@ public final class PowerManagerService extends SystemService
+ 
+             mLightsManager = getLocalService(LightsManager.class);
+             mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
++            mButtonsLight = mLightsManager.getLight(LightsManager.LIGHT_ID_BUTTONS);
+ 
+             // Initialize display power management.
+             mDisplayManagerInternal.initPowerManagement(
+@@ -1947,6 +1951,12 @@ public final class PowerManagerService extends SystemService
+                     nextTimeout = mLastUserActivityTime
+                             + screenOffTimeout - screenDimDuration;
+                     if (now < nextTimeout) {
++                        if (now > mLastUserActivityTime + BUTTON_ON_DURATION) {
++                            mButtonsLight.setBrightness(0);
++                        } else {
++                            mButtonsLight.setBrightness(mDisplayPowerRequest.screenBrightness);
++                            nextTimeout = now + BUTTON_ON_DURATION;
++                        }
+                         mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
+                     } else {
+                         nextTimeout = mLastUserActivityTime + screenOffTimeout;
+-- 
+2.15.1
+
diff --git a/patches/platform_frameworks_base/0003-power-Disable-keyboard-button-lights-while-dozing-dr.patch b/patches/platform_frameworks_base/0003-power-Disable-keyboard-button-lights-while-dozing-dr.patch
new file mode 100644
index 0000000..1c6606c
--- /dev/null
+++ b/patches/platform_frameworks_base/0003-power-Disable-keyboard-button-lights-while-dozing-dr.patch
@@ -0,0 +1,31 @@
+From 55bd603882486a351210d29ac7767d92f12000f2 Mon Sep 17 00:00:00 2001
+From: Steve Kondik <steve@cyngn.com>
+Date: Sat, 3 Jan 2015 05:13:26 -0800
+Subject: [PATCH 3/3] power: Disable keyboard/button lights while
+ dozing/dreaming
+
+ * With hardkeys and doze mode enabled, entering suspend results in
+   an epic battle over the lights. It's a bad situation. Disable
+   them when we're sleepy.
+
+Change-Id: I7f1fc35a1573717d1ea101a07c4171d6f66d1553
+---
+ services/core/java/com/android/server/power/PowerManagerService.java | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
+index 1ced53fe840..9edf6fcae1e 100644
+--- a/services/core/java/com/android/server/power/PowerManagerService.java
++++ b/services/core/java/com/android/server/power/PowerManagerService.java
+@@ -1947,7 +1947,7 @@ public final class PowerManagerService extends SystemService
+                 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
+ 
+                 mUserActivitySummary = 0;
+-                if (mLastUserActivityTime >= mLastWakeTime) {
++                if (mWakefulness == WAKEFULNESS_AWAKE && mLastUserActivityTime >= mLastWakeTime) {
+                     nextTimeout = mLastUserActivityTime
+                             + screenOffTimeout - screenDimDuration;
+                     if (now < nextTimeout) {
+-- 
+2.15.1
+
diff --git a/patches/platform_frameworks_native/0001-device-Huawei-HWC-doesn-t-understand-0-0-0-0-fullscr.patch b/patches/platform_frameworks_native/0001-device-Huawei-HWC-doesn-t-understand-0-0-0-0-fullscr.patch
new file mode 100644
index 0000000..eccd95a
--- /dev/null
+++ b/patches/platform_frameworks_native/0001-device-Huawei-HWC-doesn-t-understand-0-0-0-0-fullscr.patch
@@ -0,0 +1,100 @@
+From 6dcb8fda3d94def017ffce6f5540e88c29b1c3a4 Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@phh.me>
+Date: Fri, 5 Jan 2018 00:26:38 +0100
+Subject: [PATCH] [device] ::Huawei:: HWC doesn't understand 0,0,0,0 ==
+ fullscreen damage. Set it to the whole visible surface
+
+::Huawei:: Fix damage for Huawei compositor
+
+For Huawei compositor, the damage area is a region on the screen.
+But for SurfaceFlinger, this is a region on the source surface.
+On Huawei devices, do the plane conversion.
+
+This fixes several UI glitches, most notably GBoard.
+---
+ services/surfaceflinger/Layer.cpp          | 35 +++++++++++++++++++++++++++++-
+ services/surfaceflinger/SurfaceFlinger.cpp |  7 ++++++
+ services/surfaceflinger/SurfaceFlinger.h   |  3 +++
+ 3 files changed, 44 insertions(+), 1 deletion(-)
+
+diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
+index 038ece2e0..8099f1d3c 100755
+--- a/services/surfaceflinger/Layer.cpp
++++ b/services/surfaceflinger/Layer.cpp
+@@ -871,7 +871,40 @@ void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
+         visible.dump(LOG_TAG);
+     }
+ 
+-    error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
++    if(mFlinger->mDamageUsesScreenReference) {
++	    const Rect& frame = hwcInfo.displayFrame;
++	    int32_t left = frame.left;
++	    int32_t top = frame.top;
++	    int32_t right = frame.right;
++	    int32_t bottom = frame.bottom;
++	    if(surfaceDamageRegion.getBounds() == Rect::INVALID_RECT) {
++		    auto fullSource = Region(Rect(left, top, right, bottom));
++		    error = hwcLayer->setSurfaceDamage(fullSource);
++	    } else {
++		    //There is no easy way to scale, so just scale the bounds
++		    const Rect& preDamageRect = surfaceDamageRegion.bounds();
++		    const FloatRect& crop = hwcInfo.sourceCrop;
++
++		    float frameWidth = right - left;
++		    float frameHeight = bottom - top;
++
++		    float cropWidth = crop.right - crop.left;
++		    float cropHeight = crop.bottom - crop.top;
++
++		    float wFactor = frameWidth / cropWidth;
++		    float hFactor = frameHeight / cropHeight;
++
++		    Rect scaledDamageRect = Rect(
++				    (int)(preDamageRect.left * wFactor),
++				    (int)(preDamageRect.top * hFactor),
++				    (int)(preDamageRect.right * wFactor),
++				    (int)(preDamageRect.bottom * hFactor));
++		    Region realDamage = Region(scaledDamageRect).translate(frame.left, frame.top);
++		    error = hwcLayer->setSurfaceDamage(realDamage);
++	    }
++    } else {
++	    error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
++    }
+     if (error != HWC2::Error::None) {
+         ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
+                 to_string(error).c_str(), static_cast<int32_t>(error));
+diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
+index 4055693e4..3f806b71c 100644
+--- a/services/surfaceflinger/SurfaceFlinger.cpp
++++ b/services/surfaceflinger/SurfaceFlinger.cpp
+@@ -247,6 +247,13 @@ SurfaceFlinger::SurfaceFlinger()
+     // but since /data may be encrypted, we need to wait until after vold
+     // comes online to attempt to read the property. The property is
+     // instead read after the boot animation
++    property_get("ro.hardware", value, "");
++    if(strstr(value, "hi3660")||
++		    strstr(value, "hi6250") ||
++		    strstr(value, "hi3670") ||
++		    strstr(value, "kirin970")) {
++	    mDamageUsesScreenReference = true;
++    }
+ }
+ 
+ void SurfaceFlinger::onFirstRef()
+diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
+index 99d4a1a63..c888b1dcd 100644
+--- a/services/surfaceflinger/SurfaceFlinger.h
++++ b/services/surfaceflinger/SurfaceFlinger.h
+@@ -727,6 +727,9 @@ private:
+     // Restrict layers to use two buffers in their bufferqueues.
+     bool mLayerTripleBufferingDisabled = false;
+ 
++    bool mDamageUsesScreenReference;
++
++
+     // these are thread safe
+     mutable MessageQueue mEventQueue;
+     FrameTracker mAnimFrameTracker;
+-- 
+2.15.1
+
diff --git a/patches/platform_system_bt/0001-Make-BTM_BYPASS_EXTRA_ACL_SETUP-dynamic.patch b/patches/platform_system_bt/0001-Make-BTM_BYPASS_EXTRA_ACL_SETUP-dynamic.patch
new file mode 100644
index 0000000..f83d9f9
--- /dev/null
+++ b/patches/platform_system_bt/0001-Make-BTM_BYPASS_EXTRA_ACL_SETUP-dynamic.patch
@@ -0,0 +1,105 @@
+From e9af4318791727d9e47006aa56f243950a41ba8c Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@phh.me>
+Date: Tue, 20 Feb 2018 23:04:50 +0100
+Subject: [PATCH] Make BTM_BYPASS_EXTRA_ACL_SETUP dynamic
+
+Change-Id: Icb0868566b29b053ed7e83c9fd32e225af3f2e46
+---
+ hci/include/bt_hci_bdroid.h |  3 +++
+ include/bt_target.h         |  3 +++
+ stack/btm/btm_acl.cc        | 20 ++++++++++----------
+ stack/btm/btm_sec.cc        | 18 +++++++++---------
+ 4 files changed, 25 insertions(+), 19 deletions(-)
+
+diff --git a/hci/include/bt_hci_bdroid.h b/hci/include/bt_hci_bdroid.h
+index aa193d058..6c82f19ad 100644
+--- a/hci/include/bt_hci_bdroid.h
++++ b/hci/include/bt_hci_bdroid.h
+@@ -32,6 +32,9 @@
+ #ifdef HAS_BDROID_BUILDCFG
+ #include "bdroid_buildcfg.h"
+ #endif
++#ifndef BTM_BYPASS_EXTRA_ACL_SETUP
++#define BTM_BYPASS_EXTRA_ACL_SETUP TRUE
++#endif
+ 
+ /******************************************************************************
+  *  Constants & Macros
+diff --git a/include/bt_target.h b/include/bt_target.h
+index eadfc920f..bf1f95dae 100644
+--- a/include/bt_target.h
++++ b/include/bt_target.h
+@@ -32,6 +32,9 @@
+ #ifdef HAS_BDROID_BUILDCFG
+ #include "bdroid_buildcfg.h"
+ #endif
++#ifndef BTM_BYPASS_EXTRA_ACL_SETUP
++#define BTM_BYPASS_EXTRA_ACL_SETUP TRUE
++#endif
+ 
+ #include "bt_types.h" /* This must be defined AFTER buildcfg.h */
+ 
+diff --git a/stack/btm/btm_acl.cc b/stack/btm/btm_acl.cc
+index 8df6acb81..7eba37d3e 100644
+--- a/stack/btm/btm_acl.cc
++++ b/stack/btm/btm_acl.cc
+@@ -1164,17 +1164,17 @@ void btm_read_remote_ext_features_failed(uint8_t status, uint16_t handle) {
+ void btm_establish_continue(tACL_CONN* p_acl_cb) {
+   tBTM_BL_EVENT_DATA evt_data;
+   BTM_TRACE_DEBUG("btm_establish_continue");
+-#if (BTM_BYPASS_EXTRA_ACL_SETUP == FALSE)
+-  if (p_acl_cb->transport == BT_TRANSPORT_BR_EDR) {
+-    /* For now there are a some devices that do not like sending */
+-    /* commands events and data at the same time. */
+-    /* Set the packet types to the default allowed by the device */
+-    btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
+-
+-    if (btm_cb.btm_def_link_policy)
+-      BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
++  if (!BTM_BYPASS_EXTRA_ACL_SETUP) {
++    if (p_acl_cb->transport == BT_TRANSPORT_BR_EDR) {
++      /* For now there are a some devices that do not like sending */
++      /* commands events and data at the same time. */
++      /* Set the packet types to the default allowed by the device */
++      btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
++
++      if (btm_cb.btm_def_link_policy)
++        BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
++    }
+   }
+-#endif
+   p_acl_cb->link_up_issued = true;
+ 
+   /* If anyone cares, tell him database changed */
+diff --git a/stack/btm/btm_sec.cc b/stack/btm/btm_sec.cc
+index 60a3a17ef..5d36ef903 100644
+--- a/stack/btm/btm_sec.cc
++++ b/stack/btm/btm_sec.cc
+@@ -4490,15 +4490,15 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, uint8_t status,
+   if (p_acl_cb) {
+ /* whatever is in btm_establish_continue() without reporting the BTM_BL_CONN_EVT
+  * event */
+-#if (BTM_BYPASS_EXTRA_ACL_SETUP == FALSE)
+-    /* For now there are a some devices that do not like sending */
+-    /* commands events and data at the same time. */
+-    /* Set the packet types to the default allowed by the device */
+-    btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
+-
+-    if (btm_cb.btm_def_link_policy)
+-      BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
+-#endif
++    if(!BTM_BYPASS_EXTRA_ACL_SETUP) {
++      /* For now there are a some devices that do not like sending */
++      /* commands events and data at the same time. */
++      /* Set the packet types to the default allowed by the device */
++      btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
++
++      if (btm_cb.btm_def_link_policy)
++        BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
++    }
+   }
+   btm_acl_created(bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, handle,
+                   HCI_ROLE_SLAVE, BT_TRANSPORT_BR_EDR);
+-- 
+2.15.1
+
diff --git a/patches/platform_system_core/0001-Revert-logd-add-passcred-for-logdw-socket.patch b/patches/platform_system_core/0001-Revert-logd-add-passcred-for-logdw-socket.patch
new file mode 100644
index 0000000..5e386ce
--- /dev/null
+++ b/patches/platform_system_core/0001-Revert-logd-add-passcred-for-logdw-socket.patch
@@ -0,0 +1,53 @@
+From 1b1d4e8de5de1347f0cae699d8f154b82d6195f2 Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@phh.me>
+Date: Sun, 10 Dec 2017 00:26:21 +0100
+Subject: [PATCH] Revert "logd: add "+passcred" for logdw socket"
+
+This reverts commit 54d8ff1121440d0ef4565ce0ab3751f82fdb393c.
+
+Android 8.0 init doesn't understand this new syntax
+---
+ logd/LogListener.cpp | 10 +++++-----
+ logd/logd.rc         |  2 +-
+ 2 files changed, 6 insertions(+), 6 deletions(-)
+
+diff --git a/logd/LogListener.cpp b/logd/LogListener.cpp
+index d2df68eef..e4d2dea92 100644
+--- a/logd/LogListener.cpp
++++ b/logd/LogListener.cpp
+@@ -145,14 +145,14 @@ int LogListener::getLogSocket() {
+     static const char socketName[] = "logdw";
+     int sock = android_get_control_socket(socketName);
+ 
+-    if (sock < 0) {  // logd started up in init.sh
++    if (sock < 0) {
+         sock = socket_local_server(
+             socketName, ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_DGRAM);
++    }
+ 
+-        int on = 1;
+-        if (setsockopt(sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) {
+-            return -1;
+-        }
++    int on = 1;
++    if (setsockopt(sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)) < 0) {
++        return -1;
+     }
+     return sock;
+ }
+diff --git a/logd/logd.rc b/logd/logd.rc
+index 88042466b..7494d8fb3 100644
+--- a/logd/logd.rc
++++ b/logd/logd.rc
+@@ -1,7 +1,7 @@
+ service logd /system/bin/logd
+     socket logd stream 0666 logd logd
+     socket logdr seqpacket 0666 logd logd
+-    socket logdw dgram+passcred 0222 logd logd
++    socket logdw dgram 0222 logd logd
+     file /proc/kmsg r
+     file /dev/kmsg w
+     user logd
+-- 
+2.15.1
+
diff --git a/patches/platform_system_vold/0001-Allow-deletion-of-symlink.patch b/patches/platform_system_vold/0001-Allow-deletion-of-symlink.patch
new file mode 100644
index 0000000..b9afea8
--- /dev/null
+++ b/patches/platform_system_vold/0001-Allow-deletion-of-symlink.patch
@@ -0,0 +1,25 @@
+From f838998f3f28d93a8085047725da96404b0ae56c Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@phh.me>
+Date: Sat, 17 Feb 2018 19:39:38 +0100
+Subject: [PATCH 1/2] Allow deletion of symlink
+
+Change-Id: I9731895f88729072297f753088583aabbe6990f4
+---
+ Ext4Crypt.cpp | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/Ext4Crypt.cpp b/Ext4Crypt.cpp
+index dc2e42a..6398464 100644
+--- a/Ext4Crypt.cpp
++++ b/Ext4Crypt.cpp
+@@ -211,6 +211,7 @@ static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gi
+ static bool destroy_dir(const std::string& dir) {
+     LOG(DEBUG) << "Destroying: " << dir;
+     if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
++        if(unlink(dir.c_str()) == 0) return true;
+         PLOG(ERROR) << "Failed to destroy " << dir;
+         return false;
+     }
+-- 
+2.15.1
+
diff --git a/patches/platform_system_vold/0002-Workaround-perdev_minors-path-change-in-Linux.patch b/patches/platform_system_vold/0002-Workaround-perdev_minors-path-change-in-Linux.patch
new file mode 100644
index 0000000..73edc04
--- /dev/null
+++ b/patches/platform_system_vold/0002-Workaround-perdev_minors-path-change-in-Linux.patch
@@ -0,0 +1,42 @@
+From 2f89ac71e213bfbd45d503ef615b778697ef8dc2 Mon Sep 17 00:00:00 2001
+From: Pierre-Hugues Husson <phh@archos.com>
+Date: Tue, 28 Nov 2017 15:42:56 +0100
+Subject: [PATCH 2/2] Workaround perdev_minors path change in Linux
+
+This upstream Linux change has been discussed at https://patchwork.kernel.org/patch/8281851/
+And included in AOSP in https://android-review.googlesource.com/c/kernel/common/+/202752
+Some devices have been released without it, so we need this change to
+have a working SDcard on those devices.
+
+Change-Id: I323d85bd8381f82b75db09493ddc22f432cec548
+---
+ Disk.cpp | 6 ++++--
+ 1 file changed, 4 insertions(+), 2 deletions(-)
+
+diff --git a/Disk.cpp b/Disk.cpp
+index 9c22400..2f6ed5e 100644
+--- a/Disk.cpp
++++ b/Disk.cpp
+@@ -50,7 +50,8 @@ static const char* kSgdiskPath = "/system/bin/sgdisk";
+ static const char* kSgdiskToken = " \t\n";
+ 
+ static const char* kSysfsLoopMaxMinors = "/sys/module/loop/parameters/max_part";
+-static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
++static const char* kSysfsMmcMaxMinorsDeprecated = "/sys/module/mmcblk/parameters/perdev_minors";
++static const char* kSysfsMmcMaxMinors = "/sys/module/mmc_block/parameters/perdev_minors";
+ 
+ static const unsigned int kMajorBlockLoop = 7;
+ static const unsigned int kMajorBlockScsiA = 8;
+@@ -566,7 +567,8 @@ int Disk::getMaxMinors() {
+     case kMajorBlockMmc: {
+         // Per Documentation/devices.txt this is dynamic
+         std::string tmp;
+-        if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
++        if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp) &&
++                !ReadFileToString(kSysfsMmcMaxMinorsDeprecated, &tmp)) {
+             LOG(ERROR) << "Failed to read max minors";
+             return -errno;
+         }
+-- 
+2.15.1
+