resolved conflicts for merge of 6d607ee7 to lmp-mr1-dev-plus-aosp

Change-Id: I0a49bf5492cd5c1b03cf8cddd219db326d586909
diff --git a/CleanSpec.mk b/CleanSpec.mk
index e706b9c..334b7d8 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -284,6 +284,9 @@
 
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system)
 
+# Switch host builds to Clang by default
+$(call add-clean-step, rm -rf $(OUT_DIR)/host)
+
 # Adding dalvik.vm.dex2oat-filter
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
@@ -304,16 +307,54 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 
+# Move to libc++ as the default STL.
+$(call add-clean-step, rm -rf $(OUT_DIR))
+
+# dex2oat instruction-set changes
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
+# Make GNU++11 the default standard version. This requires a cleanspec because
+# char16_t/char32_t will be real types now instead of typedefs, which means
+# an ABI change since the names will mangle differently.
+$(call add-clean-step, rm -rf $(OUT_DIR))
+
 # 5.1!
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 
+# Remove ro.product.locale.language/country and add ro.product.locale
+# instead.
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+
+# Adding dalvik.vm.usejit
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
+# Rename dalvik.vm.usejit to debug.dalvik.vm.usejit
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
+# Revert rename dalvik.vm.usejit to debug.dalvik.vm.usejit
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
+# Change from interpret-only to verify-at-runtime.
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
 # 5.1.1!
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/core/Makefile b/core/Makefile
index 15c7f02..741d19c 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -156,29 +156,12 @@
   BUILD_DISPLAY_ID := $(build_desc)
 endif
 
-# Whether there is default locale set in PRODUCT_PROPERTY_OVERRIDES
-product_property_override_locale_language := $(strip \
-    $(patsubst ro.product.locale.language=%,%,\
-    $(filter ro.product.locale.language=%,$(PRODUCT_PROPERTY_OVERRIDES))))
-product_property_overrides_locale_region := $(strip \
-    $(patsubst ro.product.locale.region=%,%,\
-    $(filter ro.product.locale.region=%,$(PRODUCT_PROPERTY_OVERRIDES))))
-
-# Selects the first locale in the list given as the argument,
-# and splits it into language and region, which each may be
-# empty.
-define default-locale
-$(subst _, , $(firstword $(1)))
-endef
-
-# Selects the first locale in the list given as the argument
-# and returns the language (or the region), if it's not set in PRODUCT_PROPERTY_OVERRIDES;
-# Return empty string if it's already set in PRODUCT_PROPERTY_OVERRIDES.
-define default-locale-language
-$(if $(product_property_override_locale_language),,$(word 1, $(call default-locale, $(1))))
-endef
-define default-locale-region
-$(if $(product_property_overrides_locale_region),,$(word 2, $(call default-locale, $(1))))
+# Accepts a whitespace separated list of product locales such as
+# (en_US en_AU en_GB...) and returns the first locale in the list with
+# underscores replaced with hyphens. In the example above, this will
+# return "en-US".
+define get-default-product-locale
+$(strip $(subst _,-, $(firstword $(1))))
 endef
 
 BUILDINFO_SH := build/tools/buildinfo.sh
@@ -188,7 +171,7 @@
 else
 system_prop_file := $(wildcard $(TARGET_DEVICE_DIR)/system.prop)
 endif
-$(INSTALLED_BUILD_PROP_TARGET): $(BUILDINFO_SH) $(INTERNAL_BUILD_ID_MAKEFILE) $(BUILD_SYSTEM)/version_defaults.mk $(system_prop_file)
+$(INSTALLED_BUILD_PROP_TARGET): $(BUILDINFO_SH) $(INTERNAL_BUILD_ID_MAKEFILE) $(BUILD_SYSTEM)/version_defaults.mk $(system_prop_file) $(INSTALLED_ANDROID_INFO_TXT_TARGET)
 	@echo Target buildinfo: $@
 	@mkdir -p $(dir $@)
 	$(hide) echo > $@
@@ -204,8 +187,7 @@
 			TARGET_DEVICE="$(TARGET_DEVICE)" \
 			PRODUCT_NAME="$(TARGET_PRODUCT)" \
 			PRODUCT_BRAND="$(PRODUCT_BRAND)" \
-			PRODUCT_DEFAULT_LANGUAGE="$(call default-locale-language,$(PRODUCT_LOCALES))" \
-			PRODUCT_DEFAULT_REGION="$(call default-locale-region,$(PRODUCT_LOCALES))" \
+			PRODUCT_DEFAULT_LOCALE="$(call get-default-product-locale,$(PRODUCT_LOCALES))" \
 			PRODUCT_DEFAULT_WIFI_CHANNELS="$(PRODUCT_DEFAULT_WIFI_CHANNELS)" \
 			PRODUCT_MODEL="$(PRODUCT_MODEL)" \
 			PRODUCT_MANUFACTURER="$(PRODUCT_MANUFACTURER)" \
@@ -244,6 +226,7 @@
 		        echo "#" >> $@; )
 	$(hide) $(foreach line,$(ADDITIONAL_BUILD_PROPERTIES), \
 		echo "$(line)" >> $@;)
+	$(hide) cat $(INSTALLED_ANDROID_INFO_TXT_TARGET) | grep 'require version-' | sed -e 's/require version-/ro.build.expect./g' >> $@
 	$(hide) build/tools/post_process_props.py $@ $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_PROPERTY_BLACKLIST)
 
 build_desc :=
@@ -264,6 +247,21 @@
 	$(hide) echo ro.vendor.build.fingerprint="$(BUILD_FINGERPRINT)">>$@
 endif
 
+# ----------------------------------------------------------------
+# boot.img build.prop
+# as with vendor build.prop above, for verifying that the bootimage
+# build is what we think it is
+
+INSTALLED_BOOTIMAGE_BUILD_PROP_TARGET := $(TARGET_ROOT_OUT)/build.prop
+ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_BOOTIMAGE_BUILD_PROP_TARGET)
+$(INSTALLED_BOOTIMAGE_BUILD_PROP_TARGET): $(INSTALLED_BUILD_PROP_TARGET)
+	@echo Target bootimage buildinfo: $@
+	@mkdir -p $(dir $@)
+	$(hide) echo > $@
+	$(hide) echo ro.bootimage.build.date=`date`>>$@
+	$(hide) echo ro.bootimage.build.date.utc=`date +%s`>>$@
+	$(hide) echo ro.bootimage.build.fingerprint="$(BUILD_FINGERPRINT)">>$@
+
 # -----------------------------------------------------------------
 # sdk-build.prop
 #
@@ -489,23 +487,7 @@
 INSTALLED_BOOTIMAGE_TARGET := $(PRODUCT_OUT)/boot.img
 
 ifeq ($(TARGET_BOOTIMAGE_USE_EXT2),true)
-tmp_dir_for_image := $(call intermediates-dir-for,EXECUTABLES,boot_img)/bootimg
-INTERNAL_BOOTIMAGE_ARGS += --tmpdir $(tmp_dir_for_image)
-INTERNAL_BOOTIMAGE_ARGS += --genext2fs $(MKEXT2IMG)
-
-ifeq ($(TARGET_BOOTIMAGE_USE_EXTLINUX),true)
-INTERNAL_BOOTIMAGE_ARGS += --extlinuxconf $(TARGET_BOOTIMAGE_EXTLINUX_CONFIG)
-endif
-
-$(INSTALLED_BOOTIMAGE_TARGET): $(MKEXT2IMG) $(INTERNAL_BOOTIMAGE_FILES)
-	$(call pretty,"Target boot image: $@")
-	$(hide) $(MKEXT2BOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) --output $@
-
-.PHONY: bootimage-nodeps
-bootimage-nodeps: $(MKEXT2IMG)
-	@echo "make $@: ignoring dependencies"
-	$(hide) $(MKEXT2BOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET)
-
+$(error TARGET_BOOTIMAGE_USE_EXT2 is not supported anymore)
 else ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY)) # TARGET_BOOTIMAGE_USE_EXT2 != true
 
 $(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(BOOT_SIGNER)
@@ -697,8 +679,10 @@
 ifeq ($(TARGET_USERIMAGES_USE_F2FS),true)
 INTERNAL_USERIMAGES_DEPS += $(MKF2FSUSERIMG) $(MAKE_F2FS)
 endif
-else
-INTERNAL_USERIMAGES_DEPS := $(MKYAFFS2)
+endif
+
+ifeq ($(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE),squashfs)
+INTERNAL_USERIMAGES_DEPS += $(MAKE_SQUASHFS) $(MKSQUASHFSUSERIMG)
 endif
 
 INTERNAL_USERIMAGES_BINARY_PATHS := $(sort $(dir $(INTERNAL_USERIMAGES_DEPS)))
@@ -715,6 +699,7 @@
 define generate-userimage-prop-dictionary
 $(if $(INTERNAL_USERIMAGES_EXT_VARIANT),$(hide) echo "fs_type=$(INTERNAL_USERIMAGES_EXT_VARIANT)" >> $(1))
 $(if $(BOARD_SYSTEMIMAGE_PARTITION_SIZE),$(hide) echo "system_size=$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)" >> $(1))
+$(if $(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "system_fs_type=$(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE)" >> $(1))
 $(if $(BOARD_SYSTEMIMAGE_JOURNAL_SIZE),$(hide) echo "system_journal_size=$(BOARD_SYSTEMIMAGE_JOURNAL_SIZE)" >> $(1))
 $(if $(BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "userdata_fs_type=$(BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE)" >> $(1))
 $(if $(BOARD_USERDATAIMAGE_PARTITION_SIZE),$(hide) echo "userdata_size=$(BOARD_USERDATAIMAGE_PARTITION_SIZE)" >> $(1))
@@ -726,13 +711,15 @@
 $(if $(BOARD_OEMIMAGE_PARTITION_SIZE),$(hide) echo "oem_size=$(BOARD_OEMIMAGE_PARTITION_SIZE)" >> $(1))
 $(if $(BOARD_OEMIMAGE_JOURNAL_SIZE),$(hide) echo "oem_journal_size=$(BOARD_OEMIMAGE_JOURNAL_SIZE)" >> $(1))
 $(if $(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG),$(hide) echo "extfs_sparse_flag=$(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG)" >> $(1))
-$(if $(mkyaffs2_extra_flags),$(hide) echo "mkyaffs2_extra_flags=$(mkyaffs2_extra_flags)" >> $(1))
 $(hide) echo "selinux_fc=$(SELINUX_FC)" >> $(1)
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY)" >> $(1))
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity_key=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY)" >> $(1))
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity_signer_cmd=$(VERITY_SIGNER)" >> $(1))
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_VERITY_PARTITION),$(hide) echo "system_verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_VERITY_PARTITION)" >> $(1))
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_VERITY_PARTITION),$(hide) echo "vendor_verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_VERITY_PARTITION)" >> $(1))
+$(if $(filter true,$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)),\
+    $(hide) echo "system_root_image=true" >> $(1);\
+    echo "ramdisk_dir=$(TARGET_ROOT_OUT)" >> $(1))
 $(if $(2),$(hide) $(foreach kv,$(2),echo "$(kv)" >> $(1);))
 endef
 
@@ -744,12 +731,14 @@
 
 INSTALLED_RECOVERYIMAGE_TARGET := $(PRODUCT_OUT)/recovery.img
 
+INTERNAL_RECOVERYIMAGE_FILES := $(filter $(TARGET_RECOVERY_OUT)/%, \
+    $(ALL_DEFAULT_INSTALLED_MODULES))
+
 recovery_initrc := $(call include-path-for, recovery)/etc/init.rc
 recovery_sepolicy := $(call intermediates-dir-for,ETC,sepolicy.recovery)/sepolicy.recovery
 recovery_kernel := $(INSTALLED_KERNEL_TARGET) # same as a non-recovery system
 recovery_ramdisk := $(PRODUCT_OUT)/ramdisk-recovery.img
 recovery_build_prop := $(INSTALLED_BUILD_PROP_TARGET)
-recovery_binary := $(call intermediates-dir-for,EXECUTABLES,recovery)/recovery
 recovery_resources_common := $(call include-path-for, recovery)/res
 
 # Set recovery_density to the density bucket of the device.
@@ -833,51 +822,58 @@
 	@mkdir -p $(dir $@)
 	java -jar $(DUMPKEY_JAR) $(PRIVATE_OTA_PUBLIC_KEYS) $(extra_keys) > $@
 
+# $(1): output file
+define build-recoveryimage-target
+  @echo ----- Making recovery image ------
+  $(hide) mkdir -p $(TARGET_RECOVERY_OUT)
+  $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/etc $(TARGET_RECOVERY_ROOT_OUT)/tmp
+  @echo Copying baseline ramdisk...
+  $(hide) rsync -a $(TARGET_ROOT_OUT) $(TARGET_RECOVERY_OUT) # "cp -Rf" fails to overwrite broken symlinks on Mac.
+  @echo Modifying ramdisk contents...
+  $(hide) rm -f $(TARGET_RECOVERY_ROOT_OUT)/init*.rc
+  $(hide) cp -f $(recovery_initrc) $(TARGET_RECOVERY_ROOT_OUT)/
+  $(hide) rm -f $(TARGET_RECOVERY_ROOT_OUT)/sepolicy
+  $(hide) cp -f $(recovery_sepolicy) $(TARGET_RECOVERY_ROOT_OUT)/sepolicy
+  $(hide) cp $(TARGET_ROOT_OUT)/init.recovery.*.rc $(TARGET_RECOVERY_ROOT_OUT)/ | true # Ignore error when the src file doesn't exist.
+  $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/res
+  $(hide) rm -rf $(TARGET_RECOVERY_ROOT_OUT)/res/*
+  $(hide) cp -rf $(recovery_resources_common)/* $(TARGET_RECOVERY_ROOT_OUT)/res
+  $(hide) cp -f $(recovery_font) $(TARGET_RECOVERY_ROOT_OUT)/res/images/font.png
+  $(hide) $(foreach item,$(recovery_resources_private), \
+    cp -rf $(item) $(TARGET_RECOVERY_ROOT_OUT)/)
+  $(hide) $(foreach item,$(recovery_fstab), \
+    cp -f $(item) $(TARGET_RECOVERY_ROOT_OUT)/etc/recovery.fstab)
+  $(hide) cp $(RECOVERY_INSTALL_OTA_KEYS) $(TARGET_RECOVERY_ROOT_OUT)/res/keys
+  $(hide) cat $(INSTALLED_DEFAULT_PROP_TARGET) $(recovery_build_prop) \
+          > $(TARGET_RECOVERY_ROOT_OUT)/default.prop
+  $(hide) $(MKBOOTFS) $(TARGET_RECOVERY_ROOT_OUT) | $(MINIGZIP) > $(recovery_ramdisk)
+  $(hide) $(MKBOOTIMG) $(INTERNAL_RECOVERYIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(1)
+  $(if $(filter true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY)),\
+    $(BOOT_SIGNER) /recovery $(1) $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).pk8 $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem $(1))
+  $(hide) $(call assert-max-image-size,$(1),$(BOARD_RECOVERYIMAGE_PARTITION_SIZE))
+  @echo ----- Made recovery image: $(1) --------
+endef
+
 $(INSTALLED_RECOVERYIMAGE_TARGET): $(MKBOOTFS) $(MKBOOTIMG) $(MINIGZIP) \
 		$(INSTALLED_RAMDISK_TARGET) \
 		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(recovery_binary) \
+		$(INTERNAL_RECOVERYIMAGE_FILES) \
 		$(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \
 		$(INSTALLED_2NDBOOTLOADER_TARGET) \
 		$(recovery_build_prop) $(recovery_resource_deps) \
 		$(recovery_fstab) \
 		$(RECOVERY_INSTALL_OTA_KEYS)
-	@echo ----- Making recovery image ------
-	$(hide) rm -rf $(TARGET_RECOVERY_OUT)
-	$(hide) mkdir -p $(TARGET_RECOVERY_OUT)
-	$(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/etc $(TARGET_RECOVERY_ROOT_OUT)/tmp
-	@echo Copying baseline ramdisk...
-	$(hide) cp -R $(TARGET_ROOT_OUT) $(TARGET_RECOVERY_OUT)
-	@echo Modifying ramdisk contents...
-	$(hide) rm -f $(TARGET_RECOVERY_ROOT_OUT)/init*.rc
-	$(hide) cp -f $(recovery_initrc) $(TARGET_RECOVERY_ROOT_OUT)/
-	$(hide) rm -f $(TARGET_RECOVERY_ROOT_OUT)/sepolicy
-	$(hide) cp -f $(recovery_sepolicy) $(TARGET_RECOVERY_ROOT_OUT)/sepolicy
-	$(hide) -cp $(TARGET_ROOT_OUT)/init.recovery.*.rc $(TARGET_RECOVERY_ROOT_OUT)/
-	$(hide) cp -f $(recovery_binary) $(TARGET_RECOVERY_ROOT_OUT)/sbin/
-	$(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/res
-	$(hide) rm -rf $(TARGET_RECOVERY_ROOT_OUT)/res/*
-	$(hide) cp -rf $(recovery_resources_common)/* $(TARGET_RECOVERY_ROOT_OUT)/res
-	$(hide) cp -f $(recovery_font) $(TARGET_RECOVERY_ROOT_OUT)/res/images/font.png
-	$(hide) $(foreach item,$(recovery_resources_private), \
-	  cp -rf $(item) $(TARGET_RECOVERY_ROOT_OUT)/)
-	$(hide) $(foreach item,$(recovery_fstab), \
-	  cp -f $(item) $(TARGET_RECOVERY_ROOT_OUT)/etc/recovery.fstab)
-	$(hide) cp $(RECOVERY_INSTALL_OTA_KEYS) $(TARGET_RECOVERY_ROOT_OUT)/res/keys
-	$(hide) cat $(INSTALLED_DEFAULT_PROP_TARGET) $(recovery_build_prop) \
-	        > $(TARGET_RECOVERY_ROOT_OUT)/default.prop
-	$(hide) $(MKBOOTFS) $(TARGET_RECOVERY_ROOT_OUT) | $(MINIGZIP) > $(recovery_ramdisk)
-	$(hide) $(MKBOOTIMG) $(INTERNAL_RECOVERYIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@
-ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY))
-	$(BOOT_SIGNER) /recovery $@ $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).pk8 $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem $@
-endif
-	$(hide) $(call assert-max-image-size,$@,$(BOARD_RECOVERYIMAGE_PARTITION_SIZE))
-	@echo ----- Made recovery image: $@ --------
+		$(call build-recoveryimage-target, $@)
 
 $(RECOVERY_RESOURCE_ZIP): $(INSTALLED_RECOVERYIMAGE_TARGET)
 	$(hide) mkdir -p $(dir $@)
 	$(hide) find $(TARGET_RECOVERY_ROOT_OUT)/res -type f | sort | zip -0qrj $@ -@
 
+.PHONY: recoveryimage-nodeps
+recoveryimage-nodeps:
+	@echo "make $@: ignoring dependencies"
+	$(call build-recoveryimage-target, $(INSTALLED_RECOVERYIMAGE_TARGET))
+
 else
 INSTALLED_RECOVERYIMAGE_TARGET :=
 RECOVERY_RESOURCE_ZIP :=
@@ -886,16 +882,11 @@
 .PHONY: recoveryimage
 recoveryimage: $(INSTALLED_RECOVERYIMAGE_TARGET) $(RECOVERY_RESOURCE_ZIP)
 
-ifneq ($(BOARD_NAND_PAGE_SIZE),)
-mkyaffs2_extra_flags := -c $(BOARD_NAND_PAGE_SIZE)
-else
-mkyaffs2_extra_flags :=
+ifeq ($(BOARD_NAND_PAGE_SIZE),)
 BOARD_NAND_PAGE_SIZE := 2048
 endif
 
-ifneq ($(BOARD_NAND_SPARE_SIZE),)
-mkyaffs2_extra_flags += -s $(BOARD_NAND_SPARE_SIZE)
-else
+ifeq ($(BOARD_NAND_SPARE_SIZE),)
 BOARD_NAND_SPARE_SIZE := 64
 endif
 
@@ -915,6 +906,7 @@
     $(PDK_FUSION_SYSIMG_FILES) \
     $(RECOVERY_RESOURCE_ZIP))
 
+
 FULL_SYSTEMIMAGE_DEPS := $(INTERNAL_SYSTEMIMAGE_FILES) $(INTERNAL_USERIMAGES_DEPS)
 # -----------------------------------------------------------------
 # installed file list
@@ -1254,12 +1246,12 @@
 	  $(HOST_OUT_EXECUTABLES)/mkbootfs \
 	  $(HOST_OUT_EXECUTABLES)/mkbootimg \
 	  $(HOST_OUT_EXECUTABLES)/fs_config \
-	  $(HOST_OUT_EXECUTABLES)/mkyaffs2image \
 	  $(HOST_OUT_EXECUTABLES)/zipalign \
 	  $(HOST_OUT_EXECUTABLES)/bsdiff \
 	  $(HOST_OUT_EXECUTABLES)/imgdiff \
 	  $(HOST_OUT_JAVA_LIBRARIES)/dumpkey.jar \
 	  $(HOST_OUT_JAVA_LIBRARIES)/signapk.jar \
+	  $(HOST_OUT_JAVA_LIBRARIES)/BootSignature.jar \
 	  $(HOST_OUT_EXECUTABLES)/mkuserimg.sh \
 	  $(HOST_OUT_EXECUTABLES)/make_ext4fs \
 	  $(HOST_OUT_EXECUTABLES)/simg2img \
@@ -1275,6 +1267,29 @@
 .PHONY: otatools
 otatools: $(OTATOOLS)
 
+BUILT_OTATOOLS_PACKAGE := $(PRODUCT_OUT)/otatools.zip
+$(BUILT_OTATOOLS_PACKAGE): \
+	intermediate := $(call intermediates-dir-for,PACKAGING,otatools)
+$(BUILT_OTATOOLS_PACKAGE): \
+	zip_root := $(intermediate)/otatools
+
+$(BUILT_OTATOOLS_PACKAGE): \
+		$(OTATOOLS)
+	@echo "Package OTA tools: $@"
+	$(hide) rm -rf $@ $(zip_root)
+	$(hide) mkdir -p $(dir $@) $(zip_root)/bin $(zip_root)/framework $(zip_root)/releasetools
+	$(hide) $(ACP) -p $(OTATOOLS) $(zip_root)/bin
+	$(hide) mv $(zip_root)/bin/*.jar $(zip_root)/framework/
+	$(hide) $(ACP) -r -d -p build/tools/releasetools/* $(zip_root)/releasetools
+	$(hide) rm -rf $@ $(zip_root)/releasetools/*.pyc
+	$(hide) (cd $(zip_root) && zip -qry $(abspath $@) bin framework releasetools)
+	$(hide) zip -qry $(abspath $@) build/target/product/security/
+	$(hide) find device vendor -name \*.pk8 -o -name \*.x509.pem -o -name oem.prop | xargs zip -qry $(abspath $@)
+
+.PHONY: otatools-package
+otatools-package: $(BUILT_OTATOOLS_PACKAGE)
+
+
 # -----------------------------------------------------------------
 # A zip of the directories that map to the target filesystem.
 # This zip can be used to create an OTA package or filesystem image
@@ -1303,11 +1318,11 @@
 endef
 
 built_ota_tools := \
-	$(call intermediates-dir-for,EXECUTABLES,applypatch)/applypatch \
-	$(call intermediates-dir-for,EXECUTABLES,applypatch_static)/applypatch_static \
-	$(call intermediates-dir-for,EXECUTABLES,check_prereq)/check_prereq \
-	$(call intermediates-dir-for,EXECUTABLES,sqlite3)/sqlite3 \
-	$(call intermediates-dir-for,EXECUTABLES,updater)/updater
+	$(call intermediates-dir-for,EXECUTABLES,applypatch,,,$(TARGET_PREFER_32_BIT))/applypatch \
+	$(call intermediates-dir-for,EXECUTABLES,applypatch_static,,,$(TARGET_PREFER_32_BIT))/applypatch_static \
+	$(call intermediates-dir-for,EXECUTABLES,check_prereq,,,$(TARGET_PREFER_32_BIT))/check_prereq \
+	$(call intermediates-dir-for,EXECUTABLES,sqlite3,,,$(TARGET_PREFER_32_BIT))/sqlite3 \
+	$(call intermediates-dir-for,EXECUTABLES,updater,,,$(TARGET_PREFER_32_BIT))/updater
 $(BUILT_TARGET_FILES_PACKAGE): PRIVATE_OTA_TOOLS := $(built_ota_tools)
 
 $(BUILT_TARGET_FILES_PACKAGE): PRIVATE_RECOVERY_API_VERSION := $(RECOVERY_API_VERSION)
@@ -1402,7 +1417,7 @@
 	$(hide) mkdir -p $(zip_root)/META
 	$(hide) $(ACP) $(APKCERTS_FILE) $(zip_root)/META/apkcerts.txt
 	$(hide) if test -e $(tool_extensions)/releasetools.py; then $(ACP) $(tool_extensions)/releasetools.py $(zip_root)/META/; fi
-	$(hide)	echo "$(PRODUCT_OTA_PUBLIC_KEYS)" > $(zip_root)/META/otakeys.txt
+	$(hide) echo "$(PRODUCT_OTA_PUBLIC_KEYS)" > $(zip_root)/META/otakeys.txt
 	$(hide) echo "recovery_api_version=$(PRIVATE_RECOVERY_API_VERSION)" > $(zip_root)/META/misc_info.txt
 	$(hide) echo "fstab_version=$(PRIVATE_RECOVERY_FSTAB_VERSION)" >> $(zip_root)/META/misc_info.txt
 ifdef BOARD_FLASH_BLOCK_SIZE
@@ -1435,7 +1450,8 @@
 	$(hide) echo "oem_fingerprint_properties=$(OEM_THUMBPRINT_PROPERTIES)" >> $(zip_root)/META/misc_info.txt
 endif
 	$(call generate-userimage-prop-dictionary, $(zip_root)/META/misc_info.txt)
-	$(hide) ./build/tools/releasetools/make_recovery_patch $(zip_root) $(zip_root)
+	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
+	    ./build/tools/releasetools/make_recovery_patch $(zip_root) $(zip_root)
 	@# Zip everything up, preserving symlinks
 	$(hide) (cd $(zip_root) && zip -qry ../$(notdir $@) .)
 	@# Run fs_config on all the system, vendor, boot ramdisk,
@@ -1445,7 +1461,8 @@
 	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="BOOT/RAMDISK/" } /^BOOT\/RAMDISK\// {print $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config -C -S $(SELINUX_FC) > $(zip_root)/META/boot_filesystem_config.txt
 	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="RECOVERY/RAMDISK/" } /^RECOVERY\/RAMDISK\// {print $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config -C -S $(SELINUX_FC) > $(zip_root)/META/recovery_filesystem_config.txt
 	$(hide) (cd $(zip_root) && zip -q ../$(notdir $@) META/*filesystem_config.txt)
-	$(hide) ./build/tools/releasetools/add_img_to_target_files -p $(HOST_OUT) $@
+	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
+	    ./build/tools/releasetools/add_img_to_target_files -p $(HOST_OUT) $@
 
 .PHONY: target-files-package
 target-files-package: $(BUILT_TARGET_FILES_PACKAGE)
@@ -1474,7 +1491,7 @@
 
 $(INTERNAL_OTA_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(DISTTOOLS)
 	@echo "Package OTA: $@"
-	$(hide) MKBOOTIMG=$(MKBOOTIMG) \
+	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \
 	   ./build/tools/releasetools/ota_from_target_files -v \
 	   --block \
 	   -p $(HOST_OUT) \
@@ -1503,7 +1520,7 @@
 
 $(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(DISTTOOLS)
 	@echo "Package: $@"
-	$(hide) MKBOOTIMG=$(MKBOOTIMG) \
+	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \
 	   ./build/tools/releasetools/img_from_target_files -v \
 	   -p $(HOST_OUT) \
 	   $(BUILT_TARGET_FILES_PACKAGE) $@
@@ -1578,10 +1595,10 @@
 		  unobfuscated_jars=$${dict_files//proguard_dictionary/classes.jar}; \
 		  zip -q $@ $$dict_files $$unobfuscated_jars; \
 		else \
-		  touch $(dir $@)/dummy; \
-		  (cd $(dir $@) && zip -q $(notdir $@) dummy); \
-		  zip -qd $@ dummy; \
-		  rm $(dir $@)/dummy; \
+		  touch $(dir $@)/zipdummy; \
+		  (cd $(dir $@) && zip -q $(notdir $@) zipdummy); \
+		  zip -qd $@ zipdummy; \
+		  rm $(dir $@)/zipdummy; \
 		fi
 
 endif # TARGET_BUILD_APPS
@@ -1751,7 +1768,7 @@
 MAIN_SDK_NAME := $(sdk_name)
 MAIN_SDK_DIR  := $(sdk_dir)
 MAIN_SDK_ZIP  := $(INTERNAL_SDK_TARGET)
-ifneq ($(filter win_sdk,$(MAKECMDGOALS)),)
+ifneq ($(filter win_sdk winsdk-tools,$(MAKECMDGOALS)),)
 include $(TOPDIR)development/build/tools/windows_sdk.mk
 endif
 
diff --git a/core/base_rules.mk b/core/base_rules.mk
index dfed3ea..99107ab 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -220,7 +220,12 @@
 endif # LOCAL_SDK_VERSION
 $(aidl_java_sources): PRIVATE_AIDL_FLAGS := -b $(addprefix -p,$(aidl_preprocess_import)) -I$(LOCAL_PATH) -I$(LOCAL_PATH)/src $(addprefix -I,$(LOCAL_AIDL_INCLUDES))
 
-$(aidl_java_sources): $(intermediates.COMMON)/src/%.java: $(TOPDIR)$(LOCAL_PATH)/%.aidl $(LOCAL_ADDITIONAL_DEPENDENCIES) $(AIDL) $(aidl_preprocess_import)
+$(aidl_java_sources): $(intermediates.COMMON)/src/%.java: \
+        $(TOPDIR)$(LOCAL_PATH)/%.aidl \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES) \
+        $(AIDL) \
+        $(aidl_preprocess_import)
 	$(transform-aidl-to-java)
 -include $(aidl_java_sources:%.java=%.P)
 
@@ -564,27 +569,27 @@
 ###########################################################
 ## CHECK_BUILD goals
 ###########################################################
-
-ifdef java_alternative_checked_module
-  LOCAL_CHECKED_MODULE := $(java_alternative_checked_module)
-endif
-
+my_checked_module :=
 # If nobody has defined a more specific module for the
 # checked modules, use LOCAL_BUILT_MODULE.
-ifndef LOCAL_CHECKED_MODULE
-  LOCAL_CHECKED_MODULE := $(LOCAL_BUILT_MODULE)
+ifdef LOCAL_CHECKED_MODULE
+  my_checked_module := $(LOCAL_CHECKED_MODULE)
+else ifdef java_alternative_checked_module
+  my_checked_module := $(java_alternative_checked_module)
+else
+  my_checked_module := $(LOCAL_BUILT_MODULE)
 endif
 
 # If they request that this module not be checked, then don't.
 # PLEASE DON'T SET THIS.  ANY PLACES THAT SET THIS WITHOUT
 # GOOD REASON WILL HAVE IT REMOVED.
 ifdef LOCAL_DONT_CHECK_MODULE
-  LOCAL_CHECKED_MODULE :=
+  my_checked_module :=
 endif
 # Don't check build target module defined for the 2nd arch
 ifndef LOCAL_IS_HOST_MODULE
 ifdef LOCAL_2ND_ARCH_VAR_PREFIX
-  LOCAL_CHECKED_MODULE :=
+  my_checked_module :=
 endif
 endif
 
@@ -603,7 +608,7 @@
 ALL_MODULES.$(my_register_name).TAGS := \
     $(ALL_MODULES.$(my_register_name).TAGS) $(my_module_tags)
 ALL_MODULES.$(my_register_name).CHECKED := \
-    $(ALL_MODULES.$(my_register_name).CHECKED) $(LOCAL_CHECKED_MODULE)
+    $(ALL_MODULES.$(my_register_name).CHECKED) $(my_checked_module)
 ALL_MODULES.$(my_register_name).BUILT := \
     $(ALL_MODULES.$(my_register_name).BUILT) $(LOCAL_BUILT_MODULE)
 ifneq (true,$(LOCAL_UNINSTALLABLE_MODULE))
@@ -669,9 +674,9 @@
 endif
 
 ifdef j_or_n
-$(j_or_n) $(h_or_t) $(j_or_n)-$(h_or_t) : $(LOCAL_CHECKED_MODULE)
+$(j_or_n) $(h_or_t) $(j_or_n)-$(h_or_t) : $(my_checked_module)
 ifneq (,$(filter $(my_module_tags),tests))
-$(j_or_n)-$(h_or_t)-tests $(j_or_n)-tests $(h_or_t)-tests : $(LOCAL_CHECKED_MODULE)
+$(j_or_n)-$(h_or_t)-tests $(j_or_n)-tests $(h_or_t)-tests : $(my_checked_module)
 endif
 endif
 
diff --git a/core/binary.mk b/core/binary.mk
index 1e313ff..92b08fa 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -9,73 +9,6 @@
 include $(BUILD_SYSTEM)/base_rules.mk
 #######################################
 
-my_ndk_sysroot :=
-my_ndk_sysroot_include :=
-my_ndk_sysroot_lib :=
-ifdef LOCAL_SDK_VERSION
-  ifdef LOCAL_NDK_VERSION
-    $(error $(LOCAL_PATH): LOCAL_NDK_VERSION is now retired.)
-  endif
-  ifdef LOCAL_IS_HOST_MODULE
-    $(error $(LOCAL_PATH): LOCAL_SDK_VERSION cannot be used in host module)
-  endif
-  my_ndk_source_root := $(HISTORICAL_NDK_VERSIONS_ROOT)/current/sources
-  my_ndk_sysroot := $(HISTORICAL_NDK_VERSIONS_ROOT)/current/platforms/android-$(LOCAL_SDK_VERSION)/arch-$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
-  my_ndk_sysroot_include := $(my_ndk_sysroot)/usr/include
-  ifeq (x86_64,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
-    my_ndk_sysroot_lib := $(my_ndk_sysroot)/usr/lib64
-  else
-    my_ndk_sysroot_lib := $(my_ndk_sysroot)/usr/lib
-  endif
-
-  # Set up the NDK stl variant. Starting from NDK-r5 the c++ stl resides in a separate location.
-  # See ndk/docs/CPLUSPLUS-SUPPORT.html
-  my_ndk_stl_include_path :=
-  my_ndk_stl_shared_lib_fullpath :=
-  my_ndk_stl_shared_lib :=
-  my_ndk_stl_static_lib :=
-  my_ndk_stl_cppflags :=
-  LOCAL_NDK_STL_VARIANT := $(strip $(LOCAL_NDK_STL_VARIANT))
-  ifeq (,$(LOCAL_NDK_STL_VARIANT))
-    LOCAL_NDK_STL_VARIANT := system
-  endif
-  ifneq (1,$(words $(filter system stlport_static stlport_shared c++_static c++_shared gnustl_static, $(LOCAL_NDK_STL_VARIANT))))
-    $(error $(LOCAL_PATH): Unknown LOCAL_NDK_STL_VARIANT $(LOCAL_NDK_STL_VARIANT))
-  endif
-  ifeq (system,$(LOCAL_NDK_STL_VARIANT))
-    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/system/include
-    # for "system" variant, the shared library exists in the system library and -lstdc++ is added by default.
-  else # LOCAL_NDK_STL_VARIANT is not system
-  ifneq (,$(filter stlport_%, $(LOCAL_NDK_STL_VARIANT)))
-    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/stlport/stlport
-    ifeq (stlport_static,$(LOCAL_NDK_STL_VARIANT))
-      my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/stlport/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/libstlport_static.a
-    else
-      my_ndk_stl_shared_lib_fullpath := $(my_ndk_source_root)/cxx-stl/stlport/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/libstlport_shared.so
-      my_ndk_stl_shared_lib := -lstlport_shared
-    endif
-  else # LOCAL_NDK_STL_VARIANT is not stlport_* either
-  ifneq (,$(filter c++_%, $(LOCAL_NDK_STL_VARIANT)))
-    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/llvm-libc++/libcxx/include \
-                               $(my_ndk_source_root)/cxx-stl/llvm-libc++/gabi++/include \
-                               $(my_ndk_source_root)/android/support/include
-    ifeq (c++_static,$(LOCAL_NDK_STL_VARIANT))
-      my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/llvm-libc++/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/libc++_static.a
-    else
-      my_ndk_stl_shared_lib_fullpath := $(my_ndk_source_root)/cxx-stl/llvm-libc++/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/libc++_shared.so
-      my_ndk_stl_shared_lib := -lc++_shared
-    endif
-    my_ndk_stl_cppflags := -std=c++11
-  else
-    # LOCAL_NDK_STL_VARIANT is gnustl_static
-    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/include \
-                               $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/include
-    my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/libgnustl_static.a
-  endif
-  endif
-  endif
-endif
-
 ##################################################
 # Compute the dependency of the shared libraries
 ##################################################
@@ -105,18 +38,107 @@
 my_whole_static_libraries := $(LOCAL_WHOLE_STATIC_LIBRARIES)
 my_shared_libraries := $(LOCAL_SHARED_LIBRARIES)
 my_cflags := $(LOCAL_CFLAGS)
+my_conlyflags := $(LOCAL_CONLYFLAGS)
 my_cppflags := $(LOCAL_CPPFLAGS)
 my_ldflags := $(LOCAL_LDFLAGS)
+my_ldlibs := $(LOCAL_LDLIBS)
 my_asflags := $(LOCAL_ASFLAGS)
 my_cc := $(LOCAL_CC)
 my_cxx := $(LOCAL_CXX)
 my_c_includes := $(LOCAL_C_INCLUDES)
 my_generated_sources := $(LOCAL_GENERATED_SOURCES)
+my_native_coverage := $(LOCAL_NATIVE_COVERAGE)
+my_additional_dependencies := $(LOCAL_MODULE_MAKEFILE) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+
+ifdef LOCAL_IS_HOST_MODULE
+my_allow_undefined_symbols := true
+else
+my_allow_undefined_symbols := $(strip $(LOCAL_ALLOW_UNDEFINED_SYMBOLS))
+endif
+
+my_ndk_sysroot :=
+my_ndk_sysroot_include :=
+my_ndk_sysroot_lib :=
+ifdef LOCAL_SDK_VERSION
+  ifdef LOCAL_NDK_VERSION
+    $(error $(LOCAL_PATH): LOCAL_NDK_VERSION is now retired.)
+  endif
+  ifdef LOCAL_IS_HOST_MODULE
+    $(error $(LOCAL_PATH): LOCAL_SDK_VERSION cannot be used in host module)
+  endif
+  my_ndk_source_root := $(HISTORICAL_NDK_VERSIONS_ROOT)/current/sources
+  my_ndk_sysroot := $(HISTORICAL_NDK_VERSIONS_ROOT)/current/platforms/android-$(LOCAL_SDK_VERSION)/arch-$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
+  my_ndk_sysroot_include := $(my_ndk_sysroot)/usr/include
+  ifeq (x86_64,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+    my_ndk_sysroot_lib := $(my_ndk_sysroot)/usr/lib64
+  else ifeq (mips32r6,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH_VARIANT))
+    my_ndk_sysroot_lib := $(my_ndk_sysroot)/usr/libr6
+  else
+    my_ndk_sysroot_lib := $(my_ndk_sysroot)/usr/lib
+  endif
+
+  # The bionic linker now has support for gnu style hashes (which are much
+  # faster!), but shipping to older devices requires the old style hash.
+  #ifeq ($(shell expr $(LOCAL_SDK_VERSION) >= FIRST_SUPPORTED_VERSION),0)
+    my_ldflags += -Wl,--hash-style=sysv
+  #endif
+
+  # Set up the NDK stl variant. Starting from NDK-r5 the c++ stl resides in a separate location.
+  # See ndk/docs/CPLUSPLUS-SUPPORT.html
+  my_ndk_stl_include_path :=
+  my_ndk_stl_shared_lib_fullpath :=
+  my_ndk_stl_shared_lib :=
+  my_ndk_stl_static_lib :=
+  my_ndk_stl_cppflags :=
+  my_cpu_variant := $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)
+  ifeq (mips32r6,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH_VARIANT))
+    my_cpu_variant := mips32r6
+  endif
+  LOCAL_NDK_STL_VARIANT := $(strip $(LOCAL_NDK_STL_VARIANT))
+  ifeq (,$(LOCAL_NDK_STL_VARIANT))
+    LOCAL_NDK_STL_VARIANT := system
+  endif
+  ifneq (1,$(words $(filter system stlport_static stlport_shared c++_static c++_shared gnustl_static, $(LOCAL_NDK_STL_VARIANT))))
+    $(error $(LOCAL_PATH): Unknown LOCAL_NDK_STL_VARIANT $(LOCAL_NDK_STL_VARIANT))
+  endif
+  ifeq (system,$(LOCAL_NDK_STL_VARIANT))
+    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/system/include
+    # for "system" variant, the shared library exists in the system library and -lstdc++ is added by default.
+  else # LOCAL_NDK_STL_VARIANT is not system
+  ifneq (,$(filter stlport_%, $(LOCAL_NDK_STL_VARIANT)))
+    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/stlport/stlport
+    ifeq (stlport_static,$(LOCAL_NDK_STL_VARIANT))
+      my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/stlport/libs/$(my_cpu_variant)/libstlport_static.a
+    else
+      my_ndk_stl_shared_lib_fullpath := $(my_ndk_source_root)/cxx-stl/stlport/libs/$(my_cpu_variant)/libstlport_shared.so
+      my_ndk_stl_shared_lib := -lstlport_shared
+    endif
+  else # LOCAL_NDK_STL_VARIANT is not stlport_* either
+  ifneq (,$(filter c++_%, $(LOCAL_NDK_STL_VARIANT)))
+    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/llvm-libc++/libcxx/include \
+                               $(my_ndk_source_root)/cxx-stl/llvm-libc++/gabi++/include \
+                               $(my_ndk_source_root)/android/support/include
+    ifeq (c++_static,$(LOCAL_NDK_STL_VARIANT))
+      my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/llvm-libc++/libs/$(my_cpu_variant)/libc++_static.a
+    else
+      my_ndk_stl_shared_lib_fullpath := $(my_ndk_source_root)/cxx-stl/llvm-libc++/libs/$(my_cpu_variant)/libc++_shared.so
+      my_ndk_stl_shared_lib := -lc++_shared
+    endif
+    my_ndk_stl_cppflags := -std=c++11
+  else
+    # LOCAL_NDK_STL_VARIANT is gnustl_static
+    my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/libs/$(my_cpu_variant)/include \
+                               $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/include
+    my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/libs/$(my_cpu_variant)/libgnustl_static.a
+  endif
+  endif
+  endif
+endif
 
 # MinGW spits out warnings about -fPIC even for -fpie?!) being ignored because
 # all code is position independent, and then those warnings get promoted to
 # errors.
-ifeq ($(strip $(USE_MINGW)),)
+ifndef USE_MINGW
 ifeq ($(LOCAL_MODULE_CLASS),EXECUTABLES)
 my_cflags += -fpie
 else
@@ -133,12 +155,29 @@
 my_c_includes += $(LOCAL_C_INCLUDES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_C_INCLUDES_$(my_32_64_bit_suffix))
 my_generated_sources += $(LOCAL_GENERATED_SOURCES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_GENERATED_SOURCES_$(my_32_64_bit_suffix))
 
-my_clang := $(LOCAL_CLANG)
+my_clang := $(strip $(LOCAL_CLANG))
 ifdef LOCAL_CLANG_$(my_32_64_bit_suffix)
-my_clang := $(LOCAL_CLANG_$(my_32_64_bit_suffix))
+my_clang := $(strip $(LOCAL_CLANG_$(my_32_64_bit_suffix)))
 endif
 ifdef LOCAL_CLANG_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
-my_clang := $(LOCAL_CLANG_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+my_clang := $(strip $(LOCAL_CLANG_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)))
+endif
+
+# clang is enabled by default for host builds
+# enable it unless we've specifically disabled clang above
+ifdef LOCAL_IS_HOST_MODULE
+    ifneq ($(HOST_OS),windows)
+    ifeq ($(my_clang),)
+        my_clang := true
+    endif
+    endif
+endif
+
+# Add option to make clang the default for device build
+ifeq ($(USE_CLANG_PLATFORM_BUILD),true)
+    ifeq ($(my_clang),)
+        my_clang := true
+    endif
 endif
 
 # arch-specific static libraries go first so that generic ones can depend on them
@@ -147,12 +186,7 @@
 
 my_cflags := $(filter-out $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)GLOBAL_UNSUPPORTED_CFLAGS),$(my_cflags))
 
-
-# Replace libstdc++ with libc++ if it's seen
-my_libcxx := $(filter libc++, $(my_shared_libraries))
-ifdef my_libcxx
-my_system_shared_libraries := $(filter-out libstdc++, $(my_system_shared_libraries))
-endif
+include $(BUILD_SYSTEM)/cxx_stl_setup.mk
 
 # Add static HAL libraries
 ifdef LOCAL_HAL_STATIC_LIBRARIES
@@ -163,15 +197,7 @@
 b_lib :=
 endif
 
-ifeq ($(strip $(LOCAL_ADDRESS_SANITIZER)),true)
-  my_clang := true
-  # Frame pointer based unwinder in ASan requires ARM frame setup.
-  LOCAL_ARM_MODE := arm
-  my_cflags += $(ADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS)
-  my_ldflags += $(ADDRESS_SANITIZER_CONFIG_EXTRA_LDFLAGS)
-  my_shared_libraries += $(ADDRESS_SANITIZER_CONFIG_EXTRA_SHARED_LIBRARIES)
-  my_static_libraries += $(ADDRESS_SANITIZER_CONFIG_EXTRA_STATIC_LIBRARIES)
-endif
+include $(BUILD_SYSTEM)/config_sanitizers.mk
 
 ifeq ($(strip $($(LOCAL_2ND_ARCH_VAR_PREFIX)WITHOUT_$(my_prefix)CLANG)),true)
   my_clang :=
@@ -182,17 +208,20 @@
   my_static_libraries += $(COMPILER_RT_CONFIG_EXTRA_STATIC_LIBRARIES)
 endif
 
-my_compiler_dependencies :=
-
-##################################################################
+####################################################
 ## Add FDO flags if FDO is turned on and supported
 ## Please note that we will do option filtering during FDO build.
 ## i.e. Os->O2, remove -fno-early-inline and -finline-limit.
 ##################################################################
-ifeq ($(strip $(LOCAL_FDO_SUPPORT)), true)
-  ifeq ($(strip $(LOCAL_IS_HOST_MODULE)),)
-    my_cflags += $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_FDO_CFLAGS)
-    my_ldflags += $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_FDO_LDFLAGS)
+my_fdo_build :=
+ifneq ($(filter true always, $(LOCAL_FDO_SUPPORT)),)
+  ifeq ($(BUILD_FDO_INSTRUMENT),true)
+    my_cflags += $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_FDO_INSTRUMENT_CFLAGS)
+    my_ldflags += $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_FDO_INSTRUMENT_LDFLAGS)
+    my_fdo_build := true
+  else ifneq ($(filter true,$(BUILD_FDO_OPTIMIZE))$(filter always,$(LOCAL_FDO_SUPPORT)),)
+    my_cflags += $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_FDO_OPTIMIZE_CFLAGS)
+    my_fdo_build := true
   endif
 endif
 
@@ -203,30 +232,6 @@
 my_asflags += -D__ASSEMBLY__
 
 
-##########################################################
-## Set up installed module dependency
-## We cannot compute the full path of the LOCAL_SHARED_LIBRARIES for
-## they may cusomize their install path with LOCAL_MODULE_PATH
-##########################################################
-# Get the list of INSTALLED libraries as module names.
-ifdef LOCAL_SDK_VERSION
-  installed_shared_library_module_names := \
-      $(my_shared_libraries)
-else
-  installed_shared_library_module_names := \
-      $(my_system_shared_libraries) $(my_shared_libraries)
-endif
-installed_shared_library_module_names := $(sort $(installed_shared_library_module_names))
-
-# 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 installed_shared_library_module_names
-$(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
-    $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(installed_shared_library_module_names))
-endif
-endif
-
 ###########################################################
 ## Define PRIVATE_ variables from global vars
 ###########################################################
@@ -243,11 +248,12 @@
 
 ifeq ($(my_clang),true)
 my_target_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_TARGET_GLOBAL_CFLAGS)
+my_target_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_TARGET_GLOBAL_CONLYFLAGS)
 my_target_global_cppflags += $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_TARGET_GLOBAL_CPPFLAGS)
 my_target_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_TARGET_GLOBAL_LDFLAGS)
-my_target_c_includes += $(CLANG_CONFIG_EXTRA_TARGET_C_INCLUDES)
 else
 my_target_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CFLAGS)
+my_target_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CONLYFLAGS)
 my_target_global_cppflags += $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CPPFLAGS)
 my_target_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_LDFLAGS)
 endif # my_clang
@@ -255,6 +261,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_PROJECT_INCLUDES := $(my_target_project_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_C_INCLUDES := $(my_target_c_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CFLAGS := $(my_target_global_cflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CONLYFLAGS := $(my_target_global_conlyflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CPPFLAGS := $(my_target_global_cppflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_LDFLAGS := $(my_target_global_ldflags)
 
@@ -262,11 +269,13 @@
 
 ifeq ($(my_clang),true)
 my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_CFLAGS)
+my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_CONLYFLAGS)
 my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_CPPFLAGS)
 my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_LDFLAGS)
-my_host_c_includes := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_C_INCLUDES) $(CLANG_CONFIG_EXTRA_HOST_C_INCLUDES)
+my_host_c_includes := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_C_INCLUDES)
 else
 my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CFLAGS)
+my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CONLYFLAGS)
 my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CPPFLAGS)
 my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LDFLAGS)
 my_host_c_includes := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_C_INCLUDES)
@@ -274,10 +283,40 @@
 
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_C_INCLUDES := $(my_host_c_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CFLAGS := $(my_host_global_cflags)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CONLYFLAGS := $(my_host_global_conlyflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CPPFLAGS := $(my_host_global_cppflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_LDFLAGS := $(my_host_global_ldflags)
 endif # LOCAL_IS_HOST_MODULE
 
+# To enable coverage for a given module, set LOCAL_NATIVE_COVERAGE=true and
+# build with NATIVE_COVERAGE=true in your enviornment. Note that the build
+# system is not sensitive to changes to NATIVE_COVERAGE, so you should do a
+# clean build of your module after toggling it.
+ifeq ($(NATIVE_COVERAGE),true)
+    ifeq ($(my_native_coverage),true)
+        my_cflags += --coverage -O0
+        ifeq ($(my_clang),true)
+            # b/17574078
+            # We currently don't have a prebuilt libclang_rt.profile-<ARCH>.a,
+            # which clang is hardcoded to link if --coverage is passed in the
+            # link stage.  For now we manually link libprofile_rt (which is the
+            # name it is built as from external/compiler-rt).
+            #
+            # Note that clang coverage doesn't play nicely with acov out of the
+            # box. Clang apparently generates .gcno files that aren't compatible
+            # with gcov-4.8.  This can be solved by installing gcc-4.6 and
+            # invoking lcov with `--gcov-tool /usr/bin/gcov-4.6`.
+            #
+            # http://stackoverflow.com/questions/17758126/clang-code-coverage-invalid-output
+            my_static_libraries += libprofile_rt
+        else
+            my_ldflags += --coverage
+        endif
+    endif
+else
+    my_native_coverage := false
+endif
+
 ###########################################################
 ## Define PRIVATE_ variables used by multiple module types
 ###########################################################
@@ -299,7 +338,7 @@
 endif
 
 ifeq ($(strip $(my_cc)),)
-  ifeq ($(strip $(my_clang)),true)
+  ifeq ($(my_clang),true)
     my_cc := $(CLANG)
   else
     my_cc := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)CC)
@@ -315,7 +354,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CC := $(my_cc)
 
 ifeq ($(strip $(my_cxx)),)
-  ifeq ($(strip $(my_clang)),true)
+  ifeq ($(my_clang),true)
     my_cxx := $(CLANG_CXX)
   else
     my_cxx := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)CXX)
@@ -341,7 +380,7 @@
 # Certain modules like libdl have to have symbols resolved at runtime and blow
 # up if --no-undefined is passed to the linker.
 ifeq ($(strip $(LOCAL_NO_DEFAULT_COMPILER_FLAGS)),)
-ifeq ($(strip $(LOCAL_ALLOW_UNDEFINED_SYMBOLS)),)
+ifeq ($(my_allow_undefined_symbols),)
   my_ldflags +=  $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)NO_UNDEFINED_LDFLAGS)
 endif
 endif
@@ -365,7 +404,7 @@
 # actually used (although they are usually empty).
 arm_objects_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)$(arm_objects_mode)_CFLAGS)
 normal_objects_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)$(normal_objects_mode)_CFLAGS)
-ifeq ($(strip $(my_clang)),true)
+ifeq ($(my_clang),true)
 arm_objects_cflags := $(call $(LOCAL_2ND_ARCH_VAR_PREFIX)convert-to-$(my_host)clang-flags,$(arm_objects_cflags))
 normal_objects_cflags := $(call $(LOCAL_2ND_ARCH_VAR_PREFIX)convert-to-$(my_host)clang-flags,$(normal_objects_cflags))
 endif
@@ -509,9 +548,17 @@
 my_c_includes += external/protobuf/src $(proto_generated_cc_sources_dir)
 my_cflags += -DGOOGLE_PROTOBUF_NO_RTTI
 ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),full)
-my_static_libraries += libprotobuf-cpp-2.3.0-full
+    ifdef LOCAL_SDK_VERSION
+        my_static_libraries += libprotobuf-cpp-full
+    else
+        my_shared_libraries += libprotobuf-cpp-full
+    endif
 else
-my_static_libraries += libprotobuf-cpp-2.3.0-lite
+    ifdef LOCAL_SDK_VERSION
+        my_static_libraries += libprotobuf-cpp-lite
+    else
+        my_shared_libraries += libprotobuf-cpp-lite
+    endif
 endif
 endif  # $(proto_sources) non-empty
 
@@ -535,7 +582,7 @@
 ifneq ($(strip $(y_yacc_cpps)),)
 $(y_yacc_cpps): $(intermediates)/%$(LOCAL_CPP_EXTENSION): \
     $(TOPDIR)$(LOCAL_PATH)/%.y \
-    $(lex_cpps) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+    $(lex_cpps) $(my_additional_dependencies)
 	$(call transform-y-to-cpp,$(PRIVATE_CPP_EXTENSION))
 $(yacc_headers): $(intermediates)/%.h: $(intermediates)/%$(LOCAL_CPP_EXTENSION)
 endif
@@ -543,7 +590,7 @@
 ifneq ($(strip $(yy_yacc_cpps)),)
 $(yy_yacc_cpps): $(intermediates)/%$(LOCAL_CPP_EXTENSION): \
     $(TOPDIR)$(LOCAL_PATH)/%.yy \
-    $(lex_cpps) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+    $(lex_cpps) $(my_additional_dependencies)
 	$(call transform-y-to-cpp,$(PRIVATE_CPP_EXTENSION))
 $(yacc_headers): $(intermediates)/%.h: $(intermediates)/%$(LOCAL_CPP_EXTENSION)
 endif
@@ -587,7 +634,7 @@
 $(lex_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
 $(lex_objects): $(intermediates)/%.o: \
     $(intermediates)/%$(LOCAL_CPP_EXTENSION) \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
+    $(my_additional_dependencies) \
     $(yacc_headers)
 	$(transform-$(PRIVATE_HOST)cpp-to-o)
 endif
@@ -598,16 +645,33 @@
 
 # we also do this on host modules, even though
 # it's not really arm, because there are files that are shared.
-cpp_arm_sources    := $(patsubst %$(LOCAL_CPP_EXTENSION).arm,%$(LOCAL_CPP_EXTENSION),$(filter %$(LOCAL_CPP_EXTENSION).arm,$(my_src_files)))
-cpp_arm_objects    := $(addprefix $(intermediates)/,$(cpp_arm_sources:$(LOCAL_CPP_EXTENSION)=.o))
+cpp_arm_sources := $(patsubst %$(LOCAL_CPP_EXTENSION).arm,%$(LOCAL_CPP_EXTENSION),$(filter %$(LOCAL_CPP_EXTENSION).arm,$(my_src_files)))
+dotdot_arm_sources := $(filter ../%,$(cpp_arm_sources))
+cpp_arm_sources := $(filter-out ../%,$(cpp_arm_sources))
+cpp_arm_objects := $(addprefix $(intermediates)/,$(cpp_arm_sources:$(LOCAL_CPP_EXTENSION)=.o))
 
-cpp_normal_sources := $(filter %$(LOCAL_CPP_EXTENSION),$(my_src_files))
+# For source files starting with ../, we remove all the ../ in the object file path,
+# to avoid object file escaping the intermediate directory.
+dotdot_arm_objects :=
+$(foreach s,$(dotdot_arm_sources),\
+  $(eval $(call compile-dotdot-cpp-file,$(s),\
+  $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+  dotdot_arm_objects)))
+
+dotdot_sources := $(filter ../%$(LOCAL_CPP_EXTENSION),$(my_src_files))
+dotdot_objects :=
+$(foreach s,$(dotdot_sources),\
+  $(eval $(call compile-dotdot-cpp-file,$(s),\
+    $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+    dotdot_objects)))
+
+cpp_normal_sources := $(filter-out ../%,$(filter %$(LOCAL_CPP_EXTENSION),$(my_src_files)))
 cpp_normal_objects := $(addprefix $(intermediates)/,$(cpp_normal_sources:$(LOCAL_CPP_EXTENSION)=.o))
 
-$(cpp_arm_objects):    PRIVATE_ARM_MODE := $(arm_objects_mode)
-$(cpp_arm_objects):    PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
-$(cpp_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
-$(cpp_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
+$(dotdot_arm_objects) $(cpp_arm_objects): PRIVATE_ARM_MODE := $(arm_objects_mode)
+$(dotdot_arm_objects) $(cpp_arm_objects): PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
+$(dotdot_objects) $(cpp_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
+$(dotdot_objects) $(cpp_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
 
 cpp_objects        := $(cpp_arm_objects) $(cpp_normal_objects)
 
@@ -615,12 +679,13 @@
 $(cpp_objects): $(intermediates)/%.o: \
     $(TOPDIR)$(LOCAL_PATH)/%$(LOCAL_CPP_EXTENSION) \
     $(yacc_cpps) $(proto_generated_headers) \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)cpp-to-o)
 -include $(cpp_objects:%.o=%.P)
 endif
 
+cpp_objects += $(dotdot_arm_objects) $(dotdot_objects)
+
 ###########################################################
 ## C++: Compile generated .cpp files to .o.
 ###########################################################
@@ -636,8 +701,7 @@
 $(gen_cpp_objects): $(intermediates)/%.o: \
     $(intermediates)/%$(LOCAL_CPP_EXTENSION) $(yacc_cpps) \
     $(proto_generated_headers) \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)cpp-to-o)
 -include $(gen_cpp_objects:%.o=%.P)
 endif
@@ -651,8 +715,7 @@
 
 ifneq ($(strip $(gen_S_sources)),)
 $(gen_S_objects): $(intermediates)/%.o: $(intermediates)/%.S \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)s-to-o)
 -include $(gen_S_objects:%.o=%.P)
 endif
@@ -662,8 +725,7 @@
 
 ifneq ($(strip $(gen_s_objects)),)
 $(gen_s_objects): $(intermediates)/%.o: $(intermediates)/%.s \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)s-to-o-no-deps)
 -include $(gen_s_objects:%.o=%.P)
 endif
@@ -680,27 +742,45 @@
 ## C: Compile .c files to .o.
 ###########################################################
 
-c_arm_sources    := $(patsubst %.c.arm,%.c,$(filter %.c.arm,$(my_src_files)))
-c_arm_objects    := $(addprefix $(intermediates)/,$(c_arm_sources:.c=.o))
+c_arm_sources := $(patsubst %.c.arm,%.c,$(filter %.c.arm,$(my_src_files)))
+dotdot_arm_sources := $(filter ../%,$(c_arm_sources))
+c_arm_sources := $(filter-out ../%,$(c_arm_sources))
+c_arm_objects := $(addprefix $(intermediates)/,$(c_arm_sources:.c=.o))
 
-c_normal_sources := $(filter %.c,$(my_src_files))
+# For source files starting with ../, we remove all the ../ in the object file path,
+# to avoid object file escaping the intermediate directory.
+dotdot_arm_objects :=
+$(foreach s,$(dotdot_arm_sources),\
+  $(eval $(call compile-dotdot-c-file,$(s),\
+    $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+    dotdot_arm_objects)))
+
+dotdot_sources := $(filter ../%.c, $(my_src_files))
+dotdot_objects :=
+$(foreach s, $(dotdot_sources),\
+  $(eval $(call compile-dotdot-c-file,$(s),\
+    $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+    dotdot_objects)))
+
+c_normal_sources := $(filter-out ../%,$(filter %.c,$(my_src_files)))
 c_normal_objects := $(addprefix $(intermediates)/,$(c_normal_sources:.c=.o))
 
-$(c_arm_objects):    PRIVATE_ARM_MODE := $(arm_objects_mode)
-$(c_arm_objects):    PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
-$(c_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
-$(c_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
+$(dotdot_arm_objects) $(c_arm_objects): PRIVATE_ARM_MODE := $(arm_objects_mode)
+$(dotdot_arm_objects) $(c_arm_objects): PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
+$(dotdot_objects) $(c_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
+$(dotdot_objects) $(c_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
 
 c_objects        := $(c_arm_objects) $(c_normal_objects)
 
 ifneq ($(strip $(c_objects)),)
 $(c_objects): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.c $(yacc_cpps) $(proto_generated_headers) \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)c-to-o)
 -include $(c_objects:%.o=%.P)
 endif
 
+c_objects += $(dotdot_arm_objects) $(dotdot_objects)
+
 ###########################################################
 ## C: Compile generated .c files to .o.
 ###########################################################
@@ -714,8 +794,7 @@
 $(gen_c_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
 $(gen_c_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
 $(gen_c_objects): $(intermediates)/%.o: $(intermediates)/%.c $(yacc_cpps) $(proto_generated_headers) \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)c-to-o)
 -include $(gen_c_objects:%.o=%.P)
 endif
@@ -729,8 +808,7 @@
 
 ifneq ($(strip $(objc_objects)),)
 $(objc_objects): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.m $(yacc_cpps) $(proto_generated_headers) \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)m-to-o)
 -include $(objc_objects:%.o=%.P)
 endif
@@ -740,43 +818,79 @@
 ###########################################################
 
 asm_sources_S := $(filter %.S,$(my_src_files))
+dotdot_sources := $(filter ../%,$(asm_sources_S))
+asm_sources_S := $(filter-out ../%,$(asm_sources_S))
 asm_objects_S := $(addprefix $(intermediates)/,$(asm_sources_S:.S=.o))
 
+dotdot_objects_S :=
+$(foreach s,$(dotdot_sources),\
+  $(eval $(call compile-dotdot-s-file,$(s),\
+    $(my_additional_dependencies),\
+    dotdot_objects_S)))
+
 ifneq ($(strip $(asm_objects_S)),)
 $(asm_objects_S): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.S \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)s-to-o)
 -include $(asm_objects_S:%.o=%.P)
 endif
 
 asm_sources_s := $(filter %.s,$(my_src_files))
+dotdot_sources := $(filter ../%,$(asm_sources_s))
+asm_sources_s := $(filter-out ../%,$(asm_sources_s))
 asm_objects_s := $(addprefix $(intermediates)/,$(asm_sources_s:.s=.o))
 
+dotdot_objects_s :=
+$(foreach s,$(dotdot_sources),\
+  $(eval $(call compile-dotdot-s-file-no-deps,$(s),\
+    $(my_additional_dependencies),\
+    dotdot_objects_s)))
+
 ifneq ($(strip $(asm_objects_s)),)
 $(asm_objects_s): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.s \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    | $(my_compiler_dependencies)
+    $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)s-to-o-no-deps)
--include $(asm_objects_s:%.o=%.P)
 endif
 
-asm_objects := $(asm_objects_S) $(asm_objects_s)
+asm_objects := $(dotdot_objects_S) $(dotdot_objects_s) $(asm_objects_S) $(asm_objects_s)
 
 
-# .asm for x86 needs to be compiled with yasm.
-ifeq (x86,$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+# .asm for x86/x86_64 needs to be compiled with yasm.
 asm_sources_asm := $(filter %.asm,$(my_src_files))
 ifneq ($(strip $(asm_sources_asm)),)
 asm_objects_asm := $(addprefix $(intermediates)/,$(asm_sources_asm:.asm=.o))
 $(asm_objects_asm): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.asm \
-    $(LOCAL_ADDITIONAL_DEPENDENCIES)
+    $(my_additional_dependencies)
 	$(transform-asm-to-o)
 
 asm_objects += $(asm_objects_asm)
 endif
+
+
+##########################################################
+## Set up installed module dependency
+## We cannot compute the full path of the LOCAL_SHARED_LIBRARIES for
+## they may cusomize their install path with LOCAL_MODULE_PATH
+##########################################################
+# Get the list of INSTALLED libraries as module names.
+ifdef LOCAL_SDK_VERSION
+  installed_shared_library_module_names := \
+      $(my_shared_libraries)
+else
+  installed_shared_library_module_names := \
+      $(my_shared_libraries) $(my_system_shared_libraries)
 endif
 
+# 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 installed_shared_library_module_names
+$(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
+    $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(sort $(installed_shared_library_module_names)))
+endif
+endif
+
+
 ####################################################
 ## Import includes
 ####################################################
@@ -786,11 +900,12 @@
       $(call intermediates-dir-for,SHARED_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX))/export_includes) \
     $(foreach l, $(my_static_libraries) $(my_whole_static_libraries), \
       $(call intermediates-dir-for,STATIC_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX))/export_includes))
-$(import_includes) : $(import_includes_deps)
+$(import_includes): PRIVATE_IMPORT_EXPORT_INCLUDES := $(import_includes_deps)
+$(import_includes) : $(LOCAL_MODULE_MAKEFILE) $(import_includes_deps)
 	@echo Import includes file: $@
 	$(hide) mkdir -p $(dir $@) && rm -f $@
 ifdef import_includes_deps
-	$(hide) for f in $^; do \
+	$(hide) for f in $(PRIVATE_IMPORT_EXPORT_INCLUDES); do \
 	  cat $$f >> $@; \
 	done
 else
@@ -919,30 +1034,31 @@
 ###########################################################
 
 ifeq ($(my_clang),true)
+my_cflags += $(LOCAL_CLANG_CFLAGS)
+my_conlyflags += $(LOCAL_CLANG_CONLYFLAGS)
+my_cppflags += $(LOCAL_CLANG_CPPFLAGS)
+my_asflags += $(LOCAL_CLANG_ASFLAGS)
+my_ldflags += $(LOCAL_CLANG_LDFLAGS)
+my_cflags += $(LOCAL_CLANG_CFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CLANG_CFLAGS_$(my_32_64_bit_suffix))
+my_conlyflags += $(LOCAL_CLANG_CONLYFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CLANG_CONLYFLAGS_$(my_32_64_bit_suffix))
+my_cppflags += $(LOCAL_CLANG_CPPFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CLANG_CPPFLAGS_$(my_32_64_bit_suffix))
+my_ldflags += $(LOCAL_CLANG_LDFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CLANG_LDFLAGS_$(my_32_64_bit_suffix))
+my_asflags += $(LOCAL_CLANG_ASFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CLANG_ASFLAGS_$(my_32_64_bit_suffix))
 my_cflags := $(call $(LOCAL_2ND_ARCH_VAR_PREFIX)convert-to-$(my_host)clang-flags,$(my_cflags))
 my_cppflags := $(call $(LOCAL_2ND_ARCH_VAR_PREFIX)convert-to-$(my_host)clang-flags,$(my_cppflags))
 my_asflags := $(call $(LOCAL_2ND_ARCH_VAR_PREFIX)convert-to-$(my_host)clang-flags,$(my_asflags))
 my_ldflags := $(call $(LOCAL_2ND_ARCH_VAR_PREFIX)convert-to-$(my_host)clang-flags,$(my_ldflags))
 endif
 
-ifeq ($(LOCAL_FDO_SUPPORT), true)
-  build_with_fdo := false
-  ifeq ($(BUILD_FDO_INSTRUMENT), true)
-    build_with_fdo := true
-  endif
-  ifeq ($(BUILD_FDO_OPTIMIZE), true)
-    build_with_fdo := true
-  endif
-  ifeq ($(build_with_fdo), true)
-    my_cflags := $(patsubst -Os,-O2,$(my_cflags))
-    fdo_incompatible_flags=-fno-early-inlining -finline-limit=%
-    my_cflags := $(filter-out $(fdo_incompatible_flags),$(my_cflags))
-  endif
+ifeq ($(my_fdo_build), true)
+  my_cflags := $(patsubst -Os,-O2,$(my_cflags))
+  fdo_incompatible_flags := -fno-early-inlining -finline-limit=%
+  my_cflags := $(filter-out $(fdo_incompatible_flags),$(my_cflags))
 endif
 
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_YACCFLAGS := $(LOCAL_YACCFLAGS)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_ASFLAGS := $(my_asflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CONLYFLAGS := $(LOCAL_CONLYFLAGS)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CONLYFLAGS := $(my_conlyflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CFLAGS := $(my_cflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CPPFLAGS := $(my_cppflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RTTI_FLAG := $(LOCAL_RTTI_FLAG)
@@ -950,9 +1066,8 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_C_INCLUDES := $(my_c_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_IMPORT_INCLUDES := $(import_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LDFLAGS := $(my_ldflags)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LDLIBS := $(LOCAL_LDLIBS)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LDLIBS := $(my_ldlibs)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_NO_CRT := $(strip $(LOCAL_NO_CRT) $(LOCAL_NO_CRT_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)))
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LIBCXX := $(my_libcxx)
 
 # this is really the way to get the files onto the command line instead
 # of using $^, because then LOCAL_ADDITIONAL_DEPENDENCIES doesn't work
diff --git a/core/build_id.mk b/core/build_id.mk
index f39329b..f94b224 100644
--- a/core/build_id.mk
+++ b/core/build_id.mk
@@ -18,4 +18,6 @@
 # (like "CRB01").  It must be a single word, and is
 # capitalized by convention.
 
-export BUILD_ID=LKY80
+BUILD_ID := AOSP
+
+DISPLAY_BUILD_NUMBER := true
diff --git a/core/clang/HOST_x86.mk b/core/clang/HOST_x86.mk
index 510a74d..35cfe60 100644
--- a/core/clang/HOST_x86.mk
+++ b/core/clang/HOST_x86.mk
@@ -11,6 +11,10 @@
 endif
 ifeq ($(HOST_OS),darwin)
 CLANG_CONFIG_x86_HOST_TRIPLE := i686-apple-darwin
+CLANG_CONFIG_x86_HOST_COMBO_EXTRA_ASFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_ASFLAGS)
+CLANG_CONFIG_x86_HOST_COMBO_EXTRA_CFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CFLAGS)
+CLANG_CONFIG_x86_HOST_COMBO_EXTRA_CPPFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CPPFLAGS)
+CLANG_CONFIG_x86_HOST_COMBO_EXTRA_LDFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_LDFLAGS)
 endif
 ifeq ($(HOST_OS),windows)
 CLANG_CONFIG_x86_HOST_TRIPLE := i686-pc-mingw32
@@ -30,6 +34,12 @@
   $(CLANG_CONFIG_x86_HOST_COMBO_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_x86_HOST_EXTRA_ASFLAGS)
 
+CLANG_CONFIG_x86_HOST_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_HOST_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_HOST_COMBO_EXTRA_CONLYFLAGS)
+
 CLANG_CONFIG_x86_HOST_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
   $(CLANG_CONFIG_HOST_EXTRA_CPPFLAGS) \
@@ -55,6 +65,10 @@
   $(call $(clang_2nd_arch_prefix)convert-to-host-clang-flags,$($(clang_2nd_arch_prefix)HOST_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_x86_HOST_EXTRA_CFLAGS)
 
+$(clang_2nd_arch_prefix)CLANG_HOST_GLOBAL_CONLYFLAGS := \
+  $(call $(clang_2nd_arch_prefix)convert-to-host-clang-flags,$($(clang_2nd_arch_prefix)HOST_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_x86_HOST_EXTRA_CONLYFLAGS)
+
 $(clang_2nd_arch_prefix)CLANG_HOST_GLOBAL_CPPFLAGS := \
   $(call $(clang_2nd_arch_prefix)convert-to-host-clang-flags,$($(clang_2nd_arch_prefix)HOST_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_x86_HOST_EXTRA_CPPFLAGS)
diff --git a/core/clang/HOST_x86_64.mk b/core/clang/HOST_x86_64.mk
index 6b94525..c546715 100644
--- a/core/clang/HOST_x86_64.mk
+++ b/core/clang/HOST_x86_64.mk
@@ -11,6 +11,10 @@
 endif
 ifeq ($(HOST_OS),darwin)
 CLANG_CONFIG_x86_64_HOST_TRIPLE := x86_64-apple-darwin
+CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_ASFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_ASFLAGS)
+CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_CFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CFLAGS)
+CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_CPPFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CPPFLAGS)
+CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_LDFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_LDFLAGS)
 endif
 ifeq ($(HOST_OS),windows)
 CLANG_CONFIG_x86_64_HOST_TRIPLE := x86_64-pc-mingw64
@@ -30,6 +34,12 @@
   $(CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_x86_64_HOST_EXTRA_ASFLAGS)
 
+CLANG_CONFIG_x86_64_HOST_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_HOST_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_64_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_CONLYFLAGS)
+
 CLANG_CONFIG_x86_64_HOST_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
   $(CLANG_CONFIG_HOST_EXTRA_CPPFLAGS) \
@@ -55,6 +65,10 @@
   $(call convert-to-host-clang-flags,$(HOST_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_x86_64_HOST_EXTRA_CFLAGS)
 
+CLANG_HOST_GLOBAL_CONLYFLAGS := \
+  $(call convert-to-host-clang-flags,$(HOST_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_x86_64_HOST_EXTRA_CONLYFLAGS)
+
 CLANG_HOST_GLOBAL_CPPFLAGS := \
   $(call convert-to-host-clang-flags,$(HOST_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_x86_64_HOST_EXTRA_CPPFLAGS)
diff --git a/core/clang/HOST_x86_common.mk b/core/clang/HOST_x86_common.mk
index 0241cb6..74b5a69 100644
--- a/core/clang/HOST_x86_common.mk
+++ b/core/clang/HOST_x86_common.mk
@@ -1,53 +1,51 @@
 # Shared by HOST_x86.mk and HOST_x86_64.mk.
 
 ifeq ($(HOST_OS),darwin)
-# nothing required here yet
+CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_ASFLAGS := \
+  -integrated-as
+
+CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CFLAGS := \
+  -integrated-as
 endif
 
 ifeq ($(HOST_OS),linux)
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_ASFLAGS := \
   --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
-  --sysroot=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -no-integrated-as
+  --sysroot=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/sysroot
 
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CFLAGS := \
-  --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
-  -no-integrated-as
+  --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)
 
 ifneq ($(strip $($(clang_2nd_arch_prefix)HOST_IS_64_BIT)),)
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CPPFLAGS := \
   --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
   --sysroot=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6 \
-  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/x86_64-linux \
-  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/backward \
-  -no-integrated-as
+  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.8 \
+  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.8/x86_64-linux \
+  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.8/backward
 
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_LDFLAGS := \
   --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
   --sysroot=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
   -B$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/bin \
-  -B$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6 \
-  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6 \
-  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/lib64/ \
-  -no-integrated-as
+  -B$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.8 \
+  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.8 \
+  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/lib64/
 else
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CPPFLAGS := \
   --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
   --sysroot=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6 \
-  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/x86_64-linux/32 \
-  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/backward \
-  -no-integrated-as
+  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.8 \
+  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.8/x86_64-linux/32 \
+  -isystem $($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.8/backward
 
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_LDFLAGS := \
   --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
   --sysroot=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
   -B$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/bin \
-  -B$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6/32 \
-  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6/32 \
-  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/lib32/ \
-  -no-integrated-as
+  -B$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.8/32 \
+  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.8/32 \
+  -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/lib32/
 endif
 endif  # Linux
 
diff --git a/core/clang/TARGET_arm.mk b/core/clang/TARGET_arm.mk
index 59ed41f..993755f 100644
--- a/core/clang/TARGET_arm.mk
+++ b/core/clang/TARGET_arm.mk
@@ -19,6 +19,11 @@
   -target $(CLANG_CONFIG_arm_TARGET_TRIPLE) \
   $(CLANG_CONFIG_arm_TARGET_EXTRA_ASFLAGS)
 
+CLANG_CONFIG_arm_TARGET_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_TARGET_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_arm_EXTRA_CONLYFLAGS)
+
 CLANG_CONFIG_arm_TARGET_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_CPPFLAGS) \
@@ -44,6 +49,10 @@
   $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_arm_TARGET_EXTRA_CFLAGS)
 
+$(clang_2nd_arch_prefix)CLANG_TARGET_GLOBAL_CONLYFLAGS := \
+  $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_arm_TARGET_EXTRA_CONLYFLAGS)
+
 $(clang_2nd_arch_prefix)CLANG_TARGET_GLOBAL_CPPFLAGS := \
   $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_arm_TARGET_EXTRA_CPPFLAGS)
@@ -54,4 +63,4 @@
 
 $(clang_2nd_arch_prefix)RS_TRIPLE := armv7-none-linux-gnueabi
 $(clang_2nd_arch_prefix)RS_TRIPLE_CFLAGS :=
-RS_COMPAT_TRIPLE := armv7-none-linux-gnueabi
+$(clang_2nd_arch_prefix)RS_COMPAT_TRIPLE := armv7-none-linux-gnueabi
diff --git a/core/clang/TARGET_arm64.mk b/core/clang/TARGET_arm64.mk
index 6f9e540..ba6e5f1 100644
--- a/core/clang/TARGET_arm64.mk
+++ b/core/clang/TARGET_arm64.mk
@@ -18,6 +18,11 @@
   $(CLANG_CONFIG_arm64_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_arm64_TARGET_EXTRA_ASFLAGS)
 
+CLANG_CONFIG_arm64_TARGET_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_TARGET_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_arm64_EXTRA_CONLYFLAGS)
+
 CLANG_CONFIG_arm64_TARGET_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_CPPFLAGS) \
@@ -42,6 +47,10 @@
   $(call convert-to-clang-flags,$(TARGET_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_arm64_TARGET_EXTRA_CFLAGS)
 
+CLANG_TARGET_GLOBAL_CONLYFLAGS := \
+  $(call convert-to-clang-flags,$(TARGET_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_arm64_TARGET_EXTRA_CONLYFLAGS)
+
 CLANG_TARGET_GLOBAL_CPPFLAGS := \
   $(call convert-to-clang-flags,$(TARGET_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_arm64_TARGET_EXTRA_CPPFLAGS)
diff --git a/core/clang/TARGET_mips.mk b/core/clang/TARGET_mips.mk
index 91067f5..2360181 100644
--- a/core/clang/TARGET_mips.mk
+++ b/core/clang/TARGET_mips.mk
@@ -9,6 +9,7 @@
   $(CLANG_CONFIG_EXTRA_ASFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_ASFLAGS) \
   $(CLANG_CONFIG_mips_EXTRA_ASFLAGS) \
+  -fPIC \
   -target $(CLANG_CONFIG_mips_TARGET_TRIPLE) \
   -B$(CLANG_CONFIG_mips_TARGET_TOOLCHAIN_PREFIX)
 
@@ -18,6 +19,11 @@
   $(CLANG_CONFIG_mips_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_mips_TARGET_EXTRA_ASFLAGS)
 
+CLANG_CONFIG_mips_TARGET_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_TARGET_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_mips_EXTRA_CONLYFLAGS)
+
 CLANG_CONFIG_mips_TARGET_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_CPPFLAGS) \
@@ -42,6 +48,10 @@
   $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_mips_TARGET_EXTRA_CFLAGS)
 
+$(clang_2nd_arch_prefix)CLANG_TARGET_GLOBAL_CONLYFLAGS := \
+  $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_mips_TARGET_EXTRA_CONLYFLAGS)
+
 $(clang_2nd_arch_prefix)CLANG_TARGET_GLOBAL_CPPFLAGS := \
   $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_mips_TARGET_EXTRA_CPPFLAGS)
diff --git a/core/clang/TARGET_mips64.mk b/core/clang/TARGET_mips64.mk
index ab69aed..742be4b 100644
--- a/core/clang/TARGET_mips64.mk
+++ b/core/clang/TARGET_mips64.mk
@@ -18,6 +18,11 @@
   $(CLANG_CONFIG_mips64_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_mips64_TARGET_EXTRA_ASFLAGS)
 
+CLANG_CONFIG_mips64_TARGET_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_TARGET_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_mips64_EXTRA_CONLYFLAGS)
+
 CLANG_CONFIG_mips64_TARGET_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_CPPFLAGS) \
@@ -42,6 +47,10 @@
   $(call convert-to-clang-flags,$(TARGET_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_mips64_TARGET_EXTRA_CFLAGS)
 
+CLANG_TARGET_GLOBAL_CONLYFLAGS := \
+  $(call convert-to-clang-flags,$(TARGET_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_mips64_TARGET_EXTRA_CONLYFLAGS)
+
 CLANG_TARGET_GLOBAL_CPPFLAGS := \
   $(call convert-to-clang-flags,$(TARGET_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_mips64_TARGET_EXTRA_CPPFLAGS)
diff --git a/core/clang/TARGET_x86.mk b/core/clang/TARGET_x86.mk
index 60ee06f..3ba34ae 100644
--- a/core/clang/TARGET_x86.mk
+++ b/core/clang/TARGET_x86.mk
@@ -18,7 +18,20 @@
   $(CLANG_CONFIG_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_x86_EXTRA_CFLAGS) \
-  $(CLANG_CONFIG_x86_TARGET_EXTRA_ASFLAGS)
+  $(CLANG_CONFIG_x86_TARGET_EXTRA_ASFLAGS) \
+  -fno-optimize-sibling-calls \
+  -mstackrealign
+
+# http://llvm.org/bugs/show_bug.cgi?id=15086,
+# llvm tail call optimization is wrong for x86.
+# -mstackrealign is needed to realign stack in native code
+# that could be called from JNI, so that movaps instruction
+# will work on assumed stack aligned local variables.
+
+CLANG_CONFIG_x86_TARGET_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_TARGET_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_EXTRA_CONLYFLAGS)
 
 CLANG_CONFIG_x86_TARGET_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
@@ -44,6 +57,10 @@
   $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_x86_TARGET_EXTRA_CFLAGS)
 
+$(clang_2nd_arch_prefix)CLANG_TARGET_GLOBAL_CONLYFLAGS := \
+  $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_x86_TARGET_EXTRA_CONLYFLAGS)
+
 $(clang_2nd_arch_prefix)CLANG_TARGET_GLOBAL_CPPFLAGS := \
   $(call $(clang_2nd_arch_prefix)convert-to-clang-flags,$($(clang_2nd_arch_prefix)TARGET_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_x86_TARGET_EXTRA_CPPFLAGS)
@@ -54,4 +71,4 @@
 
 $(clang_2nd_arch_prefix)RS_TRIPLE := armv7-none-linux-gnueabi
 $(clang_2nd_arch_prefix)RS_TRIPLE_CFLAGS := -D__i386__
-RS_COMPAT_TRIPLE := i686-linux-android
+$(clang_2nd_arch_prefix)RS_COMPAT_TRIPLE := i686-linux-android
diff --git a/core/clang/TARGET_x86_64.mk b/core/clang/TARGET_x86_64.mk
index 5561e42..9f8e8b0 100644
--- a/core/clang/TARGET_x86_64.mk
+++ b/core/clang/TARGET_x86_64.mk
@@ -18,6 +18,11 @@
   $(CLANG_CONFIG_x86_64_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_x86_64_TARGET_EXTRA_ASFLAGS)
 
+CLANG_CONFIG_x86_64_TARGET_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_TARGET_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_64_EXTRA_CONLYFLAGS)
+
 CLANG_CONFIG_x86_64_TARGET_EXTRA_CPPFLAGS := \
   $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_CPPFLAGS) \
@@ -42,6 +47,10 @@
   $(call convert-to-clang-flags,$(TARGET_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_x86_64_TARGET_EXTRA_CFLAGS)
 
+CLANG_TARGET_GLOBAL_CONLYFLAGS := \
+  $(call convert-to-clang-flags,$(TARGET_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_x86_64_TARGET_EXTRA_CONLYFLAGS)
+
 CLANG_TARGET_GLOBAL_CPPFLAGS := \
   $(call convert-to-clang-flags,$(TARGET_GLOBAL_CPPFLAGS)) \
   $(CLANG_CONFIG_x86_64_TARGET_EXTRA_CPPFLAGS)
diff --git a/core/clang/arm.mk b/core/clang/arm.mk
index 22c7397..f76a182 100644
--- a/core/clang/arm.mk
+++ b/core/clang/arm.mk
@@ -1,16 +1,23 @@
 # Clang flags for arm arch, target or host.
 
-CLANG_CONFIG_arm_EXTRA_ASFLAGS := \
-  -no-integrated-as
+CLANG_CONFIG_arm_EXTRA_ASFLAGS :=
 
-CLANG_CONFIG_arm_EXTRA_CFLAGS := \
-  -no-integrated-as
+CLANG_CONFIG_arm_EXTRA_CFLAGS :=
 
-CLANG_CONFIG_arm_EXTRA_CPPFLAGS := \
-  -no-integrated-as
+ifneq (,$(filter krait,$(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT)))
+  # Android's clang support's krait as a CPU whereas GCC doesn't. Specify
+  # -mcpu here rather than the more normal core/combo/arch/arm/armv7-a-neon.mk.
+  CLANG_CONFIG_arm_EXTRA_CFLAGS += -mcpu=krait
+endif
 
-CLANG_CONFIG_arm_EXTRA_LDFLAGS := \
-  -no-integrated-as
+ifeq ($(HOST_OS),darwin)
+  # Darwin is really bad at dealing with idiv/sdiv. Don't use krait on Darwin.
+  CLANG_CONFIG_arm_EXTRA_CFLAGS += -mcpu=cortex-a9
+endif
+
+CLANG_CONFIG_arm_EXTRA_CPPFLAGS :=
+
+CLANG_CONFIG_arm_EXTRA_LDFLAGS :=
 
 # Include common unknown flags
 CLANG_CONFIG_arm_UNKNOWN_CFLAGS := \
@@ -19,9 +26,15 @@
   -fgcse-after-reload \
   -frerun-cse-after-loop \
   -frename-registers \
-  -fno-builtin-sin \
-  -fno-strict-volatile-bitfields \
   -fno-align-jumps \
+  -fno-builtin-sin \
+  -fno-caller-saves \
+  -fno-early-inlining \
+  -fno-move-loop-invariants \
+  -fno-partial-inlining \
+  -fno-strict-volatile-bitfields \
+  -fno-tree-copy-prop \
+  -fno-tree-loop-optimize \
   -Wa,--noexecstack
 
 define subst-clang-incompatible-arm-flags
diff --git a/core/clang/arm64.mk b/core/clang/arm64.mk
index 9fb3670..ab395b3 100644
--- a/core/clang/arm64.mk
+++ b/core/clang/arm64.mk
@@ -1,10 +1,8 @@
 # Clang flags for arm64 arch, target or host.
 
-CLANG_CONFIG_arm64_EXTRA_ASFLAGS := \
-  -no-integrated-as
+CLANG_CONFIG_arm64_EXTRA_ASFLAGS :=
 
-CLANG_CONFIG_arm64_EXTRA_CFLAGS := \
-  -no-integrated-as
+CLANG_CONFIG_arm64_EXTRA_CFLAGS :=
 
 CLANG_CONFIG_arm64_EXTRA_LDFLAGS :=
 
diff --git a/core/clang/config.mk b/core/clang/config.mk
index 5b2aea5..72a880f 100644
--- a/core/clang/config.mk
+++ b/core/clang/config.mk
@@ -6,8 +6,8 @@
 WITHOUT_HOST_CLANG := true
 endif
 
-LLVM_PREBUILTS_PATH := prebuilts/clang/$(BUILD_OS)-x86/host/3.5/bin
-LLVM_PREBUILTS_HEADER_PATH := prebuilts/clang/$(BUILD_OS)-x86/host/3.5/lib/clang/3.5/include/
+LLVM_PREBUILTS_VERSION := 3.6
+LLVM_PREBUILTS_PATH := prebuilts/clang/$(BUILD_OS)-x86/host/$(LLVM_PREBUILTS_VERSION)/bin
 
 CLANG := $(LLVM_PREBUILTS_PATH)/clang$(BUILD_EXECUTABLE_SUFFIX)
 CLANG_CXX := $(LLVM_PREBUILTS_PATH)/clang++$(BUILD_EXECUTABLE_SUFFIX)
@@ -32,6 +32,7 @@
 # Clang flags for all host or target rules
 CLANG_CONFIG_EXTRA_ASFLAGS :=
 CLANG_CONFIG_EXTRA_CFLAGS :=
+CLANG_CONFIG_EXTRA_CONLYFLAGS := -std=gnu99
 CLANG_CONFIG_EXTRA_CPPFLAGS :=
 CLANG_CONFIG_EXTRA_LDFLAGS :=
 
@@ -42,17 +43,33 @@
 CLANG_CONFIG_EXTRA_CFLAGS += \
   -Werror=int-conversion
 
+# Workaround for ccache with clang.
+# See http://petereisentraut.blogspot.com/2011/05/ccache-and-clang.html.
+CLANG_CONFIG_EXTRA_CFLAGS += \
+  -Wno-unused-command-line-argument
+
+# Disable -Winconsistent-missing-override until we can clean up the existing
+# codebase for it.
+CLANG_CONFIG_EXTRA_CPPFLAGS += \
+  -Wno-inconsistent-missing-override
+
 CLANG_CONFIG_UNKNOWN_CFLAGS := \
-  -funswitch-loops \
-  -fno-tree-sra \
+  -finline-functions \
   -finline-limit=64 \
+  -fno-canonical-system-headers \
+  -fno-tree-sra \
+  -fprefetch-loop-arrays \
+  -funswitch-loops \
+  -Wmaybe-uninitialized \
+  -Wno-error=maybe-uninitialized \
+  -Wno-free-nonheap-object \
+  -Wno-literal-suffix \
+  -Wno-maybe-uninitialized \
+  -Wno-old-style-declaration \
   -Wno-psabi \
   -Wno-unused-but-set-variable \
   -Wno-unused-but-set-parameter \
-  -Wmaybe-uninitialized \
-  -Wno-maybe-uninitialized \
-  -Wno-error=maybe-uninitialized \
-  -fno-canonical-system-headers
+  -Wno-unused-local-typedefs
 
 # Clang flags for all host rules
 CLANG_CONFIG_HOST_EXTRA_ASFLAGS :=
@@ -86,18 +103,19 @@
 include $(BUILD_SYSTEM)/clang/TARGET_$(TARGET_2ND_ARCH).mk
 endif
 
-
-# Clang compiler-specific libc headers
-CLANG_CONFIG_EXTRA_HOST_C_INCLUDES := $(LLVM_PREBUILTS_HEADER_PATH)
-CLANG_CONFIG_EXTRA_TARGET_C_INCLUDES := $(LLVM_PREBUILTS_HEADER_PATH) $(TARGET_OUT_HEADERS)/clang
-
 # Address sanitizer clang config
 ADDRESS_SANITIZER_RUNTIME_LIBRARY := libclang_rt.asan_$(TARGET_ARCH)_android
 ADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS := -fsanitize=address -fno-omit-frame-pointer
 ADDRESS_SANITIZER_CONFIG_EXTRA_LDFLAGS := -Wl,-u,__asan_preinit
+
 ADDRESS_SANITIZER_CONFIG_EXTRA_SHARED_LIBRARIES := libdl $(ADDRESS_SANITIZER_RUNTIME_LIBRARY)
 ADDRESS_SANITIZER_CONFIG_EXTRA_STATIC_LIBRARIES := libasan
 
 # This allows us to use the superset of functionality that compiler-rt
 # provides to Clang (for supporting features like -ftrapv).
 COMPILER_RT_CONFIG_EXTRA_STATIC_LIBRARIES := libcompiler_rt-extras
+
+ifeq ($(HOST_PREFER_32_BIT),true)
+# We don't have 32-bit prebuilt libLLVM/libclang, so force to build them from source.
+FORCE_BUILD_LLVM_COMPONENTS := true
+endif
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index d5a5f03..ed7771d 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -20,6 +20,7 @@
 LOCAL_MODULE_CLASS:=
 LOCAL_MODULE_SUFFIX:=
 LOCAL_PACKAGE_NAME:=
+LOCAL_PAGE_ALIGN_JNI_SHARED_LIBRARIES:=
 LOCAL_OVERRIDES_PACKAGES:=
 LOCAL_EXPORT_PACKAGE_RESOURCES:=
 LOCAL_MANIFEST_PACKAGE_NAME:=
@@ -47,11 +48,16 @@
 LOCAL_ASFLAGS:=
 LOCAL_CFLAGS:=
 LOCAL_CPPFLAGS:=
+LOCAL_CLANG_ASFLAGS:=
+LOCAL_CLANG_CFLAGS:=
+LOCAL_CLANG_CONLYFLAGS:=
+LOCAL_CLANG_CPPFLAGS:=
 LOCAL_CONLYFLAGS:=
 LOCAL_RTTI_FLAG:=
 LOCAL_C_INCLUDES:=
 LOCAL_EXPORT_C_INCLUDE_DIRS:=
 LOCAL_LDFLAGS:=
+LOCAL_CLANG_LDFLAGS:=
 LOCAL_LDLIBS:=
 LOCAL_AAPT_FLAGS:=
 LOCAL_AAPT_INCLUDE_ALL_RESOURCES:=
@@ -90,6 +96,7 @@
 LOCAL_STRIP_MODULE:=
 LOCAL_JNI_SHARED_LIBRARIES:=
 LOCAL_JNI_SHARED_LIBRARIES_ABI:=
+LOCAL_JNI_SHARED_LIBRARIES_ZIP_OPTIONS:=
 LOCAL_PREBUILT_JNI_LIBS:=
 LOCAL_JAR_MANIFEST:=
 LOCAL_INSTRUMENTATION_FOR:=
@@ -145,8 +152,10 @@
 LOCAL_SOURCE_FILES_ALL_GENERATED:= # '',true
 # Don't delete the META_INF dir when merging static Java libraries.
 LOCAL_DONT_DELETE_JAR_META_INF:=
+LOCAL_DONT_DELETE_JAR_DIRS:=
 LOCAL_ADDITIONAL_CERTIFICATES:=
 LOCAL_PREBUILT_MODULE_FILE:=
+LOCAL_POST_LINK_CMD:=
 LOCAL_POST_INSTALL_CMD:=
 LOCAL_DIST_BUNDLED_BINARIES:=
 LOCAL_HAL_STATIC_LIBRARIES:=
@@ -160,17 +169,24 @@
 LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH:=
 LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH_WARN:=
 LOCAL_MODULE_HOST_ARCH:=
+LOCAL_NO_FPIE :=
+LOCAL_CXX_STL := default
+LOCAL_NATIVE_COVERAGE :=
 LOCAL_DPI_VARIANTS:=
 LOCAL_DPI_FILE_STEM:=
 
 # arch specific variables
 LOCAL_SRC_FILES_$(TARGET_ARCH):=
 LOCAL_CFLAGS_$(TARGET_ARCH):=
+LOCAL_CLANG_CFLAGS_$(TARGET_ARCH):=
 LOCAL_CPPFLAGS_$(TARGET_ARCH):=
+LOCAL_CLANG_CPPFLAGS_$(TARGET_ARCH):=
 LOCAL_C_INCLUDES_$(TARGET_ARCH):=
 LOCAL_ASFLAGS_$(TARGET_ARCH):=
+LOCAL_CLANG_ASFLAGS_$(TARGET_ARCH):=
 LOCAL_NO_CRT_$(TARGET_ARCH):=
 LOCAL_LDFLAGS_$(TARGET_ARCH):=
+LOCAL_CLANG_LDFLAGS_$(TARGET_ARCH):=
 LOCAL_SHARED_LIBRARIES_$(TARGET_ARCH):=
 LOCAL_STATIC_LIBRARIES_$(TARGET_ARCH):=
 LOCAL_WHOLE_STATIC_LIBRARIES_$(TARGET_ARCH):=
@@ -181,11 +197,15 @@
 ifdef TARGET_2ND_ARCH
 LOCAL_SRC_FILES_$(TARGET_2ND_ARCH):=
 LOCAL_CFLAGS_$(TARGET_2ND_ARCH):=
+LOCAL_CLANG_CFLAGS_$(TARGET_2ND_ARCH):=
 LOCAL_CPPFLAGS_$(TARGET_2ND_ARCH):=
+LOCAL_CLANG_CPPFLAGS_$(TARGET_2ND_ARCH):=
 LOCAL_C_INCLUDES_$(TARGET_2ND_ARCH):=
 LOCAL_ASFLAGS_$(TARGET_2ND_ARCH):=
+LOCAL_CLANG_ASFLAGS_$(TARGET_2ND_ARCH):=
 LOCAL_NO_CRT_$(TARGET_2ND_ARCH):=
 LOCAL_LDFLAGS_$(TARGET_2ND_ARCH):=
+LOCAL_CLANG_LDFLAGS_$(TARGET_2ND_ARCH):=
 LOCAL_SHARED_LIBRARIES_$(TARGET_2ND_ARCH):=
 LOCAL_STATIC_LIBRARIES_$(TARGET_2ND_ARCH):=
 LOCAL_WHOLE_STATIC_LIBRARIES_$(TARGET_2ND_ARCH):=
@@ -196,11 +216,15 @@
 endif
 LOCAL_SRC_FILES_$(HOST_ARCH):=
 LOCAL_CFLAGS_$(HOST_ARCH):=
+LOCAL_CLANG_CFLAGS_$(HOST_ARCH):=
 LOCAL_CPPFLAGS_$(HOST_ARCH):=
+LOCAL_CLANG_CPPFLAGS_$(HOST_ARCH):=
 LOCAL_C_INCLUDES_$(HOST_ARCH):=
 LOCAL_ASFLAGS_$(HOST_ARCH):=
+LOCAL_CLANG_ASFLAGS_$(HOST_ARCH):=
 LOCAL_NO_CRT_$(HOST_ARCH):=
 LOCAL_LDFLAGS_$(HOST_ARCH):=
+LOCAL_CLANG_LDFLAGS_$(HOST_ARCH):=
 LOCAL_SHARED_LIBRARIES_$(HOST_ARCH):=
 LOCAL_STATIC_LIBRARIES_$(HOST_ARCH):=
 LOCAL_WHOLE_STATIC_LIBRARIES_$(HOST_ARCH):=
@@ -210,11 +234,15 @@
 ifdef HOST_2ND_ARCH
 LOCAL_SRC_FILES_$(HOST_2ND_ARCH):=
 LOCAL_CFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_CLANG_CFLAGS_$(HOST_2ND_ARCH):=
 LOCAL_CPPFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_CLANG_CPPFLAGS_$(HOST_2ND_ARCH):=
 LOCAL_C_INCLUDES_$(HOST_2ND_ARCH):=
 LOCAL_ASFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_CLANG_ASFLAGS_$(HOST_2ND_ARCH):=
 LOCAL_NO_CRT_$(HOST_2ND_ARCH):=
 LOCAL_LDFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_CLANG_LDFLAGS_$(HOST_2ND_ARCH):=
 LOCAL_SHARED_LIBRARIES_$(HOST_2ND_ARCH):=
 LOCAL_STATIC_LIBRARIES_$(HOST_2ND_ARCH):=
 LOCAL_WHOLE_STATIC_LIBRARIES_$(HOST_2ND_ARCH):=
@@ -241,6 +269,14 @@
 LOCAL_LDFLAGS_64:=
 LOCAL_ASFLAGS_32:=
 LOCAL_ASFLAGS_64:=
+LOCAL_CLANG_CFLAGS_32:=
+LOCAL_CLANG_CFLAGS_64:=
+LOCAL_CLANG_CPPFLAGS_32:=
+LOCAL_CLANG_CPPFLAGS_64:=
+LOCAL_CLANG_LDFLAGS_32:=
+LOCAL_CLANG_LDFLAGS_64:=
+LOCAL_CLANG_ASFLAGS_32:=
+LOCAL_CLANG_ASFLAGS_64:=
 LOCAL_C_INCLUDES_32:=
 LOCAL_C_INCLUDES_64:=
 LOCAL_MODULE_PATH_32:=
diff --git a/core/combo/HOST_darwin-x86.mk b/core/combo/HOST_darwin-x86.mk
index ec37993..7fa48ff 100644
--- a/core/combo/HOST_darwin-x86.mk
+++ b/core/combo/HOST_darwin-x86.mk
@@ -33,19 +33,8 @@
 
 $(combo_2nd_arch_prefix)HOST_TOOLCHAIN_ROOT := prebuilts/gcc/darwin-x86/host/i686-apple-darwin-4.2.1
 $(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_ROOT)/bin/i686-apple-darwin$(gcc_darwin_version)
-# Don't do anything if the toolchain is not there
-ifneq (,$(strip $(wildcard $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)-gcc)))
 $(combo_2nd_arch_prefix)HOST_CC  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)-gcc
 $(combo_2nd_arch_prefix)HOST_CXX := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)-g++
-ifneq ($(filter 10.8 10.9, $(mac_sdk_version)),)
-# Mac SDK 10.8+ no longer has stdarg.h, etc
-host_toolchain_header := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_ROOT)/lib/gcc/i686-apple-darwin$(gcc_darwin_version)/4.2.1/include
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -isystem $(host_toolchain_header)
-endif
-else
-$(combo_2nd_arch_prefix)HOST_CC := gcc
-$(combo_2nd_arch_prefix)HOST_CXX := g++
-endif # $(HOST_TOOLCHAIN_PREFIX)-gcc exists
 
 # gcc location for clang; to be updated when clang is updated
 # HOST_TOOLCHAIN_ROOT is a Darwin-specific define
@@ -54,6 +43,7 @@
 $(combo_2nd_arch_prefix)HOST_AR := $(AR)
 
 $(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -isysroot $(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version) -DMACOSX_DEPLOYMENT_TARGET=$(mac_sdk_version)
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CPPFLAGS += -isystem $(mac_sdk_path)/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
 $(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -isysroot $(mac_sdk_root) -Wl,-syslibroot,$(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version)
 
 $(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -fPIC -funwind-tables
diff --git a/core/combo/HOST_darwin-x86_64.mk b/core/combo/HOST_darwin-x86_64.mk
index a776a69..c06933d 100644
--- a/core/combo/HOST_darwin-x86_64.mk
+++ b/core/combo/HOST_darwin-x86_64.mk
@@ -33,19 +33,8 @@
 
 HOST_TOOLCHAIN_ROOT := prebuilts/gcc/darwin-x86/host/i686-apple-darwin-4.2.1
 HOST_TOOLCHAIN_PREFIX := $(HOST_TOOLCHAIN_ROOT)/bin/i686-apple-darwin$(gcc_darwin_version)
-# Don't do anything if the toolchain is not there
-ifneq (,$(strip $(wildcard $(HOST_TOOLCHAIN_PREFIX)-gcc)))
 HOST_CC  := $(HOST_TOOLCHAIN_PREFIX)-gcc
 HOST_CXX := $(HOST_TOOLCHAIN_PREFIX)-g++
-ifneq ($(filter 10.8 10.9, $(mac_sdk_version)),)
-# Mac SDK 10.8+ no longer has stdarg.h, etc
-host_toolchain_header := $(HOST_TOOLCHAIN_ROOT)/lib/gcc/i686-apple-darwin$(gcc_darwin_version)/4.2.1/include
-HOST_GLOBAL_CFLAGS += -isystem $(host_toolchain_header)
-endif
-else
-HOST_CC := gcc
-HOST_CXX := g++
-endif # $(HOST_TOOLCHAIN_PREFIX)-gcc exists
 
 # gcc location for clang; to be updated when clang is updated
 # HOST_TOOLCHAIN_ROOT is a Darwin-specific define
@@ -54,6 +43,7 @@
 HOST_AR := $(AR)
 
 HOST_GLOBAL_CFLAGS += -isysroot $(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version) -DMACOSX_DEPLOYMENT_TARGET=$(mac_sdk_version)
+HOST_GLOBAL_CPPFLAGS += -isystem $(mac_sdk_path)/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
 HOST_GLOBAL_LDFLAGS += -isysroot $(mac_sdk_root) -Wl,-syslibroot,$(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version)
 
 HOST_GLOBAL_CFLAGS += -fPIC -funwind-tables
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index 3ca7443..93a1287 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -18,20 +18,17 @@
 # Included by combo/select.mk
 
 ifeq ($(strip $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)),)
-$(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.6/bin/x86_64-linux-
+$(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8/bin/x86_64-linux-
 endif
-# Don't do anything if the toolchain is not there
-ifneq (,$(strip $(wildcard $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)gcc)))
 $(combo_2nd_arch_prefix)HOST_CC  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)gcc
 $(combo_2nd_arch_prefix)HOST_CXX := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)g++
 $(combo_2nd_arch_prefix)HOST_AR  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)ar
-endif # $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)gcc exists
 
 # gcc location for clang; to be updated when clang is updated
-$(combo_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.6/
+$(combo_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8/
 
 # We expect SSE3 floating point math.
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -mstackrealign -msse3 -mfpmath=sse -m32 -Wa,--noexecstack -march=prescott
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -msse3 -mfpmath=sse -m32 -Wa,--noexecstack -march=prescott
 $(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -m32 -Wl,-z,noexecstack
 
 ifneq ($(strip $(BUILD_HOST_static)),)
@@ -43,7 +40,7 @@
   -no-canonical-prefixes \
   -include $(call select-android-config-h,linux-x86)
 
-# Disable new longjmp in glibc 2.11 and later. See bug 2967937.
+# Disable new longjmp in glibc 2.11 and later. See bug 2967937. Same for 2.15?
 $(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0
 
 # Workaround differences in inttypes.h between host and target.
diff --git a/core/combo/HOST_linux-x86_64.mk b/core/combo/HOST_linux-x86_64.mk
index 53a3ae8..3685712 100644
--- a/core/combo/HOST_linux-x86_64.mk
+++ b/core/combo/HOST_linux-x86_64.mk
@@ -18,17 +18,14 @@
 # Included by combo/select.mk
 
 ifeq ($(strip $(HOST_TOOLCHAIN_PREFIX)),)
-HOST_TOOLCHAIN_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.6/bin/x86_64-linux-
+HOST_TOOLCHAIN_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8/bin/x86_64-linux-
 endif
-# Don't do anything if the toolchain is not there
-ifneq (,$(strip $(wildcard $(HOST_TOOLCHAIN_PREFIX)gcc)))
 HOST_CC  := $(HOST_TOOLCHAIN_PREFIX)gcc
 HOST_CXX := $(HOST_TOOLCHAIN_PREFIX)g++
 HOST_AR  := $(HOST_TOOLCHAIN_PREFIX)ar
-endif # $(HOST_TOOLCHAIN_PREFIX)gcc exists
 
 # gcc location for clang; to be updated when clang is updated
-HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.6/
+HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8/
 
 HOST_GLOBAL_CFLAGS += -m64 -Wa,--noexecstack
 HOST_GLOBAL_LDFLAGS += -m64 -Wl,-z,noexecstack
@@ -43,7 +40,7 @@
   -no-canonical-prefixes \
   -include $(call select-android-config-h,linux-x86)
 
-# Disable new longjmp in glibc 2.11 and later. See bug 2967937.
+# Disable new longjmp in glibc 2.11 and later. See bug 2967937. Same for 2.15?
 HOST_GLOBAL_CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0
 
 # Workaround differences in inttypes.h between host and target.
diff --git a/core/combo/HOST_windows-x86.mk b/core/combo/HOST_windows-x86.mk
index 00e1974..b71ac16 100644
--- a/core/combo/HOST_windows-x86.mk
+++ b/core/combo/HOST_windows-x86.mk
@@ -24,7 +24,7 @@
 
 # Settings to use MinGW has a cross-compiler under Linux
 ifneq ($(findstring Linux,$(UNAME)),)
-ifneq ($(strip $(USE_MINGW)),)
+ifdef USE_MINGW
 HOST_ACP_UNAVAILABLE := true
 TOOLS_EXE_SUFFIX :=
 $(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -DUSE_MINGW -DWIN32_LEAN_AND_MEAN
diff --git a/core/combo/HOST_windows-x86_64.mk b/core/combo/HOST_windows-x86_64.mk
index c77d82c..bd392ea 100644
--- a/core/combo/HOST_windows-x86_64.mk
+++ b/core/combo/HOST_windows-x86_64.mk
@@ -24,7 +24,7 @@
 
 # Settings to use MinGW has a cross-compiler under Linux
 ifneq ($(findstring Linux,$(UNAME)),)
-ifneq ($(strip $(USE_MINGW)),)
+ifdef USE_MINGW
 HOST_ACP_UNAVAILABLE := true
 TOOLS_EXE_SUFFIX :=
 HOST_GLOBAL_CFLAGS += -DUSE_MINGW
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index df81cd5..8059b2a 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -35,10 +35,10 @@
 endif
 
 # Decouple NDK library selection with platform compiler version
-$(combo_2nd_arch_prefix)TARGET_NDK_GCC_VERSION := 4.8
+$(combo_2nd_arch_prefix)TARGET_NDK_GCC_VERSION := 4.9
 
 ifeq ($(strip $(TARGET_GCC_VERSION_EXP)),)
-$(combo_2nd_arch_prefix)TARGET_GCC_VERSION := 4.8
+$(combo_2nd_arch_prefix)TARGET_GCC_VERSION := 4.9
 else
 $(combo_2nd_arch_prefix)TARGET_GCC_VERSION := $(TARGET_GCC_VERSION_EXP)
 endif
@@ -114,7 +114,7 @@
 # "-Wall -Werror" due to a commom idiom "ALOGV(mesg)" where ALOGV is turned
 # into no-op in some builds while mesg is defined earlier. So we explicitly
 # disable "-Wunused-but-set-variable" here.
-ifneq ($(filter 4.6 4.6.% 4.7 4.7.% 4.8, $($(combo_2nd_arch_prefix)TARGET_GCC_VERSION)),)
+ifneq ($(filter 4.6 4.6.% 4.7 4.7.% 4.8 4.9, $($(combo_2nd_arch_prefix)TARGET_GCC_VERSION)),)
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += -fno-builtin-sin \
 			-fno-strict-volatile-bitfields
 endif
@@ -133,9 +133,11 @@
 			-Wl,-z,noexecstack \
 			-Wl,-z,relro \
 			-Wl,-z,now \
+			-Wl,--build-id=md5 \
 			-Wl,--warn-shared-textrel \
 			-Wl,--fatal-warnings \
 			-Wl,--icf=safe \
+			-Wl,--hash-style=gnu \
 			$(arch_variant_ldflags)
 
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += -mthumb-interwork
@@ -153,7 +155,6 @@
 
 libc_root := bionic/libc
 libm_root := bionic/libm
-libstdc++_root := bionic/libstdc++
 
 
 ## on some hosts, the target cross-compiler is not available so do not run this command
@@ -165,6 +166,8 @@
         $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) -print-libgcc-file-name)
 $(combo_2nd_arch_prefix)TARGET_LIBATOMIC := $(shell $($(combo_2nd_arch_prefix)TARGET_CC) \
         $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) -print-file-name=libatomic.a)
+$(combo_2nd_arch_prefix)TARGET_LIBGCOV := $(shell $($(combo_2nd_arch_prefix)TARGET_CC) \
+        $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) -print-file-name=libgcov.a)
 endif
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
@@ -174,7 +177,6 @@
 $(combo_2nd_arch_prefix)TARGET_C_INCLUDES := \
 	$(libc_root)/arch-arm/include \
 	$(libc_root)/include \
-	$(libstdc++_root)/include \
 	$(KERNEL_HEADERS) \
 	$(libm_root)/include \
 	$(libm_root)/include/arm \
@@ -188,79 +190,6 @@
 
 $(combo_2nd_arch_prefix)TARGET_STRIP_MODULE:=true
 
-$(combo_2nd_arch_prefix)TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libstdc++ libm
+$(combo_2nd_arch_prefix)TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libm
 
-$(combo_2nd_arch_prefix)TARGET_CUSTOM_LD_COMMAND := true
-
-define $(combo_2nd_arch_prefix)transform-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
-	-nostdlib -Wl,-soname,$(notdir $@) \
-	-Wl,--gc-sections \
-	$(if $(filter true,$(PRIVATE_CLANG)),-shared,-Wl,-shared) \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define $(combo_2nd_arch_prefix)transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bdynamic -pie \
-	-Wl,-dynamic-linker,/system/bin/linker \
-	-Wl,--gc-sections \
-	-Wl,-z,nocopyreloc \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define $(combo_2nd_arch_prefix)transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bstatic \
-	-Wl,--gc-sections \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_STATIC_O)) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(call normalize-target-libraries,$(filter-out %libc_nomalloc.a,$(filter-out %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES)))) \
-	-Wl,--start-group \
-	$(call normalize-target-libraries,$(filter %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(call normalize-target-libraries,$(filter %libc_nomalloc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	-Wl,--end-group \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
-endef
+$(combo_2nd_arch_prefix)TARGET_LINKER := /system/bin/linker
diff --git a/core/combo/TARGET_linux-arm64.mk b/core/combo/TARGET_linux-arm64.mk
index 07d3984..07a1de9 100644
--- a/core/combo/TARGET_linux-arm64.mk
+++ b/core/combo/TARGET_linux-arm64.mk
@@ -91,6 +91,7 @@
 TARGET_GLOBAL_CFLAGS += \
     -Werror=pointer-to-int-cast \
     -Werror=int-to-pointer-cast \
+    -Werror=implicit-function-declaration \
 
 TARGET_GLOBAL_CFLAGS += -fno-strict-volatile-bitfields
 
@@ -108,11 +109,16 @@
 			-Wl,-z,noexecstack \
 			-Wl,-z,relro \
 			-Wl,-z,now \
+			-Wl,--build-id=md5 \
 			-Wl,--warn-shared-textrel \
 			-Wl,--fatal-warnings \
 			-Wl,-maarch64linux \
+			-Wl,--hash-style=gnu \
 			$(arch_variant_ldflags)
 
+# Disable transitive dependency library symbol resolving.
+TARGET_GLOBAL_LDFLAGS += -Wl,--allow-shlib-undefined
+
 TARGET_GLOBAL_CPPFLAGS += -fvisibility-inlines-hidden
 
 # More flags/options can be added here
@@ -126,12 +132,13 @@
 
 libc_root := bionic/libc
 libm_root := bionic/libm
-libstdc++_root := bionic/libstdc++
 
 TARGET_LIBGCC := $(shell $(TARGET_CC) $(TARGET_GLOBAL_CFLAGS) \
 	-print-libgcc-file-name)
 TARGET_LIBATOMIC := $(shell $(TARGET_CC) $(TARGET_GLOBAL_CFLAGS) \
 	-print-file-name=libatomic.a)
+TARGET_LIBGCOV := $(shell $(TARGET_CC) $(TARGET_GLOBAL_CFLAGS) \
+	-print-file-name=libgcov.a)
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-$(TARGET_ARCH)
@@ -140,7 +147,6 @@
 TARGET_C_INCLUDES := \
 	$(libc_root)/arch-arm64/include \
 	$(libc_root)/include \
-	$(libstdc++_root)/include \
 	$(KERNEL_HEADERS) \
 	$(libm_root)/include \
 	$(libm_root)/include/arm64 \
@@ -154,79 +160,6 @@
 
 TARGET_STRIP_MODULE:=true
 
-TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libstdc++ libm
+TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libm
 
-TARGET_CUSTOM_LD_COMMAND := true
-
-define transform-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
-	-nostdlib -Wl,-soname,$(notdir $@) \
-	-Wl,--gc-sections \
-	$(if $(filter true,$(PRIVATE_CLANG)),-shared,-Wl,-shared) \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bdynamic -pie \
-	-Wl,-dynamic-linker,/system/bin/linker64 \
-	-Wl,--gc-sections \
-	-Wl,-z,nocopyreloc \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bstatic \
-	-Wl,--gc-sections \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_STATIC_O)) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(call normalize-target-libraries,$(filter-out %libc_nomalloc.a,$(filter-out %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES)))) \
-	-Wl,--start-group \
-	$(call normalize-target-libraries,$(filter %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(call normalize-target-libraries,$(filter %libc_nomalloc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	-Wl,--end-group \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
-endef
+TARGET_LINKER := /system/bin/linker64
diff --git a/core/combo/TARGET_linux-mips.mk b/core/combo/TARGET_linux-mips.mk
index 995e63c..55566eb 100644
--- a/core/combo/TARGET_linux-mips.mk
+++ b/core/combo/TARGET_linux-mips.mk
@@ -35,7 +35,7 @@
 endif
 
 # Decouple NDK library selection with platform compiler version
-$(combo_2nd_arch_prefix)TARGET_NDK_GCC_VERSION := 4.8
+$(combo_2nd_arch_prefix)TARGET_NDK_GCC_VERSION := 4.9
 
 ifeq ($(strip $(TARGET_GCC_VERSION_EXP)),)
 $(combo_2nd_arch_prefix)TARGET_GCC_VERSION := 4.9
@@ -104,10 +104,14 @@
 			-Wl,-z,noexecstack \
 			-Wl,-z,relro \
 			-Wl,-z,now \
+			-Wl,--build-id=md5 \
 			-Wl,--warn-shared-textrel \
 			-Wl,--fatal-warnings \
 			$(arch_variant_ldflags)
 
+# Disable transitive dependency library symbol resolving.
+$(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--allow-shlib-undefined
+
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CPPFLAGS += -fvisibility-inlines-hidden
 
 # More flags/options can be added here
@@ -121,7 +125,6 @@
 
 libc_root := bionic/libc
 libm_root := bionic/libm
-libstdc++_root := bionic/libstdc++
 
 
 ## on some hosts, the target cross-compiler is not available so do not run this command
@@ -137,6 +140,8 @@
 ifneq ($(LIBGCC_EH),libgcc_eh.a)
   $(combo_2nd_arch_prefix)TARGET_LIBGCC += $(LIBGCC_EH)
 endif
+$(combo_2nd_arch_prefix)TARGET_LIBGCOV := $(shell $($(combo_2nd_arch_prefix)TARGET_CC) $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) \
+        --print-file-name=libgcov.a)
 endif
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
@@ -146,7 +151,6 @@
 $(combo_2nd_arch_prefix)TARGET_C_INCLUDES := \
 	$(libc_root)/arch-mips/include \
 	$(libc_root)/include \
-	$(libstdc++_root)/include \
 	$(KERNEL_HEADERS) \
 	$(libm_root)/include \
 	$(libm_root)/include/mips \
@@ -160,79 +164,6 @@
 
 $(combo_2nd_arch_prefix)TARGET_STRIP_MODULE:=true
 
-$(combo_2nd_arch_prefix)TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libstdc++ libm
+$(combo_2nd_arch_prefix)TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libm
 
-$(combo_2nd_arch_prefix)TARGET_CUSTOM_LD_COMMAND := true
-
-define $(combo_2nd_arch_prefix)transform-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
-	-nostdlib -Wl,-soname,$(notdir $@) \
-	-Wl,--gc-sections \
-	$(if $(filter true,$(PRIVATE_CLANG)),-shared,-Wl,-shared) \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define $(combo_2nd_arch_prefix)transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bdynamic -pie \
-	-Wl,-dynamic-linker,/system/bin/linker \
-	-Wl,--gc-sections \
-	-Wl,-z,nocopyreloc \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define $(combo_2nd_arch_prefix)transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bstatic \
-	-Wl,--gc-sections \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_STATIC_O)) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(call normalize-target-libraries,$(filter-out %libc_nomalloc.a,$(filter-out %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES)))) \
-	-Wl,--start-group \
-	$(call normalize-target-libraries,$(filter %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(call normalize-target-libraries,$(filter %libc_nomalloc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	-Wl,--end-group \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
-endef
+$(combo_2nd_arch_prefix)TARGET_LINKER := /system/bin/linker
diff --git a/core/combo/TARGET_linux-mips64.mk b/core/combo/TARGET_linux-mips64.mk
index 4511b47..c6f9f29 100644
--- a/core/combo/TARGET_linux-mips64.mk
+++ b/core/combo/TARGET_linux-mips64.mk
@@ -18,7 +18,7 @@
 # Included by combo/select.mk
 
 # You can set TARGET_ARCH_VARIANT to use an arch version other
-# than mips64. Each value should correspond to a file named
+# than mips64r6. Each value should correspond to a file named
 # $(BUILD_COMBOS)/arch/<name>.mk which must contain
 # makefile variable definitions similar to the preprocessor
 # defines in build/core/combo/include/arch/<combo>/AndroidConfig.h. Their
@@ -35,7 +35,7 @@
 endif
 
 # Decouple NDK library selection with platform compiler version
-TARGET_NDK_GCC_VERSION := 4.8
+TARGET_NDK_GCC_VERSION := 4.9
 
 ifeq ($(strip $(TARGET_GCC_VERSION_EXP)),)
 TARGET_GCC_VERSION := 4.9
@@ -96,6 +96,12 @@
 			-include $(android_config_h) \
 			-I $(dir $(android_config_h))
 
+# Help catch common 32/64-bit errors.
+TARGET_GLOBAL_CFLAGS += \
+    -Werror=pointer-to-int-cast \
+    -Werror=int-to-pointer-cast \
+    -Werror=implicit-function-declaration \
+
 ifneq ($(ARCH_MIPS_PAGE_SHIFT),)
 TARGET_GLOBAL_CFLAGS += -DPAGE_SHIFT=$(ARCH_MIPS_PAGE_SHIFT)
 endif
@@ -104,6 +110,7 @@
 			-Wl,-z,noexecstack \
 			-Wl,-z,relro \
 			-Wl,-z,now \
+			-Wl,--build-id=md5 \
 			-Wl,--warn-shared-textrel \
 			-Wl,--fatal-warnings \
 			$(arch_variant_ldflags)
@@ -121,7 +128,6 @@
 
 libc_root := bionic/libc
 libm_root := bionic/libm
-libstdc++_root := bionic/libstdc++
 libthread_db_root := bionic/libthread_db
 
 
@@ -138,6 +144,8 @@
 ifneq ($(LIBGCC_EH),libgcc_eh.a)
   TARGET_LIBGCC += $(LIBGCC_EH)
 endif
+TARGET_LIBGCOV := $(shell $(TARGET_CC) $(TARGET_GLOBAL_CFLAGS) \
+        --print-file-name=libgcov.a)
 endif
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
@@ -148,7 +156,6 @@
 TARGET_C_INCLUDES := \
 	$(libc_root)/arch-mips64/include \
 	$(libc_root)/include \
-	$(libstdc++_root)/include \
 	$(KERNEL_HEADERS) \
 	$(libm_root)/include \
 	$(libm_root)/include/mips \
@@ -166,77 +173,4 @@
 
 TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libstdc++ libm
 
-TARGET_CUSTOM_LD_COMMAND := true
-
-define transform-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
-	-nostdlib -Wl,-soname,$(notdir $@) \
-	-Wl,--gc-sections \
-	$(if $(filter true,$(PRIVATE_CLANG)),-shared,-Wl,-shared) \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bdynamic -pie \
-	-Wl,-dynamic-linker,/system/bin/linker64 \
-	-Wl,--gc-sections \
-	-Wl,-z,nocopyreloc \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bstatic \
-	-Wl,--gc-sections \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_STATIC_O)) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(call normalize-target-libraries,$(filter-out %libc_nomalloc.a,$(filter-out %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES)))) \
-	-Wl,--start-group \
-	$(call normalize-target-libraries,$(filter %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(call normalize-target-libraries,$(filter %libc_nomalloc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	-Wl,--end-group \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
-endef
+TARGET_LINKER := /system/bin/linker64
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index 0af3948..f17a514 100644
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -62,13 +62,14 @@
 	$(shell $($(combo_2nd_arch_prefix)TARGET_CC) -m32 -print-file-name=libgcc.a)
 $(combo_2nd_arch_prefix)TARGET_LIBATOMIC := \
 	$(shell $($(combo_2nd_arch_prefix)TARGET_CC) -m32 -print-file-name=libatomic.a)
+$(combo_2nd_arch_prefix)TARGET_LIBGCOV := \
+	$(shell $($(combo_2nd_arch_prefix)TARGET_CC) -m32 -print-file-name=libgcov.a)
 endif
 
 $(combo_2nd_arch_prefix)TARGET_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
 
 libc_root := bionic/libc
 libm_root := bionic/libm
-libstdc++_root := bionic/libstdc++
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-x86 # x86 covers both x86 and x86_64.
@@ -121,14 +122,15 @@
 
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,-z,noexecstack
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,-z,relro -Wl,-z,now
+$(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--build-id=md5
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--warn-shared-textrel
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--fatal-warnings
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--gc-sections
+$(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--hash-style=gnu
 
 $(combo_2nd_arch_prefix)TARGET_C_INCLUDES := \
 	$(libc_root)/arch-x86/include \
 	$(libc_root)/include \
-	$(libstdc++_root)/include \
 	$(KERNEL_HEADERS) \
 	$(libm_root)/include \
 	$(libm_root)/include/i387 \
@@ -142,75 +144,8 @@
 
 $(combo_2nd_arch_prefix)TARGET_STRIP_MODULE:=true
 
-$(combo_2nd_arch_prefix)TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libstdc++ libm
+$(combo_2nd_arch_prefix)TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libm
 
-$(combo_2nd_arch_prefix)TARGET_CUSTOM_LD_COMMAND := true
-define $(combo_2nd_arch_prefix)transform-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	 -nostdlib -Wl,-soname,$(notdir $@) \
-	$(if $(filter true,$(PRIVATE_CLANG)),-shared,-Wl,-shared) \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
-	$(PRIVATE_LDLIBS)
-endef
+$(combo_2nd_arch_prefix)TARGET_LINKER := /system/bin/linker
 
-define $(combo_2nd_arch_prefix)transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	-nostdlib -Bdynamic \
-	-Wl,-z,nocopyreloc \
-	-pie \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define $(combo_2nd_arch_prefix)transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	-nostdlib -Bstatic \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_STATIC_O)) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	-Wl,--start-group \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	-Wl,--end-group \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
-endef
+$(combo_2nd_arch_prefix)TARGET_GLOBAL_YASM_FLAGS := -f elf32 -m x86
diff --git a/core/combo/TARGET_linux-x86_64.mk b/core/combo/TARGET_linux-x86_64.mk
index 33d6a56..2adb157 100644
--- a/core/combo/TARGET_linux-x86_64.mk
+++ b/core/combo/TARGET_linux-x86_64.mk
@@ -23,7 +23,7 @@
 endif
 
 # Decouple NDK library selection with platform compiler version
-TARGET_NDK_GCC_VERSION := 4.8
+TARGET_NDK_GCC_VERSION := 4.9
 
 ifeq ($(strip $(TARGET_GCC_VERSION_EXP)),)
 TARGET_GCC_VERSION := 4.8
@@ -62,13 +62,14 @@
 	$(shell $(TARGET_CC) -m64 -print-file-name=libgcc.a)
 TARGET_LIBATOMIC := \
 	$(shell $(TARGET_CC) -m64 -print-file-name=libatomic.a)
+TARGET_LIBGCOV := \
+	$(shell $(TARGET_CC) -m64 -print-file-name=libgcov.a)
 endif
 
 TARGET_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
 
 libc_root := bionic/libc
 libm_root := bionic/libm
-libstdc++_root := bionic/libstdc++
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-x86 # x86 covers both x86 and x86_64.
@@ -96,6 +97,7 @@
 TARGET_GLOBAL_CFLAGS += \
     -Werror=pointer-to-int-cast \
     -Werror=int-to-pointer-cast \
+    -Werror=implicit-function-declaration \
 
 android_config_h := $(call select-android-config-h,target_linux-x86)
 TARGET_ANDROID_CONFIG_CFLAGS := -include $(android_config_h) -I $(dir $(android_config_h))
@@ -115,6 +117,9 @@
 ifeq ($(ARCH_X86_HAVE_SSE4_2),true)
     TARGET_GLOBAL_CFLAGS += -msse4.2
 endif
+ifeq ($(ARCH_X86_HAVE_POPCNT),true)
+    TARGET_GLOBAL_CFLAGS += -mpopcnt
+endif
 ifeq ($(ARCH_X86_HAVE_AVX),true)
     TARGET_GLOBAL_CFLAGS += -mavx
 endif
@@ -126,14 +131,15 @@
 
 TARGET_GLOBAL_LDFLAGS += -Wl,-z,noexecstack
 TARGET_GLOBAL_LDFLAGS += -Wl,-z,relro -Wl,-z,now
+TARGET_GLOBAL_LDFLAGS += -Wl,--build-id=md5
 TARGET_GLOBAL_LDFLAGS += -Wl,--warn-shared-textrel
 TARGET_GLOBAL_LDFLAGS += -Wl,--fatal-warnings
 TARGET_GLOBAL_LDFLAGS += -Wl,--gc-sections
+TARGET_GLOBAL_LDFLAGS += -Wl,--hash-style=gnu
 
 TARGET_C_INCLUDES := \
 	$(libc_root)/arch-x86_64/include \
 	$(libc_root)/include \
-	$(libstdc++_root)/include \
 	$(KERNEL_HEADERS) \
 	$(libm_root)/include \
 	$(libm_root)/include/amd64 \
@@ -147,75 +153,8 @@
 
 TARGET_STRIP_MODULE:=true
 
-TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libstdc++ libm
+TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libm
 
-TARGET_CUSTOM_LD_COMMAND := true
-define transform-o-to-shared-lib-inner
-$(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	 -nostdlib -Wl,-soname,$(notdir $@) \
-	$(if $(filter true,$(PRIVATE_CLANG)),-shared,-Wl,-shared) \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O))
-endef
+TARGET_LINKER := /system/bin/linker64
 
-define transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	-nostdlib -Bdynamic \
-	-Wl,-z,nocopyreloc \
-	-pie \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O)) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
-	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-o $@ \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
-	$(PRIVATE_LDLIBS)
-endef
-
-define transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	-nostdlib -Bstatic \
-	-o $@ \
-	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_STATIC_O)) \
-	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_ALL_OBJECTS) \
-	-Wl,--whole-archive \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
-	-Wl,--no-whole-archive \
-	-Wl,--start-group \
-	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
-	$(PRIVATE_TARGET_LIBATOMIC) \
-	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
-	-Wl,--end-group \
-	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
-	$(PRIVATE_LDLIBS)
-endef
+TARGET_GLOBAL_YASM_FLAGS := -f elf64 -m amd64
diff --git a/core/combo/arch/arm/armv7-a-neon.mk b/core/combo/arch/arm/armv7-a-neon.mk
index c6603db..d535afc 100644
--- a/core/combo/arch/arm/armv7-a-neon.mk
+++ b/core/combo/arch/arm/armv7-a-neon.mk
@@ -7,7 +7,15 @@
 ARCH_ARM_HAVE_NEON              := true
 
 ifneq (,$(filter cortex-a15 krait denver,$(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT)))
+	# TODO: krait is not a cortex-a15, we set the variant to cortex-a15 so that
+	#       hardware divide operations are generated. This should be removed and a
+	#       krait CPU variant added to GCC. For clang we specify -mcpu for krait in
+	#       core/clang/arm.mk.
 	arch_variant_cflags := -mcpu=cortex-a15
+
+	# Fake an ARM compiler flag as these processors support LPAE which GCC/clang
+	# don't advertise.
+	arch_variant_cflags += -D__ARM_FEATURE_LPAE=1
 else
 ifeq ($(strip $(TARGET_$(combo_2nd_arch_prefix)CPU_VARIANT)),cortex-a8)
 	arch_variant_cflags := -mcpu=cortex-a8
diff --git a/core/combo/arch/x86/x86-atom.mk b/core/combo/arch/x86/atom.mk
similarity index 95%
rename from core/combo/arch/x86/x86-atom.mk
rename to core/combo/arch/x86/atom.mk
index 508a0af..3800350 100644
--- a/core/combo/arch/x86/x86-atom.mk
+++ b/core/combo/arch/x86/atom.mk
@@ -11,6 +11,5 @@
 # CFLAGS for this arch
 arch_variant_cflags := \
 	-march=atom \
-	-mstackrealign \
 	-mfpmath=sse \
 
diff --git a/core/combo/arch/x86/haswell.mk b/core/combo/arch/x86/haswell.mk
index a00e0a6..b3922c0 100644
--- a/core/combo/arch/x86/haswell.mk
+++ b/core/combo/arch/x86/haswell.mk
@@ -7,10 +7,11 @@
 ARCH_X86_HAVE_SSE4_2 := true
 ARCH_X86_HAVE_AES_NI := true
 ARCH_X86_HAVE_AVX    := true
+ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_MOVBE  := true
 
 # CFLAGS for this arch
 arch_variant_cflags := \
 	-march=core-avx2 \
-	-mstackrealign \
 	-mfpmath=sse \
 
diff --git a/core/combo/arch/x86/ivybridge.mk b/core/combo/arch/x86/ivybridge.mk
index 02dc1e0..c9fc33b 100644
--- a/core/combo/arch/x86/ivybridge.mk
+++ b/core/combo/arch/x86/ivybridge.mk
@@ -7,10 +7,11 @@
 ARCH_X86_HAVE_SSE4_2 := true
 ARCH_X86_HAVE_AES_NI := true
 ARCH_X86_HAVE_AVX    := true
+ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_MOVBE  := false
 
 # CFLAGS for this arch
 arch_variant_cflags := \
 	-march=core-avx-i \
-	-mstackrealign \
 	-mfpmath=sse \
 
diff --git a/core/combo/arch/x86/sandybridge.mk b/core/combo/arch/x86/sandybridge.mk
index dfa540c..bca5953 100644
--- a/core/combo/arch/x86/sandybridge.mk
+++ b/core/combo/arch/x86/sandybridge.mk
@@ -2,13 +2,16 @@
 # Generating binaries for SandyBridge processors.
 #
 ARCH_X86_HAVE_SSSE3  := true
+ARCH_X86_HAVE_SSE4   := true
 ARCH_X86_HAVE_SSE4_1 := true
 ARCH_X86_HAVE_SSE4_2 := true
+ARCH_X86_HAVE_AES_NI := true
 ARCH_X86_HAVE_AVX    := true
+ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_MOVBE  := false
 
 # CFLAGS for this arch
 arch_variant_cflags := \
 	-march=corei7-avx \
-	-mstackrealign \
 	-mfpmath=sse \
 
diff --git a/core/combo/arch/x86/silvermont.mk b/core/combo/arch/x86/silvermont.mk
index 3a8718d..d064b1d 100644
--- a/core/combo/arch/x86/silvermont.mk
+++ b/core/combo/arch/x86/silvermont.mk
@@ -15,6 +15,5 @@
 # CFLAGS for this arch
 arch_variant_cflags := \
 	-march=slm \
-	-mstackrealign \
 	-mfpmath=sse \
 
diff --git a/core/combo/arch/x86/x86.mk b/core/combo/arch/x86/x86.mk
index 73706c4..f070426 100644
--- a/core/combo/arch/x86/x86.mk
+++ b/core/combo/arch/x86/x86.mk
@@ -13,11 +13,7 @@
 ARCH_X86_HAVE_POPCNT := false
 
 
-# XXX: This flag is probably redundant, because it should be set by default
-# by our toolchain binaries. However, there have been reports that this may
-# not always work as intended, so keep it unless we have the time to check
-# everything properly.
-
+# Some intrinsic functions used by libcxx only exist for prescott or newer CPUs.
 arch_variant_cflags := \
-    -march=i686 \
+    -march=prescott \
 
diff --git a/core/combo/arch/x86_64/haswell.mk b/core/combo/arch/x86_64/haswell.mk
index 9cf95b3..6067eee 100644
--- a/core/combo/arch/x86_64/haswell.mk
+++ b/core/combo/arch/x86_64/haswell.mk
@@ -7,6 +7,8 @@
 ARCH_X86_HAVE_SSE4_2 := true
 ARCH_X86_HAVE_AES_NI := true
 ARCH_X86_HAVE_AVX    := true
+ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_MOVBE  := true
 
 # CFLAGS for this arch
 arch_variant_cflags := \
diff --git a/core/combo/arch/x86_64/ivybridge.mk b/core/combo/arch/x86_64/ivybridge.mk
index 7b95190..90e23a9 100644
--- a/core/combo/arch/x86_64/ivybridge.mk
+++ b/core/combo/arch/x86_64/ivybridge.mk
@@ -7,6 +7,8 @@
 ARCH_X86_HAVE_SSE4_2 := true
 ARCH_X86_HAVE_AES_NI := true
 ARCH_X86_HAVE_AVX    := true
+ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_MOVBE  := false
 
 # CFLAGS for this arch
 arch_variant_cflags := \
diff --git a/core/combo/arch/x86_64/sandybridge.mk b/core/combo/arch/x86_64/sandybridge.mk
index a443b6b..865548c 100644
--- a/core/combo/arch/x86_64/sandybridge.mk
+++ b/core/combo/arch/x86_64/sandybridge.mk
@@ -2,9 +2,13 @@
 # Generating binaries for SandyBridge processors.
 #
 ARCH_X86_HAVE_SSSE3  := true
+ARCH_X86_HAVE_SSE4   := true
 ARCH_X86_HAVE_SSE4_1 := true
 ARCH_X86_HAVE_SSE4_2 := true
+ARCH_X86_HAVE_AES_NI := true
 ARCH_X86_HAVE_AVX    := true
+ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_MOVBE  := false
 
 # CFLAGS for this arch
 arch_variant_cflags := \
diff --git a/core/combo/arch/x86_64/x86_64-atom.mk b/core/combo/arch/x86_64/x86_64-atom.mk
deleted file mode 100755
index 64b07a0..0000000
--- a/core/combo/arch/x86_64/x86_64-atom.mk
+++ /dev/null
@@ -1,13 +0,0 @@
-# This file contains feature macro definitions specific to the
-# 'x86_64-atom' arch variant. This is an extension of the 'x86_64' base variant
-# that adds Atom-specific features.
-#
-# See build/core/combo/arch/x86_64/x86_64.mk for differences.
-#
-ARCH_X86_HAVE_SSSE3 := true
-ARCH_X86_HAVE_MOVBE := true
-ARCH_X86_HAVE_POPCNT := false   # popcnt is not supported by current Atom CPUs
-
-# CFLAGS for this arch
-arch_variant_cflags := \
-	-march=atom
diff --git a/core/combo/arch/x86_64/x86_64.mk b/core/combo/arch/x86_64/x86_64.mk
index 9d2b620..08dd9cd 100755
--- a/core/combo/arch/x86_64/x86_64.mk
+++ b/core/combo/arch/x86_64/x86_64.mk
@@ -8,6 +8,9 @@
 ARCH_X86_HAVE_SSSE3 := true
 ARCH_X86_HAVE_MOVBE := false # Only supported on Atom.
 ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_SSE4 := true
+ARCH_X86_HAVE_SSE4_1 := true
+ARCH_X86_HAVE_SSE4_2 := true
 
 
 # CFLAGS for this arch
diff --git a/core/combo/fdo.mk b/core/combo/fdo.mk
index 9e331b6..8fb8fd3 100644
--- a/core/combo/fdo.mk
+++ b/core/combo/fdo.mk
@@ -18,22 +18,16 @@
 
 $(combo_2nd_arch_prefix)TARGET_FDO_CFLAGS:=
 
-ifeq ($(strip $(BUILD_FDO_INSTRUMENT)), true)
-  # Set BUILD_FDO_INSTRUMENT=true to turn on FDO instrumentation.
-  # The profile will be generated on /sdcard/fdo_profile on the device.
-  $(combo_2nd_arch_prefix)TARGET_FDO_CFLAGS := -fprofile-generate=/sdcard/fdo_profile -DANDROID_FDO
-  $(combo_2nd_arch_prefix)TARGET_FDO_LDFLAGS := -lgcov -lgcc
-else
-  ifeq ($(strip $(BUILD_FDO_OPTIMIZE)), true)
-    # Set TARGET_FDO_PROFILE_PATH to set a custom profile directory for your build.
-    ifeq ($(strip $($(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH)),)
-      $(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH := vendor/google_data/fdo_profile
-    endif
+# Set BUILD_FDO_INSTRUMENT=true to turn on FDO instrumentation.
+# The profile will be generated on /sdcard/fdo_profile on the device.
+$(combo_2nd_arch_prefix)TARGET_FDO_INSTRUMENT_CFLAGS := -fprofile-generate=/sdcard/fdo_profile -DANDROID_FDO
+$(combo_2nd_arch_prefix)TARGET_FDO_INSTRUMENT_LDFLAGS := -lgcov -lgcc
 
-    ifneq ($(strip $(wildcard $($(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH)/$(PRODUCT_OUT))),)
-      $(combo_2nd_arch_prefix)TARGET_FDO_CFLAGS := -fprofile-use=$($(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH) -DANDROID_FDO -fprofile-correction -Wcoverage-mismatch -Wno-error
-    else
-      $(warning Profile directory $($(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH)/$(PRODUCT_OUT) does not exist. Turn off FDO.)
-    endif
-  endif
+# Set TARGET_FDO_PROFILE_PATH to set a custom profile directory for your build.
+ifeq ($(strip $($(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH)),)
+  $(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH := vendor/google_data/fdo_profile
 endif
+
+$(combo_2nd_arch_prefix)TARGET_FDO_OPTIMIZE_CFLAGS := \
+    -fprofile-use=$($(combo_2nd_arch_prefix)TARGET_FDO_PROFILE_PATH) \
+    -DANDROID_FDO -fprofile-correction -Wcoverage-mismatch -Wno-error
diff --git a/core/combo/include/arch/darwin-x86/AndroidConfig.h b/core/combo/include/arch/darwin-x86/AndroidConfig.h
index 54f3750..6ddfdb1 100644
--- a/core/combo/include/arch/darwin-x86/AndroidConfig.h
+++ b/core/combo/include/arch/darwin-x86/AndroidConfig.h
@@ -33,143 +33,6 @@
  */
 
 /*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- *  -- combine HAVE_CREATETHREAD, HAVE_CREATEMUTEX, and HAVE__BEGINTHREADEX
- */
-#define HAVE_PTHREADS
-
-/*
- * Do we have the futex syscall?
- */
-
-/* #define HAVE_FUTEX */
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#define HAVE_FORKEXEC
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
-#define HAVE_MACOSX_IPC
-
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
-#define  HAVE_POSIX_FILEMAP
-
-/*
- * Define this if you have <termio.h>
- */
-#define  HAVE_TERMIO_H
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-/* #define  HAVE_SYS_SENDFILE_H 1 */
-
-/*
- * Define this if you build against MSVCRT.DLL
- */
-/* #define HAVE_MS_C_RUNTIME */
-
-/*
- * Define this if you have sys/uio.h
- */
-#define  HAVE_SYS_UIO_H
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-#define HAVE_SYMLINKS
-
-/*
- * Define this if we have localtime_r().
- */
-#define HAVE_LOCALTIME_R 1
-
-/*
- * Define this if we have gethostbyname_r().
- */
-/* #define HAVE_GETHOSTBYNAME_R */
-
-/*
- * Define this if we have ioctl().
- */
-/* #define HAVE_IOCTL */
-
-/*
- * Define this if we want to use WinSock.
- */
-/* #define HAVE_WINSOCK */
-
-/*
- * Define this if have clock_gettime() and friends
- */
-/* #define HAVE_POSIX_CLOCKS */
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#if (defined(__ppc__) || defined(__ppc64__))
-#   define HAVE_BIG_ENDIAN
-#elif (defined(__i386__) || defined(__x86_64__))
-#   define HAVE_LITTLE_ENDIAN
-#endif
-
-/*
- * We need to choose between 32-bit and 64-bit off_t.  All of our code should
- * agree on the same size.  For desktop systems, use 64-bit values,
- * because some of our libraries (e.g. wxWidgets) expect to be built that way.
- */
-#define _FILE_OFFSET_BITS 64
-#define _LARGEFILE_SOURCE 1
-
-/*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-/* #define HAVE_OFF64_T */
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 0
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Defined if we have the gettid() system call.
- */
-/* #define HAVE_GETTID */
-
-
-/*
  * Add any extra platform-specific defines here.
  */
 #define _THREAD_SAFE
@@ -180,119 +43,23 @@
 /* #define HAVE_MALLOC_H */
 
 /*
- * Define if tm struct has tm_gmtoff field
- */
-#define HAVE_TM_GMTOFF 1
-
-/*
- * Define if dirent struct has d_type field
- */
-#define HAVE_DIRENT_D_TYPE 1
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-#define HAVE_MADVISE 1
-
-/*
- * Define if we include <sys/mount.h> for statfs()
- */
-#define INCLUDE_SYS_MOUNT_FOR_STATFS 1
-
-/*
- * What CPU architecture does this platform use?
- */
-#if (defined(__ppc__) || defined(__ppc64__))
-#   define ARCH_PPC
-#elif (defined(__i386__) || defined(__x86_64__))
-#   define ARCH_X86
-#endif
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.dylib"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
 
 /*
- * Is the filesystem case sensitive?
- *
- * For tools apps, we'll treat is as not case sensitive.
- */
-/* #define OS_CASE_SENSITIVE */
-
-/*
- * Define if <sys/socket.h> exists.
- */
-#define HAVE_SYS_SOCKET_H 1
-
-/*
  * Define if the strlcpy() function exists on the system.
  */
 #define HAVE_STRLCPY 1
 
 /*
- * Define if the open_memstream() function exists on the system.
- */
-/* #define HAVE_OPEN_MEMSTREAM 1 */
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-#define HAVE_FUNOPEN 1
-
-/*
- * Define if writev() exists
- */
-#define HAVE_WRITEV 1
-
-/*
  * Define if <stdint.h> exists.
  */
 #define HAVE_STDINT_H 1
 
 /*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H 1
-
-/*
- * Define if <sched.h> exists.
- */
-#define HAVE_SCHED_H 1
-
-/*
- * Define if pread() exists
- */
-#define HAVE_PREAD 1
-
-/*
- * Define if we have st_mtim in struct stat
- */
-#define HAVE_STAT_ST_MTIM 1
-
-/*
  * Define if printf() supports %zd for size_t arguments
  */
 #define HAVE_PRINTF_ZD 1
 
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
- */
-#define HAVE_BSD_QSORT_R 1
-
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
- */
-#define HAVE_GNU_QSORT_R 0
-
 #endif /*_ANDROID_CONFIG_H*/
diff --git a/core/combo/include/arch/linux-arm/AndroidConfig.h b/core/combo/include/arch/linux-arm/AndroidConfig.h
index c06c8bc..b1c963e 100644
--- a/core/combo/include/arch/linux-arm/AndroidConfig.h
+++ b/core/combo/include/arch/linux-arm/AndroidConfig.h
@@ -33,306 +33,33 @@
  */
 
 /*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- *  -- combine HAVE_CREATETHREAD, HAVE_CREATEMUTEX, and HAVE__BEGINTHREADEX
- */
-#define HAVE_PTHREADS
-
-/*
- * Do we have pthread_setname_np()?
- *
- * (HAVE_PTHREAD_SETNAME_NP is used by WebKit to enable a function with
- * the same name but different parameters, so we can't use that here.)
- */
-#define HAVE_ANDROID_PTHREAD_SETNAME_NP
-
-/*
- * Do we have the futex syscall?
- */
-#define HAVE_FUTEX
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#define HAVE_FORKEXEC
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
-#define HAVE_ANDROID_IPC
-
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
-#define  HAVE_POSIX_FILEMAP
-
-/*
- * Define this if you have <termio.h>
- */
-#define  HAVE_TERMIO_H 1
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-#define  HAVE_SYS_SENDFILE_H 1
-
-/*
- * Define this if you build against MSVCRT.DLL
- */
-/* #define HAVE_MS_C_RUNTIME */
-
-/*
- * Define this if you have sys/uio.h
- */
-#define  HAVE_SYS_UIO_H 1
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-#define HAVE_SYMLINKS
-
-/*
- * Define this if we have localtime_r().
- */
-/* #define HAVE_LOCALTIME_R 1 */
-
-/*
- * Define this if we have gethostbyname_r().
- */
-/* #define HAVE_GETHOSTBYNAME_R */
-
-/*
- * Define this if we have ioctl().
- */
-#define HAVE_IOCTL
-
-/*
- * Define this if we want to use WinSock.
- */
-/* #define HAVE_WINSOCK */
-
-/*
- * Define this if have clock_gettime() and friends
- */
-#define HAVE_POSIX_CLOCKS
-
-/*
- * Define this if we have linux style epoll()
- */
-#define HAVE_EPOLL
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#define HAVE_ENDIAN_H
-#define HAVE_LITTLE_ENDIAN
-
-/*
- * We need to choose between 32-bit and 64-bit off_t.  All of our code should
- * agree on the same size.  For desktop systems, use 64-bit values,
- * because some of our libraries (e.g. wxWidgets) expect to be built that way.
- */
-/* #define _FILE_OFFSET_BITS 64 */
-/* #define _LARGEFILE_SOURCE 1 */
-
-/*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-#define HAVE_OFF64_T
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 0
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Defined if we have the gettid() system call.
- */
-#define HAVE_GETTID
-
-/* 
- * Defined if we have the sched_setscheduler() call
- */
-#define HAVE_SCHED_SETSCHEDULER
-
-/*
- * Add any extra platform-specific defines here.
- */
-#ifndef __linux__
-#define __linux__
-#endif
-
-/*
  * Define if we have <malloc.h> header
  */
 #define HAVE_MALLOC_H
 
-/* 
+/*
  * Define if we're running on *our* linux on device or emulator.
  */
 #define HAVE_ANDROID_OS 1
 
 /*
- * Define if we have Linux-style non-filesystem Unix Domain Sockets
- */
-#define HAVE_LINUX_LOCAL_SOCKET_NAMESPACE 1
-
-/*
- * Define if we have Linux's inotify in <sys/inotify.h>.
- */
-#define HAVE_INOTIFY 1
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-#define HAVE_MADVISE 1
-
-/*
- * Define if tm struct has tm_gmtoff field
- */
-#define HAVE_TM_GMTOFF 1
-
-/*
- * Define if dirent struct has d_type field
- */
-#define HAVE_DIRENT_D_TYPE 1
-
-/*
- * Define if libc includes Android system properties implementation.
- */
-#define HAVE_LIBC_SYSTEM_PROPERTIES 1
-
-/*
- * Define if system provides a system property server (should be
- * mutually exclusive with HAVE_LIBC_SYSTEM_PROPERTIES).
- */
-/* #define HAVE_SYSTEM_PROPERTY_SERVER */
-
-/*
- * What CPU architecture does this platform use?
- */
-#define ARCH_ARM
-
-/*
- * Define if the size of enums is as short as possible,
- */
-/* #define HAVE_SHORT_ENUMS */
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE unsigned char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
 
 /*
- * Is the filesystem case sensitive?
- */
-#define OS_CASE_SENSITIVE
-
-/*
- * Define if <sys/socket.h> exists.
- */
-#define HAVE_SYS_SOCKET_H 1
-
-/*
  * Define if the strlcpy() function exists on the system.
  */
 #define HAVE_STRLCPY 1
 
 /*
- * Define if the open_memstream() function exists on the system.
- */
-/* #define HAVE_OPEN_MEMSTREAM 1 */
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-#define HAVE_FUNOPEN 1
-
-/*
- * Define if prctl() exists
- */
-#define HAVE_PRCTL 1
-
-/*
- * Define if writev() exists
- */
-#define HAVE_WRITEV 1
-
-/*
  * Define if <stdint.h> exists.
  */
 #define HAVE_STDINT_H 1
 
 /*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H 1
-
-/*
- * Define if <sched.h> exists.
- */
-#define HAVE_SCHED_H 1
-
-/*
- * Define if pread() exists
- */
-#define HAVE_PREAD 1
-
-/*
- * Define if we have st_mtim in struct stat
- */
-#define HAVE_STAT_ST_MTIM 1
-
-/*
  * Define if printf() supports %zd for size_t arguments
  */
 #define HAVE_PRINTF_ZD 1
 
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
- */
-#define HAVE_BSD_QSORT_R 0
-
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
- */
-#define HAVE_GNU_QSORT_R 0
-
 #endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/linux-arm64/AndroidConfig.h b/core/combo/include/arch/linux-arm64/AndroidConfig.h
index bcbda8f..c1e9e59 100644
--- a/core/combo/include/arch/linux-arm64/AndroidConfig.h
+++ b/core/combo/include/arch/linux-arm64/AndroidConfig.h
@@ -33,165 +33,6 @@
  */
 
 /*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- *  -- combine HAVE_CREATETHREAD, HAVE_CREATEMUTEX, and HAVE__BEGINTHREADEX
- */
-#define HAVE_PTHREADS
-
-/*
- * Do we have pthread_setname_np()?
- *
- * (HAVE_PTHREAD_SETNAME_NP is used by WebKit to enable a function with
- * the same name but different parameters, so we can't use that here.)
- */
-#define HAVE_ANDROID_PTHREAD_SETNAME_NP
-
-/*
- * Do we have the futex syscall?
- */
-#define HAVE_FUTEX
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#define HAVE_FORKEXEC
-
-/*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-#define HAVE_OOM_ADJ
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
-#define HAVE_ANDROID_IPC
-
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
-#define  HAVE_POSIX_FILEMAP
-
-/*
- * Define this if you have <termio.h>
- */
-#define  HAVE_TERMIO_H 1
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-#define  HAVE_SYS_SENDFILE_H 1
-
-/*
- * Define this if you build against MSVCRT.DLL
- */
-/* #define HAVE_MS_C_RUNTIME */
-
-/*
- * Define this if you have sys/uio.h
- */
-#define  HAVE_SYS_UIO_H 1
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-#define HAVE_SYMLINKS
-
-/*
- * Define this if we have localtime_r().
- */
-/* #define HAVE_LOCALTIME_R 1 */
-
-/*
- * Define this if we have gethostbyname_r().
- */
-/* #define HAVE_GETHOSTBYNAME_R */
-
-/*
- * Define this if we have ioctl().
- */
-#define HAVE_IOCTL
-
-/*
- * Define this if we want to use WinSock.
- */
-/* #define HAVE_WINSOCK */
-
-/*
- * Define this if have clock_gettime() and friends
- */
-#define HAVE_POSIX_CLOCKS
-
-/*
- * Define this if we have linux style epoll()
- */
-#define HAVE_EPOLL
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#define HAVE_ENDIAN_H
-#define HAVE_LITTLE_ENDIAN
-
-#define _FILE_OFFSET_BITS 64
-/* #define _LARGEFILE_SOURCE 1 */
-
-/*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-#define HAVE_OFF64_T
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 0
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Defined if we have the gettid() system call.
- */
-#define HAVE_GETTID
-
-/*
- * Defined if we have the sched_setscheduler() call
- */
-#define HAVE_SCHED_SETSCHEDULER
-
-/*
- * Add any extra platform-specific defines here.
- */
-#ifndef __linux__
-#define __linux__
-#endif
-
-/*
  * Define if we have <malloc.h> header
  */
 #define HAVE_MALLOC_H
@@ -202,139 +43,23 @@
 #define HAVE_ANDROID_OS 1
 
 /*
- * Define if we have Linux-style non-filesystem Unix Domain Sockets
- */
-#define HAVE_LINUX_LOCAL_SOCKET_NAMESPACE 1
-
-/*
- * Define if we have Linux's inotify in <sys/inotify.h>.
- */
-#define HAVE_INOTIFY 1
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-#define HAVE_MADVISE 1
-
-/*
- * Define if tm struct has tm_gmtoff field
- */
-#define HAVE_TM_GMTOFF 1
-
-/*
- * Define if dirent struct has d_type field
- */
-#define HAVE_DIRENT_D_TYPE 1
-
-/*
- * Define if libc includes Android system properties implementation.
- */
-#define HAVE_LIBC_SYSTEM_PROPERTIES 1
-
-/*
- * Define if system provides a system property server (should be
- * mutually exclusive with HAVE_LIBC_SYSTEM_PROPERTIES).
- */
-/* #define HAVE_SYSTEM_PROPERTY_SERVER */
-
-/*
- * What CPU architecture does this platform use?
- */
-#define ARCH_AARCH64
-
-/*
- * Define if the size of enums is as short as possible,
- */
-/* #define HAVE_SHORT_ENUMS */
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE unsigned char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
 
 /*
- * Is the filesystem case sensitive?
- */
-#define OS_CASE_SENSITIVE
-
-/*
- * Define if <sys/socket.h> exists.
- */
-#define HAVE_SYS_SOCKET_H 1
-
-/*
  * Define if the strlcpy() function exists on the system.
  */
 #define HAVE_STRLCPY 1
 
 /*
- * Define if the open_memstream() function exists on the system.
- */
-/* #define HAVE_OPEN_MEMSTREAM 1 */
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-#define HAVE_FUNOPEN 1
-
-/*
- * Define if prctl() exists
- */
-#define HAVE_PRCTL 1
-
-/*
- * Define if writev() exists
- */
-#define HAVE_WRITEV 1
-
-/*
  * Define if <stdint.h> exists.
  */
 #define HAVE_STDINT_H 1
 
 /*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H 1
-
-/*
- * Define if <sched.h> exists.
- */
-#define HAVE_SCHED_H 1
-
-/*
- * Define if pread() exists
- */
-#define HAVE_PREAD 1
-
-/*
- * Define if we have st_mtim in struct stat
- */
-#define HAVE_STAT_ST_MTIM 1
-
-/*
  * Define if printf() supports %zd for size_t arguments
  */
 #define HAVE_PRINTF_ZD 1
 
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
- */
-#define HAVE_BSD_QSORT_R 0
-
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
- */
-#define HAVE_GNU_QSORT_R 0
-
 #endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/linux-mips/AndroidConfig.h b/core/combo/include/arch/linux-mips/AndroidConfig.h
index bb3dc95..ac0c9e1 100644
--- a/core/combo/include/arch/linux-mips/AndroidConfig.h
+++ b/core/combo/include/arch/linux-mips/AndroidConfig.h
@@ -33,180 +33,11 @@
  */
 
 /*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- *  -- combine HAVE_CREATETHREAD, HAVE_CREATEMUTEX, and HAVE__BEGINTHREADEX
- */
-#define HAVE_PTHREADS
-
-/*
- * Do we have pthread_setname_np()?
- *
- * (HAVE_PTHREAD_SETNAME_NP is used by WebKit to enable a function with
- * the same name but different parameters, so we can't use that here.)
- */
-#define HAVE_ANDROID_PTHREAD_SETNAME_NP
-
-/*
- * Do we have the futex syscall?
- */
-#define HAVE_FUTEX
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#define HAVE_FORKEXEC
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
-#define HAVE_ANDROID_IPC
-
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
-#define  HAVE_POSIX_FILEMAP
-
-/*
- * Define this if you have <termio.h>
- */
-#define  HAVE_TERMIO_H 1
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-#define  HAVE_SYS_SENDFILE_H 1
-
-/*
  * Define this if you build against MSVCRT.DLL
  */
 /* #define HAVE_MS_C_RUNTIME */
 
 /*
- * Define this if you have sys/uio.h
- */
-#define  HAVE_SYS_UIO_H 1
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-#define HAVE_SYMLINKS
-
-/*
- * Define this if we have localtime_r().
- */
-/* #define HAVE_LOCALTIME_R */
-
-/*
- * Define this if we have gethostbyname_r().
- */
-/* #define HAVE_GETHOSTBYNAME_R */
-
-/*
- * Define this if we have ioctl().
- */
-#define HAVE_IOCTL
-
-/*
- * Define this if we want to use WinSock.
- */
-/* #define HAVE_WINSOCK */
-
-/*
- * Define this if have clock_gettime() and friends
- */
-#define HAVE_POSIX_CLOCKS
-
-/*
- * Define this if we have linux style epoll()
- */
-#define HAVE_EPOLL
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#define HAVE_ENDIAN_H
-#if defined(__MIPSEB__)
-#define HAVE_BIG_ENDIAN
-#endif
-#if defined(__MIPSEL__)
-#define HAVE_LITTLE_ENDIAN
-#endif
-
-/*
- * We need to choose between 32-bit and 64-bit off_t.  All of our code should
- * agree on the same size.  For desktop systems, use 64-bit values,
- * because some of our libraries (e.g. wxWidgets) expect to be built that way.
- */
-/* #define _FILE_OFFSET_BITS 64 */
-/* #define _LARGEFILE_SOURCE 1 */
-
-/*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-#define HAVE_OFF64_T
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 0
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Defined if we have the gettid() system call.
- */
-#define HAVE_GETTID
-
-/*
- * Defined if we have the sched_setscheduler() call
- */
-#define HAVE_SCHED_SETSCHEDULER
-
-/*
- * Add any extra platform-specific defines here.
- */
-#ifndef __linux__
-#define __linux__ 1
-#endif
-
-#ifndef __linux
-#define __linux 1
-#endif
-
-#ifdef __unix__
-#undef __unix__
-#endif
-
-#ifdef __unix
-#undef __unix
-#endif
-
-/*
  * Define if we have <malloc.h> header
  */
 #define HAVE_MALLOC_H
@@ -217,134 +48,23 @@
 #define HAVE_ANDROID_OS 1
 
 /*
- * Define if we have Linux-style non-filesystem Unix Domain Sockets
- */
-#define HAVE_LINUX_LOCAL_SOCKET_NAMESPACE 1
-
-/*
- * Define if we have Linux's inotify in <sys/inotify.h>.
- */
-#define HAVE_INOTIFY 1
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-#define HAVE_MADVISE 1
-
-/*
- * Define if tm struct has tm_gmtoff field
- */
-#define HAVE_TM_GMTOFF 1
-
-/*
- * Define if dirent struct has d_type field
- */
-#define HAVE_DIRENT_D_TYPE 1
-
-/*
- * Define if libc includes Android system properties implementation.
- */
-#define HAVE_LIBC_SYSTEM_PROPERTIES 1
-
-/*
- * Define if system provides a system property server (should be
- * mutually exclusive with HAVE_LIBC_SYSTEM_PROPERTIES).
- */
-/* #define HAVE_SYSTEM_PROPERTY_SERVER */
-
-/*
- * What CPU architecture does this platform use?
- */
-#define ARCH_MIPS 1
-
-/*
- * Define if the size of enums is as short as possible,
- */
-/* #define HAVE_SHORT_ENUMS */
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE unsigned char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
 
 /*
- * Is the filesystem case sensitive?
- */
-#define OS_CASE_SENSITIVE
-
-/*
- * Define if <sys/socket.h> exists.
- */
-#define HAVE_SYS_SOCKET_H 1
-
-/*
  * Define if the strlcpy() function exists on the system.
  */
 #define HAVE_STRLCPY 1
 
 /*
- * Define if the open_memstream() function exists on the system.
- */
-/* #define HAVE_OPEN_MEMSTREAM 1 */
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-#define HAVE_FUNOPEN 1
-
-/*
- * Define if prctl() exists
- */
-#define HAVE_PRCTL 1
-
-/*
- * Define if writev() exists
- */
-#define HAVE_WRITEV 1
-
-/*
  * Define if <stdint.h> exists.
  */
 #define HAVE_STDINT_H 1
 
 /*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H 1
-
-/*
- * Define if <sched.h> exists.
- */
-#define HAVE_SCHED_H 1
-
-/*
- * Define if pread() exists
- */
-#define HAVE_PREAD 1
-
-/*
- * Define if we have st_mtim in struct stat
- */
-#define HAVE_STAT_ST_MTIM 1
-
-/*
  * Define if printf() supports %zd for size_t arguments
  */
 #define HAVE_PRINTF_ZD 1
 
-/*
- * Whether or not _Unwind_Context is defined as a struct.
- */
-#define HAVE_UNWIND_CONTEXT_STRUCT 1
-
 #endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/linux-mips64/AndroidConfig.h b/core/combo/include/arch/linux-mips64/AndroidConfig.h
index 7ded3ce..b86c676 100644
--- a/core/combo/include/arch/linux-mips64/AndroidConfig.h
+++ b/core/combo/include/arch/linux-mips64/AndroidConfig.h
@@ -33,177 +33,6 @@
  */
 
 /*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- *  -- combine HAVE_CREATETHREAD, HAVE_CREATEMUTEX, and HAVE__BEGINTHREADEX
- */
-#define HAVE_PTHREADS
-
-/*
- * Do we have pthread_setname_np()?
- *
- * (HAVE_PTHREAD_SETNAME_NP is used by WebKit to enable a function with
- * the same name but different parameters, so we can't use that here.)
- */
-#define HAVE_ANDROID_PTHREAD_SETNAME_NP
-
-/*
- * Do we have the futex syscall?
- */
-#define HAVE_FUTEX
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#define HAVE_FORKEXEC
-
-/*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-#define HAVE_OOM_ADJ
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
-#define HAVE_ANDROID_IPC
-
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
-#define  HAVE_POSIX_FILEMAP
-
-/*
- * Define this if you have <termio.h>
- */
-#define  HAVE_TERMIO_H 1
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-#define  HAVE_SYS_SENDFILE_H 1
-
-/*
- * Define this if you build against MSVCRT.DLL
- */
-/* #define HAVE_MS_C_RUNTIME */
-
-/*
- * Define this if you have sys/uio.h
- */
-#define  HAVE_SYS_UIO_H 1
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-#define HAVE_SYMLINKS
-
-/*
- * Define this if we have localtime_r().
- */
-/* #define HAVE_LOCALTIME_R */
-
-/*
- * Define this if we have gethostbyname_r().
- */
-/* #define HAVE_GETHOSTBYNAME_R */
-
-/*
- * Define this if we have ioctl().
- */
-#define HAVE_IOCTL
-
-/*
- * Define this if we want to use WinSock.
- */
-/* #define HAVE_WINSOCK */
-
-/*
- * Define this if have clock_gettime() and friends
- */
-#define HAVE_POSIX_CLOCKS
-
-/*
- * Define this if we have linux style epoll()
- */
-#define HAVE_EPOLL
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#define HAVE_ENDIAN_H
-#define HAVE_LITTLE_ENDIAN
-
-#define _FILE_OFFSET_BITS 64
-/* #define _LARGEFILE_SOURCE 1 */
-
-/*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-#define HAVE_OFF64_T
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 0
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Defined if we have the gettid() system call.
- */
-#define HAVE_GETTID
-
-/*
- * Defined if we have the sched_setscheduler() call
- */
-#define HAVE_SCHED_SETSCHEDULER
-
-/*
- * Add any extra platform-specific defines here.
- */
-#ifndef __linux__
-#define __linux__ 1
-#endif
-
-#ifndef __linux
-#define __linux 1
-#endif
-
-#ifdef __unix__
-#undef __unix__
-#endif
-
-#ifdef __unix
-#undef __unix
-#endif
-
-/*
  * Define if we have <malloc.h> header
  */
 #define HAVE_MALLOC_H
@@ -214,134 +43,23 @@
 #define HAVE_ANDROID_OS 1
 
 /*
- * Define if we have Linux-style non-filesystem Unix Domain Sockets
- */
-#define HAVE_LINUX_LOCAL_SOCKET_NAMESPACE 1
-
-/*
- * Define if we have Linux's inotify in <sys/inotify.h>.
- */
-#define HAVE_INOTIFY 1
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-#define HAVE_MADVISE 1
-
-/*
- * Define if tm struct has tm_gmtoff field
- */
-#define HAVE_TM_GMTOFF 1
-
-/*
- * Define if dirent struct has d_type field
- */
-#define HAVE_DIRENT_D_TYPE 1
-
-/*
- * Define if libc includes Android system properties implementation.
- */
-#define HAVE_LIBC_SYSTEM_PROPERTIES 1
-
-/*
- * Define if system provides a system property server (should be
- * mutually exclusive with HAVE_LIBC_SYSTEM_PROPERTIES).
- */
-/* #define HAVE_SYSTEM_PROPERTY_SERVER */
-
-/*
- * What CPU architecture does this platform use?
- */
-#define ARCH_MIPS64 1
-
-/*
- * Define if the size of enums is as short as possible,
- */
-/* #define HAVE_SHORT_ENUMS */
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE unsigned char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
 
 /*
- * Is the filesystem case sensitive?
- */
-#define OS_CASE_SENSITIVE
-
-/*
- * Define if <sys/socket.h> exists.
- */
-#define HAVE_SYS_SOCKET_H 1
-
-/*
  * Define if the strlcpy() function exists on the system.
  */
 #define HAVE_STRLCPY 1
 
 /*
- * Define if the open_memstream() function exists on the system.
- */
-/* #define HAVE_OPEN_MEMSTREAM 1 */
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-#define HAVE_FUNOPEN 1
-
-/*
- * Define if prctl() exists
- */
-#define HAVE_PRCTL 1
-
-/*
- * Define if writev() exists
- */
-#define HAVE_WRITEV 1
-
-/*
  * Define if <stdint.h> exists.
  */
 #define HAVE_STDINT_H 1
 
 /*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H 1
-
-/*
- * Define if <sched.h> exists.
- */
-#define HAVE_SCHED_H 1
-
-/*
- * Define if pread() exists
- */
-#define HAVE_PREAD 1
-
-/*
- * Define if we have st_mtim in struct stat
- */
-#define HAVE_STAT_ST_MTIM 1
-
-/*
  * Define if printf() supports %zd for size_t arguments
  */
 #define HAVE_PRINTF_ZD 1
 
-/*
- * Whether or not _Unwind_Context is defined as a struct.
- */
-#define HAVE_UNWIND_CONTEXT_STRUCT 1
-
 #endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/linux-x86/AndroidConfig.h b/core/combo/include/arch/linux-x86/AndroidConfig.h
index 5523e49..a2897bc 100644
--- a/core/combo/include/arch/linux-x86/AndroidConfig.h
+++ b/core/combo/include/arch/linux-x86/AndroidConfig.h
@@ -33,113 +33,6 @@
  */
 
 /*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- *  -- combine HAVE_CREATETHREAD, HAVE_CREATEMUTEX, and HAVE__BEGINTHREADEX
- */
-#define HAVE_PTHREADS
-
-/*
- * Do we have the futex syscall?
- */
-
-#define HAVE_FUTEX
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#define HAVE_FORKEXEC
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
-#define HAVE_SYSV_IPC
-
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
-#define  HAVE_POSIX_FILEMAP
-
-/*
- * Define this if you have <termio.h>
- */
-#define  HAVE_TERMIO_H 1
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-#define  HAVE_SYS_SENDFILE_H 1
-
-/*
- * Define this if you build against MSVCRT.DLL
- */
-/* #define HAVE_MS_C_RUNTIME */
-
-/*
- * Define this if you have sys/uio.h
- */
-#define  HAVE_SYS_UIO_H 1
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-#define HAVE_SYMLINKS
-
-/*
- * Define this if we have localtime_r().
- */
-#define HAVE_LOCALTIME_R 1
-
-/*
- * Define this if we have gethostbyname_r().
- */
-#define HAVE_GETHOSTBYNAME_R
-
-/*
- * Define this if we have ioctl().
- */
-#define HAVE_IOCTL
-
-/*
- * Define this if we want to use WinSock.
- */
-/* #define HAVE_WINSOCK */
-
-/*
- * Define this if have clock_gettime() and friends
- */
-#define HAVE_POSIX_CLOCKS
-
-/*
- * Define this if we have linux style epoll()
- */
-#define HAVE_EPOLL
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#define HAVE_ENDIAN_H
-#define HAVE_LITTLE_ENDIAN
-
-/*
  * We need to choose between 32-bit and 64-bit off_t.  All of our code should
  * agree on the same size.  For desktop systems, use 64-bit values,
  * because some of our libraries (e.g. wxWidgets) expect to be built that way.
@@ -148,175 +41,23 @@
 #define _LARGEFILE_SOURCE 1
 
 /*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-#define HAVE_OFF64_T
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 1
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Defined if we have the gettid() system call.
- */
-/* #define HAVE_GETTID */
-
-/* 
- * Defined if we have the sched_setscheduler() call
- */
-#define HAVE_SCHED_SETSCHEDULER
-
-/*
- * Add any extra platform-specific defines here.
- */
-
-/*
  * Define if we have <malloc.h> header
  */
 #define HAVE_MALLOC_H
 
 /*
- * Define if we have Linux-style non-filesystem Unix Domain Sockets
- */
-
-/*
- * What CPU architecture does this platform use?
- */
-#define ARCH_X86
-
-
-/*
- * Define if we have Linux's inotify in <sys/inotify.h>.
- */
-/*#define HAVE_INOTIFY 1*/
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-#define HAVE_MADVISE 1
-
-/*
- * Define if tm struct has tm_gmtoff field
- */
-#define HAVE_TM_GMTOFF 1
-
-/*
- * Define if dirent struct has d_type field
- */
-#define HAVE_DIRENT_D_TYPE 1
-
-/*
- * Define if libc includes Android system properties implementation.
- */
-/* #define HAVE_LIBC_SYSTEM_PROPERTIES */
-
-/*
- * Define if system provides a system property server (should be
- * mutually exclusive with HAVE_LIBC_SYSTEM_PROPERTIES).
- */
-#define HAVE_SYSTEM_PROPERTY_SERVER
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE unsigned char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
 
 /*
- * Is the filesystem case sensitive?
- */
-#define OS_CASE_SENSITIVE
-
-/*
- * Define if <sys/socket.h> exists.
- */
-#define HAVE_SYS_SOCKET_H 1
-
-/*
- * Define if the strlcpy() function exists on the system.
- */
-/* #define HAVE_STRLCPY 1 */
-
-/*
- * Define if the open_memstream() function exists on the system.
- */
-#define HAVE_OPEN_MEMSTREAM 1
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-/* #define HAVE_FUNOPEN 1 */
-
-/*
- * Define if prctl() exists
- */
-#define HAVE_PRCTL 1
-
-/*
- * Define if writev() exists
- */
-#define HAVE_WRITEV 1
-
-/*
  * Define if <stdint.h> exists.
  */
 #define HAVE_STDINT_H 1
 
 /*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H 1
-
-/*
- * Define if <sched.h> exists.
- */
-#define HAVE_SCHED_H 1
-
-/*
- * Define if pread() exists
- */
-#define HAVE_PREAD 1
-
-/*
- * Define if we have st_mtim in struct stat
- */
-#define HAVE_STAT_ST_MTIM 1
-
-/*
  * Define if printf() supports %zd for size_t arguments
  */
 #define HAVE_PRINTF_ZD 1
 
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
- */
-#define HAVE_BSD_QSORT_R 0
-
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
- */
-#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8)
-#define HAVE_GNU_QSORT_R 1
-#else
-#define HAVE_GNU_QSORT_R 0
-#endif
-
 #endif /*_ANDROID_CONFIG_H*/
diff --git a/core/combo/include/arch/target_linux-x86/AndroidConfig.h b/core/combo/include/arch/target_linux-x86/AndroidConfig.h
index c267b2b..676913c 100644
--- a/core/combo/include/arch/target_linux-x86/AndroidConfig.h
+++ b/core/combo/include/arch/target_linux-x86/AndroidConfig.h
@@ -19,309 +19,33 @@
  */
 
 /*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- *  -- combine HAVE_CREATETHREAD, HAVE_CREATEMUTEX, and HAVE__BEGINTHREADEX
- */
-#define HAVE_PTHREADS
-
-/*
- * Do we have pthread_setname_np()?
- *
- * (HAVE_PTHREAD_SETNAME_NP is used by WebKit to enable a function with
- * the same name but different parameters, so we can't use that here.)
- */
-#define HAVE_ANDROID_PTHREAD_SETNAME_NP
-
-/*
- * Do we have the futex syscall?
- */
-#define HAVE_FUTEX
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#define HAVE_FORKEXEC
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
-#define HAVE_ANDROID_IPC 1
-
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
-#define  HAVE_POSIX_FILEMAP 1
-
-/*
- * Define this if you have <termio.h>
- */
-#define  HAVE_TERMIO_H 1
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-#define  HAVE_SYS_SENDFILE_H 1
-
-/*
- * Define this if you build against have Microsoft C runtime (MSVCRT.DLL)
- */
-/* #define HAVE_MS_C_RUNTIME */
-
-/*
- * Define this if you have sys/uio.h
- */
-#define  HAVE_SYS_UIO_H 1
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-#define HAVE_SYMLINKS 1
-
-/*
- * Define this if we have localtime_r().
- */
-/* #define HAVE_LOCALTIME_R 1 */
-
-/*
- * Define this if we have gethostbyname_r().
- */
-/* #define HAVE_GETHOSTBYNAME_R */
-
-/*
- * Define this if we have ioctl().
- */
-#define HAVE_IOCTL
-
-/*
- * Define this if we want to use WinSock.
- */
-/* #define HAVE_WINSOCK */
-
-/*
- * Define this if have clock_gettime() and friends
- *
- */
-#define HAVE_POSIX_CLOCKS
-
-/*
- * Define this if we have linux style epoll()
- */
-#define HAVE_EPOLL
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#define HAVE_ENDIAN_H
-#define HAVE_LITTLE_ENDIAN
-
-/*
- * We need to choose between 32-bit and 64-bit off_t.  All of our code should
- * agree on the same size.  For desktop systems, use 64-bit values,
- * because some of our libraries (e.g. wxWidgets) expect to be built that way.
- */
-#if __LP64__
-#define _FILE_OFFSET_BITS 64
-#endif
-/* #define _LARGEFILE_SOURCE 1 */
-
-/*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-#define HAVE_OFF64_T
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 0
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Defined if we have the gettid() system call.
- */
-#define HAVE_GETTID
-
-/* 
- * Defined if we have the sched_setscheduler() call
- */
-#define HAVE_SCHED_SETSCHEDULER
-
-/*
- * Add any extra platform-specific defines here.
- */
-#ifndef __linux__
-#define __linux__
-#endif
-
-/*
  * Define if we have <malloc.h> header
  */
 #define HAVE_MALLOC_H
 
-/* 
+/*
  * Define if we're running on *our* linux on device or emulator.
  */
 #define HAVE_ANDROID_OS 1
 
 /*
- * Define if we have Linux-style non-filesystem Unix Domain Sockets
- */
-#define HAVE_LINUX_LOCAL_SOCKET_NAMESPACE 1
-
-/*
- * Define if we have Linux's inotify in <sys/inotify.h>.
- */
-#define HAVE_INOTIFY 1
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-#define HAVE_MADVISE 1
-
-/*
- * Define if we have Linux's dbus 
- */
-/* #define HAVE_DBUS 1 */
-
-/*
- * Define if tm struct has tm_gmtoff field
- */
-#define HAVE_TM_GMTOFF 1
-
-/*
- * Define if dirent struct has d_type field
- */
-#define HAVE_DIRENT_D_TYPE 1
-
-/*
- * Define if libc includes Android system properties implementation.
- */
-#define HAVE_LIBC_SYSTEM_PROPERTIES 1
-
-/*
- * Define if system provides a system property server (should be
- * mutually exclusive with HAVE_LIBC_SYSTEM_PROPERTIES).
- */
-/* #define HAVE_SYSTEM_PROPERTY_SERVER */
-
-/*
- * What CPU architecture does this platform use?
- */
-#define ARCH_X86
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE unsigned char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
 
 /*
- * Is the filesystem case sensitive?
- */
-#define OS_CASE_SENSITIVE
-
-/*
- * Define if <sys/socket.h> exists.
- */
-#define HAVE_SYS_SOCKET_H 1
-
-/*
  * Define if the strlcpy() function exists on the system.
  */
 #define HAVE_STRLCPY 1
 
 /*
- * Define if the open_memstream() function exists on the system.
- */
-/* #define HAVE_OPEN_MEMSTREAM 1 */
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-#define HAVE_FUNOPEN 1
-
-/*
- * Define if prctl() exists
- */
-#define HAVE_PRCTL 1
-
-/*
- * Whether or not _Unwind_Context is defined as a struct.
- */
-#define HAVE_UNWIND_CONTEXT_STRUCT
-
-/*
  * Define if <stdint.h> exists.
  */
 #define HAVE_STDINT_H 1
 
 /*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H 1
-
-/*
- * Define if <sched.h> exists.
- */
-#define HAVE_SCHED_H 1
-
-/*
- * Define if pread() exists
- */
-#define HAVE_PREAD 1
-
-/*
- * Define if we have st_mtim in struct stat
- */
-#define HAVE_STAT_ST_MTIM 1
-
-/*
  * Define if printf() supports %zd for size_t arguments
  */
 #define HAVE_PRINTF_ZD 1
 
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
- */
-#define HAVE_BSD_QSORT_R 0
-
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
- */
-#define HAVE_GNU_QSORT_R 0
-
 #endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/windows/AndroidConfig.h b/core/combo/include/arch/windows/AndroidConfig.h
index 204740d..e7eb837 100644
--- a/core/combo/include/arch/windows/AndroidConfig.h
+++ b/core/combo/include/arch/windows/AndroidConfig.h
@@ -55,129 +55,22 @@
 #  endif
 #endif
 
-/*
- * Threading model.  Choose one:
- *
- * HAVE_PTHREADS - use the pthreads library.
- * HAVE_WIN32_THREADS - use Win32 thread primitives.
- */
-#define HAVE_WIN32_THREADS
-
-/*
- * Do we have the futex syscall?
- */
-
-/* #define HAVE_FUTEX */
-
-
-/*
- * Process creation model.  Choose one:
- *
- * HAVE_FORKEXEC - use fork() and exec()
- * HAVE_WIN32_PROC - use CreateProcess()
- */
-#ifdef __CYGWIN__
-#  define HAVE_FORKEXEC
-#else
-#  define HAVE_WIN32_PROC
-#endif
-
-/*
- * IPC model.  Choose one:
- *
- * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
- * HAVE_MACOSX_IPC - use Macintosh IPC mechanisms (sem_open, mmap).
- * HAVE_WIN32_IPC - use Win32 IPC (CreateSemaphore, CreateFileMapping).
- * HAVE_ANDROID_IPC - use Android versions (?, mmap).
- */
+/* TODO: replace references to this. */
 #define HAVE_WIN32_IPC
 
-/*
- * Memory-mapping model. Choose one:
- *
- * HAVE_POSIX_FILEMAP - use the Posix sys/mmap.h
- * HAVE_WIN32_FILEMAP - use Win32 filemaps
- */
 #ifdef __CYGWIN__
-#define  HAVE_POSIX_FILEMAP
-#else
-#define  HAVE_WIN32_FILEMAP
-#endif
-
-/*
- * Define this if you have <termio.h>
- */
-#ifdef __CYGWIN__
-#  define  HAVE_TERMIO_H
-#endif
-
-/*
- * Define this if you have <sys/sendfile.h>
- */
-#ifdef __CYGWIN__
-#  define  HAVE_SYS_SENDFILE_H 1
+#error "CYGWIN is unsupported for platform builds"
 #endif
 
 /*
  * Define this if you build against MSVCRT.DLL
  */
-#ifndef __CYGWIN__
-#  define HAVE_MS_C_RUNTIME
-#endif
-
-/*
- * Define this if you have sys/uio.h
- */
-#ifdef __CYGWIN__
-#define  HAVE_SYS_UIO_H
-#endif
-
-
-/*
- * Define this if we have localtime_r().
- */
-/* #define HAVE_LOCALTIME_R 1 */
-
-/*
- * Define this if we have gethostbyname_r().
- */
-/* #define HAVE_GETHOSTBYNAME_R */
-
-/*
- * Define this if we have ioctl().
- */
-/* #define HAVE_IOCTL */
+#define HAVE_MS_C_RUNTIME
 
 /*
  * Define this if we want to use WinSock.
  */
-#ifndef __CYGWIN__
 #define HAVE_WINSOCK
-#endif
-
-/*
- * Define this if your platforms implements symbolic links
- * in its filesystems
- */
-/* #define HAVE_SYMLINKS */
-
-/*
- * Define this if have clock_gettime() and friends
- */
-/* #define HAVE_POSIX_CLOCKS */
-
-/*
- * Endianness of the target machine.  Choose one:
- *
- * HAVE_ENDIAN_H -- have endian.h header we can include.
- * HAVE_LITTLE_ENDIAN -- we are little endian.
- * HAVE_BIG_ENDIAN -- we are big endian.
- */
-#ifdef __CYGWIN__
-#define HAVE_ENDIAN_H
-#endif
-
-#define HAVE_LITTLE_ENDIAN
 
 /*
  * We need to choose between 32-bit and 64-bit off_t.  All of our code should
@@ -188,50 +81,6 @@
 #define _LARGEFILE_SOURCE 1
 
 /*
- * Define if platform has off64_t (and lseek64 and other xxx64 functions)
- */
-#define HAVE_OFF64_T
-
-/*
- * Defined if we have the backtrace() call for retrieving a stack trace.
- * Needed for CallStack to operate; if not defined, CallStack is
- * non-functional.
- */
-#define HAVE_BACKTRACE 0
-
-/*
- * Defined if we have the cxxabi.h header for demangling C++ symbols.  If
- * not defined, stack crawls will be displayed with raw mangled symbols
- */
-#define HAVE_CXXABI 0
-
-/*
- * Define if tm struct has tm_gmtoff field
- */
-/* #define HAVE_TM_GMTOFF 1 */
-
-/*
- * Define if dirent struct has d_type field
- */
-/* #define HAVE_DIRENT_D_TYPE 1 */
-
-/*
- * Define if libc includes Android system properties implementation.
- */
-/* #define HAVE_LIBC_SYSTEM_PROPERTIES */
-
-/*
- * Define if system provides a system property server (should be
- * mutually exclusive with HAVE_LIBC_SYSTEM_PROPERTIES).
- */
-/* #define HAVE_SYSTEM_PROPERTY_SERVER */
-
-/*
- * Define if we have madvise() in <sys/mman.h>
- */
-/*#define HAVE_MADVISE 1*/
-
-/*
  * Add any extra platform-specific defines here.
  */
 #define WIN32 1                 /* stock Cygwin doesn't define these */
@@ -241,115 +90,15 @@
 #define HAVE_WINDOWS_PATHS      /* needed by simulator */
 
 /*
- * What CPU architecture does this platform use?
- */
-#define ARCH_X86
-
-/*
- * sprintf() format string for shared library naming.
- */
-#define OS_SHARED_LIB_FORMAT_STR    "lib%s.dll"
-
-/*
- * type for the third argument to mincore().
- */
-#define MINCORE_POINTER_TYPE unsigned char *
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '\\'
 
 /*
- * Is the filesystem case sensitive?
- */
-/* #define OS_CASE_SENSITIVE */
-
-/*
- * Define if <sys/socket.h> exists.
- * Cygwin has it, but not MinGW.
- */
-#ifdef USE_MINGW
-/* #define HAVE_SYS_SOCKET_H */
-#else
-#define HAVE_SYS_SOCKET_H 1
-#endif
-
-/*
- * Define if the strlcpy() function exists on the system.
- */
-/* #define HAVE_STRLCPY 1 */
-
-/*
- * Define if the open_memstream() function exists on the system.
- */
-/* #define HAVE_OPEN_MEMSTREAM 1 */
-
-/*
- * Define if the BSD funopen() function exists on the system.
- */
-/* #define HAVE_FUNOPEN 1 */
-
-/*
- * Define if <winsock2.h> exists.
- * Only MinGW has it.
- */
-#ifdef USE_MINGW
-#define HAVE_WINSOCK2_H 1
-#else
-/* #define HAVE_WINSOCK2_H */
-#endif
-
-/*
  * Various definitions missing in MinGW
  */
 #ifdef USE_MINGW
 #define S_IRGRP 0
 #endif
 
-/*
- * Define if writev() exists.
- */
-/* #define HAVE_WRITEV */
-
-/*
- * Define if <stdint.h> exists.
- */
-/* #define HAVE_STDINT_H */
-
-/*
- * Define if <stdbool.h> exists.
- */
-#define HAVE_STDBOOL_H
-
-/*
- * Define if <sched.h> exists.
- */
-/* #define HAVE_SCHED_H */
-
-/*
- * Define if pread() exists
- */
-/* #define HAVE_PREAD 1 */
-
-/*
- * Define if we have st_mtim in struct stat
- */
-/* #define HAVE_STAT_ST_MTIM 1 */
-
-/*
- * Define if printf() supports %zd for size_t arguments
- */
-/* #define HAVE_PRINTF_ZD 1 */
-
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a BSD style function prototype.
- */
-#define HAVE_BSD_QSORT_R 0
-
-/*
- * Define to 1 if <stdlib.h> provides qsort_r() with a GNU style function prototype.
- */
-#define HAVE_GNU_QSORT_R 0
-
 #endif /*_ANDROID_CONFIG_H*/
diff --git a/core/combo/javac.mk b/core/combo/javac.mk
index 7f91aa9..fb43ea4 100644
--- a/core/combo/javac.mk
+++ b/core/combo/javac.mk
@@ -9,11 +9,7 @@
 #   COMMON_JAVAC -- Java compiler command with common arguments
 #
 
-ifneq ($(LEGACY_USE_JAVA6),)
-common_jdk_flags := -target 1.5 -Xmaxerrs 9999999
-else
 common_jdk_flags := -source 1.7 -target 1.7 -Xmaxerrs 9999999
-endif
 
 # Use the indexer wrapper to index the codebase instead of the javac compiler
 ifeq ($(ALTERNATE_JAVAC),)
diff --git a/core/combo/select.mk b/core/combo/select.mk
index d495c6f..01f9322 100644
--- a/core/combo/select.mk
+++ b/core/combo/select.mk
@@ -33,22 +33,6 @@
 $(combo_var_prefix)AR := $(AR)
 $(combo_var_prefix)STRIP := $(STRIP)
 
-$(combo_var_prefix)BINDER_MINI := 0
-
-$(combo_var_prefix)HAVE_EXCEPTIONS := 0
-$(combo_var_prefix)HAVE_UNIX_FILE_PATH := 1
-$(combo_var_prefix)HAVE_WINDOWS_FILE_PATH := 0
-$(combo_var_prefix)HAVE_RTTI := 1
-$(combo_var_prefix)HAVE_CALL_STACKS := 1
-$(combo_var_prefix)HAVE_64BIT_IO := 1
-$(combo_var_prefix)HAVE_CLOCK_TIMERS := 1
-$(combo_var_prefix)HAVE_PTHREAD_RWLOCK := 1
-$(combo_var_prefix)HAVE_STRNLEN := 1
-$(combo_var_prefix)HAVE_STRERROR_R_STRRET := 1
-$(combo_var_prefix)HAVE_STRLCPY := 0
-$(combo_var_prefix)HAVE_STRLCAT := 0
-$(combo_var_prefix)HAVE_KERNEL_MODULES := 0
-
 $(combo_var_prefix)GLOBAL_CFLAGS := -fno-exceptions -Wno-multichar
 $(combo_var_prefix)RELEASE_CFLAGS := -O2 -g -fno-strict-aliasing
 $(combo_var_prefix)GLOBAL_CPPFLAGS :=
@@ -106,6 +90,11 @@
   endif
 endif
 
+# Stash the original values of CC and CXX so we can still use the non-wrapped
+# values later.
+$(combo_2nd_arch_prefix)CC_BARE := $($(combo_var_prefix)CC)
+$(combo_2nd_arch_prefix)CXX_BARE := $($(combo_var_prefix)CXX)
+
 # The C/C++ compiler can be wrapped by setting the CC/CXX_WRAPPER vars.
 ifdef CC_WRAPPER
   ifneq ($(CC_WRAPPER),$(firstword $($(combo_var_prefix)CC)))
diff --git a/core/config.mk b/core/config.mk
index bfa5610..0b76b53 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -69,10 +69,8 @@
 BUILD_HOST_STATIC_LIBRARY:= $(BUILD_SYSTEM)/host_static_library.mk
 BUILD_HOST_SHARED_LIBRARY:= $(BUILD_SYSTEM)/host_shared_library.mk
 BUILD_STATIC_LIBRARY:= $(BUILD_SYSTEM)/static_library.mk
-BUILD_RAW_STATIC_LIBRARY := $(BUILD_SYSTEM)/raw_static_library.mk
 BUILD_SHARED_LIBRARY:= $(BUILD_SYSTEM)/shared_library.mk
 BUILD_EXECUTABLE:= $(BUILD_SYSTEM)/executable.mk
-BUILD_RAW_EXECUTABLE:= $(BUILD_SYSTEM)/raw_executable.mk
 BUILD_HOST_EXECUTABLE:= $(BUILD_SYSTEM)/host_executable.mk
 BUILD_PACKAGE:= $(BUILD_SYSTEM)/package.mk
 BUILD_PHONY_PACKAGE:= $(BUILD_SYSTEM)/phony_package.mk
@@ -85,6 +83,7 @@
 BUILD_DROIDDOC:= $(BUILD_SYSTEM)/droiddoc.mk
 BUILD_COPY_HEADERS := $(BUILD_SYSTEM)/copy_headers.mk
 BUILD_NATIVE_TEST := $(BUILD_SYSTEM)/native_test.mk
+BUILD_NATIVE_BENCHMARK := $(BUILD_SYSTEM)/native_benchmark.mk
 BUILD_HOST_NATIVE_TEST := $(BUILD_SYSTEM)/host_native_test.mk
 
 BUILD_SHARED_TEST_LIBRARY := $(BUILD_SYSTEM)/shared_test_lib.mk
@@ -97,8 +96,6 @@
 BUILD_HOST_DALVIK_STATIC_JAVA_LIBRARY := $(BUILD_SYSTEM)/host_dalvik_static_java_library.mk
 
 
--include cts/build/config.mk
-
 # ###############################################################
 # Parse out any modifier targets.
 # ###############################################################
@@ -117,9 +114,15 @@
 COMMON_GLOBAL_CFLAGS:= -DANDROID -fmessage-length=0 -W -Wall -Wno-unused -Winit-self -Wpointer-arith
 COMMON_RELEASE_CFLAGS:= -DNDEBUG -UDEBUG
 
-COMMON_GLOBAL_CPPFLAGS:= $(COMMON_GLOBAL_CFLAGS) -Wsign-promo
+COMMON_GLOBAL_CPPFLAGS:= $(COMMON_GLOBAL_CFLAGS) -Wsign-promo -std=gnu++11
 COMMON_RELEASE_CPPFLAGS:= $(COMMON_RELEASE_CFLAGS)
 
+GLOBAL_CFLAGS_NO_OVERRIDE :=  \
+    -Werror=int-to-pointer-cast \
+    -Werror=pointer-to-int-cast \
+
+GLOBAL_CPPFLAGS_NO_OVERRIDE :=
+
 # Set the extensions used for various packages
 COMMON_PACKAGE_SUFFIX := .zip
 COMMON_JAVA_PACKAGE_SUFFIX := .jar
@@ -389,15 +392,19 @@
 else
 MKBOOTIMG := $(BOARD_CUSTOM_MKBOOTIMG)
 endif
-MKYAFFS2 := $(HOST_OUT_EXECUTABLES)/mkyaffs2image$(HOST_EXECUTABLE_SUFFIX)
 APICHECK := $(HOST_OUT_EXECUTABLES)/apicheck$(HOST_EXECUTABLE_SUFFIX)
 FS_GET_STATS := $(HOST_OUT_EXECUTABLES)/fs_get_stats$(HOST_EXECUTABLE_SUFFIX)
-MKEXT2IMG := $(HOST_OUT_EXECUTABLES)/genext2fs$(HOST_EXECUTABLE_SUFFIX)
 MAKE_EXT4FS := $(HOST_OUT_EXECUTABLES)/make_ext4fs$(HOST_EXECUTABLE_SUFFIX)
 MKEXTUSERIMG := $(HOST_OUT_EXECUTABLES)/mkuserimg.sh
+ifeq ($(HOST_OS),linux)
+MAKE_SQUASHFS := $(HOST_OUT_EXECUTABLES)/mksquashfs$(HOST_EXECUTABLE_SUFFIX)
+MKSQUASHFSUSERIMG := $(HOST_OUT_EXECUTABLES)/mksquashfsimage.sh
+else
+MAKE_SQUASHFS :=
+MKSQUASHFSUSERIMG :=
+endif
 MAKE_F2FS := $(HOST_OUT_EXECUTABLES)/make_f2fs$(HOST_EXECUTABLE_SUFFIX)
 MKF2FSUSERIMG := $(HOST_OUT_EXECUTABLES)/mkf2fsuserimg.sh
-MKEXT2BOOTIMG := external/genext2fs/mkbootimg_ext2.sh
 SIMG2IMG := $(HOST_OUT_EXECUTABLES)/simg2img$(HOST_EXECUTABLE_SUFFIX)
 E2FSCK := $(HOST_OUT_EXECUTABLES)/e2fsck$(HOST_EXECUTABLE_SUFFIX)
 MKTARBALL := build/tools/mktarball.sh
@@ -437,17 +444,7 @@
 COLUMN:= column
 endif
 
-ifeq ($(HOST_OS),darwin)
-ifeq ($(LEGACY_USE_JAVA6),)
 HOST_JDK_TOOLS_JAR:= $(shell $(BUILD_SYSTEM)/find-jdk-tools-jar.sh)
-else
-# Deliberately set to blank for Java 6 installations on MacOS. These
-# versions allegedly use a non-standard directory structure.
-HOST_JDK_TOOLS_JAR :=
-endif
-else
-HOST_JDK_TOOLS_JAR:= $(shell $(BUILD_SYSTEM)/find-jdk-tools-jar.sh)
-endif
 
 ifneq ($(HOST_JDK_TOOLS_JAR),)
 ifeq ($(wildcard $(HOST_JDK_TOOLS_JAR)),)
@@ -545,23 +542,23 @@
   TARGET_DEFAULT_JAVA_LIBRARIES := core-libart core-junit ext framework
 endif
 
-TARGET_CPU_SMP ?= true
-
 # Flags for DEX2OAT
 DEX2OAT_TARGET_ARCH := $(TARGET_ARCH)
-DEX2OAT_TARGET_CPU_VARIANT := $(TARGET_CPU_VARIANT)
-DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := default
-ifneq (,$(filter $(DEX2OAT_TARGET_CPU_VARIANT),cortex-a7 cortex-a15 krait denver))
-  DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := div
+ifeq ($(TARGET_CPU_VARIANT),)
+ifeq ($(TARGET_ARCH_VARIANT),)
+DEX2OAT_TARGET_CPU_VARIANT := default
+else
+DEX2OAT_TARGET_CPU_VARIANT := $(TARGET_ARCH_VARIANT)
 endif
+else
+DEX2OAT_TARGET_CPU_VARIANT := $(TARGET_CPU_VARIANT)
+endif
+DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := default
 
 ifdef TARGET_2ND_ARCH
 $(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH := $(TARGET_2ND_ARCH)
 $(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT := $(TARGET_2ND_CPU_VARIANT)
 $(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := default
-ifneq (,$(filter $($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT),cortex-a7 cortex-a15 krait denver))
-  $(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := div
-endif
 endif
 
 # define clang/llvm tools and global flags
@@ -616,4 +613,8 @@
 RS_PREBUILT_LIBPATH := -L prebuilts/ndk/8/platforms/android-9/arch-$(TARGET_ARCH)/usr/lib
 RS_PREBUILT_COMPILER_RT := prebuilts/sdk/renderscript/lib/$(TARGET_ARCH)/libcompiler_rt.a
 
+# API Level lists for Renderscript Compat lib.
+RSCOMPAT_32BIT_ONLY_API_LEVELS := 8 9 10 11 12 13 14 15 16 17 18 19 20
+RSCOMPAT_NO_USAGEIO_API_LEVELS := 8 9 10 11 12 13
+
 include $(BUILD_SYSTEM)/dumpvar.mk
diff --git a/core/config_sanitizers.mk b/core/config_sanitizers.mk
new file mode 100644
index 0000000..a1964a9
--- /dev/null
+++ b/core/config_sanitizers.mk
@@ -0,0 +1,32 @@
+##############################################
+## Perform configuration steps for sanitizers.
+##############################################
+
+# Configure SANITIZE_HOST.
+ifdef LOCAL_IS_HOST_MODULE
+ifeq ($(SANITIZE_HOST),true)
+ifneq ($(strip $(LOCAL_CLANG)),false)
+ifneq ($(strip $(LOCAL_ADDRESS_SANITIZER)),false)
+    LOCAL_ADDRESS_SANITIZER := true
+endif
+endif
+endif
+endif
+
+# Configure address sanitizer.
+ifeq ($(strip $(LOCAL_ADDRESS_SANITIZER)),true)
+  my_clang := true
+  # Frame pointer based unwinder in ASan requires ARM frame setup.
+  LOCAL_ARM_MODE := arm
+  my_cflags += $(ADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS)
+  my_ldflags += $(ADDRESS_SANITIZER_CONFIG_EXTRA_LDFLAGS)
+  ifdef LOCAL_IS_HOST_MODULE
+      my_ldflags += -fsanitize=address
+      # -nodefaultlibs (provided with libc++) prevents the driver from linking
+      # libraries needed with -fsanitize=address. http://b/18650275
+      my_ldlibs += -ldl -lpthread
+  else
+      my_shared_libraries += $(ADDRESS_SANITIZER_CONFIG_EXTRA_SHARED_LIBRARIES)
+      my_static_libraries += $(ADDRESS_SANITIZER_CONFIG_EXTRA_STATIC_LIBRARIES)
+  endif
+endif
diff --git a/core/cxx_stl_setup.mk b/core/cxx_stl_setup.mk
new file mode 100644
index 0000000..63e2069
--- /dev/null
+++ b/core/cxx_stl_setup.mk
@@ -0,0 +1,100 @@
+#############################################################
+## Set up flags based on LOCAL_CXX_STL.
+## Input variables: LOCAL_CXX_STL
+## Output variables: My_cflags, my_c_includes, my_shared_libraries, etc.
+#############################################################
+
+# Select the appropriate C++ STL
+ifeq ($(strip $(LOCAL_CXX_STL)),default)
+    ifndef LOCAL_SDK_VERSION
+        # Platform code. Select the appropriate STL.
+        ifndef USE_MINGW
+            my_cxx_stl := libc++
+            ifdef LOCAL_IS_HOST_MODULE
+                ifneq (,$(BUILD_HOST_static))
+                    my_cxx_stl := libc++_static
+                endif
+            endif
+        else
+            # libc++ is not supported on mingw.
+            my_cxx_stl := libstdc++
+        endif
+    else
+        my_cxx_stl := ndk
+    endif
+else
+    my_cxx_stl := $(strip $(LOCAL_CXX_STL))
+endif
+
+# Yes, this is actually what the clang driver does.
+HOST_linux_dynamic_gcclibs := -lgcc_s -lgcc -lc -lgcc_s -lgcc
+HOST_linux_static_gcclibs := -Wl,--start-group -lgcc -lgcc_eh -lc -Wl,--end-group
+HOST_darwin_dynamic_gcclibs := -lc -lSystem
+HOST_darwin_static_gcclibs := NO_STATIC_HOST_BINARIES_ON_DARWIN
+
+my_link_type := dynamic
+ifdef LOCAL_IS_HOST_MODULE
+    ifneq (,$(BUILD_HOST_static))
+        my_link_type := static
+    endif
+    ifeq (-static,$(filter -static,$(my_ldflags)))
+        my_link_type := static
+    endif
+else
+    ifeq (true,$(LOCAL_FORCE_STATIC_EXECUTABLE))
+        my_link_type := static
+    endif
+endif
+
+ifneq ($(filter $(my_cxx_stl),libc++ libc++_static),)
+    my_cflags += -D_USING_LIBCXX
+    my_c_includes += external/libcxx/include
+    ifeq ($(my_cxx_stl),libc++)
+        my_shared_libraries += libc++
+    else
+        my_static_libraries += libc++_static
+        ifndef LOCAL_IS_HOST_MODULE
+            ifeq ($(LOCAL_FORCE_STATIC_EXECUTABLE),true)
+                my_static_libraries += libm libc libdl
+            endif
+        endif
+    endif
+
+    ifdef LOCAL_IS_HOST_MODULE
+        my_cppflags += -nostdinc++
+        my_ldflags += -nodefaultlibs
+        my_ldlibs += -lpthread -lm
+        my_ldlibs += $($(my_prefix)$(HOST_OS)_$(my_link_type)_gcclibs)
+    endif
+else ifneq ($(filter $(my_cxx_stl),stlport stlport_static),)
+    ifndef LOCAL_IS_HOST_MODULE
+        my_c_includes += external/stlport/stlport bionic/libstdc++/include \
+                         bionic
+        ifeq ($(my_cxx_stl),stlport)
+            my_shared_libraries += libstdc++ libstlport
+        else
+            my_static_libraries += libstdc++ libstlport_static
+        endif
+    endif
+else ifeq ($(my_cxx_stl),ndk)
+    # Using an NDK STL. Handled farther up in this file.
+    ifndef LOCAL_IS_HOST_MODULE
+        my_system_shared_libraries += libstdc++
+    endif
+else ifeq ($(my_cxx_stl),libstdc++)
+    # Using bionic's basic libstdc++. Not actually an STL. Only around until the
+    # tree is in good enough shape to not need it.
+    ifndef LOCAL_IS_HOST_MODULE
+        my_c_includes += bionic/libstdc++/include
+        my_system_shared_libraries += libstdc++
+    endif
+    # Host builds will use GNU libstdc++.
+else ifeq ($(my_cxx_stl),none)
+    ifdef LOCAL_IS_HOST_MODULE
+        my_cppflags += -nostdinc++
+        my_ldflags += -nodefaultlibs
+        my_ldlibs += $($(my_prefix)$(HOST_OS)_$(my_link_type)_gcclibs)
+    endif
+else
+    $(error $(my_cxx_stl) is not a supported STL.)
+endif
diff --git a/core/definitions.mk b/core/definitions.mk
index 57fc434..f59b78e 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -884,8 +884,8 @@
 	-Wl,-rpath,\$$ORIGIN/../lib \
 	$(dir $@)/$(notdir $(<:.bc=.o)) \
 	$(RS_PREBUILT_COMPILER_RT) \
-	-o $@ $(TARGET_GLOBAL_LDFLAGS) -L prebuilts/gcc/ \
-	-L $(TARGET_OUT_INTERMEDIATE_LIBRARIES) $(RS_PREBUILT_LIBPATH) \
+	-o $@ $(TARGET_GLOBAL_LDFLAGS) -Wl,--hash-style=sysv -L prebuilts/gcc/ \
+	$(RS_PREBUILT_LIBPATH) -L $(TARGET_OUT_INTERMEDIATE_LIBRARIES) \
 	-lRSSupport -lm -lc
 endef
 
@@ -990,6 +990,8 @@
 	$(PRIVATE_CFLAGS) \
 	$(PRIVATE_CPPFLAGS) \
 	$(PRIVATE_DEBUG_CFLAGS) \
+	$(GLOBAL_CFLAGS_NO_OVERRIDE) \
+	$(GLOBAL_CPPFLAGS_NO_OVERRIDE) \
 	-MD -MF $(patsubst %.o,%.d,$@) -o $@ $<
 $(transform-d-to-p)
 endef
@@ -1013,6 +1015,7 @@
 	-c \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	    $(PRIVATE_TARGET_GLOBAL_CFLAGS) \
+	    $(PRIVATE_TARGET_GLOBAL_CONLYFLAGS) \
 	    $(PRIVATE_ARM_CFLAGS) \
 	 ) \
 	 $(1) \
@@ -1021,7 +1024,11 @@
 
 define transform-c-to-o-no-deps
 @echo "target $(PRIVATE_ARM_MODE) C: $(PRIVATE_MODULE) <= $<"
-$(call transform-c-or-s-to-o-no-deps, $(PRIVATE_CFLAGS) $(PRIVATE_CONLYFLAGS) $(PRIVATE_DEBUG_CFLAGS))
+$(call transform-c-or-s-to-o-no-deps, \
+    $(PRIVATE_CFLAGS) \
+    $(PRIVATE_CONLYFLAGS) \
+    $(PRIVATE_DEBUG_CFLAGS) \
+    $(GLOBAL_CFLAGS_NO_OVERRIDE))
 endef
 
 define transform-s-to-o-no-deps
@@ -1044,7 +1051,7 @@
 @mkdir -p $(dir $@)
 $(hide) $(YASM) \
     $(addprefix -I , $(PRIVATE_C_INCLUDES)) \
-    -f elf32 -m x86 \
+    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_YASM_FLAGS) \
     $(PRIVATE_ASFLAGS) \
     -o $@ $<
 endef
@@ -1111,6 +1118,7 @@
 	-c \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	    $(PRIVATE_HOST_GLOBAL_CFLAGS) \
+	    $(PRIVATE_HOST_GLOBAL_CONLYFLAGS) \
 	 ) \
 	$(1) \
 	-MD -MF $(patsubst %.o,%.d,$@) -o $@ $<
@@ -1150,6 +1158,64 @@
 $(transform-d-to-p)
 endef
 
+
+###########################################################
+## Rules to compile a single C/C++ source with ../ in the path
+###########################################################
+# Replace "../" in object paths with $(DOTDOT_REPLACEMENT).
+DOTDOT_REPLACEMENT := dotdot/
+
+## Rule to compile a C++ source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the C++ source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-cpp-file
+o := $(intermediates)/$(patsubst %$(LOCAL_CPP_EXTENSION),%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)cpp-to-o)
+-include $$(o:%.o=%.P)
+$(3) += $$(o)
+endef
+
+## Rule to compile a C source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the C source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-c-file
+o := $(intermediates)/$(patsubst %.c,%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)c-to-o)
+-include $$(o:%.o=%.P)
+$(3) += $$(o)
+endef
+
+## Rule to compile a .S source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the .S source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-s-file
+o := $(intermediates)/$(patsubst %.S,%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)s-to-o)
+-include $$(o:%.o=%.P)
+$(3) += $$(o)
+endef
+
+## Rule to compile a .s source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the .s source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-s-file-no-deps
+o := $(intermediates)/$(patsubst %.s,%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)s-to-o-no-deps)
+$(3) += $$(o)
+endef
+
 ###########################################################
 ## Commands for running ar
 ###########################################################
@@ -1176,22 +1242,41 @@
 
 # $(1): the full path of the source static library.
 define _extract-and-include-single-target-whole-static-lib
-@echo "preparing StaticLib: $(PRIVATE_MODULE) [including $(1)]"
+@echo "preparing StaticLib: $(PRIVATE_MODULE) [including $(strip $(1))]"
 $(hide) ldir=$(PRIVATE_INTERMEDIATES_DIR)/WHOLE/$(basename $(notdir $(1)))_objs;\
     rm -rf $$ldir; \
     mkdir -p $$ldir; \
+    cp $(1) $$ldir; \
+    lib_to_include=$$ldir/$(notdir $(1)); \
     filelist=; \
+    subdir=0; \
     for f in `$($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_AR) t $(1)`; do \
-        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_AR) p $(1) $$f > $$ldir/$$f; \
-        filelist="$$filelist $$ldir/$$f"; \
+        if [ -e $$ldir/$$f ]; then \
+            mkdir $$ldir/$$subdir; \
+            ext=$$subdir/; \
+            subdir=$$((subdir+1)); \
+            $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_AR) m $$lib_to_include $$f; \
+        else \
+            ext=; \
+        fi; \
+        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_AR) p $$lib_to_include $$f > $$ldir/$$ext$$f; \
+        filelist="$$filelist $$ldir/$$ext$$f"; \
     done ; \
     $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_AR) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_ARFLAGS) \
         $(PRIVATE_ARFLAGS) $@ $$filelist
 
 endef
 
+# $(1): the full path of the source static library.
+define extract-and-include-whole-static-libs-first
+$(if $(strip $(1)),
+@echo "preparing StaticLib: $(PRIVATE_MODULE) [including $(strip $(1))]"
+$(hide) cp $(1) $@)
+endef
+
 define extract-and-include-target-whole-static-libs
-$(foreach lib,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES), \
+$(call extract-and-include-whole-static-libs-first, $(firstword $(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)))
+$(foreach lib,$(wordlist 2,999,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)), \
     $(call _extract-and-include-single-target-whole-static-lib, $(lib)))
 endef
 
@@ -1213,14 +1298,25 @@
 
 # $(1): the full path of the source static library.
 define _extract-and-include-single-host-whole-static-lib
-@echo "preparing StaticLib: $(PRIVATE_MODULE) [including $(1)]"
+@echo "preparing StaticLib: $(PRIVATE_MODULE) [including $(strip $(1))]"
 $(hide) ldir=$(PRIVATE_INTERMEDIATES_DIR)/WHOLE/$(basename $(notdir $(1)))_objs;\
     rm -rf $$ldir; \
     mkdir -p $$ldir; \
+    cp $(1) $$ldir; \
+    lib_to_include=$$ldir/$(notdir $(1)); \
     filelist=; \
+    subdir=0; \
     for f in `$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) t $(1) | \grep '\.o$$'`; do \
-        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) p $(1) $$f > $$ldir/$$f; \
-        filelist="$$filelist $$ldir/$$f"; \
+        if [ -e $$ldir/$$f ]; then \
+           mkdir $$ldir/$$subdir; \
+           ext=$$subdir/; \
+           subdir=$$((subdir+1)); \
+           $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) m $$lib_to_include $$f; \
+        else \
+           ext=; \
+        fi; \
+        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) p $$lib_to_include $$f > $$ldir/$$ext$$f; \
+        filelist="$$filelist $$ldir/$$ext$$f"; \
     done ; \
     $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_ARFLAGS) \
         $(PRIVATE_ARFLAGS) $@ $$filelist
@@ -1228,7 +1324,8 @@
 endef
 
 define extract-and-include-host-whole-static-libs
-$(foreach lib,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES), \
+$(call extract-and-include-whole-static-libs-first, $(firstword $(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)))
+$(foreach lib,$(wordlist 2,999,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)), \
     $(call _extract-and-include-single-host-whole-static-lib, $(lib)))
 endef
 
@@ -1269,6 +1366,7 @@
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
+	$(if $(filter true,$(NATIVE_COVERAGE)),-lgcov) \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_LDLIBS)
@@ -1292,26 +1390,13 @@
 ## Commands for running gcc to link a shared library or package
 ###########################################################
 
-#echo >$@.vers "{"; \
-#echo >>$@.vers " global:"; \
-#$(BUILD_SYSTEM)/filter_symbols.sh $(TARGET_NM) "  " ";" $(filter %.o,$^) | sort -u >>$@.vers; \
-#echo >>$@.vers " local:"; \
-#echo >>$@.vers "  *;"; \
-#echo >>$@.vers "};"; \
-
-#	-Wl,--version-script=$@.vers \
-
-# ld just seems to be so finicky with command order that we allow
-# it to be overriden en-masse see combo/linux-arm.make for an example.
-ifneq ($(TARGET_CUSTOM_LD_COMMAND),true)
 define transform-o-to-shared-lib-inner
 $(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
-	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	-Wl,-rpath,\$$ORIGIN/../lib \
-	-Wl,-shared -Wl,-soname,$(notdir $@) \
-	$(PRIVATE_LDFLAGS) \
+	-nostdlib -Wl,-soname,$(notdir $@) \
+	-Wl,--gc-sections \
+	$(if $(filter true,$(PRIVATE_CLANG)),-shared,-Wl$(comma)-shared) \
 	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
+	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
 	$(PRIVATE_ALL_OBJECTS) \
 	-Wl,--whole-archive \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
@@ -1319,16 +1404,22 @@
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
+	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
+	$(PRIVATE_LDFLAGS) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(filter true,$(NATIVE_COVERAGE)),$(PRIVATE_TARGET_LIBGCOV)) \
+	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
 	$(PRIVATE_LDLIBS)
 endef
-endif
 
 define transform-o-to-shared-lib
 @mkdir -p $(dir $@)
 @echo "target SharedLib: $(PRIVATE_MODULE) ($@)"
-$($(PRIVATE_2ND_ARCH_VAR_PREFIX)transform-o-to-shared-lib-inner)
+$(transform-o-to-shared-lib-inner)
 endef
 
 
@@ -1344,7 +1435,8 @@
 define transform-to-stripped
 @mkdir -p $(dir $@)
 @echo "target Strip: $(PRIVATE_MODULE) ($@)"
-$(hide) $(PRIVATE_STRIP) --strip-all $< -o $@ $(TARGET_STRIP_EXTRA)
+$(hide) $(PRIVATE_STRIP) --strip-all $< -o $@ \
+  $(if $(PRIVATE_NO_DEBUGLINK),,$(TARGET_STRIP_EXTRA))
 endef
 
 define transform-to-stripped-keep-symbols
@@ -1360,14 +1452,15 @@
 ## Commands for running gcc to link an executable
 ###########################################################
 
-ifneq ($(TARGET_CUSTOM_LD_COMMAND),true)
 define transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) \
-	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
+$(hide) $(PRIVATE_CXX) -pie \
+	-nostdlib -Bdynamic \
+	-Wl,-dynamic-linker,$($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_LINKER) \
+	-Wl,--gc-sections \
+	-Wl,-z,nocopyreloc \
 	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
 	-Wl,-rpath-link=$(PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES) \
-	-Wl,-rpath,\$$ORIGIN/../lib \
-	$(PRIVATE_LDFLAGS) \
+	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O)) \
 	$(PRIVATE_ALL_OBJECTS) \
 	-Wl,--whole-archive \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
@@ -1375,35 +1468,65 @@
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
+	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
+	$(PRIVATE_LDFLAGS) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(filter true,$(NATIVE_COVERAGE)),$(PRIVATE_TARGET_LIBGCOV)) \
+	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
 	$(PRIVATE_LDLIBS)
 endef
-endif
 
 define transform-o-to-executable
 @mkdir -p $(dir $@)
 @echo "target Executable: $(PRIVATE_MODULE) ($@)"
-$($(PRIVATE_2ND_ARCH_VAR_PREFIX)transform-o-to-executable-inner)
+$(transform-o-to-executable-inner)
 endef
 
 
 ###########################################################
-## Commands for running gcc to link a statically linked
-## executable.  In practice, we only use this on arm, so
-## the other platforms don't have the
-## transform-o-to-static-executable defined
+## Commands for linking a static executable. In practice,
+## we only use this on arm, so the other platforms don't
+## have transform-o-to-static-executable defined.
+## Clang driver needs -static to create static executable.
+## However, bionic/linker uses -shared to overwrite.
+## Linker for x86 targets does not allow coexistance of -static and -shared,
+## so we add -static only if -shared is not used.
 ###########################################################
 
-ifneq ($(TARGET_CUSTOM_LD_COMMAND),true)
 define transform-o-to-static-executable-inner
+$(hide) $(PRIVATE_CXX) \
+	-nostdlib -Bstatic \
+	$(if $(filter $(PRIVATE_LDFLAGS),-shared),,-static) \
+	-Wl,--gc-sections \
+	-o $@ \
+	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
+	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_STATIC_O)) \
+	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
+	$(PRIVATE_LDFLAGS) \
+	$(PRIVATE_ALL_OBJECTS) \
+	-Wl,--whole-archive \
+	$(call normalize-target-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
+	-Wl,--no-whole-archive \
+	$(call normalize-target-libraries,$(filter-out %libcompiler_rt.a,$(filter-out %libc_nomalloc.a,$(filter-out %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))))) \
+	-Wl,--start-group \
+	$(call normalize-target-libraries,$(filter %libc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
+	$(call normalize-target-libraries,$(filter %libc_nomalloc.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(filter true,$(NATIVE_COVERAGE)),$(PRIVATE_TARGET_LIBGCOV)) \
+	$(call normalize-target-libraries,$(filter %libcompiler_rt.a,$(PRIVATE_ALL_STATIC_LIBRARIES))) \
+	$(PRIVATE_TARGET_LIBGCC) \
+	-Wl,--end-group \
+	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
 endef
-endif
 
 define transform-o-to-static-executable
 @mkdir -p $(dir $@)
 @echo "target StaticExecutable: $(PRIVATE_MODULE) ($@)"
-$($(PRIVATE_2ND_ARCH_VAR_PREFIX)transform-o-to-static-executable-inner)
+$(transform-o-to-static-executable-inner)
 endef
 
 
@@ -1430,13 +1553,13 @@
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
+	$(if $(filter true,$(NATIVE_COVERAGE)),-lgcov) \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-Wl,-rpath-link=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES) \
 	-Wl,-rpath,\$$ORIGIN/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES)) \
 	$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LD_DIRS) \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 		$(PRIVATE_HOST_GLOBAL_LDFLAGS) \
-		$(HOST_FPIE_FLAGS) \
 	) \
 	$(PRIVATE_LDFLAGS) \
 	-o $@ \
@@ -1612,6 +1735,7 @@
         jar -cfm $@ $(dir $@)/manifest.mf \
             -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) ., \
     $(hide) jar -cf $@ -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .)
+$(if $(PRIVATE_EXTRA_JAR_ARGS),$(call add-java-resources-to,$@))
 endef
 
 define transform-java-to-classes.jar
@@ -1672,6 +1796,7 @@
         jar -cfm $@ $(dir $@)/manifest.mf \
             -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) ., \
     $(hide) jar -cf $@ -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .)
+$(if $(PRIVATE_EXTRA_JAR_ARGS),$(call add-java-resources-to,$@))
 $(hide) mv $(PRIVATE_CLASS_INTERMEDIATES_DIR)/newstamp $(PRIVATE_CLASS_INTERMEDIATES_DIR)/stamp
 endef
 
@@ -1713,10 +1838,21 @@
 # so we need to give it something.
 define create-empty-package
 @mkdir -p $(dir $@)
-$(hide) touch $(dir $@)dummy
-$(hide) (cd $(dir $@) && jar cf $(notdir $@) dummy)
-$(hide) zip -qd $@ dummy
-$(hide) rm $(dir $@)dummy
+$(hide) touch $(dir $@)zipdummy
+$(hide) (cd $(dir $@) && jar cf $(notdir $@) zipdummy)
+$(hide) zip -qd $@ zipdummy
+$(hide) rm $(dir $@)zipdummy
+endef
+
+# Copy an arhchive file and delete any class files and empty folders inside.
+# $(1): the source archive file.
+# $(2): the destination archive file.
+define initialize-package-file
+@mkdir -p $(dir $(2))
+$(hide) cp -f $(1) $(2)
+$(hide) zip -qd $(2) "*.class" \
+    $(if $(strip $(PRIVATE_DONT_DELETE_JAR_DIRS)),,"*/") \
+    || true # Ignore the error when nothing to delete.
 endef
 
 #TODO: we kinda want to build different asset packages for
@@ -1760,7 +1896,7 @@
 $(foreach abi,$(PRIVATE_JNI_SHARED_LIBRARIES_ABI),\
   $(call _add-jni-shared-libs-to-package-per-abi,$(abi),\
     $(patsubst $(abi):%,%,$(filter $(abi):%,$(PRIVATE_JNI_SHARED_LIBRARIES)))))
-$(hide) (cd $(dir $@) && zip -r $(notdir $@) lib)
+$(hide) (cd $(dir $@) && zip -r $(PRIVATE_JNI_SHARED_LIBRARIES_ZIP_OPTIONS) $(notdir $@) lib)
 $(hide) rm -rf $(dir $@)lib
 endef
 
@@ -1770,24 +1906,12 @@
 endef
 
 # Add java resources added by the current module.
+# $(1) destination package
 #
-define add-java-resources-to-package
-$(call dump-words-to-file, $(PRIVATE_EXTRA_JAR_ARGS), $(dir $@)jar-arg-list)
-$(hide) jar uf $@ @$(dir $@)jar-arg-list
-@rm -f $(dir $@)jar-arg-list
-endef
-
-# Add java resources carried by static Java libraries.
-#
-define add-carried-java-resources
-$(hide) if [ -d $(PRIVATE_CLASS_INTERMEDIATES_DIR) ] ; then \
-    java_res_jar_flags=$$(find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -type f -a -not -name "*.class" \
-        | sed -e "s?^$(PRIVATE_CLASS_INTERMEDIATES_DIR)/? -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) ?"); \
-    if [ -n "$$java_res_jar_flags" ] ; then \
-        echo $$java_res_jar_flags >$(dir $@)java_res_jar_flags; \
-        jar uf $@ $$java_res_jar_flags; \
-    fi; \
-fi
+define add-java-resources-to
+$(call dump-words-to-file, $(PRIVATE_EXTRA_JAR_ARGS), $(1).jar-arg-list)
+$(hide) jar uf $(1) @$(1).jar-arg-list
+@rm -f $(1).jar-arg-list
 endef
 
 # Sign a package using the specified key/cert.
@@ -1800,12 +1924,15 @@
 $(hide) mv $@.signed $@
 endef
 
-# Align STORED entries of a package on 4-byte boundaries
-# to make them easier to mmap.
+# Align STORED entries of a package on 4-byte boundaries to make them easier to mmap.
 #
 define align-package
 $(hide) mv $@ $@.unaligned
-$(hide) $(ZIPALIGN) -f 4 $@.unaligned $@.aligned
+$(hide) $(ZIPALIGN) \
+    -f \
+    $(if $(findstring true, $(PRIVATE_PAGE_ALIGN_JNI_SHARED_LIBRARIES)),-p ,) \
+    4 \
+    $@.unaligned $@.aligned
 $(hide) mv $@.aligned $@
 endef
 
@@ -1831,7 +1958,6 @@
 define transform-host-java-to-package
 @echo "host Java: $(PRIVATE_MODULE) ($(PRIVATE_CLASS_INTERMEDIATES_DIR))"
 $(call compile-java,$(HOST_JAVAC),$(PRIVATE_BOOTCLASSPATH))
-$(if $(PRIVATE_EXTRA_JAR_ARGS), $(call add-java-resources-to-package))
 endef
 
 ###########################################################
@@ -2211,6 +2337,7 @@
 
 # Include any vendor specific definitions.mk file
 -include $(TOPDIR)vendor/*/build/core/definitions.mk
+-include $(TOPDIR)device/*/build/core/definitions.mk
 
 # broken:
 #	$(foreach file,$^,$(if $(findstring,.a,$(suffix $file)),-l$(file),$(file)))
diff --git a/core/dex_preopt.mk b/core/dex_preopt.mk
index 8a19b66..8b555e0 100644
--- a/core/dex_preopt.mk
+++ b/core/dex_preopt.mk
@@ -3,8 +3,6 @@
 #
 ####################################
 
-ifneq ($(DALVIK_VM_LIB),)
-
 # list of boot classpath jars for dexpreopt
 DEXPREOPT_BOOT_JARS := $(subst $(space),:,$(PRODUCT_BOOT_JARS))
 DEXPREOPT_BOOT_JARS_MODULES := $(PRODUCT_BOOT_JARS)
@@ -18,6 +16,9 @@
 DEXPREOPT_BOOT_JAR_DIR := system/framework
 DEXPREOPT_BOOT_JAR_DIR_FULL_PATH := $(DEXPREOPT_PRODUCT_DIR_FULL_PATH)/$(DEXPREOPT_BOOT_JAR_DIR)
 
+# The default value for LOCAL_DEX_PREOPT
+DEX_PREOPT_DEFAULT ?= true
+
 # $(1): the .jar or .apk to remove classes.dex
 define dexpreopt-remove-classes.dex
 $(hide) zip --quiet --delete $(1) classes.dex; \
@@ -46,36 +47,17 @@
 
 $(foreach b,$(DEXPREOPT_BOOT_JARS_MODULES),$(eval $(call _dexpreopt-boot-jar-remove-classes.dex,$(b))))
 
-# Conditionally include Dalvik support.
-ifeq ($(DALVIK_VM_LIB),libdvm.so)
-include $(BUILD_SYSTEM)/dex_preopt_libdvm.mk
-endif
-
-# Unconditionally include ART support because its used run dex2oat on the host for tests.
 include $(BUILD_SYSTEM)/dex_preopt_libart.mk
 
 # Define dexpreopt-one-file based on current default runtime.
 # $(1): the input .jar or .apk file
 # $(2): the output .odex file
-ifeq ($(DALVIK_VM_LIB),libdvm.so)
-define dexpreopt-one-file
-$(call dexopt-one-file,$(1),$(2))
-endef
-
-DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS := $(DEXOPT_DEPENDENCY)
-DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT := $(DEXPREOPT_BOOT_ODEXS)
-else
 define dexpreopt-one-file
 $(call dex2oat-one-file,$(1),$(2))
 endef
 
-DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS := $(DEX2OATD_DEPENDENCY)
+DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS := $(DEX2OAT_DEPENDENCY)
 DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT := $(DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME)
 ifdef TARGET_2ND_ARCH
 $(TARGET_2ND_ARCH_VAR_PREFIX)DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT := $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME)
 endif  # TARGET_2ND_ARCH
-endif  # DALVIK_VM_LIB
-else
-$(warning No DALVIK_VM_LIB, disable dexpreopt.)
-WITH_DEXPREOPT := false
-endif  # DALVIK_VM_LIB is defined.
diff --git a/core/dex_preopt_libart.mk b/core/dex_preopt_libart.mk
index cfbf221..fb62e0c 100644
--- a/core/dex_preopt_libart.mk
+++ b/core/dex_preopt_libart.mk
@@ -24,6 +24,13 @@
 COMPILED_CLASSES := $(call word-colon,1,$(firstword \
     $(filter %system/etc/compiled-classes,$(PRODUCT_COPY_FILES))))
 
+# Default to debug version to help find bugs.
+# Set USE_DEX2OAT_DEBUG to false for only building non-debug versions.
+ifneq ($(USE_DEX2OAT_DEBUG), false)
+DEX2OAT = $(DEX2OATD)
+DEX2OAT_DEPENDENCY = $(DEX2OATD_DEPENDENCY)
+endif
+
 # start of image reserved address space
 LIBART_IMG_HOST_BASE_ADDRESS   := 0x60000000
 LIBART_IMG_TARGET_BASE_ADDRESS := 0x70000000
@@ -37,7 +44,7 @@
 DEX2OAT_XMS := $(call get-product-default-property,dalvik.vm.dex2oat-Xms)
 DEX2OAT_XMX := $(call get-product-default-property,dalvik.vm.dex2oat-Xmx)
 
-ifeq ($(TARGET_ARCH),mips)
+ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),mips mips64))
 # MIPS specific overrides.
 # For MIPS the ART image is loaded at a lower address. This causes issues
 # with the image overlapping with memory on the host cross-compiling and
@@ -55,7 +62,7 @@
 # $(1): the arch name.
 # $(2): the full path (including file name) of the corresponding .jar or .apk.
 define get-odex-file-path
-$(dir $(2))$(1)/$(basename $(notdir $(2))).odex
+$(dir $(2))oat/$(1)/$(basename $(notdir $(2))).odex
 endef
 
 # Returns the path to the image file (such as "/system/framework/<arch>/boot.art"
@@ -88,7 +95,7 @@
 define dex2oat-one-file
 $(hide) rm -f $(2)
 $(hide) mkdir -p $(dir $(2))
-$(hide) $(DEX2OATD) \
+$(hide) $(DEX2OAT) \
 	--runtime-arg -Xms$(DEX2OAT_XMS) --runtime-arg -Xmx$(DEX2OAT_XMX) \
 	--boot-image=$(PRIVATE_DEX_PREOPT_IMAGE_LOCATION) \
 	--dex-file=$(1) \
@@ -96,7 +103,9 @@
 	--oat-file=$(2) \
 	--android-root=$(PRODUCT_OUT)/system \
 	--instruction-set=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH) \
+	--instruction-set-variant=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT) \
 	--instruction-set-features=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) \
 	--include-patch-information --runtime-arg -Xnorelocate --no-include-debug-symbols \
+	--abort-on-hard-verifier-error \
 	$(PRIVATE_DEX_PREOPT_FLAGS)
 endef
diff --git a/core/dex_preopt_libart_boot.mk b/core/dex_preopt_libart_boot.mk
index 6c6e0ad..2569d73 100644
--- a/core/dex_preopt_libart_boot.mk
+++ b/core/dex_preopt_libart_boot.mk
@@ -27,10 +27,7 @@
 # The .oat with symbols
 $(my_2nd_arch_prefix)LIBART_TARGET_BOOT_OAT_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)$(patsubst %.art,%.oat,$($(my_2nd_arch_prefix)LIBART_BOOT_IMAGE_FILENAME))
 
-$(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_INSTALLED_IMAGE :=
-ifneq ($(PRODUCT_DEX_PREOPT_IMAGE_IN_DATA),true)
 $(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_INSTALLED_IMAGE := $(PRODUCT_OUT)$($(my_2nd_arch_prefix)LIBART_BOOT_IMAGE_FILENAME)
-endif
 
 # Compile boot.oat as position-independent code if WITH_DEXPREOPT_PIC=true
 ifeq (true,$(WITH_DEXPREOPT_PIC))
@@ -50,11 +47,11 @@
 
 $($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME): PRIVATE_2ND_ARCH_VAR_PREFIX := $(my_2nd_arch_prefix)
 # Use dex2oat debug version for better error reporting
-$($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME) : $(LIBART_TARGET_BOOT_DEX_FILES) $(DEX2OATD_DEPENDENCY)
+$($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME) : $(LIBART_TARGET_BOOT_DEX_FILES) $(DEX2OAT_DEPENDENCY)
 	@echo "target dex2oat: $@ ($?)"
 	@mkdir -p $(dir $@)
 	@mkdir -p $(dir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_TARGET_BOOT_OAT_UNSTRIPPED))
-	$(hide) $(DEX2OATD) --runtime-arg -Xms$(DEX2OAT_IMAGE_XMS) --runtime-arg -Xmx$(DEX2OAT_IMAGE_XMX) \
+	$(hide) $(DEX2OAT) --runtime-arg -Xms$(DEX2OAT_IMAGE_XMS) --runtime-arg -Xmx$(DEX2OAT_IMAGE_XMX) \
 		--image-classes=$(PRELOADED_CLASSES) \
 		$(addprefix --dex-file=,$(LIBART_TARGET_BOOT_DEX_FILES)) \
 		$(addprefix --dex-location=,$(LIBART_TARGET_BOOT_DEX_LOCATIONS)) \
@@ -63,6 +60,7 @@
 		--oat-location=$(patsubst %.art,%.oat,$($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_BOOT_IMAGE_FILENAME)) \
 		--image=$@ --base=$(LIBART_IMG_TARGET_BASE_ADDRESS) \
 		--instruction-set=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH) \
+		--instruction-set-variant=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT) \
 		--instruction-set-features=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) \
 		--android-root=$(PRODUCT_OUT)/system --include-patch-information --runtime-arg -Xnorelocate --no-include-debug-symbols \
 		$(PRODUCT_DEX_PREOPT_BOOT_FLAGS) $(COMPILED_CLASSES_FLAGS)
diff --git a/core/dex_preopt_libdvm.mk b/core/dex_preopt_libdvm.mk
deleted file mode 100644
index 23a54e1e..0000000
--- a/core/dex_preopt_libdvm.mk
+++ /dev/null
@@ -1,76 +0,0 @@
-####################################
-# dexpreopt support for Dalvik
-#
-####################################
-
-DEXOPT := $(HOST_OUT_EXECUTABLES)/dexopt$(HOST_EXECUTABLE_SUFFIX)
-DEXPREOPT := dalvik/tools/dex-preopt
-
-DEXPREOPT_DEXOPT := $(patsubst $(DEXPREOPT_BUILD_DIR)/%,%,$(DEXOPT))
-
-DEXPREOPT_BOOT_ODEXS := $(foreach b,$(DEXPREOPT_BOOT_JARS_MODULES),\
-    $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(b).odex)
-
-# If the target is a uniprocessor, then explicitly tell the preoptimizer
-# that fact. (By default, it always optimizes for an SMP target.)
-ifeq ($(TARGET_CPU_SMP),true)
-    DEXPREOPT_UNIPROCESSOR :=
-else
-    DEXPREOPT_UNIPROCESSOR := --uniprocessor
-endif
-
-# By default, do not run rerun dexopt if the tool changes.
-# Comment out the | to force dex2oat to rerun on after all changes.
-DEXOPT_DEPENDENCY := |
-DEXOPT_DEPENDENCY += $(DEXPREOPT) $(DEXOPT)
-
-# $(1): the input .jar or .apk file
-# $(2): the output .odex file
-define dexopt-one-file
-$(hide) rm -f $(2)
-$(hide) mkdir -p $(dir $(2))
-$(hide) $(DEXPREOPT) \
-        --dexopt=$(DEXPREOPT_DEXOPT) \
-        --build-dir=$(DEXPREOPT_BUILD_DIR) \
-        --product-dir=$(DEXPREOPT_PRODUCT_DIR) \
-        --boot-dir=$(DEXPREOPT_BOOT_JAR_DIR) \
-        --boot-jars=$(DEXPREOPT_BOOT_JARS) \
-        $(DEXPREOPT_UNIPROCESSOR) \
-        $(patsubst $(DEXPREOPT_BUILD_DIR)/%,%,$(1)) \
-        $(patsubst $(DEXPREOPT_BUILD_DIR)/%,%,$(2))
-endef
-
-# Special rules for building odex files for boot jars that override java_library.mk rules
-
-# $(1): boot jar module name
-define _dexpreopt-boot-odex
-_dbj_jar := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(1).jar
-_dbj_odex := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(1).odex
-_dbj_src_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,$(1),,COMMON)/javalib.jar
-$$(_dbj_odex): PRIVATE_DBJ_JAR := $$(_dbj_jar)
-$$(_dbj_odex) : $$(_dbj_src_jar) | $(ACP) $(DEXPREOPT) $(DEXOPT)
-	@echo "Dexpreopt Boot Jar: $$@"
-	$(hide) mkdir -p $$(dir $$(PRIVATE_DBJ_JAR)) && $(ACP) -fp $$< $$(PRIVATE_DBJ_JAR)
-	$$(call dexopt-one-file,$$(PRIVATE_DBJ_JAR),$$@)
-
-_dbj_jar :=
-_dbj_odex :=
-_dbj_src_jar :=
-endef
-
-$(foreach b,$(DEXPREOPT_BOOT_JARS_MODULES),$(eval $(call _dexpreopt-boot-odex,$(b))))
-
-# $(1): the rest list of boot jars
-define _build-dexpreopt-boot-jar-dependency-pair
-$(if $(filter 1,$(words $(1)))$(filter 0,$(words $(1))),,\
-	$(eval _bdbjdp_target := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(word 2,$(1)).odex) \
-	$(eval _bdbjdp_dep := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(word 1,$(1)).odex) \
-	$(eval $(call add-dependency,$(_bdbjdp_target),$(_bdbjdp_dep))) \
-	$(eval $(call _build-dexpreopt-boot-jar-dependency-pair,$(wordlist 2,999,$(1)))))
-endef
-
-define _build-dexpreopt-boot-jar-dependency
-$(call _build-dexpreopt-boot-jar-dependency-pair,$(DEXPREOPT_BOOT_JARS_MODULES))
-endef
-
-$(eval $(call _build-dexpreopt-boot-jar-dependency))
diff --git a/core/dex_preopt_odex_install.mk b/core/dex_preopt_odex_install.mk
index cb38261..73c8146 100644
--- a/core/dex_preopt_odex_install.mk
+++ b/core/dex_preopt_odex_install.mk
@@ -33,10 +33,6 @@
 ifeq (,$(strip $(built_dex)$(my_prebuilt_src_file))) # contains no java code
 LOCAL_DEX_PREOPT :=
 endif
-# if module oat file requested in data, disable LOCAL_DEX_PREOPT, will default location to dalvik-cache
-ifneq (,$(filter $(LOCAL_MODULE),$(PRODUCT_DEX_PREOPT_PACKAGES_IN_DATA)))
-LOCAL_DEX_PREOPT :=
-endif
 # if WITH_DEXPREOPT_BOOT_IMG_ONLY=true and module is not in boot class path skip
 ifeq (true,$(WITH_DEXPREOPT_BOOT_IMG_ONLY))
 ifeq ($(filter $(DEXPREOPT_BOOT_JARS_MODULES),$(LOCAL_MODULE)),)
@@ -50,28 +46,21 @@
 ifdef LOCAL_DEX_PREOPT
 dexpreopt_boot_jar_module := $(filter $(DEXPREOPT_BOOT_JARS_MODULES),$(LOCAL_MODULE))
 ifdef dexpreopt_boot_jar_module
-ifeq ($(DALVIK_VM_LIB),libdvm.so)
-built_odex := $(basename $(LOCAL_BUILT_MODULE)).odex
-installed_odex := $(basename $(LOCAL_INSTALLED_MODULE)).odex
-built_installed_odex := $(built_odex):$(installed_odex)
-else # libdvm.so
 # For libart, the boot jars' odex files are replaced by $(DEFAULT_DEX_PREOPT_INSTALLED_IMAGE).
 # We use this installed_odex trick to get boot.art installed.
 installed_odex := $(DEFAULT_DEX_PREOPT_INSTALLED_IMAGE)
 # Append the odex for the 2nd arch if we have one.
 installed_odex += $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_INSTALLED_IMAGE)
-endif # libdvm.so
 else  # boot jar
-ifeq ($(DALVIK_VM_LIB),libdvm.so)
-built_odex := $(basename $(LOCAL_BUILT_MODULE)).odex
-installed_odex := $(basename $(LOCAL_INSTALLED_MODULE)).odex
-built_installed_odex := $(built_odex):$(installed_odex)
-
-$(built_odex) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT) \
-                $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS)
-else # libart
 ifeq ($(LOCAL_MODULE_CLASS),JAVA_LIBRARIES)
-# For a Java library, we build odex for both 1st arch and 2nd arch, if we have one.
+# For a Java library, by default we build odex for both 1st arch and 2nd arch.
+# But it can be overridden with "LOCAL_MULTILIB := first".
+ifneq (,$(filter $(PRODUCT_SYSTEM_SERVER_JARS),$(LOCAL_MODULE)))
+# For system server jars, we build for only "first".
+my_module_multilib := first
+else
+my_module_multilib := $(LOCAL_MULTILIB)
+endif
 # #################################################
 # Odex for the 1st arch
 my_2nd_arch_prefix :=
@@ -79,8 +68,10 @@
 # #################################################
 # Odex for the 2nd arch
 ifdef TARGET_2ND_ARCH
+ifneq (first,$(my_module_multilib))
 my_2nd_arch_prefix := $(TARGET_2ND_ARCH_VAR_PREFIX)
 include $(BUILD_SYSTEM)/setup_one_odex.mk
+endif  # my_module_multilib is not first.
 endif  # TARGET_2ND_ARCH
 # #################################################
 else  # must be APPS
@@ -95,7 +86,6 @@
 endif  # LOCAL_MULTILIB is both
 endif  # TARGET_2ND_ARCH
 endif  # LOCAL_MODULE_CLASS
-endif  # libart
 endif  # boot jar
 
 ifdef built_odex
diff --git a/core/droiddoc.mk b/core/droiddoc.mk
index d3e61d5..41f135c 100644
--- a/core/droiddoc.mk
+++ b/core/droiddoc.mk
@@ -154,7 +154,14 @@
 # TODO: not clear if this is used any more
 $(full_target): PRIVATE_LOCAL_PATH := $(LOCAL_PATH)
 
-$(full_target): $(full_src_files) $(droiddoc_templates) $(droiddoc) $(html_dir_files) $(full_java_lib_deps) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(full_target): \
+        $(full_src_files) \
+        $(droiddoc_templates) \
+        $(droiddoc) \
+        $(html_dir_files) \
+        $(full_java_lib_deps) \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	@echo Docs droiddoc: $(PRIVATE_OUT_DIR)
 	$(hide) mkdir -p $(dir $@)
 	$(call prepare-doc-source-list,$(PRIVATE_SRC_LIST_FILE),$(PRIVATE_JAVA_FILES), \
diff --git a/core/dynamic_binary.mk b/core/dynamic_binary.mk
index 08fb176..cf06a3d 100644
--- a/core/dynamic_binary.mk
+++ b/core/dynamic_binary.mk
@@ -88,18 +88,21 @@
   my_strip_module := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_STRIP_MODULE)
 endif
 
-ifeq ($(my_strip_module),true)
-# Strip the binary
-$(strip_output): PRIVATE_STRIP := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_STRIP)
-$(strip_output): PRIVATE_OBJCOPY := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_OBJCOPY)
-$(strip_output): $(strip_input) | $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_STRIP)
-	$(transform-to-stripped)
-else
-ifeq ($(my_strip_module),keep_symbols)
-# Strip only the debug frames, but leave the symbol table.
 $(strip_output): PRIVATE_STRIP := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_STRIP)
 $(strip_output): PRIVATE_OBJCOPY := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_OBJCOPY)
 $(strip_output): PRIVATE_READELF := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_READELF)
+ifeq ($(my_strip_module),no_debuglink)
+$(strip_output): PRIVATE_NO_DEBUGLINK := true
+else
+$(strip_output): PRIVATE_NO_DEBUGLINK :=
+endif
+
+ifneq ($(filter true no_debuglink,$(my_strip_module)),)
+# Strip the binary
+$(strip_output): $(strip_input) | $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_STRIP)
+	$(transform-to-stripped)
+else ifeq ($(my_strip_module),keep_symbols)
+# Strip only the debug frames, but leave the symbol table.
 $(strip_output): $(strip_input) | $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_STRIP)
 	$(transform-to-stripped-keep-symbols)
 
@@ -126,7 +129,6 @@
 	@echo "target Unstripped: $(PRIVATE_MODULE) ($@)"
 	$(copy-file-to-target-with-cp)
 endif
-endif
 endif # my_strip_module
 
 
diff --git a/core/envsetup.mk b/core/envsetup.mk
index ad78be3..ee04557 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -58,7 +58,7 @@
 # Under Linux, if USE_MINGW is set, we change HOST_OS to Windows to build the
 # Windows SDK. Only a subset of tools and SDK will manage to build properly.
 ifeq ($(HOST_OS),linux)
-ifneq ($(USE_MINGW),)
+ifdef USE_MINGW
   HOST_OS := windows
 endif
 endif
@@ -67,24 +67,15 @@
 $(error Unable to determine HOST_OS from uname -sm: $(UNAME)!)
 endif
 
-# TODO: Replace BUILD_HOST_64bit with a flag that forces 32-bit build,
-# after we default to 64-bit host build.
-ifeq (,$(BUILD_HOST_64bit))
-# Default to 32-bit-by-default multilib host build.
-HOST_PREFER_32_BIT := true
-endif
-
 # HOST_ARCH
 ifneq (,$(findstring x86_64,$(UNAME)))
   HOST_ARCH := x86_64
   HOST_2ND_ARCH := x86
   HOST_IS_64_BIT := true
-endif
-
-ifeq ($(HOST_PREFER_32_BIT),true)
-SDK_HOST_ARCH := x86
 else
-SDK_HOST_ARCH := $(HOST_ARCH)
+ifneq (,$(findstring x86,$(UNAME)))
+$(error Building on a 32-bit x86 host is not supported: $(UNAME)!)
+endif
 endif
 
 BUILD_ARCH := $(HOST_ARCH)
@@ -144,6 +135,17 @@
 $(error must be empty or one of: eng user userdebug)
 endif
 
+# Build host as 32-bit for SDK build.
+ifneq ($(filter $(MAKECMDGOALS),win_sdk sdk),)
+HOST_PREFER_32_BIT := true
+endif
+ifdef USE_MINGW
+# We only build sdk host tools in the MinGW windows build.
+# Build it as 32-bit as well.
+HOST_PREFER_32_BIT := true
+endif
+SDK_HOST_ARCH := x86
+
 # Boards may be defined under $(SRC_TARGET_DIR)/board/$(TARGET_DEVICE)
 # or under vendor/*/$(TARGET_DEVICE).  Search in both places, but
 # make sure only one exists.
@@ -398,8 +400,6 @@
 TARGET_INSTALLER_ROOT_OUT := $(TARGET_INSTALLER_OUT)/root
 TARGET_INSTALLER_SYSTEM_OUT := $(TARGET_INSTALLER_OUT)/root/system
 
-TARGET_FACTORY_RAMDISK_OUT := $(PRODUCT_OUT)/factory_ramdisk
-
 COMMON_MODULE_CLASSES := TARGET-NOTICE_FILES HOST-NOTICE_FILES HOST-JAVA_LIBRARIES
 
 ifeq (,$(strip $(DIST_DIR)))
diff --git a/core/executable_internal.mk b/core/executable_internal.mk
index 9325287..ebb6867 100644
--- a/core/executable_internal.mk
+++ b/core/executable_internal.mk
@@ -35,6 +35,7 @@
 
 # Define PRIVATE_ variables from global vars
 my_target_global_ld_dirs := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_LD_DIRS)
+my_target_libgcov := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_LIBGCOV)
 my_target_libgcc := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_LIBGCC)
 my_target_libatomic := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_LIBATOMIC)
 my_target_crtbegin_dynamic_o := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_CRTBEGIN_DYNAMIC_O)
@@ -54,6 +55,7 @@
 endif
 $(linked_module): PRIVATE_TARGET_GLOBAL_LD_DIRS := $(my_target_global_ld_dirs)
 $(linked_module): PRIVATE_TARGET_GLOBAL_LDFLAGS := $(my_target_global_ldflags)
+$(linked_module): PRIVATE_TARGET_LIBGCOV := $(my_target_libgcov)
 $(linked_module): PRIVATE_TARGET_LIBGCC := $(my_target_libgcc)
 $(linked_module): PRIVATE_TARGET_LIBATOMIC := $(my_target_libatomic)
 $(linked_module): PRIVATE_TARGET_CRTBEGIN_DYNAMIC_O := $(my_target_crtbegin_dynamic_o)
@@ -62,8 +64,10 @@
 $(linked_module): PRIVATE_TARGET_OUT_INTERMEDIATE_LIBRARIES := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)
 
 ifeq ($(LOCAL_FORCE_STATIC_EXECUTABLE),true)
+$(linked_module): PRIVATE_POST_LINK_CMD := $(LOCAL_POST_LINK_CMD)
 $(linked_module): $(my_target_crtbegin_static_o) $(all_objects) $(all_libraries) $(my_target_crtend_o)
 	$(transform-o-to-static-executable)
+	$(PRIVATE_POST_LINK_CMD)
 else
 $(linked_module): $(my_target_crtbegin_dynamic_o) $(all_objects) $(all_libraries) $(my_target_crtend_o)
 	$(transform-o-to-executable)
diff --git a/core/find-jdk-tools-jar.sh b/core/find-jdk-tools-jar.sh
index f150a9a..0224829 100755
--- a/core/find-jdk-tools-jar.sh
+++ b/core/find-jdk-tools-jar.sh
@@ -2,7 +2,13 @@
 if [ "x$ANDROID_JAVA_HOME" != x ] && [ -e "$ANDROID_JAVA_HOME/lib/tools.jar" ] ; then
     echo $ANDROID_JAVA_HOME/lib/tools.jar
 else
-    JAVAC=$(which javac)
+    JAVAC=$(realpath $(which javac) 2>/dev/null)
+    if [ -z "$JAVAC" ]; then
+        JAVAC=$(readlink -f $(which javac) 2>/dev/null)
+    fi
+    if [ -z "$JAVAC" ]; then
+        JAVAC=$(which javac)
+    fi
     if [ -z "$JAVAC" ] ; then
         exit 1
     fi
diff --git a/core/host_dalvik_java_library.mk b/core/host_dalvik_java_library.mk
index 61eb3ff..f8264ee 100644
--- a/core/host_dalvik_java_library.mk
+++ b/core/host_dalvik_java_library.mk
@@ -20,6 +20,7 @@
 # They will be compiled against libcore and not the host JRE.
 #
 
+ifeq ($(HOST_OS),linux)
 USE_CORE_LIB_BOOTCLASSPATH := true
 
 #######################################
@@ -69,8 +70,14 @@
 $(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES :=
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_PACKAGES :=
 $(full_classes_compiled_jar): PRIVATE_RMTYPEDEFS :=
-$(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) \
-        $(jar_manifest_file) $(proto_java_sources_file_stamp) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(full_classes_compiled_jar): \
+        $(java_sources) \
+        $(java_resource_sources) \
+        $(full_java_lib_deps) \
+        $(jar_manifest_file) \
+        $(proto_java_sources_file_stamp) \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-host-java-to-package)
 
 # Run jarjar if necessary, otherwise just copy the file.
@@ -95,13 +102,13 @@
 	$(transform-classes.jar-to-dex)
 
 $(LOCAL_BUILT_MODULE): PRIVATE_DEX_FILE := $(built_dex)
+$(LOCAL_BUILT_MODULE): PRIVATE_SOURCE_ARCHIVE := $(full_classes_jarjar_jar)
+$(LOCAL_BUILT_MODULE): PRIVATE_DONT_DELETE_JAR_DIRS := $(LOCAL_DONT_DELETE_JAR_DIRS)
 $(LOCAL_BUILT_MODULE): $(built_dex) $(java_resource_sources)
 	@echo "Host Jar: $(PRIVATE_MODULE) ($@)"
-	$(create-empty-package)
+	$(call initialize-package-file,$(PRIVATE_SOURCE_ARCHIVE),$@)
 	$(add-dex-to-package)
-	$(add-carried-java-resources)
-ifneq ($(extra_jar_args),)
-	$(add-java-resources-to-package)
-endif
 
 USE_CORE_LIB_BOOTCLASSPATH :=
+
+endif
diff --git a/core/host_dalvik_static_java_library.mk b/core/host_dalvik_static_java_library.mk
index 3ae74e4..9e5aaa3 100644
--- a/core/host_dalvik_static_java_library.mk
+++ b/core/host_dalvik_static_java_library.mk
@@ -19,6 +19,7 @@
 # These libraries will be compiled against libcore and not the host
 # JRE.
 #
+ifeq ($(HOST_OS),linux)
 
 USE_CORE_LIB_BOOTCLASSPATH := true
 LOCAL_JAVA_LIBRARIES += core-libart-hostdex
@@ -26,3 +27,5 @@
 include $(BUILD_SYSTEM)/host_java_library.mk
 
 USE_CORE_LIB_BOOTCLASSPATH :=
+
+endif
diff --git a/core/host_executable.mk b/core/host_executable.mk
index bf3cde1..0091f3f 100644
--- a/core/host_executable.mk
+++ b/core/host_executable.mk
@@ -13,6 +13,10 @@
 endif
 endif
 
+ifeq ($(LOCAL_NO_FPIE),)
+LOCAL_LDFLAGS += $(HOST_FPIE_FLAGS)
+endif
+
 ifeq ($(my_module_multilib),both)
 ifeq ($(LOCAL_MODULE_PATH_32)$(LOCAL_MODULE_STEM_32),)
 $(error $(LOCAL_PATH): LOCAL_MODULE_STEM_32 or LOCAL_MODULE_PATH_32 is required for LOCAL_MULTILIB := both for module $(LOCAL_MODULE))
diff --git a/core/host_java_library.mk b/core/host_java_library.mk
index 7e0e437..b751c5f 100644
--- a/core/host_java_library.mk
+++ b/core/host_java_library.mk
@@ -79,6 +79,12 @@
 $(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES :=
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_PACKAGES :=
 $(full_classes_compiled_jar): PRIVATE_RMTYPEDEFS :=
-$(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) \
-		$(jar_manifest_file) $(proto_java_sources_file_stamp) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(full_classes_compiled_jar): \
+        $(java_sources) \
+        $(java_resource_sources) \
+        $(full_java_lib_deps) \
+        $(jar_manifest_file) \
+        $(proto_java_sources_file_stamp) \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-host-java-to-package)
diff --git a/core/host_java_library_common.mk b/core/host_java_library_common.mk
index 973afa0..cd9e679 100644
--- a/core/host_java_library_common.mk
+++ b/core/host_java_library_common.mk
@@ -29,12 +29,12 @@
 proto_sources := $(filter %.proto,$(LOCAL_SRC_FILES))
 ifneq ($(proto_sources),)
 ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),micro)
-    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-2.3.0-micro
+    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-micro
 else
   ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
-    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-2.3.0-nano
+    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-nano
   else
-    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-2.3.0-lite
+    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-lite
   endif
 endif
 endif
diff --git a/core/host_shared_library_internal.mk b/core/host_shared_library_internal.mk
index d9769d3..f1b3311 100644
--- a/core/host_shared_library_internal.mk
+++ b/core/host_shared_library_internal.mk
@@ -40,7 +40,11 @@
 
 include $(BUILD_SYSTEM)/binary.mk
 
-$(LOCAL_BUILT_MODULE): $(all_objects) $(all_libraries) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(LOCAL_BUILT_MODULE): \
+        $(all_objects) \
+        $(all_libraries) \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-host-o-to-shared-lib)
 
 endif  # skip_build_from_source
diff --git a/core/host_test_internal.mk b/core/host_test_internal.mk
index 691468d..e0070c1 100644
--- a/core/host_test_internal.mk
+++ b/core/host_test_internal.mk
@@ -12,10 +12,4 @@
 LOCAL_CFLAGS += -DGTEST_HAS_STD_STRING -O0 -g
 LOCAL_C_INCLUDES +=  external/gtest/include
 
-ifneq ($(filter libc++,$(LOCAL_SHARED_LIBRARIES)),)
-LOCAL_STATIC_LIBRARIES += libgtest_libc++_host libgtest_main_libc++_host
-else
 LOCAL_STATIC_LIBRARIES += libgtest_host libgtest_main_host
-LOCAL_SHARED_LIBRARIES +=
-endif
-
diff --git a/core/java.mk b/core/java.mk
index a969254..cd90f03 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -42,12 +42,12 @@
 proto_sources := $(filter %.proto,$(LOCAL_SRC_FILES))
 ifneq ($(proto_sources),)
 ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),micro)
-    LOCAL_STATIC_JAVA_LIBRARIES += libprotobuf-java-2.3.0-micro
+    LOCAL_STATIC_JAVA_LIBRARIES += libprotobuf-java-micro
 else
   ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
-    LOCAL_STATIC_JAVA_LIBRARIES += libprotobuf-java-2.3.0-nano
+    LOCAL_STATIC_JAVA_LIBRARIES += libprotobuf-java-nano
   else
-    LOCAL_STATIC_JAVA_LIBRARIES += libprotobuf-java-2.3.0-lite
+    LOCAL_STATIC_JAVA_LIBRARIES += libprotobuf-java-lite
   endif
 endif
 endif
@@ -193,13 +193,30 @@
 
 ifneq ($(LOCAL_RENDERSCRIPT_COMPATIBILITY),)
 bc_files := $(patsubst %.fs,%.bc, $(patsubst %.rs,%.bc, $(notdir $(renderscript_sources))))
+
+
+ifeq ($(filter $(RSCOMPAT_32BIT_ONLY_API_LEVELS),$(renderscript_target_api)),)
+ifeq ($(TARGET_IS_64_BIT),true)
+renderscript_intermediate.bc_folder := $(renderscript_intermediate.COMMON)/res/raw/bc64/
+else
+renderscript_intermediate.bc_folder := $(renderscript_intermediate.COMMON)/res/raw/bc32/
+endif
+else
+renderscript_intermediate.bc_folder := $(renderscript_intermediate.COMMON)/res/raw/
+endif
+
 rs_generated_bc := $(addprefix \
-    $(renderscript_intermediate.COMMON)/res/raw/, $(bc_files))
+    $(renderscript_intermediate.bc_folder), $(bc_files))
 
 renderscript_intermediate := $(intermediates)/renderscript
 
 # We don't need the .so files in bundled branches
 # Prevent these from showing up on the device
+# One exception is librsjni.so, which is needed for
+# both native path and compat path.
+rs_jni_lib := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/librsjni.so
+LOCAL_JNI_SHARED_LIBRARIES += librsjni
+
 ifneq (,$(TARGET_BUILD_APPS)$(FORCE_BUILD_RS_COMPAT))
 
 rs_compatibility_jni_libs := $(addprefix \
@@ -209,17 +226,22 @@
 $(rs_generated_bc) : $(RenderScript_file_stamp)
 
 rs_support_lib := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/libRSSupport.so
-rs_jni_lib := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/librsjni.so
-LOCAL_JNI_SHARED_LIBRARIES += libRSSupport librsjni
+LOCAL_JNI_SHARED_LIBRARIES += libRSSupport
 
+rs_support_io_lib :=
+# check if the target api level support USAGE_IO
+ifeq ($(filter $(RSCOMPAT_NO_USAGEIO_API_LEVELS),$(renderscript_target_api)),)
+rs_support_io_lib := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/libRSSupportIO.so
+LOCAL_JNI_SHARED_LIBRARIES += libRSSupportIO
+endif
 
 
 $(rs_compatibility_jni_libs): $(RenderScript_file_stamp) $(RS_PREBUILT_CLCORE) \
-    $(rs_support_lib) $(rs_jni_lib) $(rs_compiler_rt)
+    $(rs_support_lib) $(rs_support_io_lib) $(rs_jni_lib) $(rs_compiler_rt)
 $(rs_compatibility_jni_libs): $(BCC_COMPAT)
 $(rs_compatibility_jni_libs): PRIVATE_CXX := $(TARGET_CXX)
 $(rs_compatibility_jni_libs): $(renderscript_intermediate)/librs.%.so: \
-    $(renderscript_intermediate.COMMON)/res/raw/%.bc
+    $(renderscript_intermediate.bc_folder)%.bc
 	$(transform-bc-to-so)
 
 endif
@@ -340,9 +362,16 @@
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_PACKAGES := $(LOCAL_JAR_EXCLUDE_PACKAGES)
 $(full_classes_compiled_jar): PRIVATE_RMTYPEDEFS := $(LOCAL_RMTYPEDEFS)
 $(full_classes_compiled_jar): PRIVATE_DONT_DELETE_JAR_META_INF := $(LOCAL_DONT_DELETE_JAR_META_INF)
-$(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) \
-        $(jar_manifest_file) $(layers_file) $(RenderScript_file_stamp) \
-        $(proto_java_sources_file_stamp) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(full_classes_compiled_jar): \
+        $(java_sources) \
+        $(java_resource_sources) \
+        $(full_java_lib_deps) \
+        $(jar_manifest_file) \
+        $(layers_file) \
+        $(RenderScript_file_stamp) \
+        $(proto_java_sources_file_stamp) \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-java-to-classes.jar)
 
 $(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
diff --git a/core/java_library.mk b/core/java_library.mk
index dffc7d9..b4e3eaa 100644
--- a/core/java_library.mk
+++ b/core/java_library.mk
@@ -58,9 +58,6 @@
 endif
 	@echo "target Static Jar: $(PRIVATE_MODULE) ($@)"
 	$(copy-file-to-target)
-ifneq ($(extra_jar_args),)
-	$(add-java-resources-to-package)
-endif
 
 $(LOCAL_BUILT_MODULE): $(common_javalib.jar)
 	$(copy-file-to-target)
@@ -68,14 +65,12 @@
 else # !LOCAL_IS_STATIC_JAVA_LIBRARY
 
 $(common_javalib.jar): PRIVATE_DEX_FILE := $(built_dex)
+$(common_javalib.jar): PRIVATE_SOURCE_ARCHIVE := $(full_classes_jarjar_jar)
+$(common_javalib.jar): PRIVATE_DONT_DELETE_JAR_DIRS := $(LOCAL_DONT_DELETE_JAR_DIRS)
 $(common_javalib.jar) : $(built_dex) $(java_resource_sources)
 	@echo "target Jar: $(PRIVATE_MODULE) ($@)"
-	$(create-empty-package)
+	$(call initialize-package-file,$(PRIVATE_SOURCE_ARCHIVE),$@)
 	$(add-dex-to-package)
-	$(add-carried-java-resources)
-ifneq ($(extra_jar_args),)
-	$(add-java-resources-to-package)
-endif
 
 ifdef LOCAL_DEX_PREOPT
 ifneq ($(dexpreopt_boot_jar_module),) # boot jar
@@ -85,12 +80,6 @@
 	$(call copy-file-to-target)
 
 # For libart boot jars, we don't have .odex files.
-ifeq ($(DALVIK_VM_LIB),libdvm.so)
-dexpreopted_boot_odex := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$(dexpreopt_boot_jar_module).odex
-$(built_odex) : $(dexpreopted_boot_odex) | $(ACP)
-	$(call copy-file-to-target)
-endif
-
 else # ! boot jar
 $(built_odex): PRIVATE_MODULE := $(LOCAL_MODULE)
 # Use pattern rule - we may have multiple built odex files.
diff --git a/core/main.mk b/core/main.mk
index 9d6e233..13465e3 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -79,7 +79,8 @@
     cacheimage-nodeps \
     vendorimage-nodeps \
     ramdisk-nodeps \
-    bootimage-nodeps
+    bootimage-nodeps \
+    recoveryimage-nodeps
 
 ifneq ($(filter $(dont_bother_goals), $(MAKECMDGOALS)),)
 dont_bother := true
@@ -92,6 +93,9 @@
 # and host information.
 include $(BUILD_SYSTEM)/config.mk
 
+# CTS-specific config.
+-include cts/build/config.mk
+
 # This allows us to force a clean build - included after the config.mk
 # environment setup is done, but before we generate any dependencies.  This
 # file does the rm -rf inline so the deps which are all done below will
@@ -140,18 +144,18 @@
 javac_version_str := $(shell unset _JAVA_OPTIONS && javac -version 2>&1)
 
 # Check for the correct version of java, should be 1.7 by
-# default, and 1.6 if LEGACY_USE_JAVA6 is set.
-ifeq ($(LEGACY_USE_JAVA6),)
+# default, and 1.8 if EXPERIMENTAL_USE_JAVA8 is set
+ifneq ($(EXPERIMENTAL_USE_JAVA8),)
+required_version := "1.8.x"
+required_javac_version := "1.8"
+java_version := $(shell echo '$(java_version_str)' | grep 'openjdk .*[ "]1\.8[\. "$$]')
+javac_version := $(shell echo '$(javac_version_str)' | grep '[ "]1\.8[\. "$$]')
+else # default
 required_version := "1.7.x"
 required_javac_version := "1.7"
 java_version := $(shell echo '$(java_version_str)' | grep '^java .*[ "]1\.7[\. "$$]')
 javac_version := $(shell echo '$(javac_version_str)' | grep '[ "]1\.7[\. "$$]')
-else # if LEGACY_USE_JAVA6
-required_version := "1.6.x"
-required_javac_version := "1.6"
-java_version := $(shell echo '$(java_version_str)' | grep '^java .*[ "]1\.6[\. "$$]')
-javac_version := $(shell echo '$(javac_version_str)' | grep '[ "]1\.6[\. "$$]')
-endif # if LEGACY_USE_JAVA6
+endif # if EXPERIMENTAL_USE_JAVA8
 
 ifeq ($(strip $(java_version)),)
 $(info ************************************************************)
@@ -170,13 +174,10 @@
 # Check for the current JDK.
 #
 # For Java 1.7, we require OpenJDK on linux and Oracle JDK on Mac OS.
-# For Java 1.6, we require Oracle for all host OSes.
 requires_openjdk := false
-ifeq ($(LEGACY_USE_JAVA6),)
 ifeq ($(HOST_OS), linux)
 requires_openjdk := true
 endif
-endif
 
 
 # Check for the current jdk
@@ -277,8 +278,8 @@
 ifneq ($(filter-out $(INTERNAL_VALID_VARIANTS),$(TARGET_BUILD_VARIANT)),)
 $(info ***************************************************************)
 $(info ***************************************************************)
-$(info Invalid variant: $(TARGET_BUILD_VARIANT)
-$(info Valid values are: $(INTERNAL_VALID_VARIANTS)
+$(info Invalid variant: $(TARGET_BUILD_VARIANT))
+$(info Valid values are: $(INTERNAL_VALID_VARIANTS))
 $(info ***************************************************************)
 $(info ***************************************************************)
 $(error stopping)
@@ -308,9 +309,19 @@
 is_sdk_build := true
 endif
 
-ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_ARCH).features=$(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES)
+# Add build properties for ART. These define system properties used by installd
+# to pass flags to dex2oat.
+ADDITIONAL_BUILD_PROPERTIES += persist.sys.dalvik.vm.lib.2=libart
+ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_ARCH).variant=$(DEX2OAT_TARGET_CPU_VARIANT)
+ifneq ($(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES),)
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_ARCH).features=$(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES)
+endif
+
 ifdef TARGET_2ND_ARCH
-ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_2ND_ARCH).features=$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES)
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_2ND_ARCH).variant=$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT)
+  ifneq ($($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES),)
+    ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_2ND_ARCH).features=$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES)
+  endif
 endif
 
 ## user/userdebug ##
@@ -325,23 +336,19 @@
   ifeq ($(user_variant),userdebug)
     # Pick up some extra useful tools
     tags_to_install += debug
-
-    # Enable Dalvik lock contention logging for userdebug builds.
-    ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.lockprof.threshold=500
   else
     # Disable debugging in plain user builds.
     enable_target_debugging :=
   endif
 
-  # Turn on Dalvik preoptimization for libdvm.so user builds, but only if not
+  # Turn on Dalvik preoptimization for user builds, but only if not
   # explicitly disabled and the build is running on Linux (since host
   # Dalvik isn't built for non-Linux hosts).
   ifeq (,$(WITH_DEXPREOPT))
-    ifeq ($(DALVIK_VM_LIB),libdvm.so)
-      ifeq ($(user_variant),user)
-        ifeq ($(HOST_OS),linux)
-          WITH_DEXPREOPT := true
-        endif
+    ifeq ($(user_variant),user)
+      ifeq ($(HOST_OS),linux)
+        # TODO: turn on WITH_DEXPREOPT for libart user builds.
+        # WITH_DEXPREOPT := true
       endif
     endif
   endif
@@ -361,6 +368,8 @@
 ifeq (true,$(strip $(enable_target_debugging)))
   # Target is more debuggable and adbd is on by default
   ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=1
+  # Enable Dalvik lock contention logging.
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.lockprof.threshold=500
   # Include the debugging/testing OTA keys in this build.
   INCLUDE_TEST_OTA_KEYS := true
 else # !enable_target_debugging
@@ -379,11 +388,12 @@
           ro.setupwizard.mode=OPTIONAL
 endif
 ifndef is_sdk_build
-  # Don't even verify the image on eng builds to speed startup
-  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.image-dex2oat-filter=verify-none
-  # Don't compile apps on eng builds to speed startup
-  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.dex2oat-filter=interpret-only
+  # Don't verify or compile the image on eng builds to speed startup.
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.image-dex2oat-filter=verify-at-runtime
+  # Don't verify or compile apps on eng builds to speed startup.
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.dex2oat-filter=verify-at-runtime
 endif
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.usejit=true
 endif
 
 ## sdk ##
@@ -408,16 +418,6 @@
 
 BUILD_WITHOUT_PV := true
 
-## precise GC ##
-
-ifneq ($(filter dalvik.gc.type-precise,$(PRODUCT_TAGS)),)
-  # Enabling type-precise GC results in larger optimized DEX files.  The
-  # additional storage requirements for ".odex" files can cause /system
-  # to overflow on some devices, so this is configured separately for
-  # each product.
-  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.dexopt-flags=m=y
-endif
-
 ADDITIONAL_BUILD_PROPERTIES += net.bt.name=Android
 
 # enable vm tracing in files for now to help track
@@ -771,10 +771,6 @@
   $(foreach m, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES), \
     $(if $(strip $(ALL_MODULES.$(m).INSTALLED) $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).INSTALLED)),,\
       $(eval dangling_modules += $(m))))
-  ifneq ($(TARGET_IS_64_BIT),true)
-    # We know those 64-bit modules don't exist in the 32-bit SDK build.
-    dangling_modules := $(filter-out %64,$(dangling_modules))
-  endif
   ifneq ($(dangling_modules),)
     $(warning: Modules '$(dangling_modules)' in PRODUCT_PACKAGES have nothing to install!)
   endif
@@ -848,12 +844,6 @@
 .PHONY: ramdisk
 ramdisk: $(INSTALLED_RAMDISK_TARGET)
 
-.PHONY: factory_ramdisk
-factory_ramdisk: $(INSTALLED_FACTORY_RAMDISK_TARGET)
-
-.PHONY: factory_bundle
-factory_bundle: $(INSTALLED_FACTORY_BUNDLE_TARGET)
-
 .PHONY: systemtarball
 systemtarball: $(INSTALLED_SYSTEMTARBALL_TARGET)
 
@@ -963,8 +953,6 @@
     $(BUILT_TARGET_FILES_PACKAGE) \
     $(INSTALLED_ANDROID_INFO_TXT_TARGET) \
     $(INSTALLED_RAMDISK_TARGET) \
-    $(INSTALLED_FACTORY_RAMDISK_TARGET) \
-    $(INSTALLED_FACTORY_BUNDLE_TARGET) \
    )
 
   # Put a copy of the radio/bootloader files in the dist dir.
diff --git a/core/multi_prebuilt.mk b/core/multi_prebuilt.mk
index bc85cea..ed2fed6 100644
--- a/core/multi_prebuilt.mk
+++ b/core/multi_prebuilt.mk
@@ -76,8 +76,7 @@
      ) \
    ) \
   $(eval LOCAL_MODULE_SUFFIX := $(suffix $(LOCAL_SRC_FILES))) \
-  $(if $(filter user,$(TARGET_BUILD_VARIANT)), \
-    $(eval LOCAL_STRIP_MODULE := $(8))) \
+  $(eval LOCAL_STRIP_MODULE := $(8)) \
   $(eval include $(BUILD_PREBUILT)) \
  )
 endef
diff --git a/core/native_benchmark.mk b/core/native_benchmark.mk
new file mode 100644
index 0000000..431e40a
--- /dev/null
+++ b/core/native_benchmark.mk
@@ -0,0 +1,12 @@
+###########################################
+## A thin wrapper around BUILD_EXECUTABLE
+## Common flags for native benchmarks are added.
+###########################################
+
+LOCAL_STATIC_LIBRARIES += libbenchmark
+
+ifndef LOCAL_MODULE_PATH
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
+endif
+
+include $(BUILD_EXECUTABLE)
diff --git a/core/package_internal.mk b/core/package_internal.mk
index a6ad354..e389b04 100644
--- a/core/package_internal.mk
+++ b/core/package_internal.mk
@@ -320,7 +320,12 @@
 
 ifneq ($(full_classes_jar),)
 $(LOCAL_BUILT_MODULE): PRIVATE_DEX_FILE := $(built_dex)
+# Use the jarjar processed arhive as the initial package file.
+$(LOCAL_BUILT_MODULE): PRIVATE_SOURCE_ARCHIVE := $(full_classes_jarjar_jar)
 $(LOCAL_BUILT_MODULE): $(built_dex)
+else
+$(LOCAL_BUILT_MODULE): PRIVATE_DEX_FILE :=
+$(LOCAL_BUILT_MODULE): PRIVATE_SOURCE_ARCHIVE :=
 endif # full_classes_jar
 
 include $(BUILD_SYSTEM)/install_jni_libs.mk
@@ -364,6 +369,8 @@
 $(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES := $(jni_shared_libraries_with_abis)
 # PRIVATE_JNI_SHARED_LIBRARIES_ABI is a list of ABI names.
 $(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES_ABI := $(jni_shared_libraries_abis)
+$(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES_ZIP_OPTIONS := $(LOCAL_JNI_SHARED_LIBRARIES_ZIP_OPTIONS)
+$(LOCAL_BUILT_MODULE): PRIVATE_PAGE_ALIGN_JNI_SHARED_LIBRARIES := $(LOCAL_PAGE_ALIGN_JNI_SHARED_LIBRARIES)
 ifneq ($(TARGET_BUILD_APPS),)
     # Include all resources for unbundled apps.
     LOCAL_AAPT_INCLUDE_ALL_RESOURCES := true
@@ -379,9 +386,12 @@
     $(LOCAL_BUILT_MODULE): PRIVATE_PRODUCT_AAPT_PREF_CONFIG := $(PRODUCT_AAPT_PREF_CONFIG)
 endif
 endif
+$(LOCAL_BUILT_MODULE): PRIVATE_DONT_DELETE_JAR_DIRS := $(LOCAL_DONT_DELETE_JAR_DIRS)
 $(LOCAL_BUILT_MODULE): $(all_res_assets) $(jni_shared_libraries) $(full_android_manifest)
 	@echo "target Package: $(PRIVATE_MODULE) ($@)"
-	$(create-empty-package)
+	$(if $(PRIVATE_SOURCE_ARCHIVE),\
+	  $(call initialize-package-file,$(PRIVATE_SOURCE_ARCHIVE),$@),\
+	  $(create-empty-package))
 	$(add-assets-to-package)
 ifneq ($(jni_shared_libraries),)
 	$(add-jni-shared-libs-to-package)
@@ -389,10 +399,6 @@
 ifneq ($(full_classes_jar),)
 	$(add-dex-to-package)
 endif
-	$(add-carried-java-resources)
-ifneq ($(extra_jar_args),)
-	$(add-java-resources-to-package)
-endif
 	$(sign-package)
 ifdef LOCAL_DEX_PREOPT
 ifneq (nostripping,$(LOCAL_DEX_PREOPT))
@@ -487,7 +493,7 @@
 	@rm -rf $(dir $@) && mkdir -p $(dir $@)
 	$(hide) cp $< $@
 	$(hide) zip -d $@ $(foreach f,$(PRIVATE_JNI_SHARED_LIBRARIES),\*/$(f))
-	$(call align-package)
+	$(align-package)
 
 $(call dist-for-goals, apps_only, $(apk_jni_stripped):$(dist_subdir)/$(LOCAL_PACKAGE_NAME).apk)
 
diff --git a/core/pathmap.mk b/core/pathmap.mk
index 0820885..2532707 100644
--- a/core/pathmap.mk
+++ b/core/pathmap.mk
@@ -27,7 +27,6 @@
 # A mapping from shorthand names to include directories.
 #
 pathmap_INCL := \
-    bootloader:bootable/bootloader/legacy/include \
     camera:system/media/camera/include \
     frameworks-base:frameworks/base/include \
     frameworks-native:frameworks/native/include \
@@ -87,7 +86,6 @@
 	    sax \
 	    telecomm \
 	    telephony \
-	    phone \
 	    wifi \
 	    keystore \
 	    rs \
diff --git a/core/phony_package.mk b/core/phony_package.mk
index b534335..30e198c 100644
--- a/core/phony_package.mk
+++ b/core/phony_package.mk
@@ -7,7 +7,7 @@
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(LOCAL_BUILT_MODULE): $(LOCAL_MODULE_MAKEFILE) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(hide) echo "Fake: $@"
 	$(hide) mkdir -p $(dir $@)
 	$(hide) touch $@
diff --git a/core/prebuilt.mk b/core/prebuilt.mk
index ba0e757..d3f9d1a 100644
--- a/core/prebuilt.mk
+++ b/core/prebuilt.mk
@@ -25,6 +25,10 @@
 ifneq ($(my_module_multilib),both)
 my_skip_non_preferred_arch := true
 endif # $(my_module_multilib)
+# For apps, we don't want to set up the prebuilt apk rule twice even if "LOCAL_MULTILIB := both".
+ifeq (APPS,$(LOCAL_MODULE_CLASS))
+my_skip_non_preferred_arch := true
+endif
 endif # $(my_module_arch_supported)
 
 ifndef my_skip_non_preferred_arch
diff --git a/core/prebuilt_internal.mk b/core/prebuilt_internal.mk
index bc6088f..47e21ef 100644
--- a/core/prebuilt_internal.mk
+++ b/core/prebuilt_internal.mk
@@ -39,6 +39,10 @@
   # Put the built targets of all shared libraries in a common directory
   # to simplify the link line.
   OVERRIDE_BUILT_MODULE_PATH := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)OUT_INTERMEDIATE_LIBRARIES)
+  ifeq ($(LOCAL_IS_HOST_MODULE)$(LOCAL_STRIP_MODULE),)
+    # Strip but not try to add debuglink
+    LOCAL_STRIP_MODULE := no_debuglink
+  endif
 endif
 
 ifneq ($(filter STATIC_LIBRARIES SHARED_LIBRARIES,$(LOCAL_MODULE_CLASS)),)
@@ -59,7 +63,7 @@
 LOCAL_INSTALLED_MODULE_STEM := $(LOCAL_MODULE).apk
 endif
 
-ifeq ($(LOCAL_STRIP_MODULE),true)
+ifneq ($(filter true no_debuglink,$(LOCAL_STRIP_MODULE)),)
   ifdef LOCAL_IS_HOST_MODULE
     $(error Cannot strip host module LOCAL_PATH=$(LOCAL_PATH))
   endif
@@ -71,6 +75,7 @@
   endif
   include $(BUILD_SYSTEM)/dynamic_binary.mk
   built_module := $(linked_module)
+
 else  # LOCAL_STRIP_MODULE not true
   include $(BUILD_SYSTEM)/base_rules.mk
   built_module := $(LOCAL_BUILT_MODULE)
@@ -96,19 +101,24 @@
 # of the shared libraries are determined.
 ifdef LOCAL_INSTALLED_MODULE
 ifdef LOCAL_SHARED_LIBRARIES
+my_shared_libraries := $(LOCAL_SHARED_LIBRARIES)
+# Extra shared libraries introduced by LOCAL_CXX_STL.
+include $(BUILD_SYSTEM)/cxx_stl_setup.mk
 $(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
-  $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(LOCAL_SHARED_LIBRARIES))
+  $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(my_shared_libraries))
 
 # We also need the LOCAL_BUILT_MODULE dependency,
 # since we use -rpath-link which points to the built module's path.
-built_shared_libraries := \
+my_built_shared_libraries := \
     $(addprefix $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)OUT_INTERMEDIATE_LIBRARIES)/, \
     $(addsuffix $($(my_prefix)SHLIB_SUFFIX), \
-        $(LOCAL_SHARED_LIBRARIES)))
-$(LOCAL_BUILT_MODULE) : $(built_shared_libraries)
+        $(my_shared_libraries)))
+$(LOCAL_BUILT_MODULE) : $(my_built_shared_libraries)
 endif
 endif
 
+# We need to enclose the above export_includes and built_shared_libraries in
+# "LOCAL_STRIP_MODULE not true" because otherwise the rules are defined in dynamic_binary.mk.
 endif  # LOCAL_STRIP_MODULE not true
 
 ifeq ($(LOCAL_MODULE_CLASS),APPS)
@@ -180,6 +190,7 @@
 include $(BUILD_SYSTEM)/dex_preopt_odex_install.mk
 #######################################
 # Sign and align non-presigned .apks.
+$(built_module) : PRIVATE_PAGE_ALIGN_JNI_SHARED_LIBRARIES := $(LOCAL_PAGE_ALIGN_JNI_SHARED_LIBRARIES)
 $(built_module) : $(my_prebuilt_src_file) | $(ACP) $(ZIPALIGN) $(SIGNAPK_JAR)
 	$(transform-prebuilt-to-target)
 ifdef extracted_jni_libs
@@ -289,6 +300,6 @@
 $(built_module) : $(common_javalib_jar)
 endif # TARGET JAVA_LIBRARIES
 
-$(built_module) : $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(built_module) : $(LOCAL_MODULE_MAKEFILE) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 
 my_prebuilt_src_file :=
diff --git a/core/product.mk b/core/product.mk
index f0fc921..d3df582 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -86,7 +86,6 @@
     PRODUCT_EXTRA_RECOVERY_KEYS \
     PRODUCT_PACKAGE_OVERLAYS \
     DEVICE_PACKAGE_OVERLAYS \
-    PRODUCT_TAGS \
     PRODUCT_SDK_ATREE_FILES \
     PRODUCT_SDK_ADDON_NAME \
     PRODUCT_SDK_ADDON_COPY_FILES \
@@ -97,9 +96,6 @@
     PRODUCT_DEFAULT_DEV_CERTIFICATE \
     PRODUCT_RESTRICT_VENDOR_FILES \
     PRODUCT_VENDOR_KERNEL_HEADERS \
-    PRODUCT_FACTORY_RAMDISK_MODULES \
-    PRODUCT_FACTORY_BUNDLE_MODULES \
-    PRODUCT_RUNTIMES \
     PRODUCT_BOOT_JARS \
     PRODUCT_SUPPORTS_VERITY \
     PRODUCT_OEM_PROPERTIES \
@@ -108,7 +104,6 @@
     PRODUCT_VERITY_SIGNING_KEY \
     PRODUCT_SYSTEM_VERITY_PARTITION \
     PRODUCT_VENDOR_VERITY_PARTITION \
-    PRODUCT_DEX_PREOPT_IMAGE_IN_DATA \
     PRODUCT_DEX_PREOPT_MODULE_CONFIGS \
     PRODUCT_DEX_PREOPT_DEFAULT_FLAGS \
     PRODUCT_DEX_PREOPT_BOOT_FLAGS \
@@ -243,7 +238,6 @@
 	TARGET_PROVIDES_INIT_RC \
 	TARGET_CPU_ABI \
 	TARGET_CPU_ABI2 \
-	TARGET_CPU_SMP \
 
 
 _product_stash_var_list += \
@@ -258,6 +252,7 @@
 	BOARD_BOOTIMAGE_PARTITION_SIZE \
 	BOARD_RECOVERYIMAGE_PARTITION_SIZE \
 	BOARD_SYSTEMIMAGE_PARTITION_SIZE \
+	BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE \
 	BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE \
 	BOARD_USERDATAIMAGE_PARTITION_SIZE \
 	BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE \
@@ -273,6 +268,10 @@
 	WITH_DEXPREOPT \
 	WITH_DEXPREOPT_BOOT_IMG_ONLY
 
+_product_stash_var_list += \
+	GLOBAL_CFLAGS_NO_OVERRIDE \
+	GLOBAL_CPPFLAGS_NO_OVERRIDE \
+
 #
 # Stash values of the variables in _product_stash_var_list.
 # $(1): Renamed prefix
diff --git a/core/product_config.mk b/core/product_config.mk
index e7fa75e..5240ae7 100644
--- a/core/product_config.mk
+++ b/core/product_config.mk
@@ -248,36 +248,6 @@
 
 
 #############################################################################
-# TODO: Remove this hack once only 1 runtime is left.
-# Include the runtime product makefile based on the product's PRODUCT_RUNTIMES
-$(call clear-var-list, $(_product_var_list))
-
-# Set PRODUCT_RUNTIMES, allowing buildspec to override using OVERRIDE_RUNTIMES
-product_runtimes := $(sort $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_RUNTIMES))
-ifneq ($(OVERRIDE_RUNTIMES),)
-  $(info Overriding PRODUCT_RUNTIMES=$(product_runtimes) with $(OVERRIDE_RUNTIMES))
-  product_runtimes := $(OVERRIDE_RUNTIMES)
-endif
-$(foreach runtime, $(product_runtimes), $(eval include $(SRC_TARGET_DIR)/product/$(runtime).mk))
-$(foreach v, $(_product_var_list), $(if $($(v)),\
-    $(eval PRODUCTS.$(INTERNAL_PRODUCT).$(v) += $(sort $($(v))))))
-
-$(call clear-var-list, $(_product_var_list))
-# Now we can assign to PRODUCT_RUNTIMES
-PRODUCT_RUNTIMES := $(product_runtimes)
-product_runtimes :=
-
-PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PROPERTY_OVERRIDES += persist.sys.dalvik.vm.lib.2=$(DALVIK_VM_LIB)
-
-ifeq ($(words $(PRODUCT_RUNTIMES)),1)
-  # If we only have one runtime, we can strip classes.dex by default during dex_preopt
-  DEX_PREOPT_DEFAULT := true
-else
-  # If we have more than one, we leave the classes.dex alone for post-boot analysis
-  DEX_PREOPT_DEFAULT := nostripping
-endif
-
-#############################################################################
 
 # A list of module names of BOOTCLASSPATH (jar files)
 PRODUCT_BOOT_JARS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_BOOT_JARS))
@@ -379,9 +349,6 @@
 DEVICE_PACKAGE_OVERLAYS := \
         $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).DEVICE_PACKAGE_OVERLAYS))
 
-# An list of whitespace-separated words.
-PRODUCT_TAGS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_TAGS))
-
 # The list of product-specific kernel header dirs
 PRODUCT_VENDOR_KERNEL_HEADERS := \
     $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_KERNEL_HEADERS)
@@ -401,10 +368,6 @@
 PRODUCT_EXTRA_RECOVERY_KEYS := $(sort \
     $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_EXTRA_RECOVERY_KEYS))
 
-# If there is no room in /system for the image, place it in /data
-PRODUCT_DEX_PREOPT_IMAGE_IN_DATA := \
-    $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_IMAGE_IN_DATA))
-
 PRODUCT_DEX_PREOPT_DEFAULT_FLAGS := \
     $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_DEFAULT_FLAGS))
 PRODUCT_DEX_PREOPT_BOOT_FLAGS := \
diff --git a/core/raw_executable.mk b/core/raw_executable.mk
deleted file mode 100644
index b64173a..0000000
--- a/core/raw_executable.mk
+++ /dev/null
@@ -1,25 +0,0 @@
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE_SUFFIX := 
-LOCAL_FORCE_STATIC_EXECUTABLE := true
-
-include $(BUILD_SYSTEM)/binary.mk
-
-$(LOCAL_BUILT_MODULE) : PRIVATE_ELF_FILE := $(intermediates)/$(PRIVATE_MODULE).elf
-$(LOCAL_BUILT_MODULE) : PRIVATE_LIBS := `$(TARGET_CC) -mthumb-interwork -print-libgcc-file-name`
-
-$(all_objects) : PRIVATE_TARGET_PROJECT_INCLUDES :=
-$(all_objects) : PRIVATE_TARGET_C_INCLUDES :=
-$(all_objects) : PRIVATE_TARGET_GLOBAL_CFLAGS :=
-$(all_objects) : PRIVATE_TARGET_GLOBAL_CPPFLAGS :=
-
-$(LOCAL_BUILT_MODULE): $(all_objects) $(all_libraries)
-	@$(mkdir -p $(dir $@)
-	@echo "target Linking: $(PRIVATE_MODULE)"
-	$(hide) $(TARGET_LD) \
-		$(addprefix --script ,$(PRIVATE_LINK_SCRIPT)) \
-		$(PRIVATE_RAW_EXECUTABLE_LDFLAGS) \
-		-o $(PRIVATE_ELF_FILE) \
-		$(PRIVATE_ALL_OBJECTS) \
-		--start-group $(PRIVATE_ALL_STATIC_LIBRARIES) --end-group \
-		$(PRIVATE_LIBS)
-	$(hide) $(TARGET_OBJCOPY) -O binary $(PRIVATE_ELF_FILE) $@
diff --git a/core/raw_static_library.mk b/core/raw_static_library.mk
deleted file mode 100644
index 14a404d..0000000
--- a/core/raw_static_library.mk
+++ /dev/null
@@ -1,4 +0,0 @@
-
-LOCAL_RAW_STATIC_LIBRARY:=true
-
-include $(BUILD_SYSTEM)/static_library_internal.mk
diff --git a/core/shared_library_internal.mk b/core/shared_library_internal.mk
index c01be37..1fda794 100644
--- a/core/shared_library_internal.mk
+++ b/core/shared_library_internal.mk
@@ -40,6 +40,7 @@
 
 # Define PRIVATE_ variables from global vars
 my_target_global_ld_dirs := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_LD_DIRS)
+my_target_libgcov := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_LIBGCOV)
 my_target_libgcc := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_LIBGCC)
 my_target_libatomic := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_LIBATOMIC)
 my_target_crtbegin_so_o := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_CRTBEGIN_SO_O)
@@ -57,14 +58,19 @@
 endif
 $(linked_module): PRIVATE_TARGET_GLOBAL_LD_DIRS := $(my_target_global_ld_dirs)
 $(linked_module): PRIVATE_TARGET_GLOBAL_LDFLAGS := $(my_target_global_ldflags)
+$(linked_module): PRIVATE_TARGET_LIBGCOV := $(my_target_libgcov)
 $(linked_module): PRIVATE_TARGET_LIBGCC := $(my_target_libgcc)
 $(linked_module): PRIVATE_TARGET_LIBATOMIC := $(my_target_libatomic)
 $(linked_module): PRIVATE_TARGET_CRTBEGIN_SO_O := $(my_target_crtbegin_so_o)
 $(linked_module): PRIVATE_TARGET_CRTEND_SO_O := $(my_target_crtend_so_o)
 
-$(linked_module): $(all_objects) $(all_libraries) \
-                  $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-                  $(my_target_crtbegin_so_o) $(my_target_crtend_so_o)
+$(linked_module): \
+        $(all_objects) \
+        $(all_libraries) \
+        $(my_target_crtbegin_so_o) \
+        $(my_target_crtend_so_o) \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-o-to-shared-lib)
 
 endif  # skip_build_from_source
diff --git a/core/target_test_internal.mk b/core/target_test_internal.mk
index 95d4159..f8a9f04 100644
--- a/core/target_test_internal.mk
+++ b/core/target_test_internal.mk
@@ -5,18 +5,11 @@
 LOCAL_CFLAGS += -DGTEST_OS_LINUX_ANDROID -DGTEST_HAS_STD_STRING
 
 LOCAL_C_INCLUDES += external/gtest/include
-ifneq ($(filter libc++,$(LOCAL_SHARED_LIBRARIES)),)
-LOCAL_STATIC_LIBRARIES += libgtest_libc++ libgtest_main_libc++
-else
-LOCAL_STATIC_LIBRARIES += libgtest libgtest_main
 
 ifndef LOCAL_SDK_VERSION
-LOCAL_C_INCLUDES += bionic \
-                    bionic/libstdc++/include \
-                    external/stlport/stlport
-LOCAL_SHARED_LIBRARIES += libstlport
-LOCAL_STATIC_LIBRARIES += libstdc++
-endif
+LOCAL_STATIC_LIBRARIES += libgtest libgtest_main
+else
+LOCAL_STATIC_LIBRARIES += libgtest_ndk libgtest_main_ndk
 endif
 
 ifdef LOCAL_MODULE_PATH
diff --git a/core/tasks/check_boot_jars/check_boot_jars.py b/core/tasks/check_boot_jars/check_boot_jars.py
index 89d9ee8..5a0ec40 100755
--- a/core/tasks/check_boot_jars/check_boot_jars.py
+++ b/core/tasks/check_boot_jars/check_boot_jars.py
@@ -64,10 +64,10 @@
 def main(argv):
   if len(argv) < 2:
     print __doc__
-    sys.exit(1)
+    return 1
 
   if not LoadWhitelist(argv[0]):
-    sys.exit(1)
+    return 1
 
   passed = True
   for jar in argv[1:]:
@@ -80,4 +80,4 @@
 
 
 if __name__ == '__main__':
-  main(sys.argv[1:])
+  sys.exit(main(sys.argv[1:]))
diff --git a/core/tasks/factory_bundle.mk b/core/tasks/factory_bundle.mk
deleted file mode 100644
index 51531cb..0000000
--- a/core/tasks/factory_bundle.mk
+++ /dev/null
@@ -1,84 +0,0 @@
-#
-# Copyright (C) 2011 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.
-#
-
-ifeq (,$(ONE_SHOT_MAKEFILE))
-ifneq ($(TARGET_BUILD_PDK),true)
-  TARGET_BUILD_FACTORY=true
-endif
-ifeq ($(TARGET_BUILD_FACTORY),true)
-
-# PRODUCT_FACTORY_RAMDISK_MODULES consists of "<module_name>:<install_path>[:<install_path>...]" tuples.
-# <install_path> is relative to the staging directory for the bundle.
-# 
-# Only host modules can be installed here. 
-# (It's possible to relax this, but it's not needed and kind of tricky.  We'll need to add
-# a better way of specifying the class. Really the answer is to stop having modules with
-# duplicate names)
-#
-# You can also add files with PRODUCT_COPY_FILES if necessary.
-#
-# For example:
-# PRODUCT_FACTORY_BUNDLE_MODULES := \
-#     adb:adb fastboot:fastboot
-requested_modules := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_FACTORY_BUNDLE_MODULES))
-
-root_dir := $(PRODUCT_OUT)/factory_bundle
-leaf := $(strip $(TARGET_PRODUCT))-factory_bundle-$(FILE_NAME_TAG)
-named_dir := $(PRODUCT_OUT)/$(leaf)
-tarball := $(PRODUCT_OUT)/$(leaf).tgz
-
-copied_files := \
-  $(foreach _fb_m, $(requested_modules), $(strip \
-    $(eval _fb_m_tuple := $(subst :, ,$(_fb_m))) \
-    $(eval _fb_m_name := $(word 1,$(_fb_m_tuple))) \
-    $(eval _fb_dests := $(wordlist 2,999,$(_fb_m_tuple))) \
-    $(eval _fb_m_built := $(filter $(HOST_OUT)/%, $(ALL_MODULES.$(_fb_m_name).BUILT))) \
-    $(if $(_fb_m_built),,$(warning no built file in requested_modules for '$(_fb_m_built)'))\
-    $(foreach _fb_f,$(_fb_dests),$(eval $(call copy-one-file,$(_fb_m_built),$(root_dir)/$(_fb_f))))\
-    $(addprefix $(root_dir)/,$(_fb_dests)) \
-    )) \
-  $(filter $(root_dir)/%, $(ALL_DEFAULT_INSTALLED_MODULES))
-
-ifneq (,$(strip $(copied_files)))
-
-#
-# These files are made by magic so we need to explicitly include them
-#
-$(eval $(call copy-one-file,$(TARGET_OUT)/build.prop,$(root_dir)/build.prop))
-copied_files += $(root_dir)/build.prop
-
-$(eval $(call copy-one-file,$(PRODUCT_OUT)/factory_ramdisk.img,$(root_dir)/factory_ramdisk.img))
-copied_files += $(root_dir)/factory_ramdisk.img
-#
-# End magic
-#
-
-$(tarball): PRIVATE_ROOT_DIR := $(root_dir)
-$(tarball): PRIVATE_NAMED_DIR := $(named_dir)
-
-$(tarball): $(copied_files)
-	@echo "Tarball: $@"
-	$(hide) rm -rf $(PRIVATE_NAMED_DIR)
-	$(hide) ( cp -r $(PRIVATE_ROOT_DIR) $(PRIVATE_NAMED_DIR) \
-			&& tar cfz $@ -C $(dir $(PRIVATE_NAMED_DIR)) $(notdir $(PRIVATE_NAMED_DIR)) \
-			) && rm -rf $(PRIVATE_NAMED_DIR)
-
-INSTALLED_FACTORY_BUNDLE_TARGET := $(tarball)
-
-endif
-
-endif # TARGET_BUILD_PDK
-endif # ONE_SHOT_MAKEFILE
diff --git a/core/tasks/factory_ramdisk.mk b/core/tasks/factory_ramdisk.mk
deleted file mode 100644
index d65d931..0000000
--- a/core/tasks/factory_ramdisk.mk
+++ /dev/null
@@ -1,95 +0,0 @@
-#
-# Copyright (C) 2011 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.
-#
-
-ifeq (,$(ONE_SHOT_MAKEFILE))
-ifneq ($(TARGET_BUILD_PDK),true)
-  TARGET_BUILD_FACTORY=true
-endif
-ifeq ($(TARGET_BUILD_FACTORY),true)
-
-# PRODUCT_FACTORY_RAMDISK_MODULES consists of "<module_name>:<install_path>[:<install_path>...]" tuples.
-# <install_path> is relative to TARGET_FACTORY_RAMDISK_OUT.
-# We can have multiple <install_path>s because multiple modules may have the same name.
-# For example:
-# PRODUCT_FACTORY_RAMDISK_MODULES := \
-#     toolbox:system/bin/toolbox adbd:sbin/adbd adb:system/bin/adb
-factory_ramdisk_modules := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_FACTORY_RAMDISK_MODULES))
-ifneq (,$(factory_ramdisk_modules))
-
-# A module name may end up in multiple modules (so multiple built files)
-# with the same name.
-# This function selects the module built file based on the install path.
-# $(1): the dest install path
-# $(2): the module built files
-define install-one-factory-ramdisk-module
-$(eval _iofrm_suffix := $(suffix $(1))) \
-$(if $(_iofrm_suffix), \
-    $(eval _iofrm_pattern := %$(_iofrm_suffix)), \
-    $(eval _iofrm_pattern := %$(notdir $(1)))) \
-$(eval _iofrm_src := $(filter $(_iofrm_pattern),$(2))) \
-$(if $(filter 1,$(words $(_iofrm_src))), \
-    $(eval _fulldest := $(TARGET_FACTORY_RAMDISK_OUT)/$(1)) \
-    $(eval $(call copy-one-file,$(_iofrm_src),$(_fulldest))) \
-    $(eval INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES += $(_fulldest)), \
-    $(warning Warning: Cannot find built file in "$(2)" for "$(1)") \
-    )
-endef
-
-INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES :=
-$(foreach m, $(factory_ramdisk_modules), \
-    $(eval _fr_m_tuple := $(subst :, ,$(m))) \
-    $(eval _fr_m_name := $(word 1,$(_fr_m_tuple))) \
-    $(eval _fr_dests := $(wordlist 2,999,$(_fr_m_tuple))) \
-    $(eval _fr_m_built := $(filter $(PRODUCT_OUT)/%, $(ALL_MODULES.$(_fr_m_name).BUILT))) \
-    $(foreach d,$(_fr_dests),$(call install-one-factory-ramdisk-module,$(d),$(_fr_m_built))) \
-    )
-endif
-
-# Files may also be installed via PRODUCT_COPY_FILES, PRODUCT_PACKAGES etc.
-INTERNAL_FACTORY_RAMDISK_FILES := $(filter $(TARGET_FACTORY_RAMDISK_OUT)/%, \
-    $(ALL_DEFAULT_INSTALLED_MODULES))
-
-ifneq (,$(INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES)$(INTERNAL_FACTORY_RAMDISK_FILES))
-
-# These files are made by magic in build/core/Makefile so we need to explicitly include them
-$(eval $(call copy-one-file,$(TARGET_OUT)/build.prop,$(TARGET_FACTORY_RAMDISK_OUT)/system/build.prop))
-INTERNAL_FACTORY_RAMDISK_FILES += $(TARGET_FACTORY_RAMDISK_OUT)/system/build.prop
-
-BUILT_FACTORY_RAMDISK_FS := $(PRODUCT_OUT)/factory_ramdisk.gz
-BUILT_FACTORY_RAMDISK_TARGET := $(PRODUCT_OUT)/factory_ramdisk.img
-
-INSTALLED_FACTORY_RAMDISK_FS := $(BUILT_FACTORY_RAMDISK_FS)
-$(INSTALLED_FACTORY_RAMDISK_FS) : $(MKBOOTFS) \
-    $(INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES) $(INTERNAL_FACTORY_RAMDISK_FILES) | $(MINIGZIP)
-	$(call pretty,"Target factory ram disk file system: $@")
-	$(hide) $(MKBOOTFS) $(TARGET_FACTORY_RAMDISK_OUT) | $(MINIGZIP) > $@
-
-TARGET_RAMDISK_KERNEL := $(INSTALLED_KERNEL_TARGET)
-INSTALLED_FACTORY_RAMDISK_TARGET := $(BUILT_FACTORY_RAMDISK_TARGET)
-ifneq (,$(BOARD_KERNEL_CMDLINE_FACTORY_BOOT))
-  RAMDISK_CMDLINE := --cmdline "$(BOARD_KERNEL_CMDLINE_FACTORY_BOOT)"
-else
-  RAMDISK_CMDLINE :=
-endif
-$(INSTALLED_FACTORY_RAMDISK_TARGET) : $(MKBOOTIMG) $(TARGET_RAMDISK_KERNEL) $(INSTALLED_FACTORY_RAMDISK_FS)
-	$(call pretty,"Target factory ram disk img format: $@")
-	$(MKBOOTIMG) --kernel $(TARGET_RAMDISK_KERNEL) --ramdisk $(INSTALLED_FACTORY_RAMDISK_FS) \
-            --base $(BOARD_KERNEL_BASE) $(BOARD_MKBOOTIMG_ARGS) $(RAMDISK_CMDLINE) --output $@
-
-endif
-
-endif # TARGET_BUILD_PDK
-endif # ONE_SHOT_MAKEFILE
diff --git a/core/tasks/product-graph.mk b/core/tasks/product-graph.mk
index fcec277..db2cf71 100644
--- a/core/tasks/product-graph.mk
+++ b/core/tasks/product-graph.mk
@@ -61,7 +61,7 @@
 $(hide) echo \"$(1)\" [ \
 label=\"$(dir $(1))\\n$(notdir $(1))\\n\\n$(subst $(close_parenthesis),,$(subst $(open_parethesis),,$(PRODUCTS.$(strip $(1)).PRODUCT_MODEL)))\\n$(PRODUCTS.$(strip $(1)).PRODUCT_DEVICE)\" \
 $(if $(filter $(1),$(PRIVATE_PRODUCTS_FILTER)), style=\"filled\" fillcolor=\"#FFFDB0\",) \
-fontcolor=\"darkblue\" href=\"products/$(1).html\" \
+colorscheme=\"svg\" fontcolor=\"darkblue\" href=\"products/$(1).html\" \
 ] >> $(2)
 
 endef
@@ -109,7 +109,6 @@
 	$(hide) echo 'PRODUCT_EXTRA_RECOVERY_KEYS=$$(PRODUCTS.$(strip $(1)).PRODUCT_EXTRA_RECOVERY_KEYS)' >> $$@
 	$(hide) echo 'PRODUCT_PACKAGE_OVERLAYS=$$(PRODUCTS.$(strip $(1)).PRODUCT_PACKAGE_OVERLAYS)' >> $$@
 	$(hide) echo 'DEVICE_PACKAGE_OVERLAYS=$$(PRODUCTS.$(strip $(1)).DEVICE_PACKAGE_OVERLAYS)' >> $$@
-	$(hide) echo 'PRODUCT_TAGS=$$(PRODUCTS.$(strip $(1)).PRODUCT_TAGS)' >> $$@
 	$(hide) echo 'PRODUCT_SDK_ADDON_NAME=$$(PRODUCTS.$(strip $(1)).PRODUCT_SDK_ADDON_NAME)' >> $$@
 	$(hide) echo 'PRODUCT_SDK_ADDON_COPY_FILES=$$(PRODUCTS.$(strip $(1)).PRODUCT_SDK_ADDON_COPY_FILES)' >> $$@
 	$(hide) echo 'PRODUCT_SDK_ADDON_COPY_MODULES=$$(PRODUCTS.$(strip $(1)).PRODUCT_SDK_ADDON_COPY_MODULES)' >> $$@
@@ -117,7 +116,6 @@
 	$(hide) echo 'PRODUCT_DEFAULT_WIFI_CHANNELS=$$(PRODUCTS.$(strip $(1)).PRODUCT_DEFAULT_WIFI_CHANNELS)' >> $$@
 	$(hide) echo 'PRODUCT_DEFAULT_DEV_CERTIFICATE=$$(PRODUCTS.$(strip $(1)).PRODUCT_DEFAULT_DEV_CERTIFICATE)' >> $$@
 	$(hide) echo 'PRODUCT_RESTRICT_VENDOR_FILES=$$(PRODUCTS.$(strip $(1)).PRODUCT_RESTRICT_VENDOR_FILES)' >> $$@
-	$(hide) echo 'PRODUCT_FACTORY_RAMDISK_MODULES=$$(PRODUCTS.$(strip $(1)).PRODUCT_FACTORY_RAMDISK_MODULES)' >> $$@
 	$(hide) echo 'PRODUCT_VENDOR_KERNEL_HEADERS=$$(PRODUCTS.$(strip $(1)).PRODUCT_VENDOR_KERNEL_HEADERS)' >> $$@
 
 $(call product-debug-filename, $(p)): \
diff --git a/envsetup.sh b/envsetup.sh
index d80e95c..f93c07d 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -14,9 +14,16 @@
 - ggrep:   Greps on all local Gradle files.
 - jgrep:   Greps on all local Java files.
 - resgrep: Greps on all local res/*.xml files.
+- mangrep: Greps on all local AndroidManifest.xml files.
+- sepgrep: Greps on all local sepolicy files.
 - sgrep:   Greps on all local source files.
 - godir:   Go to the directory containing a file.
 
+Environemnt options:
+- SANITIZE_HOST: Set to 'true' to use ASAN for all host modules. Note that
+                 ASAN_OPTIONS=detect_leaks=0 will be set by default until the
+                 build is leak-check clean.
+
 Look at the source to view more functions. The complete list is:
 EOF
     T=$(gettop)
@@ -231,6 +238,7 @@
     export ANDROID_BUILD_TOP=$(gettop)
     # With this environment variable new GCC can apply colors to warnings/errors
     export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
+    export ASAN_OPTIONS=detect_leaks=0
 }
 
 function set_sequence_number()
@@ -1027,18 +1035,6 @@
     fi
 }
 
-function gdbwrapper()
-{
-    local GDB_CMD="$1"
-    shift 1
-    $GDB_CMD -x "$@"
-}
-
-function get_symbols_directory()
-{
-    echo $(get_abs_build_var TARGET_OUT_UNSTRIPPED)
-}
-
 # Read the ELF header from /proc/$PID/exe to determine if the process is
 # 64-bit.
 function is64bit()
@@ -1055,251 +1051,6 @@
     fi
 }
 
-function adb_get_product_device() {
-  echo `adb shell getprop ro.product.device | sed s/.$//`
-}
-
-# returns 0 when process is not traced
-function adb_get_traced_by() {
-  echo `adb shell cat /proc/$1/status | grep -e "^TracerPid:" | sed "s/^TracerPid:\t//" | sed s/.$//`
-}
-
-function gdbclient() {
-  # TODO:
-  # 1. Check for ANDROID_SERIAL/multiple devices
-  local PROCESS_NAME="n/a"
-  local PID=$1
-  local PORT=5039
-  if [ -z "$PID" ]; then
-    echo "Usage: gdbclient <pid|processname> [port number]"
-    return -1
-  fi
-  local DEVICE=$(adb_get_product_device)
-
-  if [ -z "$DEVICE" ]; then
-    echo "Error: Unable to get device name. Please check if device is connected and ANDROID_SERIAL is set."
-    return -2
-  fi
-
-  if [ -n "$2" ]; then
-    PORT=$2
-  fi
-
-  local ROOT=$(gettop)
-  if [ -z "$ROOT" ]; then
-    # This is for the situation with downloaded symbols (from the build server)
-    # we check if they are available.
-    ROOT=`realpath .`
-  fi
-
-  local OUT_ROOT="$ROOT/out/target/product/$DEVICE"
-  local SYMBOLS_DIR="$OUT_ROOT/symbols"
-
-  if [ ! -d $SYMBOLS_DIR ]; then
-    echo "Error: couldn't find symbols: $SYMBOLS_DIR does not exist or is not a directory."
-    return -3
-  fi
-
-  # let's figure out which executable we are about to debug
-
-  # check if user specified a name -> resolve to pid
-  if [[ ! "$PID" =~ ^[0-9]+$ ]] ; then
-    PROCESS_NAME=$PID
-    PID=$(pid --exact $PROCESS_NAME)
-    if [ -z "$PID" ]; then
-      echo "Error: couldn't resolve pid by process name: $PROCESS_NAME"
-      return -4
-    fi
-  fi
-
-  local EXE=`adb shell readlink /proc/$PID/exe | sed s/.$//`
-  # TODO: print error in case there is no such pid
-  local LOCAL_EXE_PATH=$SYMBOLS_DIR$EXE
-
-  if [ ! -f $LOCAL_EXE_PATH ]; then
-    echo "Error: unable to find symbols for executable $EXE: file $LOCAL_EXE_PATH does not exist"
-    return -5
-  fi
-
-  local USE64BIT=""
-
-  if [[ "$(file $LOCAL_EXE_PATH)" =~ 64-bit ]]; then
-    USE64BIT="64"
-  fi
-
-  local GDB=
-  local GDB64=
-  local CPU_ABI=`adb shell getprop ro.product.cpu.abilist | sed s/.$//`
-  # TODO: we assume these are available via $PATH
-  if [[ $CPU_ABI =~ (^|,)arm64 ]]; then
-    GDB=arm-linux-androideabi-gdb
-    GDB64=aarch64-linux-android-gdb
-  elif [[ $CPU_ABI =~ (^|,)arm ]]; then
-    GDB=arm-linux-androideabi-gdb
-  elif [[ $CPU_ABI =~ (^|,)x86_64 ]]; then
-    GDB=x86_64-linux-androideabi-gdb
-  elif [[ $CPU_ABI =~ (^|,)x86 ]]; then
-    GDB=x86_64-linux-androideabi-gdb
-  elif [[ $CPU_ABI =~ (^|,)mips64 ]]; then
-    GDB=mipsel-linux-android-gdb
-    GDB64=mips64el-linux-android-gdb
-  elif [[ $CPU_ABI =~ (^|,)mips ]]; then
-    GDB=mipsel-linux-android-gdb
-  else
-    echo "Error: unrecognized cpu.abilist: $CPU_ABI"
-    return -6
-  fi
-
-  # TODO: check if tracing process is gdbserver and not some random strace...
-  if [ $(adb_get_traced_by $PID) -eq 0 ]; then
-    # start gdbserver
-    echo "Starting gdbserver..."
-    # TODO: check if adb is already listening $PORT
-    # to avoid unnecessary calls
-    echo ". adb forward for port=$PORT..."
-    adb forward tcp:$PORT tcp:$PORT
-    echo ". starting gdbserver to attach to pid=$PID..."
-    adb shell gdbserver$USE64BIT :$PORT --attach $PID &
-    echo ". give it couple of seconds to start..."
-    sleep 2
-    echo ". done"
-  else
-    echo "It looks like gdbserver is already attached to $PID (process is traced), trying to connect to it using local port=$PORT"
-  fi
-
-  local OUT_SO_SYMBOLS=$SYMBOLS_DIR/system/lib$USE64BIT
-  local OUT_VENDOR_SO_SYMBOLS=$SYMBOLS_DIR/vendor/lib$USE64BIT
-  local ART_CMD=""
-
-  echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $SYMBOLS_DIR"
-  echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $OUT_SO_SYMBOLS:$OUT_SO_SYMBOLS/hw:$OUT_SO_SYMBOLS/ssl/engines:$OUT_SO_SYMBOLS/drm:$OUT_SO_SYMBOLS/egl:$OUT_SO_SYMBOLS/soundfx:$OUT_VENDOR_SO_SYMBOLS:$OUT_VENDOR_SO_SYMBOLS/hw:$OUT_VENDOR_SO_SYMBOLS/egl"
-  local DALVIK_GDB_SCRIPT=$ROOT/development/scripts/gdb/dalvik.gdb
-  if [ -f $DALVIK_GDB_SCRIPT ]; then
-    echo >>"$OUT_ROOT/gdbclient.cmds" "source $DALVIK_GDB_SCRIPT"
-    ART_CMD="art-on"
-  else
-    echo "Warning: couldn't find $DALVIK_GDB_SCRIPT - ART debugging options will not be available"
-  fi
-  echo >>"$OUT_ROOT/gdbclient.cmds" "target remote :$PORT"
-  if [[ $EXE =~ (^|/)(app_process|dalvikvm)(|32|64)$ ]]; then
-    echo >> "$OUT_ROOT/gdbclient.cmds" $ART_CMD
-  fi
-
-  echo >>"$OUT_ROOT/gdbclient.cmds" ""
-
-  local WHICH_GDB=$GDB
-
-  if [ -n "$USE64BIT" -a -n "$GDB64" ]; then
-    WHICH_GDB=$GDB64
-  fi
-
-  gdbwrapper $WHICH_GDB "$OUT_ROOT/gdbclient.cmds" "$LOCAL_EXE_PATH"
-}
-
-# gdbclient now determines whether the user wants to debug a 32-bit or 64-bit
-# executable, set up the approriate gdbserver, then invokes the proper host
-# gdb.
-function gdbclient_old()
-{
-   local OUT_ROOT=$(get_abs_build_var PRODUCT_OUT)
-   local OUT_SYMBOLS=$(get_abs_build_var TARGET_OUT_UNSTRIPPED)
-   local OUT_SO_SYMBOLS=$(get_abs_build_var TARGET_OUT_SHARED_LIBRARIES_UNSTRIPPED)
-   local OUT_VENDOR_SO_SYMBOLS=$(get_abs_build_var TARGET_OUT_VENDOR_SHARED_LIBRARIES_UNSTRIPPED)
-   local OUT_EXE_SYMBOLS=$(get_symbols_directory)
-   local PREBUILTS=$(get_abs_build_var ANDROID_PREBUILTS)
-   local ARCH=$(get_build_var TARGET_ARCH)
-   local GDB
-   case "$ARCH" in
-       arm) GDB=arm-linux-androideabi-gdb;;
-       arm64) GDB=arm-linux-androideabi-gdb; GDB64=aarch64-linux-android-gdb;;
-       mips|mips64) GDB=mips64el-linux-android-gdb;;
-       x86) GDB=x86_64-linux-android-gdb;;
-       x86_64) GDB=x86_64-linux-android-gdb;;
-       *) echo "Unknown arch $ARCH"; return 1;;
-   esac
-
-   if [ "$OUT_ROOT" -a "$PREBUILTS" ]; then
-       local EXE="$1"
-       if [ "$EXE" ] ; then
-           EXE=$1
-           if [[ $EXE =~ ^[^/].* ]] ; then
-               EXE="system/bin/"$EXE
-           fi
-       else
-           EXE="app_process"
-       fi
-
-       local PORT="$2"
-       if [ "$PORT" ] ; then
-           PORT=$2
-       else
-           PORT=":5039"
-       fi
-
-       local PID="$3"
-       if [ "$PID" ] ; then
-           if [[ ! "$PID" =~ ^[0-9]+$ ]] ; then
-               PID=`pid $3`
-               if [[ ! "$PID" =~ ^[0-9]+$ ]] ; then
-                   # that likely didn't work because of returning multiple processes
-                   # try again, filtering by root processes (don't contain colon)
-                   PID=`adb shell ps | \grep $3 | \grep -v ":" | awk '{print $2}'`
-                   if [[ ! "$PID" =~ ^[0-9]+$ ]]
-                   then
-                       echo "Couldn't resolve '$3' to single PID"
-                       return 1
-                   else
-                       echo ""
-                       echo "WARNING: multiple processes matching '$3' observed, using root process"
-                       echo ""
-                   fi
-               fi
-           fi
-           adb forward "tcp$PORT" "tcp$PORT"
-           local USE64BIT="$(is64bit $PID)"
-           adb shell gdbserver$USE64BIT $PORT --attach $PID &
-           sleep 2
-       else
-               echo ""
-               echo "If you haven't done so already, do this first on the device:"
-               echo "    gdbserver $PORT /system/bin/$EXE"
-                   echo " or"
-               echo "    gdbserver $PORT --attach <PID>"
-               echo ""
-       fi
-
-       OUT_SO_SYMBOLS=$OUT_SO_SYMBOLS$USE64BIT
-       OUT_VENDOR_SO_SYMBOLS=$OUT_VENDOR_SO_SYMBOLS$USE64BIT
-
-       echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $OUT_SYMBOLS"
-       echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $OUT_SO_SYMBOLS:$OUT_SO_SYMBOLS/hw:$OUT_SO_SYMBOLS/ssl/engines:$OUT_SO_SYMBOLS/drm:$OUT_SO_SYMBOLS/egl:$OUT_SO_SYMBOLS/soundfx:$OUT_VENDOR_SO_SYMBOLS:$OUT_VENDOR_SO_SYMBOLS/hw:$OUT_VENDOR_SO_SYMBOLS/egl"
-       echo >>"$OUT_ROOT/gdbclient.cmds" "source $ANDROID_BUILD_TOP/development/scripts/gdb/dalvik.gdb"
-       echo >>"$OUT_ROOT/gdbclient.cmds" "target remote $PORT"
-       # Enable special debugging for ART processes.
-       if [[ $EXE =~ (^|/)(app_process|dalvikvm)(|32|64)$ ]]; then
-          echo >> "$OUT_ROOT/gdbclient.cmds" "art-on"
-       fi
-       echo >>"$OUT_ROOT/gdbclient.cmds" ""
-
-       local WHICH_GDB=
-       # 64-bit exe found
-       if [ "$USE64BIT" != "" ] ; then
-           WHICH_GDB=$ANDROID_TOOLCHAIN/$GDB64
-       # 32-bit exe / 32-bit platform
-       elif [ "$(get_build_var TARGET_2ND_ARCH)" = "" ]; then
-           WHICH_GDB=$ANDROID_TOOLCHAIN/$GDB
-       # 32-bit exe / 64-bit platform
-       else
-           WHICH_GDB=$ANDROID_TOOLCHAIN_2ND_ARCH/$GDB
-       fi
-
-       gdbwrapper $WHICH_GDB "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
-  else
-       echo "Unable to determine build system output dir."
-   fi
-
-}
-
 case `uname -s` in
     Darwin)
         function sgrep()
@@ -1333,7 +1084,7 @@
 
 function cgrep()
 {
-    find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f \( -name '*.c' -o -name '*.cc' -o -name '*.cpp' -o -name '*.h' \) -print0 | xargs -0 grep --color -n "$@"
+    find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f \( -name '*.c' -o -name '*.cc' -o -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) -print0 | xargs -0 grep --color -n "$@"
 }
 
 function resgrep()
@@ -1631,7 +1382,7 @@
     \cd $T/$pathname
 }
 
-# Force JAVA_HOME to point to java 1.7 or java 1.6  if it isn't already set.
+# Force JAVA_HOME to point to java 1.7 if it isn't already set.
 #
 # Note that the MacOS path for java 1.7 includes a minor revision number (sigh).
 # For some reason, installing the JDK doesn't make it show up in the
@@ -1648,25 +1399,14 @@
     fi
 
     if [ ! "$JAVA_HOME" ]; then
-      if [ -n "$LEGACY_USE_JAVA6" ]; then
-        case `uname -s` in
-            Darwin)
-                export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
-                ;;
-            *)
-                export JAVA_HOME=/usr/lib/jvm/java-6-sun
-                ;;
-        esac
-      else
-        case `uname -s` in
-            Darwin)
-                export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
-                ;;
-            *)
-                export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
-                ;;
-        esac
-      fi
+      case `uname -s` in
+          Darwin)
+              export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
+              ;;
+          *)
+              export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
+              ;;
+      esac
 
       # Keep track of the fact that we set JAVA_HOME ourselves, so that
       # we can change it on the next envsetup.sh, if required.
@@ -1702,11 +1442,21 @@
     local hours=$(($tdiff / 3600 ))
     local mins=$((($tdiff % 3600) / 60))
     local secs=$(($tdiff % 60))
+    local ncolors=$(tput colors 2>/dev/null)
+    if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then
+        color_failed="\e[0;31m"
+        color_success="\e[0;32m"
+        color_reset="\e[00m"
+    else
+        color_failed=""
+        color_success=""
+        color_reset=""
+    fi
     echo
     if [ $ret -eq 0 ] ; then
-        echo -n -e "#### make completed successfully "
+        echo -n -e "${color_success}#### make completed successfully "
     else
-        echo -n -e "#### make failed to build some targets "
+        echo -n -e "${color_failed}#### make failed to build some targets "
     fi
     if [ $hours -gt 0 ] ; then
         printf "(%02g:%02g:%02g (hh:mm:ss))" $hours $mins $secs
@@ -1715,13 +1465,11 @@
     elif [ $secs -gt 0 ] ; then
         printf "(%s seconds)" $secs
     fi
-    echo -e " ####"
+    echo -e " ####${color_reset}"
     echo
     return $ret
 }
 
-
-
 if [ "x$SHELL" != "x/bin/bash" ]; then
     case `ps -o command -p $$` in
         *bash*)
diff --git a/libs/host/Android.mk b/libs/host/Android.mk
index c67afbb..cab878b 100644
--- a/libs/host/Android.mk
+++ b/libs/host/Android.mk
@@ -1,5 +1,6 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
 LOCAL_SRC_FILES:= \
     CopyFile.c
@@ -20,6 +21,8 @@
 # acp to install libhost.
 LOCAL_ACP_UNAVAILABLE:= true
 
+LOCAL_ADDRESS_SANITIZER := false
+
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 # Include toolchain prebuilt modules if they exist.
diff --git a/libs/host/CopyFile.c b/libs/host/CopyFile.c
index ca52565..855a565 100644
--- a/libs/host/CopyFile.c
+++ b/libs/host/CopyFile.c
@@ -28,8 +28,9 @@
 #  define  mkdir(path,mode)   _mkdir(path)
 #endif
 
-#ifndef HAVE_SYMLINKS
-#  define  lstat              stat
+#if defined(_WIN32)
+#  define S_ISLNK(s) 0
+#  define lstat stat
 #  ifndef EACCESS   /* seems to be missing from the Mingw headers */
 #    define  EACCESS            13
 #  endif
@@ -68,15 +69,13 @@
  */
 static bool isHiresMtime(const struct stat* pSrcStat)
 {
-#if HAVE_STAT_ST_MTIM
-#if defined(MACOSX_RSRC)
+#if defined(__CYGWIN__) || defined(__MINGW32__)
+  return 0;
+#elif defined(MACOSX_RSRC)
     return pSrcStat->st_mtimespec.tv_nsec > 0;
 #else
     return pSrcStat->st_mtim.tv_nsec > 0;
 #endif
-#else
-    return 0;
-#endif
 }
 
 /*
@@ -339,7 +338,6 @@
 }
 
 
-#ifdef HAVE_SYMLINKS
 /*
  * Copy a symlink.  This only happens if we're in "no derefence" mode,
  * in which we copy the links rather than the files that are pointed at.
@@ -348,6 +346,9 @@
  * we want to throw it out and replace it.  If it's not a symlink, we
  * need to trash it so we can create one.
  */
+#if defined(_WIN32)
+extern int copySymlink(const char* src, const char* dst, const struct stat* pSrcStat, unsigned int options) __attribute__((error("no symlinks on Windows")));
+#else
 static int copySymlink(const char* src, const char* dst, const struct stat* pSrcStat, unsigned int options)
 {
     struct stat dstStat;
@@ -422,7 +423,7 @@
 
     return 0;
 }
-#endif /* HAVE_SYMLINKS */
+#endif
 
 /*
  * Copy the contents of one directory to another.  Both "src" and "dst"
@@ -618,10 +619,8 @@
         } else {
             retVal = copyDirectory(src, dst, &srcStat, options);
         }
-#ifdef HAVE_SYMLINKS
     } else if (S_ISLNK(srcStat.st_mode)) {
         retVal = copySymlink(src, dst, &srcStat, options);
-#endif		
     } else if (S_ISREG(srcStat.st_mode)) {
         retVal = copyRegular(src, dst, &srcStat, options);
     } else {
diff --git a/libs/host/list.java b/libs/host/list.java
deleted file mode 100644
index 30546e3..0000000
--- a/libs/host/list.java
+++ /dev/null
@@ -1,35 +0,0 @@
-import java.io.*;
-
-public class list {
-    private static char nibble(int c) {
-        return (char)(c < 10 ? ('0' + c) : ('a' + (c-10)));
-    }
-    public static void main(String[] argv)
-    {
-        ByteArrayOutputStream stream = new ByteArrayOutputStream(100);
-        OutputStreamWriter writer = null;
-        try {
-            writer = new OutputStreamWriter(stream, "utf-8");
-        } catch (UnsupportedEncodingException e) {
-            e.printStackTrace(System.err);
-        }
-
-        int n = Integer.parseInt(argv[1], 16);
-        try {
-            writer.write(n);
-            writer.close();
-        } catch (IOException e) {
-            e.printStackTrace(System.err);
-        }
-
-        byte[] array = stream.toByteArray();
-
-        System.out.print("        case '" + argv[0] + "':   return \"");
-        for (int i=0; i<array.length; i++) {
-            int b = array[i];
-            System.out.print("\\x" + nibble((b >> 4) & 0x0f) + nibble(b & 0xf));
-        }
-        System.out.println("\";");
-    }
-}
-
diff --git a/target/board/generic/BoardConfig.mk b/target/board/generic/BoardConfig.mk
index 3ae5860..e06c985 100644
--- a/target/board/generic/BoardConfig.mk
+++ b/target/board/generic/BoardConfig.mk
@@ -82,6 +82,11 @@
         domain.te \
         file.te \
         file_contexts \
+        goldfish_setup.te \
+        goldfish_logcat.te \
+        property.te \
+        property_contexts \
+        qemu_props.te \
         qemud.te \
         rild.te \
         shell.te \
diff --git a/target/board/generic/device.mk b/target/board/generic/device.mk
index 06a7d8a..e56a4d1 100644
--- a/target/board/generic/device.mk
+++ b/target/board/generic/device.mk
@@ -30,8 +30,3 @@
     frameworks/av/media/libstagefright/data/media_codecs_google_video.xml:system/etc/media_codecs_google_video.xml \
     device/generic/goldfish/camera/media_codecs.xml:system/etc/media_codecs.xml \
     hardware/libhardware_legacy/audio/audio_policy.conf:system/etc/audio_policy.conf
-
-PRODUCT_PACKAGES := \
-    audio.primary.goldfish \
-    power.goldfish \
-    vibrator.goldfish
diff --git a/target/board/generic/sepolicy/device.te b/target/board/generic/sepolicy/device.te
index e4af13c..d129441 100644
--- a/target/board/generic/sepolicy/device.te
+++ b/target/board/generic/sepolicy/device.te
@@ -1 +1 @@
-type qemu_device, dev_type;
+type qemu_device, dev_type, mlstrustedobject;
diff --git a/target/board/generic/sepolicy/file_contexts b/target/board/generic/sepolicy/file_contexts
index f204cde..444a47f 100644
--- a/target/board/generic/sepolicy/file_contexts
+++ b/target/board/generic/sepolicy/file_contexts
@@ -1,4 +1,9 @@
+/dev/block/mtdblock0       u:object_r:system_block_device:s0
+/dev/block/mtdblock1       u:object_r:userdata_block_device:s0
+/dev/block/mtdblock2       u:object_r:cache_block_device:s0
 /dev/qemu_.*		u:object_r:qemu_device:s0
 /dev/socket/qemud	u:object_r:qemud_socket:s0
 /system/bin/qemud	u:object_r:qemud_exec:s0
 /sys/qemu_trace(/.*)?	--	u:object_r:sysfs_writable:s0
+/system/etc/init.goldfish.sh u:object_r:goldfish_setup_exec:s0
+/system/bin/qemu-props	     u:object_r:qemu_props_exec:s0
diff --git a/target/board/generic/sepolicy/goldfish_logcat.te b/target/board/generic/sepolicy/goldfish_logcat.te
new file mode 100644
index 0000000..a785355
--- /dev/null
+++ b/target/board/generic/sepolicy/goldfish_logcat.te
@@ -0,0 +1,10 @@
+# goldfish-logcat service:  runs logcat -Q
+type goldfish_logcat, domain;
+
+domain_auto_trans(init, logcat_exec, goldfish_logcat)
+
+# Read from logd.
+read_logd(goldfish_logcat)
+
+# Write to /dev/ttyS2
+allow goldfish_logcat serial_device:chr_file { write open };
diff --git a/target/board/generic/sepolicy/goldfish_setup.te b/target/board/generic/sepolicy/goldfish_setup.te
new file mode 100644
index 0000000..584731e
--- /dev/null
+++ b/target/board/generic/sepolicy/goldfish_setup.te
@@ -0,0 +1,18 @@
+# goldfish-setup service: runs init.goldfish.sh script
+type goldfish_setup, domain;
+type goldfish_setup_exec, exec_type, file_type;
+
+init_daemon_domain(goldfish_setup)
+
+# Inherit open file to shell (interpreter) for script.
+allow goldfish_setup shell_exec:file read;
+
+# Run ifconfig, route commands to configure interfaces and routes.
+allow goldfish_setup system_file:file execute_no_trans;
+allow goldfish_setup self:capability { net_admin net_raw };
+allow goldfish_setup self:udp_socket create_socket_perms;
+
+# Set net.eth0.dns*, debug.sf.nobootanimation
+unix_socket_connect(goldfish_setup, property, init)
+allow goldfish_setup system_prop:property_service set;
+allow goldfish_setup debug_prop:property_service set;
diff --git a/target/board/generic/sepolicy/property.te b/target/board/generic/sepolicy/property.te
new file mode 100644
index 0000000..b3d15f8
--- /dev/null
+++ b/target/board/generic/sepolicy/property.te
@@ -0,0 +1 @@
+type qemu_prop, property_type;
diff --git a/target/board/generic/sepolicy/property_contexts b/target/board/generic/sepolicy/property_contexts
new file mode 100644
index 0000000..5f741f8
--- /dev/null
+++ b/target/board/generic/sepolicy/property_contexts
@@ -0,0 +1 @@
+qemu.                   u:object_r:qemu_prop:s0
diff --git a/target/board/generic/sepolicy/qemu_props.te b/target/board/generic/sepolicy/qemu_props.te
new file mode 100644
index 0000000..05c7461
--- /dev/null
+++ b/target/board/generic/sepolicy/qemu_props.te
@@ -0,0 +1,9 @@
+# qemu-props service:  Sets system properties on boot.
+type qemu_props, domain;
+type qemu_props_exec, exec_type, file_type;
+
+init_daemon_domain(qemu_props)
+
+# Set properties.
+unix_socket_connect(qemu_props, property, init)
+allow qemu_props { qemu_prop dalvik_prop config_prop }:property_service set;
diff --git a/target/board/generic/sepolicy/qemud.te b/target/board/generic/sepolicy/qemud.te
index 4ff02ec..41f2065 100644
--- a/target/board/generic/sepolicy/qemud.te
+++ b/target/board/generic/sepolicy/qemud.te
@@ -3,4 +3,6 @@
 type qemud_exec, exec_type, file_type;
 
 init_daemon_domain(qemud)
-unconfined_domain(qemud)
+
+# Access /dev/ttyS1.
+allow qemud serial_device:chr_file rw_file_perms;
diff --git a/target/board/generic_arm64/BoardConfig.mk b/target/board/generic_arm64/BoardConfig.mk
index 8afd5a8..c98624d 100644
--- a/target/board/generic_arm64/BoardConfig.mk
+++ b/target/board/generic_arm64/BoardConfig.mk
@@ -76,7 +76,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 943718400
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 1073741824
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
diff --git a/target/board/generic_arm64/device.mk b/target/board/generic_arm64/device.mk
index 11a6a31..9647a4e 100644
--- a/target/board/generic_arm64/device.mk
+++ b/target/board/generic_arm64/device.mk
@@ -30,6 +30,6 @@
     frameworks/av/media/libstagefright/data/media_codecs_google_video.xml:system/etc/media_codecs_google_video.xml \
     device/generic/goldfish/camera/media_codecs.xml:system/etc/media_codecs.xml
 
-PRODUCT_PACKAGES := \
-    audio.primary.goldfish \
-    vibrator.goldfish
+# Adjust the Dalvik heap to be appropriate for a tablet.
+$(call inherit-product-if-exists, frameworks/base/build/tablet-dalvik-heap.mk)
+$(call inherit-product-if-exists, frameworks/native/build/tablet-dalvik-heap.mk)
diff --git a/target/board/generic_armv5/BoardConfig.mk b/target/board/generic_armv5/BoardConfig.mk
index 95fb559..016937a 100644
--- a/target/board/generic_armv5/BoardConfig.mk
+++ b/target/board/generic_armv5/BoardConfig.mk
@@ -19,6 +19,5 @@
 TARGET_ARCH_VARIANT := armv5te
 TARGET_CPU_ABI := armeabi
 TARGET_CPU_ABI2 :=
-ARCH_ARM_HAVE_TLS_REGISTER := false
 
 WITH_DEXPREOPT := false
diff --git a/target/board/generic_mips/BoardConfig.mk b/target/board/generic_mips/BoardConfig.mk
index 7cef968..b40f9ba 100644
--- a/target/board/generic_mips/BoardConfig.mk
+++ b/target/board/generic_mips/BoardConfig.mk
@@ -28,6 +28,9 @@
 endif
 TARGET_CPU_ABI  := mips
 
+# Make TARGET_CPU_VARIANT the same as TARGET_ARCH_VARIANT
+TARGET_CPU_VARIANT := $(TARGET_ARCH_VARIANT)
+
 HAVE_HTC_AUDIO_DRIVER := true
 BOARD_USES_GENERIC_AUDIO := true
 
@@ -50,7 +53,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 838860800
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 1073741824
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
@@ -64,6 +67,11 @@
         domain.te \
         file.te \
         file_contexts \
+        goldfish_setup.te \
+        goldfish_logcat.te \
+        property.te \
+        property_contexts \
+        qemu_props.te \
         qemud.te \
         rild.te \
         shell.te \
diff --git a/target/board/generic_mips/device.mk b/target/board/generic_mips/device.mk
index 590f422..06a7d8a 100644
--- a/target/board/generic_mips/device.mk
+++ b/target/board/generic_mips/device.mk
@@ -34,5 +34,4 @@
 PRODUCT_PACKAGES := \
     audio.primary.goldfish \
     power.goldfish \
-    vibrator.goldfish \
-    libffi
+    vibrator.goldfish
diff --git a/target/board/generic_mips64/BoardConfig.mk b/target/board/generic_mips64/BoardConfig.mk
index f8cf4f0..2097635 100644
--- a/target/board/generic_mips64/BoardConfig.mk
+++ b/target/board/generic_mips64/BoardConfig.mk
@@ -38,6 +38,10 @@
 endif
 TARGET_2ND_CPU_ABI  := mips
 
+# Make TARGET_XXX_CPU_VARIANT the same as TARGET_XXX_ARCH_VARIANT
+TARGET_CPU_VARIANT := $(TARGET_ARCH_VARIANT)
+TARGET_2ND_CPU_VARIANT := $(TARGET_2ND_ARCH_VARIANT)
+
 # The emulator (qemu) uses the Goldfish devices
 HAVE_HTC_AUDIO_DRIVER := true
 BOARD_USES_GENERIC_AUDIO := true
@@ -61,8 +65,8 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
-BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 1101004800
+BOARD_USERDATAIMAGE_PARTITION_SIZE := 734003200
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
 BOARD_FLASH_BLOCK_SIZE := 512
diff --git a/target/board/generic_mips64/device.mk b/target/board/generic_mips64/device.mk
index 015686e..66ec9db 100644
--- a/target/board/generic_mips64/device.mk
+++ b/target/board/generic_mips64/device.mk
@@ -33,5 +33,4 @@
 
 PRODUCT_PACKAGES := \
     audio.primary.goldfish \
-    power.goldfish \
-    libffi
+    power.goldfish
diff --git a/target/board/generic_x86/BoardConfig.mk b/target/board/generic_x86/BoardConfig.mk
index 5d091f5..78b7590 100644
--- a/target/board/generic_x86/BoardConfig.mk
+++ b/target/board/generic_x86/BoardConfig.mk
@@ -53,6 +53,11 @@
         file_contexts \
         healthd.te \
         installd.te \
+        goldfish_setup.te \
+        goldfish_logcat.te \
+        property.te \
+        property_contexts \
+        qemu_props.te \
         qemud.te \
         rild.te \
         shell.te \
diff --git a/target/product/aosp_arm64.mk b/target/product/aosp_arm64.mk
index e119466..ea8ec06 100644
--- a/target/product/aosp_arm64.mk
+++ b/target/product/aosp_arm64.mk
@@ -23,8 +23,6 @@
 $(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_base_telephony.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/board/generic_arm64/device.mk)
 
-PRODUCT_RUNTIMES := runtime_libart_default
-
 include $(SRC_TARGET_DIR)/product/emulator.mk
 PRODUCT_NAME := aosp_arm64
 PRODUCT_DEVICE := generic_arm64
diff --git a/target/product/base.mk b/target/product/base.mk
index 0d052b5..85c01a2 100644
--- a/target/product/base.mk
+++ b/target/product/base.mk
@@ -95,7 +95,6 @@
     monkey \
     mtpd \
     ndc \
-    netcfg \
     netd \
     ping \
     ping6 \
diff --git a/target/product/core_minimal.mk b/target/product/core_minimal.mk
index 4c08cb0..33b49a6 100644
--- a/target/product/core_minimal.mk
+++ b/target/product/core_minimal.mk
@@ -51,6 +51,7 @@
     iptables \
     keystore \
     keystore.default \
+    ld.mc \
     libbcc \
     libOpenMAXAL \
     libOpenSLES \
@@ -100,11 +101,10 @@
     ethernet-service \
     wifi-service
 
-PRODUCT_RUNTIMES := runtime_libart_default
-
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
     ro.zygote=zygote32
 PRODUCT_COPY_FILES += \
     system/core/rootdir/init.zygote32.rc:root/init.zygote32.rc
 
+$(call inherit-product, $(SRC_TARGET_DIR)/product/runtime_libart.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
diff --git a/target/product/core_tiny.mk b/target/product/core_tiny.mk
index 9637e34..39789d9 100644
--- a/target/product/core_tiny.mk
+++ b/target/product/core_tiny.mk
@@ -101,8 +101,6 @@
     services \
     wifi-service
 
-PRODUCT_RUNTIMES := runtime_libart_default
-
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
     ro.zygote=zygote32
 PRODUCT_COPY_FILES += \
@@ -111,6 +109,7 @@
 PRODUCT_PROPERTY_OVERRIDES += \
     ro.carrier=unknown
 
+$(call inherit-product, $(SRC_TARGET_DIR)/product/runtime_libart.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
 $(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk)
 
diff --git a/target/product/embedded.mk b/target/product/embedded.mk
index b60c948..96c0b77 100644
--- a/target/product/embedded.mk
+++ b/target/product/embedded.mk
@@ -23,10 +23,10 @@
     atrace \
     bootanimation \
     debuggerd \
-    debuggerd64 \
     dumpstate \
     dumpsys \
     gralloc.default \
+    grep \
     gzip \
     healthd \
     init \
@@ -49,6 +49,7 @@
     libm \
     libpixelflinger \
     libpower \
+    libsigchain \
     libstdc++ \
     libstlport \
     libsurfaceflinger \
@@ -57,18 +58,18 @@
     libui \
     libutils \
     linker \
-    linker64 \
     lmkd \
     logcat \
     logwrapper \
     mkshrc \
     reboot \
+    recovery \
     service \
     servicemanager \
     sh \
     surfaceflinger \
     toolbox \
-    libsigchain
+    toybox \
 
 # SELinux packages
 PRODUCT_PACKAGES += \
@@ -80,6 +81,10 @@
     selinux_version \
     service_contexts
 
+# Ensure that this property is always defined so that bionic_systrace.cpp
+# can rely on it being initially set by init.
+PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
+    debug.atrace.tags.enableflags=0
 
 PRODUCT_COPY_FILES += \
     system/core/rootdir/init.usb.rc:root/init.usb.rc \
diff --git a/target/product/emulator.mk b/target/product/emulator.mk
index 62099df..3a8a4aa 100644
--- a/target/product/emulator.mk
+++ b/target/product/emulator.mk
@@ -41,11 +41,18 @@
     lights.goldfish \
     gps.goldfish \
     sensors.goldfish \
-    e2fsck
+    e2fsck \
+    audio.primary.goldfish \
+    vibrator.goldfish \
+    power.goldfish \
+    sensors.ranchu
 
 
 PRODUCT_COPY_FILES += \
     device/generic/goldfish/fstab.goldfish:root/fstab.goldfish \
     device/generic/goldfish/init.goldfish.rc:root/init.goldfish.rc \
     device/generic/goldfish/init.goldfish.sh:system/etc/init.goldfish.sh \
-    device/generic/goldfish/ueventd.goldfish.rc:root/ueventd.goldfish.rc
+    device/generic/goldfish/ueventd.goldfish.rc:root/ueventd.goldfish.rc \
+    device/generic/goldfish/init.ranchu.rc:root/init.ranchu.rc \
+    device/generic/goldfish/fstab.ranchu:root/fstab.ranchu \
+    device/generic/goldfish/ueventd.ranchu.rc:root/ueventd.ranchu.rc
diff --git a/target/product/full_base.mk b/target/product/full_base.mk
index caace76..d8dad79 100644
--- a/target/product/full_base.mk
+++ b/target/product/full_base.mk
@@ -40,7 +40,6 @@
 
 # Additional settings used in all AOSP builds
 PRODUCT_PROPERTY_OVERRIDES := \
-    ro.com.android.dateformat=MM-dd-yyyy \
     ro.config.ringtone=Ring_Synth_04.ogg \
     ro.config.notification_sound=pixiedust.ogg
 
diff --git a/target/product/full_base_telephony.mk b/target/product/full_base_telephony.mk
index 2fd2ce8..9a2c63a 100644
--- a/target/product/full_base_telephony.mk
+++ b/target/product/full_base_telephony.mk
@@ -19,9 +19,6 @@
 # build quite specifically for the emulator, and might not be
 # entirely appropriate to inherit from for on-device configurations.
 
-PRODUCT_PACKAGES := \
-    VoiceDialer
-
 PRODUCT_PROPERTY_OVERRIDES := \
     keyguard.no_require_sim=true \
     ro.com.android.dataroaming=true
diff --git a/target/product/full_mips64.mk b/target/product/full_mips64.mk
index 408e81c..e813e41 100644
--- a/target/product/full_mips64.mk
+++ b/target/product/full_mips64.mk
@@ -23,8 +23,6 @@
 $(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_base_telephony.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/board/generic_mips64/device.mk)
 
-PRODUCT_RUNTIMES := runtime_libart_default
-
 include $(SRC_TARGET_DIR)/product/emulator.mk
 
 # Overrides
diff --git a/target/product/full_x86_64.mk b/target/product/full_x86_64.mk
index d9c0c1e..051a86e 100755
--- a/target/product/full_x86_64.mk
+++ b/target/product/full_x86_64.mk
@@ -27,8 +27,6 @@
 $(call inherit-product, $(SRC_TARGET_DIR)/product/aosp_base_telephony.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/board/generic_x86_64/device.mk)
 
-PRODUCT_RUNTIMES := runtime_libart_default
-
 include $(SRC_TARGET_DIR)/product/emulator.mk
 
 ifdef NET_ETH0_STARTONBOOT
diff --git a/target/product/generic_no_telephony.mk b/target/product/generic_no_telephony.mk
index 7af62ce..dd18fab 100644
--- a/target/product/generic_no_telephony.mk
+++ b/target/product/generic_no_telephony.mk
@@ -49,9 +49,6 @@
     vibrator.default \
     power.default
 
-PRODUCT_PACKAGES += \
-    local_time.default
-
 PRODUCT_COPY_FILES := \
         frameworks/av/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf
 
diff --git a/target/product/runtime_common.mk b/target/product/runtime_common.mk
deleted file mode 100644
index 9ae182a..0000000
--- a/target/product/runtime_common.mk
+++ /dev/null
@@ -1,41 +0,0 @@
-#
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# Common runtime modules for both Dalvik and ART
-
-PRODUCT_PACKAGES += \
-    apache-xml \
-    bouncycastle \
-    cacerts \
-    conscrypt \
-    core-junit \
-    dalvikvm \
-    dexdeps \
-    dexdump \
-    dexlist \
-    dmtracedump \
-    dx \
-    ext \
-    hprof-conv \
-    libcrypto \
-    libexpat \
-    libicui18n \
-    libicuuc \
-    libjavacore \
-    libnativehelper \
-    libssl \
-    libz \
-    okhttp
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
index e4200b3..a35122b 100644
--- a/target/product/runtime_libart.mk
+++ b/target/product/runtime_libart.mk
@@ -17,11 +17,33 @@
 # Provides a functioning ART environment without Android frameworks
 
 PRODUCT_PACKAGES += \
-        core-libart \
-        libart \
-        dex2oat \
-        oatdump \
-        patchoat
+    apache-xml \
+    bouncycastle \
+    cacerts \
+    conscrypt \
+    core-junit \
+    core-libart \
+    dalvikvm \
+    dex2oat \
+    dexdeps \
+    dexdump \
+    dexlist \
+    dmtracedump \
+    dx \
+    ext \
+    hprof-conv \
+    libart \
+    libcrypto \
+    libexpat \
+    libicui18n \
+    libicuuc \
+    libjavacore \
+    libnativehelper \
+    libssl \
+    libz \
+    oatdump \
+    okhttp \
+    patchoat
 
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
     dalvik.vm.image-dex2oat-Xms=64m \
@@ -29,5 +51,3 @@
     dalvik.vm.dex2oat-Xms=64m \
     dalvik.vm.dex2oat-Xmx=512m \
     ro.dalvik.vm.native.bridge=0 \
-
-include $(SRC_TARGET_DIR)/product/runtime_common.mk
diff --git a/target/product/runtime_libart_default.mk b/target/product/runtime_libart_default.mk
deleted file mode 100644
index 2d4c793..0000000
--- a/target/product/runtime_libart_default.mk
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# Set ART as the default runtime environment
-
-DALVIK_VM_LIB := libart.so
-
-include $(SRC_TARGET_DIR)/product/runtime_libart.mk
diff --git a/target/product/runtime_libdvm.mk b/target/product/runtime_libdvm.mk
deleted file mode 100644
index 638d7d7..0000000
--- a/target/product/runtime_libdvm.mk
+++ /dev/null
@@ -1,24 +0,0 @@
-#
-# Copyright (C) 2013 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.
-#
-
-# Provides a functioning Dalvik environment without Android frameworks
-
-PRODUCT_PACKAGES += \
-    core \
-    libdvm \
-    dexopt
-
-include $(SRC_TARGET_DIR)/product/runtime_common.mk
diff --git a/target/product/runtime_libdvm_default.mk b/target/product/runtime_libdvm_default.mk
deleted file mode 100644
index b581ce5..0000000
--- a/target/product/runtime_libdvm_default.mk
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# Set Dalvik as the default runtime environment
-
-DALVIK_VM_LIB := libdvm.so
-
-include $(SRC_TARGET_DIR)/product/runtime_libdvm.mk
diff --git a/target/product/sdk_phone_arm64.mk b/target/product/sdk_phone_arm64.mk
index c501f14..a0cf6c1 100644
--- a/target/product/sdk_phone_arm64.mk
+++ b/target/product/sdk_phone_arm64.mk
@@ -21,6 +21,7 @@
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core_64_bit.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/sdk_base.mk)
+$(call inherit-product, $(SRC_TARGET_DIR)/board/generic_arm64/device.mk)
 
 # Overrides
 PRODUCT_BRAND := generic_arm64
diff --git a/tools/acp/Android.mk b/tools/acp/Android.mk
index 33c5567..2b41bc1 100644
--- a/tools/acp/Android.mk
+++ b/tools/acp/Android.mk
@@ -4,6 +4,7 @@
 
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
 LOCAL_SRC_FILES := \
     acp.c
@@ -21,5 +22,7 @@
 LOCAL_C_INCLUDES := build/libs/host/include
 LOCAL_MODULE := acp
 LOCAL_ACP_UNAVAILABLE := true
+LOCAL_CXX_STL := none
+LOCAL_ADDRESS_SANITIZER := false
 
 include $(BUILD_HOST_EXECUTABLE)
diff --git a/tools/atree/files.cpp b/tools/atree/files.cpp
index df3e987..d945f58 100644
--- a/tools/atree/files.cpp
+++ b/tools/atree/files.cpp
@@ -447,14 +447,7 @@
             continue;
         }
         string entry = path_append(path, ent->d_name);
-#ifdef HAVE_DIRENT_D_TYPE
-		bool is_directory = (ent->d_type == DT_DIR);
-#else
-	    // If dirent.d_type is missing, then use stat instead
-		struct stat stat_buf;
-		stat(entry.c_str(), &stat_buf);
-		bool is_directory = S_ISDIR(stat_buf.st_mode);
-#endif
+        bool is_directory = (ent->d_type == DT_DIR);
         add_more(entry, is_directory, rec, more);
         if (is_directory) {
             dirs.push_back(entry);
diff --git a/tools/atree/fs.cpp b/tools/atree/fs.cpp
index 9468cfd..6cd080e 100644
--- a/tools/atree/fs.cpp
+++ b/tools/atree/fs.cpp
@@ -63,14 +63,7 @@
             string full = path;
             full += '/';
             full += ent->d_name;
-#ifdef HAVE_DIRENT_D_TYPE
             bool is_directory = (ent->d_type == DT_DIR);
-#else
-            // If dirent.d_type is missing, then use stat instead
-            struct stat stat_buf;
-            stat(full.c_str(), &stat_buf);
-            bool is_directory = S_ISDIR(stat_buf.st_mode);
-#endif
             if (is_directory) {
                 dirs.push_back(full);
             } else {
diff --git a/tools/buildinfo.sh b/tools/buildinfo.sh
index a80b2db..dcd9ab5 100755
--- a/tools/buildinfo.sh
+++ b/tools/buildinfo.sh
@@ -36,11 +36,8 @@
 echo "ro.product.cpu.abilist64=$TARGET_CPU_ABI_LIST_64_BIT"
 
 echo "ro.product.manufacturer=$PRODUCT_MANUFACTURER"
-if [ -n "$PRODUCT_DEFAULT_LANGUAGE" ] ; then
-  echo "ro.product.locale.language=$PRODUCT_DEFAULT_LANGUAGE"
-fi
-if [ -n "$PRODUCT_DEFAULT_REGION" ] ; then
-  echo "ro.product.locale.region=$PRODUCT_DEFAULT_REGION"
+if [ -n "$PRODUCT_DEFAULT_LOCALE" ] ; then
+  echo "ro.product.locale=$PRODUCT_DEFAULT_LOCALE"
 fi
 echo "ro.wifi.channels=$PRODUCT_DEFAULT_WIFI_CHANNELS"
 echo "ro.board.platform=$TARGET_BOARD_PLATFORM"
diff --git a/tools/post_process_props.py b/tools/post_process_props.py
index 030826d..fa6106f 100755
--- a/tools/post_process_props.py
+++ b/tools/post_process_props.py
@@ -56,8 +56,6 @@
   """
   check_pass = True
   buildprops = prop.to_dict()
-  dev_build = buildprops.get("ro.build.version.incremental",
-                             "").startswith("eng")
   for key, value in buildprops.iteritems():
     # Check build properties' length.
     if len(key) > PROP_NAME_MAX:
@@ -66,19 +64,10 @@
                        (key, PROP_NAME_MAX))
       sys.stderr.write("%s (%d)\n" % (key, len(key)))
     if len(value) > PROP_VALUE_MAX:
-      # If dev build, show a warning message, otherwise fail the
-      # build with error message
-      if dev_build:
-        sys.stderr.write("warning: %s exceeds %d bytes: " %
-                         (key, PROP_VALUE_MAX))
-        sys.stderr.write("%s (%d)\n" % (value, len(value)))
-        sys.stderr.write("warning: This will cause the %s " % key)
-        sys.stderr.write("property return as empty at runtime\n")
-      else:
-        check_pass = False
-        sys.stderr.write("error: %s cannot exceed %d bytes: " %
-                         (key, PROP_VALUE_MAX))
-        sys.stderr.write("%s (%d)\n" % (value, len(value)))
+      check_pass = False
+      sys.stderr.write("error: %s cannot exceed %d bytes: " %
+                       (key, PROP_VALUE_MAX))
+      sys.stderr.write("%s (%d)\n" % (value, len(value)))
   return check_pass
 
 class PropFile:
diff --git a/tools/product_debug.py b/tools/product_debug.py
index 661c5b7..ff2657c 100755
--- a/tools/product_debug.py
+++ b/tools/product_debug.py
@@ -89,7 +89,6 @@
       "PRODUCT_COPY_FILES",
       "PRODUCT_PACKAGES",
       "PRODUCT_LOCALES",
-      "PRODUCT_FACTORY_RAMDISK_MODULES",
       "PRODUCT_PROPERTY_OVERRIDES",
     )
 
diff --git a/tools/releasetools/add_img_to_target_files.py b/tools/releasetools/add_img_to_target_files.py
index e98e4b6..b3d2ede 100755
--- a/tools/releasetools/add_img_to_target_files.py
+++ b/tools/releasetools/add_img_to_target_files.py
@@ -30,9 +30,6 @@
 
 import errno
 import os
-import re
-import shutil
-import subprocess
 import tempfile
 import zipfile
 
@@ -70,10 +67,8 @@
   block_list = common.MakeTempFile(prefix="system-blocklist-", suffix=".map")
   imgname = BuildSystem(OPTIONS.input_tmp, OPTIONS.info_dict,
                         block_list=block_list)
-  with open(imgname, "rb") as f:
-    common.ZipWriteStr(output_zip, prefix + "system.img", f.read())
-  with open(block_list, "rb") as f:
-    common.ZipWriteStr(output_zip, prefix + "system.map", f.read())
+  common.ZipWrite(output_zip, imgname, prefix + "system.img")
+  common.ZipWrite(output_zip, block_list, prefix + "system.map")
 
 
 def BuildSystem(input_dir, info_dict, block_list=None):
@@ -94,10 +89,8 @@
   block_list = common.MakeTempFile(prefix="vendor-blocklist-", suffix=".map")
   imgname = BuildVendor(OPTIONS.input_tmp, OPTIONS.info_dict,
                      block_list=block_list)
-  with open(imgname, "rb") as f:
-    common.ZipWriteStr(output_zip, prefix + "vendor.img", f.read())
-  with open(block_list, "rb") as f:
-    common.ZipWriteStr(output_zip, prefix + "vendor.map", f.read())
+  common.ZipWrite(output_zip, imgname, prefix + "vendor.img")
+  common.ZipWrite(output_zip, block_list, prefix + "vendor.map")
 
 
 def BuildVendor(input_dir, info_dict, block_list=None):
@@ -142,11 +135,20 @@
   fc_config = os.path.join(input_dir, "BOOT/RAMDISK/file_contexts")
   if not os.path.exists(fc_config): fc_config = None
 
+  # Override values loaded from info_dict.
+  if fs_config:
+    image_props["fs_config"] = fs_config
+  if fc_config:
+    image_props["selinux_fc"] = fc_config
+  if block_list:
+    image_props["block_list"] = block_list
+  if image_props.get("system_root_image") == "true":
+    image_props["ramdisk_dir"] = os.path.join(input_dir, "BOOT/RAMDISK")
+    image_props["ramdisk_fs_config"] = os.path.join(
+        input_dir, "META/boot_filesystem_config.txt")
+
   succ = build_image.BuildImage(os.path.join(input_dir, what),
-                                image_props, img,
-                                fs_config=fs_config,
-                                fc_config=fc_config,
-                                block_list=block_list)
+                                image_props, img)
   assert succ, "build " + what + ".img image failed"
 
   return img
@@ -296,7 +298,6 @@
   output_zip.close()
 
 def main(argv):
-
   def option_handler(o, a):
     if o in ("-a", "--add_missing"):
       OPTIONS.add_missing = True
diff --git a/tools/releasetools/blockimgdiff.py b/tools/releasetools/blockimgdiff.py
index 8b179d5..f031078 100644
--- a/tools/releasetools/blockimgdiff.py
+++ b/tools/releasetools/blockimgdiff.py
@@ -140,8 +140,11 @@
     self.style = style
     self.intact = (getattr(tgt_ranges, "monotonic", False) and
                    getattr(src_ranges, "monotonic", False))
-    self.goes_before = {}
-    self.goes_after = {}
+
+    # We use OrderedDict rather than dict so that the output is repeatable;
+    # otherwise it would depend on the hash values of the Transfer objects.
+    self.goes_before = OrderedDict()
+    self.goes_after = OrderedDict()
 
     self.stash_before = []
     self.use_stash = []
@@ -277,6 +280,8 @@
       if stashed_blocks > max_stashed_blocks:
         max_stashed_blocks = stashed_blocks
 
+      free_string = []
+
       if self.version == 1:
         src_string = xf.src_ranges.to_string_raw()
       elif self.version == 2:
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
index 24d5665..97353df 100755
--- a/tools/releasetools/build_image.py
+++ b/tools/releasetools/build_image.py
@@ -198,25 +198,39 @@
   shutil.rmtree(tempdir_name, ignore_errors=True)
   return True
 
-def BuildImage(in_dir, prop_dict, out_file,
-               fs_config=None,
-               fc_config=None,
-               block_list=None):
+def BuildImage(in_dir, prop_dict, out_file):
   """Build an image to out_file from in_dir with property prop_dict.
 
   Args:
     in_dir: path of input directory.
     prop_dict: property dictionary.
     out_file: path of the output image file.
-    fs_config: path to the fs_config file (typically
-      META/filesystem_config.txt).  If None then the configuration in
-      the local client will be used.
-    fc_config: path to the SELinux file_contexts file.  If None then
-      the value from prop_dict['selinux_fc'] will be used.
 
   Returns:
     True iff the image is built successfully.
   """
+  # system_root_image=true: build a system.img that combines the contents of /system
+  # and the ramdisk, and can be mounted at the root of the file system.
+  origin_in = in_dir
+  fs_config = prop_dict.get("fs_config")
+  if (prop_dict.get("system_root_image") == "true"
+      and prop_dict["mount_point"] == "system"):
+    in_dir = tempfile.mkdtemp()
+    # Change the mount point to "/"
+    prop_dict["mount_point"] = "/"
+    if fs_config:
+      # We need to merge the fs_config files of system and ramdisk.
+      fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config",
+                                              suffix=".txt")
+      os.close(fd)
+      with open(merged_fs_config, "w") as fw:
+        if "ramdisk_fs_config" in prop_dict:
+          with open(prop_dict["ramdisk_fs_config"]) as fr:
+            fw.writelines(fr.readlines())
+        with open(fs_config) as fr:
+          fw.writelines(fr.readlines())
+      fs_config = merged_fs_config
+
   build_command = []
   fs_type = prop_dict.get("fs_type", "")
   run_fsck = False
@@ -244,14 +258,19 @@
       build_command.extend(["-j", prop_dict["journal_size"]])
     if "timestamp" in prop_dict:
       build_command.extend(["-T", str(prop_dict["timestamp"])])
-    if fs_config is not None:
+    if fs_config:
       build_command.extend(["-C", fs_config])
-    if block_list is not None:
-      build_command.extend(["-B", block_list])
-    if fc_config is not None:
-      build_command.append(fc_config)
-    elif "selinux_fc" in prop_dict:
+    if "block_list" in prop_dict:
+      build_command.extend(["-B", prop_dict["block_list"]])
+    build_command.extend(["-L", prop_dict["mount_point"]])
+    if "selinux_fc" in prop_dict:
       build_command.append(prop_dict["selinux_fc"])
+  elif fs_type.startswith("squash"):
+    build_command = ["mksquashfsimage.sh"]
+    build_command.extend([in_dir, out_file])
+    build_command.extend(["-m", prop_dict["mount_point"]])
+    if "selinux_fc" in prop_dict:
+      build_command.extend(["-c", prop_dict["selinux_fc"]])
   elif fs_type.startswith("f2fs"):
     build_command = ["mkf2fsuserimg.sh"]
     build_command.extend([out_file, prop_dict["partition_size"]])
@@ -265,7 +284,23 @@
       build_command.append(prop_dict["selinux_fc"])
       build_command.append(prop_dict["mount_point"])
 
-  exit_code = RunCommand(build_command)
+  if in_dir != origin_in:
+    # Construct a staging directory of the root file system.
+    ramdisk_dir = prop_dict.get("ramdisk_dir")
+    if ramdisk_dir:
+      shutil.rmtree(in_dir)
+      shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
+    staging_system = os.path.join(in_dir, "system")
+    shutil.rmtree(staging_system, ignore_errors=True)
+    shutil.copytree(origin_in, staging_system, symlinks=True)
+  try:
+    exit_code = RunCommand(build_command)
+  finally:
+    if in_dir != origin_in:
+      # Clean up temporary directories and files.
+      shutil.rmtree(in_dir, ignore_errors=True)
+      if fs_config:
+        os.remove(fs_config)
   if exit_code != 0:
     return False
 
@@ -320,9 +355,13 @@
   d["mount_point"] = mount_point
   if mount_point == "system":
     copy_prop("fs_type", "fs_type")
+    # Copy the generic sysetem fs type first, override with specific one if available.
+    copy_prop("system_fs_type", "fs_type")
     copy_prop("system_size", "partition_size")
     copy_prop("system_journal_size", "journal_size")
     copy_prop("system_verity_block_device", "verity_block_device")
+    copy_prop("system_root_image","system_root_image")
+    copy_prop("ramdisk_dir","ramdisk_dir")
   elif mount_point == "data":
     # Copy the generic fs type first, override with specific one if available.
     copy_prop("fs_type", "fs_type")
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index a596c26..6903dc66 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -781,6 +781,46 @@
     return result
 
 
+def ZipWrite(zip_file, filename, arcname=None, perms=0o644,
+             compress_type=None):
+  import datetime
+
+  # http://b/18015246
+  # Python 2.7's zipfile implementation wrongly thinks that zip64 is required
+  # for files larger than 2GiB. We can work around this by adjusting their
+  # limit. Note that `zipfile.writestr()` will not work for strings larger than
+  # 2GiB. The Python interpreter sometimes rejects strings that large (though
+  # it isn't clear to me exactly what circumstances cause this).
+  # `zipfile.write()` must be used directly to work around this.
+  #
+  # This mess can be avoided if we port to python3.
+  saved_zip64_limit = zipfile.ZIP64_LIMIT
+  zipfile.ZIP64_LIMIT = (1 << 32) - 1
+
+  if compress_type is None:
+    compress_type = zip_file.compression
+  if arcname is None:
+    arcname = filename
+
+  saved_stat = os.stat(filename)
+
+  try:
+    # `zipfile.write()` doesn't allow us to pass ZipInfo, so just modify the
+    # file to be zipped and reset it when we're done.
+    os.chmod(filename, perms)
+
+    # Use a fixed timestamp so the output is repeatable.
+    epoch = datetime.datetime.fromtimestamp(0)
+    timestamp = (datetime.datetime(2009, 1, 1) - epoch).total_seconds()
+    os.utime(filename, (timestamp, timestamp))
+
+    zip_file.write(filename, arcname=arcname, compress_type=compress_type)
+  finally:
+    os.chmod(filename, saved_stat.st_mode)
+    os.utime(filename, (saved_stat.st_atime, saved_stat.st_mtime))
+    zipfile.ZIP64_LIMIT = saved_zip64_limit
+
+
 def ZipWriteStr(zip, filename, data, perms=0644, compression=None):
   # use a fixed timestamp so the output is repeatable.
   zinfo = zipfile.ZipInfo(filename=filename,
@@ -1058,58 +1098,75 @@
     self._WriteUpdate(script, output_zip)
 
   def WriteVerifyScript(self, script):
+    partition = self.partition
     if not self.src:
-      script.Print("Image %s will be patched unconditionally." % (self.partition,))
+      script.Print("Image %s will be patched unconditionally." % (partition,))
     else:
+      if self.version >= 3:
+        script.AppendExtra(('if block_image_verify("%s", '
+                            'package_extract_file("%s.transfer.list"), '
+                            '"%s.new.dat", "%s.patch.dat") then') %
+                           (self.device, partition, partition, partition))
+      else:
+        script.AppendExtra('if range_sha1("%s", "%s") == "%s" then' %
+                            (self.device, self.src.care_map.to_string_raw(),
+                            self.src.TotalSha1()))
+      script.Print('Verified %s image...' % (partition,))
+      script.AppendExtra('else');
+
+      # When generating incrementals for the system and vendor partitions,
+      # explicitly check the first block (which contains the superblock) of
+      # the partition to see if it's what we expect. If this check fails,
+      # give an explicit log message about the partition having been
+      # remounted R/W (the most likely explanation) and the need to flash to
+      # get OTAs working again.
       if self.check_first_block:
         self._CheckFirstBlock(script)
 
-      script.AppendExtra('if range_sha1("%s", "%s") == "%s" then' %
-                         (self.device, self.src.care_map.to_string_raw(),
-                          self.src.TotalSha1()))
-      script.Print("Verified %s image..." % (self.partition,))
-      # Abort the OTA update if it doesn't support resumable OTA (i.e. version<3)
-      # and the checksum doesn't match the one in the source partition.
-      if self.version < 3:
-        script.AppendExtra(('else\n'
-                            '  abort("%s partition has unexpected contents");\n'
-                            'endif;') % (self.partition))
-      else:
-        script.AppendExtra(('else\n'
-                            '  (range_sha1("%s", "%s") == "%s") ||\n'
-                            '  abort("%s partition has unexpected contents");\n'
-                            'endif;') %
-                           (self.device, self.tgt.care_map.to_string_raw(),
-                            self.tgt.TotalSha1(), self.partition))
+      # Abort the OTA update. Note that the incremental OTA cannot be applied
+      # even if it may match the checksum of the target partition.
+      # a) If version < 3, operations like move and erase will make changes
+      #    unconditionally and damage the partition.
+      # b) If version >= 3, it won't even reach here.
+      script.AppendExtra(('abort("%s partition has unexpected contents");\n'
+                          'endif;') % (partition,))
 
   def _WriteUpdate(self, script, output_zip):
-    partition = self.partition
-    with open(self.path + ".transfer.list", "rb") as f:
-      ZipWriteStr(output_zip, partition + ".transfer.list", f.read())
-    with open(self.path + ".new.dat", "rb") as f:
-      ZipWriteStr(output_zip, partition + ".new.dat", f.read())
-    with open(self.path + ".patch.dat", "rb") as f:
-      ZipWriteStr(output_zip, partition + ".patch.dat", f.read(),
-                         compression=zipfile.ZIP_STORED)
+    ZipWrite(output_zip,
+             '{}.transfer.list'.format(self.path),
+             '{}.transfer.list'.format(self.partition))
+    ZipWrite(output_zip,
+             '{}.new.dat'.format(self.path),
+             '{}.new.dat'.format(self.partition))
+    ZipWrite(output_zip,
+             '{}.patch.dat'.format(self.path),
+             '{}.patch.dat'.format(self.partition),
+             compress_type=zipfile.ZIP_STORED)
 
-    call = (('block_image_update("%s", '
-             'package_extract_file("%s.transfer.list"), '
-             '"%s.new.dat", "%s.patch.dat");\n') %
-            (self.device, partition, partition, partition))
+    call = ('block_image_update("{device}", '
+            'package_extract_file("{partition}.transfer.list"), '
+            '"{partition}.new.dat", "{partition}.patch.dat");\n'.format(
+                device=self.device, partition=self.partition))
     script.AppendExtra(script._WordWrap(call))
 
+  def _HashBlocks(self, source, ranges):
+    data = source.ReadRangeSet(ranges)
+    ctx = sha1()
+
+    for p in data:
+      ctx.update(p)
+
+    return ctx.hexdigest()
+
   def _CheckFirstBlock(self, script):
     r = RangeSet((0, 1))
-    h = sha1()
-    for data in self.src.ReadRangeSet(r):
-      h.update(data)
-    h = h.hexdigest()
+    srchash = self._HashBlocks(self.src, r);
 
     script.AppendExtra(('(range_sha1("%s", "%s") == "%s") || '
                         'abort("%s has been remounted R/W; '
                         'reflash device to reenable OTA updates");')
-                       % (self.device, r.to_string_raw(), h, self.device))
-
+                       % (self.device, r.to_string_raw(), srchash,
+                          self.device))
 
 DataImage = blockimgdiff.DataImage
 
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index e52c264..934d751 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -74,11 +74,11 @@
       raise ValueError("must specify an OEM property")
     if not value:
       raise ValueError("must specify the OEM value")
-    cmd = ('file_getprop("/oem/oem.prop", "%s") == "%s" || '
-           'abort("This package expects the value \\"%s\\"  for '
-           '\\"%s\\" on the OEM partition; '
-           'this has value \\"" + file_getprop("/oem/oem.prop") + "\\".");'
-           ) % (name, value, name, value)
+    cmd = ('file_getprop("/oem/oem.prop", "{name}") == "{value}" || '
+           'abort("This package expects the value \\"{value}\\" for '
+           '\\"{name}\\" on the OEM partition; this has value \\"" + '
+           'file_getprop("/oem/oem.prop", "{name}") + "\\".");'
+           ).format(name=name, value=value)
     self.script.append(cmd)
 
   def AssertSomeFingerprint(self, *fp):
diff --git a/tools/releasetools/img_from_target_files.py b/tools/releasetools/img_from_target_files.py
index 4b88e73..4dda0b7 100755
--- a/tools/releasetools/img_from_target_files.py
+++ b/tools/releasetools/img_from_target_files.py
@@ -88,11 +88,13 @@
       # and all we have to do is copy them to the output zip.
       images = os.listdir(images_path)
       if images:
-        for i in images:
-          if bootable_only and i not in ("boot.img", "recovery.img"): continue
-          if not i.endswith(".img"): continue
-          with open(os.path.join(images_path, i), "r") as f:
-            common.ZipWriteStr(output_zip, i, f.read())
+        for image in images:
+          if bootable_only and image not in ("boot.img", "recovery.img"):
+            continue
+          if not image.endswith(".img"):
+            continue
+          common.ZipWrite(
+              output_zip, os.path.join(images_path, image), image)
         done = True
 
     if not done:
@@ -139,7 +141,13 @@
 
   finally:
     print "cleaning up..."
+    # http://b/18015246
+    # See common.py for context.  zipfile also refers to ZIP64_LIMIT during
+    # close() when it writes out the central directory.
+    saved_zip64_limit = zipfile.ZIP64_LIMIT
+    zipfile.ZIP64_LIMIT = (1 << 32) - 1
     output_zip.close()
+    zipfile.ZIP64_LIMIT = saved_zip64_limit
     shutil.rmtree(OPTIONS.input_tmp)
 
   print "done."
diff --git a/tools/releasetools/ota_from_target_files b/tools/releasetools/ota_from_target_files
index 25309a4..b71baf9 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -349,8 +349,9 @@
   partition = itemset.partition
 
   for info in input_zip.infolist():
-    if info.filename.startswith(partition.upper() + "/"):
-      basefilename = info.filename[7:]
+    prefix = partition.upper() + "/"
+    if info.filename.startswith(prefix):
+      basefilename = info.filename[len(prefix):]
       if IsSymlink(info):
         symlinks.append((input_zip.read(info.filename),
                          "/" + partition + "/" + basefilename))
@@ -646,10 +647,8 @@
   WriteMetadata(metadata, output_zip)
 
 
-def WritePolicyConfig(file_context, output_zip):
-  f = open(file_context, 'r');
-  basename = os.path.basename(file_context)
-  common.ZipWriteStr(output_zip, basename, f.read())
+def WritePolicyConfig(file_name, output_zip):
+  common.ZipWrite(output_zip, file_name, os.path.basename(file_name))
 
 
 def WriteMetadata(metadata, output_zip):
@@ -665,7 +664,7 @@
   prefix = partition.upper() + "/"
   for info in z.infolist():
     if info.filename.startswith(prefix) and not IsSymlink(info):
-      basefilename = info.filename[7:]
+      basefilename = info.filename[len(prefix):]
       fn = partition + "/" + basefilename
       data = z.read(info.filename)
       out[fn] = common.File(fn, data)
diff --git a/tools/releasetools/sign_target_files_apks b/tools/releasetools/sign_target_files_apks
index 931acb8..9e61051 100755
--- a/tools/releasetools/sign_target_files_apks
+++ b/tools/releasetools/sign_target_files_apks
@@ -179,7 +179,8 @@
       ReplaceVerityPrivateKey(input_tf_zip, output_tf_zip, misc_info, OPTIONS.replace_verity_private_key[1])
     elif (info.filename == "BOOT/RAMDISK/verity_key" and
         OPTIONS.replace_verity_public_key):
-      ReplaceVerityPublicKey(output_tf_zip, OPTIONS.replace_verity_public_key[1])
+      new_data = ReplaceVerityPublicKey(output_tf_zip, OPTIONS.replace_verity_public_key[1])
+      write_to_temp(info.filename, info.external_attr, new_data)
     elif (info.filename.startswith("BOOT/") or
         info.filename.startswith("RECOVERY/") or
         info.filename.startswith("META/") or
@@ -392,7 +393,9 @@
 def ReplaceVerityPublicKey(targetfile_zip, key_path):
   print "Replacing verity public key with %s" % key_path
   with open(key_path) as f:
-    common.ZipWriteStr(targetfile_zip, "BOOT/RAMDISK/verity_key", f.read())
+    data = f.read()
+  common.ZipWriteStr(targetfile_zip, "BOOT/RAMDISK/verity_key", data)
+  return data
 
 def ReplaceVerityPrivateKey(targetfile_input_zip, targetfile_output_zip, misc_info, key_path):
   print "Replacing verity private key with %s" % key_path
@@ -400,6 +403,7 @@
   original_misc_info = targetfile_input_zip.read("META/misc_info.txt")
   new_misc_info = original_misc_info.replace(current_key, key_path)
   common.ZipWriteStr(targetfile_output_zip, "META/misc_info.txt", new_misc_info)
+  misc_info["verity_key"] = key_path
 
 def BuildKeyMap(misc_info, key_mapping_options):
   for s, d in key_mapping_options:
diff --git a/tools/releasetools/test_common.py b/tools/releasetools/test_common.py
new file mode 100644
index 0000000..5fdc132
--- /dev/null
+++ b/tools/releasetools/test_common.py
@@ -0,0 +1,110 @@
+#
+# 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.
+#
+import os
+import tempfile
+import time
+import unittest
+import zipfile
+
+import common
+
+
+def random_string_with_holes(size, block_size, step_size):
+  data = ["\0"] * size
+  for begin in range(0, size, step_size):
+    end = begin + block_size
+    data[begin:end] = os.urandom(block_size)
+  return "".join(data)
+
+
+class CommonZipTest(unittest.TestCase):
+  def _test_ZipWrite(self, contents, extra_zipwrite_args=None):
+    extra_zipwrite_args = dict(extra_zipwrite_args or {})
+
+    test_file = tempfile.NamedTemporaryFile(delete=False)
+    zip_file = tempfile.NamedTemporaryFile(delete=False)
+
+    test_file_name = test_file.name
+    zip_file_name = zip_file.name
+
+    # File names within an archive strip the leading slash.
+    arcname = extra_zipwrite_args.get("arcname", test_file_name)
+    if arcname[0] == "/":
+      arcname = arcname[1:]
+
+    zip_file.close()
+    zip_file = zipfile.ZipFile(zip_file_name, "w")
+
+    try:
+      test_file.write(contents)
+      test_file.close()
+
+      old_stat = os.stat(test_file_name)
+      expected_mode = extra_zipwrite_args.get("perms", 0o644)
+
+      time.sleep(5)  # Make sure the atime/mtime will change measurably.
+
+      common.ZipWrite(zip_file, test_file_name, **extra_zipwrite_args)
+
+      new_stat = os.stat(test_file_name)
+      self.assertEqual(int(old_stat.st_mode), int(new_stat.st_mode))
+      self.assertEqual(int(old_stat.st_mtime), int(new_stat.st_mtime))
+      self.assertIsNone(zip_file.testzip())
+
+      zip_file.close()
+      zip_file = zipfile.ZipFile(zip_file_name, "r")
+      info = zip_file.getinfo(arcname)
+
+      self.assertEqual(info.date_time, (2009, 1, 1, 0, 0, 0))
+      mode = (info.external_attr >> 16) & 0o777
+      self.assertEqual(mode, expected_mode)
+      self.assertEqual(zip_file.read(arcname), contents)
+      self.assertIsNone(zip_file.testzip())
+    finally:
+      os.remove(test_file_name)
+      os.remove(zip_file_name)
+
+  def test_ZipWrite(self):
+    file_contents = os.urandom(1024)
+    self._test_ZipWrite(file_contents)
+
+  def test_ZipWrite_with_opts(self):
+    file_contents = os.urandom(1024)
+    self._test_ZipWrite(file_contents, {
+        "arcname": "foobar",
+        "perms": 0o777,
+        "compress_type": zipfile.ZIP_DEFLATED,
+    })
+
+  def test_ZipWrite_large_file(self):
+    kilobytes = 1024
+    megabytes = 1024 * kilobytes
+    gigabytes = 1024 * megabytes
+
+    size = int(2 * gigabytes + 1)
+    block_size = 4 * kilobytes
+    step_size = 4 * megabytes
+    file_contents = random_string_with_holes(
+        size, block_size, step_size)
+    self._test_ZipWrite(file_contents, {
+        "compress_type": zipfile.ZIP_DEFLATED,
+    })
+
+  def test_ZipWrite_resets_ZIP64_LIMIT(self):
+    default_limit = (1 << 31) - 1
+    self.assertEqual(default_limit, zipfile.ZIP64_LIMIT)
+    self._test_ZipWrite('')
+    self.assertEqual(default_limit, zipfile.ZIP64_LIMIT)
diff --git a/tools/signapk/SignApk.java b/tools/signapk/SignApk.java
index e661e50..88f486a 100644
--- a/tools/signapk/SignApk.java
+++ b/tools/signapk/SignApk.java
@@ -35,6 +35,7 @@
 import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
 import org.bouncycastle.util.encoders.Base64;
 
+import java.io.Console;
 import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -166,18 +167,17 @@
     }
 
     /**
-     * Reads the password from stdin and returns it as a string.
+     * Reads the password from console and returns it as a string.
      *
      * @param keyFile The file containing the private key.  Used to prompt the user.
      */
     private static String readPassword(File keyFile) {
-        // TODO: use Console.readPassword() when it's available.
-        System.out.print("Enter password for " + keyFile + " (password will not be hidden): ");
-        System.out.flush();
-        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
-        try {
-            return stdin.readLine();
-        } catch (IOException ex) {
+        Console console;
+        char[] pwd;
+        if((console = System.console()) != null &&
+           (pwd = console.readPassword("[%s]", "Enter password for " + keyFile)) != null){
+            return String.valueOf(pwd);
+        } else {
             return null;
         }
     }
@@ -621,8 +621,12 @@
             this.type = new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId());
         }
 
+        /**
+         * This should actually return byte[] or something similar, but nothing
+         * actually checks it currently.
+         */
         public Object getContent() {
-            throw new UnsupportedOperationException();
+            return this;
         }
 
         public ASN1ObjectIdentifier getContentType() {
diff --git a/tools/signtos/Android.mk b/tools/signtos/Android.mk
new file mode 100644
index 0000000..94ab944
--- /dev/null
+++ b/tools/signtos/Android.mk
@@ -0,0 +1,25 @@
+#
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+LOCAL_PATH := $(call my-dir)
+
+# the signtos tool - signs Trusty images
+# ============================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := signtos
+LOCAL_SRC_FILES := SignTos.java
+LOCAL_JAR_MANIFEST := SignTos.mf
+LOCAL_STATIC_JAVA_LIBRARIES := bouncycastle-host bouncycastle-bcpkix-host
+include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tools/signtos/SignTos.java b/tools/signtos/SignTos.java
new file mode 100644
index 0000000..485ad2f
--- /dev/null
+++ b/tools/signtos/SignTos.java
@@ -0,0 +1,314 @@
+/*
+ * Copyright 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.signtos;
+
+import org.bouncycastle.asn1.ASN1InputStream;
+import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.KeyFactory;
+import java.security.MessageDigest;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.PublicKey;
+import java.security.Security;
+import java.security.Signature;
+import java.security.interfaces.ECKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.util.Arrays;
+
+import javax.crypto.Cipher;
+import javax.crypto.EncryptedPrivateKeyInfo;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+
+/**
+ * Signs Trusty images for use with operating systems that support it.
+ */
+public class SignTos {
+    /** Size of the signature footer in bytes. */
+    private static final int SIGNATURE_BLOCK_SIZE = 256;
+
+    /** Current signature version code we use. */
+    private static final int VERSION_CODE = 1;
+
+    /** Size of the header on the file to skip. */
+    private static final int HEADER_SIZE = 512;
+
+    private static BouncyCastleProvider sBouncyCastleProvider;
+
+    /**
+     * Reads the password from stdin and returns it as a string.
+     *
+     * @param keyFile The file containing the private key.  Used to prompt the user.
+     */
+    private static String readPassword(File keyFile) {
+        // TODO: use Console.readPassword() when it's available.
+        System.out.print("Enter password for " + keyFile + " (password will not be hidden): ");
+        System.out.flush();
+        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
+        try {
+            return stdin.readLine();
+        } catch (IOException ex) {
+            return null;
+        }
+    }
+
+    /**
+     * Decrypt an encrypted PKCS#8 format private key.
+     *
+     * Based on ghstark's post on Aug 6, 2006 at
+     * http://forums.sun.com/thread.jspa?threadID=758133&messageID=4330949
+     *
+     * @param encryptedPrivateKey The raw data of the private key
+     * @param keyFile The file containing the private key
+     */
+    private static PKCS8EncodedKeySpec decryptPrivateKey(byte[] encryptedPrivateKey, File keyFile)
+        throws GeneralSecurityException {
+        EncryptedPrivateKeyInfo epkInfo;
+        try {
+            epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
+        } catch (IOException ex) {
+            // Probably not an encrypted key.
+            return null;
+        }
+
+        char[] password = readPassword(keyFile).toCharArray();
+
+        SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
+        Key key = skFactory.generateSecret(new PBEKeySpec(password));
+
+        Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
+        cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());
+
+        try {
+            return epkInfo.getKeySpec(cipher);
+        } catch (InvalidKeySpecException ex) {
+            System.err.println("signapk: Password for " + keyFile + " may be bad.");
+            throw ex;
+        }
+    }
+
+    /** Read a PKCS#8 format private key. */
+    private static PrivateKey readPrivateKey(File file) throws IOException,
+            GeneralSecurityException {
+        DataInputStream input = new DataInputStream(new FileInputStream(file));
+        try {
+            byte[] bytes = new byte[(int) file.length()];
+            input.read(bytes);
+
+            /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
+            PKCS8EncodedKeySpec spec = decryptPrivateKey(bytes, file);
+            if (spec == null) {
+                spec = new PKCS8EncodedKeySpec(bytes);
+            }
+
+            /*
+             * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
+             * OID and use that to construct a KeyFactory.
+             */
+            ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
+            PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
+            String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
+
+            return KeyFactory.getInstance(algOid).generatePrivate(spec);
+        } finally {
+            input.close();
+        }
+    }
+
+    /**
+     * Tries to load a JSE Provider by class name. This is for custom PrivateKey
+     * types that might be stored in PKCS#11-like storage.
+     */
+    private static void loadProviderIfNecessary(String providerClassName) {
+        if (providerClassName == null) {
+            return;
+        }
+
+        final Class<?> klass;
+        try {
+            final ClassLoader sysLoader = ClassLoader.getSystemClassLoader();
+            if (sysLoader != null) {
+                klass = sysLoader.loadClass(providerClassName);
+            } else {
+                klass = Class.forName(providerClassName);
+            }
+        } catch (ClassNotFoundException e) {
+            e.printStackTrace();
+            System.exit(1);
+            return;
+        }
+
+        Constructor<?> constructor = null;
+        for (Constructor<?> c : klass.getConstructors()) {
+            if (c.getParameterTypes().length == 0) {
+                constructor = c;
+                break;
+            }
+        }
+        if (constructor == null) {
+            System.err.println("No zero-arg constructor found for " + providerClassName);
+            System.exit(1);
+            return;
+        }
+
+        final Object o;
+        try {
+            o = constructor.newInstance();
+        } catch (Exception e) {
+            e.printStackTrace();
+            System.exit(1);
+            return;
+        }
+        if (!(o instanceof Provider)) {
+            System.err.println("Not a Provider class: " + providerClassName);
+            System.exit(1);
+        }
+
+        Security.insertProviderAt((Provider) o, 1);
+    }
+
+    private static String getSignatureAlgorithm(Key key) {
+        if ("EC".equals(key.getAlgorithm())) {
+            ECKey ecKey = (ECKey) key;
+            int curveSize = ecKey.getParams().getOrder().bitLength();
+            if (curveSize <= 256) {
+                return "SHA256withECDSA";
+            } else if (curveSize <= 384) {
+                return "SHA384withECDSA";
+            } else {
+                return "SHA512withECDSA";
+            }
+        } else {
+            throw new IllegalArgumentException("Unsupported key type " + key.getAlgorithm());
+        }
+    }
+
+    /**
+     * @param inputFilename
+     * @param outputFilename
+     */
+    private static void signWholeFile(InputStream input, OutputStream output, PrivateKey signingKey)
+            throws Exception {
+        Signature sig = Signature.getInstance(getSignatureAlgorithm(signingKey));
+        sig.initSign(signingKey);
+
+        byte[] buffer = new byte[8192];
+
+        /* Skip the header. */
+        int skippedBytes = 0;
+        while (skippedBytes != HEADER_SIZE) {
+            int bytesRead = input.read(buffer, 0, HEADER_SIZE - skippedBytes);
+            output.write(buffer, 0, bytesRead);
+            skippedBytes += bytesRead;
+        }
+
+        int totalBytes = 0;
+        for (;;) {
+            int bytesRead = input.read(buffer);
+            if (bytesRead == -1) {
+                break;
+            }
+            totalBytes += bytesRead;
+            sig.update(buffer, 0, bytesRead);
+            output.write(buffer, 0, bytesRead);
+        }
+
+        byte[] sigBlock = new byte[SIGNATURE_BLOCK_SIZE];
+        sigBlock[0] = VERSION_CODE;
+        sig.sign(sigBlock, 1, sigBlock.length - 1);
+
+        output.write(sigBlock);
+    }
+
+    private static void usage() {
+        System.err.println("Usage: signtos " +
+                           "[-providerClass <className>] " +
+                           " privatekey.pk8 " +
+                           "input.img output.img");
+        System.exit(2);
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (args.length < 3) {
+            usage();
+        }
+
+        String providerClass = null;
+        String providerArg = null;
+
+        int argstart = 0;
+        while (argstart < args.length && args[argstart].startsWith("-")) {
+            if ("-providerClass".equals(args[argstart])) {
+                if (argstart + 1 >= args.length) {
+                    usage();
+                }
+                providerClass = args[++argstart];
+                ++argstart;
+            } else {
+                usage();
+            }
+        }
+
+        /*
+         * Should only be "<privatekey> <input> <output>" left.
+         */
+        if (argstart != args.length - 3) {
+            usage();
+        }
+
+        sBouncyCastleProvider = new BouncyCastleProvider();
+        Security.addProvider(sBouncyCastleProvider);
+
+        loadProviderIfNecessary(providerClass);
+
+        String keyFilename = args[args.length - 3];
+        String inputFilename = args[args.length - 2];
+        String outputFilename = args[args.length - 1];
+
+        PrivateKey privateKey = readPrivateKey(new File(keyFilename));
+
+        InputStream input = new BufferedInputStream(new FileInputStream(inputFilename));
+        OutputStream output = new BufferedOutputStream(new FileOutputStream(outputFilename));
+        try {
+            SignTos.signWholeFile(input, output, privateKey);
+        } finally {
+            input.close();
+            output.close();
+        }
+
+        System.out.println("Successfully signed: " + outputFilename);
+    }
+}
diff --git a/tools/signtos/SignTos.mf b/tools/signtos/SignTos.mf
new file mode 100644
index 0000000..d860296
--- /dev/null
+++ b/tools/signtos/SignTos.mf
@@ -0,0 +1 @@
+Main-Class: com.android.signtos.SignTos
diff --git a/tools/zipalign/Android.mk b/tools/zipalign/Android.mk
index 7986798..4194f81 100644
--- a/tools/zipalign/Android.mk
+++ b/tools/zipalign/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_LDLIBS += -lrt
 endif
 
-ifneq ($(strip $(USE_MINGW)),)
+ifdef USE_MINGW
 LOCAL_STATIC_LIBRARIES += libz
 else
 LOCAL_LDLIBS += -lz
diff --git a/tools/zipalign/README.txt b/tools/zipalign/README.txt
index 9c7d07e..0b80b35 100644
--- a/tools/zipalign/README.txt
+++ b/tools/zipalign/README.txt
@@ -5,6 +5,7 @@
 
   -c : check alignment only (does not modify file)
   -f : overwrite existing outfile.zip
+  -p : page align stored shared object files
   -v : verbose output
   <align> is in bytes, e.g. "4" provides 32-bit alignment
   infile.zip is an existing Zip archive
@@ -33,3 +34,7 @@
 
 You can use the "-c" flag to test whether a zip archive is properly aligned.
 
+The "-p" flag aligns any file with a ".so" extension, and which is stored
+uncompressed in the zip archive, to a 4096-byte page boundary.  This
+facilitates directly loading shared libraries from inside a zip archive.
+
diff --git a/tools/zipalign/ZipAlign.cpp b/tools/zipalign/ZipAlign.cpp
index dc2826b..a2dfd02 100644
--- a/tools/zipalign/ZipAlign.cpp
+++ b/tools/zipalign/ZipAlign.cpp
@@ -32,20 +32,39 @@
     fprintf(stderr, "Zip alignment utility\n");
     fprintf(stderr, "Copyright (C) 2009 The Android Open Source Project\n\n");
     fprintf(stderr,
-        "Usage: zipalign [-f] [-v] [-z] <align> infile.zip outfile.zip\n"
+        "Usage: zipalign [-f] [-p] [-v] [-z] <align> infile.zip outfile.zip\n"
         "       zipalign -c [-v] <align> infile.zip\n\n" );
     fprintf(stderr,
         "  <align>: alignment in bytes, e.g. '4' provides 32-bit alignment\n");
     fprintf(stderr, "  -c: check alignment only (does not modify file)\n");
     fprintf(stderr, "  -f: overwrite existing outfile.zip\n");
+    fprintf(stderr, "  -p: page align stored shared object files\n");
     fprintf(stderr, "  -v: verbose output\n");
     fprintf(stderr, "  -z: recompress using Zopfli\n");
 }
 
+static int getAlignment(bool pageAlignSharedLibs, int defaultAlignment,
+    ZipEntry* pEntry) {
+
+    static const int kPageAlignment = 4096;
+
+    if (!pageAlignSharedLibs) {
+        return defaultAlignment;
+    }
+
+    const char* ext = strrchr(pEntry->getFileName(), '.');
+    if (ext && strcmp(ext, ".so") == 0) {
+        return kPageAlignment;
+    }
+
+    return defaultAlignment;
+}
+
 /*
  * Copy all entries from "pZin" to "pZout", aligning as needed.
  */
-static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment, bool zopfli)
+static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment, bool zopfli,
+    bool pageAlignSharedLibs)
 {
     int numEntries = pZin->getNumEntries();
     ZipEntry* pEntry;
@@ -75,13 +94,15 @@
                 status = pZout->add(pZin, pEntry, padding, &pNewEntry);
             }
         } else {
+            const int alignTo = getAlignment(pageAlignSharedLibs, alignment, pEntry);
+
             /*
              * Copy the entry, adjusting as required.  We assume that the
              * file position in the new file will be equal to the file
              * position in the original.
              */
             long newOffset = pEntry->getFileOffset() + bias;
-            padding = (alignment - (newOffset % alignment)) % alignment;
+            padding = (alignTo - (newOffset % alignTo)) % alignTo;
 
             //printf("--- %s: orig at %ld(+%d) len=%ld, adding pad=%d\n",
             //    pEntry->getFileName(), (long) pEntry->getFileOffset(),
@@ -105,7 +126,7 @@
  * output file exists and "force" wasn't specified.
  */
 static int process(const char* inFileName, const char* outFileName,
-    int alignment, bool force, bool zopfli)
+    int alignment, bool force, bool zopfli, bool pageAlignSharedLibs)
 {
     ZipFile zin, zout;
 
@@ -136,7 +157,7 @@
         return 1;
     }
 
-    int result = copyAndAlign(&zin, &zout, alignment, zopfli);
+    int result = copyAndAlign(&zin, &zout, alignment, zopfli, pageAlignSharedLibs);
     if (result != 0) {
         printf("zipalign: failed rewriting '%s' to '%s'\n",
             inFileName, outFileName);
@@ -147,7 +168,8 @@
 /*
  * Verify the alignment of a zip archive.
  */
-static int verify(const char* fileName, int alignment, bool verbose)
+static int verify(const char* fileName, int alignment, bool verbose,
+    bool pageAlignSharedLibs)
 {
     ZipFile zipFile;
     bool foundBad = false;
@@ -172,11 +194,12 @@
             }
         } else {
             long offset = pEntry->getFileOffset();
-            if ((offset % alignment) != 0) {
+            const int alignTo = getAlignment(pageAlignSharedLibs, alignment, pEntry);
+            if ((offset % alignTo) != 0) {
                 if (verbose) {
                     printf("%8ld %s (BAD - %ld)\n",
                         (long) offset, pEntry->getFileName(),
-                        offset % alignment);
+                        offset % alignTo);
                 }
                 foundBad = true;
             } else {
@@ -204,6 +227,7 @@
     bool force = false;
     bool verbose = false;
     bool zopfli = false;
+    bool pageAlignSharedLibs = false;
     int result = 1;
     int alignment;
     char* endp;
@@ -233,6 +257,9 @@
             case 'z':
                 zopfli = true;
                 break;
+            case 'p':
+                pageAlignSharedLibs = true;
+                break;
             default:
                 fprintf(stderr, "ERROR: unknown flag -%c\n", *cp);
                 wantUsage = true;
@@ -260,14 +287,15 @@
 
     if (check) {
         /* check existing archive for correct alignment */
-        result = verify(argv[1], alignment, verbose);
+        result = verify(argv[1], alignment, verbose, pageAlignSharedLibs);
     } else {
         /* create the new archive */
-        result = process(argv[1], argv[2], alignment, force, zopfli);
+        result = process(argv[1], argv[2], alignment, force, zopfli, pageAlignSharedLibs);
 
         /* trust, but verify */
-        if (result == 0)
-            result = verify(argv[2], alignment, verbose);
+        if (result == 0) {
+            result = verify(argv[2], alignment, verbose, pageAlignSharedLibs);
+        }
     }
 
 bail:
diff --git a/tools/zipalign/ZipEntry.cpp b/tools/zipalign/ZipEntry.cpp
index d4d366d..b2270cb 100644
--- a/tools/zipalign/ZipEntry.cpp
+++ b/tools/zipalign/ZipEntry.cpp
@@ -356,7 +356,7 @@
  */
 void ZipEntry::setModWhen(time_t when)
 {
-#ifdef HAVE_LOCALTIME_R
+#if !defined(_WIN32)
     struct tm tmResult;
 #endif
     time_t even;
@@ -368,7 +368,7 @@
     even = (time_t)(((unsigned long)(when) + 1) & (~1));
 
     /* expand */
-#ifdef HAVE_LOCALTIME_R
+#if !defined(_WIN32)
     ptm = localtime_r(&even, &tmResult);
 #else
     ptm = localtime(&even);