Merge "Add new locales for Platform (L) release"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 46e652b..6f436ce 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -249,6 +249,33 @@
 # Adding dalvik.vm.dex2oat-flags to eng builds
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
 
+# Unset TARGET_PREFER_32_BIT_APPS for 64 bit targets.
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+
+# Switching the x86 emulator over to a 64 bit primary zygote.
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+
+# Rename persist.sys.dalvik.vm.lib.1 to allow new default
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+
+# Switching PRODUCT_RUNTIMES default for some devices
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+
+# Switching to 32-bit-by-default host multilib build
+$(call add-clean-step, rm -rf $(HOST_OUT_INTERMEDIATES))
+
+# KKWT has become API 20
+$(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/*)
+
+# ims-common.jar added to BOOTCLASSPATH
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/ETC/init.environ.rc_intermediates)
+
+# Change ro.zygote for core_64_bit.mk from zygote32_64 to zygote64_32
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/core/64_bit_blacklist.mk b/core/64_bit_blacklist.mk
deleted file mode 100644
index b7420cd..0000000
--- a/core/64_bit_blacklist.mk
+++ /dev/null
@@ -1,16 +0,0 @@
-ifneq ($(TARGET_2ND_ARCH),)
-
-# misc build errors
-_64_bit_directory_blacklist += \
-	device/generic/goldfish/opengl \
-	device/generic/goldfish/camera \
-
-_64_bit_directory_blacklist_pattern := $(addsuffix %,$(_64_bit_directory_blacklist))
-
-define directory_is_64_bit_blacklisted
-$(if $(filter $(_64_bit_directory_blacklist_pattern),$(1)),true)
-endef
-else
-define directory_is_64_bit_blacklisted
-endef
-endif
diff --git a/core/Makefile b/core/Makefile
index 75573ce..b02604f 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -475,13 +475,13 @@
 $(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES)
 	$(call pretty,"Target boot image: $@")
 	$(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@
-	$(hide) $(call assert-max-image-size,$@,$(BOARD_BOOTIMAGE_PARTITION_SIZE),raw)
+	$(hide) $(call assert-max-image-size,$@,$(BOARD_BOOTIMAGE_PARTITION_SIZE))
 
 .PHONY: bootimage-nodeps
 bootimage-nodeps: $(MKBOOTIMG)
 	@echo "make $@: ignoring dependencies"
 	$(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET)
-	$(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE),raw)
+	$(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE))
 
 endif # TARGET_BOOTIMAGE_USE_EXT2
 
@@ -634,10 +634,15 @@
 endif
 
 ifeq ($(INTERNAL_USERIMAGES_USE_EXT),true)
-INTERNAL_USERIMAGES_DEPS := $(MKEXTUSERIMG) $(MAKE_EXT4FS) $(SIMG2IMG) $(E2FSCK)
+INTERNAL_USERIMAGES_DEPS := $(SIMG2IMG)
+INTERNAL_USERIMAGES_DEPS += $(MKEXTUSERIMG) $(MAKE_EXT4FS) $(E2FSCK)
+ifeq ($(TARGET_USERIMAGES_USE_F2FS),true)
+INTERNAL_USERIMAGES_DEPS += $(MKF2FSUSERIMG) $(MAKE_F2FS)
+endif
 else
 INTERNAL_USERIMAGES_DEPS := $(MKYAFFS2)
 endif
+
 INTERNAL_USERIMAGES_BINARY_PATHS := $(sort $(dir $(INTERNAL_USERIMAGES_DEPS)))
 
 ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY))
@@ -652,6 +657,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_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))
 $(if $(BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "cache_fs_type=$(BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE)" >> $(1))
 $(if $(BOARD_CACHEIMAGE_PARTITION_SIZE),$(hide) echo "cache_size=$(BOARD_CACHEIMAGE_PARTITION_SIZE)" >> $(1))
@@ -661,6 +667,11 @@
 $(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_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_PARTITION)" >> $(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_SUPPORTS_VERITY),$(hide) echo "verity_mountpoint=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_MOUNTPOINT)" >> $(1))
 $(if $(2),$(hide) $(foreach kv,$(2),echo "$(kv)" >> $(1);))
 endef
 
@@ -673,34 +684,39 @@
 INSTALLED_RECOVERYIMAGE_TARGET := $(PRODUCT_OUT)/recovery.img
 
 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
 
-ifneq (,$(filter xxxhdpi,$(PRODUCT_AAPT_CONFIG_SP)))
-recovery_resources_common := $(recovery_resources_common)-xxxhdpi
-else ifneq (,$(filter xxhdpi,$(PRODUCT_AAPT_CONFIG_SP)))
-recovery_resources_common := $(recovery_resources_common)-xxhdpi
-else ifneq (,$(filter xhdpi,$(PRODUCT_AAPT_CONFIG_SP)))
-recovery_resources_common := $(recovery_resources_common)-xhdpi
-else ifneq (,$(filter hdpi,$(PRODUCT_AAPT_CONFIG_SP)))
-recovery_resources_common := $(recovery_resources_common)-hdpi
-else ifneq (,$(filter mdpi,$(PRODUCT_AAPT_CONFIG_SP)))
-recovery_resources_common := $(recovery_resources_common)-mdpi
+# Set recovery_density to the density bucket of the device.
+recovery_density := unknown
+ifneq (,$(PRODUCT_AAPT_PREF_CONFIG))
+# If PRODUCT_AAPT_PREF_CONFIG includes a dpi bucket, then use that value.
+recovery_density := $(filter %dpi,$(PRODUCT_AAPT_PREF_CONFIG))
 else
-# xhdpi is closest in size to the single set of resources we had
-# before, so make that the default if PRODUCT_AAPT_CONFIG doesn't
-# specify a dpi we have.
+# Otherwise, use the highest density that appears in PRODUCT_AAPT_CONFIG.
+# Order is important here; we'll take the first one that's found.
+recovery_densities := $(filter $(PRODUCT_AAPT_CONFIG_SP),xxxhdpi xxhdpi xhdpi hdpi mdpi ldpi)
+ifneq (,$(recovery_densities))
+recovery_density := $(word 1,$(recovery_densities))
+endif
+endif
+
+ifneq (,$(wildcard $(recovery_resources_common)-$(recovery_density)))
+recovery_resources_common := $(recovery_resources_common)-$(recovery_density)
+else
 recovery_resources_common := $(recovery_resources_common)-xhdpi
 endif
 
-# Select the 18x32 font on high-density devices; and the 12x22 font on
-# other devices.  Note that the font selected here can be overridden
-# for a particular device by putting a font.png in its private
-# recovery resources.
-ifneq (,$(filter xxhdpi xhdpi,$(subst $(comma),$(space),$(PRODUCT_AAPT_CONFIG))))
+# Select the 18x32 font on high-density devices (xhdpi and up); and
+# the 12x22 font on other devices.  Note that the font selected here
+# can be overridden for a particular device by putting a font.png in
+# its private recovery resources.
+
+ifneq (,$(filter xxxhdpi xxhdpi xhdpi,$(recovery_density)))
 recovery_font := $(call include-path-for, recovery)/fonts/18x32.png
 else
 recovery_font := $(call include-path-for, recovery)/fonts/12x22.png
@@ -764,7 +780,7 @@
 		$(INSTALLED_RAMDISK_TARGET) \
 		$(INSTALLED_BOOTIMAGE_TARGET) \
 		$(recovery_binary) \
-		$(recovery_initrc) $(recovery_kernel) \
+		$(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \
 		$(INSTALLED_2NDBOOTLOADER_TARGET) \
 		$(recovery_build_prop) $(recovery_resource_deps) \
 		$(recovery_fstab) \
@@ -778,6 +794,8 @@
 	@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
@@ -793,7 +811,7 @@
 	        > $(TARGET_RECOVERY_ROOT_OUT)/default.prop
 	$(hide) $(MKBOOTFS) $(TARGET_RECOVERY_ROOT_OUT) | $(MINIGZIP) > $(recovery_ramdisk)
 	$(hide) $(MKBOOTIMG) $(INTERNAL_RECOVERYIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@
-	$(hide) $(call assert-max-image-size,$@,$(BOARD_RECOVERYIMAGE_PARTITION_SIZE),raw)
+	$(hide) $(call assert-max-image-size,$@,$(BOARD_RECOVERYIMAGE_PARTITION_SIZE))
 	@echo ----- Made recovery image: $@ --------
 
 $(RECOVERY_RESOURCE_ZIP): $(INSTALLED_RECOVERYIMAGE_TARGET)
@@ -860,16 +878,23 @@
     $(call intermediates-dir-for,PACKAGING,systemimage)
 BUILT_SYSTEMIMAGE := $(systemimage_intermediates)/system.img
 
+# Create symlink /system/vendor to /vendor if necessary.
+ifdef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE
+define create-system-vendor-symlink
+$(hide) ln -sf /vendor $(TARGET_OUT)/vendor
+endef
+else
+define create-system-vendor-symlink
+endef
+endif
+
 # $(1): output file
 define build-systemimage-target
   @echo "Target system fs image: $(1)"
+  $(call create-system-vendor-symlink)
   @mkdir -p $(dir $(1)) $(systemimage_intermediates) && rm -rf $(systemimage_intermediates)/system_image_info.txt
   $(call generate-userimage-prop-dictionary, $(systemimage_intermediates)/system_image_info.txt, \
-      skip_fsck=true \
-      verity=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY) \
-      verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_PARTITION) \
-      verity_key=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY) \
-      verity_signer_cmd=$(VERITY_SIGNER))
+      skip_fsck=true)
   $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
       ./build/tools/releasetools/build_image.py \
       $(TARGET_OUT) $(systemimage_intermediates)/system_image_info.txt $(1)
@@ -902,7 +927,7 @@
 $(INSTALLED_SYSTEMIMAGE): $(BUILT_SYSTEMIMAGE) $(RECOVERY_FROM_BOOT_PATCH) | $(ACP)
 	@echo "Install system fs image: $@"
 	$(copy-file-to-target)
-	$(hide) $(call assert-max-image-size,$@ $(RECOVERY_FROM_BOOT_PATCH),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE),yaffs)
+	$(hide) $(call assert-max-image-size,$@ $(RECOVERY_FROM_BOOT_PATCH),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE))
 
 systemimage: $(INSTALLED_SYSTEMIMAGE)
 
@@ -911,7 +936,7 @@
 	            | $(INTERNAL_USERIMAGES_DEPS)
 	@echo "make $@: ignoring dependencies"
 	$(call build-systemimage-target,$(INSTALLED_SYSTEMIMAGE))
-	$(hide) $(call assert-max-image-size,$(INSTALLED_SYSTEMIMAGE),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE),yaffs)
+	$(hide) $(call assert-max-image-size,$(INSTALLED_SYSTEMIMAGE),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE))
 
 ifneq (,$(filter systemimage-nodeps snod, $(MAKECMDGOALS)))
 ifeq (true,$(WITH_DEXPREOPT))
@@ -922,10 +947,11 @@
 #######
 ## system tarball
 define build-systemtarball-target
-    $(call pretty,"Target system fs tarball: $(INSTALLED_SYSTEMTARBALL_TARGET)")
-    $(MKTARBALL) $(FS_GET_STATS) \
-		$(PRODUCT_OUT) system $(PRIVATE_SYSTEM_TAR) \
-		$(INSTALLED_SYSTEMTARBALL_TARGET)
+  $(call pretty,"Target system fs tarball: $(INSTALLED_SYSTEMTARBALL_TARGET)")
+  $(call create-system-vendor-symlink)
+  $(MKTARBALL) $(FS_GET_STATS) \
+    $(PRODUCT_OUT) system $(PRIVATE_SYSTEM_TAR) \
+    $(INSTALLED_SYSTEMTARBALL_TARGET)
 endef
 
 ifndef SYSTEM_TARBALL_FORMAT
@@ -1034,7 +1060,7 @@
   $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
       ./build/tools/releasetools/build_image.py \
       $(TARGET_OUT_DATA) $(userdataimage_intermediates)/userdata_image_info.txt $(INSTALLED_USERDATAIMAGE_TARGET)
-  $(hide) $(call assert-max-image-size,$(INSTALLED_USERDATAIMAGE_TARGET),$(BOARD_USERDATAIMAGE_PARTITION_SIZE),yaffs)
+  $(hide) $(call assert-max-image-size,$(INSTALLED_USERDATAIMAGE_TARGET),$(BOARD_USERDATAIMAGE_PARTITION_SIZE))
 endef
 
 # We just build this directly to the install location.
@@ -1089,7 +1115,7 @@
   $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
       ./build/tools/releasetools/build_image.py \
       $(TARGET_OUT_CACHE) $(cacheimage_intermediates)/cache_image_info.txt $(INSTALLED_CACHEIMAGE_TARGET)
-  $(hide) $(call assert-max-image-size,$(INSTALLED_CACHEIMAGE_TARGET),$(BOARD_CACHEIMAGE_PARTITION_SIZE),yaffs)
+  $(hide) $(call assert-max-image-size,$(INSTALLED_CACHEIMAGE_TARGET),$(BOARD_CACHEIMAGE_PARTITION_SIZE))
 endef
 
 # We just build this directly to the install location.
@@ -1122,7 +1148,7 @@
   $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
       ./build/tools/releasetools/build_image.py \
       $(TARGET_OUT_VENDOR) $(vendorimage_intermediates)/vendor_image_info.txt $(INSTALLED_VENDORIMAGE_TARGET)
-  $(hide) $(call assert-max-image-size,$(INSTALLED_VENDORIMAGE_TARGET),$(BOARD_VENDORIMAGE_PARTITION_SIZE),yaffs)
+  $(hide) $(call assert-max-image-size,$(INSTALLED_VENDORIMAGE_TARGET),$(BOARD_VENDORIMAGE_PARTITION_SIZE))
 endef
 
 # We just build this directly to the install location.
@@ -1160,7 +1186,10 @@
 	  $(HOST_OUT_EXECUTABLES)/simg2img \
 	  $(HOST_OUT_EXECUTABLES)/e2fsck \
 	  $(HOST_OUT_EXECUTABLES)/xdelta3 \
-	  $(HOST_OUT_EXECUTABLES)/syspatch_host
+	  $(HOST_OUT_EXECUTABLES)/syspatch_host \
+	  $(HOST_OUT_EXECUTABLES)/build_verity_tree \
+	  $(HOST_OUT_EXECUTABLES)/verity_signer \
+	  $(HOST_OUT_EXECUTABLES)/append2simg
 
 OTATOOLS := $(DISTTOOLS) \
 	  $(HOST_OUT_EXECUTABLES)/aapt
@@ -1324,8 +1353,10 @@
 	$(hide) ./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, boot ramdisk, and recovery ramdisk files in the zip, and save the output
+	@# Run fs_config on all the system, vendor, boot ramdisk,
+	@# and recovery ramdisk files in the zip, and save the output
 	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="SYSTEM/" } /^SYSTEM\// {print "system/" $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config -C -S $(SELINUX_FC) > $(zip_root)/META/filesystem_config.txt
+	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="VENDOR/" } /^VENDOR\// {print "vendor/" $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config -C -S $(SELINUX_FC) > $(zip_root)/META/vendor_filesystem_config.txt
 	$(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)
@@ -1357,7 +1388,7 @@
 
 $(INTERNAL_OTA_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(DISTTOOLS)
 	@echo "Package OTA: $@"
-	$(hide) MKBOOTIMG=$(BOARD_CUSTOM_MKBOOTIMG) \
+	$(hide) MKBOOTIMG=$(MKBOOTIMG) \
 	   ./build/tools/releasetools/ota_from_target_files -v \
 	   --block \
 	   -p $(HOST_OUT) \
@@ -1368,6 +1399,11 @@
 .PHONY: otapackage
 otapackage: $(INTERNAL_OTA_PACKAGE_TARGET)
 
+endif    # recovery_fstab is defined
+endif    # TARGET_NO_KERNEL != true
+endif    # TARGET_DEVICE != generic*
+endif    # TARGET_PRODUCT != sdk
+
 # -----------------------------------------------------------------
 # The update package
 
@@ -1381,7 +1417,7 @@
 
 $(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(DISTTOOLS)
 	@echo "Package: $@"
-	$(hide) MKBOOTIMG=$(BOARD_CUSTOM_MKBOOTIMG) \
+	$(hide) MKBOOTIMG=$(MKBOOTIMG) \
 	   ./build/tools/releasetools/img_from_target_files -v \
 	   -p $(HOST_OUT) \
 	   $(BUILT_TARGET_FILES_PACKAGE) $@
@@ -1389,11 +1425,6 @@
 .PHONY: updatepackage
 updatepackage: $(INTERNAL_UPDATE_PACKAGE_TARGET)
 
-endif    # recovery_fstab is defined
-endif    # TARGET_NO_KERNEL != true
-endif    # TARGET_DEVICE != generic*
-endif    # TARGET_PRODUCT != sdk
-
 # -----------------------------------------------------------------
 # A zip of the symbols directory.  Keep the full paths to make it
 # more obvious where these files came from.
@@ -1502,7 +1533,7 @@
 # The SDK
 
 # The SDK includes host-specific components, so it belongs under HOST_OUT.
-sdk_dir := $(HOST_OUT)/sdk
+sdk_dir := $(HOST_OUT)/sdk/$(TARGET_PRODUCT)
 
 # Build a name that looks like:
 #
@@ -1517,7 +1548,7 @@
   INTERNAL_SDK_HOST_OS_NAME := $(HOST_OS)
 endif
 ifneq ($(HOST_OS),windows)
-  INTERNAL_SDK_HOST_OS_NAME := $(INTERNAL_SDK_HOST_OS_NAME)-$(HOST_ARCH)
+  INTERNAL_SDK_HOST_OS_NAME := $(INTERNAL_SDK_HOST_OS_NAME)-$(SDK_HOST_ARCH)
 endif
 sdk_name := $(sdk_name)_$(INTERNAL_SDK_HOST_OS_NAME)
 
@@ -1543,7 +1574,7 @@
 
 sdk_atree_files := \
 	$(atree_dir)/sdk.exclude.atree \
-	$(atree_dir)/sdk-$(HOST_OS)-$(HOST_ARCH).atree
+	$(atree_dir)/sdk-$(HOST_OS)-$(SDK_HOST_ARCH).atree
 
 # development/build/sdk-android-<abi>.atree is used to differentiate
 # between architecture models (e.g. ARMv5TE versus ARMv7) when copying
@@ -1580,6 +1611,10 @@
 $(INTERNAL_SDK_TARGET): PRIVATE_DEP_FILE := $(sdk_dep_file)
 $(INTERNAL_SDK_TARGET): PRIVATE_INPUT_FILES := $(sdk_atree_files)
 
+sdk_font_temp_dir := $(call intermediates-dir-for,PACKAGING,sdk-fonts)
+sdk_font_input_list := frameworks/base/data/fonts external/noto-fonts external/google-fonts external/naver-fonts
+sdk_font_rename_script := frameworks/base/tools/layoutlib/rename_font/build_font.py
+
 # Set SDK_GNU_ERROR to non-empty to fail when a GNU target is built.
 #
 #SDK_GNU_ERROR := true
@@ -1595,6 +1630,9 @@
 	  fi; \
 	done; \
 	if [ $$FAIL ]; then exit 1; fi
+	$(hide) mkdir -p $(sdk_font_temp_dir)
+	$(hide) PYTHONPATH=$$PYTHONPATH:external/fonttools/Lib $(sdk_font_rename_script) $(sdk_font_input_list) \
+	        $(sdk_font_temp_dir)
 	$(hide) ( \
 		ATREE_STRIP="strip -x" \
 		$(HOST_OUT_EXECUTABLES)/atree \
@@ -1610,6 +1648,7 @@
 			-v "TARGET_ARCH=$(TARGET_ARCH)" \
 			-v "TARGET_CPU_ABI=$(TARGET_CPU_ABI)" \
 			-v "DLL_EXTENSION=$(HOST_SHLIB_SUFFIX)" \
+			-v "FONT_OUT=$(sdk_font_temp_dir)" \
 			-o $(PRIVATE_DIR) && \
 		cp -f $(target_notice_file_txt) \
 				$(PRIVATE_DIR)/system-images/android-$(PLATFORM_VERSION)/$(TARGET_CPU_ABI)/NOTICE.txt && \
@@ -1636,11 +1675,11 @@
 INTERNAL_FINDBUGS_HTML_TARGET := $(PRODUCT_OUT)/findbugs.html
 $(INTERNAL_FINDBUGS_XML_TARGET): $(ALL_FINDBUGS_FILES)
 	@echo UnionBugs: $@
-	$(hide) prebuilt/common/findbugs/bin/unionBugs $(ALL_FINDBUGS_FILES) \
+	$(hide) $(FINDBUGS_DIR)/unionBugs $(ALL_FINDBUGS_FILES) \
 	> $@
 $(INTERNAL_FINDBUGS_HTML_TARGET): $(INTERNAL_FINDBUGS_XML_TARGET)
 	@echo ConvertXmlToText: $@
-	$(hide) prebuilt/common/findbugs/bin/convertXmlToText -html:fancy.xsl \
+	$(hide) $(FINDBUGS_DIR)/convertXmlToText -html:fancy.xsl \
 	$(INTERNAL_FINDBUGS_XML_TARGET) > $@
 
 # -----------------------------------------------------------------
diff --git a/core/base_rules.mk b/core/base_rules.mk
index 0a67d42..5406607 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -98,16 +98,10 @@
   $(error $(LOCAL_PATH): LOCAL_MODULE_CLASS must contain exactly one word, not "$(LOCAL_MODULE_CLASS)")
 endif
 
-ifndef LOCAL_IS_HOST_MODULE
-my_32_64_bit_suffix := $(if $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_IS_64_BIT),64,32)
-endif
+my_32_64_bit_suffix := $(if $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)IS_64_BIT),64,32)
 
 ifneq (true,$(LOCAL_UNINSTALLABLE_MODULE))
-ifndef LOCAL_IS_HOST_MODULE
 my_multilib_module_path := $(strip $(LOCAL_MODULE_PATH_$(my_32_64_bit_suffix)))
-else
-my_multilib_module_path :=
-endif
 ifdef my_multilib_module_path
 my_module_path := $(my_multilib_module_path)
 else
@@ -150,7 +144,7 @@
 my_register_name := $(LOCAL_MODULE)
 ifdef LOCAL_2ND_ARCH_VAR_PREFIX
 ifndef LOCAL_NO_2ND_ARCH_MODULE_SUFFIX
-my_register_name := $(LOCAL_MODULE)$(TARGET_2ND_ARCH_MODULE_SUFFIX)
+my_register_name := $(LOCAL_MODULE)$($(my_prefix)2ND_ARCH_MODULE_SUFFIX)
 endif
 endif
 # Make sure that this IS_HOST/CLASS/MODULE combination is unique.
@@ -181,11 +175,11 @@
 else
   built_module_path := $(intermediates)
 endif
-LOCAL_BUILT_MODULE := $(built_module_path)/$(LOCAL_BUILT_MODULE_STEM)
+LOCAL_BUILT_MODULE := $(built_module_path)/$(my_built_module_stem)
 built_module_path :=
 
 ifneq (true,$(LOCAL_UNINSTALLABLE_MODULE))
-  LOCAL_INSTALLED_MODULE := $(my_module_path)/$(LOCAL_INSTALLED_MODULE_STEM)
+  LOCAL_INSTALLED_MODULE := $(my_module_path)/$(my_installed_module_stem)
 endif
 
 # Assemble the list of targets to create PRIVATE_ variables for.
@@ -389,7 +383,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAVA_OBJECTS := $(patsubst %.java,%.class,$(LOCAL_SRC_FILES))
 ifeq ($(my_prefix),TARGET_)
 ifeq ($(LOCAL_SDK_VERSION),)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,core)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,core-libart)
 else
 ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),current)
 # LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS.
@@ -411,7 +405,7 @@
 #                 be up-to-date.
 ifdef LOCAL_IS_HOST_MODULE
 ifeq ($(USE_CORE_LIB_BOOTCLASSPATH),true)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-deps,core-hostdex,$(LOCAL_IS_HOST_MODULE))
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-deps,core-libart-hostdex,$(LOCAL_IS_HOST_MODULE))
 
 full_shared_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 full_java_lib_deps := $(call java-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
@@ -518,6 +512,8 @@
 
 $(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_INTERMEDIATES_DIR:= $(intermediates)
 
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_2ND_ARCH_VAR_PREFIX := $(LOCAL_2ND_ARCH_VAR_PREFIX)
+
 # Tell the module and all of its sub-modules who it is.
 $(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_MODULE:= $(my_register_name)
 
@@ -575,10 +571,12 @@
 ifdef LOCAL_DONT_CHECK_MODULE
   LOCAL_CHECKED_MODULE :=
 endif
-# Don't check build the module defined for the 2nd arch
+# 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 :=
 endif
+endif
 
 ###########################################################
 ## Register with ALL_MODULES
@@ -598,8 +596,12 @@
     $(ALL_MODULES.$(my_register_name).CHECKED) $(LOCAL_CHECKED_MODULE)
 ALL_MODULES.$(my_register_name).BUILT := \
     $(ALL_MODULES.$(my_register_name).BUILT) $(LOCAL_BUILT_MODULE)
+ifneq (true,$(LOCAL_UNINSTALLABLE_MODULE))
 ALL_MODULES.$(my_register_name).INSTALLED := \
     $(strip $(ALL_MODULES.$(my_register_name).INSTALLED) $(LOCAL_INSTALLED_MODULE))
+ALL_MODULES.$(my_register_name).BUILT_INSTALLED := \
+    $(strip $(ALL_MODULES.$(my_register_name).BUILT_INSTALLED) $(LOCAL_BUILT_MODULE):$(LOCAL_INSTALLED_MODULE))
+endif
 ifdef LOCAL_PICKUP_FILES
 # Files or directories ready to pick up by the build system
 # when $(LOCAL_BUILT_MODULE) is done.
diff --git a/core/binary.mk b/core/binary.mk
index d5709ca..be0776e 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -113,21 +113,34 @@
 my_c_includes := $(LOCAL_C_INCLUDES)
 my_generated_sources := $(LOCAL_GENERATED_SOURCES)
 
-ifndef LOCAL_IS_HOST_MODULE
-my_src_files += $(LOCAL_SRC_FILES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_SRC_FILES_$(my_32_64_bit_suffix))
-my_shared_libraries += $(LOCAL_SHARED_LIBRARIES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_SHARED_LIBRARIES_$(my_32_64_bit_suffix))
-my_cflags += $(LOCAL_CFLAGS_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CFLAGS_$(my_32_64_bit_suffix))
-my_cppflags += $(LOCAL_CPPFLAGS_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CPPFLAGS_$(my_32_64_bit_suffix))
-my_ldflags += $(LOCAL_LDFLAGS_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_LDFLAGS_$(my_32_64_bit_suffix))
-my_asflags += $(LOCAL_ASFLAGS_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_ASFLAGS_$(my_32_64_bit_suffix))
-my_c_includes += $(LOCAL_C_INCLUDES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_C_INCLUDES_$(my_32_64_bit_suffix))
-my_generated_sources += $(LOCAL_GENERATED_SOURCES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_GENERATED_SOURCES_$(my_32_64_bit_suffix))
+my_src_files += $(LOCAL_SRC_FILES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_SRC_FILES_$(my_32_64_bit_suffix))
+my_shared_libraries += $(LOCAL_SHARED_LIBRARIES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_SHARED_LIBRARIES_$(my_32_64_bit_suffix))
+my_cflags += $(LOCAL_CFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CFLAGS_$(my_32_64_bit_suffix))
+my_cppflags += $(LOCAL_CPPFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CPPFLAGS_$(my_32_64_bit_suffix))
+my_ldflags += $(LOCAL_LDFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_LDFLAGS_$(my_32_64_bit_suffix))
+my_asflags += $(LOCAL_ASFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_ASFLAGS_$(my_32_64_bit_suffix))
+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)
+ifdef LOCAL_CLANG_$(my_32_64_bit_suffix)
+my_clang := $(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))
+endif
 
 # arch-specific static libraries go first so that generic ones can depend on them
-my_static_libraries := $(LOCAL_STATIC_LIBRARIES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_STATIC_LIBRARIES_$(my_32_64_bit_suffix)) $(my_static_libraries)
-my_whole_static_libraries := $(LOCAL_WHOLE_STATIC_LIBRARIES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_WHOLE_STATIC_LIBRARIES_$(my_32_64_bit_suffix)) $(my_whole_static_libraries)
+my_static_libraries := $(LOCAL_STATIC_LIBRARIES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_STATIC_LIBRARIES_$(my_32_64_bit_suffix)) $(my_static_libraries)
+my_whole_static_libraries := $(LOCAL_WHOLE_STATIC_LIBRARIES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_WHOLE_STATIC_LIBRARIES_$(my_32_64_bit_suffix)) $(my_whole_static_libraries)
 
-my_cflags := $(filter-out $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_UNSUPPORTED_CFLAGS),$(my_cflags))
+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
 
 # Add static HAL libraries
@@ -140,7 +153,7 @@
 endif
 
 ifeq ($(strip $(LOCAL_ADDRESS_SANITIZER)),true)
-  LOCAL_CLANG := 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)
@@ -150,7 +163,7 @@
 endif
 
 ifeq ($(strip $($(LOCAL_2ND_ARCH_VAR_PREFIX)WITHOUT_$(my_prefix)CLANG)),true)
-  LOCAL_CLANG :=
+  my_clang :=
 endif
 
 # Add in libcompiler_rt for all regular device builds
@@ -198,7 +211,7 @@
 ifdef LOCAL_INSTALLED_MODULE
 ifdef installed_shared_library_module_names
 $(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
-    $(LOCAL_MODULE):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(installed_shared_library_module_names))
+    $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(installed_shared_library_module_names))
 endif
 endif
 
@@ -216,7 +229,7 @@
 my_target_global_cppflags :=
 endif # LOCAL_SDK_VERSION
 
-ifeq ($(LOCAL_CLANG),true)
+ifeq ($(my_clang),true)
 my_target_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_TARGET_GLOBAL_CFLAGS)
 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)
@@ -225,7 +238,7 @@
 my_target_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CFLAGS)
 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 # LOCAL_CLANG
+endif # my_clang
 
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_PROJECT_INCLUDES := $(my_target_project_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_C_INCLUDES := $(my_target_c_includes)
@@ -235,17 +248,17 @@
 
 else # LOCAL_IS_HOST_MODULE
 
-ifeq ($(LOCAL_CLANG),true)
-my_host_global_cflags := $(CLANG_HOST_GLOBAL_CFLAGS)
-my_host_global_cppflags := $(CLANG_HOST_GLOBAL_CPPFLAGS)
-my_host_global_ldflags := $(CLANG_HOST_GLOBAL_LDFLAGS)
-my_host_c_includes := $(HOST_C_INCLUDES) $(CLANG_CONFIG_EXTRA_HOST_C_INCLUDES)
+ifeq ($(my_clang),true)
+my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_CFLAGS)
+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)
 else
-my_host_global_cflags := $(HOST_GLOBAL_CFLAGS)
-my_host_global_cppflags := $(HOST_GLOBAL_CPPFLAGS)
-my_host_global_ldflags := $(HOST_GLOBAL_LDFLAGS)
-my_host_c_includes := $(HOST_C_INCLUDES)
-endif # LOCAL_CLANG
+my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CFLAGS)
+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)
+endif # my_clang
 
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_C_INCLUDES := $(my_host_c_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_GLOBAL_CFLAGS := $(my_host_global_cflags)
@@ -274,7 +287,7 @@
 endif
 
 ifeq ($(strip $(my_cc)),)
-  ifeq ($(strip $(LOCAL_CLANG)),true)
+  ifeq ($(strip $(my_clang)),true)
     my_cc := $(CLANG)
   else
     my_cc := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)CC)
@@ -290,7 +303,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CC := $(my_cc)
 
 ifeq ($(strip $(my_cxx)),)
-  ifeq ($(strip $(LOCAL_CLANG)),true)
+  ifeq ($(strip $(my_clang)),true)
     my_cxx := $(CLANG_CXX)
   else
     my_cxx := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)CXX)
@@ -339,7 +352,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 $(LOCAL_CLANG)),true)
+ifeq ($(strip $(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
@@ -413,7 +426,9 @@
     $(renderscript_intermediate)/ScriptC_,$(patsubst %.fs,%.cpp, $(patsubst %.rs,%.cpp, \
     $(notdir $(renderscript_sources)))))
 
+# This is just a dummy rule to make sure gmake doesn't skip updating the dependents.
 $(rs_generated_cpps) : $(RenderScript_file_stamp)
+	@echo "Updated RS generated cpp file $@."
 
 my_c_includes += $(renderscript_intermediate)
 my_generated_sources += $(rs_generated_cpps)
@@ -463,9 +478,9 @@
 $(proto_generated_cc_sources): $(proto_generated_cc_sources_dir)/%.pb.cc: %.proto $(PROTOC)
 	$(transform-proto-to-cc)
 
+# This is just a dummy rule to make sure gmake doesn't skip updating the dependents.
 $(proto_generated_headers): $(proto_generated_cc_sources_dir)/%.pb.h: $(proto_generated_cc_sources_dir)/%.pb.cc
-	# This is just a dummy rule to make sure gmake doesn't skip updating the dependents.
-	@echo "Updated header file $<."
+	@echo "Updated header file $@."
 
 $(my_prefix)_$(LOCAL_MODULE_CLASS)_$(LOCAL_MODULE)_proto_defined := true
 endif  # transform-proto-to-cc rule included only once
@@ -734,6 +749,19 @@
 asm_objects := $(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_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)
+	$(transform-asm-to-o)
+
+asm_objects += $(asm_objects_asm)
+endif
+endif
+
 ####################################################
 ## Import includes
 ####################################################
@@ -875,7 +903,7 @@
 # Rule-specific variable definitions
 ###########################################################
 
-ifeq ($(LOCAL_CLANG),true)
+ifeq ($(my_clang),true)
 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))
@@ -894,6 +922,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LDFLAGS := $(my_ldflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LDLIBS := $(LOCAL_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 221a2f3..0e8e2cf 100644
--- a/core/build_id.mk
+++ b/core/build_id.mk
@@ -18,6 +18,4 @@
 # (like "CRB01").  It must be a single word, and is
 # capitalized by convention.
 
-BUILD_ID := MASTER
-
-DISPLAY_BUILD_NUMBER := true
+export BUILD_ID=MASTER
diff --git a/core/clang/HOST_x86.mk b/core/clang/HOST_x86.mk
index ee61e5e..510a74d 100644
--- a/core/clang/HOST_x86.mk
+++ b/core/clang/HOST_x86.mk
@@ -1,6 +1,6 @@
 
 include $(BUILD_SYSTEM)/clang/x86.mk
-include $(BUILD_SYSTEM)/clang/x86_common.mk
+include $(BUILD_SYSTEM)/clang/HOST_x86_common.mk
 
 ifeq ($(HOST_OS),linux)
 CLANG_CONFIG_x86_HOST_TRIPLE := i686-linux-gnu
@@ -44,21 +44,21 @@
   $(CLANG_CONFIG_x86_HOST_COMBO_EXTRA_LDFLAGS) \
   -target $(CLANG_CONFIG_x86_HOST_TRIPLE)
 
-define convert-to-host-clang-flags
+define $(clang_2nd_arch_prefix)convert-to-host-clang-flags
   $(strip \
   $(call subst-clang-incompatible-x86-flags,\
   $(filter-out $(CLANG_CONFIG_x86_UNKNOWN_CFLAGS),\
   $(1))))
 endef
 
-CLANG_HOST_GLOBAL_CFLAGS := \
-  $(call convert-to-host-clang-flags,$(HOST_GLOBAL_CFLAGS)) \
+$(clang_2nd_arch_prefix)CLANG_HOST_GLOBAL_CFLAGS := \
+  $(call $(clang_2nd_arch_prefix)convert-to-host-clang-flags,$($(clang_2nd_arch_prefix)HOST_GLOBAL_CFLAGS)) \
   $(CLANG_CONFIG_x86_HOST_EXTRA_CFLAGS)
 
-CLANG_HOST_GLOBAL_CPPFLAGS := \
-  $(call convert-to-host-clang-flags,$(HOST_GLOBAL_CPPFLAGS)) \
+$(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)
 
-CLANG_HOST_GLOBAL_LDFLAGS := \
-  $(call convert-to-host-clang-flags,$(HOST_GLOBAL_LDFLAGS)) \
+$(clang_2nd_arch_prefix)CLANG_HOST_GLOBAL_LDFLAGS := \
+  $(call $(clang_2nd_arch_prefix)convert-to-host-clang-flags,$($(clang_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS)) \
   $(CLANG_CONFIG_x86_HOST_EXTRA_LDFLAGS)
diff --git a/core/clang/HOST_x86_64.mk b/core/clang/HOST_x86_64.mk
index d60e15f..6b94525 100644
--- a/core/clang/HOST_x86_64.mk
+++ b/core/clang/HOST_x86_64.mk
@@ -1,6 +1,6 @@
 
 include $(BUILD_SYSTEM)/clang/x86_64.mk
-include $(BUILD_SYSTEM)/clang/x86_common.mk
+include $(BUILD_SYSTEM)/clang/HOST_x86_common.mk
 
 ifeq ($(HOST_OS),linux)
 CLANG_CONFIG_x86_64_HOST_TRIPLE := x86_64-linux-gnu
diff --git a/core/clang/HOST_x86_common.mk b/core/clang/HOST_x86_common.mk
new file mode 100644
index 0000000..0241cb6
--- /dev/null
+++ b/core/clang/HOST_x86_common.mk
@@ -0,0 +1,56 @@
+# Shared by HOST_x86.mk and HOST_x86_64.mk.
+
+ifeq ($(HOST_OS),darwin)
+# nothing required here yet
+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
+
+CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CFLAGS := \
+  --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
+  -no-integrated-as
+
+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
+
+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
+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
+
+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
+endif
+endif  # Linux
+
+ifeq ($(HOST_OS),windows)
+# nothing required here yet
+endif
diff --git a/core/clang/config.mk b/core/clang/config.mk
index c0be37a..1de46f0 100644
--- a/core/clang/config.mk
+++ b/core/clang/config.mk
@@ -15,7 +15,7 @@
 LLVM_LINK := $(LLVM_PREBUILTS_PATH)/llvm-link$(BUILD_EXECUTABLE_SUFFIX)
 
 CLANG_TBLGEN := $(HOST_OUT_EXECUTABLES)/clang-tblgen$(BUILD_EXECUTABLE_SUFFIX)
-TBLGEN := $(HOST_OUT_EXECUTABLES)/tblgen$(BUILD_EXECUTABLE_SUFFIX)
+LLVM_TBLGEN := $(HOST_OUT_EXECUTABLES)/llvm-tblgen$(BUILD_EXECUTABLE_SUFFIX)
 
 
 # Clang flags for all host or target rules
@@ -24,14 +24,23 @@
 CLANG_CONFIG_EXTRA_CPPFLAGS :=
 CLANG_CONFIG_EXTRA_LDFLAGS :=
 
-CLANG_CONFIG_EXTRA_CFLAGS := \
+CLANG_CONFIG_EXTRA_CFLAGS += \
   -D__compiler_offsetof=__builtin_offsetof
 
+# Help catch common 32/64-bit errors.
+CLANG_CONFIG_EXTRA_CFLAGS += \
+  -Werror=int-conversion
+
 CLANG_CONFIG_UNKNOWN_CFLAGS := \
   -funswitch-loops \
+  -fno-tree-sra \
+  -finline-limit=64 \
   -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
 
 # Clang flags for all host rules
@@ -47,10 +56,13 @@
 CLANG_CONFIG_TARGET_EXTRA_LDFLAGS :=
 
 # HOST config
-ifneq ($(strip $(BUILD_HOST_64bit)),)
-include $(BUILD_SYSTEM)/clang/HOST_x86_64.mk
-else
+clang_2nd_arch_prefix :=
 include $(BUILD_SYSTEM)/clang/HOST_$(HOST_ARCH).mk
+
+# HOST_2ND_ARCH config
+ifdef HOST_2ND_ARCH
+clang_2nd_arch_prefix := $(HOST_2ND_ARCH_VAR_PREFIX)
+include $(BUILD_SYSTEM)/clang/HOST_$(HOST_2ND_ARCH).mk
 endif
 
 # TARGET config
diff --git a/core/clang/x86_common.mk b/core/clang/x86_common.mk
deleted file mode 100644
index 0bb565f..0000000
--- a/core/clang/x86_common.mk
+++ /dev/null
@@ -1,54 +0,0 @@
-ifeq ($(HOST_OS),darwin)
-# nothing required here yet
-endif
-
-ifeq ($(HOST_OS),linux)
-CLANG_CONFIG_x86_LINUX_HOST_EXTRA_ASFLAGS := \
-  --gcc-toolchain=$(HOST_TOOLCHAIN_FOR_CLANG) \
-  --sysroot=$(HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -no-integrated-as
-
-CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CFLAGS := \
-  --gcc-toolchain=$(HOST_TOOLCHAIN_FOR_CLANG) \
-  -no-integrated-as
-
-ifneq ($(strip $(BUILD_HOST_64bit)),)
-CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CPPFLAGS :=   \
-  --gcc-toolchain=$(HOST_TOOLCHAIN_FOR_CLANG) \
-  --sysroot=$(HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -isystem $(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6 \
-  -isystem $(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/x86_64-linux \
-  -isystem $(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/backward \
-  -no-integrated-as
-
-CLANG_CONFIG_x86_LINUX_HOST_EXTRA_LDFLAGS := \
-  --gcc-toolchain=$(HOST_TOOLCHAIN_FOR_CLANG) \
-  --sysroot=$(HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -B$(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/bin \
-  -B$(HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6 \
-  -L$(HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6 \
-  -L$(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/lib64/ \
-  -no-integrated-as
-else
-CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CPPFLAGS :=   \
-  --gcc-toolchain=$(HOST_TOOLCHAIN_FOR_CLANG) \
-  --sysroot=$(HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -isystem $(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6 \
-  -isystem $(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/x86_64-linux/32 \
-  -isystem $(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/include/c++/4.6/backward \
-  -no-integrated-as
-
-CLANG_CONFIG_x86_LINUX_HOST_EXTRA_LDFLAGS := \
-  --gcc-toolchain=$(HOST_TOOLCHAIN_FOR_CLANG) \
-  --sysroot=$(HOST_TOOLCHAIN_FOR_CLANG)/sysroot \
-  -B$(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/bin \
-  -B$(HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6/32 \
-  -L$(HOST_TOOLCHAIN_FOR_CLANG)/lib/gcc/x86_64-linux/4.6/32 \
-  -L$(HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/lib32/ \
-  -no-integrated-as
-endif
-endif
-
-ifeq ($(HOST_OS),windows)
-# nothing required here yet
-endif
\ No newline at end of file
diff --git a/core/cleanbuild.mk b/core/cleanbuild.mk
index dfdf43d..0932aa1 100644
--- a/core/cleanbuild.mk
+++ b/core/cleanbuild.mk
@@ -81,6 +81,28 @@
     $(info Clean step: $(INTERNAL_CLEAN_STEP.$(step))) \
     $(shell $(INTERNAL_CLEAN_STEP.$(step))) \
    )
+
+  # Rewrite the clean step for the second arch.
+  ifdef TARGET_2ND_ARCH
+  # $(1): the clean step cmd
+  # $(2): the prefix to search for
+  # $(3): the prefix to replace with
+  define -cs-rewrite-cleanstep
+  $(if $(filter $(2)/%,$(1)),\
+    $(eval _crs_new_cmd := $(patsubst $(2)/%,$(3)/%,$(1)))\
+    $(info Clean step: $(_crs_new_cmd))\
+    $(shell $(_crs_new_cmd)))
+  endef
+  $(foreach step,$(steps), \
+    $(call -cs-rewrite-cleanstep,$(INTERNAL_CLEAN_STEP.$(step)),$(TARGET_OUT_INTERMEDIATES),$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATES))\
+    $(call -cs-rewrite-cleanstep,$(INTERNAL_CLEAN_STEP.$(step)),$(TARGET_OUT_SHARED_LIBRARIES),$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SHARED_LIBRARIES))\
+    $(call -cs-rewrite-cleanstep,$(INTERNAL_CLEAN_STEP.$(step)),$(TARGET_OUT_VENDOR_SHARED_LIBRARIES),$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_VENDOR_SHARED_LIBRARIES))\
+    $(call -cs-rewrite-cleanstep,$(INTERNAL_CLEAN_STEP.$(step)),$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATES),$(TARGET_OUT_INTERMEDIATES))\
+    $(call -cs-rewrite-cleanstep,$(INTERNAL_CLEAN_STEP.$(step)),$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SHARED_LIBRARIES),$(TARGET_OUT_SHARED_LIBRARIES))\
+    $(call -cs-rewrite-cleanstep,$(INTERNAL_CLEAN_STEP.$(step)),$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_VENDOR_SHARED_LIBRARIES),$(TARGET_OUT_VENDOR_SHARED_LIBRARIES))\
+    )
+  endif
+  _crs_new_cmd :=
   steps :=
 endif
 CURRENT_CLEAN_BUILD_VERSION :=
@@ -179,11 +201,13 @@
 	$(HOST_OUT)/obj/NOTICE_FILES \
 	$(HOST_OUT)/sdk \
 	$(PRODUCT_OUT)/*.img \
+	$(PRODUCT_OUT)/*.ini \
 	$(PRODUCT_OUT)/*.txt \
 	$(PRODUCT_OUT)/*.xlb \
 	$(PRODUCT_OUT)/*.zip \
 	$(PRODUCT_OUT)/kernel \
 	$(PRODUCT_OUT)/data \
+	$(PRODUCT_OUT)/skin \
 	$(PRODUCT_OUT)/obj/APPS \
 	$(PRODUCT_OUT)/obj/NOTICE_FILES \
 	$(PRODUCT_OUT)/obj/PACKAGING \
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index 1902d57..dc2362d 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -122,7 +122,7 @@
 LOCAL_RENDERSCRIPT_TARGET_API:=
 LOCAL_BUILD_HOST_DEX:=
 LOCAL_DEX_PREOPT:= # '',true,false,nostripping
-LOCAL_DEX_PREOPT_IMAGE:=
+LOCAL_DEX_PREOPT_IMAGE_LOCATION:=
 LOCAL_PROTOC_OPTIMIZE_TYPE:= # lite(default),micro,nano,full
 LOCAL_PROTOC_FLAGS:=
 LOCAL_PROTO_JAVA_OUTPUT_PARAMS:=
@@ -137,6 +137,7 @@
 LOCAL_ADDRESS_SANITIZER:=
 LOCAL_JAR_EXCLUDE_FILES:=
 LOCAL_JAR_PACKAGES:=
+LOCAL_JAR_EXCLUDE_PACKAGES:=
 LOCAL_LINT_FLAGS:=
 LOCAL_SOURCE_FILES_ALL_GENERATED:= # '',true
 # Don't delete the META_INF dir when merging static Java libraries.
@@ -150,10 +151,12 @@
 LOCAL_NO_SYNTAX_CHECK:=
 LOCAL_NO_STATIC_ANALYZER:=
 LOCAL_32_BIT_ONLY:= # '',true
+LOCAL_MULTILIB:=
 LOCAL_MODULE_TARGET_ARCH:=
 LOCAL_MODULE_TARGET_ARCH_WARN:=
 LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH:=
 LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH_WARN:=
+LOCAL_MODULE_HOST_ARCH:=
 
 # arch specific variables
 LOCAL_SRC_FILES_$(TARGET_ARCH):=
@@ -168,6 +171,8 @@
 LOCAL_WHOLE_STATIC_LIBRARIES_$(TARGET_ARCH):=
 LOCAL_GENERATED_SOURCES_$(TARGET_ARCH):=
 LOCAL_REQUIRED_MODULES_$(TARGET_ARCH):=
+LOCAL_CLANG_$(TARGET_ARCH):=
+LOCAL_PREBUILT_JNI_LIBS_$(TARGET_ARCH):=
 ifdef TARGET_2ND_ARCH
 LOCAL_SRC_FILES_$(TARGET_2ND_ARCH):=
 LOCAL_CFLAGS_$(TARGET_2ND_ARCH):=
@@ -181,6 +186,36 @@
 LOCAL_WHOLE_STATIC_LIBRARIES_$(TARGET_2ND_ARCH):=
 LOCAL_GENERATED_SOURCES_$(TARGET_2ND_ARCH):=
 LOCAL_REQUIRED_MODULES_$(TARGET_2ND_ARCH):=
+LOCAL_CLANG_$(TARGET_2ND_ARCH):=
+LOCAL_PREBUILT_JNI_LIBS_$(TARGET_2ND_ARCH):=
+endif
+LOCAL_SRC_FILES_$(HOST_ARCH):=
+LOCAL_CFLAGS_$(HOST_ARCH):=
+LOCAL_CPPFLAGS_$(HOST_ARCH):=
+LOCAL_C_INCLUDES_$(HOST_ARCH):=
+LOCAL_ASFLAGS_$(HOST_ARCH):=
+LOCAL_NO_CRT_$(HOST_ARCH):=
+LOCAL_LDFLAGS_$(HOST_ARCH):=
+LOCAL_SHARED_LIBRARIES_$(HOST_ARCH):=
+LOCAL_STATIC_LIBRARIES_$(HOST_ARCH):=
+LOCAL_WHOLE_STATIC_LIBRARIES_$(HOST_ARCH):=
+LOCAL_GENERATED_SOURCES_$(HOST_ARCH):=
+LOCAL_REQUIRED_MODULES_$(HOST_ARCH):=
+LOCAL_CLANG_$(HOST_ARCH):=
+ifdef HOST_2ND_ARCH
+LOCAL_SRC_FILES_$(HOST_2ND_ARCH):=
+LOCAL_CFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_CPPFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_C_INCLUDES_$(HOST_2ND_ARCH):=
+LOCAL_ASFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_NO_CRT_$(HOST_2ND_ARCH):=
+LOCAL_LDFLAGS_$(HOST_2ND_ARCH):=
+LOCAL_SHARED_LIBRARIES_$(HOST_2ND_ARCH):=
+LOCAL_STATIC_LIBRARIES_$(HOST_2ND_ARCH):=
+LOCAL_WHOLE_STATIC_LIBRARIES_$(HOST_2ND_ARCH):=
+LOCAL_GENERATED_SOURCES_$(HOST_2ND_ARCH):=
+LOCAL_REQUIRED_MODULES_$(HOST_2ND_ARCH):=
+LOCAL_CLANG_$(HOST_2ND_ARCH):=
 endif
 
 LOCAL_SRC_FILES_32:=
@@ -207,7 +242,8 @@
 LOCAL_MODULE_PATH_64:=
 LOCAL_MODULE_STEM_32:=
 LOCAL_MODULE_STEM_64:=
-LOCAL_MULTILIB:=
+LOCAL_CLANG_32:=
+LOCAL_CLANG_64:=
 
 # Trim MAKEFILE_LIST so that $(call my-dir) doesn't need to
 # iterate over thousands of entries every time.
diff --git a/core/combo/HOST_darwin-x86.mk b/core/combo/HOST_darwin-x86.mk
index b819f36..4a2bfe3 100644
--- a/core/combo/HOST_darwin-x86.mk
+++ b/core/combo/HOST_darwin-x86.mk
@@ -17,115 +17,75 @@
 # Configuration for Darwin (Mac OS X) on x86.
 # Included by combo/select.mk
 
-ifneq ($(strip $(BUILD_HOST_64bit)),)
-# By default we build everything in 32-bit, because it gives us
-# more consistency between the host tools and the target.
-# BUILD_HOST_64bit=1 overrides it for tool like emulator
-# which can benefit from 64-bit host arch.
-HOST_GLOBAL_CFLAGS += -m64
-HOST_GLOBAL_LDFLAGS += -m64
-else
-HOST_GLOBAL_CFLAGS += -m32
-HOST_GLOBAL_LDFLAGS += -m32
-endif # BUILD_HOST_64bit
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -m32
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -m32
 
 ifneq ($(strip $(BUILD_HOST_static)),)
 # Statically-linked binaries are desirable for sandboxed environment
-HOST_GLOBAL_LDFLAGS += -static
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -static
 endif # BUILD_HOST_static
 
 # Workaround differences in inttypes.h between host and target.
 # See bug 12708004.
-HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
 
-build_mac_version := $(shell sw_vers -productVersion)
+include $(BUILD_COMBOS)/mac_version.mk
 
-mac_sdk_versions_supported :=  10.6 10.7 10.8
-ifneq ($(strip $(MAC_SDK_VERSION)),)
-mac_sdk_version := $(MAC_SDK_VERSION)
-ifeq ($(filter $(mac_sdk_version),$(mac_sdk_versions_supported)),)
-$(warning ****************************************************************)
-$(warning * MAC_SDK_VERSION $(MAC_SDK_VERSION) isn't one of the supported $(mac_sdk_versions_supported))
-$(warning ****************************************************************)
-$(error Stop.)
-endif
-else
-mac_sdk_versions_installed := $(shell xcodebuild -showsdks | grep macosx | sort | sed -e "s/.*macosx//g")
-mac_sdk_version := $(firstword $(filter $(mac_sdk_versions_installed), $(mac_sdk_versions_supported)))
-ifeq ($(mac_sdk_version),)
-mac_sdk_version := $(firstword $(mac_sdk_versions_supported))
-endif
-endif
-
-mac_sdk_path := $(shell xcode-select -print-path)
-# try /Applications/Xcode*.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.?.sdk
-#  or /Volume/Xcode/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.?.sdk
-mac_sdk_root := $(mac_sdk_path)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX$(mac_sdk_version).sdk
-ifeq ($(wildcard $(mac_sdk_root)),)
-# try legacy /Developer/SDKs/MacOSX10.?.sdk
-mac_sdk_root := /Developer/SDKs/MacOSX$(mac_sdk_version).sdk
-endif
-ifeq ($(wildcard $(mac_sdk_root)),)
-$(warning *****************************************************)
-$(warning * Can not find SDK $(mac_sdk_version) at $(mac_sdk_root))
-$(warning *****************************************************)
-$(error Stop.)
-endif
-
-ifeq ($(mac_sdk_version),10.6)
-  gcc_darwin_version := 10
-else
-  gcc_darwin_version := 11
-endif
-
-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)
+$(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 $(HOST_TOOLCHAIN_PREFIX)-gcc)))
-HOST_CC  := $(HOST_TOOLCHAIN_PREFIX)-gcc
-HOST_CXX := $(HOST_TOOLCHAIN_PREFIX)-g++
+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++
 ifeq ($(mac_sdk_version),10.8)
 # 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)
+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
-HOST_CC := gcc
-HOST_CXX := g++
+$(combo_2nd_arch_prefix)HOST_CC := gcc
+$(combo_2nd_arch_prefix)HOST_CXX := g++
 endif # $(HOST_TOOLCHAIN_PREFIX)-gcc exists
-HOST_AR := $(AR)
-HOST_STRIP := $(STRIP)
-HOST_STRIP_COMMAND = $(HOST_STRIP) --strip-all $< -o $@
 
-HOST_GLOBAL_CFLAGS += -isysroot $(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version) -DMACOSX_DEPLOYMENT_TARGET=$(mac_sdk_version)
-HOST_GLOBAL_LDFLAGS += -isysroot $(mac_sdk_root) -Wl,-syslibroot,$(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version)
+# gcc location for clang; to be updated when clang is updated
+# HOST_TOOLCHAIN_ROOT is a Darwin-specific define
+$(combo_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_ROOT)
 
-HOST_GLOBAL_CFLAGS += -fPIC -funwind-tables
-HOST_NO_UNDEFINED_LDFLAGS := -Wl,-undefined,error
+$(combo_2nd_arch_prefix)HOST_AR := $(AR)
 
-HOST_SHLIB_SUFFIX := .dylib
-HOST_JNILIB_SUFFIX := .jnilib
+$(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_LDFLAGS += -isysroot $(mac_sdk_root) -Wl,-syslibroot,$(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version)
 
-HOST_GLOBAL_CFLAGS += \
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -fPIC -funwind-tables
+$(combo_2nd_arch_prefix)HOST_NO_UNDEFINED_LDFLAGS := -Wl,-undefined,error
+
+$(combo_2nd_arch_prefix)HOST_SHLIB_SUFFIX := .dylib
+$(combo_2nd_arch_prefix)HOST_JNILIB_SUFFIX := .jnilib
+
+# TODO: add AndroidConfig.h for darwin-x86_64
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += \
     -include $(call select-android-config-h,darwin-x86)
 
 ifneq ($(filter 10.7 10.7.% 10.8 10.8.%, $(build_mac_version)),)
-       HOST_RUN_RANLIB_AFTER_COPYING := false
+       $(combo_2nd_arch_prefix)HOST_RUN_RANLIB_AFTER_COPYING := false
 else
-       HOST_RUN_RANLIB_AFTER_COPYING := true
+       $(combo_2nd_arch_prefix)HOST_RUN_RANLIB_AFTER_COPYING := true
        PRE_LION_DYNAMIC_LINKER_OPTIONS := -Wl,-dynamic
 endif
-HOST_GLOBAL_ARFLAGS := cqs
+$(combo_2nd_arch_prefix)HOST_GLOBAL_ARFLAGS := cqs
+
+############################################################
+## Macros after this line are shared by the 64-bit config.
 
 HOST_CUSTOM_LD_COMMAND := true
 
 define transform-host-o-to-shared-lib-inner
 $(hide) $(PRIVATE_CXX) \
         -dynamiclib -single_module -read_only_relocs suppress \
-        $(HOST_GLOBAL_LD_DIRS) \
-	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
-	   $(PRIVATE_HOST_GLOBAL_LDFLAGS) \
-	) \
+        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LD_DIRS) \
+        $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
+            $(PRIVATE_HOST_GLOBAL_LDFLAGS) \
+        ) \
         $(PRIVATE_ALL_OBJECTS) \
         $(addprefix -force_load , $(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
         $(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
@@ -133,34 +93,28 @@
         $(PRIVATE_LDLIBS) \
         -o $@ \
         -install_name @rpath/$(notdir $@) \
-        -Wl,-rpath,@loader_path/../lib \
-        $(PRIVATE_LDFLAGS) \
-        $(HOST_LIBGCC)
+        -Wl,-rpath,@loader_path/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES)) \
+        $(PRIVATE_LDFLAGS)
 endef
 
 define transform-host-o-to-executable-inner
 $(hide) $(PRIVATE_CXX) \
-        -Wl,-rpath,@loader_path/../lib \
+        -Wl,-rpath,@loader_path/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES)) \
         -o $@ \
         $(PRE_LION_DYNAMIC_LINKER_OPTIONS) -Wl,-headerpad_max_install_names \
-        $(HOST_GLOBAL_LD_DIRS) \
-	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
-	   $(PRIVATE_HOST_GLOBAL_LDFLAGS) \
-	) \
+        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LD_DIRS) \
+        $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
+           $(PRIVATE_HOST_GLOBAL_LDFLAGS) \
+        ) \
         $(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
         $(PRIVATE_ALL_OBJECTS) \
         $(call normalize-host-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
         $(call normalize-host-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
         $(PRIVATE_LDFLAGS) \
-        $(PRIVATE_LDLIBS) \
-        $(HOST_LIBGCC)
+        $(PRIVATE_LDLIBS)
 endef
 
 # $(1): The file to check
 define get-file-size
 stat -f "%z" $(1)
 endef
-
-# gcc location for clang; to be updated when clang is updated
-# HOST_TOOLCHAIN_ROOT is a Darwin-specific define
-HOST_TOOLCHAIN_FOR_CLANG := $(HOST_TOOLCHAIN_ROOT)
\ No newline at end of file
diff --git a/core/combo/HOST_darwin-x86_64.mk b/core/combo/HOST_darwin-x86_64.mk
new file mode 100644
index 0000000..8ad3ba7
--- /dev/null
+++ b/core/combo/HOST_darwin-x86_64.mk
@@ -0,0 +1,80 @@
+#
+# Copyright (C) 2006 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.
+#
+
+# Configuration for Darwin (Mac OS X) on x86_64.
+# Included by combo/select.mk
+
+HOST_IS_64_BIT := true
+
+HOST_GLOBAL_CFLAGS += -m64
+HOST_GLOBAL_LDFLAGS += -m64
+
+ifneq ($(strip $(BUILD_HOST_static)),)
+# Statically-linked binaries are desirable for sandboxed environment
+HOST_GLOBAL_LDFLAGS += -static
+endif # BUILD_HOST_static
+
+# Workaround differences in inttypes.h between host and target.
+# See bug 12708004.
+HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
+
+include $(BUILD_COMBOS)/mac_version.mk
+
+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++
+ifeq ($(mac_sdk_version),10.8)
+# 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
+HOST_TOOLCHAIN_FOR_CLANG := $(HOST_TOOLCHAIN_ROOT)
+
+HOST_AR := $(AR)
+
+HOST_GLOBAL_CFLAGS += -isysroot $(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version) -DMACOSX_DEPLOYMENT_TARGET=$(mac_sdk_version)
+HOST_GLOBAL_LDFLAGS += -isysroot $(mac_sdk_root) -Wl,-syslibroot,$(mac_sdk_root) -mmacosx-version-min=$(mac_sdk_version)
+
+HOST_GLOBAL_CFLAGS += -fPIC -funwind-tables
+HOST_NO_UNDEFINED_LDFLAGS := -Wl,-undefined,error
+
+HOST_SHLIB_SUFFIX := .dylib
+HOST_JNILIB_SUFFIX := .jnilib
+
+HOST_GLOBAL_CFLAGS += \
+    -include $(call select-android-config-h,darwin-x86)
+
+ifneq ($(filter 10.7 10.7.% 10.8 10.8.%, $(build_mac_version)),)
+       HOST_RUN_RANLIB_AFTER_COPYING := false
+else
+       HOST_RUN_RANLIB_AFTER_COPYING := true
+endif
+HOST_GLOBAL_ARFLAGS := cqs
+
+# We Reuse the following functions with the same name from HOST_darwin-x86.mk:
+# transform-host-o-to-shared-lib-inner
+# transform-host-o-to-executable-inner
+# get-file-size
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index 1472849..c931937 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -17,49 +17,46 @@
 # Configuration for builds hosted on linux-x86.
 # Included by combo/select.mk
 
-# $(1): The file to check
-define get-file-size
-stat --format "%s" "$(1)" | tr -d '\n'
-endef
-
-ifeq ($(strip $(HOST_TOOLCHAIN_PREFIX)),)
-HOST_TOOLCHAIN_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.6/bin/x86_64-linux-
+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-
 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
+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
 
-HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.6/
-ifneq ($(strip $(BUILD_HOST_64bit)),)
-# By default we build everything in 32-bit, because it gives us
-# more consistency between the host tools and the target.
-# BUILD_HOST_64bit=1 overrides it for tool like emulator
-# which can benefit from 64-bit host arch.
-HOST_GLOBAL_CFLAGS += -m64 -Wa,--noexecstack
-HOST_GLOBAL_LDFLAGS += -m64 -Wl,-z,noexecstack
-else
+# 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/
+
 # We expect SSE3 floating point math.
-HOST_GLOBAL_CFLAGS += -mstackrealign -msse3 -mfpmath=sse -m32 -Wa,--noexecstack
-HOST_GLOBAL_LDFLAGS += -m32 -Wl,-z,noexecstack
-endif # BUILD_HOST_64bit
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -mstackrealign -msse3 -mfpmath=sse -m32 -Wa,--noexecstack
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -m32 -Wl,-z,noexecstack
 
 ifneq ($(strip $(BUILD_HOST_static)),)
 # Statically-linked binaries are desirable for sandboxed environment
-HOST_GLOBAL_LDFLAGS += -static
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -static
 endif # BUILD_HOST_static
 
-HOST_GLOBAL_CFLAGS += -fPIC \
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -fPIC \
   -no-canonical-prefixes \
   -include $(call select-android-config-h,linux-x86)
 
 # Disable new longjmp in glibc 2.11 and later. See bug 2967937.
-HOST_GLOBAL_CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0
 
 # Workaround differences in inttypes.h between host and target.
 # See bug 12708004.
-HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
 
-HOST_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
+$(combo_2nd_arch_prefix)HOST_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
+
+
+############################################################
+## Macros after this line are shared by the 64-bit config.
+
+# $(1): The file to check
+define get-file-size
+stat --format "%s" "$(1)" | tr -d '\n'
+endef
diff --git a/core/combo/HOST_linux-x86_64.mk b/core/combo/HOST_linux-x86_64.mk
new file mode 100644
index 0000000..8f3a311
--- /dev/null
+++ b/core/combo/HOST_linux-x86_64.mk
@@ -0,0 +1,55 @@
+#
+# Copyright (C) 2006 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.
+#
+
+# Configuration for builds hosted on linux-x86_64.
+# Included by combo/select.mk
+
+HOST_IS_64_BIT := true
+
+ifeq ($(strip $(HOST_TOOLCHAIN_PREFIX)),)
+HOST_TOOLCHAIN_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.6/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_GLOBAL_CFLAGS += -m64 -Wa,--noexecstack
+HOST_GLOBAL_LDFLAGS += -m64 -Wl,-z,noexecstack
+
+ifneq ($(strip $(BUILD_HOST_static)),)
+# Statically-linked binaries are desirable for sandboxed environment
+HOST_GLOBAL_LDFLAGS += -static
+endif # BUILD_HOST_static
+
+# TODO: Add AndroidConfig.h for linux-x86_64
+HOST_GLOBAL_CFLAGS += -fPIC \
+  -no-canonical-prefixes \
+  -include $(call select-android-config-h,linux-x86)
+
+# Disable new longjmp in glibc 2.11 and later. See bug 2967937.
+HOST_GLOBAL_CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0
+
+# Workaround differences in inttypes.h between host and target.
+# See bug 12708004.
+HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
+
+HOST_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
diff --git a/core/combo/HOST_windows-x86.mk b/core/combo/HOST_windows-x86.mk
index 1709711..4d871d8 100644
--- a/core/combo/HOST_windows-x86.mk
+++ b/core/combo/HOST_windows-x86.mk
@@ -27,32 +27,29 @@
 ifneq ($(strip $(USE_MINGW)),)
 HOST_ACP_UNAVAILABLE := true
 TOOLS_EXE_SUFFIX :=
-HOST_GLOBAL_CFLAGS += -DUSE_MINGW
-ifneq ($(strip $(BUILD_HOST_64bit)),)
-TOOLS_PREFIX := /usr/bin/amd64-mingw32msvc-
-HOST_C_INCLUDES += /usr/lib/gcc/amd64-mingw32msvc/4.4.2/include
-HOST_GLOBAL_LD_DIRS += -L/usr/amd64-mingw32msvc/lib
-else
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -DUSE_MINGW
 TOOLS_PREFIX := /usr/bin/i586-mingw32msvc-
-HOST_C_INCLUDES += /usr/lib/gcc/i586-mingw32msvc/3.4.4/include
-HOST_GLOBAL_LD_DIRS += -L/usr/i586-mingw32msvc/lib
-endif # BUILD_HOST_64bit
+$(combo_2nd_arch_prefix)HOST_C_INCLUDES += /usr/lib/gcc/i586-mingw32msvc/3.4.4/include
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LD_DIRS += -L/usr/i586-mingw32msvc/lib
 endif # USE_MINGW
 endif # Linux
 
 # Workaround differences in inttypes.h between host and target.
 # See bug 12708004.
-HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS -D__USE_MINGW_ANSI_STDIO
 
-HOST_CC := $(TOOLS_PREFIX)gcc$(TOOLS_EXE_SUFFIX)
-HOST_CXX := $(TOOLS_PREFIX)g++$(TOOLS_EXE_SUFFIX)
-HOST_AR := $(TOOLS_PREFIX)ar$(TOOLS_EXE_SUFFIX)
+$(combo_2nd_arch_prefix)HOST_CC := $(TOOLS_PREFIX)gcc$(TOOLS_EXE_SUFFIX)
+$(combo_2nd_arch_prefix)HOST_CXX := $(TOOLS_PREFIX)g++$(TOOLS_EXE_SUFFIX)
+$(combo_2nd_arch_prefix)HOST_AR := $(TOOLS_PREFIX)ar$(TOOLS_EXE_SUFFIX)
 
-HOST_GLOBAL_CFLAGS += -include $(call select-android-config-h,windows)
-HOST_GLOBAL_LDFLAGS += --enable-stdcall-fixup
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += \
+    -include $(call select-android-config-h,windows)
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += \
+    --enable-stdcall-fixup
+
 ifneq ($(strip $(BUILD_HOST_static)),)
 # Statically-linked binaries are desirable for sandboxed environment
-HOST_GLOBAL_LDFLAGS += -static
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -static
 endif # BUILD_HOST_static
 
 # when building under Cygwin, ensure that we use Mingw compilation by default.
@@ -66,11 +63,14 @@
 #
 ifneq ($(findstring CYGWIN,$(UNAME)),)
 ifeq ($(strip $(USE_CYGWIN)),)
-HOST_GLOBAL_CFLAGS += -mno-cygwin
-HOST_GLOBAL_LDFLAGS += -mno-cygwin -mconsole
+$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -mno-cygwin
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -mno-cygwin -mconsole
 endif
 endif
 
+############################################################
+## Macros after this line are shared by the 64-bit config.
+
 HOST_SHLIB_SUFFIX := .dll
 HOST_EXECUTABLE_SUFFIX := .exe
 
diff --git a/core/combo/HOST_windows-x86_64.mk b/core/combo/HOST_windows-x86_64.mk
new file mode 100644
index 0000000..9edc619
--- /dev/null
+++ b/core/combo/HOST_windows-x86_64.mk
@@ -0,0 +1,68 @@
+#
+# Copyright (C) 2006 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.
+#
+
+# Configuration for Windows on x86_64.
+# Included by combo/select.make
+
+# right now we get these from the environment, but we should
+# pick them from the tree somewhere
+TOOLS_PREFIX := #prebuilt/windows/host/bin/
+TOOLS_EXE_SUFFIX := .exe
+
+HOST_IS_64_BIT := true
+
+# Settings to use MinGW has a cross-compiler under Linux
+ifneq ($(findstring Linux,$(UNAME)),)
+ifneq ($(strip $(USE_MINGW)),)
+HOST_ACP_UNAVAILABLE := true
+TOOLS_EXE_SUFFIX :=
+HOST_GLOBAL_CFLAGS += -DUSE_MINGW
+TOOLS_PREFIX := /usr/bin/amd64-mingw32msvc-
+HOST_C_INCLUDES += /usr/lib/gcc/amd64-mingw32msvc/4.4.2/include
+HOST_GLOBAL_LD_DIRS += -L/usr/amd64-mingw32msvc/lib
+endif # USE_MINGW
+endif # Linux
+
+# Workaround differences in inttypes.h between host and target.
+# See bug 12708004.
+HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS -D__USE_MINGW_ANSI_STDIO
+
+HOST_CC := $(TOOLS_PREFIX)gcc$(TOOLS_EXE_SUFFIX)
+HOST_CXX := $(TOOLS_PREFIX)g++$(TOOLS_EXE_SUFFIX)
+HOST_AR := $(TOOLS_PREFIX)ar$(TOOLS_EXE_SUFFIX)
+
+HOST_GLOBAL_CFLAGS += -include $(call select-android-config-h,windows)
+HOST_GLOBAL_LDFLAGS += --enable-stdcall-fixup
+ifneq ($(strip $(BUILD_HOST_static)),)
+# Statically-linked binaries are desirable for sandboxed environment
+HOST_GLOBAL_LDFLAGS += -static
+endif # BUILD_HOST_static
+
+# when building under Cygwin, ensure that we use Mingw compilation by default.
+# you can disable this (i.e. to generate Cygwin executables) by defining the
+# USE_CYGWIN variable in your environment, e.g.:
+#
+#   export USE_CYGWIN=1
+#
+# note that the -mno-cygwin flags are not needed when cross-compiling the
+# Windows host tools on Linux
+#
+ifneq ($(findstring CYGWIN,$(UNAME)),)
+ifeq ($(strip $(USE_CYGWIN)),)
+HOST_GLOBAL_CFLAGS += -mno-cygwin
+HOST_GLOBAL_LDFLAGS += -mno-cygwin -mconsole
+endif
+endif
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index d882ea6..9968ae6 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -162,6 +162,8 @@
 # into account.
 $(combo_2nd_arch_prefix)TARGET_LIBGCC := $(shell $($(combo_2nd_arch_prefix)TARGET_CC) \
         $($(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)
 target_libgcov := $(shell $($(combo_2nd_arch_prefix)TARGET_CC) $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) \
         -print-file-name=libgcov.a)
 endif
@@ -225,6 +227,7 @@
 	-nostdlib -Wl,-soname,$(notdir $@) \
 	-Wl,--gc-sections \
 	-Wl,-shared,-Bsymbolic \
+	-shared \
 	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
 	$(PRIVATE_ALL_OBJECTS) \
@@ -240,7 +243,8 @@
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -266,7 +270,8 @@
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -288,7 +293,8 @@
 	$(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_FDO_LIB) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	-Wl,--end-group \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
 endef
diff --git a/core/combo/TARGET_linux-arm64.mk b/core/combo/TARGET_linux-arm64.mk
index 6515eb5..4bb665c 100644
--- a/core/combo/TARGET_linux-arm64.mk
+++ b/core/combo/TARGET_linux-arm64.mk
@@ -38,7 +38,7 @@
 TARGET_NDK_GCC_VERSION := 4.8
 
 ifeq ($(strip $(TARGET_GCC_VERSION_EXP)),)
-TARGET_GCC_VERSION := 4.8
+TARGET_GCC_VERSION := 4.9
 else
 TARGET_GCC_VERSION := $(TARGET_GCC_VERSION_EXP)
 endif
@@ -73,13 +73,9 @@
 
 android_config_h := $(call select-android-config-h,linux-arm64)
 
-# HACK: globally disable -fstack-protector until the toolchain supports it
-TARGET_GLOBAL_UNSUPPORTED_CFLAGS := \
-    -fstack-protector \
-    -fstack-protector-all \
-
 TARGET_GLOBAL_CFLAGS += \
 			-fpic -fPIE \
+			-fstack-protector \
 			-ffunction-sections \
 			-fdata-sections \
 			-funwind-tables \
@@ -110,10 +106,10 @@
 #
 TARGET_GLOBAL_CFLAGS += -Wno-psabi
 
-# TODO - temporarily remove "-Wl,-z,relro -Wl,-z,now" as they cause segmentation fault on the
-# v8 foundation model.
 TARGET_GLOBAL_LDFLAGS += \
 			-Wl,-z,noexecstack \
+			-Wl,-z,relro \
+			-Wl,-z,now \
 			-Wl,--warn-shared-textrel \
 			-Wl,--fatal-warnings \
 			-Wl,-maarch64linux \
@@ -136,6 +132,8 @@
 
 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)
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-$(TARGET_ARCH)
@@ -165,7 +163,9 @@
 define transform-o-to-shared-lib-inner
 $(hide) $(PRIVATE_CXX) \
 	-nostdlib -Wl,-soname,$(notdir $@) \
+	-Wl,--gc-sections \
 	-Wl,-shared,-Bsymbolic \
+	-shared \
 	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
 	$(PRIVATE_ALL_OBJECTS) \
@@ -181,7 +181,8 @@
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -189,6 +190,7 @@
 define transform-o-to-executable-inner
 $(hide) $(PRIVATE_CXX) -nostdlib -Bdynamic -fPIE -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) \
@@ -206,13 +208,15 @@
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(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)) \
@@ -227,7 +231,8 @@
 	$(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_FDO_LIB) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	-Wl,--end-group \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
 endef
diff --git a/core/combo/TARGET_linux-mips.mk b/core/combo/TARGET_linux-mips.mk
index 015d46b..f52c375 100644
--- a/core/combo/TARGET_linux-mips.mk
+++ b/core/combo/TARGET_linux-mips.mk
@@ -149,6 +149,8 @@
 # into account.
 $(combo_2nd_arch_prefix)TARGET_LIBGCC := \
   $(shell $($(combo_2nd_arch_prefix)TARGET_CC) $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) -print-file-name=libgcc.a)
+$(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)
 LIBGCC_EH := $(shell $($(combo_2nd_arch_prefix)TARGET_CC) $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) -print-file-name=libgcc_eh.a)
 ifneq ($(LIBGCC_EH),libgcc_eh.a)
   $(combo_2nd_arch_prefix)TARGET_LIBGCC += $(LIBGCC_EH)
@@ -216,6 +218,7 @@
 	-nostdlib -Wl,-soname,$(notdir $@) \
 	-Wl,--gc-sections \
 	-Wl,-shared,-Bsymbolic \
+	-shared \
 	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
 	$(PRIVATE_ALL_OBJECTS) \
@@ -225,13 +228,14 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -251,13 +255,14 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -279,7 +284,8 @@
 	$(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_FDO_LIB) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	-Wl,--end-group \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
 endef
diff --git a/core/combo/TARGET_linux-mips64.mk b/core/combo/TARGET_linux-mips64.mk
index a7b03b2..e9f5adb 100644
--- a/core/combo/TARGET_linux-mips64.mk
+++ b/core/combo/TARGET_linux-mips64.mk
@@ -155,6 +155,8 @@
 # into account.
 TARGET_LIBGCC := \
   $(shell $(TARGET_CC) $(TARGET_GLOBAL_CFLAGS) -print-file-name=libgcc.a)
+TARGET_LIBATOMIC := \
+  $(shell $(TARGET_CC) $(TARGET_GLOBAL_CFLAGS) -print-file-name=libatomic.a)
 LIBGCC_EH := $(shell $(TARGET_CC) $(TARGET_GLOBAL_CFLAGS) -print-file-name=libgcc_eh.a)
 ifneq ($(LIBGCC_EH),libgcc_eh.a)
   TARGET_LIBGCC += $(LIBGCC_EH)
@@ -224,6 +226,7 @@
 $(hide) $(PRIVATE_CXX) \
 	-nostdlib -Wl,-soname,$(notdir $@) \
 	-Wl,--gc-sections \
+	-shared \
 	-Wl,-shared,-Bsymbolic \
 	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTBEGIN_SO_O)) \
@@ -234,13 +237,14 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -260,13 +264,14 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_TARGET_GLOBAL_LDFLAGS) \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -288,7 +293,8 @@
 	$(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_FDO_LIB) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	-Wl,--end-group \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
 endef
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index 4ebcd93..bc13fb9 100644
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -60,6 +60,8 @@
 ifneq ($(wildcard $($(combo_2nd_arch_prefix)TARGET_CC)),)
 $(combo_2nd_arch_prefix)TARGET_LIBGCC := \
 	$(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)
 target_libgcov := $(shell $($(combo_2nd_arch_prefix)TARGET_CC) $($(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS) \
 	-print-file-name=libgcov.a)
 endif
@@ -190,12 +192,13 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -216,12 +219,13 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -241,7 +245,8 @@
 	-Wl,--start-group \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	-Wl,--end-group \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O))
 endef
diff --git a/core/combo/TARGET_linux-x86_64.mk b/core/combo/TARGET_linux-x86_64.mk
index ee6c6e2..e24f548 100644
--- a/core/combo/TARGET_linux-x86_64.mk
+++ b/core/combo/TARGET_linux-x86_64.mk
@@ -62,6 +62,8 @@
 ifneq ($(wildcard $(TARGET_CC)),)
 TARGET_LIBGCC := \
 	$(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) $(TARGET_GLOBAL_CFLAGS) \
 	-print-file-name=libgcov.a)
 endif
@@ -195,12 +197,13 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_SO_O))
 endef
 
@@ -220,12 +223,13 @@
 	$(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) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(if $(TARGET_BUILD_APPS),$(PRIVATE_TARGET_LIBGCC)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
 	-o $@ \
 	$(PRIVATE_LDFLAGS) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
 	$(PRIVATE_LDLIBS)
 endef
@@ -245,7 +249,8 @@
 	-Wl,--start-group \
 	$(call normalize-target-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(PRIVATE_TARGET_FDO_LIB) \
-	$(PRIVATE_TARGET_LIBGCC) \
+	$(PRIVATE_TARGET_LIBATOMIC) \
+	$(if $(PRIVATE_LIBCXX),,$(PRIVATE_TARGET_LIBGCC)) \
 	-Wl,--end-group \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(PRIVATE_TARGET_CRTEND_O)) \
 	$(PRIVATE_LDLIBS)
diff --git a/core/combo/include/arch/freebsd-x86/AndroidConfig.h b/core/combo/include/arch/freebsd-x86/AndroidConfig.h
deleted file mode 100644
index 4267508..0000000
--- a/core/combo/include/arch/freebsd-x86/AndroidConfig.h
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-/*
- * Android config -- "FreeBSD".  Used for desktop x86 FreeBSD.
- */
-#ifndef _ANDROID_CONFIG_H
-#define _ANDROID_CONFIG_H
-
-/*
- * make sure we are building for FreeBSD
- */
-#ifndef OS_FREEBSD
-#define OS_FREEBSD
-#endif
-/*
- * ===========================================================================
- *                              !!! IMPORTANT !!!
- * ===========================================================================
- *
- * This file is included by ALL C/C++ source files.  Don't put anything in
- * here unless you are absolutely certain it can't go anywhere else.
- *
- * Any C++ stuff must be wrapped with "#ifdef __cplusplus".  Do not use "//"
- * comments.
- */
-
-/*
- * 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 */
-
-/*
- * 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
- *
- * Desktop Linux has this in librt, but it's broken in goobuntu, yielding
- * mildly or wildly inaccurate results.
- */
-#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 this if you have sys/endian.h
- * NOTE: mutually exclusive with HAVE_ENDIAN_H
- */
-#define HAVE_SYS_ENDIAN_H
-
-/*
- * 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.
- */
-
-/*
- * 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 char *
-
-/*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
- * Define if we include <sys/mount.h> for statfs()
- */
-#define INCLUDE_SYS_MOUNT_FOR_STATFS 1
-  
-/*
- * 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 <alloca.h> does not exist
- * NOTE: <alloca.h> defines alloca() which
- *   on FreeBSD is defined in <stdlib.h>
- */
-#define HAVE_NO_ALLOCA_H
-
-/*
- * Defines CLOCK_PROCESS_CPUTIME_ID for clock_gettime()
- * XXX: CLOCK_PROF seems to be commonly used replacement
- */
-#ifndef  CLOCK_PROCESS_CPUTIME_ID
-#define CLOCK_PROCESS_CPUTIME_ID CLOCK_PROF
-#endif
-
-/*
- * 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 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 35eecfe..c06c8bc 100644
--- a/core/combo/include/arch/linux-arm/AndroidConfig.h
+++ b/core/combo/include/arch/linux-arm/AndroidConfig.h
@@ -55,12 +55,6 @@
 #define HAVE_FUTEX
 
 /*
- * Define if we already have the futex wrapper functions defined. Yes if
- * compiling against bionic.
- */
-#define HAVE_FUTEX_WRAPPERS 1
-
-/*
  * Process creation model.  Choose one:
  *
  * HAVE_FORKEXEC - use fork() and exec()
@@ -257,21 +251,11 @@
 #define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
 
 /*
- * Do we have __memcmp16()?
- */
-#define HAVE__MEMCMP16  1
-
-/*
  * type for the third argument to mincore().
  */
 #define MINCORE_POINTER_TYPE unsigned char *
 
 /*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
diff --git a/core/combo/include/arch/linux-arm64/AndroidConfig.h b/core/combo/include/arch/linux-arm64/AndroidConfig.h
index 6f85555..bcbda8f 100644
--- a/core/combo/include/arch/linux-arm64/AndroidConfig.h
+++ b/core/combo/include/arch/linux-arm64/AndroidConfig.h
@@ -55,12 +55,6 @@
 #define HAVE_FUTEX
 
 /*
- * Define if we already have the futex wrapper functions defined. Yes if
- * compiling against bionic.
- */
-#define HAVE_FUTEX_WRAPPERS 1
-
-/*
  * Process creation model.  Choose one:
  *
  * HAVE_FORKEXEC - use fork() and exec()
@@ -259,21 +253,11 @@
 #define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
 
 /*
- * Do we have __memcmp16()?
- */
-#define HAVE__MEMCMP16  1
-
-/*
  * type for the third argument to mincore().
  */
 #define MINCORE_POINTER_TYPE unsigned char *
 
 /*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
diff --git a/core/combo/include/arch/linux-mips/AndroidConfig.h b/core/combo/include/arch/linux-mips/AndroidConfig.h
index 33472d2..bb3dc95 100644
--- a/core/combo/include/arch/linux-mips/AndroidConfig.h
+++ b/core/combo/include/arch/linux-mips/AndroidConfig.h
@@ -55,12 +55,6 @@
 #define HAVE_FUTEX
 
 /*
- * Define if we already have the futex wrapper functions defined. Yes if
- * compiling against bionic.
- */
-#define HAVE_FUTEX_WRAPPERS 1
-
-/*
  * Process creation model.  Choose one:
  *
  * HAVE_FORKEXEC - use fork() and exec()
@@ -274,21 +268,11 @@
 #define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
 
 /*
- * Do we have __memcmp16()?
- */
-#define HAVE__MEMCMP16  1
-
-/*
  * type for the third argument to mincore().
  */
 #define MINCORE_POINTER_TYPE unsigned char *
 
 /*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
diff --git a/core/combo/include/arch/linux-mips64/AndroidConfig.h b/core/combo/include/arch/linux-mips64/AndroidConfig.h
index bfc0351..7ded3ce 100644
--- a/core/combo/include/arch/linux-mips64/AndroidConfig.h
+++ b/core/combo/include/arch/linux-mips64/AndroidConfig.h
@@ -55,12 +55,6 @@
 #define HAVE_FUTEX
 
 /*
- * Define if we already have the futex wrapper functions defined. Yes if
- * compiling against bionic.
- */
-#define HAVE_FUTEX_WRAPPERS 1
-
-/*
  * Process creation model.  Choose one:
  *
  * HAVE_FORKEXEC - use fork() and exec()
@@ -271,21 +265,11 @@
 #define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
 
 /*
- * Do we have __memcmp16()?
- */
-#define HAVE__MEMCMP16  1
-
-/*
  * type for the third argument to mincore().
  */
 #define MINCORE_POINTER_TYPE unsigned char *
 
 /*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
diff --git a/core/combo/include/arch/linux-ppc/AndroidConfig.h b/core/combo/include/arch/linux-ppc/AndroidConfig.h
deleted file mode 100644
index c68f354..0000000
--- a/core/combo/include/arch/linux-ppc/AndroidConfig.h
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-/*
- * Android config -- "Linux".  Used for desktop ppc Linux.
- */
-#ifndef _ANDROID_CONFIG_H
-#define _ANDROID_CONFIG_H
-
-/*
- * ===========================================================================
- *                              !!! IMPORTANT !!!
- * ===========================================================================
- *
- * This file is included by ALL C/C++ source files.  Don't put anything in
- * here unless you are absolutely certain it can't go anywhere else.
- *
- * Any C++ stuff must be wrapped with "#ifdef __cplusplus".  Do not use "//"
- * comments.
- */
-
-/*
- * 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
- *
- * Desktop Linux has this in librt, but it's broken in goobuntu, yielding
- * mildly or wildly inaccurate results.
- */
-/*#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_BIG_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 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_PPC
-
-
-/*
- * 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 *
-
-/*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
- * 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 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 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 79b9cef..5523e49 100644
--- a/core/combo/include/arch/linux-x86/AndroidConfig.h
+++ b/core/combo/include/arch/linux-x86/AndroidConfig.h
@@ -236,11 +236,6 @@
 #define MINCORE_POINTER_TYPE unsigned char *
 
 /*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
diff --git a/core/combo/include/arch/target_linux-x86/AndroidConfig.h b/core/combo/include/arch/target_linux-x86/AndroidConfig.h
index d44a317..c267b2b 100644
--- a/core/combo/include/arch/target_linux-x86/AndroidConfig.h
+++ b/core/combo/include/arch/target_linux-x86/AndroidConfig.h
@@ -41,12 +41,6 @@
 #define HAVE_FUTEX
 
 /*
- * Define if we already have the futex wrapper functions defined. Yes if
- * compiling against bionic.
- */
-#define HAVE_FUTEX_WRAPPERS 1
-
-/*
  * Process creation model.  Choose one:
  *
  * HAVE_FORKEXEC - use fork() and exec()
@@ -246,21 +240,11 @@
 #define OS_SHARED_LIB_FORMAT_STR    "lib%s.so"
 
 /*
- * Do we have __memcmp16()?
- */
-/* #define HAVE__MEMCMP16  1 */
-
-/*
  * type for the third argument to mincore().
  */
 #define MINCORE_POINTER_TYPE unsigned char *
 
 /*
- * Do we have the sigaction flag SA_NOCLDWAIT?
- */
-#define HAVE_SA_NOCLDWAIT
-
-/*
  * The default path separator for the platform
  */
 #define OS_PATH_SEPARATOR '/'
diff --git a/core/combo/javac.mk b/core/combo/javac.mk
index 4248af0..7f91aa9 100644
--- a/core/combo/javac.mk
+++ b/core/combo/javac.mk
@@ -1,7 +1,7 @@
 # Selects a Java compiler.
 #
 # Inputs:
-#	CUSTOM_JAVA_COMPILER -- "eclipse", "openjdk". or nothing for the system 
+#	CUSTOM_JAVA_COMPILER -- "eclipse", "openjdk". or nothing for the system
 #                           default
 #	ALTERNATE_JAVAC -- the alternate java compiler to use
 #
@@ -22,6 +22,13 @@
 JAVACC := $(ALTERNATE_JAVAC)
 endif
 
+# The actual compiler can be wrapped by setting the JAVAC_WRAPPER var.
+ifdef JAVAC_WRAPPER
+    ifneq ($(JAVAC_WRAPPER),$(firstword $(JAVACC)))
+        JAVACC := $(JAVAC_WRAPPER) $(JAVACC)
+    endif
+endif
+
 # Whatever compiler is on this system.
 ifeq ($(BUILD_OS), windows)
     COMMON_JAVAC := development/host/windows/prebuilt/javawrap.exe -J-Xmx256m \
diff --git a/core/combo/mac_version.mk b/core/combo/mac_version.mk
new file mode 100644
index 0000000..b49feee
--- /dev/null
+++ b/core/combo/mac_version.mk
@@ -0,0 +1,50 @@
+# Detect Mac OS X and SDK versions.
+# Output variables:
+#   build_mac_version
+#   mac_sdk_version
+#   mac_sdk_root
+#   gcc_darwin_version
+
+ifndef build_mac_version
+
+build_mac_version := $(shell sw_vers -productVersion)
+
+mac_sdk_versions_supported :=  10.6 10.7 10.8
+ifneq ($(strip $(MAC_SDK_VERSION)),)
+mac_sdk_version := $(MAC_SDK_VERSION)
+ifeq ($(filter $(mac_sdk_version),$(mac_sdk_versions_supported)),)
+$(warning ****************************************************************)
+$(warning * MAC_SDK_VERSION $(MAC_SDK_VERSION) isn't one of the supported $(mac_sdk_versions_supported))
+$(warning ****************************************************************)
+$(error Stop.)
+endif
+else
+mac_sdk_versions_installed := $(shell xcodebuild -showsdks | grep macosx | sort | sed -e "s/.*macosx//g")
+mac_sdk_version := $(firstword $(filter $(mac_sdk_versions_installed), $(mac_sdk_versions_supported)))
+ifeq ($(mac_sdk_version),)
+mac_sdk_version := $(firstword $(mac_sdk_versions_supported))
+endif
+endif
+
+mac_sdk_path := $(shell xcode-select -print-path)
+# try /Applications/Xcode*.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.?.sdk
+#  or /Volume/Xcode/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.?.sdk
+mac_sdk_root := $(mac_sdk_path)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX$(mac_sdk_version).sdk
+ifeq ($(wildcard $(mac_sdk_root)),)
+# try legacy /Developer/SDKs/MacOSX10.?.sdk
+mac_sdk_root := /Developer/SDKs/MacOSX$(mac_sdk_version).sdk
+endif
+ifeq ($(wildcard $(mac_sdk_root)),)
+$(warning *****************************************************)
+$(warning * Can not find SDK $(mac_sdk_version) at $(mac_sdk_root))
+$(warning *****************************************************)
+$(error Stop.)
+endif
+
+ifeq ($(mac_sdk_version),10.6)
+  gcc_darwin_version := 10
+else
+  gcc_darwin_version := 11
+endif
+
+endif  # ifndef build_mac_version
diff --git a/core/combo/select.mk b/core/combo/select.mk
index c1a7cc0..e18cb1b 100644
--- a/core/combo/select.mk
+++ b/core/combo/select.mk
@@ -18,15 +18,11 @@
 #
 # Inputs:
 #	combo_target -- prefix for final variables (HOST_ or TARGET_)
-#	combo_2nd_arch_prefix -- it's defined if this is loaded for TARGET_2ND_ARCH.
+#	combo_2nd_arch_prefix -- it's defined if this is loaded for the 2nd arch.
 #
 
 # Build a target string like "linux-arm" or "darwin-x86".
-ifdef combo_2nd_arch_prefix
-combo_os_arch := $($(combo_target)OS)-$(TARGET_2ND_ARCH)
-else
-combo_os_arch := $($(combo_target)OS)-$($(combo_target)ARCH)
-endif
+combo_os_arch := $($(combo_target)OS)-$($(combo_target)$(combo_2nd_arch_prefix)ARCH)
 
 combo_var_prefix := $(combo_2nd_arch_prefix)$(combo_target)
 
@@ -90,19 +86,30 @@
   # If we are cross-compiling Windows binaries on Linux
   # then use the linux ccache binary instead.
   ifeq ($(HOST_OS)-$(BUILD_OS),windows-linux)
-    CCACHE_HOST_TAG := linux-$(BUILD_ARCH)
+    CCACHE_HOST_TAG := linux-$(HOST_PREBUILT_ARCH)
   endif
   ccache := prebuilts/misc/$(CCACHE_HOST_TAG)/ccache/ccache
   # Check that the executable is here.
   ccache := $(strip $(wildcard $(ccache)))
   ifdef ccache
-    # prepend ccache if necessary
-    ifneq ($(ccache),$(firstword $($(combo_var_prefix)CC)))
-      $(combo_var_prefix)CC := $(ccache) $($(combo_var_prefix)CC)
+    ifndef CC_WRAPPER
+      CC_WRAPPER := $(ccache)
     endif
-    ifneq ($(ccache),$(firstword $($(combo_var_prefix)CXX)))
-      $(combo_var_prefix)CXX := $(ccache) $($(combo_var_prefix)CXX)
+    ifndef CXX_WRAPPER
+      CXX_WRAPPER := $(ccache)
     endif
     ccache =
   endif
 endif
+
+# 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)))
+    $(combo_var_prefix)CC := $(CC_WRAPPER) $($(combo_var_prefix)CC)
+  endif
+endif
+ifdef CXX_WRAPPER
+  ifneq ($(CXX_WRAPPER),$(firstword $($(combo_var_prefix)CXX)))
+    $(combo_var_prefix)CXX := $(CXX_WRAPPER) $($(combo_var_prefix)CXX)
+  endif
+endif
diff --git a/core/config.mk b/core/config.mk
index 61f1d79..64dc68e 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -216,6 +216,13 @@
 combo_2nd_arch_prefix :=
 include $(BUILD_SYSTEM)/combo/select.mk
 
+# Load the 2nd host arch if it's needed.
+ifdef HOST_2ND_ARCH
+combo_target := HOST_
+combo_2nd_arch_prefix := $(HOST_2ND_ARCH_VAR_PREFIX)
+include $(BUILD_SYSTEM)/combo/select.mk
+endif
+
 # on windows, the tools have .exe at the end, and we depend on the
 # host config stuff being done first
 
@@ -247,7 +254,7 @@
 #
 # Note that this assumes that the 2ND_CPU_ABI for a 64 bit target
 # is always 32 bits. If this isn't the case, these variables should
-# be overriden in the boarc configuration.
+# be overriden in the board configuration.
 ifeq (,$(TARGET_CPU_ABI_LIST_64_BIT))
   ifeq (true|true,$(TARGET_IS_64_BIT)|$(TARGET_SUPPORTS_64_BIT_APPS))
     TARGET_CPU_ABI_LIST_64_BIT := $(TARGET_CPU_ABI) $(TARGET_CPU_ABI2)
@@ -350,15 +357,17 @@
 # ---------------------------------------------------------------
 # Generic tools.
 
-LEX := prebuilts/misc/$(BUILD_OS)-$(BUILD_ARCH)/flex/flex-2.5.39
+LEX := prebuilts/misc/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)/flex/flex-2.5.39
 # The default PKGDATADIR built in the prebuilt bison is a relative path
 # external/bison/data.
 # To run bison from elsewhere you need to set up enviromental variable
 # BISON_PKGDATADIR.
 BISON_PKGDATADIR := $(PWD)/external/bison/data
-BISON := prebuilts/misc/$(BUILD_OS)-$(BUILD_ARCH)/bison/bison
+BISON := prebuilts/misc/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)/bison/bison
 YACC := $(BISON) -d
 
+YASM := prebuilts/misc/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)/yasm/yasm
+
 DOXYGEN:= doxygen
 AAPT := $(HOST_OUT_EXECUTABLES)/aapt$(HOST_EXECUTABLE_SUFFIX)
 AIDL := $(HOST_OUT_EXECUTABLES)/aidl$(HOST_EXECUTABLE_SUFFIX)
@@ -377,6 +386,8 @@
 MKEXT2IMG := $(HOST_OUT_EXECUTABLES)/genext2fs$(HOST_EXECUTABLE_SUFFIX)
 MAKE_EXT4FS := $(HOST_OUT_EXECUTABLES)/make_ext4fs$(HOST_EXECUTABLE_SUFFIX)
 MKEXTUSERIMG := $(HOST_OUT_EXECUTABLES)/mkuserimg.sh
+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)
@@ -400,7 +411,8 @@
 # dx is java behind a shell script; no .exe necessary.
 DX := $(HOST_OUT_EXECUTABLES)/dx
 ZIPALIGN := $(HOST_OUT_EXECUTABLES)/zipalign$(HOST_EXECUTABLE_SUFFIX)
-FINDBUGS := prebuilt/common/findbugs/bin/findbugs
+FINDBUGS_DIR := external/owasp/sanitizer/tools/findbugs/bin
+FINDBUGS := $(FINDBUGS_DIR)/findbugs
 EMMA_JAR := external/emma/lib/emma$(COMMON_JAVA_PACKAGE_SUFFIX)
 
 # Tool to merge AndroidManifest.xmls
@@ -507,29 +519,39 @@
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CPPFLAGS += $($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_RELEASE_CPPFLAGS)
 endif
 
+ifdef HOST_2ND_ARCH
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CFLAGS += $(COMMON_GLOBAL_CFLAGS)
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_RELEASE_CFLAGS += $(COMMON_RELEASE_CFLAGS)
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CPPFLAGS += $(COMMON_GLOBAL_CPPFLAGS)
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_RELEASE_CPPFLAGS += $(COMMON_RELEASE_CPPFLAGS)
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LD_DIRS += -L$($(HOST_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_PROJECT_INCLUDES := $(HOST_PROJECT_INCLUDES)
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CFLAGS += $($(HOST_2ND_ARCH_VAR_PREFIX)HOST_RELEASE_CFLAGS)
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CPPFLAGS += $($(HOST_2ND_ARCH_VAR_PREFIX)HOST_RELEASE_CPPFLAGS)
+endif
+
 # allow overriding default Java libraries on a per-target basis
 ifeq ($(TARGET_DEFAULT_JAVA_LIBRARIES),)
-  TARGET_DEFAULT_JAVA_LIBRARIES := core core-junit ext framework framework2
+  TARGET_DEFAULT_JAVA_LIBRARIES := core-libart core-junit ext framework framework2
 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
-
-# If for a 64bit build we have a 2nd architecture but the zygote isn't 64bit,
-# assume DEX2OAT should DEXPREOPT for the 2nd architecture.
-ifdef TARGET_2ND_ARCH
-  ifeq (true,$(TARGET_IS_64_BIT))
-    ifeq ($(filter ro.zygote=zygote64,$(PRODUCT_DEFAULT_PROPERTY_OVERRIDES)),)
-      DEX2OAT_TARGET_ARCH := $(TARGET_2ND_ARCH)
-      DEX2OAT_TARGET_CPU_VARIANT := $(TARGET_2ND_CPU_VARIANT)
-    endif
-  endif
+ifneq (,$(filter $(DEX2OAT_TARGET_CPU_VARIANT),cortex-a7 cortex-a15 krait denver))
+  DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := div
 endif
 
-ifneq (,$(filter $(DEX2OAT_TARGET_CPU_VARIANT),cortex-a7 cortex-a15 krait))
-  DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := div
+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
@@ -569,6 +591,9 @@
 # This is the standard way to name a directory containing prebuilt target
 # objects. E.g., prebuilt/$(TARGET_PREBUILT_TAG)/libc.so
 TARGET_PREBUILT_TAG := android-$(TARGET_ARCH)
+ifdef TARGET_2ND_ARCH
+TARGET_2ND_PREBUILT_TAG := android-$(TARGET_2ND_ARCH)
+endif
 
 # Set up RS prebuilt variables for compatibility library
 
diff --git a/core/configure_module_stem.mk b/core/configure_module_stem.mk
index 2823e37..48b7787 100644
--- a/core/configure_module_stem.mk
+++ b/core/configure_module_stem.mk
@@ -1,16 +1,20 @@
-my_multilib_stem := $(LOCAL_MODULE_STEM_$(if $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_IS_64_BIT),64,32))
+my_multilib_stem := $(LOCAL_MODULE_STEM_$(if $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)IS_64_BIT),64,32))
 ifdef my_multilib_stem
-LOCAL_MODULE_STEM := $(my_multilib_stem)
+  my_module_stem := $(my_multilib_stem)
+else ifdef LOCAL_MODULE_STEM
+  my_module_stem := $(LOCAL_MODULE_STEM)
+else
+  my_module_stem := $(LOCAL_MODULE)
 endif
 
-ifndef LOCAL_MODULE_STEM
-  LOCAL_MODULE_STEM := $(LOCAL_MODULE)
+ifdef LOCAL_BUILT_MODULE_STEM
+  my_built_module_stem := $(LOCAL_BUILT_MODULE_STEM)
+else
+  my_built_module_stem := $(my_module_stem)$(LOCAL_MODULE_SUFFIX)
 endif
 
-ifndef LOCAL_BUILT_MODULE_STEM
-  LOCAL_BUILT_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
-endif
-
-ifndef LOCAL_INSTALLED_MODULE_STEM
-  LOCAL_INSTALLED_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
+ifdef LOCAL_INSTALLED_MODULE_STEM
+  my_installed_module_stem := $(LOCAL_INSTALLED_MODULE_STEM)
+else
+  my_installed_module_stem := $(my_module_stem)$(LOCAL_MODULE_SUFFIX)
 endif
diff --git a/core/definitions.mk b/core/definitions.mk
index 8f8aa4d..d7c68f3 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -84,8 +84,9 @@
 # Target and host installed module's dependencies on shared libraries.
 # They are list of "<module_name>:<installed_file>:lib1,lib2...".
 TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES :=
-2ND_TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES :=
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES :=
 HOST_DEPENDENCIES_ON_SHARED_LIBRARIES :=
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_DEPENDENCIES_ON_SHARED_LIBRARIES :=
 
 # Generated class file names for Android resource.
 # They are escaped and quoted so can be passed safely to a bash command.
@@ -423,10 +424,10 @@
     $(if $(_idfName),, \
         $(error $(LOCAL_PATH): Name not defined in call to intermediates-dir-for)) \
     $(eval _idfPrefix := $(if $(strip $(3)),HOST,TARGET)) \
-    $(eval _idf2ndArchPrefix := $(if $(call directory_is_64_bit_blacklisted,$(LOCAL_PATH))$(strip $(5)),$(TARGET_2ND_ARCH_VAR_PREFIX))) \
+    $(eval _idf2ndArchPrefix := $(if $(strip $(5)),$(TARGET_2ND_ARCH_VAR_PREFIX))) \
     $(if $(filter $(_idfPrefix)-$(_idfClass),$(COMMON_MODULE_CLASSES))$(4), \
         $(eval _idfIntBase := $($(_idfPrefix)_OUT_COMMON_INTERMEDIATES)) \
-      ,$(if $(filter $(_idfPrefix)-$(_idfClass),TARGET-SHARED_LIBRARIES TARGET-STATIC_LIBRARIES TARGET-EXECUTABLES TARGET-GYP),\
+      ,$(if $(filter $(_idfClass),SHARED_LIBRARIES STATIC_LIBRARIES EXECUTABLES GYP),\
           $(eval _idfIntBase := $($(_idf2ndArchPrefix)$(_idfPrefix)_OUT_INTERMEDIATES)) \
        ,$(eval _idfIntBase := $($(_idfPrefix)_OUT_INTERMEDIATES)) \
        ) \
@@ -902,7 +903,7 @@
   -a $@ -MD \
   -reflect-c++ \
   $(PRIVATE_RS_FLAGS) \
-  $(foreach inc,$(PRIVATE_RS_INCLUDES),$(addprefix -I , $(inc))) \
+  $(addprefix -I , $(PRIVATE_RS_INCLUDES)) \
   $(PRIVATE_RS_SOURCE_FILES)
 $(hide) mkdir -p $(dir $@)
 $(hide) touch $@
@@ -1038,6 +1039,16 @@
 $(transform-d-to-p)
 endef
 
+# YASM compilation
+define transform-asm-to-o
+@mkdir -p $(dir $@)
+$(hide) $(YASM) \
+    $(addprefix -I , $(PRIVATE_C_INCLUDES)) \
+    -f elf32 -m x86 \
+    $(PRIVATE_ASFLAGS) \
+    -o $@ $<
+endef
+
 ###########################################################
 ## Commands for running gcc to compile an Objective-C file
 ## This should never happen for target builds but this
@@ -1170,7 +1181,7 @@
     rm -rf $$ldir; \
     mkdir -p $$ldir; \
     filelist=; \
-    for f in `$(TARGET_AR) t $(1)`; do \
+    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"; \
     done ; \
@@ -1191,7 +1202,8 @@
 @rm -f $@
 $(extract-and-include-target-whole-static-libs)
 @echo "target StaticLib: $(PRIVATE_MODULE) ($@)"
-$(call split-long-arguments,$($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_AR) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_ARFLAGS) \
+$(call split-long-arguments,$($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_AR) \
+    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_ARFLAGS) \
     $(PRIVATE_ARFLAGS) $@,$(filter %.o, $^))
 endef
 
@@ -1206,11 +1218,12 @@
     rm -rf $$ldir; \
     mkdir -p $$ldir; \
     filelist=; \
-    for f in `$(HOST_AR) t $(1) | \grep '\.o$$'`; do \
-        $(HOST_AR) p $(1) $$f > $$ldir/$$f; \
+    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"; \
     done ; \
-    $(HOST_AR) $(HOST_GLOBAL_ARFLAGS) $(PRIVATE_ARFLAGS) $@ $$filelist
+    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_ARFLAGS) \
+        $(PRIVATE_ARFLAGS) $@ $$filelist
 
 endef
 
@@ -1226,7 +1239,9 @@
 @rm -f $@
 $(extract-and-include-host-whole-static-libs)
 @echo "host StaticLib: $(PRIVATE_MODULE) ($@)"
-$(call split-long-arguments,$(HOST_AR) $(HOST_GLOBAL_ARFLAGS) $(PRIVATE_ARFLAGS) $@,$(filter %.o, $^))
+$(call split-long-arguments,$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) \
+    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_ARFLAGS) \
+    $(PRIVATE_ARFLAGS) $@,$(filter %.o, $^))
 endef
 
 
@@ -1239,10 +1254,10 @@
 ifneq ($(HOST_CUSTOM_LD_COMMAND),true)
 define transform-host-o-to-shared-lib-inner
 $(hide) $(PRIVATE_CXX) \
-	-Wl,-rpath-link=$(HOST_OUT_INTERMEDIATE_LIBRARIES) \
-	-Wl,-rpath,\$$ORIGIN/../lib \
+	-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)) \
 	-shared -Wl,-soname,$(notdir $@) \
-	$(HOST_GLOBAL_LD_DIRS) \
+	$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LD_DIRS) \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	   $(PRIVATE_HOST_GLOBAL_LDFLAGS) \
 	) \
@@ -1412,9 +1427,9 @@
 	$(call normalize-host-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-Wl,-rpath-link=$(HOST_OUT_INTERMEDIATE_LIBRARIES) \
-	-Wl,-rpath,\$$ORIGIN/../lib \
-	$(HOST_GLOBAL_LD_DIRS) \
+	-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) \
@@ -1578,10 +1593,14 @@
     -name $(word 1, $(PRIVATE_JAR_EXCLUDE_FILES)) \
     $(addprefix -o -name , $(wordlist 2, 999, $(PRIVATE_JAR_EXCLUDE_FILES))) \
     | xargs rm -rf)
-$(if $(PRIVATE_JAR_PACKAGES), $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -mindepth 1 -type d \
-    $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
-        -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))) \
-    | xargs rm -rf)
+$(if $(PRIVATE_JAR_PACKAGES), \
+    $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -mindepth 1 -type f \
+        $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
+            -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))/\*) -delete ; \
+        find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -empty -delete)
+$(if $(PRIVATE_JAR_EXCLUDE_PACKAGES), $(hide) rm -rf \
+    $(foreach pkg, $(PRIVATE_JAR_EXCLUDE_PACKAGES), \
+        $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))))
 $(if $(PRIVATE_RMTYPEDEFS), $(hide) $(RMTYPEDEFS) -v $(PRIVATE_CLASS_INTERMEDIATES_DIR))
 $(if $(PRIVATE_JAR_MANIFEST), \
     $(hide) sed -e 's/%BUILD_NUMBER%/$(BUILD_NUMBER)/' \
@@ -1634,10 +1653,14 @@
     -name $(word 1, $(PRIVATE_JAR_EXCLUDE_FILES)) \
     $(addprefix -o -name , $(wordlist 2, 999, $(PRIVATE_JAR_EXCLUDE_FILES))) \
     | xargs rm -rf)
-$(if $(PRIVATE_JAR_PACKAGES), $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -mindepth 1 -type d \
-    $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
-        -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))) \
-    | xargs rm -rf)
+$(if $(PRIVATE_JAR_PACKAGES), \
+    $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -mindepth 1 -type f \
+        $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
+            -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))/\*) -delete ; \
+        find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -empty -delete)
+$(if $(PRIVATE_JAR_EXCLUDE_PACKAGES), $(hide) rm -rf \
+    $(foreach pkg, $(PRIVATE_JAR_EXCLUDE_PACKAGES), \
+        $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))))
 $(if $(PRIVATE_RMTYPEDEFS), $(hide) $(RMTYPEDEFS) -v $(PRIVATE_CLASS_INTERMEDIATES_DIR))
 $(if $(PRIVATE_JAR_MANIFEST), \
     $(hide) sed -e 's/%BUILD_NUMBER%/$(BUILD_NUMBER)/' \
@@ -1686,10 +1709,10 @@
 # so we need to give it something.
 define create-empty-package
 @mkdir -p $(dir $@)
-$(hide) touch $(dir $@)/dummy
+$(hide) touch $(dir $@)dummy
 $(hide) (cd $(dir $@) && jar cf $(notdir $@) dummy)
 $(hide) zip -qd $@ dummy
-$(hide) rm $(dir $@)/dummy
+$(hide) rm $(dir $@)dummy
 endef
 
 #TODO: we kinda want to build different asset packages for
@@ -1704,7 +1727,7 @@
 define add-assets-to-package
 $(hide) $(AAPT) package -u $(PRIVATE_AAPT_FLAGS) \
     $(addprefix -c , $(PRIVATE_PRODUCT_AAPT_CONFIG)) \
-    $(addprefix --preferred-configurations , $(PRIVATE_PRODUCT_AAPT_PREF_CONFIG)) \
+    $(addprefix --preferred-density , $(PRIVATE_PRODUCT_AAPT_PREF_CONFIG)) \
     $(addprefix -M , $(PRIVATE_ANDROID_MANIFEST)) \
     $(addprefix -S , $(PRIVATE_RESOURCE_DIR)) \
     $(addprefix -A , $(PRIVATE_ASSET_DIR)) \
@@ -1719,10 +1742,20 @@
     -F $@
 endef
 
+# We need the extra blank line, so that the command will be on a separate line.
+# $(1): the ABI name
+# $(2): the list of shared libraies
+define _add-jni-shared-libs-to-package-per-abi
+$(hide) cp $(2) $(dir $@)lib/$(1)
+
+endef
+
 define add-jni-shared-libs-to-package
 $(hide) rm -rf $(dir $@)lib
-$(hide) mkdir -p $(dir $@)lib/$(PRIVATE_JNI_SHARED_LIBRARIES_ABI)
-$(hide) cp $(PRIVATE_JNI_SHARED_LIBRARIES) $(dir $@)lib/$(PRIVATE_JNI_SHARED_LIBRARIES_ABI)
+$(hide) mkdir -p $(addprefix $(dir $@)lib/,$(PRIVATE_JNI_SHARED_LIBRARIES_ABI))
+$(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) rm -rf $(dir $@)lib
 endef
@@ -1978,8 +2011,8 @@
 endef
 
 # $(1): The file(s) to check (often $@)
-# $(2): The maximum total image size, in decimal bytes
-# $(3): the type of filesystem "yaffs" or "raw"
+# $(2): The maximum total image size, in decimal bytes.
+#    Make sure to take into account any reserved space needed for the FS.
 #
 # If $(2) is empty, evaluates to "true"
 #
@@ -1992,15 +2025,9 @@
   total=$$(( $$( echo "$$size" ) )); \
   printname=$$(echo -n "$(1)" | tr " " +); \
   img_blocksize=$(call image-size-from-data-size,$(BOARD_FLASH_BLOCK_SIZE)); \
-  if [ "$(3)" == "yaffs" ]; then \
-    reservedblocks=8; \
-  else \
-    reservedblocks=0; \
-  fi; \
   twoblocks=$$((img_blocksize * 2)); \
   onepct=$$((((($(2) / 100) - 1) / img_blocksize + 1) * img_blocksize)); \
-  reserve=$$(((twoblocks > onepct ? twoblocks : onepct) + \
-               reservedblocks * img_blocksize)); \
+  reserve=$$((twoblocks > onepct ? twoblocks : onepct)); \
   maxsize=$$(($(2) - reserve)); \
   echo "$$printname maxsize=$$maxsize blocksize=$$img_blocksize total=$$total reserve=$$reserve"; \
   if [ "$$total" -gt "$$maxsize" ]; then \
@@ -2022,8 +2049,7 @@
 # $(2): The partition size.
 define assert-max-image-size
 $(if $(2), \
-  $(call assert-max-file-size,$(1),$(call image-size-from-data-size,$(2))), \
-  true)
+  $(call assert-max-file-size,$(1),$(call image-size-from-data-size,$(2))))
 endef
 
 
@@ -2113,20 +2139,6 @@
 endef
 
 ###########################################################
-## Expand a module name list with REQUIRED modules
-###########################################################
-# $(1): The variable name that holds the initial module name list.
-#       the variable will be modified to hold the expanded results.
-# $(2): The initial module name list.
-# Returns empty string (maybe with some whitespaces).
-define expand-required-modules
-$(eval _erm_new_modules := $(sort $(filter-out $($(1)),\
-  $(foreach m,$(2),$(ALL_MODULES.$(m).REQUIRED)))))\
-$(if $(_erm_new_modules),$(eval $(1) += $(_erm_new_modules))\
-  $(call expand-required-modules,$(1),$(_erm_new_modules)))
-endef
-
-###########################################################
 ## API Check
 ###########################################################
 
diff --git a/core/dex_preopt.mk b/core/dex_preopt.mk
index 46a6479..ab970f9 100644
--- a/core/dex_preopt.mk
+++ b/core/dex_preopt.mk
@@ -49,25 +49,26 @@
 include $(BUILD_SYSTEM)/dex_preopt_libart.mk
 
 # Define dexpreopt-one-file based on current default runtime.
-# $(1): the boot image to use (unused for libdvm)
-# $(2): the input .jar or .apk file
-# $(3): the input .jar or .apk target location (unused for libdvm)
-# $(4): the output .odex file
+# $(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,$(2),$(4))
+$(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),$(3),$(4))
+$(call dex2oat-one-file,$(1),$(2))
 endef
 
 DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS := $(DEX2OATD_DEPENDENCY)
-DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT := $(DEFAULT_DEX_PREOPT_BUILT_IMAGE)
-endif
+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
diff --git a/core/dex_preopt_libart.mk b/core/dex_preopt_libart.mk
index 73e8494..411af75 100644
--- a/core/dex_preopt_libart.mk
+++ b/core/dex_preopt_libart.mk
@@ -6,37 +6,18 @@
 DEX2OAT := $(HOST_OUT_EXECUTABLES)/dex2oat$(HOST_EXECUTABLE_SUFFIX)
 DEX2OATD := $(HOST_OUT_EXECUTABLES)/dex2oatd$(HOST_EXECUTABLE_SUFFIX)
 
-LIBART_COMPILER := $(HOST_OUT_SHARED_LIBRARIES)/libart-compiler$(HOST_SHLIB_SUFFIX)
-LIBARTD_COMPILER := $(HOST_OUT_SHARED_LIBRARIES)/libartd-compiler$(HOST_SHLIB_SUFFIX)
-
 # By default, do not run rerun dex2oat if the tool changes.
 # Comment out the | to force dex2oat to rerun on after all changes.
 DEX2OAT_DEPENDENCY := art/runtime/oat.cc # dependency on oat version number
 DEX2OAT_DEPENDENCY += art/runtime/image.cc # dependency on image version number
 DEX2OAT_DEPENDENCY += |
 DEX2OAT_DEPENDENCY += $(DEX2OAT)
-DEX2OAT_DEPENDENCY += $(LIBART_COMPILER)
 
 DEX2OATD_DEPENDENCY := $(DEX2OAT_DEPENDENCY)
 DEX2OATD_DEPENDENCY += $(DEX2OATD)
-DEX2OATD_DEPENDENCY += $(LIBARTD_COMPILER)
 
 PRELOADED_CLASSES := frameworks/base/preloaded-classes
 
-LIBART_BOOT_IMAGE := /$(DEXPREOPT_BOOT_JAR_DIR)/boot.art
-
-DEFAULT_DEX_PREOPT_BUILT_IMAGE := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/boot.art
-
-DEFAULT_DEX_PREOPT_INSTALLED_IMAGE :=
-ifneq ($(PRODUCT_DEX_PREOPT_IMAGE_IN_DATA),true)
-DEFAULT_DEX_PREOPT_INSTALLED_IMAGE := $(PRODUCT_OUT)$(LIBART_BOOT_IMAGE)
-
-# The rule to install boot.art and boot.oat
-$(DEFAULT_DEX_PREOPT_INSTALLED_IMAGE) : $(DEFAULT_DEX_PREOPT_BUILT_IMAGE) | $(ACP)
-	$(call copy-file-to-target)
-	$(hide) $(ACP) -fp $(patsubst %.art,%.oat,$<) $(patsubst %.art,%.oat,$@)
-endif
-
 # start of image reserved address space
 LIBART_IMG_HOST_BASE_ADDRESS   := 0x60000000
 
@@ -49,48 +30,50 @@
 ########################################################################
 # The full system boot classpath
 
+# Returns the path to the .odex file
+# $(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
+endef
+
+# Returns the path to the image file (such as "/system/framework/<arch>/boot.art"
+# $(1): the arch name (such as "arm")
+# $(2): the image location (such as "/system/framework/boot.art")
+define get-image-file-path
+$(dir $(2))$(1)/$(notdir $(2))
+endef
+
 # note we use core-libart.jar in place of core.jar for ART.
 LIBART_TARGET_BOOT_JARS := $(patsubst core, core-libart,$(DEXPREOPT_BOOT_JARS_MODULES))
 LIBART_TARGET_BOOT_DEX_LOCATIONS := $(foreach jar,$(LIBART_TARGET_BOOT_JARS),/$(DEXPREOPT_BOOT_JAR_DIR)/$(jar).jar)
 LIBART_TARGET_BOOT_DEX_FILES := $(foreach jar,$(LIBART_TARGET_BOOT_JARS),$(call intermediates-dir-for,JAVA_LIBRARIES,$(jar),,COMMON)/javalib.jar)
 
-# The .oat with symbols
-LIBART_TARGET_BOOT_OAT_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)$(patsubst %.art,%.oat,$(LIBART_BOOT_IMAGE))
+my_2nd_arch_prefix :=
+include $(BUILD_SYSTEM)/dex_preopt_libart_boot.mk
 
-# Use dex2oat debug version for better error reporting
-$(DEFAULT_DEX_PREOPT_BUILT_IMAGE): $(LIBART_TARGET_BOOT_DEX_FILES) $(DEX2OATD_DEPENDENCY)
-	@echo "target dex2oat: $@ ($?)"
-	@mkdir -p $(dir $@)
-	@mkdir -p $(dir $(LIBART_TARGET_BOOT_OAT_UNSTRIPPED))
-	$(hide) $(DEX2OATD) --runtime-arg -Xms256m --runtime-arg -Xmx256m --image-classes=$(PRELOADED_CLASSES) \
-		$(addprefix --dex-file=,$(LIBART_TARGET_BOOT_DEX_FILES)) \
-		$(addprefix --dex-location=,$(LIBART_TARGET_BOOT_DEX_LOCATIONS)) \
-		--oat-symbols=$(LIBART_TARGET_BOOT_OAT_UNSTRIPPED) \
-		--oat-file=$(patsubst %.art,%.oat,$@) \
-		--oat-location=$(patsubst %.art,%.oat,$(LIBART_BOOT_IMAGE)) \
-		--image=$@ --base=$(LIBART_IMG_TARGET_BASE_ADDRESS) \
-		--instruction-set=$(DEX2OAT_TARGET_ARCH) \
-		--instruction-set-features=$(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) \
-		--android-root=$(PRODUCT_OUT)/system
+ifdef TARGET_2ND_ARCH
+my_2nd_arch_prefix := $(TARGET_2ND_ARCH_VAR_PREFIX)
+include $(BUILD_SYSTEM)/dex_preopt_libart_boot.mk
+my_2nd_arch_prefix :=
+endif
 
 
 ########################################################################
 # For a single jar or APK
 
-# $(1): the boot image to use
-# $(2): the input .jar or .apk file
-# $(3): the input .jar or .apk target location
-# $(4): the output .odex file
+# $(1): the input .jar or .apk file
+# $(2): the output .odex file
 define dex2oat-one-file
-$(hide) rm -f $(4)
-$(hide) mkdir -p $(dir $(4))
+$(hide) rm -f $(2)
+$(hide) mkdir -p $(dir $(2))
 $(hide) $(DEX2OATD) \
 	--runtime-arg -Xms64m --runtime-arg -Xmx64m \
-	--boot-image=$(1) \
-	--dex-file=$(2) \
-	--dex-location=$(3) \
-	--oat-file=$(4) \
+	--boot-image=$(PRIVATE_DEX_PREOPT_IMAGE_LOCATION) \
+	--dex-file=$(1) \
+	--dex-location=$(PRIVATE_DEX_LOCATION) \
+	--oat-file=$(2) \
 	--android-root=$(PRODUCT_OUT)/system \
-	--instruction-set=$(DEX2OAT_TARGET_ARCH) \
-	--instruction-set-features=$(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES)
+	--instruction-set=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH) \
+	--instruction-set-features=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES)
 endef
diff --git a/core/dex_preopt_libart_boot.mk b/core/dex_preopt_libart_boot.mk
new file mode 100644
index 0000000..70130b6
--- /dev/null
+++ b/core/dex_preopt_libart_boot.mk
@@ -0,0 +1,55 @@
+# Rules to build boot.art
+# Input variables:
+#   my_2nd_arch_prefix: indicates if this is to build for the 2nd arch.
+
+# The image "location" is a symbolic path that with multiarchitecture
+# support doesn't really exist on the device. Typically it is
+# /system/framework/boot.art and should be the same for all supported
+# architectures on the device. The concrete architecture specific
+# content actually ends up in a "filename" that contains an
+# architecture specific directory name such as arm, arm64, mips,
+# mips64, x86, x86_64.
+#
+# Here are some example values for an x86_64 / x86 configuration:
+#
+# DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION=out/target/product/generic_x86_64/dex_bootjars/system/framework/boot.art
+# DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME=out/target/product/generic_x86_64/dex_bootjars/system/framework/x86_64/boot.art
+# LIBART_BOOT_IMAGE=/system/framework/x86_64/boot.art
+#
+# 2ND_DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION=out/target/product/generic_x86_64/dex_bootjars/system/framework/boot.art
+# 2ND_DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME=out/target/product/generic_x86_64/dex_bootjars/system/framework/x86/boot.art
+# 2ND_LIBART_BOOT_IMAGE=/system/framework/x86/boot.art
+
+$(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/boot.art
+$(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME := $(DEXPREOPT_BOOT_JAR_DIR_FULL_PATH)/$($(my_2nd_arch_prefix)DEX2OAT_TARGET_ARCH)/boot.art
+$(my_2nd_arch_prefix)LIBART_BOOT_IMAGE_FILENAME := /$(DEXPREOPT_BOOT_JAR_DIR)/$($(my_2nd_arch_prefix)DEX2OAT_TARGET_ARCH)/boot.art
+
+# 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
+
+# The rule to install boot.art and boot.oat
+$($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_INSTALLED_IMAGE) : $($(my_2nd_arch_prefix)DEFAULT_DEX_PREOPT_BUILT_IMAGE_FILENAME) | $(ACP)
+	$(call copy-file-to-target)
+	$(hide) $(ACP) -fp $(patsubst %.art,%.oat,$<) $(patsubst %.art,%.oat,$@)
+
+$($(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)
+	@echo "target dex2oat: $@ ($?)"
+	@mkdir -p $(dir $@)
+	@mkdir -p $(dir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_TARGET_BOOT_OAT_UNSTRIPPED))
+	$(hide) $(DEX2OATD) --runtime-arg -Xms256m --runtime-arg -Xmx256m --image-classes=$(PRELOADED_CLASSES) \
+		$(addprefix --dex-file=,$(LIBART_TARGET_BOOT_DEX_FILES)) \
+		$(addprefix --dex-location=,$(LIBART_TARGET_BOOT_DEX_LOCATIONS)) \
+		--oat-symbols=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)LIBART_TARGET_BOOT_OAT_UNSTRIPPED) \
+		--oat-file=$(patsubst %.art,%.oat,$@) \
+		--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-features=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) \
+		--android-root=$(PRODUCT_OUT)/system
diff --git a/core/dex_preopt_odex_install.mk b/core/dex_preopt_odex_install.mk
index b0b73af..caaa16d 100644
--- a/core/dex_preopt_odex_install.mk
+++ b/core/dex_preopt_odex_install.mk
@@ -33,38 +33,107 @@
 
 built_odex :=
 installed_odex :=
+built_installed_odex :=
 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)
 
-ifneq ($(DALVIK_VM_LIB),libdvm.so) # libart
-ifndef LOCAL_DEX_PREOPT_IMAGE
-LOCAL_DEX_PREOPT_IMAGE := $(DEFAULT_DEX_PREOPT_BUILT_IMAGE)
+$(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.
+# #################################################
+# Odex for the 1st arch
+built_odex := $(call get-odex-file-path,$(DEX2OAT_TARGET_ARCH),$(LOCAL_BUILT_MODULE))
+ifdef LOCAL_DEX_PREOPT_IMAGE_LOCATION
+my_dex_preopt_image_location := $(LOCAL_DEX_PREOPT_IMAGE_LOCATION)
+else
+my_dex_preopt_image_location := $(DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION)
 endif
+my_dex_preopt_image_filename := $(call get-image-file-path,$(DEX2OAT_TARGET_ARCH),$(my_dex_preopt_image_location))
+$(built_odex): PRIVATE_2ND_ARCH_VAR_PREFIX :=
+$(built_odex): PRIVATE_DEX_LOCATION := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
+$(built_odex): PRIVATE_DEX_PREOPT_IMAGE_LOCATION := $(my_dex_preopt_image_location)
+$(built_odex) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT) \
+                $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS) \
+                $(my_dex_preopt_image_filename)
+installed_odex := $(call get-odex-file-path,$(DEX2OAT_TARGET_ARCH),$(LOCAL_INSTALLED_MODULE))
+built_installed_odex := $(built_odex):$(installed_odex)
+# #################################################
+# Odex for the 2nd arch
+ifdef TARGET_2ND_ARCH
+built_odex2 := $(call get-odex-file-path,$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH),$(LOCAL_BUILT_MODULE))
+ifdef LOCAL_DEX_PREOPT_IMAGE_LOCATION
+my_dex_preopt_image_location := $(LOCAL_DEX_PREOPT_IMAGE_LOCATION)
+else
+my_dex_preopt_image_location := $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION)
+endif
+my_dex_preopt_image_filename := $(call get-image-file-path,$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH),$(my_dex_preopt_image_location))
+$(built_odex2): PRIVATE_2ND_ARCH_VAR_PREFIX := $(TARGET_2ND_ARCH_VAR_PREFIX)
+$(built_odex2): PRIVATE_DEX_LOCATION := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
+$(built_odex2): PRIVATE_DEX_PREOPT_IMAGE_LOCATION := $(my_dex_preopt_image_location)
+$(built_odex2) : $($(TARGET_2ND_ARCH_VAR_PREFIX)DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT) \
+                 $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS) \
+                 $(my_dex_preopt_image_filename)
+
+installed_odex2 := $(call get-odex-file-path,$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH),$(LOCAL_INSTALLED_MODULE))
+built_odex += $(built_odex2)
+installed_odex += $(installed_odex2)
+built_installed_odex += $(built_odex2):$(installed_odex2)
+endif  # TARGET_2ND_ARCH
+# #################################################
+else  # must be APPS
+# For an app, we build for the multilib arch it's targeted for.
+built_odex := $(call get-odex-file-path,$($(LOCAL_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH),$(LOCAL_BUILT_MODULE))
+ifdef LOCAL_DEX_PREOPT_IMAGE_LOCATION
+my_dex_preopt_image_location := $(LOCAL_DEX_PREOPT_IMAGE_LOCATION)
+else
+my_dex_preopt_image_location := $($(LOCAL_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_BUILT_IMAGE_LOCATION)
+endif
+my_dex_preopt_image_filename := $(call get-image-file-path,$($(LOCAL_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH),$(my_dex_preopt_image_location))
+$(built_odex): PRIVATE_2ND_ARCH_VAR_PREFIX := $(LOCAL_2ND_ARCH_VAR_PREFIX)
+$(built_odex): PRIVATE_DEX_LOCATION := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
+$(built_odex): PRIVATE_DEX_PREOPT_IMAGE_LOCATION := $(my_dex_preopt_image_location)
+$(built_odex) : $($(LOCAL_2ND_ARCH_VAR_PREFIX)DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT) \
+                $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS) \
+                $(my_dex_preopt_image_filename)
+installed_odex := $(call get-odex-file-path,$($(LOCAL_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_ARCH),$(LOCAL_INSTALLED_MODULE))
+built_installed_odex := $(built_odex):$(installed_odex)
+endif  # LOCAL_MODULE_CLASS
 endif # libart
 endif # boot jar
 
 ifdef built_odex
-# We need $(LOCAL_BUILT_MODULE) in the deps to enforce reinstallation
-# even if $(built_odex) is byproduct of $(LOCAL_BUILT_MODULE), such as in package.mk.
-$(installed_odex) : $(built_odex) $(LOCAL_BUILT_MODULE) | $(ACP)
+# Use pattern rule - we may have multiple installed odex files.
+# Ugly syntax - See the definition get-odex-file-path.
+$(installed_odex) : $(dir $(LOCAL_INSTALLED_MODULE))%$(notdir $(word 1,$(installed_odex))) \
+                  : $(dir $(LOCAL_BUILT_MODULE))%$(notdir $(word 1,$(built_odex))) \
+    | $(ACP)
 	@echo "Install: $@"
 	$(copy-file-to-target)
 endif
 
 # Add the installed_odex to the list of installed files for this module.
-ALL_MODULES.$(LOCAL_MODULE).INSTALLED += $(installed_odex)
+ALL_MODULES.$(my_register_name).INSTALLED += $(installed_odex)
+ALL_MODULES.$(my_register_name).BUILT_INSTALLED += $(built_installed_odex)
+
 # Make sure to install the .odex when you run "make <module_name>"
 $(my_register_name): $(installed_odex)
 
diff --git a/core/droiddoc.mk b/core/droiddoc.mk
index 2a9cfc6..ea5c2f2 100644
--- a/core/droiddoc.mk
+++ b/core/droiddoc.mk
@@ -65,8 +65,8 @@
     $(full_target): PRIVATE_BOOTCLASSPATH := $(call java-lib-files, sdk_v$(LOCAL_SDK_VERSION))
   endif
 else
-  LOCAL_JAVA_LIBRARIES := core ext framework framework2 $(LOCAL_JAVA_LIBRARIES)
-  $(full_target): PRIVATE_BOOTCLASSPATH := $(call java-lib-files, core)
+  LOCAL_JAVA_LIBRARIES := core-libart ext framework framework2 $(LOCAL_JAVA_LIBRARIES)
+  $(full_target): PRIVATE_BOOTCLASSPATH := $(call java-lib-files, core-libart)
 endif  # LOCAL_SDK_VERSION
 LOCAL_JAVA_LIBRARIES := $(sort $(LOCAL_JAVA_LIBRARIES))
 
diff --git a/core/dumpvar.mk b/core/dumpvar.mk
index d3f3969..510bc7d 100644
--- a/core/dumpvar.mk
+++ b/core/dumpvar.mk
@@ -72,9 +72,11 @@
 $(info   TARGET_BUILD_TYPE=$(TARGET_BUILD_TYPE))
 $(info   TARGET_BUILD_APPS=$(TARGET_BUILD_APPS))
 $(info   TARGET_ARCH=$(TARGET_ARCH))
-$(info   TARGET_2ND_ARCH=$(TARGET_2ND_ARCH))
 $(info   TARGET_ARCH_VARIANT=$(TARGET_ARCH_VARIANT))
 $(info   TARGET_CPU_VARIANT=$(TARGET_CPU_VARIANT))
+$(info   TARGET_2ND_ARCH=$(TARGET_2ND_ARCH))
+$(info   TARGET_2ND_ARCH_VARIANT=$(TARGET_2ND_ARCH_VARIANT))
+$(info   TARGET_2ND_CPU_VARIANT=$(TARGET_2ND_CPU_VARIANT))
 $(info   HOST_ARCH=$(HOST_ARCH))
 $(info   HOST_OS=$(HOST_OS))
 $(info   HOST_OS_EXTRA=$(HOST_OS_EXTRA))
diff --git a/core/dynamic_binary.mk b/core/dynamic_binary.mk
index b3ca4fc..396199c 100644
--- a/core/dynamic_binary.mk
+++ b/core/dynamic_binary.mk
@@ -26,7 +26,7 @@
 # The basename of this target must be the same as the final output
 # binary name, because it's used to set the "soname" in the binary.
 # The includer of this file will define a rule to build this target.
-linked_module := $(guessed_intermediates)/LINKED/$(LOCAL_BUILT_MODULE_STEM)
+linked_module := $(guessed_intermediates)/LINKED/$(my_built_module_stem)
 
 ALL_ORIGINAL_DYNAMIC_BINARIES += $(linked_module)
 
@@ -41,8 +41,6 @@
 include $(BUILD_SYSTEM)/binary.mk
 ###################################
 
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_2ND_ARCH_VAR_PREFIX := $(LOCAL_2ND_ARCH_VAR_PREFIX)
-
 # Make sure that our guess at the value of intermediates was correct.
 ifneq ($(intermediates),$(guessed_intermediates))
 $(error Internal error: guessed path '$(guessed_intermediates)' doesn't match '$(intermediates))
@@ -59,7 +57,7 @@
 
 ifeq ($(LOCAL_COMPRESS_MODULE_SYMBOLS),true)
 $(error Symbol compression not yet supported.)
-compress_output := $(intermediates)/COMPRESSED-$(LOCAL_BUILT_MODULE_STEM)
+compress_output := $(intermediates)/COMPRESSED-$(my_built_module_stem)
 
 #TODO: write the real $(STRIPPER) rule.
 #TODO: define a rule to build TARGET_SYMBOL_FILTER_FILE, and
@@ -81,7 +79,7 @@
 my_unstripped_path := $(LOCAL_UNSTRIPPED_PATH)
 endif
 symbolic_input := $(compress_output)
-symbolic_output := $(my_unstripped_path)/$(LOCAL_INSTALLED_MODULE_STEM)
+symbolic_output := $(my_unstripped_path)/$(my_installed_module_stem)
 $(symbolic_output) : $(symbolic_input) | $(ACP)
 	@echo "target Symbolic: $(PRIVATE_MODULE) ($@)"
 	$(copy-file-to-target)
diff --git a/core/envsetup.mk b/core/envsetup.mk
index 88f35a6..7f77883 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -40,16 +40,16 @@
 
 # HOST_OS
 ifneq (,$(findstring Linux,$(UNAME)))
-	HOST_OS := linux
+  HOST_OS := linux
 endif
 ifneq (,$(findstring Darwin,$(UNAME)))
-	HOST_OS := darwin
+  HOST_OS := darwin
 endif
 ifneq (,$(findstring Macintosh,$(UNAME)))
-	HOST_OS := darwin
+  HOST_OS := darwin
 endif
 ifneq (,$(findstring CYGWIN,$(UNAME)))
-	HOST_OS := windows
+  HOST_OS := windows
 endif
 
 # BUILD_OS is the real host doing the build.
@@ -59,7 +59,7 @@
 # Windows SDK. Only a subset of tools and SDK will manage to build properly.
 ifeq ($(HOST_OS),linux)
 ifneq ($(USE_MINGW),)
-	HOST_OS := windows
+  HOST_OS := windows
 endif
 endif
 
@@ -67,17 +67,34 @@
 $(error Unable to determine HOST_OS from uname -sm: $(UNAME)!)
 endif
 
-
-# HOST_ARCH
-ifneq (,$(findstring 86,$(UNAME)))
-	HOST_ARCH := x86
+# 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
+ifeq ($(HOST_PREFER_32_BIT),true)
+BUILD_HOST_64bit := true
+endif
 endif
 
-ifneq (,$(findstring Power,$(UNAME)))
-	HOST_ARCH := ppc
+# HOST_ARCH
+ifneq (,$(findstring x86_64,$(UNAME)))
+  HOST_ARCH := x86_64
+  HOST_2ND_ARCH := x86
+else ifneq (,$(findstring 86,$(UNAME)))
+  # It's not officially supported!
+  HOST_ARCH := x86
+  HOST_2ND_ARCH :=
+endif
+
+ifeq ($(HOST_PREFER_32_BIT),true)
+SDK_HOST_ARCH := x86
+else
+SDK_HOST_ARCH := $(HOST_ARCH)
 endif
 
 BUILD_ARCH := $(HOST_ARCH)
+BUILD_2ND_ARCH := $(HOST_2ND_ARCH)
 
 ifeq ($(HOST_ARCH),)
 $(error Unable to determine HOST_ARCH from uname -sm: $(UNAME)!)
@@ -94,12 +111,14 @@
 endif
 endif
 
+# We don't want to move all the prebuilt host tools to a $(HOST_OS)-x86_64 dir.
+HOST_PREBUILT_ARCH := x86
 # This is the standard way to name a directory containing prebuilt host
 # objects. E.g., prebuilt/$(HOST_PREBUILT_TAG)/cc
 ifeq ($(HOST_OS),windows)
   HOST_PREBUILT_TAG := windows
 else
-  HOST_PREBUILT_TAG := $(HOST_OS)-$(HOST_ARCH)
+  HOST_PREBUILT_TAG := $(HOST_OS)-$(HOST_PREBUILT_ARCH)
 endif
 
 # TARGET_COPY_OUT_* are all relative to the staging directory, ie PRODUCT_OUT.
@@ -181,11 +200,12 @@
 HOST_OUT_ROOT_debug := $(DEBUG_OUT_DIR)/host
 HOST_OUT_ROOT := $(HOST_OUT_ROOT_$(HOST_BUILD_TYPE))
 
-HOST_OUT_release := $(HOST_OUT_ROOT_release)/$(HOST_OS)-$(HOST_ARCH)
-HOST_OUT_debug := $(HOST_OUT_ROOT_debug)/$(HOST_OS)-$(HOST_ARCH)
+# We want to avoid two host bin directories in multilib build.
+HOST_OUT_release := $(HOST_OUT_ROOT_release)/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
+HOST_OUT_debug := $(HOST_OUT_ROOT_debug)/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
 HOST_OUT := $(HOST_OUT_$(HOST_BUILD_TYPE))
 
-BUILD_OUT := $(OUT_DIR)/host/$(BUILD_OS)-$(BUILD_ARCH)
+BUILD_OUT := $(OUT_DIR)/host/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)
 
 TARGET_PRODUCT_OUT_ROOT := $(TARGET_OUT_ROOT)/product
 
@@ -213,6 +233,24 @@
 HOST_OUT_GEN := $(HOST_OUT)/gen
 HOST_OUT_COMMON_GEN := $(HOST_COMMON_OUT_ROOT)/gen
 
+# Out for HOST_2ND_ARCH
+HOST_2ND_ARCH_VAR_PREFIX := 2ND_
+HOST_2ND_ARCH_MODULE_SUFFIX := _32
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATES := $(HOST_OUT)/obj32
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES := $($(HOST_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATES)/lib
+ifeq ($(HOST_PREFER_32_BIT),true)
+# To keep path compatibility, put 32-bit libs in lib/ and 64-bit libs in lib64/.
+HOST_OUT_SHARED_LIBRARIES := $(HOST_OUT)/lib64
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES := $(HOST_OUT)/lib
+else
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES := $(HOST_OUT)/lib32
+endif
+$(HOST_2ND_ARCH_VAR_PREFIX)HOST_OUT_EXECUTABLES := $(HOST_OUT_EXECUTABLES)
+
+# The default host library path.
+# It always points to the path where we build libraries in the default bitness.
+HOST_LIBRARY_PATH := $(HOST_OUT)/lib
+
 TARGET_OUT_INTERMEDIATES := $(PRODUCT_OUT)/obj
 TARGET_OUT_HEADERS := $(TARGET_OUT_INTERMEDIATES)/include
 TARGET_OUT_INTERMEDIATE_LIBRARIES := $(TARGET_OUT_INTERMEDIATES)/lib
@@ -241,8 +279,8 @@
 TARGET_OUT_FAKE := $(PRODUCT_OUT)/fake_packages
 
 # Out for TARGET_2ND_ARCH
-TARGET_2ND_ARCH_VAR_PREFIX := 2ND_
-TARGET_2ND_ARCH_MODULE_SUFFIX := _32
+TARGET_2ND_ARCH_VAR_PREFIX := $(HOST_2ND_ARCH_VAR_PREFIX)
+TARGET_2ND_ARCH_MODULE_SUFFIX := $(HOST_2ND_ARCH_MODULE_SUFFIX)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATES := $(PRODUCT_OUT)/obj_$(TARGET_2ND_ARCH)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES := $($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATES)/lib
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_SHARED_LIBRARIES := $(TARGET_OUT)/lib
@@ -284,13 +322,21 @@
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_VENDOR_APPS := $(TARGET_OUT_VENDOR_APPS)
 
 TARGET_OUT_OEM := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_OEM)
-TARGET_OUT_OEM_EXECUTABLES:= $(TARGET_OUT_OEM)/bin
-TARGET_OUT_OEM_SHARED_LIBRARIES:= $(TARGET_OUT_OEM)/lib
+TARGET_OUT_OEM_EXECUTABLES := $(TARGET_OUT_OEM)/bin
+ifneq ($(filter %64,$(TARGET_ARCH)),)
+TARGET_OUT_OEM_SHARED_LIBRARIES := $(TARGET_OUT_OEM)/lib64
+else
+TARGET_OUT_OEM_SHARED_LIBRARIES := $(TARGET_OUT_OEM)/lib
+endif
 # We don't expect Java libraries in the oem.img.
 # TARGET_OUT_OEM_JAVA_LIBRARIES:= $(TARGET_OUT_OEM)/framework
-TARGET_OUT_OEM_APPS:= $(TARGET_OUT_OEM)/app
+TARGET_OUT_OEM_APPS := $(TARGET_OUT_OEM)/app
 TARGET_OUT_OEM_ETC := $(TARGET_OUT_OEM)/etc
 
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_OEM_EXECUTABLES := $(TARGET_OUT_OEM_EXECUTABLES)
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_OEM_SHARED_LIBRARIES := $(TARGET_OUT_OEM)/lib
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_OEM_APPS := $(TARGET_OUT_OEM_APPS)
+
 TARGET_OUT_UNSTRIPPED := $(PRODUCT_OUT)/symbols
 TARGET_OUT_EXECUTABLES_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)/system/bin
 TARGET_OUT_SHARED_LIBRARIES_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)/system/lib
diff --git a/core/executable.mk b/core/executable.mk
index 7a3e08e..4dd9a23 100644
--- a/core/executable.mk
+++ b/core/executable.mk
@@ -6,6 +6,7 @@
 # LOCAL_MODULE_PATH_32 and LOCAL_MODULE_PATH_64 or LOCAL_MODULE_STEM_32 and
 # LOCAL_MODULE_STEM_64
 
+my_prefix := TARGET_
 include $(BUILD_SYSTEM)/multilib.mk
 
 ifeq ($(my_module_multilib),both)
diff --git a/core/executable_internal.mk b/core/executable_internal.mk
index c235a72..2e380b6 100644
--- a/core/executable_internal.mk
+++ b/core/executable_internal.mk
@@ -30,6 +30,7 @@
 my_target_global_ld_dirs := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_LD_DIRS)
 my_target_fdo_lib := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_FDO_LIB)
 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)
 my_target_crtbegin_static_o := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_CRTBEGIN_STATIC_O)
 my_target_crtend_o := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_CRTEND_O)
@@ -49,6 +50,7 @@
 $(linked_module): PRIVATE_TARGET_GLOBAL_LDFLAGS := $(my_target_global_ldflags)
 $(linked_module): PRIVATE_TARGET_FDO_LIB := $(my_target_fdo_lib)
 $(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)
 $(linked_module): PRIVATE_TARGET_CRTBEGIN_STATIC_O := $(my_target_crtbegin_static_o)
 $(linked_module): PRIVATE_TARGET_CRTEND_O := $(my_target_crtend_o)
diff --git a/core/executable_prefer_symlink.mk b/core/executable_prefer_symlink.mk
new file mode 100644
index 0000000..fa49e40
--- /dev/null
+++ b/core/executable_prefer_symlink.mk
@@ -0,0 +1,44 @@
+# include this makefile to create the LOCAL_MODULE symlink to the primary version binary.
+# but this requires the primary version name specified via LOCAL_MODULE_STEM_32 or LOCAL_MODULE_STEM_64,
+# and different with the LOCAL_MODULE value
+#
+# Note: now only limited to the binaries that will be installed under system/bin directory
+
+my_symlink := $(addprefix $(TARGET_OUT)/bin/, $(LOCAL_MODULE))
+# Create link to the one used depending on the target
+# configuration. Note that we require the TARGET_IS_64_BIT
+# check because 32 bit targets may not define TARGET_PREFER_32_BIT_APPS
+# et al. since those variables make no sense in that context.
+ifeq ($(TARGET_IS_64_BIT),true)
+ifeq ($(TARGET_SUPPORTS_64_BIT_APPS)|$(TARGET_SUPPORTS_32_BIT_APPS),true|true)
+  # We support both 32 and 64 bit apps, so we will have to
+  # base our decision on whether the target prefers one or the
+  # other.
+  ifneq ($(TARGET_PREFER_32_BIT_APPS),true)
+    $(my_symlink): PRIVATE_SRC_BINARY_NAME := $(LOCAL_MODULE_STEM_32)
+  else
+    $(my_symlink): PRIVATE_SRC_BINARY_NAME := $(LOCAL_MODULE_STEM_64)
+  endif
+else ifeq ($(TARGET_SUPPORTS_64_BIT_APPS),true)
+  # We support only 64 bit apps.
+  $(my_symlink): PRIVATE_SRC_BINARY_NAME := $(LOCAL_MODULE_STEM_64)
+else
+  # We support only 32 bit apps.
+  $(my_symlink): PRIVATE_SRC_BINARY_NAME := $(LOCAL_MODULE_STEM_32)
+endif
+else
+  $(my_symlink): PRIVATE_SRC_BINARY_NAME := $(LOCAL_MODULE_STEM_32)
+endif
+
+
+$(my_symlink): $(LOCAL_INSTALLED_MODULE) $(LOCAL_MODULE_MAKEFILE)
+	@echo "Symlink: $@ -> $(PRIVATE_SRC_BINARY_NAME)"
+	@mkdir -p $(dir $@)
+	@rm -rf $@
+	$(hide) ln -sf $(PRIVATE_SRC_BINARY_NAME) $@
+
+# We need this so that the installed files could be picked up based on the
+# local module name
+ALL_MODULES.$(LOCAL_MODULE).INSTALLED += $(my_symlink)
+
+my_symlink :=
diff --git a/core/host_dalvik_java_library.mk b/core/host_dalvik_java_library.mk
index a79d64d..61eb3ff 100644
--- a/core/host_dalvik_java_library.mk
+++ b/core/host_dalvik_java_library.mk
@@ -27,7 +27,7 @@
 #######################################
 
 ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
-  LOCAL_JAVA_LIBRARIES +=  core-hostdex
+  LOCAL_JAVA_LIBRARIES +=  core-libart-hostdex
 endif
 
 full_classes_compiled_jar := $(intermediates.COMMON)/classes-full-debug.jar
@@ -67,6 +67,7 @@
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES :=
 $(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)
diff --git a/core/host_dalvik_static_java_library.mk b/core/host_dalvik_static_java_library.mk
index 05c4b16..3ae74e4 100644
--- a/core/host_dalvik_static_java_library.mk
+++ b/core/host_dalvik_static_java_library.mk
@@ -21,7 +21,7 @@
 #
 
 USE_CORE_LIB_BOOTCLASSPATH := true
-LOCAL_JAVA_LIBRARIES += core-hostdex
+LOCAL_JAVA_LIBRARIES += core-libart-hostdex
 
 include $(BUILD_SYSTEM)/host_java_library.mk
 
diff --git a/core/host_executable.mk b/core/host_executable.mk
index ffb35d2..bf3cde1 100644
--- a/core/host_executable.mk
+++ b/core/host_executable.mk
@@ -1,33 +1,50 @@
-###########################################################
-## Standard rules for building an executable file.
-##
-## Additional inputs from base_rules.make:
-## None.
-###########################################################
 
-LOCAL_IS_HOST_MODULE := true
-ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
-LOCAL_MODULE_CLASS := EXECUTABLES
+my_prefix := HOST_
+include $(BUILD_SYSTEM)/multilib.mk
+
+ifndef LOCAL_MODULE_HOST_ARCH
+ifndef my_module_multilib
+ifeq ($(HOST_PREFER_32_BIT),true)
+my_module_multilib := 32
+else
+# By default we only build host module for the first arch.
+my_module_multilib := first
 endif
-ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
-LOCAL_MODULE_SUFFIX := $(HOST_EXECUTABLE_SUFFIX)
-endif
-
-$(call host-executable-hook)
-
-skip_build_from_source :=
-ifdef LOCAL_PREBUILT_MODULE_FILE
-ifeq (,$(call if-build-from-source,$(LOCAL_MODULE),$(LOCAL_PATH)))
-include $(BUILD_SYSTEM)/prebuilt_internal.mk
-skip_build_from_source := true
 endif
 endif
 
-ifndef skip_build_from_source
+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))
+endif
+ifeq ($(LOCAL_MODULE_PATH_64)$(LOCAL_MODULE_STEM_64),)
+$(error $(LOCAL_PATH): LOCAL_MODULE_STEM_64 or LOCAL_MODULE_PATH_64 is required for LOCAL_MULTILIB := both for module $(LOCAL_MODULE))
+endif
+else #!LOCAL_MULTILIB == both
+LOCAL_NO_2ND_ARCH_MODULE_SUFFIX := true
+endif
 
-include $(BUILD_SYSTEM)/binary.mk
+LOCAL_2ND_ARCH_VAR_PREFIX :=
+include $(BUILD_SYSTEM)/module_arch_supported.mk
 
-$(LOCAL_BUILT_MODULE): $(all_objects) $(all_libraries)
-	$(transform-host-o-to-executable)
+ifeq ($(my_module_arch_supported),true)
+include $(BUILD_SYSTEM)/host_executable_internal.mk
+endif
 
-endif  # skip_build_from_source
+ifdef HOST_2ND_ARCH
+LOCAL_2ND_ARCH_VAR_PREFIX := $(HOST_2ND_ARCH_VAR_PREFIX)
+include $(BUILD_SYSTEM)/module_arch_supported.mk
+ifeq ($(my_module_arch_supported),true)
+# Build for HOST_2ND_ARCH
+OVERRIDE_BUILT_MODULE_PATH :=
+LOCAL_BUILT_MODULE :=
+LOCAL_INSTALLED_MODULE :=
+LOCAL_INTERMEDIATE_TARGETS :=
+
+include $(BUILD_SYSTEM)/host_executable_internal.mk
+endif
+LOCAL_2ND_ARCH_VAR_PREFIX :=
+endif  # HOST_2ND_ARCH
+
+LOCAL_NO_2ND_ARCH_MODULE_SUFFIX :=
+my_module_arch_supported :=
diff --git a/core/host_executable_internal.mk b/core/host_executable_internal.mk
new file mode 100644
index 0000000..ffb35d2
--- /dev/null
+++ b/core/host_executable_internal.mk
@@ -0,0 +1,33 @@
+###########################################################
+## Standard rules for building an executable file.
+##
+## Additional inputs from base_rules.make:
+## None.
+###########################################################
+
+LOCAL_IS_HOST_MODULE := true
+ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
+LOCAL_MODULE_CLASS := EXECUTABLES
+endif
+ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
+LOCAL_MODULE_SUFFIX := $(HOST_EXECUTABLE_SUFFIX)
+endif
+
+$(call host-executable-hook)
+
+skip_build_from_source :=
+ifdef LOCAL_PREBUILT_MODULE_FILE
+ifeq (,$(call if-build-from-source,$(LOCAL_MODULE),$(LOCAL_PATH)))
+include $(BUILD_SYSTEM)/prebuilt_internal.mk
+skip_build_from_source := true
+endif
+endif
+
+ifndef skip_build_from_source
+
+include $(BUILD_SYSTEM)/binary.mk
+
+$(LOCAL_BUILT_MODULE): $(all_objects) $(all_libraries)
+	$(transform-host-o-to-executable)
+
+endif  # skip_build_from_source
diff --git a/core/host_java_library.mk b/core/host_java_library.mk
index 2a8f18f..7e0e437 100644
--- a/core/host_java_library.mk
+++ b/core/host_java_library.mk
@@ -77,6 +77,7 @@
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES :=
 $(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)
diff --git a/core/host_shared_library.mk b/core/host_shared_library.mk
index 56ced01..438a9ce 100644
--- a/core/host_shared_library.mk
+++ b/core/host_shared_library.mk
@@ -1,49 +1,40 @@
-###########################################################
-## Standard rules for building a normal shared library.
-##
-## Additional inputs from base_rules.make:
-## None.
-##
-## LOCAL_MODULE_SUFFIX will be set for you.
-###########################################################
+my_prefix := HOST_
+include $(BUILD_SYSTEM)/multilib.mk
 
-LOCAL_IS_HOST_MODULE := true
-
-ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
-LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+ifndef LOCAL_MODULE_HOST_ARCH
+ifndef my_module_multilib
+ifeq ($(HOST_PREFER_32_BIT),true)
+my_module_multilib := 32
+else
+# By default we only build host module for the first arch.
+my_module_multilib := first
 endif
-ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
-LOCAL_MODULE_SUFFIX := $(HOST_SHLIB_SUFFIX)
-endif
-ifneq ($(strip $(OVERRIDE_BUILT_MODULE_PATH)),)
-$(error $(LOCAL_PATH): Illegal use of OVERRIDE_BUILT_MODULE_PATH)
-endif
-ifneq ($(strip $(LOCAL_MODULE_STEM)$(LOCAL_BUILT_MODULE_STEM)),)
-$(error $(LOCAL_PATH): Cannot set module stem for a library)
-endif
-
-$(call host-shared-library-hook)
-
-skip_build_from_source :=
-ifdef LOCAL_PREBUILT_MODULE_FILE
-ifeq (,$(call if-build-from-source,$(LOCAL_MODULE),$(LOCAL_PATH)))
-include $(BUILD_SYSTEM)/prebuilt_internal.mk
-skip_build_from_source := true
 endif
 endif
 
-ifndef skip_build_from_source
+LOCAL_2ND_ARCH_VAR_PREFIX :=
+include $(BUILD_SYSTEM)/module_arch_supported.mk
 
-# Put the built modules of all shared libraries in a common directory
-# to simplify the link line.
-OVERRIDE_BUILT_MODULE_PATH := $(HOST_OUT_INTERMEDIATE_LIBRARIES)
+ifeq ($(my_module_arch_supported),true)
+include $(BUILD_SYSTEM)/host_shared_library_internal.mk
+endif
 
-include $(BUILD_SYSTEM)/binary.mk
+ifdef HOST_2ND_ARCH
+LOCAL_2ND_ARCH_VAR_PREFIX := $(HOST_2ND_ARCH_VAR_PREFIX)
+include $(BUILD_SYSTEM)/module_arch_supported.mk
+ifeq ($(my_module_arch_supported),true)
+# Build for HOST_2ND_ARCH
+OVERRIDE_BUILT_MODULE_PATH :=
+LOCAL_BUILT_MODULE :=
+LOCAL_INSTALLED_MODULE :=
+LOCAL_INTERMEDIATE_TARGETS :=
 
-$(LOCAL_BUILT_MODULE): $(all_objects) $(all_libraries) $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(transform-host-o-to-shared-lib)
+include $(BUILD_SYSTEM)/host_shared_library_internal.mk
+endif
+LOCAL_2ND_ARCH_VAR_PREFIX :=
+endif  # HOST_2ND_ARCH
 
-endif  # skip_build_from_source
+my_module_arch_supported :=
 
 ###########################################################
 ## Copy headers to the install tree
diff --git a/core/host_shared_library_internal.mk b/core/host_shared_library_internal.mk
new file mode 100644
index 0000000..d9769d3
--- /dev/null
+++ b/core/host_shared_library_internal.mk
@@ -0,0 +1,46 @@
+###########################################################
+## Standard rules for building a normal shared library.
+##
+## Additional inputs from base_rules.make:
+## None.
+##
+## LOCAL_MODULE_SUFFIX will be set for you.
+###########################################################
+
+LOCAL_IS_HOST_MODULE := true
+
+ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
+LOCAL_MODULE_CLASS := SHARED_LIBRARIES
+endif
+ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
+LOCAL_MODULE_SUFFIX := $(HOST_SHLIB_SUFFIX)
+endif
+ifneq ($(strip $(OVERRIDE_BUILT_MODULE_PATH)),)
+$(error $(LOCAL_PATH): Illegal use of OVERRIDE_BUILT_MODULE_PATH)
+endif
+ifneq ($(strip $(LOCAL_MODULE_STEM)$(LOCAL_BUILT_MODULE_STEM)),)
+$(error $(LOCAL_PATH): Cannot set module stem for a library)
+endif
+
+$(call host-shared-library-hook)
+
+skip_build_from_source :=
+ifdef LOCAL_PREBUILT_MODULE_FILE
+ifeq (,$(call if-build-from-source,$(LOCAL_MODULE),$(LOCAL_PATH)))
+include $(BUILD_SYSTEM)/prebuilt_internal.mk
+skip_build_from_source := true
+endif
+endif
+
+ifndef skip_build_from_source
+
+# Put the built modules of all shared libraries in a common directory
+# to simplify the link line.
+OVERRIDE_BUILT_MODULE_PATH := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)
+
+include $(BUILD_SYSTEM)/binary.mk
+
+$(LOCAL_BUILT_MODULE): $(all_objects) $(all_libraries) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+	$(transform-host-o-to-shared-lib)
+
+endif  # skip_build_from_source
diff --git a/core/host_static_library.mk b/core/host_static_library.mk
index 7d9b375..74ac2ea 100644
--- a/core/host_static_library.mk
+++ b/core/host_static_library.mk
@@ -1,30 +1,40 @@
-###########################################################
-## Standard rules for building a static library for the host.
-##
-## Additional inputs from base_rules.make:
-## None.
-##
-## LOCAL_MODULE_SUFFIX will be set for you.
-###########################################################
+my_prefix := HOST_
+include $(BUILD_SYSTEM)/multilib.mk
 
-ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
+ifndef LOCAL_MODULE_HOST_ARCH
+ifndef my_module_multilib
+ifeq ($(HOST_PREFER_32_BIT),true)
+my_module_multilib := 32
+else
+# By default we only build host module for the first arch.
+my_module_multilib := first
 endif
-ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
-LOCAL_MODULE_SUFFIX := .a
 endif
-ifneq ($(strip $(LOCAL_MODULE_STEM)$(LOCAL_BUILT_MODULE_STEM)),)
-$(error $(LOCAL_PATH): Cannot set module stem for a library)
 endif
-LOCAL_UNINSTALLABLE_MODULE := true
 
-LOCAL_IS_HOST_MODULE := true
+LOCAL_2ND_ARCH_VAR_PREFIX :=
+include $(BUILD_SYSTEM)/module_arch_supported.mk
 
-include $(BUILD_SYSTEM)/binary.mk
+ifeq ($(my_module_arch_supported),true)
+include $(BUILD_SYSTEM)/host_static_library_internal.mk
+endif
 
-$(LOCAL_BUILT_MODULE): $(built_whole_libraries)
-$(LOCAL_BUILT_MODULE): $(all_objects)
-	$(transform-host-o-to-static-lib)
+ifdef HOST_2ND_ARCH
+LOCAL_2ND_ARCH_VAR_PREFIX := $(HOST_2ND_ARCH_VAR_PREFIX)
+include $(BUILD_SYSTEM)/module_arch_supported.mk
+ifeq ($(my_module_arch_supported),true)
+# Build for HOST_2ND_ARCH
+OVERRIDE_BUILT_MODULE_PATH :=
+LOCAL_BUILT_MODULE :=
+LOCAL_INSTALLED_MODULE :=
+LOCAL_INTERMEDIATE_TARGETS :=
+
+include $(BUILD_SYSTEM)/host_static_library_internal.mk
+endif
+LOCAL_2ND_ARCH_VAR_PREFIX :=
+endif  # HOST_2ND_ARCH
+
+my_module_arch_supported :=
 
 ###########################################################
 ## Copy headers to the install tree
diff --git a/core/host_static_library_internal.mk b/core/host_static_library_internal.mk
new file mode 100644
index 0000000..a533cf5
--- /dev/null
+++ b/core/host_static_library_internal.mk
@@ -0,0 +1,27 @@
+###########################################################
+## Standard rules for building a static library for the host.
+##
+## Additional inputs from base_rules.make:
+## None.
+##
+## LOCAL_MODULE_SUFFIX will be set for you.
+###########################################################
+
+ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
+LOCAL_MODULE_CLASS := STATIC_LIBRARIES
+endif
+ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
+LOCAL_MODULE_SUFFIX := .a
+endif
+ifneq ($(strip $(LOCAL_MODULE_STEM)$(LOCAL_BUILT_MODULE_STEM)),)
+$(error $(LOCAL_PATH): Cannot set module stem for a library)
+endif
+LOCAL_UNINSTALLABLE_MODULE := true
+
+LOCAL_IS_HOST_MODULE := true
+
+include $(BUILD_SYSTEM)/binary.mk
+
+$(LOCAL_BUILT_MODULE): $(built_whole_libraries)
+$(LOCAL_BUILT_MODULE): $(all_objects)
+	$(transform-host-o-to-static-lib)
diff --git a/core/host_test_internal.mk b/core/host_test_internal.mk
index 650b9c6..426c400 100644
--- a/core/host_test_internal.mk
+++ b/core/host_test_internal.mk
@@ -5,7 +5,11 @@
 LOCAL_CFLAGS += -DGTEST_OS_LINUX -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
 
 LOCAL_LDLIBS += -lpthread
diff --git a/core/install_jni_libs.mk b/core/install_jni_libs.mk
index b9e70b1..918a839 100644
--- a/core/install_jni_libs.mk
+++ b/core/install_jni_libs.mk
@@ -1,28 +1,16 @@
 # Decides how to install the jni libraries needed by an apk.
 # Input variables:
-#   LOCAL_JNI_SHARED_LIBRARIES
-#   LOCAL_INSTALLED_MODULE
+#   my_module_multilib, LOCAL_2ND_ARCH_VAR_PREFIX (from package.mk or prebuilt.mk)
 #   rs_compatibility_jni_libs (from java.mk)
 #   my_module_path (from base_rules.mk)
 #   partition_tag (from base_rules.mk)
 #   my_prebuilt_src_file (from prebuilt_internal.mk)
 #
 # Output variables:
-#   jni_shared_libraries, jni_shared_libraries_abi, if we are going to embed the libraries into the apk;
-#   my_extracted_jni_libs, if we extract jni libs from prebuilt apk.
+#   jni_shared_libraries, jni_shared_libraries_abi, jni_shared_libraries_with_abis if we are going to embed the libraries into the apk;
+#   extracted_jni_libs, if we extract jni libs from prebuilt apk.
 #
 
-jni_shared_libraries := \
-    $(addprefix $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)/, \
-      $(addsuffix .so, \
-          $(LOCAL_JNI_SHARED_LIBRARIES)))
-
-# Include RS dynamically-generated libraries as well
-# Keep this ifneq, as the += otherwise adds spaces that need to be stripped.
-ifneq ($(rs_compatibility_jni_libs),)
-jni_shared_libraries += $(rs_compatibility_jni_libs)
-endif
-
 my_embed_jni :=
 ifneq ($(TARGET_BUILD_APPS),)
 my_embed_jni := true
@@ -35,87 +23,69 @@
 my_embed_jni := true
 endif
 
-# App-specific lib path.
-my_app_lib_path :=  $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET$(partition_tag)_OUT_SHARED_LIBRARIES)/$(basename $(LOCAL_INSTALLED_MODULE_STEM))
-my_extracted_jni_libs :=
+jni_shared_libraries :=
+jni_shared_libraries_abis :=
+# jni_shared_libraries_with_abis is a list of <abi>:<path-to-the-built-jni-lib>
+jni_shared_libraries_with_abis :=
+extracted_jni_libs :=
 
-ifdef my_embed_jni
-# App explicitly requires the prebuilt NDK stl shared libraies.
-# The NDK stl shared libraries should never go to the system image.
-ifneq ($(filter $(LOCAL_NDK_STL_VARIANT), stlport_shared c++_shared),)
-ifndef LOCAL_SDK_VERSION
-$(error LOCAL_SDK_VERSION must be defined with LOCAL_NDK_STL_VARIANT, \
-    LOCAL_PACKAGE_NAME=$(LOCAL_PACKAGE_NAME))
+#######################################
+# For TARGET_ARCH
+my_2nd_arch_prefix :=
+my_add_jni :=
+# The module is built for TARGET_ARCH
+ifeq ($(my_2nd_arch_prefix),$(LOCAL_2ND_ARCH_VAR_PREFIX))
+my_add_jni := true
 endif
+# Or it explicitly requires both
+ifeq ($(my_module_multilib),both)
+my_add_jni := true
 endif
-ifeq (stlport_shared,$(LOCAL_NDK_STL_VARIANT))
-jni_shared_libraries += \
-    $(HISTORICAL_NDK_VERSIONS_ROOT)/current/sources/cxx-stl/stlport/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/libstlport_shared.so
-else ifeq (c++_shared,$(LOCAL_NDK_STL_VARIANT))
-jni_shared_libraries += \
-    $(HISTORICAL_NDK_VERSIONS_ROOT)/current/sources/cxx-stl/llvm-libc++/libs/$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)/libc++_shared.so
+ifeq ($(my_add_jni),true)
+my_prebuilt_jni_libs := $(LOCAL_PREBUILT_JNI_LIBS_$(TARGET_ARCH))
+ifndef my_prebuilt_jni_libs
+my_prebuilt_jni_libs := $(LOCAL_PREBUILT_JNI_LIBS)
 endif
+include $(BUILD_SYSTEM)/install_jni_libs_internal.mk
+jni_shared_libraries += $(my_jni_shared_libraries)
+jni_shared_libraries_abis += $(my_jni_shared_libraries_abi)
+jni_shared_libraries_with_abis += $(addprefix $(my_jni_shared_libraries_abi):,\
+    $(my_jni_shared_libraries))
+extracted_jni_libs += $(my_extracted_jni_libs)
 
-# Set the abi directory used by the local JNI shared libraries.
-# (Doesn't change how the local shared libraries are compiled, just
-# sets where they are stored in the apk.)
-ifeq ($(LOCAL_JNI_SHARED_LIBRARIES_ABI),)
-    jni_shared_libraries_abi := $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)CPU_ABI)
-else
-    jni_shared_libraries_abi := $(LOCAL_JNI_SHARED_LIBRARIES_ABI)
-endif
+# Include RS dynamically-generated libraries as well
+# TODO: Add multilib support once RS supports generating multilib libraries.
+jni_shared_libraries += $(rs_compatibility_jni_libs)
+endif  # my_add_jni
 
-else  # not my_embed_jni
+#######################################
+# For TARGET_2ND_ARCH
+ifdef TARGET_2ND_ARCH
+my_2nd_arch_prefix := $(TARGET_2ND_ARCH_VAR_PREFIX)
+my_add_jni :=
+# The module is built for TARGET_2ND_ARCH
+ifeq ($(my_2nd_arch_prefix),$(LOCAL_2ND_ARCH_VAR_PREFIX))
+my_add_jni := true
+endif
+# Or it explicitly requires both
+ifeq ($(my_module_multilib),both)
+my_add_jni := true
+endif
+ifeq ($(my_add_jni),true)
+my_prebuilt_jni_libs := $(LOCAL_PREBUILT_JNI_LIBS_$(TARGET_2ND_ARCH))
+ifndef my_prebuilt_jni_libs
+my_prebuilt_jni_libs := $(LOCAL_PREBUILT_JNI_LIBS)
+endif
+include $(BUILD_SYSTEM)/install_jni_libs_internal.mk
+jni_shared_libraries += $(my_jni_shared_libraries)
+jni_shared_libraries_abis += $(my_jni_shared_libraries_abi)
+jni_shared_libraries_with_abis += $(addprefix $(my_jni_shared_libraries_abi):,\
+    $(my_jni_shared_libraries))
+extracted_jni_libs += $(my_extracted_jni_libs)
+endif  # my_add_jni
+endif  # TARGET_2ND_ARCH
 
 jni_shared_libraries := $(strip $(jni_shared_libraries))
-ifneq ($(jni_shared_libraries),)
-# The jni libaries will be installed to the system.img.
-my_jni_filenames := $(notdir $(jni_shared_libraries))
-# Make sure the JNI libraries get installed
-$(LOCAL_INSTALLED_MODULE) : | $(addprefix $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET$(partition_tag)_OUT_SHARED_LIBRARIES)/, $(my_jni_filenames))
-
-# Create symlink in the app specific lib path
-ifdef LOCAL_POST_INSTALL_CMD
-my_leading_separator := ;
-else
-my_leading_separator :=
-endif
-$(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD += \
-  $(my_leading_separator)mkdir -p $(my_app_lib_path) \
-  $(foreach lib, $(my_jni_filenames), ;ln -sf ../$(lib) $(my_app_lib_path)/$(lib))
-
-# Clear jni_shared_libraries to not embed it into the apk.
-jni_shared_libraries :=
-endif  # $(jni_shared_libraries) not empty
-endif  # my_embed_jni
-
-ifdef LOCAL_PREBUILT_JNI_LIBS
-# Install prebuilt JNI libs to the app specific lib path.
-# Files like @path/to/libfoo.so (path inside the apk) are JNI libs extracted from the prebuilt apk;
-# Files like path/to/libfoo.so (path relative to LOCAL_PATH) are prebuilts in the source tree.
-my_extracted_jni_libs := $(patsubst @%,%, \
-    $(filter @%, $(LOCAL_PREBUILT_JNI_LIBS)))
-ifdef my_extracted_jni_libs
-ifndef my_prebuilt_src_file
-$(error No prebuilt apk to extract prebuilt jni libraries $(my_extracted_jni_libs))
-endif
-# We use the first jni lib file as dependency.
-my_installed_prebuilt_jni := $(my_app_lib_path)/$(notdir $(firstword $(my_extracted_jni_libs)))
-$(my_installed_prebuilt_jni): PRIVATE_JNI_LIBS := $(my_extracted_jni_libs)
-$(my_installed_prebuilt_jni): $(my_prebuilt_src_file)
-	@echo "Extract JNI libs ($@ <- $<)"
-	@mkdir -p $(dir $@)
-	$(hide) unzip -j -o -d $(dir $@) $< $(PRIVATE_JNI_LIBS) && touch $@
-
-$(LOCAL_INSTALLED_MODULE) : | $(my_installed_prebuilt_jni)
-endif
-
-my_prebulit_jni_libs := $(addprefix $(LOCAL_PATH)/, \
-    $(filter-out @%, $(LOCAL_PREBUILT_JNI_LIBS)))
-ifdef my_prebulit_jni_libs
-$(foreach lib, $(my_prebulit_jni_libs), \
-    $(eval $(call copy-one-file, $(lib), $(my_app_lib_path)/$(notdir $(lib)))))
-
-$(LOCAL_INSTALLED_MODULE) : | $(addprefix $(my_app_lib_path)/, $(notdir $(my_prebulit_jni_libs)))
-endif
-endif  # LOCAL_PREBULT_JNI_LIBS
+jni_shared_libraries_abis := $(sort $(jni_shared_libraries_abis))
+jni_shared_libraries_with_abis := $(strip $(jni_shared_libraries_with_abis))
+extracted_jni_libs := $(strip $(extracted_jni_libs))
diff --git a/core/install_jni_libs_internal.mk b/core/install_jni_libs_internal.mk
new file mode 100644
index 0000000..b50c21e
--- /dev/null
+++ b/core/install_jni_libs_internal.mk
@@ -0,0 +1,104 @@
+# Install jni libraries for one arch.
+# Input variables:
+#   my_2nd_arch_prefix: indicate if this is for TARGET_2ND_ARCH.
+#   my_embed_jni: indicate if we want to embed the jni libs in the apk.
+#   my_prebuilt_jni_libs
+#   my_installed_module_stem (from configure_module_stem.mk)
+#   partition_tag (from base_rules.mk)
+#   my_prebuilt_src_file (from prebuilt_internal.mk)
+#
+# Output variables:
+#   my_jni_shared_libraries, my_jni_shared_libraries_abi, if we are going to embed the libraries into the apk;
+#   my_extracted_jni_libs, if we extract jni libs from prebuilt apk.
+#
+
+my_jni_shared_libraries := \
+    $(addprefix $($(my_2nd_arch_prefix)TARGET_OUT_INTERMEDIATE_LIBRARIES)/, \
+      $(addsuffix .so, \
+          $(LOCAL_JNI_SHARED_LIBRARIES)))
+
+# App-specific lib path.
+my_app_lib_path :=  $($(my_2nd_arch_prefix)TARGET$(partition_tag)_OUT_SHARED_LIBRARIES)/$(basename $(my_installed_module_stem))
+my_extracted_jni_libs :=
+
+ifdef my_embed_jni
+# App explicitly requires the prebuilt NDK stl shared libraies.
+# The NDK stl shared libraries should never go to the system image.
+ifneq ($(filter $(LOCAL_NDK_STL_VARIANT), stlport_shared c++_shared),)
+ifndef LOCAL_SDK_VERSION
+$(error LOCAL_SDK_VERSION must be defined with LOCAL_NDK_STL_VARIANT, \
+    LOCAL_PACKAGE_NAME=$(LOCAL_PACKAGE_NAME))
+endif
+endif
+ifeq (stlport_shared,$(LOCAL_NDK_STL_VARIANT))
+my_jni_shared_libraries += \
+    $(HISTORICAL_NDK_VERSIONS_ROOT)/current/sources/cxx-stl/stlport/libs/$(TARGET_$(my_2nd_arch_prefix)CPU_ABI)/libstlport_shared.so
+else ifeq (c++_shared,$(LOCAL_NDK_STL_VARIANT))
+my_jni_shared_libraries += \
+    $(HISTORICAL_NDK_VERSIONS_ROOT)/current/sources/cxx-stl/llvm-libc++/libs/$(TARGET_$(my_2nd_arch_prefix)CPU_ABI)/libc++_shared.so
+endif
+
+# Set the abi directory used by the local JNI shared libraries.
+# (Doesn't change how the local shared libraries are compiled, just
+# sets where they are stored in the apk.)
+ifeq ($(LOCAL_JNI_SHARED_LIBRARIES_ABI),)
+    my_jni_shared_libraries_abi := $(TARGET_$(my_2nd_arch_prefix)CPU_ABI)
+else
+    my_jni_shared_libraries_abi := $(LOCAL_JNI_SHARED_LIBRARIES_ABI)
+endif
+
+else  # not my_embed_jni
+
+my_jni_shared_libraries := $(strip $(my_jni_shared_libraries))
+ifneq ($(my_jni_shared_libraries),)
+# The jni libaries will be installed to the system.img.
+my_jni_filenames := $(notdir $(my_jni_shared_libraries))
+# Make sure the JNI libraries get installed
+$(LOCAL_INSTALLED_MODULE) : | $(addprefix $($(my_2nd_arch_prefix)TARGET$(partition_tag)_OUT_SHARED_LIBRARIES)/, $(my_jni_filenames))
+
+# Create symlink in the app specific lib path
+ifdef LOCAL_POST_INSTALL_CMD
+# Add a shell command separator
+LOCAL_POST_INSTALL_CMD += ;
+endif
+LOCAL_POST_INSTALL_CMD += \
+  mkdir -p $(my_app_lib_path) \
+  $(foreach lib, $(my_jni_filenames), ;ln -sf ../$(lib) $(my_app_lib_path)/$(lib))
+$(LOCAL_INSTALLED_MODULE): PRIVATE_POST_INSTALL_CMD := $(LOCAL_POST_INSTALL_CMD)
+
+# Clear jni_shared_libraries to not embed it into the apk.
+my_jni_shared_libraries :=
+endif  # $(my_jni_shared_libraries) not empty
+endif  # my_embed_jni
+
+ifdef my_prebuilt_jni_libs
+# Install prebuilt JNI libs to the app specific lib path.
+# Files like @path/to/libfoo.so (path inside the apk) are JNI libs extracted from the prebuilt apk;
+# Files like path/to/libfoo.so (path relative to LOCAL_PATH) are prebuilts in the source tree.
+my_extracted_jni_libs := $(patsubst @%,%, \
+    $(filter @%, $(my_prebuilt_jni_libs)))
+ifdef my_extracted_jni_libs
+ifndef my_prebuilt_src_file
+$(error No prebuilt apk to extract prebuilt jni libraries $(my_extracted_jni_libs))
+endif
+# We use the first jni lib file as dependency.
+my_installed_prebuilt_jni := $(my_app_lib_path)/$(notdir $(firstword $(my_extracted_jni_libs)))
+$(my_installed_prebuilt_jni): PRIVATE_JNI_LIBS := $(my_extracted_jni_libs)
+$(my_installed_prebuilt_jni): $(my_prebuilt_src_file)
+	@echo "Extract JNI libs ($@ <- $<)"
+	@mkdir -p $(dir $@)
+	$(hide) unzip -j -o -d $(dir $@) $< $(PRIVATE_JNI_LIBS) && touch $@
+
+$(LOCAL_INSTALLED_MODULE) : | $(my_installed_prebuilt_jni)
+endif
+
+# prebuilt JNI exsiting as separate source files.
+my_prebuilt_jni_libs := $(addprefix $(LOCAL_PATH)/, \
+    $(filter-out @%, $(my_prebuilt_jni_libs)))
+ifdef my_prebuilt_jni_libs
+$(foreach lib, $(my_prebuilt_jni_libs), \
+    $(eval $(call copy-one-file, $(lib), $(my_app_lib_path)/$(notdir $(lib)))))
+
+$(LOCAL_INSTALLED_MODULE) : | $(addprefix $(my_app_lib_path)/, $(notdir $(my_prebuilt_jni_libs)))
+endif  # inner my_prebuilt_jni_libs
+endif  # outer my_prebuilt_jni_libs
diff --git a/core/java.mk b/core/java.mk
index 824ae6a..8afa748 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -332,6 +332,7 @@
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES := $(LOCAL_JAR_EXCLUDE_FILES)
 $(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES := $(LOCAL_JAR_PACKAGES)
+$(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) \
@@ -504,7 +505,7 @@
 $(findbugs_html) : $(findbugs_xml)
 	@mkdir -p $(dir $@)
 	@echo ConvertXmlToText: $@
-	$(hide) prebuilt/common/findbugs/bin/convertXmlToText -html:fancy.xsl $(PRIVATE_XML_FILE) \
+	$(hide) $(FINDBUGS_DIR)/convertXmlToText -html:fancy.xsl $(PRIVATE_XML_FILE) \
 	> $@
 
 $(LOCAL_MODULE)-findbugs : $(findbugs_html)
diff --git a/core/java_library.mk b/core/java_library.mk
index 343b27e..dffc7d9 100644
--- a/core/java_library.mk
+++ b/core/java_library.mk
@@ -93,15 +93,10 @@
 
 else # ! boot jar
 $(built_odex): PRIVATE_MODULE := $(LOCAL_MODULE)
-$(built_odex): PRIVATE_DEX_LOCATION := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
-$(built_odex): PRIVATE_DEX_PREOPT_IMAGE := $(LOCAL_DEX_PREOPT_IMAGE)
-# Make sure the boot jars get dex-preopt-ed first
-$(built_odex) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT)
-$(built_odex) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS)
-$(built_odex) : $(LOCAL_DEX_PREOPT_IMAGE)
-$(built_odex) : $(common_javalib.jar)
+# Use pattern rule - we may have multiple built odex files.
+$(built_odex) : $(dir $(LOCAL_BUILT_MODULE))% : $(common_javalib.jar)
 	@echo "Dexpreopt Jar: $(PRIVATE_MODULE) ($@)"
-	$(call dexpreopt-one-file,$(PRIVATE_DEX_PREOPT_IMAGE),$<,$(PRIVATE_DEX_LOCATION),$@)
+	$(call dexpreopt-one-file,$<,$@)
 
 $(LOCAL_BUILT_MODULE) : $(common_javalib.jar) | $(ACP)
 	$(call copy-file-to-target)
diff --git a/core/main.mk b/core/main.mk
index 21a2fe3..cdf3200 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -92,8 +92,6 @@
 # and host information.
 include $(BUILD_SYSTEM)/config.mk
 
-include $(BUILD_SYSTEM)/64_bit_blacklist.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
@@ -110,7 +108,6 @@
 $(info Checking build tools versions...)
 
 ifneq ($(HOST_OS),windows)
-ifneq ($(HOST_OS)-$(HOST_ARCH),darwin-ppc)
 # check for a case sensitive file system
 ifneq (a,$(shell mkdir -p $(OUT_DIR) ; \
                 echo a > $(OUT_DIR)/casecheck.txt; \
@@ -123,7 +120,6 @@
 $(error Case-insensitive filesystems not supported)
 endif
 endif
-endif
 
 # Make sure that there are no spaces in the absolute path; the
 # build system can't deal with them.
@@ -332,13 +328,15 @@
     enable_target_debugging :=
   endif
 
-  # Turn on Dalvik preoptimization for user builds, but only if not
+  # Turn on Dalvik preoptimization for libdvm.so 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 ($(user_variant),user)
-      ifeq ($(HOST_OS),linux)
-        WITH_DEXPREOPT := true
+    ifeq ($(DALVIK_VM_LIB),libdvm.so)
+      ifeq ($(user_variant),user)
+        ifeq ($(HOST_OS),linux)
+          WITH_DEXPREOPT := true
+        endif
       endif
     endif
   endif
@@ -446,12 +444,6 @@
 endif
 
 # Bring in all modules that need to be built.
-ifeq ($(HOST_OS)-$(HOST_ARCH),darwin-ppc)
-SDK_ONLY := true
-$(info Building the SDK under darwin-ppc is actually obsolete and unsupported.)
-$(error stop)
-endif
-
 ifeq ($(HOST_OS),windows)
 SDK_ONLY := true
 endif
@@ -571,7 +563,6 @@
 # brought in as requirements of other modules.
 #
 # Resolve the required module name to 32-bit or 64-bit variant.
-ifeq ($(TARGET_IS_64_BIT),true)
 # Get a list of corresponding 32-bit module names, if one exists.
 define get-32-bit-modules
 $(strip $(foreach m,$(1),\
@@ -601,12 +592,10 @@
         $(eval r_r := $(r) $(call get-32-bit-modules,$(r)))\
        )\
      )\
-     $(eval ALL_MODULES.$(m).REQUIRED := $(r_r))\
+     $(eval ALL_MODULES.$(m).REQUIRED := $(strip $(r_r)))\
   )\
 )
 r_r :=
-endif
-
 
 define add-required-deps
 $(1): | $(2)
@@ -632,29 +621,36 @@
 t_r :=
 h_r :=
 
-# Resolve the dependencies on shared libraries.
-$(foreach m,$(TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES), \
-  $(eval p := $(subst :,$(space),$(m))) \
-  $(eval r := $(filter $(TARGET_OUT_ROOT)/%,$(call module-installed-files,\
-    $(subst $(comma),$(space),$(lastword $(p)))))) \
-  $(eval $(call add-required-deps,$(word 2,$(p)),$(r))))
-$(foreach m,$(HOST_DEPENDENCIES_ON_SHARED_LIBRARIES), \
-  $(eval p := $(subst :,$(space),$(m))) \
-  $(eval r := $(filter $(HOST_OUT_ROOT)/%,$(call module-installed-files,\
-    $(subst $(comma),$(space),$(lastword $(p)))))) \
-  $(eval $(call add-required-deps,$(word 2,$(p)),$(r))))
+# Establish the dependecies on the shared libraries.
+# It also adds the shared library module names to ALL_MODULES.$(m).REQUIRED,
+# so they can be expanded to product_MODULES later.
+# $(1): TARGET_ or HOST_.
+# $(2): non-empty for 2nd arch.
+define resolve-shared-libs-depes
+$(foreach m,$($(if $(2),$($(1)2ND_ARCH_VAR_PREFIX))$(1)DEPENDENCIES_ON_SHARED_LIBRARIES),\
+  $(eval p := $(subst :,$(space),$(m)))\
+  $(eval mod := $(firstword $(p)))\
+  $(eval deps := $(subst $(comma),$(space),$(lastword $(p))))\
+  $(if $(2),$(eval deps := $(addsuffix $($(1)2ND_ARCH_MODULE_SUFFIX),$(deps))))\
+  $(eval r := $(filter $($(1)OUT_ROOT)/%,$(call module-installed-files,\
+    $(deps))))\
+  $(eval $(call add-required-deps,$(word 2,$(p)),$(r)))\
+  $(eval ALL_MODULES.$(mod).REQUIRED += $(deps)))
+endef
+
+$(call resolve-shared-libs-depes,TARGET_)
 ifdef TARGET_2ND_ARCH
-$(foreach m,$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES), \
-  $(eval p := $(subst :,$(space),$(m))) \
-  $(eval r := $(filter $(TARGET_OUT_ROOT)/%,$(call module-installed-files,\
-    $(addsuffix $(TARGET_2ND_ARCH_MODULE_SUFFIX), \
-      $(subst $(comma),$(space),$(lastword $(p))))))) \
-  $(eval $(call add-required-deps,$(word 2,$(p)),$(r))))
+$(call resolve-shared-libs-depes,TARGET_,true)
+endif
+$(call resolve-shared-libs-depes,HOST_)
+ifdef HOST_2ND_ARCH
+$(call resolve-shared-libs-depes,HOST_,true)
 endif
 
 m :=
 r :=
 p :=
+deps :=
 add-required-deps :=
 
 # -------------------------------------------------------------------
@@ -663,6 +659,20 @@
 # Of the modules defined by the component makefiles,
 # determine what we actually want to build.
 
+###########################################################
+## Expand a module name list with REQUIRED modules
+###########################################################
+# $(1): The variable name that holds the initial module name list.
+#       the variable will be modified to hold the expanded results.
+# $(2): The initial module name list.
+# Returns empty string (maybe with some whitespaces).
+define expand-required-modules
+$(eval _erm_new_modules := $(sort $(filter-out $($(1)),\
+  $(foreach m,$(2),$(ALL_MODULES.$(m).REQUIRED)))))\
+$(if $(_erm_new_modules),$(eval $(1) += $(_erm_new_modules))\
+  $(call expand-required-modules,$(1),$(_erm_new_modules)))
+endef
+
 ifdef FULL_BUILD
   # The base list of modules to build for this product is specified
   # by the appropriate product definition file, which was included
@@ -676,17 +686,16 @@
   modules_32 := $(patsubst %:32,%,$(filter %:32, $(product_MODULES)))
   modules_64 := $(patsubst %:64,%,$(filter %:64, $(product_MODULES)))
   modules_rest := $(filter-out %:32 %:64,$(product_MODULES))
-  ifeq ($(TARGET_IS_64_BIT),true)
-    product_MODULES := $(addsuffix $(TARGET_2ND_ARCH_MODULE_SUFFIX),$(modules_32))
-    product_MODULES += $(modules_64)
-    # For the rest we add both
-    product_MODULES += $(call get-32-bit-modules, $(modules_rest))
-    product_MODULES += $(modules_rest)
-  else
-    product_MODULES := $(modules_32) $(modules_64) $(modules_rest)
-  endif
+  # Note for 32-bit product, $(modules_32) and $(modules_64) will be
+  # added as their original module names.
+  product_MODULES := $(call get-32-bit-modules-if-we-can, $(modules_32))
+  product_MODULES += $(modules_64)
+  # For the rest we add both
+  product_MODULES += $(call get-32-bit-modules, $(modules_rest))
+  product_MODULES += $(modules_rest)
 
   $(call expand-required-modules,product_MODULES,$(product_MODULES))
+
   product_FILES := $(call module-installed-files, $(product_MODULES))
   ifeq (0,1)
     $(info product_FILES for $(TARGET_DEVICE) ($(INTERNAL_PRODUCT)):)
@@ -753,7 +762,7 @@
   # TODO: Should we do this for all builds and not just the sdk?
   dangling_modules :=
   $(foreach m, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES), \
-    $(if $(strip $(ALL_MODULES.$(m).INSTALLED)),,\
+    $(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.
@@ -1000,6 +1009,12 @@
 target-native-tests : native-target-tests
 tests : host-tests target-tests
 
+# To catch more build breakage, check build tests modules in eng and userdebug builds.
+ifneq ($(TARGET_BUILD_PDK),true)
+ifneq ($(filter eng userdebug,$(TARGET_BUILD_VARIANT)),)
+droidcore : target-tests host-tests
+endif
+endif
 
 .PHONY: lintall
 
diff --git a/core/module_arch_supported.mk b/core/module_arch_supported.mk
index 753a29e..a5e4a7c 100644
--- a/core/module_arch_supported.mk
+++ b/core/module_arch_supported.mk
@@ -2,14 +2,15 @@
 ## Determine if a module can be built for an arch
 ##
 ## Inputs from module makefile:
+## my_prefix   TARGET_ or HOST_
 ## my_module_multilib
-## LOCAL_MODULE_TARGET_ARCH
-## LOCAL_MODULE_TARGET_ARCH_WARN
-## LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH
-## LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH_WARN
+## LOCAL_MODULE_$(my_prefix)ARCH
+## LOCAL_MODULE_$(my_prefix)ARCH_WARN
+## LOCAL_MODULE_UNSUPPORTED_$(my_prefix)ARCH
+## LOCAL_MODULE_UNSUPPORTED_$(my_prefix)ARCH_WARN
 ##
 ## Inputs from build system:
-## TARGET_IS_64_BIT
+## $(my_prefix)IS_64_BIT
 ## LOCAL_2ND_ARCH_VAR_PREFIX
 ##
 ## Outputs:
@@ -23,11 +24,9 @@
 endif
 
 ifeq ($(LOCAL_2ND_ARCH_VAR_PREFIX),)
-ifeq ($(TARGET_IS_64_BIT)|$(my_module_multilib),true|32)
+ifeq ($($(my_prefix)IS_64_BIT)|$(my_module_multilib),true|32)
 my_module_arch_supported := false
-else ifeq ($(TARGET_IS_64_BIT)|$(my_module_multilib),|64)
-my_module_arch_supported := false
-else ifeq ($(call directory_is_64_bit_blacklisted,$(LOCAL_PATH)),true)
+else ifeq ($($(my_prefix)IS_64_BIT)|$(my_module_multilib),|64)
 my_module_arch_supported := false
 endif
 else # LOCAL_2ND_ARCH_VAR_PREFIX
@@ -38,24 +37,24 @@
 endif
 endif # LOCAL_2ND_ARCH_VAR_PREFIX
 
-ifneq (,$(LOCAL_MODULE_TARGET_ARCH))
-ifeq (,$(filter $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_TARGET_ARCH)))
+ifneq (,$(LOCAL_MODULE_$(my_prefix)ARCH))
+ifeq (,$(filter $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_$(my_prefix)ARCH)))
 my_module_arch_supported := false
 endif
 endif
 
-ifneq (,$(LOCAL_MODULE_TARGET_ARCH_WARN))
-ifeq (,$(filter $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_TARGET_ARCH_WARN)))
+ifneq (,$(LOCAL_MODULE_$(my_prefix)ARCH_WARN))
+ifeq (,$(filter $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_$(my_prefix)ARCH_WARN)))
 my_module_arch_supported := false
-$(warning $(LOCAL_MODULE): architecture $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH) not supported)
+$(warning $(LOCAL_MODULE): architecture $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH) not supported)
 endif
 endif
 
-ifneq (,$(filter $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH)))
+ifneq (,$(filter $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_UNSUPPORTED_$(my_prefix)ARCH)))
 my_module_arch_supported := false
 endif
 
-ifneq (,$(filter $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH_WARN)))
+ifneq (,$(filter $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH),$(LOCAL_MODULE_UNSUPPORTED_$(my_prefix)ARCH_WARN)))
 my_module_arch_supported := false
-$(warning $(LOCAL_MODULE): architecture $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH) unsupported)
+$(warning $(LOCAL_MODULE): architecture $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH) unsupported)
 endif
diff --git a/core/multilib.mk b/core/multilib.mk
index f630c94..a3ced65 100644
--- a/core/multilib.mk
+++ b/core/multilib.mk
@@ -1,4 +1,4 @@
-# Translate LOCAL_32_BIT_ONLY and LOCAL_NO_2ND_ARCH to LOCAL_MULTILIB,
+# Translate LOCAL_32_BIT_ONLY to LOCAL_MULTILIB,
 # and check LOCAL_MULTILIB is a valid value.  Returns module's multilib
 # setting in my_module_multilib, or empty if not set.
 
diff --git a/core/native_test.mk b/core/native_test.mk
index fc08f79..93b7e1a 100644
--- a/core/native_test.mk
+++ b/core/native_test.mk
@@ -5,4 +5,10 @@
 
 include $(BUILD_SYSTEM)/target_test_internal.mk
 
+ifndef LOCAL_MULTILIB
+ifndef LOCAL_32_BIT_ONLY
+LOCAL_MULTILIB := both
+endif
+endif
+
 include $(BUILD_EXECUTABLE)
diff --git a/core/package.mk b/core/package.mk
index c7d68d9..78b65db 100644
--- a/core/package.mk
+++ b/core/package.mk
@@ -1,8 +1,8 @@
 # We don't automatically set up rules to build packages for both
 # TARGET_ARCH and TARGET_2ND_ARCH.
-# By default, an package is built for TARGET_ARCH.
 # To build it for TARGET_2ND_ARCH in a 64bit product, use "LOCAL_MULTILIB := 32".
 
+my_prefix := TARGET_
 include $(BUILD_SYSTEM)/multilib.mk
 
 ifeq ($(TARGET_SUPPORTS_32_BIT_APPS)|$(TARGET_SUPPORTS_64_BIT_APPS),true|true)
diff --git a/core/package_internal.mk b/core/package_internal.mk
index 598c065..57b7b1f 100644
--- a/core/package_internal.mk
+++ b/core/package_internal.mk
@@ -72,8 +72,12 @@
 LOCAL_ASSET_DIR := $(LOCAL_PATH)/assets
 endif
 
+# LOCAL_RESOURCE_DIR may point to resource generated during the build
+need_compile_res :=
 ifeq (,$(LOCAL_RESOURCE_DIR))
   LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+else
+  need_compile_res := true
 endif
 
 package_resource_overlays := $(strip \
@@ -102,6 +106,10 @@
        ) \
      ))
 
+ifneq ($(all_resources),)
+  need_compile_res := true
+endif
+
 all_res_assets := $(strip $(all_assets) $(all_resources))
 
 package_expected_intermediates_COMMON := $(call local-intermediates-dir,COMMON)
@@ -110,7 +118,7 @@
 ifeq (,$(all_assets))
 LOCAL_ASSET_DIR:=
 endif
-ifeq (,$(all_resources))
+ifneq (true,$(need_compile_res))
 LOCAL_RESOURCE_DIR:=
 R_file_stamp :=
 else
@@ -135,9 +143,9 @@
 endif
 proguard_options_file :=
 ifneq ($(LOCAL_PROGUARD_ENABLED),custom)
-ifneq ($(all_resources),)
+ifeq ($(need_compile_res),true)
     proguard_options_file := $(package_expected_intermediates_COMMON)/proguard_options
-endif # all_resources
+endif # need_compile_res
 endif # !custom
 LOCAL_PROGUARD_FLAGS := $(addprefix -include ,$(proguard_options_file)) $(LOCAL_PROGUARD_FLAGS)
 
@@ -193,7 +201,7 @@
     PRIVATE_DEFAULT_APP_TARGET_SDK := $(DEFAULT_APP_TARGET_SDK)
 endif
 
-ifneq ($(all_resources),)
+ifeq ($(need_compile_res),true)
 
 # Since we don't know where the real R.java file is going to end up,
 # we need to use another file to stand in its place.  We'll just
@@ -263,7 +271,7 @@
 $(full_classes_compiled_jar): $(R_file_stamp)
 endif
 
-endif  # all_resources
+endif  # need_compile_res
 
 ifeq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
 # We need to explicitly clear this var so that we don't
@@ -297,7 +305,7 @@
     $(foreach lib,$(LOCAL_RES_LIBRARIES),\
         $(call intermediates-dir-for,APPS,$(lib),,COMMON)/src/R.stamp)
 
-$(resource_export_package) $(R_file_stamp): $(all_library_res_package_export_deps)
+$(resource_export_package) $(R_file_stamp) $(LOCAL_BUILT_MODULE): $(all_library_res_package_export_deps)
 $(LOCAL_INTERMEDIATE_TARGETS): \
     PRIVATE_AAPT_INCLUDES := $(all_library_res_package_exports)
 endif # LOCAL_NO_STANDARD_LIBRARIES
@@ -344,20 +352,10 @@
 
 # Define the rule to build the actual package.
 $(LOCAL_BUILT_MODULE): $(AAPT) | $(ZIPALIGN)
-ifdef LOCAL_DEX_PREOPT
-$(LOCAL_BUILT_MODULE): PRIVATE_DEX_LOCATION := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
-$(LOCAL_BUILT_MODULE): PRIVATE_BUILT_ODEX := $(built_odex)
-$(LOCAL_BUILT_MODULE): PRIVATE_DEX_PREOPT_IMAGE := $(LOCAL_DEX_PREOPT_IMAGE)
-# Make sure the boot jars get dexpreopt-ed first
-$(LOCAL_BUILT_MODULE) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT)
-$(LOCAL_BUILT_MODULE) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS)
-$(LOCAL_BUILT_MODULE) : $(LOCAL_DEX_PREOPT_IMAGE)
-
-# built_odex is byproduct of LOCAL_BUILT_MODULE without its own build recipe.
-$(built_odex) : $(LOCAL_BUILT_MODULE)
-endif
-$(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES := $(jni_shared_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES_ABI := $(jni_shared_libraries_abi)
+# PRIVATE_JNI_SHARED_LIBRARIES is a list of <abi>:<path_of_built_lib>.
+$(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)
 ifneq ($(TARGET_BUILD_APPS),)
     # Include all resources for unbundled apps.
     LOCAL_AAPT_INCLUDE_ALL_RESOURCES := true
@@ -385,7 +383,6 @@
 endif
 	$(sign-package)
 ifdef LOCAL_DEX_PREOPT
-	$(call dexpreopt-one-file,$(PRIVATE_DEX_PREOPT_IMAGE),$@,$(PRIVATE_DEX_LOCATION),$(PRIVATE_BUILT_ODEX))
 ifneq (nostripping,$(LOCAL_DEX_PREOPT))
 	$(call dexpreopt-remove-classes.dex,$@)
 endif
@@ -393,6 +390,18 @@
 	@# Alignment must happen after all other zip operations.
 	$(align-package)
 
+###############################
+## Rule to build the odex file
+ifdef LOCAL_DEX_PREOPT
+$(built_odex): PRIVATE_DEX_FILE := $(built_dex)
+$(built_odex) : $(built_dex)
+	$(hide) mkdir -p $(dir $@) && rm -f $@
+	$(add-dex-to-package)
+	$(hide) mv $@ $@.input
+	$(call dexpreopt-one-file,$@.input,$@)
+	$(hide) rm $@.input
+endif
+
 # Save information about this package
 PACKAGES.$(LOCAL_PACKAGE_NAME).OVERRIDES := $(strip $(LOCAL_OVERRIDES_PACKAGES))
 PACKAGES.$(LOCAL_PACKAGE_NAME).RESOURCE_FILES := $(all_resources)
diff --git a/core/pathmap.mk b/core/pathmap.mk
index aaeb905..14c8f05 100644
--- a/core/pathmap.mk
+++ b/core/pathmap.mk
@@ -85,6 +85,7 @@
 	    drm \
 	    opengl \
 	    sax \
+	    telecomm \
 	    telephony \
 	    wifi \
 	    keystore \
diff --git a/core/pdk_config.mk b/core/pdk_config.mk
index f5fdd15..fd63820 100644
--- a/core/pdk_config.mk
+++ b/core/pdk_config.mk
@@ -53,7 +53,7 @@
 # all paths under out dir
 PDK_PLATFORM_JAVA_ZIP_JAVA_TARGET_LIB_DIR += \
 	target/common/obj/JAVA_LIBRARIES/android_stubs_current_intermediates \
-	target/common/obj/JAVA_LIBRARIES/core_intermediates \
+	target/common/obj/JAVA_LIBRARIES/core-libart_intermediates \
 	target/common/obj/JAVA_LIBRARIES/core-junit_intermediates \
 	target/common/obj/JAVA_LIBRARIES/ext_intermediates \
 	target/common/obj/JAVA_LIBRARIES/framework_intermediates \
@@ -61,6 +61,7 @@
 	target/common/obj/JAVA_LIBRARIES/android.test.runner_intermediates \
 	target/common/obj/JAVA_LIBRARIES/telephony-common_intermediates \
 	target/common/obj/JAVA_LIBRARIES/voip-common_intermediates \
+	target/common/obj/JAVA_LIBRARIES/ims-common_intermediates \
 	target/common/obj/JAVA_LIBRARIES/mms-common_intermediates \
 	target/common/obj/JAVA_LIBRARIES/android-ex-camera2_intermediates \
 	target/common/obj/JAVA_LIBRARIES/android-common_intermediates \
@@ -192,12 +193,16 @@
 ifneq (,$(filter platform platform-java, $(MAKECMDGOALS))$(filter true,$(TARGET_BUILD_PDK)))
 # files under $(PRODUCT_OUT)/symbols to help debugging.
 # Source not included to PDK due to dependency issue, so provide symbols instead.
+
+# We may not be building all of them.
+# The platform.zip just silently ignores the nonexistent ones.
 PDK_SYMBOL_FILES_LIST := \
-	system/bin/app_process
+    system/bin/app_process32 \
+    system/bin/app_process64
 
 ifdef PDK_FUSION_PLATFORM_ZIP
 # symbols should be explicitly pulled for fusion build
-$(foreach f,$(PDK_SYMBOL_FILES_LIST),\
+$(foreach f,$(filter $(PDK_SYMBOL_FILES_LIST), $(_pdk_fusion_file_list)),\
   $(eval $(call add-dependency,$(PRODUCT_OUT)/$(f),$(PRODUCT_OUT)/symbols/$(f))))
 endif # PLATFORM_ZIP
 endif # platform.zip build or PDK
diff --git a/core/prebuilt.mk b/core/prebuilt.mk
index 5f91110..33f5dc6 100644
--- a/core/prebuilt.mk
+++ b/core/prebuilt.mk
@@ -7,32 +7,43 @@
 ###########################################################
 
 ifdef LOCAL_IS_HOST_MODULE
-include $(BUILD_SYSTEM)/prebuilt_internal.mk
-else #!LOCAL_IS_HOST_MODULE
+  my_prefix := HOST_
+else
+  my_prefix := TARGET_
+endif
 
 include $(BUILD_SYSTEM)/multilib.mk
 
-ifndef my_module_multilib
-# prebuilts default to building for either architecture,
-# the first if its supported, otherwise the second.
-my_module_multilib := both
-endif
+my_skip_non_preferred_arch :=
 
 # check if first arch is supported
 include $(BUILD_SYSTEM)/module_arch_supported.mk
 ifeq ($(my_module_arch_supported),true)
 # first arch is supported
 include $(BUILD_SYSTEM)/prebuilt_internal.mk
-else ifneq (,$(TARGET_2ND_ARCH))
+ifneq ($(my_module_multilib),both)
+my_skip_non_preferred_arch := true
+endif # $(my_module_multilib)
+endif # $(my_module_arch_supported)
+
+ifndef my_skip_non_preferred_arch
+ifneq (,$($(my_prefix)2ND_ARCH))
 # check if secondary arch is supported
-LOCAL_2ND_ARCH_VAR_PREFIX := $(TARGET_2ND_ARCH_VAR_PREFIX)
+LOCAL_2ND_ARCH_VAR_PREFIX := $($(my_prefix)2ND_ARCH_VAR_PREFIX)
 include $(BUILD_SYSTEM)/module_arch_supported.mk
 ifeq ($(my_module_arch_supported),true)
 # secondary arch is supported
+OVERRIDE_BUILT_MODULE_PATH :=
+LOCAL_BUILT_MODULE :=
+LOCAL_INSTALLED_MODULE :=
+LOCAL_MODULE_STEM :=
+LOCAL_BUILT_MODULE_STEM :=
+LOCAL_INSTALLED_MODULE_STEM :=
+LOCAL_INTERMEDIATE_TARGETS :=
 include $(BUILD_SYSTEM)/prebuilt_internal.mk
-endif
-endif # TARGET_2ND_ARCH
-endif # !LOCAL_IS_HOST_MODULE
+endif # $(my_module_arch_supported)
+endif # $($(my_prefix)2ND_ARCH)
+endif # $(my_skip_non_preferred_arch) not true
 
 LOCAL_2ND_ARCH_VAR_PREFIX :=
 
diff --git a/core/prebuilt_internal.mk b/core/prebuilt_internal.mk
index bf519ee..1ee9f9a 100644
--- a/core/prebuilt_internal.mk
+++ b/core/prebuilt_internal.mk
@@ -19,21 +19,22 @@
 # Not much sense to check build prebuilts
 LOCAL_DONT_CHECK_MODULE := true
 
+my_32_64_bit_suffix := $(if $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)IS_64_BIT),64,32)
+
 ifdef LOCAL_PREBUILT_MODULE_FILE
   my_prebuilt_src_file := $(LOCAL_PREBUILT_MODULE_FILE)
 else
-  ifdef LOCAL_SRC_FILES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
-    my_prebuilt_src_file := $(LOCAL_PATH)/$(LOCAL_SRC_FILES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+  ifdef LOCAL_SRC_FILES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
+    my_prebuilt_src_file := $(LOCAL_PATH)/$(LOCAL_SRC_FILES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
   else
-    my_prebuilt_src_file := $(LOCAL_PATH)/$(LOCAL_SRC_FILES)
+    ifdef LOCAL_SRC_FILES_$(my_32_64_bit_suffix)
+      my_prebuilt_src_file := $(LOCAL_PATH)/$(LOCAL_SRC_FILES_$(my_32_64_bit_suffix))
+    else
+      my_prebuilt_src_file := $(LOCAL_PATH)/$(LOCAL_SRC_FILES)
+    endif
   endif
 endif
 
-ifdef LOCAL_IS_HOST_MODULE
-  my_prefix := HOST_
-else
-  my_prefix := TARGET_
-endif
 ifeq (SHARED_LIBRARIES,$(LOCAL_MODULE_CLASS))
   # Put the built targets of all shared libraries in a common directory
   # to simplify the link line.
@@ -91,7 +92,7 @@
 ifdef LOCAL_INSTALLED_MODULE
 ifdef LOCAL_SHARED_LIBRARIES
 $(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)DEPENDENCIES_ON_SHARED_LIBRARIES += \
-  $(LOCAL_MODULE):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(LOCAL_SHARED_LIBRARIES))
+  $(my_register_name):$(LOCAL_INSTALLED_MODULE):$(subst $(space),$(comma),$(LOCAL_SHARED_LIBRARIES))
 
 # We also need the LOCAL_BUILT_MODULE dependency,
 # since we use -rpath-link which points to the built module's path.
@@ -158,31 +159,29 @@
 # defines built_odex along with rule to install odex
 include $(BUILD_SYSTEM)/dex_preopt_odex_install.mk
 #######################################
-ifdef LOCAL_DEX_PREOPT
-$(built_module): PRIVATE_DEX_PREOPT_IMAGE := $(LOCAL_DEX_PREOPT_IMAGE)
-$(built_module): PRIVATE_DEX_LOCATION := $(patsubst $(PRODUCT_OUT)%,%,$(LOCAL_INSTALLED_MODULE))
-$(built_module): PRIVATE_BUILT_ODEX := $(built_odex)
-# Make sure the boot jars get dexpreopt-ed first
-$(built_module) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_BUILT_BOOT_PREOPT)
-$(built_module) : $(DEXPREOPT_ONE_FILE_DEPENDENCY_TOOLS)
-(built_module) : $(LOCAL_DEX_PREOPT_IMAGE)
-# built_odex is byproduct of LOCAL_BUILT_MODULE without its own build recipe.
-$(built_odex) : $(LOCAL_BUILT_MODULE)
-endif # LOCAL_DEX_PREOPT
 # Sign and align non-presigned .apks.
 $(built_module) : $(my_prebuilt_src_file) | $(ACP) $(ZIPALIGN) $(SIGNAPK_JAR)
 	$(transform-prebuilt-to-target)
-ifdef my_extracted_jni_libs
+ifdef extracted_jni_libs
 	$(hide) zip -d $@ 'lib/*.so'  # strip embedded JNI libraries.
 endif
 ifneq ($(LOCAL_CERTIFICATE),PRESIGNED)
 	$(sign-package)
 endif
 ifdef LOCAL_DEX_PREOPT
-	$(call dexpreopt-one-file,$(PRIVATE_DEX_PREOPT_IMAGE),$@,$(PRIVATE_DEX_LOCATION),$(PRIVATE_BUILT_ODEX))
+ifneq (nostripping,$(LOCAL_DEX_PREOPT))
+	$(call dexpreopt-remove-classes.dex,$@)
+endif
 endif
 	$(align-package)
 
+###############################
+## Rule to build the odex file
+ifdef LOCAL_DEX_PREOPT
+$(built_odex) : $(my_prebuilt_src_file)
+	$(call dexpreopt-one-file,$<,$@)
+endif
+
 else # LOCAL_MODULE_CLASS != APPS
 ifneq ($(LOCAL_PREBUILT_STRIP_COMMENTS),)
 $(built_module) : $(my_prebuilt_src_file)
diff --git a/core/product.mk b/core/product.mk
index 1a7685c..7eef2e5 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -104,7 +104,8 @@
     PRODUCT_OEM_PROPERTIES \
     PRODUCT_SYSTEM_PROPERTY_BLACKLIST \
     PRODUCT_VERITY_PARTITION \
-    PRODUCT_VERITY_SIGNING_KEY
+    PRODUCT_VERITY_SIGNING_KEY \
+    PRODUCT_VERITY_MOUNTPOINT
 
 define dump-product
 $(info ==== $(1) ====)\
@@ -249,11 +250,13 @@
 	BOARD_BOOTIMAGE_PARTITION_SIZE \
 	BOARD_RECOVERYIMAGE_PARTITION_SIZE \
 	BOARD_SYSTEMIMAGE_PARTITION_SIZE \
+	BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE \
 	BOARD_USERDATAIMAGE_PARTITION_SIZE \
 	BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE \
 	BOARD_CACHEIMAGE_PARTITION_SIZE \
 	BOARD_FLASH_BLOCK_SIZE \
-	BOARD_SYSTEMIMAGE_PARTITION_SIZE \
+	BOARD_VENDORIMAGE_PARTITION_SIZE \
+	BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE \
 	BOARD_INSTALLER_CMDLINE \
 
 
diff --git a/core/product_config.mk b/core/product_config.mk
index 171c394..8fa5102 100644
--- a/core/product_config.mk
+++ b/core/product_config.mk
@@ -164,13 +164,11 @@
 
 # Default to building dalvikvm on hosts that support it...
 ifeq ($(HOST_OS),linux)
-ifeq ($(BUILD_HOST_64bit),)
 # ... or if the if the option is already set
 ifeq ($(WITH_HOST_DALVIK),)
   WITH_HOST_DALVIK := true
 endif
 endif
-endif
 
 # ---------------------------------------------------------------
 # Include the product definitions.
@@ -269,7 +267,7 @@
 PRODUCT_RUNTIMES := $(product_runtimes)
 product_runtimes :=
 
-PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PROPERTY_OVERRIDES += persist.sys.dalvik.vm.lib.1=$(DALVIK_VM_LIB)
+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
diff --git a/core/proguard_basic_keeps.flags b/core/proguard_basic_keeps.flags
index 622d4ee..4a85db0 100644
--- a/core/proguard_basic_keeps.flags
+++ b/core/proguard_basic_keeps.flags
@@ -59,3 +59,6 @@
 # platform version.  We know about them, and they are safe.
 # See proguard-android.txt in the SDK package.
 -dontwarn android.support.**
+
+# Less spammy.
+-dontnote
diff --git a/core/shared_library.mk b/core/shared_library.mk
index 95a8d7b..71a3bb2 100644
--- a/core/shared_library.mk
+++ b/core/shared_library.mk
@@ -1,3 +1,12 @@
+my_prefix := TARGET_
+include $(BUILD_SYSTEM)/multilib.mk
+
+ifndef my_module_multilib
+# libraries default to building for both architecturess
+my_module_multilib := both
+endif
+
+ifeq ($(my_module_multilib),both)
 ifneq ($(LOCAL_MODULE_PATH),)
 ifneq ($(TARGET_2ND_ARCH),)
 $(warning $(LOCAL_MODULE): LOCAL_MODULE_PATH for shared libraries is unsupported in multiarch builds, use LOCAL_MODULE_RELATIVE_PATH instead)
@@ -9,13 +18,8 @@
 $(warning $(LOCAL_MODULE): LOCAL_UNSTRIPPED_PATH for shared libraries is unsupported in multiarch builds)
 endif
 endif
+endif # my_module_multilib == both
 
-include $(BUILD_SYSTEM)/multilib.mk
-
-ifndef my_module_multilib
-# libraries default to building for both architecturess
-my_module_multilib := both
-endif
 
 LOCAL_2ND_ARCH_VAR_PREFIX :=
 include $(BUILD_SYSTEM)/module_arch_supported.mk
diff --git a/core/shared_library_internal.mk b/core/shared_library_internal.mk
index bda44f4..abef11f 100644
--- a/core/shared_library_internal.mk
+++ b/core/shared_library_internal.mk
@@ -42,6 +42,7 @@
 my_target_global_ld_dirs := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_LD_DIRS)
 my_target_fdo_lib := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_FDO_LIB)
 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)
 my_target_crtend_so_o := $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_CRTEND_SO_O)
 ifdef LOCAL_SDK_VERSION
@@ -59,6 +60,7 @@
 $(linked_module): PRIVATE_TARGET_GLOBAL_LDFLAGS := $(my_target_global_ldflags)
 $(linked_module): PRIVATE_TARGET_FDO_LIB := $(my_target_fdo_lib)
 $(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)
 
diff --git a/core/static_java_library.mk b/core/static_java_library.mk
index f31ccd8..8e6029d 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -26,7 +26,10 @@
 # Hack to build static Java library with Android resource
 # See bug 5714516
 all_resources :=
+need_compile_res :=
+# A static Java library needs to explicily set LOCAL_RESOURCE_DIR.
 ifdef LOCAL_RESOURCE_DIR
+need_compile_res := true
 all_resources := $(strip \
     $(foreach dir, $(LOCAL_RESOURCE_DIR), \
       $(addprefix $(dir)/, \
@@ -36,7 +39,6 @@
       ) \
     ))
 
-ifneq (,$(all_resources))
 # By default we should remove the R/Manifest classes from a static Java library,
 # because they will be regenerated in the app that uses it.
 # But if the static Java library will be used by a library, then we may need to
@@ -56,14 +58,13 @@
 endif
 LOCAL_PROGUARD_FLAGS := $(addprefix -include ,$(proguard_options_file)) $(LOCAL_PROGUARD_FLAGS)
 
-endif  # all_resources
 endif  # LOCAL_RESOURCE_DIR
 
 all_res_assets := $(all_resources)
 
 include $(BUILD_SYSTEM)/java_library.mk
 
-ifneq (,$(all_resources))
+ifeq (true,$(need_compile_res))
 R_file_stamp := $(LOCAL_INTERMEDIATE_SOURCE_DIR)/R.stamp
 
 include $(BUILD_SYSTEM)/android_manifest.mk
@@ -117,7 +118,7 @@
 $(full_classes_compiled_jar): $(R_file_stamp)
 endif
 
-endif  # $(all_resources) not empty
+endif  # need_compile_res
 
 # Reset internal variables.
 all_res_assets :=
diff --git a/core/static_library.mk b/core/static_library.mk
index bedefd0..854cbfc 100644
--- a/core/static_library.mk
+++ b/core/static_library.mk
@@ -1,3 +1,4 @@
+my_prefix := TARGET_
 include $(BUILD_SYSTEM)/multilib.mk
 
 ifndef my_module_multilib
diff --git a/core/static_library_internal.mk b/core/static_library_internal.mk
index 2d3468c..cabe823 100644
--- a/core/static_library_internal.mk
+++ b/core/static_library_internal.mk
@@ -28,7 +28,6 @@
 $(all_objects) : PRIVATE_TARGET_GLOBAL_CPPFLAGS :=
 endif
 
-$(LOCAL_BUILT_MODULE): PRIVATE_2ND_ARCH_VAR_PREFIX := $(LOCAL_2ND_ARCH_VAR_PREFIX)
 $(LOCAL_BUILT_MODULE) : $(built_whole_libraries)
 $(LOCAL_BUILT_MODULE) : $(all_objects)
 	$(transform-o-to-static-lib)
diff --git a/core/target_test_internal.mk b/core/target_test_internal.mk
index 7b99678..87503ea 100644
--- a/core/target_test_internal.mk
+++ b/core/target_test_internal.mk
@@ -5,6 +5,9 @@
 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
@@ -14,7 +17,19 @@
 LOCAL_SHARED_LIBRARIES += libstlport
 LOCAL_STATIC_LIBRARIES += libstdc++
 endif
-
-ifndef LOCAL_MODULE_PATH
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
 endif
+
+ifdef LOCAL_MODULE_PATH
+$(error $(LOCAL_PATH): Do not set LOCAL_MODULE_PATH when building test $(LOCAL_MODULE))
+endif
+
+ifdef LOCAL_MODULE_PATH_32
+$(error $(LOCAL_PATH): Do not set LOCAL_MODULE_PATH_32 when building test $(LOCAL_MODULE))
+endif
+
+ifdef LOCAL_MODULE_PATH_64
+$(error $(LOCAL_PATH): Do not set LOCAL_MODULE_PATH_64 when building test $(LOCAL_MODULE))
+endif
+
+LOCAL_MODULE_PATH_32 := $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
+LOCAL_MODULE_PATH_64 := $(TARGET_OUT_DATA_NATIVE_TESTS)64/$(LOCAL_MODULE)
diff --git a/core/tasks/cts.mk b/core/tasks/cts.mk
index f991a9e..58bb235 100644
--- a/core/tasks/cts.mk
+++ b/core/tasks/cts.mk
@@ -18,7 +18,7 @@
 cts_name := android-cts
 
 DDMLIB_JAR := $(HOST_OUT_JAVA_LIBRARIES)/ddmlib-prebuilt.jar
-junit_host_jar := $(HOST_OUT_JAVA_LIBRARIES)/junit.jar
+JUNIT_HOST_JAR := $(HOST_OUT_JAVA_LIBRARIES)/junit.jar
 HOSTTESTLIB_JAR := $(HOST_OUT_JAVA_LIBRARIES)/hosttestlib.jar
 TF_JAR := $(HOST_OUT_JAVA_LIBRARIES)/tradefed-prebuilt.jar
 CTS_TF_JAR := $(HOST_OUT_JAVA_LIBRARIES)/cts-tradefed.jar
@@ -48,6 +48,7 @@
 	android.core.tests.libcore.package.harmony_java_text \
 	android.core.tests.libcore.package.harmony_java_util \
 	android.core.tests.libcore.package.harmony_javax_security \
+	android.core.tests.libcore.package.okhttp \
 	android.core.tests.runner
 
 # The list of test packages that apache-harmony-tests (external/apache-harmony/Android.mk)
@@ -58,17 +59,22 @@
 	android.core.tests.libcore.package.harmony_prefs \
 	android.core.tests.libcore.package.harmony_sql
 
+
+CTS_TEST_JAR_LIST := \
+	CtsJdwp
+
 # Depend on the full package paths rather than the phony targets to avoid
 # rebuilding the packages every time.
 CTS_CORE_CASES := $(foreach pkg,$(CTS_CORE_CASE_LIST),$(call intermediates-dir-for,APPS,$(pkg))/package.apk)
+CTS_TEST_JAR_FILES := $(foreach c,$(CTS_TEST_JAR_LIST),$(call intermediates-dir-for,JAVA_LIBRARIES,$(c))/javalib.jar)
 
 -include cts/CtsTestCaseList.mk
 CTS_CASE_LIST := $(CTS_CORE_CASE_LIST) $(CTS_TEST_CASE_LIST)
 
 DEFAULT_TEST_PLAN := $(cts_dir)/$(cts_name)/resource/plans
 CTS_TEST_CASE_LIST_FILES := $(foreach c, $(CTS_TEST_CASE_LIST), $(call intermediates-dir-for,APPS,$(c))/package.apk)
-$(cts_dir)/all_cts_files_stamp: PRIVATE_JUNIT_HOST_JAR := $(junit_host_jar)
-$(cts_dir)/all_cts_files_stamp: $(CTS_CORE_CASES) $(CTS_TEST_CASES) $(CTS_TEST_CASE_LIST_FILES) $(junit_host_jar) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(VMTESTSTF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(ACP)
+$(cts_dir)/all_cts_files_stamp: PRIVATE_JUNIT_HOST_JAR := $(JUNIT_HOST_JAR)
+$(cts_dir)/all_cts_files_stamp: $(CTS_CORE_CASES) $(CTS_TEST_CASES) $(CTS_TEST_CASE_LIST_FILES) $(JUNIT_HOST_JAR) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(VMTESTSTF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(ACP) $(CTS_TEST_JAR_FILES)
 # Make necessary directory for CTS
 	$(hide) rm -rf $(PRIVATE_CTS_DIR)
 	$(hide) mkdir -p $(TMP_DIR)
@@ -80,6 +86,7 @@
 	$(hide) $(ACP) -fp $(VMTESTSTF_JAR) $(PRIVATE_DIR)/repository/testcases
 	$(hide) $(ACP) -fp $(DDMLIB_JAR) $(PRIVATE_JUNIT_HOST_JAR) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(PRIVATE_DIR)/tools
 # Change mode of the executables
+	$(foreach jar,$(CTS_TEST_JAR_LIST),$(call copy-testcase-jar,$(jar)))
 	$(foreach apk,$(CTS_CASE_LIST),$(call copy-testcase-apk,$(apk)))
 	$(foreach testcase,$(CTS_TEST_CASES),$(call copy-testcase,$(testcase)))
 	$(hide) touch $@
@@ -95,24 +102,26 @@
 define generate-core-test-description
 @echo "Generate core-test description ("$(notdir $(1))")"
 $(hide) java -Xmx256M \
-	-Xbootclasspath/a:$(PRIVATE_CLASSPATH) \
-	-classpath $(PRIVATE_CLASSPATH):$(HOST_OUT_JAVA_LIBRARIES)/descGen.jar:$(HOST_OUT_JAVA_LIBRARIES)/junit.jar:$(HOST_JDK_TOOLS_JAR) \
+	-Xbootclasspath/a:$(PRIVATE_CLASSPATH):$(JUNIT_HOST_JAR) \
+	-classpath $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar:$(HOST_JDK_TOOLS_JAR) \
 	$(PRIVATE_PARAMS) CollectAllTests $(1) $(2) $(3) "$(4)" $(5) $(6)
 endef
 
-CORE_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core,,COMMON)
+CORE_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core-libart,,COMMON)
 CONSCRYPT_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,conscrypt,,COMMON)
 BOUNCYCASTLE_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,bouncycastle,,COMMON)
 APACHEXML_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,apache-xml,,COMMON)
-OKHTTP_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,okhttp,,COMMON)
-APACHEHARMONY_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,apache-harmony-tests,,COMMON)
+OKHTTP_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,okhttp-nojarjar,,COMMON)
+OKHTTPTESTS_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,okhttp-tests-nojarjar,,COMMON)
+OKHTTP_REPACKAGED_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,okhttp,,COMMON)
+APACHEHARMONYTESTS_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,apache-harmony-tests,,COMMON)
 SQLITEJDBC_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,sqlite-jdbc,,COMMON)
 JUNIT_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core-junit,,COMMON)
 CORETESTS_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core-tests,,COMMON)
 JSR166TESTS_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,jsr166-tests,,COMMON)
 CONSCRYPTTESTS_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,conscrypt-tests,,COMMON)
 
-GEN_CLASSPATH := $(CORE_INTERMEDIATES)/classes.jar:$(CONSCRYPT_INTERMEDIATES)/classes.jar:$(BOUNCYCASTLE_INTERMEDIATES)/classes.jar:$(APACHEXML_INTERMEDIATES)/classes.jar:$(APACHEHARMONY_INTERMEDIATES)/classes.jar:$(OKHTTP_INTERMEDIATES)/classes.jar:$(JUNIT_INTERMEDIATES)/classes.jar:$(SQLITEJDBC_INTERMEDIATES)/javalib.jar:$(CORETESTS_INTERMEDIATES)/javalib.jar:$(JSR166TESTS_INTERMEDIATES)/javalib.jar:$(CONSCRYPTTESTS_INTERMEDIATES)/javalib.jar
+GEN_CLASSPATH := $(CORE_INTERMEDIATES)/classes.jar:$(CONSCRYPT_INTERMEDIATES)/classes.jar:$(BOUNCYCASTLE_INTERMEDIATES)/classes.jar:$(APACHEXML_INTERMEDIATES)/classes.jar:$(APACHEHARMONYTESTS_INTERMEDIATES)/classes.jar:$(OKHTTP_INTERMEDIATES)/classes.jar:$(OKHTTPTESTS_INTERMEDIATES)/classes.jar:$(OKHTTP_REPACKAGED_INTERMEDIATES)/classes.jar:$(JUNIT_INTERMEDIATES)/classes.jar:$(SQLITEJDBC_INTERMEDIATES)/javalib.jar:$(CORETESTS_INTERMEDIATES)/javalib.jar:$(JSR166TESTS_INTERMEDIATES)/javalib.jar:$(CONSCRYPTTESTS_INTERMEDIATES)/javalib.jar
 
 CTS_CORE_XMLS := \
 	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.dalvik.xml \
@@ -136,6 +145,7 @@
 	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_logging.xml \
 	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_prefs.xml \
 	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_sql.xml \
+	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.okhttp.xml \
 
 $(CTS_CORE_XMLS): PRIVATE_CLASSPATH:=$(GEN_CLASSPATH)
 # Why does this depend on javalib.jar instead of classes.jar?  Because
@@ -143,7 +153,7 @@
 # build system requires that dependencies use javalib.jar.  If
 # javalib.jar is up-to-date, then classes.jar is as well.  Depending
 # on classes.jar will build the files incorrectly.
-CTS_CORE_XMLS_DEPS := $(CTS_CORE_CASES) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(HOST_OUT_JAVA_LIBRARIES)/junit.jar $(CORE_INTERMEDIATES)/javalib.jar $(BOUNCYCASTLE_INTERMEDIATES)/javalib.jar $(APACHEXML_INTERMEDIATES)/javalib.jar $(APACHEHARMONY_INTERMEDIATES)/javalib.jar $(OKHTTP_INTERMEDIATES)/javalib.jar $(SQLITEJDBC_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(CORETESTS_INTERMEDIATES)/javalib.jar $(JSR166TESTS_INTERMEDIATES)/javalib.jar $(CONSCRYPTTESTS_INTERMEDIATES)/javalib.jar build/core/tasks/cts.mk | $(ACP)
+CTS_CORE_XMLS_DEPS := $(CTS_CORE_CASES) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(JUNIT_HOST_JAR) $(CORE_INTERMEDIATES)/javalib.jar $(BOUNCYCASTLE_INTERMEDIATES)/javalib.jar $(APACHEXML_INTERMEDIATES)/javalib.jar $(APACHEHARMONYTESTS_INTERMEDIATES)/javalib.jar $(OKHTTP_INTERMEDIATES)/javalib.jar $(OKHTTPTESTS_INTERMEDIATES)/javalib.jar $(OKHTTP_REPACKAGED_INTERMEDIATES)/javalib.jar $(SQLITEJDBC_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(CORETESTS_INTERMEDIATES)/javalib.jar $(JSR166TESTS_INTERMEDIATES)/javalib.jar $(CONSCRYPTTESTS_INTERMEDIATES)/javalib.jar build/core/tasks/cts.mk | $(ACP)
 
 $(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.dalvik.xml: $(CTS_CORE_XMLS_DEPS)
 	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
@@ -268,44 +278,50 @@
 	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_beans,\
 		cts/tests/core/libcore/harmony_beans/AndroidManifest.xml,\
-		$(APACHEHARMONY_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.beans,\
+		$(APACHEHARMONYTESTS_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.beans,\
 		libcore/expectations external/apache-harmony/Android.mk)
 
 $(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_logging.xml: $(CTS_CORE_XMLS_DEPS)
 	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_logging,\
 		cts/tests/core/libcore/harmony_logging/AndroidManifest.xml,\
-		$(APACHEHARMONY_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.logging,\
+		$(APACHEHARMONYTESTS_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.logging,\
 		libcore/expectations external/apache-harmony/Android.mk)
 
-
 $(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_prefs.xml: $(CTS_CORE_XMLS_DEPS)
 	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_prefs,\
 		cts/tests/core/libcore/harmony_prefs/AndroidManifest.xml,\
-		$(APACHEHARMONY_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.prefs,\
+		$(APACHEHARMONYTESTS_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.prefs,\
 		libcore/expectations external/apache-harmony/Android.mk)
 
 $(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_sql.xml: $(CTS_CORE_XMLS_DEPS)
 	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.harmony_sql,\
 		cts/tests/core/libcore/harmony_sql/AndroidManifest.xml,\
-		$(APACHEHARMONY_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.sql,\
+		$(APACHEHARMONYTESTS_INTERMEDIATES)/javalib.jar,com.android.org.apache.harmony.sql,\
 		libcore/expectations external/apache-harmony/Android.mk)
 
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.okhttp.xml: $(CTS_CORE_XMLS_DEPS)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
+	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.okhttp,\
+		cts/tests/core/libcore/okhttp/AndroidManifest.xml,\
+		$(OKHTTPTESTS_INTERMEDIATES)/javalib.jar,,\
+		libcore/expectations)
+
 # ----- Generate the test descriptions for the vm-tests-tf -----
 #
 CORE_VM_TEST_TF_DESC := $(CTS_TESTCASES_OUT)/android.core.vm-tests-tf.xml
 
 # core tests only needed to get hold of junit-framework-classes
-CORE_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core,,COMMON)
+CORE_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core-libart,,COMMON)
 JUNIT_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core-junit,,COMMON)
 
 GEN_CLASSPATH := $(CORE_INTERMEDIATES)/classes.jar:$(JUNIT_INTERMEDIATES)/classes.jar:$(VMTESTSTF_JAR):$(DDMLIB_JAR):$(TF_JAR)
 
 $(CORE_VM_TEST_TF_DESC): PRIVATE_CLASSPATH:=$(GEN_CLASSPATH)
 # Please see big comment above on why this line depends on javalib.jar instead of classes.jar
-$(CORE_VM_TEST_TF_DESC): $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(HOST_OUT_JAVA_LIBRARIES)/junit.jar $(CORE_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(VMTESTSTF_JAR) $(DDMLIB_JAR) | $(ACP)
+$(CORE_VM_TEST_TF_DESC): $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(JUNIT_HOST_JAR) $(CORE_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(VMTESTSTF_JAR) $(DDMLIB_JAR) | $(ACP)
 	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.vm-tests-tf,\
 		cts/tests/vm-tests-tf/AndroidManifest.xml,\
@@ -351,3 +367,11 @@
 $(hide) $(ACP) -fp $(1) $(PRIVATE_DIR)/repository/testcases/$(notdir $1)
 
 endef
+
+define copy-testcase-jar
+
+$(hide) $(ACP) -fp $(call intermediates-dir-for,JAVA_LIBRARIES,$(1))/javalib.jar \
+	$(PRIVATE_DIR)/repository/testcases/$(1).jar
+
+endef
+
diff --git a/core/tasks/tools/package-modules.mk b/core/tasks/tools/package-modules.mk
index 19e756a..f7e04ed 100644
--- a/core/tasks/tools/package-modules.mk
+++ b/core/tasks/tools/package-modules.mk
@@ -14,27 +14,27 @@
 my_copy_pairs :=
 my_pickup_files :=
 
-# Search for modules' built files and installed files;
+# Iterate over modules' built files and installed files;
 # Calculate the dest files in the output zip file.
-# If for 1 module name we found multiple installed files,
-# we use suffix matching to find the corresponding built file.
+
 $(foreach m,$(my_modules),\
-  $(if $(ALL_MODULES.$(m).INSTALLED),,\
+  $(eval _pickup_files := $(strip $(ALL_MODULES.$(m).PICKUP_FILES)\
+    $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).PICKUP_FILES)))\
+  $(eval _built_files := $(strip $(ALL_MODULES.$(m).BUILT_INSTALLED)\
+    $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).BUILT_INSTALLED)))\
+  $(if $(_pickup_files)$(_built_files),,\
     $(warning Unknown installed file for module '$(m)'))\
-  $(eval my_pickup_files += $(ALL_MODULES.$(m).PICKUP_FILES))\
-  $(foreach i,$(filter $(TARGET_OUT_ROOT)/%,$(ALL_MODULES.$(m).INSTALLED)),\
-    $(eval my_suffix := $(suffix $(i))) \
-    $(if $(my_suffix),\
-      $(eval my_patt := $(TARGET_OUT_ROOT)/%$(my_suffix)),\
-      $(eval my_patt := $(TARGET_OUT_ROOT)/%$(notdir $(i))))\
-    $(eval b := $(filter $(my_patt),$(ALL_MODULES.$(m).BUILT)))\
-    $(if $(filter 1,$(words $(b))),\
-      $(eval my_built_modules += $(b))\
+  $(eval my_pickup_files += $(_pickup_files))\
+  $(foreach i, $(_built_files),\
+    $(eval bui_ins := $(subst :,$(space),$(i)))\
+    $(eval ins := $(word 2,$(bui_ins)))\
+    $(if $(filter $(TARGET_OUT_ROOT)/%,$(ins)),\
+      $(eval bui := $(word 1,$(bui_ins)))\
+      $(eval my_built_modules += $(bui))\
       $(eval my_copy_dest := $(patsubst data/%,DATA/%,\
-                               $(patsubst system/%,SYSTEM/%,\
-                                 $(patsubst $(PRODUCT_OUT)/%,%,$(i)))))\
-      $(eval my_copy_pairs += $(b):$(my_staging_dir)/$(my_copy_dest)),\
-      $(warning Unexpected module built file '$(b)' for module '$(m)'))\
+                               $(patsubst system/%,DATA/%,\
+                                 $(patsubst $(PRODUCT_OUT)/%,%,$(ins)))))\
+      $(eval my_copy_pairs += $(bui):$(my_staging_dir)/$(my_copy_dest)))\
   ))
 
 my_package_zip := $(my_staging_dir)/$(my_package_name).zip
diff --git a/core/tasks/vendor_module_check.mk b/core/tasks/vendor_module_check.mk
index 99d3d9e..793dd16 100644
--- a/core/tasks/vendor_module_check.mk
+++ b/core/tasks/vendor_module_check.mk
@@ -27,11 +27,15 @@
         invensense \
         intel \
         lge \
+        moto \
         nvidia \
         nxp \
+        nxpsw \
         qcom \
+        qti \
         samsung \
         samsung_arm \
+        synaptics \
         ti \
         trusted_logic \
         widevine
@@ -39,20 +43,7 @@
 
 ifneq (,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_RESTRICT_VENDOR_FILES))
 
-_vendor_check_modules := $(sort $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES))
-$(call expand-required-modules,_vendor_check_modules,$(_vendor_check_modules))
-
-# Expand the target modules installed via LOCAL_SHARED_LIBRARIES
-# $(1): the list of modules to expand.
-define expand-required-shared-libraries
-$(eval _ersl_new_modules := $(filter $(addsuffix :%,$(1)),$(TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES)))\
-$(eval _ersl_new_modules := $(foreach p,$(_ersl_new_modules),$(word 3,$(subst :,$(space),$(p)))))\
-$(eval _ersl_new_modules := $(sort $(subst $(comma),$(space),$(_ersl_new_modules))))\
-$(eval _ersl_new_modules := $(filter-out $(_vendor_check_modules),$(_ersl_new_modules)))\
-$(if $(_ersl_new_modules),$(eval _vendor_check_modules += $(_ersl_new_modules))\
-  $(call expand-required-shared-libraries,$(_ersl_new_modules)))
-endef
-$(call expand-required-shared-libraries,$(_vendor_check_modules))
+_vendor_check_modules := $(product_MODULES)
 
 _vendor_module_owner_info :=
 # Restrict owners
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index 432391f..31c3242 100644
--- a/core/version_defaults.mk
+++ b/core/version_defaults.mk
@@ -53,7 +53,7 @@
   # intermediate builds).  During development, this number remains at the
   # SDK version the branch is based on and PLATFORM_VERSION_CODENAME holds
   # the code-name of the new development work.
-  PLATFORM_SDK_VERSION := 19
+  PLATFORM_SDK_VERSION := 20
 endif
 
 ifeq "" "$(PLATFORM_VERSION_CODENAME)"
@@ -64,7 +64,7 @@
   # This is all of the development codenames that are active.  Should be either
   # the same as PLATFORM_VERSION_CODENAME or a comma-separated list of additional
   # codenames after PLATFORM_VERSION_CODENAME.
-  PLATFORM_VERSION_ALL_CODENAMES := $(PLATFORM_VERSION_CODENAME),KKWT
+  PLATFORM_VERSION_ALL_CODENAMES := $(PLATFORM_VERSION_CODENAME)
 endif
 
 ifeq "" "$(DEFAULT_APP_TARGET_SDK)"
diff --git a/envsetup.sh b/envsetup.sh
index 45768c1..665c8f3 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -1,8 +1,9 @@
+MAKE_UTIL=(`which make`)
 function hmm() {
 cat <<EOF
 Invoke ". build/envsetup.sh" from your shell to add the following functions to your environment:
 - lunch:   lunch <product_name>-<build_variant>
-- tapas:   tapas [<App1> <App2> ...] [arm|x86|mips|armv5] [eng|userdebug|user]
+- tapas:   tapas [<App1> <App2> ...] [arm|x86|mips|armv5|arm64|x86_64|mips64] [eng|userdebug|user]
 - croot:   Changes directory to the top of the tree.
 - m:       Makes from the top of the tree.
 - mm:      Builds all of the modules in the current directory, but not their dependencies.
@@ -36,7 +37,7 @@
         return
     fi
     (\cd $T; CALLED_FROM_SETUP=true BUILD_SYSTEM=build/core \
-      make --no-print-directory -f build/core/config.mk dumpvar-abs-$1)
+      $MAKE_UTIL --no-print-directory -f build/core/config.mk dumpvar-abs-$1)
 }
 
 # Get the exact value of a build variable.
@@ -48,7 +49,7 @@
         return
     fi
     (\cd $T; CALLED_FROM_SETUP=true BUILD_SYSTEM=build/core \
-      make --no-print-directory -f build/core/config.mk dumpvar-$1)
+      $MAKE_UTIL --no-print-directory -f build/core/config.mk dumpvar-$1)
 }
 
 # check to see if the supplied product is one we can build
@@ -59,7 +60,6 @@
         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
         return
     fi
-    CALLED_FROM_SETUP=true BUILD_SYSTEM=build/core \
         TARGET_PRODUCT=$1 \
         TARGET_BUILD_VARIANT= \
         TARGET_BUILD_TYPE= \
@@ -121,6 +121,7 @@
 
     # defined in core/config.mk
     targetgccversion=$(get_build_var TARGET_GCC_VERSION)
+    targetgccversion2=$(get_build_var 2ND_TARGET_GCC_VERSION)
     export TARGET_GCC_VERSION=$targetgccversion
 
     # The gcc toolchain does not exists for windows/cygwin. In this case, do not reference it.
@@ -135,7 +136,7 @@
         arm) toolchaindir=arm/arm-linux-androideabi-$targetgccversion/bin
             ;;
         arm64) toolchaindir=aarch64/aarch64-linux-android-$targetgccversion/bin;
-               toolchaindir2=arm/arm-linux-androideabi-$targetgccversion/bin
+               toolchaindir2=arm/arm-linux-androideabi-$targetgccversion2/bin
             ;;
         mips) toolchaindir=mips/mipsel-linux-android-$targetgccversion/bin
             ;;
@@ -171,7 +172,7 @@
 
     export ANDROID_QTOOLS=$T/development/emulator/qtools
     export ANDROID_DEV_SCRIPTS=$T/development/scripts:$T/prebuilts/devtools/tools
-    export ANDROID_BUILD_PATHS=$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_QTOOLS:$ANDROID_TOOLCHAIN:$ANDROID_KERNEL_TOOLCHAIN_PATH$ANDROID_DEV_SCRIPTS:
+    export ANDROID_BUILD_PATHS=$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_QTOOLS:$ANDROID_TOOLCHAIN:$ANDROID_TOOLCHAIN_2ND_ARCH:$ANDROID_KERNEL_TOOLCHAIN_PATH$ANDROID_DEV_SCRIPTS:
 
     # If prebuilts/android-emulator/<system>/ exists, prepend it to our PATH
     # to ensure that the corresponding 'emulator' binaries are used.
@@ -187,7 +188,7 @@
             ;;
     esac
     if [ -n "$ANDROID_EMULATOR_PREBUILTS" -a -d "$ANDROID_EMULATOR_PREBUILTS" ]; then
-        ANDROID_BUILD_PATHS=$ANDROID_EMULATOR_PREBUILTS:$ANDROID_BUILD_PATHS
+        ANDROID_BUILD_PATHS=$ANDROID_BUILD_PATHS$ANDROID_EMULATOR_PREBUILTS:
         export ANDROID_EMULATOR_PREBUILTS
     fi
 
@@ -589,9 +590,9 @@
 # Run tapas with one or more app names (from LOCAL_PACKAGE_NAME)
 function tapas()
 {
-    local arch="$(echo $* | xargs -n 1 echo | \grep -E '^(arm|x86|mips|armv5)$' | xargs)"
+    local arch="$(echo $* | xargs -n 1 echo | \grep -E '^(arm|x86|mips|armv5|arm64|x86_64|mips64)$' | xargs)"
     local variant="$(echo $* | xargs -n 1 echo | \grep -E '^(user|userdebug|eng)$' | xargs)"
-    local apps="$(echo $* | xargs -n 1 echo | \grep -E -v '^(user|userdebug|eng|arm|x86|mips|armv5)$' | xargs)"
+    local apps="$(echo $* | xargs -n 1 echo | \grep -E -v '^(user|userdebug|eng|arm|x86|mips|armv5|arm64|x86_64|mips64)$' | xargs)"
 
     if [ $(echo $arch | wc -w) -gt 1 ]; then
         echo "tapas: Error: Multiple build archs supplied: $arch"
@@ -604,9 +605,12 @@
 
     local product=full
     case $arch in
-      x86)   product=full_x86;;
-      mips)  product=full_mips;;
-      armv5) product=generic_armv5;;
+      x86)    product=full_x86;;
+      mips)   product=full_mips;;
+      armv5)  product=generic_armv5;;
+      arm64)  product=aosp_arm64;;
+      x86_64) product=aosp_x86_64;;
+      mips64)  product=aosp_mips64;;
     esac
     if [ -z "$variant" ]; then
         variant=eng
@@ -950,7 +954,8 @@
             adb shell cat $TMP
         else
             # Dump stacks of native process
-            adb shell debuggerd -b $PID
+            local USE64BIT="$(is64bit $PID)"
+            adb shell debuggerd$USE64BIT -b $PID
         fi
     fi
 }
@@ -962,22 +967,18 @@
     $GDB_CMD -x "$@"
 }
 
-# process the symbolic link of /proc/$PID/exe and use the host file tool to
-# determine whether it is a 32-bit or 64-bit executable. It returns "" or "64"
-# which can be conveniently used as suffix.
+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()
 {
     local PID="$1"
     if [ "$PID" ] ; then
-        local EXE=`adb shell ls -l /proc/$PID/exe \
-                   | tr -d '\r' \
-                   | cut -d'>' -f2 \
-                   | tr -d ' ' \
-                   | cut -d'/' -f4`
-
-        local OUT_EXE_SYMBOLS=$(get_abs_build_var TARGET_OUT_EXECUTABLES_UNSTRIPPED)
-        local IS64BIT=`file $OUT_EXE_SYMBOLS/$EXE | grep "64-bit"`
-        if [ "$IS64BIT" != "" ]; then
+        if [[ "$(adb shell cat /proc/$PID/exe | xxd -l 1 -s 4 -ps)" -eq "02" ]] ; then
             echo "64"
         else
             echo ""
@@ -995,7 +996,8 @@
    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_EXE_SYMBOLS=$(get_abs_build_var TARGET_OUT_EXECUTABLES_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
@@ -1013,6 +1015,9 @@
        local EXE="$1"
        if [ "$EXE" ] ; then
            EXE=$1
+           if [[ $EXE =~ ^[^/].* ]] ; then
+               EXE="system/bin/"$EXE
+           fi
        else
            EXE="app_process"
        fi
@@ -1059,7 +1064,7 @@
        OUT_SO_SYMBOLS=$OUT_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"
+       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"
        echo >>"$OUT_ROOT/gdbclient.cmds" ""
@@ -1075,6 +1080,7 @@
        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."
@@ -1471,6 +1477,36 @@
     return $retval
 }
 
+function make()
+{
+    local start_time=$(date +"%s")
+    $MAKE_UTIL $@
+    local ret=$?
+    local end_time=$(date +"%s")
+    local tdiff=$(($end_time-$start_time))
+    local hours=$(($tdiff / 3600 ))
+    local mins=$((($tdiff % 3600) / 60))
+    local secs=$(($tdiff % 60))
+    echo
+    if [ $ret -eq 0 ] ; then
+        echo -n -e "\e[0;32m#### make completed successfully "
+    else
+        echo -n -e "\e[0;31m#### make failed to build some targets "
+    fi
+    if [ $hours -gt 0 ] ; then
+        printf "(%02g:%02g:%02g (hh:mm:ss))" $hours $mins $secs
+    elif [ $mins -gt 0 ] ; then
+        printf "(%02g:%02g (mm:ss))" $mins $secs
+    elif [ $secs -gt 0 ] ; then
+        printf "(%s seconds)" $secs
+    fi
+    echo -e " ####\e[00m"
+    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 74afa55..c67afbb 100644
--- a/libs/host/Android.mk
+++ b/libs/host/Android.mk
@@ -2,7 +2,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-	CopyFile.c
+    CopyFile.c
 
 ifeq ($(HOST_OS),cygwin)
 LOCAL_CFLAGS += -DWIN32_EXE
diff --git a/target/board/generic/BoardConfig.mk b/target/board/generic/BoardConfig.mk
index c30cc75..62303d6 100644
--- a/target/board/generic/BoardConfig.mk
+++ b/target/board/generic/BoardConfig.mk
@@ -77,13 +77,11 @@
 
 BOARD_SEPOLICY_DIRS += build/target/board/generic/sepolicy
 BOARD_SEPOLICY_UNION += \
-        adbd.te \
         bootanim.te \
         device.te \
         domain.te \
         file.te \
         file_contexts \
-        mediaserver.te \
         qemud.te \
         rild.te \
         shell.te \
diff --git a/target/board/generic/sepolicy/adbd.te b/target/board/generic/sepolicy/adbd.te
deleted file mode 100644
index f65cfb3..0000000
--- a/target/board/generic/sepolicy/adbd.te
+++ /dev/null
@@ -1 +0,0 @@
-allow adbd qemu_device:chr_file rw_file_perms;
diff --git a/target/board/generic/sepolicy/domain.te b/target/board/generic/sepolicy/domain.te
index f026100..c28ca74 100644
--- a/target/board/generic/sepolicy/domain.te
+++ b/target/board/generic/sepolicy/domain.te
@@ -1,2 +1,3 @@
 # For /sys/qemu_trace files in the emulator.
 allow domain sysfs_writable:file rw_file_perms;
+allow domain qemu_device:chr_file rw_file_perms;
diff --git a/target/board/generic/sepolicy/mediaserver.te b/target/board/generic/sepolicy/mediaserver.te
deleted file mode 100644
index 90b8cf8..0000000
--- a/target/board/generic/sepolicy/mediaserver.te
+++ /dev/null
@@ -1 +0,0 @@
-allow mediaserver qemu_device:chr_file rw_file_perms;
diff --git a/target/board/generic/sepolicy/rild.te b/target/board/generic/sepolicy/rild.te
index 5de171a..e148b6c 100644
--- a/target/board/generic/sepolicy/rild.te
+++ b/target/board/generic/sepolicy/rild.te
@@ -1,2 +1 @@
-allow rild qemu_device:chr_file rw_file_perms;
 unix_socket_connect(rild, qemud, qemud)
diff --git a/target/board/generic/sepolicy/system_server.te b/target/board/generic/sepolicy/system_server.te
index ef4ce4a..d0fb79d 100644
--- a/target/board/generic/sepolicy/system_server.te
+++ b/target/board/generic/sepolicy/system_server.te
@@ -1,2 +1 @@
 unix_socket_connect(system_server, qemud, qemud)
-allow system_server qemu_device:chr_file rw_file_perms;
diff --git a/target/board/generic_arm64/BoardConfig.mk b/target/board/generic_arm64/BoardConfig.mk
index 9d3bcc0..1493bd9 100644
--- a/target/board/generic_arm64/BoardConfig.mk
+++ b/target/board/generic_arm64/BoardConfig.mk
@@ -23,7 +23,7 @@
 
 TARGET_2ND_ARCH := arm
 TARGET_2ND_ARCH_VARIANT := armv7-a-neon
-TARGET_2ND_CPU_VARIANT := generic
+TARGET_2ND_CPU_VARIANT := cortex-a15
 TARGET_2ND_CPU_ABI := armeabi-v7a
 TARGET_2ND_CPU_ABI2 := armeabi
 
@@ -48,7 +48,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 576716800
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
diff --git a/target/board/generic_mips/BoardConfig.mk b/target/board/generic_mips/BoardConfig.mk
index e66ade1..a319ad7 100644
--- a/target/board/generic_mips/BoardConfig.mk
+++ b/target/board/generic_mips/BoardConfig.mk
@@ -50,7 +50,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 681574400
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
@@ -59,13 +59,11 @@
 
 BOARD_SEPOLICY_DIRS += build/target/board/generic/sepolicy
 BOARD_SEPOLICY_UNION += \
-        adbd.te \
         bootanim.te \
         device.te \
         domain.te \
         file.te \
         file_contexts \
-        mediaserver.te \
         qemud.te \
         rild.te \
         shell.te \
diff --git a/target/board/generic_mips64/BoardConfig.mk b/target/board/generic_mips64/BoardConfig.mk
index d879b0d..7452978 100644
--- a/target/board/generic_mips64/BoardConfig.mk
+++ b/target/board/generic_mips64/BoardConfig.mk
@@ -57,7 +57,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 576716800
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
diff --git a/target/board/generic_x86/BoardConfig.mk b/target/board/generic_x86/BoardConfig.mk
index 67f0ecf..5d091f5 100644
--- a/target/board/generic_x86/BoardConfig.mk
+++ b/target/board/generic_x86/BoardConfig.mk
@@ -35,23 +35,24 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 576716800
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
 BOARD_FLASH_BLOCK_SIZE := 512
 TARGET_USERIMAGES_SPARSE_EXT_DISABLED := true
 
-BOARD_SEPOLICY_DIRS += build/target/board/generic_x86/sepolicy
+BOARD_SEPOLICY_DIRS += \
+        build/target/board/generic/sepolicy \
+        build/target/board/generic_x86/sepolicy
+
 BOARD_SEPOLICY_UNION += \
-        adbd.te \
         device.te \
         domain.te \
         file.te \
         file_contexts \
         healthd.te \
         installd.te \
-        mediaserver.te \
         qemud.te \
         rild.te \
         shell.te \
diff --git a/target/board/generic_x86/sepolicy/adbd.te b/target/board/generic_x86/sepolicy/adbd.te
deleted file mode 100644
index f65cfb3..0000000
--- a/target/board/generic_x86/sepolicy/adbd.te
+++ /dev/null
@@ -1 +0,0 @@
-allow adbd qemu_device:chr_file rw_file_perms;
diff --git a/target/board/generic_x86/sepolicy/device.te b/target/board/generic_x86/sepolicy/device.te
deleted file mode 100644
index e4af13c..0000000
--- a/target/board/generic_x86/sepolicy/device.te
+++ /dev/null
@@ -1 +0,0 @@
-type qemu_device, dev_type;
diff --git a/target/board/generic_x86/sepolicy/domain.te b/target/board/generic_x86/sepolicy/domain.te
index c17950d..0bc8d87 100644
--- a/target/board/generic_x86/sepolicy/domain.te
+++ b/target/board/generic_x86/sepolicy/domain.te
@@ -1,3 +1 @@
-# For /sys/qemu_trace files in the emulator.
-allow domain sysfs_writable:file rw_file_perms;
 allow domain cpuctl_device:dir search;
diff --git a/target/board/generic_x86/sepolicy/file.te b/target/board/generic_x86/sepolicy/file.te
deleted file mode 100644
index 6fad80a..0000000
--- a/target/board/generic_x86/sepolicy/file.te
+++ /dev/null
@@ -1 +0,0 @@
-type qemud_socket, file_type;
diff --git a/target/board/generic_x86/sepolicy/file_contexts b/target/board/generic_x86/sepolicy/file_contexts
deleted file mode 100644
index f204cde..0000000
--- a/target/board/generic_x86/sepolicy/file_contexts
+++ /dev/null
@@ -1,4 +0,0 @@
-/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
diff --git a/target/board/generic_x86/sepolicy/mediaserver.te b/target/board/generic_x86/sepolicy/mediaserver.te
deleted file mode 100644
index 90b8cf8..0000000
--- a/target/board/generic_x86/sepolicy/mediaserver.te
+++ /dev/null
@@ -1 +0,0 @@
-allow mediaserver qemu_device:chr_file rw_file_perms;
diff --git a/target/board/generic_x86/sepolicy/qemud.te b/target/board/generic_x86/sepolicy/qemud.te
deleted file mode 100644
index 4ff02ec..0000000
--- a/target/board/generic_x86/sepolicy/qemud.te
+++ /dev/null
@@ -1,6 +0,0 @@
-# qemu support daemon
-type qemud, domain;
-type qemud_exec, exec_type, file_type;
-
-init_daemon_domain(qemud)
-unconfined_domain(qemud)
diff --git a/target/board/generic_x86/sepolicy/rild.te b/target/board/generic_x86/sepolicy/rild.te
deleted file mode 100644
index 5de171a..0000000
--- a/target/board/generic_x86/sepolicy/rild.te
+++ /dev/null
@@ -1,2 +0,0 @@
-allow rild qemu_device:chr_file rw_file_perms;
-unix_socket_connect(rild, qemud, qemud)
diff --git a/target/board/generic_x86/sepolicy/shell.te b/target/board/generic_x86/sepolicy/shell.te
deleted file mode 100644
index b246d7e..0000000
--- a/target/board/generic_x86/sepolicy/shell.te
+++ /dev/null
@@ -1 +0,0 @@
-allow shell serial_device:chr_file rw_file_perms;
diff --git a/target/board/generic_x86/sepolicy/system_server.te b/target/board/generic_x86/sepolicy/system_server.te
index 9bfe5fe..5d98a14 100644
--- a/target/board/generic_x86/sepolicy/system_server.te
+++ b/target/board/generic_x86/sepolicy/system_server.te
@@ -1,3 +1 @@
 allow system_server self:process execmem;
-unix_socket_connect(system_server, qemud, qemud)
-allow system_server qemu_device:chr_file rw_file_perms;
diff --git a/target/board/generic_x86_64/BoardConfig.mk b/target/board/generic_x86_64/BoardConfig.mk
index 876caf3..c597f7d 100755
--- a/target/board/generic_x86_64/BoardConfig.mk
+++ b/target/board/generic_x86_64/BoardConfig.mk
@@ -41,7 +41,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 880803840 # 840M
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
diff --git a/target/board/generic_x86_64/device.mk b/target/board/generic_x86_64/device.mk
index aa0e5a4..b5b0faf 100755
--- a/target/board/generic_x86_64/device.mk
+++ b/target/board/generic_x86_64/device.mk
@@ -28,8 +28,7 @@
     frameworks/av/media/libstagefright/data/media_codecs_google_audio.xml:system/etc/media_codecs_google_audio.xml \
     frameworks/av/media/libstagefright/data/media_codecs_google_telephony.xml:system/etc/media_codecs_google_telephony.xml \
     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 \
-    system/core/rootdir/init.zygote64.rc:root/init.zygote64.rc
+    device/generic/goldfish/camera/media_codecs.xml:system/etc/media_codecs.xml
 
 PRODUCT_PACKAGES := \
     audio.primary.goldfish \
diff --git a/target/product/AndroidProducts.mk b/target/product/AndroidProducts.mk
index a714f1f..bce5bb5 100644
--- a/target/product/AndroidProducts.mk
+++ b/target/product/AndroidProducts.mk
@@ -42,7 +42,8 @@
     $(LOCAL_DIR)/aosp_mips.mk \
     $(LOCAL_DIR)/full_mips.mk \
     $(LOCAL_DIR)/aosp_arm64.mk \
-    $(LOCAL_DIR)/aosp_mips64.mk
+    $(LOCAL_DIR)/aosp_mips64.mk \
+    $(LOCAL_DIR)/aosp_x86_64.mk
 else
 PRODUCT_MAKEFILES := \
     $(LOCAL_DIR)/core.mk \
diff --git a/target/product/base.mk b/target/product/base.mk
index 6dd77a4..981f965 100644
--- a/target/product/base.mk
+++ b/target/product/base.mk
@@ -42,7 +42,8 @@
     libandroid_servers \
     libaudioeffect_jni \
     libaudioflinger \
-    libaudiopolicy \
+    libaudiopolicyservice \
+    libaudiopolicymanager \
     libbundlewrapper \
     libcamera_client \
     libcameraservice \
@@ -58,8 +59,10 @@
     libmedia_jni \
     libmediaplayerservice \
     libmtp \
+    libnetd_client \
     libnetlink \
     libnetutils \
+    libpdfium \
     libreference-ril \
     libreverbwrapper \
     libril \
@@ -68,6 +71,8 @@
     libskia \
     libsonivox \
     libsoundpool \
+    libsoundtrigger \
+    libsoundtriggerservice \
     libsqlite \
     libstagefright \
     libstagefright_amrnb_common \
diff --git a/target/product/core.mk b/target/product/core.mk
index a88e92f..875d08c 100644
--- a/target/product/core.mk
+++ b/target/product/core.mk
@@ -48,7 +48,9 @@
     QuickSearchBox \
     Settings \
     SharedStorageBackup \
+    Telecomm \
     TeleService \
-    VpnDialogs
+    VpnDialogs \
+    MmsService
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core_base.mk)
diff --git a/target/product/core_64_bit.mk b/target/product/core_64_bit.mk
index 971b6bd..76e2a36 100644
--- a/target/product/core_64_bit.mk
+++ b/target/product/core_64_bit.mk
@@ -22,12 +22,12 @@
 # For now this will allow 64-bit apps, but still compile all apps with JNI
 # for 32-bit only.
 
-# Copy the 32-bit primary, 64-bit secondary zygote startup script
-PRODUCT_COPY_FILES += system/core/rootdir/init.zygote32_64.rc:root/init.zygote32_64.rc
+# Copy the 64-bit primary, 32-bit secondary zygote startup script
+PRODUCT_COPY_FILES += system/core/rootdir/init.zygote64_32.rc:root/init.zygote64_32.rc
 
-# Set the zygote property to select the 32-bit primary, 64-bit secondary script
+# Set the zygote property to select the 64-bit primary, 32-bit secondary script
 # This line must be parsed before the one in core_minimal.mk
-PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.zygote=zygote32_64
+PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.zygote=zygote64_32
 
 TARGET_SUPPORTS_32_BIT_APPS := true
 TARGET_SUPPORTS_64_BIT_APPS := true
diff --git a/target/product/core_base.mk b/target/product/core_base.mk
index d63e39f..f14e53d 100644
--- a/target/product/core_base.mk
+++ b/target/product/core_base.mk
@@ -32,10 +32,8 @@
     libaudioutils \
     libfilterpack_imageproc \
     libgabi++ \
-    libkeystore \
     libmdnssd \
     libnfc_ndef \
-    libportable \
     libpowermanager \
     libspeexresampler \
     libstagefright_soft_aacdec \
@@ -48,6 +46,7 @@
     libstagefright_soft_gsmdec \
     libstagefright_soft_h264dec \
     libstagefright_soft_h264enc \
+    libstagefright_soft_hevcdec \
     libstagefright_soft_mp3dec \
     libstagefright_soft_mpeg4dec \
     libstagefright_soft_mpeg4enc \
@@ -58,28 +57,7 @@
     libvariablespeed \
     libwebrtc_audio_preprocessing \
     mdnsd \
-    mms-common \
     requestsync \
-    telephony-common \
-    voip-common \
     wifi-service
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core_minimal.mk)
-# Override the PRODUCT_BOOT_JARS set in core_minimal.mk. The order matters.
-PRODUCT_BOOT_JARS := \
-    core \
-    conscrypt \
-    okhttp \
-    core-junit \
-    bouncycastle \
-    ext \
-    framework \
-    framework2 \
-    telephony-common \
-    voip-common \
-    mms-common \
-    android.policy \
-    services \
-    apache-xml \
-    webviewchromium \
-    wifi-service
diff --git a/target/product/core_minimal.mk b/target/product/core_minimal.mk
index 7fbdee6..368e468 100644
--- a/target/product/core_minimal.mk
+++ b/target/product/core_minimal.mk
@@ -36,9 +36,11 @@
     com.android.media.remotedisplay \
     com.android.media.remotedisplay.xml \
     drmserver \
+    ethernet-service \
     framework-res \
     idmap \
     installd \
+    ims-common \
     ip \
     ip-up-vpn \
     ip6tables \
@@ -52,20 +54,29 @@
     libdrmframework \
     libdrmframework_jni \
     libfilterfw \
+    libkeystore \
     libsqlite_jni \
     libwilhelm \
     logd \
     make_ext4fs \
+    e2fsck \
+    resize2fs \
+    mms-common \
     screencap \
     sensorservice \
+    telephony-common \
     uiautomator \
     uncrypt \
+    voip-common \
     webview \
     wifi-service
 
+PRODUCT_COPY_FILES += \
+    frameworks/native/data/etc/android.software.webview.xml:system/etc/permissions/android.software.webview.xml
+
 # The order of PRODUCT_BOOT_JARS matters.
 PRODUCT_BOOT_JARS := \
-    core \
+    core-libart \
     conscrypt \
     okhttp \
     core-junit \
@@ -73,14 +84,18 @@
     ext \
     framework \
     framework2 \
+    telephony-common \
+    voip-common \
+    ims-common \
+    mms-common \
     android.policy \
     services \
     apache-xml \
+    ethernet-service \
     webviewchromium \
     wifi-service
 
 PRODUCT_RUNTIMES := runtime_libart_default
-PRODUCT_RUNTIMES += runtime_libdvm
 
 PRODUCT_DEFAULT_PROPERTY_OVERRIDES += \
     ro.zygote=zygote32
diff --git a/target/product/core_tiny.mk b/target/product/core_tiny.mk
index 9c40206..8dda1a0 100644
--- a/target/product/core_tiny.mk
+++ b/target/product/core_tiny.mk
@@ -18,6 +18,7 @@
 
 PRODUCT_PACKAGES := \
     Bluetooth \
+    CalendarProvider \
     ContactsProvider \
     CertInstaller \
     FusedLocation \
@@ -57,17 +58,27 @@
     libOpenSLES \
     libdownmix \
     libfilterfw \
+    libkeystore \
     libsqlite_jni \
     libwilhelm \
+    libdrmframework_jni \
+    libdrmframework \
     make_ext4fs \
+    e2fsck \
+    resize2fs \
+    nullwebview \
     screencap \
     sensorservice \
     uiautomator \
-    uncrypt
+    uncrypt \
+    telephony-common \
+    voip-common \
+    logd \
+    mms-common
 
 # The order matters
 PRODUCT_BOOT_JARS := \
-    core \
+    core-libart \
     conscrypt \
     okhttp \
     core-junit \
@@ -75,11 +86,15 @@
     ext \
     framework \
     framework2 \
+    telephony-common \
+    voip-common \
+    mms-common \
     android.policy \
     services \
-    apache-xml
+    apache-xml \
+    nullwebview
 
-PRODUCT_RUNTIMES := runtime_libdvm_default
+PRODUCT_RUNTIMES := runtime_libart_default
 
 PRODUCT_PROPERTY_OVERRIDES += \
     ro.carrier=unknown
diff --git a/target/product/embedded.mk b/target/product/embedded.mk
index 8764b86..b60c948 100644
--- a/target/product/embedded.mk
+++ b/target/product/embedded.mk
@@ -39,7 +39,6 @@
     libGLESv2 \
     libbinder \
     libc \
-    libctest \
     libcutils \
     libdl \
     libgui \
@@ -68,7 +67,8 @@
     servicemanager \
     sh \
     surfaceflinger \
-    toolbox
+    toolbox \
+    libsigchain
 
 # SELinux packages
 PRODUCT_PACKAGES += \
@@ -76,7 +76,9 @@
     file_contexts \
     seapp_contexts \
     property_contexts \
-    mac_permissions.xml
+    mac_permissions.xml \
+    selinux_version \
+    service_contexts
 
 
 PRODUCT_COPY_FILES += \
diff --git a/target/product/generic_no_telephony.mk b/target/product/generic_no_telephony.mk
index b4f2a7b..3ee6de8 100644
--- a/target/product/generic_no_telephony.mk
+++ b/target/product/generic_no_telephony.mk
@@ -65,7 +65,6 @@
 $(call inherit-product-if-exists, external/google-fonts/coming-soon/fonts.mk)
 $(call inherit-product-if-exists, external/noto-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/naver-fonts/fonts.mk)
-$(call inherit-product-if-exists, external/sil-fonts/fonts.mk)
 $(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
 $(call inherit-product-if-exists, frameworks/webview/chromium/chromium.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)
diff --git a/target/product/runtime_common.mk b/target/product/runtime_common.mk
index faa6fe8..9ae182a 100644
--- a/target/product/runtime_common.mk
+++ b/target/product/runtime_common.mk
@@ -39,20 +39,3 @@
     libssl \
     libz \
     okhttp
-
-# host-only dependencies
-ifeq ($(WITH_HOST_DALVIK),true)
-    PRODUCT_PACKAGES += \
-        apache-xml-hostdex \
-        bouncycastle-hostdex \
-        conscrypt-hostdex \
-        dalvik \
-        libcrypto-host \
-        libexpat-host \
-        libicui18n-host \
-        libicuuc-host \
-        libjavacore \
-        libssl-host \
-        libz-host \
-        okhttp-hostdex
-endif
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
index 1a7c925..de4cf17 100644
--- a/target/product/runtime_libart.mk
+++ b/target/product/runtime_libart.mk
@@ -22,10 +22,4 @@
         dex2oat \
         oatdump
 
-# host-only dependencies
-ifeq ($(WITH_HOST_DALVIK),true)
-    PRODUCT_PACKAGES += \
-        core-libart-hostdex
-endif
-
 include $(SRC_TARGET_DIR)/product/runtime_common.mk
diff --git a/target/product/runtime_libdvm.mk b/target/product/runtime_libdvm.mk
index e7647b8..638d7d7 100644
--- a/target/product/runtime_libdvm.mk
+++ b/target/product/runtime_libdvm.mk
@@ -21,10 +21,4 @@
     libdvm \
     dexopt
 
-# host-only dependencies
-ifeq ($(WITH_HOST_DALVIK),true)
-    PRODUCT_PACKAGES += \
-        core-hostdex
-endif
-
 include $(SRC_TARGET_DIR)/product/runtime_common.mk
diff --git a/target/product/sdk.mk b/target/product/sdk.mk
index 2e576c1..d4f2355 100644
--- a/target/product/sdk.mk
+++ b/target/product/sdk.mk
@@ -83,7 +83,6 @@
 $(call inherit-product-if-exists, external/google-fonts/coming-soon/fonts.mk)
 $(call inherit-product-if-exists, external/noto-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/naver-fonts/fonts.mk)
-$(call inherit-product-if-exists, external/sil-fonts/fonts.mk)
 $(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
 $(call inherit-product-if-exists, frameworks/webview/chromium/chromium.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)
diff --git a/target/product/sdk_arm64.mk b/target/product/sdk_arm64.mk
index 582a779..9aa58b3 100644
--- a/target/product/sdk_arm64.mk
+++ b/target/product/sdk_arm64.mk
@@ -19,6 +19,7 @@
 # build quite specifically for the emulator, and might not be
 # entirely appropriate to inherit from for on-device configurations.
 
+$(call inherit-product, $(SRC_TARGET_DIR)/product/core_64_bit.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/sdk.mk)
 
 # Overrides
diff --git a/target/product/sdk_mips64.mk b/target/product/sdk_mips64.mk
index c00de06..c46eaed 100644
--- a/target/product/sdk_mips64.mk
+++ b/target/product/sdk_mips64.mk
@@ -19,6 +19,7 @@
 # build quite specifically for the emulator, and might not be
 # entirely appropriate to inherit from for on-device configurations.
 
+$(call inherit-product, $(SRC_TARGET_DIR)/product/core_64_bit.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/sdk.mk)
 
 # Overrides
diff --git a/target/product/sdk_x86_64.mk b/target/product/sdk_x86_64.mk
index 3816cf9..62f2dbb 100644
--- a/target/product/sdk_x86_64.mk
+++ b/target/product/sdk_x86_64.mk
@@ -19,6 +19,7 @@
 # build quite specifically for the emulator, and might not be
 # entirely appropriate to inherit from for on-device configurations.
 
+$(call inherit-product, $(SRC_TARGET_DIR)/product/core_64_bit.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/sdk.mk)
 
 # Overrides
diff --git a/target/product/verity.mk b/target/product/verity.mk
index 4a1ca5e..b14eaa4 100644
--- a/target/product/verity.mk
+++ b/target/product/verity.mk
@@ -18,6 +18,7 @@
 
 PRODUCT_SUPPORTS_VERITY := true
 PRODUCT_VERITY_SIGNING_KEY := build/target/product/security/verity_private_dev_key
+PRODUCT_VERITY_MOUNTPOINT := system
 
 PRODUCT_PACKAGES += \
         verity_key
diff --git a/tools/acp/Android.mk b/tools/acp/Android.mk
index 5e0e2e4..33c5567 100644
--- a/tools/acp/Android.mk
+++ b/tools/acp/Android.mk
@@ -6,7 +6,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := \
-	acp.c
+    acp.c
 
 ifeq ($(HOST_OS),cygwin)
 LOCAL_CFLAGS += -DWIN32_EXE
@@ -23,4 +23,3 @@
 LOCAL_ACP_UNAVAILABLE := true
 
 include $(BUILD_HOST_EXECUTABLE)
-
diff --git a/tools/droiddoc/templates-sac/assets/images/sac_logo.png b/tools/droiddoc/templates-sac/assets/images/sac_logo.png
index 54b9a4c..6dc126a 100644
--- a/tools/droiddoc/templates-sac/assets/images/sac_logo.png
+++ b/tools/droiddoc/templates-sac/assets/images/sac_logo.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/css/default.css b/tools/droiddoc/templates-sdk/assets/css/default.css
index aa30c8a..3b647c2 100644
--- a/tools/droiddoc/templates-sdk/assets/css/default.css
+++ b/tools/droiddoc/templates-sdk/assets/css/default.css
@@ -98,7 +98,8 @@
 #devdoc-nav.fixed {
   position: fixed;
   margin:0;
-  top: 20px; }
+  top: 65px; /* sticky-header height + 20px gutter */
+}
 
 #devdoc-nav span.small {
   font-size:12px;
@@ -157,12 +158,6 @@
 .layout-content-row {
   display: inline-block;
   margin-bottom: 10px; }
-  .layout-content-row:after {
-    content: ".";
-    display: block;
-    height: 0;
-    clear: both;
-    visibility: hidden; }
   * html .layout-content-row {
     height: 1px; }
 
@@ -429,20 +424,19 @@
 /* content header */
 .content-header {
   height: 30px;
-  margin:20px 0 25px;
-  padding:0 0 10px;}
+  margin:36px 0 23px;  /* same as h1 */
+  padding:0 0 10px;}  /* same as h1 */
 .content-header.just-links {
   margin-bottom:0;
   padding-bottom:0;}
 
 .content-header h1 {
-  color:#000;
   margin:0;
-  border-bottom:0;
   padding:0;
+  width: 700px;
 }
 .content-header > div:first-child {
-  height:55px; /* set fixed height for the header div to ensure the
+  height:1px; /* set fixed height for the header div to ensure the
                   next/prev links align with toc on training classes */
 }
 
@@ -450,7 +444,7 @@
   border-top: 1px solid #ccc;
   margin-top: 10px;
   padding-top:10px;
-  height: 30px; }
+  width:100%; }
 
 .content-footer .col-9 {
   margin-left:0;
@@ -461,20 +455,30 @@
 .content-footer.wrap {
   width:940px;
 }
+.content-footer .plus-container {
+  margin:5px 0 0;
+  text-align:right;
+  float:right;
+}
+
+a.back-link {
+    text-decoration: none;
+    text-transform: uppercase;
+}
 
 .paging-links {
-  position: relative; }
+  position: relative;
+  height:30px; }
   .paging-links a {
     position: absolute; }
   .paging-links a,
   .training-nav-top a {
-    font-size: 14px;
-    line-height: 30px;
     color: #555555;
     text-decoration: none;
     text-transform: uppercase; }
     .paging-links .prev-page-link:before,
-    .training-nav-top .prev-page-link:before {
+    .training-nav-top .prev-page-link:before,
+    a.back-link:before {
       content: '';
       background: transparent url(../images/styles/disclosure_left.png) no-repeat scroll 50% 50%;
       width: 10px;
@@ -488,7 +492,7 @@
     .paging-links .prev-page-link {
       left: -15px; }
     .paging-links .next-page-link {
-      right: 0px; }
+      right: 0; }
     .next-page-link:after,
     .start-class-link:after,
     .start-course-link:after,
@@ -505,6 +509,9 @@
     .next-page-link.inline:after {
       content: none; }
 
+  .content-footer .paging-links .next-page-link {
+    left:0;
+  }
 
   .training-nav-top a {
     display:block;
@@ -543,7 +550,6 @@
 
   .paging-links a.start-class-link {
     width:100%;
-    text-align:right;
   }
 
   /* list of classes on course landing page */
@@ -622,19 +628,6 @@
     display:none !important;
   }
 
-  .content-footer.next-class {
-    display:block;
-    border:0;
-    margin-top:0;
-    padding-top:0;
-  }
-
-  .content-footer.next-class a.next-class-link {
-    display:block;
-    float:right;
-    text-transform:uppercase;
-  }
-
 
 
   /* inner-doc tabs w/ title */
@@ -712,6 +705,7 @@
     color: #33b5e5;
     border-bottom-color: #33b5e5; } }
 
+h1:target,
 h2:target,
 h3:target {
     -webkit-animation-name: glowheader;
@@ -893,7 +887,7 @@
   .framed-nexus4-port-216 img {
     width: 216px;
     height: 360px; }
-    
+
 .framed-nexus5-port-span-5 {
   background: transparent url(../images/styles/device_nexus5_blank_port_span5.png) no-repeat
   scroll top left;
@@ -928,6 +922,47 @@
   height: 384px;
 }
 
+/* wear device frames */
+
+.framed-wear-square {
+  background: transparent url(../images/styles/device_wear_square.png) no-repeat scroll top left;
+  background-size: 302px 302px;
+  height:222px;
+  width:222px;
+  padding:40px;
+  overflow:hidden;
+}
+
+.framed-wear-square-small {
+  background: transparent url(../images/styles/device_wear_square_small.png) no-repeat scroll top left;
+  background-size: 169px 200px;
+  height:147px;
+  width:147px;
+  padding:27px 11px;
+  overflow:hidden;
+}
+
+#jd-content
+.framed-wear-square img {
+  height:222px;
+  width: 222px;
+  padding:0;
+  margin:0;
+}
+
+#jd-content
+.framed-wear-square-small img {
+  height:147px;
+  width: 147px;
+  padding:0;
+  margin:0;
+}
+
+
+
+
+
+
 /* landing page disclosures */
 .landing-page-link {
   text-decoration: none;
@@ -1101,12 +1136,13 @@
 }
 h1 {
     color:#333;
-    font-size: 22px;
-    margin: 20px 0 20px;
+    font-size: 34px;
+    margin: 36px 0 27px;
     padding:0 0 10px;
+    font-weight:300;
 }
 h1, h2 {
-    line-height: 32px;
+    line-height: 30px;
 }
 h1.short {
   margin-right:320px;
@@ -1119,21 +1155,24 @@
 }
 h2 {
     color:#333;
-    font-size: 20px;
-    margin: 20px 0 20px;
+    font-size: 26px;
+    margin: 32px 0 20px;
     padding:0;
+    font-weight:300;
 }
 h3 {
     color:#333;
-    font-size: 18px;
+    font-size: 21px;
+    font-weight:400;
+    margin:21px 0 14px 0;
 }
 h3, h4 {
-    color:#333;
-    line-height: 20px;
-    margin: 10px 0;
+    line-height: 21px;
 }
 h4 {
-  font-size: 16px;
+  font-size: 18px;
+  margin: 12px 0;
+  font-weight:500;
 }
 h5 {
   font-size: 14px;
@@ -1146,7 +1185,7 @@
 }
 hr { /* applied to the bottom of h2 elements */
   height: 1px;
-  margin: 5px 0 20px;
+  margin: 3px 0 12px;
   border: 0;
   background: #ccc;
 }
@@ -1215,6 +1254,13 @@
   color: #33B5E5;
   text-decoration: none;
 }
+a.white {
+  color: #fff;
+  text-decoration:underline;
+}
+a.white:hover, a.white:active {
+  color: #ccc !important;
+}
 strong, b {
   font-weight:bold;
   color: #222;
@@ -1248,6 +1294,7 @@
 tr:first-of-type th:first-of-type:empty {
     visibility: hidden;
 }
+
 /* --------------------------------------------------------------------------
 Footer
 */
@@ -1378,8 +1425,7 @@
   .training-nav-top, .training-nav-bottom,
   #doc-col .content-footer,
   .nav-x, .nav-y,
-  .paging-links,
-  a.totop {
+  .paging-links {
       display: none !important;
   }
 
@@ -1504,7 +1550,8 @@
 Header, Login, Nav-X, Search
 */
 #header {
-  padding: 2.2em 0 0.2em 0;
+  margin: 0;
+  padding: 0;
 }
 #header:before, #header:after {
   content: "";
@@ -1522,6 +1569,9 @@
     color: #333;
     font-size: 16px;
 }
+.about a.selected {
+    color: #9933CC;
+}
 .design a.selected {
     color: #33b5e5;
 }
@@ -1833,6 +1883,11 @@
   margin:0 0 0 20px;
 }
 
+.training-nav-top {
+  position:relative;
+  top:73px;
+}
+
 .training-nav-bottom {
   padding:0 0 20px;
 }
@@ -1841,12 +1896,12 @@
 #qv-wrapper {
   float:right;
   clear:right;
-  margin:0 0 0 20px; /* negative top-margin to counter the content-header bottom margin */
-  padding:0 0 20px;
+  margin:6px 0 0 30px; /* negative top-margin to counter the content-header bottom margin */
+  padding:0 0 30px;
 }
 
 #tb-wrapper {
-  margin:-29px 0 0 20px; /* negative top-margin to counter the content-header bottom margin */
+  margin:51px 0 0 20px; /* negative top-margin to counter the content-header bottom margin */
 }
 
 #tb,
@@ -1930,6 +1985,10 @@
   margin:0 15px 10px 35px;
 }
 
+#tb p {
+  margin:0 15px 10px;
+}
+
 #qv ol {
   list-style:none;
   margin:0 15px 15px;
@@ -1958,28 +2017,12 @@
 
 /* related resources blocks in checklists */
 
-.rel-resources {
-  margin:10px 0px;
-  border:1px solid #ccc;
-  background-color:rgba(0, 0, 0, 0.027451);
-  border:1px solid #ccc;
-  font-size:13px;
-  color:#6f6f6f;
-}
+/* related resources sections that have dynamic content */
 
-.rel-resources ul {
-padding: .5em 1em 0 1em;
-}
 
-.rel-resources a {
-font-weight:500;
-}
 
-.rel-resources h3 {
-  margin:4px 15px 0px 15px;
-  font-size:13px;
-  font-weight:600;
-  text-transform:uppercase;
+h3.rel-resources {
+margin:1.25em auto;
 }
 
 /* --------------------------------------------------------------------------
@@ -2359,6 +2402,13 @@
 #doc-col {
   margin-right:0;
 }
+
+/* Uncomment this for preview release watermark
+#doc-col {
+  background: url('../images/preview.png') repeat;
+}
+*/
+
 #doc-content-container {
   margin-left: 291px
 }
@@ -2760,7 +2810,7 @@
 .caption {
   margin: 0.5em 0 2em 0;
   color: #000;
-  font-size: 11.5px; 
+  font-size: 11.5px;
 }
 
 .nolist, .nolist ul, .nolist ol {
@@ -2884,26 +2934,6 @@
   margin:0 0 10px;
 }
 
-#devdoc-nav a.totop {
-  display:block;
-  top:0;
-  width:inherit;
-  background: transparent url(../images/styles/gototop.png) no-repeat scroll 50% 50%;
-  text-indent:-9999em;
-}
-#devdoc-nav a.totop {
-  position:fixed;
-  display:none;
-}
-#devdoc-nav a.totop:hover {
-  background-color:#33B5E5;
-}
-
-.content-footer a.totop {
-  text-transform:uppercase;
-  line-height:30px;
-}
-
 .expandable {
   height:34px;
   padding-left:20px;
@@ -3013,6 +3043,34 @@
 }
 
 
+/* for IDE instruction toggle (Studio/Eclipse/Other) */
+select.ide {
+  background: transparent;
+  border: 1px solid #bbb;
+  border-left: 0;
+  border-right: 0;
+  margin: 10px 0;
+  padding: 10px 0;
+  color:#666;
+}
+select.ide,
+select.ide option {
+  font-family: inherit;
+  font-size:16px;
+  font-weight:500;
+}
+/* hide all except eclipse by default */
+.select-ide.studio,
+.select-ide.other {
+  display:none;
+}
+/* ... unless eclipse also includes one of the others */
+.select-ide.eclipse.studio,
+.select-ide.eclipse.other {
+  display:block;
+}
+
+
 /* -----------------------------------------------
 good/bad example containers
 */
@@ -3365,28 +3423,37 @@
 }
 
 #jd-header {
-  padding: 0 0 5px;
-  margin: 20px 0 10px;
-  font-size:13px;
+  padding: 0 0 12px;
+  margin: 20px 0 12px;
+  font-size:12px;
+  padding-bottom:12px;
   border-bottom:solid 1px #ccc;
 }
 
 #jd-header h1 {
   margin:0;
-  padding:0;
+  padding:0 0 6px 0;
 }
 
+/* not sure if this is needed in the ref docs, disabling for now
+.jd-descr h2 {
+  margin:16px 0;
+}
+*/
+
 /* page-top-right container for reference pages (holds
 links to summary tables) */
 #api-info-block {
-  font-size:13px;
+  font-size:12px;
   margin:20px 0 0;
   padding:0 10px 6px;
   font-weight:normal;
   float:right;
   text-align:right;
   color:#999;
-  max-width:70%;
+  max-width:80%;
+  font-size: 12px;
+  line-height:14px;
 }
 
 #api-info-block div.api-level {
@@ -3403,7 +3470,8 @@
   border-spacing:0;
   margin:0;
   padding:0;
-  font-size:13px;
+  font-size:12px;
+  line-height:14px;
   background-color:transparent;
 }
 .jd-inheritance-table tr td {
@@ -3968,13 +4036,175 @@
   z-index:100;
 }
 
+
+
+
+
+/************ STICKY NAV BAR ******************/
+
+#header-wrapper {
+  background: #f9f9f9;
+  margin: 0 -10px 0 -10px;
+  padding: 31px 10px 0px 10px;
+  position: relative;
+}
+#header-wrapper #nav-x div.wrap {
+  max-width: 940px;
+  height: 38px;
+}
+#header-wrapper #nav-x ul.nav-x li {
+  margin-right: 36px !important;
+  margin-top: 5px;
+  margin-bottom: 0px;
+  height: 30px;
+}
+#header-wrapper #nav-x > div.wrap ul.nav-x li.active  {
+  color: #669900;
+  border-bottom: 3px solid #669900;
+}
+#header-wrapper #nav-x > div.wrap ul.nav-x li.active a {
+  color: #669900;
+}
+#header-wrapper #nav-x > div.wrap ul.nav-x a {
+  font-size: 14.5px;
+}
+#header-wrapper .developer-console-btn {
+  float: right;
+  background: #fefefe;
+  border-radius: 4px;
+  padding: 8px 14px;
+  box-shadow: 1px 1px 0px #7a7a7a;
+  font-size: 14px;
+  margin-top: -6px;
+  cursor: pointer;
+  color: #464646;
+  margin-right: 20px;
+}
+/* not currently used */
+#header-wrapper .shadow {
+  width: 1034px;
+  height: 4px;
+  position: absolute;
+  left: 50%;
+  margin-left: -517px;
+  bottom: -4px;
+  background-image: url(../images/header-shadow.png);
+}
+
+#context {
+  clear: both;
+  padding-top: 14px;
+}
+#context .breadcrumb {
+  float: left;
+  margin-bottom: 10px;
+}
+#context .util {
+  float: right;
+  margin-right: 20px;
+}
+
+.breadcrumb {
+  list-style: none;
+  margin: 0;
+  padding: 0;
+  position: relative;
+}
+.breadcrumb li {
+  float: left;
+  padding: 0 20px 0 0;
+  color: #000;
+  white-space: nowrap;
+}
+.breadcrumb li a {
+  color: #000;
+}
+.breadcrumb li:after {
+  content: url(../images/breadcrumb.png);
+  position: relative;
+  top: 1px;
+  left: 10px;
+  width: 5px;
+  height: 10px;
+}
+.breadcrumb li.current {
+  font-weight: 700;
+}
+.breadcrumb li.current:after {
+  display: none;
+}
+
+/* Sticky Nav overrides */
+.sticky-menu {
+  position: fixed;
+  width: 940px;
+  height: 0px;
+  z-index: 51;
+  top: 12px;
+}
+#sticky-header {
+  display: none;
+  padding: 0 10px;
+  position: fixed;
+  background: #f9f9f9;
+  top: 0px;
+  left: 0px;
+  right: 0px;
+  height: 45px;
+  box-shadow: 0px 1px 5px rgba(0, 0, 0, 0.1);
+  border-bottom: 1px solid #a5c43a;
+  z-index: 50;
+}
+#sticky-header.design {
+  border-bottom: 1px solid #33b5e5;
+}
+#sticky-header.develop {
+  border-bottom: 1px solid #F80;
+}
+#sticky-header.distribute {
+  border-bottom: 1px solid #9C0;
+}
+#sticky-header.about {
+  border-bottom: 1px solid #9933CC;
+}
+#sticky-header > div {
+  overflow: hidden;
+  *zoom: 1;
+  width: 940px;
+  margin: 0 auto;
+  clear: both;
+  padding-top: 9px;
+}
+#sticky-header > div .logo {
+  float: left;
+  width: 26px;
+  height: 25px;
+  background: url(../images/dac_logo.png);
+  background-image: -webkit-image-set(url(../images/dac_logo.png) 1x, url(../images/dac_logo@2x.png) 2x);
+  z-index: 52;
+  position: relative;
+}
+#sticky-header > div .top {
+  float: left;
+  width: 38px;
+  height: 38px;
+  position: relative;
+  background: url(../images/styles/gototop.png);
+  z-index: 52;
+}
+#sticky-header > div .breadcrumb {
+  float: left;
+  padding: 0 0 0 10px;
+  border-left: 1px solid #d2d2d2;
+  line-height: 24px;
+  font-size: 14px;
+  position: relative;
+  top: 0px;
+  z-index: 52;
 }
 
 
-
-
-
-
+}
 
 
 
@@ -4014,7 +4244,6 @@
 }
 
 .logo a {
-  width:123px;
   float:left;
 }
 
@@ -4027,11 +4256,13 @@
 }
 
 
-#header .logo-wear {
+#header-wrap .logo.landing-logo {
   width:220px;
   margin:0;
+  padding:0;
+  margin-bottom:22px;
 }
-#header .logo-wear img {
+#header-wrap .logo.landing-logo img {
   padding:0 0 0 10px;
 }
 
@@ -4103,7 +4334,7 @@
 #quicknav {
  float:none;
  clear:both;
- margin-left:180px;
+ margin-left:0;
  margin-top:-30px;
  display:none;
  overflow:hidden;
@@ -4118,6 +4349,10 @@
   padding:0;
 }
 
+#quicknav ul li.about {
+  border-top:1px solid #9933CC;
+}
+
 #quicknav ul li.design {
   border-top:1px solid #33b5e5;
 }
@@ -4447,7 +4682,9 @@
 }
 
 
-
+#landing h1 {
+  margin:17px 0 20px 0 !important;
+}
 
 a.download-sdk {
     float:right;
@@ -4458,11 +4695,11 @@
 }
 
 #nav-x {
-  padding-top: 14px;
+  padding-top: 13px;
 }
 
 #nav-x .wrap {
-  min-height:34px;
+  min-height:32px;
 }
 
 #nav-x .wrap,
@@ -4618,14 +4855,14 @@
 
 /* Slideshow */
 .slideshow-develop {
-  height: 300px;
+  height: 316px;
   width: 940px;
   position: relative;
   overflow:hidden;
 }
 .slideshow-develop .frame {
   width: 940px;
-  height: 300px;
+  height: 316px;
 }
 .slideshow-develop img.play {
   max-width:350px;
@@ -4657,6 +4894,7 @@
   padding:0;
   margin-bottom:10px;
   border:none;
+  font-size:24px;
 }
 .slideshow-develop .item {
   height: 300px;
@@ -4804,53 +5042,6 @@
 
 
 
-/************ DISTRIBUTE HOMEPAGE ***************/
-
-.marquee {
-  width: 760px;
-}
-.marquee .main-img {
-  float: left;
-  margin-top: 20px;
-  width: 490px;
-}
-.marquee .copy {
-  width: 270px;
-  float: left;
-  margin-top: 30px;
-}
-.distribute-features {
-  margin: 0;
-}
-.distribute-features ul {
-  margin: 0;
-}
-.distribute-features ul li {
-  list-style: none;
-  float: left;
-  border-top: 1px solid #9C0;
-  width: 220px;
-  margin-right: 50px;
-}
-.distribute-features ul li.last {
-  margin-right: 0px;
-}
-
-.distribute-features .distribute-link li a {
-  color:red !important;
-}
-
-.distribute-features .distribute-link li a,
-.distribute-features .distribute-link li a:active {
-  color:#555 !important;
-}
-
-.distribute-features .distribute-link li a:hover,
-.distribute-features .distribute-link li a:hover * {
-  color:#7AA1B0 !important;
-}
-
-
 /************ DEVELOP TOPIC CONTAINERS ************/
 
 .landing-banner,
@@ -4876,7 +5067,8 @@
   margin-bottom:0;
 }
 .landing-banner h1 {
-  margin-top:0;
+  margin-top:16px;
+  padding-bottom:24px;
 }
 .landing-docs,
 .landing-banner {
@@ -5028,3 +5220,2113 @@
 .fullpage #footer {
   margin-top: -40px;
 }
+
+/************ DISTRIBUTE PAGES ******************/
+
+.article-detail #body-content {
+  padding-top: 10px;
+}
+
+/* A container for grid sets with uppercase h3 and rule */
+.dynamic-grid h3 {
+  font-size:14px;
+  line-height:21px;
+  color:#555;
+  text-transform:uppercase;
+  border-bottom:1px solid #CCC;
+  padding:8px 0 0 1px;
+  margin-bottom:14px;
+  clear:both;
+}
+
+.top-right-float {
+  float: right;
+}
+
+.clearfloat {
+  float: none;
+  clear: both;
+}
+
+.border-img {
+  border: 1px solid #CCC;
+}
+
+.center-img {
+  margin: auto;
+  text-align: center;
+}
+.center-img img {
+  margin-bottom: 15px;
+}
+
+.figure img, .border-img {
+  margin-bottom: 15px;
+}
+
+/************ RESOURCE CARDS ******************/
+
+/* Resource cards, 12, 13, 16-col */
+
+/* Basic card-styling with shadow */
+.resource-card {
+  border-radius: 1px;
+  box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.12);
+  background: #fefefe;
+}
+
+/* Styling for background image including tinting and section icons in stacks */
+.card-bg {
+  display: block;
+  position: absolute;
+  vertical-align: top;
+  width: 100%;
+  left: 0;
+  top: 0;
+  background-size: cover;
+  background-repeat: no-repeat;
+  background-position: center;
+  background-image: url(../images/resource-card-default-android.jpg);
+}
+.card-bg:after {
+  content: "";
+  display: block;
+  height: 100%;
+  width: 100%;
+  opacity: 1;
+  background: rgba(0, 0, 0, 0.2);
+  -webkit-transition: opacity 0.5s;
+  -moz-transition: opacity 0.5s;
+  -o-transition: opacity 0.5s;
+  transition: opacity 0.5s;
+}
+.static .card-bg:after {
+  display:none;
+}
+.card-bg .card-section-icon {
+  position: absolute;
+  top: 50%;
+  width: 100%;
+  margin-top: -35px;
+  text-align: center;
+  padding-top: 65px;
+  z-index: 100;
+}
+.card-bg .card-section-icon .icon {
+  position: absolute;
+  left: 50%;
+  margin-left: -28px;
+  top: 0px;
+  width: 56px;
+  height: 56px;
+  background-repeat: no-repeat;
+  background-position: 50% 50%;
+  background-image: url(../images/stack-icon.png);
+}
+.card-bg .card-section-icon .section {
+  text-transform: uppercase;
+  color: white;
+  font-size: 14px;
+}
+
+.card-info {
+  position: absolute;
+  -webkit-box-sizing: border-box;
+  -moz-box-sizing: border-box;
+  box-sizing: border-box;
+  top: 0;
+  right: 0;
+  bottom: 0;
+  left: 0;
+  overflow: hidden;
+  background: #fefefe;
+  padding: 4px 12px 6px 12px;
+}
+.card-info .section {
+  text-transform: uppercase;
+  color: #898989;
+  font-size: 12px;
+  margin-bottom: 1px;
+}
+.card-info .title {
+  color: #363636;
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  padding-bottom: 5px;
+  margin-bottom: -2px;
+  font-size: 16px;
+}
+.card-info .description {
+  overflow: hidden;
+}
+.card-info .description .text {
+  color: #464646;
+  font: 13px/15px Roboto Condensed;
+  overflow: hidden;
+  width:100%;
+}
+.card-info .description .util {
+  position: absolute;
+  right: 5px;
+  bottom: 70px; /*-2px;*/
+  opacity: 0;
+  -webkit-transition: opacity 0.5s;
+  -moz-transition: opacity 0.5s;
+  -o-transition: opacity 0.5s;
+  transition: opacity 0.5s;
+}
+.card-info.empty-desc .title {
+  white-space: normal;
+  overflow: visible;
+}
+.card-info.empty-desc .description {
+  display: none;
+}
+/* Truncate card summaries at bounding box and
+ * and apply ellipsis at lower right */
+.ellipsis {
+  overflow: hidden;
+  float:right;
+  line-height: 15px;
+  width:100%;
+}
+.resource-card-6x6 .card-info .description .teddddddxt {
+ float:left;
+  position:relative;
+  margin-left:0;
+}
+.ellipsis:before {
+  content:"";
+  float: left;
+  width: 5px;
+  height:100%;
+}
+.ellipsis > *:first-child.text {
+  float: right;
+  width: 100%  !important;
+  margin-left: -5px;
+}
+.ellipsis:after {
+  content: "\02026";
+  height:17px;
+  padding-bottom:4px;
+
+  box-sizing: content-box;
+  -webkit-box-sizing: content-box;
+  -moz-box-sizing: content-box;
+
+  float: right; position: relative;
+  top: -16px; left: 100%;
+  width: 4em; margin-left: -4em;
+  padding-right: 5px;
+
+  background: -webkit-gradient(linear, left top, right top,
+    from(rgba(255, 255, 255, 0)), to(white), color-stop(65%, white));
+  background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 65%, white);
+  background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 65%, white);
+  background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 65%, white);
+  background: linear-gradient(to right, rgba(255, 255, 255, 0), white 65%, white);
+}
+.ellipsis:after {
+  font-style: normal; color: #aaa;
+  font-size:13px;
+  text-align: right;
+}
+
+/* Flow Layout */
+.resource-flow-layout {
+  display: inline-block;
+}
+.resource-flow-layout .resource-card, .resource-flow-layout .resource-card-stack {
+  float: left;
+  position: relative;
+}
+.resource-flow-layout .resource-card-stack > .resource-card {
+  margin-right: 0px !important;
+}
+.resource-flow-layout:after {
+  content: ".";
+  display: block;
+  height: 0;
+  position:relative;
+  clear: both;
+  visibility: hidden;
+}
+.resource-card:hover {
+  cursor: pointer;
+}
+.static .resource-card:hover {
+  cursor: auto;
+}
+.resource-card:hover .card-bg:after {
+  opacity: 0;
+}
+/* disabled to make way for fade/ellipsis truncation,
+   and the plusone moves up.
+.resource-card:hover .card-info .description .text {
+  padding-right: 70px;
+} */
+.resource-card:hover .card-info .description .util {
+  opacity: 1;
+}
+
+/* Carousel Layout */
+/* Carousel styles for landing page */
+.resource-carousel-layout {
+  margin: 20px 0 20px 0;
+  position: relative;
+  overflow: hidden;
+}
+.resource-carousel-layout .slideshow-prev, .resource-carousel-layout .slideshow-next {
+  display: none;
+}
+.resource-carousel-layout .pagination {
+  bottom: 0px;
+}
+.resource-carousel-layout .frame li {
+  position: relative;
+}
+.resource-carousel-layout .frame li .card-bg {
+  height: 300px;
+}
+.resource-carousel-layout .frame li .card-info {
+  padding: 7px 15px 0px 15px;
+  top: 300px;
+}
+.resource-carousel-layout .frame li .card-info .section {
+  font-size: 13px;
+  margin-bottom: 7px;
+}
+.resource-carousel-layout .frame li .card-info .title {
+  font-size: 25px;
+  margin-bottom: 2px;
+}
+.resource-carousel-layout .frame li .card-info .description {
+  font-family: 15px/16px Roboto Condensed, sans-serif;
+}
+.resource-carousel-layout .frame li .card-info .description .text {
+  height: 40px;
+}
+.resource-carousel-layout .frame li .card-info .description .util {
+  bottom:97px;
+  right:4px;
+}
+
+/* Stack Layout */
+.resource-stack-layout {
+  display: inline-block;
+}
+.resource-stack-layout .resource-card-stack {
+  float: left;
+  position: relative;
+}
+.resource-stack-layout .resource-card {
+  margin-bottom: 20px;
+  display: block;
+  position: relative;
+}
+.resource-stack-layout .section-card-menu > .card-info .section, .resource-stack-layout .section-card > .card-info .title {
+  /*text-transform: uppercase;*/
+  color: #898989;
+  font-size: 17px;
+  line-height: 24px;
+  margin-bottom: 6px;
+}
+.resource-stack-layout .section-card {
+  height: 284px;
+}
+.resource-stack-layout .section-card > .card-bg {
+  height: 192px;
+}
+.resource-stack-layout .section-card > .card-info {
+  padding: 4px 12px 6px 12px;
+  top: 192px;
+}
+.resource-stack-layout .section-card > .card-info .section {
+  display: none;
+}
+.resource-stack-layout .section-card > .card-info .title {
+  font-size: 17px;
+  border-bottom: 1px solid #959595;
+  padding-bottom: 0px;
+}
+.resource-stack-layout .section-card > .card-info .description {
+  font-size: 13px;
+  line-height: 15px;
+}
+.resource-stack-layout .section-card > .card-info .description .text {
+  height: 30px;
+}
+.resource-stack-layout .related-card {
+  height: 90px;
+}
+.resource-stack-layout .related-card > .card-bg {
+  left: 0;
+  top: 0;
+  width: 90px;
+  height: 100%;
+  position: absolute;
+  display: block;
+}
+.resource-stack-layout .related-card > .card-info {
+  left: 90px;
+  padding: 4px 12px 4px 12px;
+}
+.resource-stack-layout .related-card > .card-info .section {
+  font-size: 12px;
+  margin-bottom: 1px;
+  display: none;
+}
+.resource-stack-layout .related-card > .card-info .title {
+  font-size: 16px;
+  margin-bottom: -2px;
+  white-space: normal;
+  overflow: visible;
+  text-overflow: ellipsis;
+}
+.resource-stack-layout .related-card > .card-info .title:after {
+  content: url(../images/link-out.png);
+  display: block;
+}
+.resource-stack-layout .related-card > .card-info .description {
+  display: none;
+}
+.resource-stack-layout .section-card-menu {
+  /* Flexible height */
+  display: block;
+  height: auto;
+  width: auto;
+}
+.resource-stack-layout .section-card-menu .card-bg {
+  height: 155px;
+  /* Flexible height */
+  position: relative;
+  display: inline-block;
+  vertical-align: top;
+}
+.resource-stack-layout .section-card-menu .card-info {
+  padding: 4px 12px 0px 12px;
+  /* Flexible height */
+  position: relative;
+  left: auto;
+  top: auto;
+  right: auto;
+  bottom: auto;
+}
+.resource-stack-layout .section-card-menu .card-info ul {
+  list-style: none;
+  margin: 0;
+}
+.resource-stack-layout .section-card-menu .card-info ul li {
+  list-style: none;
+  margin: 0;
+  padding: 15px 0;
+  border-top-width: 1px;
+  border-top-style: solid;
+  border-top-color: #959595;
+}
+.resource-stack-layout .section-card-menu .card-info ul li a, .resource-stack-layout .section-card-menu .card-info ul li a:focus, .resource-stack-layout .section-card-menu .card-info ul li a:link, .resource-stack-layout .section-card-menu .card-info ul li a:visited, .resource-stack-layout .section-card-menu .card-info ul li a:active, .resource-stack-layout .section-card-menu .card-info ul li a:hover {
+  color: #363636 !important;
+}
+.resource-stack-layout .section-card-menu .card-info ul li:first-child {
+  border-top: none;
+}
+.resource-stack-layout .section-card-menu .card-info ul li:hover .title:after {
+  opacity: 1;
+  -webkit-transition: opacity 0.5s;
+  -moz-transition: opacity 0.5s;
+  -o-transition: opacity 0.5s;
+  transition: opacity 0.5s;
+}
+.resource-stack-layout .section-card-menu .card-info ul li:hover .description {
+  max-height: 30px;
+  opacity: 1;
+  -webkit-transition: max-height 0.5s, opacity 1s;
+  -moz-transition: max-height 0.5s, opacity 1s;
+  -o-transition: max-height 0.5s, opacity 1s;
+  transition: max-height 0.5s, opacity 1s;
+}
+.resource-stack-layout .section-card-menu .card-info .title {
+  font-size: 16px;
+  margin-bottom: -2px;
+  position: relative;
+}
+.resource-stack-layout .section-card-menu .card-info .title:after {
+  background: url(../images/stack-arrow-right.png);
+  content: '';
+  opacity: 0;
+  -webkit-transition: opacity 0.25s;
+  -moz-transition: opacity 0.25s;
+  -o-transition: opacity 0.25s;
+  transition: opacity 0.25s;
+  position: absolute;
+  right: 0px;
+  top: 3px;
+  width: 10px;
+  height: 15px;
+}
+.resource-stack-layout .section-card-menu .card-info .title.more {
+  text-transform: uppercase;
+  color: #898989;
+  display: inline-block;
+}
+.resource-stack-layout .section-card-menu .card-info .title.more:after {
+  background: url(../images/stack-arrow-right.png);
+  content: '';
+  display: block;
+  position: absolute;
+  right: -20px;
+  top: 3px;
+  width: 10px;
+  height: 15px;
+}
+.resource-stack-layout .section-card-menu .card-info .description {
+  max-height: 0px;
+  opacity: 0;
+  overflow: hidden;
+  font-size: 13px;
+  line-height: 15px;
+  /* Hover off */
+  -webkit-transition: max-height 0.5s, opacity 0.5s;
+  -moz-transition: max-height 0.5s, opacity 0.5s;
+  -o-transition: max-height 0.5s, opacity 0.5s;
+  transition: max-height 0.5s, opacity 0.5s;
+}
+.resource-stack-layout .section-card-menu .card-info .description .text {
+  height: 30px;
+}
+.resource-stack-layout:after {
+  content: ".";
+  display: block;
+  height: 0;
+  clear: both;
+  visibility: hidden;
+}
+
+/* Generate the flow layout styles for a 3-column 16-col span */
+.resource-flow-layout.col-16 {
+  margin: 0 -14px 0 0;
+  width: 954px;
+}
+.resource-flow-layout.col-16 .resource-card, .resource-flow-layout.col-16 .resource-card-stack {
+  margin: 0 14px 20px 0;
+}
+.resource-flow-layout.col-16 .resource-card-row-stack-last {
+  margin-bottom: 0px !important;
+}
+.resource-flow-layout.col-16 .resource-card-col-stack-last {
+  margin-bottom: 0px !important;
+}
+.resource-flow-layout.col-16 .resource-card-3x6 {
+  width: 145px;
+  height: 284px;
+}
+.resource-flow-layout.col-16 .resource-card-3x12 {
+  width: 145px;
+  height: 588px;
+}
+.resource-flow-layout.col-16 .resource-card-3x18 {
+  width: 145px;
+  height: 892px;
+}
+.resource-flow-layout.col-16 .resource-card-6x6 {
+  width: 304px;
+  height: 284px;
+}
+.resource-flow-layout.col-16 .resource-card-6x12 {
+  width: 304px;
+  height: 588px;
+}
+.resource-flow-layout.col-16 .resource-card-6x18 {
+  width: 304px;
+  height: 892px;
+}
+.resource-flow-layout.col-16 .resource-card-9x6 {
+  width: 463px;
+  height: 284px;
+}
+.resource-flow-layout.col-16 .resource-card-9x12 {
+  width: 463px;
+  height: 588px;
+}
+.resource-flow-layout.col-16 .resource-card-9x18 {
+  width: 463px;
+  height: 892px;
+}
+.resource-flow-layout.col-16 .resource-card-12x6 {
+  width: 622px;
+  height: 284px;
+}
+.resource-flow-layout.col-16 .resource-card-12x12 {
+  width: 622px;
+  height: 588px;
+}
+.resource-flow-layout.col-16 .resource-card-12x18 {
+  width: 622px;
+  height: 892px;
+}
+.resource-flow-layout.col-16 .resource-card-15x6 {
+  width: 781px;
+  height: 284px;
+}
+.resource-flow-layout.col-16 .resource-card-15x12 {
+  width: 781px;
+  height: 588px;
+}
+.resource-flow-layout.col-16 .resource-card-15x18 {
+  width: 781px;
+  height: 892px;
+}
+.resource-flow-layout.col-16 .resource-card-18x6 {
+  width: 940px;
+  height: 284px;
+}
+.resource-flow-layout.col-16 .resource-card-18x12 {
+  width: 940px;
+  height: 420px;
+}
+.resource-flow-layout.col-16 .resource-card-18x18 {
+  width: 940px;
+  height: 892px;
+}
+.resource-flow-layout.col-16 .resource-card-3x2 {
+  width: 145px;
+  height: 95px;
+}
+.resource-flow-layout.col-16 .resource-card-3x2x3 {
+  width: 145px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-16 .resource-card-3x3 {
+  width: 145px;
+  height: 142px;
+}
+.resource-flow-layout.col-16 .resource-card-3x3x2 {
+  width: 145px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-16 .resource-card-6x2 {
+  width: 304px;
+  height: 95px;
+}
+.resource-flow-layout.col-16 .resource-card-6x2x3 {
+  width: 304px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-16 .resource-card-6x3 {
+  width: 304px;
+  height: 142px;
+}
+.resource-flow-layout.col-16 .resource-card-6x3x2 {
+  width: 304px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-16 .resource-card-9x2 {
+  width: 463px;
+  height: 95px;
+}
+.resource-flow-layout.col-16 .resource-card-9x2x3 {
+  width: 463px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-16 .resource-card-9x3 {
+  width: 463px;
+  height: 142px;
+}
+.resource-flow-layout.col-16 .resource-card-9x3x2 {
+  width: 463px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-16 .resource-card-12x2 {
+  width: 622px;
+  height: 95px;
+}
+.resource-flow-layout.col-16 .resource-card-12x2x3 {
+  width: 622px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-16 .resource-card-12x3 {
+  width: 622px;
+  height: 142px;
+}
+.resource-flow-layout.col-16 .resource-card-12x3x2 {
+  width: 622px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-16 .resource-card-15x2 {
+  width: 781px;
+  height: 95px;
+}
+.resource-flow-layout.col-16 .resource-card-15x2x3 {
+  width: 781px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-16 .resource-card-15x3 {
+  width: 781px;
+  height: 142px;
+}
+.resource-flow-layout.col-16 .resource-card-15x3x2 {
+  width: 781px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-16 .resource-card-18x2 {
+  width: 940px;
+  height: 95px;
+}
+.resource-flow-layout.col-16 .resource-card-18x2x3 {
+  width: 940px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-16 .resource-card-18x3 {
+  width: 940px;
+  height: 142px;
+}
+.resource-flow-layout.col-16 .resource-card-18x3x2 {
+  width: 940px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+
+/* Generate the flow layout styles for a 3-column 16-col span */
+.resource-flow-layout.col-12 {
+  margin: 0 -14px 0 0;
+  width: 714px;
+}
+
+.resource-flow-layout.col-12 .resource-card, .resource-flow-layout.col-12 .resource-card-stack {
+  margin: 0 14px 20px 0;
+}
+.resource-flow-layout.col-12 .resource-card-row-stack-last {
+  margin-bottom: 0px !important;
+}
+.resource-flow-layout.col-12 .resource-card-col-stack-last {
+  margin-bottom: 0px !important;
+}
+.resource-flow-layout.col-12 .resource-card-3x6 {
+  width: 105px;
+  height: 284px;
+}
+.resource-flow-layout.col-12 .resource-card-3x12 {
+  width: 105px;
+  height: 588px;
+}
+.resource-flow-layout.col-12 .resource-card-3x18 {
+  width: 105px;
+  height: 892px;
+}
+.resource-flow-layout.col-12 .resource-card-6x6 {
+  width: 224px;
+  height: 284px;
+}
+.resource-flow-layout.col-12 .resource-card-6x12 {
+  width: 224px;
+  height: 588px;
+}
+.resource-flow-layout.col-12 .resource-card-6x18 {
+  width: 224px;
+  height: 892px;
+}
+.resource-flow-layout.col-12 .resource-card-9x6 {
+  width: 343px;
+  height: 284px;
+}
+.resource-flow-layout.col-12 .resource-card-9x12 {
+  width: 343px;
+  height: 588px;
+}
+.resource-flow-layout.col-12 .resource-card-9x18 {
+  width: 343px;
+  height: 892px;
+}
+.resource-flow-layout.col-12 .resource-card-12x6 {
+  width: 462px;
+  height: 284px;
+}
+.resource-flow-layout.col-12 .resource-card-12x12 {
+  width: 462px;
+  height: 588px;
+}
+.resource-flow-layout.col-12 .resource-card-12x18 {
+  width: 462px;
+  height: 892px;
+}
+.resource-flow-layout.col-12 .resource-card-15x6 {
+  width: 581px;
+  height: 284px;
+}
+.resource-flow-layout.col-12 .resource-card-15x12 {
+  width: 581px;
+  height: 588px;
+}
+.resource-flow-layout.col-12 .resource-card-15x18 {
+  width: 581px;
+  height: 892px;
+}
+.resource-flow-layout.col-12 .resource-card-18x6 {
+  width: 700px;
+  height: 284px;
+}
+.resource-flow-layout.col-12 .resource-card-18x12 {
+  width: 700px;
+  height: 420px;
+}
+.resource-flow-layout.col-12 .resource-card-18x18 {
+  width: 700px;
+  height: 892px;
+}
+.resource-flow-layout.col-12 .resource-card-3x2 {
+  width: 105px;
+  height: 95px;
+}
+.resource-flow-layout.col-12 .resource-card-3x2x3 {
+  width: 105px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-12 .resource-card-3x3 {
+  width: 105px;
+  height: 142px;
+}
+.resource-flow-layout.col-12 .resource-card-3x3x2 {
+  width: 105px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-12 .resource-card-6x2 {
+  width: 224px;
+  height: 95px;
+}
+.resource-flow-layout.col-12 .resource-card-6x2x3 {
+  width: 224px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-12 .resource-card-6x3 {
+  width: 224px;
+  height: 142px;
+}
+.resource-flow-layout.col-12 .resource-card-6x3x2 {
+  width: 224px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-12 .resource-card-9x2 {
+  width: 343px;
+  height: 95px;
+}
+.resource-flow-layout.col-12 .resource-card-9x2x3 {
+  width: 343px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-12 .resource-card-9x3 {
+  width: 343px;
+  height: 142px;
+}
+.resource-flow-layout.col-12 .resource-card-9x3x2 {
+  width: 343px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-12 .resource-card-12x2 {
+  width: 462px;
+  height: 95px;
+}
+.resource-flow-layout.col-12 .resource-card-12x2x3 {
+  width: 462px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-12 .resource-card-12x3 {
+  width: 462px;
+  height: 142px;
+}
+.resource-flow-layout.col-12 .resource-card-12x3x2 {
+  width: 462px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-12 .resource-card-15x2 {
+  width: 581px;
+  height: 95px;
+}
+.resource-flow-layout.col-12 .resource-card-15x2x3 {
+  width: 581px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-12 .resource-card-15x3 {
+  width: 581px;
+  height: 142px;
+}
+.resource-flow-layout.col-12 .resource-card-15x3x2 {
+  width: 581px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-12 .resource-card-18x2 {
+  width: 700px;
+  height: 95px;
+}
+.resource-flow-layout.col-12 .resource-card-18x2x3 {
+  width: 700px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-12 .resource-card-18x3 {
+  width: 700px;
+  height: 142px;
+}
+.resource-flow-layout.col-12 .resource-card-18x3x2 {
+  width: 700px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+
+/* Generate the flow layout styles for a 3-column 13-col span */
+
+.resource-flow-layout.col-13 {
+  margin: 0 -14px 0 0;
+  width: 774px;
+}
+.resource-flow-layout.col-13 .resource-card, .resource-flow-layout.col-13 .resource-card-stack {
+  margin: 0 14px 20px 0;
+}
+.resource-flow-layout.col-13 .resource-card-row-stack-last {
+  margin-bottom: 0px !important;
+}
+.resource-flow-layout.col-13 .resource-card-col-stack-last {
+  margin-bottom: 0px !important;
+}
+.resource-flow-layout.col-13 .resource-card-3x6 {
+  width: 115px;
+  height: 284px;
+}
+.resource-flow-layout.col-13 .resource-card-3x12 {
+  width: 115px;
+  height: 588px;
+}
+.resource-flow-layout.col-13 .resource-card-3x18 {
+  width: 115px;
+  height: 892px;
+}
+.resource-flow-layout.col-13 .resource-card-6x6 {
+  width: 244px;
+  height: 284px;
+}
+.resource-flow-layout.col-13 .resource-card-6x12 {
+  width: 244px;
+  height: 588px;
+}
+.resource-flow-layout.col-13 .resource-card-6x18 {
+  width: 244px;
+  height: 892px;
+}
+.resource-flow-layout.col-13 .resource-card-9x6 {
+  width: 373px;
+  height: 284px;
+}
+.resource-flow-layout.col-13 .resource-card-9x12 {
+  width: 373px;
+  height: 588px;
+}
+.resource-flow-layout.col-13 .resource-card-9x18 {
+  width: 373px;
+  height: 892px;
+}
+.resource-flow-layout.col-13 .resource-card-12x6 {
+  width: 502px;
+  height: 284px;
+}
+.resource-flow-layout.col-13 .resource-card-12x12 {
+  width: 502px;
+  height: 588px;
+}
+.resource-flow-layout.col-13 .resource-card-12x18 {
+  width: 502px;
+  height: 892px;
+}
+.resource-flow-layout.col-13 .resource-card-15x6 {
+  width: 631px;
+  height: 284px;
+}
+.resource-flow-layout.col-13 .resource-card-15x12 {
+  width: 631px;
+  height: 588px;
+}
+.resource-flow-layout.col-13 .resource-card-15x18 {
+  width: 631px;
+  height: 892px;
+}
+.resource-flow-layout.col-13 .resource-card-18x6 {
+  width: 760px;
+  height: 284px;
+}
+.resource-flow-layout.col-13 .resource-card-18x12 {
+  width: 760px;
+  height: 420px;
+}
+.resource-flow-layout.col-13 .resource-card-18x18 {
+  width: 760px;
+  height: 892px;
+}
+.resource-flow-layout.col-13 .resource-card-3x2 {
+  width: 115px;
+  height: 95px;
+}
+.resource-flow-layout.col-13 .resource-card-3x2x3 {
+  width: 115px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-13 .resource-card-3x3 {
+  width: 115px;
+  height: 142px;
+}
+.resource-flow-layout.col-13 .resource-card-3x3x2 {
+  width: 115px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-13 .resource-card-6x2 {
+  width: 244px;
+  height: 95px;
+}
+.resource-flow-layout.col-13 .resource-card-6x2x3 {
+  width: 244px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-13 .resource-card-6x3 {
+  width: 244px;
+  height: 142px;
+}
+.resource-flow-layout.col-13 .resource-card-6x3x2 {
+  width: 244px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-13 .resource-card-9x2 {
+  width: 373px;
+  height: 95px;
+}
+.resource-flow-layout.col-13 .resource-card-9x2x3 {
+  width: 373px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-13 .resource-card-9x3 {
+  width: 373px;
+  height: 142px;
+}
+.resource-flow-layout.col-13 .resource-card-9x3x2 {
+  width: 373px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-13 .resource-card-12x2 {
+  width: 502px;
+  height: 95px;
+}
+.resource-flow-layout.col-13 .resource-card-12x2x3 {
+  width: 502px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-13 .resource-card-12x3 {
+  width: 502px;
+  height: 142px;
+}
+.resource-flow-layout.col-13 .resource-card-12x3x2 {
+  width: 502px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-13 .resource-card-15x2 {
+  width: 631px;
+  height: 95px;
+}
+.resource-flow-layout.col-13 .resource-card-15x2x3 {
+  width: 631px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-13 .resource-card-15x3 {
+  width: 631px;
+  height: 142px;
+}
+.resource-flow-layout.col-13 .resource-card-15x3x2 {
+  width: 631px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+.resource-flow-layout.col-13 .resource-card-18x2 {
+  width: 760px;
+  height: 95px;
+}
+.resource-flow-layout.col-13 .resource-card-18x2x3 {
+  width: 760px;
+  height: 90px;
+  margin-bottom: 7px;
+}
+.resource-flow-layout.col-13 .resource-card-18x3 {
+  width: 760px;
+  height: 142px;
+}
+.resource-flow-layout.col-13 .resource-card-18x3x2 {
+  width: 760px;
+  height: 138px;
+  margin-bottom: 8px;
+}
+
+/*
+  The following are styles for cards in the flowlayout above, styled by the number of rows they span
+*/
+/* Single row items, might be simpler to just apply a class */
+.resource-card-3x6 > .card-bg, .resource-card-6x6 > .card-bg, .resource-card-9x6 > .card-bg, .resource-card-12x6 > .card-bg, .resource-card-15x6 > .card-bg, .resource-card-18x6 > .card-bg {
+  height: 192px;
+}
+.resource-card-3x6 > .card-info, .resource-card-6x6 > .card-info, .resource-card-9x6 > .card-info, .resource-card-12x6 > .card-info, .resource-card-15x6 > .card-info, .resource-card-18x6 > .card-info {
+  padding: 4px 12px 6px 12px;
+  top: 192px;
+}
+.resource-card-3x6 > .card-info .section, .resource-card-6x6 > .card-info .section, .resource-card-9x6 > .card-info .section, .resource-card-12x6 > .card-info .section, .resource-card-15x6 > .card-info .section, .resource-card-18x6 > .card-info .section {
+  font-size: 12px;
+  margin-bottom: 1px;
+}
+.resource-card-3x6 > .card-info .title, .resource-card-6x6 > .card-info .title, .resource-card-9x6 > .card-info .title, .resource-card-12x6 > .card-info .title, .resource-card-15x6 > .card-info .title, .resource-card-18x6 > .card-info .title {
+  font-size: 16px;
+  margin-bottom: -2px;
+}
+.resource-card-3x6 > .card-info .description, .resource-card-6x6 > .card-info .description, .resource-card-9x6 > .card-info .description, .resource-card-12x6 > .card-info .description, .resource-card-15x6 > .card-info .description, .resource-card-18x6 > .card-info .description {
+  font-size: 13px;
+  line-height: 15px;
+}
+.resource-card-3x6 > .card-info .description .text, .resource-card-6x6 > .card-info .description .text, .resource-card-9x6 > .card-info .description .text, .resource-card-12x6 > .card-info .description .text, .resource-card-15x6 > .card-info .description .text, .resource-card-18x6 > .card-info .description .text {
+  height: 30px;
+}
+
+/* Double row items */
+.resource-card-3x12 > .card-bg, .resource-card-6x12 > .card-bg, .resource-card-9x12 > .card-bg, .resource-card-12x12 > .card-bg, .resource-card-15x12 > .card-bg, .resource-card-18x12 > .card-bg {
+  height: 320px;
+}
+.resource-card-3x12 > .card-info, .resource-card-6x12 > .card-info, .resource-card-9x12 > .card-info, .resource-card-12x12 > .card-info, .resource-card-15x12 > .card-info, .resource-card-18x12 > .card-info {
+  padding: 4px 12px 6px 12px;
+  top: 320px;
+}
+.resource-card-3x12 > .card-info .section, .resource-card-6x12 > .card-info .section, .resource-card-9x12 > .card-info .section, .resource-card-12x12 > .card-info .section, .resource-card-15x12 > .card-info .section, .resource-card-18x12 > .card-info .section {
+  font-size: 12px;
+  margin-bottom: 1px;
+}
+.resource-card-3x12 > .card-info .title, .resource-card-6x12 > .card-info .title, .resource-card-9x12 > .card-info .title, .resource-card-12x12 > .card-info .title, .resource-card-15x12 > .card-info .title, .resource-card-18x12 > .card-info .title {
+  font-size: 16px;
+  margin-bottom: -2px;
+  white-space: normal;
+}
+.resource-card-3x12 > .card-info .description, .resource-card-6x12 > .card-info .description, .resource-card-9x12 > .card-info .description, .resource-card-12x12 > .card-info .description, .resource-card-15x12 > .card-info .description, .resource-card-18x12 > .card-info .description {
+  font-size: 13px;
+  line-height: 15px;
+}
+
+/* 1/3 row items */
+.resource-card-3x2 > .card-bg, .resource-card-6x2 > .card-bg, .resource-card-9x2 > .card-bg, .resource-card-12x2 > .card-bg, .resource-card-15x2 > .card-bg, .resource-card-18x2 > .card-bg {
+  left: 0;
+  top: 0;
+  width: 90px;
+  height: 100%;
+  position: absolute;
+  display: block;
+}
+.resource-card-3x2 > .card-info, .resource-card-6x2 > .card-info, .resource-card-9x2 > .card-info, .resource-card-12x2 > .card-info, .resource-card-15x2 > .card-info, .resource-card-18x2 > .card-info {
+  left: 90px;
+  padding: 4px 12px 4px 12px;
+  height: 80px;
+  overflow: hidden;
+}
+.resource-card-3x2 > .card-info .section, .resource-card-6x2 > .card-info .section, .resource-card-6x3 > .card-info .section, .resource-card-9x2 > .card-info .section, .resource-card-12x2 > .card-info .section, .resource-card-15x2 > .card-info .section, .resource-card-18x2 > .card-info .section {
+  font-size: 12px;
+  margin-bottom: 1px;
+  /* display: none; */
+}
+.resource-card-3x2 > .card-info .title, .resource-card-6x2 > .card-info .title, .resource-card-9x2 > .card-info .title, .resource-card-12x2 > .card-info .title, .resource-card-15x2 > .card-info .title, .resource-card-18x2 > .card-info .title {
+  font-size: 16px;
+  margin-bottom: -2px;
+  white-space: normal;
+  overflow: visible;
+  text-overflow: ellipsis;
+}
+.resource-card-3x2 > .card-info .title:after, .resource-card-6x2 > .card-info .title:after, .resource-card-9x2 > .card-info .title:after, .resource-card-12x2 > .card-info .title:after, .resource-card-15x2 > .card-info .title:after, .resource-card-18x2 > .card-info .title:after {
+  /* content: url(../images/link-out.png); */
+  display: block;
+}
+.resource-card-3x2 > .card-info .description, .resource-card-6x2 > .card-info .description, .resource-card-9x2 > .card-info .description, .resource-card-12x2 > .card-info .description, .resource-card-15x2 > .card-info .description, .resource-card-18x2 > .card-info .description {
+  display: none;
+}
+
+
+/* Override to show the description instead of the content section */
+.no-section .resource-card-3x2 > .card-info .section,
+.no-section .resource-card-6x2 > .card-info .section {
+  display: none;
+}
+.no-section .resource-card-3x2 > .card-info .description,
+.no-section .resource-card-6x2 > .card-info .description {
+  display: block;
+}
+
+/* 1/2 row items */
+.resource-card-3x3 > .card-bg, .resource-card-6x3 > .card-bg, .resource-card-9x3 > .card-bg, .resource-card-12x3 > .card-bg, .resource-card-15x3 > .card-bg, .resource-card-18x3 > .card-bg {
+  left: 0;
+  top: 0;
+  width: 90px;
+  height: 100%;
+  position: absolute;
+  display: block;
+}
+.resource-card-3x3 > .card-info, .resource-card-6x3 > .card-info, .resource-card-9x3 > .card-info, .resource-card-12x3 > .card-info, .resource-card-15x3 > .card-info, .resource-card-18x3 > .card-info {
+  left: 90px;
+  padding: 4px 12px 0px 12px;
+}
+.resource-card-3x3 > .card-info .section, .resource-card-6x3 > .card-info .section, .resource-card-9x3 > .card-info .section, .resource-card-12x3 > .card-info .section, .resource-card-15x3 > .card-info .section, .resource-card-18x3 > .card-info .section {
+  font-size: 12px;
+  margin-bottom: 1px;
+  display: none;
+}
+.resource-card-3x3 > .card-info .title, .resource-card-6x3 > .card-info .title, .resource-card-9x3 > .card-info .title, .resource-card-12x3 > .card-info .title, .resource-card-15x3 > .card-info .title, .resource-card-18x3 > .card-info .title {
+  font-size: 16px;
+  margin-bottom: -2px;
+  white-space: normal;
+  overflow: visible;
+}
+.resource-card-3x3 > .card-info .description .text, .resource-card-6x3 > .card-info .description .text, .resource-card-9x3 > .card-info .description .text, .resource-card-12x3 > .card-info .description .text, .resource-card-15x3 > .card-info .description .text, .resource-card-18x3 > .card-info .description .text {
+  font-size: 12px;
+  line-height: 15px;
+  padding-right: 0px !important;
+  height: 80px;
+}
+.resource-card-3x3 > .card-info .description .util, .resource-card-6x3 > .card-info .description .util, .resource-card-9x3 > .card-info .description .util, .resource-card-12x3 > .card-info .description .util, .resource-card-15x3 > .card-info .description .util, .resource-card-18x3 > .card-info .description .util {
+  display: none;
+}
+/* placement of plusone */
+.resource-card-6x12 > .card-info .description .util, .resource-card-9x12 > .card-info .description .util, .resource-card-12x12 > .card-info .description .util, .resource-card-15x12 > .card-info .description .util {
+  bottom:2px;
+}
+.resource-card-18x12 > .card-info .description .util {
+  bottom:2px;
+}
+/* Overrides for col-16 6x6 cards linking to local content on landing pages.
+   Suppresses "section" and puts the title above a hairline rule. */
+.landing .card-info .section, .resource-flow-layout.col-16.landing .resource-card-9x6 .card-info .section {
+  display:none;
+}
+.landing  .card-info .title {
+  color: #898989;
+  font-size: 17px;
+  line-height: 24px;
+  margin-bottom: 6px;
+  border-bottom: 1px solid #959595;
+  padding-bottom: 0px;
+}
+.landing .card-info .description {
+  font-size: 13px;
+  line-height: 15px;
+}
+.landing .card-info .description .text {
+height:30px;
+}
+.landing .resource-card-6x6 > .card-info .description .util, .landing .resource-card-9x6 > .card-info .description .util {
+  bottom:2px;
+}
+/*
+  Generate a resource stack layout for a 3 column widget spanning 16 grid cols
+*/
+.resource-stack-layout.col-16 {
+  margin: 0 -14px 0 0;
+  width: 954px;
+}
+.resource-stack-layout.col-16 .resource-card-stack {
+  margin: 0 14px 0 0;
+  width: 304px;
+}
+
+/* Example of card menu tinting */
+.resource-widget[data-section=distribute\/tools] .section-card-menu
+.card-bg:after {
+  background: rgba(126, 55, 148, 0.4) !important;
+}
+.resource-widget[data-section=distribute\/tools] .section-card-menu
+.card-section-icon .icon {
+  background-color: #7e3794 !important;
+}
+.resource-widget[data-section=distribute\/tools] .section-card-menu
+.card-info ul li {
+  border-top-color: #7e3794 !important;
+}
+
+/* tinting for stacks */
+
+div.jd-descr > .resource-widget[data-section=distribute\/tools]
+.section-card-menu .card-info ul li {
+  border-top-color: #7e3794 !important;
+}
+
+
+
+/**
+ * UTILITIES
+ */
+
+
+.border-box {
+  box-sizing: border-box;
+}
+
+.vertical-center-outer {
+  display: table;
+  height: 100%;
+  width: 100%;
+}
+
+.vertical-center-inner {
+  display: table-cell;
+  vertical-align: middle;
+}
+
+/**
+ * TYPE STYLES
+ */
+
+.landing-h1 {
+  font-weight: 100;
+  font-size: 60px;
+  line-height: 78px;
+  text-align: center;
+  letter-spacing: -1px;
+}
+
+.landing-pre-h1 {
+  font-weight: 400;
+  font-size: 28px;
+  color: #93B73F;
+  line-height: 36px;
+  text-align: center;
+  letter-spacing: -1px;
+  text-transform: uppercase;
+
+}
+
+.landing-h1.hero {
+  text-align: left;
+}
+
+.landing-h2 {
+  font-weight: 300;
+  font-size: 42px;
+  line-height: 64px;
+  text-align: center;
+}
+
+.landing-subhead {
+  color: #999999;
+  font-size: 20px;
+  line-height: 28px;
+  font-weight:300;
+  text-align: center;
+}
+.landing-subhead.hero {
+  text-align: left;
+  color: white;
+}
+
+.landing-hero-description {
+  text-align: left;
+  margin: 1em 0;
+}
+
+.landing-hero-description p {
+  font-weight: 300;
+  margin: 0;
+  font-size: 18px;
+  line-height: 24px;
+}
+
+.landing-body .landing-small {
+  font-size: 14px;
+  line-height: 19px;
+}
+
+.landing-body.landing-align-center {
+  text-align: center;
+}
+
+.landing-align-left {
+  text-align: left;
+}
+
+/**
+ * LAYOUT
+ */
+
+#body-content,
+.fullpage,
+#jd-content,
+.jd-descr,
+.landing-body-content {
+  height: 100%;
+}
+
+.landing-section {
+  padding: 80px 10px 80px;
+  width: 100%;
+  margin-left: -10px;
+  text-rendering: optimizeLegibility;
+}
+
+#extending-android-to-wearables {
+  padding-top: 30px;
+}
+
+.landing-short-section {
+  padding: 40px 10px 28px;
+}
+
+.landing-gray-background {
+  background-color: #e9e9e9;
+}
+
+.landing-white-background {
+  background-color: white;
+}
+
+.landing-red-background {
+  color: white;
+  background-color: hsl(8, 70%, 54%);
+}
+
+.landing-subhead-red {
+  color: hsl(8, 71%, 84%);
+  text-align: left;
+}
+
+.landing-subhead-red p {
+  margin-top: 20px;
+}
+
+.landing-hero-container {
+  height: 100%;
+}
+
+
+.preview-hero {
+  height: calc(100% - 110px);
+  min-height: 504px;
+  margin-top: -5px;
+  padding-top: 0;
+  padding-bottom: 0;
+  background-image: url(../../preview/images/hero.jpg);
+  background-size: cover;
+  background-position: right center;
+  color: white;
+  position: relative;
+  overflow: hidden;
+}
+
+.wear-hero {
+  height: calc(100% - 110px);
+  min-height: 504px;
+  margin-top: -5px;
+  padding-top: 0;
+  padding-bottom: 0;
+  background-image: url(../../wear/images/hero.jpg);
+  background-size: cover;
+  background-position: top center;
+  color: white;
+  position: relative;
+  overflow: hidden;
+}
+
+.tv-hero {
+  height: calc(100% - 110px);
+  min-height: 504px;
+  margin-top: -5px;
+  padding-top: 0;
+  padding-bottom: 0;
+  background-image: url(../../tv/images/hero.jpg);
+  background-size: cover;
+  background-position: right center;
+  color: white;
+  position: relative;
+  overflow: hidden;
+}
+
+.auto-hero {
+  height: calc(100% - 110px);
+  min-height: 504px;
+  margin-top: -5px;
+  padding-top: 0;
+  padding-bottom: 0;
+  background-image: url(../../auto/images/hero.jpg);
+  background-size: cover;
+  background-position: right center;
+  color: white;
+  position: relative;
+  overflow: hidden;
+}
+
+.landing-hero-scrim {
+  background: black;
+  opacity: .2;
+  position: absolute;
+  width: 100%;
+  height: 100%;
+  margin-left: -10px;
+}
+
+.landing-hero-wrap {
+  margin: 0 auto;
+  width: 940px;
+  clear: both;
+  height: 100%;
+  position: relative;
+}
+
+.landing-section-header {
+  margin-bottom: 40px;
+}
+
+.landing-hero-wrap .landing-section-header {
+  margin-bottom: 16px;
+}
+
+.landing-body {
+  font-size: 18px;
+  line-height: 24px;
+}
+
+.landing-button {
+  white-space: nowrap;
+  display: inline-block;
+  padding: 16px 32px;
+  font-size: 18px;
+  font-weight: 500;
+  line-height: 24px;
+  cursor: pointer;
+  color: white;
+  -webkit-user-select: none;
+     -moz-user-select: none;
+       -o-user-select: none;
+  user-select: none;
+  -webkit-transition: .2s background-color ease-in-out;
+     -moz-transition: .2s background-color ease-in-out;
+       -o-transition: .2s background-color ease-in-out;
+  transition: .2s background-color ease-in-out;
+}
+
+.landing-primary {
+  background-color: hsl(8, 70%, 44%);
+  color: #f8f8f8;
+}
+
+.landing-button.landing-primary:hover {
+  background-color: hsl(8, 70%, 36%);
+}
+
+.landing-button.landing-primary:active {
+  background-color: hsl(8, 70%, 30%);
+}
+
+.landing-button.landing-secondary {
+  background-color: #2faddb;
+}
+
+.landing-button.landing-secondary:hover {
+  background-color: #09c;
+}
+
+.landing-button.landing-secondary:active {
+  background-color: #3990ab;
+}
+
+a.landing-button,
+a.landing-button:hover,
+a.landing-button:visited {
+  color: white !important;
+}
+
+.landing-video-link {
+  white-space: nowrap;
+  display: inline-block;
+  padding: 16px 32px 16px 82px;
+  font-size: 18px;
+  font-weight: 400;
+  line-height: 24px;
+  cursor: pointer;
+  color: hsla(0, 0%, 100%, .8);
+  -webkit-user-select: none;
+     -moz-user-select: none;
+       -o-user-select: none;
+  user-select: none;
+  -webkit-transition: .2s color ease-in-out;
+     -moz-transition: .2s color ease-in-out;
+       -o-transition: .2s color ease-in-out;
+  transition: .2s color ease-in-out;
+}
+
+.landing-video-link:before {
+  height: 64px;
+  width: 64px;
+  display: inline-block;
+  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAFuklEQVR42u2dXWgcVRSAV9LWtBBTTZVWUhNqEQtq1QeroDRKFRFsROqTYPuo+JCiIoJKFC0USqlUfCiowRcfrBgVUUElefAPkW5T8aeaGn9aRbFsjP0x2cx8PuRMvFxmdjeb2Z17Z8+B85DsZPbO+eaec3/OPSkABdXsVI2gABSAqgJQAKoKQAGoKgAFoKoAFICqAlAAqgpAAai6DqDRAiwDeoFtwB7gPaAInABKwKToCWAMeB/YDdwJrAWWNLh9+QMAXABsBQ4A3wFTwAxQBmaBAAhjNJDPy3L938BXwAvArUCHAkh+kCXAVcA+YBw4bRg7MngtkgTlDPA98CywHmhTAP8/xCbgVeAvMZZpwDQllN7xB/AysKGlAQAXAvuBkzW85UVgCBgENlfQQbmuWAXELPAnsAvoaikAQBtwh/j3coLhS2LIfqCzzu/plL8fkvvFgZiR4L2lHrfkHQBgpQTFUwmGnwC212v0KjC2y/3jQPwDPA+05xYAcBHwubx1YZzhC02QBBBRbxgBzssdAOBy4JgRZE0ZTPuNr7FHDCbEhqNAd24AAN0yUbID7QSwsZChABut3hANXY8Bq70HIMb/Ocb4w81+66v0hmGrN0QQ1ngLQJYRvpWHMWWo4KDIaMnuCcVKgdlZAGL8t2J8vpPGrwChDLyWBMFlAA8D0z4ZvwKEs8D93gCQEc9Jy/jFgkdizaRDGUSs8wXAu1bQLQE9ngHosWbPAXDQeQAypT9rBd3+gociyxi2K9riLABZUj5iuZ6RgsciM2OzFxw2A7JrAO6VwGtKTwpG+Anoy9AVmb3gDHCPcwCAFcChRox6jPu9CazMeFQUAKNRL3AJwE2yopjq228BQPZ/d2bcCyaBTa4BeNGa8Q6naIA4GQWubiKEYWvBbp8zAGQt5VfL/fQ3GEAkTzXDLVkjokA2k5a7AuA2GaLNj/tTfvhq0pQgbcwLQtlQusYVALtlzSR191MjADNI9zbJDZWBR10BMGr5/4GMADQ0SAMDlht62xUAxy0AmzMEEMnhtIO0ZF2YAH5wITd0hQw/5wE04M1bjDyXZpC2hqMlYGnWAHqBf40APOEYgChI35VSWyasWfGqrAH0WVkOIw4CSC1IG2tDoSy7XJE1gPs8ArDoIG0BmJGk30wBDHgGYFFBOgbAtqwB7GxxAHerC8rOBU0Dt2gQzjYIb8gawDor+6HVhqFdrkzEwhabiAVOTMSkUb+06FLEUVfWgj5q0cW4g64AeNo66ZLlcnTDNmesBN4y8KArAG6QU42ttCEzBVzpCoAO4EfLDeV5SzIEvgHaXdqUP2BlQud1Ux55zj2uZUX02cPRnKalRLmu17qYmPWF5YbymJgVAh8Ay5wCII3ZEZOYm6fURGT2u9X43Mnk3CDHybmfmRVYXExPv9nKEcpLejqSC3SjdY2TBzTesHqB7wc0onTEV2KucxLApXKkJy9HlAI5anuJFwCkYQ/EuCJfD+mdBnYkXOssgHY53un7MdVZ4CVgqVcADAhjMafkfTioHc14P04yvvMApIEXy5F/+7S8y6UKolPyR4BVVf7Wi2IdawwIPhTrmAW+rmZ8bwBIQ7vloXwoVzNWS6UUrwAYy9YfOlqwKZDkgneA5Qu4l3cly84F9sqGhislywLmaozuYoGFXr0DII1ukxP1hxJ6QzR7HqLxRfumZaRzXZ3f4XXZyi7gCeB3kqsnzs+kSb9s5XHgMeD8RTxDLgq3rmeuYuFvNYCoR8wqujNi+L3UWBcu9wAMt3QZ8LiMlk5RuU50teq6kcEDgTolveIRYHUQBOek1O5cFu/ukLz7/ZJgNSm+OirebWpgaPS7slxfAr4EngGuX8jopqUBxGzyrAVuB54EXgc+lV4yLhO8cfn5E+ZqUD8kBu9sQvv0Hzj4rmoEBaAAVBWAAlBVAApAVQEoAFUFoABUFYACUFUACkC1CfofXVRJocowZVYAAAAASUVORK5CYII=);
+  background-size: contain;
+  position: absolute;
+  content: "";
+  opacity: .7;
+  margin-top: -19px;
+  margin-left: -64px;
+  -webkit-transition: .2s opacity ease-in-out;
+     -moz-transition: .2s opacity ease-in-out;
+       -o-transition: .2s opacity ease-in-out;
+  transition: .2s opacity ease-in-out;
+}
+
+.landing-video-link:hover {
+  color: hsla(0, 0%, 100%, 1);
+}
+
+.landing-video-link:hover:before {
+  opacity: 1;
+}
+
+.landing-social-image {
+  float: left;
+  margin-right: 14px;
+  height: 64px;
+  width: 64px;
+}
+
+.landing-social-copy {
+  padding-left: 78px;
+}
+
+.landing-scroll-down-affordance {
+  position: absolute;
+  bottom: 0;
+  width: 100%;
+  text-align: center;
+  z-index: 10;
+}
+
+.landing-down-arrow {
+  padding: 24px;
+  display: inline-block;
+  opacity: .5;
+  -webkit-transition: .2s opacity ease-in-out;
+     -moz-transition: .2s opacity ease-in-out;
+       -o-transition: .2s opacity ease-in-out;
+  transition: .2s opacity ease-in-out;
+
+  -webkit-animation-name: pulse-opacity;
+  -webkit-animation-duration: 4s;
+}
+
+.landing-down-arrow:hover {
+  opacity: 1;
+}
+
+.landing-down-arrow img {
+  height: 28px;
+  width: 28px;
+  margin: 0 auto;
+  display: block;
+}
+
+.landing-divider {
+  display: inline-block;
+  height: 2px;
+  background-color: white;
+  position: relative;
+  margin: 10px 0;
+}
+
+/* 3 CLOLUMN LAYOUT */
+
+.landing-breakout {
+  margin-top: 40px;
+  margin-bottom: 40px;
+}
+
+.landing-breakout img {
+  margin-bottom: 20px;
+}
+
+.landing-partners img {
+  margin-bottom: 20px;
+}
+
+.landing-breakout p {
+  padding: 0 23px;
+}
+
+.landing-breakout.landing-partners img {
+  margin-bottom: 20px;
+}
+
+.col-3-wide {
+  display: inline;
+  float: left;
+  margin-left: 10px;
+  margin-right: 10px;
+}
+
+.col-3-wide {
+  width: 302px;
+}
+
+/**
+ * ANIMATION
+ */
+
+@-webkit-keyframes pulse-opacity {
+  0% {
+    opacity: .5;
+  }
+  20% {
+    opacity: .5;
+  }
+  40% {
+    opacity: 1;
+  }
+  60% {
+    opacity: .5;
+  }
+  80% {
+    opacity: 1;
+  }
+  100% {
+    opacity: .5;
+  }
+}
+
+
+
+/**
+ * VIDEO
+ */
+
+#video-container {
+  display:none;
+  position:fixed;
+  top:0;
+  left:-10px;
+  width:102%;
+  height:100%;
+  background-color:rgba(0,0,0,0.7);
+  z-index:99;
+}
+
+#video-frame {
+  width:940px;
+  height:526.4px;
+  margin:80px auto 0;
+  display:none;
+}
+
+.video-close {
+cursor: pointer;
+position: relative;
+left: 940px;
+top: 0;
+pointer-events: all;
+}
+
+#icon-video-close {
+background-image: url("../images/close.png");
+background-position: 0 0;
+height: 36px;
+width: 36px;
+display:block;
+}
+
+
+
+
+/******************
+Styles for d.a.c/index:
+*******************/
+
+
+
+/* Generic full screen carousel styling to be used across pages. */
+.fullscreen-carousel {
+  margin: 0 -10px;
+  width: 100%;
+  overflow: hidden;
+  position: relative;
+}
+
+.fullscreen-carousel-content {
+  width: 100%;
+  height: 100%;
+  position: relative;
+  display: table; /* For vertical centering */
+}
+
+.fullscreen-carousel .vcenter {
+  display: table-cell;
+  vertical-align: middle;
+  position: relative;
+}
+
+.fullscreen-carousel .vcenter > div {
+  margin: 10px auto;
+}
+
+/* Styles for the full-bleed hero image type. */
+.fullscreen-carousel .hero, .fullscreen-carousel .hero h1 {
+  color: #fff;
+}
+
+.fullscreen-carousel .hero h1 {
+  font-weight: 300;
+  font-size: 60px;
+  line-height: 68px;
+  letter-spacing: -1px;
+  margin-top: 0;
+}
+
+.fullscreen-carousel .hero p {
+  font-weight: 300;
+  font-size: 18px;
+  line-height: 24px;
+  -webkit-font-smoothing: antialiased;
+}
+
+.fullscreen-carousel .hero .hero-bg {
+  background-size: cover;
+  width: 100%;
+  height: 100%;
+  position: absolute;
+  left: 0px;
+  top: 0px;
+}
+
+
+/* Full screen carousel styling for the resource flow layout type of content */
+.fullscreen-carousel .resource-flow-layout:after {
+  height: 0; /* Dont know why this is set at 10 in default.css */
+}
+
+.fullscreen-carousel .resource-flow-layout {
+  margin-bottom: 20px;
+}
+
+
+
+/* Generic Tab carousel styling to be used across multiple pages. */
+
+.tab-carousel .tab-nav {
+  list-style: none;
+  position: relative;
+  text-align: center;
+}
+
+.tab-carousel .tab-nav li {
+  display: inline-block;
+  font-size: 22px;
+  font-weight: 400;
+  line-height: 50px;
+  list-style: none;
+  margin: 0;
+  padding: 0 25px;
+  position: relative;
+}
+
+.tab-carousel .tab-nav li a,
+.tab-carousel .tab-nav li a:hover {
+  color: #333 !important;
+  padding: 10px 10px 13px 10px;
+  position: relative;
+  z-index: 1000;
+}
+
+.tab-carousel .tab-nav li:after {
+  background: #ddd;
+  bottom: 0;
+  content: '';
+  height: 4px;
+  left: 0;
+  position: absolute;
+  width: 100%;
+  z-index: 0;
+}
+
+.tab-carousel .tab-nav .highlight {
+  position: absolute;
+  height: 4px;
+  width: 100px;
+  bottom: 0;
+  background: #33b5e5;
+}
+
+.tab-carousel .tab-carousel-content {
+  position: relative;
+  overflow: hidden;
+  white-space: nowrap;
+}
+
+.tab-carousel .tab-carousel-content [data-tab] {
+  display: inline-block;
+  white-space: normal;
+}
+
+
+
+/*
+  Resource styling for the tab carousel. The tab carousel contains either
+  a 3 column layout of resources or a single full-width resource. The
+  latter has the 18x12 class applied to it and can be styled differently
+  that way.
+*/
+
+.tab-carousel .resource .image {
+  width: 100%;
+  height: 250px;
+  background-repeat: no-repeat;
+  background-size: contain;
+  background-position: 50% 50%;
+}
+
+.tab-carousel .resource .info .title {
+  font-size: 18px;
+  line-height: 24px;
+}
+
+.tab-carousel .resource .info .summary,
+.tab-carousel .resource .info .cta {
+  line-height: 24px;
+  font-size: 16px;
+}
+
+.tab-carousel .resource-card-18x12 {
+  position: relative;
+  padding-left: 450px;
+  box-sizing: border-box;
+  display: table-cell;
+  vertical-align: middle;
+}
+
+.tab-carousel .resource-card-18x12 .image {
+  position: absolute;
+  width: 420px;
+  height: 100%;
+  left: 0;
+  top: 0;
+}
+
+.tab-carousel .resource-card-18x12 .info {
+  display: inline-block;
+}
+
+.tab-carousel .resource-card-18x12 .info .title {
+  margin-bottom: 26px;
+}
+
+
+
+
+
+/*
+   Styles for the entity link used in the actions bar and in the cta of
+   the resources that appear in the tab carousel.
+*/
+.actions-bar a:after,
+.resource .cta:after {
+  content: '›';
+  font-weight: 400;
+  font-size: 22px;
+  left: 5px;
+  line-height: 1;
+  position: relative;
+  top: 1px;
+  transition: left 190ms ease-out;
+}
+
+.actions-bar a:hover:after,
+.resource .cta:hover:after {
+  left: 10px;
+}
+
+
+
+
+/*
+  Styles for the actions bar.
+*/
+.actions-bar {
+  background: #9acd00;
+  margin: 0 -10px;
+  text-align: center;
+}
+
+.actions-bar .actions {
+  padding: 30px 0 30px;
+  text-align: justify;
+  font-size: 0.1px;
+  line-height: 0.1px;
+  margin: 0 10px 0 0;
+}
+
+.actions-bar .actions:after {
+  content: '';
+  width: 100%;
+  display: inline-block;
+}
+
+.actions-bar .actions > div {
+  display: inline-block;
+}
+
+.actions-bar a {
+  font-size: 21px;
+  line-height: 27px;
+  color: #fff;
+  font-weight: 300;
+  -webkit-font-smoothing: antialiased;
+}
+
+.actions-bar a:after {
+  top: 0px;
+  font-size: 22px;
+}
+
+.actions-bar a:hover {
+  color: #fff !important;
+}
+
+
+
+
+
+/*
+  Specific styles for new home page layout of the carousels.
+*/
+
+/* Big blue button */
+a.home-new-cta-btn,
+.home-new-carousel-1 .resource-card-18x6 .cta {
+  white-space: nowrap;
+  display: inline-block;
+  padding: 14px 32px;
+  font-size: 18px;
+  font-weight: 500;
+  line-height: 24px;
+  cursor: pointer;
+  background: #33b5e6;
+  border-radius: 4px;
+  margin-top: 20px;
+  color: #fff;
+  transition: 0.2s background-color ease-in-out;
+}
+
+.home-new-carousel-1 .resource-card-18x6 .cta:after {
+  display: none; /* Hide the entity for this button */
+}
+
+a.home-new-cta-btn:hover,
+.home-new-carousel-1 .resource-card-18x6 .cta:hover {
+  color: #fff !important;
+  background: #2d9fca;
+}
+
+.home-new-carousel-1 .resource-card-18x6 .cta {
+  position: absolute;
+  bottom: 20px;
+  left: 16px;
+}
+
+/* Fullscreen carousel. */
+.home-new-carousel-1 {
+  max-height: 700px; /* Set max height so doesn't get too long */
+}
+
+.home-new-carousel-1 .fullscreen-carousel-content {
+  min-height: 450px;  /* Set min height for all content */
+}
+
+.home-new-carousel-1 .hero {
+  background: #000;
+}
+
+.home-new-carousel-1 .hero-bg {
+  background-image: url(/home-new/images/hero.jpg);
+  background-position: right center;
+  opacity: 0.85;
+}
+
+/*
+  Styling for special top card of full screen layout resource layout.
+  We need to specifically style the 18x6 card to adjust its size and layout,
+  since it's not a standard card, not sure if this is unique to the home page
+  layout or should be namespaced within the fullscreen-carousel container.
+*/
+.home-new-carousel-1 .resource-flow-layout.col-16 .resource-card-18x6 {
+  height: 320px;
+  background-color:#F9F9F9;
+  border-radius: 0px;
+  box-shadow: 0px 0px 0px rgba(0, 0, 0, 0);
+
+}
+
+.home-new-carousel-1 .resource-card-18x6 .card-bg {
+  width: 636px;
+  height: 100%;
+}
+
+.home-new-carousel-1 .resource-card-18x6 .card-info {
+  right: 0px;
+  left: 636px;
+  height: 100%;
+  top: 0px;
+  padding: 15px 22px;
+}
+
+.home-new-carousel-1 .resource-card-18x6 .card-info .util {
+  display: none;
+}
+
+.home-new-carousel-1 .resource-card-18x6 .card-info .title {
+  font-size: 20px;
+  font-weight: 500;
+  margin-top: 15px;
+  margin-bottom: 15px;
+}
+
+.home-new-carousel-1 .resource-card-18x6 .card-info .text {
+  font-size: 15px;
+  line-height: 21px;
+}
+
+
+/* Tabbed carousel. */
+.home-new-carousel-2 {
+  margin: 35px auto 100px auto;
+}
+
+.home-new-carousel-2 h1 {
+  font-size: 47px;
+  font-weight: 100;
+  line-height: 54px;
+  text-align: center;
+}
diff --git a/tools/droiddoc/templates-sdk/assets/css/fullscreen.css b/tools/droiddoc/templates-sdk/assets/css/fullscreen.css
index 71cf65b..7912e34 100644
--- a/tools/droiddoc/templates-sdk/assets/css/fullscreen.css
+++ b/tools/droiddoc/templates-sdk/assets/css/fullscreen.css
@@ -170,7 +170,7 @@
   max-width: 100%;
 }
 
-#nav-x .wrap,
+#header-wrapper #nav-x div.wrap,
 #searchResults.wrap {
     max-width:100%;
 }
@@ -184,9 +184,17 @@
   left:20px; /* !important ... for IE i think */
 }
 
+#sticky-header {
+  padding: 0 20px;
+}
 
+#sticky-header > div {
+  width: 100%;
+}
 
-
+.sticky-menu {
+  width:100%;
+  left:-20px;
 }
 
 .col-right {
diff --git a/tools/droiddoc/templates-sdk/assets/css/resourcecards.css b/tools/droiddoc/templates-sdk/assets/css/resourcecards.css
deleted file mode 100644
index 1222b04..0000000
--- a/tools/droiddoc/templates-sdk/assets/css/resourcecards.css
+++ /dev/null
@@ -1,371 +0,0 @@
-/* content layout */
-.resource-widget.resource-flow-layout {
-  display: inline-block;
-  margin-right: -20px;
-  /* clearfix idiom */ }
-  .resource-widget.resource-flow-layout.col-1 {
-    width: 60px; }
-  .resource-widget.resource-flow-layout.col-2 {
-    width: 120px; }
-  .resource-widget.resource-flow-layout.col-3 {
-    width: 180px; }
-  .resource-widget.resource-flow-layout.col-4 {
-    width: 240px; }
-  .resource-widget.resource-flow-layout.col-5 {
-    width: 300px; }
-  .resource-widget.resource-flow-layout.col-6 {
-    width: 360px; }
-  .resource-widget.resource-flow-layout.col-7 {
-    width: 420px; }
-  .resource-widget.resource-flow-layout.col-8 {
-    width: 480px; }
-  .resource-widget.resource-flow-layout.col-9 {
-    width: 540px; }
-  .resource-widget.resource-flow-layout.col-10 {
-    width: 600px; }
-  .resource-widget.resource-flow-layout.col-11 {
-    width: 660px; }
-  .resource-widget.resource-flow-layout.col-12 {
-    width: 720px; }
-  .resource-widget.resource-flow-layout.col-13 {
-    width: 780px; }
-  .resource-widget.resource-flow-layout.col-14 {
-    width: 840px; }
-  .resource-widget.resource-flow-layout.col-15 {
-    width: 900px; }
-  .resource-widget.resource-flow-layout.col-16 {
-    width: 960px; }
-  .resource-widget.resource-flow-layout:after {
-    content: ".";
-    display: block;
-    height: 0;
-    clear: both;
-    visibility: hidden; }
-  * html .resource-widget.resource-flow-layout {
-    height: 1px; }
-
-.resource-card {
-  /* stuff that applies to all cards */
-  display: -webkit-flex;
-  -webkit-transform: translateZ(0);
-  float: left;
-  position: relative;
-  margin-right: 20px;
-  margin-bottom: 20px;
-  background-color: #fff;
-  border-radius: 2px;
-  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.25);
-  opacity: 0.8;
-  overflow: hidden;
-  transition: 0.4s box-shadow ease, 0.4s opacity ease;
-  /* card templates */
-  /* specific cards and customizations */ }
-  .resource-card .photo {
-    position: relative;
-    background-color: #eee;
-    background-size: cover;
-    background-repeat: no-repeat;
-    background-position: 50% 50%; }
-  .resource-card.nophoto .photo:after {
-    content: '';
-    display: block;
-    position: absolute;
-    left: 20px;
-    top: 20px;
-    right: 20px;
-    bottom: 20px;
-    opacity: 0.2;
-    background-position: center center;
-    background-repeat: no-repeat;
-    background-size: contain; }
-  .resource-card .icon {
-    background-position: center center;
-    background-repeat: no-repeat;
-    background-size: contain;
-    opacity: 0;
-    transition: 0.4s ease; }
-  .resource-card:hover .icon {
-    opacity: 0.2; }
-  .resource-card:hover {
-    opacity: 1;
-    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.5); }
-  .resource-card.resource-card-youtube.nophoto .photo:after, .resource-card.resource-card-youtube .icon {
-    background-image: url(../images/card_video.png); }
-  .resource-card.resource-card-samples.nophoto .photo:after, .resource-card.resource-card-samples .icon {
-    background-image: url(../images/card_sample.png); }
-  .resource-card.resource-card-blog.nophoto .photo:after, .resource-card.resource-card-blog .icon {
-    background-image: url(../images/card_post.png); }
-  .resource-card.resource-card-training.nophoto .photo:after, .resource-card.resource-card-training .icon {
-    background-image: url(../images/card_training.png); }
-  .resource-card .resource-card-text {
-    color: #333333; }
-  .resource-card .title {
-    /*font-weight: 700;*/
-    font-family: 'Roboto Condensed'; }
-  .resource-card .subtitle {
-    font-family: 'Roboto Condensed';
-    text-transform: uppercase;
-    opacity: 0.3; }
-  .resource-card .abstract {
-    font-weight: 300;
-    font-family: 'Roboto'; }
-  .resource-card.resource-card-12x7 {
-    width: 700px;
-    height: 400px;
-    -webkit-flex-direction: column; }
-    .resource-card.resource-card-12x7 .photo {
-      -webkit-flex: 1 1 auto;
-      border-bottom: 1px solid #ddd; }
-    .resource-card.resource-card-12x7 .resource-card-text {
-      margin: 20px;
-      padding-right: 88px; }
-    .resource-card.resource-card-12x7 .icon {
-      position: absolute;
-      right: 20px;
-      bottom: 20px;
-      width: 48px;
-      height: 48px; }
-    .resource-card.resource-card-12x7 .title {
-      font-size: 36px;
-      line-height: 35px;
-      max-height: 70px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical; }
-    .resource-card.resource-card-12x7 .subtitle {
-      font-size: 18px;
-      line-height: 20px;
-      max-height: 20px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 1;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      margin-top: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-12x7:hover .subtitle {
-      margin-top: 10px;
-      max-height: 20px; }
-    .resource-card.resource-card-12x7 .abstract {
-      font-size: 18px;
-      margin-top: 0;
-      line-height: 25px;
-      max-height: 75px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 3;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-12x7:hover .abstract {
-      margin-top: 20px;
-      max-height: 75px; }
-  .resource-card.resource-card-8x6 {
-    width: 460px;
-    height: 340px;
-    -webkit-flex-direction: column; }
-    .resource-card.resource-card-8x6 .photo {
-      -webkit-flex: 1 1 auto;
-      border-bottom: 1px solid #ddd; }
-    .resource-card.resource-card-8x6 .resource-card-text {
-      margin: 20px;
-      padding-right: 88px; }
-    .resource-card.resource-card-8x6 .icon {
-      position: absolute;
-      right: 20px;
-      bottom: 20px;
-      width: 48px;
-      height: 48px; }
-    .resource-card.resource-card-8x6 .title {
-      font-size: 36px;
-      line-height: 35px;
-      max-height: 70px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical; }
-    .resource-card.resource-card-8x6 .subtitle {
-      font-size: 18px;
-      line-height: 20px;
-      max-height: 20px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 1;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      margin-top: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-8x6:hover .subtitle {
-      margin-top: 10px;
-      max-height: 20px; }
-    .resource-card.resource-card-8x6 .abstract {
-      font-size: 18px;
-      margin-top: 0;
-      line-height: 25px;
-      max-height: 75px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 3;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-8x6:hover .abstract {
-      margin-top: 20px;
-      max-height: 75px; }
-    .resource-card.resource-card-8x6 .icon {
-      width: 32px;
-      height: 32px; }
-    .resource-card.resource-card-8x6 .title {
-      font-size: 24px;
-      line-height: 25px;
-      max-height: 50px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical; }
-    .resource-card.resource-card-8x6 .abstract {
-      font-size: 16px;
-      margin-top: 10px;
-      line-height: 20px;
-      max-height: 60px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 3;
-      -webkit-box-orient: vertical; }
-    .resource-card.resource-card-8x6 .subtitle {
-      font-size: 16px;
-      line-height: 20px;
-      max-height: 20px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 1;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      margin-top: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-8x6:hover .subtitle {
-      margin-top: 10px;
-      max-height: 20px; }
-    .resource-card.resource-card-8x6 .abstract {
-      font-size: 16px;
-      margin-top: 0;
-      line-height: 20px;
-      max-height: 60px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 3;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-8x6:hover .abstract {
-      margin-top: 10px;
-      max-height: 60px; }
-  .resource-card.resource-card-6x4 {
-    width: 340px;
-    height: 220px;
-    -webkit-flex-direction: column; }
-    .resource-card.resource-card-6x4 .photo {
-      -webkit-flex: 1 1 auto;
-      border-bottom: 1px solid #ddd; }
-    .resource-card.resource-card-6x4 .resource-card-text {
-      margin: 10px;
-      padding-right: 26px; }
-    .resource-card.resource-card-6x4 .icon {
-      position: absolute;
-      right: 10px;
-      bottom: 10px;
-      width: 16px;
-      height: 16px; }
-    .resource-card.resource-card-6x4 .title {
-      font-size: 16px;
-      line-height: 20px;
-      max-height: 40px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical; }
-    .resource-card.resource-card-6x4 .subtitle {
-      font-size: 13px;
-      line-height: 15px;
-      max-height: 30px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      margin-top: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-6x4:hover .subtitle {
-      max-height: 30px; }
-    .resource-card.resource-card-6x4 .abstract {
-      display: none; }
-    .resource-card.resource-card-6x4 .abstract {
-      font-size: 13px;
-      margin-top: 0;
-      line-height: 15px;
-      max-height: 30px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      display: block;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-6x4:hover .abstract {
-      margin-top: 10px;
-      max-height: 30px; }
-  .resource-card.resource-card-4x3 {
-    width: 220px;
-    height: 160px;
-    -webkit-flex-direction: column; }
-    .resource-card.resource-card-4x3 .photo {
-      -webkit-flex: 1 1 auto;
-      border-bottom: 1px solid #ddd; }
-    .resource-card.resource-card-4x3 .resource-card-text {
-      margin: 10px;
-      padding-right: 26px; }
-    .resource-card.resource-card-4x3 .icon {
-      position: absolute;
-      right: 10px;
-      bottom: 10px;
-      width: 16px;
-      height: 16px; }
-    .resource-card.resource-card-4x3 .title {
-      font-size: 16px;
-      line-height: 20px;
-      max-height: 40px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical; }
-    .resource-card.resource-card-4x3 .subtitle {
-      font-size: 13px;
-      line-height: 15px;
-      max-height: 30px;
-      text-overflow: ellipsis;
-      display: -webkit-box;
-      overflow: hidden;
-      -webkit-line-clamp: 2;
-      -webkit-box-orient: vertical;
-      max-height: 0;
-      margin-top: 0;
-      transition: 0.4s ease; }
-    .resource-card.resource-card-4x3:hover .subtitle {
-      max-height: 30px; }
-    .resource-card.resource-card-4x3 .abstract {
-      display: none; }
diff --git a/tools/droiddoc/templates-sdk/assets/images/android.png b/tools/droiddoc/templates-sdk/assets/images/android.png
new file mode 100644
index 0000000..4040f3f
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/android.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/breadcrumb.png b/tools/droiddoc/templates-sdk/assets/images/breadcrumb.png
new file mode 100644
index 0000000..407a318
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/breadcrumb.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_post.png b/tools/droiddoc/templates-sdk/assets/images/card_post.png
deleted file mode 100644
index e061ee9..0000000
--- a/tools/droiddoc/templates-sdk/assets/images/card_post.png
+++ /dev/null
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_sample.png b/tools/droiddoc/templates-sdk/assets/images/card_sample.png
deleted file mode 100644
index 3dc36e0..0000000
--- a/tools/droiddoc/templates-sdk/assets/images/card_sample.png
+++ /dev/null
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_training.png b/tools/droiddoc/templates-sdk/assets/images/card_training.png
deleted file mode 100644
index 5bb7c81..0000000
--- a/tools/droiddoc/templates-sdk/assets/images/card_training.png
+++ /dev/null
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_video.png b/tools/droiddoc/templates-sdk/assets/images/card_video.png
deleted file mode 100644
index 807c0af..0000000
--- a/tools/droiddoc/templates-sdk/assets/images/card_video.png
+++ /dev/null
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/link-out.png b/tools/droiddoc/templates-sdk/assets/images/link-out.png
new file mode 100644
index 0000000..aa55f9a
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/link-out.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/preview.png b/tools/droiddoc/templates-sdk/assets/images/preview.png
new file mode 100644
index 0000000..e5856db
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/preview.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/resource-card-default-android.jpg b/tools/droiddoc/templates-sdk/assets/images/resource-card-default-android.jpg
new file mode 100644
index 0000000..8050744
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/resource-card-default-android.jpg
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/stack-arrow-right.png b/tools/droiddoc/templates-sdk/assets/images/stack-arrow-right.png
new file mode 100644
index 0000000..46d6a50
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/stack-arrow-right.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/styles/device_wear_square.png b/tools/droiddoc/templates-sdk/assets/images/styles/device_wear_square.png
new file mode 100644
index 0000000..077a7e6
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/styles/device_wear_square.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/styles/device_wear_square_small.png b/tools/droiddoc/templates-sdk/assets/images/styles/device_wear_square_small.png
new file mode 100644
index 0000000..e7e1540
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/styles/device_wear_square_small.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/js/docs.js b/tools/droiddoc/templates-sdk/assets/js/docs.js
index 6630bf9..f03fb88 100644
--- a/tools/droiddoc/templates-sdk/assets/js/docs.js
+++ b/tools/droiddoc/templates-sdk/assets/js/docs.js
@@ -19,7 +19,6 @@
 
 /******  ON LOAD SET UP STUFF *********/
 
-var navBarIsFixed = false;
 $(document).ready(function() {
 
   // load json file for JD doc search suggestions
@@ -64,7 +63,12 @@
   $('.scroll-pane').jScrollPane( {verticalGutter:0} );
 
   // add HRs below all H2s (except for a few other h2 variants)
-  $('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
+  $('h2').not('#qv h2')
+         .not('#tb h2')
+         .not('.sidebox h2')
+         .not('#devdoc-nav h2')
+         .not('h2.norule').css({marginBottom:0})
+         .after('<hr/>');
 
   // set up the search close button
   $('.search .close').click(function() {
@@ -167,10 +171,24 @@
   // highlight Design tab
   if ($("body").hasClass("design")) {
     $("#header li.design a").addClass("selected");
+    $("#sticky-header").addClass("design");
 
+  // highlight About tabs
+  } else if ($("body").hasClass("about")) {
+    var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
+    if (rootDir == "about") {
+      $("#nav-x li.about a").addClass("selected");
+    } else if (rootDir == "wear") {
+      $("#nav-x li.wear a").addClass("selected");
+    } else if (rootDir == "tv") {
+      $("#nav-x li.tv a").addClass("selected");
+    } else if (rootDir == "auto") {
+      $("#nav-x li.auto a").addClass("selected");
+    }
   // highlight Develop tab
   } else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
     $("#header li.develop a").addClass("selected");
+    $("#sticky-header").addClass("develop");
     // In Develop docs, also highlight appropriate sub-tab
     var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
     if (rootDir == "training") {
@@ -195,12 +213,34 @@
   // highlight Distribute tab
   } else if ($("body").hasClass("distribute")) {
     $("#header li.distribute a").addClass("selected");
+    $("#sticky-header").addClass("distribute");
+
+    var baseFrag = pagePathOriginal.indexOf('/', 1) + 1;
+    var secondFrag = pagePathOriginal.substring(baseFrag, pagePathOriginal.indexOf('/', baseFrag));
+    if (secondFrag == "users") {
+      $("#nav-x li.users a").addClass("selected");
+    } else if (secondFrag == "engage") {
+      $("#nav-x li.engage a").addClass("selected");
+    } else if (secondFrag == "monetize") {
+      $("#nav-x li.monetize a").addClass("selected");
+    } else if (secondFrag == "tools") {
+      $("#nav-x li.disttools a").addClass("selected");
+    } else if (secondFrag == "stories") {
+      $("#nav-x li.stories a").addClass("selected");
+    } else if (secondFrag == "essentials") {
+      $("#nav-x li.essentials a").addClass("selected");
+    } else if (secondFrag == "googleplay") {
+      $("#nav-x li.googleplay a").addClass("selected");
+    }
+  } else if ($("body").hasClass("about")) {
+    $("#sticky-header").addClass("about");
   }
 
   // set global variable so we can highlight the sidenav a bit later (such as for google reference)
   // and highlight the sidenav
   mPagePath = pagePath;
   highlightSidenav();
+  buildBreadcrumbs();
 
   // set up prev/next links if they exist
   var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
@@ -215,7 +255,7 @@
     var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
 false; // navigate across topic boundaries only in design docs
     if ($prevListItem.length) {
-      if ($prevListItem.hasClass('nav-section')) {
+      if ($prevListItem.hasClass('nav-section') || crossBoundaries) {
         // jump to last topic of previous section
         $prevLink = $prevListItem.find('a:last');
       } else if (!$selListItem.hasClass('nav-section')) {
@@ -238,7 +278,6 @@
     // set up next links
     var $nextLink = [];
     var startClass = false;
-    var training = $(".next-class-link").length; // decides whether to provide "next class" link
     var isCrossingBoundary = false;
 
     if ($selListItem.hasClass('nav-section') && $selListItem.children('div.empty').length == 0) {
@@ -265,13 +304,15 @@
       if ($nextLink.length == 0) {
         isCrossingBoundary = true;
         // no more topics in this section, jump to the first topic in the next section
-        $nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)');
+        $nextLink = $selListItem.parents('li:eq(0)').next('li').find('a:eq(0)');
         if (!$nextLink.length) {  // Go up another layer to look for next page (lesson > class > course)
           $nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
           if ($nextLink.length == 0) {
             // if that doesn't work, we're at the end of the list, so disable NEXT link
             $('.next-page-link').attr('href','').addClass("disabled")
                                 .click(function() { return false; });
+            // and completely hide the one in the footer
+            $('.content-footer .next-page-link').hide();
           }
         }
       }
@@ -290,13 +331,19 @@
       $('.next-page-link').attr('href','')
                           .removeClass("hide").addClass("disabled")
                           .click(function() { return false; });
+      // and completely hide the one in the footer
+      $('.content-footer .next-page-link').hide();
       if ($nextLink.length) {
         $('.next-class-link').attr('href',$nextLink.attr('href'))
-                             .removeClass("hide").append($nextLink.html());
+                             .removeClass("hide")
+                             .append(": " + $nextLink.html());
         $('.next-class-link').find('.new').empty();
       }
     } else {
-      $('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide");
+      $('.next-page-link').attr('href', $nextLink.attr('href'))
+                          .removeClass("hide");
+      // for the footer link, also add the next page title
+      $('.content-footer .next-page-link').append(": " + $nextLink.html());
     }
 
     if (!startClass && $prevLink.length) {
@@ -308,14 +355,6 @@
       }
     }
 
-    // If this is a training 'article', there should be no prev/next nav
-    // ... if the grandparent is the "nav" ... and it has no child list items...
-    if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') &&
-        !$selListItem.find('li').length) {
-      $('.next-page-link,.prev-page-link').attr('href','').addClass("disabled")
-                          .click(function() { return false; });
-    }
-
   }
 
 
@@ -323,7 +362,20 @@
   // Set up the course landing pages for Training with class names and descriptions
   if ($('body.trainingcourse').length) {
     var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
-    var $classDescriptions = $classLinks.attr('description');
+
+    // create an array for all the class descriptions
+    var $classDescriptions = new Array($classLinks.length);
+    var lang = getLangPref();
+    $classLinks.each(function(index) {
+      var langDescr = $(this).attr(lang + "-description");
+      if (typeof langDescr !== 'undefined' && langDescr !== false) {
+        // if there's a class description in the selected language, use that
+        $classDescriptions[index] = langDescr;
+      } else {
+        // otherwise, use the default english description
+        $classDescriptions[index] = $(this).attr("description");
+      }
+    });
 
     var $olClasses  = $('<ol class="class-list"></ol>');
     var $liClass;
@@ -335,7 +387,7 @@
     $classLinks.each(function(index) {
       $liClass  = $('<li></li>');
       $h2Title  = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
-      $pSummary = $('<p class="description">' + $(this).attr('description') + '</p>');
+      $pSummary = $('<p class="description">' + $classDescriptions[index] + '</p>');
 
       $olLessons  = $('<ol class="lesson-list"></ol>');
 
@@ -374,7 +426,7 @@
     var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
     setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
     // make sidenav behave when resizing the window and side-scolling is a concern
-    if (navBarIsFixed) {
+    if (sticky) {
       if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
         updateSideNavPosition();
       } else {
@@ -385,70 +437,6 @@
   });
 
 
-  // Set up fixed navbar
-  var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
-  $(window).scroll(function(event) {
-    if ($('#side-nav').length == 0) return;
-    if (event.target.nodeName == "DIV") {
-      // Dump scroll event if the target is a DIV, because that means the event is coming
-      // from a scrollable div and so there's no need to make adjustments to our layout
-      return;
-    }
-    var scrollTop = $(window).scrollTop();
-    var headerHeight = $('#header').outerHeight();
-    var subheaderHeight = $('#nav-x').outerHeight();
-    var searchResultHeight = $('#searchResults').is(":visible") ?
-                             $('#searchResults').outerHeight() : 0;
-    var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
-    // we set the navbar fixed when the scroll position is beyond the height of the site header...
-    var navBarShouldBeFixed = scrollTop > totalHeaderHeight;
-    // ... except if the document content is shorter than the sidenav height.
-    // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
-    if ($("#doc-col").height() < $("#side-nav").height()) {
-      navBarShouldBeFixed = false;
-    }
-
-    var scrollLeft = $(window).scrollLeft();
-    // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
-    if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
-      updateSideNavPosition();
-      prevScrollLeft = scrollLeft;
-    }
-
-    // Don't continue if the header is sufficently far away
-    // (to avoid intensive resizing that slows scrolling)
-    if (navBarIsFixed && navBarShouldBeFixed) {
-      return;
-    }
-
-    if (navBarIsFixed != navBarShouldBeFixed) {
-      if (navBarShouldBeFixed) {
-        // make it fixed
-        var width = $('#devdoc-nav').width();
-        $('#devdoc-nav')
-            .addClass('fixed')
-            .css({'width':width+'px'})
-            .prependTo('#body-content');
-        // add neato "back to top" button
-        $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
-
-        // update the sidenaav position for side scrolling
-        updateSideNavPosition();
-      } else {
-        // make it static again
-        $('#devdoc-nav')
-            .removeClass('fixed')
-            .css({'width':'auto','margin':''})
-            .prependTo('#side-nav');
-        $('#devdoc-nav a.totop').hide();
-      }
-      navBarIsFixed = navBarShouldBeFixed;
-    }
-
-    resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
-  });
-
-
   var navBarLeftPos;
   if ($('#devdoc-nav').length) {
     setNavBarLeftPos();
@@ -522,7 +510,11 @@
     }
   }
 
+  // Resize once loading is finished
   resizeNav();
+  // Check if there's an anchor that we need to scroll into view.
+  // A delay is needed, because some browsers do not immediately scroll down to the anchor
+  window.setTimeout(offsetScrollForSticky, 100);
 
   /* init the language selector based on user cookie for lang */
   loadLangPref();
@@ -593,6 +585,28 @@
   });
 }
 
+
+/** Create the list of breadcrumb links in the sticky header */
+function buildBreadcrumbs() {
+  var $breadcrumbUl =  $("#sticky-header ul.breadcrumb");
+  // Add the secondary horizontal nav item, if provided
+  var $selectedSecondNav = $("div#nav-x ul.nav-x a.selected").clone().removeClass("selected");
+  if ($selectedSecondNav.length) {
+    $breadcrumbUl.prepend($("<li>").append($selectedSecondNav))
+  }
+  // Add the primary horizontal nav
+  var $selectedFirstNav = $("div#header-wrap ul.nav-x a.selected").clone().removeClass("selected");
+  // If there's no header nav item, use the logo link and title from alt text
+  if ($selectedFirstNav.length < 1) {
+    $selectedFirstNav = $("<a>")
+        .attr('href', $("div#header .logo a").attr('href'))
+        .text($("div#header .logo img").attr('alt'));
+  }
+  $breadcrumbUl.prepend($("<li>").append($selectedFirstNav));
+}
+
+
+
 /** Highlight the current page in sidenav, expanding children as appropriate */
 function highlightSidenav() {
   // if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
@@ -705,9 +719,8 @@
   // Then figure out based on scroll position whether the header is visible
   var windowHeight = $window.height();
   var scrollTop = $window.scrollTop();
-  var headerHeight = $('#header').outerHeight();
-  var subheaderHeight = $('#nav-x').outerHeight();
-  var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
+  var headerHeight = $('#header-wrapper').outerHeight();
+  var headerVisible = scrollTop < stickyTop;
 
   // get the height of space between nav and top of window.
   // Could be either margin or top position, depending on whether the nav is fixed.
@@ -717,7 +730,7 @@
   // Depending on whether the header is visible, set the side nav's height.
   if (headerVisible) {
     // The sidenav height grows as the header goes off screen
-    navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
+    navHeight = windowHeight - (headerHeight - scrollTop) - topMargin;
   } else {
     // Once header is off screen, the nav height is almost full window height
     navHeight = windowHeight - topMargin;
@@ -903,9 +916,111 @@
 /* #########     END COOKIES!     ########## */
 
 
+var sticky = false;
+var stickyTop;
+var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
+/* Sets the vertical scoll position at which the sticky bar should appear.
+   This method is called to reset the position when search results appear or hide */
+function setStickyTop() {
+  stickyTop = $('#header-wrapper').outerHeight() - $('#sticky-header').outerHeight();
+}
 
+/*
+ * Displays sticky nav bar on pages when dac header scrolls out of view
+ */
+$(window).scroll(function(event) {
 
+  setStickyTop();
+  var hiding = false;
+  var $stickyEl = $('#sticky-header');
+  var $menuEl = $('.menu-container');
+  // Exit if there's no sidenav
+  if ($('#side-nav').length == 0) return;
+  // Exit if the mouse target is a DIV, because that means the event is coming
+  // from a scrollable div and so there's no need to make adjustments to our layout
+  if ($(event.target).nodeName == "DIV") {
+    return;
+  }
 
+  var top = $(window).scrollTop();
+  // we set the navbar fixed when the scroll position is beyond the height of the site header...
+  var shouldBeSticky = top >= stickyTop;
+  // ... except if the document content is shorter than the sidenav height.
+  // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
+  if ($("#doc-col").height() < $("#side-nav").height()) {
+    shouldBeSticky = false;
+  }
+  // Account for horizontal scroll
+  var scrollLeft = $(window).scrollLeft();
+  // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
+  if (sticky && (scrollLeft != prevScrollLeft)) {
+    updateSideNavPosition();
+    prevScrollLeft = scrollLeft;
+  }
+
+  // Don't continue if the header is sufficently far away
+  // (to avoid intensive resizing that slows scrolling)
+  if (sticky == shouldBeSticky) {
+    return;
+  }
+
+  // If sticky header visible and position is now near top, hide sticky
+  if (sticky && !shouldBeSticky) {
+    sticky = false;
+    hiding = true;
+    // make the sidenav static again
+    $('#devdoc-nav')
+        .removeClass('fixed')
+        .css({'width':'auto','margin':''})
+        .prependTo('#side-nav');
+    // delay hide the sticky
+    $menuEl.removeClass('sticky-menu');
+    $stickyEl.fadeOut(250);
+    hiding = false;
+
+    // update the sidenaav position for side scrolling
+    updateSideNavPosition();
+  } else if (!sticky && shouldBeSticky) {
+    sticky = true;
+    $stickyEl.fadeIn(10);
+    $menuEl.addClass('sticky-menu');
+
+    // make the sidenav fixed
+    var width = $('#devdoc-nav').width();
+    $('#devdoc-nav')
+        .addClass('fixed')
+        .css({'width':width+'px'})
+        .prependTo('#body-content');
+
+    // update the sidenaav position for side scrolling
+    updateSideNavPosition();
+
+  } else if (hiding && top < 15) {
+    $menuEl.removeClass('sticky-menu');
+    $stickyEl.hide();
+    hiding = false;
+  }
+  resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
+});
+
+/*
+ * Manages secion card states and nav resize to conclude loading
+ */
+(function() {
+  $(document).ready(function() {
+
+    // Stack hover states
+    $('.section-card-menu').each(function(index, el) {
+      var height = $(el).height();
+      $(el).css({height:height+'px', position:'relative'});
+      var $cardInfo = $(el).find('.card-info');
+
+      $cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
+    });
+
+  });
+
+})();
 
 
 
@@ -972,8 +1087,16 @@
 }
 
 
+/* Call this to add listeners to a <select> element for Studio/Eclipse/Other docs */
+function setupIdeDocToggle() {
+  $( "select.ide" ).change(function() {
+    var selected = $(this).find("option:selected").attr("value");
+    $(".select-ide").hide();
+    $(".select-ide."+selected).show();
 
-
+    $("select.ide").val(selected);
+  });
+}
 
 
 
@@ -1724,6 +1847,7 @@
             $('.suggest-card').hide();
             if ($("#searchResults").is(":hidden") && (search.value != "")) {
               // if results aren't showing (and text not empty), return true to allow search to execute
+              $('body,html').animate({scrollTop:0}, '500', 'swing');
               return true;
             } else {
               // otherwise, results are already showing, so allow ajax to auto refresh the results
@@ -1736,8 +1860,12 @@
             return false;
         }
     }
-    // Stop here if Google results are showing
+    // If Google results are showing, return true to allow ajax search to execute
     else if ($("#searchResults").is(":visible")) {
+        // Also, if search_results is scrolled out of view, scroll to top to make results visible
+        if ((sticky ) && (search.value != "")) {
+          $('body,html').animate({scrollTop:0}, '500', 'swing');
+        }
         return true;
     }
     // 38 UP ARROW
@@ -2278,13 +2406,13 @@
   var query = document.getElementById('search_autocomplete').value;
   location.hash = 'q=' + query;
   loadSearchResults();
-  $("#searchResults").slideDown('slow');
+  $("#searchResults").slideDown('slow', setStickyTop);
   return false;
 }
 
 
 function hideResults() {
-  $("#searchResults").slideUp();
+  $("#searchResults").slideUp('fast', setStickyTop);
   $(".search .close").addClass("hide");
   location.hash = '';
 
@@ -2401,27 +2529,47 @@
     return;
   } else {
     // first time loading search results for this page
-    $('#searchResults').slideDown('slow');
+    $('#searchResults').slideDown('slow', setStickyTop);
     $(".search .close").removeClass("hide");
     loadSearchResults();
   }
 }, true);
 
+/* Adjust the scroll position to account for sticky header, only if the hash matches an id */
+function offsetScrollForSticky() {
+  var hash = escape(location.hash.substr(1));
+  var $matchingElement = $("#"+hash);
+  // If there's no element with the hash as an ID, then look for an <a name=''> with it.
+  if ($matchingElement.length < 1) {
+    $matchingElement = $('a[name="' + hash + '"]');
+  }
+  // Sanity check that there's an element with that ID on the page
+  if ($matchingElement.length) {
+    // If the position of the target element is near the top of the page (<20px, where we expect it
+    // to be because we need to move it down 60px to become in view), then move it down 60px
+    if (Math.abs($matchingElement.offset().top - $(window).scrollTop()) < 20) {
+      $(window).scrollTop($(window).scrollTop() - 60);
+    }
+  }
+}
+
 // when an event on the browser history occurs (back, forward, load) requery hash and do search
 $(window).hashchange( function(){
-  // Exit if the hash isn't a search query or there's an error in the query
+  // If the hash isn't a search query or there's an error in the query,
+  // then adjust the scroll position to account for sticky header, then exit.
   if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
     // If the results pane is open, close it.
     if (!$("#searchResults").is(":hidden")) {
       hideResults();
     }
+    offsetScrollForSticky();
     return;
   }
 
   // Otherwise, we have a search to do
   var query = decodeURI(getQuery(location.hash));
   searchControl.execute(query);
-  $('#searchResults').slideDown('slow');
+  $('#searchResults').slideDown('slow', setStickyTop);
   $("#search_autocomplete").focus();
   $(".search .close").removeClass("hide");
 
@@ -2529,7 +2677,7 @@
   }
 
 function updateSidenavFixedWidth() {
-  if (!navBarIsFixed) return;
+  if (!sticky) return;
   $('#devdoc-nav').css({
     'width' : $('#side-nav').css('width'),
     'margin' : $('#side-nav').css('margin')
@@ -2540,7 +2688,7 @@
 }
 
 function updateSidenavFullscreenWidth() {
-  if (!navBarIsFixed) return;
+  if (!sticky) return;
   $('#devdoc-nav').css({
     'width' : $('#side-nav').css('width'),
     'margin' : $('#side-nav').css('margin')
@@ -3233,3 +3381,836 @@
   $("#samples").append($ul);
 
 }
+
+
+
+/* ########################################################## */
+/* ###################  RESOURCE CARDS  ##################### */
+/* ########################################################## */
+
+/** Handle resource queries, collections, and grids (sections). Requires
+    jd_tag_helpers.js and the *_unified_data.js to be loaded. */
+
+(function() {
+  // Prevent the same resource from being loaded more than once per page.
+  var addedPageResources = {};
+
+  $(document).ready(function() {
+    $('.resource-widget').each(function() {
+      initResourceWidget(this);
+    });
+
+    /* Pass the line height to ellipsisfade() to adjust the height of the
+    text container to show the max number of lines possible, without
+    showing lines that are cut off. This works with the css ellipsis
+    classes to fade last text line and apply an ellipsis char. */
+
+    //card text currently uses 15px line height.
+    var lineHeight = 15;
+    $('.card-info .text').ellipsisfade(lineHeight);
+  });
+
+  /*
+    Three types of resource layouts:
+    Flow - Uses a fixed row-height flow using float left style.
+    Carousel - Single card slideshow all same dimension absolute.
+    Stack - Uses fixed columns and flexible element height.
+  */
+  function initResourceWidget(widget) {
+    var $widget = $(widget);
+    var isFlow = $widget.hasClass('resource-flow-layout'),
+        isCarousel = $widget.hasClass('resource-carousel-layout'),
+        isStack = $widget.hasClass('resource-stack-layout');
+
+    // find size of widget by pulling out its class name
+    var sizeCols = 1;
+    var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
+    if (m) {
+      sizeCols = parseInt(m[1], 10);
+    }
+
+    var opts = {
+      cardSizes: ($widget.data('cardsizes') || '').split(','),
+      maxResults: parseInt($widget.data('maxresults') || '100', 10),
+      itemsPerPage: $widget.data('itemsperpage'),
+      sortOrder: $widget.data('sortorder'),
+      query: $widget.data('query'),
+      section: $widget.data('section'),
+      sizeCols: sizeCols,
+      /* Added by LFL 6/6/14 */
+      resourceStyle: $widget.data('resourcestyle') || 'card',
+      stackSort: $widget.data('stacksort') || 'true'
+    };
+
+    // run the search for the set of resources to show
+
+    var resources = buildResourceList(opts);
+
+    if (isFlow) {
+      drawResourcesFlowWidget($widget, opts, resources);
+    } else if (isCarousel) {
+      drawResourcesCarouselWidget($widget, opts, resources);
+    } else if (isStack) {
+      /* Looks like this got removed and is not used, so repurposing for the
+          homepage style layout.
+          Modified by LFL 6/6/14
+      */
+      //var sections = buildSectionList(opts);
+      opts['numStacks'] = $widget.data('numstacks');
+      drawResourcesStackWidget($widget, opts, resources/*, sections*/);
+    }
+  }
+
+  /* Initializes a Resource Carousel Widget */
+  function drawResourcesCarouselWidget($widget, opts, resources) {
+    $widget.empty();
+    var plusone = true; //always show plusone on carousel
+
+    $widget.addClass('resource-card slideshow-container')
+      .append($('<a>').addClass('slideshow-prev').text('Prev'))
+      .append($('<a>').addClass('slideshow-next').text('Next'));
+
+    var css = { 'width': $widget.width() + 'px',
+                'height': $widget.height() + 'px' };
+
+    var $ul = $('<ul>');
+
+    for (var i = 0; i < resources.length; ++i) {
+      var $card = $('<a>')
+        .attr('href', cleanUrl(resources[i].url))
+        .decorateResourceCard(resources[i],plusone);
+
+      $('<li>').css(css)
+          .append($card)
+          .appendTo($ul);
+    }
+
+    $('<div>').addClass('frame')
+      .append($ul)
+      .appendTo($widget);
+
+    $widget.dacSlideshow({
+      auto: true,
+      btnPrev: '.slideshow-prev',
+      btnNext: '.slideshow-next'
+    });
+  };
+
+  /* Initializes a Resource Card Stack Widget (column-based layout)
+     Modified by LFL 6/6/14
+   */
+  function drawResourcesStackWidget($widget, opts, resources, sections) {
+    // Don't empty widget, grab all items inside since they will be the first
+    // items stacked, followed by the resource query
+    var plusone = true; //by default show plusone on section cards
+    var cards = $widget.find('.resource-card').detach().toArray();
+    var numStacks = opts.numStacks || 1;
+    var $stacks = [];
+    var urlString;
+
+    for (var i = 0; i < numStacks; ++i) {
+      $stacks[i] = $('<div>').addClass('resource-card-stack')
+          .appendTo($widget);
+    }
+
+    var sectionResources = [];
+
+    // Extract any subsections that are actually resource cards
+    if (sections) {
+      for (var i = 0; i < sections.length; ++i) {
+        if (!sections[i].sections || !sections[i].sections.length) {
+          // Render it as a resource card
+          sectionResources.push(
+            $('<a>')
+              .addClass('resource-card section-card')
+              .attr('href', cleanUrl(sections[i].resource.url))
+              .decorateResourceCard(sections[i].resource,plusone)[0]
+          );
+
+        } else {
+          cards.push(
+            $('<div>')
+              .addClass('resource-card section-card-menu')
+              .decorateResourceSection(sections[i],plusone)[0]
+          );
+        }
+      }
+    }
+
+    cards = cards.concat(sectionResources);
+
+    for (var i = 0; i < resources.length; ++i) {
+      var $card = createResourceElement(resources[i], opts);
+
+      if (opts.resourceStyle.indexOf('related') > -1) {
+        $card.addClass('related-card');
+      }
+
+      cards.push($card[0]);
+    }
+
+    if (opts.stackSort != 'false') {
+      for (var i = 0; i < cards.length; ++i) {
+        // Find the stack with the shortest height, but give preference to
+        // left to right order.
+        var minHeight = $stacks[0].height();
+        var minIndex = 0;
+
+        for (var j = 1; j < numStacks; ++j) {
+          var height = $stacks[j].height();
+          if (height < minHeight - 45) {
+            minHeight = height;
+            minIndex = j;
+          }
+        }
+
+        $stacks[minIndex].append($(cards[i]));
+      }
+    }
+
+  };
+
+  /*
+    Create a resource card using the given resource object and a list of html
+     configured options. Returns a jquery object containing the element.
+  */
+  function createResourceElement(resource, opts, plusone) {
+    var $el;
+
+    // The difference here is that generic cards are not entirely clickable
+    // so its a div instead of an a tag, also the generic one is not given
+    // the resource-card class so it appears with a transparent background
+    // and can be styled in whatever way the css setup.
+    if (opts.resourceStyle == 'generic') {
+      $el = $('<div>')
+        .addClass('resource')
+        .attr('href', cleanUrl(resource.url))
+        .decorateResource(resource, opts);
+    } else {
+      var cls = 'resource resource-card';
+
+      $el = $('<a>')
+        .addClass(cls)
+        .attr('href', cleanUrl(resource.url))
+        .decorateResourceCard(resource, plusone);
+    }
+
+    return $el;
+  }
+
+  /* Initializes a flow widget, see distribute.scss for generating accompanying css */
+  function drawResourcesFlowWidget($widget, opts, resources) {
+    $widget.empty();
+    var cardSizes = opts.cardSizes || ['6x6'];
+    var i = 0, j = 0;
+    var plusone = true; // by default show plusone on resource cards
+
+    while (i < resources.length) {
+      var cardSize = cardSizes[j++ % cardSizes.length];
+      cardSize = cardSize.replace(/^\s+|\s+$/,'');
+      // Some card sizes do not get a plusone button, such as where space is constrained
+      // or for cards commonly embedded in docs (to improve overall page speed).
+      plusone = !((cardSize == "6x2") || (cardSize == "6x3") ||
+                  (cardSize == "9x2") || (cardSize == "9x3") ||
+                  (cardSize == "12x2") || (cardSize == "12x3"));
+
+      // A stack has a third dimension which is the number of stacked items
+      var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
+      var stackCount = 0;
+      var $stackDiv = null;
+
+      if (isStack) {
+        // Create a stack container which should have the dimensions defined
+        // by the product of the items inside.
+        $stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
+            + 'x' + isStack[2] * isStack[3]) .appendTo($widget);
+      }
+
+      // Build each stack item or just a single item
+      do {
+        var resource = resources[i];
+
+        var $card = createResourceElement(resources[i], opts, plusone);
+
+        $card.addClass('resource-card-' + cardSize +
+          ' resource-card-' + resource.type);
+
+        if (isStack) {
+          $card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
+          if (++stackCount == parseInt(isStack[3])) {
+            $card.addClass('resource-card-row-stack-last');
+            stackCount = 0;
+          }
+        } else {
+          stackCount = 0;
+        }
+
+        $card.appendTo($stackDiv || $widget);
+
+      } while (++i < resources.length && stackCount > 0);
+    }
+  }
+
+  /* Build a site map of resources using a section as a root. */
+  function buildSectionList(opts) {
+    if (opts.section && SECTION_BY_ID[opts.section]) {
+      return SECTION_BY_ID[opts.section].sections || [];
+    }
+    return [];
+  }
+
+  function buildResourceList(opts) {
+    var maxResults = opts.maxResults || 100;
+
+    var query = opts.query || '';
+    var expressions = parseResourceQuery(query);
+    var addedResourceIndices = {};
+    var results = [];
+
+    for (var i = 0; i < expressions.length; i++) {
+      var clauses = expressions[i];
+
+      // build initial set of resources from first clause
+      var firstClause = clauses[0];
+      var resources = [];
+      switch (firstClause.attr) {
+        case 'type':
+          resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
+          break;
+        case 'lang':
+          resources = ALL_RESOURCES_BY_LANG[firstClause.value];
+          break;
+        case 'tag':
+          resources = ALL_RESOURCES_BY_TAG[firstClause.value];
+          break;
+        case 'collection':
+          var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
+          resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
+          break;
+        case 'section':
+          var urls = SITE_MAP[firstClause.value].sections || [];
+          resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
+          break;
+      }
+      // console.log(firstClause.attr + ':' + firstClause.value);
+      resources = resources || [];
+
+      // use additional clauses to filter corpus
+      if (clauses.length > 1) {
+        var otherClauses = clauses.slice(1);
+        resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
+      }
+
+      // filter out resources already added
+      if (i > 1) {
+        resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
+      }
+
+      // add to list of already added indices
+      for (var j = 0; j < resources.length; j++) {
+        // console.log(resources[j].title);
+        addedResourceIndices[resources[j].index] = 1;
+      }
+
+      // concat to final results list
+      results = results.concat(resources);
+    }
+
+    if (opts.sortOrder && results.length) {
+      var attr = opts.sortOrder;
+
+      if (opts.sortOrder == 'random') {
+        var i = results.length, j, temp;
+        while (--i) {
+          j = Math.floor(Math.random() * (i + 1));
+          temp = results[i];
+          results[i] = results[j];
+          results[j] = temp;
+        }
+      } else {
+        var desc = attr.charAt(0) == '-';
+        if (desc) {
+          attr = attr.substring(1);
+        }
+        results = results.sort(function(x,y) {
+          return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
+        });
+      }
+    }
+
+    results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
+    results = results.slice(0, maxResults);
+
+    for (var j = 0; j < results.length; ++j) {
+      addedPageResources[results[j].index] = 1;
+    }
+
+    return results;
+  }
+
+
+  function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
+    return function(resource) {
+      return !addedResourceIndices[resource.index];
+    };
+  }
+
+
+  function getResourceMatchesClausesFilter(clauses) {
+    return function(resource) {
+      return doesResourceMatchClauses(resource, clauses);
+    };
+  }
+
+
+  function doesResourceMatchClauses(resource, clauses) {
+    for (var i = 0; i < clauses.length; i++) {
+      var map;
+      switch (clauses[i].attr) {
+        case 'type':
+          map = IS_RESOURCE_OF_TYPE[clauses[i].value];
+          break;
+        case 'lang':
+          map = IS_RESOURCE_IN_LANG[clauses[i].value];
+          break;
+        case 'tag':
+          map = IS_RESOURCE_TAGGED[clauses[i].value];
+          break;
+      }
+
+      if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
+        return clauses[i].negative;
+      }
+    }
+    return true;
+  }
+
+  function cleanUrl(url)
+  {
+    if (url && url.indexOf('//') === -1) {
+      url = toRoot + url;
+    }
+
+    return url;
+  }
+
+
+  function parseResourceQuery(query) {
+    // Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
+    var expressions = [];
+    var expressionStrs = query.split(',') || [];
+    for (var i = 0; i < expressionStrs.length; i++) {
+      var expr = expressionStrs[i] || '';
+
+      // Break expression into clauses (clause e.g. 'tag:foo')
+      var clauses = [];
+      var clauseStrs = expr.split(/(?=[\+\-])/);
+      for (var j = 0; j < clauseStrs.length; j++) {
+        var clauseStr = clauseStrs[j] || '';
+
+        // Get attribute and value from clause (e.g. attribute='tag', value='foo')
+        var parts = clauseStr.split(':');
+        var clause = {};
+
+        clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
+        if (clause.attr) {
+          if (clause.attr.charAt(0) == '+') {
+            clause.attr = clause.attr.substring(1);
+          } else if (clause.attr.charAt(0) == '-') {
+            clause.negative = true;
+            clause.attr = clause.attr.substring(1);
+          }
+        }
+
+        if (parts.length > 1) {
+          clause.value = parts[1].replace(/^\s+|\s+$/g,'');
+        }
+
+        clauses.push(clause);
+      }
+
+      if (!clauses.length) {
+        continue;
+      }
+
+      expressions.push(clauses);
+    }
+
+    return expressions;
+  }
+})();
+
+(function($) {
+
+  /*
+    Utility method for creating dom for the description area of a card.
+    Used in decorateResourceCard and decorateResource.
+  */
+  function buildResourceCardDescription(resource, plusone) {
+    var $description = $('<div>').addClass('description ellipsis');
+
+    $description.append($('<div>').addClass('text').html(resource.summary));
+
+    if (resource.cta) {
+      $description.append($('<a>').addClass('cta').html(resource.cta));
+    }
+
+    if (plusone) {
+      var plusurl = resource.url.indexOf("//") > -1 ? resource.url :
+        "//developer.android.com/" + resource.url;
+
+      $description.append($('<div>').addClass('util')
+        .append($('<div>').addClass('g-plusone')
+          .attr('data-size', 'small')
+          .attr('data-align', 'right')
+          .attr('data-href', plusurl)));
+    }
+
+    return $description;
+  }
+
+
+  /* Simple jquery function to create dom for a standard resource card */
+  $.fn.decorateResourceCard = function(resource,plusone) {
+    var section = resource.group || resource.type;
+    var imgUrl = resource.image ||
+      'assets/images/resource-card-default-android.jpg';
+
+    if (imgUrl.indexOf('//') === -1) {
+      imgUrl = toRoot + imgUrl;
+    }
+
+    $('<div>').addClass('card-bg')
+      .css('background-image', 'url(' + (imgUrl || toRoot +
+        'assets/images/resource-card-default-android.jpg') + ')')
+      .appendTo(this);
+
+    $('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
+      .append($('<div>').addClass('section').text(section))
+      .append($('<div>').addClass('title').html(resource.title))
+      .append(buildResourceCardDescription(resource, plusone))
+      .appendTo(this);
+
+    return this;
+  };
+
+  /* Simple jquery function to create dom for a resource section card (menu) */
+  $.fn.decorateResourceSection = function(section,plusone) {
+    var resource = section.resource;
+    //keep url clean for matching and offline mode handling
+    var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
+    var $base = $('<a>')
+        .addClass('card-bg')
+        .attr('href', resource.url)
+        .append($('<div>').addClass('card-section-icon')
+          .append($('<div>').addClass('icon'))
+          .append($('<div>').addClass('section').html(resource.title)))
+      .appendTo(this);
+
+    var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
+
+    if (section.sections && section.sections.length) {
+      // Recurse the section sub-tree to find a resource image.
+      var stack = [section];
+
+      while (stack.length) {
+        if (stack[0].resource.image) {
+          $base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
+          break;
+        }
+
+        if (stack[0].sections) {
+          stack = stack.concat(stack[0].sections);
+        }
+
+        stack.shift();
+      }
+
+      var $ul = $('<ul>')
+        .appendTo($cardInfo);
+
+      var max = section.sections.length > 3 ? 3 : section.sections.length;
+
+      for (var i = 0; i < max; ++i) {
+
+        var subResource = section.sections[i];
+        if (!plusone) {
+          $('<li>')
+            .append($('<a>').attr('href', subResource.url)
+              .append($('<div>').addClass('title').html(subResource.title))
+              .append($('<div>').addClass('description ellipsis')
+                .append($('<div>').addClass('text').html(subResource.summary))
+                .append($('<div>').addClass('util'))))
+          .appendTo($ul);
+        } else {
+          $('<li>')
+            .append($('<a>').attr('href', subResource.url)
+              .append($('<div>').addClass('title').html(subResource.title))
+              .append($('<div>').addClass('description ellipsis')
+                .append($('<div>').addClass('text').html(subResource.summary))
+                .append($('<div>').addClass('util')
+                  .append($('<div>').addClass('g-plusone')
+                    .attr('data-size', 'small')
+                    .attr('data-align', 'right')
+                    .attr('data-href', resource.url)))))
+          .appendTo($ul);
+        }
+      }
+
+      // Add a more row
+      if (max < section.sections.length) {
+        $('<li>')
+          .append($('<a>').attr('href', resource.url)
+            .append($('<div>')
+              .addClass('title')
+              .text('More')))
+        .appendTo($ul);
+      }
+    } else {
+      // No sub-resources, just render description?
+    }
+
+    return this;
+  };
+
+
+
+
+  /* Render other types of resource styles that are not cards. */
+  $.fn.decorateResource = function(resource, opts) {
+    var imgUrl = resource.image ||
+      'assets/images/resource-card-default-android.jpg';
+    var linkUrl = resource.url;
+
+    if (imgUrl.indexOf('//') === -1) {
+      imgUrl = toRoot + imgUrl;
+    }
+
+    if (linkUrl && linkUrl.indexOf('//') === -1) {
+      linkUrl = toRoot + linkUrl;
+    }
+
+    $(this).append(
+      $('<div>').addClass('image')
+        .css('background-image', 'url(' + imgUrl + ')'),
+      $('<div>').addClass('info').append(
+        $('<h4>').addClass('title').html(resource.title),
+        $('<p>').addClass('summary').html(resource.summary),
+        $('<a>').attr('href', linkUrl).addClass('cta').html('Learn More')
+      )
+    );
+
+    return this;
+  };
+})(jQuery);
+
+
+/* Calculate the vertical area remaining */
+(function($) {
+    $.fn.ellipsisfade= function(lineHeight) {
+        this.each(function() {
+            // get element text
+            var $this = $(this);
+            var remainingHeight = $this.parent().parent().height();
+            $this.parent().siblings().each(function ()
+            {
+              if ($(this).is(":visible")) {
+                var h = $(this).height();
+                remainingHeight = remainingHeight - h;
+              }
+            });
+
+            adjustedRemainingHeight = ((remainingHeight)/lineHeight>>0)*lineHeight
+            $this.parent().css({'height': adjustedRemainingHeight});
+            $this.css({'height': "auto"});
+        });
+
+        return this;
+    };
+}) (jQuery);
+
+/*
+  Fullscreen Carousel
+
+  The following allows for an area at the top of the page that takes over the
+  entire browser height except for its top offset and an optional bottom
+  padding specified as a data attribute.
+
+  HTML:
+
+  <div class="fullscreen-carousel">
+    <div class="fullscreen-carousel-content">
+      <!-- content here -->
+    </div>
+    <div class="fullscreen-carousel-content">
+      <!-- content here -->
+    </div>
+
+    etc ...
+
+  </div>
+
+  Control over how the carousel takes over the screen can mostly be defined in
+  a css file. Setting min-height on the .fullscreen-carousel-content elements
+  will prevent them from shrinking to far vertically when the browser is very
+  short, and setting max-height on the .fullscreen-carousel itself will prevent
+  the area from becoming to long in the case that the browser is stretched very
+  tall.
+
+  There is limited functionality for having multiple sections since that request
+  was removed, but it is possible to add .next-arrow and .prev-arrow elements to
+  scroll between multiple content areas.
+*/
+
+(function() {
+  $(document).ready(function() {
+    $('.fullscreen-carousel').each(function() {
+      initWidget(this);
+    });
+  });
+
+  function initWidget(widget) {
+    var $widget = $(widget);
+
+    var topOffset = $widget.offset().top;
+    var padBottom = parseInt($widget.data('paddingbottom')) || 0;
+    var maxHeight = 0;
+    var minHeight = 0;
+    var $content = $widget.find('.fullscreen-carousel-content');
+    var $nextArrow = $widget.find('.next-arrow');
+    var $prevArrow = $widget.find('.prev-arrow');
+    var $curSection = $($content[0]);
+
+    if ($content.length <= 1) {
+      $nextArrow.hide();
+      $prevArrow.hide();
+    } else {
+      $nextArrow.click(function() {
+        var index = ($content.index($curSection) + 1);
+        $curSection.hide();
+        $curSection = $($content[index >= $content.length ? 0 : index]);
+        $curSection.show();
+      });
+
+      $prevArrow.click(function() {
+        var index = ($content.index($curSection) - 1);
+        $curSection.hide();
+        $curSection = $($content[index < 0 ? $content.length - 1 : 0]);
+        $curSection.show();
+      });
+    }
+
+    // Just hide all content sections except first.
+    $content.each(function(index) {
+      if ($(this).height() > minHeight) minHeight = $(this).height();
+      $(this).css({position: 'absolute',  display: index > 0 ? 'none' : ''});
+    });
+
+    // Register for changes to window size, and trigger.
+    $(window).resize(resizeWidget);
+    resizeWidget();
+
+    function resizeWidget() {
+      var height = $(window).height() - topOffset - padBottom;
+      $widget.width($(window).width());
+      $widget.height(height < minHeight ? minHeight :
+        (maxHeight && height > maxHeight ? maxHeight : height));
+    }
+  }
+})();
+
+
+
+
+
+/*
+  Tab Carousel
+
+  The following allows tab widgets to be installed via the html below. Each
+  tab content section should have a data-tab attribute matching one of the
+  nav items'. Also each tab content section should have a width matching the
+  tab carousel.
+
+  HTML:
+
+  <div class="tab-carousel">
+    <ul class="tab-nav">
+      <li><a href="#" data-tab="handsets">Handsets</a>
+      <li><a href="#" data-tab="wearable">Wearable</a>
+      <li><a href="#" data-tab="tv">TV</a>
+    </ul>
+
+    <div class="tab-carousel-content">
+      <div data-tab="handsets">
+        <!--Full width content here-->
+      </div>
+
+      <div data-tab="wearable">
+        <!--Full width content here-->
+      </div>
+
+      <div data-tab="tv">
+        <!--Full width content here-->
+      </div>
+    </div>
+  </div>
+
+*/
+(function() {
+  $(document).ready(function() {
+    $('.tab-carousel').each(function() {
+      initWidget(this);
+    });
+  });
+
+  function initWidget(widget) {
+    var $widget = $(widget);
+    var $nav = $widget.find('.tab-nav');
+    var $anchors = $nav.find('[data-tab]');
+    var $li = $nav.find('li');
+    var $contentContainer = $widget.find('.tab-carousel-content');
+    var $tabs = $contentContainer.find('[data-tab]');
+    var $curTab = $($tabs[0]); // Current tab is first tab.
+    var width = $widget.width();
+
+    // Setup nav interactivity.
+    $anchors.click(function(evt) {
+      evt.preventDefault();
+      var query = '[data-tab=' + $(this).data('tab') + ']';
+      transitionWidget($tabs.filter(query));
+    });
+
+    // Add highlight for navigation on first item.
+    var $highlight = $('<div>').addClass('highlight')
+      .css({left:$li.position().left + 'px', width:$li.outerWidth() + 'px'})
+      .appendTo($nav);
+
+    // Store height since we will change contents to absolute.
+    $contentContainer.height($contentContainer.height());
+
+    // Absolutely position tabs so they're ready for transition.
+    $tabs.each(function(index) {
+      $(this).css({position: 'absolute', left: index > 0 ? width + 'px' : '0'});
+    });
+
+    function transitionWidget($toTab) {
+      if (!$curTab.is($toTab)) {
+        var curIndex = $tabs.index($curTab[0]);
+        var toIndex = $tabs.index($toTab[0]);
+        var dir = toIndex > curIndex ? 1 : -1;
+
+        // Animate content sections.
+        $toTab.css({left:(width * dir) + 'px'});
+        $curTab.animate({left:(width * -dir) + 'px'});
+        $toTab.animate({left:'0'});
+
+        // Animate navigation highlight.
+        $highlight.animate({left:$($li[toIndex]).position().left + 'px',
+          width:$($li[toIndex]).outerWidth() + 'px'})
+
+        // Store new current section.
+        $curTab = $toTab;
+      }
+    }
+  }
+})();
\ No newline at end of file
diff --git a/tools/droiddoc/templates-sdk/assets/js/jd_tag_helpers.js b/tools/droiddoc/templates-sdk/assets/js/jd_tag_helpers.js
deleted file mode 100644
index d179cbc..0000000
--- a/tools/droiddoc/templates-sdk/assets/js/jd_tag_helpers.js
+++ /dev/null
@@ -1,106 +0,0 @@
-function mergeArrays() {
-  var arr = arguments[0] || [];
-  for (var i = 1; i < arguments.length; i++) {
-    arr = arr.concat(arguments[i]);
-  }
-  return arr;
-}
-
-var ALL_RESOURCES = mergeArrays(
-  DESIGN_RESOURCES,
-  DISTRIBUTE_RESOURCES,
-  GOOGLE_RESOURCES,
-  GUIDE_RESOURCES,
-  SAMPLES_RESOURCES,
-  TOOLS_RESOURCES,
-  TRAINING_RESOURCES,
-  YOUTUBE_RESOURCES,
-  BLOGGER_RESOURCES
-);
-
-for (var i = 0; i < ALL_RESOURCES.length; i++) {
-  ALL_RESOURCES[i].index = i;
-}
-
-function mergeMaps() {
-  var allRes = {};
-  var offset = 0;
-
-  for (var i = 0; i < arguments.length; i++) {
-    var r = arguments[i];
-    for (var tag in r.map) {
-      allRes[tag] = allRes[tag] || [];
-      allRes[tag] = allRes[tag].concat(r.map[tag].map(function(i){ return ALL_RESOURCES[i + offset]; }));
-    }
-    offset += r.arr.length;
-  }
-
-  return allRes;
-}
-
-function setFromArray(arr) {
-  arr = arr || [];
-  var set = {};
-  for (var i = 0; i < arr.length; i++) {
-    set[arr[i]] = true;
-  }
-  return set;
-}
-
-function buildResourceLookupMap(resourceDict) {
-  var map = {};
-  for (var key in resourceDict) {
-    var dictForKey = {};
-    var srcArr = resourceDict[key];
-    for (var i = 0; i < srcArr.length; i++) {
-      dictForKey[srcArr[i].index] = true;
-    }
-    map[key] = dictForKey;
-  }
-  return map;
-}
-
-// Type lookups
-
-var ALL_RESOURCES_BY_TYPE = {
-  'design': DESIGN_RESOURCES,
-  'distribute': DISTRIBUTE_RESOURCES,
-  'google': GOOGLE_RESOURCES,
-  'guide': GUIDE_RESOURCES,
-  'samples': SAMPLES_RESOURCES,
-  'tools': TOOLS_RESOURCES,
-  'training': TRAINING_RESOURCES,
-  'youtube': YOUTUBE_RESOURCES,
-  'blog': BLOGGER_RESOURCES
-};
-var IS_RESOURCE_OF_TYPE = buildResourceLookupMap(ALL_RESOURCES_BY_TYPE);
-
-// Tag lookups
-
-var ALL_RESOURCES_BY_TAG = mergeMaps(
-  {map:DESIGN_BY_TAG,arr:DESIGN_RESOURCES},
-  {map:DISTRIBUTE_BY_TAG,arr:DISTRIBUTE_RESOURCES},
-  {map:GOOGLE_BY_TAG,arr:GOOGLE_RESOURCES},
-  {map:GUIDE_BY_TAG,arr:GUIDE_RESOURCES},
-  {map:SAMPLES_BY_TAG,arr:SAMPLES_RESOURCES},
-  {map:TOOLS_BY_TAG,arr:TOOLS_RESOURCES},
-  {map:TRAINING_BY_TAG,arr:TRAINING_RESOURCES},
-  {map:YOUTUBE_BY_TAG,arr:YOUTUBE_RESOURCES},
-  {map:BLOGGER_BY_TAG,arr:BLOGGER_RESOURCES}
-);
-var IS_RESOURCE_TAGGED = buildResourceLookupMap(ALL_RESOURCES_BY_TAG);
-
-// Language lookups
-
-var ALL_RESOURCES_BY_LANG = {};
-for (var i = 0; i < ALL_RESOURCES.length; i++) {
-  var res = ALL_RESOURCES[i];
-  var lang = res.lang;
-  if (!lang) {
-    continue;
-  }
-
-  ALL_RESOURCES_BY_LANG[lang] = ALL_RESOURCES_BY_LANG[lang] || [];
-  ALL_RESOURCES_BY_LANG[lang].push(res);
-}
-var IS_RESOURCE_IN_LANG = buildResourceLookupMap(ALL_RESOURCES_BY_LANG);
\ No newline at end of file
diff --git a/tools/droiddoc/templates-sdk/assets/js/resourcecards.js b/tools/droiddoc/templates-sdk/assets/js/resourcecards.js
deleted file mode 100644
index fbba201..0000000
--- a/tools/droiddoc/templates-sdk/assets/js/resourcecards.js
+++ /dev/null
@@ -1,244 +0,0 @@
-// Requires jd_tag_helpers.js and the data JS to be loaded.
-
-$(document).ready(function() {
-  $('.resource-widget').each(function() {
-    initResourceWidget(this);
-  });
-});
-
-
-function initResourceWidget(widget) {
-  var $widget = $(widget);
-  var isFlow, isCarousel;
-  isFlow = $widget.hasClass('resource-flow-layout');
-  if (!isFlow) {
-    isCarousel = $widget.hasClass('resource-carousel-layout');
-  }
-
-  // find size of widget by pulling out its class name
-  var sizeCols = 1;
-  var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
-  if (m) {
-    sizeCols = parseInt(m[1], 10);
-  }
-
-  var opts = {
-    source: $widget.data('source'),
-    cardSizes: ($widget.data('cardsizes') || '').split(','),
-    maxResults: parseInt($widget.data('maxresults') || '100'),
-    itemsPerPage: $widget.data('itemsperpage'),
-    sortOrder: $widget.data('sortorder'),
-    query: $widget.data('query'),
-    collectionId: $widget.data('collectionid'),
-    sizeCols: sizeCols
-  };
-
-  // run the search for the set of resources to show
-  var resources = buildResourceList(opts);
-
-  if (isFlow) {
-    drawResourcesFlowWidget($widget, opts, resources);
-  }
-}
-
-
-function drawResourcesFlowWidget($widget, opts, resources) {
-  $widget.empty();
-  var cardSizes = opts.cardSizes || ['4x3'];
-
-  for (var i = 0; i < resources.length; i++) {
-    var resource = resources[i];
-
-    var cardSize = i >= cardSizes.length ? cardSizes[cardSizes.length - 1] : cardSizes[i];
-    cardSize = cardSize.replace(/^\s+|\s+$/,'');
-
-    var $card = $('<a>')
-        .addClass('resource-card resource-card-' + cardSize + ' resource-card-' + resource.type)
-        .attr('href', resource.url);
-
-    $('<img>')
-        .addClass('photo')
-        .attr('src', resource.image || '')
-        .appendTo($card);
-
-    var subtitle = resource.type;
-    if (resource.timestamp) {
-      var d = new Date(resource.timestamp);
-      // TODO: localize, humanize
-      subtitle = (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear() + ' on ' + subtitle;
-    }
-
-    $('<div>')
-        .addClass('resource-card-text')
-        .append($('<div>').addClass('icon'))
-        .append($('<div>').addClass('title').text(resource.title))
-        .append($('<div>').addClass('subtitle').text(subtitle))
-        .append($('<div>').addClass('abstract').text(resource.summary))
-        .appendTo($card);
-
-    $card.appendTo($widget);
-  }
-
-  $widget.find('.resource-card .photo').each(function() {
-    var src = $(this).attr('src');
-    if (!src) {
-      $(this).parents('.resource-card').addClass('nophoto');
-      $(this).replaceWith($('<div>')
-          .addClass('photo'));
-    } else {
-      $(this).replaceWith($('<div>')
-          .addClass('photo')
-          .css('background-image', 'url(' + $(this).attr('src') + ')'));
-    }
-  });
-}
-
-
-function buildResourceList(opts) {
-  var maxResults = opts.maxResults || 100;
-
-  switch (opts.source) {
-    case 'query':
-      var query = opts.query || '';
-      var expressions = parseResourceQuery(query);
-      var alreadyAddedResources = {};
-      var allResources = [];
-      for (var i = 0; i < expressions.length; i++) {
-        var clauses = expressions[i];
-
-        // build initial set of resources from first clause
-        var firstClause = clauses[0];
-        var resources = [];
-        switch (firstClause.attr) {
-          case 'type':
-            resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
-            break;
-          case 'lang':
-            resources = ALL_RESOURCES_BY_LANG[firstClause.value];
-            break;
-          case 'tag':
-            resources = ALL_RESOURCES_BY_TAG[firstClause.value];
-            break;
-        }
-        resources = resources || [];
-
-        // use additional clauses to filter corpus
-        if (clauses.length > 1) {
-          var otherClauses = clauses.slice(1);
-          resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
-        }
-
-        // filter out resources already added
-        if (i > 1) {
-          resources = resources.filter(getResourceNotAlreadyAddedFilter(alreadyAddedResources));
-        }
-
-        allResources = allResources.concat(resources);
-        if (allResources.length > maxResults) {
-          break;
-        }
-      }
-      if (opts.sortOrder) {
-        var attr = opts.sortOrder;
-        var desc = attr.charAt(0) == '-';
-        if (desc) {
-          attr = attr.substring(1);
-        }
-        allResources = allResources.sort(function(x,y) {
-          return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
-        });
-      }
-      return allResources.slice(0, maxResults);
-
-    case 'related':
-      // TODO
-      break;
-
-    case 'collection':
-      // TODO
-      break;
-  }
-}
-
-
-function getResourceNotAlreadyAddedFilter(addedResources) {
-  return function(x) {
-    return !!addedResources[x];
-  };
-}
-
-
-function getResourceMatchesClausesFilter(clauses) {
-  return function(x) {
-    return doesResourceMatchClauses(x, clauses);
-  };
-}
-
-
-function doesResourceMatchClauses(resource, clauses) {
-  for (var i = 0; i < clauses.length; i++) {
-    var map;
-    switch (clauses[i].attr) {
-      case 'type':
-        map = IS_RESOURCE_OF_TYPE[clauses[i].value];
-        break;
-      case 'lang':
-        map = IS_RESOURCE_IN_LANG[clauses[i].value];
-        break;
-      case 'tag':
-        map = IS_RESOURCE_TAGGED[clauses[i].value];
-        break;
-    }
-
-    if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
-      return false;
-    }
-  }
-  return true;
-}
-
-
-function parseResourceQuery(query) {
-  // Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
-  var expressions = [];
-  var expressionStrs = query.split(',') || [];
-  for (var i = 0; i < expressionStrs.length; i++) {
-    var expr = expressionStrs[i] || '';
-
-    // Break expression into clauses (clause e.g. 'tag:foo')
-    var clauses = [];
-    var clauseStrs = expr.split(/(?=[\+\-])/);
-    for (var j = 0; j < clauseStrs.length; j++) {
-      var clauseStr = clauseStrs[j] || '';
-
-      // Get attribute and value from clause (e.g. attribute='tag', value='foo')
-      var parts = clauseStr.split(':');
-      var clause = {};
-
-      clause.attr = parts[0].replace(/\s+/g,'');
-      if (clause.attr) {
-        if (clause.attr.charAt(0) == '+') {
-          clause.attr = clause.attr.substring(1);
-        } else if (clause.attr.charAt(0) == '-') {
-          clause.negative = true;
-          clause.attr = clause.attr.substring(1);
-        }
-      }
-
-      if (parts.length > 1) {
-        clause.value = parts[1].replace(/\s+/g,'');
-      }
-
-      clauses.push(clause);
-    }
-
-    if (!clauses.length) {
-      continue;
-    }
-
-    expressions.push(clauses);
-  }
-
-  return expressions;
-}
-
diff --git a/tools/droiddoc/templates-sdk/components/masthead.cs b/tools/droiddoc/templates-sdk/components/masthead.cs
index beead52..c880eee 100644
--- a/tools/droiddoc/templates-sdk/components/masthead.cs
+++ b/tools/droiddoc/templates-sdk/components/masthead.cs
@@ -1,231 +1,160 @@
 <?cs def:custom_masthead() ?>
-<?cs if:wear ?>
-  <?cs call:wear_masthead() ?>
+<?cs if:preview ?>
+  <?cs call:preview_masthead() ?>
 <?cs else ?>
 <a name="top"></a>
-<?cs if:!devsite ?><?cs # leave out the global header for devsite; it's in devsite template ?>
-    <!-- Header -->
+<?cs if:!devsite ?><?cs # leave out the global header for devsite; it is in devsite template ?>
+  <!-- Header -->
+  <div id="header-wrapper">
     <div id="header">
-        <div class="wrap" id="header-wrap">
-          <div class="col-3 logo">
+      <div class="wrap" id="header-wrap">
+        <div class="col-3 logo">
           <a href="<?cs var:toroot ?>index.html">
             <img src="<?cs var:toroot ?>assets/images/dac_logo.png"
                 srcset="<?cs var:toroot ?>assets/images/dac_logo@2x.png 2x"
                 width="123" height="25" alt="Android Developers" />
           </a>
           <div class="btn-quicknav" id="btn-quicknav">
-          	<a href="#" class="arrow-inactive">Quicknav</a>
-			      <a href="#" class="arrow-active">Quicknav</a>
+            <a href="#" class="arrow-inactive">Quicknav</a>
+            <a href="#" class="arrow-active">Quicknav</a>
           </div>
-          </div>
-            <ul class="nav-x col-9">
-                <li class="design">
-                  <a href="<?cs var:toroot ?>design/index.html"
-                  zh-tw-lang="設計"
-                  zh-cn-lang="设计"
-                  ru-lang="Проектирование"
-                  ko-lang="디자인"
-                  ja-lang="設計"
-                  es-lang="Diseñar"               
-                  >Design</a></li>
-                <li class="develop"><a href="<?cs var:toroot ?>develop/index.html"
-                  zh-tw-lang="開發"
-                  zh-cn-lang="开发"
-                  ru-lang="Разработка"
-                  ko-lang="개발"
-                  ja-lang="開発"
-                  es-lang="Desarrollar"               
-                  >Develop</a></li>
-                <li class="distribute last"><a href="<?cs var:toroot ?>distribute/index.html"
-                  zh-tw-lang="發佈"
-                  zh-cn-lang="分发"
-                  ru-lang="Распространение"
-                  ko-lang="배포"
-                  ja-lang="配布"
-                  es-lang="Distribuir"               
-                  >Distribute</a></li>
+        </div>
+        <ul class="nav-x col-9">
+            <li class="design">
+              <a href="<?cs var:toroot ?>design/index.html"
+              zh-tw-lang="設計"
+              zh-cn-lang="设计"
+              ru-lang="Проектирование"
+              ko-lang="디자인"
+              ja-lang="設計"
+              es-lang="Diseñar"
+              >Design</a></li>
+            <li class="develop"><a href="<?cs var:toroot ?>develop/index.html"
+              zh-tw-lang="開發"
+              zh-cn-lang="开发"
+              ru-lang="Разработка"
+              ko-lang="개발"
+              ja-lang="開発"
+              es-lang="Desarrollar"
+              >Develop</a></li>
+            <li class="distribute last"><a href="<?cs var:toroot ?>distribute/<?cs
+              if:android.whichdoc == "offline" ?>googleplay/<?cs /if ?>index.html"
+              zh-tw-lang="發佈"
+              zh-cn-lang="分发"
+              ru-lang="Распространение"
+              ko-lang="배포"
+              ja-lang="配布"
+              es-lang="Distribuir"
+              >Distribute</a></li>
+        </ul>
+
+
+        <?cs # ADD SEARCH AND MENU ?>
+        <?cs call:header_search_widget() ?>
+
+
+        <!-- Expanded quicknav -->
+        <div id="quicknav" class="col-13">
+          <ul>
+            <li class="about">
+              <ul>
+                <li><a href="<?cs var:toroot ?>about/index.html">About</a></li>
+                <li><a href="<?cs var:toroot ?>wear/index.html">Wear</a></li>
+                <li><a href="<?cs var:toroot ?>tv/index.html">TV</a></li>
+                <li><a href="<?cs var:toroot ?>auto/index.html">Auto</a></li>
+              </ul>
+            </li>
+            <li class="design">
+              <ul>
+                <li><a href="<?cs var:toroot ?>design/index.html">Get Started</a></li>
+                <li><a href="<?cs var:toroot ?>design/devices.html">Devices</a></li>
+                <li><a href="<?cs var:toroot ?>design/style/index.html">Style</a></li>
+                <li><a href="<?cs var:toroot ?>design/patterns/index.html">Patterns</a></li>
+                <li><a href="<?cs var:toroot ?>design/building-blocks/index.html">Building Blocks</a></li>
+                <li><a href="<?cs var:toroot ?>design/downloads/index.html">Downloads</a></li>
+                <li><a href="<?cs var:toroot ?>design/videos/index.html">Videos</a></li>
+              </ul>
+            </li>
+            <li class="develop">
+              <ul>
+                <li><a href="<?cs var:toroot ?>training/index.html"
+                  zh-tw-lang="訓練課程"
+                  zh-cn-lang="培训"
+                  ru-lang="Курсы"
+                  ko-lang="교육"
+                  ja-lang="トレーニング"
+                  es-lang="Capacitación"
+                  >Training</a></li>
+                <li><a href="<?cs var:toroot ?>guide/index.html"
+                  zh-tw-lang="API 指南"
+                  zh-cn-lang="API 指南"
+                  ru-lang="Руководства по API"
+                  ko-lang="API 가이드"
+                  ja-lang="API ガイド"
+                  es-lang="Guías de la API"
+                  >API Guides</a></li>
+                <li><a href="<?cs var:toroot ?>reference/packages.html"
+                  zh-tw-lang="參考資源"
+                  zh-cn-lang="参考"
+                  ru-lang="Справочник"
+                  ko-lang="참조문서"
+                  ja-lang="リファレンス"
+                  es-lang="Referencia"
+                  >Reference</a></li>
+                <li><a href="<?cs var:toroot ?>sdk/index.html"
+                  zh-tw-lang="相關工具"
+                  zh-cn-lang="工具"
+                  ru-lang="Инструменты"
+                  ko-lang="도구"
+                  ja-lang="ツール"
+                  es-lang="Herramientas"
+                  >Tools</a>
+                </li>
+                <li><a href="<?cs var:toroot ?>google/index.html">Google Services</a>
+                </li>
+                <?cs if:android.hasSamples ?>
+                  <li><a href="<?cs var:toroot ?>samples/index.html">Samples</a>
+                  </li>
+                <?cs /if ?>
+              </ul>
+            </li>
+            <li class="distribute last">
+              <ul>
+                <li><a href="<?cs var:toroot ?>distribute/googleplay/index.html">Google Play</a></li>
+                <li><a href="<?cs var:toroot ?>distribute/essentials/index.html">Essentials</a></li>
+                <li><a href="<?cs var:toroot ?>distribute/users/index.html">Get Users</a></li>
+                <li><a href="<?cs var:toroot ?>distribute/engage/index.html">Engage &amp; Retain</a></li>
+                <li><a href="<?cs var:toroot ?>distribute/monetize/index.html">Monetize</a></li>
+                <li><a href="<?cs var:toroot ?>distribute/tools/index.html">Tools &amp; Reference</a></li>
+                <li><a href="<?cs var:toroot ?>distribute/stories/index.html">Developer Stories</a></li>
+              </ul>
+            </li>
+          </ul>
+        </div><!-- /Expanded quicknav -->
+      </div><!-- end header-wrap.wrap -->
+    </div><!-- end header -->
+
+  <?cs if:about || wear || tv || auto ?>
+    <!-- Secondary x-nav -->
+    <div id="nav-x">
+        <div class="wrap">
+            <ul class="nav-x col-9 about" style="width:100%">
+                <li class="about"><a href="<?cs var:toroot ?>about/index.html"
+                  >About</a></li>
+                <li class="wear"><a href="<?cs var:toroot ?>wear/index.html"
+                  >Wear</a></li>
+                <li class="tv"><a href="<?cs var:toroot ?>tv/index.html"
+                  >TV</a></li>
+                <li class="auto"><a href="<?cs var:toroot ?>auto/index.html"
+                  >Auto</a></li>
             </ul>
-            
-            <!-- New Search -->
-            <div class="menu-container">
-            <div class="moremenu">
-    <div id="more-btn"></div>
-  </div>
-  <div class="morehover" id="moremenu">
-    <div class="top"></div>
-    <div class="mid">
-      <div class="header">Links</div>
-      <ul>
-        <li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
-        <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
-        <li><a href="<?cs var:toroot ?>about/index.html">About Android</a></li>
-      </ul>
-      <div class="header">Android Sites</div>
-      <ul>
-        <li><a href="http://www.android.com">Android.com</a></li>
-        <li class="active"><a>Android Developers</a></li>
-        <li><a href="http://source.android.com">Android Open Source Project</a></li>
-      </ul>
-      
-      <?cs # Include language switcher only in online docs ?>
-      <?cs if:android.whichdoc == "online" ?>
-        <div class="header">Language</div>
-          <div id="language" class="locales">
-            <select name="language" onChange="changeLangPref(this.value, true)">
-                <option value="en">English</option>
-                <option value="es">Español</option>
-                <option value="ja">日本語</option>
-                <option value="ko">한국어</option>
-                <option value="ru">Русский</option>
-                <option value="zh-cn">中文 (中国)</option>
-                <option value="zh-tw">中文 (台灣)</option>
-            </select>
-          </div>
-        <script type="text/javascript">
-          <!--
-          loadLangPref();
-            //-->
-        </script>
-      <?cs /if ?>
-      <?cs # End of lang switcher ?>
-
-
-      <br class="clearfix" />
-    </div>
-    <div class="bottom"></div>
-  </div>
-  <div class="search" id="search-container">
-    <div class="search-inner">
-      <div id="search-btn"></div>
-      <div class="left"></div>
-      <form onsubmit="return submit_search()">
-        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
-onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
-onkeydown="return search_changed(event, true, '<?cs var:toroot ?>')" 
-onkeyup="return search_changed(event, false, '<?cs var:toroot ?>')" />
-      </form>
-      <div class="right"></div>
-        <a class="close hide">close</a>
-        <div class="left"></div>
-        <div class="right"></div>
-    </div>
-  </div>
-
-  <div class="search_filtered_wrapper reference">
-    <div class="suggest-card reference no-display">
-      <ul class="search_filtered">
-      </ul>
-    </div>
-  </div>
-
-  <div class="search_filtered_wrapper docs">
-    <div class="suggest-card dummy no-display">&nbsp;</div>
-    <div class="suggest-card develop no-display">
-      <ul class="search_filtered">
-      </ul>
-      <div class="child-card guides no-display">
-      </div>
-      <div class="child-card training no-display">
-      </div>
-      <div class="child-card samples no-display">
-      </div>
-    </div>
-    <div class="suggest-card design no-display">
-      <ul class="search_filtered">
-      </ul>
-    </div>
-    <div class="suggest-card distribute no-display">
-      <ul class="search_filtered">
-      </ul>
-    </div>
-  </div>
-
-  </div>
-  <!-- /New Search>
-          
-          
-          <!-- Expanded quicknav -->
-           <div id="quicknav" class="col-9">
-                <ul>
-                    <li class="design">
-                      <ul>
-                        <li><a href="<?cs var:toroot ?>design/index.html">Get Started</a></li>
-                        <li><a href="<?cs var:toroot ?>design/style/index.html">Style</a></li>
-                        <li><a href="<?cs var:toroot ?>design/patterns/index.html">Patterns</a></li>
-                        <li><a href="<?cs var:toroot ?>design/building-blocks/index.html">Building Blocks</a></li>
-                        <li><a href="<?cs var:toroot ?>design/downloads/index.html">Downloads</a></li>
-                        <li><a href="<?cs var:toroot ?>design/videos/index.html">Videos</a></li>
-                      </ul>
-                    </li>
-                    <li class="develop">
-                      <ul>
-                        <li><a href="<?cs var:toroot ?>training/index.html"
-                          zh-tw-lang="訓練課程"
-                          zh-cn-lang="培训"
-                          ru-lang="Курсы"
-                          ko-lang="교육"
-                          ja-lang="トレーニング"
-                          es-lang="Capacitación"               
-                          >Training</a></li>
-                        <li><a href="<?cs var:toroot ?>guide/index.html"
-                          zh-tw-lang="API 指南"
-                          zh-cn-lang="API 指南"
-                          ru-lang="Руководства по API"
-                          ko-lang="API 가이드"
-                          ja-lang="API ガイド"
-                          es-lang="Guías de la API"               
-                          >API Guides</a></li>
-                        <li><a href="<?cs var:toroot ?>reference/packages.html"
-                          zh-tw-lang="參考資源"
-                          zh-cn-lang="参考"
-                          ru-lang="Справочник"
-                          ko-lang="참조문서"
-                          ja-lang="リファレンス"
-                          es-lang="Referencia"               
-                          >Reference</a></li>
-                        <li><a href="<?cs var:toroot ?>tools/index.html"
-                          zh-tw-lang="相關工具"
-                          zh-cn-lang="工具"
-                          ru-lang="Инструменты"
-                          ko-lang="도구"
-                          ja-lang="ツール"
-                          es-lang="Herramientas"               
-                          >Tools</a>
-                          <ul><li><a href="<?cs var:toroot ?>sdk/index.html">Get the SDK</a></li></ul>
-                        </li>
-                        <li><a href="<?cs var:toroot ?>google/index.html">Google Services</a>
-                        </li>
-                        <?cs if:android.hasSamples ?>
-                          <li><a href="<?cs var:toroot ?>samples/index.html">Samples</a>
-                          </li>
-                        <?cs /if ?>
-                      </ul>
-                    </li>
-                    <li class="distribute last">
-                      <ul>
-                        <li><a href="<?cs var:toroot ?>distribute/index.html">Google Play</a></li>
-                        <li><a href="<?cs var:toroot ?>distribute/googleplay/publish/index.html">Publishing</a></li>
-                        <li><a href="<?cs var:toroot ?>distribute/googleplay/promote/index.html">Promoting</a></li>
-                        <li><a href="<?cs var:toroot ?>distribute/googleplay/quality/index.html">App Quality</a></li>
-                        <li><a href="<?cs var:toroot ?>distribute/googleplay/spotlight/index.html">Spotlight</a></li>
-                        <li><a href="<?cs var:toroot ?>distribute/open.html">Open Distribution</a></li>
-                      </ul>
-                    </li>
-                </ul>
-          </div>
-          <!-- /Expanded quicknav -->
         </div>
     </div>
-    <!-- /Header -->
-    
-    
-  <div id="searchResults" class="wrap" style="display:none;">
-          <h2 id="searchTitle">Results</h2>
-          <div id="leftSearchControl" class="search-control">Loading...</div>
-  </div>
-    
-    
-  <?cs if:training || guide || reference || tools || develop || google || samples ?>
+    <!-- /Sendondary x-nav ABOUT -->
+
+
+
+  <?cs elif:training || guide || reference || tools || develop || google || samples ?>
     <!-- Secondary x-nav -->
     <div id="nav-x">
         <div class="wrap">
@@ -236,7 +165,7 @@
                   ru-lang="Курсы"
                   ko-lang="교육"
                   ja-lang="トレーニング"
-                  es-lang="Capacitación"               
+                  es-lang="Capacitación"
                   >Training</a></li>
                 <li class="guide"><a href="<?cs var:toroot ?>guide/index.html"
                   zh-tw-lang="API 指南"
@@ -244,7 +173,7 @@
                   ru-lang="Руководства по API"
                   ko-lang="API 가이드"
                   ja-lang="API ガイド"
-                  es-lang="Guías de la API"               
+                  es-lang="Guías de la API"
                   >API Guides</a></li>
                 <li class="reference"><a href="<?cs var:toroot ?>reference/packages.html"
                   zh-tw-lang="參考資源"
@@ -252,9 +181,9 @@
                   ru-lang="Справочник"
                   ko-lang="참조문서"
                   ja-lang="リファレンス"
-                  es-lang="Referencia"               
+                  es-lang="Referencia"
                   >Reference</a></li>
-                <li class="tools"><a href="<?cs var:toroot ?>tools/index.html"
+                <li class="tools"><a href="<?cs var:toroot ?>sdk/index.html"
                   zh-tw-lang="相關工具"
                   zh-cn-lang="工具"
                   ru-lang="Инструменты"
@@ -272,144 +201,101 @@
                 <?cs /if ?>
             </ul>
         </div>
-        
     </div>
-    <!-- /Sendondary x-nav -->
+    <!-- /Sendondary x-nav DEVELOP -->
+
+  <?cs elif:distribute || googleplay || essentials || users || engage || monetize || disttools || stories ?>
+    <!-- Secondary distribute x-nav -->
+    <div id="nav-x">
+        <div class="wrap">
+            <ul class="nav-x distribute">
+                <li class="googleplay"><a href="<?cs var:toroot ?>distribute/googleplay/index.html"
+                  >Google Play</a></li>
+                <li class="essentials"><a href="<?cs var:toroot ?>distribute/essentials/index.html"
+                  >Essentials</a></li>
+                <li class="users"><a href="<?cs var:toroot ?>distribute/users/index.html"
+                  >Get Users</a></li>
+                <li class="engage"><a href="<?cs var:toroot ?>distribute/engage/index.html"
+                  >Engage &amp; Retain</a></li>
+                <li class="monetize"><a href="<?cs var:toroot ?>distribute/monetize/index.html"
+                  >Monetize</a>
+                </li>
+                <li class="disttools"><a href="<?cs var:toroot ?>distribute/tools/index.html"
+                  >Tools</a>
+                </li>
+                <li class="stories"><a href="<?cs var:toroot ?>distribute/stories/index.html"
+                  >Stories</a>
+                </li>
+            </ul>
+            <a href="https://play.google.com/apps/publish/" class="developer-console-btn">Developer Console</a>
+        </div> <!-- /Secondary distribute x-nav -->
+    </div>
+    <!-- /Sendondary x-nav DISTRIBUTE -->
   <?cs /if ?>
 
-<?cs /if ?>
-<?cs # end if/else !devsite ?>
+    <div id="searchResults" class="wrap" style="display:none;">
+      <h2 id="searchTitle">Results</h2>
+      <div id="leftSearchControl" class="search-control">Loading...</div>
+    </div>
+  </div> <!--end header-wrapper -->
 
-<?cs /if ?><?cs # end if/else wear ?>
-  <?cs
+  <div id="sticky-header">
+    <div>
+      <a class="logo" href="#top"></a>
+      <a class="top" href="#top"></a>
+      <ul class="breadcrumb">
+        <?cs # More <li> elements added here with javascript ?>
+        <?cs if:!section.landing ?><li class="current"><?cs var:page.title ?></li><?cs
+        /if ?>
+      </ul>
+    </div>
+  </div>
+
+<?cs /if ?><?cs # end if/else !devsite ?>
+<?cs /if ?><?cs # end if/else preview ?><?cs
 /def ?>
 
-
-<?cs def:wear_masthead() ?>
+<?cs def:preview_masthead() ?>
 <a name="top"></a>
 
-    <!-- Header -->
-    <div id="header">
-        <div class="wrap" id="header-wrap">
-          <div class="col-3 logo-wear">
-          <a href="<?cs var:toroot ?>wear/index.html">
-            <img src="<?cs var:toroot ?>wear/images/android-wear.png" height="16" alt="Android Wear" />
-          </a>
-          </div>
 
-
-        <div class="col-8" style="margin:0"><h1 style="margin:1px 0 0 20px;padding:0;line-height:16px;
-  color:#666;font-weight:100;font-size:24px;">Developer Preview</h1></div>
-
-
-          <!-- New Search -->
-          <div class="menu-container">
-            <div class="moremenu">
-          <div id="more-btn"></div>
-	    </div>
-  <div class="morehover" id="moremenu">
-    <div class="top"></div>
-    <div class="mid">
-      <div class="header">Links</div>
-      <ul>
-        <li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
-        <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
-        <li><a href="<?cs var:toroot ?>about/index.html">About Android</a></li>
-      </ul>
-      <div class="header">Android Sites</div>
-      <ul>
-        <li><a href="http://www.android.com">Android.com</a></li>
-        <li class="active"><a>Android Developers</a></li>
-        <li><a href="http://source.android.com">Android Open Source Project</a></li>
-      </ul>
-
-      <?cs # Include language switcher only in online docs ?>
-      <?cs if:android.whichdoc == "online" ?>
-        <div class="header">Language</div>
-          <div id="language" class="locales">
-            <select name="language" onChange="changeLangPref(this.value, true)">
-                <option value="en">English</option>
-                <option value="es">Español</option>
-                <option value="ja">日本語</option>
-                <option value="ko">한국어</option>
-                <option value="ru">Русский</option>
-                <option value="zh-cn">中文 (中国)</option>
-                <option value="zh-tw">中文 (台灣)</option>
-            </select>
-          </div>
-        <script type="text/javascript">
-          <!--
-          loadLangPref();
-            //-->
-        </script>
-      <?cs /if ?>
-      <?cs # End of lang switcher ?>
-
-
-      <br class="clearfix" />
-    </div><!-- end mid -->
-    <div class="bottom"></div>
-  </div><!-- end morehover -->
-
-  <div class="search" id="search-container">
-    <div class="search-inner">
-      <div id="search-btn"></div>
-      <div class="left"></div>
-      <form onsubmit="return submit_search()">
-        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
-onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
-onkeydown="return search_changed(event, true, '<?cs var:toroot ?>')"
-onkeyup="return search_changed(event, false, '<?cs var:toroot ?>')" />
-      </form>
-      <div class="right"></div>
-        <a class="close hide">close</a>
-        <div class="left"></div>
-        <div class="right"></div>
-    </div>
-  </div><!--  end search -->
-
-  <div class="search_filtered_wrapper reference">
-    <div class="suggest-card reference no-display">
-      <ul class="search_filtered">
-      </ul>
-    </div>
-  </div>
-
-  <div class="search_filtered_wrapper docs">
-    <div class="suggest-card dummy no-display">&nbsp;</div>
-    <div class="suggest-card develop no-display">
-      <ul class="search_filtered">
-      </ul>
-      <div class="child-card guides no-display">
+<!-- Header -->
+<div id="header-wrapper">
+  <div id="header">
+    <div class="wrap" id="header-wrap">
+      <div class="col_3 logo landing-logo" style="width:240px">
+        <a href="<?cs var:toroot ?>preview/index.html">
+          <img src="<?cs var:toroot ?>assets/images/android.png" height="25" alt="Android"
+            style="margin:-3px 0 0" />
+        </a>
       </div>
-      <div class="child-card training no-display">
-      </div>
-      <div class="child-card samples no-display">
-      </div>
-    </div>
-    <div class="suggest-card design no-display">
-      <ul class="search_filtered">
-      </ul>
-    </div>
-    <div class="suggest-card distribute no-display">
-      <ul class="search_filtered">
-      </ul>
-    </div>
-  </div><!-- end search_filtered_wrapper -->
+      <div class="col-8" style="margin:0"><h1 style="margin: 4px 0 0 0px;padding:0;line-height:16px;
+color:#666;font-weight:100;font-size:27px;">L Developer Preview</h1></div>
 
-  </div>
-  <!-- end menu_container -->
+      <?cs # ADD SEARCH AND MENU ?>
+      <?cs call:header_search_widget() ?>
 
-
-        </div><!-- end header-wrap -->
-    </div>
-    <!-- /Header -->
+    </div><!-- end header-wrap -->
+  </div><!-- /Header -->
 
 
   <div id="searchResults" class="wrap" style="display:none;">
           <h2 id="searchTitle">Results</h2>
           <div id="leftSearchControl" class="search-control">Loading...</div>
   </div>
+</div> <!--end header-wrapper -->
 
-  <?cs 
+<div id="sticky-header">
+  <div>
+    <a class="logo" href="#top"></a>
+    <a class="top" href="#top"></a>
+    <ul class="breadcrumb">
+      <?cs # More <li> elements added here with javascript ?>
+      <?cs if:!section.landing ?><li class="current"><?cs var:page.title ?></li><?cs
+      /if ?>
+    </ul>
+  </div>
+</div>
+
+  <?cs
 /def ?>
diff --git a/tools/droiddoc/templates-sdk/customizations.cs b/tools/droiddoc/templates-sdk/customizations.cs
index 69a0d0f..e0e3ca1 100644
--- a/tools/droiddoc/templates-sdk/customizations.cs
+++ b/tools/droiddoc/templates-sdk/customizations.cs
@@ -7,7 +7,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 <?cs 
         include:"../../../../frameworks/base/docs/html/sdk/sdk_toc.cs" ?>
@@ -15,33 +14,16 @@
 
       </div>
     </div> <!-- end side-nav -->
-<?cs /def ?>
-<?cs 
-def:resources_tab_nav() ?>
+<?cs /def ?><?cs
+
+def:no_nav() ?>
   <div class="wrap clearfix" id="body-content">
-    <a
-    <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
-      <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
+<?cs /def ?><?cs
 
-<?cs 
-        include:"../../../../frameworks/base/docs/html/resources/resources_toc.cs" ?>
-
-
-      </div>
-    </div> <!-- end side-nav -->
-    <script>
-      $(document).ready(function() {
-        scrollIntoView("devdoc-nav");
-        });
-    </script>
-<?cs /def ?>
-<?cs
 def:tools_nav() ?>
   <div class="wrap clearfix" id="body-content">
     <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 <?cs 
         include:"../../../../frameworks/base/docs/html/tools/tools_toc.cs" ?>
         
@@ -59,7 +41,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 
 <?cs 
@@ -73,14 +54,110 @@
         scrollIntoView("devdoc-nav");
         });
     </script>
-<?cs /def ?>
-<?cs 
+<?cs /def ?><?cs
+
+def:googleplay_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<?cs include:"../../../../frameworks/base/docs/html/distribute/googleplay/googleplay_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?><?cs
+
+def:essentials_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<?cs include:"../../../../frameworks/base/docs/html/distribute/essentials/essentials_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?><?cs
+
+def:users_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<?cs include:"../../../../frameworks/base/docs/html/distribute/users/users_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?><?cs
+
+def:engage_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<?cs include:"../../../../frameworks/base/docs/html/distribute/engage/engage_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?><?cs
+
+def:monetize_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<?cs include:"../../../../frameworks/base/docs/html/distribute/monetize/monetize_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?><?cs
+
+def:disttools_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<?cs include:"../../../../frameworks/base/docs/html/distribute/tools/disttools_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?><?cs
+
+def:stories_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<?cs include:"../../../../frameworks/base/docs/html/distribute/stories/stories_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?><?cs
+
 def:guide_nav() ?>
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
-
 
 <?cs 
         include:"../../../../frameworks/base/docs/html/guide/guide_toc.cs" ?>
@@ -99,7 +176,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 
 <?cs
@@ -119,7 +195,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 <?cs
         include:"../../../../frameworks/base/docs/html/distribute/distribute_toc.cs" ?>
@@ -139,7 +214,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 <?cs
         include:"../../../../frameworks/base/docs/html/samples/samples_toc.cs" ?>
@@ -159,7 +233,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 <?cs
         include:"../../../../frameworks/base/docs/html/google/google_toc.cs" ?>
@@ -183,7 +256,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 <?cs
         include:"../../../../frameworks/base/docs/html/about/about_toc.cs" ?>
@@ -204,7 +276,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
 <?cs
         include:"../../../../frameworks/base/docs/html/wear/wear_toc.cs" ?>
@@ -219,6 +290,22 @@
     </script>
 <?cs /def ?>
 
+<?cs
+def:preview_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+        <?cs
+          include:"../../../../frameworks/base/docs/html/preview/preview_toc.cs" ?>
+      </div>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?>
+
 <?cs # The default side navigation for the reference docs ?><?cs 
 def:default_left_nav() ?>
 <?cs if:reference.gcm || reference.gms ?>
@@ -227,8 +314,6 @@
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
       <div id="devdoc-nav">
-
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
       <div id="api-nav-header">
         <div id="api-level-toggle">
           <label for="apiLevelCheckbox" class="disabled"
@@ -331,10 +416,111 @@
     <?cs 
 /def ?>
 
+
+<?cs
+def:header_search_widget() ?>
+<div class="menu-container">
+  <div class="moremenu">
+    <div id="more-btn"></div>
+  </div>
+  <div class="morehover" id="moremenu">
+    <div class="top"></div>
+    <div class="mid">
+      <div class="header">Links</div>
+      <ul>
+        <li><a href="https://play.google.com/apps/publish/" target="_googleplay">Google Play Developer Console</a></li>
+        <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
+        <li><a href="<?cs var:toroot ?>about/index.html">About Android</a></li>
+      </ul>
+      <div class="header">Android Sites</div>
+      <ul>
+        <li><a href="http://www.android.com">Android.com</a></li>
+        <li class="active"><a>Android Developers</a></li>
+        <li><a href="http://source.android.com">Android Open Source Project</a></li>
+      </ul>
+
+      <?cs # Include language switcher only in online docs ?>
+      <?cs if:android.whichdoc == "online" ?>
+        <div class="header">Language</div>
+          <div id="language" class="locales">
+            <select name="language" onChange="changeLangPref(this.value, true)">
+                <option value="en">English</option>
+                <option value="es">Español</option>
+                <option value="ja">日本語</option>
+                <option value="ko">한국어</option>
+                <option value="ru">Русский</option>
+                <option value="zh-cn">中文 (中国)</option>
+                <option value="zh-tw">中文 (台灣)</option>
+            </select>
+          </div>
+        <script type="text/javascript">
+          <!--
+          loadLangPref();
+            //-->
+        </script>
+      <?cs /if ?>
+      <?cs # End of lang switcher ?>
+      <br class="clearfix" />
+    </div><!-- end 'mid' -->
+    <div class="bottom"></div>
+  </div><!-- end 'moremenu' -->
+
+  <div class="search" id="search-container">
+    <div class="search-inner">
+      <div id="search-btn"></div>
+      <div class="left"></div>
+      <form onsubmit="return submit_search()">
+        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
+          onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
+          onkeydown="return search_changed(event, true, '<?cs var:toroot ?>')"
+          onkeyup="return search_changed(event, false, '<?cs var:toroot ?>')" />
+      </form>
+      <div class="right"></div>
+      <a class="close hide">close</a>
+      <div class="left"></div>
+      <div class="right"></div>
+    </div><!-- end search-inner -->
+  </div><!-- end search-container -->
+
+  <div class="search_filtered_wrapper reference">
+    <div class="suggest-card reference no-display">
+      <ul class="search_filtered">
+      </ul>
+    </div>
+  </div>
+
+  <div class="search_filtered_wrapper docs">
+    <div class="suggest-card dummy no-display">&nbsp;</div>
+    <div class="suggest-card develop no-display">
+      <ul class="search_filtered">
+      </ul>
+      <div class="child-card guides no-display">
+      </div>
+      <div class="child-card training no-display">
+      </div>
+      <div class="child-card samples no-display">
+      </div>
+    </div>
+    <div class="suggest-card design no-display">
+      <ul class="search_filtered">
+      </ul>
+    </div>
+    <div class="suggest-card distribute no-display">
+      <ul class="search_filtered">
+      </ul>
+    </div>
+  </div>
+</div><!-- end menu-container (search and menu widget) -->
+<?cs /def ?>
+
+
+
 <?cs 
 def:custom_left_nav() ?><?cs
-  if:fullpage ?><?cs 
-    call:fullpage() ?><?cs 
+  if:fullpage ?><?cs
+    call:fullpage() ?><?cs
+  elif:nonavpage ?><?cs
+    call:no_nav() ?><?cs
   elif:guide ?><?cs 
     call:guide_nav() ?><?cs 
   elif:design ?><?cs
@@ -347,17 +533,33 @@
     call:google_nav() ?><?cs 
   elif:samples ?><?cs
     call:samples_nav() ?><?cs
-  elif:more ?><?cs 
-    call:dist_more_nav() ?><?cs
   elif:distribute ?><?cs 
-    call:distribute_nav() ?><?cs 
-  elif:about ?><?cs 
+    if:googleplay ?><?cs
+      call:googleplay_nav() ?><?cs
+    elif:essentials ?><?cs
+      call:essentials_nav() ?><?cs
+    elif:users ?><?cs
+      call:users_nav() ?><?cs
+    elif:engage ?><?cs
+      call:engage_nav() ?><?cs
+    elif:monetize ?><?cs
+      call:monetize_nav() ?><?cs
+    elif:disttools ?><?cs
+      call:disttools_nav() ?><?cs
+    elif:stories ?><?cs
+      call:stories_nav() ?><?cs
+    /if ?><?cs
+  elif:about ?><?cs
     call:about_nav() ?><?cs
+  elif:distribute ?><?cs
+    call:distribute_nav() ?><?cs
   elif:wear ?><?cs
     call:wear_nav() ?><?cs
-  else ?><?cs 
-    call:default_left_nav() ?> <?cs 
-  /if ?><?cs 
+  elif:preview ?><?cs
+    call:preview_nav() ?><?cs
+  else ?><?cs
+    call:default_left_nav() ?> <?cs
+  /if ?><?cs
 /def ?>
 
 <?cs # appears at the bottom of every page ?><?cs 
diff --git a/tools/droiddoc/templates-sdk/docpage.cs b/tools/droiddoc/templates-sdk/docpage.cs
index ea462c9..4d1404b 100644
--- a/tools/droiddoc/templates-sdk/docpage.cs
+++ b/tools/droiddoc/templates-sdk/docpage.cs
@@ -2,19 +2,36 @@
 <?cs include:"macros.cs" ?>
 <html<?cs if:devsite ?> devsite<?cs /if ?>>
 <?cs include:"head_tag.cs" ?>
-<body class="gc-documentation <?cs if:(google || reference.gms || reference.gcm) ?>google<?cs /if ?>
-  <?cs if:(guide||develop||training||reference||tools||sdk||samples) ?>develop<?cs if:guide ?> guide<?cs /if ?><?cs if:samples ?> samples<?cs /if ?><?cs
-  elif:about ?>about<?cs
-  elif:design ?>design<?cs
-  elif:distribute ?>distribute<?cs
-  /if ?><?cs
-  if:page.trainingcourse ?> trainingcourse<?cs /if ?>" itemscope itemtype="http://schema.org/Article">
-<?cs include:"header.cs" ?>
+<body class="gc-documentation
 
-<div <?cs if:fullpage
-?>class="fullpage"<?cs elif:design||tools||about||sdk||distribute
-?>class="col-13" id="doc-col"<?cs else
-?>class="col-12" id="doc-col"<?cs /if ?> >
+<?cs
+if:(google || reference.gms || reference.gcm) ?>google<?cs /if ?><?cs
+  if:(guide||develop||training||reference||tools||sdk||samples) ?>develop<?cs
+    if:guide ?> guide<?cs /if ?><?cs
+    if:samples ?> samples<?cs /if ?><?cs
+  elif:(distribute||googleplay||essentials||users||engage||monetize||disttools||stories)
+    ?>distribute<?cs
+    if:googleplay ?> googleplay<?cs /if ?><?cs
+    if:essentials ?> essentials<?cs /if ?><?cs
+    if:users ?> users<?cs /if ?><?cs
+    if:engage ?> engage<?cs /if ?><?cs
+    if:monetize ?> monetize<?cs /if ?><?cs
+    if:disttools ?> disttools<?cs /if ?><?cs
+    if:stories ?> stories<?cs /if ?><?cs
+  elif:(about||wear||tv||auto) ?>about<?cs
+  elif:design ?>design<?cs
+/if ?><?cs
+if:page.trainingcourse ?> trainingcourse<?cs
+/if ?>" itemscope itemtype="http://schema.org/Article"><?cs
+include:"header.cs" ?>
+
+<div <?cs
+  if:fullpage
+    ?>class="fullpage"<?cs
+  elif:(design||tools||about||sdk||googleplay||essentials||users||monetize||disttools) && !nonavpage
+    ?>class="col-13" id="doc-col"<?cs
+  elif:!nonavpage
+    ?>class="col-12" id="doc-col"<?cs /if ?> >
 
 <?cs if:(design||training||walkthru) && !page.trainingcourse && !page.article ?><?cs # header logic for docs that provide previous/next buttons ?>
   <?cs if:header.hide ?>
@@ -73,7 +90,8 @@
       </div>
     <?cs /if ?><?cs # end if training ?>
   </div>
-  <?cs /if ?>
+  <?cs /if ?><?cs # end if header.hide ?>
+
 <?cs elif:samplesProjectIndex ?>
   <div id="api-info-block">
   <div class="sum-details-links">
@@ -83,7 +101,17 @@
   </div><!-- end sum-details-links -->
   </div><!-- end breadcurmb block -->
   <h1 itemprop="name"><?cs var:projectDir ?></h1>
+
 <?cs else ?>
+  <?cs if:training ?>
+<?cs # horrible horrible hack to move TOC up when the next/prev links are not there ?>
+<style>
+  #tb-wrapper {
+    margin-top:6px;
+  }
+</style>
+  <?cs /if ?>
+
   <?cs if:(!fullpage && !header.hide) ?>
     <?cs if:page.landing ?><?cs # header logic for docs that are landing pages ?>
       <div class="landing-banner">
@@ -129,25 +157,9 @@
                     if:fullpage ?>wrap<?cs
                     else ?>layout-content-row<?cs /if ?>"
                     itemscope itemtype="http://schema.org/SiteNavigationElement">
-        <div class="layout-content-col <?cs
-                    if:fullpage ?>col-16<?cs
-                    elif:training||guide ?>col-8<?cs
-                    else ?>col-9<?cs /if ?>" style="padding-top:4px">
-          <?cs if:!page.noplus ?><?cs if:fullpage ?><style>#___plusone_0 {float:right !important;}</style><?cs /if ?>
-            <div class="g-plusone" data-size="medium"></div>
-          <?cs /if ?>
-        </div>
         <?cs if:!fullscreen ?>
-        <div class="paging-links layout-content-col col-4">
+        <div class="paging-links layout-content-col col-10">
           <?cs if:(design||training||walkthru) && !page.landing && !page.trainingcourse && !footer.hide ?>
-            <a href="#" class="prev-page-link hide"
-                zh-tw-lang="上一堂課"
-                zh-cn-lang="上一课"
-                ru-lang="Предыдущий"
-                ko-lang="이전"
-                ja-lang="前へ"
-                es-lang="Anterior"
-                >Previous</a>
             <a href="#" class="next-page-link hide"
                 zh-tw-lang="下一堂課"
                 zh-cn-lang="下一课"
@@ -164,35 +176,29 @@
                 ja-lang="開始する"
                 es-lang="Empezar"
                 >Get started</a>
+            <a href="#" class="next-class-link hide">Next class</a>
+          <?cs /if ?>
+        </div>
+        <div class="layout-content-col plus-container col-2" >
+          <?cs if:!page.noplus ?><?cs if:fullpage ?><style>#___plusone_0 {float:right !important;}</style><?cs /if ?>
+            <div class="g-plusone" data-size="medium"></div>
           <?cs /if ?>
         </div>
         <?cs /if ?>
       </div>
 
-      <?cs # for training classes, provide a different kind of link when the next page is a different class ?>
-      <?cs if:training && !page.article ?>
-      <div class="layout-content-row content-footer next-class" style="display:none" itemscope itemtype="http://schema.org/SiteNavigationElement">
-          <a href="#" class="next-class-link hide">Next class: </a>
-      </div>
-      <?cs /if ?>
-
   </div> <!-- end jd-content -->
 
 <?cs include:"footer.cs" ?>
 </div><!-- end doc-content -->
 
 <?cs include:"trailer.cs" ?>
+  <script src="https://developer.android.com/ytblogger_lists_unified.js" type="text/javascript"></script>
+  <script src="<?cs var:toroot ?>jd_lists_unified.js?v=2" type="text/javascript"></script>
+  <script src="<?cs var:toroot ?>jd_extras.js?v=2" type="text/javascript"></script>
+  <script src="<?cs var:toroot ?>jd_collections.js?v=2" type="text/javascript"></script>
+  <script src="<?cs var:toroot ?>jd_tag_helpers.js?v=2" type="text/javascript"></script>
 
-<!-- Start of Tag -->
-<script type="text/javascript">
-var axel = Math.random() + "";
-var a = axel * 10000000000000;
-document.write('<iframe src="https://2507573.fls.doubleclick.net/activityi;src=2507573;type=other026;cat=googl348;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
-</script>
-<noscript>
-<iframe src="https://2507573.fls.doubleclick.net/activityi;src=2507573;type=other026;cat=googl348;ord=1?" width="1" height="1" frameborder="0" style="display:none"></iframe>
-</noscript>
-<!-- End of Tag -->
 </body>
 </html>
 
diff --git a/tools/droiddoc/templates-sdk/head_tag.cs b/tools/droiddoc/templates-sdk/head_tag.cs
index ff07a19..7ecb7f9 100644
--- a/tools/droiddoc/templates-sdk/head_tag.cs
+++ b/tools/droiddoc/templates-sdk/head_tag.cs
@@ -31,10 +31,16 @@
 
 <!-- STYLESHEETS -->
 <link rel="stylesheet"
-href="<?cs if:android.whichdoc != 'online' ?>http:<?cs /if ?>//fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold" title="roboto">
-<link href="<?cs var:toroot ?>assets/css/default.css" rel="stylesheet" type="text/css">
+href="<?cs
+if:android.whichdoc != 'online' ?>http:<?cs
+/if ?>//fonts.googleapis.com/css?family=Roboto+Condensed">
+<link rel="stylesheet" href="<?cs
+if:android.whichdoc != 'online' ?>http:<?cs
+/if ?>//fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold"
+  title="roboto">
+<link href="<?cs var:toroot ?>assets/css/default.css?v=2" rel="stylesheet" type="text/css">
 
-<?cs if:reference && !(reference.gms || reference.gcm || wear) ?>
+<?cs if:reference && !(reference.gms || reference.gcm || preview) ?>
 <!-- FULLSCREEN STYLESHEET -->
 <link href="<?cs var:toroot ?>assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
 type="text/css">
@@ -56,24 +62,18 @@
   var metaTags = [<?cs var:meta.tags ?>];
   var devsite = <?cs if:devsite ?>true<?cs else ?>false<?cs /if ?>;
 </script>
-<script src="<?cs var:toroot ?>assets/js/docs.js" type="text/javascript"></script>
+<script src="<?cs var:toroot ?>assets/js/docs.js?v=2" type="text/javascript"></script>
 
-<!-- RESOURCES LIBRARY -->
-<script src="<?cs if:android.whichdoc != 'online' ?>http:<?cs /if ?>//androiddevdocs-staging.appspot.com/ytblogger_lists_unified.js" type="text/javascript"></script>
-<script src="<?cs var:toroot ?>jd_lists_unified.js" type="text/javascript"></script>
-<script src="<?cs var:toroot ?>assets/js/jd_tag_helpers.js" type="text/javascript"></script>
-<link href="<?cs var:toroot ?>assets/css/resourcecards.css"  rel="stylesheet" type="text/css" />
-<script src="<?cs var:toroot ?>assets/js/resourcecards.js" type="text/javascript"></script>
+<script>
+  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
+  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
+  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
+  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
 
-<script type="text/javascript">
-  var _gaq = _gaq || [];
-  _gaq.push(['_setAccount', 'UA-5831155-1']);
-  _gaq.push(['_trackPageview']);
-
-  (function() {
-    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
-    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
-    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
-  })();
+  ga('create', 'UA-5831155-1', 'android.com');
+  ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'});  // New tracker);
+  ga('send', 'pageview');
+  ga('universal.send', 'pageview'); // Send page view for new tracker.
 </script>
+
 </head>
diff --git a/tools/droiddoc/templates-sdk/sdkpage.cs b/tools/droiddoc/templates-sdk/sdkpage.cs
index 95f6596..027f32b 100644
--- a/tools/droiddoc/templates-sdk/sdkpage.cs
+++ b/tools/droiddoc/templates-sdk/sdkpage.cs
@@ -280,7 +280,7 @@
 
 <h4><a href='' class="expandable"
   onclick="toggleExpandable(this,'.pax');hideExpandable('.myide,.reqs');return false;"
-  >DOWNLOAD FOR OTHER PLATFORMS</a></h4>
+  >VIEW ALL DOWNLOADS AND SIZES</a></h4>
 
 
 <div class="pax col-13 online" style="display:none;margin:0;">
@@ -298,7 +298,7 @@
     <td>Windows 32-bit</td>
     <td>
   <a onClick="return onDownload(this)" id="win-bundle32"
-     href="http://dl.google.com/android/adt/<?cs var:sdk.version ?>/<?cs var:sdk.win32_bundle_download ?>"><?cs var:sdk.win32_bundle_download ?></a>
+     href="http://dl.google.com/android/adt/<?cs var:sdk.win32_bundle_download ?>"><?cs var:sdk.win32_bundle_download ?></a>
     </td>
     <td><?cs var:sdk.win32_bundle_bytes ?> bytes</td>
     <td><?cs var:sdk.win32_bundle_checksum ?></td>
@@ -307,7 +307,7 @@
     <td>Windows 64-bit</td>
     <td>
   <a onClick="return onDownload(this)" id="win-bundle64"
-     href="http://dl.google.com/android/adt/<?cs var:sdk.version ?>/<?cs var:sdk.win64_bundle_download ?>"><?cs var:sdk.win64_bundle_download ?></a>
+     href="http://dl.google.com/android/adt/<?cs var:sdk.win64_bundle_download ?>"><?cs var:sdk.win64_bundle_download ?></a>
     </td>
     <td><?cs var:sdk.win64_bundle_bytes ?> bytes</td>
     <td><?cs var:sdk.win64_bundle_checksum ?></td>
@@ -316,7 +316,7 @@
     <td><nobr>Mac OS X 64-bit</nobr></td>
     <td>
   <a onClick="return onDownload(this)" id="mac-bundle64"
-     href="http://dl.google.com/android/adt/<?cs var:sdk.version ?>/<?cs var:sdk.mac64_bundle_download ?>"><?cs var:sdk.mac64_bundle_download ?></a>
+     href="http://dl.google.com/android/adt/<?cs var:sdk.mac64_bundle_download ?>"><?cs var:sdk.mac64_bundle_download ?></a>
     </td>
     <td><?cs var:sdk.mac64_bundle_bytes ?> bytes</td>
     <td><?cs var:sdk.mac64_bundle_checksum ?></td>
@@ -325,7 +325,7 @@
     <td>Linux 32-bit</td>
     <td>
   <a onClick="return onDownload(this)" id="linux-bundle32"
-     href="http://dl.google.com/android/adt/<?cs var:sdk.version ?>/<?cs var:sdk.linux32_bundle_download ?>"><?cs var:sdk.linux32_bundle_download ?></a>
+     href="http://dl.google.com/android/adt/<?cs var:sdk.linux32_bundle_download ?>"><?cs var:sdk.linux32_bundle_download ?></a>
     </td>
     <td><?cs var:sdk.linux32_bundle_bytes ?> bytes</td>
     <td><?cs var:sdk.linux32_bundle_checksum ?></td>
@@ -334,7 +334,7 @@
     <td>Linux 64-bit</td>
     <td>
   <a onClick="return onDownload(this)" id="linux-bundle64"
-     href="http://dl.google.com/android/adt/<?cs var:sdk.version ?>/<?cs var:sdk.linux64_bundle_download ?>"><?cs var:sdk.linux64_bundle_download ?></a>
+     href="http://dl.google.com/android/adt/<?cs var:sdk.linux64_bundle_download ?>"><?cs var:sdk.linux64_bundle_download ?></a>
     </td>
     <td><?cs var:sdk.linux64_bundle_bytes ?> bytes</td>
     <td><?cs var:sdk.linux64_bundle_checksum ?></td>
@@ -430,12 +430,12 @@
 
     /* set up primary adt download button */
     $('#download-bundle-button').show();
-    $('#download-bundle-button').append("Download the SDK <br/><span class='small'>ADT Bundle for " + os + "</span>");
+    $('#download-bundle-button').append("Download Eclipse ADT <br/><span class='small'>with the Android SDK for " + os + "</span>");
     $('#download-bundle-button').click(function() {return onDownload(this,true,true);}).attr('href', bundlename);
 
     /* set up sdk tools only button */
     $('#download-tools-button').show();
-    $('#download-tools-button').append("Download the SDK Tools for " + os);
+    $('#download-tools-button').append("Download the stand-alone Android SDK Tools for " + os);
     $('#download-tools-button').click(function() {return onDownload(this,true);}).attr('href', $toolslink.attr('href'));
   } else {
     $('.pax').show();
@@ -501,9 +501,18 @@
   function onDownloadForRealz(link) {
     if ($("input#agree").is(':checked') && $("#bitpicker input:checked").length) {
       $("div.sdk-terms").slideUp();
-      $("#sdk-terms-form,.sdk-terms-intro").fadeOut('slow');
-      $("#next-steps").fadeIn('slow');
-      $("h1#tos-header").text('Get Ready to Code!');
+      $("h1#tos-header").text('Now redirecting to the install instructions...');
+      $("#sdk-terms-form,.sdk-terms-intro").fadeOut('slow', function() {
+        setTimeout(function() {
+          if ($("#downloadForRealz").attr('bundle') == 'true') {
+            // User downloaded the ADT Bundle
+            window.location = "/sdk/installing/index.html?pkg=adt";
+          } else {
+            // User downloaded the SDK Tools
+            window.location = "/sdk/installing/index.html?pkg=tools";
+          }
+        }, 500);
+      });
       _gaq.push(['_trackEvent', 'SDK', 'ADT and Tools', $("#downloadForRealz").html()]);
       return true;
     } else {
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
index d3f7144..f8cba44 100755
--- a/tools/releasetools/build_image.py
+++ b/tools/releasetools/build_image.py
@@ -26,9 +26,12 @@
 import sys
 import commands
 import shutil
+import tempfile
 
 import simg_map
 
+FIXED_SALT = "aee087a5be3b982978c923f566a94613496b417f2af592639bc80d141e34dfe7"
+
 def RunCommand(cmd):
   """ Echo and run the given command
 
@@ -78,7 +81,7 @@
   return partition_size - verity_tree_size - verity_metadata_size
 
 def BuildVerityTree(sparse_image_path, verity_image_path, prop_dict):
-  cmd = ("build_verity_tree %s %s" % (sparse_image_path, verity_image_path))
+  cmd = ("build_verity_tree -A %s %s %s" % (FIXED_SALT, sparse_image_path, verity_image_path))
   print cmd
   status, output = commands.getstatusoutput(cmd)
   if status:
@@ -170,10 +173,7 @@
   signer_path = prop_dict["verity_signer_cmd"]
 
   # make a tempdir
-  tempdir_name = os.path.join(os.path.dirname(out_file), "verity_images")
-  if os.path.exists(tempdir_name):
-    shutil.rmtree(tempdir_name)
-  os.mkdir(tempdir_name)
+  tempdir_name = tempfile.mkdtemp(suffix="_verity_images")
 
   # get partial image paths
   verity_image_path = os.path.join(tempdir_name, "verity.img")
@@ -181,7 +181,7 @@
 
   # build the verity tree and get the root hash and salt
   if not BuildVerityTree(out_file, verity_image_path, prop_dict):
-    shutil.rmtree(tempdir_name)
+    shutil.rmtree(tempdir_name, ignore_errors=True)
     return False
 
   # build the metadata blocks
@@ -194,26 +194,33 @@
                               block_dev,
                               signer_path,
                               signer_key):
-    shutil.rmtree(tempdir_name)
+    shutil.rmtree(tempdir_name, ignore_errors=True)
     return False
 
   # build the full verified image
   if not BuildVerifiedImage(out_file,
                             verity_image_path,
                             verity_metadata_path):
-    shutil.rmtree(tempdir_name)
+    shutil.rmtree(tempdir_name, ignore_errors=True)
     return False
 
-  shutil.rmtree(tempdir_name)
+  shutil.rmtree(tempdir_name, ignore_errors=True)
   return True
 
-def BuildImage(in_dir, prop_dict, out_file):
+def BuildImage(in_dir, prop_dict, out_file,
+               fs_config=None,
+               fc_config=None):
   """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.
@@ -222,8 +229,10 @@
   fs_type = prop_dict.get("fs_type", "")
   run_fsck = False
 
+  is_verity_partition = prop_dict.get("mount_point") == prop_dict.get("verity_mountpoint")
+  verity_supported = prop_dict.get("verity") == "true"
   # adjust the partition size to make room for the hashes if this is to be verified
-  if prop_dict.get("verity") == "true":
+  if verity_supported and is_verity_partition:
     partition_size = int(prop_dict.get("partition_size"))
     adjusted_size = AdjustPartitionSizeForVerity(partition_size)
     if not adjusted_size:
@@ -241,8 +250,15 @@
     build_command.append(prop_dict["partition_size"])
     if "timestamp" in prop_dict:
       build_command.extend(["-T", str(prop_dict["timestamp"])])
-    if "selinux_fc" in prop_dict:
+    if fs_config is not None:
+      build_command.extend(["-C", fs_config])
+    if fc_config is not None:
+      build_command.append(fc_config)
+    elif "selinux_fc" in prop_dict:
       build_command.append(prop_dict["selinux_fc"])
+  elif fs_type.startswith("f2fs"):
+    build_command = ["mkf2fsuserimg.sh"]
+    build_command.extend([out_file, prop_dict["partition_size"]])
   else:
     build_command = ["mkyaffs2image", "-f"]
     if prop_dict.get("mkyaffs2_extra_flags", None):
@@ -258,7 +274,7 @@
     return False
 
   # create the verified image if this is to be verified
-  if prop_dict.get("verity") == "true":
+  if verity_supported and is_verity_partition:
     if not MakeVerityEnabledImage(out_file, prop_dict):
       return False
 
@@ -301,7 +317,8 @@
       "verity",
       "verity_block_device",
       "verity_key",
-      "verity_signer_cmd"
+      "verity_signer_cmd",
+      "verity_mountpoint"
       )
   for p in common_props:
     copy_prop(p, p)
@@ -311,7 +328,9 @@
     copy_prop("fs_type", "fs_type")
     copy_prop("system_size", "partition_size")
   elif mount_point == "data":
+    # Copy the generic fs type first, override with specific one if available.
     copy_prop("fs_type", "fs_type")
+    copy_prop("userdata_fs_type", "fs_type")
     copy_prop("userdata_size", "partition_size")
   elif mount_point == "cache":
     copy_prop("cache_fs_type", "fs_type")
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index fea335e..701a9cb 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -498,6 +498,8 @@
   if target.endswith(".img"): target = target[:-4]
   mount_point = "/" + target
 
+  fs_type = None
+  limit = None
   if info_dict["fstab"]:
     if mount_point == "/userdata": mount_point = "/data"
     p = info_dict["fstab"][mount_point]
@@ -966,7 +968,8 @@
 
 # map recovery.fstab's fs_types to mount/format "partition types"
 PARTITION_TYPES = { "yaffs2": "MTD", "mtd": "MTD",
-                    "ext4": "EMMC", "emmc": "EMMC" }
+                    "ext4": "EMMC", "emmc": "EMMC",
+                    "f2fs": "EMMC" }
 
 def GetTypeAndDevice(mount_point, info):
   fstab = info["fstab"]
@@ -1006,14 +1009,14 @@
   p.communicate()
   assert p.returncode == 0, "Couldn't compress patch"
 
-def MakeSystemPatch(source_file, target_file):
+def MakePartitionPatch(source_file, target_file, partition):
   with tempfile.NamedTemporaryFile() as output_file:
     XDelta3(source_file.name, target_file.name, output_file.name)
     XZ(output_file.name)
     with open(output_file.name + ".xz") as patch_file:
       patch_data = patch_file.read()
       os.unlink(patch_file.name)
-      return File("system.muimg.p", patch_data)
+      return File(partition + ".muimg.p", patch_data)
 
 def MakeRecoveryPatch(input_dir, output_sink, recovery_img, boot_img,
                       info_dict=None):
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index 43e8542..8620812 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -203,11 +203,10 @@
                           p.device, p.length, p.mount_point))
 
   def WipeBlockDevice(self, partition):
-    if partition != "/system":
-      raise ValueError(("WipeBlockDevice currently only works "
-                        "on /system, not %s\n") % (partition,))
+    if partition not in ("/system", "/vendor"):
+      raise ValueError(("WipeBlockDevice doesn't work on %s\n") % (partition,))
     fstab = self.info.get("fstab", None)
-    size = self.info.get("system_size", None)
+    size = self.info.get(partition.lstrip("/") + "_size", None)
     device = fstab[partition].device
 
     self.script.append('wipe_block_device("%s", %s);' % (device, size))
diff --git a/tools/releasetools/img_from_target_files.py b/tools/releasetools/img_from_target_files.py
index 596a47e..6043355 100755
--- a/tools/releasetools/img_from_target_files.py
+++ b/tools/releasetools/img_from_target_files.py
@@ -59,9 +59,21 @@
   data = BuildSystem(OPTIONS.input_tmp, OPTIONS.info_dict, sparse=sparse)
   common.ZipWriteStr(output_zip, "system.img", data)
 
-
 def BuildSystem(input_dir, info_dict, sparse=True, map_file=None):
-  print "creating system.img..."
+  return CreateImage(input_dir, info_dict, "system",
+                     sparse=sparse, map_file=map_file)
+
+def AddVendor(output_zip, sparse=True):
+  data = BuildVendor(OPTIONS.input_tmp, OPTIONS.info_dict, sparse=sparse)
+  common.ZipWriteStr(output_zip, "vendor.img", data)
+
+def BuildVendor(input_dir, info_dict, sparse=True, map_file=None):
+  return CreateImage(input_dir, info_dict, "vendor",
+                     sparse=sparse, map_file=map_file)
+
+
+def CreateImage(input_dir, info_dict, what, sparse=True, map_file=None):
+  print "creating " + what + ".img..."
 
   img = tempfile.NamedTemporaryFile()
 
@@ -69,8 +81,8 @@
   # mkyaffs2image.  It wants "system" but we have a directory named
   # "SYSTEM", so create a symlink.
   try:
-    os.symlink(os.path.join(input_dir, "SYSTEM"),
-               os.path.join(input_dir, "system"))
+    os.symlink(os.path.join(input_dir, what.upper()),
+               os.path.join(input_dir, what))
   except OSError, e:
       # bogus error on my mac version?
       #   File "./build/tools/releasetools/img_from_target_files", line 86, in AddSystem
@@ -79,24 +91,38 @@
     if (e.errno == errno.EEXIST):
       pass
 
-  image_props = build_image.ImagePropFromGlobalDict(info_dict, "system")
+  image_props = build_image.ImagePropFromGlobalDict(info_dict, what)
   fstab = info_dict["fstab"]
   if fstab:
-    image_props["fs_type" ] = fstab["/system"].fs_type
-  succ = build_image.BuildImage(os.path.join(input_dir, "system"),
-                                image_props, img.name)
-  assert succ, "build system.img image failed"
+    image_props["fs_type" ] = fstab["/" + what].fs_type
+
+  if what == "system":
+    fs_config_prefix = ""
+  else:
+    fs_config_prefix = what + "_"
+
+  fs_config = os.path.join(
+      input_dir, "META/" + fs_config_prefix + "filesystem_config.txt")
+  if not os.path.exists(fs_config): fs_config = None
+
+  fc_config = os.path.join(input_dir, "BOOT/RAMDISK/file_contexts")
+  if not os.path.exists(fc_config): fc_config = None
+
+  succ = build_image.BuildImage(os.path.join(input_dir, what),
+                                image_props, img.name,
+                                fs_config=fs_config,
+                                fc_config=fc_config)
+  assert succ, "build " + what + ".img image failed"
 
   mapdata = None
 
   if sparse:
-    img.seek(os.SEEK_SET, 0)
-    data = img.read()
+    data = open(img.name).read()
     img.close()
   else:
     success, name = build_image.UnsparseImage(img.name, replace=False)
     if not success:
-      assert False, "unsparsing system.img failed"
+      assert False, "unsparsing " + what + ".img failed"
 
     if map_file:
       mmap = tempfile.NamedTemporaryFile()
@@ -123,45 +149,6 @@
     return mapdata, data
 
 
-def AddVendor(output_zip):
-  """Turn the contents of VENDOR into vendor.img and store it in
-  output_zip."""
-
-  image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict,
-                                                    "vendor")
-  # The build system has to explicitly request for vendor.img.
-  if "fs_type" not in image_props:
-    return
-
-  print "creating vendor.img..."
-
-  img = tempfile.NamedTemporaryFile()
-
-  # The name of the directory it is making an image out of matters to
-  # mkyaffs2image.  It wants "vendor" but we have a directory named
-  # "VENDOR", so create a symlink or an empty directory if VENDOR does not
-  # exist.
-  if not os.path.exists(os.path.join(OPTIONS.input_tmp, "vendor")):
-    if os.path.exists(os.path.join(OPTIONS.input_tmp, "VENDOR")):
-      os.symlink(os.path.join(OPTIONS.input_tmp, "VENDOR"),
-                 os.path.join(OPTIONS.input_tmp, "vendor"))
-    else:
-      os.mkdir(os.path.join(OPTIONS.input_tmp, "vendor"))
-
-  img = tempfile.NamedTemporaryFile()
-
-  fstab = OPTIONS.info_dict["fstab"]
-  if fstab:
-    image_props["fs_type" ] = fstab["/vendor"].fs_type
-  succ = build_image.BuildImage(os.path.join(OPTIONS.input_tmp, "vendor"),
-                                image_props, img.name)
-  assert succ, "build vendor.img image failed"
-
-  common.CheckSize(img.name, "vendor.img", OPTIONS.info_dict)
-  output_zip.write(img.name, "vendor.img")
-  img.close()
-
-
 def AddUserdata(output_zip):
   """Create an empty userdata image and store it in output_zip."""
 
@@ -270,16 +257,30 @@
 
   output_zip = zipfile.ZipFile(args[1], "w", compression=zipfile.ZIP_DEFLATED)
 
-  common.GetBootableImage(
-      "boot.img", "boot.img", OPTIONS.input_tmp, "BOOT").AddToZip(output_zip)
-  common.GetBootableImage(
-      "recovery.img", "recovery.img", OPTIONS.input_tmp,
-      "RECOVERY").AddToZip(output_zip)
+  boot_image = common.GetBootableImage(
+      "boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
+  if boot_image:
+      boot_image.AddToZip(output_zip)
+  recovery_image = common.GetBootableImage(
+      "recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
+  if recovery_image:
+    recovery_image.AddToZip(output_zip)
+
+  def banner(s):
+    print "\n\n++++ " + s + " ++++\n\n"
 
   if not bootable_only:
+    banner("AddSystem")
     AddSystem(output_zip)
-    AddVendor(output_zip)
+    try:
+      input_zip.getinfo("VENDOR/")
+      banner("AddVendor")
+      AddVendor(output_zip)
+    except KeyError:
+      pass   # no vendor partition for this device
+    banner("AddUserdata")
     AddUserdata(output_zip)
+    banner("AddCache")
     AddCache(output_zip)
     CopyInfo(output_zip)
 
diff --git a/tools/releasetools/ota_from_target_files b/tools/releasetools/ota_from_target_files
index 7019c46..5f2354c 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -71,6 +71,10 @@
       instead of the binary in the build's target_files.  Use for
       development only.
 
+  -t  (--worker_threads) <int>
+      Specifies the number of worker-threads that will be used when
+      generating patches for incremental updates (defaults to 3).
+
 """
 
 import sys
@@ -159,50 +163,21 @@
     return result
   return None
 
-class Item:
-  """Items represent the metadata (user, group, mode) of files and
-  directories in the system image."""
-  ITEMS = {}
-  def __init__(self, name, dir=False):
-    self.name = name
-    self.uid = None
-    self.gid = None
-    self.mode = None
-    self.selabel = None
-    self.capabilities = None
-    self.dir = dir
+class ItemSet:
+  def __init__(self, partition, fs_config):
+    self.partition = partition
+    self.fs_config = fs_config
+    self.ITEMS = {}
 
-    if name:
-      self.parent = Item.Get(os.path.dirname(name), dir=True)
-      self.parent.children.append(self)
-    else:
-      self.parent = None
-    if dir:
-      self.children = []
+  def Get(self, name, dir=False):
+    if name not in self.ITEMS:
+      self.ITEMS[name] = Item(self, name, dir=dir)
+    return self.ITEMS[name]
 
-  def Dump(self, indent=0):
-    if self.uid is not None:
-      print "%s%s %d %d %o" % ("  "*indent, self.name, self.uid, self.gid, self.mode)
-    else:
-      print "%s%s %s %s %s" % ("  "*indent, self.name, self.uid, self.gid, self.mode)
-    if self.dir:
-      print "%s%s" % ("  "*indent, self.descendants)
-      print "%s%s" % ("  "*indent, self.best_subtree)
-      for i in self.children:
-        i.Dump(indent=indent+1)
-
-  @classmethod
-  def Get(cls, name, dir=False):
-    if name not in cls.ITEMS:
-      cls.ITEMS[name] = Item(name, dir=dir)
-    return cls.ITEMS[name]
-
-  @classmethod
-  def GetMetadata(cls, input_zip):
-
+  def GetMetadata(self, input_zip):
     # The target_files contains a record of what the uid,
     # gid, and mode are supposed to be.
-    output = input_zip.read("META/filesystem_config.txt")
+    output = input_zip.read(self.fs_config)
 
     for line in output.split("\n"):
       if not line: continue
@@ -220,7 +195,7 @@
         if key == "capabilities":
           capabilities = value
 
-      i = cls.ITEMS.get(name, None)
+      i = self.ITEMS.get(name, None)
       if i is not None:
         i.uid = int(uid)
         i.gid = int(gid)
@@ -231,11 +206,44 @@
           i.children.sort(key=lambda i: i.name)
 
     # set metadata for the files generated by this script.
-    i = cls.ITEMS.get("system/recovery-from-boot.p", None)
+    i = self.ITEMS.get("system/recovery-from-boot.p", None)
     if i: i.uid, i.gid, i.mode, i.selabel, i.capabilities = 0, 0, 0644, None, None
-    i = cls.ITEMS.get("system/etc/install-recovery.sh", None)
+    i = self.ITEMS.get("system/etc/install-recovery.sh", None)
     if i: i.uid, i.gid, i.mode, i.selabel, i.capabilities = 0, 0, 0544, None, None
 
+
+class Item:
+  """Items represent the metadata (user, group, mode) of files and
+  directories in the system image."""
+  def __init__(self, itemset, name, dir=False):
+    self.itemset = itemset
+    self.name = name
+    self.uid = None
+    self.gid = None
+    self.mode = None
+    self.selabel = None
+    self.capabilities = None
+    self.dir = dir
+
+    if name:
+      self.parent = itemset.Get(os.path.dirname(name), dir=True)
+      self.parent.children.append(self)
+    else:
+      self.parent = None
+    if dir:
+      self.children = []
+
+  def Dump(self, indent=0):
+    if self.uid is not None:
+      print "%s%s %d %d %o" % ("  "*indent, self.name, self.uid, self.gid, self.mode)
+    else:
+      print "%s%s %s %s %s" % ("  "*indent, self.name, self.uid, self.gid, self.mode)
+    if self.dir:
+      print "%s%s" % ("  "*indent, self.descendants)
+      print "%s%s" % ("  "*indent, self.best_subtree)
+      for i in self.children:
+        i.Dump(indent=indent+1)
+
   def CountChildMetadata(self):
     """Count up the (uid, gid, mode, selabel, capabilities) tuples for
     all children and determine the best strategy for using set_perm_recursive and
@@ -320,9 +328,8 @@
     recurse(self, (-1, -1, -1, -1, None, None))
 
 
-def CopySystemFiles(input_zip, output_zip=None,
-                    substitute=None):
-  """Copies files underneath system/ in the input zip to the output
+def CopyPartitionFiles(itemset, input_zip, output_zip=None, substitute=None):
+  """Copies files for the partition in the input zip to the output
   zip.  Populates the Item class with their metadata, and returns a
   list of symlinks.  output_zip may be None, in which case the copy is
   skipped (but the other side effects still happen).  substitute is an
@@ -332,15 +339,17 @@
 
   symlinks = []
 
+  partition = itemset.partition
+
   for info in input_zip.infolist():
-    if info.filename.startswith("SYSTEM/"):
+    if info.filename.startswith(partition.upper() + "/"):
       basefilename = info.filename[7:]
       if IsSymlink(info):
         symlinks.append((input_zip.read(info.filename),
-                         "/system/" + basefilename))
+                         "/" + partition + "/" + basefilename))
       else:
         info2 = copy.copy(info)
-        fn = info2.filename = "system/" + basefilename
+        fn = info2.filename = partition + "/" + basefilename
         if substitute and fn in substitute and substitute[fn] is None:
           continue
         if output_zip is not None:
@@ -350,9 +359,9 @@
             data = input_zip.read(info.filename)
           output_zip.writestr(info2, data)
         if fn.endswith("/"):
-          Item.Get(fn[:-1], dir=True)
+          itemset.Get(fn[:-1], dir=True)
         else:
-          Item.Get(fn, dir=False)
+          itemset.Get(fn, dir=False)
 
   symlinks.sort()
   return symlinks
@@ -387,6 +396,13 @@
   except KeyError:
     return False
 
+def HasVendorPartition(target_files_zip):
+  try:
+    target_files_zip.getinfo("VENDOR/")
+    return True
+  except KeyError:
+    return False
+
 def GetOemProperty(name, oem_props, oem_dict, info_dict):
   if oem_props is not None and name in oem_props:
     return oem_dict[name]
@@ -489,11 +505,14 @@
 
   if OPTIONS.wipe_user_data:
     system_progress -= 0.1
+  if HasVendorPartition(input_zip):
+    system_progress -= 0.1
 
   if "selinux_fc" in OPTIONS.info_dict:
     WritePolicyConfig(OPTIONS.info_dict["selinux_fc"], output_zip)
 
-  script.ShowProgress(system_progress, 30)
+  system_items = ItemSet("system", "META/filesystem_config.txt")
+  script.ShowProgress(system_progress, 0)
   if block_based:
     mapdata, data = img_from_target_files.BuildSystem(
         OPTIONS.input_tmp, OPTIONS.info_dict,
@@ -510,7 +529,7 @@
       script.UnpackPackageDir("recovery", "/system")
     script.UnpackPackageDir("system", "/system")
 
-    symlinks = CopySystemFiles(input_zip, output_zip)
+    symlinks = CopyPartitionFiles(system_items, input_zip, output_zip)
     script.MakeSymlinks(symlinks)
 
   boot_img = common.GetBootableImage("boot.img", "boot.img",
@@ -519,13 +538,37 @@
   if not block_based:
     def output_sink(fn, data):
       common.ZipWriteStr(output_zip, "recovery/" + fn, data)
-      Item.Get("system/" + fn, dir=False)
+      system_items.Get("system/" + fn, dir=False)
 
     common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink,
                              recovery_img, boot_img)
 
-    Item.GetMetadata(input_zip)
-    Item.Get("system").SetPermissions(script)
+    system_items.GetMetadata(input_zip)
+    system_items.Get("system").SetPermissions(script)
+
+  if HasVendorPartition(input_zip):
+    vendor_items = ItemSet("vendor", "META/vendor_filesystem_config.txt")
+    script.ShowProgress(0.1, 0)
+
+    if block_based:
+      mapdata, data = img_from_target_files.BuildVendor(
+          OPTIONS.input_tmp, OPTIONS.info_dict,
+          sparse=False, map_file=True)
+
+      common.ZipWriteStr(output_zip, "vendor.map", mapdata)
+      common.ZipWriteStr(output_zip, "vendor.muimg", data)
+      script.WipeBlockDevice("/vendor")
+      script.WriteRawImage("/vendor", "vendor.muimg", mapfn="vendor.map")
+    else:
+      script.FormatPartition("/vendor")
+      script.Mount("/vendor")
+      script.UnpackPackageDir("vendor", "/vendor")
+
+      symlinks = CopyPartitionFiles(vendor_items, input_zip, output_zip)
+      script.MakeSymlinks(symlinks)
+
+      vendor_items.GetMetadata(input_zip)
+      vendor_items.Get("vendor").SetPermissions(script)
 
   common.CheckSize(boot_img.data, "boot.img", OPTIONS.info_dict)
   common.ZipWriteStr(output_zip, "boot.img", boot_img.data)
@@ -544,7 +587,7 @@
   if OPTIONS.wipe_user_data:
     script.ShowProgress(0.1, 10)
     script.FormatPartition("/data")
-    
+
   if OPTIONS.two_step:
     script.AppendExtra("""
 set_stage("%(bcb_dev)s", "");
@@ -571,14 +614,15 @@
                      "".join(["%s=%s\n" % kv
                               for kv in sorted(metadata.iteritems())]))
 
-def LoadSystemFiles(z):
-  """Load all the files from SYSTEM/... in a given target-files
+def LoadPartitionFiles(z, partition):
+  """Load all the files from the given partition in a given target-files
   ZipFile, and return a dict of {filename: File object}."""
   out = {}
+  prefix = partition.upper() + "/"
   for info in z.infolist():
-    if info.filename.startswith("SYSTEM/") and not IsSymlink(info):
+    if info.filename.startswith(prefix) and not IsSymlink(info):
       basefilename = info.filename[7:]
-      fn = "system/" + basefilename
+      fn = partition + "/" + basefilename
       data = z.read(info.filename)
       out[fn] = common.File(fn, data)
   return out
@@ -602,6 +646,45 @@
     known_paths.add(path)
     dirs.pop()
 
+class BlockDifference:
+  def __init__(self, partition, builder, output_zip):
+    with tempfile.NamedTemporaryFile() as src_file:
+      with tempfile.NamedTemporaryFile() as tgt_file:
+        print "building source " + partition + " image..."
+        src_file = tempfile.NamedTemporaryFile()
+        src_mapdata, src_data = builder(OPTIONS.source_tmp,
+                                        OPTIONS.source_info_dict,
+                                        sparse=False, map_file=True)
+
+        self.src_sha1 = sha1(src_data).hexdigest()
+        print "source " + partition + " sha1:", self.src_sha1
+        src_file.write(src_data)
+
+        print "building target " + partition + " image..."
+        tgt_file = tempfile.NamedTemporaryFile()
+        tgt_mapdata, tgt_data = builder(OPTIONS.target_tmp,
+                                        OPTIONS.target_info_dict,
+                                        sparse=False, map_file=True)
+        self.tgt_sha1 = sha1(tgt_data).hexdigest()
+        print "target " + partition + " sha1:", self.tgt_sha1
+        tgt_len = len(tgt_data)
+        tgt_file.write(tgt_data)
+
+        system_type, self.device = common.GetTypeAndDevice("/" + partition,
+                                                           OPTIONS.info_dict)
+        self.patch = common.MakePartitionPatch(src_file, tgt_file, partition)
+
+        TestBlockPatch(src_data, src_mapdata, self.patch.data,
+                       tgt_mapdata, self.tgt_sha1)
+        src_data = None
+        tgt_data = None
+
+        self.patch.AddToZip(output_zip, compression=zipfile.ZIP_STORED)
+        self.src_mapfilename = self.patch.name + ".src.map"
+        common.ZipWriteStr(output_zip, self.src_mapfilename, src_mapdata)
+        self.tgt_mapfilename = self.patch.name + ".tgt.map"
+        common.ZipWriteStr(output_zip, self.tgt_mapfilename, tgt_mapdata)
+
 def WriteBlockIncrementalOTAPackage(target_zip, source_zip, output_zip):
   source_version = OPTIONS.source_info_dict["recovery_api_version"]
   target_version = OPTIONS.target_info_dict["recovery_api_version"]
@@ -648,40 +731,13 @@
       "/tmp/recovery.img", "recovery.img", OPTIONS.target_tmp, "RECOVERY")
   updating_recovery = (source_recovery.data != target_recovery.data)
 
-  with tempfile.NamedTemporaryFile() as src_file:
-    with tempfile.NamedTemporaryFile() as tgt_file:
-      print "building source system image..."
-      src_file = tempfile.NamedTemporaryFile()
-      src_mapdata, src_data = img_from_target_files.BuildSystem(
-          OPTIONS.source_tmp, OPTIONS.source_info_dict,
-          sparse=False, map_file=True)
-
-      src_sys_sha1 = sha1(src_data).hexdigest()
-      print "source system sha1:", src_sys_sha1
-      src_file.write(src_data)
-
-      print "building target system image..."
-      tgt_file = tempfile.NamedTemporaryFile()
-      tgt_mapdata, tgt_data = img_from_target_files.BuildSystem(
-          OPTIONS.target_tmp, OPTIONS.target_info_dict,
-          sparse=False, map_file=True)
-      tgt_sys_sha1 = sha1(tgt_data).hexdigest()
-      print "target system sha1:", tgt_sys_sha1
-      tgt_sys_len = len(tgt_data)
-      tgt_file.write(tgt_data)
-
-      system_type, system_device = common.GetTypeAndDevice("/system", OPTIONS.info_dict)
-      system_patch = common.MakeSystemPatch(src_file, tgt_file)
-
-      TestBlockPatch(src_data, src_mapdata, system_patch.data, tgt_mapdata, tgt_sys_sha1)
-      src_data = None
-      tgt_data = None
-
-      system_patch.AddToZip(output_zip, compression=zipfile.ZIP_STORED)
-      src_mapfilename = system_patch.name + ".src.map"
-      common.ZipWriteStr(output_zip, src_mapfilename, src_mapdata)
-      tgt_mapfilename = system_patch.name + ".tgt.map"
-      common.ZipWriteStr(output_zip, tgt_mapfilename, tgt_mapdata)
+  system_diff = BlockDifference("system", img_from_target_files.BuildSystem,
+                                output_zip)
+  if HasVendorPartition(target_zip):
+    if not HasVendorPartition(source_zip):
+      raise RuntimeError("can't generate incremental that adds /vendor")
+    vendor_diff = BlockDifference("vendor", img_from_target_files.BuildVendor,
+                                  output_zip)
 
   oem_props = OPTIONS.target_info_dict.get("oem_fingerprint_properties")
   oem_dict = None
@@ -774,11 +830,23 @@
 
   device_specific.IncrementalOTA_InstallBegin()
 
+  if HasVendorPartition(target_zip):
+    script.Print("Patching vendor image...")
+    script.ShowProgress(0.1, 0)
+    script.Syspatch(vendor_diff.device,
+                    vendor_diff.tgt_mapfilename, vendor_diff.tgt_sha1,
+                    vendor_diff.src_mapfilename, vendor_diff.src_sha1,
+                    vendor_diff.patch.name)
+    sys_progress = 0.8
+  else:
+    sys_progress = 0.9
+
   script.Print("Patching system image...")
-  script.Syspatch(system_device,
-                  tgt_mapfilename, tgt_sys_sha1,
-                  src_mapfilename, src_sys_sha1,
-                  system_patch.name)
+  script.ShowProgress(sys_progress, 0)
+  script.Syspatch(system_diff.device,
+                  system_diff.tgt_mapfilename, system_diff.tgt_sha1,
+                  system_diff.src_mapfilename, system_diff.src_sha1,
+                  system_diff.patch.name)
 
   if OPTIONS.two_step:
     common.ZipWriteStr(output_zip, "boot.img", target_boot.data)
@@ -791,6 +859,7 @@
       # contents of the boot partition, and write it back to the
       # partition.
       script.Print("Patching boot image...")
+      script.ShowProgress(0.1, 10)
       script.ApplyPatch("%s:%s:%d:%s:%d:%s"
                         % (boot_type, boot_device,
                            source_boot.size, source_boot.sha1,
@@ -835,7 +904,6 @@
 
   with tempfile.NamedTemporaryFile() as src_file,\
        tempfile.NamedTemporaryFile() as patch_file,\
-       tempfile.NamedTemporaryFile() as tgt_file,\
        tempfile.NamedTemporaryFile() as src_map_file,\
        tempfile.NamedTemporaryFile() as tgt_map_file:
 
@@ -851,20 +919,16 @@
 
     patch_file.write(patch_data)
 
-    tgt_total = sum(tgt_regions) * tgt_blksize
-    tgt_file.truncate(tgt_total)
-
     src_map_file.write(src_map)
     tgt_map_file.write(tgt_map)
 
     src_file.flush()
     src_map_file.flush()
     patch_file.flush()
-    tgt_file.flush()
     tgt_map_file.flush()
 
     p = common.Run(["syspatch_host", src_file.name, src_map_file.name,
-                    patch_file.name, tgt_file.name, tgt_map_file.name],
+                    patch_file.name, src_file.name, tgt_map_file.name],
                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
     stdoutdata, _ = p.communicate()
     if p.returncode != 0:
@@ -872,10 +936,11 @@
       raise ValueError("failed to reconstruct target system image from patch")
 
     h = sha1()
+    src_file.seek(0, 0)
     for i in range(0, len(tgt_regions), 2):
       c, dc = tgt_regions[i:i+2]
-      h.update(tgt_file.read(c*tgt_blksize))
-      tgt_file.seek(dc*tgt_blksize, 1)
+      h.update(src_file.read(c*tgt_blksize))
+      src_file.seek(dc*tgt_blksize, 1)
 
     if h.hexdigest() != tgt_sha1:
       raise ValueError("patch reconstructed incorrect target system image")
@@ -883,6 +948,127 @@
   print "test of system image patch succeeded"
 
 
+class FileDifference:
+  def __init__(self, partition, source_zip, target_zip, output_zip):
+    print "Loading target..."
+    self.target_data = target_data = LoadPartitionFiles(target_zip, partition)
+    print "Loading source..."
+    self.source_data = source_data = LoadPartitionFiles(source_zip, partition)
+
+    self.verbatim_targets = verbatim_targets = []
+    self.patch_list = patch_list = []
+    diffs = []
+    self.renames = renames = {}
+    known_paths = set()
+    largest_source_size = 0
+
+    matching_file_cache = {}
+    for fn, sf in source_data.items():
+      assert fn == sf.name
+      matching_file_cache["path:" + fn] = sf
+      if fn in target_data.keys():
+        AddToKnownPaths(fn, known_paths)
+      # Only allow eligibility for filename/sha matching
+      # if there isn't a perfect path match.
+      if target_data.get(sf.name) is None:
+        matching_file_cache["file:" + fn.split("/")[-1]] = sf
+        matching_file_cache["sha:" + sf.sha1] = sf
+
+    for fn in sorted(target_data.keys()):
+      tf = target_data[fn]
+      assert fn == tf.name
+      sf = ClosestFileMatch(tf, matching_file_cache, renames)
+      if sf is not None and sf.name != tf.name:
+        print "File has moved from " + sf.name + " to " + tf.name
+        renames[sf.name] = tf
+
+      if sf is None or fn in OPTIONS.require_verbatim:
+        # This file should be included verbatim
+        if fn in OPTIONS.prohibit_verbatim:
+          raise common.ExternalError("\"%s\" must be sent verbatim" % (fn,))
+        print "send", fn, "verbatim"
+        tf.AddToZip(output_zip)
+        verbatim_targets.append((fn, tf.size))
+        if fn in target_data.keys():
+          AddToKnownPaths(fn, known_paths)
+      elif tf.sha1 != sf.sha1:
+        # File is different; consider sending as a patch
+        diffs.append(common.Difference(tf, sf))
+      else:
+        # Target file data identical to source (may still be renamed)
+        pass
+
+    common.ComputeDifferences(diffs)
+
+    for diff in diffs:
+      tf, sf, d = diff.GetPatch()
+      path = "/".join(tf.name.split("/")[:-1])
+      if d is None or len(d) > tf.size * OPTIONS.patch_threshold or \
+          path not in known_paths:
+        # patch is almost as big as the file; don't bother patching
+        # or a patch + rename cannot take place due to the target
+        # directory not existing
+        tf.AddToZip(output_zip)
+        verbatim_targets.append((tf.name, tf.size))
+        if sf.name in renames:
+          del renames[sf.name]
+        AddToKnownPaths(tf.name, known_paths)
+      else:
+        common.ZipWriteStr(output_zip, "patch/" + sf.name + ".p", d)
+        patch_list.append((tf, sf, tf.size, common.sha1(d).hexdigest()))
+        largest_source_size = max(largest_source_size, sf.size)
+
+    self.largest_source_size = largest_source_size
+
+  def EmitVerification(self, script):
+    so_far = 0
+    for tf, sf, size, patch_sha in self.patch_list:
+      if tf.name != sf.name:
+        script.SkipNextActionIfTargetExists(tf.name, tf.sha1)
+      script.PatchCheck("/"+sf.name, tf.sha1, sf.sha1)
+      so_far += sf.size
+    return so_far
+
+  def RemoveUnneededFiles(self, script, extras=()):
+    script.DeleteFiles(["/"+i[0] for i in self.verbatim_targets] +
+                       ["/"+i for i in sorted(self.source_data)
+                              if i not in self.target_data and
+                              i not in self.renames] +
+                       list(extras))
+
+  def TotalPatchSize(self):
+    return sum(i[1].size for i in self.patch_list)
+
+  def EmitPatches(self, script, total_patch_size, so_far):
+    self.deferred_patch_list = deferred_patch_list = []
+    for item in self.patch_list:
+      tf, sf, size, _ = item
+      if tf.name == "system/build.prop":
+        deferred_patch_list.append(item)
+        continue
+      if (sf.name != tf.name):
+        script.SkipNextActionIfTargetExists(tf.name, tf.sha1)
+      script.ApplyPatch("/"+sf.name, "-", tf.size, tf.sha1, sf.sha1, "patch/"+sf.name+".p")
+      so_far += tf.size
+      script.SetProgress(so_far / total_patch_size)
+    return so_far
+
+  def EmitDeferredPatches(self, script):
+    for item in self.deferred_patch_list:
+      tf, sf, size, _ = item
+      script.ApplyPatch("/"+sf.name, "-", tf.size, tf.sha1, sf.sha1, "patch/"+sf.name+".p")
+    script.SetPermissions("/system/build.prop", 0, 0, 0644, None, None)
+
+  def EmitRenames(self, script):
+    if len(self.renames) > 0:
+      script.Print("Renaming files...")
+      for src, tgt in self.renames.iteritems():
+        print "Renaming " + src + " to " + tgt.name
+        script.RenameFile(src, tgt.name)
+
+
+
+
 def WriteIncrementalOTAPackage(target_zip, source_zip, output_zip):
   target_has_recovery_patch = HasRecoveryPatch(target_zip)
   source_has_recovery_patch = HasRecoveryPatch(source_zip)
@@ -925,75 +1111,13 @@
       metadata=metadata,
       info_dict=OPTIONS.info_dict)
 
-  print "Loading target..."
-  target_data = LoadSystemFiles(target_zip)
-  print "Loading source..."
-  source_data = LoadSystemFiles(source_zip)
-
-  verbatim_targets = []
-  patch_list = []
-  diffs = []
-  renames = {}
-  known_paths = set()
-  largest_source_size = 0
-
-  matching_file_cache = {}
-  for fn, sf in source_data.items():
-    assert fn == sf.name
-    matching_file_cache["path:" + fn] = sf
-    if fn in target_data.keys():
-      AddToKnownPaths(fn, known_paths)
-    # Only allow eligibility for filename/sha matching
-    # if there isn't a perfect path match.
-    if target_data.get(sf.name) is None:
-      matching_file_cache["file:" + fn.split("/")[-1]] = sf
-      matching_file_cache["sha:" + sf.sha1] = sf
-
-  for fn in sorted(target_data.keys()):
-    tf = target_data[fn]
-    assert fn == tf.name
-    sf = ClosestFileMatch(tf, matching_file_cache, renames)
-    if sf is not None and sf.name != tf.name:
-      print "File has moved from " + sf.name + " to " + tf.name
-      renames[sf.name] = tf
-
-    if sf is None or fn in OPTIONS.require_verbatim:
-      # This file should be included verbatim
-      if fn in OPTIONS.prohibit_verbatim:
-        raise common.ExternalError("\"%s\" must be sent verbatim" % (fn,))
-      print "send", fn, "verbatim"
-      tf.AddToZip(output_zip)
-      verbatim_targets.append((fn, tf.size))
-      if fn in target_data.keys():
-        AddToKnownPaths(fn, known_paths)
-    elif tf.sha1 != sf.sha1:
-      # File is different; consider sending as a patch
-      diffs.append(common.Difference(tf, sf))
-    else:
-      # Target file data identical to source (may still be renamed)
-      pass
-
-  common.ComputeDifferences(diffs)
-
-  for diff in diffs:
-    tf, sf, d = diff.GetPatch()
-    path = "/".join(tf.name.split("/")[:-1])
-    if d is None or len(d) > tf.size * OPTIONS.patch_threshold or \
-        path not in known_paths:
-      # patch is almost as big as the file; don't bother patching
-      # or a patch + rename cannot take place due to the target
-      # directory not existing
-      tf.AddToZip(output_zip)
-      verbatim_targets.append((tf.name, tf.size))
-      if sf.name in renames:
-        del renames[sf.name]
-      AddToKnownPaths(tf.name, known_paths)
-    else:
-      common.ZipWriteStr(output_zip, "patch/" + sf.name + ".p", d)
-      patch_list.append((tf, sf, tf.size, common.sha1(d).hexdigest()))
-      largest_source_size = max(largest_source_size, sf.size)
-
+  system_diff = FileDifference("system", source_zip, target_zip, output_zip)
   script.Mount("/system")
+  if HasVendorPartition(target_zip):
+    vendor_diff = FileDifference("vendor", source_zip, target_zip, output_zip)
+    script.Mount("/vendor")
+  else:
+    vendor_diff = None
 
   target_fp = CalculateFingerprint(oem_props, oem_dict, OPTIONS.target_info_dict)
   source_fp = CalculateFingerprint(oem_props, oem_dict, OPTIONS.source_info_dict)
@@ -1077,13 +1201,9 @@
   device_specific.IncrementalOTA_VerifyBegin()
 
   script.ShowProgress(0.1, 0)
-  so_far = 0
-
-  for tf, sf, size, patch_sha in patch_list:
-    if tf.name != sf.name:
-      script.SkipNextActionIfTargetExists(tf.name, tf.sha1)
-    script.PatchCheck("/"+sf.name, tf.sha1, sf.sha1)
-    so_far += sf.size
+  so_far = system_diff.EmitVerification(script)
+  if vendor_diff:
+    so_far += vendor_diff.EmitVerification(script)
 
   if updating_boot:
     d = common.Difference(target_boot, source_boot)
@@ -1101,8 +1221,12 @@
                        target_boot.size, target_boot.sha1))
     so_far += source_boot.size
 
-  if patch_list or updating_recovery or updating_boot:
-    script.CacheFreeSpaceCheck(largest_source_size)
+  size = []
+  if system_diff.patch_list: size.append(system_diff.largest_source_size)
+  if vendor_diff:
+    if vendor_diff.patch_list: size.append(vendor_diff.largest_source_size)
+  if size or updating_recovery or updating_boot:
+    script.CacheFreeSpaceCheck(max(size))
 
   device_specific.IncrementalOTA_VerifyEnd()
 
@@ -1124,30 +1248,22 @@
     print "writing full boot image (forced by two-step mode)"
 
   script.Print("Removing unneeded files...")
-  script.DeleteFiles(["/"+i[0] for i in verbatim_targets] +
-                     ["/"+i for i in sorted(source_data)
-                            if i not in target_data and
-                            i not in renames] +
-                     ["/system/recovery.img"])
+  system_diff.RemoveUnneededFiles(script, ("/system/recovery.img",))
+  if vendor_diff:
+    vendor_diff.RemoveUnneededFiles(script)
 
   script.ShowProgress(0.8, 0)
-  total_patch_size = float(sum([i[1].size for i in patch_list]) + 1)
+  total_patch_size = 1.0 + system_diff.TotalPatchSize()
+  if vendor_diff:
+    total_patch_size += vendor_diff.TotalPatchSize()
   if updating_boot:
     total_patch_size += target_boot.size
-  so_far = 0
 
   script.Print("Patching system files...")
-  deferred_patch_list = []
-  for item in patch_list:
-    tf, sf, size, _ = item
-    if tf.name == "system/build.prop":
-      deferred_patch_list.append(item)
-      continue
-    if (sf.name != tf.name):
-      script.SkipNextActionIfTargetExists(tf.name, tf.sha1)
-    script.ApplyPatch("/"+sf.name, "-", tf.size, tf.sha1, sf.sha1, "patch/"+sf.name+".p")
-    so_far += tf.size
-    script.SetProgress(so_far / total_patch_size)
+  so_far = system_diff.EmitPatches(script, total_patch_size, 0)
+  if vendor_diff:
+    script.Print("Patching vendor files...")
+    so_far = vendor_diff.EmitPatches(script, total_patch_size, so_far)
 
   if not OPTIONS.two_step:
     if updating_boot:
@@ -1168,6 +1284,10 @@
     else:
       print "boot image unchanged; skipping."
 
+  system_items = ItemSet("system", "META/filesystem_config.txt")
+  if vendor_diff:
+    vendor_items = ItemSet("vendor", "META/vendor_filesystem_config.txt")
+
   if updating_recovery:
     # Recovery is generated as a patch using both the boot image
     # (which contains the same linux kernel as recovery) and the file
@@ -1181,7 +1301,7 @@
     if not target_has_recovery_patch:
       def output_sink(fn, data):
         common.ZipWriteStr(output_zip, "recovery/" + fn, data)
-        Item.Get("system/" + fn, dir=False)
+        system_items.Get("system/" + fn, dir=False)
 
       common.MakeRecoveryPatch(OPTIONS.target_tmp, output_sink,
                                target_recovery, target_boot)
@@ -1193,16 +1313,24 @@
 
   script.ShowProgress(0.1, 10)
 
-  target_symlinks = CopySystemFiles(target_zip, None)
+  target_symlinks = CopyPartitionFiles(system_items, target_zip, None)
+  if vendor_diff:
+    target_symlinks.extend(CopyPartitionFiles(vendor_items, target_zip, None))
+
+  temp_script = script.MakeTemporary()
+  system_items.GetMetadata(target_zip)
+  system_items.Get("system").SetPermissions(temp_script)
+  if vendor_diff:
+    vendor_items.GetMetadata(target_zip)
+    vendor_items.Get("vendor").SetPermissions(temp_script)
+
+  # Note that this call will mess up the trees of Items, so make sure
+  # we're done with them.
+  source_symlinks = CopyPartitionFiles(system_items, source_zip, None)
+  if vendor_diff:
+    source_symlinks.extend(CopyPartitionFiles(vendor_items, source_zip, None))
 
   target_symlinks_d = dict([(i[1], i[0]) for i in target_symlinks])
-  temp_script = script.MakeTemporary()
-  Item.GetMetadata(target_zip)
-  Item.Get("system").SetPermissions(temp_script)
-
-  # Note that this call will mess up the tree of Items, so make sure
-  # we're done with it.
-  source_symlinks = CopySystemFiles(source_zip, None)
   source_symlinks_d = dict([(i[1], i[0]) for i in source_symlinks])
 
   # Delete all the symlinks in source that aren't in target.  This
@@ -1214,20 +1342,20 @@
       to_delete.append(link)
   script.DeleteFiles(to_delete)
 
-  if verbatim_targets:
-    script.Print("Unpacking new files...")
+  if system_diff.verbatim_targets:
+    script.Print("Unpacking new system files...")
     script.UnpackPackageDir("system", "/system")
+  if vendor_diff and vendor_diff.verbatim_targets:
+    script.Print("Unpacking new vendor files...")
+    script.UnpackPackageDir("vendor", "/vendor")
 
   if updating_recovery and not target_has_recovery_patch:
     script.Print("Unpacking new recovery...")
     script.UnpackPackageDir("recovery", "/system")
 
-  if len(renames) > 0:
-    script.Print("Renaming files...")
-
-  for src in renames:
-    print "Renaming " + src + " to " + renames[src].name
-    script.RenameFile(src, renames[src].name)
+  system_diff.EmitRenames(script)
+  if vendor_diff:
+    vendor_diff.EmitRenames(script)
 
   script.Print("Symlinks and permissions...")
 
@@ -1258,10 +1386,7 @@
   # device can still come up, it appears to be the old build and will
   # get set the OTA package again to retry.
   script.Print("Patching remaining system files...")
-  for item in deferred_patch_list:
-    tf, sf, size, _ = item
-    script.ApplyPatch("/"+sf.name, "-", tf.size, tf.sha1, sf.sha1, "patch/"+sf.name+".p")
-  script.SetPermissions("/system/build.prop", 0, 0, 0644, None, None)
+  system_diff.EmitDeferredPatches(script)
 
   if OPTIONS.wipe_user_data:
     script.Print("Erasing user data...")
@@ -1300,8 +1425,12 @@
         OPTIONS.aslr_mode = True
       else:
         OPTIONS.aslr_mode = False
-    elif o in ("--worker_threads"):
-      OPTIONS.worker_threads = int(a)
+    elif o in ("-t", "--worker_threads"):
+      if a.isdigit():
+        OPTIONS.worker_threads = int(a)
+      else:
+        raise ValueError("Cannot parse value %r for option %r - only "
+                         "integers are allowed." % (a, o))
     elif o in ("-2", "--two_step"):
       OPTIONS.two_step = True
     elif o == "--no_signing":
@@ -1315,7 +1444,7 @@
     return True
 
   args = common.ParseOptions(argv, __doc__,
-                             extra_opts="b:k:i:d:wne:a:2o:",
+                             extra_opts="b:k:i:d:wne:t:a:2o:",
                              extra_long_opts=["board_config=",
                                               "package_key=",
                                               "incremental_from=",
diff --git a/tools/releasetools/sign_target_files_apks b/tools/releasetools/sign_target_files_apks
index 5398cec..0ecb906 100755
--- a/tools/releasetools/sign_target_files_apks
+++ b/tools/releasetools/sign_target_files_apks
@@ -142,6 +142,7 @@
 
 def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
                        apk_key_map, key_passwords):
+
   maxsize = max([len(os.path.basename(i.filename))
                  for i in input_tf_zip.infolist()
                  if i.filename.endswith('.apk')])
@@ -188,7 +189,7 @@
     elif info.filename in ("SYSTEM/build.prop",
                            "RECOVERY/RAMDISK/default.prop"):
       print "rewriting %s:" % (info.filename,)
-      new_data = RewriteProps(data)
+      new_data = RewriteProps(data, misc_info)
       output_tf_zip.writestr(out_info, new_data)
       if info.filename == "RECOVERY/RAMDISK/default.prop":
         write_to_temp(info.filename, info.external_attr, new_data)
@@ -270,14 +271,20 @@
   return ",".join(sorted(tags))
 
 
-def RewriteProps(data):
+def RewriteProps(data, misc_info):
   output = []
   for line in data.split("\n"):
     line = line.strip()
     original_line = line
-    if line and line[0] != '#':
+    if line and line[0] != '#' and "=" in line:
       key, value = line.split("=", 1)
-      if key == "ro.build.fingerprint":
+      if (key == "ro.build.fingerprint"
+          and misc_info.get("oem_fingerprint_properties") is None):
+        pieces = value.split("/")
+        pieces[-1] = EditTags(pieces[-1])
+        value = "/".join(pieces)
+      elif (key == "ro.build.thumbprint"
+          and misc_info.get("oem_fingerprint_properties") is not None):
         pieces = value.split("/")
         pieces[-1] = EditTags(pieces[-1])
         value = "/".join(pieces)
@@ -291,7 +298,7 @@
       elif key == "ro.build.display.id":
         # change, eg, "JWR66N dev-keys" to "JWR66N"
         value = value.split()
-        if len(value) >  1 and value[-1].endswith("-keys"):
+        if len(value) > 1 and value[-1].endswith("-keys"):
           value.pop()
         value = " ".join(value)
       line = key + "=" + value
diff --git a/tools/signapk/SignApk.java b/tools/signapk/SignApk.java
index b247072..e661e50 100644
--- a/tools/signapk/SignApk.java
+++ b/tools/signapk/SignApk.java
@@ -461,24 +461,75 @@
      * reduce variation in the output file and make incremental OTAs
      * more efficient.
      */
-    private static void copyFiles(Manifest manifest,
-                                  JarFile in, JarOutputStream out, long timestamp) throws IOException {
+    private static void copyFiles(Manifest manifest, JarFile in, JarOutputStream out,
+                                  long timestamp, int alignment) throws IOException {
         byte[] buffer = new byte[4096];
         int num;
 
         Map<String, Attributes> entries = manifest.getEntries();
         ArrayList<String> names = new ArrayList<String>(entries.keySet());
         Collections.sort(names);
+
+        boolean firstEntry = true;
+        long offset = 0L;
+
+        // We do the copy in two passes -- first copying all the
+        // entries that are STORED, then copying all the entries that
+        // have any other compression flag (which in practice means
+        // DEFLATED).  This groups all the stored entries together at
+        // the start of the file and makes it easier to do alignment
+        // on them (since only stored entries are aligned).
+
         for (String name : names) {
             JarEntry inEntry = in.getJarEntry(name);
             JarEntry outEntry = null;
-            if (inEntry.getMethod() == JarEntry.STORED) {
-                // Preserve the STORED method of the input entry.
-                outEntry = new JarEntry(inEntry);
-            } else {
-                // Create a new entry so that the compressed len is recomputed.
-                outEntry = new JarEntry(name);
+            if (inEntry.getMethod() != JarEntry.STORED) continue;
+            // Preserve the STORED method of the input entry.
+            outEntry = new JarEntry(inEntry);
+            outEntry.setTime(timestamp);
+
+            // 'offset' is the offset into the file at which we expect
+            // the file data to begin.  This is the value we need to
+            // make a multiple of 'alignement'.
+            offset += JarFile.LOCHDR + outEntry.getName().length();
+            if (firstEntry) {
+                // The first entry in a jar file has an extra field of
+                // four bytes that you can't get rid of; any extra
+                // data you specify in the JarEntry is appended to
+                // these forced four bytes.  This is JAR_MAGIC in
+                // JarOutputStream; the bytes are 0xfeca0000.
+                offset += 4;
+                firstEntry = false;
             }
+            if (alignment > 0 && (offset % alignment != 0)) {
+                // Set the "extra data" of the entry to between 1 and
+                // alignment-1 bytes, to make the file data begin at
+                // an aligned offset.
+                int needed = alignment - (int)(offset % alignment);
+                outEntry.setExtra(new byte[needed]);
+                offset += needed;
+            }
+
+            out.putNextEntry(outEntry);
+
+            InputStream data = in.getInputStream(inEntry);
+            while ((num = data.read(buffer)) > 0) {
+                out.write(buffer, 0, num);
+                offset += num;
+            }
+            out.flush();
+        }
+
+        // Copy all the non-STORED entries.  We don't attempt to
+        // maintain the 'offset' variable past this point; we don't do
+        // alignment on these entries.
+
+        for (String name : names) {
+            JarEntry inEntry = in.getJarEntry(name);
+            JarEntry outEntry = null;
+            if (inEntry.getMethod() == JarEntry.STORED) continue;
+            // Create a new entry so that the compressed len is recomputed.
+            outEntry = new JarEntry(name);
             outEntry.setTime(timestamp);
             out.putNextEntry(outEntry);
 
@@ -589,7 +640,7 @@
                 long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;
 
                 Manifest manifest = addDigestsToManifest(inputJar, hash);
-                copyFiles(manifest, inputJar, outputJar, timestamp);
+                copyFiles(manifest, inputJar, outputJar, timestamp, 0);
                 addOtacert(outputJar, publicKeyFile, timestamp, manifest, hash);
 
                 signFile(manifest, inputJar,
@@ -778,6 +829,7 @@
 
     private static void usage() {
         System.err.println("Usage: signapk [-w] " +
+                           "[-a <alignment>] " +
                            "[-providerClass <className>] " +
                            "publickey.x509[.pem] privatekey.pk8 " +
                            "[publickey2.x509[.pem] privatekey2.pk8 ...] " +
@@ -794,6 +846,7 @@
         boolean signWholeFile = false;
         String providerClass = null;
         String providerArg = null;
+        int alignment = 4;
 
         int argstart = 0;
         while (argstart < args.length && args[argstart].startsWith("-")) {
@@ -806,6 +859,9 @@
                 }
                 providerClass = args[++argstart];
                 ++argstart;
+            } else if ("-a".equals(args[argstart])) {
+                alignment = Integer.parseInt(args[++argstart]);
+                ++argstart;
             } else {
                 usage();
             }
@@ -872,7 +928,7 @@
                 outputJar.setLevel(9);
 
                 Manifest manifest = addDigestsToManifest(inputJar, hashes);
-                copyFiles(manifest, inputJar, outputJar, timestamp);
+                copyFiles(manifest, inputJar, outputJar, timestamp, alignment);
                 signFile(manifest, inputJar, publicKey, privateKey, outputJar);
                 outputJar.close();
             }