Merge "ATest: Add test config template for python."
diff --git a/Android.mk b/Android.mk
deleted file mode 100644
index 5053e7d..0000000
--- a/Android.mk
+++ /dev/null
@@ -1 +0,0 @@
-include $(call all-subdir-makefiles)
diff --git a/Changes.md b/Changes.md
index 2d5cd97..1ed6bf8 100644
--- a/Changes.md
+++ b/Changes.md
@@ -1,5 +1,15 @@
 # Build System Changes for Android.mk Writers
 
+## `USER` deprecation  {#USER}
+
+`USER` will soon be `nobody` in many cases due to the addition of a sandbox
+around the Android build. Most of the time you shouldn't need to know the
+identity of the user running the build, but if you do, it's available in the
+make variable `BUILD_USERNAME` for now.
+
+Similarly, the `hostname` tool will also be returning a more consistent value
+of `android-build`. The real value is available as `BUILD_HOSTNAME`.
+
 ## `BUILD_NUMBER` removal from Android.mk  {#BUILD_NUMBER}
 
 `BUILD_NUMBER` should not be used directly in Android.mk files, as it would
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 7d42fc9..8a28303 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -517,6 +517,24 @@
 
 $(call add-clean-step, rm -f $(HOST_OUT)/*ts/host-libprotobuf-java-*.jar)
 
+$(call add-clean-step, find $(OUT_DIR)/target/product/mainline_arm64/system -type f -name "*.*dex" -print0 | xargs -0 rm -f)
+
+# Clean up aidegen
+$(call add-clean-step, rm -f $(HOST_OUT)/bin/aidegen)
+
+# Remove perfprofd
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/perfprofd)
+
+# Remove incorrectly created directories in the source tree
+$(call add-clean-step, find system/app system/priv-app system/framework system_other -depth -type d -print0 | xargs -0 rmdir)
+$(call add-clean-step, rm -f .d)
+
+# Remove obsolete apps
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
+
+# Remove corrupt generated rule due to using toybox's sed
+$(call add-clean-step, rm -rf $(SOONG_OUT_DIR)/.intermediates/system/core/init/generated_stub_builtin_function_map)
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/OWNERS b/OWNERS
index b9fee4e..7bc9fe0 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,8 +1,7 @@
 ccross@android.com
 dwillemsen@google.com
-nanzhang@google.com
 
-per-file * = ccross@android.com,dwillemsen@google.com,nanzhang@google.com
+per-file * = ccross@android.com,dwillemsen@google.com
 
 # for version updates
 per-file version_defaults.mk = aseaton@google.com,elisapascual@google.com
diff --git a/common/json.mk b/common/json.mk
new file mode 100644
index 0000000..ba8ffa7
--- /dev/null
+++ b/common/json.mk
@@ -0,0 +1,35 @@
+4space :=$= $(space)$(space)$(space)$(space)
+invert_bool =$= $(if $(strip $(1)),,true)
+
+# Converts a list to a JSON list.
+# $1: List separator.
+# $2: List.
+_json_list =$= [$(if $(2),"$(subst $(1),"$(comma)",$(2))")]
+
+# Converts a space-separated list to a JSON list.
+json_list =$= $(call _json_list,$(space),$(1))
+
+# Converts a comma-separated list to a JSON list.
+csv_to_json_list =$= $(call _json_list,$(comma),$(1))
+
+# Adds or removes 4 spaces from _json_indent
+json_increase_indent =$= $(eval _json_indent := $$(_json_indent)$$(4space))
+json_decrease_indent =$= $(eval _json_indent := $$(subst _,$$(space),$$(patsubst %____,%,$$(subst $$(space),_,$$(_json_indent)))))
+
+# 1: Key name
+# 2: Value
+add_json_val =$= $(eval _json_contents := $$(_json_contents)$$(_json_indent)"$$(strip $$(1))": $$(strip $$(2))$$(comma)$$(newline))
+add_json_str =$= $(call add_json_val,$(1),"$(strip $(2))")
+add_json_list =$= $(call add_json_val,$(1),$(call json_list,$(patsubst %,%,$(2))))
+add_json_csv =$= $(call add_json_val,$(1),$(call csv_to_json_list,$(strip $(2))))
+add_json_bool =$= $(call add_json_val,$(1),$(if $(strip $(2)),true,false))
+add_json_map =$= $(eval _json_contents := $$(_json_contents)$$(_json_indent)"$$(strip $$(1))": {$$(newline))$(json_increase_indent)
+end_json_map =$= $(json_decrease_indent)$(eval _json_contents := $$(_json_contents)$$(if $$(filter %$$(comma),$$(lastword $$(_json_contents))),__SV_END)$$(_json_indent)},$$(newline))
+
+# Clears _json_contents to start a new json file
+json_start =$= $(eval _json_contents := {$$(newline))$(eval _json_indent := $$(4space))
+
+# Adds the trailing close brace to _json_contents, and removes any trailing commas if necessary
+json_end =$= $(eval _json_contents := $$(subst $$(comma)$$(newline)__SV_END,$$(newline),$$(_json_contents)__SV_END}$$(newline)))
+
+json_contents =$= $(_json_contents)
diff --git a/core/Makefile b/core/Makefile
index 55bcbcc..7d1c7ff 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -122,6 +122,33 @@
 endif
 
 # -----------------------------------------------------------------
+# generate preview API fingerprint
+api_fingerprint := $(call intermediates-dir-for,PACKAGING,api_fingerprint)/api_fingerprint.txt
+.KATI_READONLY := api_fingerprint
+
+ifeq (REL,$(PLATFORM_VERSION_CODENAME))
+  $(api_fingerprint):
+	echo REL >$@
+else ifneq ($(TARGET_BUILD_APPS),)
+  # TODO: use a prebuilt api_fingerprint.txt from prebuilts/sdk/current.txt once we have one
+  #$(eval $(call copy-one-file,prebuilts/sdk/current/api_fingerprint.txt,$(api_fingerprint)))
+  $(api_fingerprint):
+	echo $(PLATFORM_PREVIEW_SDK_VERSION) >$@
+else ifneq ($(TARGET_BUILD_PDK),)
+  $(eval $(call copy-one-file,$(_pdk_fusion_intermediates)/api_fingerprint.txt,$(api_fingerprint)))
+else
+  ifeq ($(HOST_OS),darwin)
+  $(api_fingerprint): PRIVATE_HASH := md5
+  else
+  $(api_fingerprint): PRIVATE_HASH := md5sum
+  endif
+  $(api_fingerprint): $(sort $(wildcard frameworks/base/api/*current.txt))
+	cat $^ | $(PRIVATE_HASH) | cut -d' ' -f1 >$@
+
+  $(call dist-for-goals,sdk,$(api_fingerprint))
+endif
+
+# -----------------------------------------------------------------
 # property_overrides_split_enabled
 property_overrides_split_enabled :=
 ifeq ($(BOARD_PROPERTY_OVERRIDES_SPLIT_ENABLED), true)
@@ -148,6 +175,11 @@
 FINAL_VENDOR_DEFAULT_PROPERTIES += \
     $(call collapse-pairs, $(PRODUCT_DEFAULT_PROPERTY_OVERRIDES))
 
+FINAL_VENDOR_DEFAULT_PROPERTIES += ro.bionic.arch=$(TARGET_ARCH)
+FINAL_VENDOR_DEFAULT_PROPERTIES += ro.bionic.cpu_variant=$(TARGET_CPU_VARIANT)
+FINAL_VENDOR_DEFAULT_PROPERTIES += ro.bionic.2nd_arch=$(TARGET_2ND_ARCH)
+FINAL_VENDOR_DEFAULT_PROPERTIES += ro.bionic.2nd_cpu_variant=$(TARGET_2ND_CPU_VARIANT)
+
 # Although these variables are prefixed with TARGET_RECOVERY_, they are also needed under charger
 # mode (via libminui).
 ifdef TARGET_RECOVERY_DEFAULT_ROTATION
@@ -220,7 +252,7 @@
 	        echo "# ADDITIONAL_DEFAULT_PROPERTIES" >> $@; \
 	        echo "#" >> $@;
 	$(hide) $(foreach line,$(FINAL_DEFAULT_PROPERTIES), \
-		echo "$(line)" >> $@;)
+	    echo "$(line)" >> $@;)
 	$(hide) echo "#" >> $@; \
 	        echo "# BOOTIMAGE_BUILD_PROPERTIES" >> $@; \
 	        echo "#" >> $@;
@@ -245,7 +277,7 @@
 	        echo "# ADDITIONAL VENDOR DEFAULT PROPERTIES" >> $@; \
 	        echo "#" >> $@;
 	$(hide) $(foreach line,$(FINAL_VENDOR_DEFAULT_PROPERTIES), \
-		echo "$(line)" >> $@;)
+	    echo "$(line)" >> $@;)
 	$(hide) build/make/tools/post_process_props.py $@
 
 endif  # property_overrides_split_enabled
@@ -285,7 +317,7 @@
 # The string used to uniquely identify the combined build and product; used by the OTA server.
 ifeq (,$(strip $(BUILD_FINGERPRINT)))
   ifeq ($(strip $(HAS_BUILD_NUMBER)),false)
-    BF_BUILD_NUMBER := $(USER)$$($(DATE_FROM_FILE) +%m%d%H%M)
+    BF_BUILD_NUMBER := $(BUILD_USERNAME)$$($(DATE_FROM_FILE) +%m%d%H%M)
   else
     BF_BUILD_NUMBER := $(file <$(BUILD_NUMBER_FILE))
   endif
@@ -363,7 +395,7 @@
 else
 system_prop_file := $(wildcard $(TARGET_DEVICE_DIR)/system.prop)
 endif
-$(intermediate_system_build_prop): $(BUILDINFO_SH) $(BUILDINFO_COMMON_SH) $(INTERNAL_BUILD_ID_MAKEFILE) $(BUILD_SYSTEM)/version_defaults.mk $(system_prop_file) $(INSTALLED_ANDROID_INFO_TXT_TARGET)
+$(intermediate_system_build_prop): $(BUILDINFO_SH) $(BUILDINFO_COMMON_SH) $(INTERNAL_BUILD_ID_MAKEFILE) $(BUILD_SYSTEM)/version_defaults.mk $(system_prop_file) $(INSTALLED_ANDROID_INFO_TXT_TARGET) $(api_fingerprint)
 	@echo Target buildinfo: $@
 	@mkdir -p $(dir $@)
 	$(hide) echo > $@
@@ -372,58 +404,62 @@
 	        echo "# PRODUCT_OEM_PROPERTIES" >> $@; \
 	        echo "#" >> $@;
 	$(hide) $(foreach prop,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_OEM_PROPERTIES), \
-		echo "import /oem/oem.prop $(prop)" >> $@;)
+	    echo "import /oem/oem.prop $(prop)" >> $@;)
 endif
 	$(hide) $(call generate-common-build-props,system,$@)
 	$(hide) TARGET_BUILD_TYPE="$(TARGET_BUILD_VARIANT)" \
-			TARGET_BUILD_FLAVOR="$(TARGET_BUILD_FLAVOR)" \
-			TARGET_DEVICE="$(TARGET_DEVICE)" \
-			PRODUCT_NAME="$(TARGET_PRODUCT)" \
-			PRODUCT_BRAND="$(PRODUCT_BRAND)" \
-			PRODUCT_DEFAULT_LOCALE="$(call get-default-product-locale,$(PRODUCT_LOCALES))" \
-			PRODUCT_DEFAULT_WIFI_CHANNELS="$(PRODUCT_DEFAULT_WIFI_CHANNELS)" \
-			PRODUCT_MODEL="$(PRODUCT_MODEL)" \
-			PRODUCT_MANUFACTURER="$(PRODUCT_MANUFACTURER)" \
-			PRIVATE_BUILD_DESC="$(PRIVATE_BUILD_DESC)" \
-			BUILD_ID="$(BUILD_ID)" \
-			BUILD_DISPLAY_ID="$(BUILD_DISPLAY_ID)" \
-			DATE="$(DATE_FROM_FILE)" \
-			BUILD_NUMBER="$(BUILD_NUMBER_FROM_FILE)" \
-			BOARD_BUILD_SYSTEM_ROOT_IMAGE="$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)" \
-			AB_OTA_UPDATER="$(AB_OTA_UPDATER)" \
-			PLATFORM_VERSION="$(PLATFORM_VERSION)" \
-			PLATFORM_SECURITY_PATCH="$(PLATFORM_SECURITY_PATCH)" \
-			PLATFORM_BASE_OS="$(PLATFORM_BASE_OS)" \
-			PLATFORM_SDK_VERSION="$(PLATFORM_SDK_VERSION)" \
-			PLATFORM_PREVIEW_SDK_VERSION="$(PLATFORM_PREVIEW_SDK_VERSION)" \
-			PLATFORM_VERSION_CODENAME="$(PLATFORM_VERSION_CODENAME)" \
-			PLATFORM_VERSION_ALL_CODENAMES="$(PLATFORM_VERSION_ALL_CODENAMES)" \
-			PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION="$(PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION)" \
-			BUILD_VERSION_TAGS="$(BUILD_VERSION_TAGS)" \
-			BUILD_FINGERPRINT="$(BUILD_FINGERPRINT_FROM_FILE)" \
-			$(if $(OEM_THUMBPRINT_PROPERTIES),BUILD_THUMBPRINT="$(BUILD_THUMBPRINT_FROM_FILE)") \
-			TARGET_CPU_ABI_LIST="$(TARGET_CPU_ABI_LIST)" \
-			TARGET_CPU_ABI_LIST_32_BIT="$(TARGET_CPU_ABI_LIST_32_BIT)" \
-			TARGET_CPU_ABI_LIST_64_BIT="$(TARGET_CPU_ABI_LIST_64_BIT)" \
-			TARGET_CPU_ABI="$(TARGET_CPU_ABI)" \
-			TARGET_CPU_ABI2="$(TARGET_CPU_ABI2)" \
-			TARGET_AAPT_CHARACTERISTICS="$(TARGET_AAPT_CHARACTERISTICS)" \
+	        TARGET_BUILD_FLAVOR="$(TARGET_BUILD_FLAVOR)" \
+	        TARGET_DEVICE="$(TARGET_DEVICE)" \
+	        PRODUCT_NAME="$(TARGET_PRODUCT)" \
+	        PRODUCT_BRAND="$(PRODUCT_BRAND)" \
+	        PRODUCT_DEFAULT_LOCALE="$(call get-default-product-locale,$(PRODUCT_LOCALES))" \
+	        PRODUCT_DEFAULT_WIFI_CHANNELS="$(PRODUCT_DEFAULT_WIFI_CHANNELS)" \
+	        PRODUCT_MODEL="$(PRODUCT_MODEL)" \
+	        PRODUCT_MANUFACTURER="$(PRODUCT_MANUFACTURER)" \
+	        PRIVATE_BUILD_DESC="$(PRIVATE_BUILD_DESC)" \
+	        BUILD_ID="$(BUILD_ID)" \
+	        BUILD_DISPLAY_ID="$(BUILD_DISPLAY_ID)" \
+	        DATE="$(DATE_FROM_FILE)" \
+	        BUILD_USERNAME="$(BUILD_USERNAME)" \
+	        BUILD_HOSTNAME="$(BUILD_HOSTNAME)" \
+	        BUILD_NUMBER="$(BUILD_NUMBER_FROM_FILE)" \
+	        BOARD_BUILD_SYSTEM_ROOT_IMAGE="$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)" \
+	        AB_OTA_UPDATER="$(AB_OTA_UPDATER)" \
+	        PLATFORM_VERSION="$(PLATFORM_VERSION)" \
+	        PLATFORM_SECURITY_PATCH="$(PLATFORM_SECURITY_PATCH)" \
+	        PLATFORM_BASE_OS="$(PLATFORM_BASE_OS)" \
+	        PLATFORM_SDK_VERSION="$(PLATFORM_SDK_VERSION)" \
+	        PLATFORM_PREVIEW_SDK_VERSION="$(PLATFORM_PREVIEW_SDK_VERSION)" \
+	        PLATFORM_PREVIEW_SDK_FINGERPRINT="$$(cat $(api_fingerprint))" \
+	        PLATFORM_VERSION_CODENAME="$(PLATFORM_VERSION_CODENAME)" \
+	        PLATFORM_VERSION_ALL_CODENAMES="$(PLATFORM_VERSION_ALL_CODENAMES)" \
+	        PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION="$(PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION)" \
+	        BUILD_VERSION_TAGS="$(BUILD_VERSION_TAGS)" \
+	        BUILD_FINGERPRINT="$(BUILD_FINGERPRINT_FROM_FILE)" \
+	        $(if $(OEM_THUMBPRINT_PROPERTIES),BUILD_THUMBPRINT="$(BUILD_THUMBPRINT_FROM_FILE)") \
+	        TARGET_CPU_ABI_LIST="$(TARGET_CPU_ABI_LIST)" \
+	        TARGET_CPU_ABI_LIST_32_BIT="$(TARGET_CPU_ABI_LIST_32_BIT)" \
+	        TARGET_CPU_ABI_LIST_64_BIT="$(TARGET_CPU_ABI_LIST_64_BIT)" \
+	        TARGET_CPU_ABI="$(TARGET_CPU_ABI)" \
+	        TARGET_CPU_ABI2="$(TARGET_CPU_ABI2)" \
 	        bash $(BUILDINFO_SH) >> $@
 	$(hide) $(foreach file,$(system_prop_file), \
-		if [ -f "$(file)" ]; then \
-			echo "#" >> $@; \
-			echo Target buildinfo from: "$(file)"; \
-			echo "# from $(file)" >> $@; \
-			echo "#" >> $@; \
-			cat $(file) >> $@; \
-		fi;)
+	    if [ -f "$(file)" ]; then \
+	        echo Target buildinfo from: "$(file)"; \
+	        echo "" >> $@; \
+	        echo "#" >> $@; \
+	        echo "# from $(file)" >> $@; \
+	        echo "#" >> $@; \
+	        cat $(file) >> $@; \
+	        echo "# end of $(file)" >> $@; \
+	    fi;)
 	$(if $(FINAL_BUILD_PROPERTIES), \
-		$(hide) echo >> $@; \
-		        echo "#" >> $@; \
-		        echo "# ADDITIONAL_BUILD_PROPERTIES" >> $@; \
-		        echo "#" >> $@; )
+	    $(hide) echo >> $@; \
+	            echo "#" >> $@; \
+	            echo "# ADDITIONAL_BUILD_PROPERTIES" >> $@; \
+	            echo "#" >> $@; )
 	$(hide) $(foreach line,$(FINAL_BUILD_PROPERTIES), \
-		echo "$(line)" >> $@;)
+	    echo "$(line)" >> $@;)
 	$(hide) cat $(INSTALLED_ANDROID_INFO_TXT_TARGET) | grep 'require version-' | sed -e 's/require version-/ro.build.expect./g' >> $@
 	$(hide) build/make/tools/post_process_props.py $@ $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_PROPERTY_BLACKLIST)
 
@@ -473,7 +509,7 @@
 	        echo "# ADDITIONAL VENDOR BUILD PROPERTIES" >> $@; \
 	        echo "#" >> $@;
 	$(hide) $(foreach line,$(FINAL_VENDOR_BUILD_PROPERTIES), \
-		echo "$(line)" >> $@;)
+	    echo "$(line)" >> $@;)
 endif  # property_overrides_split_enabled
 	$(hide) build/make/tools/post_process_props.py $@ $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_PROPERTY_BLACKLIST)
 
@@ -482,23 +518,40 @@
 INSTALLED_PRODUCT_BUILD_PROP_TARGET := $(TARGET_OUT_PRODUCT)/build.prop
 ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_PRODUCT_BUILD_PROP_TARGET)
 
+ifdef TARGET_PRODUCT_PROP
+product_prop_files := $(TARGET_PRODUCT_PROP)
+else
+product_prop_files := $(wildcard $(TARGET_DEVICE_DIR)/product.prop)
+endif
+
 FINAL_PRODUCT_PROPERTIES += \
     $(call collapse-pairs, $(PRODUCT_PRODUCT_PROPERTIES) $(ADDITIONAL_PRODUCT_PROPERTIES))
 FINAL_PRODUCT_PROPERTIES := $(call uniq-pairs-by-first-component, \
     $(FINAL_PRODUCT_PROPERTIES),=)
 
-$(INSTALLED_PRODUCT_BUILD_PROP_TARGET): $(BUILDINFO_COMMON_SH)
+$(INSTALLED_PRODUCT_BUILD_PROP_TARGET): $(BUILDINFO_COMMON_SH) $(product_prop_files)
 	@echo Target product buildinfo: $@
 	@mkdir -p $(dir $@)
 	$(hide) echo > $@
 ifdef BOARD_USES_PRODUCTIMAGE
 	$(hide) $(call generate-common-build-props,product,$@)
 endif  # BOARD_USES_PRODUCTIMAGE
+	$(hide) $(foreach file,$(product_prop_files), \
+	    if [ -f "$(file)" ]; then \
+	        echo Target product properties from: "$(file)"; \
+	        echo "" >> $@; \
+	        echo "#" >> $@; \
+	        echo "# from $(file)" >> $@; \
+	        echo "#" >> $@; \
+	        cat $(file) >> $@; \
+	        echo "# end of $(file)" >> $@; \
+	    fi;)
 	$(hide) echo "#" >> $@; \
 	        echo "# ADDITIONAL PRODUCT PROPERTIES" >> $@; \
-	        echo "#" >> $@;
+	        echo "#" >> $@; \
+	        echo "ro.build.characteristics=$(TARGET_AAPT_CHARACTERISTICS)" >> $@;
 	$(hide) $(foreach line,$(FINAL_PRODUCT_PROPERTIES), \
-		echo "$(line)" >> $@;)
+	    echo "$(line)" >> $@;)
 	$(hide) build/make/tools/post_process_props.py $@
 
 # ----------------------------------------------------------------
@@ -523,7 +576,7 @@
 	        echo "# ADDITIONAL ODM BUILD PROPERTIES" >> $@; \
 	        echo "#" >> $@;
 	$(hide) $(foreach line,$(FINAL_ODM_BUILD_PROPERTIES), \
-		echo "$(line)" >> $@;)
+	    echo "$(line)" >> $@;)
 	$(hide) build/make/tools/post_process_props.py $@
 
 # -----------------------------------------------------------------
@@ -547,7 +600,7 @@
 	        echo "# ADDITIONAL PRODUCT_SERVICES PROPERTIES" >> $@; \
 	        echo "#" >> $@;
 	$(hide) $(foreach line,$(FINAL_PRODUCT_SERVICES_PROPERTIES), \
-		echo "$(line)" >> $@;)
+	    echo "$(line)" >> $@;)
 	$(hide) build/make/tools/post_process_props.py $@
 
 # ----------------------------------------------------------------
@@ -573,9 +626,9 @@
 	@echo SDK buildinfo: $@
 	@mkdir -p $(dir $@)
 	$(hide) grep -v "$(subst $(space),\|,$(strip \
-				$(sdk_build_prop_remove)))" $< > $@.tmp
+	            $(sdk_build_prop_remove)))" $< > $@.tmp
 	$(hide) for x in $(sdk_build_prop_remove); do \
-				echo "$$x"generic >> $@.tmp; done
+	            echo "$$x"generic >> $@.tmp; done
 	$(hide) mv $@.tmp $@
 
 # -----------------------------------------------------------------
@@ -977,30 +1030,46 @@
 $(2) : $(3)
 $(3) : $(6) $(BUILD_SYSTEM)/Makefile build/make/tools/generate-notice-files.py
 	build/make/tools/generate-notice-files.py --text-output $(2) \
-		$(if $(filter $(1),xml_excluded_extra_partitions),-e vendor$(comma)product$(comma)product_services --xml-output, \
-		  $(if $(filter $(1),xml_vendor),-i vendor --xml-output, \
-		    $(if $(filter $(1),xml_product),-i product --xml-output, \
-		      $(if $(filter $(1),xml_product_services),-i product_services --xml-output, \
-		        --html-output)))) $(3) \
-		-t $$(PRIVATE_MESSAGE) -s $$(PRIVATE_DIR)/src
+	    $(if $(filter $(1),xml_excluded_extra_partitions),-e vendor -e product -e product_services --xml-output, \
+	      $(if $(filter $(1),xml_vendor),-i vendor --xml-output, \
+	        $(if $(filter $(1),xml_product),-i product --xml-output, \
+	          $(if $(filter $(1),xml_product_services),-i product_services --xml-output, \
+	            --html-output)))) $(3) \
+	    -t $$(PRIVATE_MESSAGE) -s $$(PRIVATE_DIR)/src
 notice_files: $(2) $(3)
 endef
 
+# Notice file logic isn't relevant for TARGET_BUILD_APPS
+ifndef TARGET_BUILD_APPS
+
 # TODO These intermediate NOTICE.txt/NOTICE.html files should go into
 # TARGET_OUT_NOTICE_FILES now that the notice files are gathered from
 # the src subdirectory.
-
 target_notice_file_txt := $(TARGET_OUT_INTERMEDIATES)/NOTICE.txt
-target_notice_file_html_or_xml := $(TARGET_OUT_INTERMEDIATES)/NOTICE.html
-target_notice_file_html_or_xml_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE.html.gz
-installed_notice_html_or_xml_gz := $(TARGET_OUT)/etc/NOTICE.html.gz
 tools_notice_file_txt := $(HOST_OUT_INTERMEDIATES)/NOTICE.txt
 tools_notice_file_html := $(HOST_OUT_INTERMEDIATES)/NOTICE.html
+kernel_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/kernel.txt
+winpthreads_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/winpthreads.txt
+pdk_fusion_notice_files := $(filter $(TARGET_OUT_NOTICE_FILES)/%, $(ALL_PDK_FUSION_FILES))
 
 # TODO(b/69865032): Make PRODUCT_NOTICE_SPLIT the default behavior.
-ifeq ($(PRODUCT_NOTICE_SPLIT),true)
-target_notice_file_html_or_xml := $(TARGET_OUT_INTERMEDIATES)/NOTICE.xml
-target_notice_file_html_or_xml_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE.xml.gz
+ifneq ($(PRODUCT_NOTICE_SPLIT),true)
+target_notice_file_html := $(TARGET_OUT_INTERMEDIATES)/NOTICE.html
+target_notice_file_html_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE.html.gz
+installed_notice_html_or_xml_gz := $(TARGET_OUT)/etc/NOTICE.html.gz
+$(eval $(call combine-notice-files, html, \
+	        $(target_notice_file_txt), \
+	        $(target_notice_file_html), \
+	        "Notices for files contained in the filesystem images in this directory:", \
+	        $(TARGET_OUT_NOTICE_FILES), \
+	        $(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file) $(pdk_fusion_notice_files)))
+$(target_notice_file_html_gz): $(target_notice_file_html) | $(MINIGZIP)
+	$(hide) $(MINIGZIP) -9 < $< > $@
+$(installed_notice_html_or_xml_gz): $(target_notice_file_html_gz)
+	$(copy-file-to-target)
+else
+target_notice_file_xml := $(TARGET_OUT_INTERMEDIATES)/NOTICE.xml
+target_notice_file_xml_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE.xml.gz
 installed_notice_html_or_xml_gz := $(TARGET_OUT)/etc/NOTICE.xml.gz
 
 target_vendor_notice_file_txt := $(TARGET_OUT_INTERMEDIATES)/NOTICE_VENDOR.txt
@@ -1017,106 +1086,82 @@
 target_product_services_notice_file_xml := $(TARGET_OUT_INTERMEDIATES)/NOTICE_PRODUCT_SERVICES.xml
 target_product_services_notice_file_xml_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE_PRODUCT_SERVICES.xml.gz
 installed_product_services_notice_xml_gz := $(TARGET_OUT_PRODUCT_SERVICES)/etc/NOTICE.xml.gz
-endif
 
-ifndef TARGET_BUILD_APPS
-kernel_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/kernel.txt
-winpthreads_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/winpthreads.txt
-pdk_fusion_notice_files := $(filter $(TARGET_OUT_NOTICE_FILES)/%, $(ALL_PDK_FUSION_FILES))
+# Notice files are copied to TARGET_OUT_NOTICE_FILES as a side-effect of their module
+# being built. A notice xml file must depend on all modules that could potentially
+# install a license file relevant to it.
+license_modules := $(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file) $(pdk_fusion_notice_files)
+# Phonys/fakes don't have notice files (though their deps might)
+license_modules := $(filter-out $(TARGET_OUT_FAKE)/%,$(license_modules))
+license_modules_vendor := $(filter $(TARGET_OUT_VENDOR)/%,$(license_modules))
+license_modules_product := $(filter $(TARGET_OUT_PRODUCT)/%,$(license_modules))
+license_modules_product_services := $(filter $(TARGET_OUT_PRODUCT_SERVICES)/%,$(license_modules))
+license_modules_agg := $(license_modules_vendor) $(license_modules_product) $(license_modules_product_services)
+license_modules_rest := $(filter-out $(license_modules_agg),$(license_modules))
 
-ifdef target_vendor_notice_file_xml_gz
 $(eval $(call combine-notice-files, xml_excluded_extra_partitions, \
-			$(target_notice_file_txt), \
-			$(target_notice_file_html_or_xml), \
-			"Notices for files contained in the filesystem images in this directory:", \
-			$(TARGET_OUT_NOTICE_FILES), \
-			$(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file) $(pdk_fusion_notice_files)))
+	        $(target_notice_file_txt), \
+	        $(target_notice_file_xml), \
+	        "Notices for files contained in the filesystem images in this directory:", \
+	        $(TARGET_OUT_NOTICE_FILES), \
+	        $(license_modules_rest)))
 $(eval $(call combine-notice-files, xml_vendor, \
-			$(target_vendor_notice_file_txt), \
-			$(target_vendor_notice_file_xml), \
-			"Notices for files contained in the vendor filesystem image in this directory:", \
-			$(TARGET_OUT_NOTICE_FILES), \
-			$(target_notice_file_html_or_xml)))
-ifdef target_product_notice_file_txt
+	        $(target_vendor_notice_file_txt), \
+	        $(target_vendor_notice_file_xml), \
+	        "Notices for files contained in the vendor filesystem image in this directory:", \
+	        $(TARGET_OUT_NOTICE_FILES), \
+	        $(license_modules_vendor)))
 $(eval $(call combine-notice-files, xml_product, \
-			$(target_product_notice_file_txt), \
-			$(target_product_notice_file_xml), \
-			"Notices for files contained in the product filesystem image in this directory:", \
-			$(TARGET_OUT_NOTICE_FILES), \
-			$(target_notice_file_html_or_xml)))
-endif
-ifdef target_product_services_notice_file_txt
+	        $(target_product_notice_file_txt), \
+	        $(target_product_notice_file_xml), \
+	        "Notices for files contained in the product filesystem image in this directory:", \
+	        $(TARGET_OUT_NOTICE_FILES), \
+	        $(license_modules_product)))
 $(eval $(call combine-notice-files, xml_product_services, \
-			$(target_product_services_notice_file_txt), \
-			$(target_product_services_notice_file_xml), \
-			"Notices for files contained in the product_services filesystem image in this directory:", \
-			$(TARGET_OUT_NOTICE_FILES), \
-			$(target_notice_file_html_or_xml)))
-endif
-else
-$(eval $(call combine-notice-files, html, \
-			$(target_notice_file_txt), \
-			$(target_notice_file_html_or_xml), \
-			"Notices for files contained in the filesystem images in this directory:", \
-			$(TARGET_OUT_NOTICE_FILES), \
-			$(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file) $(pdk_fusion_notice_files)))
-endif
+	        $(target_product_services_notice_file_txt), \
+	        $(target_product_services_notice_file_xml), \
+	        "Notices for files contained in the product_services filesystem image in this directory:", \
+	        $(TARGET_OUT_NOTICE_FILES), \
+	        $(license_modules_product_services)))
 
-$(eval $(call combine-notice-files, html, \
-			$(tools_notice_file_txt), \
-			$(tools_notice_file_html), \
-			"Notices for files contained in the tools directory:", \
-			$(HOST_OUT_NOTICE_FILES), \
-			$(ALL_DEFAULT_INSTALLED_MODULES) \
-			$(winpthreads_notice_file)))
-
-# Install the html file at /system/etc/NOTICE.html.gz.
-# This is not ideal, but this is very late in the game, after a lot of
-# the module processing has already been done -- in fact, we used the
-# fact that all that has been done to get the list of modules that we
-# need notice files for.
-$(target_notice_file_html_or_xml_gz): $(target_notice_file_html_or_xml) | $(MINIGZIP)
+$(target_notice_file_xml_gz): $(target_notice_file_xml) | $(MINIGZIP)
 	$(hide) $(MINIGZIP) -9 < $< > $@
-$(installed_notice_html_or_xml_gz): $(target_notice_file_html_or_xml_gz)
-	$(copy-file-to-target)
-
-ifdef target_vendor_notice_file_xml_gz
-# Install the vendor html file at /vendor/etc/NOTICE.xml.gz.
 $(target_vendor_notice_file_xml_gz): $(target_vendor_notice_file_xml) | $(MINIGZIP)
 	$(hide) $(MINIGZIP) -9 < $< > $@
-$(installed_vendor_notice_xml_gz): $(target_vendor_notice_file_xml_gz)
-	$(copy-file-to-target)
-endif
-
-ifdef target_product_notice_file_xml_gz
-# Install the product html file at /product/etc/NOTICE.xml.gz.
 $(target_product_notice_file_xml_gz): $(target_product_notice_file_xml) | $(MINIGZIP)
 	$(hide) $(MINIGZIP) -9 < $< > $@
-$(installed_product_notice_xml_gz): $(target_product_notice_file_xml_gz)
-	$(copy-file-to-target)
-endif
-
-ifdef target_product_services_notice_file_xml_gz
-# Install the product html file at /product_services/etc/NOTICE.xml.gz.
 $(target_product_services_notice_file_xml_gz): $(target_product_services_notice_file_xml) | $(MINIGZIP)
 	$(hide) $(MINIGZIP) -9 < $< > $@
+$(installed_notice_html_or_xml_gz): $(target_notice_file_xml_gz)
+	$(copy-file-to-target)
+$(installed_vendor_notice_xml_gz): $(target_vendor_notice_file_xml_gz)
+	$(copy-file-to-target)
+$(installed_product_notice_xml_gz): $(target_product_notice_file_xml_gz)
+	$(copy-file-to-target)
 $(installed_product_services_notice_xml_gz): $(target_product_services_notice_file_xml_gz)
 	$(copy-file-to-target)
-endif
 
 # if we've been run my mm, mmm, etc, don't reinstall this every time
 ifeq ($(ONE_SHOT_MAKEFILE),)
   ALL_DEFAULT_INSTALLED_MODULES += $(installed_notice_html_or_xml_gz)
-  ifdef target_vendor_notice_file_xml_gz
-    ALL_DEFAULT_INSTALLED_MODULES += $(installed_vendor_notice_xml_gz)
-  endif
-  ifdef target_product_notice_file_xml_gz
-    ALL_DEFAULT_INSTALLED_MODULES += $(installed_product_notice_xml_gz)
-  endif
-  ifdef target_product_services_notice_file_xml_gz
-    ALL_DEFAULT_INSTALLED_MODULES += $(installed_product_services_notice_xml_gz)
-  endif
+  ALL_DEFAULT_INSTALLED_MODULES += $(installed_vendor_notice_xml_gz)
+  ALL_DEFAULT_INSTALLED_MODULES += $(installed_product_notice_xml_gz)
+  ALL_DEFAULT_INSTALLED_MODULES += $(installed_product_services_notice_xml_gz)
 endif
+endif # PRODUCT_NOTICE_SPLIT
+
+ifeq ($(ONE_SHOT_MAKEFILE),)
+  ALL_DEFAULT_INSTALLED_MODULES += $(installed_notice_html_or_xml_gz)
+endif
+
+$(eval $(call combine-notice-files, html, \
+	        $(tools_notice_file_txt), \
+	        $(tools_notice_file_html), \
+	        "Notices for files contained in the tools directory:", \
+	        $(HOST_OUT_NOTICE_FILES), \
+	        $(ALL_DEFAULT_INSTALLED_MODULES) \
+	        $(winpthreads_notice_file)))
+
 endif  # TARGET_BUILD_APPS
 
 # The kernel isn't really a module, so to get its module file in there, we
@@ -1164,7 +1209,7 @@
 ALL_DEFAULT_INSTALLED_MODULES += \
     $(TARGET_RECOVERY_ROOT_OUT)/system/etc/update_engine/update-payload-key.pub.pem
 $(TARGET_RECOVERY_ROOT_OUT)/system/etc/update_engine/update-payload-key.pub.pem: \
-		$(TARGET_OUT_ETC)/update_engine/update-payload-key.pub.pem
+	    $(TARGET_OUT_ETC)/update_engine/update-payload-key.pub.pem
 	$(hide) cp -f $< $@
 endif
 endif
@@ -1241,7 +1286,7 @@
 INTERNAL_USERIMAGES_DEPS += $(MKE2FS_CONF)
 endif
 
-ifeq (true,$(PRODUCT_USE_LOGICAL_PARTITIONS))
+ifeq (true,$(PRODUCT_USE_DYNAMIC_PARTITIONS))
 
 ifeq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),true)
   $(error vboot 1.0 doesn't support logical partition)
@@ -1250,7 +1295,7 @@
 # TODO(b/80195851): Should not define BOARD_AVB_SYSTEM_KEY_PATH without
 # BOARD_AVB_SYSTEM_DETACHED_VBMETA.
 
-endif # PRODUCT_USE_LOGICAL_PARTITIONS
+endif # PRODUCT_USE_DYNAMIC_PARTITIONS
 
 # $(1): the path of the output dictionary file
 # $(2): a subset of "system vendor cache userdata product product_services oem odm"
@@ -1522,11 +1567,111 @@
 recovery_font := $(call include-path-for, recovery)/fonts/12x22.png
 endif
 
+
+# We will only generate the recovery background text images if the variable
+# TARGET_RECOVERY_UI_SCREEN_WIDTH is defined. For devices with xxxhdpi and xxhdpi, we set the
+# variable to the commonly used values here, if it hasn't been intialized elsewhere. While for
+# devices with lower density, they must have TARGET_RECOVERY_UI_SCREEN_WIDTH defined in their
+# BoardConfig in order to use this feature.
+ifeq ($(recovery_density),xxxhdpi)
+TARGET_RECOVERY_UI_SCREEN_WIDTH ?= 1440
+else ifeq ($(recovery_density),xxhdpi)
+TARGET_RECOVERY_UI_SCREEN_WIDTH ?= 1080
+endif
+
+ifneq ($(TARGET_RECOVERY_UI_SCREEN_WIDTH),)
+# Subtracts the margin width and menu indent from the screen width; it's safe to be conservative.
+ifeq ($(TARGET_RECOVERY_UI_MARGIN_WIDTH),)
+  recovery_image_width := $$(($(TARGET_RECOVERY_UI_SCREEN_WIDTH) - 10))
+else
+  recovery_image_width := $$(($(TARGET_RECOVERY_UI_SCREEN_WIDTH) - $(TARGET_RECOVERY_UI_MARGIN_WIDTH) - 10))
+endif
+
+
+RECOVERY_INSTALLING_TEXT_FILE := $(call intermediates-dir-for,PACKAGING,recovery_text_res)/installing_text.png
+RECOVERY_INSTALLING_SECURITY_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/installing_security_text.png
+RECOVERY_ERASING_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/erasing_text.png
+RECOVERY_ERROR_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/error_text.png
+RECOVERY_NO_COMMAND_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/no_command_text.png
+
+RECOVERY_CANCEL_WIPE_DATA_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/cancel_wipe_data_text.png
+RECOVERY_FACTORY_DATA_RESET_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/factory_data_reset_text.png
+RECOVERY_TRY_AGAIN_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/try_again_text.png
+RECOVERY_WIPE_DATA_CONFIRMATION_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/wipe_data_confirmation_text.png
+RECOVERY_WIPE_DATA_MENU_HEADER_TEXT_FILE := $(dir $(RECOVERY_INSTALLING_TEXT_FILE))/wipe_data_menu_header_text.png
+
+generated_recovery_text_files := \
+  $(RECOVERY_INSTALLING_TEXT_FILE) \
+  $(RECOVERY_INSTALLING_SECURITY_TEXT_FILE) \
+  $(RECOVERY_ERASING_TEXT_FILE) \
+  $(RECOVERY_ERROR_TEXT_FILE) \
+  $(RECOVERY_NO_COMMAND_TEXT_FILE) \
+  $(RECOVERY_CANCEL_WIPE_DATA_TEXT_FILE) \
+  $(RECOVERY_FACTORY_DATA_RESET_TEXT_FILE) \
+  $(RECOVERY_TRY_AGAIN_TEXT_FILE) \
+  $(RECOVERY_WIPE_DATA_CONFIRMATION_TEXT_FILE) \
+  $(RECOVERY_WIPE_DATA_MENU_HEADER_TEXT_FILE)
+
+resource_dir := $(call include-path-for, recovery)/tools/recovery_l10n/res/
+image_generator_jar := $(HOST_OUT_JAVA_LIBRARIES)/RecoveryImageGenerator.jar
+zopflipng := $(HOST_OUT_EXECUTABLES)/zopflipng
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_SOURCE_FONTS := $(recovery_noto-fonts_dep) $(recovery_roboto-fonts_dep)
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_RECOVERY_FONT_FILES_DIR := $(call intermediates-dir-for,PACKAGING,recovery_font_files)
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_RESOURCE_DIR := $(resource_dir)
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_IMAGE_GENERATOR_JAR := $(image_generator_jar)
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_ZOPFLIPNG := $(zopflipng)
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_RECOVERY_IMAGE_WIDTH := $(recovery_image_width)
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_RECOVERY_BACKGROUND_TEXT_LIST := \
+  recovery_installing \
+  recovery_installing_security \
+  recovery_erasing \
+  recovery_error \
+  recovery_no_command
+$(RECOVERY_INSTALLING_TEXT_FILE): PRIVATE_RECOVERY_WIPE_DATA_TEXT_LIST := \
+  recovery_cancel_wipe_data \
+  recovery_factory_data_reset \
+  recovery_try_again \
+  recovery_wipe_data_menu_header \
+  recovery_wipe_data_confirmation
+$(RECOVERY_INSTALLING_TEXT_FILE): .KATI_IMPLICIT_OUTPUTS := $(filter-out $(RECOVERY_INSTALLING_TEXT_FILE),$(generated_recovery_text_files))
+$(RECOVERY_INSTALLING_TEXT_FILE): $(image_generator_jar) $(resource_dir) $(recovery_noto-fonts_dep) $(recovery_roboto-fonts_dep) $(zopflipng)
+	# Prepares the font directory.
+	@rm -rf $(PRIVATE_RECOVERY_FONT_FILES_DIR)
+	@mkdir -p $(PRIVATE_RECOVERY_FONT_FILES_DIR)
+	$(foreach filename,$(PRIVATE_SOURCE_FONTS), cp $(filename) $(PRIVATE_RECOVERY_FONT_FILES_DIR) &&) true
+	@rm -rf $(dir $@)
+	@mkdir -p $(dir $@)
+	$(foreach text_name,$(PRIVATE_RECOVERY_BACKGROUND_TEXT_LIST) $(PRIVATE_RECOVERY_WIPE_DATA_TEXT_LIST), \
+	  $(eval output_file := $(dir $@)/$(patsubst recovery_%,%_text.png,$(text_name))) \
+	  $(eval center_alignment := $(if $(filter $(text_name),$(PRIVATE_RECOVERY_BACKGROUND_TEXT_LIST)), --center_alignment)) \
+	  java -jar $(PRIVATE_IMAGE_GENERATOR_JAR) \
+	    --image_width $(PRIVATE_RECOVERY_IMAGE_WIDTH) \
+	    --text_name $(text_name) \
+	    --font_dir $(PRIVATE_RECOVERY_FONT_FILES_DIR) \
+	    --resource_dir $(PRIVATE_RESOURCE_DIR) \
+	    --output_file $(output_file) $(center_alignment) && \
+	  $(PRIVATE_ZOPFLIPNG) -y --iterations=1 --filters=0 $(output_file) $(output_file) > /dev/null &&) true
+else
+RECOVERY_INSTALLING_TEXT_FILE :=
+RECOVERY_INSTALLING_SECURITY_TEXT_FILE :=
+RECOVERY_ERASING_TEXT_FILE :=
+RECOVERY_ERROR_TEXT_FILE :=
+RECOVERY_NO_COMMAND_TEXT_FILE :=
+RECOVERY_CANCEL_WIPE_DATA_TEXT_FILE :=
+RECOVERY_FACTORY_DATA_RESET_TEXT_FILE :=
+RECOVERY_TRY_AGAIN_TEXT_FILE :=
+RECOVERY_WIPE_DATA_CONFIRMATION_TEXT_FILE :=
+RECOVERY_WIPE_DATA_MENU_HEADER_TEXT_FILE :=
+endif # TARGET_RECOVERY_UI_SCREEN_WIDTH
+
 ifndef TARGET_PRIVATE_RES_DIRS
 TARGET_PRIVATE_RES_DIRS := $(wildcard $(TARGET_DEVICE_DIR)/recovery/res)
 endif
 recovery_resource_deps := $(shell find $(recovery_resources_common) \
   $(TARGET_PRIVATE_RES_DIRS) -type f)
+recovery_resource_deps += $(generated_recovery_text_files)
+
+
 ifdef TARGET_RECOVERY_FSTAB
 recovery_fstab := $(TARGET_RECOVERY_FSTAB)
 else
@@ -1553,9 +1698,12 @@
 #   d) We include the recovery DTBO image within recovery - not needing the resource file as we
 #      do bsdiff because boot and recovery will contain different number of entries
 #      (BOARD_INCLUDE_RECOVERY_DTBO = true).
+#   e) We include the recovery ACPIO image within recovery - not needing the resource file as we
+#      do bsdiff because boot and recovery will contain different number of entries
+#      (BOARD_INCLUDE_RECOVERY_ACPIO = true).
 
 ifeq (,$(filter true, $(BOARD_USES_FULL_RECOVERY_IMAGE) $(BOARD_USES_RECOVERY_AS_BOOT) \
-  $(BOARD_BUILD_SYSTEM_ROOT_IMAGE) $(BOARD_INCLUDE_RECOVERY_DTBO)))
+  $(BOARD_BUILD_SYSTEM_ROOT_IMAGE) $(BOARD_INCLUDE_RECOVERY_DTBO) $(BOARD_INCLUDE_RECOVERY_ACPIO)))
 # Named '.dat' so we don't attempt to use imgdiff for patching it.
 RECOVERY_RESOURCE_ZIP := $(TARGET_OUT)/etc/recovery-resource.dat
 else
@@ -1592,13 +1740,13 @@
 endef
 
 $(INSTALLED_RECOVERY_BUILD_PROP_TARGET): \
-		$(INSTALLED_DEFAULT_PROP_TARGET) \
-		$(INSTALLED_VENDOR_DEFAULT_PROP_TARGET) \
-		$(intermediate_system_build_prop) \
-		$(INSTALLED_VENDOR_BUILD_PROP_TARGET) \
-		$(INSTALLED_ODM_BUILD_PROP_TARGET) \
-		$(INSTALLED_PRODUCT_BUILD_PROP_TARGET) \
-		$(INSTALLED_PRODUCT_SERVICES_BUILD_PROP_TARGET)
+	    $(INSTALLED_DEFAULT_PROP_TARGET) \
+	    $(INSTALLED_VENDOR_DEFAULT_PROP_TARGET) \
+	    $(intermediate_system_build_prop) \
+	    $(INSTALLED_VENDOR_BUILD_PROP_TARGET) \
+	    $(INSTALLED_ODM_BUILD_PROP_TARGET) \
+	    $(INSTALLED_PRODUCT_BUILD_PROP_TARGET) \
+	    $(INSTALLED_PRODUCT_SERVICES_BUILD_PROP_TARGET)
 	@echo "Target recovery buildinfo: $@"
 	$(hide) mkdir -p $(dir $@)
 	$(hide) rm -f $@
@@ -1629,6 +1777,9 @@
 ifdef BOARD_INCLUDE_RECOVERY_DTBO
   INTERNAL_RECOVERYIMAGE_ARGS += --recovery_dtbo $(BOARD_PREBUILT_DTBOIMAGE)
 endif
+ifdef BOARD_INCLUDE_RECOVERY_ACPIO
+  INTERNAL_RECOVERYIMAGE_ARGS += --recovery_acpio $(BOARD_RECOVERY_ACPIO)
+endif
 
 # Keys authorized to sign OTA packages this build will accept.  The
 # build always uses dev-keys for this; release packaging tools will
@@ -1656,9 +1807,9 @@
   # Copying baseline ramdisk...
   # Use rsync because "cp -Rf" fails to overwrite broken symlinks on Mac.
   $(hide) rsync -a --exclude=sdcard $(IGNORE_RECOVERY_SEPOLICY) $(IGNORE_CACHE_LINK) $(TARGET_ROOT_OUT) $(TARGET_RECOVERY_OUT)
-  $(if $(filter true,$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)),, \
-    $(hide) rsync -a $(TARGET_RAMDISK_OUT)/* $(TARGET_RECOVERY_ROOT_OUT)/)
   # Modifying ramdisk contents...
+  $(if $(filter true,$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)),, \
+    $(hide) ln -sf /system/bin/init $(TARGET_RECOVERY_ROOT_OUT)/init)
   $(if $(BOARD_RECOVERY_KERNEL_MODULES), \
     $(call build-image-kernel-modules,$(BOARD_RECOVERY_KERNEL_MODULES),$(TARGET_RECOVERY_ROOT_OUT),,$(call intermediates-dir-for,PACKAGING,depmod_recovery)))
   # Removes $(TARGET_RECOVERY_ROOT_OUT)/init*.rc EXCEPT init.recovery*.rc.
@@ -1668,6 +1819,8 @@
   $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/res
   $(hide) rm -rf $(TARGET_RECOVERY_ROOT_OUT)/res/*
   $(hide) cp -rf $(recovery_resources_common)/* $(TARGET_RECOVERY_ROOT_OUT)/res
+  $(hide) $(foreach recovery_text_file,$(generated_recovery_text_files), \
+    cp -rf $(recovery_text_file) $(TARGET_RECOVERY_ROOT_OUT)/res/images/ &&) true
   $(hide) cp -f $(recovery_font) $(TARGET_RECOVERY_ROOT_OUT)/res/images/font.png
   $(hide) $(foreach item,$(TARGET_PRIVATE_RES_DIRS), \
     cp -rf $(item) $(TARGET_RECOVERY_ROOT_OUT)/$(newline))
@@ -1713,19 +1866,22 @@
 ifdef BOARD_INCLUDE_RECOVERY_DTBO
 $(INSTALLED_BOOTIMAGE_TARGET): $(BOARD_PREBUILT_DTBOIMAGE)
 endif
+ifdef BOARD_INCLUDE_RECOVERY_ACPIO
+$(INSTALLED_BOOTIMAGE_TARGET): $(BOARD_RECOVERY_ACPIO)
+endif
 
 $(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTFS) $(MKBOOTIMG) $(MINIGZIP) \
-		$(INTERNAL_ROOT_FILES) \
-		$(INSTALLED_RAMDISK_TARGET) \
-		$(INTERNAL_RECOVERYIMAGE_FILES) \
-		$(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \
-		$(INSTALLED_2NDBOOTLOADER_TARGET) \
-		$(INSTALLED_RECOVERY_BUILD_PROP_TARGET) \
-		$(recovery_resource_deps) \
-		$(recovery_fstab) \
-		$(RECOVERY_INSTALL_OTA_KEYS) \
-		$(BOARD_RECOVERY_KERNEL_MODULES) \
-		$(DEPMOD)
+	    $(INTERNAL_ROOT_FILES) \
+	    $(INSTALLED_RAMDISK_TARGET) \
+	    $(INTERNAL_RECOVERYIMAGE_FILES) \
+	    $(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \
+	    $(INSTALLED_2NDBOOTLOADER_TARGET) \
+	    $(INSTALLED_RECOVERY_BUILD_PROP_TARGET) \
+	    $(recovery_resource_deps) \
+	    $(recovery_fstab) \
+	    $(RECOVERY_INSTALL_OTA_KEYS) \
+	    $(BOARD_RECOVERY_KERNEL_MODULES) \
+	    $(DEPMOD)
 	$(call pretty,"Target boot image from recovery: $@")
 	$(call build-recoveryimage-target, $@)
 endif # BOARD_USES_RECOVERY_AS_BOOT
@@ -1733,20 +1889,23 @@
 ifdef BOARD_INCLUDE_RECOVERY_DTBO
 $(INSTALLED_RECOVERYIMAGE_TARGET): $(BOARD_PREBUILT_DTBOIMAGE)
 endif
+ifdef BOARD_INCLUDE_RECOVERY_ACPIO
+$(INSTALLED_RECOVERYIMAGE_TARGET): $(BOARD_RECOVERY_ACPIO)
+endif
 
 $(INSTALLED_RECOVERYIMAGE_TARGET): $(MKBOOTFS) $(MKBOOTIMG) $(MINIGZIP) \
-		$(INTERNAL_ROOT_FILES) \
-		$(INSTALLED_RAMDISK_TARGET) \
-		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(INTERNAL_RECOVERYIMAGE_FILES) \
-		$(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \
-		$(INSTALLED_2NDBOOTLOADER_TARGET) \
-		$(INSTALLED_RECOVERY_BUILD_PROP_TARGET) \
-		$(recovery_resource_deps) \
-		$(recovery_fstab) \
-		$(RECOVERY_INSTALL_OTA_KEYS) \
-		$(BOARD_RECOVERY_KERNEL_MODULES) \
-		$(DEPMOD)
+	    $(INTERNAL_ROOT_FILES) \
+	    $(INSTALLED_RAMDISK_TARGET) \
+	    $(INSTALLED_BOOTIMAGE_TARGET) \
+	    $(INTERNAL_RECOVERYIMAGE_FILES) \
+	    $(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \
+	    $(INSTALLED_2NDBOOTLOADER_TARGET) \
+	    $(INSTALLED_RECOVERY_BUILD_PROP_TARGET) \
+	    $(recovery_resource_deps) \
+	    $(recovery_fstab) \
+	    $(RECOVERY_INSTALL_OTA_KEYS) \
+	    $(BOARD_RECOVERY_KERNEL_MODULES) \
+	    $(DEPMOD)
 	$(call build-recoveryimage-target, $@)
 
 ifdef RECOVERY_RESOURCE_ZIP
@@ -1816,11 +1975,11 @@
 	@echo "Verifying system VINTF manifest."
 	PRODUCT_ENFORCE_VINTF_MANIFEST=$(PRODUCT_ENFORCE_VINTF_MANIFEST) \
 	$(HOST_OUT_EXECUTABLES)/assemble_vintf \
-		-c $(BUILT_VENDOR_MATRIX) \
-		-i $(BUILT_SYSTEM_MANIFEST) \
-		$$([ -d $(TARGET_OUT)/etc/vintf/manifest ] && \
-			find $(TARGET_OUT)/etc/vintf/manifest -type f -name "*.xml" | \
-			sed "s/^/-i /" | tr '\n' ' ') -o $@
+	    -c $(BUILT_VENDOR_MATRIX) \
+	    -i $(BUILT_SYSTEM_MANIFEST) \
+	    $$([ -d $(TARGET_OUT)/etc/vintf/manifest ] && \
+	        find $(TARGET_OUT)/etc/vintf/manifest -type f -name "*.xml" | \
+	        sed "s/^/-i /" | tr '\n' ' ') -o $@
 
 # -----------------------------------------------------------------
 # installed file list
@@ -1943,7 +2102,7 @@
 ifneq ($(INSTALLED_BOOTIMAGE_TARGET),)
 ifneq ($(INSTALLED_RECOVERYIMAGE_TARGET),)
 ifneq ($(BOARD_USES_FULL_RECOVERY_IMAGE),true)
-ifneq (,$(filter true, $(BOARD_BUILD_SYSTEM_ROOT_IMAGE) $(BOARD_INCLUDE_RECOVERY_DTBO)))
+ifneq (,$(filter true, $(BOARD_BUILD_SYSTEM_ROOT_IMAGE) $(BOARD_INCLUDE_RECOVERY_DTBO) $(BOARD_INCLUDE_RECOVERY_ACPIO)))
 diff_tool := $(HOST_OUT_EXECUTABLES)/bsdiff
 else
 diff_tool := $(HOST_OUT_EXECUTABLES)/imgdiff
@@ -1952,9 +2111,9 @@
 RECOVERY_FROM_BOOT_PATCH := $(intermediates)/recovery_from_boot.p
 $(RECOVERY_FROM_BOOT_PATCH): PRIVATE_DIFF_TOOL := $(diff_tool)
 $(RECOVERY_FROM_BOOT_PATCH): \
-		$(INSTALLED_RECOVERYIMAGE_TARGET) \
-		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(diff_tool)
+	    $(INSTALLED_RECOVERYIMAGE_TARGET) \
+	    $(INSTALLED_BOOTIMAGE_TARGET) \
+	    $(diff_tool)
 	@echo "Construct recovery from boot"
 	mkdir -p $(dir $@)
 	$(PRIVATE_DIFF_TOOL) $(INSTALLED_BOOTIMAGE_TARGET) $(INSTALLED_RECOVERYIMAGE_TARGET) $@
@@ -1968,8 +2127,8 @@
 	@echo "Install system fs image: $@"
 	$(copy-file-to-target)
 	$(hide) $(call assert-max-image-size,$@ $(RECOVERY_FROM_BOOT_PATCH),\
-		$(call read-image-prop-dictionary,\
-			$(systemimage_intermediates)/generated_system_image_info.txt,system_size))
+	    $(call read-image-prop-dictionary,\
+	        $(systemimage_intermediates)/generated_system_image_info.txt,system_size))
 
 systemimage: $(INSTALLED_SYSTEMIMAGE_TARGET)
 
@@ -1979,8 +2138,8 @@
 	@echo "make $@: ignoring dependencies"
 	$(call build-systemimage-target,$(INSTALLED_SYSTEMIMAGE_TARGET))
 	$(hide) $(call assert-max-image-size,$(INSTALLED_SYSTEMIMAGE_TARGET),\
-		$(call read-image-prop-dictionary,\
-			$(systemimage_intermediates)/generated_system_image_info.txt,system_size))
+	    $(call read-image-prop-dictionary,\
+	        $(systemimage_intermediates)/generated_system_image_info.txt,system_size))
 
 ifneq (,$(filter systemimage-nodeps snod, $(MAKECMDGOALS)))
 ifeq (true,$(WITH_DEXPREOPT))
@@ -1988,8 +2147,8 @@
 endif
 endif
 
-.PHONY: sync
-sync: $(INTERNAL_SYSTEMIMAGE_FILES)
+.PHONY: sync syncsys
+sync syncsys: $(INTERNAL_SYSTEMIMAGE_FILES)
 
 #######
 ## system tarball
@@ -2030,9 +2189,9 @@
 ## Files under out dir will be rejected to prevent possible conflicts with other rules.
 ifneq (,$(BUILD_PLATFORM_ZIP))
 pdk_odex_javalibs := $(strip $(foreach m,$(DEXPREOPT.MODULES.JAVA_LIBRARIES),\
-  $(if $(filter $(DEXPREOPT.$(m).INSTALLED),$(ALL_DEFAULT_INSTALLED_MODULES)),$(m))))
+  $(if $(filter $(DEXPREOPT.$(m).INSTALLED_STRIPPED),$(ALL_DEFAULT_INSTALLED_MODULES)),$(m))))
 pdk_odex_apps := $(strip $(foreach m,$(DEXPREOPT.MODULES.APPS),\
-  $(if $(filter $(DEXPREOPT.$(m).INSTALLED),$(ALL_DEFAULT_INSTALLED_MODULES)),$(m))))
+  $(if $(filter $(DEXPREOPT.$(m).INSTALLED_STRIPPED),$(ALL_DEFAULT_INSTALLED_MODULES)),$(m))))
 pdk_classes_dex := $(strip \
   $(foreach m,$(pdk_odex_javalibs),$(call intermediates-dir-for,JAVA_LIBRARIES,$(m),,COMMON)/javalib.jar) \
   $(foreach m,$(pdk_odex_apps),$(call intermediates-dir-for,APPS,$(m))/package.dex.apk))
@@ -2071,7 +2230,7 @@
 $(INSTALLED_PLATFORM_ZIP) : $(SOONG_ZIP)
 # dependencies for the other partitions are defined below after their file lists
 # are known
-$(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_SYSTEMIMAGE_FILES) $(pdk_classes_dex) $(pdk_odex_config_mk)
+$(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_SYSTEMIMAGE_FILES) $(pdk_classes_dex) $(pdk_odex_config_mk) $(api_fingerprint)
 	$(call pretty,"Platform zip package: $(INSTALLED_PLATFORM_ZIP)")
 	rm -f $@ $@.lst
 	echo "-C $(PRODUCT_OUT)" >> $@.lst
@@ -2104,6 +2263,7 @@
 	@# Add dex-preopt files and config.
 	$(if $(PRIVATE_DEX_FILES),\
 	  echo "-C $(OUT_DIR) $(addprefix -f ,$(PRIVATE_DEX_FILES))") >> $@.lst
+	echo "-C $(dir $(api_fingerprint)) -f $(api_fingerprint)" >> $@.lst
 	touch $(PRODUCT_OUT)/pdk.mk
 	echo "-C $(PRODUCT_OUT) -f $(PRIVATE_ODEX_CONFIG) -f $(PRODUCT_OUT)/pdk.mk" >> $@.lst
 	$(SOONG_ZIP) --ignore_missing_files -o $@ @$@.lst
@@ -2213,8 +2373,8 @@
     $(call pretty,"Target userdata fs tarball: " \
                   "$(INSTALLED_USERDATATARBALL_TARGET)")
     $(MKTARBALL) $(FS_GET_STATS) \
-		$(PRODUCT_OUT) data $(PRIVATE_USERDATA_TAR) \
-		$(INSTALLED_USERDATATARBALL_TARGET) $(TARGET_OUT)
+	    $(PRODUCT_OUT) data $(PRIVATE_USERDATA_TAR) \
+	    $(INSTALLED_USERDATATARBALL_TARGET) $(TARGET_OUT)
 endef
 
 userdata_tar := $(PRODUCT_OUT)/userdata.tar
@@ -2318,6 +2478,9 @@
       $(ALL_PDK_FUSION_FILES)) \
     $(PDK_FUSION_SYMLINK_STAMP)
 
+# system_other dex files are installed as a side-effect of installing system image files
+INTERNAL_SYSTEMOTHERIMAGE_FILES += $(INTERNAL_SYSTEMIMAGE_FILES)
+
 INSTALLED_FILES_FILE_SYSTEMOTHER := $(PRODUCT_OUT)/installed-files-system-other.txt
 INSTALLED_FILES_JSON_SYSTEMOTHER := $(INSTALLED_FILES_FILE_SYSTEMOTHER:.txt=.json)
 $(INSTALLED_FILES_FILE_SYSTEMOTHER): .KATI_IMPLICIT_OUTPUTS := $(INSTALLED_FILES_JSON_SYSTEMOTHER)
@@ -2390,11 +2553,11 @@
 	PRODUCT_ENFORCE_VINTF_MANIFEST=$(PRODUCT_ENFORCE_VINTF_MANIFEST) \
 	$(PRIVATE_SYSTEM_ASSEMBLE_VINTF_ENV_VARS) \
 	$(HOST_OUT_EXECUTABLES)/assemble_vintf \
-		-c $(BUILT_SYSTEM_MATRIX) \
-		-i $(BUILT_VENDOR_MANIFEST) \
-		$$([ -d $(TARGET_OUT_VENDOR)/etc/vintf/manifest ] && \
-			find $(TARGET_OUT_VENDOR)/etc/vintf/manifest -type f -name "*.xml" | \
-			sed "s/^/-i /" | tr '\n' ' ') -o $@
+	    -c $(BUILT_SYSTEM_MATRIX) \
+	    -i $(BUILT_VENDOR_MANIFEST) \
+	    $$([ -d $(TARGET_OUT_VENDOR)/etc/vintf/manifest ] && \
+	        find $(TARGET_OUT_VENDOR)/etc/vintf/manifest -type f -name "*.xml" | \
+	        sed "s/^/-i /" | tr '\n' ' ') -o $@
 endif # BUILT_VENDOR_MANIFEST
 
 # platform.zip depends on $(INTERNAL_VENDORIMAGE_FILES).
@@ -2624,10 +2787,10 @@
 $(INSTALLED_DTBOIMAGE_TARGET): $(BOARD_PREBUILT_DTBOIMAGE) $(AVBTOOL) $(BOARD_AVB_DTBO_KEY_PATH)
 	cp $(BOARD_PREBUILT_DTBOIMAGE) $@
 	$(AVBTOOL) add_hash_footer \
-		--image $@ \
-		--partition_size $(BOARD_DTBOIMG_PARTITION_SIZE) \
-		--partition_name dtbo $(INTERNAL_AVB_DTBO_SIGNING_ARGS) \
-		$(BOARD_AVB_DTBO_ADD_HASH_FOOTER_ARGS)
+	    --image $@ \
+	    --partition_size $(BOARD_DTBOIMG_PARTITION_SIZE) \
+	    --partition_name dtbo $(INTERNAL_AVB_DTBO_SIGNING_ARGS) \
+	    $(BOARD_AVB_DTBO_ADD_HASH_FOOTER_ARGS)
 else
 $(INSTALLED_DTBOIMAGE_TARGET): $(BOARD_PREBUILT_DTBOIMAGE)
 	cp $(BOARD_PREBUILT_DTBOIMAGE) $@
@@ -2851,18 +3014,18 @@
 ifdef BOARD_AVB_VBMETA_SYSTEM
 INSTALLED_VBMETA_SYSTEMIMAGE_TARGET := $(PRODUCT_OUT)/vbmeta_system.img
 $(INSTALLED_VBMETA_SYSTEMIMAGE_TARGET): \
-		$(AVBTOOL) \
-		$(call images-for-partitions,$(BOARD_AVB_VBMETA_SYSTEM)) \
-		$(BOARD_AVB_VBMETA_SYSTEM_KEY_PATH)
+	    $(AVBTOOL) \
+	    $(call images-for-partitions,$(BOARD_AVB_VBMETA_SYSTEM)) \
+	    $(BOARD_AVB_VBMETA_SYSTEM_KEY_PATH)
 	$(call build-chained-vbmeta-image,vbmeta_system)
 endif
 
 ifdef BOARD_AVB_VBMETA_VENDOR
 INSTALLED_VBMETA_VENDORIMAGE_TARGET := $(PRODUCT_OUT)/vbmeta_vendor.img
 $(INSTALLED_VBMETA_VENDORIMAGE_TARGET): \
-		$(AVBTOOL) \
-		$(call images-for-partitions,$(BOARD_AVB_VBMETA_VENDOR)) \
-		$(BOARD_AVB_VBMETA_VENDOR_KEY_PATH)
+	    $(AVBTOOL) \
+	    $(call images-for-partitions,$(BOARD_AVB_VBMETA_VENDOR)) \
+	    $(BOARD_AVB_VBMETA_VENDOR_KEY_PATH)
 	$(call build-chained-vbmeta-image,vbmeta_vendor)
 endif
 
@@ -2883,20 +3046,20 @@
     --algorithm $(BOARD_AVB_ALGORITHM) --key $(BOARD_AVB_KEY_PATH)
 
 $(INSTALLED_VBMETAIMAGE_TARGET): \
-		$(AVBTOOL) \
-		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(INSTALLED_SYSTEMIMAGE_TARGET) \
-		$(INSTALLED_VENDORIMAGE_TARGET) \
-		$(INSTALLED_PRODUCTIMAGE_TARGET) \
-		$(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
-		$(INSTALLED_ODMIMAGE_TARGET) \
-		$(INSTALLED_DTBOIMAGE_TARGET) \
-		$(INSTALLED_RECOVERYIMAGE_TARGET) \
-		$(INSTALLED_VBMETA_SYSTEMIMAGE_TARGET) \
-		$(INSTALLED_VBMETA_VENDORIMAGE_TARGET) \
-		$(BOARD_AVB_VBMETA_SYSTEM_KEY_PATH) \
-		$(BOARD_AVB_VBMETA_VENDOR_KEY_PATH) \
-		$(BOARD_AVB_KEY_PATH)
+	    $(AVBTOOL) \
+	    $(INSTALLED_BOOTIMAGE_TARGET) \
+	    $(INSTALLED_SYSTEMIMAGE_TARGET) \
+	    $(INSTALLED_VENDORIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCTIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
+	    $(INSTALLED_ODMIMAGE_TARGET) \
+	    $(INSTALLED_DTBOIMAGE_TARGET) \
+	    $(INSTALLED_RECOVERYIMAGE_TARGET) \
+	    $(INSTALLED_VBMETA_SYSTEMIMAGE_TARGET) \
+	    $(INSTALLED_VBMETA_VENDORIMAGE_TARGET) \
+	    $(BOARD_AVB_VBMETA_SYSTEM_KEY_PATH) \
+	    $(BOARD_AVB_VBMETA_VENDOR_KEY_PATH) \
+	    $(BOARD_AVB_KEY_PATH)
 	$(build-vbmetaimage-target)
 
 .PHONY: vbmetaimage-nodeps
@@ -2906,75 +3069,6 @@
 endif # BOARD_AVB_ENABLE
 
 # -----------------------------------------------------------------
-# super partition image
-
-# (1): list of items like "system", "vendor", "product", "product_services"
-# return: map each item into a command ( wrapped in $$() ) that reads the size
-define read-size-of-partitions
-$(foreach p,$(1),$(call read-image-prop-dictionary,$($(p)image_intermediates)/generated_$(p)_image_info.txt,$(p)_size))
-endef
-
-ifeq (true,$(PRODUCT_BUILD_SUPER_PARTITION))
-
-# BOARD_SUPER_PARTITION_SIZE must be defined to build super image.
-ifneq ($(BOARD_SUPER_PARTITION_SIZE),)
-
-INSTALLED_SUPERIMAGE_TARGET := $(PRODUCT_OUT)/super.img
-INSTALLED_SUPERIMAGE_EMPTY_TARGET := $(PRODUCT_OUT)/super_empty.img
-
-$(INSTALLED_SUPERIMAGE_TARGET): $(call images-for-partitions,$(BOARD_SUPER_PARTITION_PARTITION_LIST))
-
-# For A/B devices, super partition always contains sub-partitions in the _a slot, because this
-# image should only be used for bootstrapping / initializing the device. When flashing the image,
-# bootloader fastboot should always mark _a slot as bootable.
-ifeq ($(AB_OTA_UPDATER),true)
-$(INSTALLED_SUPERIMAGE_TARGET) $(INSTALLED_SUPERIMAGE_EMPTY_TARGET): PRIVATE_PARTITION_SUFFIX=_a
-endif # AB_OTA_UPDATER
-
-$(INSTALLED_SUPERIMAGE_TARGET) $(INSTALLED_SUPERIMAGE_EMPTY_TARGET): $(LPMAKE)
-
-# $(1): slot A suffix (_a or empty)
-# $(2): include images or not (true or empty)
-define build-superimage-target-args
-  $(if $(2), --sparse) \
-  --metadata-size 65536 \
-  --metadata-slots $(if $(1),2,1) \
-  --device-size $(BOARD_SUPER_PARTITION_SIZE) \
-  $(foreach group,$(BOARD_SUPER_PARTITION_GROUPS), \
-    --group $(group)$(1):$(BOARD_$(call to-upper,$(group))_SIZE) \
-    $(if $(1), --group $(group)_b:$(BOARD_$(call to-upper,$(group))_SIZE)) \
-    $(foreach name,$(BOARD_$(call to-upper,$(group))_PARTITION_LIST), \
-      --partition $(name)$(1):readonly:$(if $(2),$(call read-size-of-partitions,$(name)),0):$(group)$(1) \
-      $(if $(2), --image $(name)$(1)=$(call images-for-partitions,$(name))) \
-      $(if $(1), --partition $(name)_b:readonly:0:$(group)_b) \
-  ))
-endef
-
-# $(1): output image path
-# $(2): slot A suffix (_a or empty)
-# $(3): include images or not (true or empty)
-define build-superimage-target
-  $(LPMAKE) \
-    $(call build-superimage-target-args,$(2),$(3)) \
-    --output $(1)
-endef
-
-$(INSTALLED_SUPERIMAGE_TARGET):
-	$(call pretty,"Target super fs image: $@")
-	$(call build-superimage-target,$@,$(PRIVATE_PARTITION_SUFFIX),true)
-
-$(call dist-for-goals,dist_files,$(INSTALLED_SUPERIMAGE_TARGET))
-
-$(INSTALLED_SUPERIMAGE_EMPTY_TARGET):
-	$(call pretty,"Target empty super fs image: $@")
-	$(call build-superimage-target,$@,$(PRIVATE_PARTITION_SUFFIX))
-
-$(call dist-for-goals,dist_files,$(INSTALLED_SUPERIMAGE_EMPTY_TARGET))
-
-endif # BOARD_SUPER_PARTITION_SIZE
-endif # PRODUCT_BUILD_SUPER_PARTITION
-
-# -----------------------------------------------------------------
 # Check image sizes <= size of super partition
 
 ifeq (,$(TARGET_BUILD_APPS))
@@ -2982,6 +3076,16 @@
 
 ifeq (true,$(PRODUCT_BUILD_SUPER_PARTITION))
 
+# (1): list of items like "system", "vendor", "product", "product_services"
+# return: map each item into a command ( wrapped in $$() ) that reads the size
+define read-size-of-partitions
+$(foreach p,$(1),$(call read-image-prop-dictionary,$($(p)image_intermediates)/generated_$(p)_image_info.txt,$(p)_size))
+endef
+
+define super-slot-suffix
+$(if $(filter true,$(AB_OTA_UPDATER)),$(if $(filter true,$(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS)),,_a))
+endef
+
 droid_targets: check-all-partition-sizes
 
 .PHONY: check-all-partition-sizes check-all-partition-sizes-nodeps
@@ -2989,6 +3093,24 @@
 # Add image dependencies so that generated_*_image_info.txt are written before checking.
 check-all-partition-sizes: $(call images-for-partitions,$(BOARD_SUPER_PARTITION_PARTITION_LIST))
 
+ifeq ($(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS),true)
+# Check sum(super partition block devices) == super partition
+# Non-retrofit devices already defines BOARD_SUPER_PARTITION_SUPER_DEVICE_SIZE = BOARD_SUPER_PARTITION_SIZE
+define check-super-partition-size
+  size_list="$(foreach device,$(call to-upper,$(BOARD_SUPER_PARTITION_BLOCK_DEVICES)),$(BOARD_SUPER_PARTITION_$(device)_DEVICE_SIZE))"; \
+  sum_sizes_expr=$$(sed -e 's/ /+/g' <<< "$${size_list}"); \
+  max_size_expr="$(BOARD_SUPER_PARTITION_SIZE)"; \
+  if [ $$(( $${sum_sizes_expr} )) -ne $$(( $${max_size_expr} )) ]; then \
+    echo "The sum of super partition block device sizes is not equal to BOARD_SUPER_PARTITION_SIZE:"; \
+    echo $${sum_sizes_expr} '!=' $${max_size_expr}; \
+    exit 1; \
+  else \
+    echo "The sum of super partition block device sizes is equal to BOARD_SUPER_PARTITION_SIZE:"; \
+    echo $${sum_sizes_expr} '==' $${max_size_expr}; \
+  fi
+endef
+endif
+
 # $(1): human-readable max size string
 # $(2): max size expression
 # $(3): list of partition names
@@ -3002,25 +3124,25 @@
   else \
     echo "The sum of sizes of [$(strip $(3))] is within $(strip $(1)):"; \
     echo $${sum_sizes_expr} '==' $$(( $${sum_sizes_expr} )) '<=' "$(2)" '==' $$(( $(2) )); \
-  fi
+  fi;
 endef
 
 define check-all-partition-sizes-target
-  # Check sum(all partitions) <= super partition (/ 2 for A/B)
+  # Check sum(all partitions) <= super partition (/ 2 for A/B devices launched with dynamic partitions)
   $(if $(BOARD_SUPER_PARTITION_SIZE),$(if $(BOARD_SUPER_PARTITION_PARTITION_LIST), \
-    $(call check-sum-of-partition-sizes,BOARD_SUPER_PARTITION_SIZE$(if $(filter true,$(AB_OTA_UPDATER)), / 2), \
-      $(BOARD_SUPER_PARTITION_SIZE)$(if $(filter true,$(AB_OTA_UPDATER)), / 2),$(BOARD_SUPER_PARTITION_PARTITION_LIST))))
+    $(call check-sum-of-partition-sizes,BOARD_SUPER_PARTITION_SIZE$(if $(call super-slot-suffix), / 2), \
+      $(BOARD_SUPER_PARTITION_SIZE)$(if $(call super-slot-suffix), / 2),$(BOARD_SUPER_PARTITION_PARTITION_LIST))))
 
   # For each group, check sum(partitions in group) <= group size
   $(foreach group,$(call to-upper,$(BOARD_SUPER_PARTITION_GROUPS)), \
     $(if $(BOARD_$(group)_SIZE),$(if $(BOARD_$(group)_PARTITION_LIST), \
       $(call check-sum-of-partition-sizes,BOARD_$(group)_SIZE,$(BOARD_$(group)_SIZE),$(BOARD_$(group)_PARTITION_LIST)))))
 
-  # Check sum(all group sizes) <= super partition (/ 2 for A/B)
+  # Check sum(all group sizes) <= super partition (/ 2 for A/B devices launched with dynamic partitions)
   if [[ ! -z $(BOARD_SUPER_PARTITION_SIZE) ]]; then \
     group_size_list="$(foreach group,$(call to-upper,$(BOARD_SUPER_PARTITION_GROUPS)),$(BOARD_$(group)_SIZE))"; \
     sum_sizes_expr=$$(sed -e 's/ /+/g' <<< "$${group_size_list}"); \
-    max_size_tail=$(if $(filter true,$(AB_OTA_UPDATER))," / 2"); \
+    max_size_tail=$(if $(call super-slot-suffix)," / 2"); \
     max_size_expr="$(BOARD_SUPER_PARTITION_SIZE)$${max_size_tail}"; \
     if [ $$(( $${sum_sizes_expr} )) -gt $$(( $${max_size_expr} )) ]; then \
       echo "The sum of sizes of [$(strip $(BOARD_SUPER_PARTITION_GROUPS))] is larger than BOARD_SUPER_PARTITION_SIZE$${max_size_tail}:"; \
@@ -3035,6 +3157,7 @@
 
 check-all-partition-sizes check-all-partition-sizes-nodeps:
 	$(call check-all-partition-sizes-target)
+	$(call check-super-partition-size)
 
 endif # PRODUCT_BUILD_SUPER_PARTITION
 
@@ -3058,7 +3181,7 @@
   ifeq ($(TARGET_SKIP_OTA_PACKAGE),true)
     build_ota_package := false
   endif
-  ifneq ($(strip $(SANITIZE_TARGET)),)
+  ifneq (,$(filter address, $(SANITIZE_TARGET)))
     build_ota_package := false
   endif
   ifeq ($(TARGET_PRODUCT),sdk)
@@ -3162,7 +3285,9 @@
   $(HOST_LIBRARY_PATH)/libpcre2$(HOST_SHLIB_SUFFIX) \
   $(HOST_LIBRARY_PATH)/libbrotli$(HOST_SHLIB_SUFFIX) \
   $(HOST_LIBRARY_PATH)/liblp$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext4_utils$(HOST_SHLIB_SUFFIX)
+  $(HOST_LIBRARY_PATH)/libext4_utils$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libfec$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libsquashfs_utils$(HOST_SHLIB_SUFFIX)
 
 
 .PHONY: otatools
@@ -3229,7 +3354,7 @@
 BUILT_TARGET_FILES_PACKAGE := $(intermediates)/$(name).zip
 $(BUILT_TARGET_FILES_PACKAGE): intermediates := $(intermediates)
 $(BUILT_TARGET_FILES_PACKAGE): \
-		zip_root := $(intermediates)/$(name)
+	    zip_root := $(intermediates)/$(name)
 
 # $(1): Directory to copy
 # $(2): Location to copy it to
@@ -3244,7 +3369,7 @@
 built_ota_tools :=
 
 # We can't build static executables when SANITIZE_TARGET=address
-ifeq ($(strip $(SANITIZE_TARGET)),)
+ifeq (,$(filter address, $(SANITIZE_TARGET)))
 built_ota_tools += \
     $(call intermediates-dir-for,EXECUTABLES,updater,,,$(TARGET_PREFER_32_BIT))/updater
 endif
@@ -3294,46 +3419,73 @@
 (cd $(1); find . -type d | sed 's,$$,/,'; find . \! -type d) | cut -c 3- | sort | sed 's,^,$(2),' | $(HOST_OUT_EXECUTABLES)/fs_config -C -D $(TARGET_OUT) -S $(SELINUX_FC) -R "$(2)"
 endef
 
+# $(1): file
+define dump-dynamic-partitions-info
+  $(if $(filter true,$(PRODUCT_USE_DYNAMIC_PARTITIONS)), \
+    echo "use_dynamic_partitions=true" >> $(1))
+  $(if $(filter true,$(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS)), \
+    echo "dynamic_partition_retrofit=true" >> $(1))
+  echo "lpmake=$(notdir $(LPMAKE))" >> $(1)
+  $(if $(filter true,$(PRODUCT_BUILD_SUPER_PARTITION)), $(if $(BOARD_SUPER_PARTITION_SIZE), \
+    echo "build_super_partition=true" >> $(1)))
+  $(if $(filter true,$(BOARD_BUILD_RETROFIT_DYNAMIC_PARTITIONS_OTA_PACKAGE)), \
+    echo "build_retrofit_dynamic_partitions_ota_package=true" >> $(1))
+  echo "super_metadata_device=$(BOARD_SUPER_PARTITION_METADATA_DEVICE)" >> $(1)
+  $(if $(BOARD_SUPER_PARTITION_BLOCK_DEVICES), \
+    echo "super_block_devices=$(BOARD_SUPER_PARTITION_BLOCK_DEVICES)" >> $(1))
+  $(foreach device,$(BOARD_SUPER_PARTITION_BLOCK_DEVICES), \
+    echo "super_$(device)_device_size=$(BOARD_SUPER_PARTITION_$(call to-upper,$(device))_DEVICE_SIZE)" >> $(1);)
+  $(if $(BOARD_SUPER_PARTITION_PARTITION_LIST), \
+    echo "dynamic_partition_list=$(BOARD_SUPER_PARTITION_PARTITION_LIST)" >> $(1))
+  $(if $(BOARD_SUPER_PARTITION_GROUPS),
+    echo "super_partition_groups=$(BOARD_SUPER_PARTITION_GROUPS)" >> $(1))
+  $(foreach group,$(BOARD_SUPER_PARTITION_GROUPS), \
+    echo "super_$(group)_group_size=$(BOARD_$(call to-upper,$(group))_SIZE)" >> $(1); \
+    $(if $(BOARD_$(call to-upper,$(group))_PARTITION_LIST), \
+      echo "super_$(group)_partition_list=$(BOARD_$(call to-upper,$(group))_PARTITION_LIST)" >> $(1);))
+endef
+
 # Depending on the various images guarantees that the underlying
 # directories are up-to-date.
 $(BUILT_TARGET_FILES_PACKAGE): \
-		$(INSTALLED_RAMDISK_TARGET) \
-		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(INSTALLED_RADIOIMAGE_TARGET) \
-		$(INSTALLED_RECOVERYIMAGE_TARGET) \
-		$(FULL_SYSTEMIMAGE_DEPS) \
-		$(INSTALLED_USERDATAIMAGE_TARGET) \
-		$(INSTALLED_CACHEIMAGE_TARGET) \
-		$(INSTALLED_VENDORIMAGE_TARGET) \
-		$(INSTALLED_PRODUCTIMAGE_TARGET) \
-		$(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
-		$(INSTALLED_VBMETAIMAGE_TARGET) \
-		$(INSTALLED_ODMIMAGE_TARGET) \
-		$(INSTALLED_DTBOIMAGE_TARGET) \
-		$(INTERNAL_SYSTEMOTHERIMAGE_FILES) \
-		$(INSTALLED_ANDROID_INFO_TXT_TARGET) \
-		$(INSTALLED_KERNEL_TARGET) \
-		$(INSTALLED_2NDBOOTLOADER_TARGET) \
-		$(BOARD_PREBUILT_DTBOIMAGE) \
-		$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH) \
-		$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH) \
-		$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH) \
-		$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_SERVICES_BASE_FS_PATH) \
-		$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ODM_BASE_FS_PATH) \
-		$(LPMAKE) \
-		$(SELINUX_FC) \
-		$(APKCERTS_FILE) \
-		$(SOONG_ZIP) \
-		$(HOST_OUT_EXECUTABLES)/fs_config \
-		$(HOST_OUT_EXECUTABLES)/imgdiff \
-		$(HOST_OUT_EXECUTABLES)/bsdiff \
-		$(HOST_OUT_EXECUTABLES)/care_map_generator \
-		$(BUILD_IMAGE_SRCS) \
-		$(BUILT_ASSEMBLED_SYSTEM_MANIFEST) \
-		$(BUILT_ASSEMBLED_VENDOR_MANIFEST) \
-		$(BUILT_SYSTEM_MATRIX) \
-		$(BUILT_VENDOR_MATRIX) \
-		| $(ACP)
+	    $(INSTALLED_RAMDISK_TARGET) \
+	    $(INSTALLED_BOOTIMAGE_TARGET) \
+	    $(INSTALLED_RADIOIMAGE_TARGET) \
+	    $(INSTALLED_RECOVERYIMAGE_TARGET) \
+	    $(FULL_SYSTEMIMAGE_DEPS) \
+	    $(INSTALLED_USERDATAIMAGE_TARGET) \
+	    $(INSTALLED_CACHEIMAGE_TARGET) \
+	    $(INSTALLED_VENDORIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCTIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
+	    $(INSTALLED_VBMETAIMAGE_TARGET) \
+	    $(INSTALLED_ODMIMAGE_TARGET) \
+	    $(INSTALLED_DTBOIMAGE_TARGET) \
+	    $(INTERNAL_SYSTEMOTHERIMAGE_FILES) \
+	    $(INSTALLED_ANDROID_INFO_TXT_TARGET) \
+	    $(INSTALLED_KERNEL_TARGET) \
+	    $(INSTALLED_2NDBOOTLOADER_TARGET) \
+	    $(BOARD_PREBUILT_DTBOIMAGE) \
+	    $(BOARD_RECOVERY_ACPIO) \
+	    $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH) \
+	    $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH) \
+	    $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH) \
+	    $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_SERVICES_BASE_FS_PATH) \
+	    $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ODM_BASE_FS_PATH) \
+	    $(LPMAKE) \
+	    $(SELINUX_FC) \
+	    $(APKCERTS_FILE) \
+	    $(SOONG_ZIP) \
+	    $(HOST_OUT_EXECUTABLES)/fs_config \
+	    $(HOST_OUT_EXECUTABLES)/imgdiff \
+	    $(HOST_OUT_EXECUTABLES)/bsdiff \
+	    $(HOST_OUT_EXECUTABLES)/care_map_generator \
+	    $(BUILD_IMAGE_SRCS) \
+	    $(BUILT_ASSEMBLED_SYSTEM_MANIFEST) \
+	    $(BUILT_ASSEMBLED_VENDOR_MANIFEST) \
+	    $(BUILT_SYSTEM_MATRIX) \
+	    $(BUILT_VENDOR_MATRIX) \
+	    | $(ACP)
 	@echo "Package target files: $@"
 	$(call create-system-vendor-symlink)
 	$(call create-system-product-symlink)
@@ -3345,7 +3497,7 @@
 	@# Components of the recovery image
 	$(hide) mkdir -p $(zip_root)/$(PRIVATE_RECOVERY_OUT)
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_RECOVERY_ROOT_OUT),$(zip_root)/$(PRIVATE_RECOVERY_OUT)/RAMDISK)
+	    $(TARGET_RECOVERY_ROOT_OUT),$(zip_root)/$(PRIVATE_RECOVERY_OUT)/RAMDISK)
 ifdef INSTALLED_KERNEL_TARGET
 	$(hide) cp $(INSTALLED_KERNEL_TARGET) $(zip_root)/$(PRIVATE_RECOVERY_OUT)/kernel
 endif
@@ -3355,6 +3507,9 @@
 ifdef BOARD_INCLUDE_RECOVERY_DTBO
 	$(hide) cp $(BOARD_PREBUILT_DTBOIMAGE) $(zip_root)/$(PRIVATE_RECOVERY_OUT)/recovery_dtbo
 endif
+ifdef BOARD_INCLUDE_RECOVERY_ACPIO
+	$(hide) cp $(BOARD_RECOVERY_ACPIO) $(zip_root)/$(PRIVATE_RECOVERY_OUT)/recovery_acpio
+endif
 ifdef INTERNAL_KERNEL_CMDLINE
 	$(hide) echo "$(INTERNAL_KERNEL_CMDLINE)" > $(zip_root)/$(PRIVATE_RECOVERY_OUT)/cmdline
 endif
@@ -3369,13 +3524,13 @@
 	$(hide) mkdir -p $(zip_root)/BOOT
 	$(hide) mkdir -p $(zip_root)/ROOT
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_ROOT_OUT),$(zip_root)/ROOT)
-ifneq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true)
-	$(hide) $(call package_files-copy-root, \
-		$(TARGET_RAMDISK_OUT),$(zip_root)/BOOT/RAMDISK)
-endif
+	    $(TARGET_ROOT_OUT),$(zip_root)/ROOT)
 	@# If we are using recovery as boot, this is already done when processing recovery.
 ifneq ($(BOARD_USES_RECOVERY_AS_BOOT),true)
+ifneq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true)
+	$(hide) $(call package_files-copy-root, \
+	    $(TARGET_RAMDISK_OUT),$(zip_root)/BOOT/RAMDISK)
+endif
 ifdef INSTALLED_KERNEL_TARGET
 	$(hide) cp $(INSTALLED_KERNEL_TARGET) $(zip_root)/BOOT/kernel
 endif
@@ -3397,34 +3552,34 @@
 	            cp $(t) $(zip_root)/RADIO/$(notdir $(t));)
 	@# Contents of the system image
 	$(hide) $(call package_files-copy-root, \
-		$(SYSTEMIMAGE_SOURCE_DIR),$(zip_root)/SYSTEM)
+	    $(SYSTEMIMAGE_SOURCE_DIR),$(zip_root)/SYSTEM)
 	@# Contents of the data image
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_OUT_DATA),$(zip_root)/DATA)
+	    $(TARGET_OUT_DATA),$(zip_root)/DATA)
 ifdef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE
 	@# Contents of the vendor image
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_OUT_VENDOR),$(zip_root)/VENDOR)
+	    $(TARGET_OUT_VENDOR),$(zip_root)/VENDOR)
 endif
 ifdef BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE
 	@# Contents of the product image
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_OUT_PRODUCT),$(zip_root)/PRODUCT)
+	    $(TARGET_OUT_PRODUCT),$(zip_root)/PRODUCT)
 endif
 ifdef BOARD_PRODUCT_SERVICESIMAGE_FILE_SYSTEM_TYPE
 	@# Contents of the product_services image
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_OUT_PRODUCT_SERVICES),$(zip_root)/PRODUCT_SERVICES)
+	    $(TARGET_OUT_PRODUCT_SERVICES),$(zip_root)/PRODUCT_SERVICES)
 endif
 ifdef BOARD_ODMIMAGE_FILE_SYSTEM_TYPE
 	@# Contents of the odm image
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_OUT_ODM),$(zip_root)/ODM)
+	    $(TARGET_OUT_ODM),$(zip_root)/ODM)
 endif
 ifdef INSTALLED_SYSTEMOTHERIMAGE_TARGET
 	@# Contents of the system_other image
 	$(hide) $(call package_files-copy-root, \
-		$(TARGET_OUT_SYSTEM_OTHER),$(zip_root)/SYSTEM_OTHER)
+	    $(TARGET_OUT_SYSTEM_OTHER),$(zip_root)/SYSTEM_OTHER)
 endif
 	@# Extra contents of the OTA package
 	$(hide) mkdir -p $(zip_root)/OTA
@@ -3458,6 +3613,9 @@
 ifdef BOARD_INCLUDE_RECOVERY_DTBO
 	$(hide) echo "include_recovery_dtbo=true" >> $(zip_root)/META/misc_info.txt
 endif
+ifdef BOARD_INCLUDE_RECOVERY_ACPIO
+	$(hide) echo "include_recovery_acpio=true" >> $(zip_root)/META/misc_info.txt
+endif
 ifdef BOARD_RECOVERYIMAGE_PARTITION_SIZE
 	$(hide) echo "recovery_size=$(BOARD_RECOVERYIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt
 endif
@@ -3609,6 +3767,7 @@
 endif # BOARD_AVB_DTBO_KEY_PATH
 endif # BOARD_AVB_ENABLE
 endif # BOARD_PREBUILT_DTBOIMAGE
+	$(call dump-dynamic-partitions-info,$(zip_root)/META/misc_info.txt)
 	@# The radio images in BOARD_PACK_RADIOIMAGES will be additionally copied from RADIO/ into
 	@# IMAGES/, which then will be added into <product>-img.zip. Such images must be listed in
 	@# INSTALLED_RADIOIMAGE_TARGET.
@@ -3654,21 +3813,18 @@
 ifdef BUILT_VENDOR_MATRIX
 	$(hide) cp $(BUILT_VENDOR_MATRIX) $(zip_root)/META/vendor_matrix.xml
 endif
-ifneq ($(BOARD_SUPER_PARTITION_SIZE),)
-	$(hide) echo "super_size=$(BOARD_SUPER_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt
-	$(hide) echo "lpmake=$(notdir $(LPMAKE))" >> $(zip_root)/META/misc_info.txt
-	$(hide) echo -n "lpmake_args=" >> $(zip_root)/META/misc_info.txt
-	$(hide) echo $(call build-superimage-target-args,$(if $(filter true,$(AB_OTA_UPDATER)),_a,)) \
-	    >> $(zip_root)/META/misc_info.txt
-endif
 ifneq ($(BOARD_SUPER_PARTITION_GROUPS),)
 	$(hide) echo "super_partition_groups=$(BOARD_SUPER_PARTITION_GROUPS)" > $(zip_root)/META/dynamic_partitions_info.txt
+	@# Remove 'vendor' from the group partition list if the image is not available. This should only
+	@# happen to AOSP targets built without vendor.img. We can't remove the partition from the
+	@# BoardConfig file, as it's still needed elsewhere (e.g. when creating super_empty.img).
 	$(foreach group,$(BOARD_SUPER_PARTITION_GROUPS), \
+	    $(eval _group_partition_list := $(BOARD_$(call to-upper,$(group))_PARTITION_LIST)) \
+	    $(if $(INSTALLED_VENDORIMAGE_TARGET),,$(eval _group_partition_list := $(filter-out vendor,$(_group_partition_list)))) \
 	    echo "$(group)_size=$(BOARD_$(call to-upper,$(group))_SIZE)" >> $(zip_root)/META/dynamic_partitions_info.txt; \
-	    $(if $(BOARD_$(call to-upper,$(group))_PARTITION_LIST), \
-	        echo "$(group)_partition_list=$(BOARD_$(call to-upper,$(group))_PARTITION_LIST)" >> $(zip_root)/META/dynamic_partitions_info.txt;))
-endif
-
+	    $(if $(_group_partition_list), \
+	        echo "$(group)_partition_list=$(_group_partition_list)" >> $(zip_root)/META/dynamic_partitions_info.txt;))
+endif # BOARD_SUPER_PARTITION_GROUPS
 	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \
 	    build/make/tools/releasetools/add_img_to_target_files -a -v -p $(HOST_OUT) $(zip_root)
 	@# Zip everything up, preserving symlinks and placing META/ files first to
@@ -3697,6 +3853,19 @@
 # -----------------------------------------------------------------
 # OTA update package
 
+# $(1): output file
+# $(2): additional args
+define build-ota-package-target
+PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \
+   build/make/tools/releasetools/ota_from_target_files -v \
+   --block \
+   --extracted_input_target_files $(patsubst %.zip,%,$(BUILT_TARGET_FILES_PACKAGE)) \
+   -p $(HOST_OUT) \
+   $(if $(OEM_OTA_CONFIG), -o $(OEM_OTA_CONFIG)) \
+   $(2) \
+   $(BUILT_TARGET_FILES_PACKAGE) $(1)
+endef
+
 name := $(TARGET_PRODUCT)
 ifeq ($(TARGET_BUILD_TYPE),debug)
   name := $(name)_debug
@@ -3714,20 +3883,41 @@
 endif
 
 $(INTERNAL_OTA_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) \
-		build/make/tools/releasetools/ota_from_target_files
+	    build/make/tools/releasetools/ota_from_target_files
 	@echo "Package OTA: $@"
-	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \
-	   build/make/tools/releasetools/ota_from_target_files -v \
-	   --block \
-	   --extracted_input_target_files $(patsubst %.zip,%,$(BUILT_TARGET_FILES_PACKAGE)) \
-	   -p $(HOST_OUT) \
-	   -k $(KEY_CERT_PAIR) \
-	   $(if $(OEM_OTA_CONFIG), -o $(OEM_OTA_CONFIG)) \
-	   $(BUILT_TARGET_FILES_PACKAGE) $@
+	$(call build-ota-package-target,$@,-k $(KEY_CERT_PAIR))
 
 .PHONY: otapackage
 otapackage: $(INTERNAL_OTA_PACKAGE_TARGET)
 
+ifeq ($(BOARD_BUILD_RETROFIT_DYNAMIC_PARTITIONS_OTA_PACKAGE),true)
+name := $(TARGET_PRODUCT)
+ifeq ($(TARGET_BUILD_TYPE),debug)
+  name := $(name)_debug
+endif
+name := $(name)-ota-retrofit-$(FILE_NAME_TAG)
+
+INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET := $(PRODUCT_OUT)/$(name).zip
+
+$(INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET): KEY_CERT_PAIR := $(DEFAULT_KEY_CERT_PAIR)
+
+ifeq ($(AB_OTA_UPDATER),true)
+$(INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET): $(BRILLO_UPDATE_PAYLOAD)
+else
+$(INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET): $(BROTLI)
+endif
+
+$(INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) \
+	    build/make/tools/releasetools/ota_from_target_files
+	@echo "Package OTA (retrofit dynamic partitions): $@"
+	$(call build-ota-package-target,$@,-k $(KEY_CERT_PAIR) --retrofit_dynamic_partitions)
+
+.PHONY: otardppackage
+
+otapackage otardppackage: $(INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET)
+
+endif # BOARD_BUILD_RETROFIT_DYNAMIC_PARTITIONS_OTA_PACKAGE
+
 endif    # build_ota_package
 
 # -----------------------------------------------------------------
@@ -3755,12 +3945,12 @@
 # For apps_only build we'll establish the dependency later in build/make/core/main.mk.
 ifndef TARGET_BUILD_APPS
 $(APPCOMPAT_ZIP): $(INSTALLED_SYSTEMIMAGE_TARGET) \
-		$(INSTALLED_RAMDISK_TARGET) \
-		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(INSTALLED_USERDATAIMAGE_TARGET) \
-		$(INSTALLED_VENDORIMAGE_TARGET) \
-		$(INSTALLED_PRODUCTIMAGE_TARGET) \
-		$(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET)
+	    $(INSTALLED_RAMDISK_TARGET) \
+	    $(INSTALLED_BOOTIMAGE_TARGET) \
+	    $(INSTALLED_USERDATAIMAGE_TARGET) \
+	    $(INSTALLED_VENDORIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCTIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET)
 endif
 $(APPCOMPAT_ZIP): PRIVATE_LIST_FILE := $(call intermediates-dir-for,PACKAGING,appcompat)/filelist
 $(APPCOMPAT_ZIP): $(SOONG_ZIP)
@@ -3785,14 +3975,14 @@
 # For apps_only build we'll establish the dependency later in build/make/core/main.mk.
 ifndef TARGET_BUILD_APPS
 $(SYMBOLS_ZIP): $(INSTALLED_SYSTEMIMAGE_TARGET) \
-		$(INSTALLED_RAMDISK_TARGET) \
-		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(INSTALLED_USERDATAIMAGE_TARGET) \
-		$(INSTALLED_VENDORIMAGE_TARGET) \
-		$(INSTALLED_PRODUCTIMAGE_TARGET) \
-		$(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
-		$(INSTALLED_ODMIMAGE_TARGET) \
-		$(updater_dep)
+	    $(INSTALLED_RAMDISK_TARGET) \
+	    $(INSTALLED_BOOTIMAGE_TARGET) \
+	    $(INSTALLED_USERDATAIMAGE_TARGET) \
+	    $(INSTALLED_VENDORIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCTIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
+	    $(INSTALLED_ODMIMAGE_TARGET) \
+	    $(updater_dep)
 endif
 $(SYMBOLS_ZIP): PRIVATE_LIST_FILE := $(call intermediates-dir-for,PACKAGING,symbols)/filelist
 $(SYMBOLS_ZIP): $(SOONG_ZIP)
@@ -3812,13 +4002,13 @@
 COVERAGE_ZIP := $(PRODUCT_OUT)/$(name).zip
 ifndef TARGET_BUILD_APPS
 $(COVERAGE_ZIP): $(INSTALLED_SYSTEMIMAGE_TARGET) \
-		$(INSTALLED_RAMDISK_TARGET) \
-		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(INSTALLED_USERDATAIMAGE_TARGET) \
-		$(INSTALLED_VENDORIMAGE_TARGET) \
-		$(INSTALLED_PRODUCTIMAGE_TARGET) \
-		$(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
-		$(INSTALLED_ODMIMAGE_TARGET)
+	    $(INSTALLED_RAMDISK_TARGET) \
+	    $(INSTALLED_BOOTIMAGE_TARGET) \
+	    $(INSTALLED_USERDATAIMAGE_TARGET) \
+	    $(INSTALLED_VENDORIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCTIMAGE_TARGET) \
+	    $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) \
+	    $(INSTALLED_ODMIMAGE_TARGET)
 endif
 $(COVERAGE_ZIP): PRIVATE_LIST_FILE := $(call intermediates-dir-for,PACKAGING,coverage)/filelist
 $(COVERAGE_ZIP): $(SOONG_ZIP)
@@ -3845,10 +4035,10 @@
 	$(hide) mkdir -p $(dir $@)
 	$(hide) apps_to_zip=`find $(TARGET_OUT_APPS) $(TARGET_OUT_APPS_PRIVILEGED) -mindepth 2 -maxdepth 3 -name "*.apk"`; \
 	if [ -z "$$apps_to_zip" ]; then \
-		echo "No apps to zip up. Generating empty apps archive." ; \
-		a=$$(mktemp /tmp/XXXXXXX) && touch $$a && zip $@ $$a && zip -d $@ $$a; \
+	    echo "No apps to zip up. Generating empty apps archive." ; \
+	    a=$$(mktemp /tmp/XXXXXXX) && touch $$a && zip $@ $$a && zip -d $@ $$a; \
 	else \
-		zip -qjX $@ $$apps_to_zip; \
+	    zip -qjX $@ $$apps_to_zip; \
 	fi
 
 ifeq (true,$(EMMA_INSTRUMENT))
@@ -3862,7 +4052,7 @@
 $(JACOCO_REPORT_CLASSES_ALL) :
 	@echo "Collecting uninstrumented classes"
 	$(hide) find $(TARGET_COMMON_OUT_ROOT) $(HOST_COMMON_OUT_ROOT) -name "jacoco-report-classes.jar" | \
-		zip -@ -0 -q -X $@
+	    zip -@ -0 -q -X $@
 # Meaning of these options:
 # -@ scan stdin for file paths to add to the zip
 # -0 don't do any compression
@@ -3882,19 +4072,56 @@
 $(PROGUARD_DICT_ZIP) :
 	@echo "Packaging Proguard obfuscation dictionary files."
 	$(hide) dict_files=`find $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS -name proguard_dictionary`; \
-		if [ -n "$$dict_files" ]; then \
-		  unobfuscated_jars=$${dict_files//proguard_dictionary/classes.jar}; \
-		  zip -qX $@ $$dict_files $$unobfuscated_jars; \
-		else \
-		  touch $(dir $@)/zipdummy; \
-		  (cd $(dir $@) && zip -q $(notdir $@) zipdummy); \
-		  zip -qd $@ zipdummy; \
-		  rm $(dir $@)/zipdummy; \
-		fi
+	    if [ -n "$$dict_files" ]; then \
+	      unobfuscated_jars=$${dict_files//proguard_dictionary/classes.jar}; \
+	      zip -qX $@ $$dict_files $$unobfuscated_jars; \
+	    else \
+	      touch $(dir $@)/zipdummy; \
+	      (cd $(dir $@) && zip -q $(notdir $@) zipdummy); \
+	      zip -qd $@ zipdummy; \
+	      rm $(dir $@)/zipdummy; \
+	    fi
 
 endif # TARGET_BUILD_APPS
 
 # -----------------------------------------------------------------
+# super partition image
+
+ifeq (true,$(PRODUCT_BUILD_SUPER_PARTITION))
+
+# BOARD_SUPER_PARTITION_SIZE must be defined to build super image.
+ifneq ($(BOARD_SUPER_PARTITION_SIZE),)
+
+ifneq (true,$(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS))
+INSTALLED_SUPERIMAGE_TARGET := $(PRODUCT_OUT)/super.img
+$(INSTALLED_SUPERIMAGE_TARGET): extracted_input_target_files := $(patsubst %.zip,%,$(BUILT_TARGET_FILES_PACKAGE))
+$(INSTALLED_SUPERIMAGE_TARGET): $(LPMAKE) $(BUILT_TARGET_FILES_PACKAGE) $(BUILD_SUPER_IMAGE)
+	$(call pretty,"Target super fs image: $@")
+	PATH=$(dir $(LPMAKE)):$$PATH \
+	    $(BUILD_SUPER_IMAGE) -v $(extracted_input_target_files) $@
+endif
+
+$(call dist-for-goals,dist_files,$(INSTALLED_SUPERIMAGE_TARGET))
+
+INSTALLED_SUPERIMAGE_EMPTY_TARGET := $(PRODUCT_OUT)/super_empty.img
+$(INSTALLED_SUPERIMAGE_EMPTY_TARGET): intermediates := $(call intermediates-dir-for,PACKAGING,super_empty)
+$(INSTALLED_SUPERIMAGE_EMPTY_TARGET): $(LPMAKE) $(BUILD_SUPER_IMAGE)
+	$(call pretty,"Target empty super fs image: $@")
+	mkdir -p $(intermediates)
+	rm -rf $(intermediates)/misc_info.txt
+	$(call dump-dynamic-partitions-info,$(intermediates)/misc_info.txt)
+ifeq ($(AB_OTA_UPDATER),true)
+	echo "ab_update=true" >> $(intermediates)/misc_info.txt
+endif
+	PATH=$(dir $(LPMAKE)):$$PATH \
+	    $(BUILD_SUPER_IMAGE) -v $(intermediates)/misc_info.txt $@
+
+$(call dist-for-goals,dist_files,$(INSTALLED_SUPERIMAGE_EMPTY_TARGET))
+
+endif # BOARD_SUPER_PARTITION_SIZE != ""
+endif # PRODUCT_BUILD_SUPER_PARTITION == "true"
+
+# -----------------------------------------------------------------
 # dalvik something
 .PHONY: dalvikfiles
 dalvikfiles: $(INTERNAL_DALVIK_MODULES)
@@ -3909,7 +4136,7 @@
 
 systemimage: $(INSTALLED_QEMU_SYSTEMIMAGE)
 droidcore: $(INSTALLED_QEMU_SYSTEMIMAGE)
-ifeq ($(BOARD_USES_VENDORIMAGE),true)
+ifdef INSTALLED_VENDORIMAGE_TARGET
 INSTALLED_QEMU_VENDORIMAGE := $(PRODUCT_OUT)/vendor-qemu.img
 $(INSTALLED_QEMU_VENDORIMAGE): $(INSTALLED_VENDORIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) $(SIMG2IMG)
 	@echo Create vendor-qemu.img
@@ -3918,7 +4145,7 @@
 vendorimage: $(INSTALLED_QEMU_VENDORIMAGE)
 droidcore: $(INSTALLED_QEMU_VENDORIMAGE)
 endif
-ifeq ($(BOARD_USES_PRODUCTIMAGE),true)
+ifdef INSTALLED_PRODUCTIMAGE_TARGET
 INSTALLED_QEMU_PRODUCTIMAGE := $(PRODUCT_OUT)/product-qemu.img
 $(INSTALLED_QEMU_PRODUCTIMAGE): $(INSTALLED_PRODUCTIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) $(SIMG2IMG)
 	@echo Create product-qemu.img
@@ -3927,7 +4154,7 @@
 productimage: $(INSTALLED_QEMU_PRODUCTIMAGE)
 droidcore: $(INSTALLED_QEMU_PRODUCTIMAGE)
 endif
-ifeq ($(BOARD_USES_PRODUCT_SERVICESIMAGE),true)
+ifdef INSTALLED_PRODUCT_SERVICESIMAGE_TARGET
 INSTALLED_QEMU_PRODUCT_SERVICESIMAGE := $(PRODUCT_OUT)/product_services-qemu.img
 $(INSTALLED_QEMU_PRODUCT_SERVICESIMAGE): $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) $(SIMG2IMG)
 	@echo Create product_services-qemu.img
@@ -3936,7 +4163,7 @@
 productservicesimage: $(INSTALLED_QEMU_PRODUCT_SERVICESIMAGE)
 droidcore: $(INSTALLED_QEMU_PRODUCT_SERVICESIMAGE)
 endif
-ifeq ($(BOARD_USES_ODMIMAGE),true)
+ifdef INSTALLED_ODMIMAGE_TARGET
 INSTALLED_QEMU_ODMIMAGE := $(PRODUCT_OUT)/odm-qemu.img
 $(INSTALLED_QEMU_ODMIMAGE): $(INSTALLED_ODMIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST)
 	@echo Create odm-qemu.img
@@ -4091,29 +4318,29 @@
 	if [ $$FAIL ]; then exit 1; fi
 	$(hide) echo $(notdir $(SDK_FONT_DEPS)) | tr " " "\n"  > $(SDK_FONT_TEMP)/fontsInSdk.txt
 	$(hide) ( \
-		ATREE_STRIP="$(HOST_STRIP) -x" \
-		$(HOST_OUT_EXECUTABLES)/atree \
-		$(addprefix -f ,$(PRIVATE_INPUT_FILES)) \
-			-m $(PRIVATE_DEP_FILE) \
-			-I . \
-			-I $(PRODUCT_OUT) \
-			-I $(HOST_OUT) \
-			-I $(TARGET_COMMON_OUT_ROOT) \
-			-v "PLATFORM_NAME=android-$(PLATFORM_VERSION)" \
-			-v "OUT_DIR=$(OUT_DIR)" \
-			-v "HOST_OUT=$(HOST_OUT)" \
-			-v "TARGET_ARCH=$(TARGET_ARCH)" \
-			-v "TARGET_CPU_ABI=$(TARGET_CPU_ABI)" \
-			-v "DLL_EXTENSION=$(HOST_SHLIB_SUFFIX)" \
-			-v "FONT_OUT=$(SDK_FONT_TEMP)" \
-			-o $(PRIVATE_DIR) && \
-		cp -f $(target_notice_file_txt) \
-				$(PRIVATE_DIR)/system-images/android-$(PLATFORM_VERSION)/$(TARGET_CPU_ABI)/NOTICE.txt && \
-		cp -f $(tools_notice_file_txt) $(PRIVATE_DIR)/platform-tools/NOTICE.txt && \
-		HOST_OUT_EXECUTABLES=$(HOST_OUT_EXECUTABLES) HOST_OS=$(HOST_OS) \
-			development/build/tools/sdk_clean.sh $(PRIVATE_DIR) && \
-		chmod -R ug+rwX $(PRIVATE_DIR) && \
-		cd $(dir $@) && zip -rqX $(notdir $@) $(PRIVATE_NAME) \
+	    ATREE_STRIP="$(HOST_STRIP) -x" \
+	    $(HOST_OUT_EXECUTABLES)/atree \
+	    $(addprefix -f ,$(PRIVATE_INPUT_FILES)) \
+	        -m $(PRIVATE_DEP_FILE) \
+	        -I . \
+	        -I $(PRODUCT_OUT) \
+	        -I $(HOST_OUT) \
+	        -I $(TARGET_COMMON_OUT_ROOT) \
+	        -v "PLATFORM_NAME=android-$(PLATFORM_VERSION)" \
+	        -v "OUT_DIR=$(OUT_DIR)" \
+	        -v "HOST_OUT=$(HOST_OUT)" \
+	        -v "TARGET_ARCH=$(TARGET_ARCH)" \
+	        -v "TARGET_CPU_ABI=$(TARGET_CPU_ABI)" \
+	        -v "DLL_EXTENSION=$(HOST_SHLIB_SUFFIX)" \
+	        -v "FONT_OUT=$(SDK_FONT_TEMP)" \
+	        -o $(PRIVATE_DIR) && \
+	    cp -f $(target_notice_file_txt) \
+	            $(PRIVATE_DIR)/system-images/android-$(PLATFORM_VERSION)/$(TARGET_CPU_ABI)/NOTICE.txt && \
+	    cp -f $(tools_notice_file_txt) $(PRIVATE_DIR)/platform-tools/NOTICE.txt && \
+	    HOST_OUT_EXECUTABLES=$(HOST_OUT_EXECUTABLES) HOST_OS=$(HOST_OS) \
+	        development/build/tools/sdk_clean.sh $(PRIVATE_DIR) && \
+	    chmod -R ug+rwX $(PRIVATE_DIR) && \
+	    cd $(dir $@) && zip -rqX $(notdir $@) $(PRIVATE_NAME) \
 	) || ( rm -rf $(PRIVATE_DIR) $@ && exit 44 )
 
 
diff --git a/core/OWNERS b/core/OWNERS
index 570ede8..750f1fa 100644
--- a/core/OWNERS
+++ b/core/OWNERS
@@ -1 +1,3 @@
 per-file dex_preopt*.mk = ngeoffray@google.com,calin@google.com,mathewi@google.com,dbrazdil@google.com
+per-file construct_context.sh = ngeoffray@google.com,calin@google.com,mathieuc@google.com
+per-file verify_uses_libraries.sh = ngeoffray@google.com,calin@google.com,mathieuc@google.com
diff --git a/core/android_manifest.mk b/core/android_manifest.mk
index c3af942..ed759c5 100644
--- a/core/android_manifest.mk
+++ b/core/android_manifest.mk
@@ -72,8 +72,8 @@
     my_manifest_fixer_flags += --uses-non-sdk-api
 endif
 
-ifeq (true,$(LOCAL_PREFER_INTEGRITY))
-    my_manifest_fixer_flags += --prefer-integrity
+ifeq (true,$(LOCAL_PREFER_CODE_INTEGRITY))
+    my_manifest_fixer_flags += --prefer-code-integrity
 endif
 
 $(fixed_android_manifest): PRIVATE_MANIFEST_FIXER_FLAGS := $(my_manifest_fixer_flags)
diff --git a/core/app_certificate_validate.mk b/core/app_certificate_validate.mk
new file mode 100644
index 0000000..15ddd94
--- /dev/null
+++ b/core/app_certificate_validate.mk
@@ -0,0 +1,12 @@
+
+ifeq (true,$(filter true, \
+   $(LOCAL_PRODUCT_MODULE) $(LOCAL_PRODUCT_SERVICES_MODULE) \
+   $(LOCAL_VENDOR_MODULE) $(LOCAL_PROPRIETARY_MODULE)))
+  ifneq (,$(filter $(dir $(DEFAULT_SYSTEM_DEV_CERTIFICATE))%,$(LOCAL_CERTIFICATE)))
+    CERTIFICATE_VIOLATION_MODULES += $(LOCAL_MODULE)
+    ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ENFORCE_ARTIFACT_SYSTEM_CERTIFICATE_REQUIREMENT))
+      $(if $(filter $(LOCAL_MODULE),$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ARTIFACT_SYSTEM_CERTIFICATE_REQUIREMENT_WHITELIST)),,\
+        $(call pretty-error,The module in product partition cannot be signed with certificate in system.))
+    endif
+  endif
+endif
\ No newline at end of file
diff --git a/core/aux_toolchain.mk b/core/aux_toolchain.mk
index de0b139..c710228 100644
--- a/core/aux_toolchain.mk
+++ b/core/aux_toolchain.mk
@@ -50,4 +50,3 @@
 LOCAL_SYSTEM_SHARED_LIBRARIES :=
 LOCAL_CXX_STL := none
 LOCAL_NO_PIC := true
-LOCAL_NO_LIBCOMPILER_RT := true
diff --git a/core/base_rules.mk b/core/base_rules.mk
index 9c5c69d..cb9c35a 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -277,14 +277,16 @@
 generated_sources_dir := $(call local-generated-sources-dir)
 
 ifneq ($(LOCAL_OVERRIDES_MODULES),)
-  ifeq ($(LOCAL_MODULE_CLASS),EXECUTABLES)
-    ifndef LOCAL_IS_HOST_MODULE
+  ifndef LOCAL_IS_HOST_MODULE
+    ifeq ($(LOCAL_MODULE_CLASS),EXECUTABLES)
       EXECUTABLES.$(LOCAL_MODULE).OVERRIDES := $(strip $(LOCAL_OVERRIDES_MODULES))
+    else ifeq ($(LOCAL_MODULE_CLASS),SHARED_LIBRARIES)
+      SHARED_LIBRARIES.$(LOCAL_MODULE).OVERRIDES := $(strip $(LOCAL_OVERRIDES_MODULES))
     else
-      $(call pretty-error,host modules cannot use LOCAL_OVERRIDES_MODULES)
+      $(call pretty-error,LOCAL_MODULE_CLASS := $(LOCAL_MODULE_CLASS) cannot use LOCAL_OVERRIDES_MODULES)
     endif
   else
-      $(call pretty-error,LOCAL_MODULE_CLASS := $(LOCAL_MODULE_CLASS) cannot use LOCAL_OVERRIDES_MODULES)
+    $(call pretty-error,host modules cannot use LOCAL_OVERRIDES_MODULES)
   endif
 endif
 
diff --git a/core/binary.mk b/core/binary.mk
index 07fb48a..be10c2d 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -72,6 +72,35 @@
 else
   my_native_coverage := false
 endif
+ifneq ($(NATIVE_COVERAGE),true)
+  my_native_coverage := false
+endif
+
+ifeq ($(strip $(ENABLE_XOM)),true)
+  ifndef LOCAL_IS_HOST_MODULE
+    my_xom := true
+    # Disable XOM in excluded paths.
+    combined_xom_exclude_paths := $(XOM_EXCLUDE_PATHS) \
+                                  $(PRODUCT_XOM_EXCLUDE_PATHS)
+    ifneq ($(strip $(foreach dir,$(subst $(comma),$(space),$(combined_xom_exclude_paths)),\
+           $(filter $(dir)%,$(LOCAL_PATH)))),)
+      my_xom := false
+    endif
+
+    # Allow LOCAL_XOM to override the above
+    ifdef LOCAL_XOM
+      my_xom := $(LOCAL_XOM)
+    endif
+
+    ifeq ($(strip $(my_xom)),true)
+      ifeq (arm64,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+        ifeq ($(my_use_clang_lld),true)
+          my_ldflags += -Wl,-execute-only
+        endif
+      endif
+    endif
+  endif
+endif
 
 my_allow_undefined_symbols := $(strip $(LOCAL_ALLOW_UNDEFINED_SYMBOLS))
 ifdef SANITIZE_HOST
@@ -201,7 +230,6 @@
       $(my_ndk_source_root)/cxx-stl/llvm-libc++/include
     my_ndk_stl_include_path += \
       $(my_ndk_source_root)/cxx-stl/llvm-libc++abi/include
-    my_ndk_stl_include_path += $(my_ndk_source_root)/android/support/include
 
     my_libcxx_libdir := \
       $(my_ndk_source_root)/cxx-stl/llvm-libc++/libs/$(my_cpu_variant)
@@ -214,7 +242,13 @@
       my_ndk_stl_shared_lib_fullpath := $(my_libcxx_libdir)/libc++_shared.so
     endif
 
-    my_ndk_stl_static_lib += $(my_libcxx_libdir)/libandroid_support.a
+    ifneq ($(my_ndk_api),current)
+      ifeq ($(call math_lt,$(my_ndk_api),21),true)
+        my_ndk_stl_include_path += $(my_ndk_source_root)/android/support/include
+        my_ndk_stl_static_lib += $(my_libcxx_libdir)/libandroid_support.a
+      endif
+    endif
+
     ifneq (,$(filter armeabi armeabi-v7a,$(my_cpu_variant)))
       my_ndk_stl_static_lib += $(my_libcxx_libdir)/libunwind.a
     endif
@@ -396,13 +430,6 @@
 
 include $(BUILD_SYSTEM)/config_sanitizers.mk
 
-ifneq ($(LOCAL_NO_LIBCOMPILER_RT),true)
-# Add in libcompiler_rt for all regular device builds
-ifeq (,$(WITHOUT_LIBCOMPILER_RT))
-  my_static_libraries += $(COMPILER_RT_CONFIG_EXTRA_STATIC_LIBRARIES)
-endif
-endif
-
 # Statically link libwinpthread when cross compiling win32.
 ifeq ($($(my_prefix)OS),windows)
   my_static_libraries += libwinpthread
@@ -446,144 +473,6 @@
 my_asflags += -D__ASSEMBLY__
 
 ###########################################################
-## Define PRIVATE_ variables from global vars
-###########################################################
-ifndef LOCAL_IS_HOST_MODULE
-ifdef LOCAL_USE_VNDK
-my_target_global_c_includes := \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_INCLUDES)
-my_target_global_c_system_includes := \
-    $(TARGET_OUT_HEADERS) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_SYSTEM_INCLUDES)
-else ifdef LOCAL_SDK_VERSION
-my_target_global_c_includes :=
-my_target_global_c_system_includes := $(my_ndk_stl_include_path) $(my_ndk_sysroot_include)
-else ifdef BOARD_VNDK_VERSION
-my_target_global_c_includes := $(SRC_HEADERS) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_INCLUDES) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
-my_target_global_c_system_includes := $(SRC_SYSTEM_HEADERS) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_SYSTEM_INCLUDES) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_SYSTEM_INCLUDES)
-else
-my_target_global_c_includes := $(SRC_HEADERS) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_INCLUDES) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
-my_target_global_c_system_includes := $(SRC_SYSTEM_HEADERS) $(TARGET_OUT_HEADERS) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_SYSTEM_INCLUDES) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_SYSTEM_INCLUDES)
-endif
-
-my_target_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CFLAGS)
-my_target_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CONLYFLAGS) $(my_c_std_conlyflags)
-my_target_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CPPFLAGS) $(my_cpp_std_cppflags)
-ifeq ($(my_use_clang_lld),true)
-  my_target_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LLDFLAGS)
-  include $(BUILD_SYSTEM)/pack_dyn_relocs_setup.mk
-  ifeq ($(my_pack_module_relocations),false)
-    my_target_global_ldflags += -Wl,--pack-dyn-relocs=none
-  endif
-else
-  my_target_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LDFLAGS)
-endif # my_use_clang_lld
-
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_INCLUDES := $(my_target_global_c_includes)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_SYSTEM_INCLUDES := $(my_target_global_c_system_includes)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CFLAGS := $(my_target_global_cflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CONLYFLAGS := $(my_target_global_conlyflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CPPFLAGS := $(my_target_global_cppflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_LDFLAGS := $(my_target_global_ldflags)
-
-else # LOCAL_IS_HOST_MODULE
-
-my_host_global_c_includes := $(SRC_HEADERS) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
-my_host_global_c_system_includes := $(SRC_SYSTEM_HEADERS) \
-    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_SYSTEM_INCLUDES)
-
-my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CFLAGS)
-my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CONLYFLAGS) $(my_c_std_conlyflags)
-my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CPPFLAGS) $(my_cpp_std_cppflags)
-ifeq ($(my_use_clang_lld),true)
-  my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LLDFLAGS)
-else
-  my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LDFLAGS)
-endif # my_use_clang_lld
-
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_INCLUDES := $(my_host_global_c_includes)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_SYSTEM_INCLUDES := $(my_host_global_c_system_includes)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CFLAGS := $(my_host_global_cflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CONLYFLAGS := $(my_host_global_conlyflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CPPFLAGS := $(my_host_global_cppflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_LDFLAGS := $(my_host_global_ldflags)
-endif # LOCAL_IS_HOST_MODULE
-
-# To enable coverage for a given module, set LOCAL_NATIVE_COVERAGE=true and
-# build with NATIVE_COVERAGE=true in your enviornment. Note that the build
-# system is not sensitive to changes to NATIVE_COVERAGE, so you should do a
-# clean build of your module after toggling it.
-ifeq ($(NATIVE_COVERAGE),true)
-    ifeq ($(my_native_coverage),true)
-        # Note that clang coverage doesn't play nicely with acov out of the box.
-        # Clang apparently generates .gcno files that aren't compatible with
-        # gcov-4.8.  This can be solved by installing gcc-4.6 and invoking lcov
-        # with `--gcov-tool /usr/bin/gcov-4.6`.
-        #
-        # http://stackoverflow.com/questions/17758126/clang-code-coverage-invalid-output
-        my_cflags += --coverage -O0
-        my_ldflags += --coverage
-    endif
-
-    my_coverage_lib := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)LIBPROFILE_RT)
-
-    $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_COVERAGE_LIB := $(my_coverage_lib)
-    $(LOCAL_INTERMEDIATE_TARGETS): $(my_coverage_lib)
-else
-    my_native_coverage := false
-endif
-
-###########################################################
-## Define PRIVATE_ variables used by multiple module types
-###########################################################
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_NO_DEFAULT_COMPILER_FLAGS := \
-    $(strip $(LOCAL_NO_DEFAULT_COMPILER_FLAGS))
-
-ifeq ($(strip $(WITH_STATIC_ANALYZER)),)
-  LOCAL_NO_STATIC_ANALYZER := true
-endif
-
-ifneq ($(strip $(LOCAL_IS_HOST_MODULE)),)
-  my_syntax_arch := host
-else
-  my_syntax_arch := $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
-endif
-
-ifeq ($(strip $(my_cc)),)
-  my_cc := $(my_cc_wrapper) $(CLANG)
-endif
-
-SYNTAX_TOOLS_PREFIX := \
-    $(LLVM_PREBUILTS_BASE)/$(BUILD_OS)-x86/$(LLVM_PREBUILTS_VERSION)/libexec
-
-ifneq ($(LOCAL_NO_STATIC_ANALYZER),true)
-  my_cc := CCC_CC=$(CLANG) CLANG=$(CLANG) \
-           $(SYNTAX_TOOLS_PREFIX)/ccc-analyzer
-endif
-
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CC := $(my_cc)
-
-ifeq ($(strip $(my_cxx)),)
-  my_cxx := $(my_cxx_wrapper) $(CLANG_CXX)
-endif
-
-ifneq ($(LOCAL_NO_STATIC_ANALYZER),true)
-  my_cxx := CCC_CXX=$(CLANG_CXX) CLANG_CXX=$(CLANG_CXX) \
-            $(SYNTAX_TOOLS_PREFIX)/c++-analyzer
-endif
-
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LINKER := $(my_linker)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CXX := $(my_cxx)
-
 # TODO: support a mix of standard extensions so that this isn't necessary
 LOCAL_CPP_EXTENSION := $(strip $(LOCAL_CPP_EXTENSION))
 ifeq ($(LOCAL_CPP_EXTENSION),)
@@ -889,8 +778,6 @@
 # Thus we'll actually generate source for each architecture.
 $(foreach s,$(vts_src),\
     $(eval $(call define-vts-cpp-rule,$(s),$(vts_gen_cpp_root),vts_gen_cpp)))
-$(foreach cpp,$(vts_gen_cpp), \
-    $(call include-depfile,$(addsuffix .vts.P,$(basename $(cpp))),$(cpp)))
 $(call track-src-file-gen,$(vts_src),$(vts_gen_cpp))
 
 $(vts_gen_cpp) : PRIVATE_MODULE := $(LOCAL_MODULE)
@@ -1421,6 +1308,8 @@
 
 all_objects := $(normal_objects) $(gen_o_objects)
 
+LOCAL_INTERMEDIATE_TARGETS += $(all_objects)
+
 # Cleanup file tracking
 $(foreach f,$(my_tracked_gen_files),$(eval my_src_file_gen_$(s):=))
 my_tracked_gen_files :=
@@ -1539,7 +1428,7 @@
 ifeq ($(ONE_SHOT_MAKEFILE),)
 installed_static_library_notice_file_targets := \
     $(foreach lib,$(my_static_libraries) $(my_whole_static_libraries), \
-      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST,TARGET)-STATIC_LIBRARIES-$(lib))
+      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST$(if $(my_host_cross),_CROSS,),TARGET)-STATIC_LIBRARIES-$(lib))
 else
 installed_static_library_notice_file_targets :=
 endif
@@ -1547,6 +1436,9 @@
 $(notice_target): | $(installed_static_library_notice_file_targets)
 $(LOCAL_INSTALLED_MODULE): | $(notice_target)
 
+$(notice_target): | $(installed_static_library_notice_file_targets)
+$(LOCAL_INSTALLED_MODULE): | $(notice_target)
+
 # Default is -fno-rtti.
 ifeq ($(strip $(LOCAL_RTTI_FLAG)),)
 LOCAL_RTTI_FLAG := -fno-rtti
@@ -1711,6 +1603,141 @@
 # (start-group/end-group), so append after the check above.
 my_ldlibs += $(my_cxx_ldlibs)
 
+###########################################################
+## Define PRIVATE_ variables from global vars
+###########################################################
+ifndef LOCAL_IS_HOST_MODULE
+ifdef LOCAL_USE_VNDK
+my_target_global_c_includes := \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_INCLUDES)
+my_target_global_c_system_includes := \
+    $(TARGET_OUT_HEADERS) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_SYSTEM_INCLUDES)
+else ifdef LOCAL_SDK_VERSION
+my_target_global_c_includes :=
+my_target_global_c_system_includes := $(my_ndk_stl_include_path) $(my_ndk_sysroot_include)
+else ifdef BOARD_VNDK_VERSION
+my_target_global_c_includes := $(SRC_HEADERS) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_INCLUDES) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
+my_target_global_c_system_includes := $(SRC_SYSTEM_HEADERS) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_SYSTEM_INCLUDES) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_SYSTEM_INCLUDES)
+else
+my_target_global_c_includes := $(SRC_HEADERS) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_INCLUDES) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
+my_target_global_c_system_includes := $(SRC_SYSTEM_HEADERS) $(TARGET_OUT_HEADERS) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)PROJECT_SYSTEM_INCLUDES) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_SYSTEM_INCLUDES)
+endif
+
+my_target_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CFLAGS)
+my_target_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CONLYFLAGS) $(my_c_std_conlyflags)
+my_target_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CPPFLAGS) $(my_cpp_std_cppflags)
+ifeq ($(my_use_clang_lld),true)
+  my_target_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LLDFLAGS)
+  include $(BUILD_SYSTEM)/pack_dyn_relocs_setup.mk
+  ifeq ($(my_pack_module_relocations),false)
+    my_target_global_ldflags += -Wl,--pack-dyn-relocs=none
+  endif
+else
+  my_target_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LDFLAGS)
+endif # my_use_clang_lld
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_INCLUDES := $(my_target_global_c_includes)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_SYSTEM_INCLUDES := $(my_target_global_c_system_includes)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CFLAGS := $(my_target_global_cflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CONLYFLAGS := $(my_target_global_conlyflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CPPFLAGS := $(my_target_global_cppflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_LDFLAGS := $(my_target_global_ldflags)
+
+else # LOCAL_IS_HOST_MODULE
+
+my_host_global_c_includes := $(SRC_HEADERS) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
+my_host_global_c_system_includes := $(SRC_SYSTEM_HEADERS) \
+    $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_SYSTEM_INCLUDES)
+
+my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CFLAGS)
+my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CONLYFLAGS) $(my_c_std_conlyflags)
+my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CPPFLAGS) $(my_cpp_std_cppflags)
+ifeq ($(my_use_clang_lld),true)
+  my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LLDFLAGS)
+else
+  my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LDFLAGS)
+endif # my_use_clang_lld
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_INCLUDES := $(my_host_global_c_includes)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_GLOBAL_C_SYSTEM_INCLUDES := $(my_host_global_c_system_includes)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CFLAGS := $(my_host_global_cflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CONLYFLAGS := $(my_host_global_conlyflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CPPFLAGS := $(my_host_global_cppflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_LDFLAGS := $(my_host_global_ldflags)
+endif # LOCAL_IS_HOST_MODULE
+
+# To enable coverage for a given module, set LOCAL_NATIVE_COVERAGE=true and
+# build with NATIVE_COVERAGE=true in your enviornment.
+ifeq ($(NATIVE_COVERAGE),true)
+    ifeq ($(my_native_coverage),true)
+        # Note that clang coverage doesn't play nicely with acov out of the box.
+        # Clang apparently generates .gcno files that aren't compatible with
+        # gcov-4.8.  This can be solved by installing gcc-4.6 and invoking lcov
+        # with `--gcov-tool /usr/bin/gcov-4.6`.
+        #
+        # http://stackoverflow.com/questions/17758126/clang-code-coverage-invalid-output
+        my_cflags += --coverage -O0
+        my_ldflags += --coverage
+    endif
+
+    my_coverage_lib := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)LIBPROFILE_RT)
+
+    $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_COVERAGE_LIB := $(my_coverage_lib)
+    $(LOCAL_INTERMEDIATE_TARGETS): $(my_coverage_lib)
+endif
+
+###########################################################
+## Define PRIVATE_ variables used by multiple module types
+###########################################################
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_NO_DEFAULT_COMPILER_FLAGS := \
+    $(strip $(LOCAL_NO_DEFAULT_COMPILER_FLAGS))
+
+ifeq ($(strip $(WITH_STATIC_ANALYZER)),)
+  LOCAL_NO_STATIC_ANALYZER := true
+endif
+
+ifneq ($(strip $(LOCAL_IS_HOST_MODULE)),)
+  my_syntax_arch := host
+else
+  my_syntax_arch := $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
+endif
+
+ifeq ($(strip $(my_cc)),)
+  my_cc := $(my_cc_wrapper) $(CLANG)
+endif
+
+SYNTAX_TOOLS_PREFIX := \
+    $(LLVM_PREBUILTS_BASE)/$(BUILD_OS)-x86/$(LLVM_PREBUILTS_VERSION)/libexec
+
+ifneq ($(LOCAL_NO_STATIC_ANALYZER),true)
+  my_cc := CCC_CC=$(CLANG) CLANG=$(CLANG) \
+           $(SYNTAX_TOOLS_PREFIX)/ccc-analyzer
+endif
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CC := $(my_cc)
+
+ifeq ($(strip $(my_cxx)),)
+  my_cxx := $(my_cxx_wrapper) $(CLANG_CXX)
+endif
+
+ifneq ($(LOCAL_NO_STATIC_ANALYZER),true)
+  my_cxx := CCC_CXX=$(CLANG_CXX) CLANG_CXX=$(CLANG_CXX) \
+            $(SYNTAX_TOOLS_PREFIX)/c++-analyzer
+endif
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LINKER := $(my_linker)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CXX := $(my_cxx)
+
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_YACCFLAGS := $(LOCAL_YACCFLAGS)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_ASFLAGS := $(my_asflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CONLYFLAGS := $(my_conlyflags)
diff --git a/core/build_rro_package.mk b/core/build_rro_package.mk
index ffefb9c..0b4a0c4 100644
--- a/core/build_rro_package.mk
+++ b/core/build_rro_package.mk
@@ -15,11 +15,23 @@
   $(error runtime resource overlay package should not contain sources)
 endif
 
-ifeq ($(LOCAL_RRO_THEME),)
-  LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR)/overlay
+partition :=
+ifeq ($(LOCAL_ODM_MODULE),true)
+  partition := $(TARGET_OUT_ODM)
+else ifeq ($(LOCAL_PRODUCT_MODULE),true)
+  partition := $(TARGET_OUT_PRODUCT)
+else ifeq ($(LOCAL_PRODUCT_SERVICES_MODULE),true)
+  partition := $(TARGET_OUT_PRODUCT_SERVICES)
 else
-  LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR)/overlay/$(LOCAL_RRO_THEME)
+  partition := $(TARGET_OUT_VENDOR)
 endif
 
-include $(BUILD_SYSTEM)/package.mk
+ifeq ($(LOCAL_RRO_THEME),)
+  LOCAL_MODULE_PATH := $(partition)/overlay
+else
+  LOCAL_MODULE_PATH := $(partition)/overlay/$(LOCAL_RRO_THEME)
+endif
 
+partition :=
+
+include $(BUILD_SYSTEM)/package.mk
diff --git a/core/clang/HOST_CROSS_x86.mk b/core/clang/HOST_CROSS_x86.mk
index ffd7811..7581353 100644
--- a/core/clang/HOST_CROSS_x86.mk
+++ b/core/clang/HOST_CROSS_x86.mk
@@ -1 +1,2 @@
 $(clang_2nd_arch_prefix)HOST_CROSS_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-i386.a
+$(clang_2nd_arch_prefix)HOST_CROSS_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.bulitins-i386.a
diff --git a/core/clang/HOST_CROSS_x86_64.mk b/core/clang/HOST_CROSS_x86_64.mk
index f921a1c..9a971c7 100644
--- a/core/clang/HOST_CROSS_x86_64.mk
+++ b/core/clang/HOST_CROSS_x86_64.mk
@@ -1 +1,2 @@
 $(clang_2nd_arch_prefix)HOST_CROSS_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-x86_64.a
+$(clang_2nd_arch_prefix)HOST_CROSS_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.builtins-x86_64.a
diff --git a/core/clang/HOST_x86.mk b/core/clang/HOST_x86.mk
index 2803517..2e0865b 100644
--- a/core/clang/HOST_x86.mk
+++ b/core/clang/HOST_x86.mk
@@ -1 +1,2 @@
 $(clang_2nd_arch_prefix)HOST_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-i386.a
+$(clang_2nd_arch_prefix)HOST_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.builtins-i386.a
diff --git a/core/clang/HOST_x86_64.mk b/core/clang/HOST_x86_64.mk
index 4fdffd8..3fd0541 100644
--- a/core/clang/HOST_x86_64.mk
+++ b/core/clang/HOST_x86_64.mk
@@ -1 +1,2 @@
 HOST_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-x86_64.a
+HOST_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.builtins-x86_64.a
diff --git a/core/clang/TARGET_arm.mk b/core/clang/TARGET_arm.mk
index 9c1a836..6140d7c 100644
--- a/core/clang/TARGET_arm.mk
+++ b/core/clang/TARGET_arm.mk
@@ -3,6 +3,7 @@
 $(clang_2nd_arch_prefix)RS_COMPAT_TRIPLE := armv7-none-linux-gnueabi
 
 $(clang_2nd_arch_prefix)TARGET_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-arm-android.a
+$(clang_2nd_arch_prefix)TARGET_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.builtins-arm-android.a
 
 # Address sanitizer clang config
 $(clang_2nd_arch_prefix)ADDRESS_SANITIZER_LINKER := /system/bin/linker_asan
diff --git a/core/clang/TARGET_arm64.mk b/core/clang/TARGET_arm64.mk
index 9a67b6b..9fe5530 100644
--- a/core/clang/TARGET_arm64.mk
+++ b/core/clang/TARGET_arm64.mk
@@ -3,6 +3,7 @@
 RS_COMPAT_TRIPLE := aarch64-linux-android
 
 TARGET_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-aarch64-android.a
+TARGET_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.builtins-aarch64-android.a
 
 # Address sanitizer clang config
 ADDRESS_SANITIZER_LINKER := /system/bin/linker_asan64
diff --git a/core/clang/TARGET_x86.mk b/core/clang/TARGET_x86.mk
index 1b9c78c..5e2d57e 100644
--- a/core/clang/TARGET_x86.mk
+++ b/core/clang/TARGET_x86.mk
@@ -3,6 +3,7 @@
 $(clang_2nd_arch_prefix)RS_COMPAT_TRIPLE := i686-linux-android
 
 $(clang_2nd_arch_prefix)TARGET_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-i686-android.a
+$(clang_2nd_arch_prefix)TARGET_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.builtins-i686-android.a
 
 # Address sanitizer clang config
 $(clang_2nd_arch_prefix)ADDRESS_SANITIZER_LINKER := /system/bin/linker_asan
diff --git a/core/clang/TARGET_x86_64.mk b/core/clang/TARGET_x86_64.mk
index 3161f84..86b3798 100644
--- a/core/clang/TARGET_x86_64.mk
+++ b/core/clang/TARGET_x86_64.mk
@@ -3,6 +3,7 @@
 RS_COMPAT_TRIPLE := x86_64-linux-android
 
 TARGET_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-x86_64-android.a
+TARGET_LIBCRT_BUILTINS := $(LLVM_RTLIB_PATH)/libclang_rt.builtins-x86_64-android.a
 
 # Address sanitizer clang config
 ADDRESS_SANITIZER_LINKER := /system/bin/linker_asan64
diff --git a/core/clang/config.mk b/core/clang/config.mk
index 63582c2..ca3a1fa 100644
--- a/core/clang/config.mk
+++ b/core/clang/config.mk
@@ -1,6 +1,6 @@
 ## Clang configurations.
 
-LLVM_RTLIB_PATH := $(LLVM_PREBUILTS_PATH)/../lib64/clang/$(LLVM_RELEASE_VERSION)/lib/linux/
+LLVM_RTLIB_PATH := $(LLVM_PREBUILTS_BASE)/linux-x86/$(LLVM_PREBUILTS_VERSION)/lib64/clang/$(LLVM_RELEASE_VERSION)/lib/linux/
 
 define convert-to-clang-flags
 $(strip $(filter-out $(CLANG_CONFIG_UNKNOWN_CFLAGS),$(1)))
@@ -61,8 +61,4 @@
 include $(BUILD_SYSTEM)/clang/TARGET_$(TARGET_2ND_ARCH).mk
 endif
 
-# This allows us to use the superset of functionality that compiler-rt
-# provides to Clang (for supporting features like -ftrapv).
-COMPILER_RT_CONFIG_EXTRA_STATIC_LIBRARIES := libcompiler_rt-extras
-
 include $(BUILD_SYSTEM)/clang/tidy.mk
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index 34a1db8..b47071a 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -51,7 +51,6 @@
 LOCAL_CTS_TEST_RUNNER:=
 LOCAL_CXX:=
 LOCAL_CXX_STL := default
-LOCAL_DATA_BINDING:=
 LOCAL_DEX_PREOPT_APP_IMAGE:=
 LOCAL_DEX_PREOPT_FLAGS:=
 LOCAL_DEX_PREOPT_GENERATE_PROFILE:=
@@ -184,8 +183,8 @@
 LOCAL_NO_CRT:=
 LOCAL_NO_DEFAULT_COMPILER_FLAGS:=
 LOCAL_NO_FPIE :=
-LOCAL_NO_LIBCOMPILER_RT:=
 LOCAL_NO_LIBGCC:=
+LOCAL_NO_LIBCRT_BUILTINS:=
 LOCAL_NO_NOTICE_FILE:=
 LOCAL_NO_PIC:=
 LOCAL_NOSANITIZE:=
@@ -213,7 +212,7 @@
 LOCAL_PREBUILT_OBJ_FILES:=
 LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES:=
 LOCAL_PREBUILT_STRIP_COMMENTS:=
-LOCAL_PREFER_INTEGRITY:=
+LOCAL_PREFER_CODE_INTEGRITY:=
 LOCAL_PRESUBMIT_DISABLED:=
 LOCAL_PRIVATE_PLATFORM_APIS:=
 LOCAL_PRIVILEGED_MODULE:=
@@ -248,6 +247,7 @@
 LOCAL_SANITIZE:=
 LOCAL_SANITIZE_DIAG:=
 LOCAL_SANITIZE_RECOVER:=
+LOCAL_SANITIZE_NO_RECOVER:=
 LOCAL_SANITIZE_BLACKLIST :=
 LOCAL_SDK_LIBRARIES :=
 LOCAL_SDK_RES_VERSION:=
@@ -255,6 +255,7 @@
 LOCAL_SHARED_ANDROID_LIBRARIES:=
 LOCAL_SHARED_LIBRARIES:=
 LOCAL_SOONG_AAR :=
+LOCAL_SOONG_BUILT_INSTALLED :=
 LOCAL_SOONG_BUNDLE :=
 LOCAL_SOONG_CLASSES_JAR :=
 LOCAL_SOONG_DEX_JAR :=
@@ -277,7 +278,6 @@
 LOCAL_STATIC_JAVA_AAR_LIBRARIES:=
 LOCAL_STATIC_JAVA_LIBRARIES:=
 LOCAL_STATIC_LIBRARIES:=
-LOCAL_STRIP_DEX:=
 LOCAL_STRIP_MODULE:=
 LOCAL_SYSTEM_SHARED_LIBRARIES:=none
 LOCAL_TARGET_REQUIRED_MODULES:=
@@ -302,6 +302,7 @@
 LOCAL_VTS_MODE:=
 LOCAL_WARNINGS_ENABLE:=
 LOCAL_WHOLE_STATIC_LIBRARIES:=
+LOCAL_XOM:=
 LOCAL_YACCFLAGS:=
 # TODO: deprecate, it does nothing
 OVERRIDE_BUILT_MODULE_PATH:=
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index 4e83dc4..deed943 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -26,5 +26,5 @@
 
 # $(1): The file to check
 define get-file-size
-stat --format "%s" "$(1)" | tr -d '\n'
+stat -c "%s" "$(1)" | tr -d '\n'
 endef
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index ffb6021..9514edb 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -34,11 +34,23 @@
 endif
 
 KNOWN_ARMv8_CORES := cortex-a53 cortex-a53.a57 cortex-a55 cortex-a73 cortex-a75 cortex-a76
-KNOWN_ARMv8_CORES += kryo denver64 exynos-m1 exynos-m2
+KNOWN_ARMv8_CORES += kryo kryo385 exynos-m1 exynos-m2
 
+KNOWN_ARMv82a_CORES := cortex-a55 cortex-a75 kryo385
+
+# Check for cores that implement armv8-2a ISAs.
+ifneq (,$(filter $(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT), $(KNOWN_ARMv82a_CORES)))
+  ifneq ($(TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT),armv8-2a)
+    $(warning $(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT) is armv8-2a.)
+    ifneq (,$(TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT))
+      $(warning TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT, $(TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT), ignored! Use armv8-2a instead.)
+    endif
+    # Overwrite TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT
+    TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT := armv8-2a
+  endif
 # Many devices (incorrectly) use armv7-a-neon as the 2nd architecture variant
 # for cores that implement armv8-a ISAs. The following sets it to armv8-a.
-ifneq (,$(filter $(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT), $(KNOWN_ARMv8_CORES)))
+else ifneq (,$(filter $(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT), $(KNOWN_ARMv8_CORES)))
   ifneq ($(TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT),armv8-a)
     $(warning $(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT) is armv8-a.)
     ifneq (,$(TARGET_$(combo_2nd_arch_prefix)ARCH_VARIANT))
diff --git a/core/combo/arch/arm/armv8-2a.mk b/core/combo/arch/arm/armv8-2a.mk
new file mode 100644
index 0000000..c1d8182
--- /dev/null
+++ b/core/combo/arch/arm/armv8-2a.mk
@@ -0,0 +1,9 @@
+# Configuration for Linux on ARM.
+# Generating binaries for the ARMv8-2a architecture
+#
+# Many libraries are not aware of armv8-2a, and AArch32 is (almost) a superset
+# of armv7-a-neon. So just let them think we are just like v7.
+ARCH_ARM_HAVE_ARMV7A            := true
+ARCH_ARM_HAVE_VFP               := true
+ARCH_ARM_HAVE_VFP_D32           := true
+ARCH_ARM_HAVE_NEON              := true
diff --git a/core/config.mk b/core/config.mk
index c1ea5a8..a3be194 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -90,6 +90,7 @@
   GLOBAL_CFLAGS_NO_OVERRIDE GLOBAL_CPPFLAGS_NO_OVERRIDE \
   ,GCC support has been removed. Use Clang instead)
 $(KATI_obsolete_var DIST_DIR dist_goal,Use dist-for-goals instead. See $(CHANGES_URL)#dist)
+$(KATI_deprecated_var USER,Use BUILD_USERNAME instead. See $(CHANGES_URL)#USER)
 
 # This is marked as obsolete in envsetup.mk after reading the BoardConfig.mk
 $(KATI_deprecate_export It is a global setting. See $(CHANGES_URL)#export_keyword)
@@ -120,6 +121,8 @@
 
 include $(BUILD_SYSTEM_COMMON)/strings.mk
 
+include $(BUILD_SYSTEM_COMMON)/json.mk
+
 # Various mappings to avoid hard-coding paths all over the place
 include $(BUILD_SYSTEM)/pathmap.mk
 
@@ -567,6 +570,13 @@
 endif
 .KATI_READONLY := ALLOW_MISSING_DEPENDENCIES
 
+TARGET_BUILD_APPS_USE_PREBUILT_SDK :=
+ifdef TARGET_BUILD_APPS
+  ifndef UNBUNDLED_BUILD_SDKS_FROM_SOURCE
+    TARGET_BUILD_APPS_USE_PREBUILT_SDK := true
+  endif
+endif
+
 prebuilt_sdk_tools := prebuilts/sdk/tools
 prebuilt_sdk_tools_bin := $(prebuilt_sdk_tools)/$(HOST_OS)/bin
 
@@ -678,7 +688,7 @@
 else
 AVBTOOL := $(BOARD_CUSTOM_AVBTOOL)
 endif
-APICHECK := $(HOST_OUT_EXECUTABLES)/apicheck$(HOST_EXECUTABLE_SUFFIX)
+APICHECK := $(HOST_OUT_JAVA_LIBRARIES)/metalava$(COMMON_JAVA_PACKAGE_SUFFIX)
 FS_GET_STATS := $(HOST_OUT_EXECUTABLES)/fs_get_stats$(HOST_EXECUTABLE_SUFFIX)
 MAKE_EXT4FS := $(HOST_OUT_EXECUTABLES)/mke2fs$(HOST_EXECUTABLE_SUFFIX)
 MKEXTUSERIMG := $(HOST_OUT_EXECUTABLES)/mkuserimg_mke2fs
@@ -698,6 +708,7 @@
 FAT16COPY := build/make/tools/fat16copy.py
 CHECK_LINK_TYPE := build/make/tools/check_link_type.py
 LPMAKE := $(HOST_OUT_EXECUTABLES)/lpmake$(HOST_EXECUTABLE_SUFFIX)
+BUILD_SUPER_IMAGE := build/make/tools/releasetools/build_super_image.py
 
 PROGUARD := external/proguard/bin/proguard.sh
 JAVATAGS := build/make/tools/java-event-log-tags.py
@@ -745,13 +756,7 @@
 MD5SUM:=md5sum
 endif
 
-APICHECK_CLASSPATH_ENTRIES := \
-    $(HOST_OUT_JAVA_LIBRARIES)/apicheck$(COMMON_JAVA_PACKAGE_SUFFIX) \
-    $(HOST_JDK_TOOLS_JAR) \
-    )
-APICHECK_CLASSPATH := $(subst $(space),:,$(strip $(APICHECK_CLASSPATH_ENTRIES)))
-
-APICHECK_COMMAND := $(APICHECK) -JXmx1024m -J"classpath $(APICHECK_CLASSPATH)"
+APICHECK_COMMAND := $(JAVA) -Xmx4g -jar $(APICHECK) --no-banner --compatible-output=yes
 
 # Boolean variable determining if the whitelist for compatible properties is enabled
 PRODUCT_COMPATIBLE_PROPERTY := false
@@ -923,12 +928,7 @@
     PLATFORM_SEPOLICY_VERSION \
     TOT_SEPOLICY_VERSION \
 
-# If true, kernel configuration requirements are present in OTA package (and will be enforced
-# during OTA). Otherwise, kernel configuration requirements are enforced in VTS.
-# Devices that checks the running kernel (instead of the kernel in OTA package) should not
-# set this variable to prevent OTA failures.
-ifndef PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS
-  PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS :=
+ifeq ($(PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS),)
   ifdef PRODUCT_SHIPPING_API_LEVEL
     ifeq (true,$(call math_gt_or_eq,$(PRODUCT_SHIPPING_API_LEVEL),29))
       PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS := true
@@ -937,17 +937,28 @@
 endif
 .KATI_READONLY := PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS
 
-ifeq ($(PRODUCT_USE_LOGICAL_PARTITIONS),true)
+ifeq ($(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS),true)
+  ifneq ($(PRODUCT_USE_DYNAMIC_PARTITIONS),true)
+    $(error PRODUCT_USE_DYNAMIC_PARTITIONS must be true when PRODUCT_RETROFIT_DYNAMIC_PARTITIONS \
+        is set)
+  endif
+  ifdef PRODUCT_SHIPPING_API_LEVEL
+    ifeq (true,$(call math_gt_or_eq,$(PRODUCT_SHIPPING_API_LEVEL),29))
+      $(error Devices with shipping API level $(PRODUCT_SHIPPING_API_LEVEL) must not set \
+          PRODUCT_RETROFIT_DYNAMIC_PARTITIONS)
+    endif
+  endif
+endif
+
+ifeq ($(PRODUCT_USE_DYNAMIC_PARTITIONS),true)
     requirements := \
         PRODUCT_USE_DYNAMIC_PARTITION_SIZE \
         PRODUCT_BUILD_SUPER_PARTITION \
 
     $(foreach req,$(requirements),$(if $(filter false,$($(req))),\
-        $(error PRODUCT_USE_LOGICAL_PARTITIONS requires $(req) to be true)))
+        $(error PRODUCT_USE_DYNAMIC_PARTITIONS requires $(req) to be true)))
 
     requirements :=
-
-  BOARD_KERNEL_CMDLINE += androidboot.logical_partitions=1
 endif
 
 ifeq ($(PRODUCT_USE_DYNAMIC_PARTITION_SIZE),true)
@@ -1000,6 +1011,7 @@
 #     - BOARD_{GROUP}_PARTITION_PARTITION_LIST: the list of partitions that belongs to this group.
 #       If empty, no partitions belong to this group, and the sum of sizes is effectively 0.
 $(foreach group,$(call to-upper,$(BOARD_SUPER_PARTITION_GROUPS)), \
+    $(eval BOARD_$(group)_SIZE := $(strip $(BOARD_$(group)_SIZE))) \
     $(if $(BOARD_$(group)_SIZE),,$(error BOARD_$(group)_SIZE must not be empty)) \
     $(eval .KATI_READONLY := BOARD_$(group)_SIZE) \
     $(eval BOARD_$(group)_PARTITION_LIST ?=) \
@@ -1007,7 +1019,7 @@
 )
 
 # BOARD_*_PARTITION_LIST: a list of the following tokens
-valid_super_partition_list := system vendor product product_services
+valid_super_partition_list := system vendor product product_services odm
 $(foreach group,$(call to-upper,$(BOARD_SUPER_PARTITION_GROUPS)), \
     $(if $(filter-out $(valid_super_partition_list),$(BOARD_$(group)_PARTITION_LIST)), \
         $(error BOARD_$(group)_PARTITION_LIST contains invalid partition name \
@@ -1026,6 +1038,75 @@
         $(BOARD_$(group)_PARTITION_LIST))
 .KATI_READONLY := BOARD_SUPER_PARTITION_PARTITION_LIST
 
+ifneq ($(BOARD_SUPER_PARTITION_SIZE),)
+ifeq ($(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS),true)
+
+# The metadata device must be specified manually for retrofitting.
+ifeq ($(BOARD_SUPER_PARTITION_METADATA_DEVICE),)
+$(error Must specify BOARD_SUPER_PARTITION_METADATA_DEVICE if PRODUCT_RETROFIT_DYNAMIC_PARTITIONS=true.)
+endif
+
+# The super partition block device list must be specified manually for retrofitting.
+ifeq ($(BOARD_SUPER_PARTITION_BLOCK_DEVICES),)
+$(error Must specify BOARD_SUPER_PARTITION_BLOCK_DEVICES if PRODUCT_RETROFIT_DYNAMIC_PARTITIONS=true.)
+endif
+
+# The metadata device must be included in the super partition block device list.
+ifeq (,$(filter $(BOARD_SUPER_PARTITION_METADATA_DEVICE),$(BOARD_SUPER_PARTITION_BLOCK_DEVICES)))
+$(error BOARD_SUPER_PARTITION_METADATA_DEVICE is not listed in BOARD_SUPER_PARTITION_BLOCK_DEVICES.)
+endif
+
+# The metadata device must be supplied to init via the kernel command-line.
+BOARD_KERNEL_CMDLINE += androidboot.super_partition=$(BOARD_SUPER_PARTITION_METADATA_DEVICE)
+
+BOARD_BUILD_RETROFIT_DYNAMIC_PARTITIONS_OTA_PACKAGE := true
+
+# If "vendor" is listed as one of the dynamic partitions but without its image available (e.g. an
+# AOSP target built without vendor image), don't build the retrofit full OTA package. Because we
+# won't be able to build meaningful super_* images for retrofitting purpose.
+ifneq (,$(filter vendor,$(BOARD_SUPER_PARTITION_PARTITION_LIST)))
+ifndef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE
+ifndef BOARD_PREBUILT_VENDORIMAGE
+BOARD_BUILD_RETROFIT_DYNAMIC_PARTITIONS_OTA_PACKAGE :=
+endif # BOARD_PREBUILT_VENDORIMAGE
+endif # BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE
+endif # BOARD_SUPER_PARTITION_PARTITION_LIST
+
+else # PRODUCT_RETROFIT_DYNAMIC_PARTITIONS
+
+# For normal devices, we populate BOARD_SUPER_PARTITION_BLOCK_DEVICES so the
+# build can handle both cases consistently.
+ifeq ($(BOARD_SUPER_PARTITION_METADATA_DEVICE),)
+BOARD_SUPER_PARTITION_METADATA_DEVICE := super
+endif
+
+ifeq ($(BOARD_SUPER_PARTITION_BLOCK_DEVICES),)
+BOARD_SUPER_PARTITION_BLOCK_DEVICES := $(BOARD_SUPER_PARTITION_METADATA_DEVICE)
+endif
+
+# If only one super block device, default to super partition size.
+ifeq ($(word 2,$(BOARD_SUPER_PARTITION_BLOCK_DEVICES)),)
+BOARD_SUPER_PARTITION_$(call to-upper,$(strip $(BOARD_SUPER_PARTITION_BLOCK_DEVICES)))_DEVICE_SIZE ?= \
+    $(BOARD_SUPER_PARTITION_SIZE)
+endif
+
+ifneq ($(BOARD_SUPER_PARTITION_METADATA_DEVICE),super)
+BOARD_KERNEL_CMDLINE += androidboot.super_partition=$(BOARD_SUPER_PARTITION_METADATA_DEVICE)
+endif
+BOARD_BUILD_RETROFIT_DYNAMIC_PARTITIONS_OTA_PACKAGE :=
+
+endif # PRODUCT_RETROFIT_DYNAMIC_PARTITIONS
+endif # BOARD_SUPER_PARTITION_SIZE
+.KATI_READONLY := BOARD_SUPER_PARTITION_BLOCK_DEVICES
+.KATI_READONLY := BOARD_SUPER_PARTITION_METADATA_DEVICE
+.KATI_READONLY := BOARD_BUILD_RETROFIT_DYNAMIC_PARTITIONS_OTA_PACKAGE
+
+$(foreach device,$(call to-upper,$(BOARD_SUPER_PARTITION_BLOCK_DEVICES)), \
+    $(eval BOARD_SUPER_PARTITION_$(device)_DEVICE_SIZE := $(strip $(BOARD_SUPER_PARTITION_$(device)_DEVICE_SIZE))) \
+    $(if $(BOARD_SUPER_PARTITION_$(device)_DEVICE_SIZE),, \
+        $(error BOARD_SUPER_PARTITION_$(device)_DEVICE_SIZE must not be empty)) \
+    $(eval .KATI_READONLY := BOARD_SUPER_PARTITION_$(device)_DEVICE_SIZE))
+
 endif # PRODUCT_BUILD_SUPER_PARTITION
 
 # ###############################################################
@@ -1147,10 +1228,7 @@
 
 INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-public-list.txt
 INTERNAL_PLATFORM_HIDDENAPI_PRIVATE_LIST := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-private-list.txt
-INTERNAL_PLATFORM_HIDDENAPI_WHITELIST := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-whitelist.txt
-INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-light-greylist.txt
-INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-dark-greylist.txt
-INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-blacklist.txt
+INTERNAL_PLATFORM_HIDDENAPI_FLAGS := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-flags.csv
 INTERNAL_PLATFORM_HIDDENAPI_GREYLIST_METADATA := $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/hiddenapi-greylist.csv
 
 # Missing optional uses-libraries so that the platform doesn't create build rules that depend on
diff --git a/core/config_sanitizers.mk b/core/config_sanitizers.mk
index fcf527e..6c9caa8 100644
--- a/core/config_sanitizers.mk
+++ b/core/config_sanitizers.mk
@@ -176,6 +176,7 @@
 ifneq ($(filter hwaddress,$(my_sanitize)),)
   my_sanitize := $(filter-out address,$(my_sanitize))
   my_sanitize := $(filter-out thread,$(my_sanitize))
+  my_sanitize := $(filter-out cfi,$(my_sanitize))
 endif
 
 ifneq ($(filter hwaddress,$(my_sanitize)),)
@@ -336,7 +337,7 @@
       my_ldflags += -Wl,--as-needed
     endif
 
-    ifeq ($(LOCAL_MODULE_CLASS),EXECUTABLES)
+    ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
       ifneq ($(LOCAL_FORCE_STATIC_EXECUTABLE),true)
         my_linker := $($(LOCAL_2ND_ARCH_VAR_PREFIX)ADDRESS_SANITIZER_LINKER)
         # Make sure linker_asan get installed.
@@ -400,6 +401,11 @@
   my_cflags += -fsanitize-recover=$(recover_arg)
 endif
 
+ifneq ($(strip $(LOCAL_SANITIZE_NO_RECOVER)),)
+  no_recover_arg := $(subst $(space),$(comma),$(LOCAL_SANITIZE_NO_RECOVER)),
+  my_cflags += -fno-sanitize-recover=$(no_recover_arg)
+endif
+
 ifneq ($(my_sanitize_diag),)
   # TODO(vishwath): Add diagnostic support for static executables once
   # we switch to clang-4393122 (which adds the static ubsan runtime
@@ -414,3 +420,14 @@
     endif
   endif
 endif
+
+# http://b/119329758, Android core does not boot up with this sanitizer yet.
+# Previously sanitized modules might not pass new implicit-integer-sign-change check.
+# Disable this check unless it has been explicitly specified.
+ifneq ($(findstring fsanitize,$(my_cflags)),)
+  ifneq ($(findstring integer,$(my_cflags)),)
+    ifeq ($(findstring sanitize=implicit-integer-sign-change,$(my_cflags)),)
+      my_cflags += -fno-sanitize=implicit-integer-sign-change
+    endif
+  endif
+endif
diff --git a/core/construct_context.sh b/core/construct_context.sh
index b4ae519..399c15d 100755
--- a/core/construct_context.sh
+++ b/core/construct_context.sh
@@ -16,39 +16,54 @@
 
 set -e
 
-# inputs:
-# $1 is PRIVATE_CONDITIONAL_USES_LIBRARIES_HOST
-# $2 is PRIVATE_CONDITIONAL_USES_LIBRARIES_TARGET
-
-# class_loader_context: library paths on the host
-# stored_class_loader_context_libs: library paths on device
-# these are both comma separated paths, example: lib1.jar:lib2.jar or /system/framework/lib1.jar:/system/framework/lib2.jar
-
 # target_sdk_version: parsed from manifest
-# my_conditional_host_libs: libraries conditionally added for non P
-# my_conditional_target_libs: target libraries conditionally added for non P
 #
 # outputs
 # class_loader_context_arg: final class loader conext arg
 # stored_class_loader_context_arg: final stored class loader context arg
 
-my_conditional_host_libs=$1
-my_conditional_target_libs=$2
+# The hidl.manager shared library has a dependency on hidl.base. We'll manually
+# add that information to the class loader context if we see those libraries.
+hidl_manager="android.hidl.manager-V1.0-java"
+hidl_base="android.hidl.base-V1.0-java"
 
-# Note that SDK 28 is P.
+function add_to_contexts {
+  for i in $1; do
+    if [[ -z "${class_loader_context}" ]]; then
+      export class_loader_context="PCL[$i]"
+    else
+      export class_loader_context+="#PCL[$i]"
+    fi
+    if [[ $i == *"$hidl_manager"* ]]; then
+      export class_loader_context+="{PCL[${i/$hidl_manager/$hidl_base}]}"
+    fi
+  done
+
+  for i in $2; do
+    if [[ -z "${stored_class_loader_context}" ]]; then
+      export stored_class_loader_context="PCL[$i]"
+    else
+      export stored_class_loader_context+="#PCL[$i]"
+    fi
+    if [[ $i == *"$hidl_manager"* ]]; then
+      export stored_class_loader_context+="{PCL[${i/$hidl_manager/$hidl_base}]}"
+    fi
+  done
+}
+
+# The order below must match what the package manager also computes for
+# class loader context.
+
 if [[ "${target_sdk_version}" -lt "28" ]]; then
-  if [[ -z "${class_loader_context}" ]]; then
-    export class_loader_context="${my_conditional_host_libs}"
-  else
-    export class_loader_context="${my_conditional_host_libs}:${class_loader_context}"
-  fi
-  if [[ -z "${stored_class_loader_context_libs}" ]]; then
-    export stored_class_loader_context_libs="${my_conditional_target_libs}";
-  else
-    export stored_class_loader_context_libs="${my_conditional_target_libs}:${stored_class_loader_context_libs}";
-  fi
+  add_to_contexts "${conditional_host_libs_28}" "${conditional_target_libs_28}"
 fi
 
+if [[ "${target_sdk_version}" -lt "29" ]]; then
+  add_to_contexts "${conditional_host_libs_29}" "${conditional_target_libs_29}"
+fi
+
+add_to_contexts "${dex_preopt_host_libraries}" "${dex_preopt_target_libraries}"
+
 # Generate the actual context string.
-export class_loader_context_arg="--class-loader-context=PCL[${class_loader_context}]"
-export stored_class_loader_context_arg="--stored-class-loader-context=PCL[${stored_class_loader_context_libs}]"
+export class_loader_context_arg="--class-loader-context=PCL[]{${class_loader_context}}"
+export stored_class_loader_context_arg="--stored-class-loader-context=PCL[]{${stored_class_loader_context}}"
diff --git a/core/cxx_stl_setup.mk b/core/cxx_stl_setup.mk
index 3590079..25fd642 100644
--- a/core/cxx_stl_setup.mk
+++ b/core/cxx_stl_setup.mk
@@ -51,8 +51,8 @@
 darwin_dynamic_gcclibs := -lc -lSystem
 darwin_static_gcclibs := NO_STATIC_HOST_BINARIES_ON_DARWIN
 windows_dynamic_gcclibs := \
-    -Wl,--start-group -lmingw32 -lgcc -lgcc_eh -lmoldname -lmingwex -lmsvcr110 \
-    -lmsvcrt -lpthread -ladvapi32 -lshell32 -luser32 -lkernel32 -lpsapi \
+    -Wl,--start-group -lmingw32 -lgcc -lgcc_eh -lmoldname -lmingwex \
+    -lmsvcrt -lucrt -lpthread -ladvapi32 -lshell32 -luser32 -lkernel32 -lpsapi \
     -Wl,--end-group
 windows_static_gcclibs := NO_STATIC_HOST_BINARIES_ON_WINDOWS
 
diff --git a/core/definitions.mk b/core/definitions.mk
index 0e959d6..d5c7b91 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -77,6 +77,9 @@
 # GPL module license files
 ALL_GPL_MODULE_LICENSE_FILES:=
 
+# Packages with certificate violation
+CERTIFICATE_VIOLATION_MODULES :=
+
 # Target and host installed module's dependencies on shared libraries.
 # They are list of "<module_name>:<installed_file>:lib1,lib2...".
 TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES :=
@@ -797,13 +800,13 @@
 # $(1): path (and optionally line) information
 # $(2): message to print
 define echo-warning
-echo -e "$(ESC_BOLD)$(1): $(ESC_WARNING)warning:$(ESC_RESET)$(ESC_BOLD)" $(2) "$(ESC_RESET)" >&2
+echo -e "$(ESC_BOLD)$(1): $(ESC_WARNING)warning:$(ESC_RESET)$(ESC_BOLD)" '$(subst ','\'',$(2))'  "$(ESC_RESET)" >&2
 endef
 
 # $(1): path (and optionally line) information
 # $(2): message to print
 define echo-error
-echo -e "$(ESC_BOLD)$(1): $(ESC_ERROR)error:$(ESC_RESET)$(ESC_BOLD)" $(2) "$(ESC_RESET)" >&2
+echo -e "$(ESC_BOLD)$(1): $(ESC_ERROR)error:$(ESC_RESET)$(ESC_BOLD)" '$(subst ','\'',$(2))'  "$(ESC_RESET)" >&2
 endef
 
 ###########################################################
@@ -1023,7 +1026,7 @@
 @mkdir -p $(dir $@)
 @mkdir -p $(PRIVATE_HEADER_OUTPUT_DIR)
 @echo "Generating C++ from VTS: $(PRIVATE_MODULE) <= $<"
-$(hide) $(VTSC) -d$(basename $@).vts.P $(PRIVATE_VTS_FLAGS) \
+$(hide) $(VTSC) -TODO_b/120496070 $(PRIVATE_VTS_FLAGS) \
     $< $(PRIVATE_HEADER_OUTPUT_DIR) $@
 endef
 
@@ -1693,6 +1696,7 @@
 	$(PRIVATE_ALL_STATIC_LIBRARIES) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
 	$(if $(filter true,$(NATIVE_COVERAGE)),$(PRIVATE_TARGET_COVERAGE_LIB)) \
+	$(PRIVATE_TARGET_LIBCRT_BUILTINS) \
 	$(PRIVATE_TARGET_LIBATOMIC) \
 	$(PRIVATE_TARGET_LIBGCC) \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
@@ -1728,6 +1732,7 @@
 	$(PRIVATE_ALL_STATIC_LIBRARIES) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
 	$(if $(filter true,$(NATIVE_COVERAGE)),$(PRIVATE_TARGET_COVERAGE_LIB)) \
+	$(PRIVATE_TARGET_LIBCRT_BUILTINS) \
 	$(PRIVATE_TARGET_LIBATOMIC) \
 	$(PRIVATE_TARGET_LIBGCC) \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
@@ -1775,6 +1780,7 @@
 	$(if $(filter true,$(NATIVE_COVERAGE)),$(PRIVATE_TARGET_COVERAGE_LIB)) \
 	$(PRIVATE_TARGET_LIBATOMIC) \
 	$(filter %libcompiler_rt.a %libcompiler_rt.hwasan.a,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
+	$(PRIVATE_TARGET_LIBCRT_BUILTINS) \
 	$(PRIVATE_TARGET_LIBGCC) \
 	-Wl,--end-group \
 	$(PRIVATE_TARGET_CRTEND_O)
@@ -2367,14 +2373,11 @@
 define run-appcompat
 $(hide) \
   echo "appcompat.sh output:" >> $(PRODUCT_OUT)/appcompat/$(PRIVATE_MODULE).log && \
-  PACKAGING=$(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING art/tools/veridex/appcompat.sh --dex-file=$@ 2>&1 >> $(PRODUCT_OUT)/appcompat/$(PRIVATE_MODULE).log
+  PACKAGING=$(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING ANDROID_LOG_TAGS="*:e" art/tools/veridex/appcompat.sh --dex-file=$@ 2>&1 >> $(PRODUCT_OUT)/appcompat/$(PRIVATE_MODULE).log
 endef
 appcompat-files = \
   art/tools/veridex/appcompat.sh \
-  $(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST) \
-  $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST) \
-  $(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST) \
-  $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST) \
+  $(INTERNAL_PLATFORM_HIDDENAPI_FLAGS) \
   $(HOST_OUT_EXECUTABLES)/veridex \
   $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/core_dex_intermediates/classes.dex \
   $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/oahl_dex_intermediates/classes.dex
@@ -2668,17 +2671,13 @@
 # Java semantics of the result dex bytecode. Use at own risk.
 ifneq ($(UNSAFE_DISABLE_HIDDENAPI_FLAGS),true)
 define hiddenapi-copy-dex-files
-$(2): $(1) $(HIDDENAPI) $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST) \
-      $(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST) $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST)
+$(2): $(1) $(HIDDENAPI) $(INTERNAL_PLATFORM_HIDDENAPI_FLAGS)
 	@rm -rf $(dir $(2))
 	@mkdir -p $(dir $(2))
 	for INPUT_DEX in `find $(dir $(1)) -maxdepth 1 -name "classes*.dex" | sort`; do \
 	    echo "--input-dex=$$$${INPUT_DEX}"; \
 	    echo "--output-dex=$(dir $(2))/`basename $$$${INPUT_DEX}`"; \
-	done | xargs $(HIDDENAPI) encode \
-	    --light-greylist=$(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST) \
-	    --dark-greylist=$(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST) \
-	    --blacklist=$(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST)
+	done | xargs $(HIDDENAPI) encode --api-flags=$(INTERNAL_PLATFORM_HIDDENAPI_FLAGS)
 
 $(INTERNAL_PLATFORM_HIDDENAPI_PRIVATE_LIST): $(1)
 $(INTERNAL_PLATFORM_HIDDENAPI_PRIVATE_LIST): PRIVATE_DEX_INPUTS := $$(PRIVATE_DEX_INPUTS) $(1)
@@ -2694,30 +2693,23 @@
 endif  # UNSAFE_DISABLE_HIDDENAPI_FLAGS
 
 # Generate a greylist.txt from a classes.jar
-define hiddenapi-generate-greylist-txt
+define hiddenapi-generate-csv
 ifneq (,$(wildcard frameworks/base))
 # Only generate this target if we're in a tree with frameworks/base present.
-$(3): .KATI_IMPLICIT_OUTPUTS := $(2) $(4)
-# For now, write P & Q blacklist to single file until runtime support is finished
+$(2): $(1) $(CLASS2GREYLIST) $(INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST)
+	$(CLASS2GREYLIST) --public-api-list $(INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST) $(1) \
+	    --write-flags-csv $(2)
+
 $(3): $(1) $(CLASS2GREYLIST) $(INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST)
 	$(CLASS2GREYLIST) --public-api-list $(INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST) $(1) \
-	    --write-whitelist $(2) \
-	    --write-greylist none,28:$(3) \
-	    --write-greylist 26:$(4)
+	    --write-metadata-csv $(3)
 
-$(5): $(1) $(CLASS2GREYLIST) $(INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST)
-	$(CLASS2GREYLIST) --public-api-list $(INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST) $(1) \
-	    --write-metadata-csv $(5)
+$(INTERNAL_PLATFORM_HIDDENAPI_FLAGS): $(2)
+$(INTERNAL_PLATFORM_HIDDENAPI_FLAGS): PRIVATE_FLAGS_INPUTS := $$(PRIVATE_FLAGS_INPUTS) $(2)
 
-$(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST): $(2) $(3) $(4)
-$(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST): \
-    PRIVATE_WHITELIST_INPUTS := $$(PRIVATE_WHITELIST_INPUTS) $(2)
-$(INTERNAL_PLATFORM_HIDDENAPI_WHITELIST): \
-    PRIVATE_GREYLIST_INPUTS := $$(PRIVATE_GREYLIST_INPUTS) $(3)
-    PRIVATE_DARKGREYLIST_INPUTS := $$(PRIVATE_DARKGREYLIST_INPUTS) $(4)
-$(INTERNAL_PLATFORM_HIDDENAPI_GREYLIST_METADATA): $(5)
+$(INTERNAL_PLATFORM_HIDDENAPI_GREYLIST_METADATA): $(3)
 $(INTERNAL_PLATFORM_HIDDENAPI_GREYLIST_METADATA): \
-    PRIVATE_METADATA_INPUTS := $$(PRIVATE_METADATA_INPUTS) $(5)
+    PRIVATE_METADATA_INPUTS := $$(PRIVATE_METADATA_INPUTS) $(3)
 
 endif
 endef
@@ -2749,6 +2741,14 @@
 ###########################################################
 ## Commands to call R8
 ###########################################################
+
+# Use --debug flag for eng builds by default
+ifeq (eng,$(TARGET_BUILD_VARIANT))
+R8_DEBUG_MODE := --debug
+else
+R8_DEBUG_MODE :=
+endif
+
 define transform-jar-to-dex-r8
 @echo R8: $@
 $(hide) rm -f $(PRIVATE_PROGUARD_DICTIONARY)
@@ -2756,6 +2756,7 @@
     --min-api $(PRIVATE_MIN_SDK_VERSION) \
     --no-data-resources \
     --force-proguard-compatibility --output $(subst classes.dex,,$@) \
+    $(R8_DEBUG_MODE) \
     $(PRIVATE_PROGUARD_FLAGS) \
     $(addprefix -injars , $(PRIVATE_EXTRA_INPUT_JAR)) \
     $(PRIVATE_DX_FLAGS)
@@ -2906,7 +2907,7 @@
 define check-api
 $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/$(strip $(1))-timestamp: $(2) $(3) $(4) $(APICHECK) $(9)
 	@echo "Checking API:" $(1)
-	$(hide) ( $(APICHECK_COMMAND) $(6) $(2) $(3) $(4) $(5) || ( $(7) ; exit 38 ) )
+	$(hide) ( $(APICHECK_COMMAND) --check-api-files $(6) $(2) $(3) $(4) $(5) || ( $(7) ; exit 38 ) )
 	$(hide) mkdir -p $$(dir $$@)
 	$(hide) touch $$@
 $(8): $(TARGET_OUT_COMMON_INTERMEDIATES)/PACKAGING/$(strip $(1))-timestamp
diff --git a/core/dex_preopt.mk b/core/dex_preopt.mk
index 92ed970..4d7d11c 100644
--- a/core/dex_preopt.mk
+++ b/core/dex_preopt.mk
@@ -3,31 +3,7 @@
 #
 ####################################
 
-# list of boot classpath jars for dexpreopt
-DEXPREOPT_BOOT_JARS := $(subst $(space),:,$(PRODUCT_BOOT_JARS))
-DEXPREOPT_BOOT_JARS_MODULES := $(PRODUCT_BOOT_JARS)
-PRODUCT_BOOTCLASSPATH := $(subst $(space),:,$(foreach m,$(DEXPREOPT_BOOT_JARS_MODULES),/system/framework/$(m).jar))
-
-PRODUCT_SYSTEM_SERVER_CLASSPATH := $(subst $(space),:,$(foreach m,$(PRODUCT_SYSTEM_SERVER_JARS),/system/framework/$(m).jar))
-
-DEXPREOPT_BUILD_DIR := $(OUT_DIR)
-DEXPREOPT_PRODUCT_DIR_FULL_PATH := $(PRODUCT_OUT)/dex_bootjars
-DEXPREOPT_PRODUCT_DIR := $(patsubst $(DEXPREOPT_BUILD_DIR)/%,%,$(DEXPREOPT_PRODUCT_DIR_FULL_PATH))
-DEXPREOPT_BOOT_JAR_DIR := system/framework
-DEXPREOPT_BOOT_JAR_DIR_FULL_PATH := $(DEXPREOPT_PRODUCT_DIR_FULL_PATH)/$(DEXPREOPT_BOOT_JAR_DIR)
-
-# The default value for LOCAL_DEX_PREOPT
-DEX_PREOPT_DEFAULT ?= true
-
-# The default filter for which files go into the system_other image (if it is
-# being used). To bundle everything one should set this to '%'
-SYSTEM_OTHER_ODEX_FILTER ?= \
-    app/% \
-    priv-app/% \
-    product_services/app/% \
-    product_services/priv-app/% \
-    product/app/% \
-    product/priv-app/% \
+include $(BUILD_SYSTEM)/dex_preopt_config.mk
 
 # Method returning whether the install path $(1) should be for system_other.
 # Under SANITIZE_LITE, we do not want system_other. Just put things under /data/asan.
@@ -37,35 +13,6 @@
 install-on-system-other = $(filter-out $(PRODUCT_DEXPREOPT_SPEED_APPS) $(PRODUCT_SYSTEM_SERVER_APPS),$(basename $(notdir $(filter $(foreach f,$(SYSTEM_OTHER_ODEX_FILTER),$(TARGET_OUT)/$(f)),$(1)))))
 endif
 
-# The default values for pre-opting: always preopt PIC.
-# Conditional to building on linux, as dex2oat currently does not work on darwin.
-ifeq ($(HOST_OS),linux)
-  WITH_DEXPREOPT ?= true
-  ifeq (eng,$(TARGET_BUILD_VARIANT))
-    # Don't strip for quick development turnarounds.
-    DEX_PREOPT_DEFAULT := nostripping
-    # For an eng build only pre-opt the boot image and system server. This gives reasonable performance
-    # and still allows a simple workflow: building in frameworks/base and syncing.
-    WITH_DEXPREOPT_BOOT_IMG_AND_SYSTEM_SERVER_ONLY ?= true
-  endif
-  # Add mini-debug-info to the boot classpath unless explicitly asked not to.
-  ifneq (false,$(WITH_DEXPREOPT_DEBUG_INFO))
-    PRODUCT_DEX_PREOPT_BOOT_FLAGS += --generate-mini-debug-info
-  endif
-
-  # Non eng linux builds must have preopt enabled so that system server doesn't run as interpreter
-  # only. b/74209329
-  ifeq (,$(filter eng, $(TARGET_BUILD_VARIANT)))
-    ifneq (true,$(WITH_DEXPREOPT))
-      ifneq (true,$(WITH_DEXPREOPT_BOOT_IMG_AND_SYSTEM_SERVER_ONLY))
-        $(call pretty-error, DEXPREOPT must be enabled for user and userdebug builds)
-      endif
-    endif
-  endif
-endif
-
-GLOBAL_DEXPREOPT_FLAGS :=
-
 # Special rules for building stripped boot jars that override java_library.mk rules
 
 # $(1): boot jar module name
@@ -83,19 +30,6 @@
 
 include $(BUILD_SYSTEM)/dex_preopt_libart.mk
 
-# Define dexpreopt-one-file based on current default runtime.
-# $(1): the input .jar or .apk file
-# $(2): the output .odex file
-define dexpreopt-one-file
-$(call dex2oat-one-file,$(1),$(2))
-endef
-
-DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS := $(DEX2OAT_DEPENDENCY)
-DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT := $(DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME)
-ifdef TARGET_2ND_ARCH
-$(TARGET_2ND_ARCH_VAR_PREFIX)DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT := $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME)
-endif  # TARGET_2ND_ARCH
-
 # === hiddenapi rules ===
 
 hiddenapi_stubs_jar = $(call intermediates-dir-for,JAVA_LIBRARIES,$(1),,COMMON)/javalib.jar
@@ -149,10 +83,12 @@
 	$(call commit-change-for-toc,$(INTERNAL_PLATFORM_HIDDENAPI_PUBLIC_LIST))
 	$(call commit-change-for-toc,$(INTERNAL_PLATFORM_HIDDENAPI_PRIVATE_LIST))
 
+
+
 ifeq ($(PRODUCT_DIST_BOOT_AND_SYSTEM_JARS),true)
 boot_profile_jars_zip := $(PRODUCT_OUT)/boot_profile_jars.zip
 all_boot_jars := \
-  $(foreach m,$(DEXPREOPT_BOOT_JARS_MODULES),$(PRODUCT_OUT)/system/framework/$(m).jar) \
+  $(foreach m,$(PRODUCT_BOOT_JARS),$(PRODUCT_OUT)/system/framework/$(m).jar) \
   $(foreach m,$(PRODUCT_SYSTEM_SERVER_JARS),$(PRODUCT_OUT)/system/framework/$(m).jar)
 
 $(boot_profile_jars_zip): PRIVATE_JARS := $(all_boot_jars)
diff --git a/core/dex_preopt_config.mk b/core/dex_preopt_config.mk
new file mode 100644
index 0000000..3eaf55b
--- /dev/null
+++ b/core/dex_preopt_config.mk
@@ -0,0 +1,206 @@
+DEX_PREOPT_CONFIG := $(PRODUCT_OUT)/dexpreopt.config
+
+# list of boot classpath jars for dexpreopt
+DEXPREOPT_BOOT_JARS_MODULES := $(strip $(filter-out conscrypt,$(PRODUCT_BOOT_JARS)))
+PRODUCT_BOOTCLASSPATH_JARS := $(strip $(DEXPREOPT_BOOT_JARS_MODULES) $(filter conscrypt,$(PRODUCT_BOOT_JARS)))
+PRODUCT_BOOTCLASSPATH := $(subst $(space),:,$(foreach m,$(PRODUCT_BOOTCLASSPATH_JARS),/system/framework/$(m).jar))
+
+PRODUCT_SYSTEM_SERVER_CLASSPATH := $(subst $(space),:,$(foreach m,$(PRODUCT_SYSTEM_SERVER_JARS),/system/framework/$(m).jar))
+
+DEXPREOPT_BUILD_DIR := $(OUT_DIR)
+DEXPREOPT_PRODUCT_DIR_FULL_PATH := $(PRODUCT_OUT)/dex_bootjars
+DEXPREOPT_PRODUCT_DIR := $(patsubst $(DEXPREOPT_BUILD_DIR)/%,%,$(DEXPREOPT_PRODUCT_DIR_FULL_PATH))
+DEXPREOPT_BOOT_JAR_DIR := system/framework
+DEXPREOPT_BOOT_JAR_DIR_FULL_PATH := $(DEXPREOPT_PRODUCT_DIR_FULL_PATH)/$(DEXPREOPT_BOOT_JAR_DIR)
+
+DEXPREOPT_BOOTCLASSPATH_DEX_LOCATIONS := $(foreach m,$(PRODUCT_BOOTCLASSPATH_JARS),/$(DEXPREOPT_BOOT_JAR_DIR)/$(m).jar)
+DEXPREOPT_BOOTCLASSPATH_DEX_FILES := $(foreach jar,$(DEXPREOPT_BOOTCLASSPATH_DEX_LOCATIONS),$(PRODUCT_OUT)$(jar))
+
+DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/boot.art
+DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(DEX2OAT_TARGET_ARCH)/boot.art
+
+ifdef TARGET_2ND_ARCH
+  $(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/boot.art
+  $(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH)/boot.art
+endif
+
+# The default value for LOCAL_DEX_PREOPT
+DEX_PREOPT_DEFAULT ?= true
+
+# The default filter for which files go into the system_other image (if it is
+# being used). To bundle everything one should set this to '%'
+SYSTEM_OTHER_ODEX_FILTER ?= \
+    app/% \
+    priv-app/% \
+    product_services/app/% \
+    product_services/priv-app/% \
+    product/app/% \
+    product/priv-app/% \
+
+# The default values for pre-opting: always preopt PIC.
+# Conditional to building on linux, as dex2oat currently does not work on darwin.
+ifeq ($(HOST_OS),linux)
+  WITH_DEXPREOPT ?= true
+  ifeq (eng,$(TARGET_BUILD_VARIANT))
+    # Don't strip for quick development turnarounds.
+    DEX_PREOPT_DEFAULT := nostripping
+    # For an eng build only pre-opt the boot image and system server. This gives reasonable performance
+    # and still allows a simple workflow: building in frameworks/base and syncing.
+    WITH_DEXPREOPT_BOOT_IMG_AND_SYSTEM_SERVER_ONLY ?= true
+  endif
+  # Add mini-debug-info to the boot classpath unless explicitly asked not to.
+  ifneq (false,$(WITH_DEXPREOPT_DEBUG_INFO))
+    PRODUCT_DEX_PREOPT_BOOT_FLAGS += --generate-mini-debug-info
+  endif
+
+  # Non eng linux builds must have preopt enabled so that system server doesn't run as interpreter
+  # only. b/74209329
+  ifeq (,$(filter eng, $(TARGET_BUILD_VARIANT)))
+    ifneq (true,$(WITH_DEXPREOPT))
+      ifneq (true,$(WITH_DEXPREOPT_BOOT_IMG_AND_SYSTEM_SERVER_ONLY))
+        $(call pretty-error, DEXPREOPT must be enabled for user and userdebug builds)
+      endif
+    endif
+  endif
+endif
+
+# Default to debug version to help find bugs.
+# Set USE_DEX2OAT_DEBUG to false for only building non-debug versions.
+ifeq ($(USE_DEX2OAT_DEBUG),false)
+DEX2OAT := $(HOST_OUT_EXECUTABLES)/dex2oat$(HOST_EXECUTABLE_SUFFIX)
+else
+DEX2OAT := $(HOST_OUT_EXECUTABLES)/dex2oatd$(HOST_EXECUTABLE_SUFFIX)
+endif
+
+DEX2OAT_DEPENDENCY += $(DEX2OAT)
+
+# Use the first preloaded-classes file in PRODUCT_COPY_FILES.
+PRELOADED_CLASSES := $(call word-colon,1,$(firstword \
+    $(filter %system/etc/preloaded-classes,$(PRODUCT_COPY_FILES))))
+
+# Use the first dirty-image-objects file in PRODUCT_COPY_FILES.
+DIRTY_IMAGE_OBJECTS := $(call word-colon,1,$(firstword \
+    $(filter %system/etc/dirty-image-objects,$(PRODUCT_COPY_FILES))))
+
+define get-product-default-property
+$(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)
+DEX2OAT_IMAGE_XMX := $(call get-product-default-property,dalvik.vm.image-dex2oat-Xmx)
+DEX2OAT_XMS := $(call get-product-default-property,dalvik.vm.dex2oat-Xms)
+DEX2OAT_XMX := $(call get-product-default-property,dalvik.vm.dex2oat-Xmx)
+
+ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),mips mips64))
+# MIPS specific overrides.
+# For MIPS the ART image is loaded at a lower address. This causes issues
+# with the image overlapping with memory on the host cross-compiling and
+# building the image. We therefore limit the Xmx value. This isn't done
+# via a property as we want the larger Xmx value if we're running on a
+# MIPS device.
+DEX2OAT_XMX := 128m
+endif
+
+ifeq ($(WRITE_SOONG_VARIABLES),true)
+
+  $(call json_start)
+
+  $(call add_json_bool, DefaultNoStripping,                 $(filter nostripping,$(DEX_PREOPT_DEFAULT)))
+  $(call add_json_list, DisablePreoptModules,               $(DEXPREOPT_DISABLED_MODULES))
+  $(call add_json_bool, OnlyPreoptBootImageAndSystemServer, $(filter true,$(WITH_DEXPREOPT_BOOT_IMG_AND_SYSTEM_SERVER_ONLY)))
+  $(call add_json_bool, DontUncompressPrivAppsDex,          $(filter true,$(DONT_UNCOMPRESS_PRIV_APPS_DEXS)))
+  $(call add_json_list, ModulesLoadedByPrivilegedModules,   $(PRODUCT_LOADED_BY_PRIVILEGED_MODULES))
+  $(call add_json_bool, HasSystemOther,                     $(BOARD_USES_SYSTEM_OTHER_ODEX))
+  $(call add_json_list, PatternsOnSystemOther,              $(SYSTEM_OTHER_ODEX_FILTER))
+  $(call add_json_bool, DisableGenerateProfile,             $(filter false,$(WITH_DEX_PREOPT_GENERATE_PROFILE)))
+  $(call add_json_list, PreoptBootClassPathDexFiles,        $(DEXPREOPT_BOOTCLASSPATH_DEX_FILES))
+  $(call add_json_list, PreoptBootClassPathDexLocations,    $(DEXPREOPT_BOOTCLASSPATH_DEX_LOCATIONS))
+  $(call add_json_list, BootJars,                           $(PRODUCT_BOOT_JARS))
+  $(call add_json_list, PreoptBootJars,                     $(DEXPREOPT_BOOT_JARS_MODULES))
+  $(call add_json_list, SystemServerJars,                   $(PRODUCT_SYSTEM_SERVER_JARS))
+  $(call add_json_list, SystemServerApps,                   $(PRODUCT_SYSTEM_SERVER_APPS))
+  $(call add_json_list, SpeedApps,                          $(PRODUCT_DEXPREOPT_SPEED_APPS))
+  $(call add_json_list, PreoptFlags,                        $(PRODUCT_DEX_PREOPT_DEFAULT_FLAGS))
+  $(call add_json_str,  DefaultCompilerFilter,              $(PRODUCT_DEX_PREOPT_DEFAULT_COMPILER_FILTER))
+  $(call add_json_str,  SystemServerCompilerFilter,         $(PRODUCT_SYSTEM_SERVER_COMPILER_FILTER))
+  $(call add_json_bool, GenerateDmFiles,                    $(PRODUCT_DEX_PREOPT_GENERATE_DM_FILES))
+  $(call add_json_bool, NoDebugInfo,                        $(filter false,$(WITH_DEXPREOPT_DEBUG_INFO)))
+  $(call add_json_bool, AlwaysSystemServerDebugInfo,        $(filter true,$(PRODUCT_SYSTEM_SERVER_DEBUG_INFO)))
+  $(call add_json_bool, NeverSystemServerDebugInfo,         $(filter false,$(PRODUCT_SYSTEM_SERVER_DEBUG_INFO)))
+  $(call add_json_bool, AlwaysOtherDebugInfo,               $(filter true,$(PRODUCT_OTHER_JAVA_DEBUG_INFO)))
+  $(call add_json_bool, NeverOtherDebugInfo,                $(filter false,$(PRODUCT_OTHER_JAVA_DEBUG_INFO)))
+  $(call add_json_list, MissingUsesLibraries,               $(INTERNAL_PLATFORM_MISSING_USES_LIBRARIES))
+  $(call add_json_bool, IsEng,                              $(filter eng,$(TARGET_BUILD_VARIANT)))
+  $(call add_json_bool, SanitizeLite,                       $(SANITIZE_LITE))
+  $(call add_json_bool, DefaultAppImages,                   $(WITH_DEX_PREOPT_APP_IMAGE))
+  $(call add_json_str,  Dex2oatXmx,                         $(DEX2OAT_XMX))
+  $(call add_json_str,  Dex2oatXms,                         $(DEX2OAT_XMS))
+  $(call add_json_str,  EmptyDirectory,                     $(OUT_DIR)/empty)
+
+  $(call add_json_map,  DefaultDexPreoptImageLocation)
+  $(call add_json_str,  $(TARGET_ARCH), $(DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION))
+  ifdef TARGET_2ND_ARCH
+    $(call add_json_str, $(TARGET_2ND_ARCH), $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION))
+  endif
+  $(call end_json_map)
+
+  $(call add_json_map,  CpuVariant)
+  $(call add_json_str,  $(TARGET_ARCH), $(DEX2OAT_TARGET_CPU_VARIANT))
+  ifdef TARGET_2ND_ARCH
+    $(call add_json_str, $(TARGET_2ND_ARCH), $($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT))
+  endif
+  $(call end_json_map)
+
+  $(call add_json_map,  InstructionSetFeatures)
+  $(call add_json_str,  $(TARGET_ARCH), $(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES))
+  ifdef TARGET_2ND_ARCH
+    $(call add_json_str, $(TARGET_2ND_ARCH), $($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES))
+  endif
+  $(call end_json_map)
+
+  $(call add_json_map,  Tools)
+  $(call add_json_str,  Profman,                            $(PROFMAN))
+  $(call add_json_str,  Dex2oat,                            $(DEX2OAT))
+  $(call add_json_str,  Aapt,                               $(AAPT))
+  $(call add_json_str,  SoongZip,                           $(SOONG_ZIP))
+  $(call add_json_str,  Zip2zip,                            $(ZIP2ZIP))
+  $(call add_json_str,  VerifyUsesLibraries,                $(BUILD_SYSTEM)/verify_uses_libraries.sh)
+  $(call add_json_str,  ConstructContext,                   $(BUILD_SYSTEM)/construct_context.sh)
+  $(call end_json_map)
+
+  $(call json_end)
+
+  $(shell mkdir -p $(dir $(DEX_PREOPT_CONFIG)))
+  $(file >$(DEX_PREOPT_CONFIG).tmp,$(json_contents))
+
+  $(shell \
+    if ! cmp -s $(DEX_PREOPT_CONFIG).tmp $(DEX_PREOPT_CONFIG); then \
+      mv $(DEX_PREOPT_CONFIG).tmp $(DEX_PREOPT_CONFIG); \
+    else \
+      rm $(DEX_PREOPT_CONFIG).tmp; \
+    fi)
+endif
+
+# Dummy rule to create dexpreopt.config, it will already have been created
+# by the $(file) call above, but a rule needs to exist to keep the dangling
+# rule check happy.
+$(DEX_PREOPT_CONFIG):
+	@#empty
+
+DEXPREOPT_GEN_DEPS := \
+  $(PROFMAN) \
+  $(DEX2OAT) \
+  $(AAPT) \
+  $(SOONG_ZIP) \
+  $(ZIP2ZIP) \
+  $(BUILD_SYSTEM)/verify_uses_libraries.sh \
+  $(BUILD_SYSTEM)/construct_context.sh \
+
+DEXPREOPT_GEN_DEPS += $(DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME)
+ifdef TARGET_2ND_ARCH
+  ifneq ($(TARGET_TRANSLATE_2ND_ARCH),true)
+    DEXPREOPT_GEN_DEPS += $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME)
+  endif
+endif
diff --git a/core/dex_preopt_libart.mk b/core/dex_preopt_libart.mk
index 698034c..631db0a 100644
--- a/core/dex_preopt_libart.mk
+++ b/core/dex_preopt_libart.mk
@@ -3,77 +3,9 @@
 #
 ####################################
 
-# Default to debug version to help find bugs.
-# Set USE_DEX2OAT_DEBUG to false for only building non-debug versions.
-ifeq ($(USE_DEX2OAT_DEBUG),false)
-DEX2OAT := $(HOST_OUT_EXECUTABLES)/dex2oat$(HOST_EXECUTABLE_SUFFIX)
-else
-DEX2OAT := $(HOST_OUT_EXECUTABLES)/dex2oatd$(HOST_EXECUTABLE_SUFFIX)
-endif
-
-DEX2OAT_DEPENDENCY += $(DEX2OAT)
-
-# Use the first preloaded-classes file in PRODUCT_COPY_FILES.
-PRELOADED_CLASSES := $(call word-colon,1,$(firstword \
-    $(filter %system/etc/preloaded-classes,$(PRODUCT_COPY_FILES))))
-
-# Use the first dirty-image-objects file in PRODUCT_COPY_FILES.
-DIRTY_IMAGE_OBJECTS := $(call word-colon,1,$(firstword \
-    $(filter %system/etc/dirty-image-objects,$(PRODUCT_COPY_FILES))))
-
-define get-product-default-property
-$(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)
-DEX2OAT_IMAGE_XMX := $(call get-product-default-property,dalvik.vm.image-dex2oat-Xmx)
-DEX2OAT_XMS := $(call get-product-default-property,dalvik.vm.dex2oat-Xms)
-DEX2OAT_XMX := $(call get-product-default-property,dalvik.vm.dex2oat-Xmx)
-
-ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),mips mips64))
-# MIPS specific overrides.
-# For MIPS the ART image is loaded at a lower address. This causes issues
-# with the image overlapping with memory on the host cross-compiling and
-# building the image. We therefore limit the Xmx value. This isn't done
-# via a property as we want the larger Xmx value if we're running on a
-# MIPS device.
-DEX2OAT_XMX := 128m
-endif
-
 ########################################################################
 # The full system boot classpath
 
-# Returns the path to the .odex file
-# $(1): the arch name.
-# $(2): the full path (including file name) of the corresponding .jar or .apk.
-define get-odex-file-path
-$(dir $(2))oat/$(1)/$(basename $(notdir $(2))).odex
-endef
-
-# Returns the full path to the installed .odex file.
-# This handles BOARD_USES_SYSTEM_OTHER_ODEX to install odex files into another
-# partition.
-# $(1): the arch name.
-# $(2): the full install path (including file name) of the corresponding .apk.
-ifeq ($(BOARD_USES_SYSTEM_OTHER_ODEX),true)
-define get-odex-installed-file-path
-$(if $(call install-on-system-other, $(2)),
-  $(call get-odex-file-path,$(1),$(patsubst $(TARGET_OUT)/%,$(TARGET_OUT_SYSTEM_OTHER)/%,$(2))),
-  $(call get-odex-file-path,$(1),$(2)))
-endef
-else
-get-odex-installed-file-path = $(get-odex-file-path)
-endif
-
-# Returns the path to the image file (such as "/system/framework/<arch>/boot.art"
-# $(1): the arch name (such as "arm")
-# $(2): the image location (such as "/system/framework/boot.art")
-define get-image-file-path
-$(dir $(2))$(1)/$(notdir $(2))
-endef
-
 LIBART_TARGET_BOOT_JARS := $(DEXPREOPT_BOOT_JARS_MODULES)
 LIBART_TARGET_BOOT_DEX_LOCATIONS := $(foreach jar,$(LIBART_TARGET_BOOT_JARS),/$(DEXPREOPT_BOOT_JAR_DIR)/$(jar).jar)
 LIBART_TARGET_BOOT_DEX_FILES := $(foreach jar,$(LIBART_TARGET_BOOT_JARS),$(call intermediates-dir-for,JAVA_LIBRARIES,$(jar),,COMMON)/javalib.jar)
@@ -164,47 +96,3 @@
 	$(hide) ln -sf /$(DEXPREOPT_BOOT_JAR_DIR)/$(notdir $@) $(SECOND_ARCH_DIR)$(notdir $@)
 
 my_2nd_arch_prefix :=
-
-########################################################################
-# For a single jar or APK
-
-# $(1): the input .jar or .apk file
-# $(2): the output .odex file
-# In the case where LOCAL_ENFORCE_USES_LIBRARIES is true, PRIVATE_DEX2OAT_CLASS_LOADER_CONTEXT
-# contains the normalized path list of the libraries. This makes it easier to conditionally prepend
-# org.apache.http.legacy.impl based on the SDK level if required.
-define dex2oat-one-file
-$(hide) rm -f $(2)
-$(hide) mkdir -p $(dir $(2))
-stored_class_loader_context_libs=$(PRIVATE_DEX2OAT_STORED_CLASS_LOADER_CONTEXT_LIBS) && \
-class_loader_context_arg=--class-loader-context=$(PRIVATE_DEX2OAT_CLASS_LOADER_CONTEXT) && \
-class_loader_context=$(PRIVATE_DEX2OAT_CLASS_LOADER_CONTEXT) && \
-stored_class_loader_context_arg="" && \
-uses_library_names="$(PRIVATE_USES_LIBRARY_NAMES)" && \
-optional_uses_library_names="$(PRIVATE_OPTIONAL_USES_LIBRARY_NAMES)" && \
-aapt_binary="$(AAPT)" && \
-$(if $(filter true,$(PRIVATE_ENFORCE_USES_LIBRARIES)), \
-source build/make/core/verify_uses_libraries.sh "$(1)" && \
-source build/make/core/construct_context.sh "$(PRIVATE_CONDITIONAL_USES_LIBRARIES_HOST)" "$(PRIVATE_CONDITIONAL_USES_LIBRARIES_TARGET)" && \
-,) \
-ANDROID_LOG_TAGS="*:e" $(DEX2OAT) \
-	--runtime-arg -Xms$(DEX2OAT_XMS) --runtime-arg -Xmx$(DEX2OAT_XMX) \
-	$${class_loader_context_arg} \
-	$${stored_class_loader_context_arg} \
-	--boot-image=$(PRIVATE_DEX_PREOPT_IMAGE_LOCATION) \
-	--dex-file=$(1) \
-	--dex-location=$(PRIVATE_DEX_LOCATION) \
-	--oat-file=$(2) \
-	--android-root=$(PRODUCT_OUT)/system \
-	--instruction-set=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH) \
-	--instruction-set-variant=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT) \
-	--instruction-set-features=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) \
-	--no-generate-debug-info --generate-build-id \
-	--abort-on-hard-verifier-error \
-	--force-determinism \
-	--no-inline-from=core-oj.jar \
-	$(PRIVATE_DEX_PREOPT_FLAGS) \
-	$(PRIVATE_ART_FILE_PREOPT_FLAGS) \
-	$(PRIVATE_PROFILE_PREOPT_FLAGS) \
-	$(GLOBAL_DEXPREOPT_FLAGS)
-endef
diff --git a/core/dex_preopt_libart_boot.mk b/core/dex_preopt_libart_boot.mk
index 14955f0..47a8de8 100644
--- a/core/dex_preopt_libart_boot.mk
+++ b/core/dex_preopt_libart_boot.mk
@@ -20,8 +20,6 @@
 # 2ND_DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME=out/target/product/generic_x86_64/dex_bootjars/system/framework/x86/boot.art
 # 2ND_LIBART_BOOT_IMAGE=/system/framework/x86/boot.art
 
-$(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/boot.art
-$(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$($(my_2nd_arch_prefix)DEX2OAT_TARGET_ARCH)/boot.art
 $(my_2nd_arch_prefix)LIBART_BOOT_IMAGE_FILENAME := /$(DEXPREOPT_BOOT_JAR_DIR)/$($(my_2nd_arch_prefix)DEX2OAT_TARGET_ARCH)/boot.art
 
 # The .oat with symbols
@@ -86,14 +84,19 @@
 $($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME): PRIVATE_BOOT_IMAGE_FLAGS := $(my_boot_image_flags)
 $($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME): PRIVATE_2ND_ARCH_VAR_PREFIX := $(my_2nd_arch_prefix)
 # Use dex2oat debug version for better error reporting
+# Pass --avoid-storing-invocation to make the output deterministics between
+# different products that may have different paths on the command line.
 $($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME) : $(LIBART_TARGET_BOOT_DEX_FILES) $(PRELOADED_CLASSES) $(DIRTY_IMAGE_OBJECTS) $(DEX2OAT_DEPENDENCY) $(my_out_boot_image_profile_location)
 	@echo "target dex2oat: $@"
 	@mkdir -p $(dir $@)
 	@mkdir -p $(dir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_TARGET_BOOT_OAT_UNSTRIPPED))
-	@rm -f $(dir $@)/*.art $(dir $@)/*.oat
+	@rm -f $(dir $@)/*.art $(dir $@)/*.oat $(dir $@)/*.invocation
 	@rm -f $(dir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_TARGET_BOOT_OAT_UNSTRIPPED))/*.art
 	@rm -f $(dir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_TARGET_BOOT_OAT_UNSTRIPPED))/*.oat
+	@rm -f $(dir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_TARGET_BOOT_OAT_UNSTRIPPED))/*.invocation
 	$(hide) $(DEX2OAT_BOOT_IMAGE_LOG_TAGS) $(DEX2OAT) --runtime-arg -Xms$(DEX2OAT_IMAGE_XMS) \
+		--avoid-storing-invocation \
+		--write-invocation-to=$(patsubst %.art,%.invocation,$@) \
 		--runtime-arg -Xmx$(DEX2OAT_IMAGE_XMX) \
 		$(PRIVATE_BOOT_IMAGE_FLAGS) \
 		$(addprefix --dex-file=,$(LIBART_TARGET_BOOT_DEX_FILES)) \
@@ -110,8 +113,7 @@
 		--android-root=$(PRODUCT_OUT)/system \
 		--no-inline-from=core-oj.jar \
 		--abort-on-hard-verifier-error \
-		--abort-on-soft-verifier-error \
-		$(PRODUCT_DEX_PREOPT_BOOT_FLAGS) $(GLOBAL_DEXPREOPT_FLAGS) $(ART_BOOT_IMAGE_EXTRA_ARGS) \
+		$(PRODUCT_DEX_PREOPT_BOOT_FLAGS) $(ART_BOOT_IMAGE_EXTRA_ARGS) \
 		|| ( echo "$(DEX2OAT_FAILURE_MESSAGE)" ; false )
 
 endif
diff --git a/core/dex_preopt_odex_install.mk b/core/dex_preopt_odex_install.mk
index 6a892e2..69790cb 100644
--- a/core/dex_preopt_odex_install.mk
+++ b/core/dex_preopt_odex_install.mk
@@ -3,7 +3,7 @@
 # Output variables: LOCAL_DEX_PREOPT, LOCAL_UNCOMPRESS_DEX, built_odex,
 #                   dexpreopt_boot_jar_module
 
-ifeq (true,$(LOCAL_PREFER_INTEGRITY))
+ifeq (true,$(LOCAL_PREFER_CODE_INTEGRITY))
   LOCAL_UNCOMPRESS_DEX := true
 else
   LOCAL_UNCOMPRESS_DEX :=
@@ -25,24 +25,6 @@
 LOCAL_DEX_PREOPT := $(strip $(LOCAL_DEX_PREOPT))
 ifndef LOCAL_DEX_PREOPT # LOCAL_DEX_PREOPT undefined
   LOCAL_DEX_PREOPT := $(DEX_PREOPT_DEFAULT)
-
-  ifeq ($(filter $(TARGET_OUT)/%,$(my_module_path)),) # Not installed to system.img.
-    # Default to nostripping for non system preopt (enables preopt).
-    # Don't strip in case the oat/vdex version in system ROM doesn't match the one in other
-    # partitions. It needs to be able to fall back to the APK for that case.
-    LOCAL_DEX_PREOPT := nostripping
-  endif
-
-  ifneq (,$(LOCAL_APK_LIBRARIES)) # LOCAL_APK_LIBRARIES not empty
-    LOCAL_DEX_PREOPT := nostripping
-  endif
-endif
-
-ifeq (nostripping,$(LOCAL_DEX_PREOPT))
-  LOCAL_DEX_PREOPT := true
-  LOCAL_STRIP_DEX :=
-else
-  LOCAL_STRIP_DEX := true
 endif
 
 ifeq (false,$(LOCAL_DEX_PREOPT))
@@ -90,38 +72,8 @@
   endif
 endif
 
-ifeq ($(LOCAL_DEX_PREOPT),true)
-  # Don't strip with dexes we explicitly uncompress (dexopt will not store the dex code).
-  ifeq ($(LOCAL_UNCOMPRESS_DEX),true)
-    LOCAL_STRIP_DEX :=
-  endif  # LOCAL_UNCOMPRESS_DEX
-
-  # system_other isn't there for an OTA, so don't strip
-  # if module is on system, and odex is on system_other.
-  ifeq ($(BOARD_USES_SYSTEM_OTHER_ODEX),true)
-    ifneq ($(call install-on-system-other, $(my_module_path)),)
-      LOCAL_STRIP_DEX :=
-    endif  # install-on-system-other
-  endif  # BOARD_USES_SYSTEM_OTHER_ODEX
-
-  # We also don't strip if all dexs are uncompressed (dexopt will not store the dex code),
-  # but that requires to inspect the source file, which is too early at this point (as we
-  # don't know if the source file will actually be used).
-  # See dexpreopt-remove-classes.dex.
-endif  # LOCAL_DEX_PREOPT
-
-built_odex :=
-built_vdex :=
-built_art :=
-installed_odex :=
-installed_vdex :=
-installed_art :=
-built_installed_odex :=
-built_installed_vdex :=
-built_installed_art :=
 my_process_profile :=
 my_profile_is_text_listing :=
-my_generate_dm :=
 
 ifeq (false,$(WITH_DEX_PREOPT_GENERATE_PROFILE))
   LOCAL_DEX_PREOPT_GENERATE_PROFILE := false
@@ -135,7 +87,7 @@
 
   ifneq (,$(wildcard $(LOCAL_DEX_PREOPT_PROFILE)))
     my_process_profile := true
-    my_profile_is_text_listing := false
+    my_profile_is_text_listing :=
   endif
 else
   my_process_profile := $(LOCAL_DEX_PREOPT_GENERATE_PROFILE)
@@ -144,273 +96,72 @@
 endif
 
 ifeq (true,$(my_process_profile))
-
-  ifeq (,$(LOCAL_DEX_PREOPT_APP_IMAGE))
-    LOCAL_DEX_PREOPT_APP_IMAGE := true
-  endif
-
   ifndef LOCAL_DEX_PREOPT_PROFILE
     $(call pretty-error,Must have specified class listing (LOCAL_DEX_PREOPT_PROFILE))
   endif
   ifeq (,$(dex_preopt_profile_src_file))
     $(call pretty-error, Internal error: dex_preopt_profile_src_file must be set)
   endif
-  my_built_profile := $(dir $(LOCAL_BUILT_MODULE))/profile.prof
-  my_dex_location := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
-  # Remove compressed APK extension.
-  my_dex_location := $(patsubst %.gz,%,$(my_dex_location))
-  $(my_built_profile): PRIVATE_BUILT_MODULE := $(dex_preopt_profile_src_file)
-  $(my_built_profile): PRIVATE_DEX_LOCATION := $(my_dex_location)
-  $(my_built_profile): PRIVATE_SOURCE_CLASSES := $(LOCAL_DEX_PREOPT_PROFILE)
-  $(my_built_profile): $(LOCAL_DEX_PREOPT_PROFILE)
-  $(my_built_profile): $(PROFMAN)
-  $(my_built_profile): $(dex_preopt_profile_src_file)
-  ifeq (true,$(my_profile_is_text_listing))
-    # The profile is a test listing of classes (used for framework jars).
-    # We need to generate the actual binary profile before being able to compile.
-    $(my_built_profile):
-	$(hide) mkdir -p $(dir $@)
-	ANDROID_LOG_TAGS="*:e" $(PROFMAN) \
-		--create-profile-from=$(PRIVATE_SOURCE_CLASSES) \
-		--apk=$(PRIVATE_BUILT_MODULE) \
-		--dex-location=$(PRIVATE_DEX_LOCATION) \
-		--reference-profile-file=$@
-  else
-    # The profile is binary profile (used for apps). Run it through profman to
-    # ensure the profile keys match the apk.
-    $(my_built_profile):
-	$(hide) mkdir -p $(dir $@)
-	touch $@
-	ANDROID_LOG_TAGS="*:i" $(PROFMAN) \
-	  --copy-and-update-profile-key \
-		--profile-file=$(PRIVATE_SOURCE_CLASSES) \
-		--apk=$(PRIVATE_BUILT_MODULE) \
-		--dex-location=$(PRIVATE_DEX_LOCATION) \
-		--reference-profile-file=$@ \
-	|| echo "Profile out of date for $(PRIVATE_BUILT_MODULE)"
-  endif
-
-  my_profile_is_text_listing :=
-  dex_preopt_profile_src_file :=
-
-  # Remove compressed APK extension.
-  my_installed_profile := $(patsubst %.gz,%,$(LOCAL_INSTALLED_MODULE)).prof
-
-  # my_installed_profile := $(LOCAL_INSTALLED_MODULE).prof
-  $(eval $(call copy-one-file,$(my_built_profile),$(my_installed_profile)))
-  build_installed_profile:=$(my_built_profile):$(my_installed_profile)
-else
-  build_installed_profile:=
-  my_installed_profile :=
 endif
 
+# If LOCAL_ENFORCE_USES_LIBRARIES is not set, default to true if either of LOCAL_USES_LIBRARIES or
+# LOCAL_OPTIONAL_USES_LIBRARIES are specified.
+ifeq (,$(LOCAL_ENFORCE_USES_LIBRARIES))
+  # Will change the default to true unconditionally in the future.
+  ifneq (,$(LOCAL_OPTIONAL_USES_LIBRARIES))
+    LOCAL_ENFORCE_USES_LIBRARIES := true
+  endif
+  ifneq (,$(LOCAL_USES_LIBRARIES))
+    LOCAL_ENFORCE_USES_LIBRARIES := true
+  endif
+endif
+
+my_dexpreopt_archs :=
+
 ifdef LOCAL_DEX_PREOPT
-
-  dexpreopt_boot_jar_module := $(filter $(DEXPREOPT_BOOT_JARS_MODULES),$(LOCAL_MODULE))
-
-  ifdef dexpreopt_boot_jar_module
-    # For libart, the boot jars' odex files are replaced by $(DEFAULT_DEX_PREOPT_INSTALLED_IMAGE).
-    # We use this installed_odex trick to get boot.art installed.
-    installed_odex := $(DEFAULT_DEX_PREOPT_INSTALLED_IMAGE)
-    # Append the odex for the 2nd arch if we have one.
-    installed_odex += $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_INSTALLED_IMAGE)
-  else  # boot jar
-    ifeq ($(LOCAL_MODULE_CLASS),JAVA_LIBRARIES)
-
-      my_module_multilib := $(LOCAL_MULTILIB)
-      # If the module is not an SDK library and it's a system server jar, only preopt the primary arch.
-      my_filtered_lib_name := $(patsubst %.impl,%,$(LOCAL_MODULE))
-      ifeq (,$(filter $(JAVA_SDK_LIBRARIES),$(my_filtered_lib_name)))
-        # For a Java library, by default we build odex for both 1st arch and 2nd arch.
-        # But it can be overridden with "LOCAL_MULTILIB := first".
-        ifneq (,$(filter $(PRODUCT_SYSTEM_SERVER_JARS),$(LOCAL_MODULE)))
-          # For system server jars, we build for only "first".
-          my_module_multilib := first
-        endif
-      endif
-
-      # Only preopt primary arch for translated arch since there is only an image there.
-      ifeq ($(TARGET_TRANSLATE_2ND_ARCH),true)
+  ifeq ($(LOCAL_MODULE_CLASS),JAVA_LIBRARIES)
+    my_module_multilib := $(LOCAL_MULTILIB)
+    # If the module is not an SDK library and it's a system server jar, only preopt the primary arch.
+    my_filtered_lib_name := $(patsubst %.impl,%,$(LOCAL_MODULE))
+    ifeq (,$(filter $(JAVA_SDK_LIBRARIES),$(my_filtered_lib_name)))
+      # For a Java library, by default we build odex for both 1st arch and 2nd arch.
+      # But it can be overridden with "LOCAL_MULTILIB := first".
+      ifneq (,$(filter $(PRODUCT_SYSTEM_SERVER_JARS),$(LOCAL_MODULE)))
+        # For system server jars, we build for only "first".
         my_module_multilib := first
       endif
-
-      # #################################################
-      # Odex for the 1st arch
-      my_2nd_arch_prefix :=
-      include $(BUILD_SYSTEM)/setup_one_odex.mk
-      # #################################################
-      # Odex for the 2nd arch
-      ifdef TARGET_2ND_ARCH
-        ifneq ($(TARGET_TRANSLATE_2ND_ARCH),true)
-          ifneq (first,$(my_module_multilib))
-            my_2nd_arch_prefix := $(TARGET_2ND_ARCH_VAR_PREFIX)
-            include $(BUILD_SYSTEM)/setup_one_odex.mk
-          endif  # my_module_multilib is not first.
-        endif  # TARGET_TRANSLATE_2ND_ARCH not true
-      endif  # TARGET_2ND_ARCH
-      # #################################################
-    else  # must be APPS
-      # The preferred arch
-      my_2nd_arch_prefix := $(LOCAL_2ND_ARCH_VAR_PREFIX)
-      # Save the module multilib since setup_one_odex modifies it.
-      saved_my_module_multilib := $(my_module_multilib)
-      include $(BUILD_SYSTEM)/setup_one_odex.mk
-      my_module_multilib := $(saved_my_module_multilib)
-      ifdef TARGET_2ND_ARCH
-        ifeq ($(my_module_multilib),both)
-          # The non-preferred arch
-          my_2nd_arch_prefix := $(if $(LOCAL_2ND_ARCH_VAR_PREFIX),,$(TARGET_2ND_ARCH_VAR_PREFIX))
-          include $(BUILD_SYSTEM)/setup_one_odex.mk
-        endif  # LOCAL_MULTILIB is both
-      endif  # TARGET_2ND_ARCH
-    endif  # LOCAL_MODULE_CLASS
-  endif  # boot jar
-
-  built_odex := $(strip $(built_odex))
-  built_vdex := $(strip $(built_vdex))
-  built_art := $(strip $(built_art))
-  installed_odex := $(strip $(installed_odex))
-  installed_vdex := $(strip $(installed_vdex))
-  installed_art := $(strip $(installed_art))
-
-  ifdef built_odex
-    ifeq (true,$(my_process_profile))
-      $(built_odex): $(my_built_profile)
-      $(built_odex): PRIVATE_PROFILE_PREOPT_FLAGS := --profile-file=$(my_built_profile)
-    else
-      $(built_odex): PRIVATE_PROFILE_PREOPT_FLAGS :=
     endif
 
-    ifndef LOCAL_DEX_PREOPT_FLAGS
-      LOCAL_DEX_PREOPT_FLAGS := $(DEXPREOPT.$(TARGET_PRODUCT).$(LOCAL_MODULE).CONFIG)
-      ifndef LOCAL_DEX_PREOPT_FLAGS
-        LOCAL_DEX_PREOPT_FLAGS := $(PRODUCT_DEX_PREOPT_DEFAULT_FLAGS)
-      endif
+    # Only preopt primary arch for translated arch since there is only an image there.
+    ifeq ($(TARGET_TRANSLATE_2ND_ARCH),true)
+      my_module_multilib := first
     endif
 
-    my_system_server_compiler_filter := $(PRODUCT_SYSTEM_SERVER_COMPILER_FILTER)
-    ifeq (,$(my_system_server_compiler_filter))
-      my_system_server_compiler_filter := speed
-    endif
-
-    my_default_compiler_filter := $(PRODUCT_DEX_PREOPT_DEFAULT_COMPILER_FILTER)
-    ifeq (,$(my_default_compiler_filter))
-      # If no default compiler filter is specified, default to 'quicken' to save on storage.
-      my_default_compiler_filter := quicken
-    endif
-
-    ifeq (,$(filter --compiler-filter=%, $(LOCAL_DEX_PREOPT_FLAGS)))
-      ifneq (,$(filter $(PRODUCT_SYSTEM_SERVER_JARS),$(LOCAL_MODULE)))
-        # Jars of system server, use the product option if it is set, speed otherwise.
-        LOCAL_DEX_PREOPT_FLAGS += --compiler-filter=$(my_system_server_compiler_filter)
-      else
-        ifneq (,$(filter $(PRODUCT_DEXPREOPT_SPEED_APPS) $(PRODUCT_SYSTEM_SERVER_APPS),$(LOCAL_MODULE)))
-          # Apps loaded into system server, and apps the product default to being compiled with the
-          # 'speed' compiler filter.
-          LOCAL_DEX_PREOPT_FLAGS += --compiler-filter=speed
-        else
-          ifeq (true,$(my_process_profile))
-            # For non system server jars, use speed-profile when we have a profile.
-            LOCAL_DEX_PREOPT_FLAGS += --compiler-filter=speed-profile
-          else
-            LOCAL_DEX_PREOPT_FLAGS += --compiler-filter=$(my_default_compiler_filter)
-          endif
-        endif
-      endif
-    endif
-
-    my_generate_dm := $(PRODUCT_DEX_PREOPT_GENERATE_DM_FILES)
-    ifeq (,$(filter $(LOCAL_DEX_PREOPT_FLAGS),--compiler-filter=verify))
-      # Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
-      my_generate_dm := false
-    endif
-
-    # No reason to use a dm file if the dex is already uncompressed.
-    ifeq ($(LOCAL_UNCOMPRESS_DEX),true)
-      my_generate_dm := false
-    endif
-
-    ifeq (true,$(my_generate_dm))
-      LOCAL_DEX_PREOPT_FLAGS += --copy-dex-files=false
-      LOCAL_DEX_PREOPT := true
-      LOCAL_STRIP_DEX :=
-      my_built_dm := $(dir $(LOCAL_BUILT_MODULE))generated.dm
-      my_installed_dm := $(patsubst %.apk,%,$(LOCAL_INSTALLED_MODULE)).dm
-      my_copied_vdex := $(dir $(LOCAL_BUILT_MODULE))primary.vdex
-      $(eval $(call copy-one-file,$(built_vdex),$(my_copied_vdex)))
-      $(my_built_dm): PRIVATE_INPUT_VDEX := $(my_copied_vdex)
-      $(my_built_dm): $(my_copied_vdex) $(ZIPTIME)
-	$(hide) mkdir -p $(dir $@)
-	$(hide) rm -f $@
-	$(hide) zip -qD -j -X -9 $@ $(PRIVATE_INPUT_VDEX)
-	$(ZIPTIME) $@
-      $(eval $(call copy-one-file,$(my_built_dm),$(my_installed_dm)))
-    endif
-
-    # By default, emit debug info.
-    my_dexpreopt_debug_info := true
-    # If the global setting suppresses mini-debug-info, disable it.
-    ifeq (false,$(WITH_DEXPREOPT_DEBUG_INFO))
-      my_dexpreopt_debug_info := false
-    endif
-
-    # PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
-    # PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
-    ifneq (,$(filter $(PRODUCT_SYSTEM_SERVER_JARS),$(LOCAL_MODULE)))
-      ifeq (true,$(PRODUCT_SYSTEM_SERVER_DEBUG_INFO))
-        my_dexpreopt_debug_info := true
-      else ifeq (false,$(PRODUCT_SYSTEM_SERVER_DEBUG_INFO))
-        my_dexpreopt_debug_info := false
-      endif
-    else
-      ifeq (true,$(PRODUCT_OTHER_JAVA_DEBUG_INFO))
-        my_dexpreopt_debug_info := true
-      else ifeq (false,$(PRODUCT_OTHER_JAVA_DEBUG_INFO))
-        my_dexpreopt_debug_info := false
-      endif
-    endif
-
-    # Never enable on eng.
-    ifeq (eng,$(filter eng, $(TARGET_BUILD_VARIANT)))
-      my_dexpreopt_debug_info := false
-    endif
-
-    # Add dex2oat flag for debug-info/no-debug-info.
-    ifeq (true,$(my_dexpreopt_debug_info))
-      LOCAL_DEX_PREOPT_FLAGS += --generate-mini-debug-info
-    else ifeq (false,$(my_dexpreopt_debug_info))
-      LOCAL_DEX_PREOPT_FLAGS += --no-generate-mini-debug-info
-    endif
-
-    # Set the compiler reason to 'prebuilt' to identify the oat files produced
-    # during the build, as opposed to compiled on the device.
-    LOCAL_DEX_PREOPT_FLAGS += --compilation-reason=prebuilt
-
-    $(built_odex): PRIVATE_DEX_PREOPT_FLAGS := $(LOCAL_DEX_PREOPT_FLAGS)
-    $(built_vdex): $(built_odex)
-    $(built_art): $(built_odex)
-  endif
-
-  ifneq (true,$(my_generate_dm))
-    # Add the installed_odex to the list of installed files for this module if we aren't generating a
-    # dm file.
-    ALL_MODULES.$(my_register_name).INSTALLED += $(installed_odex)
-    ALL_MODULES.$(my_register_name).INSTALLED += $(installed_vdex)
-    ALL_MODULES.$(my_register_name).INSTALLED += $(installed_art)
-
-    ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(built_installed_odex)
-    ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(built_installed_vdex)
-    ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(built_installed_art)
-
-    # Make sure to install the .odex and .vdex when you run "make <module_name>"
-    $(my_all_targets): $(installed_odex) $(installed_vdex) $(installed_art)
-  else
-    ALL_MODULES.$(my_register_name).INSTALLED += $(my_installed_dm)
-    ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(my_built_dm) $(my_installed_dm)
-
-    # Make sure to install the .dm when you run "make <module_name>"
-    $(my_all_targets): $(installed_dm)
-  endif
+    # #################################################
+    # Odex for the 1st arch
+    my_dexpreopt_archs += $(TARGET_ARCH)
+    # Odex for the 2nd arch
+    ifdef TARGET_2ND_ARCH
+      ifneq ($(TARGET_TRANSLATE_2ND_ARCH),true)
+        ifneq (first,$(my_module_multilib))
+          my_dexpreopt_archs += $(TARGET_2ND_ARCH)
+        endif  # my_module_multilib is not first.
+      endif  # TARGET_TRANSLATE_2ND_ARCH not true
+    endif  # TARGET_2ND_ARCH
+    # #################################################
+  else  # must be APPS
+    # The preferred arch
+    # Save the module multilib since setup_one_odex modifies it.
+    my_2nd_arch_prefix := $(LOCAL_2ND_ARCH_VAR_PREFIX)
+    my_dexpreopt_archs += $(TARGET_$(my_2nd_arch_prefix)ARCH)
+    ifdef TARGET_2ND_ARCH
+      ifeq ($(my_module_multilib),both)
+        # The non-preferred arch
+        my_2nd_arch_prefix := $(if $(LOCAL_2ND_ARCH_VAR_PREFIX),,$(TARGET_2ND_ARCH_VAR_PREFIX))
+        my_dexpreopt_archs += $(TARGET_$(my_2nd_arch_prefix)ARCH)
+      endif  # LOCAL_MULTILIB is both
+    endif  # TARGET_2ND_ARCH
+  endif  # LOCAL_MODULE_CLASS
 
   # Record dex-preopt config.
   DEXPREOPT.$(LOCAL_MODULE).DEX_PREOPT := $(LOCAL_DEX_PREOPT)
@@ -419,17 +170,104 @@
   DEXPREOPT.$(LOCAL_MODULE).PRIVILEGED_MODULE := $(LOCAL_PRIVILEGED_MODULE)
   DEXPREOPT.$(LOCAL_MODULE).VENDOR_MODULE := $(LOCAL_VENDOR_MODULE)
   DEXPREOPT.$(LOCAL_MODULE).TARGET_ARCH := $(LOCAL_MODULE_TARGET_ARCH)
-  DEXPREOPT.$(LOCAL_MODULE).INSTALLED := $(installed_odex)
   DEXPREOPT.$(LOCAL_MODULE).INSTALLED_STRIPPED := $(LOCAL_INSTALLED_MODULE)
   DEXPREOPT.MODULES.$(LOCAL_MODULE_CLASS) := $(sort \
     $(DEXPREOPT.MODULES.$(LOCAL_MODULE_CLASS)) $(LOCAL_MODULE))
 
+  $(call json_start)
+
+  $(call add_json_str,  Name,                          $(LOCAL_MODULE))
+  $(call add_json_str,  DexLocation,                   $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE)))
+  $(call add_json_str,  BuildPath,                     $(LOCAL_BUILT_MODULE))
+  $(call add_json_str,  DexPath,                       $$1)
+  $(call add_json_str,  ExtrasOutputPath,              $$2)
+  $(call add_json_bool, PreferCodeIntegrity,           $(filter true,$(LOCAL_PREFER_CODE_INTEGRITY)))
+  $(call add_json_bool, Privileged,                    $(filter true,$(LOCAL_PRIVILEGED_MODULE)))
+  $(call add_json_bool, UncompressedDex,               $(filter true,$(LOCAL_UNCOMPRESS_DEX)))
+  $(call add_json_bool, HasApkLibraries,               $(LOCAL_APK_LIBRARIES))
+  $(call add_json_list, PreoptFlags,                   $(LOCAL_DEX_PREOPT_FLAGS))
+  $(call add_json_str,  ProfileClassListing,           $(if $(my_process_profile),$(LOCAL_DEX_PREOPT_PROFILE)))
+  $(call add_json_bool, ProfileIsTextListing,          $(my_profile_is_text_listing))
+  $(call add_json_bool, EnforceUsesLibraries,          $(LOCAL_ENFORCE_USES_LIBRARIES))
+  $(call add_json_list, OptionalUsesLibraries,         $(LOCAL_OPTIONAL_USES_LIBRARIES))
+  $(call add_json_list, UsesLibraries,                 $(LOCAL_USES_LIBRARIES))
+  $(call add_json_map,  LibraryPaths)
+  $(foreach lib,$(sort $(LOCAL_USES_LIBRARIES) $(LOCAL_OPTIONAL_USES_LIBRARIES) org.apache.http.legacy.impl android.hidl.base-V1.0-java android.hidl.manager-V1.0-java),\
+    $(call add_json_str, $(lib), $(call intermediates-dir-for,JAVA_LIBRARIES,$(lib),,COMMON)/javalib.jar))
+  $(call end_json_map)
+  $(call add_json_list, Archs,                         $(my_dexpreopt_archs))
+  $(call add_json_str,  DexPreoptImageLocation,        $(LOCAL_DEX_PREOPT_IMAGE_LOCATION))
+  $(call add_json_bool, PreoptExtractedApk,            $(my_preopt_for_extracted_apk))
+  $(call add_json_bool, NoCreateAppImage,              $(filter false,$(LOCAL_DEX_PREOPT_APP_IMAGE)))
+  $(call add_json_bool, ForceCreateAppImage,           $(filter true,$(LOCAL_DEX_PREOPT_APP_IMAGE)))
+  $(call add_json_bool, PresignedPrebuilt,             $(filter PRESIGNED,$(LOCAL_CERTIFICATE)))
+
+  $(call add_json_bool, NoStripping,                   $(filter nostripping,$(LOCAL_DEX_PREOPT)))
+  $(call add_json_str,  StripInputPath,                $$1)
+  $(call add_json_str,  StripOutputPath,               $$2)
+
+  $(call json_end)
+
+  my_dexpreopt_config := $(intermediates)/dexpreopt.config
+  my_dexpreopt_script := $(intermediates)/dexpreopt.sh
+  my_strip_script := $(intermediates)/strip.sh
+  my_dexpreopt_zip := $(intermediates)/dexpreopt.zip
+
+  $(my_dexpreopt_config): PRIVATE_MODULE := $(LOCAL_MODULE)
+  $(my_dexpreopt_config): PRIVATE_CONTENTS := $(json_contents)
+  $(my_dexpreopt_config):
+	@echo "$(PRIVATE_MODULE) dexpreopt.config"
+	echo -e -n '$(subst $(newline),\n,$(subst ','\'',$(subst \,\\,$(PRIVATE_CONTENTS))))' > $@
+
+  .KATI_RESTAT: $(my_dexpreopt_script) $(my_strip_script)
+  $(my_dexpreopt_script): PRIVATE_MODULE := $(LOCAL_MODULE)
+  $(my_dexpreopt_script): PRIVATE_GLOBAL_CONFIG := $(PRODUCT_OUT)/dexpreopt.config
+  $(my_dexpreopt_script): PRIVATE_MODULE_CONFIG := $(my_dexpreopt_config)
+  $(my_dexpreopt_script): PRIVATE_STRIP_SCRIPT := $(my_strip_script)
+  $(my_dexpreopt_script): .KATI_IMPLICIT_OUTPUTS := $(my_strip_script)
+  $(my_dexpreopt_script): $(DEXPREOPT_GEN)
+  $(my_dexpreopt_script): $(my_dexpreopt_config) $(PRODUCT_OUT)/dexpreopt.config
+	@echo "$(PRIVATE_MODULE) dexpreopt gen"
+	$(DEXPREOPT_GEN) -global $(PRIVATE_GLOBAL_CONFIG) -module $(PRIVATE_MODULE_CONFIG) \
+	-dexpreopt_script $@ -strip_script $(PRIVATE_STRIP_SCRIPT)
+
+  my_dexpreopt_deps := $(my_dex_jar)
+  my_dexpreopt_deps += $(if $(my_process_profile),$(LOCAL_DEX_PREOPT_PROFILE))
+  my_dexpreopt_deps += \
+    $(foreach lib,$(sort $(LOCAL_USES_LIBRARIES) $(LOCAL_OPTIONAL_USES_LIBRARIES) org.apache.http.legacy.impl android.hidl.base-V1.0-java android.hidl.manager-V1.0-java),\
+      $(call intermediates-dir-for,JAVA_LIBRARIES,$(lib),,COMMON)/javalib.jar)
+  my_dexpreopt_deps += $(LOCAL_DEX_PREOPT_IMAGE_LOCATION)
+  # TODO: default boot images
+
+  $(my_dexpreopt_zip): PRIVATE_MODULE := $(LOCAL_MODULE)
+  $(my_dexpreopt_zip): $(my_dexpreopt_deps)
+  $(my_dexpreopt_zip): | $(DEXPREOPT_GEN_DEPS)
+  $(my_dexpreopt_zip): .KATI_DEPFILE := $(my_dexpreopt_zip).d
+  $(my_dexpreopt_zip): PRIVATE_DEX := $(my_dex_jar)
+  $(my_dexpreopt_zip): PRIVATE_SCRIPT := $(my_dexpreopt_script)
+  $(my_dexpreopt_zip): $(my_dexpreopt_script)
+	@echo "$(PRIVATE_MODULE) dexpreopt"
+	bash $(PRIVATE_SCRIPT) $(PRIVATE_DEX) $@
+
+  ifdef LOCAL_POST_INSTALL_CMD
+    # Add a shell command separator
+    LOCAL_POST_INSTALL_CMD += &&
+  endif
+
+  LOCAL_POST_INSTALL_CMD += \
+    for i in $$(zipinfo -1 $(my_dexpreopt_zip)); \
+      do mkdir -p $(PRODUCT_OUT)/$$(dirname $$i); \
+    done && \
+    ( unzip -qo -d $(PRODUCT_OUT) $(my_dexpreopt_zip) 2>&1 | grep -v "zipfile is empty"; exit $${PIPESTATUS[0]} ) || \
+      ( code=$$?; if [ $$code -ne 0 -a $$code -ne 1 ]; then exit $$code; fi )
+
+  $(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD := $(LOCAL_POST_INSTALL_CMD)
+  $(LOCAL_INSTALLED_MODULE): $(my_dexpreopt_zip)
+
+  $(my_all_targets): $(my_dexpreopt_zip)
+
+  my_dexpreopt_config :=
+  my_dexpreopt_script :=
+  my_strip_script :=
+  my_dexpreopt_zip :=
 endif # LOCAL_DEX_PREOPT
-
-# Profile doesn't depend on LOCAL_DEX_PREOPT.
-ALL_MODULES.$(my_register_name).INSTALLED += $(my_installed_profile)
-ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(build_installed_profile)
-
-my_process_profile :=
-
-$(my_all_targets): $(my_installed_profile)
diff --git a/core/executable_internal.mk b/core/executable_internal.mk
index 70b2ea8..c28c144 100644
--- a/core/executable_internal.mk
+++ b/core/executable_internal.mk
@@ -36,6 +36,11 @@
 endif
 
 # Define PRIVATE_ variables from global vars
+ifeq ($(LOCAL_NO_LIBCRT_BUILTINS),true)
+my_target_libcrt_builtins :=
+else
+my_target_libcrt_builtins := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)LIBCRT_BUILTINS)
+endif
 ifeq ($(LOCAL_NO_LIBGCC),true)
 my_target_libgcc :=
 else
@@ -60,6 +65,7 @@
 my_target_crtbegin_static_o := $(wildcard $(my_ndk_sysroot_lib)/crtbegin_static.o)
 my_target_crtend_o := $(wildcard $(my_ndk_sysroot_lib)/crtend_android.o)
 endif
+$(linked_module): PRIVATE_TARGET_LIBCRT_BUILTINS := $(my_target_libcrt_builtins)
 $(linked_module): PRIVATE_TARGET_LIBGCC := $(my_target_libgcc)
 $(linked_module): PRIVATE_TARGET_LIBATOMIC := $(my_target_libatomic)
 $(linked_module): PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O := $(my_target_crtbegin_dynamic_o)
@@ -68,11 +74,11 @@
 $(linked_module): PRIVATE_POST_LINK_CMD := $(LOCAL_POST_LINK_CMD)
 
 ifeq ($(LOCAL_FORCE_STATIC_EXECUTABLE),true)
-$(linked_module): $(my_target_crtbegin_static_o) $(all_objects) $(all_libraries) $(my_target_crtend_o) $(my_target_libgcc) $(my_target_libatomic)
+$(linked_module): $(my_target_crtbegin_static_o) $(all_objects) $(all_libraries) $(my_target_crtend_o) $(my_target_libcrt_builtins) $(my_target_libgcc) $(my_target_libatomic)
 	$(transform-o-to-static-executable)
 	$(PRIVATE_POST_LINK_CMD)
 else
-$(linked_module): $(my_target_crtbegin_dynamic_o) $(all_objects) $(all_libraries) $(my_target_crtend_o) $(my_target_libgcc) $(my_target_libatomic)
+$(linked_module): $(my_target_crtbegin_dynamic_o) $(all_objects) $(all_libraries) $(my_target_crtend_o) $(my_target_libcrt_builtins) $(my_target_libgcc) $(my_target_libatomic)
 	$(transform-o-to-executable)
 	$(PRIVATE_POST_LINK_CMD)
 endif
diff --git a/core/generate_enforce_rro.mk b/core/generate_enforce_rro.mk
index 62a8c8d..c88c779 100644
--- a/core/generate_enforce_rro.mk
+++ b/core/generate_enforce_rro.mk
@@ -27,4 +27,10 @@
 LOCAL_AAPT_FLAGS += --auto-add-overlay
 LOCAL_RESOURCE_DIR := $(enforce_rro_source_overlays)
 
+ifeq (framework-res__auto_generated_rro,$(enforce_rro_module))
+LOCAL_PRIVATE_PLATFORM_APIS := true
+else
+LOCAL_SDK_VERSION := current
+endif
+
 include $(BUILD_RRO_PACKAGE)
diff --git a/core/goma.mk b/core/goma.mk
index 3787dfd..c265259 100644
--- a/core/goma.mk
+++ b/core/goma.mk
@@ -16,41 +16,18 @@
 
 # Notice: this works only with Google's Goma build infrastructure.
 ifneq ($(filter-out false,$(USE_GOMA)),)
-  # Goma requires a lot of processes and file descriptors.
-  ifeq ($(shell echo $$(($$(ulimit -u) < 2500 || $$(ulimit -n) < 16000))),1)
-    $(warning Max user processes and/or open files are insufficient)
-    ifeq ($(shell uname),Darwin)
-      $(error See go/ma/how-to-use-goma/how-to-use-goma-for-android to relax the limit)
-    else
-      $(error Adjust the limit by ulimit -u and ulimit -n)
-    endif
-  endif
-
   ifdef GOMA_DIR
     goma_dir := $(GOMA_DIR)
   else
     goma_dir := $(HOME)/goma
   endif
-  goma_ctl := $(goma_dir)/goma_ctl.py
   GOMA_CC := $(goma_dir)/gomacc
 
-  $(if $(wildcard $(goma_ctl)),, \
-   $(warning You should have goma in $$GOMA_DIR or $(HOME)/goma) \
-   $(error See go/ma/how-to-use-goma/how-to-use-goma-for-android for detail))
-
   # Append gomacc to existing *_WRAPPER variables so it's possible to
   # use both ccache and gomacc.
   CC_WRAPPER := $(strip $(CC_WRAPPER) $(GOMA_CC))
   CXX_WRAPPER := $(strip $(CXX_WRAPPER) $(GOMA_CC))
   JAVAC_WRAPPER := $(strip $(JAVAC_WRAPPER) $(GOMA_CC))
 
-  # gomacc can start goma client's daemon process automatically, but
-  # it is safer and faster to start up it beforehand. We run this as a
-  # background process so this won't slow down the build.
-  ifndef NOSTART_GOMA
-    $(shell ( $(goma_ctl) ensure_start ) &> /dev/null &)
-  endif
-
-  goma_ctl :=
   goma_dir :=
 endif
diff --git a/core/jacoco.mk b/core/jacoco.mk
index 6406df4..148bb04 100644
--- a/core/jacoco.mk
+++ b/core/jacoco.mk
@@ -51,7 +51,7 @@
 	  -d $(PRIVATE_UNZIPPED_PATH) \
 	  $(PRIVATE_INCLUDE_ARGS)
 	(cd $(PRIVATE_UNZIPPED_PATH) && rm -rf $(PRIVATE_EXCLUDE_ARGS))
-	(cd $(PRIVATE_UNZIPPED_PATH) && find -not -name "*.class" -type f | xargs --no-run-if-empty rm)
+	(cd $(PRIVATE_UNZIPPED_PATH) && find -not -name "*.class" -type f -exec rm {} \;)
 	touch $(PRIVATE_UNZIPPED_TIMESTAMP_PATH)
 # Unfortunately in the previous task above,
 # 'rm -rf $(PRIVATE_EXCLUDE_ARGS)' needs to be a separate
diff --git a/core/java.mk b/core/java.mk
index 30571b7..e564db2 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -74,10 +74,8 @@
 built_dex_hiddenapi := $(intermediates.COMMON)/dex-hiddenapi/classes.dex
 full_classes_stubs_jar := $(intermediates.COMMON)/stubs.jar
 java_source_list_file := $(intermediates.COMMON)/java-source-list
-hiddenapi_whitelist_txt := $(intermediates.COMMON)/hiddenapi/whitelist.txt
-hiddenapi_greylist_txt := $(intermediates.COMMON)/hiddenapi/greylist.txt
-hiddenapi_darkgreylist_txt := $(intermediates.COMMON)/hiddenapi/darkgreylist.txt
-hiddenapi_greylist_metadata_csv := $(intermediates.COMMON)/hiddenapi/greylist.csv
+hiddenapi_flags_csv := $(intermediates.COMMON)/hiddenapi/flags.csv
+hiddenapi_metadata_csv := $(intermediates.COMMON)/hiddenapi/greylist.csv
 
 ifeq ($(LOCAL_MODULE_CLASS)$(LOCAL_SRC_FILES)$(LOCAL_STATIC_JAVA_LIBRARIES)$(LOCAL_SOURCE_FILES_ALL_GENERATED),APPS)
 # If this is an apk without any Java code (e.g. framework-res), we should skip compiling Java.
@@ -111,7 +109,7 @@
 
 aidl_preprocess_import :=
 ifdef LOCAL_SDK_VERSION
-ifneq ($(filter current system_current test_current core_current, $(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS)),)
+ifneq ($(filter current system_current test_current core_current, $(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS_USE_PREBUILT_SDK)),)
   # LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS
   aidl_preprocess_import := $(TARGET_OUT_COMMON_INTERMEDIATES)/framework.aidl
 else
@@ -508,8 +506,8 @@
   # dex later on. The difference is academic currently, as we don't proguard any
   # bootclasspath code at the moment. If we were to do that, we should add keep
   # rules for all members with the @UnsupportedAppUsage annotation.
-  $(eval $(call hiddenapi-generate-greylist-txt, $(full_classes_pre_proguard_jar),$(hiddenapi_whitelist_txt),$(hiddenapi_greylist_txt),$(hiddenapi_darkgreylist_txt),$(hiddenapi_greylist_metadata_csv)))
-  LOCAL_INTERMEDIATE_TARGETS += $(hiddenapi_whitelist_txt) $(hiddenapi_greylist_txt) $(hiddenapi_darkgreylist_txt) $(hiddenapi_greylist_metadata_csv)
+  $(eval $(call hiddenapi-generate-csv, $(full_classes_pre_proguard_jar),$(hiddenapi_flags_csv),$(hiddenapi_metadata_csv)))
+  LOCAL_INTERMEDIATE_TARGETS += $(hiddenapi_flags_csv) $(hiddenapi_metadata_csv)
   $(eval $(call hiddenapi-copy-dex-files,$(built_dex_intermediate),$(built_dex_hiddenapi)))
   built_dex_copy_from := $(built_dex_hiddenapi)
 else # !is_boot_jar
diff --git a/core/java_common.mk b/core/java_common.mk
index bb981a6..ac26e5e 100644
--- a/core/java_common.mk
+++ b/core/java_common.mk
@@ -29,7 +29,7 @@
     LOCAL_JAVA_LANGUAGE_VERSION := 1.7
   else ifneq (,$(filter $(LOCAL_SDK_VERSION), $(TARGET_SDK_VERSIONS_WITHOUT_JAVA_19_SUPPORT)))
     LOCAL_JAVA_LANGUAGE_VERSION := 1.8
-  else ifneq (,$(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS))
+  else ifneq (,$(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS_USE_PREBUILT_SDK))
     # TODO(ccross): allow 1.9 for current and unbundled once we have SDK system modules
     LOCAL_JAVA_LANGUAGE_VERSION := 1.8
   else
@@ -82,21 +82,21 @@
 $(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_DIR := $(proto_java_sources_dir)
 $(proto_java_sources_file_stamp): PRIVATE_PROTOC_FLAGS := $(LOCAL_PROTOC_FLAGS)
 ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),micro)
-  $(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javamicro_out
-else ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
-  $(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javanano_out
-else ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),stream)
-  $(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javastream_out
-  $(proto_java_sources_file_stamp): PRIVATE_PROTOC_FLAGS += --plugin=$(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
-  $(proto_java_sources_file_stamp): $(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
-else ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),lite)
-  $(proto_java_sources_file_stamp): PRIVATE_PROTOC_FLAGS += --plugin=$(HOST_OUT_EXECUTABLES)/protoc-gen-javalite
-  $(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javalite_out
-  $(proto_java_sources_file_stamp): $(HOST_OUT_EXECUTABLES)/protoc-gen-javalite
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javamicro_out
 else
-  $(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --java_out
+  ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javanano_out
+  else
+    ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),stream)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javastream_out
+$(proto_java_sources_file_stamp): PRIVATE_PROTOC_FLAGS += --plugin=$(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
+$(proto_java_sources_file_stamp): $(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
+    else
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --java_out
+    endif
+  endif
 endif
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_PARAMS := $(LOCAL_PROTO_JAVA_OUTPUT_PARAMS)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_PARAMS := $(if $(filter lite,$(LOCAL_PROTOC_OPTIMIZE_TYPE)),lite$(if $(LOCAL_PROTO_JAVA_OUTPUT_PARAMS),:,),)$(LOCAL_PROTO_JAVA_OUTPUT_PARAMS)
 $(proto_java_sources_file_stamp) : $(proto_sources_fullpath) $(PROTOC)
 	$(call transform-proto-to-java)
 
@@ -276,7 +276,7 @@
       my_system_modules := $(DEFAULT_SYSTEM_MODULES)
     endif  # LOCAL_NO_STANDARD_LIBRARIES
 
-    ifneq (,$(TARGET_BUILD_APPS))
+    ifneq (,$(TARGET_BUILD_APPS_USE_PREBUILT_SDK))
       sdk_libs := $(foreach lib_name,$(LOCAL_SDK_LIBRARIES),$(call resolve-prebuilt-sdk-module,system_current,$(lib_name)))
     else
       # When SDK libraries are referenced from modules built without SDK, provide the all APIs to them
@@ -291,7 +291,7 @@
              Choices are: $(TARGET_AVAILABLE_SDK_VERSIONS))
     endif
 
-    ifneq (,$(TARGET_BUILD_APPS)$(filter-out %current,$(LOCAL_SDK_VERSION)))
+    ifneq (,$(TARGET_BUILD_APPS_USE_PREBUILT_SDK)$(filter-out %current,$(LOCAL_SDK_VERSION)))
       # TARGET_BUILD_APPS mode or numbered SDK. Use prebuilt modules.
       sdk_module := $(call resolve-prebuilt-sdk-module,$(LOCAL_SDK_VERSION))
       sdk_libs := $(foreach lib_name,$(LOCAL_SDK_LIBRARIES),$(call resolve-prebuilt-sdk-module,$(LOCAL_SDK_VERSION),$(lib_name)))
@@ -333,7 +333,7 @@
   # related classes to be present. This change adds stubs needed for
   # javac to compile lambdas.
   ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
-    ifdef TARGET_BUILD_APPS
+    ifdef TARGET_BUILD_APPS_USE_PREBUILT_SDK
       full_java_bootclasspath_libs += $(call java-lib-header-files,sdk-core-lambda-stubs)
     else
       full_java_bootclasspath_libs += $(call java-lib-header-files,core-lambda-stubs)
@@ -499,7 +499,7 @@
 ifeq ($(ONE_SHOT_MAKEFILE),)
 installed_static_library_notice_file_targets := \
     $(foreach lib,$(LOCAL_STATIC_JAVA_LIBRARIES), \
-      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST,TARGET)-JAVA_LIBRARIES-$(lib))
+      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST$(if $(my_host_cross),_CROSS,),TARGET)-JAVA_LIBRARIES-$(lib))
 else
 installed_static_library_notice_file_targets :=
 endif
diff --git a/core/java_library.mk b/core/java_library.mk
index e4e51d8..3e54b0e 100644
--- a/core/java_library.mk
+++ b/core/java_library.mk
@@ -50,6 +50,8 @@
 LOCAL_EMMA_INSTRUMENT := false
 endif # EMMA_INSTRUMENT
 
+my_dex_jar := $(common_javalib.jar)
+
 #################################
 include $(BUILD_SYSTEM)/java.mk
 #################################
@@ -90,13 +92,13 @@
 
 # For libart boot jars, we don't have .odex files.
 else # ! boot jar
-$(built_odex): PRIVATE_MODULE := $(LOCAL_MODULE)
-# Use pattern rule - we may have multiple built odex files.
-$(built_odex) : $(dir $(LOCAL_BUILT_MODULE))% : $(common_javalib.jar)
-	@echo "Dexpreopt Jar: $(PRIVATE_MODULE) ($@)"
-	$(call dexpreopt-one-file,$<,$@)
 
-$(eval $(call dexpreopt-copy-jar,$(common_javalib.jar),$(LOCAL_BUILT_MODULE),$(LOCAL_STRIP_DEX)))
+$(LOCAL_BUILT_MODULE): PRIVATE_STRIP_SCRIPT := $(intermediates)/strip.sh
+$(LOCAL_BUILT_MODULE): $(intermediates)/strip.sh
+$(LOCAL_BUILT_MODULE): | $(DEXPREOPT_GEN_DEPS)
+$(LOCAL_BUILT_MODULE): .KATI_DEPFILE := $(LOCAL_BUILT_MODULE).d
+$(LOCAL_BUILT_MODULE): $(common_javalib.jar)
+	$(PRIVATE_STRIP_SCRIPT) $< $@
 
 endif # ! boot jar
 
diff --git a/core/java_renderscript.mk b/core/java_renderscript.mk
index 406d679..13a6f8e 100644
--- a/core/java_renderscript.mk
+++ b/core/java_renderscript.mk
@@ -82,8 +82,8 @@
 $(rs_generated_src_jar): $(renderscript_sources_fullpath) $(LOCAL_RENDERSCRIPT_CC) $(SOONG_ZIP)
 	$(transform-renderscripts-to-java-and-bc)
 
-# include the dependency files (.d/.P) generated by llvm-rs-cc.
-$(call include-depfile,$(rs_generated_src_jar).P,$(rs_generated_src_jar))
+# include the dependency files (.d) generated by llvm-rs-cc.
+$(call include-depfile,$(rs_generated_src_jar).d,$(rs_generated_src_jar))
 
 ifneq ($(LOCAL_RENDERSCRIPT_COMPATIBILITY),)
 
diff --git a/core/local_systemsdk.mk b/core/local_systemsdk.mk
index 49085fd..7acb57a 100644
--- a/core/local_systemsdk.mk
+++ b/core/local_systemsdk.mk
@@ -25,7 +25,7 @@
   ifneq (,$(filter JAVA_LIBRARIES APPS,$(LOCAL_MODULE_CLASS)))
     ifndef LOCAL_SDK_VERSION
       ifeq ($(_is_vendor_app),true)
-        ifeq (,$(findstring __auto_generated_rro,$(LOCAL_MODULE)))
+        ifeq (,$(filter framework-res__auto_generated_rro,$(LOCAL_MODULE)))
           # Runtime resource overlay for framework-res is exempted from building
           # against System SDK.
           # TODO(b/35859726): remove this exception
diff --git a/core/main.mk b/core/main.mk
index fdf14de..282821c 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -80,7 +80,7 @@
 ifeq ($(strip $(HAS_BUILD_NUMBER)),false)
   # BUILD_NUMBER has a timestamp in it, which means that
   # it will change every time.  Pick a stable value.
-  FILE_NAME_TAG := eng.$(USER)
+  FILE_NAME_TAG := eng.$(BUILD_USERNAME)
 else
   FILE_NAME_TAG := $(file <$(BUILD_NUMBER_FILE))
 endif
@@ -244,7 +244,13 @@
 ADDITIONAL_DEFAULT_PROPERTIES += ro.actionable_compatible_property.enabled=${PRODUCT_COMPATIBLE_PROPERTY}
 endif
 
-ADDITIONAL_PRODUCT_PROPERTIES += ro.boot.logical_partitions=$(PRODUCT_USE_LOGICAL_PARTITIONS)
+ifeq ($(PRODUCT_USE_DYNAMIC_PARTITIONS),true)
+ADDITIONAL_PRODUCT_PROPERTIES += ro.boot.dynamic_partitions=true
+endif
+
+ifeq ($(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS),true)
+ADDITIONAL_PRODUCT_PROPERTIES += ro.boot.dynamic_partitions_retrofit=true
+endif
 
 # -----------------------------------------------------------------
 ###
@@ -404,7 +410,9 @@
 # Typical build; include any Android.mk files we can find.
 #
 
-
+# Before we go and include all of the module makefiles, strip values for easier
+# processing.
+$(call strip-product-vars)
 # Before we go and include all of the module makefiles, mark the PRODUCT_*
 # and ADDITIONAL*PROPERTIES values readonly so that they won't be modified.
 $(call readonly-product-vars)
@@ -965,7 +973,7 @@
 # Expand a list of modules to the modules that they override (if any)
 # $(1): The list of modules.
 define module-overrides
-$(foreach m,$(1),$(PACKAGES.$(m).OVERRIDES) $(EXECUTABLES.$(m).OVERRIDES))
+$(foreach m,$(1),$(PACKAGES.$(m).OVERRIDES) $(EXECUTABLES.$(m).OVERRIDES) $(SHARED_LIBRARIES.$(m).OVERRIDES))
 endef
 
 ###########################################################
@@ -1075,7 +1083,8 @@
   product_MODULES := $(_pif_modules)
 
   # Verify the artifact path requirements made by included products.
-
+  is_asan := $(if $(filter address,$(SANITIZE_TARGET)),true)
+  ifneq (true,$(or $(is_asan),$(DISABLE_ARTIFACT_PATH_REQUIREMENTS)))
   # Fakes don't get installed, and host files are irrelevant.
   static_whitelist_patterns := $(TARGET_OUT_FAKE)/% $(HOST_OUT)/%
   # RROs become REQUIRED by the source module, but are always placed on the vendor partition.
@@ -1087,6 +1096,13 @@
       $(TARGET_OUT_SYSTEM_OTHER)/%.vdex \
       $(TARGET_OUT_SYSTEM_OTHER)/%.art
   endif
+
+CERTIFICATE_VIOLATION_MODULES_FILENAME := $(PRODUCT_OUT)/certificate_violation_modules.txt
+$(CERTIFICATE_VIOLATION_MODULES_FILENAME):
+	rm -f $@
+	$(foreach m,$(sort $(CERTIFICATE_VIOLATION_MODULES)), echo $(m) >> $@;)
+$(call dist-for-goals,droidcore,$(CERTIFICATE_VIOLATION_MODULES_FILENAME))
+
   all_offending_files :=
   $(foreach makefile,$(ARTIFACT_PATH_REQUIREMENT_PRODUCTS),\
     $(eval requirements := $(PRODUCTS.$(makefile).ARTIFACT_PATH_REQUIREMENTS)) \
@@ -1119,6 +1135,7 @@
 $(PRODUCT_OUT)/offending_artifacts.txt:
 	rm -f $@
 	$(foreach f,$(sort $(all_offending_files)),echo $(f) >> $@;)
+  endif
 else
   # We're not doing a full build, and are probably only including
   # a subset of the module makefiles.  Don't try to build any modules
@@ -1198,6 +1215,9 @@
 modules_to_check += $(foreach m,$(ALL_MODULES),$(ALL_MODULES.$(m).BUILT))
 endif
 
+# Build docs as part of checkbuild to catch more breakages.
+module_to_check += $(ALL_DOCS)
+
 # for easier debugging
 modules_to_check := $(sort $(modules_to_check))
 #$(error modules_to_check $(modules_to_check))
@@ -1382,6 +1402,7 @@
   $(call dist-for-goals, droidcore, \
     $(INTERNAL_UPDATE_PACKAGE_TARGET) \
     $(INTERNAL_OTA_PACKAGE_TARGET) \
+    $(INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET) \
     $(BUILT_OTATOOLS_PACKAGE) \
     $(SYMBOLS_ZIP) \
     $(COVERAGE_ZIP) \
@@ -1522,7 +1543,7 @@
 .PHONY: dump-files
 dump-files:
 	$(info product_FILES for $(TARGET_DEVICE) ($(INTERNAL_PRODUCT)):)
-	$(foreach p,$(product_FILES),$(info :   $(p)))
+	$(foreach p,$(sort $(product_FILES)),$(info :   $(p)))
 	@echo Successfully dumped product file list
 
 .PHONY: nothing
diff --git a/core/notice_files.mk b/core/notice_files.mk
index 08778c5..e687ab2 100644
--- a/core/notice_files.mk
+++ b/core/notice_files.mk
@@ -119,6 +119,6 @@
 # Define it even if the notice file doesn't exist so that other
 # modules can depend on it.
 notice_target := NOTICE-$(if \
-    $(LOCAL_IS_HOST_MODULE),HOST,TARGET)-$(LOCAL_MODULE_CLASS)-$(LOCAL_MODULE)
+    $(LOCAL_IS_HOST_MODULE),HOST$(if $(my_host_cross),_CROSS,),TARGET)-$(LOCAL_MODULE_CLASS)-$(LOCAL_MODULE)
 .PHONY: $(notice_target)
 $(notice_target): $(installed_notice_file)
diff --git a/core/package_internal.mk b/core/package_internal.mk
index 8e83dab..c657f2e 100644
--- a/core/package_internal.mk
+++ b/core/package_internal.mk
@@ -87,6 +87,23 @@
   LOCAL_RESOURCE_DIR := $(foreach d,$(LOCAL_RESOURCE_DIR),$(call clean-path,$(d)))
 endif
 
+# If LOCAL_MODULE matches a rule in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES,
+# override the manfest package name by the (first) rule matched
+override_manifest_name := $(strip $(word 1,\
+  $(foreach rule,$(PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES),\
+    $(eval _pkg_name_pat := $(call word-colon,1,$(rule)))\
+    $(eval _manifest_name_pat := $(call word-colon,2,$(rule)))\
+    $(if $(filter $(_pkg_name_pat),$(LOCAL_MODULE)),\
+      $(patsubst $(_pkg_name_pat),$(_manifest_name_pat),$(LOCAL_MODULE))\
+     )\
+   )\
+))
+
+ifneq (,$(override_manifest_name))
+# Note: this can override LOCAL_MANFEST_PACKAGE_NAME value set in Android.mk
+LOCAL_MANIFEST_PACKAGE_NAME := $(override_manifest_name)
+endif
+
 include $(BUILD_SYSTEM)/force_aapt2.mk
 
 # Process Support Library dependencies.
@@ -309,23 +326,6 @@
 
 rs_compatibility_jni_libs :=
 
-ifeq ($(LOCAL_DATA_BINDING),true)
-data_binding_intermediates := $(intermediates.COMMON)/data-binding
-
-LOCAL_JAVACFLAGS += -processorpath $(DATA_BINDING_COMPILER) -s $(data_binding_intermediates)/anno-src
-
-LOCAL_STATIC_JAVA_LIBRARIES += databinding-baselibrary
-LOCAL_STATIC_JAVA_AAR_LIBRARIES += databinding-library databinding-adapters
-
-data_binding_res_in := $(LOCAL_RESOURCE_DIR)
-data_binding_res_out := $(data_binding_intermediates)/res
-
-# Replace with the processed merged res dir.
-LOCAL_RESOURCE_DIR := $(data_binding_res_out)
-
-LOCAL_AAPT_FLAGS += --auto-add-overlay --extra-packages com.android.databinding.library
-endif  # LOCAL_DATA_BINDING
-
 # If the module is a compressed module, we don't pre-opt it because its final
 # installation location will be the data partition.
 ifdef LOCAL_COMPRESSED_MODULE
@@ -432,6 +432,8 @@
 
 endif  # need_compile_res
 
+my_dex_jar := $(intermediates.COMMON)/dex.jar
+
 called_from_package_internal := true
 #################################
 include $(BUILD_SYSTEM)/java.mk
@@ -458,34 +460,6 @@
 $(LOCAL_INTERMEDIATE_TARGETS): \
     PRIVATE_ANDROID_MANIFEST := $(full_android_manifest)
 
-ifeq ($(LOCAL_DATA_BINDING),true)
-data_binding_stamp := $(data_binding_intermediates)/data-binding.stamp
-$(data_binding_stamp): PRIVATE_INTERMEDIATES := $(data_binding_intermediates)
-$(data_binding_stamp): PRIVATE_MANIFEST := $(full_android_manifest)
-# Generate code into $(LOCAL_INTERMEDIATE_SOURCE_DIR) so that the generated .java files
-# will be automatically picked up by function compile-java.
-$(data_binding_stamp): PRIVATE_SRC_OUT := $(LOCAL_INTERMEDIATE_SOURCE_DIR)/data-binding
-$(data_binding_stamp): PRIVATE_XML_OUT := $(data_binding_intermediates)/xml
-$(data_binding_stamp): PRIVATE_RES_OUT := $(data_binding_res_out)
-$(data_binding_stamp): PRIVATE_RES_IN := $(data_binding_res_in)
-$(data_binding_stamp): PRIVATE_ANNO_SRC_DIR := $(data_binding_intermediates)/anno-src
-
-$(data_binding_stamp) : $(all_res_assets) $(full_android_manifest) \
-    $(DATA_BINDING_COMPILER)
-	@echo "Data-binding process: $@"
-	@rm -rf $(PRIVATE_INTERMEDIATES) $(PRIVATE_SRC_OUT) && \
-	  mkdir -p $(PRIVATE_INTERMEDIATES) $(PRIVATE_SRC_OUT) \
-	      $(PRIVATE_XML_OUT) $(PRIVATE_RES_OUT) $(PRIVATE_ANNO_SRC_DIR)
-	$(hide) $(JAVA) -classpath $(DATA_BINDING_COMPILER) android.databinding.tool.MakeCopy \
-	  $(PRIVATE_MANIFEST) $(PRIVATE_SRC_OUT) $(PRIVATE_XML_OUT) $(PRIVATE_RES_OUT) $(PRIVATE_RES_IN)
-	$(hide) touch $@
-
-# Make sure the data-binding process happens before javac and generation of R.java.
-$(R_file_stamp): $(data_binding_stamp)
-$(java_source_list_file): $(data_binding_stamp)
-$(full_classes_compiled_jar): $(data_binding_stamp)
-endif  # LOCAL_DATA_BINDING
-
 framework_res_package_export :=
 
 ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
@@ -494,7 +468,7 @@
 # resources.
 ifeq ($(LOCAL_SDK_RES_VERSION),core_current)
 # core_current doesn't contain any framework resources.
-else ifneq ($(filter-out current system_current test_current,$(LOCAL_SDK_RES_VERSION))$(if $(TARGET_BUILD_APPS),$(filter current system_current test_current,$(LOCAL_SDK_RES_VERSION))),)
+else ifneq ($(filter-out current system_current test_current,$(LOCAL_SDK_RES_VERSION))$(if $(TARGET_BUILD_APPS_USE_PREBUILT_SDK),$(filter current system_current test_current,$(LOCAL_SDK_RES_VERSION))),)
 # for released sdk versions, the platform resources were built into android.jar.
 framework_res_package_export := \
     $(call resolve-prebuilt-sdk-jar-path,$(LOCAL_SDK_RES_VERSION))
@@ -561,6 +535,7 @@
 ifeq ($(dir $(strip $(LOCAL_CERTIFICATE))),./)
     LOCAL_CERTIFICATE := $(dir $(DEFAULT_SYSTEM_DEV_CERTIFICATE))$(LOCAL_CERTIFICATE)
 endif
+include $(BUILD_SYSTEM)/app_certificate_validate.mk
 private_key := $(LOCAL_CERTIFICATE).pk8
 certificate := $(LOCAL_CERTIFICATE).x509.pem
 additional_certificates := $(foreach c,$(LOCAL_ADDITIONAL_CERTIFICATES), $(c).x509.pem $(c).pk8)
@@ -631,6 +606,12 @@
 ifneq ($(BUILD_PLATFORM_ZIP),)
 $(LOCAL_BUILT_MODULE) : .KATI_IMPLICIT_OUTPUTS := $(dir $(LOCAL_BUILT_MODULE))package.dex.apk
 endif
+ifdef LOCAL_DEX_PREOPT
+$(LOCAL_BUILT_MODULE) : PRIVATE_STRIP_SCRIPT := $(intermediates)/strip.sh
+$(LOCAL_BUILT_MODULE) : $(intermediates)/strip.sh
+$(LOCAL_BUILT_MODULE) : | $(DEXPREOPT_GEN_DEPS)
+$(LOCAL_BUILT_MODULE): .KATI_DEPFILE := $(LOCAL_BUILT_MODULE).d
+endif
 $(LOCAL_BUILT_MODULE):
 	@echo "target Package: $(PRIVATE_MODULE) ($@)"
 	rm -rf $@.parts
@@ -670,9 +651,8 @@
 	@# Keep a copy of apk with classes.dex unstripped
 	$(hide) cp -f $@ $(dir $@)package.dex.apk
 endif  # BUILD_PLATFORM_ZIP
-ifdef LOCAL_STRIP_DEX
-	$(call dexpreopt-remove-classes.dex,$@)
-endif
+	mv -f $@ $@.tmp
+	$(PRIVATE_STRIP_SCRIPT) $@.tmp $@
 endif  # LOCAL_DEX_PREOPT
 	$(sign-package)
 ifdef LOCAL_COMPRESSED_MODULE
@@ -711,15 +691,18 @@
         endif
         ifeq ($(full_classes_jar),)
         # We don't build jar, need to add the Java resources here.
-	  $(if $(PRIVATE_EXTRA_JAR_ARGS),$(call create-java-resources-jar,$@.parts/res.zip))
+	  $(if $(PRIVATE_EXTRA_JAR_ARGS),\
+	    $(call create-java-resources-jar,$@.parts/res.zip) && \
+	    $(ZIP2ZIP) -i $@.parts/res.zip -o $@.parts/res.zip.tmp "**/*:root/" && \
+	    mv -f $@.parts/res.zip.tmp $@.parts/res.zip)
         else  # full_classes_jar
 	  $(call create-dex-jar,$@.parts/dex.zip,$(PRIVATE_DEX_FILE))
 	  $(ZIP2ZIP) -i $@.parts/dex.zip -o $@.parts/dex.zip.tmp "classes*.dex:dex/"
 	  mv -f $@.parts/dex.zip.tmp $@.parts/dex.zip
 	  $(call extract-resources-jar,$@.parts/res.zip,$(PRIVATE_SOURCE_ARCHIVE))
+	  $(ZIP2ZIP) -i $@.parts/res.zip -o $@.parts/res.zip.tmp "**/*:root/"
+	  mv -f $@.parts/res.zip.tmp $@.parts/res.zip
         endif  # full_classes_jar
-	$(ZIP2ZIP) -i $@.parts/res.zip -o $@.parts/res.zip.tmp "**/*:root/"
-	mv -f $@.parts/res.zip.tmp $@.parts/res.zip
 	$(MERGE_ZIPS) $@ $@.parts/*.zip
 	rm -rf $@.parts
   ALL_MODULES.$(LOCAL_MODULE).BUNDLE := $(my_bundle_module)
@@ -736,23 +719,13 @@
 endif
 
 ###############################
-## Rule to build the odex file
+## Rule to build a jar containing dex files to dexpreopt without waiting for
+## the APK
 ifdef LOCAL_DEX_PREOPT
-$(built_odex): PRIVATE_DEX_FILE := $(built_dex)
-ifeq (true, $(LOCAL_UNCOMPRESS_DEX))
-$(built_odex): $(ZIP2ZIP)
-endif
-# Use pattern rule - we may have multiple built odex files.
-$(built_odex) : $(dir $(LOCAL_BUILT_MODULE))% : $(built_dex)
+  $(my_dex_jar): PRIVATE_DEX_FILE := $(built_dex)
+  $(my_dex_jar): $(built_dex)
 	$(hide) mkdir -p $(dir $@) && rm -f $@
 	$(call create-dex-jar,$@,$(PRIVATE_DEX_FILE))
-ifeq (true, $(LOCAL_UNCOMPRESS_DEX))
-	$(uncompress-dexs)
-	$(align-package)
-endif
-	$(hide) mv $@ $@.input
-	$(call dexpreopt-one-file,$@.input,$@)
-	$(hide) rm $@.input
 endif
 
 ###############################
diff --git a/core/prebuilt_internal.mk b/core/prebuilt_internal.mk
index a4b58fc..960d8d1 100644
--- a/core/prebuilt_internal.mk
+++ b/core/prebuilt_internal.mk
@@ -306,6 +306,8 @@
   $(built_module) : PRIVATE_CERTIFICATE := $(LOCAL_CERTIFICATE).x509.pem
 endif
 
+include $(BUILD_SYSTEM)/app_certificate_validate.mk
+
 # Disable dex-preopt of prebuilts to save space, if requested.
 ifndef LOCAL_DEX_PREOPT
 ifeq ($(DONT_DEXPREOPT_PREBUILTS),true)
@@ -319,6 +321,8 @@
 LOCAL_DEX_PREOPT := false
 endif
 
+my_dex_jar := $(my_prebuilt_src_file)
+
 #######################################
 # defines built_odex along with rule to install odex
 include $(BUILD_SYSTEM)/dex_preopt_odex_install.mk
@@ -342,7 +346,6 @@
 embedded_prebuilt_jni_libs :=
 endif
 $(built_module): PRIVATE_EMBEDDED_JNI_LIBS := $(embedded_prebuilt_jni_libs)
-$(built_module): $(ZIP2ZIP)
 
 ifdef LOCAL_COMPRESSED_MODULE
 $(built_module) : $(MINIGZIP)
@@ -356,7 +359,15 @@
 ifneq ($(BUILD_PLATFORM_ZIP),)
 $(built_module) : .KATI_IMPLICIT_OUTPUTS := $(dir $(LOCAL_BUILT_MODULE))package.dex.apk
 endif
-$(built_module) : $(my_prebuilt_src_file) | $(ZIPALIGN) $(SIGNAPK_JAR)
+ifneq ($(LOCAL_CERTIFICATE),PRESIGNED)
+ifdef LOCAL_DEX_PREOPT
+$(built_module) : PRIVATE_STRIP_SCRIPT := $(intermediates)/strip.sh
+$(built_module) : $(intermediates)/strip.sh
+$(built_module) : | $(DEXPREOPT_GEN_DEPS)
+$(built_module) : .KATI_DEPFILE := $(built_module).d
+endif
+endif
+$(built_module) : $(my_prebuilt_src_file) | $(ZIPALIGN) $(ZIP2ZIP) $(SIGNAPK_JAR)
 	$(transform-prebuilt-to-target)
 	$(uncompress-prebuilt-embedded-jni-libs)
 ifeq (true, $(LOCAL_UNCOMPRESS_DEX))
@@ -380,9 +391,8 @@
 	$(run-appcompat)
 endif  # module_run_appcompat
 ifdef LOCAL_DEX_PREOPT
-ifdef LOCAL_STRIP_DEX
-	$(call dexpreopt-remove-classes.dex,$@)
-endif  # LOCAL_STRIP_DEX
+	mv -f $@ $@.tmp
+	$(PRIVATE_STRIP_SCRIPT) $@.tmp $@
 endif  # LOCAL_DEX_PREOPT
 	$(sign-package)
 	# No need for align-package because sign-package takes care of alignment
@@ -394,20 +404,6 @@
 endif  # LOCAL_COMPRESSED_MODULE
 endif  # ! LOCAL_REPLACE_PREBUILT_APK_INSTALLED
 
-###############################
-## Rule to build the odex file.
-# In case we don't strip the built module, use it, as dexpreopt
-# can do optimizations based on whether the built module only
-# contains uncompressed dex code.
-ifdef LOCAL_DEX_PREOPT
-ifndef LOCAL_STRIP_DEX
-$(built_odex) : $(built_module)
-	$(call dexpreopt-one-file,$<,$@)
-else
-$(built_odex) : $(my_prebuilt_src_file)
-	$(call dexpreopt-one-file,$<,$@)
-endif
-endif
 
 ###############################
 ## Install split apks.
@@ -450,6 +446,7 @@
 endif # LOCAL_PACKAGE_SPLITS
 
 else ifeq ($(prebuilt_module_is_dex_javalib),true)  # ! LOCAL_MODULE_CLASS != APPS
+my_dex_jar := $(my_prebuilt_src_file)
 # This is a target shared library, i.e. a jar with classes.dex.
 #######################################
 # defines built_odex along with rule to install odex
@@ -464,13 +461,14 @@
 
 # For libart boot jars, we don't have .odex files.
 else # ! boot jar
-$(built_odex): PRIVATE_MODULE := $(LOCAL_MODULE)
-# Use pattern rule - we may have multiple built odex files.
-$(built_odex) : $(dir $(LOCAL_BUILT_MODULE))% : $(my_prebuilt_src_file)
-	@echo "Dexpreopt Jar: $(PRIVATE_MODULE) ($@)"
-	$(call dexpreopt-one-file,$<,$@)
 
-$(eval $(call dexpreopt-copy-jar,$(my_prebuilt_src_file),$(built_module),$(LOCAL_STRIP_DEX)))
+$(built_module): PRIVATE_STRIP_SCRIPT := $(intermediates)/strip.sh
+$(built_module): $(intermediates)/strip.sh
+$(built_module): | $(DEXPREOPT_GEN_DEPS)
+$(built_module): .KATI_DEPFILE := $(built_module).d
+$(built_module): $(my_prebuilt_src_file)
+	$(PRIVATE_STRIP_SCRIPT) $< $@
+
 endif # boot jar
 else # ! LOCAL_DEX_PREOPT
 $(built_module) : $(my_prebuilt_src_file)
diff --git a/core/product.mk b/core/product.mk
index f9f8d60..2d7ace2 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -203,13 +203,19 @@
     PRODUCT_CFI_EXCLUDE_PATHS \
     PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE \
     PRODUCT_ACTIONABLE_COMPATIBLE_PROPERTY_DISABLE \
-    PRODUCT_USE_LOGICAL_PARTITIONS \
     PRODUCT_ENFORCE_ARTIFACT_PATH_REQUIREMENTS \
+    PRODUCT_ENFORCE_ARTIFACT_SYSTEM_CERTIFICATE_REQUIREMENT \
+    PRODUCT_ARTIFACT_SYSTEM_CERTIFICATE_REQUIREMENT_WHITELIST \
     PRODUCT_ARTIFACT_PATH_REQUIREMENT_HINT \
     PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST \
     PRODUCT_USE_DYNAMIC_PARTITION_SIZE \
     PRODUCT_BUILD_SUPER_PARTITION \
     PRODUCT_FORCE_PRODUCT_MODULES_TO_SYSTEM_PARTITION \
+    PRODUCT_USE_DYNAMIC_PARTITIONS \
+    PRODUCT_RETROFIT_DYNAMIC_PARTITIONS \
+    PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS \
+    PRODUCT_XOM_EXCLUDE_PATHS \
+    PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES \
 
 define dump-product
 $(info ==== $(1) ====)\
@@ -401,7 +407,7 @@
 	WITH_DEXPREOPT_BOOT_IMG_AND_SYSTEM_SERVER_ONLY
 
 # Logical partitions related variables.
-_product_stash_var_list += \
+_dynamic_partitions_var_list += \
 	BOARD_SYSTEMIMAGE_PARTITION_RESERVED_SIZE \
 	BOARD_VENDORIMAGE_PARTITION_RESERVED_SIZE \
 	BOARD_ODMIMAGE_PARTITION_RESERVED_SIZE \
@@ -410,6 +416,9 @@
 	BOARD_SUPER_PARTITION_SIZE \
 	BOARD_SUPER_PARTITION_GROUPS \
 
+_product_stash_var_list += $(_dynamic_partitions_var_list)
+_product_strip_var_list := $(_dynamic_partitions_var_list)
+
 #
 # Mark the variables in _product_stash_var_list as readonly
 #
@@ -420,6 +429,13 @@
  )
 endef
 
+#
+# Strip the variables in _product_strip_var_list
+#
+define strip-product-vars
+$(foreach v,$(_product_strip_var_list),$(eval $(v) := $(strip $($(v)))))
+endef
+
 define add-to-product-copy-files-if-exists
 $(if $(wildcard $(word 1,$(subst :, ,$(1)))),$(1))
 endef
diff --git a/core/product_config.mk b/core/product_config.mk
index 577bafe..c58405c 100644
--- a/core/product_config.mk
+++ b/core/product_config.mk
@@ -175,15 +175,9 @@
 include $(BUILD_SYSTEM)/product.mk
 include $(BUILD_SYSTEM)/device.mk
 
-ifneq ($(strip $(TARGET_BUILD_APPS)),)
-# An unbundled app build needs only the core product makefiles.
-all_product_configs := $(call get-product-makefiles,\
-    $(SRC_TARGET_DIR)/product/AndroidProducts.mk)
-else
 # Read in all of the product definitions specified by the AndroidProducts.mk
 # files in the tree.
 all_product_configs := $(get-all-product-makefiles)
-endif
 
 all_named_products :=
 
@@ -352,6 +346,11 @@
 # used for adding properties to default.prop
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES := \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEFAULT_PROPERTY_OVERRIDES))
+
+$(foreach rule,$(PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES),\
+    $(if $(filter 2,$(words $(subst :,$(space),$(rule)))),,\
+        $(error Rule "$(rule)" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDE is not <module_name>:<manifest_name>)))
+
 .KATI_READONLY := PRODUCT_DEFAULT_PROPERTY_OVERRIDES
 
 # A list of property assignments, like "key = value", with zero or more
@@ -368,6 +367,11 @@
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_PROPERTIES))
 .KATI_READONLY := PRODUCT_PRODUCT_PROPERTIES
 
+ENFORCE_SYSTEM_CERTIFICATE := \
+    $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ENFORCE_ARTIFACT_SYSTEM_CERTIFICATE_REQUIREMENT)
+
+ENFORCE_SYSTEM_CERTIFICATE_WHITELIST := \
+    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ARTIFACT_SYSTEM_CERTIFICATE_REQUIREMENT_WHITELIST))
 
 # A list of property assignments, like "key = value", with zero or more
 # whitespace characters on either side of the '='.
@@ -501,6 +505,10 @@
 PRODUCT_CFI_INCLUDE_PATHS := \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_CFI_INCLUDE_PATHS))
 
+# Whether any paths are excluded from being set XOM when ENABLE_XOM=true
+PRODUCT_XOM_EXCLUDE_PATHS := \
+    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_XOM_EXCLUDE_PATHS))
+
 # which Soong namespaces to export to Make
 PRODUCT_SOONG_NAMESPACES := \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SOONG_NAMESPACES))
@@ -513,20 +521,30 @@
 PRODUCT_ACTIONABLE_COMPATIBLE_PROPERTY_DISABLE := \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ACTIONABLE_COMPATIBLE_PROPERTY_DISABLE))
 
-# Logical and Resizable Partitions feature flag.
-PRODUCT_USE_LOGICAL_PARTITIONS := \
-    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_USE_LOGICAL_PARTITIONS))
-.KATI_READONLY := PRODUCT_USE_LOGICAL_PARTITIONS
+# Dynamic partition feature flags.
 
-# All requirements of PRODUCT_USE_LOGICAL_PARTITIONS falls back to
-# PRODUCT_USE_LOGICAL_PARTITIONS if not defined.
+# When this is true, dynamic partitions is retrofitted on a device that has
+# already been launched without dynamic partitions. Otherwise, the device
+# is launched with dynamic partitions.
+# This flag implies PRODUCT_USE_DYNAMIC_PARTITIONS.
+PRODUCT_RETROFIT_DYNAMIC_PARTITIONS := \
+    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_RETROFIT_DYNAMIC_PARTITIONS))
+.KATI_READONLY := PRODUCT_RETROFIT_DYNAMIC_PARTITIONS
+
+PRODUCT_USE_DYNAMIC_PARTITIONS := $(or \
+    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_USE_DYNAMIC_PARTITIONS)), \
+    $(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS))
+.KATI_READONLY := PRODUCT_USE_DYNAMIC_PARTITIONS
+
+# All requirements of PRODUCT_USE_DYNAMIC_PARTITIONS falls back to
+# PRODUCT_USE_DYNAMIC_PARTITIONS if not defined.
 PRODUCT_USE_DYNAMIC_PARTITION_SIZE := $(or \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_USE_DYNAMIC_PARTITION_SIZE)),\
-    $(PRODUCT_USE_LOGICAL_PARTITIONS))
+    $(PRODUCT_USE_DYNAMIC_PARTITIONS))
 .KATI_READONLY := PRODUCT_USE_DYNAMIC_PARTITION_SIZE
 PRODUCT_BUILD_SUPER_PARTITION := $(or \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_BUILD_SUPER_PARTITION)),\
-    $(PRODUCT_USE_LOGICAL_PARTITIONS))
+    $(PRODUCT_USE_DYNAMIC_PARTITIONS))
 .KATI_READONLY := PRODUCT_BUILD_SUPER_PARTITION
 
 # List of modules that should be forcefully unmarked from being LOCAL_PRODUCT_MODULE, and hence
@@ -534,3 +552,17 @@
 PRODUCT_FORCE_PRODUCT_MODULES_TO_SYSTEM_PARTITION := \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_FORCE_PRODUCT_MODULES_TO_SYSTEM_PARTITION))
 .KATI_READONLY := PRODUCT_FORCE_PRODUCT_MODULES_TO_SYSTEM_PARTITION
+
+# If set, kernel configuration requirements are present in OTA package (and will be enforced
+# during OTA). Otherwise, kernel configuration requirements are enforced in VTS.
+# Devices that checks the running kernel (instead of the kernel in OTA package) should not
+# set this variable to prevent OTA failures.
+PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS := \
+    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS))
+
+# List of <module_name>:<manifest_name> pairs to override the manifest package name
+# of a module <module_name> to <manifest_name>. Patterns can be used as in
+# com.android.%:com.acme.android.%.release
+PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES := \
+    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES))
+.KATI_READONLY := PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
diff --git a/core/setup_one_odex.mk b/core/setup_one_odex.mk
deleted file mode 100644
index 92f58b2..0000000
--- a/core/setup_one_odex.mk
+++ /dev/null
@@ -1,140 +0,0 @@
-#
-# Copyright (C) 2014 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.
-#
-
-# Set up variables and dependency for one odex file
-# Input variables: my_2nd_arch_prefix
-# Output(modified) variables: built_odex, installed_odex, built_installed_odex
-
-my_built_odex := $(call get-odex-file-path,$($(my_2nd_arch_prefix)DEX2OAT_TARGET_ARCH),$(LOCAL_BUILT_MODULE))
-ifdef LOCAL_DEX_PREOPT_IMAGE_LOCATION
-my_dex_preopt_image_location := $(LOCAL_DEX_PREOPT_IMAGE_LOCATION)
-else
-my_dex_preopt_image_location := $($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION)
-endif
-my_dex_preopt_image_filename := $(call get-image-file-path,$($(my_2nd_arch_prefix)DEX2OAT_TARGET_ARCH),$(my_dex_preopt_image_location))
-
-# If LOCAL_ENFORCE_USES_LIBRARIES is not set, default to true if either of LOCAL_USES_LIBRARIES or
-# LOCAL_OPTIONAL_USES_LIBRARIES are specified.
-ifeq (,$(LOCAL_ENFORCE_USES_LIBRARIES))
-# Will change the default to true unconditionally in the future.
-ifneq (,$(LOCAL_OPTIONAL_USES_LIBRARIES))
-LOCAL_ENFORCE_USES_LIBRARIES := true
-endif
-ifneq (,$(LOCAL_USES_LIBRARIES))
-LOCAL_ENFORCE_USES_LIBRARIES := true
-endif
-endif
-
-my_uses_libraries := $(LOCAL_USES_LIBRARIES)
-my_optional_uses_libraries := $(LOCAL_OPTIONAL_USES_LIBRARIES)
-my_missing_uses_libraries := $(INTERNAL_PLATFORM_MISSING_USES_LIBRARIES)
-
-# If we have either optional or required uses-libraries, set up the class loader context
-# accordingly.
-my_lib_names :=
-my_optional_lib_names :=
-my_filtered_optional_uses_libraries :=
-my_system_dependencies :=
-my_stored_preopt_class_loader_context_libs :=
-my_conditional_uses_libraries_host :=
-my_conditional_uses_libraries_target :=
-
-ifneq (true,$(LOCAL_ENFORCE_USES_LIBRARIES))
-  # Pass special class loader context to skip the classpath and collision check.
-  # This will get removed once LOCAL_USES_LIBRARIES is enforced.
-  # Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
-  # to the &.
-  my_dex_preopt_class_loader_context := \&
-else
-  # Compute the filtered optional uses libraries by removing ones that are not supposed to exist.
-  my_filtered_optional_uses_libraries := \
-      $(filter-out $(my_missing_uses_libraries), $(my_optional_uses_libraries))
-  my_filtered_uses_libraries := $(my_uses_libraries) $(my_filtered_optional_uses_libraries)
-
-  # These are the ones we are verifying in the make rule, use the unfiltered libraries.
-  my_lib_names := $(my_uses_libraries)
-  my_optional_lib_names := $(my_optional_uses_libraries)
-
-  # Calculate system build dependencies based on the filtered libraries.
-  my_intermediate_libs := $(foreach lib_name, $(my_lib_names) $(my_filtered_optional_uses_libraries), \
-    $(call intermediates-dir-for,JAVA_LIBRARIES,$(lib_name),,COMMON)/javalib.jar)
-  my_dex_preopt_system_dependencies := $(my_intermediate_libs)
-  my_dex_preopt_class_loader_context := $(call normalize-path-list,$(my_intermediate_libs))
-
-  # The class loader context checksums are filled in by dex2oat.
-  my_stored_preopt_class_loader_context_libs := $(call normalize-path-list, \
-      $(foreach lib_name,$(my_filtered_uses_libraries),/system/framework/$(lib_name).jar))
-
-  # Fix up org.apache.http.legacy.impl since it should be org.apache.http.legacy in the manifest.
-  my_lib_names := $(patsubst org.apache.http.legacy.impl,org.apache.http.legacy,$(my_lib_names))
-  my_optional_lib_names := $(patsubst org.apache.http.legacy.impl,org.apache.http.legacy,$(my_optional_lib_names))
-  ifeq (,$(filter org.apache.http.legacy,$(my_lib_names) $(my_optional_lib_names)))
-    my_conditional_uses_libraries_host := $(call intermediates-dir-for,JAVA_LIBRARIES,org.apache.http.legacy.impl,,COMMON)/javalib.jar
-    my_conditional_uses_libraries_target := /system/framework/org.apache.http.legacy.impl.jar
-  endif
-endif
-
-$(my_built_odex): $(AAPT)
-$(my_built_odex): $(my_conditional_uses_libraries_host)
-$(my_built_odex): $(my_dex_preopt_system_dependencies)
-$(my_built_odex): PRIVATE_ENFORCE_USES_LIBRARIES := $(LOCAL_ENFORCE_USES_LIBRARIES)
-$(my_built_odex): PRIVATE_CONDITIONAL_USES_LIBRARIES_HOST := $(my_conditional_uses_libraries_host)
-$(my_built_odex): PRIVATE_CONDITIONAL_USES_LIBRARIES_TARGET := $(my_conditional_uses_libraries_target)
-$(my_built_odex): PRIVATE_USES_LIBRARY_NAMES := $(my_lib_names)
-$(my_built_odex): PRIVATE_OPTIONAL_USES_LIBRARY_NAMES := $(my_optional_lib_names)
-$(my_built_odex): PRIVATE_2ND_ARCH_VAR_PREFIX := $(my_2nd_arch_prefix)
-$(my_built_odex): PRIVATE_DEX_LOCATION := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
-$(my_built_odex): PRIVATE_DEX_PREOPT_IMAGE_LOCATION := $(my_dex_preopt_image_location)
-$(my_built_odex): PRIVATE_DEX2OAT_CLASS_LOADER_CONTEXT := $(my_dex_preopt_class_loader_context)
-$(my_built_odex): PRIVATE_DEX2OAT_STORED_CLASS_LOADER_CONTEXT_LIBS := $(my_stored_preopt_class_loader_context_libs)
-$(my_built_odex) : $($(my_2nd_arch_prefix)DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT) \
-    $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS) \
-    $(my_dex_preopt_image_filename)
-
-my_installed_odex := $(call get-odex-installed-file-path,$($(my_2nd_arch_prefix)DEX2OAT_TARGET_ARCH),$(LOCAL_INSTALLED_MODULE))
-
-my_built_vdex := $(patsubst %.odex,%.vdex,$(my_built_odex))
-my_installed_vdex := $(patsubst %.odex,%.vdex,$(my_installed_odex))
-my_installed_art := $(patsubst %.odex,%.art,$(my_installed_odex))
-
-ifndef LOCAL_DEX_PREOPT_APP_IMAGE
-# Local override not defined, use the global one.
-ifeq (true,$(WITH_DEX_PREOPT_APP_IMAGE))
-  LOCAL_DEX_PREOPT_APP_IMAGE := true
-endif
-endif
-
-ifeq (true,$(LOCAL_DEX_PREOPT_APP_IMAGE))
-my_built_art := $(patsubst %.odex,%.art,$(my_built_odex))
-$(my_built_odex): PRIVATE_ART_FILE_PREOPT_FLAGS := --app-image-file=$(my_built_art) \
-    --image-format=lz4
-$(eval $(call copy-one-file,$(my_built_art),$(my_installed_art)))
-built_art += $(my_built_art)
-installed_art += $(my_installed_art)
-built_installed_art += $(my_built_art):$(my_installed_art)
-endif
-
-$(eval $(call copy-one-file,$(my_built_odex),$(my_installed_odex)))
-$(eval $(call copy-one-file,$(my_built_vdex),$(my_installed_vdex)))
-
-built_odex += $(my_built_odex)
-built_vdex += $(my_built_vdex)
-
-installed_odex += $(my_installed_odex)
-installed_vdex += $(my_installed_vdex)
-
-built_installed_odex += $(my_built_odex):$(my_installed_odex)
-built_installed_vdex += $(my_built_vdex):$(my_installed_vdex)
diff --git a/core/shared_library_internal.mk b/core/shared_library_internal.mk
index 41e6a95..44bb020 100644
--- a/core/shared_library_internal.mk
+++ b/core/shared_library_internal.mk
@@ -34,6 +34,11 @@
 include $(BUILD_SYSTEM)/dynamic_binary.mk
 
 # Define PRIVATE_ variables from global vars
+ifeq ($(LOCAL_NO_LIBCRT_BUILTINS),true)
+my_target_libcrt_builtins :=
+else
+my_target_libcrt_builtins := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)LIBCRT_BUILTINS)
+endif
 ifeq ($(LOCAL_NO_LIBGCC),true)
 my_target_libgcc :=
 else
@@ -54,6 +59,7 @@
 my_target_crtbegin_so_o := $(wildcard $(my_ndk_sysroot_lib)/crtbegin_so.o)
 my_target_crtend_so_o := $(wildcard $(my_ndk_sysroot_lib)/crtend_so.o)
 endif
+$(linked_module): PRIVATE_TARGET_LIBCRT_BUILTINS := $(my_target_libcrt_builtins)
 $(linked_module): PRIVATE_TARGET_LIBGCC := $(my_target_libgcc)
 $(linked_module): PRIVATE_TARGET_LIBATOMIC := $(my_target_libatomic)
 $(linked_module): PRIVATE_TARGET_CRTBEGIN_SO_O := $(my_target_crtbegin_so_o)
@@ -64,6 +70,7 @@
         $(all_libraries) \
         $(my_target_crtbegin_so_o) \
         $(my_target_crtend_so_o) \
+        $(my_target_libcrt_builtins) \
         $(my_target_libgcc) \
         $(my_target_libatomic) \
         $(LOCAL_ADDITIONAL_DEPENDENCIES)
diff --git a/core/soong_app_prebuilt.mk b/core/soong_app_prebuilt.mk
index 837920f..f723633 100644
--- a/core/soong_app_prebuilt.mk
+++ b/core/soong_app_prebuilt.mk
@@ -1,6 +1,16 @@
 # App prebuilt coming from Soong.
 # Extra inputs:
+# LOCAL_SOONG_BUILT_INSTALLED
+# LOCAL_SOONG_BUNDLE
+# LOCAL_SOONG_CLASSES_JAR
+# LOCAL_SOONG_DEX_JAR
+# LOCAL_SOONG_HEADER_JAR
+# LOCAL_SOONG_JACOCO_REPORT_CLASSES_JAR
+# LOCAL_SOONG_PROGUARD_DICT
 # LOCAL_SOONG_RESOURCE_EXPORT_PACKAGE
+# LOCAL_SOONG_RRO_DIRS
+# LOCAL_SOONG_JNI_LIBS_$(TARGET_ARCH)
+# LOCAL_SOONG_JNI_LIBS_$(TARGET_2ND_ARCH)
 
 ifneq ($(LOCAL_MODULE_MAKEFILE),$(SOONG_ANDROID_MK))
   $(call pretty-error,soong_app_prebuilt.mk may only be used from Soong)
@@ -59,20 +69,19 @@
 
 java-dex: $(LOCAL_SOONG_DEX_JAR)
 
-# defines built_odex along with rule to install odex
-include $(BUILD_SYSTEM)/dex_preopt_odex_install.mk
 
 ifneq ($(BUILD_PLATFORM_ZIP),)
   $(eval $(call copy-one-file,$(LOCAL_SOONG_DEX_JAR),$(dir $(LOCAL_BUILT_MODULE))package.dex.apk))
 endif
 
-ifdef LOCAL_DEX_PREOPT
-  $(built_odex): $(LOCAL_SOONG_DEX_JAR)
-	$(call dexpreopt-one-file,$<,$@)
-  $(eval $(call dexpreopt-copy-jar,$(LOCAL_PREBUILT_MODULE_FILE),$(LOCAL_BUILT_MODULE),$(LOCAL_STRIP_DEX)))
-else
-  $(eval $(call copy-one-file,$(LOCAL_PREBUILT_MODULE_FILE),$(LOCAL_BUILT_MODULE)))
-endif
+$(eval $(call copy-one-file,$(LOCAL_PREBUILT_MODULE_FILE),$(LOCAL_BUILT_MODULE)))
+
+my_built_installed := $(foreach f,$(LOCAL_SOONG_BUILT_INSTALLED),\
+  $(call word-colon,1,$(f)):$(PRODUCT_OUT)$(call word-colon,2,$(f)))
+my_installed := $(call copy-many-files, $(my_built_installed))
+ALL_MODULES.$(my_register_name).INSTALLED += $(my_installed)
+ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(my_built_installed)
+$(my_register_name): $(my_installed)
 
 # embedded JNI will already have been handled by soong
 my_embed_jni :=
@@ -99,7 +108,7 @@
   PACKAGES.$(LOCAL_MODULE).CERTIFICATE := $(LOCAL_CERTIFICATE)
   PACKAGES.$(LOCAL_MODULE).PRIVATE_KEY := $(patsubst %.x509.pem,%.pk8,$(LOCAL_CERTIFICATE))
 endif
-
+include $(BUILD_SYSTEM)/app_certificate_validate.mk
 PACKAGES.$(LOCAL_MODULE).OVERRIDES := $(strip $(LOCAL_OVERRIDES_PACKAGES))
 
 ifdef LOCAL_SOONG_BUNDLE
diff --git a/core/soong_cc_prebuilt.mk b/core/soong_cc_prebuilt.mk
index ae67fb8..088b076 100644
--- a/core/soong_cc_prebuilt.mk
+++ b/core/soong_cc_prebuilt.mk
@@ -188,7 +188,7 @@
       $(LOCAL_STATIC_LIBRARIES))
 installed_static_library_notice_file_targets := \
     $(foreach lib,$(my_static_libraries) $(LOCAL_WHOLE_STATIC_LIBRARIES), \
-      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST,TARGET)-STATIC_LIBRARIES-$(lib))
+      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST$(if $(my_host_cross),_CROSS,),TARGET)-STATIC_LIBRARIES-$(lib))
 
 $(notice_target): | $(installed_static_library_notice_file_targets)
 $(LOCAL_INSTALLED_MODULE): | $(notice_target)
diff --git a/core/soong_config.mk b/core/soong_config.mk
index 7a884e0..77329c3 100644
--- a/core/soong_config.mk
+++ b/core/soong_config.mk
@@ -13,32 +13,14 @@
 endif
 endif
 
+include $(BUILD_SYSTEM)/dex_preopt_config.mk
+
 ifeq ($(WRITE_SOONG_VARIABLES),true)
-# Converts a list to a JSON list.
-# $1: List separator.
-# $2: List.
-_json_list = [$(if $(2),"$(subst $(1),"$(comma)",$(2))")]
-
-# Converts a space-separated list to a JSON list.
-json_list = $(call _json_list,$(space),$(1))
-
-# Converts a comma-separated list to a JSON list.
-csv_to_json_list = $(call _json_list,$(comma),$(1))
-
-# 1: Key name
-# 2: Value
-add_json_val = $(eval _contents := $$(_contents)    "$$(strip $$(1))":$$(space)$$(strip $$(2))$$(comma)$$(newline))
-add_json_str = $(call add_json_val,$(1),"$(strip $(2))")
-add_json_list = $(call add_json_val,$(1),$(call json_list,$(patsubst %,%,$(2))))
-add_json_csv = $(call add_json_val,$(1),$(call csv_to_json_list,$(strip $(2))))
-add_json_bool = $(call add_json_val,$(1),$(if $(strip $(2)),true,false))
-
-invert_bool = $(if $(strip $(1)),,true)
 
 # Create soong.variables with copies of makefile settings.  Runs every build,
 # but only updates soong.variables if it changes
 $(shell mkdir -p $(dir $(SOONG_VARIABLES)))
-_contents := {$(newline)
+$(call json_start)
 
 $(call add_json_str,  Make_suffix, -$(TARGET_PRODUCT))
 
@@ -54,6 +36,7 @@
 
 $(call add_json_bool, Allow_missing_dependencies,        $(ALLOW_MISSING_DEPENDENCIES))
 $(call add_json_bool, Unbundled_build,                   $(TARGET_BUILD_APPS))
+$(call add_json_bool, Unbundled_build_sdks_from_source,  $(UNBUNDLED_BUILD_SDKS_FROM_SOURCE))
 $(call add_json_bool, Pdk,                               $(filter true,$(TARGET_BUILD_PDK)))
 
 $(call add_json_bool, Debuggable,                        $(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
@@ -100,6 +83,8 @@
 $(call add_json_bool, EnableCFI,                         $(call invert_bool,$(filter false,$(ENABLE_CFI))))
 $(call add_json_list, CFIExcludePaths,                   $(CFI_EXCLUDE_PATHS) $(PRODUCT_CFI_EXCLUDE_PATHS))
 $(call add_json_list, CFIIncludePaths,                   $(CFI_INCLUDE_PATHS) $(PRODUCT_CFI_INCLUDE_PATHS))
+$(call add_json_bool, EnableXOM,                         $(filter true,$(ENABLE_XOM)))
+$(call add_json_list, XOMExcludePaths,                   $(XOM_EXCLUDE_PATHS) $(PRODUCT_XOM_EXCLUDE_PATHS))
 $(call add_json_list, IntegerOverflowExcludePaths,       $(INTEGER_OVERFLOW_EXCLUDE_PATHS) $(PRODUCT_INTEGER_OVERFLOW_EXCLUDE_PATHS))
 
 $(call add_json_bool, ClangTidy,                         $(filter 1 true,$(WITH_TIDY)))
@@ -112,7 +97,6 @@
 $(call add_json_bool, ArtUseReadBarrier,                 $(call invert_bool,$(filter false,$(PRODUCT_ART_USE_READ_BARRIER))))
 $(call add_json_bool, Binder32bit,                       $(BINDER32BIT))
 $(call add_json_str,  BtConfigIncludeDir,                $(BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR))
-$(call add_json_bool, Device_uses_hwc2,                  $(filter true,$(TARGET_USES_HWC2)))
 $(call add_json_list, DeviceKernelHeaders,               $(TARGET_PROJECT_SYSTEM_INCLUDES))
 $(call add_json_bool, DevicePrefer32BitApps,             $(filter true,$(TARGET_PREFER_32_BIT_APPS)))
 $(call add_json_bool, DevicePrefer32BitExecutables,      $(filter true,$(TARGET_PREFER_32_BIT_EXECUTABLES)))
@@ -123,11 +107,16 @@
 $(call add_json_list, Platform_systemsdk_versions,       $(PLATFORM_SYSTEMSDK_VERSIONS))
 $(call add_json_bool, Malloc_not_svelte,                 $(call invert_bool,$(filter true,$(MALLOC_SVELTE))))
 $(call add_json_str,  Override_rs_driver,                $(OVERRIDE_RS_DRIVER))
+
 $(call add_json_bool, UncompressPrivAppDex,              $(call invert_bool,$(filter true,$(DONT_UNCOMPRESS_PRIV_APPS_DEXS))))
 $(call add_json_list, ModulesLoadedByPrivilegedModules,  $(PRODUCT_LOADED_BY_PRIVILEGED_MODULES))
-$(call add_json_bool, DefaultStripDex,                   $(call invert_bool,$(filter nostripping,$(DEX_PREOPT_DEFAULT))))
-$(call add_json_bool, DisableDexPreopt,                  $(filter false,$(WITH_DEXPREOPT)))
+
+$(call add_json_list, BootJars,                          $(PRODUCT_BOOT_JARS))
+$(call add_json_list, PreoptBootJars,                    $(DEXPREOPT_BOOT_JARS_MODULES))
+
+$(call add_json_bool, DisableDexPreopt,                  $(call invert_bool,$(filter true,$(WITH_DEXPREOPT))))
 $(call add_json_list, DisableDexPreoptModules,           $(DEXPREOPT_DISABLED_MODULES))
+$(call add_json_str,  DexPreoptProfileDir,               $(PRODUCT_DEX_PREOPT_PROFILE_DIR))
 
 $(call add_json_bool, Product_is_iot,                    $(filter true,$(PRODUCT_IOT)))
 
@@ -154,17 +143,26 @@
 $(call add_json_list, BoardPlatPublicSepolicyDirs,       $(BOARD_PLAT_PUBLIC_SEPOLICY_DIR))
 $(call add_json_list, BoardPlatPrivateSepolicyDirs,      $(BOARD_PLAT_PRIVATE_SEPOLICY_DIR))
 
-_contents := $(_contents)    "VendorVars": {$(newline)
+$(call add_json_bool, FlattenApex,                       $(filter true,$(TARGET_FLATTEN_APEX)))
+
+$(call add_json_str,  DexpreoptGlobalConfig,             $(DEX_PREOPT_CONFIG))
+
+$(call add_json_list, ManifestPackageNameOverrides,      $(PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES))
+
+$(call add_json_bool, EnforceSystemCertificate,          $(ENFORCE_SYSTEM_CERTIFICATE))
+$(call add_json_list, EnforceSystemCertificateWhitelist, $(ENFORCE_SYSTEM_CERTIFICATE_WHITELIST))
+
+$(call add_json_map, VendorVars)
 $(foreach namespace,$(SOONG_CONFIG_NAMESPACES),\
-  $(eval _contents := $$(_contents)        "$(namespace)": {$$(newline)) \
+  $(call add_json_map, $(namespace))\
   $(foreach key,$(SOONG_CONFIG_$(namespace)),\
-    $(eval _contents := $$(_contents)            "$(key)": "$(SOONG_CONFIG_$(namespace)_$(key))",$$(newline)))\
-  $(eval _contents := $$(_contents)$(if $(strip $(SOONG_CONFIG_$(namespace))),__SV_END)        },$$(newline)))
-_contents := $(_contents)$(if $(strip $(SOONG_CONFIG_NAMESPACES)),__SV_END)    },$(newline)
+    $(call add_json_str,$(key),$(SOONG_CONFIG_$(namespace)_$(key))))\
+  $(call end_json_map))
+$(call end_json_map)
 
-_contents := $(subst $(comma)$(newline)__SV_END,$(newline),$(_contents)__SV_END}$(newline))
+$(call json_end)
 
-$(file >$(SOONG_VARIABLES).tmp,$(_contents))
+$(file >$(SOONG_VARIABLES).tmp,$(json_contents))
 
 $(shell if ! cmp -s $(SOONG_VARIABLES).tmp $(SOONG_VARIABLES); then \
 	  mv $(SOONG_VARIABLES).tmp $(SOONG_VARIABLES); \
@@ -172,15 +170,4 @@
 	  rm $(SOONG_VARIABLES).tmp; \
 	fi)
 
-_json_list :=
-json_list :=
-csv_to_json_list :=
-add_json_val :=
-add_json_str :=
-add_json_list :=
-add_json_csv :=
-add_json_bool :=
-invert_bool :=
-_contents :=
-
 endif # CONFIGURE_SOONG
diff --git a/core/soong_java_prebuilt.mk b/core/soong_java_prebuilt.mk
index 3e6b261..a62590d 100644
--- a/core/soong_java_prebuilt.mk
+++ b/core/soong_java_prebuilt.mk
@@ -1,5 +1,7 @@
 # Java prebuilt coming from Soong.
 # Extra inputs:
+# LOCAL_SOONG_BUILT_INSTALLED
+# LOCAL_SOONG_CLASSES_JAR
 # LOCAL_SOONG_HEADER_JAR
 # LOCAL_SOONG_DEX_JAR
 # LOCAL_SOONG_JACOCO_REPORT_CLASSES_JAR
@@ -19,13 +21,11 @@
 full_classes_pre_proguard_jar := $(intermediates.COMMON)/classes-pre-proguard.jar
 full_classes_header_jar := $(intermediates.COMMON)/classes-header.jar
 common_javalib.jar := $(intermediates.COMMON)/javalib.jar
-hiddenapi_whitelist_txt := $(intermediates.COMMON)/hiddenapi/whitelist.txt
-hiddenapi_greylist_txt := $(intermediates.COMMON)/hiddenapi/greylist.txt
-hiddenapi_darkgreylist_txt := $(intermediates.COMMON)/hiddenapi/darkgreylist.txt
-hiddenapi_greylist_metadata_csv := $(intermediates.COMMON)/hiddenapi/greylist.csv
+hiddenapi_flags_csv := $(intermediates.COMMON)/hiddenapi/flags.csv
+hiddenapi_metadata_csv := $(intermediates.COMMON)/hiddenapi/greylist.csv
 
-$(eval $(call copy-one-file,$(LOCAL_PREBUILT_MODULE_FILE),$(full_classes_jar)))
-$(eval $(call copy-one-file,$(LOCAL_PREBUILT_MODULE_FILE),$(full_classes_pre_proguard_jar)))
+$(eval $(call copy-one-file,$(LOCAL_SOONG_CLASSES_JAR),$(full_classes_jar)))
+$(eval $(call copy-one-file,$(LOCAL_SOONG_CLASSES_JAR),$(full_classes_pre_proguard_jar)))
 
 ifdef LOCAL_SOONG_JACOCO_REPORT_CLASSES_JAR
   $(eval $(call copy-one-file,$(LOCAL_SOONG_JACOCO_REPORT_CLASSES_JAR),\
@@ -80,39 +80,26 @@
         # We use full_classes_jar here, which is the post-proguard jar (on the basis that we also
         # have a full_classes_pre_proguard_jar). This is consistent with the equivalent code in
         # java.mk.
-        $(eval $(call hiddenapi-generate-greylist-txt,$(full_classes_jar),$(hiddenapi_whitelist_txt),$(hiddenapi_greylist_txt),$(hiddenapi_darkgreylist_txt),$(hiddenapi_greylist_metadata_csv)))
+        $(eval $(call hiddenapi-generate-csv,$(full_classes_jar),$(hiddenapi_flags_csv),$(hiddenapi_metadata_csv)))
         $(eval $(call hiddenapi-copy-soong-jar,$(LOCAL_SOONG_DEX_JAR),$(common_javalib.jar)))
+
+        ifeq (true,$(WITH_DEXPREOPT))
+          # For libart, the boot jars' odex files are replaced by $(DEFAULT_DEX_PREOPT_INSTALLED_IMAGE).
+          # We use this installed_odex trick to get boot.art installed.
+          installed_odex := $(DEFAULT_DEX_PREOPT_INSTALLED_IMAGE)
+          # Append the odex for the 2nd arch if we have one.
+          installed_odex += $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_INSTALLED_IMAGE)
+          ALL_MODULES.$(my_register_name).INSTALLED += $(installed_odex)
+          # Make sure to install the .odex and .vdex when you run "make <module_name>"
+         $(my_all_targets): $(installed_odex)
+        endif
       else # !is_boot_jar
         $(eval $(call copy-one-file,$(LOCAL_SOONG_DEX_JAR),$(common_javalib.jar)))
       endif # is_boot_jar
       $(eval $(call add-dependency,$(common_javalib.jar),$(full_classes_jar) $(full_classes_header_jar)))
 
-      dex_preopt_profile_src_file := $(common_javalib.jar)
-
-      # defines built_odex along with rule to install odex
-      include $(BUILD_SYSTEM)/dex_preopt_odex_install.mk
-
-      dex_preopt_profile_src_file :=
-
-      ifdef LOCAL_DEX_PREOPT
-        ifneq ($(dexpreopt_boot_jar_module),) # boot jar
-          # boot jar's rules are defined in dex_preopt.mk
-          dexpreopted_boot_jar := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(dexpreopt_boot_jar_module)_nodex.jar
-          $(eval $(call copy-one-file,$(dexpreopted_boot_jar),$(LOCAL_BUILT_MODULE)))
-
-          # For libart boot jars, we don't have .odex files.
-        else # ! boot jar
-          $(built_odex): PRIVATE_MODULE := $(LOCAL_MODULE)
-          # Use pattern rule - we may have multiple built odex files.
-$(built_odex) : $(dir $(LOCAL_BUILT_MODULE))% : $(common_javalib.jar)
-	@echo "Dexpreopt Jar: $(PRIVATE_MODULE) ($@)"
-	$(call dexpreopt-one-file,$<,$@)
-
-         $(eval $(call dexpreopt-copy-jar,$(common_javalib.jar),$(LOCAL_BUILT_MODULE),$(LOCAL_STRIP_DEX)))
-        endif # ! boot jar
-      else # LOCAL_DEX_PREOPT
-        $(eval $(call copy-one-file,$(common_javalib.jar),$(LOCAL_BUILT_MODULE)))
-      endif # LOCAL_DEX_PREOPT
+      $(eval $(call copy-one-file,$(LOCAL_PREBUILT_MODULE_FILE),$(LOCAL_BUILT_MODULE)))
+      $(eval $(call add-dependency,$(LOCAL_BUILT_MODULE),$(common_javalib.jar)))
     else # LOCAL_IS_HOST_MODULE
       $(eval $(call copy-one-file,$(LOCAL_SOONG_DEX_JAR),$(LOCAL_BUILT_MODULE)))
       $(eval $(call add-dependency,$(LOCAL_BUILT_MODULE),$(full_classes_jar) $(full_classes_header_jar)))
@@ -126,7 +113,7 @@
       # We use full_classes_jar here, which is the post-proguard jar (on the basis that we also
       # have a full_classes_pre_proguard_jar). This is consistent with the equivalent code in
       # java.mk.
-      $(eval $(call hiddenapi-generate-greylist-txt,$(full_classes_jar),$(hiddenapi_whitelist_txt),$(hiddenapi_greylist_txt),$(hiddenapi_darkgreylist_txt),$(hiddenapi_greylist_metadata_csv)))
+      $(eval $(call hiddenapi-generate-csv,$(full_classes_jar),$(hiddenapi_flags_csv),$(hiddenapi_metadata_csv)))
     endif
 
     $(eval $(call copy-one-file,$(full_classes_jar),$(LOCAL_BUILT_MODULE)))
@@ -137,6 +124,13 @@
   $(eval $(call copy-one-file,$(full_classes_jar),$(LOCAL_BUILT_MODULE)))
 endif  # LOCAL_SOONG_DEX_JAR
 
+my_built_installed := $(foreach f,$(LOCAL_SOONG_BUILT_INSTALLED),\
+  $(call word-colon,1,$(f)):$(PRODUCT_OUT)$(call word-colon,2,$(f)))
+my_installed := $(call copy-many-files, $(my_built_installed))
+ALL_MODULES.$(my_register_name).INSTALLED += $(my_installed)
+ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(my_built_installed)
+$(my_register_name): $(my_installed)
+
 ifdef LOCAL_SOONG_AAR
   ALL_MODULES.$(LOCAL_MODULE).AAR := $(LOCAL_SOONG_AAR)
 endif
diff --git a/core/static_java_library.mk b/core/static_java_library.mk
index 2a87705..cee7c9e 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -110,7 +110,7 @@
 framework_res_package_export :=
 # Please refer to package.mk
 ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
-ifneq ($(filter-out current system_current test_current,$(LOCAL_SDK_RES_VERSION))$(if $(TARGET_BUILD_APPS),$(filter current system_current test_current,$(LOCAL_SDK_RES_VERSION))),)
+ifneq ($(filter-out current system_current test_current,$(LOCAL_SDK_RES_VERSION))$(if $(TARGET_BUILD_APPS_USE_PREBUILT_SDK),$(filter current system_current test_current,$(LOCAL_SDK_RES_VERSION))),)
 framework_res_package_export := \
     $(call resolve-prebuilt-sdk-jar-path,$(LOCAL_SDK_RES_VERSION))
 else
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index 42a3bea..c4f9a52 100644
--- a/core/version_defaults.mk
+++ b/core/version_defaults.mk
@@ -179,8 +179,11 @@
     # SDK version the package was built for, otherwise it should fall back to
     # assuming the device can only support APIs as of the previous official
     # public release.
-    # This value will always be 0 for release builds.
-    PLATFORM_PREVIEW_SDK_VERSION := 0
+    # This value will always be forced to 0 for release builds by the logic
+    # in the "ifeq" block above, so the value below will be used on any
+    # non-release builds, and it should always be at least 1, to indicate that
+    # APIs may have changed since the claimed PLATFORM_SDK_VERSION.
+    PLATFORM_PREVIEW_SDK_VERSION := 1
   endif
 endif
 .KATI_READONLY := PLATFORM_PREVIEW_SDK_VERSION
@@ -249,7 +252,7 @@
     #  It must be of the form "YYYY-MM-DD" on production devices.
     #  It must match one of the Android Security Patch Level strings of the Public Security Bulletins.
     #  If there is no $PLATFORM_SECURITY_PATCH set, keep it empty.
-      PLATFORM_SECURITY_PATCH := 2018-09-05
+      PLATFORM_SECURITY_PATCH := 2018-12-05
 endif
 .KATI_READONLY := PLATFORM_SECURITY_PATCH
 
@@ -311,7 +314,7 @@
   # If no BUILD_NUMBER is set, create a useful "I am an engineering build
   # from this date/time" value.  Make it start with a non-digit so that
   # anyone trying to parse it as an integer will probably get "0".
-  BUILD_NUMBER := eng.$(shell echo $${USER:0:6}).$(shell $(DATE) +%Y%m%d.%H%M%S)
+  BUILD_NUMBER := eng.$(shell echo $${BUILD_USERNAME:0:6}).$(shell $(DATE) +%Y%m%d.%H%M%S)
   HAS_BUILD_NUMBER := false
 endif
 .KATI_READONLY := BUILD_NUMBER HAS_BUILD_NUMBER
diff --git a/envsetup.sh b/envsetup.sh
index a4d950e..c4c4972 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -4,28 +4,31 @@
 Run "m help" for help with the build system itself.
 
 Invoke ". build/envsetup.sh" from your shell to add the following functions to your environment:
-- lunch:     lunch <product_name>-<build_variant>
-             Selects <product_name> as the product to build, and <build_variant> as the variant to
-             build, and stores those selections in the environment to be read by subsequent
-             invocations of 'm' etc.
-- tapas:     tapas [<App1> <App2> ...] [arm|x86|mips|arm64|x86_64|mips64] [eng|userdebug|user]
-- croot:     Changes directory to the top of the tree.
-- m:         Makes from the top of the tree.
-- mm:        Builds all of the modules in the current directory, but not their dependencies.
-- mmm:       Builds all of the modules in the supplied directories, but not their dependencies.
-             To limit the modules being built use the syntax: mmm dir/:target1,target2.
-- mma:       Builds all of the modules in the current directory, and their dependencies.
-- mmma:      Builds all of the modules in the supplied directories, and their dependencies.
-- provision: Flash device with all required partitions. Options will be passed on to fastboot.
-- cgrep:     Greps on all local C/C++ files.
-- ggrep:     Greps on all local Gradle files.
-- jgrep:     Greps on all local Java files.
-- resgrep:   Greps on all local res/*.xml files.
-- mangrep:   Greps on all local AndroidManifest.xml files.
-- mgrep:     Greps on all local Makefiles files.
-- sepgrep:   Greps on all local sepolicy files.
-- sgrep:     Greps on all local source files.
-- godir:     Go to the directory containing a file.
+- lunch:      lunch <product_name>-<build_variant>
+              Selects <product_name> as the product to build, and <build_variant> as the variant to
+              build, and stores those selections in the environment to be read by subsequent
+              invocations of 'm' etc.
+- tapas:      tapas [<App1> <App2> ...] [arm|x86|mips|arm64|x86_64|mips64] [eng|userdebug|user]
+- croot:      Changes directory to the top of the tree.
+- m:          Makes from the top of the tree.
+- mm:         Builds all of the modules in the current directory, but not their dependencies.
+- mmm:        Builds all of the modules in the supplied directories, but not their dependencies.
+              To limit the modules being built use the syntax: mmm dir/:target1,target2.
+- mma:        Builds all of the modules in the current directory, and their dependencies.
+- mmma:       Builds all of the modules in the supplied directories, and their dependencies.
+- provision:  Flash device with all required partitions. Options will be passed on to fastboot.
+- cgrep:      Greps on all local C/C++ files.
+- ggrep:      Greps on all local Gradle files.
+- jgrep:      Greps on all local Java files.
+- resgrep:    Greps on all local res/*.xml files.
+- mangrep:    Greps on all local AndroidManifest.xml files.
+- mgrep:      Greps on all local Makefiles files.
+- sepgrep:    Greps on all local sepolicy files.
+- sgrep:      Greps on all local source files.
+- godir:      Go to the directory containing a file.
+- allmod:     List all modules.
+- gomod:      Go to the directory containing a module.
+- refreshmod: Refresh list of modules for allmod/gomod.
 
 Environment options:
 - SANITIZE_HOST: Set to 'true' to use ASAN for all host modules. Note that
@@ -263,7 +266,14 @@
     fi
 
     export PATH=$ANDROID_BUILD_PATHS$PATH
-    export PYTHONPATH=$T/development/python-packages:$PYTHONPATH
+
+    # out with the duplicate old
+    if [ -n $ANDROID_PYTHONPATH ]; then
+        export PYTHONPATH=${PYTHONPATH//$ANDROID_PYTHONPATH/}
+    fi
+    # and in with the new
+    export ANDROID_PYTHONPATH=$T/development/python-packages:
+    export PYTHONPATH=$ANDROID_PYTHONPATH$PYTHONPATH
 
     export ANDROID_JAVA_HOME=$(get_abs_build_var ANDROID_JAVA_HOME)
     export JAVA_HOME=$ANDROID_JAVA_HOME
@@ -359,6 +369,9 @@
         complete -C "bit --tab" bit
     fi
     complete -F _lunch lunch
+
+    complete -F _complete_android_module_names gomod
+    complete -F _complete_android_module_names m
 }
 
 function choosetype()
@@ -759,6 +772,9 @@
 {
     local TOPFILE=build/make/core/envsetup.mk
     local HERE=$PWD
+    if [ "$1" ]; then
+        \cd $1
+    fi;
     local T=
     while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
         T=`PWD= /bin/pwd`
@@ -839,24 +855,29 @@
             # Remove the leading ./ and trailing / if any exists.
             DIR=${DIR#./}
             DIR=${DIR%/}
-            if [ -f $DIR/Android.mk -o -f $DIR/Android.bp ]; then
-                local TO_CHOP=`(\cd -P -- $T && pwd -P) | wc -c | tr -d ' '`
-                local TO_CHOP=`expr $TO_CHOP + 1`
-                local START=`PWD= /bin/pwd`
-                local MDIR=`echo $START | cut -c${TO_CHOP}-`
-                if [ "$MDIR" = "" ] ; then
-                    MDIR=$DIR
-                else
-                    MDIR=$MDIR/$DIR
+            local M
+            if [ "$DIR_MODULES" = "" ]; then
+                M=$(findmakefile $DIR)
+            else
+                # Only check the target directory if a module is specified.
+                if [ -f $DIR/Android.mk -o -f $DIR/Android.bp ]; then
+                    local HERE=$PWD
+                    cd $DIR
+                    M=`PWD= /bin/pwd`
+                    M=$M/Android.mk
+                    cd $HERE
                 fi
-                MDIR=${MDIR%/.}
+            fi
+            if [ "$M" ]; then
+                # Remove the path to top as the makefilepath needs to be relative
+                local M=`echo $M|sed 's:'$T'/::'`
                 if [ "$DIR_MODULES" = "" ]; then
-                    MODULES_IN_PATHS="$MODULES_IN_PATHS MODULES-IN-$MDIR"
-                    GET_INSTALL_PATHS="$GET_INSTALL_PATHS GET-INSTALL-PATH-IN-$MDIR"
+                    MODULES_IN_PATHS="$MODULES_IN_PATHS MODULES-IN-$(dirname ${M})"
+                    GET_INSTALL_PATHS="$GET_INSTALL_PATHS GET-INSTALL-PATH-IN-$(dirname ${M})"
                 else
                     MODULES="$MODULES $DIR_MODULES"
                 fi
-                MAKEFILE="$MAKEFILE $MDIR/Android.mk"
+                MAKEFILE="$MAKEFILE $M"
             else
                 case $DIR in
                   showcommands | snod | dist | *=*) ARGS="$ARGS $DIR";;
@@ -1095,7 +1116,7 @@
 {
     local PID="$1"
     if [ "$PID" ] ; then
-        if [[ "$(adb shell cat /proc/$PID/exe | xxd -l 1 -s 4 -ps)" -eq "02" ]] ; then
+        if [[ "$(adb shell cat /proc/$PID/exe | xxd -l 1 -s 4 -p)" -eq "02" ]] ; then
             echo "64"
         else
             echo ""
@@ -1109,7 +1130,7 @@
     Darwin)
         function sgrep()
         {
-            find -E . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.(c|h|cc|cpp|S|java|xml|sh|mk|aidl|vts)' \
+            find -E . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.(c|h|cc|cpp|hpp|S|java|xml|sh|mk|aidl|vts)' \
                 -exec grep --color -n "$@" {} +
         }
 
@@ -1117,7 +1138,7 @@
     *)
         function sgrep()
         {
-            find . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.\(c\|h\|cc\|cpp\|S\|java\|xml\|sh\|mk\|aidl\|vts\)' \
+            find . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.\(c\|h\|cc\|cpp\|hpp\|S\|java\|xml\|sh\|mk\|aidl\|vts\)' \
                 -exec grep --color -n "$@" {} +
         }
         ;;
@@ -1182,7 +1203,7 @@
 
         function treegrep()
         {
-            find -E . -name .repo -prune -o -name .git -prune -o -type f -iregex '.*\.(c|h|cpp|S|java|xml)' \
+            find -E . -name .repo -prune -o -name .git -prune -o -type f -iregex '.*\.(c|h|cpp|hpp|S|java|xml)' \
                 -exec grep --color -n -i "$@" {} +
         }
 
@@ -1196,7 +1217,7 @@
 
         function treegrep()
         {
-            find . -name .repo -prune -o -name .git -prune -o -regextype posix-egrep -iregex '.*\.(c|h|cpp|S|java|xml)' -type f \
+            find . -name .repo -prune -o -name .git -prune -o -regextype posix-egrep -iregex '.*\.(c|h|cpp|hpp|S|java|xml)' -type f \
                 -exec grep --color -n -i "$@" {} +
         }
 
@@ -1463,6 +1484,77 @@
     \cd $T/$pathname
 }
 
+# Update module-info.json in out.
+function refreshmod() {
+    if [ ! "$ANDROID_PRODUCT_OUT" ]; then
+        echo "No ANDROID_PRODUCT_OUT. Try running 'lunch' first." >&2
+        return 1
+    fi
+
+    echo "Refreshing modules (building module-info.json). Log at $ANDROID_PRODUCT_OUT/module-info.json.build.log." >&2
+
+    # for the output of the next command
+    mkdir -p $ANDROID_PRODUCT_OUT || return 1
+
+    # Note, can't use absolute path because of the way make works.
+    m out/target/product/$(get_build_var TARGET_DEVICE)/module-info.json \
+        > $ANDROID_PRODUCT_OUT/module-info.json.build.log 2>&1
+}
+
+# List all modules for the current device, as cached in module-info.json. If any build change is
+# made and it should be reflected in the output, you should run 'refreshmod' first.
+function allmod() {
+    if [ ! "$ANDROID_PRODUCT_OUT" ]; then
+        echo "No ANDROID_PRODUCT_OUT. Try running 'lunch' first." >&2
+        return 1
+    fi
+
+    if [ ! -f "$ANDROID_PRODUCT_OUT/module-info.json" ]; then
+        echo "Could not find module-info.json. It will only be built once, and it can be updated with 'refreshmod'" >&2
+        refreshmod || return 1
+    fi
+
+    python -c "import json; print '\n'.join(sorted(json.load(open('$ANDROID_PRODUCT_OUT/module-info.json')).keys()))"
+}
+
+# Go to a specific module in the android tree, as cached in module-info.json. If any build change
+# is made, and it should be reflected in the output, you should run 'refreshmod' first.
+function gomod() {
+    if [ ! "$ANDROID_PRODUCT_OUT" ]; then
+        echo "No ANDROID_PRODUCT_OUT. Try running 'lunch' first." >&2
+        return 1
+    fi
+
+    if [[ $# -ne 1 ]]; then
+        echo "usage: gomod <module>" >&2
+        return 1
+    fi
+
+    if [ ! -f "$ANDROID_PRODUCT_OUT/module-info.json" ]; then
+        echo "Could not find module-info.json. It will only be built once, and it can be updated with 'refreshmod'" >&2
+        refreshmod || return 1
+    fi
+
+    local relpath=$(python -c "import json, os
+module = '$1'
+module_info = json.load(open('$ANDROID_PRODUCT_OUT/module-info.json'))
+if module not in module_info:
+    exit(1)
+print module_info[module]['path'][0]" 2>/dev/null)
+
+    if [ -z "$relpath" ]; then
+        echo "Could not find module '$1' (try 'refreshmod' if there have been build changes?)." >&2
+        return 1
+    else
+        cd $ANDROID_BUILD_TOP/$relpath
+    fi
+}
+
+function _complete_android_module_names() {
+    local word=${COMP_WORDS[COMP_CWORD]}
+    COMPREPLY=( $(allmod | grep -E "^$word") )
+}
+
 # Print colored exit condition
 function pez {
     "$@"
@@ -1567,10 +1659,19 @@
 
 function atest()
 {
-    # TODO (sbasi): Replace this to be a destination in the build out when & if
-    # atest is built by the build system. (This will be necessary if it ever
-    # depends on external pip projects).
-    "$(gettop)"/tools/tradefederation/core/atest/atest.py "$@"
+    # Let's use the built version over the prebuilt, then source code.
+    local os_arch=$(get_build_var HOST_PREBUILT_TAG)
+    local built_atest=${ANDROID_HOST_OUT}/bin/atest
+    local prebuilt_atest="$(gettop)"/prebuilts/asuite/atest/$os_arch/atest
+    if [[ -x $built_atest ]]; then
+        $built_atest "$@"
+    elif [[ -x $prebuilt_atest ]]; then
+        $prebuilt_atest "$@"
+    else
+        # TODO: once prebuilt atest released, remove the source code section
+        # and change the location of atest_completion.sh in addcompletions().
+        "$(gettop)"/tools/tradefederation/core/atest/atest.py "$@"
+    fi
 }
 
 # Zsh needs bashcompinit called to support bash-style completion.
@@ -1610,12 +1711,27 @@
     case $host_os_arch in
         linux-x86) "$(gettop)"/prebuilts/asuite/acloud/linux-x86/acloud "$@"
         ;;
+        darwin-x86) "$(gettop)"/prebuilts/asuite/acloud/darwin-x86/acloud "$@"
+        ;;
     *)
         echo "acloud is not supported on your host arch: $host_os_arch"
         ;;
     esac
 }
 
+function aidegen()
+{
+    # Always use the prebuilt version.
+    local host_os_arch=$(get_build_var HOST_PREBUILT_TAG)
+    case $host_os_arch in
+        linux-x86) "$(gettop)"/prebuilts/asuite/aidegen/linux-x86/aidegen "$@"
+        ;;
+    *)
+        echo "aidegen is not supported on your host arch: $host_os_arch"
+        ;;
+    esac
+}
+
 # Execute the contents of any vendorsetup.sh files we can find.
 function source_vendorsetup() {
     for dir in device vendor product; do
diff --git a/target/Android.mk b/target/Android.mk
deleted file mode 100644
index 9929b00..0000000
--- a/target/Android.mk
+++ /dev/null
@@ -1,23 +0,0 @@
-#
-# Copyright (C) 2017 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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-# Only if this Android.mk was included not by a symlink should it be used.
-# This facilitates the transition away from symlinks: b/64397960
-ifeq ($(LOCAL_PATH),build/make/target)
-include $(call first-makefiles-under,$(LOCAL_PATH))
-endif
diff --git a/target/OWNERS b/target/OWNERS
new file mode 100644
index 0000000..feb2742
--- /dev/null
+++ b/target/OWNERS
@@ -0,0 +1 @@
+hansson@google.com
diff --git a/target/board/BoardConfigEmuCommon.mk b/target/board/BoardConfigEmuCommon.mk
index 69ae6f0..1e325b9 100644
--- a/target/board/BoardConfigEmuCommon.mk
+++ b/target/board/BoardConfigEmuCommon.mk
@@ -10,7 +10,6 @@
 # no hardware camera
 USE_CAMERA_STUB := true
 
-TARGET_USES_HWC2 := true
 NUM_FRAMEBUFFER_SURFACE_BUFFERS := 3
 
 # Build OpenGLES emulation guest and host libraries
@@ -21,8 +20,6 @@
 # the GLES renderer disables itself if host GL acceleration isn't available.
 USE_OPENGL_RENDERER := true
 
-TARGET_COPY_OUT_VENDOR := vendor
-
 # ~100 MB vendor image. Please adjust system image / vendor image sizes
 # when finalizing them. The partition size needs to be a multiple of image
 # block size: 4096.
@@ -32,4 +29,4 @@
 DEVICE_MATRIX_FILE   := device/generic/goldfish/compatibility_matrix.xml
 
 BOARD_SEPOLICY_DIRS += device/generic/goldfish/sepolicy/common
-BOARD_PROPERTY_OVERRIDES_SPLIT_ENABLED := true
+
diff --git a/target/board/BoardConfigGsiCommon.mk b/target/board/BoardConfigGsiCommon.mk
index dfa103a..f9e9ee1 100644
--- a/target/board/BoardConfigGsiCommon.mk
+++ b/target/board/BoardConfigGsiCommon.mk
@@ -1,32 +1,44 @@
 # BoardConfigGsiCommon.mk
 #
 # Common compile-time definitions for GSI
+# Builds upon the mainline config.
 #
 
-# The generic product target doesn't have any hardware-specific pieces.
-TARGET_NO_BOOTLOADER := true
-TARGET_NO_KERNEL := true
+include build/make/target/board/BoardConfigMainlineCommon.mk
 
-# GSIs always use ext4.
-TARGET_USERIMAGES_USE_EXT4 := true
+# Enable system property split for Treble
+BOARD_PROPERTY_OVERRIDES_SPLIT_ENABLED := true
+
+# This flag is set by mainline but isn't desired for GSI.
+BOARD_USES_SYSTEM_OTHER_ODEX :=
+
 # GSIs are historically released in sparse format.
 # Some vendors' bootloaders don't work properly with raw format images. So
 # we explicit specify this need below (even though it's the current default).
 TARGET_USERIMAGES_SPARSE_EXT_DISABLED := false
 
+# system.img is always ext4 with sparse option
+# GSI also includes make_f2fs to support userdata parition in f2fs
+# for some devices
+TARGET_USERIMAGES_USE_F2FS := true
+
 # Enable dynamic system image size and reserved 64MB in it.
 BOARD_SYSTEMIMAGE_PARTITION_RESERVED_SIZE := 67108864
 
+# GSI always requires separate vendor packages to vendor.img
+TARGET_COPY_OUT_VENDOR := vendor
+
+# Creates metadata partition mount point under root for
+# the devices with metadata parition
+BOARD_USES_METADATA_PARTITION := true
+
 # Android Verified Boot (AVB):
-#   1) Sets BOARD_AVB_ENABLE to sign the GSI image.
-#   2) Sets AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED (--flag 2) in
-#      vbmeta.img to disable AVB verification.
+#   Set AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED (--flag 2) in
+#   vbmeta.img to disable AVB verification.
 #
 # To disable AVB for GSI, use the vbmeta.img and the GSI together.
 # To enable AVB for GSI, include the GSI public key into the device-specific
 # vbmeta.img.
-BOARD_AVB_ENABLE := true
-BOARD_AVB_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
 BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS += --flag 2
 
 # Enable chain partition for system.
@@ -35,27 +47,14 @@
 BOARD_AVB_SYSTEM_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
 BOARD_AVB_SYSTEM_ROLLBACK_INDEX_LOCATION := 1
 
+# GSI specific System Properties
 ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
 # GSI is always userdebug and needs a couple of properties taking precedence
 # over those set by the vendor.
 TARGET_SYSTEM_PROP := build/make/target/board/gsi_system.prop
 endif
-BOARD_VNDK_VERSION := current
-
-# system-as-root is mandatory from Android P
-TARGET_NO_RECOVERY := true
-BOARD_BUILD_SYSTEM_ROOT_IMAGE := true
-
-# 64 bits binder interface is mandatory from Android P
-TARGET_USES_64_BIT_BINDER := true
-
-# Android generic system image always create metadata partition
-BOARD_USES_METADATA_PARTITION := true
 
 # Set this to create /cache mount point for non-A/B devices that mounts /cache.
 # The partition size doesn't matter, just to make build pass.
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
 BOARD_CACHEIMAGE_PARTITION_SIZE := 16777216
-
-# Audio: must using XML format for Treblized devices
-USE_XML_AUDIO_POLICY_CONF := 1
diff --git a/target/board/BoardConfigMainlineCommon.mk b/target/board/BoardConfigMainlineCommon.mk
new file mode 100644
index 0000000..ec3c74f
--- /dev/null
+++ b/target/board/BoardConfigMainlineCommon.mk
@@ -0,0 +1,28 @@
+# BoardConfigMainlineCommon.mk
+#
+# Common compile-time definitions for mainline images.
+
+# The generic product target doesn't have any hardware-specific pieces.
+TARGET_NO_BOOTLOADER := true
+TARGET_NO_KERNEL := true
+
+TARGET_USERIMAGES_USE_EXT4 := true
+
+# system-as-root is mandatory from Android P
+TARGET_NO_RECOVERY := true
+BOARD_BUILD_SYSTEM_ROOT_IMAGE := true
+
+BOARD_VNDK_VERSION := current
+
+# Required flag for non-64 bit devices from P.
+TARGET_USES_64_BIT_BINDER := true
+
+# Puts odex files on system_other, as well as causing dex files not to get
+# stripped from APKs.
+BOARD_USES_SYSTEM_OTHER_ODEX := true
+
+# Audio: must using XML format for Treblized devices
+USE_XML_AUDIO_POLICY_CONF := 1
+
+BOARD_AVB_ENABLE := true
+BOARD_AVB_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
diff --git a/target/board/generic/BoardConfig.mk b/target/board/generic/BoardConfig.mk
index 738c037..cdb1d29 100644
--- a/target/board/generic/BoardConfig.mk
+++ b/target/board/generic/BoardConfig.mk
@@ -16,9 +16,10 @@
 # arm emulator specific definitions
 TARGET_ARCH := arm
 
-# Note: Before Pi, we built the platform images for ARMv7-A _without_ NEON.
+# Note: Before P, we built the platform images for ARMv7-A _without_ NEON.
+# Note: Before Q, we built the CTS and SDK images for ARMv7-A _without_ NEON.
 #
-ifneq ($(TARGET_BUILD_APPS)$(filter cts sdk,$(MAKECMDGOALS)),)
+ifneq ($(TARGET_BUILD_APPS),)
 # DO NOT USE
 #
 # This architecture variant should NOT be used for 32 bit arm platform
diff --git a/target/board/generic_arm64/BoardConfig.mk b/target/board/generic_arm64/BoardConfig.mk
index 1b6429c..3331d18 100644
--- a/target/board/generic_arm64/BoardConfig.mk
+++ b/target/board/generic_arm64/BoardConfig.mk
@@ -23,7 +23,7 @@
 TARGET_2ND_CPU_ABI := armeabi-v7a
 TARGET_2ND_CPU_ABI2 := armeabi
 
-ifneq ($(TARGET_BUILD_APPS)$(filter cts vts sdk,$(MAKECMDGOALS)),)
+ifneq ($(TARGET_BUILD_APPS)$(filter cts sdk vts,$(MAKECMDGOALS)),)
 # DO NOT USE
 # DO NOT USE
 #
@@ -41,7 +41,11 @@
 #
 # DO NOT USE
 # DO NOT USE
+ifneq ($(filter cts sdk vts,$(MAKECMDGOALS)),)
+TARGET_2ND_ARCH_VARIANT := armv7-a-neon
+else
 TARGET_2ND_ARCH_VARIANT := armv7-a
+endif
 # DO NOT USE
 # DO NOT USE
 TARGET_2ND_CPU_VARIANT := generic
diff --git a/target/board/generic_arm64_a/BoardConfig.mk b/target/board/generic_arm64_a/BoardConfig.mk
index 34a8ac0..68aedfc 100644
--- a/target/board/generic_arm64_a/BoardConfig.mk
+++ b/target/board/generic_arm64_a/BoardConfig.mk
@@ -14,7 +14,7 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_64.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_ARCH := arm64
 TARGET_ARCH_VARIANT := armv8-a
@@ -27,3 +27,6 @@
 TARGET_2ND_CPU_ABI := armeabi-v7a
 TARGET_2ND_CPU_ABI2 := armeabi
 TARGET_2ND_CPU_VARIANT := generic
+
+# This is a non-system-as-root Legacy GSI build target
+BOARD_BUILD_SYSTEM_ROOT_IMAGE := false
diff --git a/target/board/generic_arm64_ab/BoardConfig.mk b/target/board/generic_arm64_ab/BoardConfig.mk
index 88b90a8..6e54d81 100644
--- a/target/board/generic_arm64_ab/BoardConfig.mk
+++ b/target/board/generic_arm64_ab/BoardConfig.mk
@@ -14,7 +14,7 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_64.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_ARCH := arm64
 TARGET_ARCH_VARIANT := armv8-a
@@ -28,21 +28,12 @@
 TARGET_2ND_CPU_ABI2 := armeabi
 TARGET_2ND_CPU_VARIANT := generic
 
-# Enable A/B update
-TARGET_NO_RECOVERY := true
-BOARD_BUILD_SYSTEM_ROOT_IMAGE := true
-
 # TODO(jiyong) These might be SoC specific.
 BOARD_ROOT_EXTRA_FOLDERS += firmware firmware/radio persist
 BOARD_ROOT_EXTRA_SYMLINKS += /vendor/lib/dsp:/dsp
 BOARD_ROOT_EXTRA_SYMLINKS += /vendor/firmware_mnt/image:/firmware/image
 BOARD_ROOT_EXTRA_SYMLINKS += /vendor/firmware_mnt/verinfo:/firmware/verinfo
 
-# Set this to create /cache mount point for non-A/B devices that mounts /cache.
-# The partition size doesn't matter, just to make build pass.
-BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
-BOARD_CACHEIMAGE_PARTITION_SIZE := 16777216
-
 # TODO(b/36764215): remove this setting when the generic system image
 # no longer has QCOM-specific directories under /.
 BOARD_SEPOLICY_DIRS += build/target/board/generic_arm64_ab/sepolicy
diff --git a/target/board/generic_arm_a/BoardConfig.mk b/target/board/generic_arm_a/BoardConfig.mk
index 57a5196..464a74f 100644
--- a/target/board/generic_arm_a/BoardConfig.mk
+++ b/target/board/generic_arm_a/BoardConfig.mk
@@ -14,10 +14,16 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_32.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_ARCH := arm
 TARGET_ARCH_VARIANT := armv7-a-neon
 TARGET_CPU_ABI := armeabi-v7a
 TARGET_CPU_ABI2 := armeabi
 TARGET_CPU_VARIANT := generic
+
+# Legacy GSI keeps 32 bits binder for 32 bits CPU Arch
+TARGET_USES_64_BIT_BINDER := false
+
+# This is a non-system-as-root Legacy GSI build target
+BOARD_BUILD_SYSTEM_ROOT_IMAGE := false
diff --git a/target/board/generic_arm_ab/BoardConfig.mk b/target/board/generic_arm_ab/BoardConfig.mk
index 3d14842..9100094 100644
--- a/target/board/generic_arm_ab/BoardConfig.mk
+++ b/target/board/generic_arm_ab/BoardConfig.mk
@@ -14,7 +14,7 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_32.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_ARCH := arm
 TARGET_ARCH_VARIANT := armv7-a-neon
@@ -22,9 +22,8 @@
 TARGET_CPU_ABI2 := armeabi
 TARGET_CPU_VARIANT := generic
 
-# Enable A/B update
-TARGET_NO_RECOVERY := true
-BOARD_BUILD_SYSTEM_ROOT_IMAGE := true
+# Legacy GSI keeps 32 bits binder for 32 bits CPU Arch
+TARGET_USES_64_BIT_BINDER := false
 
 # TODO(jiyong) These might be SoC specific.
 BOARD_ROOT_EXTRA_FOLDERS += firmware firmware/radio persist
@@ -32,11 +31,6 @@
 BOARD_ROOT_EXTRA_SYMLINKS += /vendor/firmware_mnt/image:/firmware/image
 BOARD_ROOT_EXTRA_SYMLINKS += /vendor/firmware_mnt/verinfo:/firmware/verinfo
 
-# Set this to create /cache mount point for non-A/B devices that mounts /cache.
-# The partition size doesn't matter, just to make build pass.
-BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
-BOARD_CACHEIMAGE_PARTITION_SIZE := 16777216
-
 # TODO(b/36764215): remove this setting when the generic system image
 # no longer has QCOM-specific directories under /.
 BOARD_SEPOLICY_DIRS += build/target/board/generic_arm64_ab/sepolicy
diff --git a/target/board/generic_x86_64_a/BoardConfig.mk b/target/board/generic_x86_64_a/BoardConfig.mk
index 2c02604..07eef4f 100644
--- a/target/board/generic_x86_64_a/BoardConfig.mk
+++ b/target/board/generic_x86_64_a/BoardConfig.mk
@@ -14,7 +14,7 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_64.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_CPU_ABI := x86_64
 TARGET_ARCH := x86_64
@@ -23,3 +23,6 @@
 TARGET_2ND_CPU_ABI := x86
 TARGET_2ND_ARCH := x86
 TARGET_2ND_ARCH_VARIANT := x86_64
+
+# This is a non-system-as-root Legacy GSI build target
+BOARD_BUILD_SYSTEM_ROOT_IMAGE := false
diff --git a/target/board/generic_x86_64_ab/BoardConfig.mk b/target/board/generic_x86_64_ab/BoardConfig.mk
index a098dfe..1dd5e48 100644
--- a/target/board/generic_x86_64_ab/BoardConfig.mk
+++ b/target/board/generic_x86_64_ab/BoardConfig.mk
@@ -14,7 +14,7 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_64.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_CPU_ABI := x86_64
 TARGET_ARCH := x86_64
@@ -23,12 +23,3 @@
 TARGET_2ND_CPU_ABI := x86
 TARGET_2ND_ARCH := x86
 TARGET_2ND_ARCH_VARIANT := x86_64
-
-# Set this to create /cache mount point for non-A/B devices that mounts /cache.
-# The partition size doesn't matter, just to make build pass.
-BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
-BOARD_CACHEIMAGE_PARTITION_SIZE := 16777216
-
-# Enable A/B update
-TARGET_NO_RECOVERY := true
-BOARD_BUILD_SYSTEM_ROOT_IMAGE := true
diff --git a/target/board/generic_x86_a/BoardConfig.mk b/target/board/generic_x86_a/BoardConfig.mk
index 67cb07d..e3e8a3a 100644
--- a/target/board/generic_x86_a/BoardConfig.mk
+++ b/target/board/generic_x86_a/BoardConfig.mk
@@ -14,8 +14,14 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_32.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_CPU_ABI := x86
 TARGET_ARCH := x86
 TARGET_ARCH_VARIANT := x86
+
+# Legacy GSI keeps 32 bits binder for 32 bits CPU Arch
+TARGET_USES_64_BIT_BINDER := false
+
+# This is a non-system-as-root Legacy GSI build target
+BOARD_BUILD_SYSTEM_ROOT_IMAGE := false
diff --git a/target/board/generic_x86_ab/BoardConfig.mk b/target/board/generic_x86_ab/BoardConfig.mk
index db4dacd..53acffd 100644
--- a/target/board/generic_x86_ab/BoardConfig.mk
+++ b/target/board/generic_x86_ab/BoardConfig.mk
@@ -14,17 +14,11 @@
 # limitations under the License.
 #
 
-include build/make/target/board/treble_common_32.mk
+include build/make/target/board/BoardConfigGsiCommon.mk
 
 TARGET_CPU_ABI := x86
 TARGET_ARCH := x86
 TARGET_ARCH_VARIANT := x86
 
-# Set this to create /cache mount point for non-A/B devices that mounts /cache.
-# The partition size doesn't matter, just to make build pass.
-BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
-BOARD_CACHEIMAGE_PARTITION_SIZE := 16777216
-
-# Enable A/B update
-TARGET_NO_RECOVERY := true
-BOARD_BUILD_SYSTEM_ROOT_IMAGE := true
+# Legacy GSI keeps 32 bits binder for 32 bits CPU Arch
+TARGET_USES_64_BIT_BINDER := false
diff --git a/target/board/mainline_arm64/BoardConfig.mk b/target/board/mainline_arm64/BoardConfig.mk
index 906a566..521d976 100644
--- a/target/board/mainline_arm64/BoardConfig.mk
+++ b/target/board/mainline_arm64/BoardConfig.mk
@@ -24,4 +24,4 @@
 TARGET_2ND_CPU_ABI2 := armeabi
 TARGET_2ND_CPU_VARIANT := generic
 
-include build/make/target/board/BoardConfigGsiCommon.mk
+include build/make/target/board/BoardConfigMainlineCommon.mk
diff --git a/target/board/treble_common.mk b/target/board/treble_common.mk
deleted file mode 100644
index 9413a75..0000000
--- a/target/board/treble_common.mk
+++ /dev/null
@@ -1,71 +0,0 @@
-#
-# Copyright (C) 2017 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.
-#
-
-# Common boardconfig settings for generic AOSP products targetting mobile
-# (phone/table) devices.
-
-# VNDK
-BOARD_VNDK_VERSION := current
-
-# Properties
-TARGET_SYSTEM_PROP := build/make/target/board/treble_system.prop
-BOARD_PROPERTY_OVERRIDES_SPLIT_ENABLED := true
-
-# Bootloader, kernel and recovery are not part of generic AOSP image
-TARGET_NO_BOOTLOADER := true
-TARGET_NO_KERNEL := true
-
-# system.img is always ext4 with sparse option
-# GSI also includes make_f2fs to support userdata parition in f2fs
-# for some devices
-TARGET_USERIMAGES_USE_EXT4 := true
-TARGET_USERIMAGES_USE_F2FS := true
-TARGET_USERIMAGES_SPARSE_EXT_DISABLED := false
-
-# Enable dynamic system image size and reserved 64MB in it.
-BOARD_SYSTEMIMAGE_PARTITION_RESERVED_SIZE := 67108864
-
-# Generic AOSP image always requires separate vendor.img
-TARGET_COPY_OUT_VENDOR := vendor
-
-# Android generic system image always create metadata partition
-BOARD_USES_METADATA_PARTITION := true
-
-# Generic AOSP image does NOT support HWC1
-TARGET_USES_HWC2 := true
-# Set emulator framebuffer display device buffer count to 3
-NUM_FRAMEBUFFER_SURFACE_BUFFERS := 3
-
-# Audio
-USE_XML_AUDIO_POLICY_CONF := 1
-
-# Android Verified Boot (AVB):
-#   1) Sets BOARD_AVB_ENABLE to sign the GSI image.
-#   2) Sets AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED (--flag 2) in
-#      vbmeta.img to disable AVB verification.
-#
-# To disable AVB for GSI, use the vbmeta.img and the GSI together.
-# To enable AVB for GSI, include the GSI public key into the device-specific
-# vbmeta.img.
-BOARD_AVB_ENABLE := true
-BOARD_AVB_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
-BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS += --flag 2
-
-# Enable chain partition for system.
-BOARD_AVB_SYSTEM_KEY_PATH := external/avb/test/data/testkey_rsa2048.pem
-BOARD_AVB_SYSTEM_ALGORITHM := SHA256_RSA2048
-BOARD_AVB_SYSTEM_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
-BOARD_AVB_SYSTEM_ROLLBACK_INDEX_LOCATION := 1
diff --git a/target/board/treble_common_32.mk b/target/board/treble_common_32.mk
deleted file mode 100644
index b66c41e..0000000
--- a/target/board/treble_common_32.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright (C) 2017 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.
-#
-
-include build/make/target/board/treble_common.mk
diff --git a/target/board/treble_common_64.mk b/target/board/treble_common_64.mk
deleted file mode 100644
index 8980dfd..0000000
--- a/target/board/treble_common_64.mk
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Copyright (C) 2017 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.
-#
-
-include build/make/target/board/treble_common.mk
-
-# Enable 64-bits binder
-TARGET_USES_64_BIT_BINDER := true
diff --git a/target/board/treble_system.prop b/target/board/treble_system.prop
deleted file mode 100644
index 0c04a95..0000000
--- a/target/board/treble_system.prop
+++ /dev/null
@@ -1,8 +0,0 @@
-# GSI always generate dex pre-opt in system image
-ro.cp_system_other_odex=0
-
-# GSI always disables adb authentication
-ro.adb.secure=0
-
-# TODO(b/78105955): disable privapp_permissions checking before the bug solved
-ro.control_privapp_permissions=disable
diff --git a/target/product/OWNERS b/target/product/OWNERS
new file mode 100644
index 0000000..1c74859
--- /dev/null
+++ b/target/product/OWNERS
@@ -0,0 +1 @@
+per-file runtime_libart.mk = agampe@google.com, calin@google.com, mast@google.com, ngeoffray@google.com, oth@google.com, rpl@google.com, sehr@google.com, vmarko@google.com
diff --git a/target/product/aosp_arm.mk b/target/product/aosp_arm.mk
index 795f8aa..98114c1 100644
--- a/target/product/aosp_arm.mk
+++ b/target/product/aosp_arm.mk
@@ -38,6 +38,11 @@
 # Needed by Pi newly launched device to pass VtsTrebleSysProp on GSI
 PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE := true
 
+# GSI specific tasks on boot
+PRODUCT_COPY_FILES += \
+    build/make/target/product/gsi/skip_mount.cfg:system/etc/init/config/skip_mount.cfg \
+    build/make/target/product/gsi/init.gsi.rc:system/etc/init/init.gsi.rc \
+
 # Support addtional P vendor interface
 PRODUCT_EXTRA_VNDK_VERSIONS := 28
 
diff --git a/target/product/aosp_arm64.mk b/target/product/aosp_arm64.mk
index f3f3c5a..87e14d7 100644
--- a/target/product/aosp_arm64.mk
+++ b/target/product/aosp_arm64.mk
@@ -54,6 +54,11 @@
 # Needed by Pi newly launched device to pass VtsTrebleSysProp on GSI
 PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE := true
 
+# GSI specific tasks on boot
+PRODUCT_COPY_FILES += \
+    build/make/target/product/gsi/skip_mount.cfg:system/etc/init/config/skip_mount.cfg \
+    build/make/target/product/gsi/init.gsi.rc:system/etc/init/init.gsi.rc \
+
 # Support addtional P vendor interface
 PRODUCT_EXTRA_VNDK_VERSIONS := 28
 
diff --git a/target/product/aosp_arm64_a.mk b/target/product/aosp_arm64_a.mk
index 3c7af33..b1c4b7d 100644
--- a/target/product/aosp_arm64_a.mk
+++ b/target/product/aosp_arm64_a.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 include build/make/target/product/treble_common_64.mk
 
diff --git a/target/product/aosp_arm64_ab.mk b/target/product/aosp_arm64_ab.mk
index d389c74..92f5055 100644
--- a/target/product/aosp_arm64_ab.mk
+++ b/target/product/aosp_arm64_ab.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 # aosp_arm64_ab-userdebug is a Legacy GSI for the devices with:
 # - ARM 64 bits user space
diff --git a/target/product/aosp_arm_a.mk b/target/product/aosp_arm_a.mk
index 3060fa9..d89a326 100644
--- a/target/product/aosp_arm_a.mk
+++ b/target/product/aosp_arm_a.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 include build/make/target/product/treble_common_32.mk
 
diff --git a/target/product/aosp_arm_ab.mk b/target/product/aosp_arm_ab.mk
index 5845d3b..b35e517 100644
--- a/target/product/aosp_arm_ab.mk
+++ b/target/product/aosp_arm_ab.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 # aosp_arm_ab-userdebug is a Legacy GSI for the devices with:
 # - ARM 32 bits user space
diff --git a/target/product/aosp_x86.mk b/target/product/aosp_x86.mk
index e3167af..50d7355 100644
--- a/target/product/aosp_x86.mk
+++ b/target/product/aosp_x86.mk
@@ -38,6 +38,11 @@
 # Needed by Pi newly launched device to pass VtsTrebleSysProp on GSI
 PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE := true
 
+# GSI specific tasks on boot
+PRODUCT_COPY_FILES += \
+    build/make/target/product/gsi/skip_mount.cfg:system/etc/init/config/skip_mount.cfg \
+    build/make/target/product/gsi/init.gsi.rc:system/etc/init/init.gsi.rc \
+
 # Support addtional P vendor interface
 PRODUCT_EXTRA_VNDK_VERSIONS := 28
 
diff --git a/target/product/aosp_x86_64.mk b/target/product/aosp_x86_64.mk
index 222adaa..499831b 100644
--- a/target/product/aosp_x86_64.mk
+++ b/target/product/aosp_x86_64.mk
@@ -54,6 +54,11 @@
 # Needed by Pi newly launched device to pass VtsTrebleSysProp on GSI
 PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE := true
 
+# GSI specific tasks on boot
+PRODUCT_COPY_FILES += \
+    build/make/target/product/gsi/skip_mount.cfg:system/etc/init/config/skip_mount.cfg \
+    build/make/target/product/gsi/init.gsi.rc:system/etc/init/init.gsi.rc \
+
 # Support addtional P vendor interface
 PRODUCT_EXTRA_VNDK_VERSIONS := 28
 
diff --git a/target/product/aosp_x86_64_a.mk b/target/product/aosp_x86_64_a.mk
index a7fb740..6b6785a 100644
--- a/target/product/aosp_x86_64_a.mk
+++ b/target/product/aosp_x86_64_a.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 include build/make/target/product/treble_common_64.mk
 
diff --git a/target/product/aosp_x86_64_ab.mk b/target/product/aosp_x86_64_ab.mk
index d9163d7..35bf61a 100644
--- a/target/product/aosp_x86_64_ab.mk
+++ b/target/product/aosp_x86_64_ab.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 # aosp_x86_64_ab-userdebug is a Legacy GSI for the devices with:
 # - x86 64 bits user space
diff --git a/target/product/aosp_x86_a.mk b/target/product/aosp_x86_a.mk
index 9ed2995..99ed7e4 100644
--- a/target/product/aosp_x86_a.mk
+++ b/target/product/aosp_x86_a.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 include build/make/target/product/treble_common_32.mk
 
diff --git a/target/product/aosp_x86_ab.mk b/target/product/aosp_x86_ab.mk
index 4fff3d1..185e2f0 100644
--- a/target/product/aosp_x86_ab.mk
+++ b/target/product/aosp_x86_ab.mk
@@ -17,7 +17,7 @@
 # PRODUCT_PROPERTY_OVERRIDES cannot be used here because sysprops will be at
 # /vendor/[build|default].prop when build split is on. In order to have sysprops
 # on the generic system image, place them in build/make/target/board/
-# treble_system.prop.
+# gsi_system.prop.
 
 # aosp_x86_ab-userdebug is a Legacy GSI for the devices with:
 # - x86 32 bits user space
diff --git a/target/product/base_system.mk b/target/product/base_system.mk
index 7b70c86..df793bf 100644
--- a/target/product/base_system.mk
+++ b/target/product/base_system.mk
@@ -16,6 +16,7 @@
 
 # Base modules and settings for the system partition.
 PRODUCT_PACKAGES += \
+    abb \
     adb \
     adbd \
     am \
@@ -48,10 +49,12 @@
     bu \
     bugreport \
     bugreportz \
-    cameraserver \
     charger \
     cmd \
+    com.android.conscrypt \
     com.android.location.provider \
+    com.android.resolv \
+    com.android.tzdata \
     ContactsProvider \
     content \
     crash_dump \
@@ -59,6 +62,7 @@
     CtsShimPrivPrebuilt \
     debuggerd\
     DefaultContainerService \
+    dmctl \
     dnsmasq \
     DownloadProvider \
     dpm \
@@ -78,7 +82,7 @@
     heapprofd \
     heapprofd_client \
     gatekeeperd \
-    healthd \
+    gpuservice \
     hid \
     hwservicemanager \
     idmap \
@@ -114,14 +118,14 @@
     libaudioutils \
     libbinder \
     libbinder_ndk \
-    libc \
+    libc.bootstrap \
     libcamera2ndk \
     libcamera_client \
     libcameraservice \
     libc_malloc_debug \
     libc_malloc_hooks \
     libcutils \
-    libdl \
+    libdl.bootstrap \
     libdrmframework \
     libdrmframework_jni \
     libEGL \
@@ -141,7 +145,7 @@
     libjnigraphics \
     libjpeg \
     liblog \
-    libm \
+    libm.bootstrap \
     libmdnssd \
     libmedia \
     libmedia_jni \
@@ -191,6 +195,7 @@
     locksettings \
     logcat \
     logd \
+    lpdump \
     lshal \
     mdnsd \
     media \
@@ -202,10 +207,12 @@
     MediaProvider \
     mediaserver \
     mke2fs \
+    ModuleMetadata \
     monkey \
     mtpd \
     ndc \
     netd \
+    NetworkStack \
     org.apache.http.legacy \
     perfetto \
     ping \
@@ -217,6 +224,7 @@
     racoon \
     recovery-persist \
     resize2fs \
+    rss_hwm_reset \
     run-as \
     schedtest \
     screencap \
@@ -251,6 +259,7 @@
     uncrypt \
     usbd \
     vdc \
+    viewcompiler \
     voip-common \
     vold \
     WallpaperBackup \
@@ -309,14 +318,19 @@
 # Packages included only for eng or userdebug builds, previously debug tagged
 PRODUCT_PACKAGES_DEBUG := \
     adb_keys \
-    apex.test.key \
+    arping \
     iotop \
+    iw \
     logpersist.start \
-    perfprofd \
     procrank \
     showmap \
     sqlite3 \
+    ss \
     strace \
+    sanitizer-status \
+    tracepath \
+    tracepath6 \
+    traceroute6 \
     unwind_info \
     unwind_reg_info \
     unwind_symbols \
diff --git a/target/product/base_vendor.mk b/target/product/base_vendor.mk
index 9bb45d1..1bb4bee 100644
--- a/target/product/base_vendor.mk
+++ b/target/product/base_vendor.mk
@@ -53,6 +53,10 @@
     vndservice \
     vndservicemanager \
 
+# Base modules and settings for the product partition.
+PRODUCT_PACKAGES += \
+    healthd \
+
 # VINTF data for vendor image
 PRODUCT_PACKAGES += \
     device_manifest.xml \
diff --git a/target/product/go_defaults_common.mk b/target/product/go_defaults_common.mk
index 18907c1..06bdec9 100644
--- a/target/product/go_defaults_common.mk
+++ b/target/product/go_defaults_common.mk
@@ -61,6 +61,10 @@
 # Do not generate libartd.
 PRODUCT_ART_TARGET_INCLUDE_DEBUG_BUILD := false
 
+# Do not spin up a separate process for the network stack on go devices, use an in-process lib.
+PRODUCT_PACKAGES += NetworkStackLib
+PRODUCT_SYSTEM_SERVER_JARS += NetworkStackLib
+
 # Strip the local variable table and the local variable type table to reduce
 # the size of the system image. This has no bearing on stack traces, but will
 # leave less information available via JDWP.
diff --git a/target/product/vndk/28.txt b/target/product/gsi/28.txt
similarity index 100%
rename from target/product/vndk/28.txt
rename to target/product/gsi/28.txt
diff --git a/target/product/vndk/Android.mk b/target/product/gsi/Android.mk
similarity index 100%
rename from target/product/vndk/Android.mk
rename to target/product/gsi/Android.mk
diff --git a/target/product/vndk/OWNERS b/target/product/gsi/OWNERS
similarity index 100%
rename from target/product/vndk/OWNERS
rename to target/product/gsi/OWNERS
diff --git a/target/product/vndk/current.txt b/target/product/gsi/current.txt
similarity index 95%
rename from target/product/vndk/current.txt
rename to target/product/gsi/current.txt
index 6120e9d..9eff6b6 100644
--- a/target/product/vndk/current.txt
+++ b/target/product/gsi/current.txt
@@ -23,6 +23,7 @@
 VNDK-SP: android.hidl.memory.token@1.0.so
 VNDK-SP: android.hidl.memory@1.0.so
 VNDK-SP: android.hidl.memory@1.0-impl.so
+VNDK-SP: android.hidl.safe_union@1.0.so
 VNDK-SP: libRSCpuRef.so
 VNDK-SP: libRSDriver.so
 VNDK-SP: libRS_internal.so
@@ -42,7 +43,6 @@
 VNDK-SP: libhwbinder_noltopgo.so
 VNDK-SP: libion.so
 VNDK-SP: liblzma.so
-VNDK-SP: libunwind.so
 VNDK-SP: libunwindstack.so
 VNDK-SP: libutils.so
 VNDK-SP: libutilscallstack.so
@@ -57,16 +57,20 @@
 VNDK-core: android.hardware.audio.common@2.0-util.so
 VNDK-core: android.hardware.audio.common@4.0.so
 VNDK-core: android.hardware.audio.common@4.0-util.so
+VNDK-core: android.hardware.audio.common@5.0.so
 VNDK-core: android.hardware.audio.effect@2.0.so
 VNDK-core: android.hardware.audio.effect@4.0.so
+VNDK-core: android.hardware.audio.effect@5.0.so
 VNDK-core: android.hardware.audio@2.0.so
 VNDK-core: android.hardware.audio@4.0.so
+VNDK-core: android.hardware.audio@5.0.so
 VNDK-core: android.hardware.authsecret@1.0.so
 VNDK-core: android.hardware.automotive.audiocontrol@1.0.so
 VNDK-core: android.hardware.automotive.evs@1.0.so
 VNDK-core: android.hardware.automotive.vehicle@2.0.so
 VNDK-core: android.hardware.biometrics.fingerprint@2.1.so
 VNDK-core: android.hardware.bluetooth.a2dp@1.0.so
+VNDK-core: android.hardware.bluetooth.audio@2.0.so
 VNDK-core: android.hardware.bluetooth@1.0.so
 VNDK-core: android.hardware.boot@1.0.so
 VNDK-core: android.hardware.broadcastradio@1.0.so
@@ -115,17 +119,22 @@
 VNDK-core: android.hardware.neuralnetworks@1.2.so
 VNDK-core: android.hardware.nfc@1.0.so
 VNDK-core: android.hardware.nfc@1.1.so
+VNDK-core: android.hardware.nfc@1.2.so
 VNDK-core: android.hardware.oemlock@1.0.so
+VNDK-core: android.hardware.power.stats@1.0.so
 VNDK-core: android.hardware.power@1.0.so
 VNDK-core: android.hardware.power@1.1.so
 VNDK-core: android.hardware.power@1.2.so
 VNDK-core: android.hardware.power@1.3.so
 VNDK-core: android.hardware.radio.config@1.0.so
+VNDK-core: android.hardware.radio.config@1.1.so
+VNDK-core: android.hardware.radio.config@1.2.so
 VNDK-core: android.hardware.radio.deprecated@1.0.so
 VNDK-core: android.hardware.radio@1.0.so
 VNDK-core: android.hardware.radio@1.1.so
 VNDK-core: android.hardware.radio@1.2.so
 VNDK-core: android.hardware.radio@1.3.so
+VNDK-core: android.hardware.radio@1.4.so
 VNDK-core: android.hardware.secure_element@1.0.so
 VNDK-core: android.hardware.sensors@1.0.so
 VNDK-core: android.hardware.soundtrigger@2.0.so
@@ -154,7 +163,6 @@
 VNDK-core: android.hardware.wifi@1.2.so
 VNDK-core: android.hidl.allocator@1.0.so
 VNDK-core: android.hidl.memory.block@1.0.so
-VNDK-core: android.hidl.safe_union@1.0.so
 VNDK-core: android.hidl.token@1.0.so
 VNDK-core: android.hidl.token@1.0-utils.so
 VNDK-core: android.system.net.netd@1.0.so
@@ -256,4 +264,3 @@
 VNDK-private: libcompiler_rt.so
 VNDK-private: libft2.so
 VNDK-private: libgui.so
-VNDK-private: libunwind.so
diff --git a/target/product/gsi/init.gsi.rc b/target/product/gsi/init.gsi.rc
new file mode 100644
index 0000000..c6faba7
--- /dev/null
+++ b/target/product/gsi/init.gsi.rc
@@ -0,0 +1,3 @@
+#
+# Android init script for GSI required initialization
+#
diff --git a/target/product/vndk/init.gsi.rc b/target/product/gsi/init.legacy-gsi.rc
similarity index 98%
rename from target/product/vndk/init.gsi.rc
rename to target/product/gsi/init.legacy-gsi.rc
index 0150b1a..00dd576 100644
--- a/target/product/vndk/init.gsi.rc
+++ b/target/product/gsi/init.legacy-gsi.rc
@@ -1,2 +1,3 @@
 # If ro.vndk.version is not defined, import init.vndk-27.rc.
 import /system/etc/init/gsi/init.vndk-${ro.vndk.version:-27}.rc
+
diff --git a/target/product/vndk/init.vndk-27.rc b/target/product/gsi/init.vndk-27.rc
similarity index 100%
rename from target/product/vndk/init.vndk-27.rc
rename to target/product/gsi/init.vndk-27.rc
diff --git a/target/product/gsi/skip_mount.cfg b/target/product/gsi/skip_mount.cfg
new file mode 100644
index 0000000..549767e
--- /dev/null
+++ b/target/product/gsi/skip_mount.cfg
@@ -0,0 +1,2 @@
+/product
+/product_services
diff --git a/target/product/handheld_system.mk b/target/product/handheld_system.mk
index a961d1e..0a763fb 100644
--- a/target/product/handheld_system.mk
+++ b/target/product/handheld_system.mk
@@ -36,52 +36,33 @@
     Bluetooth \
     BluetoothMidiService \
     BookmarkProvider \
-    Browser2 \
     BuiltInPrintService \
-    Calendar \
     CalendarProvider \
-    Camera2 \
+    cameraserver \
     CaptivePortalLogin \
     CertInstaller \
     clatd \
     clatd.conf \
-    Contacts \
-    DeskClock \
     DocumentsUI \
     DownloadProviderUi \
     EasterEgg \
-    Email \
-    ExactCalculator \
     ExternalStorageProvider \
     FusedLocation \
-    Gallery2 \
-    Home \
     InputDevices \
     KeyChain \
-    LatinIME \
-    Launcher3QuickStep \
     librs_jni \
     ManagedProvisioning \
     MmsService \
     MtpDocumentsProvider \
-    Music \
     MusicFX \
     NfcNci \
-    OneTimeInitializer \
     PacProcessor \
-    PrintRecommendationService \
     PrintSpooler \
-    Provision \
     ProxyHandler \
-    QuickSearchBox \
     screenrecord \
     SecureElement \
-    Settings \
-    SettingsIntelligence \
     SharedStorageBackup \
     SimAppDialog \
-    StorageManager \
-    SystemUI \
     Telecom \
     TelephonyProvider \
     TeleService \
@@ -89,7 +70,6 @@
     UserDictionaryProvider \
     VpnDialogs \
     vr \
-    WallpaperCropper \
 
 
 PRODUCT_SYSTEM_SERVER_APPS += \
@@ -105,4 +85,3 @@
     ro.carrier=unknown \
     ro.config.notification_sound=OnTheHunt.ogg \
     ro.config.alarm_alert=Alarm_Classic.ogg
-
diff --git a/target/product/handheld_vendor.mk b/target/product/handheld_vendor.mk
index 0f73875..b9970e9 100644
--- a/target/product/handheld_vendor.mk
+++ b/target/product/handheld_vendor.mk
@@ -19,6 +19,8 @@
 # it definitely doesn't belong on other types of devices (if it
 # does, use base_vendor.mk).
 $(call inherit-product, $(SRC_TARGET_DIR)/product/media_vendor.mk)
+
+# /vendor packages
 PRODUCT_PACKAGES += \
     audio.primary.default \
     DisplayCutoutEmulationCornerOverlay \
@@ -28,3 +30,25 @@
     power.default \
     SysuiDarkThemeOverlay \
     vibrator.default \
+
+# /product packages
+PRODUCT_PACKAGES += \
+    Browser2 \
+    Calendar \
+    Camera2 \
+    Contacts \
+    DeskClock \
+    Email \
+    Gallery2 \
+    LatinIME \
+    Launcher3QuickStep \
+    Music \
+    OneTimeInitializer \
+    PrintRecommendationService \
+    Provision \
+    QuickSearchBox \
+    Settings \
+    SettingsIntelligence \
+    StorageManager \
+    SystemUI \
+    WallpaperCropper \
diff --git a/target/product/languages_default.mk b/target/product/languages_default.mk
new file mode 100644
index 0000000..a13a23c
--- /dev/null
+++ b/target/product/languages_default.mk
@@ -0,0 +1,105 @@
+#
+# Copyright (C) 2009 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.
+#
+
+# This is a build configuration that just contains a list of languages, with
+# en_US set as the default language.
+PRODUCT_LOCALES := \
+        en_US \
+        af_ZA \
+        am_ET \
+        ar_EG \
+        ar_XB \
+        as_IN \
+        az_AZ \
+        be_BY \
+        bg_BG \
+        bn_BD \
+        bs_BA \
+        ca_ES \
+        cs_CZ \
+        da_DK \
+        de_DE \
+        el_GR \
+        en_AU \
+        en_CA \
+        en_GB \
+        en_IN \
+        en_XA \
+        es_ES \
+        es_US \
+        et_EE \
+        eu_ES \
+        fa_IR \
+        fi_FI \
+        fr_CA \
+        fr_FR \
+        gl_ES \
+        gu_IN \
+        hi_IN \
+        hr_HR \
+        hu_HU \
+        hy_AM \
+        in_ID \
+        is_IS \
+        it_IT \
+        iw_IL \
+        ja_JP \
+        ka_GE \
+        kk_KZ \
+        km_KH \
+        kn_IN \
+        ko_KR \
+        ky_KG \
+        lo_LA \
+        lt_LT \
+        lv_LV \
+        mk_MK \
+        ml_IN \
+        mn_MN \
+        mr_IN \
+        ms_MY \
+        my_MM \
+        nb_NO \
+        ne_NP \
+        nl_NL \
+        or_IN \
+        pa_IN \
+        pl_PL \
+        pt_BR \
+        pt_PT \
+        ro_RO \
+        ru_RU \
+        si_LK \
+        sk_SK \
+        sl_SI \
+        sq_AL \
+        sr_Latn_RS \
+        sr_RS \
+        sv_SE \
+        sw_TZ \
+        ta_IN \
+        te_IN \
+        th_TH \
+        tl_PH \
+        tr_TR \
+        uk_UA \
+        ur_PK \
+        uz_UZ \
+        vi_VN \
+        zh_CN \
+        zh_HK \
+        zh_TW \
+        zu_ZA \
diff --git a/target/product/languages_full.mk b/target/product/languages_full.mk
index 5f3795f..43a40a7 100644
--- a/target/product/languages_full.mk
+++ b/target/product/languages_full.mk
@@ -14,94 +14,9 @@
 # limitations under the License.
 #
 
-# This is a build configuration that just contains a list of languages.
-#
-# These are all the locales that have translations.
-PRODUCT_LOCALES := \
-        en_US \
-        af_ZA \
-        am_ET \
-        ar_EG \
-        ar_XB \
-        as_IN \
-        az_AZ \
-        be_BY \
-        bg_BG \
-        bn_BD \
-        bs_BA \
-        ca_ES \
-        cs_CZ \
-        da_DK \
-        de_DE \
-        el_GR \
-        en_AU \
-        en_CA \
-        en_GB \
-        en_IN \
-        en_XA \
-        en_XC \
-        es_ES \
-        es_US \
-        et_EE \
-        eu_ES \
-        fa_IR \
-        fi_FI \
-        fr_CA \
-        fr_FR \
-        gl_ES \
-        gu_IN \
-        hi_IN \
-        hr_HR \
-        hu_HU \
-        hy_AM \
-        in_ID \
-        is_IS \
-        it_IT \
-        iw_IL \
-        ja_JP \
-        ka_GE \
-        kk_KZ \
-        km_KH \
-        kn_IN \
-        ko_KR \
-        ky_KG \
-        lo_LA \
-        lt_LT \
-        lv_LV \
-        mk_MK \
-        ml_IN \
-        mn_MN \
-        mr_IN \
-        ms_MY \
-        my_MM \
-        nb_NO \
-        ne_NP \
-        nl_NL \
-        or_IN \
-        pa_IN \
-        pl_PL \
-        pt_BR \
-        pt_PT \
-        ro_RO \
-        ru_RU \
-        si_LK \
-        sk_SK \
-        sl_SI \
-        sq_AL \
-        sr_Latn_RS \
-        sr_RS \
-        sv_SE \
-        sw_TZ \
-        ta_IN \
-        te_IN \
-        th_TH \
-        tl_PH \
-        tr_TR \
-        uk_UA \
-        ur_PK \
-        uz_UZ \
-        vi_VN \
-        zh_CN \
-        zh_HK \
-        zh_TW \
-        zu_ZA
+# This is a build configuration that contains the default list of languages,
+# as well as the en_XC pseudo-locale, which is useful for localization test
+# builds.
+
+$(call inherit-product, $(SRC_TARGET_DIR)/product/languages_default.mk)
+PRODUCT_LOCALES += en_XC
diff --git a/target/product/languages_small.mk b/target/product/languages_small.mk
deleted file mode 100644
index d695ca8..0000000
--- a/target/product/languages_small.mk
+++ /dev/null
@@ -1,24 +0,0 @@
-#
-# Copyright (C) 2009 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.
-#
-
-# This is a build configuration that just contains a list of languages.
-# It helps in situations where laugnages must come first in the list,
-# mostly because screen densities interfere with the list of locales and
-# the system misbehaves when a density is the first locale.
-
-# This is the list of languages that originally shipped on ADP1
-
-PRODUCT_LOCALES := en_US en_GB fr_FR it_IT de_DE es_ES
diff --git a/target/product/mainline.mk b/target/product/mainline.mk
new file mode 100644
index 0000000..44dcd60
--- /dev/null
+++ b/target/product/mainline.mk
@@ -0,0 +1,21 @@
+#
+# Copyright (C) 2019 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.
+#
+
+# Makefile including the mainline system image, and the relevant AOSP portions
+# for the other partitions.
+$(call inherit-product, $(SRC_TARGET_DIR)/product/mainline_system.mk)
+$(call inherit-product, $(SRC_TARGET_DIR)/product/handheld_vendor.mk)
+$(call inherit-product, $(SRC_TARGET_DIR)/product/telephony_vendor.mk)
diff --git a/target/product/mainline_arm64.mk b/target/product/mainline_arm64.mk
index cc04844..6122ac1 100644
--- a/target/product/mainline_arm64.mk
+++ b/target/product/mainline_arm64.mk
@@ -15,9 +15,7 @@
 #
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core_64_bit.mk)
-$(call inherit-product, $(SRC_TARGET_DIR)/product/mainline_system.mk)
-$(call inherit-product, $(SRC_TARGET_DIR)/product/handheld_vendor.mk)
-$(call inherit-product, $(SRC_TARGET_DIR)/product/telephony_vendor.mk)
+$(call inherit-product, $(SRC_TARGET_DIR)/product/mainline.mk)
 
 PRODUCT_NAME := mainline_arm64
 PRODUCT_DEVICE := generic_arm64
@@ -25,8 +23,47 @@
 PRODUCT_SHIPPING_API_LEVEL := 28
 PRODUCT_RESTRICT_VENDOR_FILES := all
 
-PRODUCT_ENFORCE_ARTIFACT_PATH_REQUIREMENTS := true
-PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST := \
+PRODUCT_ENFORCE_ARTIFACT_PATH_REQUIREMENTS := relaxed
+# Target device doesn't have a product partition, so whitelist the /system/ fallback path.
+PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST := system/product/%
+PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST += \
   root/init.zygote64_32.rc \
   system/etc/seccomp_policy/crash_dump.arm.policy \
   system/etc/seccomp_policy/mediacodec.policy \
+
+# Modules that are to be moved to /product
+PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST += \
+  system/app/Browser2/Browser2.apk \
+  system/app/Calendar/Calendar.apk \
+  system/app/Camera2/Camera2.apk \
+  system/app/DeskClock/DeskClock.apk \
+  system/app/Email/Email.apk \
+  system/app/Gallery2/Gallery2.apk \
+  system/app/LatinIME/LatinIME.apk \
+  system/app/LatinIME/oat/arm64/LatinIME.odex \
+  system/app/LatinIME/oat/arm64/LatinIME.vdex \
+  system/app/Music/Music.apk \
+  system/app/PrintRecommendationService/PrintRecommendationService.apk \
+  system/app/QuickSearchBox/QuickSearchBox.apk \
+  system/bin/healthd \
+  system/etc/init/healthd.rc \
+  system/etc/vintf/manifest/manifest_healthd.xml \
+  system/lib64/libjni_eglfence.so \
+  system/lib64/libjni_filtershow_filters.so \
+  system/lib64/libjni_jpegstream.so \
+  system/lib64/libjni_jpegutil.so \
+  system/lib64/libjni_latinime.so \
+  system/lib64/libjni_tinyplanet.so \
+  system/priv-app/CarrierConfig/CarrierConfig.apk \
+  system/priv-app/Contacts/Contacts.apk \
+  system/priv-app/Dialer/Dialer.apk \
+  system/priv-app/Launcher3QuickStep/Launcher3QuickStep.apk \
+  system/priv-app/OneTimeInitializer/OneTimeInitializer.apk \
+  system/priv-app/Provision/Provision.apk \
+  system/priv-app/Settings/Settings.apk \
+  system/priv-app/SettingsIntelligence/SettingsIntelligence.apk \
+  system/priv-app/StorageManager/StorageManager.apk \
+  system/priv-app/SystemUI/SystemUI.apk \
+  system/priv-app/SystemUI/oat/arm64/SystemUI.odex \
+  system/priv-app/SystemUI/oat/arm64/SystemUI.vdex \
+  system/priv-app/WallpaperCropper/WallpaperCropper.apk \
diff --git a/target/product/mainline_system.mk b/target/product/mainline_system.mk
index b0edb56..b9b422f 100644
--- a/target/product/mainline_system.mk
+++ b/target/product/mainline_system.mk
@@ -17,6 +17,9 @@
 # This makefile is the basis of a generic system image for a handheld device.
 $(call inherit-product, $(SRC_TARGET_DIR)/product/handheld_system.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/telephony_system.mk)
+$(call inherit-product, $(SRC_TARGET_DIR)/product/languages_default.mk)
+# Add adb keys to debuggable AOSP builds (if they exist)
+$(call inherit-product-if-exists, vendor/google/security/adb/vendor_key.mk)
 
 # Shared java libs
 PRODUCT_PACKAGES += \
@@ -31,6 +34,11 @@
     RcsService \
     SafetyRegulatoryInfo \
     Stk \
+    Tag \
+    TimeZoneUpdater \
+
+# Binaries
+PRODUCT_PACKAGES += llkd
 
 # OTA support
 PRODUCT_PACKAGES += \
@@ -38,12 +46,10 @@
     update_verifier \
 
 # Wrapped net utils for /vendor access.
-PRODUCT_PACKAGES += \
-    netutils-wrapper-1.0 \
+PRODUCT_PACKAGES += netutils-wrapper-1.0
 
 # Charger images
-PRODUCT_PACKAGES += \
-    charger_res_images \
+PRODUCT_PACKAGES += charger_res_images
 
 # system_other support
 PRODUCT_PACKAGES += \
@@ -55,6 +61,30 @@
     audio.a2dp.default \
     audio.hearing_aid.default \
 
+# For ringtones that rely on forward lock encryption
+PRODUCT_PACKAGES += libfwdlockengine
+
+# System libraries commonly depended on by things on the product partition.
+# This list will be pruned periodically.
+PRODUCT_PACKAGES += \
+    android.hardware.biometrics.fingerprint@2.1 \
+    android.hardware.radio@1.0 \
+    android.hardware.radio@1.1 \
+    android.hardware.radio@1.2 \
+    android.hardware.radio.config@1.0 \
+    android.hardware.radio.deprecated@1.0 \
+    android.hardware.secure_element@1.0 \
+    android.hardware.tests.libhwbinder@1.0-impl \
+    android.hardware.wifi@1.0 \
+    android.hidl.base@1.0 \
+    libaudio-resampler \
+    liblogwrap \
+    liblz4 \
+    libminui \
+    libnl \
+    libprotobuf-cpp-full \
+    libprotobuf-cpp-full-rtti \
+
 PRODUCT_PACKAGES_DEBUG += \
     avbctl \
     bootctl \
@@ -64,11 +94,14 @@
     tinypcminfo \
     update_engine_client \
 
+# Enable stats logging in LMKD
+TARGET_LMKD_STATS_LOG := true
+PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+    ro.lmk.log_stats=true
+
 # Enable dynamic partition size
 PRODUCT_USE_DYNAMIC_PARTITION_SIZE := true
 
-PRODUCT_LOCALES := en_US af_ZA am_ET ar_EG as_IN az_AZ be_BY bg_BG bn_BD bs_BA ca_ES cs_CZ da_DK de_DE el_GR en_AU en_CA en_GB en_IN es_ES es_US et_EE eu_ES fa_IR fi_FI fr_CA fr_FR gl_ES gu_IN hi_IN hr_HR hu_HU hy_AM in_ID is_IS it_IT iw_IL ja_JP ka_GE kk_KZ km_KH ko_KR ky_KG lo_LA lt_LT lv_LV km_MH kn_IN mn_MN ml_IN mk_MK mr_IN ms_MY my_MM ne_NP nb_NO nl_NL or_IN pa_IN pl_PL pt_BR pt_PT ro_RO ru_RU si_LK sk_SK sl_SI sq_AL sr_Latn_RS sr_RS sv_SE sw_TZ ta_IN te_IN th_TH tl_PH tr_TR uk_UA ur_PK uz_UZ vi_VN zh_CN zh_HK zh_TW zu_ZA en_XA ar_XB
-
 PRODUCT_NAME := mainline_system
 PRODUCT_BRAND := generic
 
diff --git a/target/product/media_vendor.mk b/target/product/media_vendor.mk
index 1db0b58..f30e6f3 100644
--- a/target/product/media_vendor.mk
+++ b/target/product/media_vendor.mk
@@ -20,6 +20,11 @@
 # base_vendor.mk.
 $(call inherit-product, $(SRC_TARGET_DIR)/product/base_vendor.mk)
 
+# /vendor packages
 PRODUCT_PACKAGES += \
     libaudiopreprocessing \
     libwebrtc_audio_preprocessing \
+
+# /product packages
+PRODUCT_PACKAGES += \
+    webview \
diff --git a/target/product/product_launched_with_k.mk b/target/product/product_launched_with_k.mk
new file mode 100644
index 0000000..87faa12
--- /dev/null
+++ b/target/product/product_launched_with_k.mk
@@ -0,0 +1,2 @@
+#PRODUCT_SHIPPING_API_LEVEL indicates the first api level, device has been commercially launched on.
+PRODUCT_SHIPPING_API_LEVEL := 19
diff --git a/target/product/product_launched_with_l.mk b/target/product/product_launched_with_l.mk
index 6e782f7..4e79749 100644
--- a/target/product/product_launched_with_l.mk
+++ b/target/product/product_launched_with_l.mk
@@ -1,3 +1,2 @@
 #PRODUCT_SHIPPING_API_LEVEL indicates the first api level, device has been commercially launched on.
 PRODUCT_SHIPPING_API_LEVEL := 21
-
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
index bda4524..f1b09c1 100644
--- a/target/product/runtime_libart.mk
+++ b/target/product/runtime_libart.mk
@@ -51,6 +51,8 @@
 PRODUCT_PACKAGES += art-runtime
 # ART/dex helpers.
 PRODUCT_PACKAGES += art-tools
+# Android Runtime APEX module.
+PRODUCT_PACKAGES += com.android.runtime
 
 # Certificates.
 PRODUCT_PACKAGES += \
@@ -96,4 +98,5 @@
 
 # Enable minidebuginfo generation unless overridden.
 PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+    dalvik.vm.minidebuginfo=true \
     dalvik.vm.dex2oat-minidebuginfo=true
diff --git a/target/product/telephony_system.mk b/target/product/telephony_system.mk
index 0b1e8a2..fd79472 100644
--- a/target/product/telephony_system.mk
+++ b/target/product/telephony_system.mk
@@ -18,10 +18,8 @@
 # hardware, and install on the system partition.
 
 PRODUCT_PACKAGES := \
-    ANS \
-    CarrierConfig \
+    ONS \
     CarrierDefaultApp \
-    Dialer \
     CallLogBackup \
     CellBroadcastReceiver \
     EmergencyInfo \
diff --git a/target/product/telephony_vendor.mk b/target/product/telephony_vendor.mk
index bddd383..4cff16d 100644
--- a/target/product/telephony_vendor.mk
+++ b/target/product/telephony_vendor.mk
@@ -17,7 +17,13 @@
 # This is the list of modules that are specific to products that have telephony
 # hardware, and install outside the system partition.
 
+# /vendor packages
 PRODUCT_PACKAGES := \
     rild \
 
+# /product packages
+PRODUCT_PACKAGES += \
+    CarrierConfig \
+    Dialer \
+
 PRODUCT_COPY_FILES := \
diff --git a/target/product/treble_common.mk b/target/product/treble_common.mk
index d3cce76..7642876 100644
--- a/target/product/treble_common.mk
+++ b/target/product/treble_common.mk
@@ -38,7 +38,7 @@
 # Telephony:
 #   Provide a default APN configuration
 PRODUCT_COPY_FILES += \
-    device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml
+    device/sample/etc/apns-full-conf.xml:system/etc/apns-conf.xml
 
 # NFC:
 #   Provide default libnfc-nci.conf file for devices that does not have one in
@@ -46,10 +46,15 @@
 PRODUCT_COPY_FILES += \
     device/generic/common/nfc/libnfc-nci.conf:system/etc/libnfc-nci.conf
 
+# GSI specific tasks on boot
+PRODUCT_COPY_FILES += \
+    build/make/target/product/gsi/skip_mount.cfg:system/etc/init/config/skip_mount.cfg \
+    build/make/target/product/gsi/init.gsi.rc:system/etc/init/init.gsi.rc \
+
 # Support for the O-MR1 devices
 PRODUCT_COPY_FILES += \
-    build/make/target/product/vndk/init.gsi.rc:system/etc/init/init.gsi.rc \
-    build/make/target/product/vndk/init.vndk-27.rc:system/etc/init/gsi/init.vndk-27.rc
+    build/make/target/product/gsi/init.legacy-gsi.rc:system/etc/init/init.legacy-gsi.rc \
+    build/make/target/product/gsi/init.vndk-27.rc:system/etc/init/gsi/init.vndk-27.rc
 
 # Name space configuration file for non-enforcing VNDK
 PRODUCT_PACKAGES += \
diff --git a/tools/Android.mk b/tools/Android.mk
deleted file mode 100644
index c05d681..0000000
--- a/tools/Android.mk
+++ /dev/null
@@ -1,23 +0,0 @@
-#
-# Copyright (C) 2010 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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-# Only if this Android.mk was included not by a symlink should it be used.
-# This facilitates the transition away from symlinks: b/64397960
-ifeq ($(LOCAL_PATH),build/make/tools)
-include $(call all-makefiles-under,$(LOCAL_PATH))
-endif
diff --git a/tools/buildinfo.sh b/tools/buildinfo.sh
index 5a54462..7286f95 100755
--- a/tools/buildinfo.sh
+++ b/tools/buildinfo.sh
@@ -8,6 +8,7 @@
 echo "ro.build.version.incremental=$BUILD_NUMBER"
 echo "ro.build.version.sdk=$PLATFORM_SDK_VERSION"
 echo "ro.build.version.preview_sdk=$PLATFORM_PREVIEW_SDK_VERSION"
+echo "ro.build.version.preview_sdk_fingerprint=$PLATFORM_PREVIEW_SDK_FINGERPRINT"
 echo "ro.build.version.codename=$PLATFORM_VERSION_CODENAME"
 echo "ro.build.version.all_codenames=$PLATFORM_VERSION_ALL_CODENAMES"
 echo "ro.build.version.release=$PLATFORM_VERSION"
@@ -17,8 +18,8 @@
 echo "ro.build.date=`$DATE`"
 echo "ro.build.date.utc=`$DATE +%s`"
 echo "ro.build.type=$TARGET_BUILD_TYPE"
-echo "ro.build.user=$USER"
-echo "ro.build.host=`hostname`"
+echo "ro.build.user=$BUILD_USERNAME"
+echo "ro.build.host=$BUILD_HOSTNAME"
 echo "ro.build.tags=$BUILD_VERSION_TAGS"
 echo "ro.build.flavor=$TARGET_BUILD_FLAVOR"
 if [ -n "$BOARD_BUILD_SYSTEM_ROOT_IMAGE" ] ; then
@@ -59,6 +60,5 @@
 if [ -n "$BUILD_THUMBPRINT" ] ; then
   echo "ro.build.thumbprint=$BUILD_THUMBPRINT"
 fi
-echo "ro.build.characteristics=$TARGET_AAPT_CHARACTERISTICS"
 
 echo "# end build properties"
diff --git a/tools/checkowners.py b/tools/checkowners.py
index 8568ccf..7f03968 100755
--- a/tools/checkowners.py
+++ b/tools/checkowners.py
@@ -56,7 +56,8 @@
   glob = '[a-zA-Z0-9_\\.\\-\\*\\?]+'
   globs = '(%s( *, *%s)*)' % (glob, glob)
   perfile = 'per-file +' + globs + ' *= *' + directive
-  pats = '(|%s|%s|%s)$' % (noparent, email, perfile)
+  include = 'include +([^ :]+ *: *)?[^ ]+'
+  pats = '(|%s|%s|%s|%s)$' % (noparent, email, perfile, include)
   patterns = re.compile(pats)
   address_pattern = re.compile('([^@ ]+@[^ @]+)')
   perfile_pattern = re.compile('per-file +.*=(.*)')
diff --git a/tools/droiddoc/Android.mk b/tools/droiddoc/Android.mk
deleted file mode 100644
index ff08edc..0000000
--- a/tools/droiddoc/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright (C) 2008 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.
-
-LOCAL_PATH := $(call my-dir)
-
-# Droiddoc is now Doclava -- See external/doclava.
diff --git a/tools/fs_config/Android.mk b/tools/fs_config/Android.mk
index cb32b9e..5ade258 100644
--- a/tools/fs_config/Android.mk
+++ b/tools/fs_config/Android.mk
@@ -104,11 +104,14 @@
 
 include $(BUILD_HOST_EXECUTABLE)
 fs_config_generate_bin := $(LOCAL_INSTALLED_MODULE)
-# List of all supported vendor, oem and odm Partitions
+# List of supported vendor, oem, odm, product and product_services Partitions
 fs_config_generate_extra_partition_list := $(strip \
   $(if $(BOARD_USES_VENDORIMAGE)$(BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE),vendor) \
   $(if $(BOARD_USES_OEMIMAGE)$(BOARD_OEMIMAGE_FILE_SYSTEM_TYPE),oem) \
-  $(if $(BOARD_USES_ODMIMAGE)$(BOARD_ODMIMAGE_FILE_SYSTEM_TYPE),odm))
+  $(if $(BOARD_USES_ODMIMAGE)$(BOARD_ODMIMAGE_FILE_SYSTEM_TYPE),odm) \
+  $(if $(BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE),product) \
+  $(if $(BOARD_PRODUCT_SERVICESIMAGE_FILE_SYSTEM_TYPE),product_services) \
+)
 
 ##################################
 # Generate the <p>/etc/fs_config_dirs binary files for each partition.
@@ -163,10 +166,11 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
 include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): PRIVATE_PARTITION_LIST := $(fs_config_generate_extra_partition_list)
 $(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
 	@mkdir -p $(dir $@)
-	$< -D $(if $(fs_config_generate_extra_partition_list), \
-	   -P '$(subst $(space),$(comma),$(addprefix -,$(fs_config_generate_extra_partition_list)))') \
+	$< -D $(if $(PRIVATE_PARTITION_LIST), \
+	   -P '$(subst $(space),$(comma),$(addprefix -,$(PRIVATE_PARTITION_LIST)))') \
 	   -o $@
 
 ##################################
@@ -179,10 +183,11 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_INSTALLED_MODULE_STEM := fs_config_files
 include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): PRIVATE_PARTITION_LIST := $(fs_config_generate_extra_partition_list)
 $(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
 	@mkdir -p $(dir $@)
-	$< -F $(if $(fs_config_generate_extra_partition_list), \
-	   -P '$(subst $(space),$(comma),$(addprefix -,$(fs_config_generate_extra_partition_list)))') \
+	$< -F $(if $(PRIVATE_PARTITION_LIST), \
+	   -P '$(subst $(space),$(comma),$(addprefix -,$(PRIVATE_PARTITION_LIST)))') \
 	   -o $@
 
 ifneq ($(filter vendor,$(fs_config_generate_extra_partition_list)),)
@@ -284,6 +289,72 @@
 
 endif
 
+ifneq ($(filter product,$(fs_config_generate_extra_partition_list)),)
+##################################
+# Generate the product/etc/fs_config_dirs binary file for the target
+# Add fs_config_dirs or fs_config_dirs_product to PRODUCT_PACKAGES in
+# the device make file to enable
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := fs_config_dirs_product
+LOCAL_MODULE_CLASS := ETC
+LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
+LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT)/etc
+include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+	@mkdir -p $(dir $@)
+	$< -D -P product -o $@
+
+##################################
+# Generate the product/etc/fs_config_files binary file for the target
+# Add fs_config_files of fs_config_files_product to PRODUCT_PACKAGES in
+# the device make file to enable
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := fs_config_files_product
+LOCAL_MODULE_CLASS := ETC
+LOCAL_INSTALLED_MODULE_STEM := fs_config_files
+LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT)/etc
+include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+	@mkdir -p $(dir $@)
+	$< -F -P product -o $@
+
+endif
+
+ifneq ($(filter product_services,$(fs_config_generate_extra_partition_list)),)
+##################################
+# Generate the product_services/etc/fs_config_dirs binary file for the target
+# Add fs_config_dirs or fs_config_dirs_product_services to PRODUCT_PACKAGES in
+# the device make file to enable
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := fs_config_dirs_product_services
+LOCAL_MODULE_CLASS := ETC
+LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
+LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT_SERVICES)/etc
+include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+	@mkdir -p $(dir $@)
+	$< -D -P product_services -o $@
+
+##################################
+# Generate the product_services/etc/fs_config_files binary file for the target
+# Add fs_config_files of fs_config_files_product_services to PRODUCT_PACKAGES in
+# the device make file to enable
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := fs_config_files_product_services
+LOCAL_MODULE_CLASS := ETC
+LOCAL_INSTALLED_MODULE_STEM := fs_config_files
+LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT_SERVICES)/etc
+include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+	@mkdir -p $(dir $@)
+	$< -F -P product_services -o $@
+
+endif
+
 ##################################
 # Build the oemaid header library when fs config files are present.
 # Intentionally break build if you require generated AIDs
diff --git a/tools/fs_config/OWNERS b/tools/fs_config/OWNERS
new file mode 100644
index 0000000..5599644
--- /dev/null
+++ b/tools/fs_config/OWNERS
@@ -0,0 +1,2 @@
+tomcherry@google.com
+salyzyn@google.com
diff --git a/tools/fs_config/android_filesystem_config_test_data.h b/tools/fs_config/android_filesystem_config_test_data.h
index 07bc8e5..c65d406 100644
--- a/tools/fs_config/android_filesystem_config_test_data.h
+++ b/tools/fs_config/android_filesystem_config_test_data.h
@@ -26,6 +26,8 @@
     {00555, AID_ROOT, AID_SYSTEM, 0, "vendor/etc"},
     {00555, AID_ROOT, AID_SYSTEM, 0, "oem/etc"},
     {00555, AID_ROOT, AID_SYSTEM, 0, "odm/etc"},
+    {00555, AID_ROOT, AID_SYSTEM, 0, "product/etc"},
+    {00555, AID_ROOT, AID_SYSTEM, 0, "product_services/etc"},
     {00755, AID_SYSTEM, AID_ROOT, 0, "system/oem/etc"},
     {00755, AID_SYSTEM, AID_ROOT, 0, "system/odm/etc"},
     {00755, AID_SYSTEM, AID_ROOT, 0, "system/vendor/etc"},
@@ -41,16 +43,22 @@
     {00444, AID_ROOT, AID_SYSTEM, 0, "vendor/etc/fs_config_dirs"},
     {00444, AID_ROOT, AID_SYSTEM, 0, "oem/etc/fs_config_dirs"},
     {00444, AID_ROOT, AID_SYSTEM, 0, "odm/etc/fs_config_dirs"},
+    {00444, AID_ROOT, AID_SYSTEM, 0, "product/etc/fs_config_dirs"},
+    {00444, AID_ROOT, AID_SYSTEM, 0, "product_services/etc/fs_config_dirs"},
     {00444, AID_ROOT, AID_SYSTEM, 0, "system/etc/fs_config_files"},
     {00444, AID_ROOT, AID_SYSTEM, 0, "vendor/etc/fs_config_files"},
     {00444, AID_ROOT, AID_SYSTEM, 0, "oem/etc/fs_config_files"},
     {00444, AID_ROOT, AID_SYSTEM, 0, "odm/etc/fs_config_files"},
+    {00444, AID_ROOT, AID_SYSTEM, 0, "product/etc/fs_config_files"},
+    {00444, AID_ROOT, AID_SYSTEM, 0, "product_services/etc/fs_config_files"},
     {00644, AID_SYSTEM, AID_ROOT, 0, "system/vendor/etc/fs_config_dirs"},
     {00644, AID_SYSTEM, AID_ROOT, 0, "system/oem/etc/fs_config_dirs"},
     {00644, AID_SYSTEM, AID_ROOT, 0, "system/odm/etc/fs_config_dirs"},
     {00644, AID_SYSTEM, AID_ROOT, 0, "system/vendor/etc/fs_config_files"},
     {00644, AID_SYSTEM, AID_ROOT, 0, "system/oem/etc/fs_config_files"},
     {00644, AID_SYSTEM, AID_ROOT, 0, "system/odm/etc/fs_config_files"},
+    {00644, AID_SYSTEM, AID_ROOT, 0, "system/product/etc/fs_config_files"},
+    {00644, AID_SYSTEM, AID_ROOT, 0, "system/product_services/etc/fs_config_files"},
     {00644, AID_SYSTEM, AID_ROOT, 0, "etc/fs_config_files"},
     {00666, AID_ROOT, AID_SYSTEM, 0, "data/misc/oem"},
 };
diff --git a/tools/fs_config/fs_config_generate.c b/tools/fs_config/fs_config_generate.c
index cb7ff9d..dddd331 100644
--- a/tools/fs_config/fs_config_generate.c
+++ b/tools/fs_config/fs_config_generate.c
@@ -41,18 +41,7 @@
 #endif
 
 #ifdef NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_FILES
-static const struct fs_path_config android_device_files[] = {
-#ifdef NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS
-    {0000, AID_ROOT, AID_ROOT, 0, "system/etc/fs_config_dirs"},
-    {0000, AID_ROOT, AID_ROOT, 0, "vendor/etc/fs_config_dirs"},
-    {0000, AID_ROOT, AID_ROOT, 0, "oem/etc/fs_config_dirs"},
-    {0000, AID_ROOT, AID_ROOT, 0, "odm/etc/fs_config_dirs"},
-#endif
-    {0000, AID_ROOT, AID_ROOT, 0, "system/etc/fs_config_files"},
-    {0000, AID_ROOT, AID_ROOT, 0, "vendor/etc/fs_config_files"},
-    {0000, AID_ROOT, AID_ROOT, 0, "oem/etc/fs_config_files"},
-    {0000, AID_ROOT, AID_ROOT, 0, "odm/etc/fs_config_files"},
-};
+static const struct fs_path_config android_device_files[] = { };
 #endif
 
 static void usage() {
diff --git a/tools/fs_config/fs_config_generator.py b/tools/fs_config/fs_config_generator.py
index cd534ec..0a8def8 100755
--- a/tools/fs_config/fs_config_generator.py
+++ b/tools/fs_config/fs_config_generator.py
@@ -909,22 +909,6 @@
         '#warning No device-supplied android_filesystem_config.h,'
         ' using empty default.')
 
-    # Long names.
-    # pylint: disable=invalid-name
-    _NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS_ENTRY = (
-        '{ 00000, AID_ROOT, AID_ROOT, 0,'
-        '"system/etc/fs_config_dirs" },')
-
-    _NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_FILES_ENTRY = (
-        '{ 00000, AID_ROOT, AID_ROOT, 0,'
-        '"system/etc/fs_config_files" },')
-
-    _IFDEF_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS = (
-        '#ifdef NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS')
-    # pylint: enable=invalid-name
-
-    _ENDIF = '#endif'
-
     _OPEN_FILE_STRUCT = (
         'static const struct fs_path_config android_device_files[] = {')
 
@@ -1082,12 +1066,6 @@
             for fs_config in files:
                 self._to_fs_entry(fs_config)
 
-            if not are_dirs:
-                print FSConfigGen._IFDEF_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS
-                print(
-                    '    ' +
-                    FSConfigGen._NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS_ENTRY)
-                print FSConfigGen._ENDIF
             print FSConfigGen._CLOSE_FILE_STRUCT
 
         if are_dirs:
@@ -1108,9 +1086,14 @@
 
     _INCLUDE = '#include <private/android_filesystem_config.h>'
 
+    # Note that the android_id name field is of type 'const char[]' instead of
+    # 'const char*'.  While this seems less straightforward as we need to
+    # calculate the max length of all names, this allows the entire android_ids
+    # table to be placed in .rodata section instead of .data.rel.ro section,
+    # resulting in less memory pressure.
     _STRUCT_FS_CONFIG = textwrap.dedent("""
                          struct android_id_info {
-                             const char *name;
+                             const char name[%d];
                              unsigned aid;
                          };""")
 
@@ -1132,12 +1115,13 @@
     def __call__(self, args):
 
         hdr = AIDHeaderParser(args['hdrfile'])
+        max_name_length = max(len(aid.friendly) + 1 for aid in hdr.aids)
 
         print AIDArrayGen._GENERATED
         print
         print AIDArrayGen._INCLUDE
         print
-        print AIDArrayGen._STRUCT_FS_CONFIG
+        print AIDArrayGen._STRUCT_FS_CONFIG % max_name_length
         print
         print AIDArrayGen._OPEN_ID_ARRAY
 
@@ -1310,6 +1294,28 @@
 
         print "%s::%s:" % (logon, uid)
 
+@generator('print')
+class PrintGen(BaseGenerator):
+    """Prints just the constants and values, separated by spaces, in an easy to
+    parse format for use by other scripts.
+
+    Each line is just the identifier and the value, separated by a space.
+    """
+
+    def add_opts(self, opt_group):
+        opt_group.add_argument(
+            'aid-header', help='An android_filesystem_config.h file.')
+
+    def __call__(self, args):
+
+        hdr_parser = AIDHeaderParser(args['aid-header'])
+        aids = hdr_parser.aids
+
+        aids.sort(key=lambda item: int(item.normalized_value))
+
+        for aid in aids:
+            print '%s %s' % (aid.identifier, aid.normalized_value)
+
 
 def main():
     """Main entry point for execution."""
diff --git a/tools/fs_config/fs_config_test.cpp b/tools/fs_config/fs_config_test.cpp
index f95a4ca..916c615 100644
--- a/tools/fs_config/fs_config_test.cpp
+++ b/tools/fs_config/fs_config_test.cpp
@@ -23,7 +23,6 @@
 #include <android-base/file.h>
 #include <android-base/macros.h>
 #include <android-base/strings.h>
-#include <android-base/stringprintf.h>
 #include <gtest/gtest.h>
 #include <private/android_filesystem_config.h>
 #include <private/fs_config.h>
@@ -31,12 +30,12 @@
 #include "android_filesystem_config_test_data.h"
 
 // must run test in the test directory
-const static char fs_config_generate_command[] = "./fs_config_generate_test";
+static const std::string fs_config_generate_command = "./fs_config_generate_test";
 
-static std::string popenToString(std::string command) {
+static std::string popenToString(const std::string command) {
   std::string ret;
 
-  FILE* fp = popen(command.c_str(), "r");
+  auto fp = popen(command.c_str(), "r");
   if (fp) {
     if (!android::base::ReadFdToString(fileno(fp), &ret)) ret = "";
     pclose(fp);
@@ -46,15 +45,14 @@
 
 static void confirm(std::string&& data, const fs_path_config* config,
                     ssize_t num_config) {
-  const struct fs_path_config_from_file* pc =
-      reinterpret_cast<const fs_path_config_from_file*>(data.c_str());
-  size_t len = data.size();
+  auto pc = reinterpret_cast<const fs_path_config_from_file*>(data.c_str());
+  auto len = data.size();
 
   ASSERT_TRUE(config != NULL);
   ASSERT_LT(0, num_config);
 
   while (len > 0) {
-    uint16_t host_len = pc->len;
+    auto host_len = pc->len;
     if (host_len > len) break;
 
     EXPECT_EQ(config->mode, pc->mode);
@@ -76,148 +74,114 @@
 /* See local android_filesystem_config.h for test data */
 
 TEST(fs_conf_test, dirs) {
-  confirm(popenToString(
-              android::base::StringPrintf("%s -D", fs_config_generate_command)),
+  confirm(popenToString(fs_config_generate_command + " -D"),
           android_device_dirs, arraysize(android_device_dirs));
 }
 
 TEST(fs_conf_test, files) {
-  confirm(popenToString(
-              android::base::StringPrintf("%s -F", fs_config_generate_command)),
+  confirm(popenToString(fs_config_generate_command + " -F"),
           android_device_files, arraysize(android_device_files));
 }
 
-static const char vendor_str[] = "vendor/";
-static const char vendor_alt_str[] = "system/vendor/";
-static const char oem_str[] = "oem/";
-static const char oem_alt_str[] = "system/oem/";
-static const char odm_str[] = "odm/";
-static const char odm_alt_str[] = "system/odm/";
+static bool is_system(const char* prefix) {
+  return !android::base::StartsWith(prefix, "vendor/") &&
+         !android::base::StartsWith(prefix, "system/vendor/") &&
+         !android::base::StartsWith(prefix, "oem/") &&
+         !android::base::StartsWith(prefix, "system/oem/") &&
+         !android::base::StartsWith(prefix, "odm/") &&
+         !android::base::StartsWith(prefix, "system/odm/") &&
+         !android::base::StartsWith(prefix, "product/") &&
+         !android::base::StartsWith(prefix, "system/product/") &&
+         !android::base::StartsWith(prefix, "product_services/") &&
+         !android::base::StartsWith(prefix, "system/product_services/");
+}
 
 TEST(fs_conf_test, system_dirs) {
   std::vector<fs_path_config> dirs;
-  const fs_path_config* config = android_device_dirs;
-  for (size_t num = arraysize(android_device_dirs); num; --num) {
-    if (!android::base::StartsWith(config->prefix, vendor_str) &&
-        !android::base::StartsWith(config->prefix, vendor_alt_str) &&
-        !android::base::StartsWith(config->prefix, oem_str) &&
-        !android::base::StartsWith(config->prefix, oem_alt_str) &&
-        !android::base::StartsWith(config->prefix, odm_str) &&
-        !android::base::StartsWith(config->prefix, odm_alt_str)) {
+  auto config = android_device_dirs;
+  for (auto num = arraysize(android_device_dirs); num; --num) {
+    if (is_system(config->prefix)) {
       dirs.emplace_back(*config);
     }
     ++config;
   }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -D -P -vendor,-oem,-odm", fs_config_generate_command)),
+  confirm(popenToString(fs_config_generate_command + " -D -P -vendor,-oem,-odm,-product,-product_services"),
+          &dirs[0], dirs.size());
+}
+
+static void fs_conf_test_dirs(const std::string& partition_name) {
+  std::vector<fs_path_config> dirs;
+  auto config = android_device_dirs;
+  const auto str = partition_name + "/";
+  const auto alt_str = "system/" + partition_name + "/";
+  for (auto num = arraysize(android_device_dirs); num; --num) {
+    if (android::base::StartsWith(config->prefix, str) ||
+        android::base::StartsWith(config->prefix, alt_str)) {
+      dirs.emplace_back(*config);
+    }
+    ++config;
+  }
+  confirm(popenToString(fs_config_generate_command + " -D -P " + partition_name),
           &dirs[0], dirs.size());
 }
 
 TEST(fs_conf_test, vendor_dirs) {
-  std::vector<fs_path_config> dirs;
-  const fs_path_config* config = android_device_dirs;
-  for (size_t num = arraysize(android_device_dirs); num; --num) {
-    if (android::base::StartsWith(config->prefix, vendor_str) ||
-        android::base::StartsWith(config->prefix, vendor_alt_str)) {
-      dirs.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -D -P vendor", fs_config_generate_command)),
-          &dirs[0], dirs.size());
+  fs_conf_test_dirs("vendor");
 }
 
 TEST(fs_conf_test, oem_dirs) {
-  std::vector<fs_path_config> dirs;
-  const fs_path_config* config = android_device_dirs;
-  for (size_t num = arraysize(android_device_dirs); num; --num) {
-    if (android::base::StartsWith(config->prefix, oem_str) ||
-        android::base::StartsWith(config->prefix, oem_alt_str)) {
-      dirs.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -D -P oem", fs_config_generate_command)),
-          &dirs[0], dirs.size());
+  fs_conf_test_dirs("oem");
 }
 
 TEST(fs_conf_test, odm_dirs) {
-  std::vector<fs_path_config> dirs;
-  const fs_path_config* config = android_device_dirs;
-  for (size_t num = arraysize(android_device_dirs); num; --num) {
-    if (android::base::StartsWith(config->prefix, odm_str) ||
-        android::base::StartsWith(config->prefix, odm_alt_str)) {
-      dirs.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -D -P odm", fs_config_generate_command)),
-          &dirs[0], dirs.size());
+  fs_conf_test_dirs("odm");
 }
 
 TEST(fs_conf_test, system_files) {
   std::vector<fs_path_config> files;
-  const fs_path_config* config = android_device_files;
-  for (size_t num = arraysize(android_device_files); num; --num) {
-    if (!android::base::StartsWith(config->prefix, vendor_str) &&
-        !android::base::StartsWith(config->prefix, vendor_alt_str) &&
-        !android::base::StartsWith(config->prefix, oem_str) &&
-        !android::base::StartsWith(config->prefix, oem_alt_str) &&
-        !android::base::StartsWith(config->prefix, odm_str) &&
-        !android::base::StartsWith(config->prefix, odm_alt_str)) {
+  auto config = android_device_files;
+  for (auto num = arraysize(android_device_files); num; --num) {
+    if (is_system(config->prefix)) {
       files.emplace_back(*config);
     }
     ++config;
   }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -F -P -vendor,-oem,-odm", fs_config_generate_command)),
+  confirm(popenToString(fs_config_generate_command + " -F -P -vendor,-oem,-odm,-product,-product_services"),
+          &files[0], files.size());
+}
+
+static void fs_conf_test_files(const std::string& partition_name) {
+  std::vector<fs_path_config> files;
+  auto config = android_device_files;
+  const auto str = partition_name + "/";
+  const auto alt_str = "system/" + partition_name + "/";
+  for (auto num = arraysize(android_device_files); num; --num) {
+    if (android::base::StartsWith(config->prefix, str) ||
+        android::base::StartsWith(config->prefix, alt_str)) {
+      files.emplace_back(*config);
+    }
+    ++config;
+  }
+  confirm(popenToString(fs_config_generate_command + " -F -P " + partition_name),
           &files[0], files.size());
 }
 
 TEST(fs_conf_test, vendor_files) {
-  std::vector<fs_path_config> files;
-  const fs_path_config* config = android_device_files;
-  for (size_t num = arraysize(android_device_files); num; --num) {
-    if (android::base::StartsWith(config->prefix, vendor_str) ||
-        android::base::StartsWith(config->prefix, vendor_alt_str)) {
-      files.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -F -P vendor", fs_config_generate_command)),
-          &files[0], files.size());
+  fs_conf_test_files("vendor");
 }
 
 TEST(fs_conf_test, oem_files) {
-  std::vector<fs_path_config> files;
-  const fs_path_config* config = android_device_files;
-  for (size_t num = arraysize(android_device_files); num; --num) {
-    if (android::base::StartsWith(config->prefix, oem_str) ||
-        android::base::StartsWith(config->prefix, oem_alt_str)) {
-      files.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -F -P oem", fs_config_generate_command)),
-          &files[0], files.size());
+  fs_conf_test_files("oem");
 }
 
 TEST(fs_conf_test, odm_files) {
-  std::vector<fs_path_config> files;
-  const fs_path_config* config = android_device_files;
-  for (size_t num = arraysize(android_device_files); num; --num) {
-    if (android::base::StartsWith(config->prefix, odm_str) ||
-        android::base::StartsWith(config->prefix, odm_alt_str)) {
-      files.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(android::base::StringPrintf(
-              "%s -F -P odm", fs_config_generate_command)),
-          &files[0], files.size());
+  fs_conf_test_files("odm");
+}
+
+TEST(fs_conf_test, product_files) {
+  fs_conf_test_files("product");
+}
+
+TEST(fs_conf_test, product_services_files) {
+  fs_conf_test_files("product_services");
 }
diff --git a/tools/releasetools/OWNERS b/tools/releasetools/OWNERS
index 39448cf..766adb4 100644
--- a/tools/releasetools/OWNERS
+++ b/tools/releasetools/OWNERS
@@ -1 +1,2 @@
 tbao@google.com
+xunchang@google.com
diff --git a/tools/releasetools/add_img_to_target_files.py b/tools/releasetools/add_img_to_target_files.py
index ddc50be..e75b3b7 100755
--- a/tools/releasetools/add_img_to_target_files.py
+++ b/tools/releasetools/add_img_to_target_files.py
@@ -55,6 +55,7 @@
 import zipfile
 
 import build_image
+import build_super_image
 import common
 import rangelib
 import sparse_img
@@ -81,18 +82,23 @@
 
 
 class OutputFile(object):
-  def __init__(self, output_zip, input_dir, prefix, name):
-    self._output_zip = output_zip
-    self.input_name = os.path.join(input_dir, prefix, name)
+  """A helper class to write a generated file to the given dir or zip.
 
+  When generating images, we want the outputs to go into the given zip file, or
+  the given dir.
+
+  Attributes:
+    name: The name of the output file, regardless of the final destination.
+  """
+
+  def __init__(self, output_zip, input_dir, prefix, name):
+    # We write the intermediate output file under the given input_dir, even if
+    # the final destination is a zip archive.
+    self.name = os.path.join(input_dir, prefix, name)
+    self._output_zip = output_zip
     if self._output_zip:
       self._zip_name = os.path.join(prefix, name)
 
-      root, suffix = os.path.splitext(name)
-      self.name = common.MakeTempFile(prefix=root + '-', suffix=suffix)
-    else:
-      self.name = self.input_name
-
   def Write(self):
     if self._output_zip:
       common.ZipWrite(self._output_zip, self.name, self._zip_name)
@@ -128,9 +134,9 @@
   output_zip. Returns the name of the system image file."""
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("system.img already exists; no need to rebuild...")
-    return img.input_name
+    return img.name
 
   def output_sink(fn, data):
     ofile = open(os.path.join(OPTIONS.input_tmp, "SYSTEM", fn), "w")
@@ -160,7 +166,7 @@
   and store it in output_zip."""
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "system_other.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("system_other.img already exists; no need to rebuild...")
     return
 
@@ -172,9 +178,9 @@
   output_zip."""
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("vendor.img already exists; no need to rebuild...")
-    return img.input_name
+    return img.name
 
   block_list = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "vendor.map")
   CreateImage(OPTIONS.input_tmp, OPTIONS.info_dict, "vendor", img,
@@ -187,9 +193,9 @@
   output_zip."""
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "product.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("product.img already exists; no need to rebuild...")
-    return img.input_name
+    return img.name
 
   block_list = OutputFile(
       output_zip, OPTIONS.input_tmp, "IMAGES", "product.map")
@@ -205,9 +211,9 @@
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES",
                    "product_services.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("product_services.img already exists; no need to rebuild...")
-    return img.input_name
+    return img.name
 
   block_list = OutputFile(
       output_zip, OPTIONS.input_tmp, "IMAGES", "product_services.map")
@@ -221,9 +227,9 @@
   """Turn the contents of ODM into an odm image and store it in output_zip."""
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "odm.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("odm.img already exists; no need to rebuild...")
-    return img.input_name
+    return img.name
 
   block_list = OutputFile(
       output_zip, OPTIONS.input_tmp, "IMAGES", "odm.map")
@@ -240,9 +246,9 @@
   image under PREBUILT_IMAGES/, signs it as needed, and returns the image name.
   """
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "dtbo.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("dtbo.img already exists; no need to rebuild...")
-    return img.input_name
+    return img.name
 
   dtbo_prebuilt_path = os.path.join(
       OPTIONS.input_tmp, "PREBUILT_IMAGES", "dtbo.img")
@@ -260,11 +266,7 @@
     args = OPTIONS.info_dict.get("avb_dtbo_add_hash_footer_args")
     if args and args.strip():
       cmd.extend(shlex.split(args))
-    proc = common.Run(cmd)
-    output, _ = proc.communicate()
-    assert proc.returncode == 0, \
-        "Failed to call 'avbtool add_hash_footer' for {}:\n{}".format(
-            img.name, output)
+    common.RunAndCheckOutput(cmd)
 
   img.Write()
   return img.name
@@ -330,6 +332,12 @@
       image_blocks_key = what + "_image_blocks"
       info_dict[image_blocks_key] = int(image_size) / 4096 - 1
 
+  use_dynamic_size = (
+      info_dict.get("use_dynamic_partition_size") == "true" and
+      what in shlex.split(info_dict.get("dynamic_partition_list", "").strip()))
+  if use_dynamic_size:
+    info_dict.update(build_image.GlobalDictFromImageProp(image_props, what))
+
 
 def AddUserdata(output_zip):
   """Create a userdata image and store it in output_zip.
@@ -341,7 +349,7 @@
   """
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "userdata.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("userdata.img already exists; no need to rebuild...")
     return
 
@@ -415,9 +423,9 @@
 
   img = OutputFile(
       output_zip, OPTIONS.input_tmp, "IMAGES", "{}.img".format(name))
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("%s.img already exists; not rebuilding...", name)
-    return img.input_name
+    return img.name
 
   avbtool = os.getenv('AVBTOOL') or OPTIONS.info_dict["avb_avbtool"]
   cmd = [avbtool, "make_vbmeta_image", "--output", img.name]
@@ -457,10 +465,7 @@
         assert found, 'Failed to find {}'.format(image_path)
     cmd.extend(split_args)
 
-  proc = common.Run(cmd)
-  stdoutdata, _ = proc.communicate()
-  assert proc.returncode == 0, \
-      "avbtool make_vbmeta_image failed:\n{}".format(stdoutdata)
+  common.RunAndCheckOutput(cmd)
   img.Write()
   return img.name
 
@@ -487,11 +492,7 @@
   args = OPTIONS.info_dict.get("board_bpt_make_table_args")
   if args:
     cmd.extend(shlex.split(args))
-
-  proc = common.Run(cmd)
-  stdoutdata, _ = proc.communicate()
-  assert proc.returncode == 0, \
-      "bpttool make_table failed:\n{}".format(stdoutdata)
+  common.RunAndCheckOutput(cmd)
 
   img.Write()
   bpt.Write()
@@ -501,7 +502,7 @@
   """Create an empty cache image and store it in output_zip."""
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "cache.img")
-  if os.path.exists(img.input_name):
+  if os.path.exists(img.name):
     logger.info("cache.img already exists; no need to rebuild...")
     return
 
@@ -606,10 +607,7 @@
 
   temp_care_map = common.MakeTempFile(prefix="caremap-", suffix=".pb")
   care_map_gen_cmd = ["care_map_generator", temp_care_map_text, temp_care_map]
-  proc = common.Run(care_map_gen_cmd)
-  output, _ = proc.communicate()
-  assert proc.returncode == 0, \
-      "Failed to generate the care_map proto message:\n{}".format(output)
+  common.RunAndCheckOutput(care_map_gen_cmd)
 
   care_map_path = "META/care_map.pb"
   if output_zip and care_map_path not in output_zip.namelist():
@@ -656,18 +654,23 @@
   """Create a super_empty.img and store it in output_zip."""
 
   img = OutputFile(output_zip, OPTIONS.input_tmp, "IMAGES", "super_empty.img")
-  cmd = [OPTIONS.info_dict.get('lpmake')]
-  cmd += shlex.split(OPTIONS.info_dict.get('lpmake_args').strip())
-  cmd += ['--output', img.name]
-
-  proc = common.Run(cmd)
-  stdoutdata, _ = proc.communicate()
-  assert proc.returncode == 0, \
-      "lpmake tool failed:\n{}".format(stdoutdata)
-
+  build_super_image.BuildSuperImage(OPTIONS.info_dict, img.name)
   img.Write()
 
 
+def AddSuperSplit(output_zip):
+  """Create split super_*.img and store it in output_zip."""
+
+  outdir = os.path.join(OPTIONS.input_tmp, "OTA")
+  built = build_super_image.BuildSuperImage(OPTIONS.input_tmp, outdir)
+
+  if built:
+    for dev in OPTIONS.info_dict['super_block_devices'].strip().split():
+      img = OutputFile(output_zip, OPTIONS.input_tmp, "OTA",
+                       "super_" + dev + ".img")
+      img.Write()
+
+
 def ReplaceUpdatedFiles(zip_filename, files_list):
   """Updates all the ZIP entries listed in files_list.
 
@@ -861,10 +864,15 @@
     banner("vbmeta")
     AddVBMeta(output_zip, partitions, "vbmeta", vbmeta_partitions)
 
-  if OPTIONS.info_dict.get("super_size"):
+  if OPTIONS.info_dict.get("build_super_partition") == "true":
     banner("super_empty")
     AddSuperEmpty(output_zip)
 
+    if OPTIONS.info_dict.get(
+        "build_retrofit_dynamic_partitions_ota_package") == "true":
+      banner("super split images")
+      AddSuperSplit(output_zip)
+
   banner("radio")
   ab_partitions_txt = os.path.join(OPTIONS.input_tmp, "META",
                                    "ab_partitions.txt")
diff --git a/tools/releasetools/blockimgdiff.py b/tools/releasetools/blockimgdiff.py
index 2d20e23..80d4023 100644
--- a/tools/releasetools/blockimgdiff.py
+++ b/tools/releasetools/blockimgdiff.py
@@ -26,7 +26,8 @@
 import re
 import sys
 import threading
-from collections import deque, OrderedDict
+import zlib
+from collections import deque, namedtuple, OrderedDict
 from hashlib import sha1
 
 import common
@@ -36,8 +37,12 @@
 
 logger = logging.getLogger(__name__)
 
+# The tuple contains the style and bytes of a bsdiff|imgdiff patch.
+PatchInfo = namedtuple("PatchInfo", ["imgdiff", "content"])
+
 
 def compute_patch(srcfile, tgtfile, imgdiff=False):
+  """Calls bsdiff|imgdiff to compute the patch data, returns a PatchInfo."""
   patchfile = common.MakeTempFile(prefix='patch-')
 
   cmd = ['imgdiff', '-z'] if imgdiff else ['bsdiff']
@@ -52,7 +57,7 @@
     raise ValueError(output)
 
   with open(patchfile, 'rb') as f:
-    return f.read()
+    return PatchInfo(imgdiff, f.read())
 
 
 class Image(object):
@@ -203,17 +208,17 @@
     self.id = len(by_id)
     by_id.append(self)
 
-    self._patch = None
+    self._patch_info = None
 
   @property
-  def patch(self):
-    return self._patch
+  def patch_info(self):
+    return self._patch_info
 
-  @patch.setter
-  def patch(self, patch):
-    if patch:
+  @patch_info.setter
+  def patch_info(self, info):
+    if info:
       assert self.style == "diff"
-    self._patch = patch
+    self._patch_info = info
 
   def NetStashChange(self):
     return (sum(sr.size() for (_, sr) in self.stash_before) -
@@ -224,7 +229,7 @@
     self.use_stash = []
     self.style = "new"
     self.src_ranges = RangeSet()
-    self.patch = None
+    self.patch_info = None
 
   def __str__(self):
     return (str(self.id) + ": <" + str(self.src_ranges) + " " + self.style +
@@ -462,19 +467,27 @@
     self.AbbreviateSourceNames()
     self.FindTransfers()
 
-    # Find the ordering dependencies among transfers (this is O(n^2)
-    # in the number of transfers).
-    self.GenerateDigraph()
-    # Find a sequence of transfers that satisfies as many ordering
-    # dependencies as possible (heuristically).
-    self.FindVertexSequence()
-    # Fix up the ordering dependencies that the sequence didn't
-    # satisfy.
-    self.ReverseBackwardEdges()
-    self.ImproveVertexSequence()
+    self.FindSequenceForTransfers()
 
     # Ensure the runtime stash size is under the limit.
     if common.OPTIONS.cache_size is not None:
+      stash_limit = (common.OPTIONS.cache_size *
+                     common.OPTIONS.stash_threshold / self.tgt.blocksize)
+      # Ignore the stash limit and calculate the maximum simultaneously stashed
+      # blocks needed.
+      _, max_stashed_blocks = self.ReviseStashSize(ignore_stash_limit=True)
+
+      # We cannot stash more blocks than the stash limit simultaneously. As a
+      # result, some 'diff' commands will be converted to new; leading to an
+      # unintended large package. To mitigate this issue, we can carefully
+      # choose the transfers for conversion. The number '1024' can be further
+      # tweaked here to balance the package size and build time.
+      if max_stashed_blocks > stash_limit + 1024:
+        self.SelectAndConvertDiffTransfersToNew()
+        # Regenerate the sequence as the graph has changed.
+        self.FindSequenceForTransfers()
+
+      # Revise the stash size again to keep the size under limit.
       self.ReviseStashSize()
 
     # Double-check our work.
@@ -704,7 +717,21 @@
           "max stashed blocks: %d  (%d bytes), limit: <unknown>\n",
           max_stashed_blocks, self._max_stashed_size)
 
-  def ReviseStashSize(self):
+  def ReviseStashSize(self, ignore_stash_limit=False):
+    """ Revises the transfers to keep the stash size within the size limit.
+
+    Iterates through the transfer list and calculates the stash size each
+    transfer generates. Converts the affected transfers to new if we reach the
+    stash limit.
+
+    Args:
+      ignore_stash_limit: Ignores the stash limit and calculates the max
+      simultaneous stashed blocks instead. No change will be made to the
+      transfer list with this flag.
+
+    Return:
+      A tuple of (tgt blocks converted to new, max stashed blocks)
+    """
     logger.info("Revising stash size...")
     stash_map = {}
 
@@ -719,16 +746,19 @@
       for stash_raw_id, _ in xf.use_stash:
         stash_map[stash_raw_id] += (xf,)
 
-    # Compute the maximum blocks available for stash based on /cache size and
-    # the threshold.
-    cache_size = common.OPTIONS.cache_size
-    stash_threshold = common.OPTIONS.stash_threshold
-    max_allowed = cache_size * stash_threshold / self.tgt.blocksize
+    max_allowed_blocks = None
+    if not ignore_stash_limit:
+      # Compute the maximum blocks available for stash based on /cache size and
+      # the threshold.
+      cache_size = common.OPTIONS.cache_size
+      stash_threshold = common.OPTIONS.stash_threshold
+      max_allowed_blocks = cache_size * stash_threshold / self.tgt.blocksize
 
     # See the comments for 'stashes' in WriteTransfers().
     stashes = {}
     stashed_blocks = 0
     new_blocks = 0
+    max_stashed_blocks = 0
 
     # Now go through all the commands. Compute the required stash size on the
     # fly. If a command requires excess stash than available, it deletes the
@@ -745,7 +775,7 @@
         if sh not in stashes:
           stashed_blocks_after += sr.size()
 
-        if stashed_blocks_after > max_allowed:
+        if max_allowed_blocks and stashed_blocks_after > max_allowed_blocks:
           # We cannot stash this one for a later command. Find out the command
           # that will use this stash and replace the command with "new".
           use_cmd = stash_map[stash_raw_id][2]
@@ -758,15 +788,21 @@
           else:
             stashes[sh] = 1
           stashed_blocks = stashed_blocks_after
+          max_stashed_blocks = max(max_stashed_blocks, stashed_blocks)
 
       # "move" and "diff" may introduce implicit stashes in BBOTA v3. Prior to
       # ComputePatches(), they both have the style of "diff".
       if xf.style == "diff":
         assert xf.tgt_ranges and xf.src_ranges
         if xf.src_ranges.overlaps(xf.tgt_ranges):
-          if stashed_blocks + xf.src_ranges.size() > max_allowed:
+          if (max_allowed_blocks and
+              stashed_blocks + xf.src_ranges.size() > max_allowed_blocks):
             replaced_cmds.append(xf)
             logger.info("%10d  %9s  %s", xf.src_ranges.size(), "implicit", xf)
+          else:
+            # The whole source ranges will be stashed for implicit stashes.
+            max_stashed_blocks = max(max_stashed_blocks,
+                                     stashed_blocks + xf.src_ranges.size())
 
       # Replace the commands in replaced_cmds with "new"s.
       for cmd in replaced_cmds:
@@ -795,7 +831,7 @@
     logger.info(
         "  Total %d blocks (%d bytes) are packed as new blocks due to "
         "insufficient cache size.", new_blocks, num_of_bytes)
-    return new_blocks
+    return new_blocks, max_stashed_blocks
 
   def ComputePatches(self, prefix):
     logger.info("Reticulating splines...")
@@ -829,7 +865,7 @@
             # These are identical; we don't need to generate a patch,
             # just issue copy commands on the device.
             xf.style = "move"
-            xf.patch = None
+            xf.patch_info = None
             tgt_size = xf.tgt_ranges.size() * self.tgt.blocksize
             if xf.src_ranges != xf.tgt_ranges:
               logger.info(
@@ -839,11 +875,10 @@
                       xf.tgt_name + " (from " + xf.src_name + ")"),
                   str(xf.tgt_ranges), str(xf.src_ranges))
           else:
-            if xf.patch:
-              # We have already generated the patch with imgdiff, while
-              # splitting large APKs (i.e. in FindTransfers()).
-              assert not self.disable_imgdiff
-              imgdiff = True
+            if xf.patch_info:
+              # We have already generated the patch (e.g. during split of large
+              # APKs or reduction of stash size)
+              imgdiff = xf.patch_info.imgdiff
             else:
               imgdiff = self.CanUseImgdiff(
                   xf.tgt_name, xf.tgt_ranges, xf.src_ranges)
@@ -854,85 +889,16 @@
         else:
           assert False, "unknown style " + xf.style
 
-    if diff_queue:
-      if self.threads > 1:
-        logger.info("Computing patches (using %d threads)...", self.threads)
-      else:
-        logger.info("Computing patches...")
-
-      diff_total = len(diff_queue)
-      patches = [None] * diff_total
-      error_messages = []
-
-      # Using multiprocessing doesn't give additional benefits, due to the
-      # pattern of the code. The diffing work is done by subprocess.call, which
-      # already runs in a separate process (not affected much by the GIL -
-      # Global Interpreter Lock). Using multiprocess also requires either a)
-      # writing the diff input files in the main process before forking, or b)
-      # reopening the image file (SparseImage) in the worker processes. Doing
-      # neither of them further improves the performance.
-      lock = threading.Lock()
-      def diff_worker():
-        while True:
-          with lock:
-            if not diff_queue:
-              return
-            xf_index, imgdiff, patch_index = diff_queue.pop()
-            xf = self.transfers[xf_index]
-
-          patch = xf.patch
-          if not patch:
-            src_ranges = xf.src_ranges
-            tgt_ranges = xf.tgt_ranges
-
-            src_file = common.MakeTempFile(prefix="src-")
-            with open(src_file, "wb") as fd:
-              self.src.WriteRangeDataToFd(src_ranges, fd)
-
-            tgt_file = common.MakeTempFile(prefix="tgt-")
-            with open(tgt_file, "wb") as fd:
-              self.tgt.WriteRangeDataToFd(tgt_ranges, fd)
-
-            message = []
-            try:
-              patch = compute_patch(src_file, tgt_file, imgdiff)
-            except ValueError as e:
-              message.append(
-                  "Failed to generate %s for %s: tgt=%s, src=%s:\n%s" % (
-                      "imgdiff" if imgdiff else "bsdiff",
-                      xf.tgt_name if xf.tgt_name == xf.src_name else
-                      xf.tgt_name + " (from " + xf.src_name + ")",
-                      xf.tgt_ranges, xf.src_ranges, e.message))
-            if message:
-              with lock:
-                error_messages.extend(message)
-
-          with lock:
-            patches[patch_index] = (xf_index, patch)
-
-      threads = [threading.Thread(target=diff_worker)
-                 for _ in range(self.threads)]
-      for th in threads:
-        th.start()
-      while threads:
-        threads.pop().join()
-
-      if error_messages:
-        logger.error('ERROR:')
-        logger.error('\n'.join(error_messages))
-        logger.error('\n\n\n')
-        sys.exit(1)
-    else:
-      patches = []
+    patches = self.ComputePatchesForInputList(diff_queue, False)
 
     offset = 0
     with open(prefix + ".patch.dat", "wb") as patch_fd:
-      for index, patch in patches:
+      for index, patch_info, _ in patches:
         xf = self.transfers[index]
-        xf.patch_len = len(patch)
+        xf.patch_len = len(patch_info.content)
         xf.patch_start = offset
         offset += xf.patch_len
-        patch_fd.write(patch)
+        patch_fd.write(patch_info.content)
 
         tgt_size = xf.tgt_ranges.size() * self.tgt.blocksize
         logger.info(
@@ -999,6 +965,32 @@
       for i in range(s, e):
         assert touched[i] == 1
 
+  def FindSequenceForTransfers(self):
+    """Finds a sequence for the given transfers.
+
+     The goal is to minimize the violation of order dependencies between these
+     transfers, so that fewer blocks are stashed when applying the update.
+    """
+
+    # Clear the existing dependency between transfers
+    for xf in self.transfers:
+      xf.goes_before = OrderedDict()
+      xf.goes_after = OrderedDict()
+
+      xf.stash_before = []
+      xf.use_stash = []
+
+    # Find the ordering dependencies among transfers (this is O(n^2)
+    # in the number of transfers).
+    self.GenerateDigraph()
+    # Find a sequence of transfers that satisfies as many ordering
+    # dependencies as possible (heuristically).
+    self.FindVertexSequence()
+    # Fix up the ordering dependencies that the sequence didn't
+    # satisfy.
+    self.ReverseBackwardEdges()
+    self.ImproveVertexSequence()
+
   def ImproveVertexSequence(self):
     logger.info("Improving vertex order...")
 
@@ -1248,6 +1240,152 @@
           b.goes_before[a] = size
           a.goes_after[b] = size
 
+  def ComputePatchesForInputList(self, diff_queue, compress_target):
+    """Returns a list of patch information for the input list of transfers.
+
+      Args:
+        diff_queue: a list of transfers with style 'diff'
+        compress_target: If True, compresses the target ranges of each
+            transfers; and save the size.
+
+      Returns:
+        A list of (transfer order, patch_info, compressed_size) tuples.
+    """
+
+    if not diff_queue:
+      return []
+
+    if self.threads > 1:
+      logger.info("Computing patches (using %d threads)...", self.threads)
+    else:
+      logger.info("Computing patches...")
+
+    diff_total = len(diff_queue)
+    patches = [None] * diff_total
+    error_messages = []
+
+    # Using multiprocessing doesn't give additional benefits, due to the
+    # pattern of the code. The diffing work is done by subprocess.call, which
+    # already runs in a separate process (not affected much by the GIL -
+    # Global Interpreter Lock). Using multiprocess also requires either a)
+    # writing the diff input files in the main process before forking, or b)
+    # reopening the image file (SparseImage) in the worker processes. Doing
+    # neither of them further improves the performance.
+    lock = threading.Lock()
+
+    def diff_worker():
+      while True:
+        with lock:
+          if not diff_queue:
+            return
+          xf_index, imgdiff, patch_index = diff_queue.pop()
+          xf = self.transfers[xf_index]
+
+        message = []
+        compressed_size = None
+
+        patch_info = xf.patch_info
+        if not patch_info:
+          src_file = common.MakeTempFile(prefix="src-")
+          with open(src_file, "wb") as fd:
+            self.src.WriteRangeDataToFd(xf.src_ranges, fd)
+
+          tgt_file = common.MakeTempFile(prefix="tgt-")
+          with open(tgt_file, "wb") as fd:
+            self.tgt.WriteRangeDataToFd(xf.tgt_ranges, fd)
+
+          try:
+            patch_info = compute_patch(src_file, tgt_file, imgdiff)
+          except ValueError as e:
+            message.append(
+                "Failed to generate %s for %s: tgt=%s, src=%s:\n%s" % (
+                    "imgdiff" if imgdiff else "bsdiff",
+                    xf.tgt_name if xf.tgt_name == xf.src_name else
+                    xf.tgt_name + " (from " + xf.src_name + ")",
+                    xf.tgt_ranges, xf.src_ranges, e.message))
+
+        if compress_target:
+          tgt_data = self.tgt.ReadRangeSet(xf.tgt_ranges)
+          try:
+            # Compresses with the default level
+            compress_obj = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS)
+            compressed_data = (compress_obj.compress("".join(tgt_data))
+                               + compress_obj.flush())
+            compressed_size = len(compressed_data)
+          except zlib.error as e:
+            message.append(
+                "Failed to compress the data in target range {} for {}:\n"
+                "{}".format(xf.tgt_ranges, xf.tgt_name, e.message))
+
+        if message:
+          with lock:
+            error_messages.extend(message)
+
+        with lock:
+          patches[patch_index] = (xf_index, patch_info, compressed_size)
+
+    threads = [threading.Thread(target=diff_worker)
+               for _ in range(self.threads)]
+    for th in threads:
+      th.start()
+    while threads:
+      threads.pop().join()
+
+    if error_messages:
+      logger.error('ERROR:')
+      logger.error('\n'.join(error_messages))
+      logger.error('\n\n\n')
+      sys.exit(1)
+
+    return patches
+
+  def SelectAndConvertDiffTransfersToNew(self):
+    """Converts the diff transfers to reduce the max simultaneous stash.
+
+    Since the 'new' data is compressed with deflate, we can select the 'diff'
+    transfers for conversion by comparing its patch size with the size of the
+    compressed data. Ideally, we want to convert the transfers with a small
+    size increase, but using a large number of stashed blocks.
+    """
+
+    logger.info("Selecting diff commands to convert to new.")
+    diff_queue = []
+    for xf in self.transfers:
+      if xf.style == "diff" and xf.src_sha1 != xf.tgt_sha1:
+        use_imgdiff = self.CanUseImgdiff(xf.tgt_name, xf.tgt_ranges,
+                                         xf.src_ranges)
+        diff_queue.append((xf.order, use_imgdiff, len(diff_queue)))
+
+    # Remove the 'move' transfers, and compute the patch & compressed size
+    # for the remaining.
+    result = self.ComputePatchesForInputList(diff_queue, True)
+
+    removed_stashed_blocks = 0
+    for xf_index, patch_info, compressed_size in result:
+      xf = self.transfers[xf_index]
+      if not xf.patch_info:
+        xf.patch_info = patch_info
+
+      size_ratio = len(xf.patch_info.content) * 100.0 / compressed_size
+      diff_style = "imgdiff" if xf.patch_info.imgdiff else "bsdiff"
+      logger.info("%s, target size: %d, style: %s, patch size: %d,"
+                  " compression_size: %d, ratio %.2f%%", xf.tgt_name,
+                  xf.tgt_ranges.size(), diff_style,
+                  len(xf.patch_info.content), compressed_size, size_ratio)
+
+      # Convert the transfer to new if the compressed size is smaller or equal.
+      # We don't need to maintain the stash_before lists here because the
+      # graph will be regenerated later.
+      if len(xf.patch_info.content) >= compressed_size:
+        removed_stashed_blocks += sum(sr.size() for _, sr in xf.use_stash)
+        logger.info("Converting %s to new", xf.tgt_name)
+        xf.ConvertToNew()
+
+    # TODO(xunchang) convert more transfers by sorting:
+    # (compressed size - patch_size) / used_stashed_blocks
+
+    logger.info("Removed %d stashed blocks", removed_stashed_blocks)
+
   def FindTransfers(self):
     """Parse the file_map to generate all the transfers."""
 
@@ -1585,7 +1723,7 @@
                                 self.tgt.RangeSha1(tgt_ranges),
                                 self.src.RangeSha1(src_ranges),
                                 "diff", self.transfers)
-      transfer_split.patch = patch
+      transfer_split.patch_info = PatchInfo(True, patch)
 
   def AbbreviateSourceNames(self):
     for k in self.src.file_map.keys():
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
index 74da3a1..521b319 100755
--- a/tools/releasetools/build_image.py
+++ b/tools/releasetools/build_image.py
@@ -75,26 +75,30 @@
   """
   cmd = ["find", path, "-print"]
   output = common.RunAndCheckOutput(cmd, verbose=False)
-  # increase by > 4% as number of files and directories is not whole picture.
-  return output.count('\n') * 25 // 24
+  # TODO(b/122328872) Fix estimation algorithm to not need the multiplier.
+  return output.count('\n') * 2
 
 
-def GetFilesystemCharacteristics(sparse_image_path):
-  """Returns various filesystem characteristics of "sparse_image_path".
+def GetFilesystemCharacteristics(image_path, sparse_image=True):
+  """Returns various filesystem characteristics of "image_path".
 
   Args:
-    sparse_image_path: The file to analyze.
+    image_path: The file to analyze.
+    sparse_image: Image is sparse
 
   Returns:
     The characteristics dictionary.
   """
-  unsparse_image_path = UnsparseImage(sparse_image_path, replace=False)
+  unsparse_image_path = image_path
+  if sparse_image:
+    unsparse_image_path = UnsparseImage(image_path, replace=False)
 
   cmd = ["tune2fs", "-l", unsparse_image_path]
   try:
     output = common.RunAndCheckOutput(cmd, verbose=False)
   finally:
-    os.remove(unsparse_image_path)
+    if sparse_image:
+      os.remove(unsparse_image_path)
   fs_dict = {}
   for line in output.splitlines():
     fields = line.split(":")
@@ -221,8 +225,8 @@
             adjusted_blocks))
 
 
-def BuildImage(in_dir, prop_dict, out_file, target_out=None):
-  """Builds an image for the files under in_dir and writes it to out_file.
+def BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config):
+  """Builds a pure image for the files under in_dir and writes it to out_file.
 
   Args:
     in_dir: Path to input directory.
@@ -233,104 +237,15 @@
         points to the /system directory under PRODUCT_OUT. fs_config (the one
         under system/core/libcutils) reads device specific FS config files from
         there.
+    fs_config: The fs_config file that drives the prototype
 
   Raises:
     BuildImageError: On build image failures.
   """
-  original_mount_point = prop_dict["mount_point"]
-  in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
-
   build_command = []
   fs_type = prop_dict.get("fs_type", "")
   run_e2fsck = False
 
-  fs_spans_partition = True
-  if fs_type.startswith("squash"):
-    fs_spans_partition = False
-
-  is_verity_partition = "verity_block_device" in prop_dict
-  verity_supported = prop_dict.get("verity") == "true"
-  verity_fec_supported = prop_dict.get("verity_fec") == "true"
-
-  avb_footer_type = None
-  if prop_dict.get("avb_hash_enable") == "true":
-    avb_footer_type = "hash"
-  elif prop_dict.get("avb_hashtree_enable") == "true":
-    avb_footer_type = "hashtree"
-
-  if avb_footer_type:
-    avbtool = prop_dict.get("avb_avbtool")
-    avb_signing_args = prop_dict.get(
-        "avb_add_" + avb_footer_type + "_footer_args")
-
-  if (prop_dict.get("use_dynamic_partition_size") == "true" and
-      "partition_size" not in prop_dict):
-    # If partition_size is not defined, use output of `du' + reserved_size.
-    size = GetDiskUsage(in_dir)
-    logger.info(
-        "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
-    # If not specified, give us 16MB margin for GetDiskUsage error ...
-    size += int(prop_dict.get("partition_reserved_size", BYTES_IN_MB * 16))
-    # Round this up to a multiple of 4K so that avbtool works
-    size = common.RoundUpTo4K(size)
-    # Adjust partition_size to add more space for AVB footer, to prevent
-    # it from consuming partition_reserved_size.
-    if avb_footer_type:
-      size = verity_utils.AVBCalcMinPartitionSize(
-          size,
-          lambda x: verity_utils.AVBCalcMaxImageSize(
-              avbtool, avb_footer_type, x, avb_signing_args))
-    prop_dict["partition_size"] = str(size)
-    if fs_type.startswith("ext"):
-      if "extfs_inode_count" not in prop_dict:
-        prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
-      logger.info(
-          "First Pass based on estimates of %d MB and %s inodes.",
-          size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
-      prop_dict["mount_point"] = original_mount_point
-      BuildImage(in_dir, prop_dict, out_file, target_out)
-      fs_dict = GetFilesystemCharacteristics(out_file)
-      block_size = int(fs_dict.get("Block size", "4096"))
-      free_size = int(fs_dict.get("Free blocks", "0")) * block_size
-      reserved_size = int(prop_dict.get("partition_reserved_size", 0))
-      if free_size <= reserved_size:
-        logger.info(
-            "Not worth reducing image %d <= %d.", free_size, reserved_size)
-      else:
-        size -= free_size + (free_size // 60)
-        size += reserved_size
-        if block_size <= 4096:
-          size = common.RoundUpTo4K(size)
-        else:
-          size = ((size + block_size - 1) // block_size) * block_size
-      extfs_inode_count = prop_dict["extfs_inode_count"]
-      inodes = int(fs_dict.get("Inode count", extfs_inode_count))
-      inodes -= int(fs_dict.get("Free inodes", "0"))
-      prop_dict["extfs_inode_count"] = str(inodes)
-      prop_dict["partition_size"] = str(size)
-      logger.info(
-          "Allocating %d Inodes for %s.", inodes, out_file)
-    logger.info(
-        "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
-
-  prop_dict["image_size"] = prop_dict["partition_size"]
-
-  # Adjust the image size to make room for the hashes if this is to be verified.
-  if verity_supported and is_verity_partition:
-    partition_size = int(prop_dict.get("partition_size"))
-    image_size, verity_size = verity_utils.AdjustPartitionSizeForVerity(
-        partition_size, verity_fec_supported)
-    prop_dict["image_size"] = str(image_size)
-    prop_dict["verity_size"] = str(verity_size)
-
-  # Adjust the image size for AVB hash footer or AVB hashtree footer.
-  if avb_footer_type:
-    partition_size = prop_dict["partition_size"]
-    # avb_add_hash_footer_args or avb_add_hashtree_footer_args.
-    max_image_size = verity_utils.AVBCalcMaxImageSize(
-        avbtool, avb_footer_type, partition_size, avb_signing_args)
-    prop_dict["image_size"] = str(max_image_size)
-
   if fs_type.startswith("ext"):
     build_command = [prop_dict["ext_mkuserimg"]]
     if "extfs_sparse_flag" in prop_dict:
@@ -369,6 +284,7 @@
         build_command.extend(["-S", prop_dict["hash_seed"]])
     if "ext4_share_dup_blocks" in prop_dict:
       build_command.append("-c")
+    build_command.extend(["--inode_size", "256"])
     if "selinux_fc" in prop_dict:
       build_command.append(prop_dict["selinux_fc"])
   elif fs_type.startswith("squash"):
@@ -423,8 +339,8 @@
       logger.exception("Failed to compute disk usage with du")
       du_str = "unknown"
     print(
-        "Out of space? The tree size of {} is {}, with reserved space of {} "
-        "bytes ({} MB).".format(
+        "Out of space? Out of inodes? The tree size of {} is {}, "
+        "with reserved space of {} bytes ({} MB).".format(
             in_dir, du_str,
             int(prop_dict.get("partition_reserved_size", 0)),
             int(prop_dict.get("partition_reserved_size", 0)) // BYTES_IN_MB))
@@ -437,38 +353,6 @@
             int(prop_dict["partition_size"]) // BYTES_IN_MB))
     raise
 
-  # Check if there's enough headroom space available for ext4 image.
-  if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
-    CheckHeadroom(mkfs_output, prop_dict)
-
-  if not fs_spans_partition:
-    mount_point = prop_dict.get("mount_point")
-    image_size = int(prop_dict["image_size"])
-    sparse_image_size = verity_utils.GetSimgSize(out_file)
-    if sparse_image_size > image_size:
-      raise BuildImageError(
-          "Error: {} image size of {} is larger than partition size of "
-          "{}".format(mount_point, sparse_image_size, image_size))
-    if verity_supported and is_verity_partition:
-      verity_utils.ZeroPadSimg(out_file, image_size - sparse_image_size)
-
-  # Create the verified image if this is to be verified.
-  if verity_supported and is_verity_partition:
-    verity_utils.MakeVerityEnabledImage(
-        out_file, verity_fec_supported, prop_dict)
-
-  # Add AVB HASH or HASHTREE footer (metadata).
-  if avb_footer_type:
-    partition_size = prop_dict["partition_size"]
-    partition_name = prop_dict["partition_name"]
-    # key_path and algorithm are only available when chain partition is used.
-    key_path = prop_dict.get("avb_key_path")
-    algorithm = prop_dict.get("avb_algorithm")
-    salt = prop_dict.get("avb_salt")
-    verity_utils.AVBAddFooter(
-        out_file, avbtool, avb_footer_type, partition_size, partition_name,
-        key_path, algorithm, salt, avb_signing_args)
-
   if run_e2fsck and prop_dict.get("skip_fsck") != "true":
     unsparse_image = UnsparseImage(out_file, replace=False)
 
@@ -479,6 +363,123 @@
     finally:
       os.remove(unsparse_image)
 
+  return mkfs_output
+
+
+def BuildImage(in_dir, prop_dict, out_file, target_out=None):
+  """Builds an image for the files under in_dir and writes it to out_file.
+
+  Args:
+    in_dir: Path to input directory.
+    prop_dict: A property dict that contains info like partition size. Values
+        will be updated with computed values.
+    out_file: The output image file.
+    target_out: Path to the TARGET_OUT directory as in Makefile. It actually
+        points to the /system directory under PRODUCT_OUT. fs_config (the one
+        under system/core/libcutils) reads device specific FS config files from
+        there.
+
+  Raises:
+    BuildImageError: On build image failures.
+  """
+  in_dir, fs_config = SetUpInDirAndFsConfig(in_dir, prop_dict)
+
+  build_command = []
+  fs_type = prop_dict.get("fs_type", "")
+
+  fs_spans_partition = True
+  if fs_type.startswith("squash"):
+    fs_spans_partition = False
+
+  # Get a builder for creating an image that's to be verified by Verified Boot,
+  # or None if not applicable.
+  verity_image_builder = verity_utils.CreateVerityImageBuilder(prop_dict)
+
+  if (prop_dict.get("use_dynamic_partition_size") == "true" and
+      "partition_size" not in prop_dict):
+    # If partition_size is not defined, use output of `du' + reserved_size.
+    size = GetDiskUsage(in_dir)
+    logger.info(
+        "The tree size of %s is %d MB.", in_dir, size // BYTES_IN_MB)
+    # If not specified, give us 16MB margin for GetDiskUsage error ...
+    reserved_size = int(prop_dict.get("partition_reserved_size", BYTES_IN_MB * 16))
+    partition_headroom = int(prop_dict.get("partition_headroom", 0))
+    if fs_type.startswith("ext4") and partition_headroom > reserved_size:
+      reserved_size = partition_headroom
+    size += reserved_size
+    # Round this up to a multiple of 4K so that avbtool works
+    size = common.RoundUpTo4K(size)
+    if fs_type.startswith("ext"):
+      prop_dict["partition_size"] = str(size)
+      prop_dict["image_size"] = str(size)
+      if "extfs_inode_count" not in prop_dict:
+        prop_dict["extfs_inode_count"] = str(GetInodeUsage(in_dir))
+      logger.info(
+          "First Pass based on estimates of %d MB and %s inodes.",
+          size // BYTES_IN_MB, prop_dict["extfs_inode_count"])
+      BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
+      sparse_image = False
+      if "extfs_sparse_flag" in prop_dict:
+        sparse_image = True
+      fs_dict = GetFilesystemCharacteristics(out_file, sparse_image)
+      os.remove(out_file)
+      block_size = int(fs_dict.get("Block size", "4096"))
+      free_size = int(fs_dict.get("Free blocks", "0")) * block_size
+      reserved_size = int(prop_dict.get("partition_reserved_size", 0))
+      partition_headroom = int(fs_dict.get("partition_headroom", 0))
+      if fs_type.startswith("ext4") and partition_headroom > reserved_size:
+        reserved_size = partition_headroom
+      if free_size <= reserved_size:
+        logger.info(
+            "Not worth reducing image %d <= %d.", free_size, reserved_size)
+      else:
+        size -= free_size
+        size += reserved_size
+        if reserved_size == 0:
+          # add .2% margin
+          size = size * 1002 // 1000
+        # Use a minimum size, otherwise we will fail to calculate an AVB footer
+        # or fail to construct an ext4 image.
+        size = max(size, 256 * 1024)
+        if block_size <= 4096:
+          size = common.RoundUpTo4K(size)
+        else:
+          size = ((size + block_size - 1) // block_size) * block_size
+      extfs_inode_count = prop_dict["extfs_inode_count"]
+      inodes = int(fs_dict.get("Inode count", extfs_inode_count))
+      inodes -= int(fs_dict.get("Free inodes", "0"))
+      # add .2% margin
+      inodes = inodes * 1002 // 1000
+      prop_dict["extfs_inode_count"] = str(inodes)
+      prop_dict["partition_size"] = str(size)
+      logger.info(
+          "Allocating %d Inodes for %s.", inodes, out_file)
+    if verity_image_builder:
+      size = verity_image_builder.CalculateDynamicPartitionSize(size)
+    prop_dict["partition_size"] = str(size)
+    logger.info(
+        "Allocating %d MB for %s.", size // BYTES_IN_MB, out_file)
+
+  prop_dict["image_size"] = prop_dict["partition_size"]
+
+  # Adjust the image size to make room for the hashes if this is to be verified.
+  if verity_image_builder:
+    max_image_size = verity_image_builder.CalculateMaxImageSize()
+    prop_dict["image_size"] = str(max_image_size)
+
+  mkfs_output = BuildImageMkfs(in_dir, prop_dict, out_file, target_out, fs_config)
+
+  # Check if there's enough headroom space available for ext4 image.
+  if "partition_headroom" in prop_dict and fs_type.startswith("ext4"):
+    CheckHeadroom(mkfs_output, prop_dict)
+
+  if not fs_spans_partition and verity_image_builder:
+    verity_image_builder.PadSparseImage(out_file)
+
+  # Create the verified image if this is to be verified.
+  if verity_image_builder:
+    verity_image_builder.Build(out_file)
+
 
 def ImagePropFromGlobalDict(glob_dict, mount_point):
   """Build an image property dictionary from the global dictionary.
diff --git a/tools/releasetools/build_super_image.py b/tools/releasetools/build_super_image.py
new file mode 100755
index 0000000..bb0e641
--- /dev/null
+++ b/tools/releasetools/build_super_image.py
@@ -0,0 +1,229 @@
+#!/usr/bin/env python
+#
+# 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.
+
+"""
+Usage: build_super_image input_file output_dir_or_file
+
+input_file: one of the following:
+  - directory containing extracted target files. It will load info from
+    META/misc_info.txt and build full super image / split images using source
+    images from IMAGES/.
+  - target files package. Same as above, but extracts the archive before
+    building super image.
+  - a dictionary file containing input arguments to build. Check
+    `dump_dynamic_partitions_info' for details.
+    In addition:
+    - "ab_update" needs to be true for A/B devices.
+    - If source images should be included in the output image (for super.img
+      and super split images), a list of "*_image" should be paths of each
+      source images.
+
+output_dir_or_file:
+    If a single super image is built (for super_empty.img, or super.img for
+    launch devices), this argument is the output file.
+    If a collection of split images are built (for retrofit devices), this
+    argument is the output directory.
+"""
+
+from __future__ import print_function
+
+import logging
+import os.path
+import shlex
+import sys
+import zipfile
+
+import common
+import sparse_img
+
+if sys.hexversion < 0x02070000:
+  print("Python 2.7 or newer is required.", file=sys.stderr)
+  sys.exit(1)
+
+logger = logging.getLogger(__name__)
+
+
+UNZIP_PATTERN = ["IMAGES/*", "META/*"]
+
+
+def GetPartitionSizeFromImage(img):
+  try:
+    simg = sparse_img.SparseImage(img)
+    return simg.blocksize * simg.total_blocks
+  except ValueError:
+    return os.path.getsize(img)
+
+
+def GetArgumentsForImage(partition, group, image=None):
+  image_size = GetPartitionSizeFromImage(image) if image else 0
+
+  cmd = ["--partition",
+         "{}:readonly:{}:{}".format(partition, image_size, group)]
+  if image:
+    cmd += ["--image", "{}={}".format(partition, image)]
+
+  return cmd
+
+
+def BuildSuperImageFromDict(info_dict, output):
+
+  cmd = [info_dict["lpmake"],
+         "--metadata-size", "65536",
+         "--super-name", info_dict["super_metadata_device"]]
+
+  ab_update = info_dict.get("ab_update") == "true"
+  retrofit = info_dict.get("dynamic_partition_retrofit") == "true"
+  block_devices = shlex.split(info_dict.get("super_block_devices", "").strip())
+  groups = shlex.split(info_dict.get("super_partition_groups", "").strip())
+
+  if ab_update:
+    cmd += ["--metadata-slots", "2"]
+  else:
+    cmd += ["--metadata-slots", "1"]
+
+  if ab_update and retrofit:
+    cmd.append("--auto-slot-suffixing")
+
+  for device in block_devices:
+    size = info_dict["super_{}_device_size".format(device)]
+    cmd += ["--device", "{}:{}".format(device, size)]
+
+  append_suffix = ab_update and not retrofit
+  has_image = False
+  for group in groups:
+    group_size = info_dict["super_{}_group_size".format(group)]
+    if append_suffix:
+      cmd += ["--group", "{}_a:{}".format(group, group_size),
+              "--group", "{}_b:{}".format(group, group_size)]
+    else:
+      cmd += ["--group", "{}:{}".format(group, group_size)]
+
+    partition_list = shlex.split(
+        info_dict["super_{}_partition_list".format(group)].strip())
+
+    for partition in partition_list:
+      image = info_dict.get("{}_image".format(partition))
+      if image:
+        has_image = True
+
+      if not append_suffix:
+        cmd += GetArgumentsForImage(partition, group, image)
+        continue
+
+      # For A/B devices, super partition always contains sub-partitions in
+      # the _a slot, because this image should only be used for
+      # bootstrapping / initializing the device. When flashing the image,
+      # bootloader fastboot should always mark _a slot as bootable.
+      cmd += GetArgumentsForImage(partition + "_a", group + "_a", image)
+
+      other_image = None
+      if partition == "system" and "system_other_image" in info_dict:
+        other_image = info_dict["system_other_image"]
+        has_image = True
+
+      cmd += GetArgumentsForImage(partition + "_b", group + "_b", other_image)
+
+  if has_image:
+    cmd.append("--sparse")
+
+  cmd += ["--output", output]
+
+  common.RunAndCheckOutput(cmd)
+
+  if retrofit and has_image:
+    logger.info("Done writing images to directory %s", output)
+  else:
+    logger.info("Done writing image %s", output)
+
+  return True
+
+
+def BuildSuperImageFromExtractedTargetFiles(inp, out):
+  info_dict = common.LoadInfoDict(inp)
+  partition_list = shlex.split(
+      info_dict.get("dynamic_partition_list", "").strip())
+
+  if "system" in partition_list:
+    image_path = os.path.join(inp, "IMAGES", "system_other.img")
+    if os.path.isfile(image_path):
+      info_dict["system_other_image"] = image_path
+
+  missing_images = []
+  for partition in partition_list:
+    image_path = os.path.join(inp, "IMAGES", "{}.img".format(partition))
+    if not os.path.isfile(image_path):
+      missing_images.append(image_path)
+    else:
+      info_dict["{}_image".format(partition)] = image_path
+  if missing_images:
+    logger.warning("Skip building super image because the following "
+                   "images are missing from target files:\n%s",
+                   "\n".join(missing_images))
+    return False
+  return BuildSuperImageFromDict(info_dict, out)
+
+
+def BuildSuperImageFromTargetFiles(inp, out):
+  input_tmp = common.UnzipTemp(inp, UNZIP_PATTERN)
+  return BuildSuperImageFromExtractedTargetFiles(input_tmp, out)
+
+
+def BuildSuperImage(inp, out):
+
+  if isinstance(inp, dict):
+    logger.info("Building super image from info dict...")
+    return BuildSuperImageFromDict(inp, out)
+
+  if isinstance(inp, str):
+    if os.path.isdir(inp):
+      logger.info("Building super image from extracted target files...")
+      return BuildSuperImageFromExtractedTargetFiles(inp, out)
+
+    if zipfile.is_zipfile(inp):
+      logger.info("Building super image from target files...")
+      return BuildSuperImageFromTargetFiles(inp, out)
+
+    if os.path.isfile(inp):
+      with open(inp) as f:
+        lines = f.read()
+      logger.info("Building super image from info dict...")
+      return BuildSuperImageFromDict(common.LoadDictionaryFromLines(lines.split("\n")), out)
+
+  raise ValueError("{} is not a dictionary or a valid path".format(inp))
+
+
+def main(argv):
+
+  args = common.ParseOptions(argv, __doc__)
+
+  if len(args) != 2:
+    common.Usage(__doc__)
+    sys.exit(1)
+
+  common.InitLogging()
+
+  BuildSuperImage(args[0], args[1])
+
+
+if __name__ == "__main__":
+  try:
+    common.CloseInheritedPipes()
+    main(sys.argv[1:])
+  except common.ExternalError:
+    logger.exception("\n   ERROR:\n")
+    sys.exit(1)
+  finally:
+    common.Cleanup()
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index fe63458..dcc083c 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -623,10 +623,13 @@
   # "boot" or "recovery", without extension.
   partition_name = os.path.basename(sourcedir).lower()
 
-  if (partition_name == "recovery" and
-      info_dict.get("include_recovery_dtbo") == "true"):
-    fn = os.path.join(sourcedir, "recovery_dtbo")
-    cmd.extend(["--recovery_dtbo", fn])
+  if partition_name == "recovery":
+    if info_dict.get("include_recovery_dtbo") == "true":
+      fn = os.path.join(sourcedir, "recovery_dtbo")
+      cmd.extend(["--recovery_dtbo", fn])
+    if info_dict.get("include_recovery_acpio") == "true":
+      fn = os.path.join(sourcedir, "recovery_acpio")
+      cmd.extend(["--recovery_acpio", fn])
 
   RunAndCheckOutput(cmd)
 
@@ -827,10 +830,10 @@
     ranges = image.file_map[entry]
 
     # If a RangeSet has been tagged as using shared blocks while loading the
-    # image, its block list must be already incomplete due to that reason. Don't
-    # give it 'incomplete' tag to avoid messing up the imgdiff stats.
+    # image, check the original block list to determine its completeness. Note
+    # that the 'incomplete' flag would be tagged to the original RangeSet only.
     if ranges.extra.get('uses_shared_blocks'):
-      continue
+      ranges = ranges.extra['uses_shared_blocks']
 
     if RoundUpTo4K(info.file_size) > ranges.size() * 4096:
       ranges.extra['incomplete'] = True
diff --git a/tools/releasetools/ota_from_target_files.py b/tools/releasetools/ota_from_target_files.py
index 2264655..7ec8ad8 100755
--- a/tools/releasetools/ota_from_target_files.py
+++ b/tools/releasetools/ota_from_target_files.py
@@ -64,6 +64,13 @@
       Generate an OTA package that will wipe the user data partition when
       installed.
 
+  --retrofit_dynamic_partitions
+      Generates an OTA package that updates a device to support dynamic
+      partitions (default False). This flag is implied when generating
+      an incremental OTA where the base build does not support dynamic
+      partitions but the target build does. For A/B, when this flag is set,
+      --skip_postinstall is implied.
+
 Non-A/B OTA specific options
 
   -b  (--binary) <file>
@@ -213,11 +220,14 @@
 OPTIONS.extracted_input = None
 OPTIONS.key_passwords = []
 OPTIONS.skip_postinstall = False
+OPTIONS.retrofit_dynamic_partitions = False
 
 
 METADATA_NAME = 'META-INF/com/android/metadata'
 POSTINSTALL_CONFIG = 'META/postinstall_config.txt'
+DYNAMIC_PARTITION_INFO = 'META/dynamic_partitions_info.txt'
 UNZIP_PATTERN = ['IMAGES/*', 'META/*']
+SUPER_SPLIT_PATTERN = ['OTA/super_*.img']
 
 
 class BuildInfo(object):
@@ -1717,6 +1727,60 @@
   return target_file
 
 
+def GetTargetFilesZipForRetrofitDynamicPartitions(input_file,
+                                                  super_block_devices):
+  """Returns a target-files.zip for retrofitting dynamic partitions.
+
+  This allows brillo_update_payload to generate an OTA based on the exact
+  bits on the block devices. Postinstall is disabled.
+
+  Args:
+    input_file: The input target-files.zip filename.
+    super_block_devices: The list of super block devices
+
+  Returns:
+    The filename of target-files.zip with *.img replaced with super_*.img for
+    each block device in super_block_devices.
+  """
+  assert super_block_devices, "No super_block_devices are specified."
+
+  replace = {'OTA/super_{}.img'.format(dev): 'IMAGES/{}.img'.format(dev)
+             for dev in super_block_devices}
+
+  target_file = common.MakeTempFile(prefix="targetfiles-", suffix=".zip")
+  shutil.copyfile(input_file, target_file)
+
+  with zipfile.ZipFile(input_file, 'r') as input_zip:
+    namelist = input_zip.namelist()
+
+  # Always skip postinstall for a retrofit update.
+  to_delete = [POSTINSTALL_CONFIG]
+
+  # Delete dynamic_partitions_info.txt so that brillo_update_payload thinks this
+  # is a regular update on devices without dynamic partitions support.
+  to_delete += [DYNAMIC_PARTITION_INFO]
+
+  # Remove the existing partition images as well as the map files.
+  to_delete += replace.values()
+  to_delete += ['IMAGES/{}.map'.format(dev) for dev in super_block_devices]
+
+  common.ZipDelete(target_file, to_delete)
+
+  input_tmp = common.UnzipTemp(input_file, SUPER_SPLIT_PATTERN)
+  target_zip = zipfile.ZipFile(target_file, 'a', allowZip64=True)
+
+  # Write super_{foo}.img as {foo}.img.
+  for src, dst in replace.items():
+    assert src in namelist, \
+          'Missing {} in {}; {} cannot be written'.format(src, input_file, dst)
+    unzipped_file = os.path.join(input_tmp, *src.split('/'))
+    common.ZipWrite(target_zip, unzipped_file, arcname=dst)
+
+  common.ZipClose(target_zip)
+
+  return target_file
+
+
 def WriteABOTAPackageWithBrilloScript(target_file, output_file,
                                       source_file=None):
   """Generates an Android OTA package that has A/B update payload."""
@@ -1738,7 +1802,10 @@
   # Metadata to comply with Android OTA package format.
   metadata = GetPackageMetadata(target_info, source_info)
 
-  if OPTIONS.skip_postinstall:
+  if OPTIONS.retrofit_dynamic_partitions:
+    target_file = GetTargetFilesZipForRetrofitDynamicPartitions(
+        target_file, target_info.get("super_block_devices").strip().split())
+  elif OPTIONS.skip_postinstall:
     target_file = GetTargetFilesZipWithoutPostinstallConfig(target_file)
 
   # Generate payload.
@@ -1870,6 +1937,8 @@
       OPTIONS.extracted_input = a
     elif o == "--skip_postinstall":
       OPTIONS.skip_postinstall = True
+    elif o == "--retrofit_dynamic_partitions":
+      OPTIONS.retrofit_dynamic_partitions = True
     else:
       return False
     return True
@@ -1900,6 +1969,7 @@
                                  "payload_signer_args=",
                                  "extracted_input_target_files=",
                                  "skip_postinstall",
+                                 "retrofit_dynamic_partitions",
                              ], extra_option_handler=option_handler)
 
   if len(args) != 2:
@@ -1943,6 +2013,23 @@
   # Load OEM dicts if provided.
   OPTIONS.oem_dicts = _LoadOemDicts(OPTIONS.oem_source)
 
+  # Assume retrofitting dynamic partitions when base build does not set
+  # use_dynamic_partitions but target build does.
+  if (OPTIONS.source_info_dict and
+      OPTIONS.source_info_dict.get("use_dynamic_partitions") != "true" and
+      OPTIONS.target_info_dict.get("use_dynamic_partitions") == "true"):
+    if OPTIONS.target_info_dict.get("dynamic_partition_retrofit") != "true":
+      raise common.ExternalError(
+          "Expect to generate incremental OTA for retrofitting dynamic "
+          "partitions, but dynamic_partition_retrofit is not set in target "
+          "build.")
+    logger.info("Implicitly generating retrofit incremental OTA.")
+    OPTIONS.retrofit_dynamic_partitions = True
+
+  # Skip postinstall for retrofitting dynamic partitions.
+  if OPTIONS.retrofit_dynamic_partitions:
+    OPTIONS.skip_postinstall = True
+
   ab_update = OPTIONS.info_dict.get("ab_update") == "true"
 
   # Use the default key to sign the package if not specified with package_key.
diff --git a/tools/releasetools/sign_target_files_apks.py b/tools/releasetools/sign_target_files_apks.py
index de3ead6..a07f67f 100755
--- a/tools/releasetools/sign_target_files_apks.py
+++ b/tools/releasetools/sign_target_files_apks.py
@@ -309,6 +309,10 @@
     if filename.startswith("IMAGES/"):
       continue
 
+    # Skip split super images, which will be re-generated during signing.
+    if filename.startswith("OTA/") and filename.endswith(".img"):
+      continue
+
     data = input_tf_zip.read(filename)
     out_info = copy.copy(info)
     (is_apk, is_compressed, should_be_skipped) = GetApkFileInfo(
diff --git a/tools/releasetools/sparse_img.py b/tools/releasetools/sparse_img.py
index 5ebb1f0..7919ba4 100644
--- a/tools/releasetools/sparse_img.py
+++ b/tools/releasetools/sparse_img.py
@@ -248,15 +248,21 @@
         ranges = rangelib.RangeSet.parse(ranges)
 
         if allow_shared_blocks:
-          # Find the shared blocks that have been claimed by others.
+          # Find the shared blocks that have been claimed by others. If so, tag
+          # the entry so that we can skip applying imgdiff on this file.
           shared_blocks = ranges.subtract(remaining)
           if shared_blocks:
-            ranges = ranges.subtract(shared_blocks)
-            if not ranges:
+            non_shared = ranges.subtract(shared_blocks)
+            if not non_shared:
               continue
 
-            # Tag the entry so that we can skip applying imgdiff on this file.
-            ranges.extra['uses_shared_blocks'] = True
+            # There shouldn't anything in the extra dict yet.
+            assert not ranges.extra, "Non-empty RangeSet.extra"
+
+            # Put the non-shared RangeSet as the value in the block map, which
+            # has a copy of the original RangeSet.
+            non_shared.extra['uses_shared_blocks'] = ranges
+            ranges = non_shared
 
         out[fn] = ranges
         assert ranges.size() == ranges.intersect(remaining).size()
diff --git a/tools/releasetools/test_add_img_to_target_files.py b/tools/releasetools/test_add_img_to_target_files.py
index ad22b72..d2a274d 100644
--- a/tools/releasetools/test_add_img_to_target_files.py
+++ b/tools/releasetools/test_add_img_to_target_files.py
@@ -40,11 +40,7 @@
 
     # Calls an external binary to convert the proto message.
     cmd = ["care_map_generator", "--parse_proto", file_name, text_file]
-    proc = common.Run(cmd)
-    output, _ = proc.communicate()
-    self.assertEqual(
-        0, proc.returncode,
-        "Failed to run care_map_generator:\n{}".format(output))
+    common.RunAndCheckOutput(cmd)
 
     with open(text_file, 'r') as verify_fp:
       plain_text = verify_fp.read()
diff --git a/tools/releasetools/test_blockimgdiff.py b/tools/releasetools/test_blockimgdiff.py
index 857026e..806ff4b 100644
--- a/tools/releasetools/test_blockimgdiff.py
+++ b/tools/releasetools/test_blockimgdiff.py
@@ -127,11 +127,11 @@
 
     # Sufficient cache to stash 5 blocks (size * 0.8 >= 5).
     common.OPTIONS.cache_size = 7 * 4096
-    self.assertEqual(0, block_image_diff.ReviseStashSize())
+    self.assertEqual((0, 5), block_image_diff.ReviseStashSize())
 
     # Insufficient cache to stash 5 blocks (size * 0.8 < 5).
     common.OPTIONS.cache_size = 6 * 4096
-    self.assertEqual(10, block_image_diff.ReviseStashSize())
+    self.assertEqual((10, 0), block_image_diff.ReviseStashSize())
 
   def test_ReviseStashSize_bug_33687949(self):
     """ReviseStashSize() should "free" the used stash _after_ the command.
@@ -169,7 +169,7 @@
 
     # Insufficient cache to stash 15 blocks (size * 0.8 < 15).
     common.OPTIONS.cache_size = 15 * 4096
-    self.assertEqual(15, block_image_diff.ReviseStashSize())
+    self.assertEqual((15, 5), block_image_diff.ReviseStashSize())
 
   def test_FileTypeSupportedByImgdiff(self):
     self.assertTrue(
diff --git a/tools/releasetools/test_validate_target_files.py b/tools/releasetools/test_validate_target_files.py
index d778d11..a6a8876 100644
--- a/tools/releasetools/test_validate_target_files.py
+++ b/tools/releasetools/test_validate_target_files.py
@@ -24,6 +24,7 @@
 import test_utils
 import verity_utils
 from validate_target_files import ValidateVerifiedBootImages
+from verity_utils import CreateVerityImageBuilder
 
 
 class ValidateTargetFilesTest(test_utils.ReleaseToolsTestCase):
@@ -107,10 +108,16 @@
         options)
 
   def _generate_system_image(self, output_file):
-    verity_fec = True
-    partition_size = 1024 * 1024
-    image_size, verity_size = verity_utils.AdjustPartitionSizeForVerity(
-        partition_size, verity_fec)
+    prop_dict = {
+        'partition_size': str(1024 * 1024),
+        'verity': 'true',
+        'verity_block_device': '/dev/block/system',
+        'verity_key' : os.path.join(self.testdata_dir, 'testkey'),
+        'verity_fec': "true",
+        'verity_signer_cmd': 'verity_signer',
+    }
+    verity_image_builder = CreateVerityImageBuilder(prop_dict)
+    image_size = verity_image_builder.CalculateMaxImageSize()
 
     # Use an empty root directory.
     system_root = common.MakeTempDir()
@@ -124,15 +131,7 @@
             stdoutdata))
 
     # Append the verity metadata.
-    prop_dict = {
-        'partition_size' : str(partition_size),
-        'image_size' : str(image_size),
-        'verity_block_device' : '/dev/block/system',
-        'verity_key' : os.path.join(self.testdata_dir, 'testkey'),
-        'verity_signer_cmd' : 'verity_signer',
-        'verity_size' : str(verity_size),
-    }
-    verity_utils.MakeVerityEnabledImage(output_file, verity_fec, prop_dict)
+    verity_image_builder.Build(output_file)
 
   def test_ValidateVerifiedBootImages_systemImage(self):
     input_tmp = common.MakeTempDir()
diff --git a/tools/releasetools/test_verity_utils.py b/tools/releasetools/test_verity_utils.py
index 0988d8e..e0607c8 100644
--- a/tools/releasetools/test_verity_utils.py
+++ b/tools/releasetools/test_verity_utils.py
@@ -16,6 +16,7 @@
 
 """Unittests for verity_utils.py."""
 
+import copy
 import math
 import os.path
 import random
@@ -25,10 +26,11 @@
 from rangelib import RangeSet
 from test_utils import get_testdata_dir, ReleaseToolsTestCase
 from verity_utils import (
-    AdjustPartitionSizeForVerity, AVBCalcMinPartitionSize, BLOCK_SIZE,
-    CreateHashtreeInfoGenerator, HashtreeInfo, MakeVerityEnabledImage,
+    CreateHashtreeInfoGenerator, CreateVerityImageBuilder, HashtreeInfo,
     VerifiedBootVersion1HashtreeInfoGenerator)
 
+BLOCK_SIZE = common.BLOCK_SIZE
+
 
 class VerifiedBootVersion1HashtreeInfoGeneratorTest(ReleaseToolsTestCase):
 
@@ -64,8 +66,17 @@
 
   def _generate_image(self):
     partition_size = 1024 * 1024
-    adjusted_size, verity_size = AdjustPartitionSizeForVerity(
-        partition_size, True)
+    prop_dict = {
+        'partition_size': str(partition_size),
+        'verity': 'true',
+        'verity_block_device': '/dev/block/system',
+        'verity_key': os.path.join(self.testdata_dir, 'testkey'),
+        'verity_fec': 'true',
+        'verity_signer_cmd': 'verity_signer',
+    }
+    verity_image_builder = CreateVerityImageBuilder(prop_dict)
+    self.assertIsNotNone(verity_image_builder)
+    adjusted_size = verity_image_builder.CalculateMaxImageSize()
 
     raw_image = ""
     for i in range(adjusted_size):
@@ -74,15 +85,7 @@
     output_file = self._create_simg(raw_image)
 
     # Append the verity metadata.
-    prop_dict = {
-        'partition_size': str(partition_size),
-        'image_size': str(adjusted_size),
-        'verity_block_device': '/dev/block/system',
-        'verity_key': os.path.join(self.testdata_dir, 'testkey'),
-        'verity_signer_cmd': 'verity_signer',
-        'verity_size': str(verity_size),
-    }
-    MakeVerityEnabledImage(output_file, True, prop_dict)
+    verity_image_builder.Build(output_file)
 
     return output_file
 
@@ -163,23 +166,174 @@
     self.assertEqual(self.expected_root_hash, info.root_hash)
 
 
-class VerityUtilsTest(ReleaseToolsTestCase):
+class VerifiedBootVersion1VerityImageBuilderTest(ReleaseToolsTestCase):
 
-  def setUp(self):
-    # To test AVBCalcMinPartitionSize(), by using 200MB to 2GB image size.
+  DEFAULT_PARTITION_SIZE = 4096 * 1024
+  DEFAULT_PROP_DICT = {
+      'partition_size': str(DEFAULT_PARTITION_SIZE),
+      'verity': 'true',
+      'verity_block_device': '/dev/block/system',
+      'verity_key': os.path.join(get_testdata_dir(), 'testkey'),
+      'verity_fec': 'true',
+      'verity_signer_cmd': 'verity_signer',
+  }
+
+  def test_init(self):
+    prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
+    verity_image_builder = CreateVerityImageBuilder(prop_dict)
+    self.assertIsNotNone(verity_image_builder)
+    self.assertEqual(1, verity_image_builder.version)
+
+  def test_init_MissingProps(self):
+    prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
+    del prop_dict['verity']
+    self.assertIsNone(CreateVerityImageBuilder(prop_dict))
+
+    prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
+    del prop_dict['verity_block_device']
+    self.assertIsNone(CreateVerityImageBuilder(prop_dict))
+
+  def test_CalculateMaxImageSize(self):
+    verity_image_builder = CreateVerityImageBuilder(self.DEFAULT_PROP_DICT)
+    size = verity_image_builder.CalculateMaxImageSize()
+    self.assertLess(size, self.DEFAULT_PARTITION_SIZE)
+
+    # Same result by explicitly passing the partition size.
+    self.assertEqual(
+        verity_image_builder.CalculateMaxImageSize(),
+        verity_image_builder.CalculateMaxImageSize(
+            self.DEFAULT_PARTITION_SIZE))
+
+  @staticmethod
+  def _BuildAndVerify(prop, verify_key):
+    verity_image_builder = CreateVerityImageBuilder(prop)
+    image_size = verity_image_builder.CalculateMaxImageSize()
+
+    # Build the sparse image with verity metadata.
+    input_dir = common.MakeTempDir()
+    image = common.MakeTempFile(suffix='.img')
+    cmd = ['mkuserimg_mke2fs', input_dir, image, 'ext4', '/system',
+           str(image_size), '-j', '0', '-s']
+    common.RunAndCheckOutput(cmd)
+    verity_image_builder.Build(image)
+
+    # Verify the verity metadata.
+    cmd = ['verity_verifier', image, '-mincrypt', verify_key]
+    common.RunAndCheckOutput(cmd)
+
+  def test_Build(self):
+    self._BuildAndVerify(
+        self.DEFAULT_PROP_DICT,
+        os.path.join(get_testdata_dir(), 'testkey_mincrypt'))
+
+  def test_Build_SanityCheck(self):
+    # A sanity check for the test itself: the image shouldn't be verifiable
+    # with wrong key.
+    self.assertRaises(
+        common.ExternalError,
+        self._BuildAndVerify,
+        self.DEFAULT_PROP_DICT,
+        os.path.join(get_testdata_dir(), 'verity_mincrypt'))
+
+  def test_Build_FecDisabled(self):
+    prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
+    del prop_dict['verity_fec']
+    self._BuildAndVerify(
+        prop_dict,
+        os.path.join(get_testdata_dir(), 'testkey_mincrypt'))
+
+  def test_Build_SquashFs(self):
+    verity_image_builder = CreateVerityImageBuilder(self.DEFAULT_PROP_DICT)
+    verity_image_builder.CalculateMaxImageSize()
+
+    # Build the sparse image with verity metadata.
+    input_dir = common.MakeTempDir()
+    image = common.MakeTempFile(suffix='.img')
+    cmd = ['mksquashfsimage.sh', input_dir, image, '-s']
+    common.RunAndCheckOutput(cmd)
+    verity_image_builder.PadSparseImage(image)
+    verity_image_builder.Build(image)
+
+    # Verify the verity metadata.
+    cmd = ["verity_verifier", image, '-mincrypt',
+           os.path.join(get_testdata_dir(), 'testkey_mincrypt')]
+    common.RunAndCheckOutput(cmd)
+
+
+class VerifiedBootVersion2VerityImageBuilderTest(ReleaseToolsTestCase):
+
+  DEFAULT_PROP_DICT = {
+      'partition_size': str(4096 * 1024),
+      'partition_name': 'system',
+      'avb_avbtool': 'avbtool',
+      'avb_hashtree_enable': 'true',
+      'avb_add_hashtree_footer_args': '',
+  }
+
+  def test_init(self):
+    prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
+    verity_image_builder = CreateVerityImageBuilder(prop_dict)
+    self.assertIsNotNone(verity_image_builder)
+    self.assertEqual(2, verity_image_builder.version)
+
+  def test_init_MissingProps(self):
+    prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
+    del prop_dict['avb_hashtree_enable']
+    verity_image_builder = CreateVerityImageBuilder(prop_dict)
+    self.assertIsNone(verity_image_builder)
+
+  def test_Build(self):
+    prop_dict = copy.deepcopy(self.DEFAULT_PROP_DICT)
+    verity_image_builder = CreateVerityImageBuilder(prop_dict)
+    self.assertIsNotNone(verity_image_builder)
+    self.assertEqual(2, verity_image_builder.version)
+
+    input_dir = common.MakeTempDir()
+    image_dir = common.MakeTempDir()
+    system_image = os.path.join(image_dir, 'system.img')
+    system_image_size = verity_image_builder.CalculateMaxImageSize()
+    cmd = ['mkuserimg_mke2fs', input_dir, system_image, 'ext4', '/system',
+           str(system_image_size), '-j', '0', '-s']
+    common.RunAndCheckOutput(cmd)
+    verity_image_builder.Build(system_image)
+
+    # Additionally make vbmeta image so that we can verify with avbtool.
+    vbmeta_image = os.path.join(image_dir, 'vbmeta.img')
+    cmd = ['avbtool', 'make_vbmeta_image', '--include_descriptors_from_image',
+           system_image, '--output', vbmeta_image]
+    common.RunAndCheckOutput(cmd)
+
+    # Verify the verity metadata.
+    cmd = ['avbtool', 'verify_image', '--image', vbmeta_image]
+    common.RunAndCheckOutput(cmd)
+
+  def _test_CalculateMinPartitionSize_SetUp(self):
+    # To test CalculateMinPartitionSize(), by using 200MB to 2GB image size.
     #   -  51200 = 200MB * 1024 * 1024 / 4096
     #   - 524288 = 2GB * 1024 * 1024 * 1024 / 4096
-    self._image_sizes = [BLOCK_SIZE * random.randint(51200, 524288) + offset
-                         for offset in range(BLOCK_SIZE)]
+    image_sizes = [BLOCK_SIZE * random.randint(51200, 524288) + offset
+                   for offset in range(BLOCK_SIZE)]
 
-  def test_AVBCalcMinPartitionSize_LinearFooterSize(self):
+    prop_dict = {
+        'partition_size': None,
+        'partition_name': 'system',
+        'avb_avbtool': 'avbtool',
+        'avb_hashtree_enable': 'true',
+        'avb_add_hashtree_footer_args': None,
+    }
+    builder = CreateVerityImageBuilder(prop_dict)
+    self.assertEqual(2, builder.version)
+    return image_sizes, builder
+
+  def test_CalculateMinPartitionSize_LinearFooterSize(self):
     """Tests with footer size which is linear to partition size."""
-    for image_size in self._image_sizes:
+    image_sizes, builder = self._test_CalculateMinPartitionSize_SetUp()
+    for image_size in image_sizes:
       for ratio in 0.95, 0.56, 0.22:
         expected_size = common.RoundUpTo4K(int(math.ceil(image_size / ratio)))
         self.assertEqual(
             expected_size,
-            AVBCalcMinPartitionSize(
+            builder.CalculateMinPartitionSize(
                 image_size, lambda x, ratio=ratio: int(x * ratio)))
 
   def test_AVBCalcMinPartitionSize_SlowerGrowthFooterSize(self):
@@ -190,8 +344,10 @@
       # Minus footer size to return max image size.
       return partition_size - int(math.pow(partition_size, 0.95))
 
-    for image_size in self._image_sizes:
-      min_partition_size = AVBCalcMinPartitionSize(image_size, _SizeCalculator)
+    image_sizes, builder = self._test_CalculateMinPartitionSize_SetUp()
+    for image_size in image_sizes:
+      min_partition_size = builder.CalculateMinPartitionSize(
+          image_size, _SizeCalculator)
       # Checks min_partition_size can accommodate image_size.
       self.assertGreaterEqual(
           _SizeCalculator(min_partition_size),
@@ -201,7 +357,7 @@
           _SizeCalculator(min_partition_size - BLOCK_SIZE),
           image_size)
 
-  def test_AVBCalcMinPartitionSize_FasterGrowthFooterSize(self):
+  def test_CalculateMinPartitionSize_FasterGrowthFooterSize(self):
     """Tests with footer size which grows faster than partition size."""
 
     def _SizeCalculator(partition_size):
@@ -210,8 +366,10 @@
       # footer size grows faster than partition size.
       return int(math.pow(partition_size, 0.95))
 
-    for image_size in self._image_sizes:
-      min_partition_size = AVBCalcMinPartitionSize(image_size, _SizeCalculator)
+    image_sizes, builder = self._test_CalculateMinPartitionSize_SetUp()
+    for image_size in image_sizes:
+      min_partition_size = builder.CalculateMinPartitionSize(
+          image_size, _SizeCalculator)
       # Checks min_partition_size can accommodate image_size.
       self.assertGreaterEqual(
           _SizeCalculator(min_partition_size),
diff --git a/tools/releasetools/testdata/verity_mincrypt b/tools/releasetools/testdata/verity_mincrypt
new file mode 100644
index 0000000..31982d9
--- /dev/null
+++ b/tools/releasetools/testdata/verity_mincrypt
Binary files differ
diff --git a/tools/releasetools/validate_target_files.py b/tools/releasetools/validate_target_files.py
index 1cc4a60..eeb802b 100755
--- a/tools/releasetools/validate_target_files.py
+++ b/tools/releasetools/validate_target_files.py
@@ -89,13 +89,20 @@
         logging.warning('Skipping %s that has incomplete block list', entry)
         continue
 
+      # Use the original RangeSet if applicable, which includes the shared
+      # blocks. And this needs to happen before checking the monotonicity flag.
+      if ranges.extra.get('uses_shared_blocks'):
+        file_ranges = ranges.extra['uses_shared_blocks']
+      else:
+        file_ranges = ranges
+
       # TODO(b/79951650): Handle files with non-monotonic ranges.
-      if not ranges.monotonic:
+      if not file_ranges.monotonic:
         logging.warning(
-            'Skipping %s that has non-monotonic ranges: %s', entry, ranges)
+            'Skipping %s that has non-monotonic ranges: %s', entry, file_ranges)
         continue
 
-      blocks_sha1 = image.RangeSha1(ranges)
+      blocks_sha1 = image.RangeSha1(file_ranges)
 
       # The filename under unpacked directory, such as SYSTEM/bin/sh.
       unpacked_name = os.path.join(
@@ -104,7 +111,7 @@
       file_sha1 = unpacked_file.sha1
       assert blocks_sha1 == file_sha1, \
           'file: %s, range: %s, blocks_sha1: %s, file_sha1: %s' % (
-              entry, ranges, blocks_sha1, file_sha1)
+              entry, file_ranges, blocks_sha1, file_sha1)
 
   logging.info('Validating file consistency.')
 
@@ -311,31 +318,9 @@
   if info_dict.get("avb_enable") == "true":
     logging.info('Verifying Verified Boot 2.0 (AVB) images...')
 
-    key = options['verity_key']
-    if key is None:
-      key = info_dict['avb_vbmeta_key_path']
-
-    # avbtool verifies all the images that have descriptors listed in vbmeta.
-    image = os.path.join(input_tmp, 'IMAGES', 'vbmeta.img')
-    cmd = ['avbtool', 'verify_image', '--image', image, '--key', key]
-
-    # Append the args for chained partitions if any.
-    for partition in common.AVB_PARTITIONS:
-      key_name = 'avb_' + partition + '_key_path'
-      if info_dict.get(key_name) is not None:
-        chained_partition_arg = common.GetAvbChainedPartitionArg(
-            partition, info_dict, options[key_name])
-        cmd.extend(["--expected_chain_partition", chained_partition_arg])
-
-    proc = common.Run(cmd)
-    stdoutdata, _ = proc.communicate()
-    assert proc.returncode == 0, \
-        'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
-            image, key, stdoutdata)
-
-    logging.info(
-        'Verified %s with avbtool (key: %s):\n%s', image, key,
-        stdoutdata.rstrip())
+    # TODO(b/120517892): Temporarily disable the verification for AVB-signed
+    # images. Needing supporting changes in caller to pass in the desired keys.
+    logging.info('Temporarily disabled due to b/120517892')
 
 
 def main():
diff --git a/tools/releasetools/verity_utils.py b/tools/releasetools/verity_utils.py
index 00af296..3a58755 100644
--- a/tools/releasetools/verity_utils.py
+++ b/tools/releasetools/verity_utils.py
@@ -39,30 +39,30 @@
     Exception.__init__(self, message)
 
 
-def GetVerityFECSize(partition_size):
-  cmd = ["fec", "-s", str(partition_size)]
+def GetVerityFECSize(image_size):
+  cmd = ["fec", "-s", str(image_size)]
   output = common.RunAndCheckOutput(cmd, verbose=False)
   return int(output)
 
 
-def GetVerityTreeSize(partition_size):
-  cmd = ["build_verity_tree", "-s", str(partition_size)]
+def GetVerityTreeSize(image_size):
+  cmd = ["build_verity_tree", "-s", str(image_size)]
   output = common.RunAndCheckOutput(cmd, verbose=False)
   return int(output)
 
 
-def GetVerityMetadataSize(partition_size):
-  cmd = ["build_verity_metadata.py", "size", str(partition_size)]
+def GetVerityMetadataSize(image_size):
+  cmd = ["build_verity_metadata.py", "size", str(image_size)]
   output = common.RunAndCheckOutput(cmd, verbose=False)
   return int(output)
 
 
-def GetVeritySize(partition_size, fec_supported):
-  verity_tree_size = GetVerityTreeSize(partition_size)
-  verity_metadata_size = GetVerityMetadataSize(partition_size)
+def GetVeritySize(image_size, fec_supported):
+  verity_tree_size = GetVerityTreeSize(image_size)
+  verity_metadata_size = GetVerityMetadataSize(image_size)
   verity_size = verity_tree_size + verity_metadata_size
   if fec_supported:
-    fec_size = GetVerityFECSize(partition_size + verity_size)
+    fec_size = GetVerityFECSize(image_size + verity_size)
     return verity_size + fec_size
   return verity_size
 
@@ -79,54 +79,6 @@
   simg.AppendFillChunk(0, blocks)
 
 
-def AdjustPartitionSizeForVerity(partition_size, fec_supported):
-  """Modifies the provided partition size to account for the verity metadata.
-
-  This information is used to size the created image appropriately.
-
-  Args:
-    partition_size: the size of the partition to be verified.
-
-  Returns:
-    A tuple of the size of the partition adjusted for verity metadata, and
-    the size of verity metadata.
-  """
-  key = "%d %d" % (partition_size, fec_supported)
-  if key in AdjustPartitionSizeForVerity.results:
-    return AdjustPartitionSizeForVerity.results[key]
-
-  hi = partition_size
-  if hi % BLOCK_SIZE != 0:
-    hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
-
-  # verity tree and fec sizes depend on the partition size, which
-  # means this estimate is always going to be unnecessarily small
-  verity_size = GetVeritySize(hi, fec_supported)
-  lo = partition_size - verity_size
-  result = lo
-
-  # do a binary search for the optimal size
-  while lo < hi:
-    i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
-    v = GetVeritySize(i, fec_supported)
-    if i + v <= partition_size:
-      if result < i:
-        result = i
-        verity_size = v
-      lo = i + BLOCK_SIZE
-    else:
-      hi = i
-
-  logger.info(
-      "Adjusted partition size for verity, partition_size: %s, verity_size: %s",
-      result, verity_size)
-  AdjustPartitionSizeForVerity.results[key] = (result, verity_size)
-  return (result, verity_size)
-
-
-AdjustPartitionSizeForVerity.results = {}
-
-
 def BuildVerityFEC(sparse_image_path, verity_path, verity_fec_path,
                    padding_size):
   cmd = ["fec", "-e", "-p", str(padding_size), sparse_image_path,
@@ -168,6 +120,7 @@
   try:
     common.RunAndCheckOutput(cmd)
   except:
+    logger.exception(error_message)
     raise BuildVerityImageError(error_message)
 
 
@@ -182,190 +135,369 @@
       for line in input_file:
         out_file.write(line)
   except IOError:
+    logger.exception(error_message)
     raise BuildVerityImageError(error_message)
 
 
-def BuildVerifiedImage(data_image_path, verity_image_path,
-                       verity_metadata_path, verity_fec_path,
-                       padding_size, fec_supported):
-  Append(
-      verity_image_path, verity_metadata_path,
-      "Could not append verity metadata!")
-
-  if fec_supported:
-    # Build FEC for the entire partition, including metadata.
-    BuildVerityFEC(
-        data_image_path, verity_image_path, verity_fec_path, padding_size)
-    Append(verity_image_path, verity_fec_path, "Could not append FEC!")
-
-  Append2Simg(
-      data_image_path, verity_image_path, "Could not append verity data!")
-
-
-def MakeVerityEnabledImage(out_file, fec_supported, prop_dict):
-  """Creates an image that is verifiable using dm-verity.
+def CreateVerityImageBuilder(prop_dict):
+  """Returns a verity image builder based on the given build properties.
 
   Args:
-    out_file: the location to write the verifiable image at
-    prop_dict: a dictionary of properties required for image creation and
-               verification
-
-  Raises:
-    AssertionError: On invalid partition sizes.
-  """
-  # get properties
-  image_size = int(prop_dict["image_size"])
-  block_dev = prop_dict["verity_block_device"]
-  signer_key = prop_dict["verity_key"] + ".pk8"
-  if OPTIONS.verity_signer_path is not None:
-    signer_path = OPTIONS.verity_signer_path
-  else:
-    signer_path = prop_dict["verity_signer_cmd"]
-  signer_args = OPTIONS.verity_signer_args
-
-  tempdir_name = common.MakeTempDir(suffix="_verity_images")
-
-  # Get partial image paths.
-  verity_image_path = os.path.join(tempdir_name, "verity.img")
-  verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
-  verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
-
-  # Build the verity tree and get the root hash and salt.
-  root_hash, salt = BuildVerityTree(out_file, verity_image_path)
-
-  # Build the metadata blocks.
-  verity_disable = "verity_disable" in prop_dict
-  BuildVerityMetadata(
-      image_size, verity_metadata_path, root_hash, salt, block_dev, signer_path,
-      signer_key, signer_args, verity_disable)
-
-  # Build the full verified image.
-  partition_size = int(prop_dict["partition_size"])
-  verity_size = int(prop_dict["verity_size"])
-
-  padding_size = partition_size - image_size - verity_size
-  assert padding_size >= 0
-
-  BuildVerifiedImage(
-      out_file, verity_image_path, verity_metadata_path, verity_fec_path,
-      padding_size, fec_supported)
-
-
-def AVBCalcMaxImageSize(avbtool, footer_type, partition_size, additional_args):
-  """Calculates max image size for a given partition size.
-
-  Args:
-    avbtool: String with path to avbtool.
-    footer_type: 'hash' or 'hashtree' for generating footer.
-    partition_size: The size of the partition in question.
-    additional_args: Additional arguments to pass to "avbtool add_hash_footer"
-        or "avbtool add_hashtree_footer".
+    prop_dict: A dict that contains the build properties. In particular, it will
+        look for verity-related property values.
 
   Returns:
-    The maximum image size.
-
-  Raises:
-    BuildVerityImageError: On invalid image size.
+    A VerityImageBuilder instance for Verified Boot 1.0 or Verified Boot 2.0; or
+        None if the given build doesn't support Verified Boot.
   """
-  cmd = [avbtool, "add_%s_footer" % footer_type,
-         "--partition_size", str(partition_size), "--calc_max_image_size"]
-  cmd.extend(shlex.split(additional_args))
+  partition_size = prop_dict.get("partition_size")
+  # partition_size could be None at this point, if using dynamic partitions.
+  if partition_size:
+    partition_size = int(partition_size)
 
-  output = common.RunAndCheckOutput(cmd)
-  image_size = int(output)
-  if image_size <= 0:
-    raise BuildVerityImageError(
-        "Invalid max image size: {}".format(output))
-  return image_size
-
-
-def AVBCalcMinPartitionSize(image_size, size_calculator):
-  """Calculates min partition size for a given image size.
-
-  Args:
-    image_size: The size of the image in question.
-    size_calculator: The function to calculate max image size
-        for a given partition size.
-
-  Returns:
-    The minimum partition size required to accommodate the image size.
-  """
-  # Use image size as partition size to approximate final partition size.
-  image_ratio = size_calculator(image_size) / float(image_size)
-
-  # Prepare a binary search for the optimal partition size.
-  lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE
-
-  # Ensure lo is small enough: max_image_size should <= image_size.
-  delta = BLOCK_SIZE
-  max_image_size = size_calculator(lo)
-  while max_image_size > image_size:
-    image_ratio = max_image_size / float(lo)
-    lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta
-    delta *= 2
-    max_image_size = size_calculator(lo)
-
-  hi = lo + BLOCK_SIZE
-
-  # Ensure hi is large enough: max_image_size should >= image_size.
-  delta = BLOCK_SIZE
-  max_image_size = size_calculator(hi)
-  while max_image_size < image_size:
-    image_ratio = max_image_size / float(hi)
-    hi = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta
-    delta *= 2
-    max_image_size = size_calculator(hi)
-
-  partition_size = hi
-
-  # Start to binary search.
-  while lo < hi:
-    mid = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
-    max_image_size = size_calculator(mid)
-    if max_image_size >= image_size:  # if mid can accommodate image_size
-      if mid < partition_size:  # if a smaller partition size is found
-        partition_size = mid
-      hi = mid
+  # Verified Boot 1.0
+  verity_supported = prop_dict.get("verity") == "true"
+  is_verity_partition = "verity_block_device" in prop_dict
+  if verity_supported and is_verity_partition:
+    if OPTIONS.verity_signer_path is not None:
+      signer_path = OPTIONS.verity_signer_path
     else:
-      lo = mid + BLOCK_SIZE
+      signer_path = prop_dict["verity_signer_cmd"]
+    return Version1VerityImageBuilder(
+        partition_size,
+        prop_dict["verity_block_device"],
+        prop_dict.get("verity_fec") == "true",
+        signer_path,
+        prop_dict["verity_key"] + ".pk8",
+        OPTIONS.verity_signer_args,
+        "verity_disable" in prop_dict)
 
-  logger.info(
-      "AVBCalcMinPartitionSize(%d): partition_size: %d.",
-      image_size, partition_size)
+  # Verified Boot 2.0
+  if (prop_dict.get("avb_hash_enable") == "true" or
+      prop_dict.get("avb_hashtree_enable") == "true"):
+    # key_path and algorithm are only available when chain partition is used.
+    key_path = prop_dict.get("avb_key_path")
+    algorithm = prop_dict.get("avb_algorithm")
+    if prop_dict.get("avb_hash_enable") == "true":
+      return VerifiedBootVersion2VerityImageBuilder(
+          prop_dict["partition_name"],
+          partition_size,
+          VerifiedBootVersion2VerityImageBuilder.AVB_HASH_FOOTER,
+          prop_dict["avb_avbtool"],
+          key_path,
+          algorithm,
+          prop_dict.get("avb_salt"),
+          prop_dict["avb_add_hash_footer_args"])
+    else:
+      return VerifiedBootVersion2VerityImageBuilder(
+          prop_dict["partition_name"],
+          partition_size,
+          VerifiedBootVersion2VerityImageBuilder.AVB_HASHTREE_FOOTER,
+          prop_dict["avb_avbtool"],
+          key_path,
+          algorithm,
+          prop_dict.get("avb_salt"),
+          prop_dict["avb_add_hashtree_footer_args"])
 
-  return partition_size
+  return None
 
 
-def AVBAddFooter(image_path, avbtool, footer_type, partition_size,
-                 partition_name, key_path, algorithm, salt,
-                 additional_args):
-  """Adds dm-verity hashtree and AVB metadata to an image.
+class VerityImageBuilder(object):
+  """A builder that generates an image with verity metadata for Verified Boot.
 
-  Args:
-    image_path: Path to image to modify.
-    avbtool: String with path to avbtool.
-    footer_type: 'hash' or 'hashtree' for generating footer.
-    partition_size: The size of the partition in question.
-    partition_name: The name of the partition - will be embedded in metadata.
-    key_path: Path to key to use or None.
-    algorithm: Name of algorithm to use or None.
-    salt: The salt to use (a hexadecimal string) or None.
-    additional_args: Additional arguments to pass to "avbtool add_hash_footer"
-        or "avbtool add_hashtree_footer".
+  A VerityImageBuilder instance handles the works for building an image with
+  verity metadata for supporting Android Verified Boot. This class defines the
+  common interface between Verified Boot 1.0 and Verified Boot 2.0. A matching
+  builder will be returned based on the given build properties.
+
+  More info on the verity image generation can be found at the following link.
+  https://source.android.com/security/verifiedboot/dm-verity#implementation
   """
-  cmd = [avbtool, "add_%s_footer" % footer_type,
-         "--partition_size", partition_size,
-         "--partition_name", partition_name,
-         "--image", image_path]
 
-  if key_path and algorithm:
-    cmd.extend(["--key", key_path, "--algorithm", algorithm])
-  if salt:
-    cmd.extend(["--salt", salt])
+  def CalculateMaxImageSize(self, partition_size):
+    """Calculates the filesystem image size for the given partition size."""
+    raise NotImplementedError
 
-  cmd.extend(shlex.split(additional_args))
+  def CalculateDynamicPartitionSize(self, image_size):
+    """Calculates and sets the partition size for a dynamic partition."""
+    raise NotImplementedError
 
-  common.RunAndCheckOutput(cmd)
+  def PadSparseImage(self, out_file):
+    """Adds padding to the generated sparse image."""
+    raise NotImplementedError
+
+  def Build(self, out_file):
+    """Builds the verity image and writes it to the given file."""
+    raise NotImplementedError
+
+
+class Version1VerityImageBuilder(VerityImageBuilder):
+  """A VerityImageBuilder for Verified Boot 1.0."""
+
+  def __init__(self, partition_size, block_dev, fec_supported, signer_path,
+               signer_key, signer_args, verity_disable):
+    self.version = 1
+    self.partition_size = partition_size
+    self.block_device = block_dev
+    self.fec_supported = fec_supported
+    self.signer_path = signer_path
+    self.signer_key = signer_key
+    self.signer_args = signer_args
+    self.verity_disable = verity_disable
+    self.image_size = None
+    self.verity_size = None
+
+  def CalculateDynamicPartitionSize(self, image_size):
+    # This needs to be implemented. Note that returning the given image size as
+    # the partition size doesn't make sense, as it will fail later.
+    raise NotImplementedError
+
+  def CalculateMaxImageSize(self, partition_size=None):
+    """Calculates the max image size by accounting for the verity metadata.
+
+    Args:
+      partition_size: The partition size, which defaults to self.partition_size
+          if unspecified.
+
+    Returns:
+      The size of the image adjusted for verity metadata.
+    """
+    if partition_size is None:
+      partition_size = self.partition_size
+    assert partition_size > 0, \
+        "Invalid partition size: {}".format(partition_size)
+
+    hi = partition_size
+    if hi % BLOCK_SIZE != 0:
+      hi = (hi // BLOCK_SIZE) * BLOCK_SIZE
+
+    # verity tree and fec sizes depend on the partition size, which
+    # means this estimate is always going to be unnecessarily small
+    verity_size = GetVeritySize(hi, self.fec_supported)
+    lo = partition_size - verity_size
+    result = lo
+
+    # do a binary search for the optimal size
+    while lo < hi:
+      i = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
+      v = GetVeritySize(i, self.fec_supported)
+      if i + v <= partition_size:
+        if result < i:
+          result = i
+          verity_size = v
+        lo = i + BLOCK_SIZE
+      else:
+        hi = i
+
+    self.image_size = result
+    self.verity_size = verity_size
+
+    logger.info(
+        "Calculated image size for verity: partition_size %d, image_size %d, "
+        "verity_size %d", partition_size, result, verity_size)
+    return result
+
+  def Build(self, out_file):
+    """Creates an image that is verifiable using dm-verity.
+
+    Args:
+      out_file: the output image.
+
+    Returns:
+      AssertionError: On invalid partition sizes.
+      BuildVerityImageError: On other errors.
+    """
+    image_size = int(self.image_size)
+    tempdir_name = common.MakeTempDir(suffix="_verity_images")
+
+    # Get partial image paths.
+    verity_image_path = os.path.join(tempdir_name, "verity.img")
+    verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
+
+    # Build the verity tree and get the root hash and salt.
+    root_hash, salt = BuildVerityTree(out_file, verity_image_path)
+
+    # Build the metadata blocks.
+    BuildVerityMetadata(
+        image_size, verity_metadata_path, root_hash, salt, self.block_device,
+        self.signer_path, self.signer_key, self.signer_args,
+        self.verity_disable)
+
+    padding_size = self.partition_size - self.image_size - self.verity_size
+    assert padding_size >= 0
+
+    # Build the full verified image.
+    Append(
+        verity_image_path, verity_metadata_path,
+        "Failed to append verity metadata")
+
+    if self.fec_supported:
+      # Build FEC for the entire partition, including metadata.
+      verity_fec_path = os.path.join(tempdir_name, "verity_fec.img")
+      BuildVerityFEC(
+          out_file, verity_image_path, verity_fec_path, padding_size)
+      Append(verity_image_path, verity_fec_path, "Failed to append FEC")
+
+    Append2Simg(
+        out_file, verity_image_path, "Failed to append verity data")
+
+  def PadSparseImage(self, out_file):
+    sparse_image_size = GetSimgSize(out_file)
+    if sparse_image_size > self.image_size:
+      raise BuildVerityImageError(
+          "Error: image size of {} is larger than partition size of "
+          "{}".format(sparse_image_size, self.image_size))
+    ZeroPadSimg(out_file, self.image_size - sparse_image_size)
+
+
+class VerifiedBootVersion2VerityImageBuilder(VerityImageBuilder):
+  """A VerityImageBuilder for Verified Boot 2.0."""
+
+  AVB_HASH_FOOTER = 1
+  AVB_HASHTREE_FOOTER = 2
+
+  def __init__(self, partition_name, partition_size, footer_type, avbtool,
+               key_path, algorithm, salt, signing_args):
+    self.version = 2
+    self.partition_name = partition_name
+    self.partition_size = partition_size
+    self.footer_type = footer_type
+    self.avbtool = avbtool
+    self.algorithm = algorithm
+    self.key_path = key_path
+    self.salt = salt
+    self.signing_args = signing_args
+    self.image_size = None
+
+  def CalculateMinPartitionSize(self, image_size, size_calculator=None):
+    """Calculates min partition size for a given image size.
+
+    This is used when determining the partition size for a dynamic partition,
+    which should be cover the given image size (for filesystem files) as well as
+    the verity metadata size.
+
+    Args:
+      image_size: The size of the image in question.
+      size_calculator: The function to calculate max image size
+          for a given partition size.
+
+    Returns:
+      The minimum partition size required to accommodate the image size.
+    """
+    if size_calculator is None:
+      size_calculator = self.CalculateMaxImageSize
+
+    # Use image size as partition size to approximate final partition size.
+    image_ratio = size_calculator(image_size) / float(image_size)
+
+    # Prepare a binary search for the optimal partition size.
+    lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - BLOCK_SIZE
+
+    # Ensure lo is small enough: max_image_size should <= image_size.
+    delta = BLOCK_SIZE
+    max_image_size = size_calculator(lo)
+    while max_image_size > image_size:
+      image_ratio = max_image_size / float(lo)
+      lo = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE - delta
+      delta *= 2
+      max_image_size = size_calculator(lo)
+
+    hi = lo + BLOCK_SIZE
+
+    # Ensure hi is large enough: max_image_size should >= image_size.
+    delta = BLOCK_SIZE
+    max_image_size = size_calculator(hi)
+    while max_image_size < image_size:
+      image_ratio = max_image_size / float(hi)
+      hi = int(image_size / image_ratio) // BLOCK_SIZE * BLOCK_SIZE + delta
+      delta *= 2
+      max_image_size = size_calculator(hi)
+
+    partition_size = hi
+
+    # Start to binary search.
+    while lo < hi:
+      mid = ((lo + hi) // (2 * BLOCK_SIZE)) * BLOCK_SIZE
+      max_image_size = size_calculator(mid)
+      if max_image_size >= image_size:  # if mid can accommodate image_size
+        if mid < partition_size:  # if a smaller partition size is found
+          partition_size = mid
+        hi = mid
+      else:
+        lo = mid + BLOCK_SIZE
+
+    logger.info(
+        "CalculateMinPartitionSize(%d): partition_size %d.", image_size,
+        partition_size)
+
+    return partition_size
+
+  def CalculateDynamicPartitionSize(self, image_size):
+    self.partition_size = self.CalculateMinPartitionSize(image_size)
+    return self.partition_size
+
+  def CalculateMaxImageSize(self, partition_size=None):
+    """Calculates max image size for a given partition size.
+
+    Args:
+      partition_size: The partition size, which defaults to self.partition_size
+          if unspecified.
+
+    Returns:
+      The maximum image size.
+
+    Raises:
+      BuildVerityImageError: On error or getting invalid image size.
+    """
+    if partition_size is None:
+      partition_size = self.partition_size
+    assert partition_size > 0, \
+        "Invalid partition size: {}".format(partition_size)
+
+    add_footer = ("add_hash_footer" if self.footer_type == self.AVB_HASH_FOOTER
+                  else "add_hashtree_footer")
+    cmd = [self.avbtool, add_footer, "--partition_size",
+           str(partition_size), "--calc_max_image_size"]
+    cmd.extend(shlex.split(self.signing_args))
+
+    proc = common.Run(cmd)
+    output, _ = proc.communicate()
+    if proc.returncode != 0:
+      raise BuildVerityImageError(
+          "Failed to calculate max image size:\n{}".format(output))
+    image_size = int(output)
+    if image_size <= 0:
+      raise BuildVerityImageError(
+          "Invalid max image size: {}".format(output))
+    self.image_size = image_size
+    return image_size
+
+  def PadSparseImage(self, out_file):
+    # No-op as the padding is taken care of by avbtool.
+    pass
+
+  def Build(self, out_file):
+    """Adds dm-verity hashtree and AVB metadata to an image.
+
+    Args:
+      out_file: Path to image to modify.
+    """
+    add_footer = ("add_hash_footer" if self.footer_type == self.AVB_HASH_FOOTER
+                  else "add_hashtree_footer")
+    cmd = [self.avbtool, add_footer,
+           "--partition_size", str(self.partition_size),
+           "--partition_name", self.partition_name,
+           "--image", out_file]
+    if self.key_path and self.algorithm:
+      cmd.extend(["--key", self.key_path, "--algorithm", self.algorithm])
+    if self.salt:
+      cmd.extend(["--salt", self.salt])
+    cmd.extend(shlex.split(self.signing_args))
+
+    proc = common.Run(cmd)
+    output, _ = proc.communicate()
+    if proc.returncode != 0:
+      raise BuildVerityImageError("Failed to add AVB footer: {}".format(output))
 
 
 class HashtreeInfoGenerationError(Exception):
@@ -415,7 +547,7 @@
 
     Arguments:
       partition_size: The whole size in bytes of a partition, including the
-        filesystem size, padding size, and verity size.
+          filesystem size, padding size, and verity size.
       block_size: Expected size in bytes of each block for the sparse image.
       fec_supported: True if the verity section contains fec data.
     """
@@ -429,6 +561,20 @@
     self.hashtree_size = None
     self.metadata_size = None
 
+    prop_dict = {
+        'partition_size': str(partition_size),
+        'verity': 'true',
+        'verity_fec': 'true' if fec_supported else None,
+        # 'verity_block_device' needs to be present to indicate a verity-enabled
+        # partition.
+        'verity_block_device': '',
+        # We don't need the following properties that are needed for signing the
+        # verity metadata.
+        'verity_key': '',
+        'verity_signer_cmd': None,
+    }
+    self.verity_image_builder = CreateVerityImageBuilder(prop_dict)
+
     self.hashtree_info = HashtreeInfo()
 
   def DecomposeSparseImage(self, image):
@@ -445,8 +591,7 @@
         "partition size {} doesn't match with the calculated image size." \
         " total_blocks: {}".format(self.partition_size, image.total_blocks)
 
-    adjusted_size, _ = AdjustPartitionSizeForVerity(
-        self.partition_size, self.fec_supported)
+    adjusted_size = self.verity_image_builder.CalculateMaxImageSize()
     assert adjusted_size % self.block_size == 0
 
     verity_tree_size = GetVerityTreeSize(adjusted_size)
@@ -502,7 +647,7 @@
   def ValidateHashtree(self):
     """Checks that we can reconstruct the verity hash tree."""
 
-    # Writes the file system section to a temp file; and calls the executable
+    # Writes the filesystem section to a temp file; and calls the executable
     # build_verity_tree to construct the hash tree.
     adjusted_partition = common.MakeTempFile(prefix="adjusted_partition")
     with open(adjusted_partition, "wb") as fd:
diff --git a/tools/signapk/Android.bp b/tools/signapk/Android.bp
index e95205d..ad9d957 100644
--- a/tools/signapk/Android.bp
+++ b/tools/signapk/Android.bp
@@ -28,4 +28,10 @@
     ],
 
     required: ["libconscrypt_openjdk_jni"],
+
+    // The post-build signing tools need signapk.jar (and its shared libraries,
+    // handled in their own Android.bp files)
+    dist: {
+        targets: ["droidcore"],
+    },
 }
diff --git a/tools/signapk/Android.mk b/tools/signapk/Android.mk
deleted file mode 100644
index ff54d6d..0000000
--- a/tools/signapk/Android.mk
+++ /dev/null
@@ -1,26 +0,0 @@
-#
-# Copyright (C) 2008 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.
-#
-LOCAL_PATH := $(call my-dir)
-
-ifeq ($(TARGET_BUILD_APPS),)
-# The post-build signing tools need signapk.jar and its shared libraries,
-# but we don't need this if we're just doing unbundled apps.
-my_dist_files := $(HOST_OUT_JAVA_LIBRARIES)/signapk.jar \
-    $(HOST_OUT_SHARED_LIBRARIES)/libconscrypt_openjdk_jni$(HOST_SHLIB_SUFFIX)
-
-$(call dist-for-goals,droidcore,$(my_dist_files))
-my_dist_files :=
-endif