Merge "Clean up noisy error log in find-shareduid-violation.py"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index e5a8b5e..d66ac1e 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -549,6 +549,52 @@
 
 # Clean up previous default location of RROs
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/vendor/overlay)
+
+# Remove ART artifacts installed only by modules `art-runtime` and
+# `art-tools` in /system on target.
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dalvikvm)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dalvikvm32)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dalvikvm64)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dex2oat)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dex2oatd)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dexdiag)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dexdump)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dexlist)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dexoptanalyzer)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/dexoptanalyzerd)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/oatdump)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/profman)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/bin/profmand)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libadbconnection.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libadbconnectiond.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libart-compiler.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libartd-compiler.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libart-dexlayout.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libartd-dexlayout.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libart-disassembler.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libart.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libartd.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libartbase.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libartbased.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libdexfile.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libdexfiled.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libdexfile_external.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libdexfile_support.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libdt_fd_forward.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libdt_socket.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libjdwp.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libnpt.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libopenjdkd.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libopenjdkjvm.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libopenjdkjvmd.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libopenjdkjvmti.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libopenjdkjvmtid.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libprofile.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libprofiled.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libtombstoned_client.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libvixl.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib*/libvixld.so)
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/core/Makefile b/core/Makefile
index 1846a88..a211f13 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -3497,6 +3497,7 @@
 	$(hide) rm -rf $@ $(zip_root)
 	$(hide) mkdir -p $(dir $@) $(zip_root)/bin $(zip_root)/framework $(zip_root)/releasetools
 	$(call copy-files-with-structure,$(OTATOOLS),$(HOST_OUT)/,$(zip_root))
+	$(hide) cp $(SOONG_ZIP) $(zip_root)/bin/
 	$(hide) cp -r -d -p build/make/tools/releasetools/* $(zip_root)/releasetools
 	$(hide) rm -rf $@ $(zip_root)/releasetools/*.pyc
 	$(hide) $(SOONG_ZIP) -o $@ -C $(zip_root) -D $(zip_root) \
@@ -4312,20 +4313,23 @@
 dalvikfiles: $(INTERNAL_DALVIK_MODULES)
 
 ifeq ($(BUILD_QEMU_IMAGES),true)
-INSTALLED_QEMU_SYSTEMIMAGE := $(PRODUCT_OUT)/system-qemu.img
 MK_QEMU_IMAGE_SH := device/generic/goldfish/tools/mk_qemu_image.sh
 SGDISK_HOST := $(HOST_OUT_EXECUTABLES)/sgdisk
+
+ifdef INSTALLED_SYSTEMIMAGE_TARGET
+INSTALLED_QEMU_SYSTEMIMAGE := $(PRODUCT_OUT)/system-qemu.img
 $(INSTALLED_QEMU_SYSTEMIMAGE): $(INSTALLED_SYSTEMIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) $(SIMG2IMG)
 	@echo Create system-qemu.img
-	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/system.img)
+	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) $(INSTALLED_SYSTEMIMAGE_TARGET))
 
 systemimage: $(INSTALLED_QEMU_SYSTEMIMAGE)
 droidcore: $(INSTALLED_QEMU_SYSTEMIMAGE)
+endif
 ifdef INSTALLED_VENDORIMAGE_TARGET
 INSTALLED_QEMU_VENDORIMAGE := $(PRODUCT_OUT)/vendor-qemu.img
 $(INSTALLED_QEMU_VENDORIMAGE): $(INSTALLED_VENDORIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) $(SIMG2IMG)
 	@echo Create vendor-qemu.img
-	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/vendor.img)
+	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) $(INSTALLED_VENDORIMAGE_TARGET))
 
 vendorimage: $(INSTALLED_QEMU_VENDORIMAGE)
 droidcore: $(INSTALLED_QEMU_VENDORIMAGE)
@@ -4334,7 +4338,7 @@
 INSTALLED_QEMU_PRODUCTIMAGE := $(PRODUCT_OUT)/product-qemu.img
 $(INSTALLED_QEMU_PRODUCTIMAGE): $(INSTALLED_PRODUCTIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) $(SIMG2IMG)
 	@echo Create product-qemu.img
-	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/product.img)
+	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) $(INSTALLED_PRODUCTIMAGE_TARGET))
 
 productimage: $(INSTALLED_QEMU_PRODUCTIMAGE)
 droidcore: $(INSTALLED_QEMU_PRODUCTIMAGE)
@@ -4343,7 +4347,7 @@
 INSTALLED_QEMU_PRODUCT_SERVICESIMAGE := $(PRODUCT_OUT)/product_services-qemu.img
 $(INSTALLED_QEMU_PRODUCT_SERVICESIMAGE): $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) $(SIMG2IMG)
 	@echo Create product_services-qemu.img
-	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/product_services.img)
+	(export SGDISK=$(SGDISK_HOST) SIMG2IMG=$(SIMG2IMG); $(MK_QEMU_IMAGE_SH) $(INSTALLED_PRODUCT_SERVICESIMAGE_TARGET))
 
 productservicesimage: $(INSTALLED_QEMU_PRODUCT_SERVICESIMAGE)
 droidcore: $(INSTALLED_QEMU_PRODUCT_SERVICESIMAGE)
@@ -4352,7 +4356,7 @@
 INSTALLED_QEMU_ODMIMAGE := $(PRODUCT_OUT)/odm-qemu.img
 $(INSTALLED_QEMU_ODMIMAGE): $(INSTALLED_ODMIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST)
 	@echo Create odm-qemu.img
-	(export SGDISK=$(SGDISK_HOST); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/odm.img)
+	(export SGDISK=$(SGDISK_HOST); $(MK_QEMU_IMAGE_SH) $(INSTALLED_ODMIMAGE_TARGET))
 
 odmimage: $(INSTALLED_QEMU_ODMIMAGE)
 droidcore: $(INSTALLED_QEMU_ODMIMAGE)
diff --git a/core/binary.mk b/core/binary.mk
index 92bf62d..ccf5580 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -257,6 +257,14 @@
   else # LOCAL_NDK_STL_VARIANT must be none
     # Do nothing.
   endif
+
+  # Clang's coverage/profile runtime needs symbols like 'stderr' that were not
+  # exported from libc prior to API level 23
+  ifneq ($(my_ndk_api),current)
+    ifeq ($(call math_lt, $(my_ndk_api),23),true)
+      my_native_coverage := false
+    endif
+  endif
 endif
 
 ifneq ($(LOCAL_USE_VNDK),)
diff --git a/core/check_elf_file.mk b/core/check_elf_file.mk
index 69d891c..8f2eafb 100644
--- a/core/check_elf_file.mk
+++ b/core/check_elf_file.mk
@@ -35,7 +35,7 @@
 	$(hide) touch $@
 
 ifneq ($(PRODUCT_CHECK_ELF_FILES)$(CHECK_ELF_FILES),)
-ifneq ($(LOCAL_CHECK_ELF_FILES),false)
+ifneq ($(strip $(LOCAL_CHECK_ELF_FILES)),false)
 $(LOCAL_BUILT_MODULE): $(check_elf_files_stamp)
 check-elf-files: $(check_elf_files_stamp)
 endif  # LOCAL_CHECK_ELF_FILES
diff --git a/core/config.mk b/core/config.mk
index 71c3f68..518e138 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -945,6 +945,10 @@
 endif
 
 ifeq ($(PRODUCT_USE_DYNAMIC_PARTITIONS),true)
+    ifeq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true)
+        $(error BOARD_BUILD_SYSTEM_ROOT_IMAGE cannot be true for devices with dynamic partitions)
+    endif
+
     requirements := \
         PRODUCT_USE_DYNAMIC_PARTITION_SIZE \
         PRODUCT_BUILD_SUPER_PARTITION \
diff --git a/core/definitions.mk b/core/definitions.mk
index 4739204..c97f647 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -2480,12 +2480,15 @@
 
 # Copies many files.
 # $(1): The files to copy.  Each entry is a ':' separated src:dst pair
+# $(2): An optional directory to prepend to the destination
 # Evaluates to the list of the dst files (ie suitable for a dependency list)
 define copy-many-files
 $(foreach f, $(1), $(strip \
     $(eval _cmf_tuple := $(subst :, ,$(f))) \
     $(eval _cmf_src := $(word 1,$(_cmf_tuple))) \
     $(eval _cmf_dest := $(word 2,$(_cmf_tuple))) \
+    $(if $(strip $(2)), \
+      $(eval _cmf_dest := $(patsubst %/,%,$(strip $(2)))/$(patsubst /%,%,$(_cmf_dest)))) \
     $(if $(filter-out $(_cmf_src), $(_cmf_dest)), \
       $(eval $(call copy-one-file,$(_cmf_src),$(_cmf_dest)))) \
     $(_cmf_dest)))
diff --git a/core/dex_preopt_config.mk b/core/dex_preopt_config.mk
index 4dd84e7..c417839 100644
--- a/core/dex_preopt_config.mk
+++ b/core/dex_preopt_config.mk
@@ -45,7 +45,11 @@
     product/app/% \
     product/priv-app/% \
 
-# The default values for pre-opting: always preopt PIC.
+# The default values for pre-opting. To support the runtime module we ensure no dex files
+# get stripped.
+ifeq ($(PRODUCT_DEX_PREOPT_NEVER_ALLOW_STRIPPING),)
+  PRODUCT_DEX_PREOPT_NEVER_ALLOW_STRIPPING := true
+endif
 # Conditional to building on linux, as dex2oat currently does not work on darwin.
 ifeq ($(HOST_OS),linux)
   WITH_DEXPREOPT ?= true
@@ -134,6 +138,7 @@
   $(call add_json_str,  DefaultCompilerFilter,              $(PRODUCT_DEX_PREOPT_DEFAULT_COMPILER_FILTER))
   $(call add_json_str,  SystemServerCompilerFilter,         $(PRODUCT_SYSTEM_SERVER_COMPILER_FILTER))
   $(call add_json_bool, GenerateDmFiles,                    $(PRODUCT_DEX_PREOPT_GENERATE_DM_FILES))
+  $(call add_json_bool, NeverAllowStripping,                $(PRODUCT_DEX_PREOPT_NEVER_ALLOW_STRIPPING))
   $(call add_json_bool, NoDebugInfo,                        $(filter false,$(WITH_DEXPREOPT_DEBUG_INFO)))
   $(call add_json_bool, AlwaysSystemServerDebugInfo,        $(filter true,$(PRODUCT_SYSTEM_SERVER_DEBUG_INFO)))
   $(call add_json_bool, NeverSystemServerDebugInfo,         $(filter false,$(PRODUCT_SYSTEM_SERVER_DEBUG_INFO)))
diff --git a/core/dex_preopt_odex_install.mk b/core/dex_preopt_odex_install.mk
index b33d0f8..203a669 100644
--- a/core/dex_preopt_odex_install.mk
+++ b/core/dex_preopt_odex_install.mk
@@ -120,6 +120,17 @@
 my_dexpreopt_images :=
 
 ifdef LOCAL_DEX_PREOPT
+  ifeq (,$(filter PRESIGNED,$(LOCAL_CERTIFICATE)))
+    # Store uncompressed dex files preopted in /system
+    ifeq ($(BOARD_USES_SYSTEM_OTHER_ODEX),true)
+      ifeq ($(call install-on-system-other, $(my_module_path)),)
+        LOCAL_UNCOMPRESS_DEX := true
+      endif  # install-on-system-other
+    else  # BOARD_USES_SYSTEM_OTHER_ODEX
+      LOCAL_UNCOMPRESS_DEX := true
+    endif
+  endif
+
   ifeq ($(LOCAL_MODULE_CLASS),JAVA_LIBRARIES)
     my_module_multilib := $(LOCAL_MULTILIB)
     # If the module is not an SDK library and it's a system server jar, only preopt the primary arch.
diff --git a/core/main.mk b/core/main.mk
index 71b6ed7..610ab28 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -1510,11 +1510,15 @@
     $(call dist-for-goals, dist_files, $(JACOCO_REPORT_CLASSES_ALL))
 
     # Put XML formatted API files in the dist dir.
+    $(TARGET_OUT_COMMON_INTERMEDIATES)/api.xml: $(call java-lib-header-files,android_stubs_current) $(APICHECK)
+    $(TARGET_OUT_COMMON_INTERMEDIATES)/system-api.xml: $(call java-lib-header-files,android_system_stubs_current) $(APICHECK)
+    $(TARGET_OUT_COMMON_INTERMEDIATES)/test-api.xml: $(call java-lib-header-files,android_test_stubs_current) $(APICHECK)
+
     api_xmls := $(addprefix $(TARGET_OUT_COMMON_INTERMEDIATES)/,api.xml system-api.xml test-api.xml)
-    $(api_xmls): $(TARGET_OUT_COMMON_INTERMEDIATES)/%api.xml : frameworks/base/api/%current.txt $(APICHECK)
+    $(api_xmls):
 	$(hide) echo "Converting API file to XML: $@"
 	$(hide) mkdir -p $(dir $@)
-	$(hide) $(APICHECK_COMMAND) -convert2xml $< $@
+	$(hide) $(APICHECK_COMMAND) --input-api-jar $< --api-xml $@
 
     $(call dist-for-goals, dist_files, $(api_xmls))
     api_xmls :=
@@ -1590,11 +1594,6 @@
 	@echo "$(call module-names-for-tag-list,$(ALL_MODULE_TAGS))" | \
 	      tr -s ' ' '\n' | sort -u | $(COLUMN)
 
-.PHONY: dump-products
-dump-products:
-	$(dump-products)
-	@echo Successfully dumped products
-
 .PHONY: dump-files
 dump-files:
 	$(info product_FILES for $(TARGET_DEVICE) ($(INTERNAL_PRODUCT)):)
diff --git a/core/prebuilt_internal.mk b/core/prebuilt_internal.mk
index cd48025..337b2fe 100644
--- a/core/prebuilt_internal.mk
+++ b/core/prebuilt_internal.mk
@@ -170,14 +170,29 @@
 include $(BUILD_SYSTEM)/link_type.mk
 endif  # prebuilt_module_is_a_library
 
-# Check prebuilt ELF binaries.
-include $(BUILD_SYSTEM)/check_elf_file.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)
+ifdef LOCAL_IS_HOST_MODULE
+    ifeq ($(LOCAL_SYSTEM_SHARED_LIBRARIES),none)
+        my_system_shared_libraries :=
+    else
+        my_system_shared_libraries := $(LOCAL_SYSTEM_SHARED_LIBRARIES)
+    endif
+else
+    ifeq ($(LOCAL_SYSTEM_SHARED_LIBRARIES),none)
+        my_system_shared_libraries := libc libm libdl
+    else
+        my_system_shared_libraries := $(LOCAL_SYSTEM_SHARED_LIBRARIES)
+        my_system_shared_libraries := $(patsubst libc,libc libdl,$(my_system_shared_libraries))
+    endif
+endif
+
+my_shared_libraries := \
+    $(filter-out $(my_system_shared_libraries),$(LOCAL_SHARED_LIBRARIES)) \
+    $(my_system_shared_libraries)
+
+ifdef my_shared_libraries
 # Extra shared libraries introduced by LOCAL_CXX_STL.
 include $(BUILD_SYSTEM)/cxx_stl_setup.mk
 ifdef LOCAL_USE_VNDK
@@ -187,12 +202,15 @@
 $(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
   $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(my_shared_libraries))
 endif
-endif
+endif  # my_shared_libraries
 
 # We need to enclose the above export_includes and my_built_shared_libraries in
 # "my_strip_module not true" because otherwise the rules are defined in dynamic_binary.mk.
 endif  # my_strip_module not true
 
+# Check prebuilt ELF binaries.
+include $(BUILD_SYSTEM)/check_elf_file.mk
+
 ifeq ($(NATIVE_COVERAGE),true)
 ifneq (,$(strip $(LOCAL_PREBUILT_COVERAGE_ARCHIVE)))
   $(eval $(call copy-one-file,$(LOCAL_PREBUILT_COVERAGE_ARCHIVE),$(intermediates)/$(LOCAL_MODULE).gcnodir))
diff --git a/core/product.mk b/core/product.mk
index 30bd87a..2ddbeaf 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -180,6 +180,7 @@
     PRODUCT_DEX_PREOPT_PROFILE_DIR \
     PRODUCT_DEX_PREOPT_BOOT_IMAGE_PROFILE_LOCATION \
     PRODUCT_DEX_PREOPT_GENERATE_DM_FILES \
+    PRODUCT_DEX_PREOPT_NEVER_ALLOW_STRIPPING \
     PRODUCT_USE_PROFILE_FOR_BOOT_IMAGE \
     PRODUCT_SYSTEM_SERVER_COMPILER_FILTER \
     PRODUCT_SANITIZER_MODULE_CONFIGS \
@@ -233,10 +234,10 @@
     PRODUCT_CHECK_ELF_FILES \
 
 define dump-product
-$(info ==== $(1) ====)\
+$(warning ==== $(1) ====)\
 $(foreach v,$(_product_var_list),\
-$(info PRODUCTS.$(1).$(v) := $(PRODUCTS.$(1).$(v))))\
-$(info --------)
+$(warning PRODUCTS.$(1).$(v) := $(PRODUCTS.$(1).$(v))))\
+$(warning --------)
 endef
 
 define dump-products
diff --git a/core/product_config.mk b/core/product_config.mk
index 01fbc0a..cff42db 100644
--- a/core/product_config.mk
+++ b/core/product_config.mk
@@ -237,6 +237,10 @@
 # Sanity check
 $(check-all-products)
 
+ifneq ($(filter dump-products, $(MAKECMDGOALS)),)
+$(dump-products)
+endif
+
 # Convert a short name like "sooner" into the path to the product
 # file defining that product.
 #
@@ -408,6 +412,8 @@
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_BOOT_FLAGS))
 PRODUCT_DEX_PREOPT_PROFILE_DIR := \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_PROFILE_DIR))
+PRODUCT_DEX_PREOPT_NEVER_ALLOW_STRIPPING := \
+    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_NEVER_ALLOW_STRIPPING))
 
 # Boot image options.
 PRODUCT_USE_PROFILE_FOR_BOOT_IMAGE := \
diff --git a/core/soong_cc_prebuilt.mk b/core/soong_cc_prebuilt.mk
index 39cc0f0..dd33852 100644
--- a/core/soong_cc_prebuilt.mk
+++ b/core/soong_cc_prebuilt.mk
@@ -123,6 +123,8 @@
   ifdef LOCAL_SOONG_UNSTRIPPED_BINARY
     # Store a copy with symbols for symbolic debugging
     my_unstripped_path := $(TARGET_OUT_UNSTRIPPED)/$(patsubst $(PRODUCT_OUT)/%,%,$(my_module_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))
diff --git a/core/soong_config.mk b/core/soong_config.mk
index 1f2e258..1fb0c29 100644
--- a/core/soong_config.mk
+++ b/core/soong_config.mk
@@ -158,6 +158,10 @@
 $(call add_json_bool, EnforceSystemCertificate,          $(ENFORCE_SYSTEM_CERTIFICATE))
 $(call add_json_list, EnforceSystemCertificateWhitelist, $(ENFORCE_SYSTEM_CERTIFICATE_WHITELIST))
 
+$(call add_json_list, ProductHiddenAPIStubs,             $(PRODUCT_HIDDENAPI_STUBS))
+$(call add_json_list, ProductHiddenAPIStubsSystem,       $(PRODUCT_HIDDENAPI_STUBS_SYSTEM))
+$(call add_json_list, ProductHiddenAPIStubsTest,         $(PRODUCT_HIDDENAPI_STUBS_TEST))
+
 $(call add_json_map, VendorVars)
 $(foreach namespace,$(SOONG_CONFIG_NAMESPACES),\
   $(call add_json_map, $(namespace))\
diff --git a/core/static_java_library.mk b/core/static_java_library.mk
index cee7c9e..ee759b9 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -85,14 +85,22 @@
 LOCAL_INTERMEDIATE_TARGETS += $(R_file_stamp)
 
 ifeq ($(LOCAL_USE_AAPT2),true)
-# For library we treat all the resource equal with no overlay.
-my_res_resources := $(all_resources)
-my_overlay_resources :=
-# For libraries put everything in the COMMON intermediate directory.
-my_res_package := $(intermediates.COMMON)/package-res.apk
+  ifneq ($(strip $(LOCAL_STATIC_ANDROID_LIBRARIES) $(LOCAL_STATIC_JAVA_AAR_LIBRARIES)),)
+    # If we are using static android libraries, every source file becomes an overlay.
+    # This is to emulate old AAPT behavior which simulated library support.
+    my_res_resources :=
+    my_overlay_resources := $(all_resources)
+  else
+    # Otherwise, for a library we treat all the resource equal with no overlay.
+    my_res_resources := $(all_resources)
+    my_overlay_resources :=
+  endif
+  # For libraries put everything in the COMMON intermediate directory.
+  my_res_package := $(intermediates.COMMON)/package-res.apk
 
-LOCAL_INTERMEDIATE_TARGETS += $(my_res_package)
+  LOCAL_INTERMEDIATE_TARGETS += $(my_res_package)
 endif  # LOCAL_USE_AAPT2
+
 endif  # need_compile_res
 
 all_res_assets := $(all_resources)
diff --git a/envsetup.sh b/envsetup.sh
index 5d2e550..0953487 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -1765,11 +1765,33 @@
 }
 
 # Execute the contents of any vendorsetup.sh files we can find.
+# Unless we find an allowed-vendorsetup_sh-files file, in which case we'll only
+# load those.
+#
+# This allows loading only approved vendorsetup.sh files
 function source_vendorsetup() {
+    allowed=
+    for f in $(find -L device vendor product -maxdepth 4 -name 'allowed-vendorsetup_sh-files' 2>/dev/null | sort); do
+        if [ -n "$allowed" ]; then
+            echo "More than one 'allowed_vendorsetup_sh-files' file found, not including any vendorsetup.sh files:"
+            echo "  $allowed"
+            echo "  $f"
+            return
+        fi
+        allowed="$f"
+    done
+
+    allowed_files=
+    [ -n "$allowed" ] && allowed_files=$(cat "$allowed")
     for dir in device vendor product; do
         for f in $(test -d $dir && \
             find -L $dir -maxdepth 4 -name 'vendorsetup.sh' 2>/dev/null | sort); do
-            echo "including $f"; . $f
+
+            if [[ -z "$allowed" || "$allowed_files" =~ $f ]]; then
+                echo "including $f"; . "$f"
+            else
+                echo "ignoring $f, not in $allowed"
+            fi
         done
     done
 }
diff --git a/target/board/BoardConfigGsiCommon.mk b/target/board/BoardConfigGsiCommon.mk
index 23cdf53..658ccf3 100644
--- a/target/board/BoardConfigGsiCommon.mk
+++ b/target/board/BoardConfigGsiCommon.mk
@@ -49,9 +49,9 @@
 
 # GSI specific System Properties
 ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
-# GSI is always userdebug and needs a couple of properties taking precedence
-# over those set by the vendor.
 TARGET_SYSTEM_PROP := build/make/target/board/gsi_system.prop
+else
+TARGET_SYSTEM_PROP := build/make/target/board/gsi_system_user.prop
 endif
 
 # Set this to create /cache mount point for non-A/B devices that mounts /cache.
diff --git a/target/board/gsi_system_user.prop b/target/board/gsi_system_user.prop
new file mode 100644
index 0000000..1aa553b
--- /dev/null
+++ b/target/board/gsi_system_user.prop
@@ -0,0 +1,5 @@
+# GSI always generate dex pre-opt in system image
+ro.cp_system_other_odex=0
+
+# TODO(b/78105955): disable privapp_permissions checking before the bug solved
+ro.control_privapp_permissions=disable
diff --git a/target/product/base_vendor.mk b/target/product/base_vendor.mk
index e8f9e0c..8574aff 100644
--- a/target/product/base_vendor.mk
+++ b/target/product/base_vendor.mk
@@ -18,6 +18,7 @@
 PRODUCT_PACKAGES += \
     adbd.recovery \
     android.hardware.health@2.0-impl-default.recovery \
+    cgroups.recovery.json \
     init_second_stage.recovery \
     ld.config.recovery.txt \
     linker.recovery \
diff --git a/target/product/gsi/Android.mk b/target/product/gsi/Android.mk
index 7953db0..eaaa051 100644
--- a/target/product/gsi/Android.mk
+++ b/target/product/gsi/Android.mk
@@ -100,11 +100,14 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE := vndk_package
 LOCAL_REQUIRED_MODULES := \
-    $(addsuffix .vendor,$(VNDK_CORE_LIBRARIES)) \
-    $(addsuffix .vendor,$(VNDK_SAMEPROCESS_LIBRARIES)) \
     $(LLNDK_LIBRARIES) \
     llndk.libraries.txt \
     vndksp.libraries.txt
+ifneq ($(TARGET_SKIP_CURRENT_VNDK),true)
+LOCAL_REQUIRED_MODULES += \
+    $(addsuffix .vendor,$(VNDK_CORE_LIBRARIES)) \
+    $(addsuffix .vendor,$(VNDK_SAMEPROCESS_LIBRARIES))
+endif
 include $(BUILD_PHONY_PACKAGE)
 
 include $(CLEAR_VARS)
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
index 4aad5f7..35c45da 100644
--- a/target/product/runtime_libart.mk
+++ b/target/product/runtime_libart.mk
@@ -38,10 +38,11 @@
     libicui18n \
     libicuuc \
 
-# ART.
-PRODUCT_PACKAGES += art-runtime
-# ART/dex helpers.
-PRODUCT_PACKAGES += art-tools
+# TODO(b/124498388): This currently needs to be in /system/lib for the debugger
+# transport to work.
+PRODUCT_PACKAGES += \
+    libnpt
+
 # Android Runtime APEX module.
 PRODUCT_PACKAGES += com.android.runtime
 
diff --git a/target/product/security/com.android.conscrypt.pk8 b/target/product/security/com.android.conscrypt.pk8
deleted file mode 100644
index 4c04deb..0000000
--- a/target/product/security/com.android.conscrypt.pk8
+++ /dev/null
Binary files differ
diff --git a/target/product/security/com.android.conscrypt.x509.pem b/target/product/security/com.android.conscrypt.x509.pem
deleted file mode 100644
index ba914fa..0000000
--- a/target/product/security/com.android.conscrypt.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIF1DCCA7ygAwIBAgIJAN0lMAb+9i0JMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV
-BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
-aWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRyb2lkMR4wHAYDVQQD
-DBVjb20uYW5kcm9pZC5jb25zY3J5cHQwIBcNMTkwMTI1MTcxNjM3WhgPNDc1NjEy
-MjExNzE2MzdaMH4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYw
-FAYDVQQHDA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQL
-DAdBbmRyb2lkMR4wHAYDVQQDDBVjb20uYW5kcm9pZC5jb25zY3J5cHQwggIiMA0G
-CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCcfdThwuWhAk0362p7+s/8xL0Hi6Fe
-orQL30Kat8iK4ZPWM5HxOY1zmktBzjgKQ0qM4fuvHzrQJr2+SLl+l2miX4XTruAL
-w7MBS1EGzh0YC4cOBq9z8IsAW/lB6MDeAJ6TuflTk5BRun+bDB70IkWd0ylYSiTi
-AWEs4LM03rBbTcxpNuoLMj1PDNkNOmWiu0rtRbO2Y5+GI9Kw2lyPsWKkU0ixifq2
-o3gHAepmwD7bt5tDFSuOW+uCeF7TzyqsE/CFvqWYUn+5rlOlcyFARAgCh1NZXqxq
-mkcyI9vmtneIUimYw0dzgNoG0dijYAvpuQgSr0HSa2JBiQOgMrJug2PtmWpH2PNk
-UubVZYSfPiO4wTB9Jus63Y27KRdo4Bz4R4n/u0FjIi/cu0Zms07MTo60NPaGHNM/
-nMJSEDDjQ7ppoPXsamn0DID8HlZMivmcQgzokWswxw4b/i1O2fUotKEDf3wvJhUB
-4U7bAgF55FNWWfcaHYqhytWc0qO4zdMUyVqFF+/Db3hz4IkhJyzjCYxBovSSx4yN
-atHa93SwM+uH1s2iI3gOJbn/SrsfKbkrU85S5zVRDEOQg9lm2d99PMnXqXED7bRw
-G9pKmUfOzMANm8yhvL/urlSXVDHxtdw+IJGSVUlzYT3OAx2eFdnpiymiQyWotr8W
-IXfOyr/lB6IkvQIDAQABo1MwUTAdBgNVHQ4EFgQU/vXb6Hy1AxgAxhDuwnO457cD
-3+owHwYDVR0jBBgwFoAU/vXb6Hy1AxgAxhDuwnO457cD3+owDwYDVR0TAQH/BAUw
-AwEB/zANBgkqhkiG9w0BAQsFAAOCAgEARVpJBLitmnJXL/suxt+IsszEBz/pj5g1
-uwor1L3Zvb8j614BhqrKFlPia3PKlHJHotNugjs35CrQ6S4zC3Dx3R2Wb/hBOhtk
-bfpjKZuWaPvqHx1nlBsRa6H7tOKOW/6DHkkb/L5oJo7FPZT0Y0XNandFAmveBL69
-CLZS5dFnhkbVHi7PuvSwcFEXSr/fozcIMnCsQAds42cWqlWlDDVq90vYzOM+jQxS
-cctJ3cZiL0heWEyiZmG0J95Z6kB28gEmaDw8LNUwaUsyaO7U6GwXIe/KQvI2cT/F
-yjpkBmKqDr89Xvyd9DYtZv8GbndTQLwyrPhlKLNOoly3jqjbxqAZGBpyxwVDU+Mo
-/NwkCheQeEYLrGXBgv9fLfyOLSZA7yihPTc0IQcm27DnpkZmJ/lWJ5jDG0VEkNp+
-60O5GYCs2/r3tO+YoiDSFNjsFgCoTcnOQwYhbBZC7YJLOKV0lYDjfsohE6tcCUuS
-H8Ln6Em9HhFAXZBVQU0N+OyC0bAuDTD72ClvbMQikyeWwhdvY3F0x5dDima0liqe
-0jMTJxlizLoa2YKOiLqLomLt6+sJawF0+bGSKSHpcy0NoopXTb3UBlkFpxRp9UnN
-vrnN6KyRzj7OssDEHfXSZgSR0ZAVrAsgP3vc+lBpze9jtNbITDV1gOxUBX771hdU
-UIxewtyODcY=
------END CERTIFICATE-----
diff --git a/target/product/security/com.android.media.pk8 b/target/product/security/com.android.media.pk8
deleted file mode 100644
index 6df741e..0000000
--- a/target/product/security/com.android.media.pk8
+++ /dev/null
Binary files differ
diff --git a/target/product/security/com.android.media.x509.pem b/target/product/security/com.android.media.x509.pem
deleted file mode 100644
index e7908fa..0000000
--- a/target/product/security/com.android.media.x509.pem
+++ /dev/null
@@ -1,33 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIFzDCCA7SgAwIBAgIJAO05DBBusaaLMA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV
-BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
-aWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRyb2lkMRowGAYDVQQD
-DBFjb20uYW5kcm9pZC5tZWRpYTAgFw0xOTAxMjUxNzE3MTdaGA80NzU2MTIyMTE3
-MTcxN1owejELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNV
-BAcMDU1vdW50YWluIFZpZXcxEDAOBgNVBAoMB0FuZHJvaWQxEDAOBgNVBAsMB0Fu
-ZHJvaWQxGjAYBgNVBAMMEWNvbS5hbmRyb2lkLm1lZGlhMIICIjANBgkqhkiG9w0B
-AQEFAAOCAg8AMIICCgKCAgEAmNkVxUbp/bLbeGbvKqYXzwBycSDpmOhh///lNGYQ
-/AMUD0q6EaZzU2bd4aL0rOGqfoYlhKd0kMVmMUmfdE9ODAfKxleEeEaRl2GJS8a9
-ABi770l3GHbB2xMI2sEWeOD9xsPFF6+ByPZmoUuNhMr4pUbXsDpE3h8ljrgXHtIg
-bh7ofbvddruwBV0lS1k9OZ9jPVGhEKkJnhgQa67cwgdjizAMbI0Dcz9gtMMawsDj
-Z2aQd1r+vxgh1/XkI/NMmXCnG2ERytXcJeC5S4gEtHfTTPoP0FuVgSB6y6dalMuZ
-F0NBZw8Mvgdy3QJip0uNa36J63CMZKTJWbTdlFpPL2hk0PgaYvje8C5Xtk5282wT
-dMocc8n2zIXbzbnSXGvjcNZib3Pfu55YUnX6eTqZ1BxlJ0FHZAsC4quFFWXxYBYD
-LCRoNNFEtIDQpuvuHF2DuHNDULpAQjy2y6+7eot0KEsVoDmZ4H8BpuAVVu2SxYNb
-gYflR9SmM0tmYeAcRT48q3xrocGyEHMqvgQRUpPfvct/8l8xVcDzOI/sJVDqmYzM
-u0Cj3fkSypGDJOMF/esFSmVvoI01tS7kaNS5vvtKYib//xqKRC9f0dCsGfFLnuUK
-o4KYbYWYwMyJqEd/5/ZvXyKIPAEeJL174L9+wTkc3cQpoBwJN4t+2E5MnhOEq6do
-5L0CAwEAAaNTMFEwHQYDVR0OBBYEFHjNK/GZko1RdZp+8iavWXL5xz9wMB8GA1Ud
-IwQYMBaAFHjNK/GZko1RdZp+8iavWXL5xz9wMA8GA1UdEwEB/wQFMAMBAf8wDQYJ
-KoZIhvcNAQELBQADggIBACmPQMksuLrNV1vbI44S1f70I0FHdBxchFGB39zuLbcn
-SsYom/LPtYJiD0Dl4bB4eb+ZnxkQP2XeP6pycmUH2j1EWexFwvdUvlfe8Qz+wAec
-ap4AxiX4Z2Ke2ivYotIZFUHdZOLkX20js8Wex1mzY43MLQn5APl9gK1VZTxDggeR
-EObH1S+JVjGwQqYZj2e6gNZH34Q25NQ698RL85GDkYtSISAifJtaJsU/B3vKm82I
-k9xMiCooCH6bRdGHG1jze4SRpidjxEm8cxkiaQagfcuXeCLziXJr3qAMKYiEY6bp
-0+bAqCt3S8OrrN3RQZfQrnlwitsM1jJJ/+C+WoDg4eY5AFrXDLvNeKh1qO/f8xv+
-fCXkQPcVVphLfRH9oxNrSgOWBP5/qIDH4s1YUL9luGT6H+08dlue3RkbzDbBqsQu
-7fQ/BbrIG/GuVKgyEM+a7C9gv7zc86YlueVYJEyxKidnn7RxOqyDBqyyfXA3zvme
-Rro7xIrMHPL7Nu3AWjwjXzbp/w0z+tEFPsfVB+OOHKsWPcUG0HUTJGkyeO/uHRjN
-qPEkkf7BHHUO4V2gjOIdCsELxKwHf7vsZTOk40EV751fZ7FDHMr1eddQkgH4eqAb
-DB79uP+SLfUo+42n4q6eMmoqw8d76bBXRoUhIo/Ms4sebhV0sRtAS67OQioc9UUg
------END CERTIFICATE-----
diff --git a/target/product/security/com.android.resolv.pk8 b/target/product/security/com.android.resolv.pk8
deleted file mode 100644
index 3481a69..0000000
--- a/target/product/security/com.android.resolv.pk8
+++ /dev/null
Binary files differ
diff --git a/target/product/security/com.android.resolv.x509.pem b/target/product/security/com.android.resolv.x509.pem
deleted file mode 100644
index 77650f0..0000000
--- a/target/product/security/com.android.resolv.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIFzjCCA7agAwIBAgIJAJuYkMMWaDUCMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNV
-BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
-aWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRyb2lkMRswGQYDVQQD
-DBJjb20uYW5kcm9pZC5yZXNvbHYwIBcNMTkwMTI1MTcxODEwWhgPNDc1NjEyMjEx
-NzE4MTBaMHsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYD
-VQQHDA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdB
-bmRyb2lkMRswGQYDVQQDDBJjb20uYW5kcm9pZC5yZXNvbHYwggIiMA0GCSqGSIb3
-DQEBAQUAA4ICDwAwggIKAoICAQDHKz23/+Ji2wjvzYMMjvIm8jE6ghgqDrUfadQz
-UkfN0FnkDkBMQE3Qh41SYFxd7wn4q22HKn3OtO/TR8f9X15+HF9vCN6LMtHWRO+w
-wHNOuCYRLqNyKx3XlYOyokiF0NLMkUrmHyflqZQ6xwJIcYj6J13cp11sAc61snRR
-wwczxDiSiIExeKIC6LtEzbAxp09a3BgRVQrlQllr1MPBmXjQxkJ9nAglM3HFq7oQ
-xYGafwabjkpvC8x7hHEmi7XEOssHaT66C1adwFNc3trGK+1ZNOHmkmM+fRO1hffF
-wQ5yhbAt1zKaqj7TXYdJ2NaJYfCZSnJ8bH9Q5u28wBMoUYUh1b4zwWPUyszJ61h2
-nb8oZp8P1tZzD4R9LsQ7iW31D6i3wVAazhLnbXnH0BREWamKvkbA3/PTCSC+/AMc
-4wh/aN/SU/TzCvvI6i6CG5un38OSvsNLTBmLj4Y8ECD7nxUwfeMKKSba37Twh/YG
-PlslsbVBZK0iHtG+hCJuyy7ttGpGydE93m8Rqm1CJnm+/HaKa8UKCHd5GqiDhKtT
-EvdfLJwQPsf49IVrNWQp+1Q15WNVhSA9nLiMYVQYtBVbTYtYghXbRcSD2IjUdfA4
-lIcubkPxWD+jthBFZhlyGoJ9OapNrbRf0isHCsTUMnCy02MQNnMTaLGfseBFAFqj
-+95SJQIDAQABo1MwUTAdBgNVHQ4EFgQUny0NZgR8PJCPSYJ6BQ721hhB2DkwHwYD
-VR0jBBgwFoAUny0NZgR8PJCPSYJ6BQ721hhB2DkwDwYDVR0TAQH/BAUwAwEB/zAN
-BgkqhkiG9w0BAQsFAAOCAgEAWabMCkP4kcG7DwAwpyGCehh5rg0FTSkRRKTY4S0P
-gSEmgPUNV1uqFUECGGr1HeOf6PUYCdAQ6K2tnhnknBLqfcQX+h652D+0Md/KldJt
-7HwC16S0MEfR35w/VgUfxe2oO0OYDJdkUXeEjou2+VrAYT6pe9TRB5+F5KQetgZa
-3H9KW7RVc1oeK3kZtSNA5zDsJNcvgdfWoSJkewlHZ8KNLQBaZoDYV/mfF8d06ydE
-L7SnTkHrJZF9MZ0V58y06sIX9XwlKhypY8sZi3bq+H0t5mzsVAaBHVOC8NHCy351
-XLArkCFdDMb50FaxN8F9eY6A997n08msfeMlMjBrem8r14tf5UEjYyykuLfhW19R
-W+Kli67PZ2VR1I7reEjab2hKt6nwBfw9/Pnb2lugIh48GG5kQ6sgROyAu14q/rnL
-Mof+athhTSD+ttU3YyBOq6hA7Vbft9xAnFqr50bBRbbO21OBJuN8PTWQm82FwXKB
-hNwMy7HSggJqZSJt8HiA2rmoZ79/gNIic6GddoYnASQqjxaCv6vhg8/FQ+r/FJ+x
-gy89yQ6WFLau4/YjVjTyBqGeUPorRuysK7XPH6vDZZKJawwNV3jaYzG8BQAIBqqp
-dNEx97jin7bJQ6ObGF5pmvjzo1XYAiKuj/sjzCC2EN2BjjimTVlsoB+Gv/CFUTbr
-8vw=
------END CERTIFICATE-----
diff --git a/target/product/security/com.android.runtime.debug.pk8 b/target/product/security/com.android.runtime.debug.pk8
deleted file mode 100644
index 5eec5d8..0000000
--- a/target/product/security/com.android.runtime.debug.pk8
+++ /dev/null
Binary files differ
diff --git a/target/product/security/com.android.runtime.debug.x509.pem b/target/product/security/com.android.runtime.debug.x509.pem
deleted file mode 100644
index 73402f5..0000000
--- a/target/product/security/com.android.runtime.debug.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIF0DCCA7igAwIBAgIJALbaJLNNAiRDMA0GCSqGSIb3DQEBCwUAMHwxCzAJBgNV
-BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
-aWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRyb2lkMRwwGgYDVQQD
-DBNjb20uYW5kcm9pZC5ydW50aW1lMCAXDTE5MDEyNTE3MTQ1NloYDzQ3NTYxMjIx
-MTcxNDU2WjB8MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG
-A1UEBwwNTW91bnRhaW4gVmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UECwwH
-QW5kcm9pZDEcMBoGA1UEAwwTY29tLmFuZHJvaWQucnVudGltZTCCAiIwDQYJKoZI
-hvcNAQEBBQADggIPADCCAgoCggIBAN1Ns75c0ZdLKnUvEuEotzJ0xyOLzOHYP3y6
-RzcwFyPf84aADc7rQDtjbmEuf9g9QpJhZAxe7G2Jg/wxqaxMW6wCfkpuElW5CAcj
-XQ0i12hRVtqePs5Z5bjzJ/8C7luWh82Vb/s2YoRPoKNXVWFT16CB4RMnw2nW5Uyo
-RHZ98N4MgFSGilafIc6Z0DImreTTwlEvcyKihVUSuzeyPG8CRjshw0C1Hqxt4a8J
-rxAgfPpd84Xo4etYePpVr2K5+vNAVwLpUdD48Y7q9peOJ0tbL8DSohudkzvZsQUo
-CfEfrVBfZv7aPnt6ZJYhcFo1WRBMYczKP4jWb0KgmF963ee3zliU1pXtIYsNBNth
-Mdvy3ml301tI7CKE5A3Yevm40VVqo+IDt7FNxoV3rKPhnO9vi/YqzX/1xMvAto8E
-9A5NvMTqHmS2P0wt1pt9KSuXXjoIAWaHZOATDkVI+jLjDrYFNdhqXVgbAaVtI60j
-lRaSWxzBr4o+g2W8ks/JgM2mwJ6qaTNoDMzg823MKzy/t3935sxm5GhFs9AY9Qz/
-4B3exqYUEFJLN6dJLCVppCmFCdCONSxN7bXPo+3b9LlZuKAOP17N04+eKcwXVeYz
-Z3a7SfyMzq+DtLhAn/TSliSbbCAVUxiOZnVX1nM0Gs3/BYCs0TUh2tSqO48pwDrx
-Pw7z9+m5AgMBAAGjUzBRMB0GA1UdDgQWBBRT9s/tu4uqtrglUFjQbwY5p+17DjAf
-BgNVHSMEGDAWgBRT9s/tu4uqtrglUFjQbwY5p+17DjAPBgNVHRMBAf8EBTADAQH/
-MA0GCSqGSIb3DQEBCwUAA4ICAQBNY5giwZCM0sE93Dj2zEe8qCRwIaV4bvSe744X
-Y1+405vdrNEHKPUfFn1xLSnhiGU3loZrP15lexmWvxycLNEy0UxZgq3eR7HuW6xp
-GIm9ttYDZEP+pL9hwew3jiR38NRRR1Ur1MsBNkZnCELC1W8RFWIi77Fsb4fj2mGn
-2R+2voBvVS5kjkytW079CEIsZN9RVYfERiKPCfJDa87kk0xduqyh7sDegQl0B2Ot
-R9KnD1dJZjbii2GRkhpJ/Ig17CQH3J8PY/SIt9L+QAchnIEF051sjbBRUJuPK9gL
-eBEkZkwD1JLqGO6fxkcjNx7MIevTnIBjX2Epr8luyRy7eR3TdBT3aRQcCUqBCi3i
-WxAVR5sOZ90INTXftFbztoklitpQ9mxKXgFr+xggL6u3BdJk1Nt9BsYmRzh5Bg+6
-1eMDBumy3JEA7whE8p75X9cSnKTNrDQU3DA5XzpIhmI91XJArBhBfxgqGxaTf0uq
-SfZRDfnaO456ZsZdKUy62mry6Vg/hvzX52x/HxDlSQWbpYp5t03hshaWxtNE376q
-GdqOoGRRWCvyWi/UOYzabp6czTjwV1JH9IU379CsqIO5UNJ2MM2re4TDXofefU1C
-6eiYihy28xDfIiCdretLRlvFYFF/5X5xby/XWsDA9sGlL5OOiXC6o0Pl9vbek2+T
-Ibx3Nw==
------END CERTIFICATE-----
diff --git a/target/product/security/com.android.runtime.release.pk8 b/target/product/security/com.android.runtime.release.pk8
deleted file mode 100644
index c63efb8..0000000
--- a/target/product/security/com.android.runtime.release.pk8
+++ /dev/null
Binary files differ
diff --git a/target/product/security/com.android.runtime.release.x509.pem b/target/product/security/com.android.runtime.release.x509.pem
deleted file mode 100644
index 4a7607a..0000000
--- a/target/product/security/com.android.runtime.release.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIF0DCCA7igAwIBAgIJAMtsu/wrkZurMA0GCSqGSIb3DQEBCwUAMHwxCzAJBgNV
-BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
-aWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRyb2lkMRwwGgYDVQQD
-DBNjb20uYW5kcm9pZC5ydW50aW1lMCAXDTE5MDEyNTE3MTU0MFoYDzQ3NTYxMjIx
-MTcxNTQwWjB8MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG
-A1UEBwwNTW91bnRhaW4gVmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UECwwH
-QW5kcm9pZDEcMBoGA1UEAwwTY29tLmFuZHJvaWQucnVudGltZTCCAiIwDQYJKoZI
-hvcNAQEBBQADggIPADCCAgoCggIBAL+aGSc+HU69vV1VbZb6WjXMDrE2Jo+JjXLU
-yVS3o8qlQeqN0RFbsbwnihnwg2xBnM6JiskAcuocz87dDuEt1zUEInC3Hpt/C2eg
-GUZepbq8po+v+b04YlX3aTaYTFqMjU0aQkjOqhnmVxg+KHpvudlvKB3VhH3D61al
-RReQzgM/Q6aUxcr4Z8XwvzV3i0K5NjiSuSt14K2yIaheh2OTbbwtvm3d+0sQDco6
-1gl0l4rM4e+GjxgWVqx8mfKhd4HTS3YIBDWXR6DFPBARzVBIpZu2QK4U6Jdsy2wI
-xg8+d5KWAoNQb7IQK6LQy7Fbw3PNJDo4Ph39G2wNgeMemz8uSQ9FZujc0AgxBom6
-J+ad7zlJBhYFC4UIKBYrRfJCHTN3GLuLvhu0p0jNMfdQXF6Tv/iG9g8JdZ0QjeWm
-/K+h1p6LUAIUV0UP7j8nIdp0j6NqMywkoeRDYlVQV/XdI7BiQe9Z8yNbF5Y3CxWT
-hMfN9iby11ImPilzpgv39ORVjDQdxxcwhJg2Xuu1752cBxcHu3ZcR8AiB7PCksXu
-EpUrjjOH8eVxoG1JJ/na5elUg/H35Or+JYYd8I8Ad1/GRkPrnIBAGzuyntOsNs4t
-2CEnhmV6EkEH8KP8miTdaa5NdPIwFRIHVBHcrqsqdmrINvoJhaVRH7YwmFjv48ak
-N4OyW3oLAgMBAAGjUzBRMB0GA1UdDgQWBBRqVJ0tsEOyqhKiZOrOfRD1+jQFMDAf
-BgNVHSMEGDAWgBRqVJ0tsEOyqhKiZOrOfRD1+jQFMDAPBgNVHRMBAf8EBTADAQH/
-MA0GCSqGSIb3DQEBCwUAA4ICAQAs+I1tRWRPmhA+FqcRdlAcY2Vy7NO12hjWXCT9
-hqenGk1/VnhH8aZT5lXZNaWeKonT5W7XydyrjiF09ndZBGew0rEZh6sMXH+G/drT
-9JxvfHsCQGrmX32V1XgAoRjV1VpUYIb2747fFWHHbl5frowNj955pkfseeKilSnF
-orUl5uGNxr6iNaVEUDfXBWkHwipYVyejAqdHkCQDhLtDBWsiskKpLWmmNKuy2QXQ
-uoyUyfeSR1Y+pT83qgmGb1LFLiOqL9ZKPrsIP+tG4lYB8L4SrYJf4MgfoJaKQ8ed
-2jsd42MegvOB2vdMyLgkf7EM/9DpE4BLpAy2mNd1AccL9YQ+0ezruxh6sYklJWGe
-2bHEbZk0duoNPsA87ZNKfFVV2cNVwSg/22HHjGieMUyPIwyGIzsHId8XiwXpZhLX
-VyacOVRd0SjTWK5Pxj6g21NrrcMXvFeCbveucf2ljKVxBVSbQKt67YlXxd9nLZjN
-zHnJWzDwlWXbyvxheLVVGEo0cqRbhxYMxXd9dM01EXJmIWqS8t0+aw90KKPFITNv
-qpxXnF5JJm1CzeBDtpmfepDupUR1bWansOd0sUuiDF/H1UcDiuBUC643RET1vjhv
-MllsShSeC6KGm3WwE0bhcvA9IdZC8CA3Btzw2J9aJO1gbVZ6vRkH+21cfR07so4N
-yXgprQ==
------END CERTIFICATE-----
diff --git a/target/product/security/com.android.tzdata.pk8 b/target/product/security/com.android.tzdata.pk8
deleted file mode 100644
index f786710..0000000
--- a/target/product/security/com.android.tzdata.pk8
+++ /dev/null
Binary files differ
diff --git a/target/product/security/com.android.tzdata.x509.pem b/target/product/security/com.android.tzdata.x509.pem
deleted file mode 100644
index bf78bee..0000000
--- a/target/product/security/com.android.tzdata.x509.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIFzjCCA7agAwIBAgIJAIyjs8l5WRp5MA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNV
-BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW
-aWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRyb2lkMRswGQYDVQQD
-DBJjb20uYW5kcm9pZC50emRhdGEwIBcNMTkwMTI1MTY0ODE0WhgPNDc1NjEyMjEx
-NjQ4MTRaMHsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYD
-VQQHDA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdB
-bmRyb2lkMRswGQYDVQQDDBJjb20uYW5kcm9pZC50emRhdGEwggIiMA0GCSqGSIb3
-DQEBAQUAA4ICDwAwggIKAoICAQC3PzY5waM71QpWUVQPfTrtCf9Mx9097DjM6RlD
-jaOd2FtN7gUN/d+z19h0WRkBcBMDWH3z4aHIDp4YXABIdqIzXehhdCFLro4W6H4I
-TNcbH6/M4rmtGs2v0zCkrr8z/mEasCdsw9iz8LOiyouGxgt0Q2qPSQ3OcbZSGX0C
-T8VNxDIP1RpQdRUKhZt/hsmcuPHGq64yil/i7FHX4dLgjnik4sUkHPsQTam/H/J/
-brl9OToTCyRuTgaq6EfxCZVXPfxQE6KTDchFr4wYSbxIgSN9zk2wPLXCsyvSb2lV
-fDSbkRmS89cCaCArF3SP3FAKoZdxdNtT1Q/KayMs7c/jrhFloiIpkstNCzMrPT9i
-j5QwRqcBscSijqaEJOyK458EhaO7m3GHc9e+1afsxTIn//vbrpJU7ewOiwcAsJAT
-KGFMotbK1fV4jGCzKxDVBd1OP5yN/iPYS8INH4tt1W1Q5jaQn/Uy+RuS1tPZTtrL
-ldj/QJ/K9XNSg4v12hXlLDwUlwEMu2Akbe6BYItfhdAEITRr332l6e466cQDp3V2
-mOWANPEX35s5/CaxeqJOi3Y+DSx4iwjOKiormnnEalRFAZrSDU2UNxIqrmidl03Y
-/0p13ugbPmJbpXFPZFDPsUuvPuGLSAU2luUuFSgT0FVyWj5BfzFmcuLxQom03+ds
-cX8GxQIDAQABo1MwUTAdBgNVHQ4EFgQUVCZf+AGkP1wMi7C0l6FFefk9kVAwHwYD
-VR0jBBgwFoAUVCZf+AGkP1wMi7C0l6FFefk9kVAwDwYDVR0TAQH/BAUwAwEB/zAN
-BgkqhkiG9w0BAQsFAAOCAgEAc0NA+Ya/L5Vs+8CZ/5rP6dIbzbgL7tm1nmjU65jY
-8znsSrB0JDTEHCLc+9u35YU77Z3sW9lFE9el1i693gYQnYSy1lducHHKzbnss2/f
-+DJ4QExrPR+PfnkSxdjL8+MXVAtVZDCeEBTcUgLES6m4WLS9hKL4+Oe+igXkAJA+
-d8w1/5ASuood3cTNy3nxssdueAKl4Tyj0y0zejoVlznaYw4zMTmlnrz1l0ZbaKiM
-tr52U2kASEVQW6EhiielsLMzDngqAQ49FQriv7oUhrlbmP3+CkhhPWbM3keSHm/a
-vIQGD3+mbJpekuRgC5w1nCborCxpnHoZUXMyb6/3PnY9u4O8VT5rY5NipVfL/Cvu
-12w0kvcuXTP58gvOJANB5t8Jo4tctG99hO0ECr7/439YM4NMkL5nYEcJe3DemquB
-pB7xVBAD7WKEcB5KV/oDXoLjxMlassKSAvBVbx+fvbGIW6k1pe3uiHl8p/zvxoNb
-9FFRoElCyuzzVP5r/kN5uNbPVIexbVET4elOcUhKigHWZHYv/PQ9ncpA8tbDeAIr
-vzoofKWv4r4tyQZLR4YnEYTGBORO6rX//Mcg8zKE6vXb0zKLW5vW1zxv31q1p2lC
-0R5e4ix7UjR8OJcBCnyKuqSRdCIpMitam2V+BXwh/7mLZBA4LuV4koNofVaBFxlt
-BCo=
------END CERTIFICATE-----
diff --git a/target/product/security/networkstack.pk8 b/target/product/security/networkstack.pk8
new file mode 100644
index 0000000..877f516
--- /dev/null
+++ b/target/product/security/networkstack.pk8
Binary files differ
diff --git a/target/product/security/networkstack.x509.pem b/target/product/security/networkstack.x509.pem
new file mode 100644
index 0000000..c49b95a
--- /dev/null
+++ b/target/product/security/networkstack.x509.pem
@@ -0,0 +1,34 @@
+-----BEGIN CERTIFICATE-----
+MIIF3DCCA8SgAwIBAgIJAPxssNim/dFoMA0GCSqGSIb3DQEBCwUAMIGBMQswCQYD
+VQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4g
+VmlldzEQMA4GA1UECgwHQW5kcm9pZDEQMA4GA1UECwwHQW5kcm9pZDEhMB8GA1UE
+AwwYY29tLmFuZHJvaWQubmV0d29ya3N0YWNrMCAXDTE5MDIxMjAxNDYyMFoYDzQ3
+NTcwMTA4MDE0NjIwWjCBgTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3Ju
+aWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEDAOBgNVBAoMB0FuZHJvaWQxEDAO
+BgNVBAsMB0FuZHJvaWQxITAfBgNVBAMMGGNvbS5hbmRyb2lkLm5ldHdvcmtzdGFj
+azCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALtx9RN/8LLXV6zCyj03
+jg+N4RCQ1crz1J4xTTXCg7d4sC15LY66RANkypcJhUQWYPC8AK+8Y91hGxv1GtKK
+Ht0h4ASPVIuA+L0RPiVoKCL1fauCc6+vEsZNGaDGviOPPmbdx5sQ/ZJpMePuYKe/
+YYZE2jwsT8QoE51F0nvtp/5F4wB1tJPq1uwBzdVdkxwKZX4uWXQspjK23DhCot63
+0iRDyAkpHXpUkgOuauNWWCpMoj8w8FScTshAinUnjpXGnoOQrVKAvO+u9vEwmkG9
+nzv7XRLcp+eexv1oSBk/qatygiSIe0+T6YXsfL9kAbDoY6S5HAXQRvBA/pVABLFk
+WVT8tBFM7h6LZLR9cZoZ70wAHLGD9/PhZuQ/VtaAR8NEDaNP31KdRCdLiy9q+zRQ
+ka2K1Lk71cVdUihqXTwVdGXbjd9i5822sQ+xiIgEav3SY65vISXZBldZx+QvhhCm
+dG7b3FR9QwFhLu7Dw8vRJN7OzI04sg5zsT8k7nyhOpjF9h8MgbB9K1GXSbwry54J
+Sa72wRij6BJearV/zka7CRpmdA4Qsxx0C4kZAMDs2pzGnstPM2mZixdRBt0KT/1w
+JOt+df7dGlsTHQuytAxjSR48+GuJV7IVIbOpbtE3alGmrGl4ZrAlbe4bzZq5oYi/
+TO2AtZpfJMLamlXrew5QIRbjAgMBAAGjUzBRMB0GA1UdDgQWBBSTg8ks+/CZ1cR7
+DDZX2GIqCEty4TAfBgNVHSMEGDAWgBSTg8ks+/CZ1cR7DDZX2GIqCEty4TAPBgNV
+HRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQBqBQE4L94qa49wxgzRuO5P
+eIcYwoixcCWO86liMLZQBWUNakxCpZqXst3sUCQT57Q4+9BgNj10t0ojI4Kn93/T
+2jTjj3n60DWotHLFz/NlgYoBGNh/oeMcx+1L79J2KHYMKQmAw8w7f/DP0Bt1/x/M
+g+mBtbJaVNhbaKgEJKwmAV+zpMdUlppxF0wLwoP2yIGR3O1gniRfWTj/0K15kZji
+0L9jQiIcGwpdMy7S//xmiYLKu8t9O2MP+EduXISsCtN635IkA1IAA5+V7B+pW/g3
+lsDomGE1zuLcrvGQskmFWn5zl9SgvxfqY9l4WJxrSBGKOB//vXkMRNgCM+LjUpKj
+tVM8o/LMFz+Fz5BK3+Lk4hg9weug664HuDmoH/G8kuKSVQlXyFma8h6cBJe5I0zj
+RfP1CLHMhyqlXdtedzxcfdZXe5qLba7SCuH/S4IG/Z9cj1oiuhmAvvAa5vyyZZuX
+rVuYX6gcAZ/+AI3dnIEwwG/GAyshScIgn8Q4p+jDsgzgNlCtMcTuSPFpd3oK4YK3
+LKMbgVQPYfFn2Net9Pa7IzD/XCQDckUADYFywSq11apYkLixLbDw5yliZOtm5/lx
+TDEARkn7S4ZABfnEPIDbP23lL9RNbiA2v+f1gHFW7Vq1kdBv1ruTukM06ic5r4tB
+7SaGRU5gtmbRBzi7e6iAAQ==
+-----END CERTIFICATE-----
diff --git a/tools/fs_config/Android.bp b/tools/fs_config/Android.bp
index 797cfe2..19a4624 100644
--- a/tools/fs_config/Android.bp
+++ b/tools/fs_config/Android.bp
@@ -21,43 +21,3 @@
     ],
     cflags: ["-Werror"],
 }
-
-// -----------------------------------------------------------------------------
-// Unit tests.
-// -----------------------------------------------------------------------------
-
-test_c_flags = [
-    "-fstack-protector-all",
-    "-g",
-    "-Wall",
-    "-Wextra",
-    "-Werror",
-    "-fno-builtin",
-    "-DANDROID_FILESYSTEM_CONFIG=\"android_filesystem_config_test_data.h\"",
-]
-
-//#################################
-// test executable
-cc_test_host {
-    name: "fs_config_generate_test",
-    srcs: ["fs_config_generate.c"],
-    shared_libs: ["libcutils"],
-    cflags: test_c_flags,
-    relative_install_path: "fs_config-unit-tests",
-    no_named_install_directory: true,
-    gtest: false,
-
-}
-
-//#################################
-// gTest tool
-cc_test_host {
-    name: "fs_config-unit-tests",
-    cflags: test_c_flags + ["-DHOST"],
-    shared_libs: [
-        "liblog",
-        "libcutils",
-        "libbase",
-    ],
-    srcs: ["fs_config_test.cpp"],
-}
diff --git a/tools/fs_config/Android.mk b/tools/fs_config/Android.mk
index a0a91e3..0e0b1da 100644
--- a/tools/fs_config/Android.mk
+++ b/tools/fs_config/Android.mk
@@ -19,50 +19,14 @@
 #   for generating the android_filesystem_config.h file.
 #
 # More information can be found in the README
-ANDROID_FS_CONFIG_H := android_filesystem_config.h
 
-my_fs_config_h := $(LOCAL_PATH)/default/$(ANDROID_FS_CONFIG_H)
-system_android_filesystem_config := system/core/include/private/android_filesystem_config.h
-
-##################################
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := fs_config_generate.c
-LOCAL_MODULE := fs_config_generate_$(TARGET_DEVICE)
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_SHARED_LIBRARIES := libcutils
-LOCAL_CFLAGS := -Werror -Wno-error=\#warnings
-
-ifneq ($(TARGET_FS_CONFIG_GEN),)
-# Generate the "generated_oem_aid.h" file
-oem := $(local-generated-sources-dir)/generated_oem_aid.h
-$(oem): PRIVATE_LOCAL_PATH := $(LOCAL_PATH)
-$(oem): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
-$(oem): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
-$(oem): PRIVATE_CUSTOM_TOOL = $(PRIVATE_LOCAL_PATH)/fs_config_generator.py oemaid --aid-header=$(PRIVATE_ANDROID_FS_HDR) $(PRIVATE_TARGET_FS_CONFIG_GEN) > $@
-$(oem): $(TARGET_FS_CONFIG_GEN) $(LOCAL_PATH)/fs_config_generator.py
-	$(transform-generated-source)
-
-# Generate the fs_config header
-gen := $(local-generated-sources-dir)/$(ANDROID_FS_CONFIG_H)
-$(gen): PRIVATE_LOCAL_PATH := $(LOCAL_PATH)
-$(gen): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
-$(gen): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
-$(gen): PRIVATE_CUSTOM_TOOL = $(PRIVATE_LOCAL_PATH)/fs_config_generator.py fsconfig --aid-header=$(PRIVATE_ANDROID_FS_HDR) $(PRIVATE_TARGET_FS_CONFIG_GEN) > $@
-$(gen): $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(LOCAL_PATH)/fs_config_generator.py
-	$(transform-generated-source)
-
-LOCAL_GENERATED_SOURCES := $(oem) $(gen)
-
-my_fs_config_h := $(gen)
-my_gen_oem_aid := $(oem)
-gen :=
-oem :=
+ifneq ($(wildcard $(TARGET_DEVICE_DIR)/android_filesystem_config.h),)
+$(error Using $(TARGET_DEVICE_DIR)/android_filesystem_config.h is deprecated, please use TARGET_FS_CONFIG_GEN instead)
 endif
 
-LOCAL_C_INCLUDES := $(dir $(my_fs_config_h)) $(dir $(my_gen_oem_aid))
+system_android_filesystem_config := system/core/include/private/android_filesystem_config.h
+system_capability_header := bionic/libc/kernel/uapi/linux/capability.h
 
-include $(BUILD_HOST_EXECUTABLE)
-fs_config_generate_bin := $(LOCAL_INSTALLED_MODULE)
 # List of supported vendor, oem, odm, product and product_services Partitions
 fs_config_generate_extra_partition_list := $(strip \
   $(if $(BOARD_USES_VENDORIMAGE)$(BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE),vendor) \
@@ -125,12 +89,20 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
 include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
 $(LOCAL_BUILT_MODULE): PRIVATE_PARTITION_LIST := $(fs_config_generate_extra_partition_list)
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -D $(if $(PRIVATE_PARTITION_LIST), \
-	   -P '$(subst $(space),$(comma),$(addprefix -,$(PRIVATE_PARTITION_LIST)))') \
-	   -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition system \
+	   --all-partitions $(subst $(space),$(comma),$(PRIVATE_PARTITION_LIST)) \
+	   --dirs \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 ##################################
 # Generate the system/etc/fs_config_files binary file for the target
@@ -142,12 +114,20 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_INSTALLED_MODULE_STEM := fs_config_files
 include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
 $(LOCAL_BUILT_MODULE): PRIVATE_PARTITION_LIST := $(fs_config_generate_extra_partition_list)
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -F $(if $(PRIVATE_PARTITION_LIST), \
-	   -P '$(subst $(space),$(comma),$(addprefix -,$(PRIVATE_PARTITION_LIST)))') \
-	   -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition system \
+	   --all-partitions $(subst $(space),$(comma),$(PRIVATE_PARTITION_LIST)) \
+	   --files \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 ifneq ($(filter vendor,$(fs_config_generate_extra_partition_list)),)
 ##################################
@@ -161,9 +141,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
 LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -D -P vendor -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition vendor \
+	   --dirs \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 ##################################
 # Generate the vendor/etc/fs_config_files binary file for the target
@@ -176,9 +165,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_files
 LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -F -P vendor -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition vendor \
+	   --files \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 endif
 
@@ -194,9 +192,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
 LOCAL_MODULE_PATH := $(TARGET_OUT_OEM)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -D -P oem -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition oem \
+	   --dirs \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 ##################################
 # Generate the oem/etc/fs_config_files binary file for the target
@@ -209,9 +216,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_files
 LOCAL_MODULE_PATH := $(TARGET_OUT_OEM)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -F -P oem -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition oem \
+	   --files \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 endif
 
@@ -227,9 +243,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
 LOCAL_MODULE_PATH := $(TARGET_OUT_ODM)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -D -P odm -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition odm \
+	   --dirs \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 ##################################
 # Generate the odm/etc/fs_config_files binary file for the target
@@ -242,9 +267,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_files
 LOCAL_MODULE_PATH := $(TARGET_OUT_ODM)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -F -P odm -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition odm \
+	   --files \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 endif
 
@@ -260,9 +294,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
 LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -D -P product -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition product \
+	   --dirs \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 ##################################
 # Generate the product/etc/fs_config_files binary file for the target
@@ -275,10 +318,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_files
 LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -F -P product -o $@
-
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition product \
+	   --files \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 endif
 
 ifneq ($(filter product_services,$(fs_config_generate_extra_partition_list)),)
@@ -293,9 +344,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_dirs
 LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT_SERVICES)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -D -P product_services -o $@
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition product_services \
+	   --dirs \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 
 ##################################
 # Generate the product_services/etc/fs_config_files binary file for the target
@@ -308,10 +368,18 @@
 LOCAL_INSTALLED_MODULE_STEM := fs_config_files
 LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT_SERVICES)/etc
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): $(fs_config_generate_bin)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_CAP_HDR := $(system_capability_header)
+$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config) $(system_capability_header)
 	@mkdir -p $(dir $@)
-	$< -F -P product_services -o $@
-
+	$< fsconfig \
+	   --aid-header $(PRIVATE_ANDROID_FS_HDR) \
+	   --capability-header $(PRIVATE_ANDROID_CAP_HDR) \
+	   --partition product_services \
+	   --files \
+	   --out_file $@ \
+	   $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null)
 endif
 
 ##################################
@@ -321,8 +389,21 @@
 ifneq ($(TARGET_FS_CONFIG_GEN),)
 include $(CLEAR_VARS)
 LOCAL_MODULE := oemaids_headers
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(dir $(my_gen_oem_aid))
-LOCAL_EXPORT_C_INCLUDE_DEPS := $(my_gen_oem_aid)
+
+LOCAL_MODULE_CLASS := ETC
+
+# Generate the "generated_oem_aid.h" file
+oem := $(local-generated-sources-dir)/generated_oem_aid.h
+$(oem): PRIVATE_LOCAL_PATH := $(LOCAL_PATH)
+$(oem): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
+$(oem): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
+$(oem): PRIVATE_CUSTOM_TOOL = $(PRIVATE_LOCAL_PATH)/fs_config_generator.py oemaid --aid-header=$(PRIVATE_ANDROID_FS_HDR) $(PRIVATE_TARGET_FS_CONFIG_GEN) > $@
+$(oem): $(TARGET_FS_CONFIG_GEN) $(LOCAL_PATH)/fs_config_generator.py
+	$(transform-generated-source)
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(dir $(oem))
+LOCAL_EXPORT_C_INCLUDE_DEPS := $(oem)
+
 include $(BUILD_HEADER_LIBRARY)
 endif
 
@@ -338,15 +419,11 @@
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
-ifneq ($(TARGET_FS_CONFIG_GEN),)
 $(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
-else
-$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := /dev/null
-endif
 $(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
 $(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config)
 	@mkdir -p $(dir $@)
-	$(hide) $< passwd --required-prefix=vendor_ --aid-header=$(PRIVATE_ANDROID_FS_HDR) $(PRIVATE_TARGET_FS_CONFIG_GEN) > $@
+	$(hide) $< passwd --required-prefix=vendor_ --aid-header=$(PRIVATE_ANDROID_FS_HDR) $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null) > $@
 
 ##################################
 # Generate the vendor/etc/group text file for the target
@@ -360,20 +437,12 @@
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
-ifneq ($(TARGET_FS_CONFIG_GEN),)
 $(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := $(TARGET_FS_CONFIG_GEN)
-else
-$(LOCAL_BUILT_MODULE): PRIVATE_TARGET_FS_CONFIG_GEN := /dev/null
-endif
 $(LOCAL_BUILT_MODULE): PRIVATE_ANDROID_FS_HDR := $(system_android_filesystem_config)
 $(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/fs_config_generator.py $(TARGET_FS_CONFIG_GEN) $(system_android_filesystem_config)
 	@mkdir -p $(dir $@)
-	$(hide) $< group --required-prefix=vendor_ --aid-header=$(PRIVATE_ANDROID_FS_HDR) $(PRIVATE_TARGET_FS_CONFIG_GEN) > $@
+	$(hide) $< group --required-prefix=vendor_ --aid-header=$(PRIVATE_ANDROID_FS_HDR) $(or $(PRIVATE_TARGET_FS_CONFIG_GEN),/dev/null) > $@
 
 system_android_filesystem_config :=
-
-ANDROID_FS_CONFIG_H :=
-my_fs_config_h :=
-fs_config_generate_bin :=
-my_gen_oem_aid :=
+system_capability_header :=
 fs_config_generate_extra_partition_list :=
diff --git a/tools/fs_config/android_filesystem_config_test_data.h b/tools/fs_config/android_filesystem_config_test_data.h
deleted file mode 100644
index c65d406..0000000
--- a/tools/fs_config/android_filesystem_config_test_data.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <private/android_filesystem_config.h>
-
-/* Test Data */
-
-#undef NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS
-#undef NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_FILES
-
-static const struct fs_path_config android_device_dirs[] = {
-    {00555, AID_ROOT, AID_SYSTEM, 0, "system/etc"},
-    {00555, AID_ROOT, AID_SYSTEM, 0, "vendor/etc"},
-    {00555, AID_ROOT, AID_SYSTEM, 0, "oem/etc"},
-    {00555, AID_ROOT, AID_SYSTEM, 0, "odm/etc"},
-    {00555, AID_ROOT, AID_SYSTEM, 0, "product/etc"},
-    {00555, AID_ROOT, AID_SYSTEM, 0, "product_services/etc"},
-    {00755, AID_SYSTEM, AID_ROOT, 0, "system/oem/etc"},
-    {00755, AID_SYSTEM, AID_ROOT, 0, "system/odm/etc"},
-    {00755, AID_SYSTEM, AID_ROOT, 0, "system/vendor/etc"},
-    {00755, AID_SYSTEM, AID_ROOT, 0, "data/misc"},
-    {00755, AID_SYSTEM, AID_ROOT, 0, "oem/data/misc"},
-    {00755, AID_SYSTEM, AID_ROOT, 0, "odm/data/misc"},
-    {00755, AID_SYSTEM, AID_ROOT, 0, "vendor/data/misc"},
-    {00555, AID_SYSTEM, AID_ROOT, 0, "etc"},
-};
-
-static const struct fs_path_config android_device_files[] = {
-    {00444, AID_ROOT, AID_SYSTEM, 0, "system/etc/fs_config_dirs"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "vendor/etc/fs_config_dirs"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "oem/etc/fs_config_dirs"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "odm/etc/fs_config_dirs"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "product/etc/fs_config_dirs"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "product_services/etc/fs_config_dirs"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "system/etc/fs_config_files"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "vendor/etc/fs_config_files"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "oem/etc/fs_config_files"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "odm/etc/fs_config_files"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "product/etc/fs_config_files"},
-    {00444, AID_ROOT, AID_SYSTEM, 0, "product_services/etc/fs_config_files"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/vendor/etc/fs_config_dirs"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/oem/etc/fs_config_dirs"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/odm/etc/fs_config_dirs"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/vendor/etc/fs_config_files"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/oem/etc/fs_config_files"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/odm/etc/fs_config_files"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/product/etc/fs_config_files"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "system/product_services/etc/fs_config_files"},
-    {00644, AID_SYSTEM, AID_ROOT, 0, "etc/fs_config_files"},
-    {00666, AID_ROOT, AID_SYSTEM, 0, "data/misc/oem"},
-};
diff --git a/tools/fs_config/default/android_filesystem_config.h b/tools/fs_config/default/android_filesystem_config.h
deleted file mode 100644
index b7d936a..0000000
--- a/tools/fs_config/default/android_filesystem_config.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* This file is used to enhance the properties of the filesystem
-** images generated by build tools (mkbootfs and mkyaffs2image) and
-** by the device side of adb.
-*/
-
-/* Rules for directories.
-** These rules are applied based on "first match", so they
-** should start with the most specific path and work their
-** way up to the root.
-*/
-
-#define NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS 1 /* opt out of specifying */
-
-/* Rules for files.
-** These rules are applied based on "first match", so they
-** should start with the most specific path and work their
-** way up to the root. Prefixes ending in * denotes wildcard
-** and will allow partial matches.
-*/
-
-#define NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_FILES 1 /* opt out of specifying */
diff --git a/tools/fs_config/end_to_end_test/config.fs b/tools/fs_config/end_to_end_test/config.fs
new file mode 100644
index 0000000..339e5ae
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/config.fs
@@ -0,0 +1,108 @@
+# 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.
+#
+
+# This file is used to define the properties of the filesystem
+# images generated by build tools (mkbootfs and mkyaffs2image) and
+# by the device side of adb.
+
+[AID_VENDOR_NEW_SERVICE]
+value: 2900
+
+[AID_VENDOR_NEW_SERVICE_TWO]
+value:2902
+
+[vendor/bin/service1]
+mode: 0755
+user: AID_SYSTEM
+group: AID_VENDOR_NEW_SERVICE
+caps: CHOWN DAC_OVERRIDE
+
+[vendor/bin/service2]
+mode: 0755
+user: AID_VENDOR_NEW_SERVICE_TWO
+group: AID_SYSTEM
+caps: AUDIT_READ CHOWN SYS_ADMIN
+
+[system/vendor/bin/service3]
+mode: 0755
+user: AID_SYSTEM
+group: AID_SYSTEM
+caps: AUDIT_READ CHOWN SYS_ADMIN
+
+[vendor/dir/]
+mode: 0755
+user: AID_VENDOR_NEW_SERVICE_TWO
+group: AID_SYSTEM
+caps: 0
+
+[system/vendor/dir2/]
+mode: 0755
+user: AID_VENDOR_NEW_SERVICE_TWO
+group: AID_SYSTEM
+caps: 0
+
+[product/bin/service1]
+mode: 0755
+user: AID_SYSTEM
+group: AID_SYSTEM
+caps: 0x34
+
+[product/bin/service2]
+mode: 0755
+user: AID_SYSTEM
+group: AID_SYSTEM
+caps: NET_BIND_SERVICE WAKE_ALARM
+
+[system/product/bin/service3]
+mode: 0755
+user: AID_SYSTEM
+group: AID_SYSTEM
+caps: NET_BIND_SERVICE WAKE_ALARM
+
+[product/dir/]
+mode: 0755
+user: AID_SYSTEM
+group: AID_SYSTEM
+caps: 0
+
+[system/product/dir/]
+mode: 0755
+user: AID_SYSTEM
+group: AID_SYSTEM
+caps: 0
+
+[system/bin/service]
+mode: 0755
+user: AID_SYSTEM
+group: AID_RADIO
+caps: NET_BIND_SERVICE
+
+[system/dir/]
+mode: 0755
+user: AID_SYSTEM
+group: AID_RADIO
+caps: 0
+
+[root_file]
+mode: 0755
+user: AID_SYSTEM
+group: AID_RADIO
+caps: 0
+
+[root_dir/]
+mode: 0755
+user: AID_SYSTEM
+group: AID_RADIO
+caps: 0
diff --git a/tools/fs_config/end_to_end_test/product_fs_config_dirs b/tools/fs_config/end_to_end_test/product_fs_config_dirs
new file mode 100644
index 0000000..e69ad65
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/product_fs_config_dirs
Binary files differ
diff --git a/tools/fs_config/end_to_end_test/product_fs_config_files b/tools/fs_config/end_to_end_test/product_fs_config_files
new file mode 100644
index 0000000..376a2a6
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/product_fs_config_files
Binary files differ
diff --git a/tools/fs_config/end_to_end_test/run_test.sh b/tools/fs_config/end_to_end_test/run_test.sh
new file mode 100755
index 0000000..7402276
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/run_test.sh
@@ -0,0 +1,76 @@
+cd $ANDROID_BUILD_TOP/build/make/tools/fs_config/end_to_end_test
+
+$ANDROID_BUILD_TOP/build/make/tools/fs_config/fs_config_generator.py fsconfig \
+  --aid-header $ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h \
+  --capability-header $ANDROID_BUILD_TOP/bionic/libc/kernel/uapi/linux/capability.h \
+  --partition system \
+  --all-partitions vendor,product \
+  --files \
+  --out_file result_system_fs_config_files \
+  ./config.fs
+
+diff system_fs_config_files result_system_fs_config_files 1>/dev/null && echo 'Success system_fs_config_files' ||
+  echo 'Fail: Mismatch between system_fs_config_files and result_system_fs_config_files'
+
+$ANDROID_BUILD_TOP/build/make/tools/fs_config/fs_config_generator.py fsconfig \
+  --aid-header $ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h \
+  --capability-header $ANDROID_BUILD_TOP/bionic/libc/kernel/uapi/linux/capability.h \
+  --partition system \
+  --all-partitions vendor,product \
+  --dirs \
+  --out_file result_system_fs_config_dirs \
+  ./config.fs
+
+diff system_fs_config_dirs result_system_fs_config_dirs 1>/dev/null && echo 'Success system_fs_config_dirs' ||
+  echo 'Fail: Mismatch between system_fs_config_dirs and result_system_fs_config_dirs'
+
+$ANDROID_BUILD_TOP/build/make/tools/fs_config/fs_config_generator.py fsconfig \
+  --aid-header $ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h \
+  --capability-header $ANDROID_BUILD_TOP/bionic/libc/kernel/uapi/linux/capability.h \
+  --partition vendor \
+  --files \
+  --out_file result_vendor_fs_config_files \
+  ./config.fs
+
+diff vendor_fs_config_files result_vendor_fs_config_files 1>/dev/null && echo 'Success vendor_fs_config_files' ||
+  echo 'Fail: Mismatch between vendor_fs_config_files and result_vendor_fs_config_files'
+
+$ANDROID_BUILD_TOP/build/make/tools/fs_config/fs_config_generator.py fsconfig \
+  --aid-header $ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h \
+  --capability-header $ANDROID_BUILD_TOP/bionic/libc/kernel/uapi/linux/capability.h \
+  --partition vendor \
+  --dirs \
+  --out_file result_vendor_fs_config_dirs \
+  ./config.fs
+
+diff vendor_fs_config_dirs result_vendor_fs_config_dirs 1>/dev/null && echo 'Success vendor_fs_config_dirs' ||
+  echo 'Fail: Mismatch between vendor_fs_config_dirs and result_vendor_fs_config_dirs'
+
+$ANDROID_BUILD_TOP/build/make/tools/fs_config/fs_config_generator.py fsconfig \
+  --aid-header $ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h \
+  --capability-header $ANDROID_BUILD_TOP/bionic/libc/kernel/uapi/linux/capability.h \
+  --partition product \
+  --files \
+  --out_file result_product_fs_config_files \
+  ./config.fs
+
+diff product_fs_config_files result_product_fs_config_files 1>/dev/null && echo 'Success product_fs_config_files' ||
+  echo 'Fail: Mismatch between product_fs_config_files and result_product_fs_config_files'
+
+$ANDROID_BUILD_TOP/build/make/tools/fs_config/fs_config_generator.py fsconfig \
+  --aid-header $ANDROID_BUILD_TOP/system/core/include/private/android_filesystem_config.h \
+  --capability-header $ANDROID_BUILD_TOP/bionic/libc/kernel/uapi/linux/capability.h \
+  --partition product \
+  --dirs \
+  --out_file result_product_fs_config_dirs \
+  ./config.fs
+
+diff product_fs_config_dirs result_product_fs_config_dirs 1>/dev/null && echo 'Success product_fs_config_dirs' ||
+  echo 'Fail: Mismatch between product_fs_config_dirs and result_product_fs_config_dirs'
+
+rm result_system_fs_config_files
+rm result_system_fs_config_dirs
+rm result_vendor_fs_config_files
+rm result_vendor_fs_config_dirs
+rm result_product_fs_config_files
+rm result_product_fs_config_dirs
diff --git a/tools/fs_config/end_to_end_test/system_fs_config_dirs b/tools/fs_config/end_to_end_test/system_fs_config_dirs
new file mode 100644
index 0000000..3a95e40
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/system_fs_config_dirs
Binary files differ
diff --git a/tools/fs_config/end_to_end_test/system_fs_config_files b/tools/fs_config/end_to_end_test/system_fs_config_files
new file mode 100644
index 0000000..578091c
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/system_fs_config_files
Binary files differ
diff --git a/tools/fs_config/end_to_end_test/vendor_fs_config_dirs b/tools/fs_config/end_to_end_test/vendor_fs_config_dirs
new file mode 100644
index 0000000..02dded7
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/vendor_fs_config_dirs
Binary files differ
diff --git a/tools/fs_config/end_to_end_test/vendor_fs_config_files b/tools/fs_config/end_to_end_test/vendor_fs_config_files
new file mode 100644
index 0000000..90bedc9
--- /dev/null
+++ b/tools/fs_config/end_to_end_test/vendor_fs_config_files
Binary files differ
diff --git a/tools/fs_config/fs_config_generate.c b/tools/fs_config/fs_config_generate.c
deleted file mode 100644
index dddd331..0000000
--- a/tools/fs_config/fs_config_generate.c
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <ctype.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <private/android_filesystem_config.h>
-
-/*
- * This program expects android_device_dirs and android_device_files
- * to be defined in the supplied android_filesystem_config.h file in
- * the device/<vendor>/<product> $(TARGET_DEVICE_DIR). Then generates
- * the binary format used in the /system/etc/fs_config_dirs and
- * the /system/etc/fs_config_files to be used by the runtimes.
- */
-#ifdef ANDROID_FILESYSTEM_CONFIG
-#include ANDROID_FILESYSTEM_CONFIG
-#else
-#include "android_filesystem_config.h"
-#endif
-
-#ifdef NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS
-static const struct fs_path_config android_device_dirs[] = { };
-#endif
-
-#ifdef NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_FILES
-static const struct fs_path_config android_device_files[] = { };
-#endif
-
-static void usage() {
-  fprintf(stderr,
-    "Generate binary content for fs_config_dirs (-D) and fs_config_files (-F)\n"
-    "from device-specific android_filesystem_config.h override.  Filter based\n"
-    "on a comma separated partition list (-P) whitelist or prefixed by a\n"
-    "minus blacklist.  Partitions are identified as path references to\n"
-    "<partition>/ or system/<partition>/\n\n"
-    "Usage: fs_config_generate -D|-F [-P list] [-o output-file]\n");
-}
-
-/* If tool switches to C++, use android-base/macros.h array_size() */
-#ifndef ARRAY_SIZE /* popular macro */
-#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
-#endif
-
-int main(int argc, char** argv) {
-  const struct fs_path_config* pc;
-  const struct fs_path_config* end;
-  bool dir = false, file = false;
-  const char* partitions = NULL;
-  FILE* fp = stdout;
-  int opt;
-  static const char optstring[] = "DFP:ho:";
-
-  while ((opt = getopt(argc, argv, optstring)) != -1) {
-    switch (opt) {
-    case 'D':
-      if (file) {
-        fprintf(stderr, "Must specify only -D or -F\n");
-        usage();
-        exit(EXIT_FAILURE);
-      }
-      dir = true;
-      break;
-    case 'F':
-      if (dir) {
-        fprintf(stderr, "Must specify only -F or -D\n");
-        usage();
-        exit(EXIT_FAILURE);
-      }
-      file = true;
-      break;
-    case 'P':
-      if (partitions) {
-        fprintf(stderr, "Specify only one partition list\n");
-        usage();
-        exit(EXIT_FAILURE);
-      }
-      while (*optarg && isspace(*optarg)) ++optarg;
-      if (!optarg[0]) {
-        fprintf(stderr, "Partition list empty\n");
-        usage();
-        exit(EXIT_FAILURE);
-      }
-      if (!optarg[1]) {
-        fprintf(stderr, "Partition list too short \"%s\"\n", optarg);
-        usage();
-        exit(EXIT_FAILURE);
-      }
-      if ((optarg[0] == '-') && strchr(optstring, optarg[1]) && !optarg[2]) {
-        fprintf(stderr, "Partition list is a flag \"%s\"\n", optarg);
-        usage();
-        exit(EXIT_FAILURE);
-      }
-      partitions = optarg;
-      break;
-    case 'o':
-      if (fp != stdout) {
-        fprintf(stderr, "Specify only one output file\n");
-        usage();
-        exit(EXIT_FAILURE);
-      }
-      fp = fopen(optarg, "wb");
-      if (fp == NULL) {
-        fprintf(stderr, "Can not open \"%s\"\n", optarg);
-        exit(EXIT_FAILURE);
-      }
-      break;
-    case 'h':
-      usage();
-      exit(EXIT_SUCCESS);
-    default:
-      usage();
-      exit(EXIT_FAILURE);
-    }
-  }
-
-  if (optind < argc) {
-    fprintf(stderr, "Unknown non-argument \"%s\"\n", argv[optind]);
-    usage();
-    exit(EXIT_FAILURE);
-  }
-
-  if (!file && !dir) {
-    fprintf(stderr, "Must specify either -F or -D\n");
-    usage();
-    exit(EXIT_FAILURE);
-  }
-
-  if (dir) {
-    pc = android_device_dirs;
-    end = &android_device_dirs[ARRAY_SIZE(android_device_dirs)];
-  } else {
-    pc = android_device_files;
-    end = &android_device_files[ARRAY_SIZE(android_device_files)];
-  }
-  for (; (pc < end) && pc->prefix; pc++) {
-    bool submit;
-    char buffer[512];
-    ssize_t len = fs_config_generate(buffer, sizeof(buffer), pc);
-    if (len < 0) {
-      fprintf(stderr, "Entry too large\n");
-      exit(EXIT_FAILURE);
-    }
-    submit = true;
-    if (partitions) {
-      char* partitions_copy = strdup(partitions);
-      char* arg = partitions_copy;
-      char* sv = NULL; /* Do not leave uninitialized, NULL is known safe. */
-      /* Deal with case all iterated partitions are blacklists with no match */
-      bool all_blacklist_but_no_match = true;
-      submit = false;
-
-      if (!partitions_copy) {
-        fprintf(stderr, "Failed to allocate a copy of %s\n", partitions);
-        exit(EXIT_FAILURE);
-      }
-      /* iterate through (officially) comma separated list of partitions */
-      while (!!(arg = strtok_r(arg, ",:; \t\n\r\f", &sv))) {
-        static const char system[] = "system/";
-        size_t plen;
-        bool blacklist = false;
-        if (*arg == '-') {
-          blacklist = true;
-          ++arg;
-        } else {
-          all_blacklist_but_no_match = false;
-        }
-        plen = strlen(arg);
-        /* deal with evil callers */
-        while (arg[plen - 1] == '/') {
-          --plen;
-        }
-        /* check if we have <partition>/ or /system/<partition>/ */
-        if ((!strncmp(pc->prefix, arg, plen) && (pc->prefix[plen] == '/')) ||
-            (!strncmp(pc->prefix, system, strlen(system)) &&
-             !strncmp(pc->prefix + strlen(system), arg, plen) &&
-             (pc->prefix[strlen(system) + plen] == '/'))) {
-          all_blacklist_but_no_match = false;
-          /* we have a match !!! */
-          if (!blacklist) submit = true;
-          break;
-        }
-        arg = NULL;
-      }
-      free(partitions_copy);
-      if (all_blacklist_but_no_match) submit = true;
-    }
-    if (submit && (fwrite(buffer, 1, len, fp) != (size_t)len)) {
-      fprintf(stderr, "Write failure\n");
-      exit(EXIT_FAILURE);
-    }
-  }
-  fclose(fp);
-
-  return 0;
-}
diff --git a/tools/fs_config/fs_config_generator.py b/tools/fs_config/fs_config_generator.py
index 0a8def8..dccff92 100755
--- a/tools/fs_config/fs_config_generator.py
+++ b/tools/fs_config/fs_config_generator.py
@@ -12,6 +12,7 @@
 
 import argparse
 import ConfigParser
+import ctypes
 import re
 import sys
 import textwrap
@@ -112,7 +113,8 @@
                 'Cannot specify delimiter character ":" in uid: "%s"' % uid)
         if ':' in logon:
             raise ValueError(
-                'Cannot specify delimiter character ":" in logon: "%s"' % logon)
+                'Cannot specify delimiter character ":" in logon: "%s"' %
+                logon)
         return logon, uid
 
 
@@ -158,16 +160,17 @@
 
         try:
             self.normalized_value = str(int(value, 0))
-        except ValueException:
-            raise ValueError('Invalid "value", not aid number, got: \"%s\"' % value)
+        except ValueError:
+            raise ValueError(
+                'Invalid "value", not aid number, got: \"%s\"' % value)
 
         # Where we calculate the friendly name
         friendly = identifier[len(AID.PREFIX):].lower()
         self.friendly = AID._fixup_friendly(friendly)
 
         if len(self.friendly) > 31:
-            raise ValueError('AID names must be under 32 characters "%s"' % self.friendly)
-
+            raise ValueError(
+                'AID names must be under 32 characters "%s"' % self.friendly)
 
     def __eq__(self, other):
 
@@ -217,6 +220,7 @@
         user (str): The uid or #define identifier (AID_SYSTEM)
         group (str): The gid or #define identifier (AID_SYSTEM)
         caps (str): The capability set.
+        path (str): The path of the file or directory.
         filename (str): The file it was found in.
     """
 
@@ -227,6 +231,7 @@
             user (str): The uid or #define identifier (AID_SYSTEM)
             group (str): The gid or #define identifier (AID_SYSTEM)
             caps (str): The capability set as a list.
+            path (str): The path of the file or directory.
             filename (str): The file it was found in.
         """
         self.mode = mode
@@ -242,6 +247,51 @@
             and self.group == other.group and self.caps == other.caps \
             and self.path == other.path and self.filename == other.filename
 
+    def __repr__(self):
+        return 'FSConfig(%r, %r, %r, %r, %r, %r)' % (self.mode, self.user,
+                                                     self.group, self.caps,
+                                                     self.path, self.filename)
+
+
+class CapabilityHeaderParser(object):
+    """Parses capability.h file
+
+    Parses a C header file and extracts lines starting with #define CAP_<name>.
+    """
+
+    _CAP_DEFINE = re.compile(r'\s*#define\s+(CAP_\S+)\s+(\S+)')
+    _SKIP_CAPS = ['CAP_LAST_CAP', 'CAP_TO_INDEX(x)', 'CAP_TO_MASK(x)']
+
+    def __init__(self, capability_header):
+        """
+        Args:
+            capability_header (str): file name for the header file containing AID entries.
+        """
+
+        self.caps = {}
+        with open(capability_header) as open_file:
+            self._parse(open_file)
+
+    def _parse(self, capability_file):
+        """Parses a capability header file. Internal use only.
+
+        Args:
+            capability_file (file): The open capability header file to parse.
+        """
+
+        for line in capability_file:
+            match = CapabilityHeaderParser._CAP_DEFINE.match(line)
+            if match:
+                cap = match.group(1)
+                value = match.group(2)
+
+                if not cap in self._SKIP_CAPS:
+                    try:
+                        self.caps[cap] = int(value, 0)
+                    except ValueError:
+                        sys.exit('Could not parse capability define "%s":"%s"'
+                                 % (cap, value))
+
 
 class AIDHeaderParser(object):
     """Parses an android_filesystem_config.h file.
@@ -256,10 +306,10 @@
     work.
     """
 
-
     _SKIP_AIDS = [
         re.compile(r'%sUNUSED[0-9].*' % AID.PREFIX),
-        re.compile(r'%sAPP' % AID.PREFIX), re.compile(r'%sUSER' % AID.PREFIX)
+        re.compile(r'%sAPP' % AID.PREFIX),
+        re.compile(r'%sUSER' % AID.PREFIX)
     ]
     _AID_DEFINE = re.compile(r'\s*#define\s+%s.*' % AID.PREFIX)
     _OEM_START_KW = 'START'
@@ -310,7 +360,9 @@
                 identifier = chunks[1]
                 value = chunks[2]
 
-                if any(x.match(identifier) for x in AIDHeaderParser._SKIP_AIDS):
+                if any(
+                        x.match(identifier)
+                        for x in AIDHeaderParser._SKIP_AIDS):
                     continue
 
                 try:
@@ -322,8 +374,8 @@
                         self._handle_aid(identifier, value)
                 except ValueError as exception:
                     sys.exit(
-                        error_message('{} for "{}"'.format(exception,
-                                                           identifier)))
+                        error_message('{} for "{}"'.format(
+                            exception, identifier)))
 
     def _handle_aid(self, identifier, value):
         """Handle an AID C #define.
@@ -346,8 +398,8 @@
             raise ValueError('Duplicate aid "%s"' % identifier)
 
         if value in self._aid_value_to_name and aid.identifier not in AIDHeaderParser._COLLISION_OK:
-            raise ValueError('Duplicate aid value "%s" for %s' % (value,
-                                                                  identifier))
+            raise ValueError(
+                'Duplicate aid value "%s" for %s' % (value, identifier))
 
         self._aid_name_to_value[aid.friendly] = aid
         self._aid_value_to_name[value] = aid.friendly
@@ -400,11 +452,11 @@
             if tmp == int_value:
                 raise ValueError('START and END values equal %u' % int_value)
             elif is_start and tmp < int_value:
-                raise ValueError('END value %u less than START value %u' %
-                                 (tmp, int_value))
+                raise ValueError(
+                    'END value %u less than START value %u' % (tmp, int_value))
             elif not is_start and tmp > int_value:
-                raise ValueError('END value %u less than START value %u' %
-                                 (int_value, tmp))
+                raise ValueError(
+                    'END value %u less than START value %u' % (int_value, tmp))
 
         # Add START values to the head of the list and END values at the end.
         # Thus, the list is ordered with index 0 as START and index 1 as END.
@@ -533,7 +585,7 @@
 
     # list of handler to required options, used to identify the
     # parsing section
-    _SECTIONS = [('_handle_aid', ('value',)),
+    _SECTIONS = [('_handle_aid', ('value', )),
                  ('_handle_path', ('mode', 'user', 'group', 'caps'))]
 
     def __init__(self, config_files, oem_ranges):
@@ -596,8 +648,8 @@
                     break
 
             if not found:
-                sys.exit('Invalid section "%s" in file: "%s"' %
-                         (section, file_name))
+                sys.exit('Invalid section "%s" in file: "%s"' % (section,
+                                                                 file_name))
 
             # sort entries:
             # * specified path before prefix match
@@ -717,9 +769,9 @@
             try:
                 # test if string is int, if it is, use as is.
                 int(cap, 0)
-                tmp.append('(' + cap + ')')
+                tmp.append(cap)
             except ValueError:
-                tmp.append('CAP_MASK_LONG(CAP_' + cap.upper() + ')')
+                tmp.append('CAP_' + cap.upper())
 
         caps = tmp
 
@@ -734,7 +786,7 @@
         if len(mode) != 4:
             sys.exit('Mode must be 3 or 4 characters, got: "%s"' % mode)
 
-        caps_str = '|'.join(caps)
+        caps_str = ','.join(caps)
 
         entry = FSConfig(mode, user, group, caps_str, section_name, file_name)
         if section_name[-1] == '/':
@@ -892,41 +944,20 @@
     Output is  used in generating fs_config_files and fs_config_dirs.
     """
 
-    _GENERATED = textwrap.dedent("""\
-        /*
-         * THIS IS AN AUTOGENERATED FILE! DO NOT MODIFY
-         */
-        """)
-
-    _INCLUDES = [
-        '<private/android_filesystem_config.h>', '"generated_oem_aid.h"'
-    ]
-
-    _DEFINE_NO_DIRS = '#define NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_DIRS'
-    _DEFINE_NO_FILES = '#define NO_ANDROID_FILESYSTEM_CONFIG_DEVICE_FILES'
-
-    _DEFAULT_WARNING = (
-        '#warning No device-supplied android_filesystem_config.h,'
-        ' using empty default.')
-
-    _OPEN_FILE_STRUCT = (
-        'static const struct fs_path_config android_device_files[] = {')
-
-    _OPEN_DIR_STRUCT = (
-        'static const struct fs_path_config android_device_dirs[] = {')
-
-    _CLOSE_FILE_STRUCT = '};'
-
-    _GENERIC_DEFINE = "#define %s\t%s"
-
-    _FILE_COMMENT = '// Defined in file: \"%s\"'
-
     def __init__(self, *args, **kwargs):
         BaseGenerator.__init__(args, kwargs)
 
         self._oem_parser = None
         self._base_parser = None
         self._friendly_to_aid = None
+        self._id_to_aid = None
+        self._capability_parser = None
+
+        self._partition = None
+        self._all_partitions = None
+        self._out_file = None
+        self._generate_files = False
+        self._generate_dirs = False
 
     def add_opts(self, opt_group):
 
@@ -939,11 +970,56 @@
             help='An android_filesystem_config.h file'
             ' to parse AIDs and OEM Ranges from')
 
+        opt_group.add_argument(
+            '--capability-header',
+            required=True,
+            help='A capability.h file to parse capability defines from')
+
+        opt_group.add_argument(
+            '--partition',
+            required=True,
+            help='Partition to generate contents for')
+
+        opt_group.add_argument(
+            '--all-partitions',
+            help='Comma separated list of all possible partitions, used to'
+            ' ignore these partitions when generating the output for the system partition'
+        )
+
+        opt_group.add_argument(
+            '--files', action='store_true', help='Output fs_config_files')
+
+        opt_group.add_argument(
+            '--dirs', action='store_true', help='Output fs_config_dirs')
+
+        opt_group.add_argument('--out_file', required=True, help='Output file')
+
     def __call__(self, args):
 
+        self._capability_parser = CapabilityHeaderParser(
+            args['capability_header'])
         self._base_parser = AIDHeaderParser(args['aid_header'])
         self._oem_parser = FSConfigFileParser(args['fsconfig'],
                                               self._base_parser.oem_ranges)
+
+        self._partition = args['partition']
+        self._all_partitions = args['all_partitions']
+        if self._partition == 'system' and self._all_partitions is None:
+            sys.exit(
+                'All other partitions must be provided if generating output'
+                ' for the system partition')
+
+        self._out_file = args['out_file']
+
+        self._generate_files = args['files']
+        self._generate_dirs = args['dirs']
+
+        if self._generate_files and self._generate_dirs:
+            sys.exit('Only one of --files or --dirs can be provided')
+
+        if not self._generate_files and not self._generate_dirs:
+            sys.exit('One of --files or --dirs must be provided')
+
         base_aids = self._base_parser.aids
         oem_aids = self._oem_parser.aids
 
@@ -959,7 +1035,7 @@
 
         common = base_set & oem_set
 
-        if len(common) > 0:
+        if common:
             emsg = 'Following AID Collisions detected for: \n'
             for friendly in common:
                 base = base_friendly[friendly]
@@ -973,53 +1049,105 @@
         self._friendly_to_aid = oem_friendly
         self._friendly_to_aid.update(base_friendly)
 
+        self._id_to_aid = {aid.identifier: aid for aid in base_aids}
+        self._id_to_aid.update({aid.identifier: aid for aid in oem_aids})
+
         self._generate()
 
-    def _to_fs_entry(self, fs_config):
+    def _to_fs_entry(self, fs_config, out_file):
         """Converts an FSConfig entry to an fs entry.
 
-        Prints '{ mode, user, group, caps, "path" },'.
+        Writes the fs_config contents to the output file.
 
         Calls sys.exit() on error.
 
         Args:
-            fs_config (FSConfig): The entry to convert to
-                a valid C array entry.
+            fs_config (FSConfig): The entry to convert to write to file.
+            file (File): The file to write to.
         """
 
         # Get some short names
         mode = fs_config.mode
         user = fs_config.user
         group = fs_config.group
-        fname = fs_config.filename
         caps = fs_config.caps
         path = fs_config.path
 
-        emsg = 'Cannot convert friendly name "%s" to identifier!'
+        emsg = 'Cannot convert "%s" to identifier!'
 
-        # remap friendly names to identifier names
+        # convert mode from octal string to integer
+        mode = int(mode, 8)
+
+        # remap names to values
         if AID.is_friendly(user):
             if user not in self._friendly_to_aid:
                 sys.exit(emsg % user)
-            user = self._friendly_to_aid[user].identifier
+            user = self._friendly_to_aid[user].value
+        else:
+            if user not in self._id_to_aid:
+                sys.exit(emsg % user)
+            user = self._id_to_aid[user].value
 
         if AID.is_friendly(group):
             if group not in self._friendly_to_aid:
                 sys.exit(emsg % group)
-            group = self._friendly_to_aid[group].identifier
+            group = self._friendly_to_aid[group].value
+        else:
+            if group not in self._id_to_aid:
+                sys.exit(emsg % group)
+            group = self._id_to_aid[group].value
 
-        fmt = '{ %s, %s, %s, %s, "%s" },'
+        caps_dict = self._capability_parser.caps
 
-        expanded = fmt % (mode, user, group, caps, path)
+        caps_value = 0
 
-        print FSConfigGen._FILE_COMMENT % fname
-        print '    ' + expanded
+        try:
+            # test if caps is an int
+            caps_value = int(caps, 0)
+        except ValueError:
+            caps_split = caps.split(',')
+            for cap in caps_split:
+                if cap not in caps_dict:
+                    sys.exit('Unkonwn cap "%s" found!' % cap)
+                caps_value += 1 << caps_dict[cap]
 
-    @staticmethod
-    def _gen_inc():
-        """Generate the include header lines and print to stdout."""
-        for include in FSConfigGen._INCLUDES:
-            print '#include %s' % include
+        path_length_with_null = len(path) + 1
+        path_length_aligned_64 = (path_length_with_null + 7) & ~7
+        # 16 bytes of header plus the path length with alignment
+        length = 16 + path_length_aligned_64
+
+        length_binary = bytearray(ctypes.c_uint16(length))
+        mode_binary = bytearray(ctypes.c_uint16(mode))
+        user_binary = bytearray(ctypes.c_uint16(int(user, 0)))
+        group_binary = bytearray(ctypes.c_uint16(int(group, 0)))
+        caps_binary = bytearray(ctypes.c_uint64(caps_value))
+        path_binary = ctypes.create_string_buffer(path,
+                                                  path_length_aligned_64).raw
+
+        out_file.write(length_binary)
+        out_file.write(mode_binary)
+        out_file.write(user_binary)
+        out_file.write(group_binary)
+        out_file.write(caps_binary)
+        out_file.write(path_binary)
+
+    def _emit_entry(self, fs_config):
+        """Returns a boolean whether or not to emit the input fs_config"""
+
+        path = fs_config.path
+
+        if self._partition == 'system':
+            for skip_partition in self._all_partitions.split(','):
+                if path.startswith(skip_partition) or path.startswith(
+                        'system/' + skip_partition):
+                    return False
+            return True
+        else:
+            if path.startswith(
+                    self._partition) or path.startswith('system/' +
+                                                        self._partition):
+                return True
+            return False
 
     def _generate(self):
         """Generates an OEM android_filesystem_config.h header file to stdout.
@@ -1030,50 +1158,20 @@
                 entries.
             aids ([AIDS]): A list of AID objects for Android Id entries.
         """
-        print FSConfigGen._GENERATED
-        print
-
-        FSConfigGen._gen_inc()
-        print
-
         dirs = self._oem_parser.dirs
         files = self._oem_parser.files
-        aids = self._oem_parser.aids
 
-        are_dirs = len(dirs) > 0
-        are_files = len(files) > 0
-        are_aids = len(aids) > 0
+        if self._generate_files:
+            with open(self._out_file, 'wb') as open_file:
+                for fs_config in files:
+                    if self._emit_entry(fs_config):
+                        self._to_fs_entry(fs_config, open_file)
 
-        if are_aids:
-            for aid in aids:
-                # use the preserved _path value
-                print FSConfigGen._FILE_COMMENT % aid.found
-                print FSConfigGen._GENERIC_DEFINE % (aid.identifier, aid.value)
-
-            print
-
-        if not are_dirs:
-            print FSConfigGen._DEFINE_NO_DIRS + '\n'
-
-        if not are_files:
-            print FSConfigGen._DEFINE_NO_FILES + '\n'
-
-        if not are_files and not are_dirs and not are_aids:
-            return
-
-        if are_files:
-            print FSConfigGen._OPEN_FILE_STRUCT
-            for fs_config in files:
-                self._to_fs_entry(fs_config)
-
-            print FSConfigGen._CLOSE_FILE_STRUCT
-
-        if are_dirs:
-            print FSConfigGen._OPEN_DIR_STRUCT
-            for dir_entry in dirs:
-                self._to_fs_entry(dir_entry)
-
-            print FSConfigGen._CLOSE_FILE_STRUCT
+        if self._generate_dirs:
+            with open(self._out_file, 'wb') as open_file:
+                for dir_entry in dirs:
+                    if self._emit_entry(dir_entry):
+                        self._to_fs_entry(dir_entry, open_file)
 
 
 @generator('aidarray')
@@ -1234,11 +1332,12 @@
         aids = parser.aids
 
         # nothing to do if no aids defined
-        if len(aids) == 0:
+        if not aids:
             return
 
         for aid in aids:
-            if required_prefix is None or aid.friendly.startswith(required_prefix):
+            if required_prefix is None or aid.friendly.startswith(
+                    required_prefix):
                 self._print_formatted_line(aid)
             else:
                 sys.exit("%s: AID '%s' must start with '%s'" %
@@ -1294,6 +1393,7 @@
 
         print "%s::%s:" % (logon, uid)
 
+
 @generator('print')
 class PrintGen(BaseGenerator):
     """Prints just the constants and values, separated by spaces, in an easy to
diff --git a/tools/fs_config/fs_config_test.cpp b/tools/fs_config/fs_config_test.cpp
deleted file mode 100644
index 916c615..0000000
--- a/tools/fs_config/fs_config_test.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdio.h>
-#include <sys/cdefs.h>
-
-#include <string>
-#include <vector>
-
-#include <android-base/file.h>
-#include <android-base/macros.h>
-#include <android-base/strings.h>
-#include <gtest/gtest.h>
-#include <private/android_filesystem_config.h>
-#include <private/fs_config.h>
-
-#include "android_filesystem_config_test_data.h"
-
-// must run test in the test directory
-static const std::string fs_config_generate_command = "./fs_config_generate_test";
-
-static std::string popenToString(const std::string command) {
-  std::string ret;
-
-  auto fp = popen(command.c_str(), "r");
-  if (fp) {
-    if (!android::base::ReadFdToString(fileno(fp), &ret)) ret = "";
-    pclose(fp);
-  }
-  return ret;
-}
-
-static void confirm(std::string&& data, const fs_path_config* config,
-                    ssize_t num_config) {
-  auto pc = reinterpret_cast<const fs_path_config_from_file*>(data.c_str());
-  auto len = data.size();
-
-  ASSERT_TRUE(config != NULL);
-  ASSERT_LT(0, num_config);
-
-  while (len > 0) {
-    auto host_len = pc->len;
-    if (host_len > len) break;
-
-    EXPECT_EQ(config->mode, pc->mode);
-    EXPECT_EQ(config->uid, pc->uid);
-    EXPECT_EQ(config->gid, pc->gid);
-    EXPECT_EQ(config->capabilities, pc->capabilities);
-    EXPECT_STREQ(config->prefix, pc->prefix);
-
-    EXPECT_LT(0, num_config);
-    --num_config;
-    if (num_config >= 0) ++config;
-    pc = reinterpret_cast<const fs_path_config_from_file*>(
-        reinterpret_cast<const char*>(pc) + host_len);
-    len -= host_len;
-  }
-  EXPECT_EQ(0, num_config);
-}
-
-/* See local android_filesystem_config.h for test data */
-
-TEST(fs_conf_test, dirs) {
-  confirm(popenToString(fs_config_generate_command + " -D"),
-          android_device_dirs, arraysize(android_device_dirs));
-}
-
-TEST(fs_conf_test, files) {
-  confirm(popenToString(fs_config_generate_command + " -F"),
-          android_device_files, arraysize(android_device_files));
-}
-
-static bool is_system(const char* prefix) {
-  return !android::base::StartsWith(prefix, "vendor/") &&
-         !android::base::StartsWith(prefix, "system/vendor/") &&
-         !android::base::StartsWith(prefix, "oem/") &&
-         !android::base::StartsWith(prefix, "system/oem/") &&
-         !android::base::StartsWith(prefix, "odm/") &&
-         !android::base::StartsWith(prefix, "system/odm/") &&
-         !android::base::StartsWith(prefix, "product/") &&
-         !android::base::StartsWith(prefix, "system/product/") &&
-         !android::base::StartsWith(prefix, "product_services/") &&
-         !android::base::StartsWith(prefix, "system/product_services/");
-}
-
-TEST(fs_conf_test, system_dirs) {
-  std::vector<fs_path_config> dirs;
-  auto config = android_device_dirs;
-  for (auto num = arraysize(android_device_dirs); num; --num) {
-    if (is_system(config->prefix)) {
-      dirs.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(fs_config_generate_command + " -D -P -vendor,-oem,-odm,-product,-product_services"),
-          &dirs[0], dirs.size());
-}
-
-static void fs_conf_test_dirs(const std::string& partition_name) {
-  std::vector<fs_path_config> dirs;
-  auto config = android_device_dirs;
-  const auto str = partition_name + "/";
-  const auto alt_str = "system/" + partition_name + "/";
-  for (auto num = arraysize(android_device_dirs); num; --num) {
-    if (android::base::StartsWith(config->prefix, str) ||
-        android::base::StartsWith(config->prefix, alt_str)) {
-      dirs.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(fs_config_generate_command + " -D -P " + partition_name),
-          &dirs[0], dirs.size());
-}
-
-TEST(fs_conf_test, vendor_dirs) {
-  fs_conf_test_dirs("vendor");
-}
-
-TEST(fs_conf_test, oem_dirs) {
-  fs_conf_test_dirs("oem");
-}
-
-TEST(fs_conf_test, odm_dirs) {
-  fs_conf_test_dirs("odm");
-}
-
-TEST(fs_conf_test, system_files) {
-  std::vector<fs_path_config> files;
-  auto config = android_device_files;
-  for (auto num = arraysize(android_device_files); num; --num) {
-    if (is_system(config->prefix)) {
-      files.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(fs_config_generate_command + " -F -P -vendor,-oem,-odm,-product,-product_services"),
-          &files[0], files.size());
-}
-
-static void fs_conf_test_files(const std::string& partition_name) {
-  std::vector<fs_path_config> files;
-  auto config = android_device_files;
-  const auto str = partition_name + "/";
-  const auto alt_str = "system/" + partition_name + "/";
-  for (auto num = arraysize(android_device_files); num; --num) {
-    if (android::base::StartsWith(config->prefix, str) ||
-        android::base::StartsWith(config->prefix, alt_str)) {
-      files.emplace_back(*config);
-    }
-    ++config;
-  }
-  confirm(popenToString(fs_config_generate_command + " -F -P " + partition_name),
-          &files[0], files.size());
-}
-
-TEST(fs_conf_test, vendor_files) {
-  fs_conf_test_files("vendor");
-}
-
-TEST(fs_conf_test, oem_files) {
-  fs_conf_test_files("oem");
-}
-
-TEST(fs_conf_test, odm_files) {
-  fs_conf_test_files("odm");
-}
-
-TEST(fs_conf_test, product_files) {
-  fs_conf_test_files("product");
-}
-
-TEST(fs_conf_test, product_services_files) {
-  fs_conf_test_files("product_services");
-}
diff --git a/tools/fs_config/test_fs_config_generator.py b/tools/fs_config/test_fs_config_generator.py
index a49058a..b7f173e 100755
--- a/tools/fs_config/test_fs_config_generator.py
+++ b/tools/fs_config/test_fs_config_generator.py
@@ -45,19 +45,21 @@
     def test_aid(self):
         """Test AID class constructor"""
 
-        aid = AID('AID_FOO_BAR', '0xFF', 'myfakefile')
-        self.assertEquals(aid.identifier, 'AID_FOO_BAR')
-        self.assertEquals(aid.value, '0xFF')
-        self.assertEquals(aid.found, 'myfakefile')
-        self.assertEquals(aid.normalized_value, '255')
-        self.assertEquals(aid.friendly, 'foo_bar')
+        aid = AID('AID_FOO_BAR', '0xFF', 'myfakefile', '/system/bin/sh')
+        self.assertEqual(aid.identifier, 'AID_FOO_BAR')
+        self.assertEqual(aid.value, '0xFF')
+        self.assertEqual(aid.found, 'myfakefile')
+        self.assertEqual(aid.normalized_value, '255')
+        self.assertEqual(aid.friendly, 'foo_bar')
+        self.assertEqual(aid.login_shell, '/system/bin/sh')
 
-        aid = AID('AID_MEDIA_EX', '1234', 'myfakefile')
-        self.assertEquals(aid.identifier, 'AID_MEDIA_EX')
-        self.assertEquals(aid.value, '1234')
-        self.assertEquals(aid.found, 'myfakefile')
-        self.assertEquals(aid.normalized_value, '1234')
-        self.assertEquals(aid.friendly, 'mediaex')
+        aid = AID('AID_MEDIA_EX', '1234', 'myfakefile', '/vendor/bin/sh')
+        self.assertEqual(aid.identifier, 'AID_MEDIA_EX')
+        self.assertEqual(aid.value, '1234')
+        self.assertEqual(aid.found, 'myfakefile')
+        self.assertEqual(aid.normalized_value, '1234')
+        self.assertEqual(aid.friendly, 'mediaex')
+        self.assertEqual(aid.login_shell, '/vendor/bin/sh')
 
     def test_aid_header_parser_good(self):
         """Test AID Header Parser good input file"""
@@ -265,9 +267,9 @@
             dirs = parser.dirs
             aids = parser.aids
 
-            self.assertEquals(len(files), 1)
-            self.assertEquals(len(dirs), 1)
-            self.assertEquals(len(aids), 1)
+            self.assertEqual(len(files), 1)
+            self.assertEqual(len(dirs), 1)
+            self.assertEqual(len(aids), 1)
 
             aid = aids[0]
             fcap = files[0]
@@ -275,14 +277,14 @@
 
             self.assertEqual(fcap,
                              FSConfig('0777', 'AID_FOO', 'AID_SYSTEM',
-                                      '(1ULL << CAP_BLOCK_SUSPEND)',
+                                      'CAP_BLOCK_SUSPEND',
                                       '/system/bin/file', temp_file.name))
 
             self.assertEqual(dcap,
-                             FSConfig('0777', 'AID_FOO', 'AID_SYSTEM', '(0)',
+                             FSConfig('0777', 'AID_FOO', 'AID_SYSTEM', '0',
                                       '/vendor/path/dir/', temp_file.name))
 
-            self.assertEqual(aid, AID('AID_OEM1', '0x1389', temp_file.name))
+            self.assertEqual(aid, AID('AID_OEM1', '0x1389', temp_file.name, '/vendor/bin/sh'))
 
     def test_fs_config_file_parser_bad(self):
         """Test FSConfig Parser bad input file"""
diff --git a/tools/releasetools/add_img_to_target_files.py b/tools/releasetools/add_img_to_target_files.py
index e75b3b7..5132ae7 100755
--- a/tools/releasetools/add_img_to_target_files.py
+++ b/tools/releasetools/add_img_to_target_files.py
@@ -119,9 +119,12 @@
 
   simg = sparse_img.SparseImage(imgname)
   care_map_ranges = simg.care_map
-  key = which + "_image_blocks"
-  image_blocks = OPTIONS.info_dict.get(key)
-  if image_blocks:
+  size_key = which + "_image_size"
+  image_size = OPTIONS.info_dict.get(size_key)
+  if image_size:
+    # excludes the verity metadata blocks of the given image. When AVB is enabled,
+    # this size is the max image size returned by the AVB tool
+    image_blocks = int(image_size) / 4096 - 1
     assert image_blocks > 0, "blocks for {} must be positive".format(which)
     care_map_ranges = care_map_ranges.intersect(
         rangelib.RangeSet("0-{}".format(image_blocks)))
@@ -319,9 +322,7 @@
   if block_list:
     block_list.Write()
 
-  # Set the '_image_blocks' that excludes the verity metadata blocks of the
-  # given image. When AVB is enabled, this size is the max image size returned
-  # by the AVB tool.
+  # Set the '_image_size' for given image size.
   is_verity_partition = "verity_block_device" in image_props
   verity_supported = (image_props.get("verity") == "true" or
                       image_props.get("avb_enable") == "true")
@@ -329,8 +330,8 @@
   if verity_supported and (is_verity_partition or is_avb_enable):
     image_size = image_props.get("image_size")
     if image_size:
-      image_blocks_key = what + "_image_blocks"
-      info_dict[image_blocks_key] = int(image_size) / 4096 - 1
+      image_size_key = what + "_image_size"
+      info_dict[image_size_key] = int(image_size)
 
   use_dynamic_size = (
       info_dict.get("use_dynamic_partition_size") == "true" and
@@ -733,6 +734,7 @@
                           os.path.exists(os.path.join(OPTIONS.input_tmp,
                                                       "IMAGES",
                                                       "product_services.img")))
+  has_system = os.path.isdir(os.path.join(OPTIONS.input_tmp, "SYSTEM"))
   has_system_other = os.path.isdir(os.path.join(OPTIONS.input_tmp,
                                                 "SYSTEM_OTHER"))
 
@@ -797,9 +799,10 @@
         if output_zip:
           recovery_two_step_image.AddToZip(output_zip)
 
-  banner("system")
-  partitions['system'] = AddSystem(
-      output_zip, recovery_img=recovery_image, boot_img=boot_image)
+  if has_system:
+    banner("system")
+    partitions['system'] = AddSystem(
+        output_zip, recovery_img=recovery_image, boot_img=boot_image)
 
   if has_vendor:
     banner("vendor")
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 5d310d2..8a60f7d 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -190,6 +190,25 @@
   return subprocess.Popen(args, **kwargs)
 
 
+def RunAndWait(args, verbose=None, **kwargs):
+  """Runs the given command and returns the exit code.
+
+  Args:
+    args: The command represented as a list of strings.
+    verbose: Whether the commands should be shown. Default to the global
+        verbosity if unspecified.
+    kwargs: Any additional args to be passed to subprocess.Popen(), such as env,
+        stdin, etc. stdout and stderr will default to subprocess.PIPE and
+        subprocess.STDOUT respectively unless caller specifies any of them.
+
+  Returns:
+    The process return code.
+  """
+  proc = Run(args, verbose=verbose, **kwargs)
+  proc.wait()
+  return proc.returncode
+
+
 def RunAndCheckOutput(args, verbose=None, **kwargs):
   """Runs the given command and returns the output.
 
diff --git a/tools/releasetools/merge_target_files.py b/tools/releasetools/merge_target_files.py
new file mode 100755
index 0000000..b02363c
--- /dev/null
+++ b/tools/releasetools/merge_target_files.py
@@ -0,0 +1,679 @@
+#!/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.
+
+"""
+This script merges two partial target files packages (one of which contains
+system files, and the other contains non-system files) together, producing a
+complete target files package that can be used to generate an OTA package.
+
+Usage: merge_target_files.py [args]
+
+  --system-target-files system-target-files-zip-archive
+      The input target files package containing system bits. This is a zip
+      archive.
+
+  --other-target-files other-target-files-zip-archive
+      The input target files package containing other bits. This is a zip
+      archive.
+
+  --output-target-files output-target-files-package
+      The output merged target files package. Also a zip archive.
+"""
+
+from __future__ import print_function
+
+import argparse
+import fnmatch
+import logging
+import os
+import sys
+import zipfile
+
+import common
+import add_img_to_target_files
+
+logger = logging.getLogger(__name__)
+OPTIONS = common.OPTIONS
+OPTIONS.verbose = True
+
+# system_extract_as_is_item_list is a list of items to extract from the partial
+# system target files package as is, meaning these items will land in the
+# output target files package exactly as they appear in the input partial
+# system target files package.
+
+system_extract_as_is_item_list = [
+    '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/*',
+    'SYSTEM/*',
+]
+
+# system_extract_special_item_list is a list of items to extract from the
+# partial system target files package that need some special processing, such
+# as some sort of combination with items from the partial other target files
+# package.
+
+system_extract_special_item_list = [
+    'META/*',
+]
+
+# system_misc_info_keys is a list of keys to obtain from the system instance of
+# META/misc_info.txt. The remaining keys from the other instance.
+
+system_misc_info_keys = [
+    'avb_system_hashtree_enable',
+    'avb_system_add_hashtree_footer_args',
+    'avb_system_key_path',
+    'avb_system_algorithm',
+    'avb_system_rollback_index_location',
+    'avb_product_hashtree_enable',
+    'avb_product_add_hashtree_footer_args',
+    'avb_product_services_hashtree_enable',
+    'avb_product_services_add_hashtree_footer_args',
+    'system_root_image',
+    'root_dir',
+    'ab_update',
+    'default_system_dev_certificate',
+    'system_size',
+]
+
+# other_extract_as_is_item_list is a list of items to extract from the partial
+# other target files package as is, meaning these items will land in the output
+# target files package exactly as they appear in the input partial other target
+# files package.
+
+other_extract_as_is_item_list = [
+    'META/boot_filesystem_config.txt',
+    'META/otakeys.txt',
+    'META/releasetools.py',
+    'META/vendor_filesystem_config.txt',
+    'META/vendor_manifest.xml',
+    'META/vendor_matrix.xml',
+    'BOOT/*',
+    'DATA/*',
+    'ODM/*',
+    'OTA/android-info.txt',
+    'PREBUILT_IMAGES/*',
+    'RADIO/*',
+    'VENDOR/*',
+]
+
+# other_extract_for_merge_item_list is a list of items to extract from the
+# partial other target files package that need some special processing, such as
+# some sort of combination with items from the partial system target files
+# package.
+
+other_extract_special_item_list = [
+    'META/*',
+]
+
+
+def extract_items(target_files, target_files_temp_dir, extract_item_list):
+  """Extract items from target files to temporary directory.
+
+  This function extracts from the specified target files zip archive into the
+  specified temporary directory, the items specified in the extract item list.
+
+  Args:
+    target_files: The target files zip archive from which to extract items.
+
+    target_files_temp_dir: The temporary directory where the extracted items
+    will land.
+
+    extract_item_list: A list of items to extract.
+
+  Returns:
+    On success, 0. Otherwise, a non-zero exit code from unzip.
+  """
+
+  logger.info('extracting from %s', target_files)
+
+  # Filter the extract_item_list to remove any items that do not exist in the
+  # zip file. Otherwise, the extraction step will fail.
+
+  with zipfile.ZipFile(
+      target_files,
+      'r',
+      allowZip64=True) as target_files_zipfile:
+    target_files_namelist = target_files_zipfile.namelist()
+
+  filtered_extract_item_list = []
+  for pattern in extract_item_list:
+    matching_namelist = fnmatch.filter(target_files_namelist, pattern)
+    if not matching_namelist:
+      logger.warning('no match for %s', pattern)
+    else:
+      filtered_extract_item_list.append(pattern)
+
+  # Extract the filtered_extract_item_list from target_files into
+  # target_files_temp_dir.
+
+  # TODO(b/124464492): Extend common.UnzipTemp() to handle this use case.
+  command = [
+      'unzip',
+      '-n',
+      '-q',
+      '-d', target_files_temp_dir,
+      target_files
+  ] + filtered_extract_item_list
+
+  result = common.RunAndWait(command, verbose=True)
+
+  if result != 0:
+    logger.error('extract_items command %s failed %d', str(command), result)
+    return result
+
+  return 0
+
+
+def process_ab_partitions_txt(
+    system_target_files_temp_dir,
+    other_target_files_temp_dir,
+    output_target_files_temp_dir):
+  """Perform special processing for META/ab_partitions.txt
+
+  This function merges the contents of the META/ab_partitions.txt files from
+  the system directory and the other directory, placing the merged result in
+  the output directory. The precondition in that the files are already
+  extracted. The post condition is that the output META/ab_partitions.txt
+  contains the merged content. The format for each ab_partitions.txt a one
+  partition name per line. The output file contains the union of the parition
+  names.
+
+  Args:
+    system_target_files_temp_dir: The name of a directory containing the
+    special items extracted from the system target files package.
+
+    other_target_files_temp_dir: The name of a directory containing the
+    special items extracted from the other target files package.
+
+    output_target_files_temp_dir: The name of a directory that will be used
+    to create the output target files package after all the special cases
+    are processed.
+  """
+
+  system_ab_partitions_txt = os.path.join(
+      system_target_files_temp_dir, 'META', 'ab_partitions.txt')
+
+  other_ab_partitions_txt = os.path.join(
+      other_target_files_temp_dir, 'META', 'ab_partitions.txt')
+
+  with open(system_ab_partitions_txt) as f:
+    system_ab_partitions = f.read().splitlines()
+
+  with open(other_ab_partitions_txt) as f:
+    other_ab_partitions = f.read().splitlines()
+
+  output_ab_partitions = set(system_ab_partitions + other_ab_partitions)
+
+  output_ab_partitions_txt = os.path.join(
+      output_target_files_temp_dir, 'META', 'ab_partitions.txt')
+
+  with open(output_ab_partitions_txt, 'w') as output:
+    for partition in sorted(output_ab_partitions):
+      output.write('%s\n' % partition)
+
+
+def process_misc_info_txt(
+    system_target_files_temp_dir,
+    other_target_files_temp_dir,
+    output_target_files_temp_dir):
+  """Perform special processing for META/misc_info.txt
+
+  This function merges the contents of the META/misc_info.txt files from the
+  system directory and the other directory, placing the merged result in the
+  output directory. The precondition in that the files are already extracted.
+  The post condition is that the output META/misc_info.txt contains the merged
+  content.
+
+  Args:
+    system_target_files_temp_dir: The name of a directory containing the
+    special items extracted from the system target files package.
+
+    other_target_files_temp_dir: The name of a directory containing the
+    special items extracted from the other target files package.
+
+    output_target_files_temp_dir: The name of a directory that will be used
+    to create the output target files package after all the special cases
+    are processed.
+  """
+
+  def read_helper(d):
+    misc_info_txt = os.path.join(d, 'META', 'misc_info.txt')
+    with open(misc_info_txt) as f:
+      return list(f.read().splitlines())
+
+  system_info_dict = common.LoadDictionaryFromLines(
+      read_helper(system_target_files_temp_dir))
+
+  # We take most of the misc info from the other target files.
+
+  merged_info_dict = common.LoadDictionaryFromLines(
+      read_helper(other_target_files_temp_dir))
+
+  # Replace certain values in merged_info_dict with values from
+  # system_info_dict. TODO(b/124467065): This should be more flexible than
+  # using the hard-coded system_misc_info_keys.
+
+  for key in system_misc_info_keys:
+    merged_info_dict[key] = system_info_dict[key]
+
+  output_misc_info_txt = os.path.join(
+      output_target_files_temp_dir,
+      'META', 'misc_info.txt')
+
+  sorted_keys = sorted(merged_info_dict.keys())
+
+  with open(output_misc_info_txt, 'w') as output:
+    for key in sorted_keys:
+      output.write('{}={}\n'.format(key, merged_info_dict[key]))
+
+
+def process_file_contexts_bin(temp_dir, output_target_files_temp_dir):
+  """Perform special processing for META/file_contexts.bin.
+
+  This function combines plat_file_contexts and vendor_file_contexts, which are
+  expected to already be extracted in temp_dir, to produce a merged
+  file_contexts.bin that will land in temp_dir at META/file_contexts.bin.
+
+  Args:
+    temp_dir: The name of a scratch directory that this function can use for
+    intermediate files generated during processing.
+
+    output_target_files_temp_dir: The name of the working directory that must
+    already contain plat_file_contexts and vendor_file_contexts (in the
+    appropriate sub directories), and to which META/file_contexts.bin will be
+    written.
+
+  Returns:
+    On success, 0. Otherwise, a non-zero exit code.
+  """
+
+  # To create a merged file_contexts.bin file, we use the system and vendor
+  # file contexts files as input, the m4 tool to combine them, the sorting tool
+  # to sort, and finally the sefcontext_compile tool to generate the final
+  # output. We currently omit a checkfc step since the files had been checked
+  # as part of the build.
+
+  # The m4 step concatenates the two input files contexts files. Since m4
+  # writes to stdout, we receive that into an array of bytes, and then write it
+  # to a file.
+
+  # Collect the file contexts that we're going to combine from SYSTEM, VENDOR,
+  # PRODUCT, and ODM. We require SYSTEM and VENDOR, but others are optional.
+
+  file_contexts_list = []
+
+  for partition in ['SYSTEM', 'VENDOR', 'PRODUCT', 'ODM']:
+    prefix = 'plat' if partition == 'SYSTEM' else partition.lower()
+
+    file_contexts = os.path.join(
+        output_target_files_temp_dir,
+        partition, 'etc', 'selinux', prefix + '_file_contexts')
+
+    mandatory = partition in ['SYSTEM', 'VENDOR']
+
+    if mandatory or os.path.isfile(file_contexts):
+      file_contexts_list.append(file_contexts)
+    else:
+      logger.warning('file not found: %s', file_contexts)
+
+  command = ['m4', '--fatal-warnings', '-s'] + file_contexts_list
+
+  merged_content = common.RunAndCheckOutput(command, verbose=False)
+
+  merged_file_contexts_txt = os.path.join(temp_dir, 'merged_file_contexts.txt')
+
+  with open(merged_file_contexts_txt, 'wb') as f:
+    f.write(merged_content)
+
+  # The sort step sorts the concatenated file.
+
+  sorted_file_contexts_txt = os.path.join(temp_dir, 'sorted_file_contexts.txt')
+  command = ['fc_sort', merged_file_contexts_txt, sorted_file_contexts_txt]
+
+  # TODO(b/124521133): Refector RunAndWait to raise exception on failure.
+  result = common.RunAndWait(command, verbose=True)
+
+  if result != 0:
+    return result
+
+  # Finally, the compile step creates the final META/file_contexts.bin.
+
+  file_contexts_bin = os.path.join(
+      output_target_files_temp_dir,
+      'META', 'file_contexts.bin')
+
+  command = [
+      'sefcontext_compile',
+      '-o', file_contexts_bin,
+      sorted_file_contexts_txt,
+  ]
+
+  result = common.RunAndWait(command, verbose=True)
+
+  if result != 0:
+    return result
+
+  return 0
+
+
+def process_special_cases(
+    temp_dir,
+    system_target_files_temp_dir,
+    other_target_files_temp_dir,
+    output_target_files_temp_dir):
+  """Perform special-case processing for certain target files items.
+
+  Certain files in the output target files package require special-case
+  processing. This function performs all that special-case processing.
+
+  Args:
+    temp_dir: The name of a scratch directory that this function can use for
+    intermediate files generated during processing.
+
+    system_target_files_temp_dir: The name of a directory containing the
+    special items extracted from the system target files package.
+
+    other_target_files_temp_dir: The name of a directory containing the
+    special items extracted from the other target files package.
+
+    output_target_files_temp_dir: The name of a directory that will be used
+    to create the output target files package after all the special cases
+    are processed.
+
+  Returns:
+    On success, 0. Otherwise, a non-zero exit code.
+  """
+
+  process_ab_partitions_txt(
+      system_target_files_temp_dir=system_target_files_temp_dir,
+      other_target_files_temp_dir=other_target_files_temp_dir,
+      output_target_files_temp_dir=output_target_files_temp_dir)
+
+  process_misc_info_txt(
+      system_target_files_temp_dir=system_target_files_temp_dir,
+      other_target_files_temp_dir=other_target_files_temp_dir,
+      output_target_files_temp_dir=output_target_files_temp_dir)
+
+  result = process_file_contexts_bin(
+      temp_dir=temp_dir,
+      output_target_files_temp_dir=output_target_files_temp_dir)
+
+  if result != 0:
+    return result
+
+  return 0
+
+
+def merge_target_files(
+    temp_dir,
+    system_target_files,
+    other_target_files,
+    output_target_files):
+  """Merge two target files packages together.
+
+  This function takes system and other target files packages as input, performs
+  various file extractions, special case processing, and finally creates a
+  merged zip archive as output.
+
+  Args:
+    temp_dir: The name of a directory we use when we extract items from the
+    input target files packages, and also a scratch directory that we use for
+    temporary files.
+
+    system_target_files: The name of the zip archive containing the system
+    partial target files package.
+
+    other_target_files: The name of the zip archive containing the other
+    partial target files package.
+
+    output_target_files: The name of the output zip archive target files
+    package created by merging system and other.
+
+  Returns:
+    On success, 0. Otherwise, a non-zero exit code.
+  """
+
+  # Create directory names that we'll use when we extract files from system,
+  # and other, and for zipping the final output.
+
+  system_target_files_temp_dir = os.path.join(temp_dir, 'system')
+  other_target_files_temp_dir = os.path.join(temp_dir, 'other')
+  output_target_files_temp_dir = os.path.join(temp_dir, 'output')
+
+  # Extract "as is" items from the input system partial target files package.
+  # We extract them directly into the output temporary directory since the
+  # items do not need special case processing.
+
+  result = extract_items(
+      target_files=system_target_files,
+      target_files_temp_dir=output_target_files_temp_dir,
+      extract_item_list=system_extract_as_is_item_list)
+
+  if result != 0:
+    return result
+
+  # Extract "as is" items from the input other partial target files package. We
+  # extract them directly into the output temporary directory since the items
+  # do not need special case processing.
+
+  result = extract_items(
+      target_files=other_target_files,
+      target_files_temp_dir=output_target_files_temp_dir,
+      extract_item_list=other_extract_as_is_item_list)
+
+  if result != 0:
+    return result
+
+  # Extract "special" items from the input system partial target files package.
+  # We extract these items to different directory since they require special
+  # processing before they will end up in the output directory.
+
+  result = extract_items(
+      target_files=system_target_files,
+      target_files_temp_dir=system_target_files_temp_dir,
+      extract_item_list=system_extract_special_item_list)
+
+  if result != 0:
+    return result
+
+  # Extract "special" items from the input other partial target files package.
+  # We extract these items to different directory since they require special
+  # processing before they will end up in the output directory.
+
+  result = extract_items(
+      target_files=other_target_files,
+      target_files_temp_dir=other_target_files_temp_dir,
+      extract_item_list=other_extract_special_item_list)
+
+  if result != 0:
+    return result
+
+  # Now that the temporary directories contain all the extracted files, perform
+  # special case processing on any items that need it. After this function
+  # completes successfully, all the files we need to create the output target
+  # files package are in place.
+
+  result = process_special_cases(
+      temp_dir=temp_dir,
+      system_target_files_temp_dir=system_target_files_temp_dir,
+      other_target_files_temp_dir=other_target_files_temp_dir,
+      output_target_files_temp_dir=output_target_files_temp_dir)
+
+  if result != 0:
+    return result
+
+  # Regenerate IMAGES in the temporary directory.
+
+  add_img_args = [
+      '--verbose',
+      output_target_files_temp_dir,
+  ]
+
+  add_img_to_target_files.main(add_img_args)
+
+  # Finally, create the output target files zip archive.
+
+  output_zip = os.path.abspath(output_target_files)
+  output_target_files_list = os.path.join(temp_dir, 'output.list')
+  output_target_files_meta_dir = os.path.join(
+      output_target_files_temp_dir, 'META')
+
+  command = [
+      'find',
+      output_target_files_meta_dir,
+  ]
+  # TODO(bpeckham): sort this to be more like build.
+  meta_content = common.RunAndCheckOutput(command, verbose=False)
+  command = [
+      'find',
+      output_target_files_temp_dir,
+      '-path',
+      output_target_files_meta_dir,
+      '-prune',
+      '-o',
+      '-print'
+  ]
+  # TODO(bpeckham): sort this to be more like build.
+  other_content = common.RunAndCheckOutput(command, verbose=False)
+
+  with open(output_target_files_list, 'wb') as f:
+    f.write(meta_content)
+    f.write(other_content)
+
+  command = [
+      # TODO(124468071): Use soong_zip from otatools.zip
+      'prebuilts/build-tools/linux-x86/bin/soong_zip',
+      '-d',
+      '-o', output_zip,
+      '-C', output_target_files_temp_dir,
+      '-l', output_target_files_list,
+  ]
+  logger.info('creating %s', output_target_files)
+  result = common.RunAndWait(command, verbose=True)
+
+  if result != 0:
+    logger.error('zip command %s failed %d', str(command), result)
+    return result
+
+  return 0
+
+
+def merge_target_files_with_temp_dir(
+    system_target_files,
+    other_target_files,
+    output_target_files,
+    keep_tmp):
+  """Manage the creation and cleanup of the temporary directory.
+
+  This function wraps merge_target_files after first creating a temporary
+  directory. It also cleans up the temporary directory.
+
+  Args:
+    system_target_files: The name of the zip archive containing the system
+    partial target files package.
+
+    other_target_files: The name of the zip archive containing the other
+    partial target files package.
+
+    output_target_files: The name of the output zip archive target files
+    package created by merging system and other.
+
+    keep_tmp: Keep the temporary directory after processing is complete.
+
+  Returns:
+    On success, 0. Otherwise, a non-zero exit code.
+  """
+
+  # Create a temporary directory. This will serve as the parent of directories
+  # we use when we extract items from the input target files packages, and also
+  # a scratch directory that we use for temporary files.
+
+  logger.info(
+      'starting: merge system %s and other %s into output %s',
+      system_target_files,
+      other_target_files,
+      output_target_files)
+
+  temp_dir = common.MakeTempDir(prefix='merge_target_files_')
+
+  try:
+    return merge_target_files(
+        temp_dir=temp_dir,
+        system_target_files=system_target_files,
+        other_target_files=other_target_files,
+        output_target_files=output_target_files)
+  except:
+    raise
+  finally:
+    if keep_tmp:
+      logger.info('keeping %s', temp_dir)
+    else:
+      common.Cleanup()
+
+
+def main():
+  """The main function.
+
+  Process command line arguments, then call merge_target_files_with_temp_dir to
+  perform the heavy lifting.
+
+  Returns:
+    On success, 0. Otherwise, a non-zero exit code.
+  """
+
+  common.InitLogging()
+
+  parser = argparse.ArgumentParser()
+
+  parser.add_argument(
+      '--system-target-files',
+      required=True,
+      help='The input target files package containing system bits.')
+
+  parser.add_argument(
+      '--other-target-files',
+      required=True,
+      help='The input target files package containing other bits.')
+
+  parser.add_argument(
+      '--output-target-files',
+      required=True,
+      help='The output merged target files package.')
+
+  parser.add_argument(
+      '--keep-tmp',
+      required=False,
+      action='store_true',
+      help='Keep the temporary directories after execution.')
+
+  args = parser.parse_args()
+
+  return merge_target_files_with_temp_dir(
+      system_target_files=args.system_target_files,
+      other_target_files=args.other_target_files,
+      output_target_files=args.output_target_files,
+      keep_tmp=args.keep_tmp)
+
+
+if __name__ == '__main__':
+  sys.exit(main())
diff --git a/tools/releasetools/test_add_img_to_target_files.py b/tools/releasetools/test_add_img_to_target_files.py
index d2a274d..482f86c 100644
--- a/tools/releasetools/test_add_img_to_target_files.py
+++ b/tools/releasetools/test_add_img_to_target_files.py
@@ -362,7 +362,7 @@
         (0xCAC3, 4),
         (0xCAC1, 6)])
     OPTIONS.info_dict = {
-        'system_image_blocks' : 12,
+        'system_image_size' : 53248,
     }
     name, care_map = GetCareMap('system', sparse_image)
     self.assertEqual('system', name)
@@ -377,6 +377,6 @@
         (0xCAC3, 4),
         (0xCAC1, 6)])
     OPTIONS.info_dict = {
-        'system_image_blocks' : -12,
+        'system_image_size' : -45056,
     }
     self.assertRaises(AssertionError, GetCareMap, 'system', sparse_image)