Merge changes from topic "vintf_ota_delete"

* changes:
  merge_target_files: Checks VINTF metadata of resulting target files
  Check VINTF compatibility at OTA generation time.
  releasetools: add tests for check_target_files_vintf
  Add a script to check VINTF compat of target files package.
diff --git a/core/aux_config.mk b/core/aux_config.mk
index a508a2d..86dc10a 100644
--- a/core/aux_config.mk
+++ b/core/aux_config.mk
@@ -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 e3f8a70..7147f6d 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -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/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 2e24eb9..b98027d 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:=
@@ -214,6 +215,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
@@ -241,6 +243,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/cxx_stl_setup.mk b/core/cxx_stl_setup.mk
index 55c4975..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
diff --git a/core/envsetup.mk b/core/envsetup.mk
index 92c5cca..c61760b 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -328,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
@@ -895,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/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/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/rbe.mk b/core/rbe.mk
index fb39d51..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 --labels=type=compile,lang=cpp,compiler=clang
+  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/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/target/board/BoardConfigMainlineCommon.mk b/target/board/BoardConfigMainlineCommon.mk
index 70cfe39..ff6defd 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.
diff --git a/target/product/base_system.mk b/target/product/base_system.mk
index 60646c3..cd98a48 100644
--- a/target/product/base_system.mk
+++ b/target/product/base_system.mk
@@ -359,6 +359,7 @@
     gdbserver \
     init-debug.rc \
     iotop \
+    iperf3 \
     iw \
     logpersist.start \
     logtagd.rc \
diff --git a/target/product/gsi/current.txt b/target/product/gsi/current.txt
index d954e9f..4b6c010 100644
--- a/target/product/gsi/current.txt
+++ b/target/product/gsi/current.txt
@@ -151,6 +151,7 @@
 VNDK-core: android.hardware.thermal@1.1.so
 VNDK-core: android.hardware.tv.cec@1.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
diff --git a/target/product/mainline_system.mk b/target/product/mainline_system.mk
index 8bcc212..1ada3c7 100644
--- a/target/product/mainline_system.mk
+++ b/target/product/mainline_system.mk
@@ -73,6 +73,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 \
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/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/common.py b/tools/releasetools/common.py
index 2401e46..8339cad 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"]
diff --git a/tools/releasetools/img_from_target_files.py b/tools/releasetools/img_from_target_files.py
index 4b94ad8..28b1b53 100755
--- a/tools/releasetools/img_from_target_files.py
+++ b/tools/releasetools/img_from_target_files.py
@@ -40,13 +40,21 @@
 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.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.
@@ -56,21 +64,21 @@
   """
   info = OPTIONS.info_dict = common.LoadInfoDict(input_file)
 
-  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")
+      output_zip, os.path.join(input_tmp, 'OTA', 'android-info.txt'),
+      'android-info.txt')
 
 
 def CopyUserImages(input_tmp, output_zip):
@@ -80,33 +88,33 @@
     input_tmp: path to the unzipped input.
     output_zip: a ZipFile instance to write images to.
   """
-  dynamic_images = [p + ".img" for p in OPTIONS.dynamic_partition_list]
+  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")
+  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"):
+    if OPTIONS.bootable_only and image not in ('boot.img', 'recovery.img'):
       continue
-    if not image.endswith(".img"):
+    if not image.endswith('.img'):
       continue
     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))
+    logger.info('writing %s to archive...', os.path.join('IMAGES', image))
     common.ZipWrite(output_zip, os.path.join(images_path, image), image)
 
 
 def WriteSuperImages(input_tmp, output_zip):
   """Writes super images from the unzipped input into output_zip.
 
-  This is only done if super_image_in_update_package is set to "true".
+  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.
@@ -122,21 +130,21 @@
 
   if OPTIONS.retrofit_dap:
     # retrofit devices already have split super images under OTA/
-    images_path = os.path.join(input_tmp, "OTA")
+    images_path = os.path.join(input_tmp, 'OTA')
     for device in OPTIONS.super_device_list:
-      image = "super_%s.img" % device
+      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))
+      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)
+    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")
+    logger.info('writing super.img to archive...')
+    common.ZipWrite(output_zip, super_file, 'super.img')
 
 
 def ImgFromTargetFiles(input_file, output_file):
@@ -150,9 +158,9 @@
     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/,
@@ -161,7 +169,7 @@
 
   LoadOptions(input_tmp)
   output_zip = zipfile.ZipFile(
-      output_file, "w", compression=zipfile.ZIP_DEFLATED,
+      output_file, 'w', compression=zipfile.ZIP_DEFLATED,
       allowZip64=not OPTIONS.sparse_userimages)
 
   try:
@@ -169,28 +177,23 @@
     CopyUserImages(input_tmp, output_zip)
     WriteSuperImages(input_tmp, output_zip)
   finally:
-    logger.info("cleaning up...")
     common.ZipClose(output_zip)
 
 
 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
+    if o in ('-z', '--bootable_zip'):
+      OPTIONS.bootable_only = True
     else:
       return False
     return True
 
   args = common.ParseOptions(argv, __doc__,
-                             extra_opts="z",
-                             extra_long_opts=["bootable_zip"],
+                             extra_opts='z',
+                             extra_long_opts=['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 +202,7 @@
 
   ImgFromTargetFiles(args[0], args[1])
 
-  logger.info("done.")
+  logger.info('done.')
 
 
 if __name__ == '__main__':
@@ -207,7 +210,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()