Merge "Use file_contexts for flattened apexes"
diff --git a/core/Makefile b/core/Makefile
index 61dcf3e..7104334 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -773,8 +773,11 @@
 
 ifeq ($(TARGET_BOOTIMAGE_USE_EXT2),true)
 $(error TARGET_BOOTIMAGE_USE_EXT2 is not supported anymore)
+endif # TARGET_BOOTIMAGE_USE_EXT2
 
-else ifeq (true,$(BOARD_AVB_ENABLE)) # TARGET_BOOTIMAGE_USE_EXT2 != true
+$(foreach b,$(INSTALLED_BOOTIMAGE_TARGET), $(eval $(call add-dependency,$(b),$(call bootimage-to-kernel,$(b)))))
+
+ifeq (true,$(BOARD_AVB_ENABLE))
 
 # $1: boot image target
 define build_boot_board_avb_enabled
@@ -787,7 +790,7 @@
           $(BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS)
 endef
 
-$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(AVBTOOL) $(INTERNAL_BOOTIMAGE_FILES) $(BOARD_AVB_BOOT_KEY_PATH) $(call bootimage-to-kernel,$@)
+$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(AVBTOOL) $(INTERNAL_BOOTIMAGE_FILES) $(BOARD_AVB_BOOT_KEY_PATH)
 	$(call pretty,"Target boot image: $@")
 	$(call build_boot_board_avb_enabled,$@)
 
@@ -805,7 +808,7 @@
   $(call assert-max-image-size,$(1),$(BOARD_BOOTIMAGE_PARTITION_SIZE))
 endef
 
-$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(BOOT_SIGNER) $(call bootimage-to-kernel,$@)
+$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(BOOT_SIGNER)
 	$(call pretty,"Target boot image: $@")
 	$(call build_boot_supports_boot_signer,$@)
 
@@ -823,7 +826,7 @@
   $(call assert-max-image-size,$(1),$(BOARD_BOOTIMAGE_PARTITION_SIZE))
 endef
 
-$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(VBOOT_SIGNER) $(FUTILITY) $(call bootimage-to-kernel,$@)
+$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(VBOOT_SIGNER) $(FUTILITY)
 	$(call pretty,"Target boot image: $@")
 	$(call build_boot_supports_vboot,$@)
 
@@ -840,7 +843,7 @@
   $(call assert-max-image-size,$1,$(BOARD_BOOTIMAGE_PARTITION_SIZE))
 endef
 
-$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(call bootimage-to-kernel,$@)
+$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES)
 	$(call pretty,"Target boot image: $@")
 	$(call build_boot_novboot,$@)
 
@@ -849,7 +852,7 @@
 	@echo "make $@: ignoring dependencies"
 	$(foreach b,$(INSTALLED_BOOTIMAGE_TARGET),$(call build_boot_novboot,$(b)))
 
-endif # TARGET_BOOTIMAGE_USE_EXT2
+endif # BOARD_AVB_ENABLE
 endif # BUILDING_BOOT_IMAGE
 
 else # TARGET_NO_KERNEL == "true"
@@ -1974,6 +1977,7 @@
 endif
 
 ifeq ($(BOARD_USES_RECOVERY_AS_BOOT),true)
+$(foreach b,$(INSTALLED_BOOTIMAGE_TARGET), $(eval $(call add-dependency,$(b),$(call bootimage-to-kernel,$(b)))))
 $(INSTALLED_BOOTIMAGE_TARGET): $(recoveryimage-deps)
 	$(call pretty,"Target boot image from recovery: $@")
 	$(call build-recoveryimage-target, $@, $(PRODUCT_OUT)/$(subst .img,,$(subst boot,kernel,$(notdir $@))))
diff --git a/core/check_elf_file.mk b/core/check_elf_file.mk
index d54a5b7..b5be81f 100644
--- a/core/check_elf_file.mk
+++ b/core/check_elf_file.mk
@@ -14,12 +14,14 @@
 # - my_installed_module_stem
 # - my_prebuilt_src_file
 # - my_check_elf_file_shared_lib_files
+# - my_system_shared_libraries
 
 ifndef LOCAL_IS_HOST_MODULE
 ifneq ($(filter $(LOCAL_MODULE_CLASS),SHARED_LIBRARIES EXECUTABLES NATIVE_TESTS),)
 check_elf_files_stamp := $(intermediates)/check_elf_files.timestamp
 $(check_elf_files_stamp): PRIVATE_SONAME := $(if $(filter $(LOCAL_MODULE_CLASS),SHARED_LIBRARIES),$(my_installed_module_stem))
 $(check_elf_files_stamp): PRIVATE_ALLOW_UNDEFINED_SYMBOLS := $(LOCAL_ALLOW_UNDEFINED_SYMBOLS)
+$(check_elf_files_stamp): PRIVATE_SYSTEM_SHARED_LIBRARIES := $(my_system_shared_libraries)
 # PRIVATE_SHARED_LIBRARY_FILES are file paths to built shared libraries.
 # In addition to $(my_check_elf_file_shared_lib_files), some file paths are
 # added by `resolve-shared-libs-for-elf-file-check` from `core/main.mk`.
@@ -33,6 +35,7 @@
 	    --skip-unknown-elf-machine \
 	    $(if $(PRIVATE_SONAME),--soname $(PRIVATE_SONAME)) \
 	    $(foreach l,$(PRIVATE_SHARED_LIBRARY_FILES),--shared-lib $(l)) \
+	    $(foreach l,$(PRIVATE_SYSTEM_SHARED_LIBRARIES),--system-shared-lib $(l)) \
 	    $(if $(PRIVATE_ALLOW_UNDEFINED_SYMBOLS),--allow-undefined-symbols) \
 	    --llvm-readobj=$(LLVM_READOBJ) \
 	    $<
diff --git a/core/main.mk b/core/main.mk
index ebec885..8c29045 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -1639,6 +1639,10 @@
 # dist_files only for putting your library into the dist directory with a full build.
 .PHONY: dist_files
 
+ifeq ($(SOONG_COLLECT_JAVA_DEPS), true)
+  $(call dist-for-goals, dist_files, $(SOONG_OUT_DIR)/module_bp_java_deps.json)
+endif
+
 .PHONY: apps_only
 ifneq ($(TARGET_BUILD_APPS),)
   # If this build is just for apps, only build apps and not the full system by default.
diff --git a/core/soong_cc_prebuilt.mk b/core/soong_cc_prebuilt.mk
index a0315a5..770408c 100644
--- a/core/soong_cc_prebuilt.mk
+++ b/core/soong_cc_prebuilt.mk
@@ -91,6 +91,7 @@
 ifdef LOCAL_INSTALLED_MODULE
   ifneq ($(LOCAL_CHECK_ELF_FILES),)
     my_prebuilt_src_file := $(LOCAL_PREBUILT_MODULE_FILE)
+    my_system_shared_libraries := $(LOCAL_SYSTEM_SHARED_LIBRARIES)
     include $(BUILD_SYSTEM)/check_elf_file.mk
   endif
 endif
@@ -149,11 +150,14 @@
 $(LOCAL_BUILT_MODULE): $(LOCAL_PREBUILT_MODULE_FILE)
 ifeq ($(LOCAL_IS_HOST_MODULE) $(if $(filter EXECUTABLES SHARED_LIBRARIES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),true,),true true)
 	$(copy-or-link-prebuilt-to-target)
+  ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
+	[ -x $@ ] || $(call echo-error,$@,Target of symlink is not executable)
+  endif
 else
 	$(transform-prebuilt-to-target)
-endif
-ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
+  ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
 	$(hide) chmod +x $@
+  endif
 endif
 
 ifndef LOCAL_IS_HOST_MODULE
diff --git a/core/soong_rust_prebuilt.mk b/core/soong_rust_prebuilt.mk
index b54f300..2f4c6e7 100644
--- a/core/soong_rust_prebuilt.mk
+++ b/core/soong_rust_prebuilt.mk
@@ -59,11 +59,14 @@
 $(LOCAL_BUILT_MODULE): $(LOCAL_PREBUILT_MODULE_FILE)
 ifeq ($(LOCAL_IS_HOST_MODULE) $(if $(filter EXECUTABLES SHARED_LIBRARIES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),true,),true true)
 	$(copy-or-link-prebuilt-to-target)
+  ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
+	[ -x $@ ] || $(call echo-error,$@,Target of symlink is not executable)
+  endif
 else
 	$(transform-prebuilt-to-target)
-endif
-ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
+  ifneq ($(filter EXECUTABLES NATIVE_TESTS,$(LOCAL_MODULE_CLASS)),)
 	$(hide) chmod +x $@
+  endif
 endif
 
 ifndef LOCAL_IS_HOST_MODULE
diff --git a/core/tasks/art-host-tests.mk b/core/tasks/art-host-tests.mk
new file mode 100644
index 0000000..96e2c74
--- /dev/null
+++ b/core/tasks/art-host-tests.mk
@@ -0,0 +1,29 @@
+# Copyright (C) 2020 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.
+
+.PHONY: art-host-tests
+
+intermediates_dir := $(call intermediates-dir-for,PACKAGING,art-host-tests)
+art_host_tests_zip := $(PRODUCT_OUT)/art-host-tests.zip
+$(art_host_tests_zip) : $(COMPATIBILITY.art-host-tests.FILES) $(SOONG_ZIP)
+	echo $(sort $(COMPATIBILITY.art-host-tests.FILES)) | tr " " "\n" > $@.list
+	grep $(HOST_OUT_TESTCASES) $@.list > $@-host.list || true
+	grep $(TARGET_OUT_TESTCASES) $@.list > $@-target.list || true
+	$(hide) $(SOONG_ZIP) -d -o $@ -P host -C $(HOST_OUT) -l $@-host.list -P target -C $(PRODUCT_OUT) -l $@-target.list
+	rm -f $@.list $@-host.list $@-target.list
+
+art-host-tests: $(art_host_tests_zip)
+$(call dist-for-goals, art-host-tests, $(art_host_tests_zip))
+
+tests: art-host-tests
diff --git a/core/tasks/find-shareduid-violation.mk b/core/tasks/find-shareduid-violation.mk
index 86052f2..972b1ec 100644
--- a/core/tasks/find-shareduid-violation.mk
+++ b/core/tasks/find-shareduid-violation.mk
@@ -28,5 +28,13 @@
 
 $(shareduid_violation_modules_filename): $(find_shareduid_script)
 $(shareduid_violation_modules_filename): $(AAPT2)
-	$(find_shareduid_script) $(PRODUCT_OUT) $(AAPT2) > $@
+	$(find_shareduid_script) \
+		--product_out $(PRODUCT_OUT) \
+		--aapt $(AAPT2) \
+		--copy_out_system $(TARGET_COPY_OUT_SYSTEM) \
+		--copy_out_vendor $(TARGET_COPY_OUT_VENDOR) \
+		--copy_out_product $(TARGET_COPY_OUT_PRODUCT) \
+		--copy_out_system_ext $(TARGET_COPY_OUT_SYSTEM_EXT) \
+		> $@
+
 $(call dist-for-goals,droidcore,$(shareduid_violation_modules_filename))
diff --git a/core/tasks/find-shareduid-violation.py b/core/tasks/find-shareduid-violation.py
index 1f8e4df..8dba5a1 100755
--- a/core/tasks/find-shareduid-violation.py
+++ b/core/tasks/find-shareduid-violation.py
@@ -14,19 +14,31 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+import argparse
+import json
 import os
 import subprocess
-from glob import glob
-from collections import defaultdict
 import sys
-import json
 
-if len(sys.argv) < 3:
-    product_out = os.environ["PRODUCT_OUT"]
-    aapt = "aapt2"
-else:
-    product_out = sys.argv[1]
-    aapt = sys.argv[2]
+from collections import defaultdict
+from glob import glob
+
+def parse_args():
+    """Parse commandline arguments."""
+    parser = argparse.ArgumentParser(description='Find sharedUserId violators')
+    parser.add_argument('--product_out', help='PRODUCT_OUT directory',
+                        default=os.environ.get("PRODUCT_OUT"))
+    parser.add_argument('--aapt', help='Path to aapt or aapt2',
+                        default="aapt2")
+    parser.add_argument('--copy_out_system', help='TARGET_COPY_OUT_SYSTEM',
+                        default="system")
+    parser.add_argument('--copy_out_vendor', help='TARGET_COPY_OUT_VENDOR',
+                        default="vendor")
+    parser.add_argument('--copy_out_product', help='TARGET_COPY_OUT_PRODUCT',
+                        default="product")
+    parser.add_argument('--copy_out_system_ext', help='TARGET_COPY_OUT_SYSTEM_EXT',
+                        default="system_ext")
+    return parser.parse_args()
 
 def execute(cmd):
     p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
@@ -45,7 +57,6 @@
     else:
         print(error_msg, file=sys.stderr)
         sys.exit()
-        return None
 
     for l in manifest.split('\n'):
         if "sharedUserId" in l:
@@ -53,18 +64,28 @@
     return None
 
 
-partitions = ["system", "vendor", "product"]
+args = parse_args()
+
+product_out = args.product_out
+aapt = args.aapt
+
+partitions = (
+        ("system", args.copy_out_system),
+        ("vendor", args.copy_out_vendor),
+        ("product", args.copy_out_product),
+        ("system_ext", args.copy_out_system_ext),
+)
 
 shareduid_app_dict = defaultdict(list)
 
-for p in partitions:
-    for f in glob(os.path.join(product_out, p, "*", "*", "*.apk")):
+for part, location in partitions:
+    for f in glob(os.path.join(product_out, location, "*", "*", "*.apk")):
         apk_file = os.path.basename(f)
         shared_uid = extract_shared_uid(f)
 
         if shared_uid is None:
             continue
-        shareduid_app_dict[shared_uid].append((p, apk_file))
+        shareduid_app_dict[shared_uid].append((part, apk_file))
 
 
 output = defaultdict(lambda: defaultdict(list))
diff --git a/core/tasks/platform_availability_check.mk b/core/tasks/platform_availability_check.mk
index f252ff5..7ce6b40 100644
--- a/core/tasks/platform_availability_check.mk
+++ b/core/tasks/platform_availability_check.mk
@@ -51,6 +51,6 @@
   endef
 
   $(foreach m,$(_modules_not_available_for_platform),\
-    $(foreach i,$(ALL_MODULES.$(m).INSTALLED),\
+    $(foreach i,$(filter-out $(HOST_OUT)/%,$(ALL_MODULES.$(m).INSTALLED)),\
       $(eval $(call not_available_for_platform_rule,$(i),$(m)))))
 endif
diff --git a/envsetup.sh b/envsetup.sh
index b836e54..a3b07a7 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -356,7 +356,7 @@
 
 function addcompletions()
 {
-    local T dir f
+    local f=
 
     # Keep us from trying to run in something that's neither bash nor zsh.
     if [ -z "$BASH_VERSION" -a -z "$ZSH_VERSION" ]; then
diff --git a/rbesetup.sh b/rbesetup.sh
index 724ad7d..0182bfd 100644
--- a/rbesetup.sh
+++ b/rbesetup.sh
@@ -1,4 +1,31 @@
-source build/envsetup.sh
+function _source_env_setup_script() {
+  local -r ENV_SETUP_SCRIPT="build/make/envsetup.sh"
+  local -r TOP_DIR=$(
+    while [[ ! -f "${ENV_SETUP_SCRIPT}" ]] && [[ "${PWD}" != "/" ]]; do
+      \cd ..
+    done
+    if [[ -f "${ENV_SETUP_SCRIPT}" ]]; then
+      echo "$(PWD= /bin/pwd -P)"
+    fi
+  )
+
+  local -r FULL_PATH_ENV_SETUP_SCRIPT="${TOP_DIR}/${ENV_SETUP_SCRIPT}"
+  if [[ ! -f "${FULL_PATH_ENV_SETUP_SCRIPT}" ]]; then
+    echo "ERROR: Unable to source ${ENV_SETUP_SCRIPT}"
+    return 1
+  fi
+
+  # Need to change directory to the repo root so vendor scripts can be sourced
+  # as well.
+  local -r CUR_DIR=$PWD
+  \cd "${TOP_DIR}"
+  source "${FULL_PATH_ENV_SETUP_SCRIPT}"
+  \cd "${CUR_DIR}"
+}
+
+# This function needs to run first as the remaining defining functions may be
+# using the envsetup.sh defined functions.
+_source_env_setup_script || return
 
 # This function prefixes the given command with appropriate variables needed
 # for the build to be executed with RBE.
@@ -28,7 +55,7 @@
 # ANDROID_ENABLE_METRICS_UPLOAD.
 function _export_metrics_uploader() {
   local uploader_path="$(gettop)/vendor/google/misc/metrics_uploader_prebuilt/metrics_uploader.sh"
-  if [ -x "${uploader_path}" ]; then
+  if [[ -x "${uploader_path}" ]]; then
     export ANDROID_ENABLE_METRICS_UPLOAD="${uploader_path}"
   fi
 }
diff --git a/target/product/base_system.mk b/target/product/base_system.mk
index b97d98d..586c058 100644
--- a/target/product/base_system.mk
+++ b/target/product/base_system.mk
@@ -281,6 +281,12 @@
     system_manifest.xml \
     system_compatibility_matrix.xml \
 
+# HWASAN runtime for SANITIZE_TARGET=hwaddress builds
+ifneq (,$(filter hwaddress,$(SANITIZE_TARGET)))
+  PRODUCT_PACKAGES += \
+   libclang_rt.hwasan-aarch64-android.bootstrap
+endif
+
 # Host tools to install
 PRODUCT_HOST_PACKAGES += \
     BugReport \
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
index 1bd2af7..7633abe 100644
--- a/target/product/runtime_libart.mk
+++ b/target/product/runtime_libart.mk
@@ -92,8 +92,4 @@
     dalvik.vm.minidebuginfo=true \
     dalvik.vm.dex2oat-minidebuginfo=true
 
-# Enable iorapd by default
-PRODUCT_SYSTEM_PROPERTIES += \
-    ro.iorapd.enable=true
-
 PRODUCT_USES_DEFAULT_ART_CONFIG := true
diff --git a/target/product/virtual_ab_ota_compression.mk b/target/product/virtual_ab_ota_compression.mk
new file mode 100644
index 0000000..c4849be
--- /dev/null
+++ b/target/product/virtual_ab_ota_compression.mk
@@ -0,0 +1,21 @@
+#
+# Copyright (C) 2020 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_VENDOR_PROPERTIES += ro.virtual_ab.compression.enabled=true
+
+PRODUCT_PACKAGES += snapuserd_ramdisk
diff --git a/target/product/virtual_ab_ota_retrofit_compression.mk b/target/product/virtual_ab_ota_retrofit_compression.mk
new file mode 100644
index 0000000..8059f75
--- /dev/null
+++ b/target/product/virtual_ab_ota_retrofit_compression.mk
@@ -0,0 +1,22 @@
+#
+# Copyright (C) 2020 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_retrofit.mk)
+
+PRODUCT_VENDOR_PROPERTIES += ro.virtual_ab.compression.enabled=true
+
+PRODUCT_PACKAGES += snapuserd_ramdisk
+
diff --git a/tools/check_elf_file.py b/tools/check_elf_file.py
index ee8efd5..1ff8e65 100755
--- a/tools/check_elf_file.py
+++ b/tools/check_elf_file.py
@@ -397,7 +397,7 @@
       sys.exit(2)
 
 
-  def check_dt_needed(self):
+  def check_dt_needed(self, system_shared_lib_names):
     """Check whether all DT_NEEDED entries are specified in the build
     system."""
 
@@ -417,6 +417,11 @@
       dt_needed = sorted(set(self._file_under_test.dt_needed))
       modules = [re.sub('\\.so$', '', lib) for lib in dt_needed]
 
+      # Remove system shared libraries from the suggestion since they are added
+      # by default.
+      modules = [name for name in modules
+                 if name not in system_shared_lib_names]
+
       self._note()
       self._note('Fix suggestions:')
       self._note(
@@ -502,6 +507,11 @@
   parser.add_argument('--shared-lib', action='append', default=[],
                       help='Path to shared library dependencies')
 
+  # System Shared library names
+  parser.add_argument('--system-shared-lib', action='append', default=[],
+                      help='System shared libraries to be hidden from fix '
+                      'suggestions')
+
   # Check options
   parser.add_argument('--skip-bad-elf-magic', action='store_true',
                       help='Ignore the input file without the ELF magic word')
@@ -535,7 +545,7 @@
   if args.soname:
     checker.check_dt_soname(args.soname)
 
-  checker.check_dt_needed()
+  checker.check_dt_needed(args.system_shared_lib)
 
   if not args.allow_undefined_symbols:
     checker.check_symbols()
diff --git a/tools/releasetools/add_img_to_target_files.py b/tools/releasetools/add_img_to_target_files.py
index a1f8e31..eb041ec 100644
--- a/tools/releasetools/add_img_to_target_files.py
+++ b/tools/releasetools/add_img_to_target_files.py
@@ -739,6 +739,18 @@
   common.ZipClose(output_zip)
 
 
+def HasPartition(partition_name):
+  """Determines if the target files archive should build a given partition."""
+
+  return ((os.path.isdir(
+      os.path.join(OPTIONS.input_tmp, partition_name.upper())) and
+           OPTIONS.info_dict.get(
+               "building_{}_image".format(partition_name)) == "true") or
+          os.path.exists(
+              os.path.join(OPTIONS.input_tmp, "IMAGES",
+                           "{}.img".format(partition_name))))
+
+
 def AddImagesToTargetFiles(filename):
   """Creates and adds images (boot/recovery/system/...) to a target_files.zip.
 
@@ -767,49 +779,16 @@
   has_boot = OPTIONS.info_dict.get("no_boot") != "true"
   has_vendor_boot = OPTIONS.info_dict.get("vendor_boot") == "true"
 
-  # {vendor,odm,product,system_ext,vendor_dlkm,odm_dlkm}.img
-  # are unlike system.img or
-  # system_other.img, because it could be built from source, or  dropped into
-  # target_files.zip as a prebuilt blob. We consider either of them as
-  # {vendor,product,system_ext}.img being available, which could be
-  # used when generating vbmeta.img for AVB.
-  has_vendor = ((os.path.isdir(os.path.join(OPTIONS.input_tmp, "VENDOR")) and
-                 OPTIONS.info_dict.get("building_vendor_image") == "true") or
-                os.path.exists(
-                    os.path.join(OPTIONS.input_tmp, "IMAGES", "vendor.img")))
-  has_odm = ((os.path.isdir(os.path.join(OPTIONS.input_tmp, "ODM")) and
-              OPTIONS.info_dict.get("building_odm_image") == "true") or
-             os.path.exists(
-                 os.path.join(OPTIONS.input_tmp, "IMAGES", "odm.img")))
-  has_vendor_dlkm = ((os.path.isdir(os.path.join(OPTIONS.input_tmp,
-                                                 "VENDOR_DLKM")) and
-                      OPTIONS.info_dict.get("building_vendor_dlkm_image")
-                      == "true") or
-                     os.path.exists(
-                         os.path.join(OPTIONS.input_tmp, "IMAGES",
-                                      "vendor_dlkm.img")))
-  has_odm_dlkm = ((os.path.isdir(os.path.join(OPTIONS.input_tmp,
-                                              "ODM_DLKM")) and
-                   OPTIONS.info_dict.get("building_odm_dlkm_image")
-                   == "true") or
-                  os.path.exists(os.path.join(OPTIONS.input_tmp, "IMAGES",
-                                              "odm_dlkm.img")))
-  has_product = ((os.path.isdir(os.path.join(OPTIONS.input_tmp, "PRODUCT")) and
-                  OPTIONS.info_dict.get("building_product_image") == "true") or
-                 os.path.exists(
-                     os.path.join(OPTIONS.input_tmp, "IMAGES", "product.img")))
-  has_system_ext = (
-      (os.path.isdir(os.path.join(OPTIONS.input_tmp, "SYSTEM_EXT")) and
-       OPTIONS.info_dict.get("building_system_ext_image") == "true") or
-      os.path.exists(
-          os.path.join(OPTIONS.input_tmp, "IMAGES", "system_ext.img")))
-  has_system = (
-      os.path.isdir(os.path.join(OPTIONS.input_tmp, "SYSTEM")) and
-      OPTIONS.info_dict.get("building_system_image") == "true")
-
-  has_system_other = (
-      os.path.isdir(os.path.join(OPTIONS.input_tmp, "SYSTEM_OTHER")) and
-      OPTIONS.info_dict.get("building_system_other_image") == "true")
+  # {vendor,odm,product,system_ext,vendor_dlkm,odm_dlkm, system, system_other}.img
+  # can be built from source, or  dropped into target_files.zip as a prebuilt blob.
+  has_vendor = HasPartition("vendor")
+  has_odm = HasPartition("odm")
+  has_vendor_dlkm = HasPartition("vendor_dlkm")
+  has_odm_dlkm = HasPartition("odm_dlkm")
+  has_product = HasPartition("product")
+  has_system_ext = HasPartition("system_ext")
+  has_system = HasPartition("system")
+  has_system_other = HasPartition("system_other")
   has_userdata = OPTIONS.info_dict.get("building_userdata_image") == "true"
   has_cache = OPTIONS.info_dict.get("building_cache_image") == "true"
 
diff --git a/tools/releasetools/merge_target_files.py b/tools/releasetools/merge_target_files.py
index 45532f5..bfd2f90 100755
--- a/tools/releasetools/merge_target_files.py
+++ b/tools/releasetools/merge_target_files.py
@@ -197,8 +197,6 @@
     'PREBUILT_IMAGES/*',
     'RADIO/*',
     'VENDOR/*',
-    'VENDOR_DLKM/*',
-    'ODM_DLKM/*',
 )
 
 # VENDOR_EXTRACT_SPECIAL_ITEM_LIST is a list of items to extract from the