Merge "Use more variables from Soong"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index a84e793..284ef39 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -614,6 +614,10 @@
 # Clean up old location of system_other.avbpubkey
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/etc/security/avb/)
 
+# Clean up bufferhub files
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/hw/android.frameworks.bufferhub@1.0-service)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/etc/init/android.frameworks.bufferhub@1.0-service.rc)
+
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/super.img)
 
 $(call add-clean-step, find $(PRODUCT_OUT) -type f -name "generated_*_image_info.txt" -print0 | xargs -0 rm -f)
@@ -635,6 +639,9 @@
 
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libc_malloc*)
 
+# Clean up old location of soft OMX plugins
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libstagefright_soft*)
+
 # Move odm build.prop to /odm/etc/.
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/odm/build.prop)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/vendor/odm/build.prop)
@@ -655,6 +662,10 @@
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/product/generic*/*/product)
 $(call add-clean-step, rm -rf $(OUT_DIR)/target/product/generic*/*/system_ext)
 
+# Move GSI-specific files from /system to /system/system_ext
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/etc/init/init.gsi.rc)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/etc/init/config/)
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/common/core.mk b/common/core.mk
index e5264b0..7d505c0 100644
--- a/common/core.mk
+++ b/common/core.mk
@@ -42,6 +42,9 @@
 backslash := \a
 backslash := $(patsubst %a,%,$(backslash))
 
+TOP :=$= .
+TOPDIR :=$=
+
 # Prevent accidentally changing these variables
 .KATI_READONLY := SHELL empty space comma newline pound backslash
 
diff --git a/core/Makefile b/core/Makefile
index 6ced027..c9b8cd1 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -502,6 +502,7 @@
 	$(hide) echo ro.vendor.product.cpu.abilist64="$(TARGET_CPU_ABI_LIST_64_BIT)">>$@
 	$(hide) echo ro.product.board="$(TARGET_BOOTLOADER_BOARD_NAME)">>$@
 	$(hide) echo ro.board.platform="$(TARGET_BOARD_PLATFORM)">>$@
+	$(hide) echo ro.hwui.use_vulkan="$(TARGET_USES_VULKAN)">>$@
 ifdef TARGET_SCREEN_DENSITY
 	$(hide) echo ro.sf.lcd_density="$(TARGET_SCREEN_DENSITY)">>$@
 endif
@@ -762,30 +763,6 @@
 endif
 
 # -----------------------------------------------------------------
-# package stats
-ifdef BUILDING_SYSTEM_IMAGE
-
-PACKAGE_STATS_FILE := $(PRODUCT_OUT)/package-stats.txt
-PACKAGES_TO_STAT := \
-    $(sort $(filter $(TARGET_OUT)/% $(TARGET_OUT_DATA)/%, \
-	$(filter %.jar %.apk, $(ALL_DEFAULT_INSTALLED_MODULES))))
-$(PACKAGE_STATS_FILE): $(PACKAGES_TO_STAT)
-	@echo Package stats: $@
-	@mkdir -p $(dir $@)
-	$(hide) rm -f $@
-ifeq ($(PACKAGES_TO_STAT),)
-# Create empty package stats file if target builds no jar(s) or apk(s).
-	$(hide) touch $@
-else
-	$(hide) build/make/tools/dump-package-stats $^ > $@
-endif
-
-.PHONY: package-stats
-package-stats: $(PACKAGE_STATS_FILE)
-
-endif # BUILDING_SYSTEM_IMAGE
-
-# -----------------------------------------------------------------
 # Cert-to-package mapping.  Used by the post-build signing tools.
 # Use a macro to add newline to each echo command
 define _apkcerts_write_line
@@ -2722,12 +2699,19 @@
 # -- Kernel version and configurations.
 ifeq ($(PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS),true)
 
+intermediates := $(call intermediates-dir-for,ETC,$(notdir $(BUILT_ASSEMBLED_VENDOR_MANIFEST)))
+BUILT_KERNEL_CONFIGS_FILE := $(intermediates)/kernel_configs.txt
+BUILT_KERNEL_VERSION_FILE := $(intermediates)/kernel_version.txt
+
 # BOARD_KERNEL_CONFIG_FILE and BOARD_KERNEL_VERSION can be used to override the values extracted
 # from INSTALLED_KERNEL_TARGET.
 ifdef BOARD_KERNEL_CONFIG_FILE
 ifdef BOARD_KERNEL_VERSION
-$(BUILT_ASSEMBLED_VENDOR_MANIFEST): $(BOARD_KERNEL_CONFIG_FILE)
-$(BUILT_ASSEMBLED_VENDOR_MANIFEST): PRIVATE_FLAGS += --kernel $(BOARD_KERNEL_VERSION):$(BOARD_KERNEL_CONFIG_FILE)
+$(BUILT_KERNEL_CONFIGS_FILE): $(BOARD_KERNEL_CONFIG_FILE)
+	cp $< $@
+$(BUILT_KERNEL_VERSION_FILE):
+	echo $(BOARD_KERNEL_VERSION) > $@
+
 my_board_extracted_kernel := true
 endif # BOARD_KERNEL_VERSION
 endif # BOARD_KERNEL_CONFIG_FILE
@@ -2742,7 +2726,6 @@
     BOARD_KERNEL_VERSION manually; or (3) unsetting PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS \
     manually.)
 else
-intermediates := $(call intermediates-dir-for,ETC,$(notdir $(BUILT_ASSEMBLED_VENDOR_MANIFEST)))
 
 # Tools for decompression that is not in PATH.
 # Check $(EXTRACT_KERNEL) for decompression algorithms supported by the script.
@@ -2750,29 +2733,25 @@
 my_decompress_tools := \
     lz4:$(HOST_OUT_EXECUTABLES)/lz4 \
 
-my_kernel_configs := $(intermediates)/kernel_configs.txt
-my_kernel_version := $(intermediates)/kernel_version.txt
-$(my_kernel_configs): .KATI_IMPLICIT_OUTPUTS := $(my_kernel_version)
-$(my_kernel_configs): PRIVATE_KERNEL_VERSION_FILE := $(my_kernel_version)
-$(my_kernel_configs): PRIVATE_DECOMPRESS_TOOLS := $(my_decompress_tools)
-$(my_kernel_configs): $(foreach pair,$(my_decompress_tools),$(call word-colon,2,$(pair)))
-$(my_kernel_configs): $(EXTRACT_KERNEL) $(INSTALLED_KERNEL_TARGET)
+$(BUILT_KERNEL_CONFIGS_FILE): .KATI_IMPLICIT_OUTPUTS := $(BUILT_KERNEL_VERSION_FILE)
+$(BUILT_KERNEL_CONFIGS_FILE): PRIVATE_DECOMPRESS_TOOLS := $(my_decompress_tools)
+$(BUILT_KERNEL_CONFIGS_FILE): $(foreach pair,$(my_decompress_tools),$(call word-colon,2,$(pair)))
+$(BUILT_KERNEL_CONFIGS_FILE): $(EXTRACT_KERNEL) $(INSTALLED_KERNEL_TARGET)
 	$< --tools $(PRIVATE_DECOMPRESS_TOOLS) --input $(INSTALLED_KERNEL_TARGET) \
 	  --output-configs $@ \
-	  --output-version $(PRIVATE_KERNEL_VERSION_FILE)
-
-$(BUILT_ASSEMBLED_VENDOR_MANIFEST): $(my_kernel_configs) $(my_kernel_version)
-$(BUILT_ASSEMBLED_VENDOR_MANIFEST): PRIVATE_FLAGS += --kernel $$(cat $(my_kernel_version)):$(my_kernel_configs)
+	  --output-version $(BUILT_KERNEL_VERSION_FILE)
 
 intermediates :=
-my_kernel_configs :=
-my_kernel_version :=
 my_decompress_tools :=
 
 endif # my_board_extracted_kernel
 my_board_extracted_kernel :=
 
 endif # INSTALLED_KERNEL_TARGET
+
+$(BUILT_ASSEMBLED_VENDOR_MANIFEST): $(BUILT_KERNEL_CONFIGS_FILE) $(BUILT_KERNEL_VERSION_FILE)
+$(BUILT_ASSEMBLED_VENDOR_MANIFEST): PRIVATE_FLAGS += --kernel $$(cat $(BUILT_KERNEL_VERSION_FILE)):$(BUILT_KERNEL_CONFIGS_FILE)
+
 endif # PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS
 
 $(BUILT_ASSEMBLED_VENDOR_MANIFEST):
@@ -3396,6 +3375,7 @@
   $(hide) rm -rf $(AVB_CHAIN_KEY_DIR)
 endef
 
+ifdef BUILDING_VBMETA_IMAGE
 INSTALLED_VBMETAIMAGE_TARGET := $(BUILT_VBMETAIMAGE_TARGET)
 $(INSTALLED_VBMETAIMAGE_TARGET): PRIVATE_AVB_VBMETA_SIGNING_ARGS := \
     --algorithm $(BOARD_AVB_ALGORITHM) --key $(BOARD_AVB_KEY_PATH)
@@ -3420,6 +3400,7 @@
 .PHONY: vbmetaimage-nodeps
 vbmetaimage-nodeps:
 	$(build-vbmetaimage-target)
+endif # BUILDING_VBMETA_IMAGE
 
 endif # BOARD_AVB_ENABLE
 
@@ -3620,7 +3601,8 @@
 ifeq ($(build_otatools_package),true)
 
 INTERNAL_OTATOOLS_MODULES := \
-  aapt \
+  aapt2 \
+  add_img_to_target_files \
   append2simg \
   avbtool \
   blk_alloc_to_base_fs \
@@ -3633,6 +3615,9 @@
   build_verity_metadata \
   build_verity_tree \
   care_map_generator \
+  check_ota_package_signature \
+  check_target_files_signatures \
+  check_target_files_vintf \
   checkvintf \
   delta_generator \
   e2fsck \
@@ -3642,11 +3627,13 @@
   fs_config \
   generate_verity_key \
   img2simg \
+  img_from_target_files \
   imgdiff \
   libconscrypt_openjdk_jni \
   lpmake \
   lpunpack \
   make_f2fs \
+  merge_target_files \
   minigzip \
   mk_combined_img \
   mkbootfs \
@@ -3661,11 +3648,14 @@
   sefcontext_compile \
   sgdisk \
   shflags \
+  sign_apex \
+  sign_target_files_apks \
   signapk \
   simg2img \
   sload_f2fs \
   tune2fs \
   update_host_simulator \
+  validate_target_files \
   verity_signer \
   verity_verifier \
   zipalign \
@@ -3705,10 +3695,6 @@
   $(sort $(shell find external/avb/test/data -type f -name "testkey_*.pem" -o \
       -name "atx_metadata.bin"))
 endif
-ifneq (,$(wildcard system/update_engine))
-INTERNAL_OTATOOLS_PACKAGE_FILES += \
-  $(sort $(shell find system/update_engine/scripts -name "*.pyc" -prune -o -type f -print))
-endif
 ifeq (true,$(PRODUCT_SUPPORTS_VBOOT))
 INTERNAL_OTATOOLS_PACKAGE_FILES += \
   $(sort $(shell find external/vboot_reference/tests/devkeys -type f))
@@ -3723,13 +3709,13 @@
 $(BUILT_OTATOOLS_PACKAGE): PRIVATE_OTATOOLS_PACKAGE_FILES := $(INTERNAL_OTATOOLS_PACKAGE_FILES)
 $(BUILT_OTATOOLS_PACKAGE): PRIVATE_OTATOOLS_RELEASETOOLS := $(INTERNAL_OTATOOLS_RELEASETOOLS)
 $(BUILT_OTATOOLS_PACKAGE): $(INTERNAL_OTATOOLS_PACKAGE_FILES) $(INTERNAL_OTATOOLS_RELEASETOOLS)
-$(BUILT_OTATOOLS_PACKAGE): $(SOONG_ZIP)
+$(BUILT_OTATOOLS_PACKAGE): $(SOONG_ZIP) $(ZIP2ZIP)
 	@echo "Package OTA tools: $@"
 	rm -rf $@ $(PRIVATE_ZIP_ROOT)
 	mkdir -p $(dir $@)
 	$(call copy-files-with-structure,$(PRIVATE_OTATOOLS_PACKAGE_FILES),$(HOST_OUT)/,$(PRIVATE_ZIP_ROOT))
 	$(call copy-files-with-structure,$(PRIVATE_OTATOOLS_RELEASETOOLS),build/make/tools/,$(PRIVATE_ZIP_ROOT))
-	cp $(SOONG_ZIP) $(PRIVATE_ZIP_ROOT)/bin/
+	cp $(SOONG_ZIP) $(ZIP2ZIP) $(PRIVATE_ZIP_ROOT)/bin/
 	$(SOONG_ZIP) -o $@ -C $(PRIVATE_ZIP_ROOT) -D $(PRIVATE_ZIP_ROOT)
 
 .PHONY: otatools-package
@@ -3864,6 +3850,13 @@
 endif # BOARD_AVB_ENABLE
 endif # BOARD_PREBUILT_DTBOIMAGE
 	$(call dump-dynamic-partitions-info,$@)
+	@# VINTF checks
+ifeq ($(PRODUCT_ENFORCE_VINTF_MANIFEST),true)
+	$(hide) echo "vintf_enforce=true" >> $@
+endif
+ifdef ODM_MANIFEST_SKUS
+	$(hide) echo "vintf_odm_manifest_skus=$(ODM_MANIFEST_SKUS)" >> $@
+endif
 
 .PHONY: misc_info
 misc_info: $(INSTALLED_MISC_INFO_TARGET)
@@ -4017,13 +4010,14 @@
 	    $(SOONG_APEX_KEYS_FILE) \
 	    $(SOONG_ZIP) \
 	    $(HOST_OUT_EXECUTABLES)/fs_config \
-	    $(HOST_OUT_EXECUTABLES)/care_map_generator \
+	    $(ADD_IMG_TO_TARGET_FILES) \
 	    $(MAKE_RECOVERY_PATCH) \
-	    $(BUILD_IMAGE_SRCS) \
 	    $(BUILT_ASSEMBLED_FRAMEWORK_MANIFEST) \
 	    $(BUILT_ASSEMBLED_VENDOR_MANIFEST) \
 	    $(BUILT_SYSTEM_MATRIX) \
 	    $(BUILT_VENDOR_MATRIX) \
+	    $(BUILT_KERNEL_CONFIGS_FILE) \
+	    $(BUILT_KERNEL_VERSION_FILE) \
 	    | $(ACP)
 	@echo "Package target files: $@"
 	$(call create-system-vendor-symlink)
@@ -4272,6 +4266,12 @@
 ifdef BUILT_VENDOR_MATRIX
 	$(hide) cp $(BUILT_VENDOR_MATRIX) $(zip_root)/META/vendor_matrix.xml
 endif
+ifdef BUILT_KERNEL_CONFIGS_FILE
+	$(hide) cp $(BUILT_KERNEL_CONFIGS_FILE) $(zip_root)/META/kernel_configs.txt
+endif
+ifdef BUILT_KERNEL_VERSION_FILE
+	$(hide) cp $(BUILT_KERNEL_VERSION_FILE) $(zip_root)/META/kernel_version.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
@@ -4286,7 +4286,7 @@
 endif # BOARD_SUPER_PARTITION_GROUPS
 	@# TODO(b/134525174): Remove `-r` after addressing the issue with recovery patch generation.
 	$(hide) PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$$PATH MKBOOTIMG=$(MKBOOTIMG) \
-	    build/make/tools/releasetools/add_img_to_target_files -a -r -v -p $(HOST_OUT) $(zip_root)
+	    $(ADD_IMG_TO_TARGET_FILES) -a -r -v -p $(HOST_OUT) $(zip_root)
 ifeq ($(BUILD_QEMU_IMAGES),true)
 	$(hide) AVBTOOL=$(AVBTOOL) $(MK_VBMETA_BOOT_KERNEL_CMDLINE_SH) $(zip_root)/IMAGES/vbmeta.img \
 	    $(zip_root)/IMAGES/system.img $(zip_root)/IMAGES/VerifiedBootParams.textproto
@@ -4494,25 +4494,28 @@
 
 #------------------------------------------------------------------
 # A zip of Proguard obfuscation dictionary files.
-# Only for apps_only build.
 #
-ifdef TARGET_BUILD_APPS
 PROGUARD_DICT_ZIP := $(PRODUCT_OUT)/$(TARGET_PRODUCT)-proguard-dict-$(FILE_NAME_TAG).zip
-# the dependency will be set up later in build/make/core/main.mk.
-$(PROGUARD_DICT_ZIP) :
+# For apps_only build we'll establish the dependency later in build/make/core/main.mk.
+ifndef TARGET_BUILD_APPS
+$(PROGUARD_DICT_ZIP): \
+    $(INSTALLED_SYSTEMIMAGE_TARGET) \
+    $(INSTALLED_RAMDISK_TARGET) \
+    $(INSTALLED_BOOTIMAGE_TARGET) \
+    $(INSTALLED_USERDATAIMAGE_TARGET) \
+    $(INSTALLED_VENDORIMAGE_TARGET) \
+    $(INSTALLED_PRODUCTIMAGE_TARGET) \
+    $(INSTALLED_SYSTEM_EXTIMAGE_TARGET) \
+    $(INSTALLED_ODMIMAGE_TARGET) \
+    $(updater_dep)
+endif
+$(PROGUARD_DICT_ZIP): PRIVATE_LIST_FILE := $(call intermediates-dir-for,PACKAGING,proguard)/filelist
+$(PROGUARD_DICT_ZIP): $(SOONG_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
-
-endif # TARGET_BUILD_APPS
+	mkdir -p $(dir $@) $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS $(dir $(PRIVATE_LIST_FILE))
+	find $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS -name proguard_dictionary | \
+	    sed -e 's/\(.*\)\/proguard_dictionary/\0\n\1\/classes.jar/' > $(PRIVATE_LIST_FILE)
+	$(SOONG_ZIP) --ignore_missing_files -d -o $@ -C $(OUT_DIR)/.. -l $(PRIVATE_LIST_FILE)
 
 
 ifeq (true,$(PRODUCT_USE_DYNAMIC_PARTITIONS))
@@ -4539,7 +4542,6 @@
 
 # For real devices and for dist builds, build super image from target files to an intermediate directory.
 INTERNAL_SUPERIMAGE_DIST_TARGET := $(call intermediates-dir-for,PACKAGING,super.img)/super.img
-INTERNAL_SUPERIMAGE_MISC_INFO := $(call intermediates-dir-for,PACKAGING,superimage_debug)/misc_info.txt
 $(INTERNAL_SUPERIMAGE_DIST_TARGET): extracted_input_target_files := $(patsubst %.zip,%,$(BUILT_TARGET_FILES_PACKAGE))
 $(INTERNAL_SUPERIMAGE_DIST_TARGET): $(LPMAKE) $(BUILT_TARGET_FILES_PACKAGE) $(BUILD_SUPER_IMAGE)
 	$(call pretty,"Target super fs image from target files: $@")
@@ -4591,13 +4593,15 @@
 $(INSTALLED_SUPERIMAGE_TARGET): $(INSTALLED_SUPERIMAGE_DEPENDENCIES)
 	$(call pretty,"Target super fs image for debug: $@")
 	$(call build-superimage-target,$(INSTALLED_SUPERIMAGE_TARGET),\
-	  $(INTERNAL_SUPERIMAGE_MISC_INFO))
+          $(call intermediates-dir-for,PACKAGING,superimage_debug)/misc_info.txt)
 
 droidcore: $(INSTALLED_SUPERIMAGE_TARGET)
 
 # For devices that uses super image directly, the superimage target points to the file in $(PRODUCT_OUT).
 .PHONY: superimage
 superimage: $(INSTALLED_SUPERIMAGE_TARGET)
+
+$(call dist-for-goals,dist_files,$(INSTALLED_MISC_INFO_TARGET):super_misc_info.txt)
 endif # BOARD_BUILD_SUPER_IMAGE_BY_DEFAULT
 
 # Build $(PRODUCT_OUT)/super.img without dependencies.
@@ -4645,37 +4649,12 @@
 
 INTERNAL_UPDATE_PACKAGE_TARGET := $(PRODUCT_OUT)/$(name).zip
 
-$(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(ZIP2ZIP)
-
-ifeq (true,$(BOARD_SUPER_IMAGE_IN_UPDATE_PACKAGE))
-$(INTERNAL_UPDATE_PACKAGE_TARGET): $(INTERNAL_SUPERIMAGE_DIST_TARGET)
-	@echo "Package: $@"
-	# Filter out super_empty and images in BOARD_SUPER_PARTITION_PARTITION_LIST.
-	# Filter out system_other for launch DAP devices because it is in super image.
-	# Include OTA/super_*.img for retrofit devices and super.img for non-retrofit
-	# devices.
-	$(hide) $(ZIP2ZIP) -i $(BUILT_TARGET_FILES_PACKAGE) -o $@ \
-	  -x IMAGES/super_empty.img \
-	  $(foreach partition,$(BOARD_SUPER_PARTITION_PARTITION_LIST), \
-	    -x IMAGES/$(partition).img) \
-	  $(if $(filter system, $(BOARD_SUPER_PARTITION_PARTITION_LIST)), \
-	    $(if $(filter true, $(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS)),, \
-	      -x IMAGES/system_other.img)) \
-	  $(if $(filter true,$(PRODUCT_RETROFIT_DYNAMIC_PARTITIONS)), \
-	    $(foreach device,$(BOARD_SUPER_PARTITION_BLOCK_DEVICES), \
-	      OTA/super_$(device).img:super_$(device).img)) \
-	  IMAGES/VerifiedBootParams.textproto:VerifiedBootParams.textproto \
-	  OTA/android-info.txt:android-info.txt "IMAGES/*.img:."
-	$(if $(INTERNAL_SUPERIMAGE_MISC_INFO), zip -q -j -u $@ $(INTERNAL_SUPERIMAGE_MISC_INFO))
-	$(if $(INTERNAL_SUPERIMAGE_DIST_TARGET), zip -q -j -u $@ $(INTERNAL_SUPERIMAGE_DIST_TARGET))
-else
-$(INTERNAL_UPDATE_PACKAGE_TARGET): $(INSTALLED_MISC_INFO_TARGET)
-	@echo "Package: $@"
-	$(hide) $(ZIP2ZIP) -i $(BUILT_TARGET_FILES_PACKAGE) -o $@ \
-	  IMAGES/VerifiedBootParams.textproto:VerifiedBootParams.textproto \
-	  OTA/android-info.txt:android-info.txt "IMAGES/*.img:."
-	$(if $(INSTALLED_MISC_INFO_TARGET), zip -q -j -u $@ $(INSTALLED_MISC_INFO_TARGET))
-endif # BOARD_SUPER_IMAGE_IN_UPDATE_PACKAGE
+$(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(IMG_FROM_TARGET_FILES)
+	$(call pretty,"Package: $@")
+	PATH=$(INTERNAL_USERIMAGES_BINARY_PATHS):$(dir $(ZIP2ZIP)):$$PATH \
+	    $(IMG_FROM_TARGET_FILES) \
+	        --additional IMAGES/VerifiedBootParams.textproto:VerifiedBootParams.textproto \
+	        $(BUILT_TARGET_FILES_PACKAGE) $@
 
 .PHONY: updatepackage
 updatepackage: $(INTERNAL_UPDATE_PACKAGE_TARGET)
diff --git a/core/aux_config.mk b/core/aux_config.mk
index a508a2d..10d2536 100644
--- a/core/aux_config.mk
+++ b/core/aux_config.mk
@@ -32,7 +32,7 @@
 
 # setup AUX globals
 AUX_SHLIB_SUFFIX := .so
-AUX_GLOBAL_ARFLAGS := cqsD
+AUX_GLOBAL_ARFLAGS := crsPD
 AUX_STATIC_LIB_SUFFIX := .a
 
 # Load ever-lasting "indexed" version of AUX variant environment; it is treated as READ-ONLY from this
@@ -149,6 +149,8 @@
 variant_sfx :=_aux_variant_config.mk
 os_sfx :=_aux_os_config.mk
 
+ifdef AUX_OS_VARIANT_LIST
+
 config_roots := $(wildcard device vendor)
 all_configs :=
 ifdef config_roots
@@ -180,4 +182,6 @@
 )
 endif
 
+endif # AUX_OS_VARIANT_LIST
+
 INSTALLED_AUX_TARGETS :=
diff --git a/core/base_rules.mk b/core/base_rules.mk
index 4a0c15b..7147f6d 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -524,11 +524,11 @@
 
 # Only set up copy rules once, even if another arch variant shares it
 my_vintf_new_pairs := $(filter-out $(ALL_VINTF_MANIFEST_FRAGMENTS_LIST),$(my_vintf_pairs))
-my_vintf_new_installed := $(call copy-many-vintf-manifest-files-checked,$(my_vintf_pairs))
+my_vintf_new_installed := $(call copy-many-vintf-manifest-files-checked,$(my_vintf_new_pairs))
 
 ALL_VINTF_MANIFEST_FRAGMENTS_LIST += $(my_vintf_new_pairs)
 
-$(my_all_targets) : $(my_vintf_installed)
+$(my_all_targets) : $(my_vintf_new_installed)
 endif # LOCAL_VINTF_FRAGMENTS
 endif # !LOCAL_IS_HOST_MODULE
 endif # !LOCAL_UNINSTALLABLE_MODULE
@@ -748,7 +748,7 @@
 ## Register with ALL_MODULES
 ###########################################################
 
-ifeq ($(filter $(my_register_name),$(ALL_MODULES)),)
+ifndef ALL_MODULES.$(my_register_name).PATH
     # These keys are no longer used, they've been replaced by keys that specify
     # target/host/host_cross (REQUIRED_FROM_TARGET / REQUIRED_FROM_HOST) and similar.
     #
@@ -878,18 +878,23 @@
 ##########################################################
 # Track module-level dependencies.
 # Use $(LOCAL_MODULE) instead of $(my_register_name) to ignore module's bitness.
+ifneq (,$(filter deps-license,$(MAKECMDGOALS)))
 ALL_DEPS.MODULES := $(ALL_DEPS.MODULES) $(LOCAL_MODULE)
 ALL_DEPS.$(LOCAL_MODULE).ALL_DEPS := $(sort \
   $(ALL_DEPS.$(LOCAL_MODULE).ALL_DEPS) \
   $(LOCAL_STATIC_LIBRARIES) \
   $(LOCAL_WHOLE_STATIC_LIBRARIES) \
   $(LOCAL_SHARED_LIBRARIES) \
+  $(LOCAL_DYLIB_LIBRARIES) \
+  $(LOCAL_RLIB_LIBRARIES) \
+  $(LOCAL_PROC_MACRO_LIBRARIES) \
   $(LOCAL_HEADER_LIBRARIES) \
   $(LOCAL_STATIC_JAVA_LIBRARIES) \
   $(LOCAL_JAVA_LIBRARIES) \
   $(LOCAL_JNI_SHARED_LIBRARIES))
 
 ALL_DEPS.$(LOCAL_MODULE).LICENSE := $(sort $(ALL_DEPS.$(LOCAL_MODULE).LICENSE) $(license_files))
+endif
 
 ###########################################################
 ## Take care of my_module_tags
@@ -899,14 +904,14 @@
 ALL_MODULE_TAGS := $(sort $(ALL_MODULE_TAGS) $(my_module_tags))
 
 # Add this module name to the tag list of each specified tag.
-$(foreach tag,$(my_module_tags),\
+$(foreach tag,$(filter-out optional,$(my_module_tags)),\
     $(eval ALL_MODULE_NAME_TAGS.$(tag) := $$(ALL_MODULE_NAME_TAGS.$(tag)) $(my_register_name)))
 
 ###########################################################
 ## umbrella targets used to verify builds
 ###########################################################
 j_or_n :=
-ifneq (,$(filter EXECUTABLES SHARED_LIBRARIES STATIC_LIBRARIES HEADER_LIBRARIES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)))
+ifneq (,$(filter EXECUTABLES SHARED_LIBRARIES STATIC_LIBRARIES HEADER_LIBRARIES NATIVE_TESTS RLIB_LIBRARIES DYLIB_LIBRARIES PROC_MACRO_LIBRARIES,$(LOCAL_MODULE_CLASS)))
 j_or_n := native
 else
 ifneq (,$(filter JAVA_LIBRARIES APPS,$(LOCAL_MODULE_CLASS)))
diff --git a/core/binary.mk b/core/binary.mk
index e916164..d9763f9 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -54,6 +54,7 @@
 my_cc := $(LOCAL_CC)
 my_cc_wrapper := $(CC_WRAPPER)
 my_cxx := $(LOCAL_CXX)
+my_cxx_link := $(LOCAL_CXX)
 my_cxx_ldlibs :=
 my_cxx_wrapper := $(CXX_WRAPPER)
 my_c_includes := $(LOCAL_C_INCLUDES)
@@ -1704,13 +1705,20 @@
   my_cxx := $(my_cxx_wrapper) $(CLANG_CXX)
 endif
 
+ifeq ($(strip $(my_cxx_link)),)
+  my_cxx_link := $(CLANG_CXX)
+endif
+
 ifneq ($(LOCAL_NO_STATIC_ANALYZER),true)
   my_cxx := CCC_CXX=$(CLANG_CXX) CLANG_CXX=$(CLANG_CXX) \
             $(SYNTAX_TOOLS_PREFIX)/c++-analyzer
+  my_cxx_link := 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_CXX_LINK := $(my_cxx_link)
 
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_YACCFLAGS := $(LOCAL_YACCFLAGS)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_ASFLAGS := $(my_asflags)
diff --git a/core/board_config.mk b/core/board_config.mk
index db60cee..a6aef87 100644
--- a/core/board_config.mk
+++ b/core/board_config.mk
@@ -358,6 +358,13 @@
 endif
 .KATI_READONLY := BUILDING_USERDATA_IMAGE
 
+# Are we building a vbmeta image
+BUILDING_VBMETA_IMAGE := true
+ifeq ($(PRODUCT_BUILD_VBMETA_IMAGE),false)
+  BUILDING_VBMETA_IMAGE :=
+endif
+.KATI_READONLY := BUILDING_VBMETA_IMAGE
+
 ###########################################
 # Now we can substitute with the real value of TARGET_COPY_OUT_VENDOR
 ifeq ($(TARGET_COPY_OUT_VENDOR),$(_vendor_path_placeholder))
diff --git a/core/build_id.mk b/core/build_id.mk
index bac2f48..2329288 100644
--- a/core/build_id.mk
+++ b/core/build_id.mk
@@ -18,4 +18,4 @@
 # (like "CRB01").  It must be a single word, and is
 # capitalized by convention.
 
-BUILD_ID=PI
+BUILD_ID=QT
diff --git a/core/cc_prebuilt_internal.mk b/core/cc_prebuilt_internal.mk
index a8930d5..6313019 100644
--- a/core/cc_prebuilt_internal.mk
+++ b/core/cc_prebuilt_internal.mk
@@ -180,15 +180,8 @@
 endif
 endif
 
-ifneq ($(filter init%rc,$(notdir $(LOCAL_INSTALLED_MODULE)))$(filter %/etc/init,$(dir $(LOCAL_INSTALLED_MODULE))),)
-  $(eval $(call copy-init-script-file-checked,$(my_prebuilt_src_file),$(built_module)))
-else ifneq ($(LOCAL_PREBUILT_STRIP_COMMENTS),)
-$(built_module) : $(my_prebuilt_src_file)
-	$(transform-prebuilt-to-target-strip-comments)
-else
 $(built_module) : $(my_prebuilt_src_file)
 	$(transform-prebuilt-to-target)
-endif
 ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
 	$(hide) chmod +x $@
 endif
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index 3cc8594..3cadcc2 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -80,6 +80,7 @@
 LOCAL_DROIDDOC_TEMPLATE_DIR:=
 LOCAL_DROIDDOC_USE_STANDARD_DOCLET:=
 LOCAL_DX_FLAGS:=
+LOCAL_DYLIB_LIBRARIES:=
 LOCAL_EMMA_COVERAGE_FILTER:=
 LOCAL_EMMA_INSTRUMENT:=
 LOCAL_ENFORCE_USES_LIBRARIES:=
@@ -114,6 +115,7 @@
 LOCAL_HOST_PREFIX:=
 LOCAL_HOST_REQUIRED_MODULES:=
 LOCAL_INIT_RC:=
+LOCAL_INJECT_BSSL_HASH:=
 LOCAL_INSTALLED_MODULE:=
 LOCAL_INSTALLED_MODULE_STEM:=
 LOCAL_INSTRUMENTATION_FOR:=
@@ -214,6 +216,7 @@
 LOCAL_PRESUBMIT_DISABLED:=
 LOCAL_PRIVATE_PLATFORM_APIS:=
 LOCAL_PRIVILEGED_MODULE:=
+LOCAL_PROC_MACRO_LIBRARIES:=
 # '',full,custom,disabled,obfuscation,optimization
 LOCAL_PRODUCT_MODULE:=
 # TODO(b/135957588) Remove LOCAL_PRODUCT_SERVICES_MODULE
@@ -221,6 +224,7 @@
 LOCAL_PROGUARD_ENABLED:=
 LOCAL_PROGUARD_FLAG_FILES:=
 LOCAL_PROGUARD_FLAGS:=
+LOCAL_PROGUARD_FLAGS_DEPS:=
 LOCAL_PROPRIETARY_MODULE:=
 LOCAL_PROTOC_FLAGS:=
 # lite(default),micro,nano,stream,full,nanopb-c,nanopb-c-enable_malloc,nanopb-c-16bit,nanopb-c-enable_malloc-16bit,nanopb-c-32bit,nanopb-c-enable_malloc-32bit
@@ -240,6 +244,7 @@
 LOCAL_REQUIRED_MODULES:=
 LOCAL_RES_LIBRARIES:=
 LOCAL_RESOURCE_DIR:=
+LOCAL_RLIB_LIBRARIES:=
 LOCAL_RMTYPEDEFS:=
 LOCAL_RRO_THEME:=
 LOCAL_RTTI_FLAG:=
diff --git a/core/combo/HOST_darwin-x86_64.mk b/core/combo/HOST_darwin-x86_64.mk
index 07f8d9f..dac3bbf 100644
--- a/core/combo/HOST_darwin-x86_64.mk
+++ b/core/combo/HOST_darwin-x86_64.mk
@@ -59,8 +59,3 @@
         $(PRIVATE_LDFLAGS) \
         $(PRIVATE_LDLIBS)
 endef
-
-# $(1): The file to check
-define get-file-size
-stat -f "%z" $(1)
-endef
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index deed943..3f4ec0a 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -23,8 +23,3 @@
 
 ############################################################
 ## Macros after this line are shared by the 64-bit config.
-
-# $(1): The file to check
-define get-file-size
-stat -c "%s" "$(1)" | tr -d '\n'
-endef
diff --git a/core/combo/select.mk b/core/combo/select.mk
index eab4c72..33c8e6d 100644
--- a/core/combo/select.mk
+++ b/core/combo/select.mk
@@ -28,7 +28,7 @@
 
 # Set reasonable defaults for the various variables
 
-$(combo_var_prefix)GLOBAL_ARFLAGS := cqsD -format=gnu
+$(combo_var_prefix)GLOBAL_ARFLAGS := crsPD -format=gnu
 
 $(combo_var_prefix)STATIC_LIB_SUFFIX := .a
 
diff --git a/core/config.mk b/core/config.mk
index e4dfe3a..d120d61 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -119,6 +119,7 @@
   ARCH_X86_HAVE_SSSE3 \
 )
 $(KATI_obsolete_var PRODUCT_IOT)
+$(KATI_obsolete_var MD5SUM)
 
 # Used to force goals to build.  Only use for conditionally defined goals.
 .PHONY: FORCE
@@ -594,8 +595,10 @@
 FAT16COPY := build/make/tools/fat16copy.py
 CHECK_ELF_FILE := build/make/tools/check_elf_file.py
 LPMAKE := $(HOST_OUT_EXECUTABLES)/lpmake$(HOST_EXECUTABLE_SUFFIX)
+ADD_IMG_TO_TARGET_FILES := $(HOST_OUT_EXECUTABLES)/add_img_to_target_files$(HOST_EXECUTABLE_SUFFIX)
 BUILD_IMAGE := $(HOST_OUT_EXECUTABLES)/build_image$(HOST_EXECUTABLE_SUFFIX)
 BUILD_SUPER_IMAGE := $(HOST_OUT_EXECUTABLES)/build_super_image$(HOST_EXECUTABLE_SUFFIX)
+IMG_FROM_TARGET_FILES := $(HOST_OUT_EXECUTABLES)/img_from_target_files$(HOST_EXECUTABLE_SUFFIX)
 MAKE_RECOVERY_PATCH := $(HOST_OUT_EXECUTABLES)/make_recovery_patch$(HOST_EXECUTABLE_SUFFIX)
 OTA_FROM_TARGET_FILES := $(HOST_OUT_EXECUTABLES)/ota_from_target_files$(HOST_EXECUTABLE_SUFFIX)
 SPARSE_IMG := $(HOST_OUT_EXECUTABLES)/sparse_img$(HOST_EXECUTABLE_SUFFIX)
@@ -605,7 +608,6 @@
 PROGUARD_DEPS := $(PROGUARD) $(PROGUARD_HOME)/lib/proguard.jar
 JAVATAGS := build/make/tools/java-event-log-tags.py
 MERGETAGS := build/make/tools/merge-event-log-tags.py
-BUILD_IMAGE_SRCS := $(wildcard build/make/tools/releasetools/*.py)
 APPEND2SIMG := $(HOST_OUT_EXECUTABLES)/append2simg
 VERITY_SIGNER := $(HOST_OUT_EXECUTABLES)/verity_signer
 BUILD_VERITY_METADATA := $(HOST_OUT_EXECUTABLES)/build_verity_metadata
@@ -636,13 +638,6 @@
 # Path to tools.jar
 HOST_JDK_TOOLS_JAR := $(ANDROID_JAVA8_HOME)/lib/tools.jar
 
-# It's called md5 on Mac OS and md5sum on Linux
-ifeq ($(HOST_OS),darwin)
-MD5SUM:=md5 -q
-else
-MD5SUM:=md5sum
-endif
-
 APICHECK_COMMAND := $(JAVA) -Xmx4g -jar $(APICHECK) --no-banner --compatible-output=yes
 
 # Boolean variable determining if the whitelist for compatible properties is enabled
@@ -774,6 +769,13 @@
 endif
 .KATI_READONLY := DEFAULT_SYSTEM_DEV_CERTIFICATE
 
+# Certificate for the NetworkStack sepolicy context
+ifdef PRODUCT_MAINLINE_SEPOLICY_DEV_CERTIFICATES
+  MAINLINE_SEPOLICY_DEV_CERTIFICATES := $(PRODUCT_MAINLINE_SEPOLICY_DEV_CERTIFICATES)
+else
+  MAINLINE_SEPOLICY_DEV_CERTIFICATES := $(dir $(DEFAULT_SYSTEM_DEV_CERTIFICATE))
+endif
+
 BUILD_NUMBER_FROM_FILE := $$(cat $(OUT_DIR)/build_number.txt)
 BUILD_DATETIME_FROM_FILE := $$(cat $(BUILD_DATETIME_FILE))
 
@@ -789,7 +791,7 @@
 # is made which breaks compatibility with the previous platform sepolicy version,
 # not just on every increase in PLATFORM_SDK_VERSION.  The minor version should
 # be reset to 0 on every bump of the PLATFORM_SDK_VERSION.
-sepolicy_major_vers := 28
+sepolicy_major_vers := 29
 sepolicy_minor_vers := 0
 
 ifneq ($(sepolicy_major_vers), $(PLATFORM_SDK_VERSION))
diff --git a/core/cxx_stl_setup.mk b/core/cxx_stl_setup.mk
index 7d3ca5c..8e4a46c 100644
--- a/core/cxx_stl_setup.mk
+++ b/core/cxx_stl_setup.mk
@@ -55,8 +55,6 @@
 
 my_cxx_ldlibs :=
 ifneq ($(filter $(my_cxx_stl),libc++ libc++_static),)
-    my_cflags += -D_USING_LIBCXX
-
     ifeq ($($(my_prefix)OS),darwin)
         # libc++'s headers are annotated with availability macros that indicate
         # which version of Mac OS was the first to ship with a libc++ feature
@@ -84,6 +82,7 @@
         my_ldflags += -nodefaultlibs
         my_cxx_ldlibs += $($($(my_prefix)OS)_$(my_link_type)_gcclibs)
     else
+        my_static_libraries += libc++demangle
         ifeq (arm,$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
             my_static_libraries += libunwind_llvm
             my_ldflags += -Wl,--exclude-libs,libunwind_llvm.a
diff --git a/core/definitions.mk b/core/definitions.mk
index d54fd90..381a2a7 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -951,7 +951,7 @@
 $(hide) mkdir -p $(dir $@)
 $(hide) $(BCC_COMPAT) -O3 -o $(dir $@)/$(notdir $(<:.bc=.o)) -fPIC -shared \
   -rt-path $(RS_PREBUILT_CLCORE) -mtriple $(RS_COMPAT_TRIPLE) $<
-$(hide) $(PRIVATE_CXX) -shared -Wl,-soname,$(notdir $@) -nostdlib \
+$(hide) $(PRIVATE_CXX_LINK) -shared -Wl,-soname,$(notdir $@) -nostdlib \
   -Wl,-rpath,\$$ORIGIN/../lib \
   $(dir $@)/$(notdir $(<:.bc=.o)) \
   $(RS_PREBUILT_COMPILER_RT) \
@@ -1533,7 +1533,7 @@
 endef
 
 define transform-o-to-aux-executable-inner
-$(hide) $(PRIVATE_CXX) -pie \
+$(hide) $(PRIVATE_CXX_LINK) -pie \
   -Bdynamic \
   -Wl,--gc-sections \
   $(PRIVATE_ALL_OBJECTS) \
@@ -1552,7 +1552,7 @@
 endef
 
 define transform-o-to-aux-static-executable-inner
-$(hide) $(PRIVATE_CXX) \
+$(hide) $(PRIVATE_CXX_LINK) \
   -Bstatic \
   -Wl,--gc-sections \
   $(PRIVATE_ALL_OBJECTS) \
@@ -1653,7 +1653,7 @@
 # it to be overriden en-masse see combo/linux-arm.make for an example.
 ifneq ($(HOST_CUSTOM_LD_COMMAND),true)
 define transform-host-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
+$(hide) $(PRIVATE_CXX_LINK) \
   -Wl,-rpath,\$$ORIGIN/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_SHARED_LIBRARIES)) \
   -Wl,-rpath,\$$ORIGIN/$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_SHARED_LIBRARIES)) \
   -shared -Wl,-soname,$(notdir $@) \
@@ -1694,7 +1694,7 @@
 ###########################################################
 
 define transform-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
+$(hide) $(PRIVATE_CXX_LINK) \
   -nostdlib -Wl,-soname,$(notdir $@) \
   -Wl,--gc-sections \
   -shared \
@@ -1729,7 +1729,7 @@
 ###########################################################
 
 define transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) -pie \
+$(hide) $(PRIVATE_CXX_LINK) -pie \
   -nostdlib -Bdynamic \
   -Wl,-dynamic-linker,$(PRIVATE_LINKER) \
   -Wl,--gc-sections \
@@ -1772,7 +1772,7 @@
 ###########################################################
 
 define transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) \
+$(hide) $(PRIVATE_CXX_LINK) \
   -nostdlib -Bstatic \
   $(if $(filter $(PRIVATE_LDFLAGS),-shared),,-static) \
   -Wl,--gc-sections \
@@ -1810,7 +1810,7 @@
 
 ifneq ($(HOST_CUSTOM_LD_COMMAND),true)
 define transform-host-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) \
+$(hide) $(PRIVATE_CXX_LINK) \
   $(PRIVATE_ALL_OBJECTS) \
   -Wl,--whole-archive \
   $(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES) \
@@ -2302,7 +2302,7 @@
 ifeq ($(HOST_OS),linux)
 # Runs appcompat and store logs in $(PRODUCT_OUT)/appcompat
 define extract-package
-$(AAPT2) dump $@ | awk -F ' |=' '/^Package/{print $$3}' >> $(PRODUCT_OUT)/appcompat/$(PRIVATE_MODULE).log &&
+$(AAPT2) dump resources $@ | awk -F ' |=' '/^Package/{print $$3}' >> $(PRODUCT_OUT)/appcompat/$(PRIVATE_MODULE).log &&
 endef
 define appcompat-header
 $(hide) \
@@ -2678,9 +2678,9 @@
 ###########################################################
 
 # $(1): The file to check
-ifndef get-file-size
-$(error HOST_OS must define get-file-size)
-endif
+define get-file-size
+stat -c "%s" "$(1)" | tr -d '\n'
+endef
 
 # $(1): The file(s) to check (often $@)
 # $(2): The partition size.
diff --git a/core/dex_preopt_config.mk b/core/dex_preopt_config.mk
index b856bf4..69eaea1 100644
--- a/core/dex_preopt_config.mk
+++ b/core/dex_preopt_config.mk
@@ -99,7 +99,7 @@
   $(call add_json_bool, DisableGenerateProfile,             $(filter false,$(WITH_DEX_PREOPT_GENERATE_PROFILE)))
   $(call add_json_str,  ProfileDir,                         $(PRODUCT_DEX_PREOPT_PROFILE_DIR))
   $(call add_json_list, BootJars,                           $(PRODUCT_BOOT_JARS))
-  $(call add_json_list, RuntimeApexJars,                    $(RUNTIME_APEX_JARS))
+  $(call add_json_list, ArtApexJars,                        $(ART_APEX_JARS))
   $(call add_json_list, ProductUpdatableBootModules,        $(PRODUCT_UPDATABLE_BOOT_MODULES))
   $(call add_json_list, ProductUpdatableBootLocations,      $(PRODUCT_UPDATABLE_BOOT_LOCATIONS))
   $(call add_json_list, SystemServerJars,                   $(PRODUCT_SYSTEM_SERVER_JARS))
diff --git a/core/dynamic_binary.mk b/core/dynamic_binary.mk
index 0accdc0..27ff2c9 100644
--- a/core/dynamic_binary.mk
+++ b/core/dynamic_binary.mk
@@ -39,6 +39,17 @@
 include $(BUILD_SYSTEM)/binary.mk
 ###################################
 
+ifdef LOCAL_INJECT_BSSL_HASH
+inject_module := $(intermediates)/INJECT_BSSL_HASH/$(notdir $(my_installed_module_stem))
+LOCAL_INTERMEDIATE_TARGETS += $(inject_module)
+$(inject_module): $(SOONG_HOST_OUT)/bin/bssl_inject_hash
+$(inject_module): $(linked_module)
+	@echo "target inject BSSL hash: $(PRIVATE_MODULE) ($@)"
+	$(SOONG_HOST_OUT)/bin/bssl_inject_hash -in-object $< -o $@
+else
+inject_module := $(linked_module)
+endif
+
 ###########################################################
 ## Store a copy with symbols for symbolic debugging
 ###########################################################
@@ -47,7 +58,7 @@
 else
 my_unstripped_path := $(LOCAL_UNSTRIPPED_PATH)
 endif
-symbolic_input := $(linked_module)
+symbolic_input := $(inject_module)
 symbolic_output := $(my_unstripped_path)/$(my_installed_module_stem)
 $(symbolic_output) : $(symbolic_input)
 	@echo "target Symbolic: $(PRIVATE_MODULE) ($@)"
@@ -59,7 +70,7 @@
 
 ifeq ($(BREAKPAD_GENERATE_SYMBOLS),true)
 my_breakpad_path := $(TARGET_OUT_BREAKPAD)/$(patsubst $(PRODUCT_OUT)/%,%,$(my_module_path))
-breakpad_input := $(linked_module)
+breakpad_input := $(inject_module)
 breakpad_output := $(my_breakpad_path)/$(my_installed_module_stem).sym
 $(breakpad_output) : $(breakpad_input) | $(BREAKPAD_DUMP_SYMS) $(PRIVATE_READELF)
 	@echo "target breakpad: $(PRIVATE_MODULE) ($@)"
@@ -133,6 +144,7 @@
 
 $(cleantarget): PRIVATE_CLEAN_FILES += \
     $(linked_module) \
+    $(inject_module) \
     $(breakpad_output) \
     $(symbolic_output) \
     $(strip_output)
diff --git a/core/envsetup.mk b/core/envsetup.mk
index 3e8fd3f..88bf352 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -111,9 +111,6 @@
 ifneq (,$(findstring Darwin,$(UNAME)))
   HOST_OS := darwin
 endif
-ifneq (,$(findstring Macintosh,$(UNAME)))
-  HOST_OS := darwin
-endif
 
 HOST_OS_EXTRA := $(shell uname -rsm)
 ifeq ($(HOST_OS),linux)
@@ -256,10 +253,10 @@
 #################################################################
 # Set up minimal BOOTCLASSPATH list of jars to build/execute
 # java code with dalvikvm/art.
-# Jars present in the runtime apex. These should match exactly the list of
-# Java libraries in the runtime apex build rule.
-RUNTIME_APEX_JARS := core-oj core-libart okhttp bouncycastle apache-xml
-TARGET_CORE_JARS := $(RUNTIME_APEX_JARS) conscrypt
+# Jars present in the ART apex. These should match exactly the list of
+# Java libraries in the ART apex build rule.
+ART_APEX_JARS := core-oj core-libart core-icu4j okhttp bouncycastle apache-xml
+TARGET_CORE_JARS := $(ART_APEX_JARS) conscrypt
 ifeq ($(EMMA_INSTRUMENT),true)
   ifneq ($(EMMA_INSTRUMENT_STATIC),true)
     # For instrumented build, if Jacoco is not being included statically
@@ -331,6 +328,7 @@
 
 HOST_OUT_EXECUTABLES := $(HOST_OUT)/bin
 HOST_OUT_SHARED_LIBRARIES := $(HOST_OUT)/lib64
+HOST_OUT_DYLIB_LIBRARIES := $(HOST_OUT)/lib64
 HOST_OUT_RENDERSCRIPT_BITCODE := $(HOST_OUT_SHARED_LIBRARIES)
 HOST_OUT_JAVA_LIBRARIES := $(HOST_OUT)/framework
 HOST_OUT_SDK_ADDON := $(HOST_OUT)/sdk_addon
@@ -817,7 +815,16 @@
 TARGET_OUT_SYSTEM_EXT_APPS := $(target_out_system_ext_app_base)/app
 TARGET_OUT_SYSTEM_EXT_APPS_PRIVILEGED := $(target_out_system_ext_app_base)/priv-app
 TARGET_OUT_SYSTEM_EXT_ETC := $(TARGET_OUT_SYSTEM_EXT)/etc
+TARGET_OUT_SYSTEM_EXT_EXECUTABLES := $(TARGET_OUT_SYSTEM_EXT)/bin
+.KATI_READONLY := \
+  TARGET_OUT_SYSTEM_EXT_EXECUTABLES \
+  TARGET_OUT_SYSTEM_EXT_SHARED_LIBRARIES \
+  TARGET_OUT_SYSTEM_EXT_JAVA_LIBRARIES \
+  TARGET_OUT_SYSTEM_EXT_APPS \
+  TARGET_OUT_SYSTEM_EXT_APPS_PRIVILEGED \
+  TARGET_OUT_SYSTEM_EXT_ETC
 
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_EXECUTABLES := $(TARGET_OUT_SYSTEM_EXT_EXECUTABLES)
 ifeq ($(TARGET_TRANSLATE_2ND_ARCH),true)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_SHARED_LIBRARIES := $(target_out_system_ext_shared_libraries_base)/lib/$(TARGET_2ND_ARCH)
 else
@@ -825,6 +832,11 @@
 endif
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_APPS := $(TARGET_OUT_SYSTEM_EXT_APPS)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_APPS_PRIVILEGED := $(TARGET_OUT_SYSTEM_EXT_APPS_PRIVILEGED)
+.KATI_READONLY := \
+  $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_EXECUTABLES \
+  $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_SHARED_LIBRARIES \
+  $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_APPS \
+  $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SYSTEM_EXT_APPS_PRIVILEGED
 
 TARGET_OUT_BREAKPAD := $(PRODUCT_OUT)/breakpad
 .KATI_READONLY := TARGET_OUT_BREAKPAD
@@ -884,7 +896,7 @@
   TARGET_INSTALLER_SYSTEM_OUT
 
 COMMON_MODULE_CLASSES := TARGET-NOTICE_FILES HOST-NOTICE_FILES HOST-JAVA_LIBRARIES
-PER_ARCH_MODULE_CLASSES := SHARED_LIBRARIES STATIC_LIBRARIES EXECUTABLES GYP RENDERSCRIPT_BITCODE NATIVE_TESTS HEADER_LIBRARIES
+PER_ARCH_MODULE_CLASSES := SHARED_LIBRARIES STATIC_LIBRARIES EXECUTABLES GYP RENDERSCRIPT_BITCODE NATIVE_TESTS HEADER_LIBRARIES RLIB_LIBRARIES DYLIB_LIBRARIES
 .KATI_READONLY := COMMON_MODULE_CLASSES PER_ARCH_MODULE_CLASSES
 
 ifeq ($(CALLED_FROM_SETUP),true)
diff --git a/core/fuzz_test.mk b/core/fuzz_test.mk
index f5bdef0..71801ba 100644
--- a/core/fuzz_test.mk
+++ b/core/fuzz_test.mk
@@ -64,12 +64,12 @@
 $(error $(LOCAL_PATH): Do not set LOCAL_MODULE_PATH_64 when building test $(LOCAL_MODULE))
 endif
 
-LOCAL_MODULE_PATH_64 := $(TARGET_OUT_DATA_NATIVE_TESTS)/fuzzers/$(LOCAL_MODULE)
-LOCAL_MODULE_PATH_32 := $($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_DATA_NATIVE_TESTS)/fuzzers/$(LOCAL_MODULE)
+LOCAL_MODULE_PATH_64 := $(TARGET_OUT_DATA_NATIVE_TESTS)/fuzzers/$(my_fuzzer)/$(LOCAL_MODULE)
+LOCAL_MODULE_PATH_32 := $($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_DATA_NATIVE_TESTS)/fuzzers/$(my_fuzzer)/$(LOCAL_MODULE)
 
 ifndef LOCAL_MULTILIB
 ifndef LOCAL_32_BIT_ONLY
-LOCAL_MULTILIB := both
+LOCAL_MULTILIB := 64
 endif
 endif
 
diff --git a/core/instrumentation_test_config_template.xml b/core/instrumentation_test_config_template.xml
index afaa561..18ea676 100644
--- a/core/instrumentation_test_config_template.xml
+++ b/core/instrumentation_test_config_template.xml
@@ -22,8 +22,6 @@
         <option name="test-file-name" value="{MODULE}.apk" />
     </target_preparer>
 
-    {EXTRA_CONFIGS}
-
     <test class="com.android.tradefed.testtype.{TEST_TYPE}" >
         <option name="package" value="{PACKAGE}" />
         <option name="runner" value="{RUNNER}" />
diff --git a/core/java.mk b/core/java.mk
index b463037..d080450 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -470,6 +470,8 @@
 proguard_flag_files := $(addprefix $(LOCAL_PATH)/, $(LOCAL_PROGUARD_FLAG_FILES))
 proguard_flag_files += $(addprefix $(LOCAL_PATH)/, $(LOCAL_R8_FLAG_FILES))
 LOCAL_PROGUARD_FLAGS += $(addprefix -include , $(proguard_flag_files))
+LOCAL_PROGUARD_FLAGS_DEPS += $(proguard_flag_files)
+proguard_flag_files :=
 
 ifdef LOCAL_TEST_MODULE_TO_PROGUARD_WITH
 extra_input_jar := $(call intermediates-dir-for,APPS,$(LOCAL_TEST_MODULE_TO_PROGUARD_WITH),,COMMON)/classes.jar
@@ -481,8 +483,6 @@
   $(built_dex_intermediate): .KATI_IMPLICIT_OUTPUTS := $(proguard_dictionary) $(proguard_configuration)
 endif
 
-else  # LOCAL_PROGUARD_ENABLED not defined
-proguard_flag_files :=
 endif # LOCAL_PROGUARD_ENABLED defined
 
 ifneq ($(LOCAL_IS_STATIC_JAVA_LIBRARY),true)
@@ -492,7 +492,7 @@
   $(built_dex_intermediate): PRIVATE_EXTRA_INPUT_JAR := $(extra_input_jar)
   $(built_dex_intermediate): PRIVATE_PROGUARD_FLAGS := $(legacy_proguard_flags) $(common_proguard_flags) $(LOCAL_PROGUARD_FLAGS)
   $(built_dex_intermediate): PRIVATE_PROGUARD_DICTIONARY := $(proguard_dictionary)
-  $(built_dex_intermediate) : $(full_classes_pre_proguard_jar) $(extra_input_jar) $(my_proguard_sdk_raise) $(common_proguard_flag_files) $(proguard_flag_files) $(legacy_proguard_lib_deps) $(R8_COMPAT_PROGUARD)
+  $(built_dex_intermediate) : $(full_classes_pre_proguard_jar) $(extra_input_jar) $(my_proguard_sdk_raise) $(common_proguard_flag_files) $(legacy_proguard_lib_deps) $(R8_COMPAT_PROGUARD) $(LOCAL_PROGUARD_FLAGS_DEPS)
 	$(transform-jar-to-dex-r8)
 else # !LOCAL_PROGUARD_ENABLED
   $(built_dex_intermediate): PRIVATE_D8_LIBS := $(full_java_bootclasspath_libs) $(full_shared_java_header_libs)
diff --git a/core/java_common.mk b/core/java_common.mk
index cb88a9e..a23d92d 100644
--- a/core/java_common.mk
+++ b/core/java_common.mk
@@ -81,19 +81,17 @@
 $(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_DIR := $(proto_java_sources_dir)
 $(proto_java_srcjar): PRIVATE_PROTOC_FLAGS := $(LOCAL_PROTOC_FLAGS)
 ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),micro)
-$(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javamicro_out
+  $(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javamicro_out
+  $(proto_java_srcjar): PRIVATE_PROTOC_FLAGS += --plugin=$(HOST_OUT_EXECUTABLES)/protoc-gen-javamicro
+  $(proto_java_srcjar): $(HOST_OUT_EXECUTABLES)/protoc-gen-javamicro
+else ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
+  $(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javanano_out
+else ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),stream)
+  $(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javastream_out
+  $(proto_java_srcjar): PRIVATE_PROTOC_FLAGS += --plugin=$(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
+  $(proto_java_srcjar): $(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
 else
-  ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
-$(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javanano_out
-  else
-    ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),stream)
-$(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javastream_out
-$(proto_java_srcjar): PRIVATE_PROTOC_FLAGS += --plugin=$(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
-$(proto_java_srcjar): $(HOST_OUT_EXECUTABLES)/protoc-gen-javastream
-    else
-$(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --java_out
-    endif
-  endif
+  $(proto_java_srcjar): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --java_out
 endif
 $(proto_java_srcjar): 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_srcjar) : $(proto_sources_fullpath) $(PROTOC) $(SOONG_ZIP)
diff --git a/core/java_library.mk b/core/java_library.mk
index 34e4874..4734eaf 100644
--- a/core/java_library.mk
+++ b/core/java_library.mk
@@ -44,6 +44,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES += jacocoagent
 # Exclude jacoco classes from proguard
 LOCAL_PROGUARD_FLAGS += -include $(BUILD_SYSTEM)/proguard.jacoco.flags
+LOCAL_PROGUARD_FLAGS_DEPS += $(BUILD_SYSTEM)/proguard.jacoco.flags
 endif # LOCAL_EMMA_INSTRUMENT
 endif # EMMA_INSTRUMENT_STATIC
 else
diff --git a/core/java_renderscript.mk b/core/java_renderscript.mk
index 820967a..672863b 100644
--- a/core/java_renderscript.mk
+++ b/core/java_renderscript.mk
@@ -139,6 +139,7 @@
     $(rs_support_lib) $(rs_support_io_lib) $(rs_jni_lib) $(rs_compiler_rt)
 $(rs_compatibility_jni_libs): $(BCC_COMPAT)
 $(rs_compatibility_jni_libs): PRIVATE_CXX := $(CXX_WRAPPER) $(CLANG_CXX)
+$(rs_compatibility_jni_libs): PRIVATE_CXX_LINK := $(CLANG_CXX)
 $(rs_compatibility_jni_libs): PRIVATE_SDK_VERSION := $(my_min_sdk_version)
 $(rs_compatibility_jni_libs): $(renderscript_intermediate)/librs.%.so: \
     $(renderscript_intermediate.bc_folder)%.bc \
diff --git a/core/main.mk b/core/main.mk
index a240b35..9eea513 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -1,14 +1,3 @@
-# Only use ANDROID_BUILD_SHELL to wrap around bash.
-# DO NOT use other shells such as zsh.
-ifdef ANDROID_BUILD_SHELL
-SHELL := $(ANDROID_BUILD_SHELL)
-else
-# Use bash, not whatever shell somebody has installed as /bin/sh
-# This is repeated in config.mk, since envsetup.sh runs that file
-# directly.
-SHELL := /bin/bash
-endif
-
 ifndef KATI
 $(warning Calling make directly is no longer supported.)
 $(warning Either use 'envsetup.sh; m' or 'build/soong/soong_ui.bash --make-mode')
@@ -22,9 +11,6 @@
 # the top of the source tree, for example when "make -C" is used in m/mm/mmm.
 PWD := $(shell pwd)
 
-TOP := .
-TOPDIR :=
-
 # This is the default target.  It must be the first declared target.
 .PHONY: droid
 DEFAULT_GOAL := droid
@@ -1677,6 +1663,7 @@
     $(INTERNAL_OTA_RETROFIT_DYNAMIC_PARTITIONS_PACKAGE_TARGET) \
     $(BUILT_OTATOOLS_PACKAGE) \
     $(SYMBOLS_ZIP) \
+    $(PROGUARD_DICT_ZIP) \
     $(COVERAGE_ZIP) \
     $(APPCOMPAT_ZIP) \
     $(INSTALLED_FILES_FILE) \
@@ -1708,7 +1695,6 @@
     $(call dist-for-goals, droidcore, \
       $(APPS_ZIP) \
       $(INTERNAL_EMULATOR_PACKAGE_TARGET) \
-      $(PACKAGE_STATS_FILE) \
     )
   endif
   endif
@@ -1792,12 +1778,13 @@
 LSDUMP_PATHS_FILE := $(PRODUCT_OUT)/lsdump_paths.txt
 
 .PHONY: findlsdumps
-findlsdumps: $(LSDUMP_PATHS_FILE) $(LSDUMP_PATHS)
+# LSDUMP_PATHS is a list of tag:path.
+findlsdumps: $(LSDUMP_PATHS_FILE) $(foreach p,$(LSDUMP_PATHS),$(call word-colon,2,$(p)))
 
 $(LSDUMP_PATHS_FILE): PRIVATE_LSDUMP_PATHS := $(LSDUMP_PATHS)
 $(LSDUMP_PATHS_FILE):
 	@echo "Generate $@"
-	@rm -rf $@ && echo "$(PRIVATE_LSDUMP_PATHS)" | sed -e 's/ /\n/g' > $@
+	@rm -rf $@ && echo -e "$(subst :,:$(space),$(subst $(space),\n,$(PRIVATE_LSDUMP_PATHS)))" > $@
 
 .PHONY: check-elf-files
 check-elf-files:
diff --git a/core/misc_prebuilt_internal.mk b/core/misc_prebuilt_internal.mk
index cc2683c..a52b9e5 100644
--- a/core/misc_prebuilt_internal.mk
+++ b/core/misc_prebuilt_internal.mk
@@ -25,7 +25,14 @@
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
+ifneq ($(filter init%rc,$(notdir $(LOCAL_INSTALLED_MODULE)))$(filter %/etc/init,$(dir $(LOCAL_INSTALLED_MODULE))),)
+  $(eval $(call copy-init-script-file-checked,$(my_prebuilt_src_file),$(LOCAL_BUILT_MODULE)))
+else ifneq ($(LOCAL_PREBUILT_STRIP_COMMENTS),)
+$(LOCAL_BUILT_MODULE) : $(my_prebuilt_src_file)
+	$(transform-prebuilt-to-target-strip-comments)
+else
 $(LOCAL_BUILT_MODULE) : $(my_prebuilt_src_file)
 	$(transform-prebuilt-to-target)
+endif
 
-built_module := $(LOCAL_BUILT_MODULE)
\ No newline at end of file
+built_module := $(LOCAL_BUILT_MODULE)
diff --git a/core/notice_files.mk b/core/notice_files.mk
index 6df570e..680a0b1 100644
--- a/core/notice_files.mk
+++ b/core/notice_files.mk
@@ -55,7 +55,7 @@
   module_installed_filename := $(patsubst $(PRODUCT_OUT)/%,%,$(LOCAL_INSTALLED_MODULE))
 else
   # This module isn't installable
-  ifneq ($(filter STATIC_LIBRARIES HEADER_LIBRARIES,$(LOCAL_MODULE_CLASS)),)
+  ifneq ($(filter  STATIC_LIBRARIES RLIB_LIBRARIES PROC_MACRO_LIBRARIES HEADER_LIBRARIES,$(LOCAL_MODULE_CLASS)),)
     # Stick the static libraries with the dynamic libraries.
     # We can't use xxx_OUT_STATIC_LIBRARIES because it points into
     # device-obj or host-obj.
diff --git a/core/package_internal.mk b/core/package_internal.mk
index c06a63c..557a2c6 100644
--- a/core/package_internal.mk
+++ b/core/package_internal.mk
@@ -253,6 +253,7 @@
 endif # need_compile_res
 endif # !custom
 LOCAL_PROGUARD_FLAGS := $(addprefix -include ,$(proguard_options_file)) $(LOCAL_PROGUARD_FLAGS)
+LOCAL_PROGUARD_FLAGS_DEPS += $(proguard_options_file)
 
 ifeq (true,$(EMMA_INSTRUMENT))
 ifndef LOCAL_EMMA_INSTRUMENT
@@ -272,6 +273,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES += jacocoagent
 # Exclude jacoco classes from proguard
 LOCAL_PROGUARD_FLAGS += -include $(BUILD_SYSTEM)/proguard.jacoco.flags
+LOCAL_PROGUARD_FLAGS_DEPS += $(BUILD_SYSTEM)/proguard.jacoco.flags
 endif # Contains java code
 else
 ifdef LOCAL_SDK_VERSION
@@ -282,6 +284,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES += jacocoagent
 # Exclude jacoco classes from proguard
 LOCAL_PROGUARD_FLAGS += -include $(BUILD_SYSTEM)/proguard.jacoco.flags
+LOCAL_PROGUARD_FLAGS_DEPS += $(BUILD_SYSTEM)/proguard.jacoco.flags
 endif # Contains java code
 endif # TARGET_BUILD_APPS
 endif # LOCAL_SDK_VERSION
diff --git a/core/pdk_config.mk b/core/pdk_config.mk
index ce78ece..4a069d3 100644
--- a/core/pdk_config.mk
+++ b/core/pdk_config.mk
@@ -20,6 +20,7 @@
   target/common/obj/JAVA_LIBRARIES/conscrypt_intermediates \
   target/common/obj/JAVA_LIBRARIES/core-oj_intermediates \
   target/common/obj/JAVA_LIBRARIES/core-libart_intermediates \
+  target/common/obj/JAVA_LIBRARIES/core-icu4j_intermediates \
   target/common/obj/JAVA_LIBRARIES/ext_intermediates \
   target/common/obj/JAVA_LIBRARIES/framework_intermediates \
   target/common/obj/JAVA_LIBRARIES/hwbinder_intermediates \
diff --git a/core/product-graph.mk b/core/product-graph.mk
index 9fc8e57..b97a69d 100644
--- a/core/product-graph.mk
+++ b/core/product-graph.mk
@@ -131,6 +131,7 @@
 	$(hide) echo 'PRODUCT_SDK_ADDON_DOC_MODULES=$$(PRODUCTS.$(strip $(1)).PRODUCT_SDK_ADDON_DOC_MODULES)' >> $$@
 	$(hide) echo 'PRODUCT_DEFAULT_WIFI_CHANNELS=$$(PRODUCTS.$(strip $(1)).PRODUCT_DEFAULT_WIFI_CHANNELS)' >> $$@
 	$(hide) echo 'PRODUCT_DEFAULT_DEV_CERTIFICATE=$$(PRODUCTS.$(strip $(1)).PRODUCT_DEFAULT_DEV_CERTIFICATE)' >> $$@
+	$(hide) echo 'PRODUCT_MAINLINE_SEPOLICY_DEV_CERTIFICATES=$$(PRODUCTS.$(strip $(1)).PRODUCT_MAINLINE_SEPOLICY_DEV_CERTIFICATES)' >> $$@
 	$(hide) echo 'PRODUCT_RESTRICT_VENDOR_FILES=$$(PRODUCTS.$(strip $(1)).PRODUCT_RESTRICT_VENDOR_FILES)' >> $$@
 	$(hide) echo 'PRODUCT_VENDOR_KERNEL_HEADERS=$$(PRODUCTS.$(strip $(1)).PRODUCT_VENDOR_KERNEL_HEADERS)' >> $$@
 
diff --git a/core/product.mk b/core/product.mk
index c54583d..2c89fab 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -205,6 +205,7 @@
 
 _product_list_vars += PRODUCT_DEFAULT_WIFI_CHANNELS
 _product_list_vars += PRODUCT_DEFAULT_DEV_CERTIFICATE
+_product_list_vars += PRODUCT_MAINLINE_SEPOLICY_DEV_CERTIFICATES
 _product_list_vars += PRODUCT_RESTRICT_VENDOR_FILES
 
 # The list of product-specific kernel header dirs
@@ -361,6 +362,7 @@
 _product_single_value_vars += PRODUCT_BUILD_USERDATA_IMAGE
 _product_single_value_vars += PRODUCT_BUILD_RECOVERY_IMAGE
 _product_single_value_vars += PRODUCT_BUILD_BOOT_IMAGE
+_product_single_value_vars += PRODUCT_BUILD_VBMETA_IMAGE
 
 _product_list_vars += PRODUCT_UPDATABLE_BOOT_MODULES
 _product_list_vars += PRODUCT_UPDATABLE_BOOT_LOCATIONS
@@ -368,6 +370,12 @@
 # Whether the product would like to check prebuilt ELF files.
 _product_single_value_vars += PRODUCT_CHECK_ELF_FILES
 
+# If set, device uses virtual A/B.
+_product_single_value_vars += PRODUCT_VIRTUAL_AB_OTA
+
+# If set, device retrofits virtual A/B.
+_product_single_value_vars += PRODUCT_VIRTUAL_AB_OTA_RETROFIT
+
 .KATI_READONLY := _product_single_value_vars _product_list_vars
 _product_var_list :=$= $(_product_single_value_vars) $(_product_list_vars)
 
diff --git a/core/rbe.mk b/core/rbe.mk
index 766b121..231859b 100644
--- a/core/rbe.mk
+++ b/core/rbe.mk
@@ -21,7 +21,7 @@
   else
     rbe_dir := $(HOME)/rbe
   endif
-  RBE_WRAPPER := $(rbe_dir)/rewrapper
+  RBE_WRAPPER := $(rbe_dir)/rewrapper --labels=type=compile,lang=cpp,compiler=clang --env_var_whitelist=PWD
 
   # Append rewrapper to existing *_WRAPPER variables so it's possible to
   # use both ccache and rewrapper.
diff --git a/core/sdk_check.mk b/core/sdk_check.mk
index 49ea2a8..c09fc7c 100644
--- a/core/sdk_check.mk
+++ b/core/sdk_check.mk
@@ -8,6 +8,11 @@
 
 whitelisted_modules := framework-res__auto_generated_rro
 
+
+ifeq (,$(JAVA_SDK_ENFORCEMENT_ERROR))
+  JAVA_SDK_ENFORCEMENT_ERROR := APPS
+endif
+
 ifeq ($(LOCAL_SDK_VERSION)$(LOCAL_PRIVATE_PLATFORM_APIS),)
   ifeq (,$(filter $(LOCAL_MODULE),$(whitelisted_modules)))
     ifneq ($(JAVA_SDK_ENFORCEMENT_WARNING)$(JAVA_SDK_ENFORCEMENT_ERROR),)
diff --git a/core/soong_config.mk b/core/soong_config.mk
index 6737472..bcd025b 100644
--- a/core/soong_config.mk
+++ b/core/soong_config.mk
@@ -135,6 +135,7 @@
 $(call add_json_list, BootJars,                          $(PRODUCT_BOOT_JARS))
 
 $(call add_json_bool, VndkUseCoreVariant,                $(TARGET_VNDK_USE_CORE_VARIANT))
+$(call add_json_bool, VndkSnapshotBuildArtifacts,        $(VNDK_SNAPSHOT_BUILD_ARTIFACTS))
 
 $(call add_json_bool, Treble_linker_namespaces,          $(filter true,$(PRODUCT_TREBLE_LINKER_NAMESPACES)))
 $(call add_json_bool, Enforce_vintf_manifest,            $(filter true,$(PRODUCT_ENFORCE_VINTF_MANIFEST)))
@@ -163,7 +164,7 @@
 $(call add_json_list, BoardPlatPrivateSepolicyDirs,      $(BOARD_PLAT_PRIVATE_SEPOLICY_DIR))
 $(call add_json_list, BoardSepolicyM4Defs,               $(BOARD_SEPOLICY_M4DEFS))
 
-$(call add_json_bool, FlattenApex,                       $(filter true,$(TARGET_FLATTEN_APEX)))
+$(call add_json_bool, Flatten_apex,                      $(filter true,$(TARGET_FLATTEN_APEX)))
 
 $(call add_json_str,  DexpreoptGlobalConfig,             $(DEX_PREOPT_CONFIG))
 
diff --git a/core/soong_rust_prebuilt.mk b/core/soong_rust_prebuilt.mk
new file mode 100644
index 0000000..ea43078
--- /dev/null
+++ b/core/soong_rust_prebuilt.mk
@@ -0,0 +1,127 @@
+# Native prebuilt coming from Soong.
+# Extra inputs:
+# LOCAL_SOONG_UNSTRIPPED_BINARY
+
+ifneq ($(LOCAL_MODULE_MAKEFILE),$(SOONG_ANDROID_MK))
+  $(call pretty-error,soong_rust_prebuilt.mk may only be used from Soong)
+endif
+
+ifdef LOCAL_IS_HOST_MODULE
+  ifneq ($(HOST_OS),$(LOCAL_MODULE_HOST_OS))
+    my_prefix := HOST_CROSS_
+    LOCAL_HOST_PREFIX := $(my_prefix)
+  else
+    my_prefix := HOST_
+    LOCAL_HOST_PREFIX :=
+  endif
+else
+  my_prefix := TARGET_
+endif
+
+ifeq ($($(my_prefix)ARCH),$(LOCAL_MODULE_$(my_prefix)ARCH))
+  # primary arch
+  LOCAL_2ND_ARCH_VAR_PREFIX :=
+else ifeq ($($(my_prefix)2ND_ARCH),$(LOCAL_MODULE_$(my_prefix)ARCH))
+  # secondary arch
+  LOCAL_2ND_ARCH_VAR_PREFIX := $($(my_prefix)2ND_ARCH_VAR_PREFIX)
+else
+  $(call pretty-error,Unsupported LOCAL_MODULE_$(my_prefix)ARCH=$(LOCAL_MODULE_$(my_prefix)ARCH))
+endif
+
+skip_module :=
+ifeq ($(TARGET_TRANSLATE_2ND_ARCH),true)
+  ifndef LOCAL_IS_HOST_MODULE
+    ifdef LOCAL_2ND_ARCH_VAR_PREFIX
+      # Only support rlib and dylib libraries for translated arch
+      ifeq ($(filter RLIB_LIBRARIES DYLIB_LIBRARIES PROC_MACRO_LIBRARIES,$(LOCAL_MODULE_CLASS)),)
+        skip_module := true
+      endif
+    endif
+  endif
+endif
+
+
+ifndef skip_module
+
+# Don't install rlib/proc_macro libraries.
+ifndef LOCAL_UNINSTALLABLE_MODULE
+  ifneq ($(filter RLIB_LIBRARIES PROC_MACRO_LIBRARIES,$(LOCAL_MODULE_CLASS)),)
+    LOCAL_UNINSTALLABLE_MODULE := true
+  endif
+endif
+
+
+#######################################
+include $(BUILD_SYSTEM)/base_rules.mk
+#######################################
+
+# The real dependency will be added after all Android.mks are loaded and the install paths
+# of the shared libraries are determined.
+ifdef LOCAL_INSTALLED_MODULE
+  ifdef LOCAL_SHARED_LIBRARIES
+    my_shared_libraries := $(LOCAL_SHARED_LIBRARIES)
+    $(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
+      $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(my_shared_libraries))
+  endif
+  ifdef LOCAL_DYLIB_LIBRARIES
+    my_dylibs := $(LOCAL_DYLIB_LIBRARIES)
+    # Treat these as shared library dependencies for installation purposes.
+    $(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
+      $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(my_dylibs))
+  endif
+endif
+
+$(LOCAL_BUILT_MODULE): $(LOCAL_PREBUILT_MODULE_FILE)
+	$(transform-prebuilt-to-target)
+ifneq ($(filter EXECUTABLES,$(LOCAL_MODULE_CLASS)),)
+	$(hide) chmod +x $@
+endif
+
+ifndef LOCAL_IS_HOST_MODULE
+  ifdef LOCAL_SOONG_UNSTRIPPED_BINARY
+    my_symbol_path := $(if $(LOCAL_SOONG_SYMBOL_PATH),$(LOCAL_SOONG_SYMBOL_PATH),$(my_module_path))
+    # Store a copy with symbols for symbolic debugging
+    my_unstripped_path := $(TARGET_OUT_UNSTRIPPED)/$(patsubst $(PRODUCT_OUT)/%,%,$(my_symbol_path))
+    # drop /root as /root is mounted as /
+    my_unstripped_path := $(patsubst $(TARGET_OUT_UNSTRIPPED)/root/%,$(TARGET_OUT_UNSTRIPPED)/%, $(my_unstripped_path))
+    symbolic_output := $(my_unstripped_path)/$(my_installed_module_stem)
+    $(eval $(call copy-one-file,$(LOCAL_SOONG_UNSTRIPPED_BINARY),$(symbolic_output)))
+    $(call add-dependency,$(LOCAL_BUILT_MODULE),$(symbolic_output))
+  endif
+endif
+
+# A product may be configured to strip everything in some build variants.
+# We do the stripping as a post-install command so that LOCAL_BUILT_MODULE
+# is still with the symbols and we don't need to clean it (and relink) when
+# you switch build variant.
+ifneq ($(filter $(STRIP_EVERYTHING_BUILD_VARIANTS),$(TARGET_BUILD_VARIANT)),)
+$(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD := \
+  $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_STRIP) --strip-all $(LOCAL_INSTALLED_MODULE)
+endif
+
+$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
+
+# We don't care about installed rlib/static libraries, since the libraries have
+# already been linked into the module at that point. We do, however, care
+# about the NOTICE files for any rlib/static libraries that we use.
+# (see notice_files.mk)
+#
+# Filter out some NDK libraries that are not being exported.
+my_static_libraries := \
+    $(filter-out ndk_libc++_static ndk_libc++abi ndk_libandroid_support ndk_libunwind \
+      ndk_libc++_static.native_bridge ndk_libc++abi.native_bridge \
+      ndk_libandroid_support.native_bridge ndk_libunwind.native_bridge, \
+      $(LOCAL_STATIC_LIBRARIES))
+installed_static_library_notice_file_targets := \
+    $(foreach lib,$(my_static_libraries), \
+      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST$(if $(my_host_cross),_CROSS,),TARGET)-STATIC_LIBRARIES-$(lib))
+installed_static_library_notice_file_targets += \
+    $(foreach lib,$(LOCAL_RLIB_LIBRARIES), \
+      NOTICE-$(if $(LOCAL_IS_HOST_MODULE),HOST$(if $(my_host_cross),_CROSS,),TARGET)-RLIB_LIBRARIES-$(lib))
+
+$(notice_target): | $(installed_static_library_notice_file_targets)
+$(LOCAL_INSTALLED_MODULE): | $(notice_target)
+endif # !skip_module
+
+skip_module :=
+
diff --git a/core/static_java_library.mk b/core/static_java_library.mk
index cb3281a..7eef167 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -74,6 +74,7 @@
 endif
 
 LOCAL_PROGUARD_FLAGS := $(addprefix -include ,$(proguard_options_file)) $(LOCAL_PROGUARD_FLAGS)
+LOCAL_PROGUARD_FLAGS_DEPS += $(proguard_options_file)
 
 R_file_stamp := $(intermediates.COMMON)/src/R.stamp
 LOCAL_INTERMEDIATE_TARGETS += $(R_file_stamp)
diff --git a/core/tasks/check_boot_jars/package_whitelist.txt b/core/tasks/check_boot_jars/package_whitelist.txt
index 3b63843..8d9878f 100644
--- a/core/tasks/check_boot_jars/package_whitelist.txt
+++ b/core/tasks/check_boot_jars/package_whitelist.txt
@@ -243,3 +243,4 @@
 ###################################################
 # Packages used for Android in Chrome OS
 org\.chromium\.arc
+org\.chromium\.arc\..*
diff --git a/core/tasks/cts.mk b/core/tasks/cts.mk
index 33c3a83..f3b4368 100644
--- a/core/tasks/cts.mk
+++ b/core/tasks/cts.mk
@@ -14,7 +14,6 @@
 
 test_suite_name := cts
 test_suite_tradefed := cts-tradefed
-# TODO: Fix the following two lines after harness is moved to its own repo
 test_suite_dynamic_config := test/suite_harness/tools/cts-tradefed/DynamicConfig.xml
 test_suite_readme := test/suite_harness/tools/cts-tradefed/README
 
diff --git a/core/tasks/cts_instant.mk b/core/tasks/cts_instant.mk
deleted file mode 100644
index 18f1db3..0000000
--- a/core/tasks/cts_instant.mk
+++ /dev/null
@@ -1,25 +0,0 @@
-# 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.
-
-test_suite_name := cts_instant
-test_suite_tradefed := cts-instant-tradefed
-test_suite_dynamic_config := test/suite_harness/tools/cts-instant-tradefed/DynamicConfig.xml
-test_suite_readme := test/suite_harness/tools/cts-instant-tradefed/README
-
-include $(BUILD_SYSTEM)/tasks/tools/compatibility.mk
-
-.PHONY: cts_instant
-cts_instant: $(compatibility_zip)
-$(call dist-for-goals, cts_instant, $(compatibility_zip))
-
diff --git a/core/tasks/tools/compatibility.mk b/core/tasks/tools/compatibility.mk
index f480300..b6dd39e 100644
--- a/core/tasks/tools/compatibility.mk
+++ b/core/tasks/tools/compatibility.mk
@@ -55,7 +55,7 @@
 # Copy tools
 	$(hide) cp $(PRIVATE_TOOLS) $(PRIVATE_OUT_DIR)/tools
 	$(if $(PRIVATE_DYNAMIC_CONFIG),$(hide) cp $(PRIVATE_DYNAMIC_CONFIG) $(PRIVATE_OUT_DIR)/testcases/$(PRIVATE_SUITE_NAME).dynamic)
-	$(hide) find $(dir $@)/$(PRIVATE_NAME) | sort >$@.list
+	$(hide) find $(PRIVATE_OUT_DIR)/tools $(PRIVATE_OUT_DIR)/testcases | sort >$@.list
 	$(hide) $(SOONG_ZIP) -d -o $@ -C $(dir $@) -l $@.list
 
 # Reset all input variables
diff --git a/core/tasks/vndk.mk b/core/tasks/vndk.mk
index 90ebd92..b487f53 100644
--- a/core/tasks/vndk.mk
+++ b/core/tasks/vndk.mk
@@ -47,64 +47,28 @@
 
 vndk_snapshot_top := $(call intermediates-dir-for,PACKAGING,vndk-snapshot)
 vndk_snapshot_out := $(vndk_snapshot_top)/vndk-snapshot
+vndk_snapshot_soong_dir := $(call intermediates-dir-for,PACKAGING,vndk-snapshot-soong)
 vndk_snapshot_configs_out := $(vndk_snapshot_top)/configs
 
 #######################################
 # vndk_snapshot_zip
 vndk_snapshot_variant := $(vndk_snapshot_out)/$(TARGET_ARCH)
-binder :=
-ifneq ($(TARGET_IS_64_BIT), true)
-  ifneq ($(TARGET_USES_64_BIT_BINDER), true)
-    binder := binder32
-  endif
-endif
-vndk_lib_dir := $(subst $(space),/,$(strip $(vndk_snapshot_variant) $(binder) arch-$(TARGET_ARCH)-$(TARGET_ARCH_VARIANT)))
-vndk_lib_dir_2nd := $(subst $(space),/,$(strip $(vndk_snapshot_variant) $(binder) arch-$(TARGET_2ND_ARCH)-$(TARGET_2ND_ARCH_VARIANT)))
 vndk_snapshot_zip := $(PRODUCT_OUT)/android-vndk-$(TARGET_PRODUCT).zip
 
 $(vndk_snapshot_zip): PRIVATE_VNDK_SNAPSHOT_OUT := $(vndk_snapshot_out)
 
-prebuilts := $(SOONG_VNDK_SNAPSHOT_CORE_LIBS)
-$(vndk_snapshot_zip): PRIVATE_VNDK_CORE_OUT := $(vndk_lib_dir)/shared/vndk-core
-$(vndk_snapshot_zip): PRIVATE_VNDK_CORE_SOONG_PREBUILTS := $(prebuilts)
-$(vndk_snapshot_zip): $(prebuilts)
-prebuilts :=
-
-prebuilts := $(SOONG_VNDK_SNAPSHOT_SP_LIBS)
-$(vndk_snapshot_zip): PRIVATE_VNDK_SP_OUT := $(vndk_lib_dir)/shared/vndk-sp
-$(vndk_snapshot_zip): PRIVATE_VNDK_SP_SOONG_PREBUILTS := $(prebuilts)
-$(vndk_snapshot_zip): $(prebuilts)
-prebuilts :=
-
 deps := $(call paths-of-intermediates,$(foreach txt,$(vndk_prebuilt_txts), \
           $(txt):$(patsubst %.txt,%.$(PLATFORM_VNDK_VERSION).txt,$(txt))))
-prebuilts := $(SOONG_VNDK_SNAPSHOT_CONFIGS)
 $(vndk_snapshot_zip): PRIVATE_CONFIGS_OUT := $(vndk_snapshot_variant)/configs
 $(vndk_snapshot_zip): PRIVATE_CONFIGS_INTERMEDIATES := $(deps)
-$(vndk_snapshot_zip): PRIVATE_CONFIGS_SOONG_PREBUILTS := $(prebuilts)
-$(vndk_snapshot_zip): $(foreach d,$(deps),$(call word-colon,1,$(d))) $(prebuilts)
+$(vndk_snapshot_zip): $(foreach d,$(deps),$(call word-colon,1,$(d)))
 deps :=
-prebuilts :=
 
-prebuilts := $(SOONG_VNDK_SNAPSHOT_NOTICES)
-$(vndk_snapshot_zip): PRIVATE_NOTICE_FILES_OUT := $(vndk_snapshot_variant)/NOTICE_FILES
-$(vndk_snapshot_zip): PRIVATE_NOTICE_FILES_SOONG_PREBUILTS := $(prebuilts)
-$(vndk_snapshot_zip): $(prebuilts)
-prebuilts :=
+vndk_snapshot_soong_files := $(call copy-many-files, $(SOONG_VNDK_SNAPSHOT_FILES), $(vndk_snapshot_soong_dir))
 
-ifdef TARGET_2ND_ARCH
-prebuilts := $(SOONG_VNDK_SNAPSHOT_CORE_LIBS_2ND)
-$(vndk_snapshot_zip): PRIVATE_VNDK_CORE_OUT_2ND := $(vndk_lib_dir_2nd)/shared/vndk-core
-$(vndk_snapshot_zip): PRIVATE_VNDK_CORE_SOONG_PREBUILTS_2ND := $(prebuilts)
-$(vndk_snapshot_zip): $(prebuilts)
-prebuilts :=
-
-prebuilts := $(SOONG_VNDK_SNAPSHOT_SP_LIBS_2ND)
-$(vndk_snapshot_zip): PRIVATE_VNDK_SP_OUT_2ND := $(vndk_lib_dir_2nd)/shared/vndk-sp
-$(vndk_snapshot_zip): PRIVATE_VNDK_SP_SOONG_PREBUILTS_2ND := $(prebuilts)
-$(vndk_snapshot_zip): $(prebuilts)
-prebuilts :=
-endif
+$(vndk_snapshot_zip): PRIVATE_VNDK_SNAPSHOT_SOONG_DIR := $(vndk_snapshot_soong_dir)
+$(vndk_snapshot_zip): PRIVATE_VNDK_SNAPSHOT_SOONG_FILES := $(sort $(vndk_snapshot_soong_files))
+$(vndk_snapshot_zip): $(vndk_snapshot_soong_files)
 
 # Args
 #   $(1): destination directory
@@ -118,16 +82,6 @@
     true \
   ))
 
-# Args
-#   $(1): destination directory
-#   $(2): list of prebuilts to copy
-$(vndk_snapshot_zip): private-copy-prebuilts = \
-  $(if $(2),$(strip \
-    @mkdir -p $(1) && \
-    $(foreach file, $(2), cp $(file) $(1) && ) \
-    true \
-  ))
-
 $(vndk_snapshot_zip): $(SOONG_ZIP)
 	@echo 'Generating VNDK snapshot: $@'
 	@rm -f $@
@@ -135,21 +89,8 @@
 	@mkdir -p $(PRIVATE_VNDK_SNAPSHOT_OUT)
 	$(call private-copy-intermediates, \
 		$(PRIVATE_CONFIGS_OUT),$(PRIVATE_CONFIGS_INTERMEDIATES))
-	$(call private-copy-prebuilts, \
-		$(PRIVATE_VNDK_CORE_OUT),$(PRIVATE_VNDK_CORE_SOONG_PREBUILTS))
-	$(call private-copy-prebuilts, \
-		$(PRIVATE_VNDK_SP_OUT),$(PRIVATE_VNDK_SP_SOONG_PREBUILTS))
-	$(call private-copy-prebuilts, \
-		$(PRIVATE_CONFIGS_OUT),$(PRIVATE_CONFIGS_SOONG_PREBUILTS))
-	$(call private-copy-prebuilts, \
-		$(PRIVATE_NOTICE_FILES_OUT),$(PRIVATE_NOTICE_FILES_SOONG_PREBUILTS))
-ifdef TARGET_2ND_ARCH
-	$(call private-copy-prebuilts, \
-		$(PRIVATE_VNDK_CORE_OUT_2ND),$(PRIVATE_VNDK_CORE_SOONG_PREBUILTS_2ND))
-	$(call private-copy-prebuilts, \
-		$(PRIVATE_VNDK_SP_OUT_2ND),$(PRIVATE_VNDK_SP_SOONG_PREBUILTS_2ND))
-endif
-	$(hide) $(SOONG_ZIP) -o $@ -C $(PRIVATE_VNDK_SNAPSHOT_OUT) -D $(PRIVATE_VNDK_SNAPSHOT_OUT)
+	$(hide) $(SOONG_ZIP) -o $@ -C $(PRIVATE_VNDK_SNAPSHOT_OUT) -D $(PRIVATE_VNDK_SNAPSHOT_OUT) \
+		-C $(PRIVATE_VNDK_SNAPSHOT_SOONG_DIR) $(foreach f,$(PRIVATE_VNDK_SNAPSHOT_SOONG_FILES),-f $(f))
 
 .PHONY: vndk
 vndk: $(vndk_snapshot_zip)
@@ -162,11 +103,10 @@
 vndk_prebuilt_txts :=
 vndk_snapshot_top :=
 vndk_snapshot_out :=
+vndk_snapshot_soong_dir :=
+vndk_snapshot_soong_files :=
 vndk_snapshot_configs_out :=
 vndk_snapshot_variant :=
-binder :=
-vndk_lib_dir :=
-vndk_lib_dir_2nd :=
 
 else # BOARD_VNDK_RUNTIME_DISABLE is set to 'true'
 error_msg := "CANNOT generate VNDK snapshot. BOARD_VNDK_RUNTIME_DISABLE must not be set to 'true'."
diff --git a/core/tasks/vts-core-tests.mk b/core/tasks/vts-core-tests.mk
index 919354c..fb1e1c6 100644
--- a/core/tasks/vts-core-tests.mk
+++ b/core/tasks/vts-core-tests.mk
@@ -45,3 +45,5 @@
 
 vts-core: $(vts-core-zip)
 $(call dist-for-goals, vts-core, $(vts-core-zip) $(vts-core-list-zip) $(vts-core-configs-zip))
+
+tests: vts-core
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index efaacf5..00c5ed0 100644
--- a/core/version_defaults.mk
+++ b/core/version_defaults.mk
@@ -84,12 +84,10 @@
 # generate the range of allowed SDK versions, so it must have an entry for every
 # unreleased API level targetable by this branch, not just those that are valid
 # lunch targets for this branch.
-PLATFORM_VERSION.QP1A := Q
 PLATFORM_VERSION.RP1A := R
 
 # These are the current development codenames, if the build is not a final
 # release build.  If this is a final release build, it is simply "REL".
-PLATFORM_VERSION_CODENAME.QP1A := Q
 PLATFORM_VERSION_CODENAME.RP1A := R
 
 ifndef PLATFORM_VERSION
@@ -114,7 +112,7 @@
   # When you increment the PLATFORM_SDK_VERSION please ensure you also
   # clear out the following text file of all older PLATFORM_VERSION's:
   # cts/tests/tests/os/assets/platform_versions.txt
-  PLATFORM_SDK_VERSION := 28
+  PLATFORM_SDK_VERSION := 29
 endif
 .KATI_READONLY := PLATFORM_SDK_VERSION
 
@@ -252,7 +250,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 := 2019-07-05
+      PLATFORM_SECURITY_PATCH := 2019-09-05
 endif
 .KATI_READONLY := PLATFORM_SECURITY_PATCH
 
diff --git a/envsetup.sh b/envsetup.sh
index 0392e86..40f7705 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -23,6 +23,7 @@
 - resgrep:    Greps on all local res/*.xml files.
 - mangrep:    Greps on all local AndroidManifest.xml files.
 - mgrep:      Greps on all local Makefiles and *.bp files.
+- owngrep:    Greps on all local OWNERS files.
 - sepgrep:    Greps on all local sepolicy files.
 - sgrep:      Greps on all local source files.
 - godir:      Go to the directory containing a file.
@@ -995,6 +996,12 @@
         -exec grep --color -n "$@" {} +
 }
 
+function owngrep()
+{
+    find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -type f -name 'OWNERS' \
+        -exec grep --color -n "$@" {} +
+}
+
 function sepgrep()
 {
     find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -name sepolicy -type d \
diff --git a/target/board/BoardConfigEmuCommon.mk b/target/board/BoardConfigEmuCommon.mk
index ac21918..f941918 100644
--- a/target/board/BoardConfigEmuCommon.mk
+++ b/target/board/BoardConfigEmuCommon.mk
@@ -35,9 +35,23 @@
   # 3G + header
   BOARD_SUPER_PARTITION_SIZE := 3229614080
   BOARD_SUPER_PARTITION_GROUPS := emulator_dynamic_partitions
-  BOARD_EMULATOR_DYNAMIC_PARTITIONS_PARTITION_LIST := \
-      system \
-      vendor
+
+  ifeq ($(QEMU_USE_SYSTEM_EXT_PARTITIONS),true)
+    BOARD_EMULATOR_DYNAMIC_PARTITIONS_PARTITION_LIST := \
+        system \
+        system_ext \
+        product \
+        vendor
+
+    TARGET_COPY_OUT_PRODUCT := product
+    BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE := ext4
+    TARGET_COPY_OUT_SYSTEM_EXT := system_ext
+    BOARD_SYSTEM_EXTIMAGE_FILE_SYSTEM_TYPE := ext4
+  else
+    BOARD_EMULATOR_DYNAMIC_PARTITIONS_PARTITION_LIST := \
+        system \
+        vendor
+  endif
 
   # 3G
   BOARD_EMULATOR_DYNAMIC_PARTITIONS_SIZE := 3221225472
diff --git a/target/board/BoardConfigGsiCommon.mk b/target/board/BoardConfigGsiCommon.mk
index e4dd032..31d0bdf 100644
--- a/target/board/BoardConfigGsiCommon.mk
+++ b/target/board/BoardConfigGsiCommon.mk
@@ -56,7 +56,3 @@
 
 # Disable 64 bit mediadrmserver
 TARGET_ENABLE_MEDIADRM_64 :=
-
-# Ordinary (non-flattened) APEX may require kernel changes. For maximum compatibility,
-# use flattened APEX for GSI
-TARGET_FLATTEN_APEX := true
diff --git a/target/board/BoardConfigMainlineCommon.mk b/target/board/BoardConfigMainlineCommon.mk
index 70cfe39..52ba814 100644
--- a/target/board/BoardConfigMainlineCommon.mk
+++ b/target/board/BoardConfigMainlineCommon.mk
@@ -13,6 +13,10 @@
 TARGET_COPY_OUT_VENDOR := vendor
 TARGET_COPY_OUT_PRODUCT := product
 
+# Creates metadata partition mount point under root for
+# the devices with metadata parition
+BOARD_USES_METADATA_PARTITION := true
+
 BOARD_VNDK_VERSION := current
 
 # Required flag for non-64 bit devices from P.
@@ -45,6 +49,3 @@
 
 # Generate an APEX image for experiment b/119800099.
 DEXPREOPT_GENERATE_APEX_IMAGE := true
-
-# Mainline devices support apex
-TARGET_FLATTEN_APEX := false
diff --git a/target/board/generic_x86_arm/BoardConfig.mk b/target/board/generic_x86_arm/BoardConfig.mk
index 6fae411..e879001 100644
--- a/target/board/generic_x86_arm/BoardConfig.mk
+++ b/target/board/generic_x86_arm/BoardConfig.mk
@@ -18,14 +18,10 @@
 TARGET_ARCH := x86
 TARGET_ARCH_VARIANT := x86
 
-TARGET_2ND_ARCH := arm
-TARGET_2ND_CPU_ABI := armeabi-v7a
-TARGET_2ND_CPU_ABI2 := armeabi
-TARGET_2ND_ARCH_VARIANT := armv7-a-neon
-TARGET_2ND_CPU_VARIANT := generic
-
-TARGET_CPU_ABI_LIST := x86 armeabi-v7a armeabi
-TARGET_TRANSLATE_2ND_ARCH := true
+TARGET_NATIVE_BRIDGE_ARCH := arm
+TARGET_NATIVE_BRIDGE_ARCH_VARIANT := armv7-a-neon
+TARGET_NATIVE_BRIDGE_CPU_VARIANT := generic
+TARGET_NATIVE_BRIDGE_ABI := armeabi-v7a armeabi
 
 BUILD_BROKEN_DUP_RULES := true
 
diff --git a/target/board/go_defaults.prop b/target/board/go_defaults.prop
new file mode 100644
index 0000000..93071cd
--- /dev/null
+++ b/target/board/go_defaults.prop
@@ -0,0 +1,15 @@
+#
+# 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.
+#
diff --git a/target/board/go_defaults_512.prop b/target/board/go_defaults_512.prop
new file mode 100644
index 0000000..a8eea9c
--- /dev/null
+++ b/target/board/go_defaults_512.prop
@@ -0,0 +1,23 @@
+#
+# 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.
+#
+
+# 512MB specific properties.
+
+# lmkd can kill more now.
+ro.lmk.medium=700
+
+# madvise random in ART to reduce page cache thrashing.
+dalvik.vm.madvise-random=true
diff --git a/target/board/go_defaults_common.prop b/target/board/go_defaults_common.prop
new file mode 100644
index 0000000..d4989e0
--- /dev/null
+++ b/target/board/go_defaults_common.prop
@@ -0,0 +1,42 @@
+#
+# 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.
+#
+
+# Sets Android Go recommended default values for propreties.
+
+# Set lowram options
+ro.lmk.critical_upgrade=true
+ro.lmk.upgrade_pressure=40
+ro.lmk.downgrade_pressure=60
+ro.lmk.kill_heaviest_task=false
+ro.statsd.enable=true
+
+# set threshold to filter unused apps
+pm.dexopt.downgrade_after_inactive_days=10
+
+# set the compiler filter for shared apks to quicken.
+# Rationale: speed has a lot of dex code expansion, it uses more ram and space
+# compared to quicken. Using quicken for shared APKs on Go devices may save RAM.
+# Note that this is a trade-off: here we trade clean pages for dirty pages,
+# extra cpu and battery. That's because the quicken files will be jit-ed in all
+# the processes that load of shared apk and the code cache is not shared.
+# Some notable apps that will be affected by this are gms and chrome.
+# b/65591595.
+pm.dexopt.shared=quicken
+
+# Default heap sizes. Allow up to 256m for large heaps to make sure a single app
+# doesn't take all of the RAM.
+dalvik.vm.heapgrowthlimit=128m
+dalvik.vm.heapsize=256m
diff --git a/target/product/aosp_product.mk b/target/product/aosp_product.mk
index fa56779..cda977b 100644
--- a/target/product/aosp_product.mk
+++ b/target/product/aosp_product.mk
@@ -29,8 +29,6 @@
     system/app/WAPPushManager/oat/% \
     system/bin/healthd \
     system/etc/init/healthd.rc \
-    system/etc/seccomp_policy/crash_dump.%.policy \
-    system/etc/seccomp_policy/mediacodec.policy \
     system/etc/vintf/manifest/manifest_healthd.xml \
     system/lib/libframesequence.so \
     system/lib/libgiftranscode.so \
diff --git a/target/product/base_system.mk b/target/product/base_system.mk
index 60646c3..2ef104b 100644
--- a/target/product/base_system.mk
+++ b/target/product/base_system.mk
@@ -56,6 +56,8 @@
     com.android.conscrypt \
     com.android.i18n \
     com.android.location.provider \
+    com.android.media \
+    com.android.media.swcodec \
     com.android.resolv \
     com.android.neuralnetworks \
     com.android.tzdata \
@@ -65,13 +67,14 @@
     CtsShimPrebuilt \
     CtsShimPrivPrebuilt \
     debuggerd\
-    DefaultContainerService \
+    device_config \
     dmctl \
     dnsmasq \
     DownloadProvider \
     dpm \
     dumpstate \
     dumpsys \
+    DynamicSystemInstallationService \
     e2fsck \
     ExtServices \
     ExtShared \
@@ -84,6 +87,7 @@
     fs_config_dirs_system \
     group_system \
     gsid \
+    gsi_tool \
     heapprofd \
     heapprofd_client \
     gatekeeperd \
@@ -91,6 +95,8 @@
     hid \
     hwservicemanager \
     idmap \
+    idmap2 \
+    idmap2d \
     ime \
     ims-common \
     incident \
@@ -111,6 +117,7 @@
     ld.config.txt \
     ld.mc \
     libaaudio \
+    libamidi \
     libandroid \
     libandroidfw \
     libandroid_runtime \
@@ -118,10 +125,6 @@
     libartpalette-system \
     libashmemd_client \
     libaudioeffect_jni \
-    libaudioflinger \
-    libaudiopolicymanager \
-    libaudiopolicyservice \
-    libaudioutils \
     libbinder \
     libbinder_ndk \
     libc.bootstrap \
@@ -154,7 +157,6 @@
     libmedia \
     libmedia_jni \
     libmediandk \
-    libmediaplayerservice \
     libmtp \
     libnetd_client \
     libnetlink \
@@ -168,12 +170,11 @@
     libradio_metadata \
     librtp_jni \
     libsensorservice \
+    libsfplugin_ccodec \
     libskia \
     libsonic \
     libsonivox \
     libsoundpool \
-    libsoundtrigger \
-    libsoundtriggerservice \
     libspeexresampler \
     libsqlite \
     libstagefright \
@@ -194,6 +195,7 @@
     linker \
     linkerconfig \
     lmkd \
+    LocalTransport \
     locksettings \
     logcat \
     logd \
@@ -201,6 +203,7 @@
     lshal \
     mdnsd \
     media \
+    mediacodec.policy \
     mediadrmserver \
     mediaextractor \
     mediametrics \
@@ -215,8 +218,10 @@
     NetworkStack \
     org.apache.http.legacy \
     otacerts \
+    PackageInstaller \
     passwd_system \
     perfetto \
+    PermissionController \
     ping \
     ping6 \
     platform.xml \
@@ -253,7 +258,6 @@
     tc \
     telecom \
     telephony-common \
-    thermalserviced \
     tombstoned \
     traced \
     traced_probes \
@@ -292,6 +296,7 @@
     flags_health_check \
     icu-data_host_i18n_apex \
     icu_tzdata.dat_host_tzdata_apex \
+    idmap2 \
     incident_report \
     ld.mc \
     lpdump \
@@ -325,10 +330,12 @@
     ext \
     telephony-common \
     voip-common \
-    ims-common
-PRODUCT_UPDATABLE_BOOT_MODULES := conscrypt
+    ims-common \
+    updatable-media
+PRODUCT_UPDATABLE_BOOT_MODULES := conscrypt updatable-media
 PRODUCT_UPDATABLE_BOOT_LOCATIONS := \
-    /apex/com.android.conscrypt/javalib/conscrypt.jar
+    /apex/com.android.conscrypt/javalib/conscrypt.jar \
+    /apex/com.android.media/javalib/updatable-media.jar
 
 
 PRODUCT_COPY_FILES += \
@@ -359,6 +366,7 @@
     gdbserver \
     init-debug.rc \
     iotop \
+    iperf3 \
     iw \
     logpersist.start \
     logtagd.rc \
@@ -383,7 +391,9 @@
     WallpaperBackup
 
 # Packages included only for eng/userdebug builds, when building with SANITIZE_TARGET=address
-PRODUCT_PACKAGES_DEBUG_ASAN :=
+PRODUCT_PACKAGES_DEBUG_ASAN := \
+    fuzz \
+    honggfuzz
 
 PRODUCT_PACKAGES_DEBUG_JAVA_COVERAGE := \
     libdumpcoverage
diff --git a/target/product/base_vendor.mk b/target/product/base_vendor.mk
index c57cc3f..1e1effb 100644
--- a/target/product/base_vendor.mk
+++ b/target/product/base_vendor.mk
@@ -40,7 +40,7 @@
 
 # Base modules and settings for the vendor partition.
 PRODUCT_PACKAGES += \
-    android.hardware.cas@1.0-service \
+    android.hardware.cas@1.1-service \
     android.hardware.configstore@1.1-service \
     android.hardware.media.omx@1.0-service \
     dumpsys_vendor \
@@ -48,6 +48,7 @@
     fs_config_dirs_nonsystem \
     gralloc.default \
     group_odm \
+    group_system_ext \
     group_vendor \
     init_vendor \
     libashmemd_hidl_client \
@@ -64,6 +65,7 @@
     libril \
     libvisualizer \
     passwd_odm \
+    passwd_system_ext \
     passwd_vendor \
     selinux_policy_nonsystem \
     shell_and_utilities_vendor \
diff --git a/target/product/emulator.mk b/target/product/emulator.mk
index f6e1011..322eab4 100644
--- a/target/product/emulator.mk
+++ b/target/product/emulator.mk
@@ -53,14 +53,14 @@
 #config.disable_location=true
 
 # Enable Perfetto traced
-PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+PRODUCT_SYSTEM_EXT_PROPERTIES += \
     persist.traced.enable=1
 
 # enable Google-specific location features,
 # like NetworkLocationProvider and LocationCollector
-PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+PRODUCT_SYSTEM_EXT_PROPERTIES += \
     ro.com.google.locationfeatures=1
 
 # disable setupwizard
-PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+PRODUCT_SYSTEM_EXT_PROPERTIES += \
     ro.setupwizard.mode=DISABLED
diff --git a/target/product/emulator_vendor.mk b/target/product/emulator_vendor.mk
index 727987c..9c3be8e 100644
--- a/target/product/emulator_vendor.mk
+++ b/target/product/emulator_vendor.mk
@@ -58,14 +58,14 @@
 #config.disable_location=true
 
 # Enable Perfetto traced
-PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+PRODUCT_SYSTEM_EXT_PROPERTIES += \
     persist.traced.enable=1
 
 # enable Google-specific location features,
 # like NetworkLocationProvider and LocationCollector
-PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+PRODUCT_SYSTEM_EXT_PROPERTIES += \
     ro.com.google.locationfeatures=1
 
 # disable setupwizard
-PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \
+PRODUCT_SYSTEM_EXT_PROPERTIES += \
     ro.setupwizard.mode=DISABLED
diff --git a/target/product/go_defaults.mk b/target/product/go_defaults.mk
index cb9383f..b717486 100644
--- a/target/product/go_defaults.mk
+++ b/target/product/go_defaults.mk
@@ -17,3 +17,6 @@
 # Inherit common Android Go defaults.
 $(call inherit-product, build/make/target/product/go_defaults_common.mk)
 
+# Add the system properties.
+TARGET_SYSTEM_PROP += \
+    build/make/target/board/go_defaults.prop
diff --git a/target/product/go_defaults_512.mk b/target/product/go_defaults_512.mk
index 985912f..70d067e 100644
--- a/target/product/go_defaults_512.mk
+++ b/target/product/go_defaults_512.mk
@@ -17,12 +17,6 @@
 # Inherit common Android Go defaults.
 $(call inherit-product, build/make/target/product/go_defaults_common.mk)
 
-# 512MB specific properties.
-
-# lmkd can kill more now.
-PRODUCT_PROPERTY_OVERRIDES += \
-     ro.lmk.medium=700 \
-
-# madvise random in ART to reduce page cache thrashing.
-PRODUCT_PROPERTY_OVERRIDES += \
-     dalvik.vm.madvise-random=true
+# Add the system properties.
+TARGET_SYSTEM_PROP += \
+    build/make/target/board/go_defaults_512.prop
diff --git a/target/product/go_defaults_common.mk b/target/product/go_defaults_common.mk
index 7042f6d..7b9c783 100644
--- a/target/product/go_defaults_common.mk
+++ b/target/product/go_defaults_common.mk
@@ -14,21 +14,13 @@
 # limitations under the License.
 #
 
-# Sets Android Go recommended default values for propreties.
+# Sets Android Go recommended default product options..
 
-# Set lowram options
+
+# Set lowram options and enable traced by default
 PRODUCT_PROPERTY_OVERRIDES += \
      ro.config.low_ram=true \
-     ro.lmk.critical_upgrade=true \
-     ro.lmk.upgrade_pressure=40 \
-     ro.lmk.downgrade_pressure=60 \
-     ro.lmk.kill_heaviest_task=false \
-     ro.statsd.enable=false
-
-# set threshold to filter unused apps
-PRODUCT_PROPERTY_OVERRIDES += \
-     pm.dexopt.downgrade_after_inactive_days=10
-
+     persist.traced.enable=1 \
 
 # Speed profile services and wifi-service to reduce RAM and storage.
 PRODUCT_SYSTEM_SERVER_COMPILER_FILTER := speed-profile
@@ -42,22 +34,6 @@
 PRODUCT_USE_PROFILE_FOR_BOOT_IMAGE := true
 PRODUCT_DEX_PREOPT_BOOT_IMAGE_PROFILE_LOCATION := frameworks/base/config/boot-image-profile.txt
 
-# set the compiler filter for shared apks to quicken.
-# Rationale: speed has a lot of dex code expansion, it uses more ram and space
-# compared to quicken. Using quicken for shared APKs on Go devices may save RAM.
-# Note that this is a trade-off: here we trade clean pages for dirty pages,
-# extra cpu and battery. That's because the quicken files will be jit-ed in all
-# the processes that load of shared apk and the code cache is not shared.
-# Some notable apps that will be affected by this are gms and chrome.
-# b/65591595.
-PRODUCT_PROPERTY_OVERRIDES += \
-     pm.dexopt.shared=quicken
-
-# Default heap sizes. Allow up to 256m for large heaps to make sure a single app
-# doesn't take all of the RAM.
-PRODUCT_PROPERTY_OVERRIDES += dalvik.vm.heapgrowthlimit=128m
-PRODUCT_PROPERTY_OVERRIDES += dalvik.vm.heapsize=256m
-
 # Do not generate libartd.
 PRODUCT_ART_TARGET_INCLUDE_DEBUG_BUILD := false
 
@@ -73,3 +49,14 @@
 ifneq (,$(filter eng, $(TARGET_BUILD_VARIANT)))
   PRODUCT_DISABLE_SCUDO := true
 endif
+
+# Add the system properties.
+TARGET_SYSTEM_PROP += \
+    build/make/target/board/go_defaults_common.prop
+
+# use the go specific handheld_core_hardware.xml from frameworks
+PRODUCT_COPY_FILES += \
+    frameworks/native/data/etc/go_handheld_core_hardware.xml:$(TARGET_COPY_OUT_VENDOR)/etc/permissions/handheld_core_hardware.xml
+
+# Dedupe VNDK libraries with identical core variants.
+TARGET_VNDK_USE_CORE_VARIANT := true
diff --git a/target/product/gsi/29.txt b/target/product/gsi/29.txt
new file mode 100644
index 0000000..14faba5
--- /dev/null
+++ b/target/product/gsi/29.txt
@@ -0,0 +1,273 @@
+LLNDK: libEGL.so
+LLNDK: libGLESv1_CM.so
+LLNDK: libGLESv2.so
+LLNDK: libGLESv3.so
+LLNDK: libRS.so
+LLNDK: libandroid_net.so
+LLNDK: libc.so
+LLNDK: libcgrouprc.so
+LLNDK: libdl.so
+LLNDK: libft2.so
+LLNDK: liblog.so
+LLNDK: libm.so
+LLNDK: libmediandk.so
+LLNDK: libnativewindow.so
+LLNDK: libneuralnetworks.so
+LLNDK: libsync.so
+LLNDK: libvndksupport.so
+LLNDK: libvulkan.so
+VNDK-SP: android.hardware.graphics.common@1.0.so
+VNDK-SP: android.hardware.graphics.common@1.1.so
+VNDK-SP: android.hardware.graphics.common@1.2.so
+VNDK-SP: android.hardware.graphics.mapper@2.0.so
+VNDK-SP: android.hardware.graphics.mapper@2.1.so
+VNDK-SP: android.hardware.graphics.mapper@3.0.so
+VNDK-SP: android.hardware.renderscript@1.0.so
+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
+VNDK-SP: libbacktrace.so
+VNDK-SP: libbase.so
+VNDK-SP: libbcinfo.so
+VNDK-SP: libbinderthreadstate.so
+VNDK-SP: libblas.so
+VNDK-SP: libc++.so
+VNDK-SP: libcompiler_rt.so
+VNDK-SP: libcutils.so
+VNDK-SP: libhardware.so
+VNDK-SP: libhidlbase.so
+VNDK-SP: libhidlmemory.so
+VNDK-SP: libhidltransport.so
+VNDK-SP: libhwbinder.so
+VNDK-SP: libhwbinder_noltopgo.so
+VNDK-SP: libion.so
+VNDK-SP: libjsoncpp.so
+VNDK-SP: liblzma.so
+VNDK-SP: libprocessgroup.so
+VNDK-SP: libunwindstack.so
+VNDK-SP: libutils.so
+VNDK-SP: libutilscallstack.so
+VNDK-SP: libz.so
+VNDK-core: android.frameworks.cameraservice.common@2.0.so
+VNDK-core: android.frameworks.cameraservice.device@2.0.so
+VNDK-core: android.frameworks.cameraservice.service@2.0.so
+VNDK-core: android.frameworks.displayservice@1.0.so
+VNDK-core: android.frameworks.schedulerservice@1.0.so
+VNDK-core: android.frameworks.sensorservice@1.0.so
+VNDK-core: android.frameworks.stats@1.0.so
+VNDK-core: android.frameworks.vr.composer@1.0.so
+VNDK-core: android.hardware.atrace@1.0.so
+VNDK-core: android.hardware.audio.common@2.0.so
+VNDK-core: android.hardware.audio.common@4.0.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.face@1.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
+VNDK-core: android.hardware.broadcastradio@1.1.so
+VNDK-core: android.hardware.broadcastradio@2.0.so
+VNDK-core: android.hardware.camera.common@1.0.so
+VNDK-core: android.hardware.camera.device@1.0.so
+VNDK-core: android.hardware.camera.device@3.2.so
+VNDK-core: android.hardware.camera.device@3.3.so
+VNDK-core: android.hardware.camera.device@3.4.so
+VNDK-core: android.hardware.camera.device@3.5.so
+VNDK-core: android.hardware.camera.metadata@3.2.so
+VNDK-core: android.hardware.camera.metadata@3.3.so
+VNDK-core: android.hardware.camera.metadata@3.4.so
+VNDK-core: android.hardware.camera.provider@2.4.so
+VNDK-core: android.hardware.camera.provider@2.5.so
+VNDK-core: android.hardware.cas.native@1.0.so
+VNDK-core: android.hardware.cas@1.0.so
+VNDK-core: android.hardware.cas@1.1.so
+VNDK-core: android.hardware.configstore-utils.so
+VNDK-core: android.hardware.configstore@1.0.so
+VNDK-core: android.hardware.configstore@1.1.so
+VNDK-core: android.hardware.confirmationui-support-lib.so
+VNDK-core: android.hardware.confirmationui@1.0.so
+VNDK-core: android.hardware.contexthub@1.0.so
+VNDK-core: android.hardware.drm@1.0.so
+VNDK-core: android.hardware.drm@1.1.so
+VNDK-core: android.hardware.drm@1.2.so
+VNDK-core: android.hardware.dumpstate@1.0.so
+VNDK-core: android.hardware.fastboot@1.0.so
+VNDK-core: android.hardware.gatekeeper@1.0.so
+VNDK-core: android.hardware.gnss.measurement_corrections@1.0.so
+VNDK-core: android.hardware.gnss.visibility_control@1.0.so
+VNDK-core: android.hardware.gnss@1.0.so
+VNDK-core: android.hardware.gnss@1.1.so
+VNDK-core: android.hardware.gnss@2.0.so
+VNDK-core: android.hardware.graphics.allocator@2.0.so
+VNDK-core: android.hardware.graphics.allocator@3.0.so
+VNDK-core: android.hardware.graphics.bufferqueue@1.0.so
+VNDK-core: android.hardware.graphics.bufferqueue@2.0.so
+VNDK-core: android.hardware.graphics.composer@2.1.so
+VNDK-core: android.hardware.graphics.composer@2.2.so
+VNDK-core: android.hardware.graphics.composer@2.3.so
+VNDK-core: android.hardware.health.storage@1.0.so
+VNDK-core: android.hardware.health@1.0.so
+VNDK-core: android.hardware.health@2.0.so
+VNDK-core: android.hardware.input.classifier@1.0.so
+VNDK-core: android.hardware.input.common@1.0.so
+VNDK-core: android.hardware.ir@1.0.so
+VNDK-core: android.hardware.keymaster@3.0.so
+VNDK-core: android.hardware.keymaster@4.0.so
+VNDK-core: android.hardware.light@2.0.so
+VNDK-core: android.hardware.media.bufferpool@1.0.so
+VNDK-core: android.hardware.media.bufferpool@2.0.so
+VNDK-core: android.hardware.media.c2@1.0.so
+VNDK-core: android.hardware.media.omx@1.0.so
+VNDK-core: android.hardware.media@1.0.so
+VNDK-core: android.hardware.memtrack@1.0.so
+VNDK-core: android.hardware.neuralnetworks@1.0.so
+VNDK-core: android.hardware.neuralnetworks@1.1.so
+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.secure_element@1.1.so
+VNDK-core: android.hardware.sensors@1.0.so
+VNDK-core: android.hardware.sensors@2.0.so
+VNDK-core: android.hardware.soundtrigger@2.0.so
+VNDK-core: android.hardware.soundtrigger@2.0-core.so
+VNDK-core: android.hardware.soundtrigger@2.1.so
+VNDK-core: android.hardware.soundtrigger@2.2.so
+VNDK-core: android.hardware.tetheroffload.config@1.0.so
+VNDK-core: android.hardware.tetheroffload.control@1.0.so
+VNDK-core: android.hardware.thermal@1.0.so
+VNDK-core: android.hardware.thermal@1.1.so
+VNDK-core: android.hardware.thermal@2.0.so
+VNDK-core: android.hardware.tv.cec@1.0.so
+VNDK-core: android.hardware.tv.cec@2.0.so
+VNDK-core: android.hardware.tv.input@1.0.so
+VNDK-core: android.hardware.usb.gadget@1.0.so
+VNDK-core: android.hardware.usb@1.0.so
+VNDK-core: android.hardware.usb@1.1.so
+VNDK-core: android.hardware.usb@1.2.so
+VNDK-core: android.hardware.vibrator@1.0.so
+VNDK-core: android.hardware.vibrator@1.1.so
+VNDK-core: android.hardware.vibrator@1.2.so
+VNDK-core: android.hardware.vibrator@1.3.so
+VNDK-core: android.hardware.vr@1.0.so
+VNDK-core: android.hardware.weaver@1.0.so
+VNDK-core: android.hardware.wifi.hostapd@1.0.so
+VNDK-core: android.hardware.wifi.hostapd@1.1.so
+VNDK-core: android.hardware.wifi.offload@1.0.so
+VNDK-core: android.hardware.wifi.supplicant@1.0.so
+VNDK-core: android.hardware.wifi.supplicant@1.1.so
+VNDK-core: android.hardware.wifi.supplicant@1.2.so
+VNDK-core: android.hardware.wifi@1.0.so
+VNDK-core: android.hardware.wifi@1.1.so
+VNDK-core: android.hardware.wifi@1.2.so
+VNDK-core: android.hardware.wifi@1.3.so
+VNDK-core: android.hidl.allocator@1.0.so
+VNDK-core: android.hidl.memory.block@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
+VNDK-core: android.system.net.netd@1.1.so
+VNDK-core: android.system.suspend@1.0.so
+VNDK-core: android.system.wifi.keystore@1.0.so
+VNDK-core: libadf.so
+VNDK-core: libaudioroute.so
+VNDK-core: libaudioutils.so
+VNDK-core: libbinder.so
+VNDK-core: libcamera_metadata.so
+VNDK-core: libcap.so
+VNDK-core: libcn-cbor.so
+VNDK-core: libcodec2.so
+VNDK-core: libcrypto.so
+VNDK-core: libcrypto_utils.so
+VNDK-core: libcurl.so
+VNDK-core: libdiskconfig.so
+VNDK-core: libdumpstateutil.so
+VNDK-core: libevent.so
+VNDK-core: libexif.so
+VNDK-core: libexpat.so
+VNDK-core: libfmq.so
+VNDK-core: libgatekeeper.so
+VNDK-core: libgui.so
+VNDK-core: libhardware_legacy.so
+VNDK-core: libhidlallocatorutils.so
+VNDK-core: libhidlcache.so
+VNDK-core: libjpeg.so
+VNDK-core: libkeymaster_messages.so
+VNDK-core: libkeymaster_portable.so
+VNDK-core: libldacBT_abr.so
+VNDK-core: libldacBT_enc.so
+VNDK-core: liblz4.so
+VNDK-core: libmedia_helper.so
+VNDK-core: libmedia_omx.so
+VNDK-core: libmemtrack.so
+VNDK-core: libminijail.so
+VNDK-core: libmkbootimg_abi_check.so
+VNDK-core: libnetutils.so
+VNDK-core: libnl.so
+VNDK-core: libpcre2.so
+VNDK-core: libpiex.so
+VNDK-core: libpng.so
+VNDK-core: libpower.so
+VNDK-core: libprocinfo.so
+VNDK-core: libprotobuf-cpp-full.so
+VNDK-core: libprotobuf-cpp-lite.so
+VNDK-core: libpuresoftkeymasterdevice.so
+VNDK-core: libradio_metadata.so
+VNDK-core: libselinux.so
+VNDK-core: libsoftkeymasterdevice.so
+VNDK-core: libspeexresampler.so
+VNDK-core: libsqlite.so
+VNDK-core: libssl.so
+VNDK-core: libstagefright_bufferpool@2.0.so
+VNDK-core: libstagefright_bufferqueue_helper.so
+VNDK-core: libstagefright_foundation.so
+VNDK-core: libstagefright_omx.so
+VNDK-core: libstagefright_omx_utils.so
+VNDK-core: libstagefright_xmlparser.so
+VNDK-core: libsysutils.so
+VNDK-core: libtinyalsa.so
+VNDK-core: libtinyxml2.so
+VNDK-core: libui.so
+VNDK-core: libusbhost.so
+VNDK-core: libwifi-system-iface.so
+VNDK-core: libxml2.so
+VNDK-core: libyuv.so
+VNDK-core: libziparchive.so
+VNDK-private: libbacktrace.so
+VNDK-private: libbinderthreadstate.so
+VNDK-private: libblas.so
+VNDK-private: libcompiler_rt.so
+VNDK-private: libft2.so
+VNDK-private: libgui.so
diff --git a/target/product/gsi/Android.mk b/target/product/gsi/Android.mk
index 1ef124b..54f41ca 100644
--- a/target/product/gsi/Android.mk
+++ b/target/product/gsi/Android.mk
@@ -120,13 +120,13 @@
 
 $(check-vndk-abi-dump-list-timestamp): $(VNDK_ABI_DUMPS) $(NDK_ABI_DUMPS)
 	$(eval added_vndk_abi_dumps := $(strip $(sort $(filter-out \
-	  $(addsuffix .so.lsdump,$(VNDK_SAMEPROCESS_LIBRARIES) $(VNDK_CORE_LIBRARIES)), \
+	  $(addsuffix .so.lsdump,$(filter-out $(NDK_MIGRATED_LIBS) $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES) $(VNDK_SAMEPROCESS_LIBRARIES) $(VNDK_CORE_LIBRARIES))), \
 	  $(notdir $(VNDK_ABI_DUMPS))))))
 	$(if $(added_vndk_abi_dumps), \
 	  echo -e "Found ABI reference dumps for non-VNDK libraries. Run \`find \$${ANDROID_BUILD_TOP}/$(VNDK_ABI_DUMP_DIR) '(' -name $(subst $(space), -or -name ,$(added_vndk_abi_dumps)) ')' -delete\` to delete the dumps.")
 
 	$(eval added_ndk_abi_dumps := $(strip $(sort $(filter-out \
-	  $(addsuffix .so.lsdump,$(NDK_MIGRATED_LIBS) $(LLNDK_LIBRARIES)), \
+	  $(addsuffix .so.lsdump,$(NDK_MIGRATED_LIBS)), \
 	  $(notdir $(NDK_ABI_DUMPS))))))
 	$(if $(added_ndk_abi_dumps), \
 	  echo -e "Found ABI reference dumps for non-NDK libraries. Run \`find \$${ANDROID_BUILD_TOP}/$(NDK_ABI_DUMP_DIR) '(' -name $(subst $(space), -or -name ,$(added_ndk_abi_dumps)) ')' -delete\` to delete the dumps.")
@@ -144,7 +144,7 @@
 LOCAL_MODULE := vndk_package
 # Filter LLNDK libs moved to APEX to avoid pulling them into /system/LIB
 LOCAL_REQUIRED_MODULES := \
-    $(filter-out $(LLNDK_MOVED_TO_APEX_LIBRARIES),$(LLNDK_LIBRARIES)))
+    $(filter-out $(LLNDK_MOVED_TO_APEX_LIBRARIES),$(LLNDK_LIBRARIES))
 
 ifneq ($(TARGET_SKIP_CURRENT_VNDK),true)
 LOCAL_REQUIRED_MODULES += \
@@ -169,3 +169,38 @@
 include $(BUILD_PHONY_PACKAGE)
 
 endif # BOARD_VNDK_VERSION is set
+
+#####################################################################
+# skip_mount.cfg, read by init to skip mounting some partitions when GSI is used.
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := gsi_skip_mount.cfg
+LOCAL_MODULE_STEM := skip_mount.cfg
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+LOCAL_MODULE_CLASS := ETC
+LOCAL_SYSTEM_EXT_MODULE := true
+LOCAL_MODULE_RELATIVE_PATH := init/config
+
+# Adds a symlink under /system/etc/init/config pointing to /system/system_ext/etc/init/config
+# because first-stage init in Android 10.0 will read the skip_mount.cfg from /system/etc/* after
+# chroot /system.
+# TODO: remove this symlink when no need to support new GSI on Android 10.
+# The actual file needs to be under /system/system_ext because it's GSI-specific and does not
+# belong to core CSI.
+LOCAL_POST_INSTALL_CMD := \
+    mkdir -p $(TARGET_OUT)/etc/init; \
+    ln -sf /system/system_ext/etc/init/config $(TARGET_OUT)/etc/init/config
+
+include $(BUILD_PREBUILT)
+
+#####################################################################
+# init.gsi.rc, GSI-specific init script.
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := init.gsi.rc
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+LOCAL_MODULE_CLASS := ETC
+LOCAL_SYSTEM_EXT_MODULE := true
+LOCAL_MODULE_RELATIVE_PATH := init
+
+include $(BUILD_PREBUILT)
diff --git a/target/product/gsi/current.txt b/target/product/gsi/current.txt
index d954e9f..a11531e 100644
--- a/target/product/gsi/current.txt
+++ b/target/product/gsi/current.txt
@@ -19,8 +19,10 @@
 LLNDK: libvulkan.so
 VNDK-SP: android.hardware.graphics.common@1.0.so
 VNDK-SP: android.hardware.graphics.common@1.1.so
+VNDK-SP: android.hardware.graphics.common@1.2.so
 VNDK-SP: android.hardware.graphics.mapper@2.0.so
 VNDK-SP: android.hardware.graphics.mapper@2.1.so
+VNDK-SP: android.hardware.graphics.mapper@3.0.so
 VNDK-SP: android.hardware.renderscript@1.0.so
 VNDK-SP: android.hidl.memory.token@1.0.so
 VNDK-SP: android.hidl.memory@1.0.so
@@ -42,7 +44,6 @@
 VNDK-SP: libhidlmemory.so
 VNDK-SP: libhidltransport.so
 VNDK-SP: libhwbinder.so
-VNDK-SP: libhwbinder_noltopgo.so
 VNDK-SP: libion.so
 VNDK-SP: libjsoncpp.so
 VNDK-SP: liblzma.so
@@ -51,16 +52,17 @@
 VNDK-SP: libutils.so
 VNDK-SP: libutilscallstack.so
 VNDK-SP: libz.so
+VNDK-core: android.frameworks.cameraservice.common@2.0.so
+VNDK-core: android.frameworks.cameraservice.device@2.0.so
+VNDK-core: android.frameworks.cameraservice.service@2.0.so
 VNDK-core: android.frameworks.displayservice@1.0.so
 VNDK-core: android.frameworks.schedulerservice@1.0.so
 VNDK-core: android.frameworks.sensorservice@1.0.so
+VNDK-core: android.frameworks.stats@1.0.so
 VNDK-core: android.frameworks.vr.composer@1.0.so
 VNDK-core: android.hardware.atrace@1.0.so
-VNDK-core: android.hardware.audio.common-util.so
 VNDK-core: android.hardware.audio.common@2.0.so
-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
@@ -72,6 +74,7 @@
 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.face@1.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
@@ -85,11 +88,15 @@
 VNDK-core: android.hardware.camera.device@3.2.so
 VNDK-core: android.hardware.camera.device@3.3.so
 VNDK-core: android.hardware.camera.device@3.4.so
+VNDK-core: android.hardware.camera.device@3.5.so
 VNDK-core: android.hardware.camera.metadata@3.2.so
 VNDK-core: android.hardware.camera.metadata@3.3.so
+VNDK-core: android.hardware.camera.metadata@3.4.so
 VNDK-core: android.hardware.camera.provider@2.4.so
+VNDK-core: android.hardware.camera.provider@2.5.so
 VNDK-core: android.hardware.cas.native@1.0.so
 VNDK-core: android.hardware.cas@1.0.so
+VNDK-core: android.hardware.cas@1.1.so
 VNDK-core: android.hardware.configstore-utils.so
 VNDK-core: android.hardware.configstore@1.0.so
 VNDK-core: android.hardware.configstore@1.1.so
@@ -98,23 +105,34 @@
 VNDK-core: android.hardware.contexthub@1.0.so
 VNDK-core: android.hardware.drm@1.0.so
 VNDK-core: android.hardware.drm@1.1.so
+VNDK-core: android.hardware.drm@1.2.so
 VNDK-core: android.hardware.dumpstate@1.0.so
 VNDK-core: android.hardware.fastboot@1.0.so
 VNDK-core: android.hardware.gatekeeper@1.0.so
+VNDK-core: android.hardware.gnss.measurement_corrections@1.0.so
+VNDK-core: android.hardware.gnss.visibility_control@1.0.so
 VNDK-core: android.hardware.gnss@1.0.so
 VNDK-core: android.hardware.gnss@1.1.so
+VNDK-core: android.hardware.gnss@2.0.so
 VNDK-core: android.hardware.graphics.allocator@2.0.so
+VNDK-core: android.hardware.graphics.allocator@3.0.so
 VNDK-core: android.hardware.graphics.bufferqueue@1.0.so
+VNDK-core: android.hardware.graphics.bufferqueue@2.0.so
 VNDK-core: android.hardware.graphics.composer@2.1.so
 VNDK-core: android.hardware.graphics.composer@2.2.so
+VNDK-core: android.hardware.graphics.composer@2.3.so
 VNDK-core: android.hardware.health.storage@1.0.so
 VNDK-core: android.hardware.health@1.0.so
 VNDK-core: android.hardware.health@2.0.so
+VNDK-core: android.hardware.input.classifier@1.0.so
+VNDK-core: android.hardware.input.common@1.0.so
 VNDK-core: android.hardware.ir@1.0.so
 VNDK-core: android.hardware.keymaster@3.0.so
 VNDK-core: android.hardware.keymaster@4.0.so
 VNDK-core: android.hardware.light@2.0.so
 VNDK-core: android.hardware.media.bufferpool@1.0.so
+VNDK-core: android.hardware.media.bufferpool@2.0.so
+VNDK-core: android.hardware.media.c2@1.0.so
 VNDK-core: android.hardware.media.omx@1.0.so
 VNDK-core: android.hardware.media@1.0.so
 VNDK-core: android.hardware.memtrack@1.0.so
@@ -142,30 +160,40 @@
 VNDK-core: android.hardware.secure_element@1.0.so
 VNDK-core: android.hardware.secure_element@1.1.so
 VNDK-core: android.hardware.sensors@1.0.so
+VNDK-core: android.hardware.sensors@2.0.so
 VNDK-core: android.hardware.soundtrigger@2.0.so
 VNDK-core: android.hardware.soundtrigger@2.0-core.so
 VNDK-core: android.hardware.soundtrigger@2.1.so
+VNDK-core: android.hardware.soundtrigger@2.2.so
 VNDK-core: android.hardware.tetheroffload.config@1.0.so
 VNDK-core: android.hardware.tetheroffload.control@1.0.so
 VNDK-core: android.hardware.thermal@1.0.so
 VNDK-core: android.hardware.thermal@1.1.so
+VNDK-core: android.hardware.thermal@2.0.so
 VNDK-core: android.hardware.tv.cec@1.0.so
+VNDK-core: android.hardware.tv.cec@2.0.so
 VNDK-core: android.hardware.tv.input@1.0.so
+VNDK-core: android.hardware.tv.tuner@1.0.so
 VNDK-core: android.hardware.usb.gadget@1.0.so
 VNDK-core: android.hardware.usb@1.0.so
 VNDK-core: android.hardware.usb@1.1.so
+VNDK-core: android.hardware.usb@1.2.so
 VNDK-core: android.hardware.vibrator@1.0.so
 VNDK-core: android.hardware.vibrator@1.1.so
 VNDK-core: android.hardware.vibrator@1.2.so
+VNDK-core: android.hardware.vibrator@1.3.so
 VNDK-core: android.hardware.vr@1.0.so
 VNDK-core: android.hardware.weaver@1.0.so
 VNDK-core: android.hardware.wifi.hostapd@1.0.so
+VNDK-core: android.hardware.wifi.hostapd@1.1.so
 VNDK-core: android.hardware.wifi.offload@1.0.so
 VNDK-core: android.hardware.wifi.supplicant@1.0.so
 VNDK-core: android.hardware.wifi.supplicant@1.1.so
+VNDK-core: android.hardware.wifi.supplicant@1.2.so
 VNDK-core: android.hardware.wifi@1.0.so
 VNDK-core: android.hardware.wifi@1.1.so
 VNDK-core: android.hardware.wifi@1.2.so
+VNDK-core: android.hardware.wifi@1.3.so
 VNDK-core: android.hidl.allocator@1.0.so
 VNDK-core: android.hidl.memory.block@1.0.so
 VNDK-core: android.hidl.token@1.0.so
@@ -182,6 +210,7 @@
 VNDK-core: libcamera_metadata.so
 VNDK-core: libcap.so
 VNDK-core: libcn-cbor.so
+VNDK-core: libcodec2.so
 VNDK-core: libcrypto.so
 VNDK-core: libcrypto_utils.so
 VNDK-core: libcurl.so
@@ -208,7 +237,6 @@
 VNDK-core: libmkbootimg_abi_check.so
 VNDK-core: libnetutils.so
 VNDK-core: libnl.so
-VNDK-core: libopus.so
 VNDK-core: libpcre2.so
 VNDK-core: libpiex.so
 VNDK-core: libpng.so
@@ -223,41 +251,17 @@
 VNDK-core: libspeexresampler.so
 VNDK-core: libsqlite.so
 VNDK-core: libssl.so
-VNDK-core: libstagefright_amrnb_common.so
+VNDK-core: libstagefright_bufferpool@2.0.so
 VNDK-core: libstagefright_bufferqueue_helper.so
-VNDK-core: libstagefright_enc_common.so
-VNDK-core: libstagefright_flacdec.so
 VNDK-core: libstagefright_foundation.so
 VNDK-core: libstagefright_omx.so
 VNDK-core: libstagefright_omx_utils.so
-VNDK-core: libstagefright_soft_aacdec.so
-VNDK-core: libstagefright_soft_aacenc.so
-VNDK-core: libstagefright_soft_amrdec.so
-VNDK-core: libstagefright_soft_amrnbenc.so
-VNDK-core: libstagefright_soft_amrwbenc.so
-VNDK-core: libstagefright_soft_avcdec.so
-VNDK-core: libstagefright_soft_avcenc.so
-VNDK-core: libstagefright_soft_flacdec.so
-VNDK-core: libstagefright_soft_flacenc.so
-VNDK-core: libstagefright_soft_g711dec.so
-VNDK-core: libstagefright_soft_gsmdec.so
-VNDK-core: libstagefright_soft_hevcdec.so
-VNDK-core: libstagefright_soft_mp3dec.so
-VNDK-core: libstagefright_soft_mpeg2dec.so
-VNDK-core: libstagefright_soft_mpeg4dec.so
-VNDK-core: libstagefright_soft_mpeg4enc.so
-VNDK-core: libstagefright_soft_opusdec.so
-VNDK-core: libstagefright_soft_rawdec.so
-VNDK-core: libstagefright_soft_vorbisdec.so
-VNDK-core: libstagefright_soft_vpxdec.so
-VNDK-core: libstagefright_soft_vpxenc.so
 VNDK-core: libstagefright_xmlparser.so
 VNDK-core: libsysutils.so
 VNDK-core: libtinyalsa.so
 VNDK-core: libtinyxml2.so
 VNDK-core: libui.so
 VNDK-core: libusbhost.so
-VNDK-core: libvorbisidec.so
 VNDK-core: libwifi-system-iface.so
 VNDK-core: libxml2.so
 VNDK-core: libyuv.so
diff --git a/target/product/gsi/skip_mount.cfg b/target/product/gsi/gsi_skip_mount.cfg
similarity index 100%
rename from target/product/gsi/skip_mount.cfg
rename to target/product/gsi/gsi_skip_mount.cfg
diff --git a/target/product/gsi_common.mk b/target/product/gsi_common.mk
index 1b5cd55..bfecc95 100644
--- a/target/product/gsi_common.mk
+++ b/target/product/gsi_common.mk
@@ -50,11 +50,6 @@
 # Some GSI builds enable dexpreopt, whitelist these preopt files
 PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST += %.odex %.vdex %.art
 
-# Exclude GSI specific files
-PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST += \
-    system/etc/init/config/skip_mount.cfg \
-    system/etc/init/init.gsi.rc \
-
 # Exclude all files under system/product and system/system_ext
 PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST += \
     system/product/% \
@@ -71,9 +66,9 @@
 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 \
+PRODUCT_PACKAGES += \
+    gsi_skip_mount.cfg \
+    init.gsi.rc
 
 # Support addtional P vendor interface
 PRODUCT_EXTRA_VNDK_VERSIONS := 28
diff --git a/target/product/gsi_release.mk b/target/product/gsi_release.mk
index 4c471db..cab3916 100644
--- a/target/product/gsi_release.mk
+++ b/target/product/gsi_release.mk
@@ -24,11 +24,6 @@
 # - etc.
 #
 
-# Exclude GSI specific files
-PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST += \
-    system/etc/init/config/skip_mount.cfg \
-    system/etc/init/init.gsi.rc \
-
 # Exclude all files under system/product and system/system_ext
 PRODUCT_ARTIFACT_PATH_REQUIREMENT_WHITELIST += \
     system/product/% \
@@ -50,12 +45,12 @@
 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 \
+PRODUCT_PACKAGES += \
+    gsi_skip_mount.cfg \
+    init.gsi.rc
 
-# Support addtional P VNDK packages
-PRODUCT_EXTRA_VNDK_VERSIONS := 28
+# Support addtional P and Q VNDK packages
+PRODUCT_EXTRA_VNDK_VERSIONS := 28 29
 
 # The 64 bits GSI build targets inhiert core_64_bit.mk to enable 64 bits and
 # include the init.zygote64_32.rc.
diff --git a/target/product/handheld_product.mk b/target/product/handheld_product.mk
index 758fa9b..0d100b2 100644
--- a/target/product/handheld_product.mk
+++ b/target/product/handheld_product.mk
@@ -40,3 +40,7 @@
     StorageManager \
     SystemUI \
     WallpaperCropper \
+    frameworks-base-overlays
+
+PRODUCT_PACKAGES_DEBUG += \
+    frameworks-base-overlays-debug
diff --git a/target/product/handheld_system.mk b/target/product/handheld_system.mk
index a4dd6d7..6463a54 100644
--- a/target/product/handheld_system.mk
+++ b/target/product/handheld_system.mk
@@ -24,6 +24,7 @@
 $(call inherit-product-if-exists, external/google-fonts/carrois-gothic-sc/fonts.mk)
 $(call inherit-product-if-exists, external/google-fonts/coming-soon/fonts.mk)
 $(call inherit-product-if-exists, external/google-fonts/cutive-mono/fonts.mk)
+$(call inherit-product-if-exists, external/google-fonts/source-sans-pro/fonts.mk)
 $(call inherit-product-if-exists, external/noto-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/roboto-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/hyphenation-patterns/patterns.mk)
@@ -56,6 +57,7 @@
     MtpDocumentsProvider \
     MusicFX \
     NfcNci \
+    OsuLogin \
     PacProcessor \
     PrintRecommendationService \
     PrintSpooler \
diff --git a/target/product/handheld_vendor.mk b/target/product/handheld_vendor.mk
index ca7760a..cb7cf74 100644
--- a/target/product/handheld_vendor.mk
+++ b/target/product/handheld_vendor.mk
@@ -23,10 +23,7 @@
 # /vendor packages
 PRODUCT_PACKAGES += \
     audio.primary.default \
-    DisplayCutoutEmulationCornerOverlay \
-    DisplayCutoutEmulationDoubleOverlay \
-    DisplayCutoutEmulationTallOverlay \
     local_time.default \
     power.default \
-    SysuiDarkThemeOverlay \
     vibrator.default \
+
diff --git a/target/product/mainline_arm64.mk b/target/product/mainline_arm64.mk
index c098c9f..6d998d6 100644
--- a/target/product/mainline_arm64.mk
+++ b/target/product/mainline_arm64.mk
@@ -28,46 +28,9 @@
 PRODUCT_ENFORCE_ARTIFACT_PATH_REQUIREMENTS := relaxed
 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
+# Modules that should probably 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/DeskClock/oat/arm64/DeskClock.odex \
-  system/app/DeskClock/oat/arm64/DeskClock.vdex \
-  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/QuickSearchBox/QuickSearchBox.apk \
-  system/app/webview/webview.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/CarrierConfig/oat/arm64/CarrierConfig.odex \
-  system/priv-app/CarrierConfig/oat/arm64/CarrierConfig.vdex \
-  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 8bcc212..43bc45f 100644
--- a/target/product/mainline_system.mk
+++ b/target/product/mainline_system.mk
@@ -18,8 +18,6 @@
 $(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)
-# Enable updating of APEXes
-#$(call inherit-product, $(SRC_TARGET_DIR)/product/updatable_apex.mk)
 # Add adb keys to debuggable AOSP builds (if they exist)
 $(call inherit-product-if-exists, vendor/google/security/adb/vendor_key.mk)
 
@@ -73,6 +71,8 @@
     android.hardware.radio@1.0 \
     android.hardware.radio@1.1 \
     android.hardware.radio@1.2 \
+    android.hardware.radio@1.3 \
+    android.hardware.radio@1.4 \
     android.hardware.radio.config@1.0 \
     android.hardware.radio.deprecated@1.0 \
     android.hardware.secure_element@1.0 \
@@ -85,6 +85,11 @@
     libnl \
     libprotobuf-cpp-full \
 
+# Camera service uses 'libdepthphoto' for adding dynamic depth
+# metadata inside depth jpegs.
+PRODUCT_PACKAGES += \
+    libdepthphoto \
+
 PRODUCT_PACKAGES_DEBUG += \
     avbctl \
     bootctl \
@@ -100,6 +105,9 @@
 # Enable dynamic partition size
 PRODUCT_USE_DYNAMIC_PARTITION_SIZE := true
 
+PRODUCT_PACKAGES += \
+    com.android.apex.cts.shim.v1_prebuilt
+
 PRODUCT_NAME := mainline_system
 PRODUCT_BRAND := generic
 
diff --git a/target/product/media_system.mk b/target/product/media_system.mk
index 2ba7005..5c0902d 100644
--- a/target/product/media_system.mk
+++ b/target/product/media_system.mk
@@ -31,31 +31,9 @@
     fsck.f2fs \
     HTMLViewer \
     libfilterpack_imageproc \
-    libstagefright_soft_aacdec \
-    libstagefright_soft_aacenc \
-    libstagefright_soft_amrdec \
-    libstagefright_soft_amrnbenc \
-    libstagefright_soft_amrwbenc \
-    libstagefright_soft_avcdec \
-    libstagefright_soft_avcenc \
-    libstagefright_soft_flacdec \
-    libstagefright_soft_flacenc \
-    libstagefright_soft_g711dec \
-    libstagefright_soft_gsmdec \
-    libstagefright_soft_hevcdec \
-    libstagefright_soft_mp3dec \
-    libstagefright_soft_mpeg2dec \
-    libstagefright_soft_mpeg4dec \
-    libstagefright_soft_mpeg4enc \
-    libstagefright_soft_opusdec \
-    libstagefright_soft_rawdec \
-    libstagefright_soft_vorbisdec \
-    libstagefright_soft_vpxdec \
-    libstagefright_soft_vpxenc \
     libwebviewchromium_loader \
     libwebviewchromium_plat_support \
     make_f2fs \
-    PackageInstaller \
     requestsync \
     StatementService \
     vndk_snapshot_package \
diff --git a/target/product/profile_boot_common.mk b/target/product/profile_boot_common.mk
index fc19954..a40b3e9 100644
--- a/target/product/profile_boot_common.mk
+++ b/target/product/profile_boot_common.mk
@@ -20,29 +20,11 @@
 # Ideally we would just generate an empty boot.art but we don't have the build
 # support to separate the image from the compile code.
 PRODUCT_DEX_PREOPT_BOOT_IMAGE_PROFILE_LOCATION := build/make/target/product/empty-profile
-PRODUCT_DEX_PREOPT_BOOT_FLAGS := --count-hotness-in-compiled-code
 DEX_PREOPT_DEFAULT := nostripping
 
-# Disable uncompressing priv apps so that there is enough space to build the system partition.
-DONT_UNCOMPRESS_PRIV_APPS_DEXS := true
-
-# Use an empty preloaded-classes list.
-PRODUCT_COPY_FILES += \
-    build/make/target/product/empty-preloaded-classes:system/etc/preloaded-classes
-
 # Boot image property overrides.
 PRODUCT_PROPERTY_OVERRIDES += \
-    dalvik.vm.jitinitialsize=32m \
-    dalvik.vm.jitmaxsize=32m \
-    dalvik.vm.usejitprofiles=true \
-    dalvik.vm.hot-startup-method-samples=256 \
     dalvik.vm.profilesystemserver=true \
-    dalvik.vm.profilebootimage=true
-
-# Use speed compiler filter since system server doesn't have JIT.
-PRODUCT_DEX_PREOPT_BOOT_FLAGS += --compiler-filter=speed
-# System server is speed compiled and doesn't have a separate preopt flag,
-# so we enable hotness in compiled code for everything.
-PRODUCT_DEX_PREOPT_DEFAULT_FLAGS := --count-hotness-in-compiled-code
+    dalvik.vm.profilebootclasspath=true
 
 PRODUCT_DIST_BOOT_AND_SYSTEM_JARS := true
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
index 5db32f2..581a72b 100644
--- a/target/product/runtime_libart.mk
+++ b/target/product/runtime_libart.mk
@@ -33,9 +33,12 @@
 PRODUCT_PACKAGES += \
     ext \
 
-# Android Runtime APEX module.
+# Runtime (Bionic) APEX module.
 PRODUCT_PACKAGES += com.android.runtime
-PRODUCT_HOST_PACKAGES += com.android.runtime
+
+# ART APEX module.
+PRODUCT_PACKAGES += com.android.art
+PRODUCT_HOST_PACKAGES += com.android.art
 
 # Certificates.
 PRODUCT_PACKAGES += \
diff --git a/target/product/sdk_phone_arm64.mk b/target/product/sdk_phone_arm64.mk
index 96f0bfd..ad72633 100644
--- a/target/product/sdk_phone_arm64.mk
+++ b/target/product/sdk_phone_arm64.mk
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+QEMU_USE_SYSTEM_EXT_PARTITIONS := true
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_arm64.mk)
 
diff --git a/target/product/sdk_phone_armv7.mk b/target/product/sdk_phone_armv7.mk
index 04d8d6a..77b8b50 100644
--- a/target/product/sdk_phone_armv7.mk
+++ b/target/product/sdk_phone_armv7.mk
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+QEMU_USE_SYSTEM_EXT_PARTITIONS := true
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_arm.mk)
 
diff --git a/target/product/sdk_phone_x86.mk b/target/product/sdk_phone_x86.mk
index b34e5b6..b3e205c 100644
--- a/target/product/sdk_phone_x86.mk
+++ b/target/product/sdk_phone_x86.mk
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+QEMU_USE_SYSTEM_EXT_PARTITIONS := true
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_x86.mk)
 
diff --git a/target/product/sdk_phone_x86_64.mk b/target/product/sdk_phone_x86_64.mk
index 37c078e..8062459 100644
--- a/target/product/sdk_phone_x86_64.mk
+++ b/target/product/sdk_phone_x86_64.mk
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+QEMU_USE_SYSTEM_EXT_PARTITIONS := true
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_x86_64.mk)
 
diff --git a/target/product/updatable_apex.mk b/target/product/updatable_apex.mk
index 038f66e..a9f4baf 100644
--- a/target/product/updatable_apex.mk
+++ b/target/product/updatable_apex.mk
@@ -17,5 +17,4 @@
 # Inherit this when the target needs to support updating APEXes
 
 PRODUCT_PROPERTY_OVERRIDES := ro.apex.updatable=true
-PRODUCT_PACKAGES := com.android.apex.cts.shim.v1_prebuilt
 TARGET_FLATTEN_APEX := false
diff --git a/target/product/virtual_ab_ota.mk b/target/product/virtual_ab_ota.mk
new file mode 100644
index 0000000..c00b0ed
--- /dev/null
+++ b/target/product/virtual_ab_ota.mk
@@ -0,0 +1,19 @@
+#
+# 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.
+#
+
+PRODUCT_VIRTUAL_AB_OTA := true
+
+PRODUCT_PRODUCT_PROPERTIES += ro.virtual_ab.enabled=true
diff --git a/target/product/virtual_ab_ota_retrofit.mk b/target/product/virtual_ab_ota_retrofit.mk
new file mode 100644
index 0000000..b492fad
--- /dev/null
+++ b/target/product/virtual_ab_ota_retrofit.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.
+#
+
+$(call inherit-product, $(SRC_TARGET_DIR)/product/virtual_ab_ota.mk)
+
+PRODUCT_VIRTUAL_AB_OTA_RETROFIT := true
+
+PRODUCT_PRODUCT_PROPERTIES += ro.virtual_ab.retrofit=true
diff --git a/tools/auto_gen_test_config_test.py b/tools/auto_gen_test_config_test.py
index e68c27f..51a8583 100644
--- a/tools/auto_gen_test_config_test.py
+++ b/tools/auto_gen_test_config_test.py
@@ -34,7 +34,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.android.my.tests.x">
     <instrumentation
-        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:name="androidx.test.runner.AndroidJUnitRunner"
         android:targetPackage="com.android.my.tests" />
 </manifest>
 """
@@ -72,7 +72,7 @@
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="com.android.my.tests.x" />
-        <option name="runner" value="android.support.test.runner.AndroidJUnitRunner" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
     </test>
 </configuration>
 """
diff --git a/tools/dump-package-stats b/tools/dump-package-stats
deleted file mode 100755
index 7814368..0000000
--- a/tools/dump-package-stats
+++ /dev/null
@@ -1,142 +0,0 @@
-#!/bin/bash
-#
-# Copyright (C) 2007 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.
-#
-
-PROGNAME=`basename $0`
-
-function fail ()
-{
-    if [ ! -z "$@" ]
-    then
-        echo "$PROGNAME: ERROR: $@" >&2
-    fi
-    echo "$PROGNAME: ERROR: failed." >&2
-    exit 1
-}
-
-function usage ()
-{
-    cat << HERE
-usage: $PROGNAME <.jar/.apk-file-list>
-    Dumps a summary of the compressed and uncompressed sizes of various
-    types of files in each package.  Emits one line per package.
-    Packages must be zipfiles, readable using "unzip".
-
-    Example output line:
-
-        filesize=642684 all=603288/919304 dex=119529/353815 name="out/App.apk"
-
-    filesize: the size of the package on disk
-    name: the name of the package as passed to $PROGNAME
-
-    These fields are presented as <uncompressed bytes>/<compressed bytes>:
-
-        all: the sum of all entries in the package
-        dex: the sum of all "*.dex" entries in the package
-HERE
-    exit 1
-}
-
-if [ $# -lt 1 ]
-then
-    usage
-fi
-
-UNAME=`uname`
-if [ "x$UNAME" = "xDarwin" ]
-then
-    statArgs="-f %z"
-elif [ "x$UNAME" = "xLinux" ]
-then
-    statArgs="-c %s"
-else
-    fail "Unknown uname $UNAME"
-fi
-
-function printFileSize ()
-{
-    stat $statArgs $1
-}
-
-for file
-do
-    if [ ! -f "$file" ]
-    then
-        fail "$file doesn't exist or isn't a file"
-    fi
-    unzip -lvq "$file" | awk '
-        BEGIN {
-          total_compressed = 0;
-          total_uncompressed = 0;
-          dex_compressed = 0;
-          dex_uncompressed = 0;
-        }
-
-        # Make sure the output of unzip -lv looks like something we expect.
-        #
-        NR == "1" {
-            if (NF != "8" ||
-                $1 != "Length" ||
-                $2 != "Method" ||
-                $3 != "Size" ||
-                ($4 != "Ratio" && $4 != "Cmpr") ||
-                $5 != "Date" ||
-                $6 != "Time" ||
-                $7 != "CRC-32" ||
-                $8 != "Name")
-            {
-                print "'$PROGNAME': ERROR: Unexpected zip listing format" > \
-                        "/dev/stderr";
-                print "'$PROGNAME': ERROR: Line 2 is \"" $0 "\"" > \
-                        "/dev/stderr";
-                failed = 1;
-                exit 1;
-            } else {
-                saw_listing = 1;
-            }
-        }
-
-        # Only look for lines where the ratio is the fourth column;
-        # this filters out the header and footer.
-        #
-        $4 ~ /%$/ {
-            uncompressed = $1;
-            compressed = $3;
-            if ($0 ~ /.dex$/) {
-                dex_compressed += compressed;
-                dex_uncompressed += uncompressed;
-            }
-            total_compressed += compressed;
-            total_uncompressed += uncompressed;
-        }
-        { next }
-
-        END {
-            if (!failed && saw_listing) {
-                print "filesize='$(printFileSize "$file")'",
-                      "all=" total_compressed "/" total_uncompressed,
-                      "dex=" dex_compressed "/" dex_uncompressed,
-                      "name=\"'"$file"'\"";
-            } else {
-                exit 1;
-            }
-        }
-    '
-    if [ $? -ne 0 ]
-    then
-        fail "Could not get stats for $file"
-    fi
-done
diff --git a/tools/releasetools/Android.bp b/tools/releasetools/Android.bp
index 3732b78..6cde77e 100644
--- a/tools/releasetools/Android.bp
+++ b/tools/releasetools/Android.bp
@@ -12,6 +12,107 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+//
+// Module-specific defaults.
+//
+// For module X, if we need to build it both as a library and an executable:
+//  - A default rule `releasetools_X_defaults` is created, which lists `srcs`, `libs` and
+//    `required` properties.
+//  - `python_library_host` and `python_binary_host` are created by listing
+//    `releasetools_X_defaults` in their defaults.
+//
+
+python_defaults {
+    name: "releasetools_add_img_to_target_files_defaults",
+    srcs: [
+        "add_img_to_target_files.py",
+    ],
+    libs: [
+        "releasetools_build_image",
+        "releasetools_build_super_image",
+        "releasetools_common",
+    ],
+    required: [
+        "care_map_generator",
+    ],
+}
+
+python_defaults {
+    name: "releasetools_build_image_defaults",
+    srcs: [
+        "build_image.py",
+    ],
+    libs: [
+        "releasetools_common",
+        "releasetools_verity_utils",
+    ],
+    required: [
+        "blk_alloc_to_base_fs",
+        "e2fsck",
+        "simg2img",
+        "tune2fs",
+    ],
+}
+
+python_defaults {
+    name: "releasetools_build_super_image_defaults",
+    srcs: [
+        "build_super_image.py",
+    ],
+    libs: [
+        "releasetools_common",
+    ],
+}
+
+python_defaults {
+    name: "releasetools_img_from_target_files_defaults",
+    srcs: [
+        "img_from_target_files.py",
+    ],
+    libs: [
+        "releasetools_build_super_image",
+        "releasetools_common",
+    ],
+    required: [
+        "zip2zip",
+    ],
+}
+
+python_defaults {
+    name: "releasetools_check_target_files_vintf_defaults",
+    srcs: [
+        "check_target_files_vintf.py",
+    ],
+    libs: [
+        "releasetools_common",
+    ],
+    required: [
+        "checkvintf",
+    ],
+}
+
+python_defaults {
+    name: "releasetools_ota_from_target_files_defaults",
+    srcs: [
+        "edify_generator.py",
+        "ota_from_target_files.py",
+        "target_files_diff.py",
+    ],
+    libs: [
+        "releasetools_check_target_files_vintf",
+        "releasetools_common",
+        "releasetools_verity_utils",
+    ],
+    required: [
+        "brillo_update_payload",
+        "checkvintf",
+    ],
+}
+
+//
+// Host libraries.
+//
+
 python_defaults {
     name: "releasetools_library_defaults",
     version: {
@@ -25,10 +126,45 @@
 }
 
 python_library_host {
-    name: "releasetools_build_super_image",
+    name: "releasetools_add_img_to_target_files",
+    defaults: [
+        "releasetools_library_defaults",
+        "releasetools_add_img_to_target_files_defaults",
+    ],
+}
+
+python_library_host {
+    name: "releasetools_apex_utils",
     defaults: ["releasetools_library_defaults"],
     srcs: [
-        "build_super_image.py",
+        "apex_utils.py",
+    ],
+    libs: [
+        "releasetools_common",
+    ],
+}
+
+python_library_host {
+    name: "releasetools_build_image",
+    defaults: [
+        "releasetools_library_defaults",
+        "releasetools_build_image_defaults",
+    ],
+}
+
+python_library_host {
+    name: "releasetools_build_super_image",
+    defaults: [
+        "releasetools_library_defaults",
+        "releasetools_build_super_image_defaults",
+    ],
+}
+
+python_library_host {
+    name: "releasetools_check_target_files_vintf",
+    defaults: [
+        "releasetools_library_defaults",
+        "releasetools_check_target_files_vintf_defaults",
     ],
 }
 
@@ -45,7 +181,7 @@
     // Only the tools that are referenced directly are listed as required modules. For example,
     // `avbtool` is not here, as the script always uses the one from info_dict['avb_avbtool'].
     required: [
-        "aapt",
+        "aapt2",
         "boot_signer",
         "brotli",
         "bsdiff",
@@ -56,6 +192,22 @@
 }
 
 python_library_host {
+    name: "releasetools_img_from_target_files",
+    defaults: [
+        "releasetools_library_defaults",
+        "releasetools_img_from_target_files_defaults",
+    ],
+}
+
+python_library_host {
+    name: "releasetools_ota_from_target_files",
+    defaults: [
+        "releasetools_library_defaults",
+        "releasetools_ota_from_target_files_defaults",
+    ],
+}
+
+python_library_host {
     name: "releasetools_verity_utils",
     defaults: ["releasetools_library_defaults"],
     srcs: [
@@ -69,6 +221,10 @@
     ],
 }
 
+//
+// Host binaries.
+//
+
 python_defaults {
     name: "releasetools_binary_defaults",
     version: {
@@ -84,34 +240,71 @@
 }
 
 python_binary_host {
+    name: "add_img_to_target_files",
+    defaults: [
+        "releasetools_binary_defaults",
+        "releasetools_add_img_to_target_files_defaults",
+    ],
+}
+
+python_binary_host {
     name: "build_image",
-    defaults: ["releasetools_binary_defaults"],
-    srcs: [
-        "build_image.py",
-    ],
-    main: "build_image.py",
-    libs: [
-        "releasetools_common",
-        "releasetools_verity_utils",
-    ],
-    required: [
-        "blk_alloc_to_base_fs",
-        "e2fsck",
-        "simg2img",
-        "tune2fs",
+    defaults: [
+        "releasetools_binary_defaults",
+        "releasetools_build_image_defaults",
     ],
 }
 
 python_binary_host {
     name: "build_super_image",
+    defaults: [
+        "releasetools_binary_defaults",
+        "releasetools_build_super_image_defaults",
+    ],
+}
+
+python_binary_host {
+    name: "check_ota_package_signature",
     defaults: ["releasetools_binary_defaults"],
     srcs: [
-        "build_super_image.py",
+        "check_ota_package_signature.py",
     ],
-    main: "build_super_image.py",
     libs: [
         "releasetools_common",
     ],
+    required: [
+        "delta_generator",
+    ],
+}
+
+python_binary_host {
+    name: "check_target_files_signatures",
+    defaults: ["releasetools_binary_defaults"],
+    srcs: [
+        "check_target_files_signatures.py",
+    ],
+    libs: [
+        "releasetools_common",
+    ],
+    required: [
+        "aapt",
+    ],
+}
+
+python_binary_host {
+    name: "check_target_files_vintf",
+    defaults: [
+        "releasetools_binary_defaults",
+        "releasetools_check_target_files_vintf_defaults"
+    ],
+}
+
+python_binary_host {
+    name: "img_from_target_files",
+    defaults: [
+        "releasetools_binary_defaults",
+        "releasetools_img_from_target_files_defaults",
+    ],
 }
 
 python_binary_host {
@@ -131,7 +324,6 @@
     srcs: [
         "merge_builds.py",
     ],
-    main: "merge_builds.py",
     libs: [
         "releasetools_build_super_image",
         "releasetools_common",
@@ -139,20 +331,38 @@
 }
 
 python_binary_host {
-    name: "ota_from_target_files",
+    name: "merge_target_files",
     defaults: ["releasetools_binary_defaults"],
     srcs: [
-        "edify_generator.py",
-        "ota_from_target_files.py",
-        "target_files_diff.py",
+        "merge_target_files.py",
     ],
-    main: "ota_from_target_files.py",
     libs: [
+        "releasetools_add_img_to_target_files",
+        "releasetools_build_super_image",
+        "releasetools_check_target_files_vintf",
         "releasetools_common",
-        "releasetools_verity_utils",
+        "releasetools_img_from_target_files",
+        "releasetools_ota_from_target_files",
     ],
     required: [
-        "brillo_update_payload",
+        "checkvintf",
+    ],
+}
+
+python_binary_host {
+    name: "ota_from_target_files",
+    defaults: [
+        "releasetools_binary_defaults",
+        "releasetools_ota_from_target_files_defaults",
+    ],
+}
+
+python_binary_host {
+    name: "ota_package_parser",
+    defaults: ["releasetools_binary_defaults"],
+    srcs: [
+        "ota_package_parser.py",
+        "rangelib.py",
     ],
 }
 
@@ -163,37 +373,75 @@
         "rangelib.py",
         "sparse_img.py",
     ],
-    main: "sparse_img.py",
 }
 
+python_binary_host {
+    name: "sign_apex",
+    defaults: ["releasetools_binary_defaults"],
+    srcs: [
+        "sign_apex.py",
+    ],
+    libs: [
+        "releasetools_apex_utils",
+        "releasetools_common",
+    ],
+}
+
+python_binary_host {
+    name: "sign_target_files_apks",
+    defaults: ["releasetools_binary_defaults"],
+    srcs: [
+        "sign_target_files_apks.py",
+    ],
+    libs: [
+        "releasetools_add_img_to_target_files",
+        "releasetools_apex_utils",
+        "releasetools_common",
+    ],
+}
+
+python_binary_host {
+    name: "validate_target_files",
+    defaults: ["releasetools_binary_defaults"],
+    srcs: [
+        "validate_target_files.py",
+    ],
+    libs: [
+        "releasetools_common",
+    ],
+}
+
+//
+// Tests.
+//
+
 python_defaults {
     name: "releasetools_test_defaults",
     srcs: [
-        "add_img_to_target_files.py",
-        "apex_utils.py",
-        "build_image.py",
         "check_ota_package_signature.py",
         "check_target_files_signatures.py",
-        "edify_generator.py",
-        "img_from_target_files.py",
         "make_recovery_patch.py",
         "merge_target_files.py",
-        "ota_from_target_files.py",
         "ota_package_parser.py",
         "sign_apex.py",
         "sign_target_files_apks.py",
-        "target_files_diff.py",
         "validate_target_files.py",
 
         "test_*.py",
     ],
     libs: [
+        "releasetools_add_img_to_target_files",
+        "releasetools_apex_utils",
+        "releasetools_build_image",
         "releasetools_build_super_image",
+        "releasetools_check_target_files_vintf",
         "releasetools_common",
+        "releasetools_img_from_target_files",
+        "releasetools_ota_from_target_files",
         "releasetools_verity_utils",
     ],
     data: [
-        "testdata/*",
+        "testdata/**/*",
     ],
     required: [
         "otatools",
diff --git a/tools/releasetools/apex_utils.py b/tools/releasetools/apex_utils.py
index 6eaa12f..18ad8ce 100644
--- a/tools/releasetools/apex_utils.py
+++ b/tools/releasetools/apex_utils.py
@@ -177,6 +177,7 @@
   payload_dir = common.MakeTempDir(prefix='apex-payload-')
   with zipfile.ZipFile(apex_file) as apex_fd:
     payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
+    zip_items = apex_fd.namelist()
 
   payload_info = ParseApexPayloadInfo(avbtool, payload_file)
   SignApexPayload(
@@ -192,7 +193,8 @@
   payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
 
   common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
-  common.ZipDelete(apex_file, APEX_PUBKEY)
+  if APEX_PUBKEY in zip_items:
+    common.ZipDelete(apex_file, APEX_PUBKEY)
   apex_zip = zipfile.ZipFile(apex_file, 'a')
   common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
   common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
diff --git a/tools/releasetools/build_super_image.py b/tools/releasetools/build_super_image.py
index 045ad55..f63453d 100755
--- a/tools/releasetools/build_super_image.py
+++ b/tools/releasetools/build_super_image.py
@@ -80,10 +80,12 @@
   block_devices = shlex.split(info_dict.get("super_block_devices", "").strip())
   groups = shlex.split(info_dict.get("super_partition_groups", "").strip())
 
-  if ab_update:
+  if ab_update and retrofit:
     cmd += ["--metadata-slots", "2"]
+  elif ab_update:
+    cmd += ["--metadata-slots", "3"]
   else:
-    cmd += ["--metadata-slots", "1"]
+    cmd += ["--metadata-slots", "2"]
 
   if ab_update and retrofit:
     cmd.append("--auto-slot-suffixing")
diff --git a/tools/releasetools/check_target_files_signatures.py b/tools/releasetools/check_target_files_signatures.py
index 60200a3..8c1bb9a 100755
--- a/tools/releasetools/check_target_files_signatures.py
+++ b/tools/releasetools/check_target_files_signatures.py
@@ -213,7 +213,7 @@
     self.certs = frozenset(out)
 
   def ReadManifest(self, full_filename):
-    p = common.Run(["aapt", "dump", "xmltree", full_filename,
+    p = common.Run(["aapt2", "dump", "xmltree", full_filename, "--file",
                     "AndroidManifest.xml"],
                    stdout=subprocess.PIPE)
     manifest, err = p.communicate()
diff --git a/tools/releasetools/check_target_files_vintf.py b/tools/releasetools/check_target_files_vintf.py
new file mode 100755
index 0000000..543147c
--- /dev/null
+++ b/tools/releasetools/check_target_files_vintf.py
@@ -0,0 +1,232 @@
+#!/usr/bin/env python
+#
+# 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.
+
+"""
+Check VINTF compatibility from a target files package.
+
+Usage: check_target_files_vintf target_files
+
+target_files can be a ZIP file or an extracted target files directory.
+"""
+
+import logging
+import subprocess
+import sys
+import os
+import zipfile
+
+import common
+
+logger = logging.getLogger(__name__)
+
+OPTIONS = common.OPTIONS
+
+# Keys are paths that VINTF searches. Must keep in sync with libvintf's search
+# paths (VintfObject.cpp).
+# These paths are stored in different directories in target files package, so
+# we have to search for the correct path and tell checkvintf to remap them.
+DIR_SEARCH_PATHS = {
+    '/system': ('SYSTEM',),
+    '/vendor': ('VENDOR', 'SYSTEM/vendor'),
+    '/product': ('PRODUCT', 'SYSTEM/product'),
+    '/odm': ('ODM', 'VENDOR/odm'),
+}
+
+UNZIP_PATTERN = ['META/*', '*/build.prop']
+
+
+def GetDirmap(input_tmp):
+  dirmap = {}
+  for device_path, target_files_rel_paths in DIR_SEARCH_PATHS.items():
+    for target_files_rel_path in target_files_rel_paths:
+      target_files_path = os.path.join(input_tmp, target_files_rel_path)
+      if os.path.isdir(target_files_path):
+        dirmap[device_path] = target_files_path
+        break
+    if device_path not in dirmap:
+      raise ValueError("Can't determine path for device path " + device_path +
+                       ". Searched the following:" +
+                       ("\n".join(target_files_rel_paths)))
+  return dirmap
+
+
+def GetArgsForSkus(info_dict):
+  skus = info_dict.get('vintf_odm_manifest_skus', '').strip().split()
+  if not skus:
+    logger.info("ODM_MANIFEST_SKUS is not defined. Check once without SKUs.")
+    skus = ['']
+  return [['--property', 'ro.boot.product.hardware.sku=' + sku]
+          for sku in skus]
+
+
+def GetArgsForShippingApiLevel(info_dict):
+  shipping_api_level = info_dict['vendor.build.prop'].get(
+      'ro.product.first_api_level')
+  if not shipping_api_level:
+    logger.warning('Cannot determine ro.product.first_api_level')
+    return []
+  return ['--property', 'ro.product.first_api_level=' + shipping_api_level]
+
+
+def GetArgsForKernel(input_tmp):
+  version_path = os.path.join(input_tmp, 'META/kernel_version.txt')
+  config_path = os.path.join(input_tmp, 'META/kernel_configs.txt')
+
+  if not os.path.isfile(version_path) or not os.path.isfile(config_path):
+    logger.info('Skipping kernel config checks because ' +
+                'PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS is not set')
+    return []
+
+  with open(version_path) as f:
+    version = f.read().strip()
+
+  return ['--kernel', '{}:{}'.format(version, config_path)]
+
+
+def CheckVintfFromExtractedTargetFiles(input_tmp, info_dict=None):
+  """
+  Checks VINTF metadata of an extracted target files directory.
+
+  Args:
+    inp: path to the directory that contains the extracted target files archive.
+    info_dict: The build-time info dict. If None, it will be loaded from inp.
+
+  Returns:
+    True if VINTF check is skipped or compatible, False if incompatible. Raise
+    a RuntimeError if any error occurs.
+  """
+
+  if info_dict is None:
+    info_dict = common.LoadInfoDict(input_tmp)
+
+  if info_dict.get('vintf_enforce') != 'true':
+    logger.warning('PRODUCT_ENFORCE_VINTF_MANIFEST is not set, skipping checks')
+    return True
+
+  dirmap = GetDirmap(input_tmp)
+  args_for_skus = GetArgsForSkus(info_dict)
+  shipping_api_level_args = GetArgsForShippingApiLevel(info_dict)
+  kernel_args = GetArgsForKernel(input_tmp)
+
+  common_command = [
+      'checkvintf',
+      '--check-compat',
+  ]
+  for device_path, real_path in dirmap.items():
+    common_command += ['--dirmap', '{}:{}'.format(device_path, real_path)]
+  common_command += kernel_args
+  common_command += shipping_api_level_args
+
+  success = True
+  for sku_args in args_for_skus:
+    command = common_command + sku_args
+    proc = common.Run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    out, err = proc.communicate()
+    if proc.returncode == 0:
+      logger.info("Command `%s` returns 'compatible'", ' '.join(command))
+    elif out.strip() == "INCOMPATIBLE":
+      logger.info("Command `%s` returns 'incompatible'", ' '.join(command))
+      success = False
+    else:
+      raise common.ExternalError(
+          "Failed to run command '{}' (exit code {}):\nstdout:{}\nstderr:{}"
+          .format(' '.join(command), proc.returncode, out, err))
+    logger.info("stdout: %s", out)
+    logger.info("stderr: %s", err)
+
+  return success
+
+
+def GetVintfFileList():
+  """
+  Returns a list of VINTF metadata files that should be read from a target files
+  package before executing checkvintf.
+  """
+  def PathToPatterns(path):
+    if path[-1] == '/':
+      path += '*'
+    for device_path, target_files_rel_paths in DIR_SEARCH_PATHS.items():
+      if path.startswith(device_path):
+        suffix = path[len(device_path):]
+        return [rel_path + suffix for rel_path in target_files_rel_paths]
+    raise RuntimeError('Unrecognized path from checkvintf --dump-file-list: ' +
+                       path)
+
+  out = common.RunAndCheckOutput(['checkvintf', '--dump-file-list'])
+  paths = out.strip().split('\n')
+  paths = sum((PathToPatterns(path) for path in paths if path), [])
+  return paths
+
+
+def CheckVintfFromTargetFiles(inp, info_dict=None):
+  """
+  Checks VINTF metadata of a target files zip.
+
+  Args:
+    inp: path to the target files archive.
+    info_dict: The build-time info dict. If None, it will be loaded from inp.
+
+  Returns:
+    True if VINTF check is skipped or compatible, False if incompatible. Raise
+    a RuntimeError if any error occurs.
+  """
+  input_tmp = common.UnzipTemp(inp, GetVintfFileList() + UNZIP_PATTERN)
+  return CheckVintfFromExtractedTargetFiles(input_tmp, info_dict)
+
+
+def CheckVintf(inp, info_dict=None):
+  """
+  Checks VINTF metadata of a target files zip or extracted target files
+  directory.
+
+  Args:
+    inp: path to the (possibly extracted) target files archive.
+    info_dict: The build-time info dict. If None, it will be loaded from inp.
+
+  Returns:
+    True if VINTF check is skipped or compatible, False if incompatible. Raise
+    a RuntimeError if any error occurs.
+  """
+  if os.path.isdir(inp):
+    logger.info('Checking VINTF compatibility extracted target files...')
+    return CheckVintfFromExtractedTargetFiles(inp, info_dict)
+
+  if zipfile.is_zipfile(inp):
+    logger.info('Checking VINTF compatibility target files...')
+    return CheckVintfFromTargetFiles(inp, info_dict)
+
+  raise ValueError('{} is not a valid directory or zip file'.format(inp))
+
+
+def main(argv):
+  args = common.ParseOptions(argv, __doc__)
+  if len(args) != 1:
+    common.Usage(__doc__)
+    sys.exit(1)
+  common.InitLogging()
+  if not CheckVintf(args[0]):
+    sys.exit(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 2401e46..6756049 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -616,6 +616,10 @@
   """Append signing arguments for avbtool."""
   # e.g., "--key path/to/signing_key --algorithm SHA256_RSA4096"
   key_path = OPTIONS.info_dict.get("avb_" + partition + "_key_path")
+  if key_path and not os.path.exists(key_path) and OPTIONS.search_path:
+    new_key_path = os.path.join(OPTIONS.search_path, key_path)
+    if os.path.exists(new_key_path):
+      key_path = new_key_path
   algorithm = OPTIONS.info_dict.get("avb_" + partition + "_algorithm")
   if key_path and algorithm:
     cmd.extend(["--key", key_path, "--algorithm", algorithm])
@@ -668,6 +672,10 @@
   """
   if key is None:
     key = info_dict["avb_" + partition + "_key_path"]
+  if key and not os.path.exists(key) and OPTIONS.search_path:
+    new_key_path = os.path.join(OPTIONS.search_path, key)
+    if os.path.exists(new_key_path):
+      key = new_key_path
   pubkey_path = ExtractAvbPublicKey(info_dict["avb_avbtool"], key)
   rollback_index_location = info_dict[
       "avb_" + partition + "_rollback_index_location"]
@@ -1192,7 +1200,7 @@
 def GetMinSdkVersion(apk_name):
   """Gets the minSdkVersion declared in the APK.
 
-  It calls 'aapt' to query the embedded minSdkVersion from the given APK file.
+  It calls 'aapt2' to query the embedded minSdkVersion from the given APK file.
   This can be both a decimal number (API Level) or a codename.
 
   Args:
@@ -1205,12 +1213,12 @@
     ExternalError: On failing to obtain the min SDK version.
   """
   proc = Run(
-      ["aapt", "dump", "badging", apk_name], stdout=subprocess.PIPE,
+      ["aapt2", "dump", "badging", apk_name], stdout=subprocess.PIPE,
       stderr=subprocess.PIPE)
   stdoutdata, stderrdata = proc.communicate()
   if proc.returncode != 0:
     raise ExternalError(
-        "Failed to obtain minSdkVersion: aapt return code {}:\n{}\n{}".format(
+        "Failed to obtain minSdkVersion: aapt2 return code {}:\n{}\n{}".format(
             proc.returncode, stdoutdata, stderrdata))
 
   for line in stdoutdata.split("\n"):
@@ -1218,7 +1226,7 @@
     m = re.match(r'sdkVersion:\'([^\']*)\'', line)
     if m:
       return m.group(1)
-  raise ExternalError("No minSdkVersion returned by aapt")
+  raise ExternalError("No minSdkVersion returned by aapt2")
 
 
 def GetMinSdkVersionInt(apk_name, codename_to_api_level_map):
diff --git a/tools/releasetools/img_from_target_files.py b/tools/releasetools/img_from_target_files.py
index 4b94ad8..ab38d0d 100755
--- a/tools/releasetools/img_from_target_files.py
+++ b/tools/releasetools/img_from_target_files.py
@@ -27,6 +27,14 @@
       Include only the bootable images (eg 'boot' and 'recovery') in
       the output.
 
+  --additional <filespec>
+      Include an additional entry into the generated zip file. The filespec is
+      in a format that's accepted by zip2zip (e.g.
+      'OTA/android-info.txt:android-info.txt', to copy `OTA/android-info.txt`
+      from input_file into output_file as `android-info.txt`. Refer to the
+      `filespec` arg in zip2zip's help message). The option can be repeated to
+      include multiple entries.
+
 """
 
 from __future__ import print_function
@@ -40,103 +48,129 @@
 from build_super_image import BuildSuperImage
 
 if sys.hexversion < 0x02070000:
-  print("Python 2.7 or newer is required.", file=sys.stderr)
+  print('Python 2.7 or newer is required.', file=sys.stderr)
   sys.exit(1)
 
 logger = logging.getLogger(__name__)
 
 OPTIONS = common.OPTIONS
 
+OPTIONS.additional_entries = []
+OPTIONS.bootable_only = False
+OPTIONS.put_super = None
+OPTIONS.dynamic_partition_list = None
+OPTIONS.super_device_list = None
+OPTIONS.retrofit_dap = None
+OPTIONS.build_super = None
+OPTIONS.sparse_userimages = None
+
 
 def LoadOptions(input_file):
   """Loads information from input_file to OPTIONS.
 
   Args:
-    input_file: Path to the root dir of an extracted target_files zip.
+    input_file: Path to the input target_files zip file.
   """
-  info = OPTIONS.info_dict = common.LoadInfoDict(input_file)
+  with zipfile.ZipFile(input_file) as input_zip:
+    info = OPTIONS.info_dict = common.LoadInfoDict(input_zip)
 
-  OPTIONS.put_super = info.get("super_image_in_update_package") == "true"
-  OPTIONS.dynamic_partition_list = info.get("dynamic_partition_list",
-                                            "").strip().split()
-  OPTIONS.super_device_list = info.get("super_block_devices",
-                                       "").strip().split()
-  OPTIONS.retrofit_dap = info.get("dynamic_partition_retrofit") == "true"
-  OPTIONS.build_super = info.get("build_super_partition") == "true"
-  OPTIONS.sparse_userimages = bool(info.get("extfs_sparse_flag"))
+  OPTIONS.put_super = info.get('super_image_in_update_package') == 'true'
+  OPTIONS.dynamic_partition_list = info.get('dynamic_partition_list',
+                                            '').strip().split()
+  OPTIONS.super_device_list = info.get('super_block_devices',
+                                       '').strip().split()
+  OPTIONS.retrofit_dap = info.get('dynamic_partition_retrofit') == 'true'
+  OPTIONS.build_super = info.get('build_super_partition') == 'true'
+  OPTIONS.sparse_userimages = bool(info.get('extfs_sparse_flag'))
 
 
-def CopyInfo(input_tmp, output_zip):
-  """Copies the android-info.txt file from the input to the output."""
-  common.ZipWrite(
-      output_zip, os.path.join(input_tmp, "OTA", "android-info.txt"),
-      "android-info.txt")
-
-
-def CopyUserImages(input_tmp, output_zip):
-  """Copies user images from the unzipped input and write to output_zip.
+def CopyZipEntries(input_file, output_file, entries):
+  """Copies ZIP entries between input and output files.
 
   Args:
-    input_tmp: path to the unzipped input.
-    output_zip: a ZipFile instance to write images to.
+    input_file: Path to the input target_files zip.
+    output_file: Output filename.
+    entries: A list of entries to copy, in a format that's accepted by zip2zip
+        (e.g. 'OTA/android-info.txt:android-info.txt', which copies
+        `OTA/android-info.txt` from input_file into output_file as
+        `android-info.txt`. Refer to the `filespec` arg in zip2zip's help
+        message).
   """
-  dynamic_images = [p + ".img" for p in OPTIONS.dynamic_partition_list]
+  logger.info('Writing %d entries to archive...', len(entries))
+  cmd = ['zip2zip', '-i', input_file, '-o', output_file]
+  cmd.extend(entries)
+  common.RunAndCheckOutput(cmd)
+
+
+def EntriesForUserImages(input_file):
+  """Returns the user images entries to be copied.
+
+  Args:
+    input_file: Path to the input target_files zip file.
+  """
+  dynamic_images = [p + '.img' for p in OPTIONS.dynamic_partition_list]
 
   # Filter out system_other for launch DAP devices because it is in super image.
-  if not OPTIONS.retrofit_dap and "system" in OPTIONS.dynamic_partition_list:
-    dynamic_images.append("system_other.img")
+  if not OPTIONS.retrofit_dap and 'system' in OPTIONS.dynamic_partition_list:
+    dynamic_images.append('system_other.img')
 
-  images_path = os.path.join(input_tmp, "IMAGES")
-  # A target-files zip must contain the images since Lollipop.
-  assert os.path.exists(images_path)
-  for image in sorted(os.listdir(images_path)):
-    if OPTIONS.bootable_only and image not in ("boot.img", "recovery.img"):
+  entries = [
+      'OTA/android-info.txt:android-info.txt',
+  ]
+  with zipfile.ZipFile(input_file) as input_zip:
+    namelist = input_zip.namelist()
+
+  for image_path in [name for name in namelist if name.startswith('IMAGES/')]:
+    image = os.path.basename(image_path)
+    if OPTIONS.bootable_only and image not in ('boot.img', 'recovery.img'):
       continue
-    if not image.endswith(".img"):
+    if not image.endswith('.img'):
       continue
+    # Filter out super_empty and the images that are already in super partition.
     if OPTIONS.put_super:
-      if image == "super_empty.img":
+      if image == 'super_empty.img':
         continue
       if image in dynamic_images:
         continue
-    logger.info("writing %s to archive...", os.path.join("IMAGES", image))
-    common.ZipWrite(output_zip, os.path.join(images_path, image), image)
+    entries.append('{}:{}'.format(image_path, image))
+  return entries
 
 
-def WriteSuperImages(input_tmp, output_zip):
-  """Writes super images from the unzipped input into output_zip.
+def EntriesForSplitSuperImages(input_file):
+  """Returns the entries for split super images.
 
-  This is only done if super_image_in_update_package is set to "true".
-
-  - For retrofit dynamic partition devices, copy split super images from target
-    files package.
-  - For devices launched with dynamic partitions, build super image from target
-    files package.
+  This is only done for retrofit dynamic partition devices.
 
   Args:
-    input_tmp: path to the unzipped input.
-    output_zip: a ZipFile instance to write images to.
+    input_file: Path to the input target_files zip file.
   """
-  if not OPTIONS.build_super or not OPTIONS.put_super:
-    return
+  with zipfile.ZipFile(input_file) as input_zip:
+    namelist = input_zip.namelist()
+  entries = []
+  for device in OPTIONS.super_device_list:
+    image = 'OTA/super_{}.img'.format(device)
+    assert image in namelist, 'Failed to find {}'.format(image)
+    entries.append('{}:{}'.format(image, os.path.basename(image)))
+  return entries
 
-  if OPTIONS.retrofit_dap:
-    # retrofit devices already have split super images under OTA/
-    images_path = os.path.join(input_tmp, "OTA")
-    for device in OPTIONS.super_device_list:
-      image = "super_%s.img" % device
-      image_path = os.path.join(images_path, image)
-      assert os.path.exists(image_path)
-      logger.info("writing %s to archive...", os.path.join("OTA", image))
-      common.ZipWrite(output_zip, image_path, image)
-  else:
-    # super image for non-retrofit devices aren't in target files package,
-    # so build it.
-    super_file = common.MakeTempFile("super_", ".img")
-    logger.info("building super image %s...", super_file)
-    BuildSuperImage(input_tmp, super_file)
-    logger.info("writing super.img to archive...")
-    common.ZipWrite(output_zip, super_file, "super.img")
+
+def RebuildAndWriteSuperImages(input_file, output_file):
+  """Builds and writes super images to the output file."""
+  logger.info('Building super image...')
+
+  # We need files under IMAGES/, OTA/, META/ for img_from_target_files.py.
+  # However, common.LoadInfoDict() may read additional files under BOOT/,
+  # RECOVERY/ and ROOT/. So unzip everything from the target_files.zip.
+  input_tmp = common.UnzipTemp(input_file)
+
+  super_file = common.MakeTempFile('super_', '.img')
+  BuildSuperImage(input_tmp, super_file)
+
+  logger.info('Writing super.img to archive...')
+  with zipfile.ZipFile(
+      output_file, 'a', compression=zipfile.ZIP_DEFLATED,
+      allowZip64=not OPTIONS.sparse_userimages) as output_zip:
+    common.ZipWrite(output_zip, super_file, 'super.img')
 
 
 def ImgFromTargetFiles(input_file, output_file):
@@ -150,47 +184,51 @@
     ValueError: On invalid input.
   """
   if not zipfile.is_zipfile(input_file):
-    raise ValueError("%s is not a valid zipfile" % input_file)
+    raise ValueError('%s is not a valid zipfile' % input_file)
 
-  logger.info("Building image zip from target files zip.")
+  logger.info('Building image zip from target files zip.')
 
-  # We need files under IMAGES/, OTA/, META/ for img_from_target_files.py.
-  # However, common.LoadInfoDict() may read additional files under BOOT/,
-  # RECOVERY/ and ROOT/. So unzip everything from the target_files.zip.
-  input_tmp = common.UnzipTemp(input_file)
+  LoadOptions(input_file)
 
-  LoadOptions(input_tmp)
-  output_zip = zipfile.ZipFile(
-      output_file, "w", compression=zipfile.ZIP_DEFLATED,
-      allowZip64=not OPTIONS.sparse_userimages)
+  # Entries to be copied into the output file.
+  entries = EntriesForUserImages(input_file)
 
-  try:
-    CopyInfo(input_tmp, output_zip)
-    CopyUserImages(input_tmp, output_zip)
-    WriteSuperImages(input_tmp, output_zip)
-  finally:
-    logger.info("cleaning up...")
-    common.ZipClose(output_zip)
+  # Only for devices that retrofit dynamic partitions there're split super
+  # images available in the target_files.zip.
+  rebuild_super = False
+  if OPTIONS.build_super and OPTIONS.put_super:
+    if OPTIONS.retrofit_dap:
+      entries += EntriesForSplitSuperImages(input_file)
+    else:
+      rebuild_super = True
+
+  # Any additional entries provided by caller.
+  entries += OPTIONS.additional_entries
+
+  CopyZipEntries(input_file, output_file, entries)
+
+  if rebuild_super:
+    RebuildAndWriteSuperImages(input_file, output_file)
 
 
 def main(argv):
-  # This allows modifying the value from inner function.
-  bootable_only_array = [False]
 
-  def option_handler(o, _):
-    if o in ("-z", "--bootable_zip"):
-      bootable_only_array[0] = True
+  def option_handler(o, a):
+    if o in ('-z', '--bootable_zip'):
+      OPTIONS.bootable_only = True
+    elif o == '--additional':
+      OPTIONS.additional_entries.append(a)
     else:
       return False
     return True
 
   args = common.ParseOptions(argv, __doc__,
-                             extra_opts="z",
-                             extra_long_opts=["bootable_zip"],
+                             extra_opts='z',
+                             extra_long_opts=[
+                                 'additional=',
+                                 'bootable_zip',
+                             ],
                              extra_option_handler=option_handler)
-
-  OPTIONS.bootable_only = bootable_only_array[0]
-
   if len(args) != 2:
     common.Usage(__doc__)
     sys.exit(1)
@@ -199,7 +237,7 @@
 
   ImgFromTargetFiles(args[0], args[1])
 
-  logger.info("done.")
+  logger.info('done.')
 
 
 if __name__ == '__main__':
@@ -207,7 +245,7 @@
     common.CloseInheritedPipes()
     main(sys.argv[1:])
   except common.ExternalError as e:
-    logger.exception("\n   ERROR:\n")
+    logger.exception('\n   ERROR:\n')
     sys.exit(1)
   finally:
     common.Cleanup()
diff --git a/tools/releasetools/merge_target_files.py b/tools/releasetools/merge_target_files.py
index cfffbc7..61c4f4e 100755
--- a/tools/releasetools/merge_target_files.py
+++ b/tools/releasetools/merge_target_files.py
@@ -87,6 +87,7 @@
 
 import add_img_to_target_files
 import build_super_image
+import check_target_files_vintf
 import common
 import img_from_target_files
 import ota_from_target_files
@@ -117,8 +118,6 @@
     'META/apkcerts.txt',
     'META/filesystem_config.txt',
     'META/root_filesystem_config.txt',
-    'META/system_manifest.xml',
-    'META/system_matrix.xml',
     'META/update_engine_config.txt',
     'PRODUCT/*',
     'ROOT/*',
@@ -163,8 +162,6 @@
     'META/otakeys.txt',
     'META/releasetools.py',
     'META/vendor_filesystem_config.txt',
-    'META/vendor_manifest.xml',
-    'META/vendor_matrix.xml',
     'BOOT/*',
     'DATA/*',
     'ODM/*',
@@ -781,6 +778,7 @@
   # Regenerate IMAGES in the target directory.
 
   add_img_args = ['--verbose']
+  add_img_args.append('--add_missing')
   if rebuild_recovery:
     add_img_args.append('--rebuild_recovery')
   add_img_args.append(target_files_dir)
@@ -909,6 +907,9 @@
       vendor_target_files, vendor_item_list, framework_misc_info_keys,
       rebuild_recovery)
 
+  if not check_target_files_vintf.CheckVintf(output_target_files_temp_dir):
+    raise RuntimeError("Incompatible VINTF metadata")
+
   generate_images(output_target_files_temp_dir, rebuild_recovery)
 
   generate_super_empty_image(output_target_files_temp_dir, output_super_empty)
diff --git a/tools/releasetools/ota_from_target_files.py b/tools/releasetools/ota_from_target_files.py
index 1a4f7e1..67cec1c 100755
--- a/tools/releasetools/ota_from_target_files.py
+++ b/tools/releasetools/ota_from_target_files.py
@@ -72,7 +72,7 @@
       --skip_postinstall is implied.
 
   --skip_compatibility_check
-      Skip adding the compatibility package to the generated OTA package.
+      Skip checking compatibility of the input target files package.
 
   --output_metadata_path
       Write a copy of the metadata to a separate file. Therefore, users can
@@ -139,6 +139,9 @@
 
 A/B OTA specific options
 
+  --disable_fec_computation
+      Disable the on device FEC data computation for incremental updates.
+
   --include_secondary
       Additionally include the payload for secondary slot images (default:
       False). Only meaningful when generating A/B OTAs.
@@ -181,6 +184,7 @@
 
 from __future__ import print_function
 
+import collections
 import logging
 import multiprocessing
 import os.path
@@ -188,9 +192,9 @@
 import shutil
 import struct
 import sys
-import tempfile
 import zipfile
 
+import check_target_files_vintf
 import common
 import edify_generator
 import verity_utils
@@ -234,6 +238,7 @@
 OPTIONS.retrofit_dynamic_partitions = False
 OPTIONS.skip_compatibility_check = False
 OPTIONS.output_metadata_path = None
+OPTIONS.disable_fec_computation = False
 
 
 METADATA_NAME = 'META-INF/com/android/metadata'
@@ -241,6 +246,9 @@
 DYNAMIC_PARTITION_INFO = 'META/dynamic_partitions_info.txt'
 AB_PARTITIONS = 'META/ab_partitions.txt'
 UNZIP_PATTERN = ['IMAGES/*', 'META/*', 'OTA/*', 'RADIO/*']
+# Files to be unzipped for target diffing purpose.
+TARGET_DIFFING_UNZIP_PATTERN = ['BOOT', 'RECOVERY', 'SYSTEM/*', 'VENDOR/*',
+                                'PRODUCT/*', 'SYSTEM_EXT/*', 'ODM/*']
 RETROFIT_DAP_UNZIP_PATTERN = ['OTA/super_*.img', AB_PARTITIONS]
 
 
@@ -539,7 +547,7 @@
     self.payload_properties = None
     self.secondary = secondary
 
-  def _Run(self, cmd):
+  def _Run(self, cmd):  # pylint: disable=no-self-use
     # Don't pipe (buffer) the output if verbose is set. Let
     # brillo_update_payload write to stdout/stderr directly, so its progress can
     # be monitored.
@@ -567,6 +575,8 @@
            "--target_image", target_file]
     if source_file is not None:
       cmd.extend(["--source_image", source_file])
+      if OPTIONS.disable_fec_computation:
+        cmd.extend(["--disable_fec_computation", "true"])
     cmd.extend(additional_args)
     self._Run(cmd)
 
@@ -719,20 +729,15 @@
     return False
 
 
-def HasVendorPartition(target_files_zip):
-  return HasPartition(target_files_zip, "vendor")
+def HasTrebleEnabled(target_files, target_info):
+  def HasVendorPartition(target_files):
+    if os.path.isdir(target_files):
+      return os.path.isdir(os.path.join(target_files, "VENDOR"))
+    if zipfile.is_zipfile(target_files):
+      return HasPartition(zipfile.ZipFile(target_files), "vendor")
+    raise ValueError("Unknown target_files argument")
 
-
-def HasProductPartition(target_files_zip):
-  return HasPartition(target_files_zip, "product")
-
-
-def HasOdmPartition(target_files_zip):
-  return HasPartition(target_files_zip, "odm")
-
-
-def HasTrebleEnabled(target_files_zip, target_info):
-  return (HasVendorPartition(target_files_zip) and
+  return (HasVendorPartition(target_files) and
           target_info.GetBuildProp("ro.treble.enabled") == "true")
 
 
@@ -757,74 +762,23 @@
         source_info.GetBuildProp("ro.build.thumbprint"))
 
 
-def AddCompatibilityArchiveIfTrebleEnabled(target_zip, output_zip, target_info,
-                                           source_info=None):
-  """Adds compatibility info into the output zip if it's Treble-enabled target.
+def CheckVintfIfTrebleEnabled(target_files, target_info):
+  """Checks compatibility info of the input target files.
 
-  Metadata used for on-device compatibility verification is retrieved from
-  target_zip then added to compatibility.zip which is added to the output_zip
-  archive.
+  Metadata used for compatibility verification is retrieved from target_zip.
 
-  Compatibility archive should only be included for devices that have enabled
+  Compatibility should only be checked for devices that have enabled
   Treble support.
 
   Args:
-    target_zip: Zip file containing the source files to be included for OTA.
-    output_zip: Zip file that will be sent for OTA.
+    target_files: Path to zip file containing the source files to be included
+        for OTA. Can also be the path to extracted directory.
     target_info: The BuildInfo instance that holds the target build info.
-    source_info: The BuildInfo instance that holds the source build info, if
-        generating an incremental OTA; None otherwise.
   """
 
-  def AddCompatibilityArchive(framework_updated, device_updated):
-    """Adds compatibility info based on update status of both sides of Treble
-    boundary.
-
-    Args:
-      framework_updated: If True, the system / product image will be updated
-          and therefore their metadata should be included.
-      device_updated: If True, the vendor / odm image will be updated and
-          therefore their metadata should be included.
-    """
-    # Determine what metadata we need. Files are names relative to META/.
-    compatibility_files = []
-    device_metadata = ("vendor_manifest.xml", "vendor_matrix.xml")
-    framework_metadata = ("system_manifest.xml", "system_matrix.xml")
-    if device_updated:
-      compatibility_files += device_metadata
-    if framework_updated:
-      compatibility_files += framework_metadata
-
-    # Create new archive.
-    compatibility_archive = tempfile.NamedTemporaryFile()
-    compatibility_archive_zip = zipfile.ZipFile(
-        compatibility_archive, "w", compression=zipfile.ZIP_DEFLATED)
-
-    # Add metadata.
-    for file_name in compatibility_files:
-      target_file_name = "META/" + file_name
-
-      if target_file_name in target_zip.namelist():
-        data = target_zip.read(target_file_name)
-        common.ZipWriteStr(compatibility_archive_zip, file_name, data)
-
-    # Ensure files are written before we copy into output_zip.
-    compatibility_archive_zip.close()
-
-    # Only add the archive if we have any compatibility info.
-    if compatibility_archive_zip.namelist():
-      common.ZipWrite(output_zip, compatibility_archive.name,
-                      arcname="compatibility.zip",
-                      compress_type=zipfile.ZIP_STORED)
-
-  def FingerprintChanged(source_fp, target_fp):
-    if source_fp is None or target_fp is None:
-      return True
-    return source_fp != target_fp
-
   # Will only proceed if the target has enabled the Treble support (as well as
   # having a /vendor partition).
-  if not HasTrebleEnabled(target_zip, target_info):
+  if not HasTrebleEnabled(target_files, target_info):
     return
 
   # Skip adding the compatibility package as a workaround for b/114240221. The
@@ -832,28 +786,96 @@
   if OPTIONS.skip_compatibility_check:
     return
 
-  # Full OTA carries the info for system/vendor/product/odm
-  if source_info is None:
-    AddCompatibilityArchive(True, True)
-    return
+  if not check_target_files_vintf.CheckVintf(target_files, target_info):
+    raise RuntimeError("VINTF compatibility check failed")
 
-  source_fp = source_info.fingerprint
-  target_fp = target_info.fingerprint
-  system_updated = source_fp != target_fp
 
-  # other build fingerprints could be possibly blacklisted at build time. For
-  # such a case, we consider those images being changed.
-  vendor_updated = FingerprintChanged(source_info.vendor_fingerprint,
-                                      target_info.vendor_fingerprint)
-  product_updated = HasProductPartition(target_zip) and \
-                    FingerprintChanged(source_info.product_fingerprint,
-                                       target_info.product_fingerprint)
-  odm_updated = HasOdmPartition(target_zip) and \
-                FingerprintChanged(source_info.odm_fingerprint,
-                                   target_info.odm_fingerprint)
+def GetBlockDifferences(target_zip, source_zip, target_info, source_info,
+                        device_specific):
+  """Returns a ordered dict of block differences with partition name as key."""
 
-  AddCompatibilityArchive(system_updated or product_updated,
-                          vendor_updated or odm_updated)
+  def GetIncrementalBlockDifferenceForPartition(name):
+    if not HasPartition(source_zip, name):
+      raise RuntimeError("can't generate incremental that adds {}".format(name))
+
+    partition_src = common.GetUserImage(name, OPTIONS.source_tmp, source_zip,
+                                        info_dict=source_info,
+                                        allow_shared_blocks=allow_shared_blocks)
+
+    hashtree_info_generator = verity_utils.CreateHashtreeInfoGenerator(
+        name, 4096, target_info)
+    partition_tgt = common.GetUserImage(name, OPTIONS.target_tmp, target_zip,
+                                        info_dict=target_info,
+                                        allow_shared_blocks=allow_shared_blocks,
+                                        hashtree_info_generator=
+                                        hashtree_info_generator)
+
+    # Check the first block of the source system partition for remount R/W only
+    # if the filesystem is ext4.
+    partition_source_info = source_info["fstab"]["/" + name]
+    check_first_block = partition_source_info.fs_type == "ext4"
+    # Disable using imgdiff for squashfs. 'imgdiff -z' expects input files to be
+    # in zip formats. However with squashfs, a) all files are compressed in LZ4;
+    # b) the blocks listed in block map may not contain all the bytes for a
+    # given file (because they're rounded to be 4K-aligned).
+    partition_target_info = target_info["fstab"]["/" + name]
+    disable_imgdiff = (partition_source_info.fs_type == "squashfs" or
+                       partition_target_info.fs_type == "squashfs")
+    return common.BlockDifference(name, partition_src, partition_tgt,
+                                  check_first_block,
+                                  version=blockimgdiff_version,
+                                  disable_imgdiff=disable_imgdiff)
+
+  if source_zip:
+    # See notes in common.GetUserImage()
+    allow_shared_blocks = (source_info.get('ext4_share_dup_blocks') == "true" or
+                           target_info.get('ext4_share_dup_blocks') == "true")
+    blockimgdiff_version = max(
+        int(i) for i in target_info.get(
+            "blockimgdiff_versions", "1").split(","))
+    assert blockimgdiff_version >= 3
+
+  block_diff_dict = collections.OrderedDict()
+  partition_names = ["system", "vendor", "product", "odm", "system_ext"]
+  for partition in partition_names:
+    if not HasPartition(target_zip, partition):
+      continue
+    # Full OTA update.
+    if not source_zip:
+      tgt = common.GetUserImage(partition, OPTIONS.input_tmp, target_zip,
+                                info_dict=target_info,
+                                reset_file_map=True)
+      block_diff_dict[partition] = common.BlockDifference(partition, tgt,
+                                                          src=None)
+    # Incremental OTA update.
+    else:
+      block_diff_dict[partition] = GetIncrementalBlockDifferenceForPartition(
+          partition)
+  assert "system" in block_diff_dict
+
+  # Get the block diffs from the device specific script. If there is a
+  # duplicate block diff for a partition, ignore the diff in the generic script
+  # and use the one in the device specific script instead.
+  if source_zip:
+    device_specific_diffs = device_specific.IncrementalOTA_GetBlockDifferences()
+    function_name = "IncrementalOTA_GetBlockDifferences"
+  else:
+    device_specific_diffs = device_specific.FullOTA_GetBlockDifferences()
+    function_name = "FullOTA_GetBlockDifferences"
+
+  if device_specific_diffs:
+    assert all(isinstance(diff, common.BlockDifference)
+               for diff in device_specific_diffs), \
+        "{} is not returning a list of BlockDifference objects".format(
+            function_name)
+    for diff in device_specific_diffs:
+      if diff.partition in block_diff_dict:
+        logger.warning("Duplicate block difference found. Device specific block"
+                       " diff for partition '%s' overrides the one in generic"
+                       " script.", diff.partition)
+      block_diff_dict[diff.partition] = diff
+
+  return block_diff_dict
 
 
 def WriteFullOTAPackage(input_zip, output_file):
@@ -897,6 +919,11 @@
   target_info.WriteDeviceAssertions(script, OPTIONS.oem_no_mount)
   device_specific.FullOTA_Assertions()
 
+  block_diff_dict = GetBlockDifferences(target_zip=input_zip, source_zip=None,
+                                        target_info=target_info,
+                                        source_info=None,
+                                        device_specific=device_specific)
+
   # Two-step package strategy (in chronological order, which is *not*
   # the order in which the generated script has things):
   #
@@ -948,67 +975,39 @@
 
   device_specific.FullOTA_InstallBegin()
 
-  system_progress = 0.75
-
+  # All other partitions as well as the data wipe use 10% of the progress, and
+  # the update of the system partition takes the remaining progress.
+  system_progress = 0.9 - (len(block_diff_dict) - 1) * 0.1
   if OPTIONS.wipe_user_data:
     system_progress -= 0.1
-  if HasVendorPartition(input_zip):
-    system_progress -= 0.1
-
-  script.ShowProgress(system_progress, 0)
-
-  def GetBlockDifference(partition):
-    # Full OTA is done as an "incremental" against an empty source image. This
-    # has the effect of writing new data from the package to the entire
-    # partition, but lets us reuse the updater code that writes incrementals to
-    # do it.
-    tgt = common.GetUserImage(partition, OPTIONS.input_tmp, input_zip,
-                              info_dict=target_info,
-                              reset_file_map=True)
-    diff = common.BlockDifference(partition, tgt, src=None)
-    return diff
-
-  device_specific_diffs = device_specific.FullOTA_GetBlockDifferences()
-  if device_specific_diffs:
-    assert all(isinstance(diff, common.BlockDifference)
-               for diff in device_specific_diffs), \
-        "FullOTA_GetBlockDifferences is not returning a list of " \
-        "BlockDifference objects"
-
-  progress_dict = dict()
-  block_diffs = [GetBlockDifference("system")]
-  if HasVendorPartition(input_zip):
-    block_diffs.append(GetBlockDifference("vendor"))
-    progress_dict["vendor"] = 0.1
-  if device_specific_diffs:
-    block_diffs += device_specific_diffs
+  progress_dict = {partition: 0.1 for partition in block_diff_dict}
+  progress_dict["system"] = system_progress
 
   if target_info.get('use_dynamic_partitions') == "true":
     # Use empty source_info_dict to indicate that all partitions / groups must
     # be re-added.
     dynamic_partitions_diff = common.DynamicPartitionsDifference(
         info_dict=OPTIONS.info_dict,
-        block_diffs=block_diffs,
+        block_diffs=block_diff_dict.values(),
         progress_dict=progress_dict)
     dynamic_partitions_diff.WriteScript(script, output_zip,
                                         write_verify_script=OPTIONS.verify)
   else:
-    for block_diff in block_diffs:
+    for block_diff in block_diff_dict.values():
       block_diff.WriteScript(script, output_zip,
                              progress=progress_dict.get(block_diff.partition),
                              write_verify_script=OPTIONS.verify)
 
-  AddCompatibilityArchiveIfTrebleEnabled(input_zip, output_zip, target_info)
+  CheckVintfIfTrebleEnabled(OPTIONS.input_tmp, target_info)
 
   boot_img = common.GetBootableImage(
       "boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
   common.CheckSize(boot_img.data, "boot.img", target_info)
   common.ZipWriteStr(output_zip, "boot.img", boot_img.data)
 
-  script.ShowProgress(0.05, 5)
   script.WriteRawImage("/boot", "boot.img")
 
-  script.ShowProgress(0.2, 10)
+  script.ShowProgress(0.1, 10)
   device_specific.FullOTA_InstallEnd()
 
   if OPTIONS.extra_script is not None:
@@ -1568,69 +1567,13 @@
   target_recovery = common.GetBootableImage(
       "/tmp/recovery.img", "recovery.img", OPTIONS.target_tmp, "RECOVERY")
 
-  # See notes in common.GetUserImage()
-  allow_shared_blocks = (source_info.get('ext4_share_dup_blocks') == "true" or
-                         target_info.get('ext4_share_dup_blocks') == "true")
-  system_src = common.GetUserImage("system", OPTIONS.source_tmp, source_zip,
-                                   info_dict=source_info,
-                                   allow_shared_blocks=allow_shared_blocks)
+  block_diff_dict = GetBlockDifferences(target_zip=target_zip,
+                                        source_zip=source_zip,
+                                        target_info=target_info,
+                                        source_info=source_info,
+                                        device_specific=device_specific)
 
-  hashtree_info_generator = verity_utils.CreateHashtreeInfoGenerator(
-      "system", 4096, target_info)
-  system_tgt = common.GetUserImage("system", OPTIONS.target_tmp, target_zip,
-                                   info_dict=target_info,
-                                   allow_shared_blocks=allow_shared_blocks,
-                                   hashtree_info_generator=
-                                   hashtree_info_generator)
-
-  blockimgdiff_version = max(
-      int(i) for i in target_info.get("blockimgdiff_versions", "1").split(","))
-  assert blockimgdiff_version >= 3
-
-  # Check the first block of the source system partition for remount R/W only
-  # if the filesystem is ext4.
-  system_src_partition = source_info["fstab"]["/system"]
-  check_first_block = system_src_partition.fs_type == "ext4"
-  # Disable using imgdiff for squashfs. 'imgdiff -z' expects input files to be
-  # in zip formats. However with squashfs, a) all files are compressed in LZ4;
-  # b) the blocks listed in block map may not contain all the bytes for a given
-  # file (because they're rounded to be 4K-aligned).
-  system_tgt_partition = target_info["fstab"]["/system"]
-  disable_imgdiff = (system_src_partition.fs_type == "squashfs" or
-                     system_tgt_partition.fs_type == "squashfs")
-  system_diff = common.BlockDifference("system", system_tgt, system_src,
-                                       check_first_block,
-                                       version=blockimgdiff_version,
-                                       disable_imgdiff=disable_imgdiff)
-
-  if HasVendorPartition(target_zip):
-    if not HasVendorPartition(source_zip):
-      raise RuntimeError("can't generate incremental that adds /vendor")
-    vendor_src = common.GetUserImage("vendor", OPTIONS.source_tmp, source_zip,
-                                     info_dict=source_info,
-                                     allow_shared_blocks=allow_shared_blocks)
-    hashtree_info_generator = verity_utils.CreateHashtreeInfoGenerator(
-        "vendor", 4096, target_info)
-    vendor_tgt = common.GetUserImage(
-        "vendor", OPTIONS.target_tmp, target_zip,
-        info_dict=target_info,
-        allow_shared_blocks=allow_shared_blocks,
-        hashtree_info_generator=hashtree_info_generator)
-
-    # Check first block of vendor partition for remount R/W only if
-    # disk type is ext4
-    vendor_partition = source_info["fstab"]["/vendor"]
-    check_first_block = vendor_partition.fs_type == "ext4"
-    disable_imgdiff = vendor_partition.fs_type == "squashfs"
-    vendor_diff = common.BlockDifference("vendor", vendor_tgt, vendor_src,
-                                         check_first_block,
-                                         version=blockimgdiff_version,
-                                         disable_imgdiff=disable_imgdiff)
-  else:
-    vendor_diff = None
-
-  AddCompatibilityArchiveIfTrebleEnabled(
-      target_zip, output_zip, target_info, source_info)
+  CheckVintfIfTrebleEnabled(OPTIONS.target_tmp, target_info)
 
   # Assertions (e.g. device properties check).
   target_info.WriteDeviceAssertions(script, OPTIONS.oem_no_mount)
@@ -1694,12 +1637,8 @@
   WriteFingerprintAssertion(script, target_info, source_info)
 
   # Check the required cache size (i.e. stashed blocks).
-  size = []
-  if system_diff:
-    size.append(system_diff.required_cache)
-  if vendor_diff:
-    size.append(vendor_diff.required_cache)
-
+  required_cache_sizes = [diff.required_cache for diff in
+                          block_diff_dict.values()]
   if updating_boot:
     boot_type, boot_device = common.GetTypeAndDevice("/boot", source_info)
     d = common.Difference(target_boot, source_boot)
@@ -1722,10 +1661,14 @@
           "{}:{}:{}:{}".format(
               boot_type, boot_device, source_boot.size, source_boot.sha1))
 
-      size.append(target_boot.size)
+      required_cache_sizes.append(target_boot.size)
 
-  if size:
-    script.CacheFreeSpaceCheck(max(size))
+  if required_cache_sizes:
+    script.CacheFreeSpaceCheck(max(required_cache_sizes))
+
+  # Verify the existing partitions.
+  for diff in block_diff_dict.values():
+    diff.WriteVerifyScript(script, touched_blocks_only=True)
 
   device_specific.IncrementalOTA_VerifyEnd()
 
@@ -1742,30 +1685,12 @@
     # Stage 3/3: Make changes.
     script.Comment("Stage 3/3")
 
-  # Verify the existing partitions.
-  system_diff.WriteVerifyScript(script, touched_blocks_only=True)
-  if vendor_diff:
-    vendor_diff.WriteVerifyScript(script, touched_blocks_only=True)
-  device_specific_diffs = device_specific.IncrementalOTA_GetBlockDifferences()
-  if device_specific_diffs:
-    assert all(isinstance(diff, common.BlockDifference)
-               for diff in device_specific_diffs), \
-        "IncrementalOTA_GetBlockDifferences is not returning a list of " \
-        "BlockDifference objects"
-    for diff in device_specific_diffs:
-      diff.WriteVerifyScript(script, touched_blocks_only=True)
-
   script.Comment("---- start making changes here ----")
 
   device_specific.IncrementalOTA_InstallBegin()
 
-  block_diffs = [system_diff]
-  progress_dict = {"system": 0.8 if vendor_diff else 0.9}
-  if vendor_diff:
-    block_diffs.append(vendor_diff)
-    progress_dict["vendor"] = 0.1
-  if device_specific_diffs:
-    block_diffs += device_specific_diffs
+  progress_dict = {partition: 0.1 for partition in block_diff_dict}
+  progress_dict["system"] = 1 - len(block_diff_dict) * 0.1
 
   if OPTIONS.source_info_dict.get("use_dynamic_partitions") == "true":
     if OPTIONS.target_info_dict.get("use_dynamic_partitions") != "true":
@@ -1774,12 +1699,12 @@
     dynamic_partitions_diff = common.DynamicPartitionsDifference(
         info_dict=OPTIONS.target_info_dict,
         source_info_dict=OPTIONS.source_info_dict,
-        block_diffs=block_diffs,
+        block_diffs=block_diff_dict.values(),
         progress_dict=progress_dict)
     dynamic_partitions_diff.WriteScript(
         script, output_zip, write_verify_script=OPTIONS.verify)
   else:
-    for block_diff in block_diffs:
+    for block_diff in block_diff_dict.values():
       block_diff.WriteScript(script, output_zip,
                              progress=progress_dict.get(block_diff.partition),
                              write_verify_script=OPTIONS.verify)
@@ -2005,8 +1930,7 @@
   return target_file
 
 
-def WriteABOTAPackageWithBrilloScript(target_file, output_file,
-                                      source_file=None):
+def GenerateAbOtaPackage(target_file, output_file, source_file=None):
   """Generates an Android OTA package that has A/B update payload."""
   # Stage the output zip package for package signing.
   if not OPTIONS.no_signing:
@@ -2084,11 +2008,10 @@
     else:
       logger.warning("Cannot find care map file in target_file package")
 
-  AddCompatibilityArchiveIfTrebleEnabled(
-      target_zip, output_zip, target_info, source_info)
-
   common.ZipClose(target_zip)
 
+  CheckVintfIfTrebleEnabled(target_file, target_info)
+
   # We haven't written the metadata entry yet, which will be handled in
   # FinalizeMetadata().
   common.ZipClose(output_zip)
@@ -2104,6 +2027,66 @@
   FinalizeMetadata(metadata, staging_file, output_file, needed_property_files)
 
 
+def GenerateNonAbOtaPackage(target_file, output_file, source_file=None):
+  """Generates a non-A/B OTA package."""
+  # Sanity check the loaded info dicts first.
+  if OPTIONS.info_dict.get("no_recovery") == "true":
+    raise common.ExternalError(
+        "--- target build has specified no recovery ---")
+
+  # Non-A/B OTAs rely on /cache partition to store temporary files.
+  cache_size = OPTIONS.info_dict.get("cache_size")
+  if cache_size is None:
+    logger.warning("--- can't determine the cache partition size ---")
+  OPTIONS.cache_size = cache_size
+
+  if OPTIONS.extra_script is not None:
+    with open(OPTIONS.extra_script) as fp:
+      OPTIONS.extra_script = fp.read()
+
+  if OPTIONS.extracted_input is not None:
+    OPTIONS.input_tmp = OPTIONS.extracted_input
+  else:
+    logger.info("unzipping target target-files...")
+    OPTIONS.input_tmp = common.UnzipTemp(target_file, UNZIP_PATTERN)
+  OPTIONS.target_tmp = OPTIONS.input_tmp
+
+  # If the caller explicitly specified the device-specific extensions path via
+  # -s / --device_specific, use that. Otherwise, use META/releasetools.py if it
+  # is present in the target target_files. Otherwise, take the path of the file
+  # from 'tool_extensions' in the info dict and look for that in the local
+  # filesystem, relative to the current directory.
+  if OPTIONS.device_specific is None:
+    from_input = os.path.join(OPTIONS.input_tmp, "META", "releasetools.py")
+    if os.path.exists(from_input):
+      logger.info("(using device-specific extensions from target_files)")
+      OPTIONS.device_specific = from_input
+    else:
+      OPTIONS.device_specific = OPTIONS.info_dict.get("tool_extensions")
+
+  if OPTIONS.device_specific is not None:
+    OPTIONS.device_specific = os.path.abspath(OPTIONS.device_specific)
+
+  # Generate a full OTA.
+  if source_file is None:
+    with zipfile.ZipFile(target_file) as input_zip:
+      WriteFullOTAPackage(
+          input_zip,
+          output_file)
+
+  # Generate an incremental OTA.
+  else:
+    logger.info("unzipping source target-files...")
+    OPTIONS.source_tmp = common.UnzipTemp(
+        OPTIONS.incremental_source, UNZIP_PATTERN)
+    with zipfile.ZipFile(target_file) as input_zip, \
+        zipfile.ZipFile(source_file) as source_zip:
+      WriteBlockIncrementalOTAPackage(
+          input_zip,
+          source_zip,
+          output_file)
+
+
 def main(argv):
 
   def option_handler(o, a):
@@ -2170,6 +2153,8 @@
       OPTIONS.skip_compatibility_check = True
     elif o == "--output_metadata_path":
       OPTIONS.output_metadata_path = a
+    elif o == "--disable_fec_computation":
+      OPTIONS.disable_fec_computation = True
     else:
       return False
     return True
@@ -2204,6 +2189,7 @@
                                  "retrofit_dynamic_partitions",
                                  "skip_compatibility_check",
                                  "output_metadata_path=",
+                                 "disable_fec_computation",
                              ], extra_option_handler=option_handler)
 
   if len(args) != 2:
@@ -2278,76 +2264,29 @@
     OPTIONS.key_passwords = common.GetKeyPasswords([OPTIONS.package_key])
 
   if ab_update:
-    WriteABOTAPackageWithBrilloScript(
+    GenerateAbOtaPackage(
         target_file=args[0],
         output_file=args[1],
         source_file=OPTIONS.incremental_source)
 
-    logger.info("done.")
-    return
-
-  # Sanity check the loaded info dicts first.
-  if OPTIONS.info_dict.get("no_recovery") == "true":
-    raise common.ExternalError(
-        "--- target build has specified no recovery ---")
-
-  # Non-A/B OTAs rely on /cache partition to store temporary files.
-  cache_size = OPTIONS.info_dict.get("cache_size")
-  if cache_size is None:
-    logger.warning("--- can't determine the cache partition size ---")
-  OPTIONS.cache_size = cache_size
-
-  if OPTIONS.extra_script is not None:
-    with open(OPTIONS.extra_script) as fp:
-      OPTIONS.extra_script = fp.read()
-
-  if OPTIONS.extracted_input is not None:
-    OPTIONS.input_tmp = OPTIONS.extracted_input
   else:
-    logger.info("unzipping target target-files...")
-    OPTIONS.input_tmp = common.UnzipTemp(args[0], UNZIP_PATTERN)
-  OPTIONS.target_tmp = OPTIONS.input_tmp
+    GenerateNonAbOtaPackage(
+        target_file=args[0],
+        output_file=args[1],
+        source_file=OPTIONS.incremental_source)
 
-  # If the caller explicitly specified the device-specific extensions path via
-  # -s / --device_specific, use that. Otherwise, use META/releasetools.py if it
-  # is present in the target target_files. Otherwise, take the path of the file
-  # from 'tool_extensions' in the info dict and look for that in the local
-  # filesystem, relative to the current directory.
-  if OPTIONS.device_specific is None:
-    from_input = os.path.join(OPTIONS.input_tmp, "META", "releasetools.py")
-    if os.path.exists(from_input):
-      logger.info("(using device-specific extensions from target_files)")
-      OPTIONS.device_specific = from_input
-    else:
-      OPTIONS.device_specific = OPTIONS.info_dict.get("tool_extensions")
+  # Post OTA generation works.
+  if OPTIONS.incremental_source is not None and OPTIONS.log_diff:
+    logger.info("Generating diff logs...")
+    logger.info("Unzipping target-files for diffing...")
+    target_dir = common.UnzipTemp(args[0], TARGET_DIFFING_UNZIP_PATTERN)
+    source_dir = common.UnzipTemp(
+        OPTIONS.incremental_source, TARGET_DIFFING_UNZIP_PATTERN)
 
-  if OPTIONS.device_specific is not None:
-    OPTIONS.device_specific = os.path.abspath(OPTIONS.device_specific)
-
-  # Generate a full OTA.
-  if OPTIONS.incremental_source is None:
-    with zipfile.ZipFile(args[0], 'r') as input_zip:
-      WriteFullOTAPackage(
-          input_zip,
-          output_file=args[1])
-
-  # Generate an incremental OTA.
-  else:
-    logger.info("unzipping source target-files...")
-    OPTIONS.source_tmp = common.UnzipTemp(
-        OPTIONS.incremental_source, UNZIP_PATTERN)
-    with zipfile.ZipFile(args[0], 'r') as input_zip, \
-        zipfile.ZipFile(OPTIONS.incremental_source, 'r') as source_zip:
-      WriteBlockIncrementalOTAPackage(
-          input_zip,
-          source_zip,
-          output_file=args[1])
-
-    if OPTIONS.log_diff:
-      with open(OPTIONS.log_diff, 'w') as out_file:
-        import target_files_diff
-        target_files_diff.recursiveDiff(
-            '', OPTIONS.source_tmp, OPTIONS.input_tmp, out_file)
+    with open(OPTIONS.log_diff, 'w') as out_file:
+      import target_files_diff
+      target_files_diff.recursiveDiff(
+          '', source_dir, target_dir, out_file)
 
   logger.info("done.")
 
diff --git a/tools/releasetools/test_check_target_files_vintf.py b/tools/releasetools/test_check_target_files_vintf.py
new file mode 100644
index 0000000..a1328c2
--- /dev/null
+++ b/tools/releasetools/test_check_target_files_vintf.py
@@ -0,0 +1,143 @@
+#
+# 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.
+#
+
+import os.path
+
+import common
+import test_utils
+from check_target_files_vintf import CheckVintf
+
+# A skeleton target files directory structure. This is VINTF compatible.
+SKELETON_TARGET_FILE_STRUCTURE = {
+    # Empty files
+    'PRODUCT/build.prop': '',
+    'PRODUCT/etc/build.prop': '',
+    'VENDOR/etc/build.prop': '',
+    'ODM/build.prop': '',
+    'ODM/etc/build.prop': '',
+    'RECOVERY/RAMDISK/etc/recovery.fstab': '',
+    'SYSTEM/build.prop': '',
+    'SYSTEM/etc/build.prop': '',
+    'SYSTEM_EXT/build.prop': '',
+    'SYSTEM_EXT/etc/build.prop': '',
+
+    # Non-empty files
+    'SYSTEM/compatibility_matrix.xml':"""
+        <compatibility-matrix version="1.0" type="framework">
+            <sepolicy>
+                <sepolicy-version>0.0</sepolicy-version>
+                <kernel-sepolicy-version>0</kernel-sepolicy-version>
+            </sepolicy>
+        </compatibility-matrix>""",
+    'SYSTEM/manifest.xml':
+        '<manifest version="1.0" type="framework" />',
+    'VENDOR/build.prop': 'ro.product.first_api_level=29\n',
+    'VENDOR/compatibility_matrix.xml':
+        '<compatibility-matrix version="1.0" type="device" />',
+    'VENDOR/manifest.xml':
+        '<manifest version="1.0" type="device"/>',
+    'META/misc_info.txt':
+        'recovery_api_version=3\nfstab_version=2\nvintf_enforce=true\n',
+}
+
+
+def write_string_to_file(content, path, mode='w'):
+  if not os.path.isdir(os.path.dirname(path)):
+    os.makedirs(os.path.dirname(path))
+  with open(path, mode=mode) as f:
+    f.write(content)
+
+
+class CheckTargetFilesVintfTest(test_utils.ReleaseToolsTestCase):
+
+  def setUp(self):
+    self.testdata_dir = test_utils.get_testdata_dir()
+
+  def prepare_test_dir(self, test_delta_rel_path):
+    test_delta_dir = os.path.join(self.testdata_dir, test_delta_rel_path)
+    test_dir = common.MakeTempDir(prefix='check_target_files_vintf')
+
+    # Create a skeleton directory structure of target files
+    for rel_path, content in SKELETON_TARGET_FILE_STRUCTURE.items():
+      write_string_to_file(content, os.path.join(test_dir, rel_path))
+
+    # Overwrite with files from test_delta_rel_path
+    for root, _, files in os.walk(test_delta_dir):
+      rel_root = os.path.relpath(root, test_delta_dir)
+      for f in files:
+        output_file = os.path.join(test_dir, rel_root, f)
+        with open(os.path.join(root, f)) as inp:
+          write_string_to_file(inp.read(), output_file)
+
+    return test_dir
+
+  @test_utils.SkipIfExternalToolsUnavailable()
+  def test_CheckVintf_sanity(self):
+    msg = 'Sanity check with skeleton target files failed.'
+    test_dir = self.prepare_test_dir('does-not-exist')
+    self.assertTrue(CheckVintf(test_dir), msg=msg)
+
+  @test_utils.SkipIfExternalToolsUnavailable()
+  def test_CheckVintf_matrix_incompat(self):
+    msg = 'vintf/matrix_incompat should be incompatible because sepolicy ' \
+          'version fails to match'
+    test_dir = self.prepare_test_dir('vintf/matrix_incompat')
+    self.assertFalse(CheckVintf(test_dir), msg=msg)
+
+  @test_utils.SkipIfExternalToolsUnavailable()
+  def test_CheckVintf_kernel_compat(self):
+    msg = 'vintf/kernel with 4.14.1 kernel version should be compatible'
+    test_dir = self.prepare_test_dir('vintf/kernel')
+    write_string_to_file('', os.path.join(test_dir, 'META/kernel_configs.txt'))
+    write_string_to_file('4.14.1',
+                         os.path.join(test_dir, 'META/kernel_version.txt'))
+    self.assertTrue(CheckVintf(test_dir), msg=msg)
+
+  @test_utils.SkipIfExternalToolsUnavailable()
+  def test_CheckVintf_kernel_incompat(self):
+    msg = 'vintf/kernel with 4.14.0 kernel version should be incompatible ' \
+          'because 4.14.1 kernel version is required'
+    test_dir = self.prepare_test_dir('vintf/kernel')
+    write_string_to_file('', os.path.join(test_dir, 'META/kernel_configs.txt'))
+    write_string_to_file('4.14.0',
+                         os.path.join(test_dir, 'META/kernel_version.txt'))
+    self.assertFalse(CheckVintf(test_dir), msg=msg)
+
+  @test_utils.SkipIfExternalToolsUnavailable()
+  def test_CheckVintf_sku_compat(self):
+    msg = 'vintf/sku_compat should be compatible because ' \
+          'ODM/etc/vintf/manifest_sku.xml has the required HALs'
+    test_dir = self.prepare_test_dir('vintf/sku_compat')
+    write_string_to_file('vintf_odm_manifest_skus=sku',
+                         os.path.join(test_dir, 'META/misc_info.txt'), mode='a')
+    self.assertTrue(CheckVintf(test_dir), msg=msg)
+
+  @test_utils.SkipIfExternalToolsUnavailable()
+  def test_CheckVintf_sku_incompat(self):
+    msg = 'vintf/sku_compat should be compatible because ' \
+          'ODM/etc/vintf/manifest_sku.xml does not have the required HALs'
+    test_dir = self.prepare_test_dir('vintf/sku_incompat')
+    write_string_to_file('vintf_odm_manifest_skus=sku',
+                         os.path.join(test_dir, 'META/misc_info.txt'), mode='a')
+    self.assertFalse(CheckVintf(test_dir), msg=msg)
+
+  @test_utils.SkipIfExternalToolsUnavailable()
+  def test_CheckVintf_bad_xml(self):
+    test_dir = self.prepare_test_dir('does-not-exist')
+    write_string_to_file('not an XML',
+                         os.path.join(test_dir, 'VENDOR/manifest.xml'))
+    # Should raise an error because a file has invalid format.
+    self.assertRaises(common.ExternalError, CheckVintf, test_dir)
diff --git a/tools/releasetools/test_sign_target_files_apks.py b/tools/releasetools/test_sign_target_files_apks.py
index 70c147e..e0a635a 100644
--- a/tools/releasetools/test_sign_target_files_apks.py
+++ b/tools/releasetools/test_sign_target_files_apks.py
@@ -525,3 +525,26 @@
             'system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem',
             'build/make/target/product/security/testkey'),
         }, keys_info)
+
+  def test_ReadApexKeysInfo_presignedKeys(self):
+    apex_keys = self.APEX_KEYS_TXT + (
+        'name="apex.apexd_test_different_app2.apex" '
+        'private_key="PRESIGNED" '
+        'public_key="PRESIGNED" '
+        'container_certificate="PRESIGNED" '
+        'container_private_key="PRESIGNED"')
+    target_files = common.MakeTempFile(suffix='.zip')
+    with zipfile.ZipFile(target_files, 'w') as target_files_zip:
+      target_files_zip.writestr('META/apexkeys.txt', apex_keys)
+
+    with zipfile.ZipFile(target_files) as target_files_zip:
+      keys_info = ReadApexKeysInfo(target_files_zip)
+
+    self.assertEqual({
+        'apex.apexd_test.apex': (
+            'system/apex/apexd/apexd_testdata/com.android.apex.test_package.pem',
+            'build/make/target/product/security/testkey'),
+        'apex.apexd_test_different_app.apex': (
+            'system/apex/apexd/apexd_testdata/com.android.apex.test_package_2.pem',
+            'build/make/target/product/security/testkey'),
+        }, keys_info)
diff --git a/tools/releasetools/testdata/vintf/kernel/SYSTEM/compatibility_matrix.xml b/tools/releasetools/testdata/vintf/kernel/SYSTEM/compatibility_matrix.xml
new file mode 100644
index 0000000..ed46b6b
--- /dev/null
+++ b/tools/releasetools/testdata/vintf/kernel/SYSTEM/compatibility_matrix.xml
@@ -0,0 +1,7 @@
+<compatibility-matrix version="1.0" type="framework">
+    <kernel version="4.14.1" />
+    <sepolicy>
+        <sepolicy-version>0.0</sepolicy-version>
+        <kernel-sepolicy-version>0</kernel-sepolicy-version>
+    </sepolicy>
+</compatibility-matrix>
diff --git a/tools/releasetools/testdata/vintf/matrix_incompat/SYSTEM/compatibility_matrix.xml b/tools/releasetools/testdata/vintf/matrix_incompat/SYSTEM/compatibility_matrix.xml
new file mode 100644
index 0000000..5d891fa
--- /dev/null
+++ b/tools/releasetools/testdata/vintf/matrix_incompat/SYSTEM/compatibility_matrix.xml
@@ -0,0 +1,6 @@
+<compatibility-matrix version="1.0" type="framework">
+    <sepolicy>
+        <sepolicy-version>1.0</sepolicy-version>
+        <kernel-sepolicy-version>0</kernel-sepolicy-version>
+    </sepolicy>
+</compatibility-matrix>
diff --git a/tools/releasetools/testdata/vintf/sku_compat/ODM/etc/vintf/manifest_sku.xml b/tools/releasetools/testdata/vintf/sku_compat/ODM/etc/vintf/manifest_sku.xml
new file mode 100644
index 0000000..bcd7ce4
--- /dev/null
+++ b/tools/releasetools/testdata/vintf/sku_compat/ODM/etc/vintf/manifest_sku.xml
@@ -0,0 +1,7 @@
+<manifest version="1.0" type="device">
+    <hal format="hidl">
+        <name>foo</name>
+        <transport>hwbinder</transport>
+        <fqname>@1.0::IFoo/default</fqname>
+    </hal>
+</manifest>
diff --git a/tools/releasetools/testdata/vintf/sku_compat/SYSTEM/compatibility_matrix.xml b/tools/releasetools/testdata/vintf/sku_compat/SYSTEM/compatibility_matrix.xml
new file mode 100644
index 0000000..19a9b6a
--- /dev/null
+++ b/tools/releasetools/testdata/vintf/sku_compat/SYSTEM/compatibility_matrix.xml
@@ -0,0 +1,14 @@
+<compatibility-matrix version="1.0" type="framework">
+    <hal format="hidl" optional="false">
+        <name>foo</name>
+        <version>1.0</version>
+        <interface>
+            <name>IFoo</name>
+            <instance>default</instance>
+        </interface>
+    </hal>
+    <sepolicy>
+        <sepolicy-version>0.0</sepolicy-version>
+        <kernel-sepolicy-version>0</kernel-sepolicy-version>
+    </sepolicy>
+</compatibility-matrix>
diff --git a/tools/releasetools/testdata/vintf/sku_incompat/ODM/etc/vintf/manifest_sku.xml b/tools/releasetools/testdata/vintf/sku_incompat/ODM/etc/vintf/manifest_sku.xml
new file mode 100644
index 0000000..bcd7ce4
--- /dev/null
+++ b/tools/releasetools/testdata/vintf/sku_incompat/ODM/etc/vintf/manifest_sku.xml
@@ -0,0 +1,7 @@
+<manifest version="1.0" type="device">
+    <hal format="hidl">
+        <name>foo</name>
+        <transport>hwbinder</transport>
+        <fqname>@1.0::IFoo/default</fqname>
+    </hal>
+</manifest>
diff --git a/tools/releasetools/testdata/vintf/sku_incompat/SYSTEM/compatibility_matrix.xml b/tools/releasetools/testdata/vintf/sku_incompat/SYSTEM/compatibility_matrix.xml
new file mode 100644
index 0000000..e0e0d6c
--- /dev/null
+++ b/tools/releasetools/testdata/vintf/sku_incompat/SYSTEM/compatibility_matrix.xml
@@ -0,0 +1,14 @@
+<compatibility-matrix version="1.0" type="framework">
+    <hal format="hidl" optional="false">
+        <name>foo</name>
+        <version>1.1</version>
+        <interface>
+            <name>IFoo</name>
+            <instance>default</instance>
+        </interface>
+    </hal>
+    <sepolicy>
+        <sepolicy-version>0.0</sepolicy-version>
+        <kernel-sepolicy-version>0</kernel-sepolicy-version>
+    </sepolicy>
+</compatibility-matrix>