am b53a073d: am e375c940: Merge "SDK: Use "strip -x" for atree."

* commit 'b53a073ddb3a5036f41ea2956792991b7a46da02':
  SDK: Use "strip -x" for atree.
diff --git a/CleanSpec.mk b/CleanSpec.mk
index ea28ec0..74ad978 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -107,6 +107,19 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libbcinfo_intermediates)
+
+# ICS MR2!!!!!!!!!!!!
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libbcinfo_intermediates)
+
+# WAIT, I MEAN JELLY BEAN!!!!!!!!!!!!
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+
+# Changing where ro.carrier value is instantiated for system/build.prop
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
 
 # Now we switched to build against Mac OS X SDK 10.6
diff --git a/core/Makefile b/core/Makefile
index 74883d4..f0b866a 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -9,6 +9,8 @@
   FILE_NAME_TAG := $(BUILD_NUMBER)
 endif
 
+is_tests_build := $(filter tests,$(MAKECMDGOALS))
+
 # -----------------------------------------------------------------
 # Define rules to copy PRODUCT_COPY_FILES defined by the product.
 # PRODUCT_COPY_FILES contains words like <source file>:<dest file>.
@@ -26,20 +28,25 @@
     $(eval _src := $(call word-colon,1,$(cf))) \
     $(eval _dest := $(call word-colon,2,$(cf))) \
     $(call check-product-copy-files,$(cf)) \
-    $(if $(filter $(unique_product_copy_files_destinations),$(_dest)),, \
+    $(if $(filter $(unique_product_copy_files_destinations),$(_dest)), \
+        $(info PRODUCT_COPY_FILES $(cf) ignored.), \
         $(eval _fulldest := $(call append-path,$(PRODUCT_OUT),$(_dest))) \
-        $(eval $(call copy-one-file,$(_src),$(_fulldest))) \
+        $(if $(filter %.xml,$(_dest)),\
+            $(eval $(call copy-xml-file-checked,$(_src),$(_fulldest))),\
+            $(eval $(call copy-one-file,$(_src),$(_fulldest)))) \
         $(eval ALL_DEFAULT_INSTALLED_MODULES += $(_fulldest)) \
         $(eval unique_product_copy_files_destinations += $(_dest))))
 unique_product_copy_files_destinations :=
 
 # -----------------------------------------------------------------
 # docs/index.html
+ifeq (,$(TARGET_BUILD_APPS))
 gen := $(OUT_DOCS)/index.html
 ALL_DOCS += $(gen)
 $(gen): frameworks/base/docs/docs-redirect-index.html
 	@mkdir -p $(dir $@)
 	@cp -f $< $@
+endif
 
 # -----------------------------------------------------------------
 # default.prop
@@ -295,18 +302,21 @@
 
 all_event_log_tags_file := $(TARGET_OUT_COMMON_INTERMEDIATES)/all-event-log-tags.txt
 
+event_log_tags_file := $(TARGET_OUT)/etc/event-log-tags
+
 # Include tags from all packages that we know about
 all_event_log_tags_src := \
     $(sort $(foreach m, $(ALL_MODULES), $(ALL_MODULES.$(m).EVENT_LOG_TAGS)))
 
-$(all_event_log_tags_file): PRIVATE_SRC_FILES := $(all_event_log_tags_src)
-$(all_event_log_tags_file): $(all_event_log_tags_src)
+# PDK builds will already have a full list of tags that needs to get merged
+# in with the ones from source
+pdk_fusion_log_tags_file := $(patsubst $(PRODUCT_OUT)/%,$(_pdk_fusion_intermediates)/%,$(filter $(event_log_tags_file),$(ALL_PDK_FUSION_FILES)))
+
+$(all_event_log_tags_file): PRIVATE_SRC_FILES := $(all_event_log_tags_src) $(pdk_fusion_log_tags_file)
+$(all_event_log_tags_file): $(all_event_log_tags_src) $(pdk_fusion_log_tags_file)
 	$(hide) mkdir -p $(dir $@)
 	$(hide) build/tools/merge-event-log-tags.py -o $@ $(PRIVATE_SRC_FILES)
 
-
-event_log_tags_file := $(TARGET_OUT)/etc/event-log-tags
-
 # Include tags from all packages included in this product, plus all
 # tags that are part of the system (ie, not in a vendor/ or device/
 # directory).
@@ -317,9 +327,9 @@
       $(ALL_MODULES.$(m).EVENT_LOG_TAGS)) \
       $(filter-out vendor/% device/% out/%,$(all_event_log_tags_src)))
 
-$(event_log_tags_file): PRIVATE_SRC_FILES := $(event_log_tags_src)
+$(event_log_tags_file): PRIVATE_SRC_FILES := $(event_log_tags_src) $(pdk_fusion_log_tags_file)
 $(event_log_tags_file): PRIVATE_MERGED_FILE := $(all_event_log_tags_file)
-$(event_log_tags_file): $(event_log_tags_src) $(all_event_log_tags_file)
+$(event_log_tags_file): $(event_log_tags_src) $(all_event_log_tags_file) $(pdk_fusion_log_tags_file)
 	$(hide) mkdir -p $(dir $@)
 	$(hide) build/tools/merge-event-log-tags.py -o $@ -m $(PRIVATE_MERGED_FILE) $(PRIVATE_SRC_FILES)
 
@@ -409,6 +419,11 @@
 # -----------------------------------------------------------------
 # NOTICE files
 #
+# We are required to publish the licenses for all code under BSD, GPL and
+# Apache licenses (and possibly other more exotic ones as well). We err on the
+# side of caution, so the licenses for other third-party code are included here
+# too.
+#
 # This needs to be before the systemimage rules, because it adds to
 # ALL_DEFAULT_INSTALLED_MODULES, which those use to pick which files
 # go into the systemimage.
@@ -436,78 +451,10 @@
 # Then we could traverse that without quite as much bash drama.
 define combine-notice-files
 $(1) $(2): PRIVATE_MESSAGE := $(3)
-$(1) $(2) $(4)/hash-timestamp: PRIVATE_DIR := $(4)
-$(4)/hash-timestamp: $(5) $(BUILD_SYSTEM)/Makefile
-	@echo Finding NOTICE files: $$@
-	$$(hide) rm -rf $$@ $$(PRIVATE_DIR)/hash
-	$$(hide) mkdir -p $$(PRIVATE_DIR)/hash
-	$$(hide) for file in $$$$(find $$(PRIVATE_DIR)/src -type f); do \
-			hash=$$$$($(MD5SUM) $$$$file | sed -e "s/ .*//"); \
-			hashfile=$$(PRIVATE_DIR)/hash/$$$$hash; \
-			echo $$$$file >> $$$$hashfile; \
-		done
-	$$(hide) touch $$@
-$(1): $(4)/hash-timestamp
-	@echo Combining NOTICE files: $$@
-	$$(hide) mkdir -p $$(dir $$@)
-	$$(hide) echo $$(PRIVATE_MESSAGE) > $$@
-	$$(hide) find $$(PRIVATE_DIR)/hash -type f | xargs cat | sort | \
-		sed -e "s:$$(PRIVATE_DIR)/src\(.*\)\.txt:  \1:" >> $$@
-	$$(hide) echo >> $$@
-	$$(hide) echo >> $$@
-	$$(hide) echo >> $$@
-	$$(hide) for hashfile in $$$$(find $$(PRIVATE_DIR)/hash -type f); do \
-			echo "============================================================"\
-				>> $$@; \
-			echo "Notices for file(s):" >> $$@; \
-			cat $$$$hashfile | sort | \
-				sed -e "s:$$(PRIVATE_DIR)/src\(.*\)\.txt:  \1:" >> \
-				$$@; \
-			echo "------------------------------------------------------------"\
-				>> $$@; \
-			echo >> $$@; \
-			orig=$$$$(head -n 1 $$$$hashfile); \
-			cat $$$$orig >> $$@; \
-			echo >> $$@; \
-			echo >> $$@; \
-			echo >> $$@; \
-		done
-$(2): $(4)/hash-timestamp
-	@echo Combining NOTICE files: $$@
-	$$(hide) mkdir -p $$(dir $$@)
-	$$(hide) echo "<html><head>" > $$@
-	$$(hide) echo "<style type=\"text/css\">" >> $$@
-	$$(hide) echo "body { padding: 0; font-family: sans-serif; }" >> $$@
-	$$(hide) echo ".same-license { background-color: #eeeeee; border-top: 20px solid white; padding: 10px; }" >> $$@
-	$$(hide) echo ".label { font-weight: bold; }" >> $$@
-	$$(hide) echo ".file-list { margin-left: 1em; font-color: blue; }" >> $$@
-	$$(hide) echo "</style>" >> $$@
-	$$(hide) echo "</head><body topmargin=\"0\" leftmargin=\"0\" rightmargin=\"0\" bottommargin=\"0\">" >> $$@
-	$$(hide) echo "<table cellpading=\"0\" cellspacing=\"0\" border=\"0\">" \
-		>> $$@
-	$$(hide) for hashfile in $$$$(find $$(PRIVATE_DIR)/hash -type f); do \
-			cat $$$$hashfile | sort | \
-				sed -e "s:$$(PRIVATE_DIR)/src\(.*\)\.txt:  <a name=\"\1\"></a>:" >> \
-				$$@; \
-			echo "<tr><td class=\"same-license\">" >> $$@; \
-			echo "<div class=\"label\">Notices for file(s):</div>" >> $$@; \
-			echo "<div class=\"file-list\">" >> $$@; \
-			cat $$$$hashfile | sort | \
-				sed -e "s:$$(PRIVATE_DIR)/src\(.*\)\.txt:  \1<br/>:" >> $$@; \
-			echo "</div><!-- file-list -->" >> $$@; \
-			echo >> $$@; \
-			orig=$$$$(head -n 1 $$$$hashfile); \
-			echo "<pre class=\"license-text\">" >> $$@; \
-			cat $$$$orig | sed -e "s/\&/\&amp;/g" | sed -e "s/</\&lt;/g" \
-					| sed -e "s/>/\&gt;/g" >> $$@; \
-			echo "</pre><!-- license-text -->" >> $$@; \
-			echo "</td></tr><!-- same-license -->" >> $$@; \
-			echo >> $$@; \
-			echo >> $$@; \
-			echo >> $$@; \
-		done
-	$$(hide) echo "</table>" >> $$@
-	$$(hide) echo "</body></html>" >> $$@
+$(1) $(2): PRIVATE_DIR := $(4)
+$(1) : $(2)
+$(2) : $(5) $(BUILD_SYSTEM)/Makefile build/tools/generate-notice-files.py
+	build/tools/generate-notice-files.py $(1) $(2) $$(PRIVATE_MESSAGE) $$(PRIVATE_DIR)/src
 notice_files: $(1) $(2)
 endef
 
@@ -522,13 +469,14 @@
 tools_notice_file_html := $(HOST_OUT_INTERMEDIATES)/NOTICE.html
 
 kernel_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/kernel.txt
+pdk_fusion_notice_files := $(filter $(TARGET_OUT_NOTICE_FILES)/%, $(ALL_PDK_FUSION_FILES))
 
 $(eval $(call combine-notice-files, \
 			$(target_notice_file_txt), \
 			$(target_notice_file_html), \
 			"Notices for files contained in the filesystem images in this directory:", \
 			$(TARGET_OUT_NOTICE_FILES), \
-			$(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file)))
+			$(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file) $(pdk_fusion_notice_files)))
 
 $(eval $(call combine-notice-files, \
 			$(tools_notice_file_txt), \
@@ -607,24 +555,22 @@
 
 ifeq ($(INTERNAL_USERIMAGES_USE_EXT),true)
 INTERNAL_USERIMAGES_DEPS := $(MKEXTUSERIMG) $(MAKE_EXT4FS)
-INTERNAL_USERIMAGES_BINARY_PATHS := $(sort $(dir $(INTERNAL_USERIMAGES_DEPS)))
-
-# $(1): src directory
-# $(2): output file
-# $(3): mount point
-# $(4): ext variant (ext2, ext3, ext4)
-# $(5): size of the partition
-define build-userimage-ext-target
-  @mkdir -p $(dir $(2))
-  $(if $(filter true, $(strip $(HAVE_SELINUX))), \
-	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
-		$(MKEXTUSERIMG) $(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG) $(1) $(2) $(4) $(3) $(5) $(TARGET_ROOT_OUT)/file_contexts, \
-	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
-		$(MKEXTUSERIMG) $(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG) $(1) $(2) $(4) $(3) $(5))
-endef
 else
 INTERNAL_USERIMAGES_DEPS := $(MKYAFFS2)
 endif
+INTERNAL_USERIMAGES_BINARY_PATHS := $(sort $(dir $(INTERNAL_USERIMAGES_DEPS)))
+
+# $(1): the path of the output dictionary file
+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_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))
+$(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))
+$(if $(filter true, $(strip $(HAVE_SELINUX))), echo "selinux_fc=$(TARGET_ROOT_OUT)/file_contexts" >> $(1))
+endef
 
 # -----------------------------------------------------------------
 # Recovery image
@@ -747,10 +693,19 @@
 #
 
 INTERNAL_SYSTEMIMAGE_FILES := $(filter $(TARGET_OUT)/%, \
-	$(ALL_PREBUILT) \
-	$(ALL_COPIED_HEADERS) \
-	$(ALL_GENERATED_SOURCES) \
-	$(ALL_DEFAULT_INSTALLED_MODULES))
+    $(ALL_PREBUILT) \
+    $(ALL_COPIED_HEADERS) \
+    $(ALL_GENERATED_SOURCES) \
+    $(ALL_DEFAULT_INSTALLED_MODULES)\
+    $(ALL_PDK_FUSION_FILES))
+
+ifdef is_tests_build
+# We don't want to install tests modules to the system partition
+# when building "tests", because now "tests" may be built in a user, userdebug
+# or eng build variant and we don't want to pollute the system partition.
+# INTERNAL_SYSTEMIMAGE_FILES += $(filter $(TARGET_OUT)/%, \
+#    $(tests_MODULES))
+endif
 
 FULL_SYSTEMIMAGE_DEPS := $(INTERNAL_SYSTEMIMAGE_FILES) $(INTERNAL_USERIMAGES_DEPS) $(SELINUX_DEPENDS)
 # -----------------------------------------------------------------
@@ -776,30 +731,19 @@
 endif
 
 systemimage_intermediates := \
-	$(call intermediates-dir-for,PACKAGING,systemimage)
+    $(call intermediates-dir-for,PACKAGING,systemimage)
 BUILT_SYSTEMIMAGE := $(systemimage_intermediates)/system.img
 
-ifeq ($(INTERNAL_USERIMAGES_USE_EXT),true)
-## generate an ext image
 # $(1): output file
 define build-systemimage-target
-    @echo "Target system fs image: $(1)"
-    $(call build-userimage-ext-target,$(TARGET_OUT),$(1),system,$(INTERNAL_USERIMAGES_EXT_VARIANT),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE))
+  @echo "Target system fs image: $(1)"
+  @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)
+  $(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)
 endef
 
-else # INTERNAL_USERIMAGES_USE_EXT != true
-
-## generate a yaffs2 image
-# $(1): output file
-define build-systemimage-target
-    @echo "Target system fs image: $(1)"
-    @mkdir -p $(dir $(1))
-    $(if $(filter true, $(strip $(HAVE_SELINUX))), \
-        $(hide) $(MKYAFFS2) -f $(mkyaffs2_extra_flags) $(TARGET_OUT) $(1) $(TARGET_ROOT_OUT)/file_contexts /system, \
-        $(hide) $(MKYAFFS2) -f $(mkyaffs2_extra_flags) $(TARGET_OUT) $(1))
-endef
-endif # INTERNAL_USERIMAGES_USE_EXT
-
 $(BUILT_SYSTEMIMAGE): $(FULL_SYSTEMIMAGE_DEPS) $(INSTALLED_FILES_FILE)
 	$(call build-systemimage-target,$@)
 
@@ -871,6 +815,36 @@
 .PHONY: stnod
 stnod: systemtarball-nodeps
 
+# For platform-java goal, add platform as well
+ifneq (,$(filter platform-java, $(MAKECMDGOALS)))
+PLATFORM_ZIP_ADD_JAVA := true
+endif
+
+#######
+## platform.zip: system, plus other files to be used in PDK fusion build,
+## in a zip file
+INSTALLED_PLATFORM_ZIP := $(PRODUCT_OUT)/platform.zip
+$(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_SYSTEMIMAGE_FILES)
+	$(call pretty,"Platform zip package: $(INSTALLED_PLATFORM_ZIP)")
+	$(hide) rm -f $@
+	$(hide) cd $(dir $@) && zip -qry $(notdir $@) \
+		$(TARGET_COPY_OUT_SYSTEM) \
+		$(patsubst $(PRODUCT_OUT)/%, %, $(TARGET_OUT_NOTICE_FILES))
+ifeq (true,$(PLATFORM_ZIP_ADD_JAVA))
+	$(hide) cd $(OUT_DIR) && zip -qry $(patsubst $(OUT_DIR)/%,%,$@) $(PDK_PLATFORM_JAVA_ZIP_CONTENTS)
+endif
+
+
+.PHONY: platform
+platform: $(INSTALLED_PLATFORM_ZIP)
+
+.PHONY: platform-java
+platform-java: platform
+
+# Dist the platform.zip
+ifneq (,$(filter platform platform-java, $(MAKECMDGOALS)))
+$(call dist-for-goals, platform platform-java, $(INSTALLED_PLATFORM_ZIP))
+endif
 
 #######
 ## boot tarball
@@ -903,32 +877,29 @@
 # -----------------------------------------------------------------
 # data partition image
 INTERNAL_USERDATAIMAGE_FILES := \
-	$(filter $(TARGET_OUT_DATA)/%,$(ALL_DEFAULT_INSTALLED_MODULES))
+    $(filter $(TARGET_OUT_DATA)/%,$(ALL_DEFAULT_INSTALLED_MODULES))
 
-ifeq ($(INTERNAL_USERIMAGES_USE_EXT),true)
-## Generate an ext2 image
-define build-userdataimage-target
-    $(call pretty,"Target userdata fs image: $(INSTALLED_USERDATAIMAGE_TARGET)")
-    @mkdir -p $(TARGET_OUT_DATA)
-    $(call build-userimage-ext-target,$(TARGET_OUT_DATA),$(INSTALLED_USERDATAIMAGE_TARGET),data,$(INTERNAL_USERIMAGES_EXT_VARIANT),$(BOARD_USERDATAIMAGE_PARTITION_SIZE))
-    $(hide) $(call assert-max-image-size,$(INSTALLED_USERDATAIMAGE_TARGET),$(BOARD_USERDATAIMAGE_PARTITION_SIZE),yaffs)
-endef
+# If we build "tests" at the same time, make sure $(tests_MODULES) get covered.
+ifdef is_tests_build
+INTERNAL_USERDATAIMAGE_FILES += \
+    $(filter $(TARGET_OUT_DATA)/%,$(tests_MODULES))
+endif
 
-else # INTERNAL_USERIMAGES_USE_EXT != true
-
-## Generate a yaffs2 image
-define build-userdataimage-target
-    $(call pretty,"Target userdata fs image: $(INSTALLED_USERDATAIMAGE_TARGET)")
-    @mkdir -p $(TARGET_OUT_DATA)
-    $(if $(filter true, $(strip $(HAVE_SELINUX))), \
-        $(hide) $(MKYAFFS2) -f $(mkyaffs2_extra_flags) $(TARGET_OUT_DATA) $(INSTALLED_USERDATAIMAGE_TARGET) $(TARGET_ROOT_OUT)/file_contexts /data, \
-        $(hide) $(MKYAFFS2) -f $(mkyaffs2_extra_flags) $(TARGET_OUT_DATA) $(INSTALLED_USERDATAIMAGE_TARGET))
-    $(hide) $(call assert-max-image-size,$(INSTALLED_USERDATAIMAGE_TARGET),$(BOARD_USERDATAIMAGE_PARTITION_SIZE),yaffs)
-endef
-endif # INTERNAL_USERIMAGES_USE_EXT
-
+userdataimage_intermediates := \
+    $(call intermediates-dir-for,PACKAGING,userdata)
 BUILT_USERDATAIMAGE_TARGET := $(PRODUCT_OUT)/userdata.img
 
+define build-userdataimage-target
+  $(call pretty,"Target userdata fs image: $(INSTALLED_USERDATAIMAGE_TARGET)")
+  @mkdir -p $(TARGET_OUT_DATA)
+  @mkdir -p $(userdataimage_intermediates) && rm -rf $(userdataimage_intermediates)/userdata_image_info.txt
+  $(call generate-userimage-prop-dictionary, $(userdataimage_intermediates)/userdata_image_info.txt)
+  $(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)
+endef
+
 # We just build this directly to the install location.
 INSTALLED_USERDATAIMAGE_TARGET := $(BUILT_USERDATAIMAGE_TARGET)
 $(INSTALLED_USERDATAIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) \
@@ -961,31 +932,62 @@
 
 
 # -----------------------------------------------------------------
+# cache partition image
+ifdef BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE
+INTERNAL_CACHEIMAGE_FILES := \
+    $(filter $(TARGET_OUT_CACHE)/%,$(ALL_DEFAULT_INSTALLED_MODULES))
+
+cacheimage_intermediates := \
+    $(call intermediates-dir-for,PACKAGING,cache)
+BUILT_CACHEIMAGE_TARGET := $(PRODUCT_OUT)/cache.img
+
+define build-cacheimage-target
+  $(call pretty,"Target cache fs image: $(INSTALLED_CACHEIMAGE_TARGET)")
+  @mkdir -p $(TARGET_OUT_CACHE)
+  @mkdir -p $(cacheimage_intermediates) && rm -rf $(cacheimage_intermediates)/cache_image_info.txt
+  $(call generate-userimage-prop-dictionary, $(cacheimage_intermediates)/cache_image_info.txt)
+  $(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)
+endef
+
+# We just build this directly to the install location.
+INSTALLED_CACHEIMAGE_TARGET := $(BUILT_CACHEIMAGE_TARGET)
+$(INSTALLED_CACHEIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) $(INTERNAL_CACHEIMAGE_FILES)
+	$(build-cacheimage-target)
+
+.PHONY: cacheimage-nodeps
+cacheimage-nodeps: | $(INTERNAL_USERIMAGES_DEPS)
+	$(build-cacheimage-target)
+
+endif # BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE
+
+# -----------------------------------------------------------------
 # bring in the installer image generation defines if necessary
 ifeq ($(TARGET_USE_DISKINSTALLER),true)
 include bootable/diskinstaller/config.mk
 endif
 
 # -----------------------------------------------------------------
-# host tools needed to build OTA packages
+# host tools needed to build dist and OTA packages
 
-OTATOOLS :=  $(HOST_OUT_EXECUTABLES)/minigzip \
+DISTTOOLS :=  $(HOST_OUT_EXECUTABLES)/minigzip \
 	  $(HOST_OUT_EXECUTABLES)/mkbootfs \
 	  $(HOST_OUT_EXECUTABLES)/mkbootimg \
 	  $(HOST_OUT_EXECUTABLES)/fs_config \
 	  $(HOST_OUT_EXECUTABLES)/mkyaffs2image \
 	  $(HOST_OUT_EXECUTABLES)/zipalign \
-	  $(HOST_OUT_EXECUTABLES)/aapt \
 	  $(HOST_OUT_EXECUTABLES)/bsdiff \
 	  $(HOST_OUT_EXECUTABLES)/imgdiff \
 	  $(HOST_OUT_JAVA_LIBRARIES)/dumpkey.jar \
 	  $(HOST_OUT_JAVA_LIBRARIES)/signapk.jar \
 	  $(HOST_OUT_EXECUTABLES)/mkuserimg.sh \
-	  $(HOST_OUT_EXECUTABLES)/genext2fs \
-	  $(HOST_OUT_EXECUTABLES)/tune2fs \
-	  $(HOST_OUT_EXECUTABLES)/e2fsck \
 	  $(HOST_OUT_EXECUTABLES)/make_ext4fs
 
+OTATOOLS := $(DISTTOOLS) \
+	  $(HOST_OUT_EXECUTABLES)/aapt
+
 .PHONY: otatools
 otatools: $(OTATOOLS)
 
@@ -1041,6 +1043,7 @@
 		$(INSTALLED_RECOVERYIMAGE_TARGET) \
 		$(INSTALLED_SYSTEMIMAGE) \
 		$(INSTALLED_USERDATAIMAGE_TARGET) \
+		$(INSTALLED_CACHEIMAGE_TARGET) \
 		$(INSTALLED_ANDROID_INFO_TXT_TARGET) \
 		$(built_ota_tools) \
 		$(APKCERTS_FILE) \
@@ -1117,23 +1120,12 @@
 ifdef BOARD_RECOVERYIMAGE_PARTITION_SIZE
 	$(hide) echo "recovery_size=$(BOARD_RECOVERYIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt
 endif
-ifdef BOARD_SYSTEMIMAGE_PARTITION_SIZE
-	$(hide) echo "system_size=$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt
-endif
-ifdef BOARD_USERDATAIMAGE_PARTITION_SIZE
-	$(hide) echo "userdata_size=$(BOARD_USERDATAIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt
-endif
 	$(hide) echo "tool_extensions=$(tool_extensions)" >> $(zip_root)/META/misc_info.txt
-ifdef mkyaffs2_extra_flags
-	$(hide) echo "mkyaffs2_extra_flags=$(mkyaffs2_extra_flags)" >> $(zip_root)/META/misc_info.txt
-endif
-ifdef INTERNAL_USERIMAGES_SPARSE_EXT_FLAG
-	$(hide) echo "extfs_sparse_flag=$(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG)" >> $(zip_root)/META/misc_info.txt
-endif
 	$(hide) echo "default_system_dev_certificate=$(DEFAULT_SYSTEM_DEV_CERTIFICATE)" >> $(zip_root)/META/misc_info.txt
 ifdef PRODUCT_EXTRA_RECOVERY_KEYS
 	$(hide) echo "extra_recovery_keys=$(PRODUCT_EXTRA_RECOVERY_KEYS)" >> $(zip_root)/META/misc_info.txt
 endif
+	$(call generate-userimage-prop-dictionary, $(zip_root)/META/misc_info.txt)
 	@# 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
@@ -1164,10 +1156,9 @@
 
 $(INTERNAL_OTA_PACKAGE_TARGET): KEY_CERT_PAIR := $(DEFAULT_KEY_CERT_PAIR)
 
-$(INTERNAL_OTA_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(OTATOOLS) $(SELINUX_DEPENDS)
+$(INTERNAL_OTA_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(DISTTOOLS) $(SELINUX_DEPENDS)
 	@echo "Package OTA: $@"
 	$(hide) ./build/tools/releasetools/ota_from_target_files -v \
-	   $(if $(filter true, $(strip $(HAVE_SELINUX))),-S $(TARGET_ROOT_OUT)/file_contexts) \
 	   -p $(HOST_OUT) \
 	   -k $(KEY_CERT_PAIR) \
 	   $(BUILT_TARGET_FILES_PACKAGE) $@
@@ -1193,12 +1184,11 @@
 $(INTERNAL_UPDATE_PACKAGE_TARGET): extensions := $(TARGET_RELEASETOOLS_EXTENSIONS)
 endif
 
-$(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(OTATOOLS) $(SELINUX_DEPENDS)
+$(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(DISTTOOLS) $(SELINUX_DEPENDS)
 	@echo "Package: $@"
 	$(hide) ./build/tools/releasetools/img_from_target_files -v \
 	   -s $(extensions) \
 	   -p $(HOST_OUT) \
-	   $(if $(filter true, $(strip $(HAVE_SELINUX))),-S $(TARGET_ROOT_OUT)/file_contexts) \
 	   $(BUILT_TARGET_FILES_PACKAGE) $@
 
 .PHONY: updatepackage
@@ -1212,7 +1202,7 @@
 # -----------------------------------------------------------------
 # A zip of the tests that are built when running "make tests".
 # This is very similar to BUILT_TARGET_FILES_PACKAGE, but we
-# only grab SYSTEM and DATA, and it's called "*-tests-*.zip".
+# only grab DATA, and it's called "*-tests-*.zip".
 #
 name := $(TARGET_PRODUCT)
 ifeq ($(TARGET_BUILD_TYPE),debug)
@@ -1228,21 +1218,11 @@
 # Depending on the images guarantees that the underlying
 # directories are up-to-date.
 $(BUILT_TESTS_ZIP_PACKAGE): \
-		$(BUILT_SYSTEMIMAGE) \
-		$(INSTALLED_USERDATAIMAGE_TARGET) \
-		| $(ACP)
+    $(INSTALLED_USERDATAIMAGE_TARGET) \
+    | $(ACP)
 	@echo "Package test files: $@"
 	$(hide) rm -rf $@ $(zip_root)
 	$(hide) mkdir -p $(dir $@) $(zip_root)
-	@# Some parts of the system image
-	$(hide) $(call package_files-copy-root, \
-		$(SYSTEMIMAGE_SOURCE_DIR)/xbin,$(zip_root)/SYSTEM/xbin)
-	$(hide) $(call package_files-copy-root, \
-		$(SYSTEMIMAGE_SOURCE_DIR)/lib,$(zip_root)/SYSTEM/lib)
-	$(hide) $(call package_files-copy-root, \
-		$(SYSTEMIMAGE_SOURCE_DIR)/framework, \
-		$(zip_root)/SYSTEM/framework)
-	$(hide) $(ACP) $(SYSTEMIMAGE_SOURCE_DIR)/build.prop $(zip_root)/SYSTEM
 	@# Contents of the data image
 	$(hide) $(call package_files-copy-root, \
 		$(TARGET_OUT_DATA),$(zip_root)/DATA)
@@ -1253,13 +1233,17 @@
 
 # Target needed by tests build
 .PHONY: tests-build-target
-tests-build-target: $(BUILT_TESTS_ZIP_PACKAGE) \
-                    $(BUILT_USERDATAIMAGE_TARGET)
+tests-build-target: $(BUILT_TESTS_ZIP_PACKAGE)
 
 ifneq (,$(filter $(MAKECMDGOALS),tests-build-target))
   $(call dist-for-goals, tests-build-target, \
-          $(BUILT_TESTS_ZIP_PACKAGE) \
-          $(BUILT_USERDATAIMAGE_TARGET))
+          $(BUILT_TESTS_ZIP_PACKAGE))
+endif
+
+.PHONY: tests
+tests: $(BUILT_TESTS_ZIP_PACKAGE)
+ifneq (,$(filter tests, $(MAKECMDGOALS)))
+$(call dist-for-goals, tests, $(BUILT_TESTS_ZIP_PACKAGE))
 endif
 
 # -----------------------------------------------------------------
@@ -1331,11 +1315,13 @@
 	$(hide) zip -qj $@ $(INTERNAL_EMULATOR_PACKAGE_FILES)
 
 # -----------------------------------------------------------------
+# Old PDK stuffs, retired
 # The pdk package (Platform Development Kit)
 
-ifneq (,$(filter pdk,$(MAKECMDGOALS)))
-  include development/pdk/Pdk.mk
-endif
+#ifneq (,$(filter pdk,$(MAKECMDGOALS)))
+#  include development/pdk/Pdk.mk
+#endif
+
 
 # -----------------------------------------------------------------
 # The SDK
diff --git a/core/armelf.x b/core/armelf.x
deleted file mode 100644
index d38dc1d..0000000
--- a/core/armelf.x
+++ /dev/null
@@ -1,204 +0,0 @@
-/* Default linker script, for normal executables */
-OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm",
-	      "elf32-littlearm")
-OUTPUT_ARCH(arm)
-ENTRY(_start)
-SEARCH_DIR("/usr/local/armdev/arm-elf/lib");
-/* Do we need any of these for elf?
-   __DYNAMIC = 0;    */
-SECTIONS
-{
-  /* Read-only sections, merged into text segment: */
-/*  PROVIDE (__executable_start = 0x8000); . = 0x8000; */
-. = 0x8000 + SIZEOF_HEADERS; 
-  .interp         : { *(.interp) }
-  .hash           : { *(.hash) }
-  .dynsym         : { *(.dynsym) }
-  .dynstr         : { *(.dynstr) }
-  .gnu.version    : { *(.gnu.version) }
-  .gnu.version_d  : { *(.gnu.version_d) }
-  .gnu.version_r  : { *(.gnu.version_r) }
-  .rel.init       : { *(.rel.init) }
-  .rela.init      : { *(.rela.init) }
-  .rel.text       : { *(.rel.text .rel.text.* .rel.gnu.linkonce.t.*) }
-  .rela.text      : { *(.rela.text .rela.text.* .rela.gnu.linkonce.t.*) }
-  .rel.fini       : { *(.rel.fini) }
-  .rela.fini      : { *(.rela.fini) }
-  .rel.rodata     : { *(.rel.rodata .rel.rodata.* .rel.gnu.linkonce.r.*) }
-  .rela.rodata    : { *(.rela.rodata .rela.rodata.* .rela.gnu.linkonce.r.*) }
-  .rel.data.rel.ro   : { *(.rel.data.rel.ro*) }
-  .rela.data.rel.ro   : { *(.rel.data.rel.ro*) }
-  .rel.data       : { *(.rel.data .rel.data.* .rel.gnu.linkonce.d.*) }
-  .rela.data      : { *(.rela.data .rela.data.* .rela.gnu.linkonce.d.*) }
-  .rel.tdata	  : { *(.rel.tdata .rel.tdata.* .rel.gnu.linkonce.td.*) }
-  .rela.tdata	  : { *(.rela.tdata .rela.tdata.* .rela.gnu.linkonce.td.*) }
-  .rel.tbss	  : { *(.rel.tbss .rel.tbss.* .rel.gnu.linkonce.tb.*) }
-  .rela.tbss	  : { *(.rela.tbss .rela.tbss.* .rela.gnu.linkonce.tb.*) }
-  .rel.ctors      : { *(.rel.ctors) }
-  .rela.ctors     : { *(.rela.ctors) }
-  .rel.dtors      : { *(.rel.dtors) }
-  .rela.dtors     : { *(.rela.dtors) }
-  .rel.got        : { *(.rel.got) }
-  .rela.got       : { *(.rela.got) }
-  .rel.bss        : { *(.rel.bss .rel.bss.* .rel.gnu.linkonce.b.*) }
-  .rela.bss       : { *(.rela.bss .rela.bss.* .rela.gnu.linkonce.b.*) }
-  .rel.plt        : { *(.rel.plt) }
-  .rela.plt       : { *(.rela.plt) }
-  .init           :
-  {
-    KEEP (*(.init))
-  } =0
-  .plt            : { *(.plt) }
-  .text           :
-  {
-    *(.text .stub .text.* .gnu.linkonce.t.*)
-    KEEP (*(.text.*personality*))
-    /* .gnu.warning sections are handled specially by elf32.em.  */
-    *(.gnu.warning)
-    *(.glue_7t) *(.glue_7)
-  } =0
-  .fini           :
-  {
-    KEEP (*(.fini))
-  } =0
-  PROVIDE (__etext = .);
-  PROVIDE (_etext = .);
-  PROVIDE (etext = .);
-  .rodata         : { *(.rodata .rodata.* .gnu.linkonce.r.*) }
-  .rodata1        : { *(.rodata1) }
-  /* We have to wrap extab and exidx sections with KEEP because we use
-     --gc-sections. */
-  .ARM.extab   : { KEEP (*(.ARM.extab* .gnu.linkonce.armextab.*)) }
-   __exidx_start = .;
-  .ARM.exidx   : { KEEP (*(.ARM.exidx* .gnu.linkonce.armexidx.*)) }
-   __exidx_end = .;
-  .eh_frame_hdr : { *(.eh_frame_hdr) }
-  .eh_frame       : ONLY_IF_RO { KEEP (*(.eh_frame)) }
-  .gcc_except_table   : ONLY_IF_RO { KEEP (*(.gcc_except_table)) *(.gcc_except_table.*) }
-  /* Adjust the address for the data segment.  We want to align at exactly
-     a page boundary to make life easier for apriori. */
-  . = ALIGN(4096);
-  /* Exception handling  */
-  .eh_frame       : ONLY_IF_RW { KEEP (*(.eh_frame)) }
-  .gcc_except_table   : ONLY_IF_RW { KEEP (*(.gcc_except_table)) *(.gcc_except_table.*) }
-  /* Thread Local Storage sections  */
-  .tdata	  : { *(.tdata .tdata.* .gnu.linkonce.td.*) }
-  .tbss		  : { *(.tbss .tbss.* .gnu.linkonce.tb.*) *(.tcommon) }
-  /* Ensure the __preinit_array_start label is properly aligned.  We
-     could instead move the label definition inside the section, but
-     the linker would then create the section even if it turns out to
-     be empty, which isn't pretty.  */
-  . = ALIGN(32 / 8);
-  PROVIDE (__preinit_array_start = .);
-  .preinit_array     : { KEEP (*(.preinit_array)) }
-  PROVIDE (__preinit_array_end = .);
-  PROVIDE (__init_array_start = .);
-  .init_array     : { KEEP (*(.init_array)) }
-  PROVIDE (__init_array_end = .);
-  PROVIDE (__fini_array_start = .);
-  .fini_array     : { KEEP (*(.fini_array)) }
-  PROVIDE (__fini_array_end = .);
-  .ctors          :
-  {
-    /* gcc uses crtbegin.o to find the start of
-       the constructors, so we make sure it is
-       first.  Because this is a wildcard, it
-       doesn't matter if the user does not
-       actually link against crtbegin.o; the
-       linker won't look for a file to match a
-       wildcard.  The wildcard also means that it
-       doesn't matter which directory crtbegin.o
-       is in.  */
-    KEEP (*crtbegin*.o(.ctors))
-    /* We don't want to include the .ctor section from
-       from the crtend.o file until after the sorted ctors.
-       The .ctor section from the crtend file contains the
-       end of ctors marker and it must be last */
-    KEEP (*(EXCLUDE_FILE (*crtend*.o ) .ctors))
-    KEEP (*(SORT(.ctors.*)))
-    KEEP (*(.ctors))
-  }
-  .dtors          :
-  {
-    KEEP (*crtbegin*.o(.dtors))
-    KEEP (*(EXCLUDE_FILE (*crtend*.o ) .dtors))
-    KEEP (*(SORT(.dtors.*)))
-    KEEP (*(.dtors))
-  }
-  .jcr            : { KEEP (*(.jcr)) }
-  .data.rel.ro : { *(.data.rel.ro.local) *(.data.rel.ro*) }
-  .dynamic        : { *(.dynamic) }
-  .got            : { *(.got.plt) *(.got) }
-  .data           :
-  {
-    __data_start = . ;
-    *(.data .data.* .gnu.linkonce.d.*)
-    KEEP (*(.gnu.linkonce.d.*personality*))
-    SORT(CONSTRUCTORS)
-  }
-  .data1          : { *(.data1) }
-  _edata = .;
-  PROVIDE (edata = .);
-  __bss_start = .;
-  __bss_start__ = .;
-  .bss            :
-  {
-   *(.dynbss)
-   *(.bss .bss.* .gnu.linkonce.b.*)
-   *(COMMON)
-   /* Align here to ensure that the .bss section occupies space up to
-      _end.  Align after .bss to ensure correct alignment even if the
-      .bss section disappears because there are no input sections.  */
-   . = ALIGN(32 / 8);
-  }
-  . = ALIGN(32 / 8);
-  _end = .;
-  _bss_end__ = . ; __bss_end__ = . ; __end__ = . ;
-  PROVIDE (end = .);
-  /* Stabs debugging sections.  */
-  .stab          0 : { *(.stab) }
-  .stabstr       0 : { *(.stabstr) }
-  .stab.excl     0 : { *(.stab.excl) }
-  .stab.exclstr  0 : { *(.stab.exclstr) }
-  .stab.index    0 : { *(.stab.index) }
-  .stab.indexstr 0 : { *(.stab.indexstr) }
-  .comment       0 : { *(.comment) }
-  /* DWARF debug sections.
-     Symbols in the DWARF debugging sections are relative to the beginning
-     of the section so we begin them at 0.  */
-  /* DWARF 1 */
-  .debug          0 : { *(.debug) }
-  .line           0 : { *(.line) }
-  /* GNU DWARF 1 extensions */
-  .debug_srcinfo  0 : { *(.debug_srcinfo) }
-  .debug_sfnames  0 : { *(.debug_sfnames) }
-  /* DWARF 1.1 and DWARF 2 */
-  .debug_aranges  0 : { *(.debug_aranges) }
-  .debug_pubnames 0 : { *(.debug_pubnames) }
-  /* DWARF 2 */
-  .debug_info     0 : { *(.debug_info .gnu.linkonce.wi.*) }
-  .debug_abbrev   0 : { *(.debug_abbrev) }
-  .debug_line     0 : { *(.debug_line) }
-  .debug_frame    0 : { *(.debug_frame) }
-  .debug_str      0 : { *(.debug_str) }
-  .debug_loc      0 : { *(.debug_loc) }
-  .debug_macinfo  0 : { *(.debug_macinfo) }
-  /* SGI/MIPS DWARF 2 extensions */
-  .debug_weaknames 0 : { *(.debug_weaknames) }
-  .debug_funcnames 0 : { *(.debug_funcnames) }
-  .debug_typenames 0 : { *(.debug_typenames) }
-  .debug_varnames  0 : { *(.debug_varnames) }
-  /* Adding the word ABSOLUTE below, so that the _stack below won't float 
-     into a random section. If _stack is not absolutely with .stack section,
-     we saw that sometimes _stack got inserted into the .debug_frame section
-     because it's processed by the linker at that moment. As a result, _stack
-     symbol will get wrongly moved and gelf_update_symshndx() will return
-     invalid data. */
-    .stack         0x80000 :
-  {
-    _stack = ABSOLUTE(.);
-    *(.stack)
-  }
-  .note.gnu.arm.ident 0 : { KEEP (*(.note.gnu.arm.ident)) }
-  /DISCARD/ : { *(.note.GNU-stack) }
-}
diff --git a/core/armelflib.x b/core/armelflib.x
deleted file mode 100644
index 0150e02..0000000
--- a/core/armelflib.x
+++ /dev/null
@@ -1,164 +0,0 @@
-/* Default linker script, for normal executables */
-OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm",
-	      "elf32-littlearm")
-OUTPUT_ARCH(arm)
-ENTRY(_start)
-SEARCH_DIR("/usr/local/armdev/arm-elf/lib");
-/* Do we need any of these for elf?
-   __DYNAMIC = 0;    */
-SECTIONS
-{
-  /* Read-only sections, merged into text segment: */
-/*  PROVIDE (__executable_start = 0x8000); . = 0x8000; */
-. = 0 + SIZEOF_HEADERS; 
-  .interp         : { *(.interp) }
-  .init           :
-  {
-    KEEP (*(.init))
-  } =0
-  .plt            : { *(.plt) }
-  .text           :
-  {
-    *(.text .stub .text.* .gnu.linkonce.t.*)
-    KEEP (*(.text.*personality*))
-    /* .gnu.warning sections are handled specially by elf32.em.  */
-    *(.gnu.warning)
-    *(.glue_7t) *(.glue_7)
-  } =0
-  .fini           :
-  {
-    KEEP (*(.fini))
-  } =0
-  PROVIDE (__etext = .);
-  PROVIDE (_etext = .);
-  PROVIDE (etext = .);
-  .rodata         : { *(.rodata .rodata.* .gnu.linkonce.r.*) }
-  .rodata1        : { *(.rodata1) }
-  .ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) }
-   __exidx_start = .;
-  .ARM.exidx   : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) }
-   __exidx_end = .;
-  .eh_frame_hdr : { *(.eh_frame_hdr) }
-  .eh_frame       : ONLY_IF_RO { KEEP (*(.eh_frame)) }
-  .gcc_except_table   : ONLY_IF_RO { KEEP (*(.gcc_except_table)) *(.gcc_except_table.*) }
-  /* Adjust the address for the data segment.  We want to adjust up to
-     the same address within the page on the next page up.  */
-  . = ALIGN(256) + (. & (256 - 1));
-  /* Exception handling  */
-  .eh_frame       : ONLY_IF_RW { KEEP (*(.eh_frame)) }
-  .gcc_except_table   : ONLY_IF_RW { KEEP (*(.gcc_except_table)) *(.gcc_except_table.*) }
-  /* Thread Local Storage sections  */
-  .tdata	  : { *(.tdata .tdata.* .gnu.linkonce.td.*) }
-  .tbss		  : { *(.tbss .tbss.* .gnu.linkonce.tb.*) *(.tcommon) }
-  /* Ensure the __preinit_array_start label is properly aligned.  We
-     could instead move the label definition inside the section, but
-     the linker would then create the section even if it turns out to
-     be empty, which isn't pretty.  */
-  . = ALIGN(32 / 8);
-  PROVIDE (__preinit_array_start = .);
-  .preinit_array     : { KEEP (*(.preinit_array)) }
-  PROVIDE (__preinit_array_end = .);
-  PROVIDE (__init_array_start = .);
-  .init_array     : { KEEP (*(.init_array)) }
-  PROVIDE (__init_array_end = .);
-  PROVIDE (__fini_array_start = .);
-  .fini_array     : { KEEP (*(.fini_array)) }
-  PROVIDE (__fini_array_end = .);
-  .ctors          :
-  {
-    /* gcc uses crtbegin.o to find the start of
-       the constructors, so we make sure it is
-       first.  Because this is a wildcard, it
-       doesn't matter if the user does not
-       actually link against crtbegin.o; the
-       linker won't look for a file to match a
-       wildcard.  The wildcard also means that it
-       doesn't matter which directory crtbegin.o
-       is in.  */
-    KEEP (*crtbegin*.o(.ctors))
-    /* We don't want to include the .ctor section from
-       from the crtend.o file until after the sorted ctors.
-       The .ctor section from the crtend file contains the
-       end of ctors marker and it must be last */
-    KEEP (*(EXCLUDE_FILE (*crtend*.o ) .ctors))
-    KEEP (*(SORT(.ctors.*)))
-    KEEP (*(.ctors))
-  }
-  .dtors          :
-  {
-    KEEP (*crtbegin*.o(.dtors))
-    KEEP (*(EXCLUDE_FILE (*crtend*.o ) .dtors))
-    KEEP (*(SORT(.dtors.*)))
-    KEEP (*(.dtors))
-  }
-  .jcr            : { KEEP (*(.jcr)) }
-  .data.rel.ro : { *(.data.rel.ro.local) *(.data.rel.ro*) }
-  .got            : { *(.got.plt) *(.got) }
-  .data           :
-  {
-    __data_start = . ;
-    *(.data .data.* .gnu.linkonce.d.*)
-    KEEP (*(.gnu.linkonce.d.*personality*))
-    SORT(CONSTRUCTORS)
-  }
-  .data1          : { *(.data1) }
-  _edata = .;
-  PROVIDE (edata = .);
-  .dynamic        : { *(.dynamic) }
-  .hash           : { *(.hash) }
-  .dynsym         : { *(.dynsym) }
-  .dynstr         : { *(.dynstr) }
-/*  .shstrtab	  : { *(.shstrtab) } */
-  .rel.plt        : { *(.rel.plt) }
-  .rel.dyn	  : { *(.rel.*) }
-  __bss_start = .;
-  __bss_start__ = .;
-  .bss            :
-  {
-   *(.dynbss)
-   *(.bss .bss.* .gnu.linkonce.b.*)
-   *(COMMON)
-   /* Align here to ensure that the .bss section occupies space up to
-      _end.  Align after .bss to ensure correct alignment even if the
-      .bss section disappears because there are no input sections.  */
-   . = ALIGN(32 / 8);
-  }
-  . = ALIGN(32 / 8);
-  _end = .;
-  _bss_end__ = . ; __bss_end__ = . ; __end__ = . ;
-  PROVIDE (end = .);
-  /* Stabs debugging sections.  */
-  .stab          0 : { *(.stab) }
-  .stabstr       0 : { *(.stabstr) }
-  .stab.excl     0 : { *(.stab.excl) }
-  .stab.exclstr  0 : { *(.stab.exclstr) }
-  .stab.index    0 : { *(.stab.index) }
-  .stab.indexstr 0 : { *(.stab.indexstr) }
-  /* DWARF debug sections.
-     Symbols in the DWARF debugging sections are relative to the beginning
-     of the section so we begin them at 0.  */
-  /* DWARF 1 */
-  .debug          0 : { *(.debug) }
-  .line           0 : { *(.line) }
-  /* GNU DWARF 1 extensions */
-  .debug_srcinfo  0 : { *(.debug_srcinfo) }
-  .debug_sfnames  0 : { *(.debug_sfnames) }
-  /* DWARF 1.1 and DWARF 2 */
-  .debug_aranges  0 : { *(.debug_aranges) }
-  .debug_pubnames 0 : { *(.debug_pubnames) }
-  /* DWARF 2 */
-  .debug_info     0 : { *(.debug_info .gnu.linkonce.wi.*) }
-  .debug_abbrev   0 : { *(.debug_abbrev) }
-  .debug_line     0 : { *(.debug_line) }
-  .debug_frame    0 : { *(.debug_frame) }
-  .debug_str      0 : { *(.debug_str) }
-  .debug_loc      0 : { *(.debug_loc) }
-  .debug_macinfo  0 : { *(.debug_macinfo) }
-  /* SGI/MIPS DWARF 2 extensions */
-  .debug_weaknames 0 : { *(.debug_weaknames) }
-  .debug_funcnames 0 : { *(.debug_funcnames) }
-  .debug_typenames 0 : { *(.debug_typenames) }
-  .debug_varnames  0 : { *(.debug_varnames) }
-  .note.gnu.arm.ident 0 : { KEEP (*(.note.gnu.arm.ident)) }
-  /DISCARD/ : { *(.note.GNU-stack) *(.comment*) *(.stack*) *(.shstrtab) }
-}
diff --git a/core/base_rules.mk b/core/base_rules.mk
index 242b53d..51fb398 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -55,6 +55,7 @@
 #space := $(empty) $(empty)
 #$(shell echo $(lastword $(filter-out config/% out/%,$(MAKEFILE_LIST))),$(LOCAL_MODULE),$(strip $(LOCAL_MODULE_CLASS)),$(subst $(space),$(comma),$(sort $(LOCAL_MODULE_TAGS))) >> tag-list.csv)
 
+LOCAL_UNINSTALLABLE_MODULE := $(strip $(LOCAL_UNINSTALLABLE_MODULE))
 LOCAL_MODULE_TAGS := $(sort $(LOCAL_MODULE_TAGS))
 ifeq (,$(LOCAL_MODULE_TAGS))
 ifeq (true,$(LOCAL_UNINSTALLABLE_MODULE))
@@ -110,8 +111,10 @@
 # find files like MODULE_LICENSE_GPL_AND_AFL but exclude files like
 # MODULE_LICENSE_LGPL.
 #
-ifneq ($(call find-parent-file,$(LOCAL_PATH),MODULE_LICENSE*_GPL* MODULE_LICENSE*_MPL*),)
+gpl_license_file := $(call find-parent-file,$(LOCAL_PATH),MODULE_LICENSE*_GPL* MODULE_LICENSE*_MPL*)
+ifneq ($(gpl_license_file),)
   LOCAL_MODULE_TAGS += gnu
+  ALL_GPL_MODULE_LICENSE_FILES := $(sort $(ALL_GPL_MODULE_LICENSE_FILES) $(gpl_license_file))
 endif
 
 #
@@ -122,18 +125,6 @@
   LOCAL_MODULE_TAGS := $(sort $(LOCAL_MODULE_TAGS) user)
 endif
 
-ifdef LOCAL_IS_HOST_MODULE
-  partition_tag :=
-else
-ifeq (true,$(LOCAL_PROPRIETARY_MODULE))
-  partition_tag := _VENDOR
-else
-  # The definition of should-install-to-system will be different depending
-  # on which goal (e.g., sdk or just droid) is being built.
-  partition_tag := $(if $(call should-install-to-system,$(LOCAL_MODULE_TAGS)),,_DATA)
-endif
-endif
-
 LOCAL_MODULE_CLASS := $(strip $(LOCAL_MODULE_CLASS))
 ifneq ($(words $(LOCAL_MODULE_CLASS)),1)
   $(error $(LOCAL_PATH): LOCAL_MODULE_CLASS must contain exactly one word, not "$(LOCAL_MODULE_CLASS)")
@@ -147,6 +138,19 @@
   endif
 endif
 
+ifneq (true,$(LOCAL_UNINSTALLABLE_MODULE))
+ifdef LOCAL_IS_HOST_MODULE
+  partition_tag :=
+else
+ifeq (true,$(LOCAL_PROPRIETARY_MODULE))
+  partition_tag := _VENDOR
+else
+  # The definition of should-install-to-system will be different depending
+  # on which goal (e.g., sdk or just droid) is being built.
+  partition_tag := $(if $(call should-install-to-system,$(LOCAL_MODULE_TAGS)),,_DATA)
+endif
+endif
+
 LOCAL_MODULE_PATH := $(strip $(LOCAL_MODULE_PATH))
 ifeq ($(LOCAL_MODULE_PATH),)
   LOCAL_MODULE_PATH := $($(my_prefix)OUT$(partition_tag)_$(LOCAL_MODULE_CLASS))
@@ -154,6 +158,7 @@
     $(error $(LOCAL_PATH): unhandled LOCAL_MODULE_CLASS "$(LOCAL_MODULE_CLASS)")
   endif
 endif
+endif # not LOCAL_UNINSTALLABLE_MODULE
 
 ifneq ($(strip $(LOCAL_BUILT_MODULE)$(LOCAL_INSTALLED_MODULE)),)
   $(error $(LOCAL_PATH): LOCAL_BUILT_MODULE and LOCAL_INSTALLED_MODULE must not be defined by component makefiles)
@@ -198,7 +203,6 @@
 LOCAL_BUILT_MODULE := $(built_module_path)/$(LOCAL_BUILT_MODULE_STEM)
 built_module_path :=
 
-LOCAL_UNINSTALLABLE_MODULE := $(strip $(LOCAL_UNINSTALLABLE_MODULE))
 ifneq (true,$(LOCAL_UNINSTALLABLE_MODULE))
   LOCAL_INSTALLED_MODULE := $(LOCAL_MODULE_PATH)/$(LOCAL_INSTALLED_MODULE_STEM)
 endif
@@ -224,7 +228,8 @@
 aidl_preprocess_import :=
 LOCAL_SDK_VERSION:=$(strip $(LOCAL_SDK_VERSION))
 ifdef LOCAL_SDK_VERSION
-ifeq ($(LOCAL_SDK_VERSION),current)
+ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),current)
+  # LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS
   aidl_preprocess_import := $(TARGET_OUT_COMMON_INTERMEDIATES)/framework.aidl
 else
   aidl_preprocess_import := $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_VERSION)/framework.aidl
@@ -381,7 +386,7 @@
 
 ## PRIVATE java vars ######################################
 
-ifneq ($(strip $(all_java_sources)$(all_res_assets)),)
+ifneq ($(strip $(all_java_sources)$(all_res_assets))$(LOCAL_STATIC_JAVA_LIBRARIES),)
 
 full_static_java_libs := \
     $(foreach lib,$(LOCAL_STATIC_JAVA_LIBRARIES), \
@@ -397,7 +402,8 @@
 ifeq ($(LOCAL_SDK_VERSION),)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,core)
 else
-ifeq ($(LOCAL_SDK_VERSION),current)
+ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),current)
+# LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS.
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,android_stubs_current)
 else
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,sdk_v$(LOCAL_SDK_VERSION))
@@ -587,6 +593,10 @@
     $(ALL_MODULES.$(LOCAL_MODULE).EVENT_LOG_TAGS) $(event_log_tags)
 ALL_MODULES.$(LOCAL_MODULE).INTERMEDIATE_SOURCE_DIR := \
     $(ALL_MODULES.$(LOCAL_MODULE).INTERMEDIATE_SOURCE_DIR) $(LOCAL_INTERMEDIATE_SOURCE_DIR)
+ifdef LOCAL_MODULE_OWNER
+ALL_MODULES.$(LOCAL_MODULE).OWNER := \
+    $(strip $(ALL_MODULES.$(LOCAL_MODULE).OWNER) $(LOCAL_MODULE_OWNER))
+endif
 
 INSTALLABLE_FILES.$(LOCAL_INSTALLED_MODULE).MODULE := $(LOCAL_MODULE)
 
diff --git a/core/binary.mk b/core/binary.mk
index e488200..04ac90b 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -124,6 +124,21 @@
 include $(BUILD_SYSTEM)/base_rules.mk
 #######################################
 
+ifeq ($(strip $(LOCAL_ADDRESS_SANITIZER)),true)
+  LOCAL_CLANG := true
+  LOCAL_CFLAGS += $(ADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS)
+  LOCAL_LDFLAGS += $(ADDRESS_SANITIZER_CONFIG_EXTRA_LDFLAGS)
+  LOCAL_SHARED_LIBRARIES += $(ADDRESS_SANITIZER_CONFIG_EXTRA_SHARED_LIBRARIES)
+  LOCAL_STATIC_LIBRARIES += $(ADDRESS_SANITIZER_CONFIG_EXTRA_STATIC_LIBRARIES)
+endif
+
+my_compiler_dependencies :=
+ifeq ($(strip $(LOCAL_CLANG)),true)
+  LOCAL_CFLAGS += $(CLANG_CONFIG_EXTRA_CFLAGS)
+  LOCAL_LDFLAGS += $(CLANG_CONFIG_EXTRA_LDFLAGS)
+  my_compiler_dependencies := $(CLANG) $(CLANG_CXX)
+endif
+
 ####################################################
 ## Add FDO flags if FDO is turned on and supported
 ####################################################
@@ -142,20 +157,29 @@
 ###########################################################
 ## Define PRIVATE_ variables from global vars
 ###########################################################
+ifeq ($(strip $(LOCAL_CLANG)),true)
+my_target_global_cflags := $(TARGET_GLOBAL_CLANG_FLAGS)
+else
+my_target_global_cflags := $(TARGET_GLOBAL_CFLAGS)
+endif
+
 ifdef LOCAL_NDK_VERSION
 my_target_project_includes :=
-my_target_c_inclues := $(my_ndk_stl_include_path) $(my_ndk_version_root)/usr/include
+my_target_c_includes := $(my_ndk_stl_include_path) $(my_ndk_version_root)/usr/include
 # TODO: more reliable way to remove platform stuff.
-my_target_global_cflags := $(filter-out -include -I system/%, $(TARGET_GLOBAL_CFLAGS))
+my_target_global_cflags := $(filter-out -include -I system/%, $(my_target_global_cflags))
 my_target_global_cppflags := $(filter-out -include -I system/%, $(TARGET_GLOBAL_CPPFLAGS))
 else
 my_target_project_includes := $(TARGET_PROJECT_INCLUDES)
-my_target_c_inclues := $(TARGET_C_INCLUDES)
-my_target_global_cflags := $(TARGET_GLOBAL_CFLAGS)
+my_target_c_includes := $(TARGET_C_INCLUDES)
+my_target_global_cflags := $(my_target_global_cflags)
 my_target_global_cppflags := $(TARGET_GLOBAL_CPPFLAGS)
+ifeq ($(strip $(LOCAL_CLANG)),true)
+  my_target_c_includes += $(CLANG_CONFIG_EXTRA_TARGET_C_INCLUDES)
+endif
 endif
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_PROJECT_INCLUDES := $(my_target_project_includes)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_C_INCLUDES := $(my_target_c_inclues)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_C_INCLUDES := $(my_target_c_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CFLAGS := $(my_target_global_cflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_GLOBAL_CPPFLAGS := $(my_target_global_cppflags)
 
@@ -163,15 +187,23 @@
 ## Define PRIVATE_ variables used by multiple module types
 ###########################################################
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_NO_DEFAULT_COMPILER_FLAGS := \
-	$(strip $(LOCAL_NO_DEFAULT_COMPILER_FLAGS))
+    $(strip $(LOCAL_NO_DEFAULT_COMPILER_FLAGS))
 
 ifeq ($(strip $(LOCAL_CC)),)
-  LOCAL_CC := $($(my_prefix)CC)
+  ifeq ($(strip $(LOCAL_CLANG)),true)
+    LOCAL_CC := $(CLANG)
+  else
+    LOCAL_CC := $($(my_prefix)CC)
+  endif
 endif
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CC := $(LOCAL_CC)
 
 ifeq ($(strip $(LOCAL_CXX)),)
-  LOCAL_CXX := $($(my_prefix)CXX)
+  ifeq ($(strip $(LOCAL_CLANG)),true)
+    LOCAL_CXX := $(CLANG_CXX)
+  else
+    LOCAL_CXX := $($(my_prefix)CXX)
+  endif
 endif
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CXX := $(LOCAL_CXX)
 
@@ -207,8 +239,14 @@
 # Read the values from something like TARGET_arm_CFLAGS or
 # TARGET_thumb_CFLAGS.  HOST_(arm|thumb)_CFLAGS values aren't
 # actually used (although they are usually empty).
+ifeq ($(strip $(LOCAL_CLANG)),true)
+arm_objects_cflags := $($(my_prefix)$(arm_objects_mode)_CLANG_CFLAGS)
+normal_objects_cflags := $($(my_prefix)$(normal_objects_mode)_CLANG_CFLAGS)
+else
 arm_objects_cflags := $($(my_prefix)$(arm_objects_mode)_CFLAGS)
 normal_objects_cflags := $($(my_prefix)$(normal_objects_mode)_CFLAGS)
+endif
+
 else
 arm_objects_mode :=
 normal_objects_mode :=
@@ -247,7 +285,7 @@
 proto_sources_fullpath := $(addprefix $(LOCAL_PATH)/, $(proto_sources))
 proto_generated_cc_sources_dir := $(intermediates)/proto
 proto_generated_cc_sources := $(addprefix $(proto_generated_cc_sources_dir)/, \
-	$(patsubst %.proto,%.pb.cc,$(proto_sources_fullpath)))
+    $(patsubst %.proto,%.pb.cc,$(proto_sources_fullpath)))
 proto_generated_objects := $(patsubst %.cc,%.o, $(proto_generated_cc_sources))
 
 $(proto_generated_cc_sources): PRIVATE_PROTO_INCLUDES := $(TOP)
@@ -261,7 +299,7 @@
 
 $(proto_generated_cc_sources): PRIVATE_ARM_MODE := $(normal_objects_mode)
 $(proto_generated_cc_sources): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
-$(proto_generated_objects): $(proto_generated_cc_sources_dir)/%.o: $(proto_generated_cc_sources_dir)/%.cc
+$(proto_generated_objects): $(proto_generated_cc_sources_dir)/%.o: $(proto_generated_cc_sources_dir)/%.cc $(proto_generated_headers)
 	$(transform-$(PRIVATE_HOST)cpp-to-o)
 -include $(proto_generated_objects:%.o=%.P)
 
@@ -281,14 +319,14 @@
 
 yacc_sources := $(filter %.y,$(LOCAL_SRC_FILES))
 yacc_cpps := $(addprefix \
-	$(intermediates)/,$(yacc_sources:.y=$(LOCAL_CPP_EXTENSION)))
+    $(intermediates)/,$(yacc_sources:.y=$(LOCAL_CPP_EXTENSION)))
 yacc_headers := $(yacc_cpps:$(LOCAL_CPP_EXTENSION)=.h)
 yacc_objects := $(yacc_cpps:$(LOCAL_CPP_EXTENSION)=.o)
 
 ifneq ($(strip $(yacc_cpps)),)
 $(yacc_cpps): $(intermediates)/%$(LOCAL_CPP_EXTENSION): \
-		$(TOPDIR)$(LOCAL_PATH)/%.y \
-		$(lex_cpps) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+    $(TOPDIR)$(LOCAL_PATH)/%.y \
+    $(lex_cpps) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(call transform-y-to-cpp,$(PRIVATE_CPP_EXTENSION))
 $(yacc_headers): $(intermediates)/%.h: $(intermediates)/%$(LOCAL_CPP_EXTENSION)
 
@@ -304,20 +342,20 @@
 
 lex_sources := $(filter %.l,$(LOCAL_SRC_FILES))
 lex_cpps := $(addprefix \
-	$(intermediates)/,$(lex_sources:.l=$(LOCAL_CPP_EXTENSION)))
+    $(intermediates)/,$(lex_sources:.l=$(LOCAL_CPP_EXTENSION)))
 lex_objects := $(lex_cpps:$(LOCAL_CPP_EXTENSION)=.o)
 
 ifneq ($(strip $(lex_cpps)),)
 $(lex_cpps): $(intermediates)/%$(LOCAL_CPP_EXTENSION): \
-		$(TOPDIR)$(LOCAL_PATH)/%.l
+    $(TOPDIR)$(LOCAL_PATH)/%.l
 	$(transform-l-to-cpp)
 
 $(lex_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
 $(lex_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
 $(lex_objects): $(intermediates)/%.o: \
-		$(intermediates)/%$(LOCAL_CPP_EXTENSION) \
-		$(LOCAL_ADDITIONAL_DEPENDENCIES) \
-		$(yacc_headers)
+    $(intermediates)/%$(LOCAL_CPP_EXTENSION) \
+    $(LOCAL_ADDITIONAL_DEPENDENCIES) \
+    $(yacc_headers)
 	$(transform-$(PRIVATE_HOST)cpp-to-o)
 endif
 
@@ -342,8 +380,9 @@
 
 ifneq ($(strip $(cpp_objects)),)
 $(cpp_objects): $(intermediates)/%.o: \
-		$(TOPDIR)$(LOCAL_PATH)/%$(LOCAL_CPP_EXTENSION) \
-		$(yacc_cpps) $(proto_generated_headers) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+    $(TOPDIR)$(LOCAL_PATH)/%$(LOCAL_CPP_EXTENSION) \
+    $(yacc_cpps) $(proto_generated_headers) $(my_compiler_dependencies) \
+    $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)cpp-to-o)
 -include $(cpp_objects:%.o=%.P)
 endif
@@ -360,7 +399,10 @@
 # TODO: support compiling certain generated files as arm.
 $(gen_cpp_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
 $(gen_cpp_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
-$(gen_cpp_objects): $(intermediates)/%.o: $(intermediates)/%$(LOCAL_CPP_EXTENSION) $(yacc_cpps) $(proto_generated_headers) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(gen_cpp_objects): $(intermediates)/%.o: \
+    $(intermediates)/%$(LOCAL_CPP_EXTENSION) $(yacc_cpps) \
+    $(proto_generated_headers)  $(my_compiler_dependencies) \
+    $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)cpp-to-o)
 -include $(gen_cpp_objects:%.o=%.P)
 endif
@@ -373,7 +415,8 @@
 gen_S_objects := $(gen_S_sources:%.S=%.o)
 
 ifneq ($(strip $(gen_S_sources)),)
-$(gen_S_objects): $(intermediates)/%.o: $(intermediates)/%.S $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(gen_S_objects): $(intermediates)/%.o: $(intermediates)/%.S \
+    $(my_compiler_dependencies) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)s-to-o)
 -include $(gen_S_objects:%.o=%.P)
 endif
@@ -382,7 +425,8 @@
 gen_s_objects := $(gen_s_sources:%.s=%.o)
 
 ifneq ($(strip $(gen_s_objects)),)
-$(gen_s_objects): $(intermediates)/%.o: $(intermediates)/%.s $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(gen_s_objects): $(intermediates)/%.o: $(intermediates)/%.s \
+    $(my_compiler_dependencies) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)s-to-o-no-deps)
 -include $(gen_s_objects:%.o=%.P)
 endif
@@ -407,7 +451,8 @@
 c_objects        := $(c_arm_objects) $(c_normal_objects)
 
 ifneq ($(strip $(c_objects)),)
-$(c_objects): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.c $(yacc_cpps) $(proto_generated_headers) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(c_objects): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.c $(yacc_cpps) $(proto_generated_headers) \
+    $(my_compiler_dependencies) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)c-to-o)
 -include $(c_objects:%.o=%.P)
 endif
@@ -424,7 +469,8 @@
 # TODO: support compiling certain generated files as arm.
 $(gen_c_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
 $(gen_c_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
-$(gen_c_objects): $(intermediates)/%.o: $(intermediates)/%.c $(yacc_cpps) $(proto_generated_headers) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(gen_c_objects): $(intermediates)/%.o: $(intermediates)/%.c $(yacc_cpps) $(proto_generated_headers) \
+    $(my_compiler_dependencies) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)c-to-o)
 -include $(gen_c_objects:%.o=%.P)
 endif
@@ -437,7 +483,8 @@
 objc_objects := $(addprefix $(intermediates)/,$(objc_sources:.m=.o))
 
 ifneq ($(strip $(objc_objects)),)
-$(objc_objects): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.m $(yacc_cpps) $(proto_generated_headers) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(objc_objects): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.m $(yacc_cpps) $(proto_generated_headers) \
+    $(my_compiler_dependencies) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)m-to-o)
 -include $(objc_objects:%.o=%.P)
 endif
@@ -450,7 +497,8 @@
 asm_objects_S := $(addprefix $(intermediates)/,$(asm_sources_S:.S=.o))
 
 ifneq ($(strip $(asm_objects_S)),)
-$(asm_objects_S): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.S $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(asm_objects_S): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.S \
+    $(my_compiler_dependencies) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)s-to-o)
 -include $(asm_objects_S:%.o=%.P)
 endif
@@ -459,7 +507,8 @@
 asm_objects_s := $(addprefix $(intermediates)/,$(asm_sources_s:.s=.o))
 
 ifneq ($(strip $(asm_objects_s)),)
-$(asm_objects_s): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.s $(LOCAL_ADDITIONAL_DEPENDENCIES)
+$(asm_objects_s): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.s \
+    $(my_compiler_dependencies) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-$(PRIVATE_HOST)s-to-o-no-deps)
 -include $(asm_objects_s:%.o=%.P)
 endif
@@ -467,6 +516,26 @@
 asm_objects := $(asm_objects_S) $(asm_objects_s)
 
 
+####################################################
+## Import includes
+####################################################
+import_includes := $(intermediates)/import_includes
+import_includes_deps := $(strip \
+    $(foreach l, $(installed_shared_library_module_names), \
+      $(call intermediates-dir-for,SHARED_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE))/export_includes) \
+    $(foreach l, $(LOCAL_STATIC_LIBRARIES) $(LOCAL_WHOLE_STATIC_LIBRARIES), \
+      $(call intermediates-dir-for,STATIC_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE))/export_includes))
+$(import_includes) : $(import_includes_deps)
+	@echo Import includes file: $@
+	$(hide) mkdir -p $(dir $@) && rm -f $@
+ifdef import_includes_deps
+	$(hide) for f in $^; do \
+	  cat $$f >> $@; \
+	done
+else
+	$(hide) touch $@
+endif
+
 ###########################################################
 ## Common object handling.
 ###########################################################
@@ -474,25 +543,25 @@
 # some rules depend on asm_objects being first.  If your code depends on
 # being first, it's reasonable to require it to be assembly
 all_objects := \
-	$(asm_objects) \
-	$(cpp_objects) \
-	$(gen_cpp_objects) \
-	$(gen_asm_objects) \
-	$(c_objects) \
-	$(gen_c_objects) \
-	$(objc_objects) \
-	$(yacc_objects) \
-	$(lex_objects) \
-	$(proto_generated_objects) \
-	$(addprefix $(TOPDIR)$(LOCAL_PATH)/,$(LOCAL_PREBUILT_OBJ_FILES))
+    $(asm_objects) \
+    $(cpp_objects) \
+    $(gen_cpp_objects) \
+    $(gen_asm_objects) \
+    $(c_objects) \
+    $(gen_c_objects) \
+    $(objc_objects) \
+    $(yacc_objects) \
+    $(lex_objects) \
+    $(proto_generated_objects) \
+    $(addprefix $(TOPDIR)$(LOCAL_PATH)/,$(LOCAL_PREBUILT_OBJ_FILES))
 
-LOCAL_C_INCLUDES += $(TOPDIR)$(LOCAL_PATH) $(intermediates) $(base_intermediates)
+LOCAL_C_INCLUDES += $(TOPDIR)$(LOCAL_PATH) $(intermediates)
 
 ifndef LOCAL_NDK_VERSION
   LOCAL_C_INCLUDES += $(JNI_H_INCLUDE)
 endif
 
-$(all_objects) : | $(LOCAL_GENERATED_SOURCES)
+$(all_objects) : | $(LOCAL_GENERATED_SOURCES) $(import_includes)
 ALL_C_CPP_ETC_OBJECTS += $(all_objects)
 
 ###########################################################
@@ -571,7 +640,7 @@
 # We don't care about installed static libraries, since the
 # libraries have already been linked into the module at that point.
 # We do, however, care about the NOTICE files for any static
-# libraries that we use. (see notice_files.make)
+# libraries that we use. (see notice_files.mk)
 
 installed_static_library_notice_file_targets := \
     $(foreach lib,$(LOCAL_STATIC_LIBRARIES) $(LOCAL_WHOLE_STATIC_LIBRARIES), \
@@ -592,6 +661,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RTTI_FLAG := $(LOCAL_RTTI_FLAG)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_DEBUG_CFLAGS := $(debug_cflags)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_C_INCLUDES := $(LOCAL_C_INCLUDES)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_IMPORT_INCLUDES := $(import_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LDFLAGS := $(LOCAL_LDFLAGS)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_LDLIBS := $(LOCAL_LDLIBS)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_NO_CRT := $(LOCAL_NO_CRT)
@@ -616,3 +686,22 @@
 # are linked into this module.  This will force them to be installed
 # when this module is.
 $(LOCAL_INSTALLED_MODULE): | $(installed_static_library_notice_file_targets)
+
+###########################################################
+# Export includes
+###########################################################
+export_includes := $(intermediates)/export_includes
+$(export_includes): PRIVATE_EXPORT_C_INCLUDE_DIRS := $(LOCAL_EXPORT_C_INCLUDE_DIRS)
+$(export_includes) : $(LOCAL_MODULE_MAKEFILE)
+	@echo Export includes file: $< -- $@
+	$(hide) mkdir -p $(dir $@) && rm -f $@
+ifdef LOCAL_EXPORT_C_INCLUDE_DIRS
+	$(hide) for d in $(PRIVATE_EXPORT_C_INCLUDE_DIRS); do \
+	        echo "-I $$d" >> $@; \
+	        done
+else
+	$(hide) touch $@
+endif
+
+# Make sure export_includes gets generated when you are running mm/mmm
+$(LOCAL_BUILT_MODULE) : | $(export_includes)
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index 66e6232..f3929ad 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -44,6 +44,7 @@
 LOCAL_CPPFLAGS:=
 LOCAL_RTTI_FLAG:=
 LOCAL_C_INCLUDES:=
+LOCAL_EXPORT_C_INCLUDE_DIRS:=
 LOCAL_LDFLAGS:=
 LOCAL_LDLIBS:=
 LOCAL_AAPT_FLAGS:=
@@ -103,10 +104,12 @@
 LOCAL_PROGUARD_FLAG_FILES:=
 LOCAL_EMMA_COVERAGE_FILTER:=
 LOCAL_WARNINGS_ENABLE:=
+LOCAL_FULL_MANIFEST_FILE:=
 LOCAL_MANIFEST_FILE:=
 LOCAL_RENDERSCRIPT_INCLUDES:=
 LOCAL_RENDERSCRIPT_INCLUDES_OVERRIDE:=
 LOCAL_RENDERSCRIPT_CC:=
+LOCAL_RENDERSCRIPT_FLAGS:=
 LOCAL_RENDERSCRIPT_TARGET_API:=
 LOCAL_BUILD_HOST_DEX:=
 LOCAL_DEX_PREOPT:= # '',true,false,nostripping
@@ -114,7 +117,14 @@
 LOCAL_PROTOC_FLAGS:=
 LOCAL_NO_CRT:=
 LOCAL_PROPRIETARY_MODULE:=
+LOCAL_MODULE_OWNER:=
 LOCAL_CTS_TEST_PACKAGE:=
+LOCAL_CTS_TEST_RUNNER:=
+LOCAL_CLANG:=
+LOCAL_ADDRESS_SANITIZER:=
+# Whether to keep the generated R/Manifest classes when building static Java library
+# with Android resource. false(default), or true
+LOCAL_KEEP_R_CLASS_IN_STATIC_JAVA_LIBRARY:=
 
 # 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 5ab2c0d..2ad3dd9 100644
--- a/core/combo/HOST_darwin-x86.mk
+++ b/core/combo/HOST_darwin-x86.mk
@@ -17,11 +17,17 @@
 # Configuration for Darwin (Mac OS X) on x86.
 # Included by combo/select.mk
 
-# We build everything in 32-bit, because some host tools are
-# 32-bit-only anyway (emulator, acc), and because it gives us
+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
 
 mac_sdk_version := 10.6
 mac_sdk_root := /Developer/SDKs/MacOSX$(mac_sdk_version).sdk
@@ -74,25 +80,46 @@
 
 HOST_CUSTOM_LD_COMMAND := true
 
+# Workaround for lack of "-Wl,--whole-archive" in MacOS's linker.
+define _darwin-extract-and-include-single-whole-static-lib
+@echo "preparing StaticLib: $(PRIVATE_MODULE) [including $(1)]"
+$(hide) ldir=$(PRIVATE_INTERMEDIATES_DIR)/WHOLE/$(basename $(notdir $(1)))_objs;\
+    mkdir -p $$ldir; \
+    for f in `$(HOST_AR) t $(1)`; do \
+        $(HOST_AR) p $(1) $$f > $$ldir/$$f; \
+    done ;
+
+endef
+
+define darwin-extract-and-include-whole-static-libs
+$(if $(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES), $(hide) rm -rf $(PRIVATE_INTERMEDIATES_DIR)/WHOLE)
+$(foreach lib,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES), \
+    $(call _darwin-extract-and-include-single-whole-static-lib, $(lib)))
+endef
+
 define transform-host-o-to-shared-lib-inner
+$(call darwin-extract-and-include-whole-static-libs)
 $(hide) $(PRIVATE_CXX) \
         -dynamiclib -single_module -read_only_relocs suppress \
         $(HOST_GLOBAL_LD_DIRS) \
         $(HOST_GLOBAL_LDFLAGS) \
         $(PRIVATE_ALL_OBJECTS) \
+        $(if $(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES), `find $(PRIVATE_INTERMEDIATES_DIR)/WHOLE -name '*.o' 2>/dev/null`) \
         $(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-        $(call normalize-host-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
         $(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--start-group) \
         $(call normalize-host-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
         $(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
         $(PRIVATE_LDLIBS) \
         -o $@ \
+        -install_name @rpath/$(notdir $@) \
+        -Wl,-rpath,@loader_path/../lib \
         $(PRIVATE_LDFLAGS) \
         $(HOST_LIBGCC)
 endef
 
 define transform-host-o-to-executable-inner
 $(hide) $(PRIVATE_CXX) \
+        -Wl,-rpath,@loader_path/../lib \
         -o $@ \
         $(PRE_LION_DYNAMIC_LINKER_OPTIONS) -headerpad_max_install_names \
         $(HOST_GLOBAL_LD_DIRS) \
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index 1014f4b..a4da5ce 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -32,7 +32,6 @@
 # which is loaded by the 64-bit JVM through JNI), will have to use
 # LOCAL_CC and LOCAL_CXX to override this.
 #
-ifeq ($(TARGET_PRODUCT),sdk)
 HOST_SDK_TOOLCHAIN_PREFIX := prebuilts/tools/gcc-sdk
 # Don't do anything if the toolchain is not there
 ifneq (,$(strip $(wildcard $(HOST_SDK_TOOLCHAIN_PREFIX)/gcc)))
@@ -40,13 +39,18 @@
 HOST_CXX := $(HOST_SDK_TOOLCHAIN_PREFIX)/g++
 HOST_AR  := $(HOST_SDK_TOOLCHAIN_PREFIX)/ar
 endif # $(HOST_SDK_TOOLCHAIN_PREFIX)/gcc exists
-endif # TARGET_PRODUCT == sdk
 
-# We build everything in 32-bit, because some host tools are
-# 32-bit-only anyway (emulator, acc), and because it gives us
+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
 
 HOST_GLOBAL_CFLAGS += -fPIC
 HOST_GLOBAL_CFLAGS += \
diff --git a/core/combo/HOST_windows-x86.mk b/core/combo/HOST_windows-x86.mk
index 9870998..fe4bd66 100644
--- a/core/combo/HOST_windows-x86.mk
+++ b/core/combo/HOST_windows-x86.mk
@@ -26,13 +26,19 @@
 ifneq ($(findstring Linux,$(UNAME)),)
 ifneq ($(strip $(USE_MINGW)),)
 HOST_ACP_UNAVAILABLE := true
-TOOLS_PREFIX := /usr/bin/i586-mingw32msvc-
 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
+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
-endif
+endif # BUILD_HOST_64bit
+endif # USE_MINGW
+endif # Linux
 
 HOST_CC := $(TOOLS_PREFIX)gcc$(TOOLS_EXE_SUFFIX)
 HOST_CXX := $(TOOLS_PREFIX)g++$(TOOLS_EXE_SUFFIX)
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index 4971a0c..14c3d28 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -43,8 +43,8 @@
 
 # You can set TARGET_TOOLS_PREFIX to get gcc from somewhere else
 ifeq ($(strip $(TARGET_TOOLS_PREFIX)),)
-TARGET_TOOLS_PREFIX := \
-	prebuilts/gcc/$(HOST_PREBUILT_TAG)/arm/arm-linux-androideabi-4.6/bin/arm-linux-androideabi-
+TARGET_TOOLCHAIN_ROOT := prebuilts/gcc/$(HOST_PREBUILT_TAG)/arm/arm-linux-androideabi-4.6
+TARGET_TOOLS_PREFIX := $(TARGET_TOOLCHAIN_ROOT)/bin/arm-linux-androideabi-
 endif
 
 # Only define these if there's actually a gcc in there.
@@ -102,7 +102,7 @@
 arch_include_dir := $(dir $(android_config_h))
 
 TARGET_GLOBAL_CFLAGS += \
-			-msoft-float -fpic \
+			-msoft-float -fpic -fPIE \
 			-ffunction-sections \
 			-fdata-sections \
 			-funwind-tables \
@@ -135,6 +135,8 @@
 
 TARGET_GLOBAL_LDFLAGS += \
 			-Wl,-z,noexecstack \
+			-Wl,-z,relro \
+			-Wl,-z,now \
 			-Wl,--icf=safe \
 			$(arch_variant_ldflags)
 
@@ -246,7 +248,7 @@
 
 define transform-o-to-shared-lib-inner
 $(hide) $(PRIVATE_CXX) \
-	-nostdlib -Wl,-soname,$(notdir $@) -Wl,-T,$(BUILD_SYSTEM)/armelf.xsc \
+	-nostdlib -Wl,-soname,$(notdir $@) \
 	-Wl,--gc-sections \
 	-Wl,-shared,-Bsymbolic \
 	$(PRIVATE_TARGET_GLOBAL_LD_DIRS) \
@@ -268,7 +270,7 @@
 endef
 
 define transform-o-to-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bdynamic -Wl,-T,$(BUILD_SYSTEM)/armelf.x \
+$(hide) $(PRIVATE_CXX) -nostdlib -Bdynamic -fPIE -pie \
 	-Wl,-dynamic-linker,/system/bin/linker \
     -Wl,--gc-sections \
 	-Wl,-z,nocopyreloc \
diff --git a/core/combo/TARGET_linux-sh.mk b/core/combo/TARGET_linux-sh.mk
index fe4c4f3..9ecd649 100644
--- a/core/combo/TARGET_linux-sh.mk
+++ b/core/combo/TARGET_linux-sh.mk
@@ -19,8 +19,8 @@
 
 # You can set TARGET_TOOLS_PREFIX to get gcc from somewhere else
 ifeq ($(strip $(TARGET_TOOLS_PREFIX)),)
-TARGET_TOOLS_PREFIX := \
-	prebuilt/$(HOST_PREBUILT_TAG)/toolchain/sh-4.3.3/bin/sh-linux-gnu-
+TARGET_TOOLCHAIN_ROOT := prebuilt/$(HOST_PREBUILT_TAG)/toolchain/sh-4.3.3
+TARGET_TOOLS_PREFIX := $(TARGET_TOOLCHAIN_ROOT)/bin/sh-linux-gnu-
 endif
 
 TARGET_CC := $(TARGET_TOOLS_PREFIX)gcc$(HOST_EXECUTABLE_SUFFIX)
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index 5020c84..0863e63 100644
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -22,10 +22,22 @@
 TARGET_ARCH_VARIANT := x86
 endif
 
+# Include the arch-variant-specific configuration file.
+# Its role is to define various ARCH_X86_HAVE_XXX feature macros,
+# plus initial values for TARGET_GLOBAL_CFLAGS
+#
+TARGET_ARCH_SPECIFIC_MAKEFILE := $(BUILD_COMBOS)/arch/$(TARGET_ARCH)/$(TARGET_ARCH_VARIANT).mk
+ifeq ($(strip $(wildcard $(TARGET_ARCH_SPECIFIC_MAKEFILE))),)
+$(error Unknown $(TARGET_ARCH) architecture version: $(TARGET_ARCH_VARIANT))
+endif
+
+include $(TARGET_ARCH_SPECIFIC_MAKEFILE)
+
+
 # You can set TARGET_TOOLS_PREFIX to get gcc from somewhere else
 ifeq ($(strip $(TARGET_TOOLS_PREFIX)),)
-TARGET_TOOLS_PREFIX := \
-	prebuilts/gcc/$(HOST_PREBUILT_TAG)/x86/i686-linux-android-4.6/bin/i686-linux-android-
+TARGET_TOOLCHAIN_ROOT := prebuilts/gcc/$(HOST_PREBUILT_TAG)/x86/i686-linux-android-4.6
+TARGET_TOOLS_PREFIX := $(TARGET_TOOLCHAIN_ROOT)/bin/i686-linux-android-
 endif
 
 TARGET_CC := $(TARGET_TOOLS_PREFIX)gcc$(HOST_EXECUTABLE_SUFFIX)
@@ -73,7 +85,7 @@
 			-Wa,--noexecstack \
 			-Werror=format-security \
 			-Wstrict-aliasing=2 \
-			-fPIC \
+			-fPIC -fPIE \
 			-ffunction-sections \
 			-finline-functions \
 			-finline-limit=300 \
@@ -84,45 +96,50 @@
 			-funwind-tables \
 			-include $(call select-android-config-h,target_linux-x86)
 
-# Needs to be fixed later
-#TARGET_GLOBAL_CFLAGS += \
-#			-fstack-protector
-
-# Needs to be added for RELEASE
-#TARGET_GLOBAL_CFLAGS += \
-#			-DNDEBUG
-
+# XXX: Not sure this is still needed. Must check with our toolchains.
 TARGET_GLOBAL_CPPFLAGS += \
 			-fno-use-cxa-atexit
 
-ifeq ($(TARGET_ARCH_VARIANT),x86-atom)
-    # Basic ATOM flags.
-    TARGET_GLOBAL_CFLAGS += -march=atom -mstackrealign -mfpmath=sse
+# XXX: Our toolchain is normally configured to always set these flags by default
+# however, there have been reports that this is sometimes not the case. So make
+# them explicit here unless we have the time to carefully check it
+#
+TARGET_GLOBAL_CFLAGS += -mstackrealign -msse3 -mfpmath=sse
 
-    # There are various levels of ATOM processors out there. Different ones have different
-    # capabilities. This first define matches the NDK's minimum ABI requirements.
-    # Note: Not all of the flags set here are actually used in Android. They are provided
-    # to allow for the addition of corresponding optimizations.
-    TARGET_GLOBAL_CFLAGS += -DUSE_MMX -DUSE_SSE -DUSE_SSE2 -DUSE_SSE3
-
-    # If you wish to build a BSP that will only be used on hardware that has additional
-    # available instructions, enable them here. By default, this is commented off so that
-    # the default images can run on all processors that are NDK ABI compliant.
-    # TARGET_GLOBAL_CFLAGS += -DUSE_SSSE3
-else
-    # Plain 'x86' - lowest common denominator. This should run pretty much on any hardware.
-    #
-    # Note: The NDK's ABI (see the NDK ABI documentation) requires many of the more recent
-    # instruction set additions. You can build an "x86" BSP that will run on very old hardware,
-    # but it won't be able to run much of the x86 NDK compliant code.
-    TARGET_GLOBAL_CFLAGS += -march=i686
+# XXX: These flags should not be defined here anymore. Instead, the Android.mk
+# of the modules that depend on these features should instead check the
+# corresponding macros (e.g. ARCH_X86_HAVE_SSE2 and ARCH_X86_HAVE_SSSE3)
+# Keep them here until this is all cleared up.
+#
+ifeq ($(ARCH_X86_HAVE_SSE2),true)
+TARGET_GLOBAL_CFLAGS += -DUSE_SSE2
 endif
 
+ifeq ($(ARCH_X86_HAVE_SSSE3),true)   # yes, really SSSE3, not SSE3!
+TARGET_GLOBAL_CFLAGS += -DUSE_SSSE3
+endif
+
+# XXX: This flag is probably redundant. I believe our toolchain always sets
+# it by default. Consider for removal.
+#
 TARGET_GLOBAL_CFLAGS += -mbionic
+
+# XXX: This flag is probably redundant. The macro should be defined by our
+# toolchain binaries automatically (as a compiler built-in).
+# Check with: $BINPREFIX-gcc -dM -E < /dev/null
+#
+# Consider for removal.
+#
 TARGET_GLOBAL_CFLAGS += -D__ANDROID__
 
+# XXX: This flag is probably redundant since our toolchain binaries already
+# generate 32-bit machine code. It probably dates back to the old days
+# where we were using the host toolchain on Linux to build the platform
+# images. Consider it for removal.
 TARGET_GLOBAL_LDFLAGS += -m32
+
 TARGET_GLOBAL_LDFLAGS += -Wl,-z,noexecstack
+TARGET_GLOBAL_LDFLAGS += -Wl,-z,relro -Wl,-z,now
 TARGET_GLOBAL_LDFLAGS += -Wl,--gc-sections
 
 TARGET_C_INCLUDES := \
@@ -175,6 +192,7 @@
 	-nostdlib -Bdynamic \
 	-Wl,-dynamic-linker,/system/bin/linker \
 	-Wl,-z,nocopyreloc \
+	-fPIE -pie \
 	-o $@ \
 	$(TARGET_GLOBAL_LD_DIRS) \
 	-Wl,-rpath-link=$(TARGET_OUT_INTERMEDIATE_LIBRARIES) \
@@ -210,3 +228,21 @@
 	-Wl,--end-group \
 	$(if $(filter true,$(PRIVATE_NO_CRT)),,$(TARGET_CRTEND_O))
 endef
+
+# Special check for x86 NDK ABI compatibility.
+# The TARGET_CPU_ABI variable should be defined in BoardConfig.mk to 'x86'
+# *only* if the platform image is compatible with the NDK x86 ABI.
+#
+# We perform a small check here to ensure that nothing bad can happen.
+#
+ifeq ($(TARGET_CPU_ABI),x86)
+  ifneq (true-true-true-true,$(ARCH_X86_HAVE_MMX)-$(ARCH_X86_HAVE_SSE)-$(ARCH_X86_HAVE_SSE2)-$(ARCH_X86_HAVE_SSE3))
+    $(info ERROR: Your x86 platform image is not compatible with the NDK x86 ABI)
+    $(info As such, you should *not* define TARGET_CPU_ABI to 'x86' in your BoardConfig.mk)
+    $(info to ensure that your device will not be mistakenly listed as compatible by
+    $(info the Android Market. Also, it is likely that the image will fail the CTS tests)
+    $(info Please undefine TARGET_CPU_ABI in your BoardConfig.mk, or select the value 'none')
+    $(info The corresponding image will still be able to run Dalvik-based Android applications)
+    $(error Aborting build! Please fix your BoardConfig.mk)
+  endif
+endif
diff --git a/core/combo/arch/arm/armv7-a-neon.mk b/core/combo/arch/arm/armv7-a-neon.mk
index 7b5b8ed..32273ff 100644
--- a/core/combo/arch/arm/armv7-a-neon.mk
+++ b/core/combo/arch/arm/armv7-a-neon.mk
@@ -8,6 +8,7 @@
 ARCH_ARM_HAVE_CLZ               := true
 ARCH_ARM_HAVE_FFS               := true
 ARCH_ARM_HAVE_ARMV7A            := true
+ARCH_ARM_HAVE_TLS_REGISTER      := true
 ARCH_ARM_HAVE_VFP               := true
 ARCH_ARM_HAVE_VFP_D32           := true
 ARCH_ARM_HAVE_NEON              := true
diff --git a/core/combo/arch/arm/armv7-a.mk b/core/combo/arch/arm/armv7-a.mk
index 0ca3ec6..220f7ec 100644
--- a/core/combo/arch/arm/armv7-a.mk
+++ b/core/combo/arch/arm/armv7-a.mk
@@ -8,6 +8,7 @@
 ARCH_ARM_HAVE_CLZ               := true
 ARCH_ARM_HAVE_FFS               := true
 ARCH_ARM_HAVE_ARMV7A            := true
+ARCH_ARM_HAVE_TLS_REGISTER      := true
 ARCH_ARM_HAVE_VFP               := true
 
 # Note: Hard coding the 'tune' value here is probably not ideal,
diff --git a/core/combo/arch/x86/x86-atom.mk b/core/combo/arch/x86/x86-atom.mk
new file mode 100644
index 0000000..85998e7
--- /dev/null
+++ b/core/combo/arch/x86/x86-atom.mk
@@ -0,0 +1,18 @@
+# This file contains feature macro definitions specific to the
+# 'x86-atom' arch variant. This is an extension of the 'x86' base variant
+# that adds Atom-specific features.
+#
+# See build/core/combo/arch/x86/x86.mk for differences.
+#
+ARCH_X86_HAVE_MMX   := true
+ARCH_X86_HAVE_SSE   := true
+ARCH_X86_HAVE_SSE2  := true
+ARCH_X86_HAVE_SSE3  := true
+
+ARCH_X86_HAVE_SSSE3 := true
+ARCH_X86_HAVE_MOVBE := true
+ARCH_X86_HAVE_POPCNT := false   # popcnt is not supported by current Atom CPUs
+
+# This flag is used to enabled Atom-specific optimizations with our toolchain
+#
+TARGET_GLOBAL_CFLAGS += -march=atom
diff --git a/core/combo/arch/x86/x86.mk b/core/combo/arch/x86/x86.mk
new file mode 100644
index 0000000..476da45
--- /dev/null
+++ b/core/combo/arch/x86/x86.mk
@@ -0,0 +1,35 @@
+# This file contains feature macro definitions specific to the
+# base 'x86' platform ABI. This one must *strictly* match the NDK x86 ABI
+# which mandates specific CPU extensions to be available.
+#
+# It is also used to build full_x86-eng / sdk_x86-eng platform images that
+# are run in the emulator under KVM emulation (i.e. running directly on
+# the host development machine's CPU).
+#
+
+# If your target device doesn't support the four following features, then
+# it cannot be compatible with the NDK x86 ABI. You should define a new
+# target arch variant (e.g. "x86-mydevice") and a corresponding file
+# under build/core/combo/arch/x86/
+#
+ARCH_X86_HAVE_MMX   := true
+ARCH_X86_HAVE_SSE   := true
+ARCH_X86_HAVE_SSE2  := true
+ARCH_X86_HAVE_SSE3  := true
+
+# These features are optional and shall not be included in the base platform
+# Otherwise, they sdk_x86-eng system images might fail to run on some
+# developer machines.
+#
+
+ARCH_X86_HAVE_SSSE3 := false
+ARCH_X86_HAVE_MOVBE := false
+ARCH_X86_HAVE_POPCNT := false
+
+
+# XXX: This flag is probably redundant, because it should be set by default
+# by our toolchain binaries. However, there have been reports that this may
+# not always work as intended, so keep it unless we have the time to check
+# everything properly.
+
+TARGET_GLOBAL_CFLAGS += -march=i686
diff --git a/core/combo/select.mk b/core/combo/select.mk
index cdeb68a..803cfc0 100644
--- a/core/combo/select.mk
+++ b/core/combo/select.mk
@@ -66,7 +66,7 @@
   ifeq ($(HOST_OS)-$(BUILD_OS),windows-linux)
     CCACHE_HOST_TAG := linux-$(BUILD_ARCH)
   endif
-  ccache := prebuilt/$(CCACHE_HOST_TAG)/ccache/ccache
+  ccache := prebuilts/misc/$(CCACHE_HOST_TAG)/ccache/ccache
   # Check that the executable is here.
   ccache := $(strip $(wildcard $(ccache)))
   ifdef ccache
diff --git a/core/config.mk b/core/config.mk
index 41e60ea..b0b5082 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -28,10 +28,12 @@
 	$(TOPDIR)hardware/libhardware/include \
 	$(TOPDIR)hardware/libhardware_legacy/include \
 	$(TOPDIR)hardware/ril/include \
-	$(TOPDIR)dalvik/libnativehelper/include \
+	$(TOPDIR)libnativehelper/include \
+	$(TOPDIR)frameworks/native/include \
+	$(TOPDIR)frameworks/native/opengl/include \
+	$(TOPDIR)frameworks/av/include \
 	$(TOPDIR)frameworks/base/include \
 	$(TOPDIR)frameworks/base/opengl/include \
-    $(TOPDIR)frameworks/base/native/include \
 	$(TOPDIR)external/skia/include
 SRC_HOST_HEADERS:=$(TOPDIR)tools/include
 SRC_LIBRARIES:= $(TOPDIR)libs
@@ -73,6 +75,8 @@
 BUILD_NATIVE_TEST := $(BUILD_SYSTEM)/native_test.mk
 BUILD_HOST_NATIVE_TEST := $(BUILD_SYSTEM)/host_native_test.mk
 
+-include cts/build/config.mk
+
 # ###############################################################
 # Parse out any modifier targets.
 # ###############################################################
@@ -117,7 +121,10 @@
 # If this file doesn't exist, the environemnt variables will
 # be used, and if that doesn't work, then the default is an
 # arm build
--include $(TOPDIR)buildspec.mk
+ifndef ANDROID_BUILDSPEC
+ANDROID_BUILDSPEC := $(TOPDIR)buildspec.mk
+endif
+-include $(ANDROID_BUILDSPEC)
 
 # ---------------------------------------------------------------
 # Define most of the global variables.  These are the ones that
@@ -144,6 +151,64 @@
 TARGET_DEVICE_DIR := $(patsubst %/,%,$(dir $(board_config_mk)))
 board_config_mk :=
 
+# The build system exposes several variables for where to find the kernel
+# headers:
+#   TARGET_DEVICE_KERNEL_HEADERS is automatically created for the current
+#       device being built. It is set as $(TARGET_DEVICE_DIR)/kernel-headers,
+#       e.g. device/samsung/tuna/kernel-headers. This directory is not
+#       explicitly set by anyone, the build system always adds this subdir.
+#
+#   TARGET_BOARD_KERNEL_HEADERS is specified by the BoardConfig.mk file
+#       to allow other directories to be included. This is useful if there's
+#       some common place where a few headers are being kept for a group
+#       of devices. For example, device/<vendor>/common/kernel-headers could
+#       contain some headers for several of <vendor>'s devices.
+#
+#   TARGET_PRODUCT_KERNEL_HEADERS is generated by the product inheritance
+#       graph. This allows architecture products to provide headers for the
+#       devices using that architecture. For example,
+#       hardware/ti/omap4xxx/omap4.mk will specify
+#       PRODUCT_VENDOR_KERNEL_HEADERS variable that specify where the omap4
+#       specific headers are, e.g. hardware/ti/omap4xxx/kernel-headers.
+#       The build system then combines all the values specified by all the
+#       PRODUCT_VENDOR_KERNEL_HEADERS directives in the product inheritance
+#       tree and then exports a TARGET_PRODUCT_KERNEL_HEADERS variable.
+#
+# The layout of subdirs in any of the kernel-headers dir should mirror the
+# layout of the kernel include/ directory. For example,
+#     device/samsung/tuna/kernel-headers/linux/,
+#     hardware/ti/omap4xxx/kernel-headers/media/,
+#     etc.
+#
+# NOTE: These directories MUST contain post-processed headers using the
+# bionic/libc/kernel/clean_header.py tool. Additionally, the original kernel
+# headers must also be checked in, but in a different subdirectory. By
+# convention, the originals should be checked into original-kernel-headers
+# directory of the same parent dir. For example,
+#     device/samsung/tuna/kernel-headers            <----- post-processed
+#     device/samsung/tuna/original-kernel-headers   <----- originals
+#
+TARGET_DEVICE_KERNEL_HEADERS := $(strip $(wildcard $(TARGET_DEVICE_DIR)/kernel-headers))
+
+define validate-kernel-headers
+$(if $(firstword $(foreach hdr_dir,$(1),\
+         $(filter-out kernel-headers,$(notdir $(hdr_dir))))),\
+     $(error Kernel header dirs must be end in kernel-headers: $(1)))
+endef
+# also allow the board config to provide additional directories since
+# there could be device/oem/base_hw and device/oem/derived_hw
+# that both are valid devices but derived_hw needs to use kernel headers
+# from base_hw.
+TARGET_BOARD_KERNEL_HEADERS := $(strip $(wildcard $(TARGET_BOARD_KERNEL_HEADERS)))
+TARGET_BOARD_KERNEL_HEADERS := $(patsubst %/,%,$(TARGET_BOARD_KERNEL_HEADERS))
+$(call validate-kernel-headers,$(TARGET_BOARD_KERNEL_HEADERS))
+
+# then add product-inherited includes, to allow for
+# hardware/sivendor/chip/chip.mk to include their own headers
+TARGET_PRODUCT_KERNEL_HEADERS := $(strip $(wildcard $(PRODUCT_VENDOR_KERNEL_HEADERS)))
+TARGET_PRODUCT_KERNEL_HEADERS := $(patsubst %/,%,$(TARGET_PRODUCT_KERNEL_HEADERS))
+$(call validate-kernel-headers,$(TARGET_PRODUCT_KERNEL_HEADERS))
+
 # Clean up/verify variables defined by the board config file.
 TARGET_BOOTLOADER_BOARD_NAME := $(strip $(TARGET_BOOTLOADER_BOARD_NAME))
 TARGET_CPU_ABI := $(strip $(TARGET_CPU_ABI))
@@ -166,6 +231,14 @@
 combo_target := TARGET_
 include $(BUILD_SYSTEM)/combo/select.mk
 
+# Compute TARGET_TOOLCHAIN_ROOT from TARGET_TOOLS_PREFIX
+# if only TARGET_TOOLS_PREFIX is passed to the make command.
+ifndef TARGET_TOOLCHAIN_ROOT
+TARGET_TOOLCHAIN_ROOT := $(patsubst %/, %, $(dir $(TARGET_TOOLS_PREFIX)))
+TARGET_TOOLCHAIN_ROOT := $(patsubst %/, %, $(dir $(TARGET_TOOLCHAIN_ROOT)))
+TARGET_TOOLCHAIN_ROOT := $(wildcard $(TARGET_TOOLCHAIN_ROOT))
+endif
+
 # Pick a Java compiler.
 include $(BUILD_SYSTEM)/combo/javac.mk
 
@@ -230,7 +303,6 @@
 DX := $(HOST_OUT_EXECUTABLES)/dx
 ZIPALIGN := $(HOST_OUT_EXECUTABLES)/zipalign$(HOST_EXECUTABLE_SUFFIX)
 FINDBUGS := prebuilt/common/findbugs/bin/findbugs
-LOCALIZE := $(HOST_OUT_EXECUTABLES)/localize$(HOST_EXECUTABLE_SUFFIX)
 EMMA_JAR := external/emma/lib/emma$(COMMON_JAVA_PACKAGE_SUFFIX)
 
 # Deal with archaic version of bison on Mac OS X.
@@ -254,7 +326,7 @@
 ifeq ($(HOST_OS),darwin)
 dir := $(HOST_OS)-$(HOST_ARCH)
 endif
-OLD_FLEX := prebuilt/$(HOST_PREBUILT_TAG)/flex/flex-2.5.4a$(HOST_EXECUTABLE_SUFFIX)
+OLD_FLEX := prebuilts/misc/$(HOST_PREBUILT_TAG)/flex/flex-2.5.4a$(HOST_EXECUTABLE_SUFFIX)
 
 ifeq ($(HOST_OS),darwin)
 # Mac OS' screwy version of java uses a non-standard directory layout
@@ -315,7 +387,9 @@
 TARGET_GLOBAL_LD_DIRS += -L$(TARGET_OUT_INTERMEDIATE_LIBRARIES)
 
 HOST_PROJECT_INCLUDES:= $(SRC_HEADERS) $(SRC_HOST_HEADERS) $(HOST_OUT_HEADERS)
-TARGET_PROJECT_INCLUDES:= $(SRC_HEADERS) $(TARGET_OUT_HEADERS)
+TARGET_PROJECT_INCLUDES:= $(SRC_HEADERS) $(TARGET_OUT_HEADERS) \
+		$(TARGET_DEVICE_KERNEL_HEADERS) $(TARGET_BOARD_KERNEL_HEADERS) \
+		$(TARGET_PRODUCT_KERNEL_HEADERS)
 
 # Many host compilers don't support these flags, so we have to make
 # sure to only specify them for the target compilers checked in to
@@ -329,6 +403,9 @@
 TARGET_GLOBAL_CFLAGS += $(TARGET_RELEASE_CFLAGS)
 TARGET_GLOBAL_CPPFLAGS += $(TARGET_RELEASE_CPPFLAGS)
 
+# define llvm tools and global flags
+include $(BUILD_SYSTEM)/llvm_config.mk
+
 PREBUILT_IS_PRESENT := $(if $(wildcard prebuilt/Android.mk),true)
 
 # ###############################################################
@@ -336,8 +413,8 @@
 # For use with the LOCAL_SDK_VERSION variable for include $(BUILD_PACKAGE)
 # ###############################################################
 
-HISTORICAL_SDK_VERSIONS_ROOT := $(TOPDIR)prebuilt/sdk
-HISTORICAL_NDK_VERSIONS_ROOT := $(TOPDIR)prebuilt/ndk
+HISTORICAL_SDK_VERSIONS_ROOT := $(TOPDIR)prebuilts/sdk
+HISTORICAL_NDK_VERSIONS_ROOT := $(TOPDIR)prebuilts/ndk
 
 # Historical SDK version N is stored in $(HISTORICAL_SDK_VERSIONS_ROOT)/N.
 # The 'current' version is whatever this source tree is.
@@ -355,7 +432,7 @@
     ( sgrax $(1) | sort -g ) )
 endef
 
-TARGET_AVAILABLE_SDK_VERSIONS := current $(call numerically_sort,\
+TARGET_AVAILABLE_SDK_VERSIONS := $(call numerically_sort,\
     $(patsubst $(HISTORICAL_SDK_VERSIONS_ROOT)/%/android.jar,%, \
     $(wildcard $(HISTORICAL_SDK_VERSIONS_ROOT)/*/android.jar)))
 
diff --git a/core/definitions.mk b/core/definitions.mk
index b678158..f3e4966 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -78,6 +78,9 @@
 # All findbugs xml files
 ALL_FINDBUGS_FILES:=
 
+# GPL module license files
+ALL_GPL_MODULE_LICENSE_FILES:=
+
 ###########################################################
 ## Debugging; prints a variable list to stdout
 ###########################################################
@@ -110,11 +113,11 @@
 # Figure out where we are.
 define my-dir
 $(strip \
-  $(eval md_file_ := $$(lastword $$(MAKEFILE_LIST))) \
-  $(if $(filter $(CLEAR_VARS),$(md_file_)), \
+  $(eval LOCAL_MODULE_MAKEFILE := $$(lastword $$(MAKEFILE_LIST))) \
+  $(if $(filter $(CLEAR_VARS),$(LOCAL_MODULE_MAKEFILE)), \
     $(error LOCAL_PATH must be set before including $$(CLEAR_VARS)) \
    , \
-    $(patsubst %/,%,$(dir $(md_file_))) \
+    $(patsubst %/,%,$(dir $(LOCAL_MODULE_MAKEFILE))) \
    ) \
  )
 endef
@@ -802,6 +805,7 @@
   -d $(PRIVATE_RS_OUTPUT_DIR) \
   -a $@ -MD \
   $(addprefix -target-api , $(PRIVATE_RS_TARGET_API)) \
+  $(PRIVATE_RS_FLAGS) \
   $(foreach inc,$(PRIVATE_RS_INCLUDES),$(addprefix -I , $(inc))) \
   $(PRIVATE_RS_SOURCE_FILES)
 #$(hide) $(LLVM_RS_LINK) \
@@ -848,7 +852,7 @@
         $(addprefix --proto_path=, $(PRIVATE_PROTO_INCLUDES)) \
         $(PRIVATE_PROTO_JAVA_OUTPUT_OPTION)=$(PRIVATE_PROTO_JAVA_OUTPUT_DIR) \
         $(PRIVATE_PROTOC_FLAGS) \
-        $$f; \
+        $$f || exit 33; \
         done
 $(hide) touch $@
 endef
@@ -875,6 +879,7 @@
 @echo "target $(PRIVATE_ARM_MODE) C++: $(PRIVATE_MODULE) <= $<"
 $(hide) $(PRIVATE_CXX) \
 	$(addprefix -I , $(PRIVATE_C_INCLUDES)) \
+	@$(PRIVATE_IMPORT_INCLUDES) \
 	$(addprefix -isystem ,\
 	    $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	        $(filter-out $(PRIVATE_C_INCLUDES), \
@@ -904,6 +909,7 @@
 @mkdir -p $(dir $@)
 $(hide) $(PRIVATE_CC) \
 	$(addprefix -I , $(PRIVATE_C_INCLUDES)) \
+	@$(PRIVATE_IMPORT_INCLUDES) \
 	$(addprefix -isystem ,\
 	    $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	        $(filter-out $(PRIVATE_C_INCLUDES), \
@@ -965,6 +971,7 @@
 @echo "host C++: $(PRIVATE_MODULE) <= $<"
 $(hide) $(PRIVATE_CXX) \
 	$(addprefix -I , $(PRIVATE_C_INCLUDES)) \
+	@$(PRIVATE_IMPORT_INCLUDES) \
 	$(addprefix -isystem ,\
 	    $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	        $(filter-out $(PRIVATE_C_INCLUDES), \
@@ -992,6 +999,7 @@
 @mkdir -p $(dir $@)
 $(hide) $(PRIVATE_CC) \
 	$(addprefix -I , $(PRIVATE_C_INCLUDES)) \
+	@$(PRIVATE_IMPORT_INCLUDES) \
 	$(addprefix -isystem ,\
 	    $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	        $(filter-out $(PRIVATE_C_INCLUDES), \
@@ -1104,7 +1112,7 @@
     rm -rf $$ldir; \
     mkdir -p $$ldir; \
     filelist=; \
-    for f in `$(HOST_AR) t $(1) | grep '\.o$$'`; do \
+    for f in `$(HOST_AR) t $(1) | \grep '\.o$$'`; do \
         $(HOST_AR) p $(1) $$f > $$ldir/$$f; \
         filelist="$$filelist $$ldir/$$f"; \
     done ; \
@@ -1444,7 +1452,8 @@
 fi
 $(hide) tr ' ' '\n' < $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list \
     | sort -u > $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq
-$(hide) $(1) -encoding UTF-8 \
+$(hide) if [ -s $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq ] ; then \
+    $(1) -encoding UTF-8 \
     $(strip $(PRIVATE_JAVAC_DEBUG_FLAGS)) \
     $(if $(findstring true,$(LOCAL_WARNINGS_ENABLE)),$(xlint_unchecked),) \
     $(2) \
@@ -1454,9 +1463,14 @@
     -extdirs "" -d $(PRIVATE_CLASS_INTERMEDIATES_DIR) \
     $(PRIVATE_JAVACFLAGS) \
     \@$(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq \
-    || ( rm -rf $(PRIVATE_CLASS_INTERMEDIATES_DIR) ; exit 41 )
+    || ( rm -rf $(PRIVATE_CLASS_INTERMEDIATES_DIR) ; exit 41 ) \
+fi
 $(hide) rm -f $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list
 $(hide) rm -f $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq
+$(if $(PRIVATE_JAR_EXCLUDE_FILES), $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) \
+    -name $(word 1, $(PRIVATE_JAR_EXCLUDE_FILES)) \
+    $(addprefix -o -name , $(wordlist 2, 999, $(PRIVATE_JAR_EXCLUDE_FILES))) \
+    | xargs rm -rf)
 $(hide) jar $(if $(strip $(PRIVATE_JAR_MANIFEST)),-cfm,-cf) \
     $@ $(PRIVATE_JAR_MANIFEST) -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .
 endef
@@ -1693,6 +1707,16 @@
 	$$(copy-file-to-target)
 endef
 
+# Copy the file only if it's a well-formed xml file. For use via $(eval).
+# $(1): source file
+# $(2): destination file, must end with .xml.
+define copy-xml-file-checked
+$(2): $(1) | $(ACP)
+	@echo "Copy xml: $$@"
+	$(hide) xmllint $$< >/dev/null  # Don't print the xml file to stdout.
+	$$(copy-file-to-target)
+endef
+
 # The -t option to acp and the -p option to cp is
 # required for OSX.  OSX has a ridiculous restriction
 # where it's an error for a .a file's modification time
@@ -1865,7 +1889,6 @@
   size=$$(for i in $(1); do $(call get-file-size,$$i); echo +; done; echo 0); \
   total=$$(( $$( echo "$$size" ) )); \
   printname=$$(echo -n "$(1)" | tr " " +); \
-  echo "$$printname total size is $$total"; \
   img_blocksize=$(call image-size-from-data-size,$(BOARD_FLASH_BLOCK_SIZE)); \
   if [ "$(3)" == "yaffs" ]; then \
     reservedblocks=8; \
@@ -1877,6 +1900,7 @@
   reserve=$$(((twoblocks > onepct ? twoblocks : onepct) + \
                reservedblocks * img_blocksize)); \
   maxsize=$$(($(2) - reserve)); \
+  echo "$$printname maxsize=$$maxsize blocksize=$$img_blocksize total=$$total reserve=$$reserve"; \
   if [ "$$total" -gt "$$maxsize" ]; then \
     echo "error: $$printname too large ($$total > [$(2) - $$reserve])"; \
     false; \
@@ -1917,6 +1941,21 @@
 	$$(transform-prebuilt-to-target)
 endef
 
+# Version of add-radio-file that also arranges for the version of the
+# file to be checked against the contents of
+# $(TARGET_BOARD_INFO_FILE).
+# $(1): filename
+# $(2): name of version variable in board-info (eg, "version-baseband")
+define add-radio-file-checked
+  $(eval $(call add-radio-file-checked-internal,$(1),$(notdir $(1)),$(2)))
+endef
+define add-radio-file-checked-internal
+INSTALLED_RADIOIMAGE_TARGET += $$(PRODUCT_OUT)/$(2)
+BOARD_INFO_CHECK += $(3):$(LOCAL_PATH)/$(1)
+$$(PRODUCT_OUT)/$(2) : $$(LOCAL_PATH)/$(1) | $$(ACP)
+	$$(transform-prebuilt-to-target)
+endef
+
 
 ###########################################################
 # Override the package defined in $(1), setting the
@@ -1970,6 +2009,19 @@
   ,)
 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
 
 ###########################################################
 ## Other includes
diff --git a/core/dex_preopt.mk b/core/dex_preopt.mk
index b801ac2..38982c0 100644
--- a/core/dex_preopt.mk
+++ b/core/dex_preopt.mk
@@ -4,7 +4,7 @@
 ####################################
 
 # TODO: replace it with device's BOOTCLASSPATH
-DEXPREOPT_BOOT_JARS := core:core-junit:bouncycastle:ext:framework:android.policy:services:apache-xml:filterfw
+DEXPREOPT_BOOT_JARS := core:core-junit:bouncycastle:ext:framework:android.policy:services:apache-xml
 DEXPREOPT_BOOT_JARS_MODULES := $(subst :, ,$(DEXPREOPT_BOOT_JARS))
 
 DEXPREOPT_BUILD_DIR := $(OUT_DIR)
diff --git a/core/droiddoc.mk b/core/droiddoc.mk
index 91d8166..e312965 100644
--- a/core/droiddoc.mk
+++ b/core/droiddoc.mk
@@ -63,9 +63,18 @@
 
 ifneq ($(LOCAL_IS_HOST_MODULE),true)
 
-ifeq ($(LOCAL_JAVA_LIBRARIES),)
-LOCAL_JAVA_LIBRARIES := core ext framework
-endif
+ifneq ($(LOCAL_SDK_VERSION),)
+  ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),current)
+    # Use android_stubs_current if LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS.
+    LOCAL_JAVA_LIBRARIES := android_stubs_current $(LOCAL_JAVA_LIBRARIES)
+  else
+    LOCAL_JAVA_LIBRARIES := sdk_v$(LOCAL_SDK_VERSION) $(LOCAL_JAVA_LIBRARIES)
+  endif
+else
+  LOCAL_JAVA_LIBRARIES := core ext framework $(LOCAL_JAVA_LIBRARIES)
+endif  # LOCAL_SDK_VERSION
+LOCAL_JAVA_LIBRARIES := $(sort $(LOCAL_JAVA_LIBRARIES))
+
 full_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))
 
diff --git a/core/dumpvar.mk b/core/dumpvar.mk
index 7929dbb..4a44f77 100644
--- a/core/dumpvar.mk
+++ b/core/dumpvar.mk
@@ -9,11 +9,17 @@
 ABP:=$(PWD)/$(HOST_OUT_EXECUTABLES)
 endif
 
-# Add the toolchain bin dir if it actually exists
+# Add the ARM toolchain bin dir if it actually exists
 ifneq ($(wildcard $(PWD)/prebuilts/gcc/$(HOST_PREBUILT_TAG)/arm/arm-linux-androideabi-4.6/bin),)
 	# this should be copied to HOST_OUT_EXECUTABLES instead
 	ABP:=$(ABP):$(PWD)/prebuilts/gcc/$(HOST_PREBUILT_TAG)/arm/arm-linux-androideabi-4.6/bin
 endif
+
+# Add the x86 toolchain bin dir if it actually exists
+ifneq ($(wildcard $(PWD)/prebuilts/gcc/$(HOST_PREBUILT_TAG)/x86/i686-linux-android-4.6/bin),)
+	# this should be copied to HOST_OUT_EXECUTABLES instead
+	ABP:=$(ABP):$(PWD)/prebuilts/gcc/$(HOST_PREBUILT_TAG)/x86/i686-linux-android-4.6/bin
+endif
 ANDROID_BUILD_PATHS := $(ABP)
 ANDROID_PREBUILTS := prebuilt/$(HOST_PREBUILT_TAG)
 ANDROID_GCC_PREBUILTS := prebuilts/gcc/$(HOST_PREBUILT_TAG)
diff --git a/core/envsetup.mk b/core/envsetup.mk
index e8c924e..74e9100 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -102,6 +102,14 @@
   HOST_PREBUILT_TAG := $(HOST_OS)-$(HOST_ARCH)
 endif
 
+# TARGET_COPY_OUT_* are all relative to the staging directory, ie PRODUCT_OUT.
+# Define them here so they can be used in product config files.
+TARGET_COPY_OUT_SYSTEM := system
+TARGET_COPY_OUT_DATA := data
+TARGET_COPY_OUT_VENDOR := system/vendor
+TARGET_COPY_OUT_ROOT := root
+TARGET_COPY_OUT_RECOVERY := recovery
+
 # Read the product specs so we an get TARGET_DEVICE and other
 # variables that we need in order to locate the output files.
 include $(BUILD_SYSTEM)/product_config.mk
@@ -186,7 +194,7 @@
 TARGET_OUT_INTERMEDIATE_LIBRARIES := $(TARGET_OUT_INTERMEDIATES)/lib
 TARGET_OUT_COMMON_INTERMEDIATES := $(TARGET_COMMON_OUT_ROOT)/obj
 
-TARGET_OUT := $(PRODUCT_OUT)/system
+TARGET_OUT := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_SYSTEM)
 TARGET_OUT_EXECUTABLES:= $(TARGET_OUT)/bin
 TARGET_OUT_OPTIONAL_EXECUTABLES:= $(TARGET_OUT)/xbin
 TARGET_OUT_SHARED_LIBRARIES:= $(TARGET_OUT)/lib
@@ -199,7 +207,7 @@
 TARGET_OUT_NOTICE_FILES:=$(TARGET_OUT_INTERMEDIATES)/NOTICE_FILES
 TARGET_OUT_FAKE := $(PRODUCT_OUT)/fake_packages
 
-TARGET_OUT_DATA := $(PRODUCT_OUT)/data
+TARGET_OUT_DATA := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_DATA)
 TARGET_OUT_DATA_EXECUTABLES:= $(TARGET_OUT_EXECUTABLES)
 TARGET_OUT_DATA_SHARED_LIBRARIES:= $(TARGET_OUT_SHARED_LIBRARIES)
 TARGET_OUT_DATA_JAVA_LIBRARIES:= $(TARGET_OUT_JAVA_LIBRARIES)
@@ -210,7 +218,9 @@
 TARGET_OUT_DATA_STATIC_LIBRARIES:= $(TARGET_OUT_STATIC_LIBRARIES)
 TARGET_OUT_DATA_NATIVE_TESTS := $(TARGET_OUT_DATA)/nativetest
 
-TARGET_OUT_VENDOR := $(PRODUCT_OUT)/system/vendor
+TARGET_OUT_CACHE := $(PRODUCT_OUT)/cache
+
+TARGET_OUT_VENDOR := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_VENDOR)
 TARGET_OUT_VENDOR_EXECUTABLES:= $(TARGET_OUT_VENDOR)/bin
 TARGET_OUT_VENDOR_OPTIONAL_EXECUTABLES:= $(TARGET_OUT_VENDOR)/xbin
 TARGET_OUT_VENDOR_SHARED_LIBRARIES:= $(TARGET_OUT_VENDOR)/lib
@@ -225,13 +235,13 @@
 TARGET_ROOT_OUT_SBIN_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)/sbin
 TARGET_ROOT_OUT_BIN_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)/bin
 
-TARGET_ROOT_OUT := $(PRODUCT_OUT)/root
+TARGET_ROOT_OUT := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_ROOT)
 TARGET_ROOT_OUT_BIN := $(TARGET_ROOT_OUT)/bin
 TARGET_ROOT_OUT_SBIN := $(TARGET_ROOT_OUT)/sbin
 TARGET_ROOT_OUT_ETC := $(TARGET_ROOT_OUT)/etc
 TARGET_ROOT_OUT_USR := $(TARGET_ROOT_OUT)/usr
 
-TARGET_RECOVERY_OUT := $(PRODUCT_OUT)/recovery
+TARGET_RECOVERY_OUT := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_RECOVERY)
 TARGET_RECOVERY_ROOT_OUT := $(TARGET_RECOVERY_OUT)/root
 
 TARGET_SYSLOADER_OUT := $(PRODUCT_OUT)/sysloader
@@ -243,6 +253,8 @@
 TARGET_INSTALLER_ROOT_OUT := $(TARGET_INSTALLER_OUT)/root
 TARGET_INSTALLER_SYSTEM_OUT := $(TARGET_INSTALLER_OUT)/root/system
 
+TARGET_FACTORY_RAMDISK_OUT := $(PRODUCT_OUT)/factory_ramdisk
+
 COMMON_MODULE_CLASSES := TARGET-NOTICE_FILES HOST-NOTICE_FILES HOST-JAVA_LIBRARIES
 
 ifeq (,$(strip $(DIST_DIR)))
diff --git a/core/host_java_library.mk b/core/host_java_library.mk
index 322d10f..6cc0b1f 100644
--- a/core/host_java_library.mk
+++ b/core/host_java_library.mk
@@ -52,6 +52,7 @@
 $(cleantarget): PRIVATE_CLEAN_FILES += $(intermediates.COMMON)
 
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
+$(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES :=
 $(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) $(jar_manifest_file)
 	$(transform-host-java-to-package)
 
@@ -87,6 +88,7 @@
 
 else
 $(LOCAL_BUILT_MODULE): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
+$(LOCAL_BUILT_MODULE): PRIVATE_JAR_EXCLUDE_FILES :=
 $(LOCAL_BUILT_MODULE): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) $(jar_manifest_file)
 	$(transform-host-java-to-package)
 endif  # LOCAL_BUILD_HOST_DEX
diff --git a/core/host_shared_library.mk b/core/host_shared_library.mk
index f78b17b..976a942 100644
--- a/core/host_shared_library.mk
+++ b/core/host_shared_library.mk
@@ -18,6 +18,9 @@
 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): Can not set module stem for a library)
+endif
 
 # Put the built modules of all shared libraries in a common directory
 # to simplify the link line.
diff --git a/core/host_static_library.mk b/core/host_static_library.mk
index 39c99ee..b04291b 100644
--- a/core/host_static_library.mk
+++ b/core/host_static_library.mk
@@ -13,6 +13,9 @@
 ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
 LOCAL_MODULE_SUFFIX := .a
 endif
+ifneq ($(strip $(LOCAL_MODULE_STEM)$(LOCAL_BUILT_MODULE_STEM)),)
+$(error $(LOCAL_PATH): Can not set module stem for a library)
+endif
 LOCAL_UNINSTALLABLE_MODULE := true
 
 LOCAL_IS_HOST_MODULE := true
diff --git a/core/java.mk b/core/java.mk
index 1cde62b..2b6851b 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -3,9 +3,19 @@
 # LOCAL_MODULE_CLASS
 # all_res_assets
 
+ifeq ($(TARGET_BUILD_PDK),true)
+ifeq ($(TARGET_BUILD_PDK_JAVA),)
+# LOCAL_SDK not defined or set to current
+ifeq ($(filter-out current,$(LOCAL_SDK_VERSION)),)
+LOCAL_SDK_VERSION := $(PDK_BUILD_SDK_VERSION)
+endif
+endif # !PDK_JAVA
+endif #PDK
+
+
 # Make sure there's something to build.
 # It's possible to build a package that doesn't contain any classes.
-ifeq (,$(strip $(LOCAL_SRC_FILES)$(all_res_assets)))
+ifeq (,$(strip $(LOCAL_SRC_FILES)$(all_res_assets)$(LOCAL_STATIC_JAVA_LIBRARIES)))
 $(error $(LOCAL_PATH): Target java module does not define any source or resource files)
 endif
 
@@ -20,8 +30,9 @@
       $(error $(LOCAL_PATH): Invalid LOCAL_SDK_VERSION '$(LOCAL_SDK_VERSION)' \
              Choices are: $(TARGET_AVAILABLE_SDK_VERSIONS))
     else
-      ifeq ($(LOCAL_SDK_VERSION),current)
-        LOCAL_JAVA_LIBRARIES := android_stubs_$(LOCAL_SDK_VERSION) $(LOCAL_JAVA_LIBRARIES)
+      ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),current)
+        # Use android_stubs_current if LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS.
+        LOCAL_JAVA_LIBRARIES := android_stubs_current $(LOCAL_JAVA_LIBRARIES)
       else
         LOCAL_JAVA_LIBRARIES := sdk_v$(LOCAL_SDK_VERSION) $(LOCAL_JAVA_LIBRARIES)
       endif
@@ -29,7 +40,7 @@
   endif
 else
   ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
-    LOCAL_JAVA_LIBRARIES := core core-junit ext framework filterfw $(LOCAL_JAVA_LIBRARIES)
+    LOCAL_JAVA_LIBRARIES := core core-junit ext framework $(LOCAL_JAVA_LIBRARIES)
   endif
 endif
 
@@ -152,16 +163,22 @@
 LOCAL_RENDERSCRIPT_CC := $(LLVM_RS_CC)
 endif
 
+# Turn on all warnings and warnings as errors for RS compiles.
+# This can be disabled with LOCAL_RENDERSCRIPT_FLAGS := -Wno-error
+renderscript_flags := -Wall -Werror
+renderscript_flags += $(LOCAL_RENDERSCRIPT_FLAGS)
+
 # prepend the RenderScript system include path
-ifneq ($(filter-out current,$(LOCAL_SDK_VERSION)),)
+ifneq ($(filter-out current,$(LOCAL_SDK_VERSION))$(if $(TARGET_BUILD_APPS),$(filter current,$(LOCAL_SDK_VERSION))),)
+# if a numeric LOCAL_SDK_VERSION, or current LOCAL_SDK_VERSION with TARGET_BUILD_APPS
 LOCAL_RENDERSCRIPT_INCLUDES := \
-    $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_VERSION)/renderscript/clang-include \
-    $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_VERSION)/renderscript/include \
+    $(HISTORICAL_SDK_VERSIONS_ROOT)/renderscript/clang-include \
+    $(HISTORICAL_SDK_VERSIONS_ROOT)/renderscript/include \
     $(LOCAL_RENDERSCRIPT_INCLUDES)
 else
 LOCAL_RENDERSCRIPT_INCLUDES := \
     $(TOPDIR)external/clang/lib/Headers \
-    $(TOPDIR)frameworks/base/libs/rs/scriptc \
+    $(TOPDIR)frameworks/rs/scriptc \
     $(LOCAL_RENDERSCRIPT_INCLUDES)
 endif
 
@@ -171,6 +188,7 @@
 
 $(RenderScript_file_stamp): PRIVATE_RS_INCLUDES := $(LOCAL_RENDERSCRIPT_INCLUDES)
 $(RenderScript_file_stamp): PRIVATE_RS_CC := $(LOCAL_RENDERSCRIPT_CC)
+$(RenderScript_file_stamp): PRIVATE_RS_FLAGS := $(renderscript_flags)
 $(RenderScript_file_stamp): PRIVATE_RS_SOURCE_FILES := $(renderscript_sources_fullpath)
 # By putting the generated java files into $(LOCAL_INTERMEDIATE_SOURCE_DIR), they will be
 # automatically found by the java compiling function transform-java-to-classes.jar.
@@ -214,7 +232,7 @@
 # If the module includes java code (i.e., it's not framework-res), compile it.
 full_classes_jar :=
 built_dex :=
-ifneq (,$(strip $(all_java_sources)))
+ifneq (,$(strip $(all_java_sources)$(full_static_java_libs)))
 
 # If LOCAL_BUILT_MODULE_STEM wasn't overridden by our caller,
 # full_classes_jar will be the same module as LOCAL_BUILT_MODULE.
@@ -243,6 +261,7 @@
 # Deps for generated source files must be handled separately,
 # via deps on the target that generates the sources.
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
+$(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES := $(LOCAL_JAR_EXCLUDE_FILES)
 $(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) $(jar_manifest_file) \
 	$(RenderScript_file_stamp) $(proto_java_sources_file_stamp)
 	$(transform-java-to-classes.jar)
diff --git a/core/java_library.mk b/core/java_library.mk
index c210be6..06cdfc4 100644
--- a/core/java_library.mk
+++ b/core/java_library.mk
@@ -14,9 +14,11 @@
 $(error $(LOCAL_PATH): Target java libraries may not set LOCAL_ASSET_DIR)
 endif
 
+ifneq (true,$(LOCAL_IS_STATIC_JAVA_LIBRARY))
 ifneq (,$(LOCAL_RESOURCE_DIR))
 $(error $(LOCAL_PATH): Target java libraries may not set LOCAL_RESOURCE_DIR)
 endif
+endif
 
 #xxx base_rules.mk looks at this
 all_res_assets :=
diff --git a/core/legacy_prebuilts.mk b/core/legacy_prebuilts.mk
index 41943b1..f883b02 100644
--- a/core/legacy_prebuilts.mk
+++ b/core/legacy_prebuilts.mk
@@ -43,6 +43,7 @@
 	cdt.bin \
 	chat-ril \
 	cmu6plus.ok.zip \
+	content \
 	cpcap-key.kl \
 	data \
 	dbus.conf \
@@ -84,7 +85,6 @@
 	libGLESv1_CM_tegra.so \
 	libGLESv2_POWERVR_SGX530_121.so \
 	libGLESv2_tegra.so \
-	libmdmctrl.a \
 	libmoto_ril.so \
 	libpppd_plugin-ril.so \
 	libril_rds.so \
diff --git a/core/llvm_config.mk b/core/llvm_config.mk
new file mode 100644
index 0000000..4145028
--- /dev/null
+++ b/core/llvm_config.mk
@@ -0,0 +1,73 @@
+CLANG := $(HOST_OUT_EXECUTABLES)/clang$(HOST_EXECUTABLE_SUFFIX)
+CLANG_CXX := $(HOST_OUT_EXECUTABLES)/clang++$(HOST_EXECUTABLE_SUFFIX)
+LLVM_AS := $(HOST_OUT_EXECUTABLES)/llvm-as$(HOST_EXECUTABLE_SUFFIX)
+LLVM_LINK := $(HOST_OUT_EXECUTABLES)/llvm-link$(HOST_EXECUTABLE_SUFFIX)
+
+define do-clang-flags-subst
+  TARGET_GLOBAL_CLANG_FLAGS := $(subst $(1),$(2),$(TARGET_GLOBAL_CLANG_FLAGS))
+  HOST_GLOBAL_CLANG_FLAGS := $(subst $(1),$(2),$(HOST_GLOBAL_CLANG_FLAGS))
+endef
+
+define clang-flags-subst
+  $(eval $(call do-clang-flags-subst,$(1),$(2)))
+endef
+
+
+CLANG_CONFIG_EXTRA_CFLAGS := \
+  -D__compiler_offsetof=__builtin_offsetof \
+  -Dnan=__builtin_nan \
+
+CLANG_CONFIG_UNKNOWN_CFLAGS := \
+  -funswitch-loops
+
+ifeq ($(TARGET_ARCH),arm)
+  CLANG_CONFIG_EXTRA_CFLAGS += \
+    -target arm-linux-androideabi \
+    -nostdlibinc \
+    -B$(TARGET_TOOLCHAIN_ROOT)/arm-linux-androideabi/bin \
+    -mllvm -arm-enable-ehabi
+  CLANG_CONFIG_EXTRA_LDFLAGS += \
+    -target arm-linux-androideabi \
+    -B$(TARGET_TOOLCHAIN_ROOT)/arm-linux-androideabi/bin
+  CLANG_CONFIG_UNKNOWN_CFLAGS += \
+    -mthumb-interwork \
+    -fgcse-after-reload \
+    -frerun-cse-after-loop \
+    -frename-registers \
+    -fno-builtin-sin \
+    -fno-strict-volatile-bitfields \
+    -fno-align-jumps \
+    -Wa,--noexecstack
+endif
+ifeq ($(TARGET_ARCH),x86)
+  CLANG_CONFIG_EXTRA_CFLAGS += \
+    -target i686-linux-android \
+    -nostdlibinc \
+    -B$(TARGET_TOOLCHAIN_ROOT)/i686-linux-android/bin
+  CLANG_CONFIG_EXTRA_LDFLAGS += \
+    -target i686-linux-android \
+    -B$(TARGET_TOOLCHAIN_ROOT)/i686-linux-android/bin
+  CLANG_CONFIG_UNKNOWN_CFLAGS += \
+    -finline-limit=300 \
+    -fno-inline-functions-called-once \
+    -mfpmath=sse \
+    -mbionic
+endif
+
+CLANG_CONFIG_EXTRA_TARGET_C_INCLUDES := external/clang/lib/include $(TARGET_OUT_HEADERS)/clang
+
+# remove unknown flags to define CLANG_FLAGS
+TARGET_GLOBAL_CLANG_FLAGS += $(filter-out $(CLANG_CONFIG_UNKNOWN_CFLAGS),$(TARGET_GLOBAL_CFLAGS))
+HOST_GLOBAL_CLANG_FLAGS += $(filter-out $(CLANG_CONFIG_UNKNOWN_CFLAGS),$(HOST_GLOBAL_CFLAGS))
+
+TARGET_arm_CLANG_CFLAGS += $(filter-out $(CLANG_CONFIG_UNKNOWN_CFLAGS),$(TARGET_arm_CFLAGS))
+TARGET_thumb_CLANG_CFLAGS += $(filter-out $(CLANG_CONFIG_UNKNOWN_CFLAGS),$(TARGET_thumb_CFLAGS))
+
+# llvm does not yet support -march=armv5e nor -march=armv5te, fall back to armv5 or armv5t
+$(call clang-flags-subst,-march=armv5te,-march=armv5t)
+$(call clang-flags-subst,-march=armv5e,-march=armv5)
+
+ADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS := -faddress-sanitizer
+ADDRESS_SANITIZER_CONFIG_EXTRA_LDFLAGS := -Wl,-u,__asan_preinit
+ADDRESS_SANITIZER_CONFIG_EXTRA_SHARED_LIBRARIES := libdl libasan_preload
+ADDRESS_SANITIZER_CONFIG_EXTRA_STATIC_LIBRARIES := libasan
diff --git a/core/main.mk b/core/main.mk
index 3d8d6e0..8a5b407 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -45,13 +45,18 @@
 $(warning ********************************************************************************)
 $(warning *  You are using version $(MAKE_VERSION) of make.)
 $(warning *  Android can only be built by versions 3.81 and 3.82.)
-$(warning *  see http://source.android.com/source/download.html)
+$(warning *  see https://source.android.com/source/download.html)
 $(warning ********************************************************************************)
 $(error stopping)
 endif
 endif
 endif
 
+# Absolute path of the present working direcotry.
+# This overrides the shell variable $PWD, which does not necessarily points to
+# the top of the source tree, for example when "make -C" is used in m/mm/mmm.
+PWD := $(shell pwd)
+
 TOP := .
 TOPDIR :=
 
@@ -131,7 +136,7 @@
 $(info The correct version is: Java SE 1.6.)
 $(info $(space))
 $(info Please follow the machine setup instructions at)
-$(info $(space)$(space)$(space)$(space)http://source.android.com/source/download.html)
+$(info $(space)$(space)$(space)$(space)https://source.android.com/source/download.html)
 $(info ************************************************************)
 $(error stop)
 endif
@@ -147,7 +152,7 @@
 $(info The correct version is: 1.6.)
 $(info $(space))
 $(info Please follow the machine setup instructions at)
-$(info $(space)$(space)$(space)$(space)http://source.android.com/source/download.html)
+$(info $(space)$(space)$(space)$(space)https://source.android.com/source/download.html)
 $(info ************************************************************)
 $(error stop)
 endif
@@ -183,7 +188,7 @@
 # Bring in dex_preopt.mk
 include $(BUILD_SYSTEM)/dex_preopt.mk
 
-ifneq ($(filter eng user userdebug tests,$(MAKECMDGOALS)),)
+ifneq ($(filter eng user userdebug,$(MAKECMDGOALS)),)
 $(info ***************************************************************)
 $(info ***************************************************************)
 $(info Don't pass '$(filter eng user userdebug tests,$(MAKECMDGOALS))' on \
@@ -207,6 +212,11 @@
 $(error stopping)
 endif
 
+# -----------------------------------------------------------------
+# The pdk (Platform Development Kit) build
+include build/core/pdk_config.mk
+
+# -----------------------------------------------------------------
 ###
 ### In this section we set up the things that are different
 ### between the build variants
@@ -322,17 +332,6 @@
   ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.dexopt-flags=m=y
 endif
 
-ifneq ($(BUILD_TINY_ANDROID),true)
-# Install an apns-conf.xml file if one's not already being installed.
-ifeq (,$(filter %:system/etc/apns-conf.xml, $(PRODUCT_COPY_FILES)))
-  PRODUCT_COPY_FILES += \
-        development/data/etc/apns-conf_sdk.xml:system/etc/apns-conf.xml
-  ifeq ($(filter eng tests,$(TARGET_BUILD_VARIANT)),)
-    $(warning implicitly installing apns-conf_sdk.xml)
-  endif
-endif
-endif
-
 ADDITIONAL_BUILD_PROPERTIES += net.bt.name=Android
 
 # enable vm tracing in files for now to help track
@@ -416,11 +415,11 @@
 	build/libs \
 	build/target \
 	build/tools/acp \
+	external/gcc-demangle \
 	external/mksh \
 	external/yaffs2 \
 	external/zlib
 else	# !BUILD_TINY_ANDROID
-
 #
 # Typical build; include any Android.mk files we can find.
 #
@@ -467,8 +466,12 @@
 	$(shell build/tools/findleaves.py --prune=out --prune=.repo --prune=.git $(subdirs) Android.mk)
 
 include $(subdir_makefiles)
+
 endif # ONE_SHOT_MAKEFILE
 
+# Now with all Android.mks loaded we can do post cleaning steps.
+include $(BUILD_SYSTEM)/post_clean.mk
+
 ifeq ($(stash_product_vars),true)
   $(call assert-product-vars, __STASHED)
 endif
@@ -552,13 +555,9 @@
   # The base list of modules to build for this product is specified
   # by the appropriate product definition file, which was included
   # by product_config.make.
-  user_PACKAGES := $(call module-installed-files, \
-                       $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES))
-  ifeq (0,1)
-    $(info user packages for $(TARGET_DEVICE) ($(INTERNAL_PRODUCT)):)
-    $(foreach p,$(user_PACKAGES),$(info :   $(p)))
-    $(error done)
-  endif
+  user_PACKAGES := $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES)
+  $(call expand-required-modules,user_PACKAGES,$(user_PACKAGES))
+  user_PACKAGES := $(call module-installed-files, $(user_PACKAGES))
 else
   # We're not doing a full build, and are probably only including
   # a subset of the module makefiles.  Don't try to build any modules
@@ -669,6 +668,9 @@
 .PHONY: ramdisk
 ramdisk: $(INSTALLED_RAMDISK_TARGET)
 
+.PHONY: factory_ramdisk
+factory_ramdisk: $(INSTALLED_FACTORY_RAMDISK_TARGET)
+
 .PHONY: systemtarball
 systemtarball: $(INSTALLED_SYSTEMTARBALL_TARGET)
 
@@ -685,6 +687,9 @@
 .PHONY: userdatatarball
 userdatatarball: $(INSTALLED_USERDATATARBALL_TARGET)
 
+.PHONY: cacheimage
+cacheimage: $(INSTALLED_CACHEIMAGE_TARGET)
+
 .PHONY: bootimage
 bootimage: $(INSTALLED_BOOTIMAGE_TARGET)
 
@@ -699,6 +704,7 @@
 	$(INSTALLED_BOOTIMAGE_TARGET) \
 	$(INSTALLED_RECOVERYIMAGE_TARGET) \
 	$(INSTALLED_USERDATAIMAGE_TARGET) \
+	$(INSTALLED_CACHEIMAGE_TARGET) \
 	$(INSTALLED_FILES_FILE)
 
 # dist_files only for putting your library into the dist directory with a full build.
@@ -737,16 +743,22 @@
     $(INTERNAL_UPDATE_PACKAGE_TARGET) \
     $(INTERNAL_OTA_PACKAGE_TARGET) \
     $(SYMBOLS_ZIP) \
-    $(APPS_ZIP) \
-    $(INTERNAL_EMULATOR_PACKAGE_TARGET) \
-    $(PACKAGE_STATS_FILE) \
     $(INSTALLED_FILES_FILE) \
     $(INSTALLED_BUILD_PROP_TARGET) \
     $(BUILT_TARGET_FILES_PACKAGE) \
     $(INSTALLED_ANDROID_INFO_TXT_TARGET) \
     $(INSTALLED_RAMDISK_TARGET) \
+    $(INSTALLED_FACTORY_RAMDISK_TARGET) \
    )
 
+  ifneq ($(TARGET_BUILD_PDK),true)
+    $(call dist-for-goals, droidcore, \
+      $(APPS_ZIP) \
+      $(INTERNAL_EMULATOR_PACKAGE_TARGET) \
+      $(PACKAGE_STATS_FILE) \
+    )
+  endif
+
 # Building a full system-- the default is to build droidcore
 droid: droidcore dist_files
 
@@ -754,8 +766,7 @@
 endif # droid in $(MAKECMDGOALS)
 
 
-.PHONY: droid tests
-tests: droidcore
+.PHONY: droid
 
 # phony target that include any targets in $(ALL_MODULES)
 .PHONY: all_modules
diff --git a/core/node_fns.mk b/core/node_fns.mk
index 38ecea7..40abff7 100644
--- a/core/node_fns.mk
+++ b/core/node_fns.mk
@@ -98,7 +98,7 @@
 space := $(empty) $(empty)
 define uniq-word
 $(strip \
-  $(if $(filter $(2),$(1)), \
+  $(if $(filter-out 0 1,$(words $(filter $(2),$(1)))), \
     $(eval h := |||$(subst $(space),|||,$(strip $(1)))|||) \
     $(eval h := $(subst |||$(strip $(2))|||,|||$(space)|||,$(h))) \
     $(eval h := $(word 1,$(h)) $(2) $(wordlist 2,9999,$(h))) \
diff --git a/core/package.mk b/core/package.mk
index 52d52a2..c689031 100644
--- a/core/package.mk
+++ b/core/package.mk
@@ -65,6 +65,12 @@
 LOCAL_MANIFEST_FILE := AndroidManifest.xml
 endif
 
+# If you need to put the MANIFEST_FILE outside of LOCAL_PATH
+# you can use FULL_MANIFEST_FILE
+ifeq ($(strip $(LOCAL_FULL_MANIFEST_FILE)),)
+LOCAL_FULL_MANIFEST_FILE := $(LOCAL_PATH)/$(LOCAL_MANIFEST_FILE)
+endif
+
 ifneq ($(strip $(LOCAL_MODULE_CLASS)),)
 $(error $(LOCAL_PATH): Package modules may not set LOCAL_MODULE_CLASS)
 endif
@@ -88,12 +94,14 @@
 ifeq (,$(LOCAL_RESOURCE_DIR))
   LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 endif
-LOCAL_RESOURCE_DIR := \
-  $(wildcard $(foreach dir, $(PRODUCT_PACKAGE_OVERLAYS), \
-    $(addprefix $(dir)/, $(LOCAL_RESOURCE_DIR)))) \
-  $(wildcard $(foreach dir, $(DEVICE_PACKAGE_OVERLAYS), \
-    $(addprefix $(dir)/, $(LOCAL_RESOURCE_DIR)))) \
-  $(LOCAL_RESOURCE_DIR)
+
+package_resource_overlays := $(strip \
+    $(wildcard $(foreach dir, $(PRODUCT_PACKAGE_OVERLAYS), \
+      $(addprefix $(dir)/, $(LOCAL_RESOURCE_DIR)))) \
+    $(wildcard $(foreach dir, $(DEVICE_PACKAGE_OVERLAYS), \
+      $(addprefix $(dir)/, $(LOCAL_RESOURCE_DIR)))))
+
+LOCAL_RESOURCE_DIR := $(package_resource_overlays) $(LOCAL_RESOURCE_DIR)
 
 all_assets := $(call find-subdir-assets,$(LOCAL_ASSET_DIR))
 all_assets := $(addprefix $(LOCAL_ASSET_DIR)/,$(patsubst assets/%,%,$(all_assets)))
@@ -171,7 +179,7 @@
   LOCAL_SDK_RES_VERSION:=$(LOCAL_SDK_VERSION)
 endif
 
-full_android_manifest := $(LOCAL_PATH)/$(LOCAL_MANIFEST_FILE)
+full_android_manifest := $(LOCAL_FULL_MANIFEST_FILE)
 $(LOCAL_INTERMEDIATE_TARGETS): \
     PRIVATE_ANDROID_MANIFEST := $(full_android_manifest)
 ifneq (,$(filter-out current, $(LOCAL_SDK_VERSION)))
@@ -261,7 +269,7 @@
 # Most packages should link against the resources defined by framework-res.
 # Even if they don't have their own resources, they may use framework
 # resources.
-ifneq ($(filter-out current,$(LOCAL_SDK_RES_VERSION)),)
+ifneq ($(filter-out current,$(LOCAL_SDK_RES_VERSION))$(if $(TARGET_BUILD_APPS),$(filter current,$(LOCAL_SDK_RES_VERSION))),)
 # for released sdk versions, the platform resources were built into android.jar.
 framework_res_package_export := \
     $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_RES_VERSION)/android.jar
@@ -393,6 +401,9 @@
 # Save information about this package
 PACKAGES.$(LOCAL_PACKAGE_NAME).OVERRIDES := $(strip $(LOCAL_OVERRIDES_PACKAGES))
 PACKAGES.$(LOCAL_PACKAGE_NAME).RESOURCE_FILES := $(all_resources)
+ifdef package_resource_overlays
+PACKAGES.$(LOCAL_PACKAGE_NAME).RESOURCE_OVERLAYS := $(package_resource_overlays)
+endif
 
 PACKAGES := $(PACKAGES) $(LOCAL_PACKAGE_NAME)
 
diff --git a/core/pathmap.mk b/core/pathmap.mk
index 6b84418..91a7fd4 100644
--- a/core/pathmap.mk
+++ b/core/pathmap.mk
@@ -31,9 +31,11 @@
     bluez:external/bluetooth/bluez \
     glib:external/bluetooth/glib \
     bootloader:bootable/bootloader/legacy/include \
+    camera:system/media/camera/include \
     corecg:external/skia/include/core \
     dbus:external/dbus \
     frameworks-base:frameworks/base/include \
+    frameworks-native:frameworks/native/include \
     graphics:external/skia/include/core \
     libc:bionic/libc/include \
     libdrm1:frameworks/base/media/libdrm/mobile1/include \
@@ -41,16 +43,19 @@
     libhardware_legacy:hardware/libhardware_legacy/include \
     libhost:build/libs/host/include \
     libm:bionic/libm/include \
-    libnativehelper:dalvik/libnativehelper/include \
+    libnativehelper:libnativehelper/include \
     libpagemap:system/extras/libpagemap/include \
     libril:hardware/ril/include \
     libstdc++:bionic/libstdc++/include \
     libthread_db:bionic/libthread_db/include \
     mkbootimg:system/core/mkbootimg \
+    opengl-tests-includes:frameworks/native/opengl/tests/include \
     recovery:bootable/recovery \
     system-core:system/core/include \
-    wilhelm:system/media/wilhelm/include \
-    wilhelm-ut:system/media/wilhelm/src/ut \
+    audio-effects:system/media/audio_effects/include \
+    audio-utils:system/media/audio_utils/include \
+    wilhelm:frameworks/wilhelm/include \
+    wilhelm-ut:frameworks/wilhelm/src/ut \
     speex:external/speex/include
 
 #
@@ -85,6 +90,9 @@
 	    graphics \
 	    location \
 	    media \
+	    media/mca/effect \
+	    media/mca/filterfw \
+	    media/mca/filterpacks \
 	    drm \
 	    opengl \
 	    sax \
diff --git a/core/pdk_config.mk b/core/pdk_config.mk
new file mode 100644
index 0000000..492a9c4
--- /dev/null
+++ b/core/pdk_config.mk
@@ -0,0 +1,137 @@
+# This file defines the rule to fuse the platform.zip into the current PDK build.
+
+.PHONY: pdk fusion
+pdk fusion: $(DEFAULT_GOAL)
+
+# What to build:
+# pdk fusion if:
+# 1) the platform.zip exists in the default location
+# or
+# 2) PDK_FUSION_PLATFORM_ZIP is passed in from the environment
+# or
+# 3) fusion is a command line build goal,
+#    PDK_FUSION_PLATFORM_ZIP is needed anyway, then do we need the 'fusion' goal?
+# otherwise pdk only if:
+# 1) pdk is a command line build goal
+# or
+# 2) TARGET_BUILD_PDK is passed in from the environment
+
+# TODO: what's the best default location?
+_pdk_fusion_default_platform_zip := vendor/pdk/$(TARGET_DEVICE)/$(TARGET_PRODUCT)-$(TARGET_BUILD_VARIANT)/platform/platform.zip
+ifneq (,$(wildcard $(_pdk_fusion_default_platform_zip)))
+$(info $(_pdk_fusion_default_platform_zip) found, do a PDK fusion build.)
+PDK_FUSION_PLATFORM_ZIP := $(_pdk_fusion_default_platform_zip)
+TARGET_BUILD_PDK := true
+endif
+
+ifneq (,$(filter pdk fusion, $(MAKECMDGOALS)))
+TARGET_BUILD_PDK := true
+ifneq (,$(filter fusion, $(MAKECMDGOALS)))
+ifndef PDK_FUSION_PLATFORM_ZIP
+  $(error Specify PDK_FUSION_PLATFORM_ZIP to do a PDK fusion.)
+endif
+endif  # fusion
+endif  # pdk or fusion
+
+
+# additional items to add to platform.zip for platform-java build
+# For these dirs, add classes.jar and javalib.jar from the dir to platform.zip
+# all paths under out dir
+PDK_PLATFORM_JAVA_ZIP_JAVA_LIB_DIR := \
+	target/common/obj/JAVA_LIBRARIES/android_stubs_current_intermediates \
+	target/common/obj/JAVA_LIBRARIES/core_intermediates \
+	target/common/obj/JAVA_LIBRARIES/core-junit_intermediates \
+	target/common/obj/JAVA_LIBRARIES/ext_intermediates \
+	target/common/obj/JAVA_LIBRARIES/framework_intermediates \
+	target/common/obj/JAVA_LIBRARIES/android.test.runner_intermediates
+# not java libraries
+PDK_PLATFORM_JAVA_ZIP_CONTENTS := \
+	target/common/obj/APPS/framework-res_intermediates/package-export.apk \
+	target/common/obj/APPS/framework-res_intermediates/src/R.stamp
+PDK_PLATFORM_JAVA_ZIP_CONTENTS += $(foreach lib_dir,$(PDK_PLATFORM_JAVA_ZIP_JAVA_LIB_DIR),\
+    $(lib_dir)/classes.jar $(lib_dir)/javalib.jar)
+
+
+ifdef PDK_FUSION_PLATFORM_ZIP
+TARGET_BUILD_PDK := true
+ifeq (,$(wildcard $(PDK_FUSION_PLATFORM_ZIP)))
+  $(error Cannot find file $(PDK_FUSION_PLATFORM_ZIP).)
+endif
+
+_pdk_fusion_intermediates := $(call intermediates-dir-for, PACKAGING, pdk_fusion)
+_pdk_fusion_stamp := $(_pdk_fusion_intermediates)/pdk_fusion.stamp
+
+_pdk_fusion_file_list := $(shell unzip -Z -1 $(PDK_FUSION_PLATFORM_ZIP) \
+    '*[^/]' -x 'target/common/*' 2>/dev/null)
+_pdk_fusion_java_file_list := \
+	$(shell unzip -Z -1 $(PDK_FUSION_PLATFORM_ZIP) 'target/common/*' 2>/dev/null)
+_pdk_fusion_files := $(addprefix $(_pdk_fusion_intermediates)/,\
+    $(_pdk_fusion_file_list) $(_pdk_fusion_java_file_list))
+ifneq ($(_pdk_fusion_java_file_list),)
+TARGET_BUILD_PDK_JAVA := true
+endif
+
+$(_pdk_fusion_stamp) : $(PDK_FUSION_PLATFORM_ZIP)
+	@echo "Unzip $(dir $@) <- $<"
+	$(hide) rm -rf $(dir $@) && mkdir -p $(dir $@)
+	$(hide) unzip -qo $< -d $(dir $@)
+	$(call split-long-arguments,-touch,$(_pdk_fusion_files))
+	$(hide) touch $@
+
+
+$(_pdk_fusion_files) : $(_pdk_fusion_stamp)
+
+
+# Implicit pattern rules to copy the fusion files to the system image directory.
+# Note that if there is already explicit rule in the build system to generate a file,
+# the pattern rule will be just ignored by make.
+# That's desired by us: we want only absent files from the platform zip package.
+# Copy with the last-modified time preserved, never follow symbolic links.
+$(PRODUCT_OUT)/% : $(_pdk_fusion_intermediates)/% $(_pdk_fusion_stamp)
+	@mkdir -p $(dir $@)
+	$(hide) cp -fpPR $< $@
+
+ifeq (true,$(TARGET_BUILD_PDK_JAVA))
+
+define JAVA_dependency_template
+$(OUT_DIR)/$(strip $(1)): $(_pdk_fusion_intermediates)/$(strip $(1)) $(OUT_DIR)/$(strip $(2)) \
+  $(_pdk_fusion_stamp)
+	@mkdir -p $$(dir $$@)
+	$(hide) cp -fpPR $$< $$@
+endef
+
+# needs explicit dependency as package-export.apk is not explicitly pulled
+$(eval $(call JAVA_dependency_template,\
+target/common/obj/APPS/framework-res_intermediates/src/R.stamp,\
+target/common/obj/APPS/framework-res_intermediates/package-export.apk))
+
+# javalib.jar should pull classes.jar as classes.jar is not explicitly pulled.
+$(foreach lib_dir,$(PDK_PLATFORM_JAVA_ZIP_JAVA_LIB_DIR),\
+$(eval $(call JAVA_dependency_template,$(lib_dir)/javalib.jar,\
+$(lib_dir)/classes.jar)))
+
+# implicit rules for all others
+$(TARGET_COMMON_OUT_ROOT)/% : $(_pdk_fusion_intermediates)/target/common/% $(_pdk_fusion_stamp)
+	@mkdir -p $(dir $@)
+	$(hide) cp -fpPR $< $@
+endif
+
+ALL_PDK_FUSION_FILES := $(addprefix $(PRODUCT_OUT)/, $(_pdk_fusion_file_list))
+
+endif # PDK_FUSION_PLATFORM_ZIP
+
+ifeq ($(TARGET_BUILD_PDK),true)
+
+ifeq ($(TARGET_BUILD_PDK_JAVA),)
+
+# SDK used for Java build under PDK
+PDK_BUILD_SDK_VERSION := $(lastword $(TARGET_AVAILABLE_SDK_VERSIONS))
+$(info PDK Build uses SDK $(PDK_BUILD_SDK_VERSION))
+
+else # PDK_JAVA
+
+$(info PDK Build uses the current platform API)
+
+endif # PDK_JAVA
+
+endif # BUILD_PDK
diff --git a/core/phony_package.mk b/core/phony_package.mk
index 3644db8..70b6aac 100644
--- a/core/phony_package.mk
+++ b/core/phony_package.mk
@@ -2,10 +2,6 @@
 $(error LOCAL_SRC_FILES are not allowed for phony packages)
 endif
 
-ifeq ($(strip $(LOCAL_REQUIRED_MODULES)),)
-$(error LOCAL_REQUIRED_MODULES is required for phony packages)
-endif
-
 LOCAL_MODULE_CLASS := FAKE
 LOCAL_MODULE_SUFFIX := -timestamp
 
diff --git a/core/post_clean.mk b/core/post_clean.mk
new file mode 100644
index 0000000..213c43c
--- /dev/null
+++ b/core/post_clean.mk
@@ -0,0 +1,53 @@
+# Copyright (C) 2012 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.
+
+# Clean steps that need global knowledge of individual modules.
+# This file must be included after all Android.mks have been loaded.
+
+# Checks the current build configurations against the previous build,
+# clean artifacts in TARGET_COMMON_OUT_ROOT if necessary.
+# If a package's resource overlay has been changed, its R class needs to be
+# regenerated.
+previous_package_overlay_config := $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS/previous_overlays.txt
+current_package_overlay_config := $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS/current_overlays.txt
+current_all_packages_config := $(dir $(current_package_overlay_config))current_packages.txt
+
+$(shell rm -rf $(current_package_overlay_config) \
+    && mkdir -p $(dir $(current_package_overlay_config)) \
+    && touch $(current_package_overlay_config))
+$(shell echo '$(PACKAGES)' > $(current_all_packages_config))
+$(foreach p, $(PACKAGES), $(if $(PACKAGES.$(p).RESOURCE_OVERLAYS), \
+  $(shell echo '$(p)' '$(PACKAGES.$(p).RESOURCE_OVERLAYS)' >> $(current_package_overlay_config))))
+
+ifneq (,$(wildcard $(previous_package_overlay_config)))
+packages_overlay_changed := $(shell build/tools/diff_package_overlays.py \
+    $(current_all_packages_config) $(current_package_overlay_config) \
+    $(previous_package_overlay_config))
+ifneq (,$(packages_overlay_changed))
+overlay_cleanup_cmd := $(strip rm -rf $(foreach p, $(packages_overlay_changed),\
+    $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS/$(p)_intermediates))
+$(info *** Overlay change detected, clean shared intermediate files...)
+$(info *** $(overlay_cleanup_cmd))
+$(shell $(overlay_cleanup_cmd))
+overlay_cleanup_cmd :=
+endif
+packages_overlay_changed :=
+endif
+
+# Now current becomes previous.
+$(shell mv -f $(current_package_overlay_config) $(previous_package_overlay_config))
+
+previous_package_overlay_config :=
+current_package_overlay_config :=
+current_all_packages_config :=
diff --git a/core/prebuilt.mk b/core/prebuilt.mk
index 54a7fa9..b06bb6e 100644
--- a/core/prebuilt.mk
+++ b/core/prebuilt.mk
@@ -27,6 +27,14 @@
   OVERRIDE_BUILT_MODULE_PATH := $($(my_prefix)OUT_INTERMEDIATE_LIBRARIES)
 endif
 
+# Deal with the OSX library timestamp issue when installing
+# a prebuilt simulator library.
+ifneq ($(filter STATIC_LIBRARIES SHARED_LIBRARIES,$(LOCAL_MODULE_CLASS)),)
+  prebuilt_module_is_a_library := true
+else
+  prebuilt_module_is_a_library :=
+endif
+
 ifeq ($(LOCAL_STRIP_MODULE),true)
   ifdef LOCAL_IS_HOST_MODULE
     $(error Cannot strip host module LOCAL_PATH=$(LOCAL_PATH))
@@ -42,14 +50,15 @@
 else
   include $(BUILD_SYSTEM)/base_rules.mk
   built_module := $(LOCAL_BUILT_MODULE)
-endif
 
-# Deal with the OSX library timestamp issue when installing
-# a prebuilt simulator library.
-ifneq ($(filter STATIC_LIBRARIES SHARED_LIBRARIES,$(LOCAL_MODULE_CLASS)),)
-  prebuilt_module_is_a_library := true
-else
-  prebuilt_module_is_a_library :=
+ifdef prebuilt_module_is_a_library
+# Create a dummy export_includes.
+$(intermediates)/export_includes:
+	$(hide) mkdir -p $(dir $@) && rm -f $@
+	$(hide) touch $@
+
+$(LOCAL_BUILT_MODULE) : | $(intermediates)/export_includes
+endif
 endif
 
 PACKAGES.$(LOCAL_MODULE).OVERRIDES := $(strip $(LOCAL_OVERRIDES_PACKAGES))
@@ -115,6 +124,13 @@
 else
 $(built_module) : $(LOCAL_PATH)/$(LOCAL_SRC_FILES) | $(ACP)
 	$(transform-prebuilt-to-target)
+ifneq ($(prebuilt_module_is_a_library),)
+  ifneq ($(LOCAL_IS_HOST_MODULE),)
+	$(transform-host-ranlib-copy-hack)
+  else
+	$(transform-ranlib-copy-hack)
+  endif
+endif
 endif
 endif
 
@@ -135,11 +151,3 @@
 # make sure the classes.jar and javalib.jar are built before $(LOCAL_BUILT_MODULE)
 $(built_module) : $(common_javalib_jar)
 endif # TARGET JAVA_LIBRARIES
-
-ifneq ($(prebuilt_module_is_a_library),)
-  ifneq ($(LOCAL_IS_HOST_MODULE),)
-	$(transform-host-ranlib-copy-hack)
-  else
-	$(transform-ranlib-copy-hack)
-  endif
-endif
diff --git a/core/product.mk b/core/product.mk
index f48d2be..d9e4186 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -84,6 +84,9 @@
     PRODUCT_SDK_ADDON_DOC_MODULES \
     PRODUCT_DEFAULT_WIFI_CHANNELS \
     PRODUCT_DEFAULT_DEV_CERTIFICATE \
+    PRODUCT_RESTRICT_VENDOR_FILES \
+    PRODUCT_FACTORY_RAMDISK_MODULES \
+    PRODUCT_VENDOR_KERNEL_HEADERS \
 
 
 define dump-product
@@ -199,6 +202,9 @@
 	TARGET_ARCH_VARIANT \
 	TARGET_BOARD_PLATFORM \
 	TARGET_BOARD_PLATFORM_GPU \
+	TARGET_BOARD_KERNEL_HEADERS \
+	TARGET_DEVICE_KERNEL_HEADERS \
+	TARGET_PRODUCT_KERNEL_HEADERS \
 	TARGET_BOOTLOADER_BOARD_NAME \
 	TARGET_COMPRESS_MODULE_SYMBOLS \
 	TARGET_NO_BOOTLOADER \
@@ -227,6 +233,8 @@
 	BOARD_RECOVERYIMAGE_PARTITION_SIZE \
 	BOARD_SYSTEMIMAGE_PARTITION_SIZE \
 	BOARD_USERDATAIMAGE_PARTITION_SIZE \
+	BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE \
+	BOARD_CACHEIMAGE_PARTITION_SIZE \
 	BOARD_FLASH_BLOCK_SIZE \
 	BOARD_SYSTEMIMAGE_PARTITION_SIZE \
 	BOARD_VENDOR_QCOM_GPS_LOC_API_HARDWARE \
@@ -264,3 +272,7 @@
     $(eval $(error The following variables have been changed: $(changed_variables))),)
 )
 endef
+
+define add-to-product-copy-files-if-exists
+$(if $(wildcard $(word 1,$(subst :, ,$(1)))),$(1))
+endef
diff --git a/core/product_config.mk b/core/product_config.mk
index c455723..ea3e517 100644
--- a/core/product_config.mk
+++ b/core/product_config.mk
@@ -306,6 +306,10 @@
 # An list of whitespace-separated words.
 PRODUCT_TAGS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_TAGS))
 
+# The list of product-specific kernel header dirs
+PRODUCT_VENDOR_KERNEL_HEADERS := \
+    $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_KERNEL_HEADERS)
+
 # Add the product-defined properties to the build properties.
 ADDITIONAL_BUILD_PROPERTIES := \
     $(ADDITIONAL_BUILD_PROPERTIES) \
diff --git a/core/shared_library.mk b/core/shared_library.mk
index ca639eb..d715349 100644
--- a/core/shared_library.mk
+++ b/core/shared_library.mk
@@ -16,6 +16,9 @@
 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): Can not set module stem for a library)
+endif
 
 # Put the built targets of all shared libraries in a common directory
 # to simplify the link line.
diff --git a/core/static_java_library.mk b/core/static_java_library.mk
index 93d770a..367ea5f 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -21,5 +21,90 @@
 
 LOCAL_UNINSTALLABLE_MODULE := true
 LOCAL_IS_STATIC_JAVA_LIBRARY := true
+
+# Hack to build static Java library with Android resource
+# See bug 5714516
+all_resources :=
+ifdef LOCAL_RESOURCE_DIR
+all_resources := $(strip \
+    $(foreach dir, $(LOCAL_RESOURCE_DIR), \
+      $(addprefix $(dir)/, \
+        $(patsubst res/%,%, \
+          $(call find-subdir-assets,$(dir)) \
+        ) \
+      ) \
+    ))
+
+ifneq (,$(all_resources))
+# Those files will be excluded from the built jar.
+# The R/Manifest classes should be re-generated in the app Module instead.
+# Use '' and $ escape because they will be passed to bash.
+ifneq (true,$(LOCAL_KEEP_R_CLASS_IN_STATIC_JAVA_LIBRARY))
+LOCAL_JAR_EXCLUDE_FILES := 'R.class' 'R$$*.class' 'Manifest.class' 'Manifest$$*.class'
+endif
+endif
+endif
+
 include $(BUILD_SYSTEM)/java_library.mk
+
+ifneq (,$(all_resources))
+R_file_stamp := $(LOCAL_INTERMEDIATE_SOURCE_DIR)/R.stamp
+
+ifeq ($(strip $(LOCAL_MANIFEST_FILE)),)
+LOCAL_MANIFEST_FILE := AndroidManifest.xml
+endif
+full_android_manifest := $(LOCAL_PATH)/$(LOCAL_MANIFEST_FILE)
+
+LOCAL_SDK_RES_VERSION:=$(strip $(LOCAL_SDK_RES_VERSION))
+ifeq ($(LOCAL_SDK_RES_VERSION),)
+  LOCAL_SDK_RES_VERSION:=$(LOCAL_SDK_VERSION)
+endif
+
+framework_res_package_export :=
+framework_res_package_export_deps :=
+# Please refer to package.mk
+ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
+ifneq ($(filter-out current,$(LOCAL_SDK_RES_VERSION))$(if $(TARGET_BUILD_APPS),$(filter current,$(LOCAL_SDK_RES_VERSION))),)
+framework_res_package_export := \
+    $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_RES_VERSION)/android.jar
+framework_res_package_export_deps := $(framework_res_package_export)
+else
+framework_res_package_export := \
+    $(call intermediates-dir-for,APPS,framework-res,,COMMON)/package-export.apk
+framework_res_package_export_deps := \
+    $(dir $(framework_res_package_export))src/R.stamp
+endif
+endif
+
+$(R_file_stamp): PRIVATE_MODULE := $(LOCAL_MODULE)
+# add --non-constant-id to prevent inlining constants.
+$(R_file_stamp): PRIVATE_AAPT_FLAGS := $(LOCAL_AAPT_FLAGS) --non-constant-id
+$(R_file_stamp): PRIVATE_SOURCE_INTERMEDIATES_DIR := $(LOCAL_INTERMEDIATE_SOURCE_DIR)
+$(R_file_stamp): PRIVATE_ANDROID_MANIFEST := $(full_android_manifest)
+$(R_file_stamp): PRIVATE_RESOURCE_PUBLICS_OUTPUT := $(intermediates.COMMON)/public_resources.xml
+$(R_file_stamp): PRIVATE_RESOURCE_DIR := $(LOCAL_RESOURCE_DIR)
+$(R_file_stamp): PRIVATE_AAPT_INCLUDES := $(framework_res_package_export)
+ifneq (,$(filter-out current, $(LOCAL_SDK_VERSION)))
+$(R_file_stamp): PRIVATE_DEFAULT_APP_TARGET_SDK := $(LOCAL_SDK_VERSION)
+else
+$(R_file_stamp): PRIVATE_DEFAULT_APP_TARGET_SDK := $(DEFAULT_APP_TARGET_SDK)
+endif
+$(R_file_stamp): PRIVATE_ASSET_DIR :=
+$(R_file_stamp): PRIVATE_PROGUARD_OPTIONS_FILE :=
+$(R_file_stamp): PRIVATE_MANIFEST_PACKAGE_NAME :=
+$(R_file_stamp): PRIVATE_MANIFEST_INSTRUMENTATION_FOR :=
+
+$(R_file_stamp) : $(all_resources) $(full_android_manifest) $(AAPT) $(framework_res_package_export_deps)
+	@echo "target R.java/Manifest.java: $(PRIVATE_MODULE) ($@)"
+	$(create-resource-java-files)
+	$(hide) find $(PRIVATE_SOURCE_INTERMEDIATES_DIR) -name R.java | xargs cat > $@
+
+$(LOCAL_BUILT_MODULE): $(R_file_stamp)
+ifneq ($(full_classes_jar),)
+$(full_classes_compiled_jar): $(R_file_stamp)
+endif
+
+endif  # $(all_resources) not empty
+
 LOCAL_IS_STATIC_JAVA_LIBRARY :=
+LOCAL_JAR_EXCLUDE_FILES :=
diff --git a/core/static_library.mk b/core/static_library.mk
index 4ff5a34..66e091b 100644
--- a/core/static_library.mk
+++ b/core/static_library.mk
@@ -14,6 +14,9 @@
 LOCAL_MODULE_SUFFIX := .a
 endif
 LOCAL_UNINSTALLABLE_MODULE := true
+ifneq ($(strip $(LOCAL_MODULE_STEM)$(LOCAL_BUILT_MODULE_STEM)),)
+$(error $(LOCAL_PATH): Can not set module stem for a library)
+endif
 
 include $(BUILD_SYSTEM)/binary.mk
 
diff --git a/core/tasks/apicheck.mk b/core/tasks/apicheck.mk
index 96e0f44..8d9928e 100644
--- a/core/tasks/apicheck.mk
+++ b/core/tasks/apicheck.mk
@@ -17,7 +17,8 @@
 # api compatibility or added apis illegally.
 #
 
-ifneq ($(BUILD_TINY_ANDROID), true)
+# skip api check for TINY_ANDROID and PDK buid
+ifeq (,$(filter true, $(BUILD_TINY_ANDROID) $(TARGET_BUILD_PDK)))
 
 .PHONY: checkapi
 
diff --git a/core/tasks/collect_gpl_sources.mk b/core/tasks/collect_gpl_sources.mk
new file mode 100644
index 0000000..3c7afcc
--- /dev/null
+++ b/core/tasks/collect_gpl_sources.mk
@@ -0,0 +1,30 @@
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+gpl_source_tgz := $(call intermediates-dir-for,PACKAGING,gpl_source,HOST,COMMON)/gpl_source.tgz
+
+$(gpl_source_tgz): PRIVATE_PATHS := $(sort $(patsubst %/, %, $(dir $(ALL_GPL_MODULE_LICENSE_FILES))))
+$(gpl_source_tgz) : $(ALL_GPL_MODULE_LICENSE_FILES)
+	@echo Package gpl sources: $@
+	@rm -rf $(dir $@) && mkdir -p $(dir $@)
+	$(hide) tar cfz $@ --exclude ".git*" $(PRIVATE_PATHS)
+
+
+.PHONY: gpl_source_tgz
+gpl_source_tgz : $(gpl_source_tgz)
+
+# Dist the tgz only if we are doing a full build
+ifeq (,$(TARGET_BUILD_APPS))
+$(call dist-for-goals, droidcore, $(gpl_source_tgz))
+endif
diff --git a/core/tasks/cts.mk b/core/tasks/cts.mk
index 45dcd0f..4f624d8 100644
--- a/core/tasks/cts.mk
+++ b/core/tasks/cts.mk
@@ -25,6 +25,9 @@
 CTS_TF_EXEC_PATH := $(HOST_OUT_EXECUTABLES)/cts-tradefed
 CTS_TF_README_PATH := $(cts_tools_src_dir)/tradefed-host/README
 
+VMTESTSTF_INTERMEDIATES :=$(call intermediates-dir-for,EXECUTABLES,vm-tests-tf,1,)
+VMTESTSTF_JAR := $(VMTESTSTF_INTERMEDIATES)/android.core.vm-tests-tf.jar
+
 CTS_CORE_CASE_LIST := \
 	android.core.tests.libcore.package.dalvik \
 	android.core.tests.libcore.package.com \
@@ -34,6 +37,10 @@
 	android.core.tests.libcore.package.libcore \
 	android.core.tests.runner
 
+# 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)
+
 -include cts/CtsTestCaseList.mk
 CTS_CASE_LIST := $(CTS_CORE_CASE_LIST) $(CTS_TEST_CASE_LIST)
 
@@ -41,8 +48,7 @@
 
 $(cts_dir)/all_cts_files_stamp: PRIVATE_JUNIT_HOST_JAR := $(junit_host_jar)
 
--include cts/CtsHostLibraryList.mk
-$(cts_dir)/all_cts_files_stamp: $(CTS_CASE_LIST) $(CTS_TEST_CASES) $(junit_host_jar) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(ACP)
+$(cts_dir)/all_cts_files_stamp: $(CTS_CORE_CASES) $(CTS_TEST_CASES) $(CTS_TEST_CASE_LIST) $(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)
 # Make necessary directory for CTS
 	$(hide) rm -rf $(PRIVATE_CTS_DIR)
 	$(hide) mkdir -p $(TMP_DIR)
@@ -51,6 +57,7 @@
 	$(hide) mkdir -p $(PRIVATE_DIR)/repository/testcases
 	$(hide) mkdir -p $(PRIVATE_DIR)/repository/plans
 # Copy executable and JARs to CTS directory
+	$(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 apk,$(CTS_CASE_LIST),$(call copy-testcase-apk,$(apk)))
@@ -81,96 +88,72 @@
 
 GEN_CLASSPATH := $(CORE_INTERMEDIATES)/classes.jar:$(BOUNCYCASTLE_INTERMEDIATES)/classes.jar:$(APACHEXML_INTERMEDIATES)/classes.jar:$(JUNIT_INTERMEDIATES)/classes.jar:$(SQLITEJDBC_INTERMEDIATES)/javalib.jar:$(CORETESTS_INTERMEDIATES)/javalib.jar
 
-$(cts_dir)/all_cts_core_files_stamp: PRIVATE_CLASSPATH:=$(GEN_CLASSPATH)
+CTS_CORE_XMLS := \
+	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.dalvik.xml \
+	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.com.xml \
+	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.sun.xml \
+	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.tests.xml \
+	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.org.xml \
+	$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.libcore.xml
+
+$(CTS_CORE_XMLS): PRIVATE_CLASSPATH:=$(GEN_CLASSPATH)
 # Why does this depend on javalib.jar instead of classes.jar?  Because
 # even though the tool will operate on the classes.jar files, the
 # 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_dir)/all_cts_core_files_stamp: $(CTS_CORE_CASE_LIST) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(CORE_INTERMEDIATES)/javalib.jar $(BOUNCYCASTLE_INTERMEDIATES)/javalib.jar $(APACHEXML_INTERMEDIATES)/javalib.jar $(SQLITEJDBC_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(CORETESTS_INTERMEDIATES)/javalib.jar $(cts_dir)/all_cts_files_stamp | $(ACP)
-	$(call generate-core-test-description,$(cts_dir)/$(cts_name)/repository/testcases/android.core.tests.libcore.package.dalvik,\
+$(CTS_CORE_XMLS): $(CTS_CORE_CASES) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(CORE_INTERMEDIATES)/javalib.jar $(BOUNCYCASTLE_INTERMEDIATES)/javalib.jar $(APACHEXML_INTERMEDIATES)/javalib.jar $(SQLITEJDBC_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(CORETESTS_INTERMEDIATES)/javalib.jar | $(ACP)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
+	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.dalvik,\
 		cts/tests/core/libcore/dalvik/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,dalvik,\
 		libcore/expectations)
-	$(call generate-core-test-description,$(cts_dir)/$(cts_name)/repository/testcases/android.core.tests.libcore.package.com,\
+	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.com,\
 		cts/tests/core/libcore/com/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,com,\
 		libcore/expectations)
-	$(call generate-core-test-description,$(cts_dir)/$(cts_name)/repository/testcases/android.core.tests.libcore.package.sun,\
+	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.sun,\
 		cts/tests/core/libcore/sun/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,sun,\
 		libcore/expectations)
-	$(call generate-core-test-description,$(cts_dir)/$(cts_name)/repository/testcases/android.core.tests.libcore.package.tests,\
+	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.tests,\
 		cts/tests/core/libcore/tests/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,tests,\
 		libcore/expectations)
-	$(call generate-core-test-description,$(cts_dir)/$(cts_name)/repository/testcases/android.core.tests.libcore.package.org,\
+	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.org,\
 		cts/tests/core/libcore/org/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,org,\
 		libcore/expectations)
-	$(call generate-core-test-description,$(cts_dir)/$(cts_name)/repository/testcases/android.core.tests.libcore.package.libcore,\
+	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.libcore,\
 		cts/tests/core/libcore/libcore/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,libcore,\
 		libcore/expectations)
-	$(hide) touch $@
-
-
-# ----- Generate the test descriptions for the vm-tests -----
-#  TODO: remove this section once cts-tf replaces cts.
-#
-CORE_VM_TEST_DESC := $(cts_dir)/$(cts_name)/repository/testcases/android.core.vm-tests
-
-VMTESTS_INTERMEDIATES :=$(call intermediates-dir-for,EXECUTABLES,vm-tests,1,)
-# core tests only needed to get hold of junit-framework-classes
-CORE_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core,,COMMON)
-JUNIT_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core-junit,,COMMON)
-
-GEN_CLASSPATH := $(CORE_INTERMEDIATES)/classes.jar:$(JUNIT_INTERMEDIATES)/classes.jar:$(VMTESTS_INTERMEDIATES)/android.core.vm-tests.jar:$(HOSTTESTLIB_JAR):$(DDMLIB_JAR)
-
-$(CORE_VM_TEST_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_DESC): vm-tests $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(CORE_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(VMTESTS_INTERMEDIATES)/android.core.vm-tests.jar $(HOSTTESTLIB_JAR) $(DDMLIB_JAR) $(cts_dir)/all_cts_files_stamp | $(ACP)
-	$(call generate-core-test-description,$(CORE_VM_TEST_DESC),\
-		cts/tests/vm-tests/AndroidManifest.xml,\
-		$(VMTESTS_INTERMEDIATES)/android.core.vm-tests.jar,"",\
-		libcore/expectations,\
-		cts/tools/vm-tests/Android.mk)
-	$(ACP) -fv $(VMTESTS_INTERMEDIATES)/android.core.vm-tests.jar $(PRIVATE_DIR)/repository/testcases/android.core.vm-tests.jar
 
 # ----- Generate the test descriptions for the vm-tests-tf -----
 #
-CORE_VM_TEST_TF_DESC := $(cts_dir)/$(cts_name)/repository/testcases/android.core.vm-tests-tf
+CORE_VM_TEST_TF_DESC := $(CTS_TESTCASES_OUT)/android.core.vm-tests-tf.xml
 
-VMTESTSTF_INTERMEDIATES :=$(call intermediates-dir-for,EXECUTABLES,vm-tests-tf,1,)
 # core tests only needed to get hold of junit-framework-classes
 CORE_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core,,COMMON)
 JUNIT_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,core-junit,,COMMON)
 
-GEN_CLASSPATH := $(CORE_INTERMEDIATES)/classes.jar:$(JUNIT_INTERMEDIATES)/classes.jar:$(VMTESTSTF_INTERMEDIATES)/android.core.vm-tests-tf.jar:$(DDMLIB_JAR):$(TF_JAR)
+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 $(CORE_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(VMTESTSTF_INTERMEDIATES)/android.core.vm-tests-tf.jar $(DDMLIB_JAR) $(cts_dir)/all_cts_files_stamp | $(ACP)
-	$(call generate-core-test-description,$(CORE_VM_TEST_TF_DESC),\
+$(CORE_VM_TEST_TF_DESC): $(HOST_OUT_JAVA_LIBRARIES)/descGen.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,\
-		$(VMTESTSTF_INTERMEDIATES)/android.core.vm-tests-tf.jar,"",\
+		$(VMTESTSTF_JAR),"",\
 		libcore/expectations,\
 		cts/tools/vm-tests-tf/Android.mk)
-	$(ACP) -fv $(VMTESTSTF_INTERMEDIATES)/android.core.vm-tests-tf.jar $(PRIVATE_DIR)/repository/testcases/android.core.vm-tests-tf.jar
-
-
-# Move app security host-side tests to the repository
-APP_SECURITY_LIB := $(cts_dir)/$(cts_name)/repository/testcases/CtsAppSecurityTests.jar
-
-$(APP_SECURITY_LIB): $(HOST_OUT_JAVA_LIBRARIES)/CtsAppSecurityTests.jar $(cts_dir)/all_cts_files_stamp $(ACP)
-	$(ACP) -fv $(HOST_OUT_JAVA_LIBRARIES)/CtsAppSecurityTests.jar $(APP_SECURITY_LIB)
-
 
 # Generate the default test plan for User.
 # Usage: buildCts.py <testRoot> <ctsOutputDir> <tempDir> <androidRootDir> <docletPath>
 
-$(DEFAULT_TEST_PLAN): $(cts_dir)/all_cts_files_stamp $(cts_dir)/all_cts_core_files_stamp $(cts_tools_src_dir)/utils/buildCts.py $(CORE_VM_TEST_TF_DESC) $(CORE_VM_TEST_DESC) $(APP_SECURITY_LIB) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(CTS_TEST_XMLS) | $(ACP)
-	$(hide) $(ACP) -fp $(CTS_TEST_XMLS) $(PRIVATE_DIR)/repository/testcases
+$(DEFAULT_TEST_PLAN): $(cts_dir)/all_cts_files_stamp $(cts_tools_src_dir)/utils/buildCts.py $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(CTS_CORE_XMLS) $(CTS_TEST_XMLS) $(CORE_VM_TEST_TF_DESC) | $(ACP)
+	$(hide) $(ACP) -fp $(CTS_CORE_XMLS) $(CTS_TEST_XMLS) $(CORE_VM_TEST_TF_DESC) $(PRIVATE_DIR)/repository/testcases
 	$(hide) $(cts_tools_src_dir)/utils/buildCts.py cts/tests/tests/ $(PRIVATE_DIR) $(TMP_DIR) \
 		$(TOP) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar
 
@@ -183,7 +166,7 @@
 $(INTERNAL_CTS_TARGET): PRIVATE_CTS_DIR := $(cts_dir)
 $(INTERNAL_CTS_TARGET): PRIVATE_DIR := $(cts_dir)/$(cts_name)
 $(INTERNAL_CTS_TARGET): TMP_DIR := $(cts_dir)/temp
-$(INTERNAL_CTS_TARGET): $(cts_dir)/all_cts_files_stamp $(DEFAULT_TEST_PLAN) $(CORE_VM_TEST_DESC)
+$(INTERNAL_CTS_TARGET): $(cts_dir)/all_cts_files_stamp $(DEFAULT_TEST_PLAN)
 	$(hide) echo "Package CTS: $@"
 	$(hide) cd $(dir $@) && zip -rq $(notdir $@) $(PRIVATE_NAME)
 
diff --git a/core/tasks/factory_ramdisk.mk b/core/tasks/factory_ramdisk.mk
new file mode 100644
index 0000000..576a159
--- /dev/null
+++ b/core/tasks/factory_ramdisk.mk
@@ -0,0 +1,90 @@
+#
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+ifeq (,$(ONE_SHOT_MAKEFILE))
+
+# PRODUCT_FACTORY_RAMDISK_MODULES consists of "<module_name>:<install_path>[:<install_path>...]" tuples.
+# <install_path> is relative to TARGET_FACTORY_RAMDISK_OUT.
+# We can have multiple <install_path>s because multiple modules may have the same name.
+# For example:
+# PRODUCT_FACTORY_RAMDISK_MODULES := \
+#     toolbox:system/bin/toolbox adbd:sbin/adbd adb:system/bin/adb
+factory_ramdisk_modules := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_FACTORY_RAMDISK_MODULES))
+ifneq (,$(factory_ramdisk_modules))
+
+# A module name may end up in multiple modules (so multiple built files)
+# with the same name.
+# This function selects the module built file based on the install path.
+# $(1): the dest install path
+# $(2): the module built files
+define install-one-factory-ramdisk-module
+$(eval _iofrm_suffix := $(suffix $(1))) \
+$(if $(_iofrm_suffix), \
+    $(eval _iofrm_pattern := %$(_iofrm_suffix)), \
+    $(eval _iofrm_pattern := %$(notdir $(1)))) \
+$(eval _iofrm_src := $(filter $(_iofrm_pattern),$(2))) \
+$(if $(filter 1,$(words $(_iofrm_src))), \
+    $(eval _fulldest := $(TARGET_FACTORY_RAMDISK_OUT)/$(1)) \
+    $(eval $(call copy-one-file,$(_iofrm_src),$(_fulldest))) \
+    $(eval INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES += $(_fulldest)), \
+    $(error Error: Can not find match in "$(2)" for "$(1)") \
+    )
+endef
+
+INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES :=
+$(foreach m, $(factory_ramdisk_modules), \
+    $(eval _fr_m_tuple := $(subst :, ,$(m))) \
+    $(eval _fr_m_name := $(word 1,$(_fr_m_tuple))) \
+    $(eval _fr_dests := $(wordlist 2,999,$(_fr_m_tuple))) \
+    $(eval _fr_m_built := $(filter $(PRODUCT_OUT)/%, $(ALL_MODULES.$(_fr_m_name).BUILT))) \
+    $(foreach d,$(_fr_dests),$(call install-one-factory-ramdisk-module,$(d),$(_fr_m_built))) \
+    )
+endif
+
+# Files may also be installed via PRODUCT_COPY_FILES, PRODUCT_PACKAGES etc.
+INTERNAL_FACTORY_RAMDISK_FILES := $(filter $(TARGET_FACTORY_RAMDISK_OUT)/%, \
+    $(ALL_DEFAULT_INSTALLED_MODULES))
+
+ifneq (,$(INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES)$(INTERNAL_FACTORY_RAMDISK_FILES))
+
+# These files are made by magic in build/core/Makefile so we need to explicitly include them
+$(eval $(call copy-one-file,$(TARGET_OUT)/build.prop,$(TARGET_FACTORY_RAMDISK_OUT)/system/build.prop))
+INTERNAL_FACTORY_RAMDISK_FILES += $(TARGET_FACTORY_RAMDISK_OUT)/system/build.prop
+
+BUILT_FACTORY_RAMDISK_FS := $(PRODUCT_OUT)/factory_ramdisk.gz
+BUILT_FACTORY_RAMDISK_TARGET := $(PRODUCT_OUT)/factory_ramdisk.img
+
+INSTALLED_FACTORY_RAMDISK_FS := $(BUILT_FACTORY_RAMDISK_FS)
+$(INSTALLED_FACTORY_RAMDISK_FS) : $(MKBOOTFS) \
+    $(INTERNAL_FACTORY_RAMDISK_EXTRA_MODULES_FILES) $(INTERNAL_FACTORY_RAMDISK_FILES) | $(MINIGZIP)
+	$(call pretty,"Target factory ram disk file system: $@")
+	$(hide) $(MKBOOTFS) $(TARGET_FACTORY_RAMDISK_OUT) | $(MINIGZIP) > $@
+
+TARGET_RAMDISK_KERNEL := $(INSTALLED_KERNEL_TARGET)
+INSTALLED_FACTORY_RAMDISK_TARGET := $(BUILT_FACTORY_RAMDISK_TARGET)
+ifneq (,$(BOARD_KERNEL_CMDLINE_FACTORY_BOOT))
+  RAMDISK_CMDLINE := --cmdline "$(BOARD_KERNEL_CMDLINE_FACTORY_BOOT)"
+else
+  RAMDISK_CMDLINE :=
+endif
+$(INSTALLED_FACTORY_RAMDISK_TARGET) : $(MKBOOTIMG) $(TARGET_RAMDISK_KERNEL) $(INSTALLED_FACTORY_RAMDISK_FS)
+	$(call pretty,"Target factory ram disk img format: $@")
+	$(MKBOOTIMG) --kernel $(TARGET_RAMDISK_KERNEL) --ramdisk $(INSTALLED_FACTORY_RAMDISK_FS) \
+            --base $(BOARD_KERNEL_BASE) $(RAMDISK_CMDLINE) --output $@
+
+endif
+
+endif # ONE_SHOT_MAKEFILE
diff --git a/core/tasks/vendor_module_check.mk b/core/tasks/vendor_module_check.mk
new file mode 100644
index 0000000..f492468
--- /dev/null
+++ b/core/tasks/vendor_module_check.mk
@@ -0,0 +1,73 @@
+#
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Restrict the vendor module owners here.
+_vendor_owner_whitelist := \
+        asus \
+	audience \
+	broadcom \
+	csr \
+        elan \
+	imgtec \
+	invensense \
+        nvidia \
+	nxp \
+	samsung \
+	samsung_arm \
+	ti \
+	widevine
+
+
+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))
+
+# Restrict owners
+ifneq (,$(filter true owner all, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_RESTRICT_VENDOR_FILES)))
+
+ifneq (,$(filter vendor/%, $(PRODUCT_PACKAGE_OVERLAYS) $(DEVICE_PACKAGE_OVERLAYS)))
+$(error Error: Product "$(TARGET_PRODUCT)" can not have overlay in vendor tree: \
+    $(filter vendor/%, $(PRODUCT_PACKAGE_OVERLAYS) $(DEVICE_PACKAGE_OVERLAYS)))
+endif
+ifneq (,$(filter vendor/%, $(PRODUCT_COPY_FILES)))
+$(error Error: Product "$(TARGET_PRODUCT)" can not have PRODUCT_COPY_FILES from vendor tree: \
+    $(filter vendor/%, $(PRODUCT_COPY_FILES)))
+endif
+
+$(foreach m, $(_vendor_check_modules), \
+  $(if $(filter vendor/%, $(ALL_MODULES.$(m).PATH)),\
+    $(if $(filter $(_vendor_owner_whitelist), $(ALL_MODULES.$(m).OWNER)),,\
+      $(error Error: vendor module "$(m)" in $(ALL_MODULES.$(m).PATH) with unknown owner \
+        "$(ALL_MODULES.$(m).OWNER)" in product "$(TARGET_PRODUCT)"))))
+
+endif
+
+
+# Restrict paths
+ifneq (,$(filter path all, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_RESTRICT_VENDOR_FILES)))
+
+$(foreach m, $(_vendor_check_modules), \
+  $(if $(filter vendor/%, $(ALL_MODULES.$(m).PATH)),\
+    $(if $(filter $(TARGET_OUT_VENDOR)/%, $(ALL_MODULES.$(m).INSTALLED)),,\
+      $(error Error: vendor module "$(m)" in $(ALL_MODULES.$(m).PATH) \
+        in product "$(TARGET_PRODUCT)" being installed to \
+        $(ALL_MODULES.$(m).INSTALLED) which is not in the vendor tree))))
+
+endif
+
+_vendor_check_modules :=
+endif
diff --git a/core/user_tags.mk b/core/user_tags.mk
index b88e541..ca2594b 100644
--- a/core/user_tags.mk
+++ b/core/user_tags.mk
@@ -50,7 +50,6 @@
 	applypatch \
 	app_process \
 	archquery \
-	asm-3.1 \
 	atree \
 	audio \
 	badblocks \
@@ -72,6 +71,7 @@
 	com.android.phone.common \
 	com.android.vcard \
 	commons-compress-1.0 \
+	content \
 	copybit.qsd8k \
 	copybit.s5pc110 \
 	coverage \
@@ -164,7 +164,6 @@
 	jsr305lib \
 	junit \
 	jython \
-	keystore \
 	kxml2-2.3.0 \
 	launch-wrapper \
 	layoutlib \
@@ -444,7 +443,6 @@
 	resize2fs \
 	resize2fs_host \
 	rgb2565 \
-	rild \
 	rsg-generator \
 	run-as \
 	runtime \
@@ -471,7 +469,6 @@
 	sig-create \
 	signapk \
 	signature-tools \
-	simg2img \
 	spec-progress \
 	sqlite3 \
 	stack_dump \
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index 274a15a..02ac42c 100644
--- a/core/version_defaults.mk
+++ b/core/version_defaults.mk
@@ -41,7 +41,7 @@
   # which is the version that we reveal to the end user.
   # Update this value when the platform version changes (rather
   # than overriding it somewhere else).  Can be an arbitrary string.
-  PLATFORM_VERSION := 4.0.4.0.4.0.4
+  PLATFORM_VERSION := 4.0.9.99.999.9999.99999
 endif
 
 ifeq "" "$(PLATFORM_SDK_VERSION)"
diff --git a/envsetup.sh b/envsetup.sh
index 6ad4600..84ec3e5 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -1,4 +1,4 @@
-function help() {
+function hmm() {
 cat <<EOF
 Invoke ". build/envsetup.sh" from your shell to add the following functions to your environment:
 - croot:   Changes directory to the top of the tree.
@@ -116,25 +116,40 @@
 
     # The gcc toolchain does not exists for windows/cygwin. In this case, do not reference it.
     export ANDROID_EABI_TOOLCHAIN=
-    case $(get_build_var TARGET_ARCH) in
+    local ARCH=$(get_build_var TARGET_ARCH)
+    case $ARCH in
         x86) toolchaindir=x86/i686-linux-android-4.6/bin
             ;;
-        arm|*) toolchaindir=arm/arm-linux-androideabi-4.6/bin
+        arm) toolchaindir=arm/arm-linux-androideabi-4.6/bin
+            ;;
+        *)
+            echo "Can't find toolchain for unknown architecture: $ARCH"
+            toolchaindir=xxxxxxxxx
             ;;
     esac
-    if [ -d "$prebuiltdir/$toolchaindir" ]; then
-        export ANDROID_EABI_TOOLCHAIN=$prebuiltdir/$toolchaindir
+    if [ -d "$gccprebuiltdir/$toolchaindir" ]; then
+        export ANDROID_EABI_TOOLCHAIN=$gccprebuiltdir/$toolchaindir
     fi
 
     export ARM_EABI_TOOLCHAIN=
-    toolchaindir=toolchain/arm-eabi-4.4.3/bin
-    if [ -d "$prebuiltdir/$toolchaindir" ]; then
-        export ARM_EABI_TOOLCHAIN=$prebuiltdir/$toolchaindir
+    case $ARCH in
+        x86) toolchaindir=x86/i686-eabi-4.4.3/bin
+            ;;
+        arm) toolchaindir=arm/arm-eabi-4.6/bin
+            ;;
+        *)
+            echo "Can't find toolchain for unknown architecture: $ARCH"
+            toolchaindir=xxxxxxxxx
+            ;;
+    esac
+    if [ -d "$gccprebuiltdir/$toolchaindir" ]; then
+        export ARM_EABI_TOOLCHAIN=$gccprebuiltdir/$toolchaindir
     fi
 
     export ANDROID_TOOLCHAIN=$ANDROID_EABI_TOOLCHAIN
     export ANDROID_QTOOLS=$T/development/emulator/qtools
-    export ANDROID_BUILD_PATHS=:$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_QTOOLS:$ANDROID_TOOLCHAIN:$ARM_EABI_TOOLCHAIN$CODE_REVIEWS
+    export ANDROID_DEV_SCRIPTS=$T/development/scripts
+    export ANDROID_BUILD_PATHS=:$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_QTOOLS:$ANDROID_TOOLCHAIN:$ARM_EABI_TOOLCHAIN$CODE_REVIEWS:$ANDROID_DEV_SCRIPTS
     export PATH=$PATH$ANDROID_BUILD_PATHS
 
     unset ANDROID_JAVA_TOOLCHAIN
@@ -152,6 +167,10 @@
     unset ANDROID_HOST_OUT
     export ANDROID_HOST_OUT=$(get_abs_build_var HOST_OUT)
 
+    # needed for processing samples collected by perf counters
+    unset OPROFILE_EVENTS_DIR
+    export OPROFILE_EVENTS_DIR=$T/external/oprofile/events
+
     # needed for building linux on MacOS
     # TODO: fix the path
     #export HOST_EXTRACFLAGS="-I "$T/system/kernel_headers/host_include
@@ -508,8 +527,8 @@
 # Run tapas with one ore more app names (from LOCAL_PACKAGE_NAME)
 function tapas()
 {
-    local variant=$(echo -n $(echo $* | xargs -n 1 echo | grep -E '^(user|userdebug|eng)$'))
-    local apps=$(echo -n $(echo $* | xargs -n 1 echo | grep -E -v '^(user|userdebug|eng)$'))
+    local variant=$(echo -n $(echo $* | xargs -n 1 echo | \grep -E '^(user|userdebug|eng)$'))
+    local apps=$(echo -n $(echo $* | xargs -n 1 echo | \grep -E -v '^(user|userdebug|eng)$'))
 
     if [ $(echo $variant | wc -w) -gt 1 ]; then
         echo "tapas: Error: Multiple build variants supplied: $variant"
@@ -617,12 +636,17 @@
     T=$(gettop)
     if [ "$T" ]; then
         local MAKEFILE=
+        local MODULES=
         local ARGS=
         local DIR TO_CHOP
         local DASH_ARGS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
         local DIRS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
         for DIR in $DIRS ; do
-            DIR=`echo $DIR | sed -e 's:/$::'`
+            MODULES=`echo $DIR | sed -n -e 's/.*:\(.*$\)/\1/p' | sed 's/,/ /'`
+            if [ "$MODULES" = "" ]; then
+                MODULES=all_modules
+            fi
+            DIR=`echo $DIR | sed -e 's/:.*//' -e 's:/$::'`
             if [ -f $DIR/Android.mk ]; then
                 TO_CHOP=`(cd -P -- $T && pwd -P) | wc -c | tr -d ' '`
                 TO_CHOP=`expr $TO_CHOP + 1`
@@ -649,7 +673,7 @@
                 fi
             fi
         done
-        ONE_SHOT_MAKEFILE="$MAKEFILE" make -C $T $DASH_ARGS all_modules $ARGS
+        ONE_SHOT_MAKEFILE="$MAKEFILE" make -C $T $DASH_ARGS $MODULES $ARGS
     else
         echo "Couldn't locate the top of the tree.  Try setting TOP."
     fi
@@ -710,6 +734,14 @@
    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 PREBUILTS=$(get_abs_build_var ANDROID_PREBUILTS)
+   local ARCH=$(get_build_var TARGET_ARCH)
+   local GDB
+   case "$ARCH" in
+       x86) GDB=i686-linux-android-gdb;;
+       arm) GDB=arm-linux-androideabi-gdb;;
+       *) echo "Unknown arch $ARCH"; return 1;;
+   esac
+
    if [ "$OUT_ROOT" -a "$PREBUILTS" ]; then
        local EXE="$1"
        if [ "$EXE" ] ; then
@@ -746,11 +778,11 @@
        fi
 
        echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $OUT_SYMBOLS"
-       echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $OUT_SO_SYMBOLS"
+       echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $OUT_SO_SYMBOLS:$OUT_SO_SYMBOLS/hw:$OUT_SO_SYMBOLS/ssl/engines"
        echo >>"$OUT_ROOT/gdbclient.cmds" "target remote $PORT"
        echo >>"$OUT_ROOT/gdbclient.cmds" ""
 
-       $ANDROID_EABI_TOOLCHAIN/*-gdb -x "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
+       $ANDROID_TOOLCHAIN/$GDB -x "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
   else
        echo "Unable to determine build system output dir."
    fi
@@ -914,7 +946,7 @@
     echo "Running hat on $localFile"
     echo "View the output by pointing your browser at http://localhost:7000/"
     echo ""
-    hat $localFile
+    hat -JXmx512m $localFile
 }
 
 function getbugreports()
@@ -1013,7 +1045,7 @@
         echo ""
     fi
     local lines
-    lines=($(grep "$1" $T/filelist | sed -e 's/\/[^/]*$//' | sort | uniq))
+    lines=($(\grep "$1" $T/filelist | sed -e 's/\/[^/]*$//' | sort | uniq))
     if [[ ${#lines[@]} = 0 ]]; then
         echo "Not found"
         return
diff --git a/libs/host/Android.mk b/libs/host/Android.mk
index d02e4b2..9900f59 100644
--- a/libs/host/Android.mk
+++ b/libs/host/Android.mk
@@ -23,3 +23,5 @@
 
 include $(BUILD_HOST_STATIC_LIBRARY)
 
+# Include toolchain prebuilt modules if they exist.
+-include $(TARGET_TOOLCHAIN_ROOT)/toolchain.mk
diff --git a/libs/host/CopyFile.c b/libs/host/CopyFile.c
index 23f1260..ca52565 100644
--- a/libs/host/CopyFile.c
+++ b/libs/host/CopyFile.c
@@ -137,7 +137,7 @@
                 return -1;
             }
             if (writeCount != readCount) {
-                fprintf(stderr, "acp: partial write to '%s' (%d of %d)\n",
+                fprintf(stderr, "acp: partial write to '%s' (%zd of %zd)\n",
                     dst, writeCount, readCount);
                 return -1;
             }
diff --git a/target/board/Android.mk b/target/board/Android.mk
index 58164f6..7d94ee0 100644
--- a/target/board/Android.mk
+++ b/target/board/Android.mk
@@ -26,19 +26,20 @@
 # device we're building for.  This file is typically packaged up
 # with everything else.
 #
-# If the file "board-info.txt" appears in $(TARGET_DEVICE_DIR),
-# it will be used; otherwise TARGET_BOARD_INFO_FILE is used, which
-# can be set in BoardConfig.mk.
+# If TARGET_BOARD_INFO_FILE (which can be set in BoardConfig.mk) is
+# defined, it is used, otherwise board-info.txt is looked for in
+# $(TARGET_DEVICE_DIR).
 #
 INSTALLED_ANDROID_INFO_TXT_TARGET := $(PRODUCT_OUT)/android-info.txt
-board_info_txt := $(wildcard $(TARGET_DEVICE_DIR)/board-info.txt)
-ifndef board_info_txt
 board_info_txt := $(TARGET_BOARD_INFO_FILE)
+ifndef board_info_txt
+board_info_txt := $(wildcard $(TARGET_DEVICE_DIR)/board-info.txt)
 endif
 $(INSTALLED_ANDROID_INFO_TXT_TARGET): $(board_info_txt)
+	$(hide) build/tools/check_radio_versions.py $< $(BOARD_INFO_CHECK)
 	$(call pretty,"Generated: ($@)")
 ifdef board_info_txt
-	$(hide) cat $< > $@
+	$(hide) grep -v '#' $< > $@
 else
 	$(hide) echo "board=$(TARGET_BOOTLOADER_BOARD_NAME)" > $@
 endif
diff --git a/target/board/generic/BoardConfig.mk b/target/board/generic/BoardConfig.mk
index b25abb0..cee09ce 100644
--- a/target/board/generic/BoardConfig.mk
+++ b/target/board/generic/BoardConfig.mk
@@ -21,6 +21,7 @@
 TARGET_ARCH_VARIANT := armv7-a
 TARGET_CPU_ABI := armeabi-v7a
 TARGET_CPU_ABI2 := armeabi
+ARCH_ARM_HAVE_TLS_REGISTER := true
 
 HAVE_HTC_AUDIO_DRIVER := true
 BOARD_USES_GENERIC_AUDIO := true
diff --git a/target/board/generic/device.mk b/target/board/generic/device.mk
index 4edcc19..737a607 100644
--- a/target/board/generic/device.mk
+++ b/target/board/generic/device.mk
@@ -23,9 +23,12 @@
     ro.adb.qemud=1
 
 PRODUCT_COPY_FILES := \
-    development/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
-    development/data/etc/vold.conf:system/etc/vold.conf \
-    development/tools/emulator/system/camera/media_profiles.xml:system/etc/media_profiles.xml \
+    device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
+    device/generic/goldfish/data/etc/vold.conf:system/etc/vold.conf \
+    $(call add-to-product-copy-files-if-exists,development/tools/emulator/system/camera/media_profiles.xml:system/etc/media_profiles.xml) \
+    $(call add-to-product-copy-files-if-exists,development/tools/emulator/system/camera/media_codecs.xml:system/etc/media_codecs.xml) \
+    hardware/libhardware_legacy/audio/audio_policy.conf:system/etc/audio_policy.conf
 
 PRODUCT_PACKAGES := \
-    audio.primary.goldfish
+    audio.primary.goldfish \
+    power.goldfish
diff --git a/target/board/generic_armv5/AndroidBoard.mk b/target/board/generic_armv5/AndroidBoard.mk
deleted file mode 100644
index 7daff27..0000000
--- a/target/board/generic_armv5/AndroidBoard.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright (C) 2011 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
--include build/target/board/generic/AndroidBoard.mk
diff --git a/target/board/generic_armv5/BoardConfig.mk b/target/board/generic_armv5/BoardConfig.mk
deleted file mode 100644
index d8fa2fe..0000000
--- a/target/board/generic_armv5/BoardConfig.mk
+++ /dev/null
@@ -1,23 +0,0 @@
-#
-# Copyright (C) 2011 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-include build/target/board/generic/BoardConfig.mk
-
-TARGET_ARCH_VARIANT :=
-TARGET_CPU_ABI := armeabi
-TARGET_CPU_ABI2 :=
-
-WITH_DEXPREOPT := false
diff --git a/target/board/generic_armv5/README.txt b/target/board/generic_armv5/README.txt
deleted file mode 100644
index 25d590a..0000000
--- a/target/board/generic_armv5/README.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-The "generic_armv5" product defines a non-hardware-specific target
-without a kernel or bootloader.
-
-It is not a product "base class"; no other products inherit
-from it or use it in any way.
diff --git a/target/board/generic_armv5/device.mk b/target/board/generic_armv5/device.mk
deleted file mode 100644
index 7c4aaf2..0000000
--- a/target/board/generic_armv5/device.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright (C) 2011 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-include build/target/board/generic/device.mk
diff --git a/target/board/generic_armv5/system.prop b/target/board/generic_armv5/system.prop
deleted file mode 100644
index 137a0f9..0000000
--- a/target/board/generic_armv5/system.prop
+++ /dev/null
@@ -1,6 +0,0 @@
-#
-# system.prop for generic sdk
-#
-
-rild.libpath=/system/lib/libreference-ril.so
-rild.libargs=-d /dev/ttyS0
diff --git a/target/board/generic_x86/BoardConfig.mk b/target/board/generic_x86/BoardConfig.mk
index 35a5520..c0d7a25 100644
--- a/target/board/generic_x86/BoardConfig.mk
+++ b/target/board/generic_x86/BoardConfig.mk
@@ -8,7 +8,7 @@
 TARGET_NO_KERNEL := true
 TARGET_CPU_ABI := x86
 TARGET_ARCH := x86
-TARGET_ARCH_VARIANT := x86-atom
+TARGET_ARCH_VARIANT := x86
 TARGET_PRELINK_MODULE := false
 
 # The IA emulator (qemu) uses the Goldfish devices
diff --git a/target/board/generic_x86/device.mk b/target/board/generic_x86/device.mk
index fdd74bd..d24f3ac 100644
--- a/target/board/generic_x86/device.mk
+++ b/target/board/generic_x86/device.mk
@@ -23,9 +23,10 @@
     ro.adb.qemud=1
 
 PRODUCT_COPY_FILES := \
-    development/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
-    development/data/etc/vold.conf:system/etc/vold.conf \
-    development/tools/emulator/system/camera/media_profiles.xml:system/etc/media_profiles.xml
+    device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
+    device/generic/goldfish/data/etc/vold.conf:system/etc/vold.conf \
+    development/tools/emulator/system/camera/media_profiles.xml:system/etc/media_profiles.xml \
+    development/tools/emulator/system/camera/media_codecs.xml:system/etc/media_codecs.xml
 
 PRODUCT_PACKAGES := \
     audio.primary.goldfish
diff --git a/target/board/vbox_x86/BoardConfig.mk b/target/board/vbox_x86/BoardConfig.mk
index 244190e..80a9077 100644
--- a/target/board/vbox_x86/BoardConfig.mk
+++ b/target/board/vbox_x86/BoardConfig.mk
@@ -13,10 +13,12 @@
 TARGET_CPU_ABI := x86
 TARGET_USERIMAGES_USE_EXT4 := true
 TARGET_BOOTIMAGE_USE_EXT2 := true
+BOARD_CACHEIMAGE_PARTITION_SIZE := 268435456
+BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
 
 # For VirtualBox and likely other emulators
 BOARD_INSTALLER_CMDLINE := init=/init console=ttyS0 console=tty0 vga=788 verbose
-BOARD_KERNEL_CMDLINE := init=/init qemu=1 console=ttyS0 console=tty0 vga=788 verbose androidboot.hardware=vbox_x86 androidboot.console=ttyS0 android.qemud=ttyS1
+BOARD_KERNEL_CMDLINE := init=/init qemu=1 console=tty0 vga=788 verbose androidboot.hardware=vbox_x86 androidboot.console=tty0 android.qemud=tty0
 TARGET_USE_DISKINSTALLER := true
 
 TARGET_DISK_LAYOUT_CONFIG := build/target/board/vbox_x86/disk_layout.conf
diff --git a/target/board/vbox_x86/device.mk b/target/board/vbox_x86/device.mk
index 07ebb1c..b03cbd3 100644
--- a/target/board/vbox_x86/device.mk
+++ b/target/board/vbox_x86/device.mk
@@ -27,9 +27,12 @@
 LOCAL_KERNEL := prebuilts/qemu-kernel/x86/kernel-vbox
 
 PRODUCT_COPY_FILES := \
-    development/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
-    development/data/etc/vold.conf:system/etc/vold.conf \
+    device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
+    device/generic/goldfish/data/etc/vold.conf:system/etc/vold.conf \
     development/tools/emulator/system/camera/media_profiles.xml:system/etc/media_profiles.xml \
-    build/target/board/vbox_x86/init.rc:root/init.rc \
+    development/tools/emulator/system/camera/media_codecs.xml:system/etc/media_codecs.xml \
+    system/core/rootdir/init.rc:root/init.rc \
     build/target/board/vbox_x86/init.vbox_x86.rc:root/init.vbox_x86.rc \
     $(LOCAL_KERNEL):kernel
+
+$(call inherit-product, frameworks/native/build/phone-xhdpi-1024-dalvik-heap.mk)
diff --git a/target/board/vbox_x86/init.rc b/target/board/vbox_x86/init.rc
deleted file mode 100644
index 100cc09..0000000
--- a/target/board/vbox_x86/init.rc
+++ /dev/null
@@ -1,426 +0,0 @@
-on early-init
-    start ueventd
-
-on init
-
-sysclktz 0
-
-loglevel 3
-
-# setup the global environment
-    export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin
-    export LD_LIBRARY_PATH /vendor/lib:/system/lib
-    export ANDROID_BOOTLOGO 1
-    export ANDROID_ROOT /system
-    export ANDROID_ASSETS /system/app
-    export ANDROID_DATA /data
-    export EXTERNAL_STORAGE /mnt/sdcard
-    export ASEC_MOUNTPOINT /mnt/asec
-    export LOOP_MOUNTPOINT /mnt/obb
-    export BOOTCLASSPATH /system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar
-
-# Backward compatibility
-    symlink /system/etc /etc
-    symlink /sys/kernel/debug /d
-
-# Right now vendor lives on the same filesystem as system,
-# but someday that may change.
-    symlink /system/vendor /vendor
-
-# create mountpoints
-    mkdir /mnt 0775 root system
-    mkdir /mnt/sdcard 0000 system system
-
-# Create cgroup mount point for cpu accounting
-    mkdir /acct
-    mount cgroup none /acct cpuacct
-    mkdir /acct/uid
-
-# Backwards Compat - XXX: Going away in G*
-    symlink /mnt/sdcard /sdcard
-
-    mkdir /system
-    mkdir /data 0771 system system
-    mkdir /cache 0770 system cache
-    mkdir /config 0500 root root
-
-    # Directory for putting things only root should see.
-    mkdir /mnt/secure 0700 root root
-
-    # Directory for staging bindmounts
-    mkdir /mnt/secure/staging 0700 root root
-
-    # Directory-target for where the secure container
-    # imagefile directory will be bind-mounted
-    mkdir /mnt/secure/asec  0700 root root
-
-    # Secure container public mount points.
-    mkdir /mnt/asec  0700 root system
-    mount tmpfs tmpfs /mnt/asec mode=0755,gid=1000
-
-    # Filesystem image public mount points.
-    mkdir /mnt/obb 0700 root system
-    mount tmpfs tmpfs /mnt/obb mode=0755,gid=1000
-
-    write /proc/sys/kernel/panic_on_oops 1
-    write /proc/sys/kernel/hung_task_timeout_secs 0
-    write /proc/cpu/alignment 4
-    write /proc/sys/kernel/sched_latency_ns 10000000
-    write /proc/sys/kernel/sched_wakeup_granularity_ns 2000000
-    write /proc/sys/kernel/sched_compat_yield 1
-    write /proc/sys/kernel/sched_child_runs_first 0
-
-# Create cgroup mount points for process groups
-    mkdir /dev/cpuctl
-    mount cgroup none /dev/cpuctl cpu
-    chown system system /dev/cpuctl
-    chown system system /dev/cpuctl/tasks
-    chmod 0777 /dev/cpuctl/tasks
-    write /dev/cpuctl/cpu.shares 1024
-
-    mkdir /dev/cpuctl/fg_boost
-    chown system system /dev/cpuctl/fg_boost/tasks
-    chmod 0777 /dev/cpuctl/fg_boost/tasks
-    write /dev/cpuctl/fg_boost/cpu.shares 1024
-
-    mkdir /dev/cpuctl/bg_non_interactive
-    chown system system /dev/cpuctl/bg_non_interactive/tasks
-    chmod 0777 /dev/cpuctl/bg_non_interactive/tasks
-    # 5.0 %
-    write /dev/cpuctl/bg_non_interactive/cpu.shares 52
-
-on fs
-# mount sda partitions
-    mount ext4 /dev/block/sda6 /system
-    mount ext4 /dev/block/sda6 /system ro remount
-    mount ext4 /dev/block/sda7 /data nosuid nodev
-    mount ext4 /dev/block/sda8 /cache nosuid nodev
-
-on post-fs
-    # once everything is setup, no need to modify /
-    mount rootfs rootfs / ro remount
-
-    # We chown/chmod /data again so because mount is run as root + defaults
-    chown system system /data
-    chmod 0771 /data
-
-    # Create dump dir and collect dumps.
-    # Do this before we mount cache so eventually we can use cache for
-    # storing dumps on platforms which do not have a dedicated dump partition.
-   
-    mkdir /data/dontpanic
-    chown root log /data/dontpanic
-    chmod 0750 /data/dontpanic
-
-    # Collect apanic data, free resources and re-arm trigger
-    copy /proc/apanic_console /data/dontpanic/apanic_console
-    chown root log /data/dontpanic/apanic_console
-    chmod 0640 /data/dontpanic/apanic_console
-
-    copy /proc/apanic_threads /data/dontpanic/apanic_threads
-    chown root log /data/dontpanic/apanic_threads
-    chmod 0640 /data/dontpanic/apanic_threads
-
-    write /proc/apanic_console 1
-
-    # Same reason as /data above
-    chown system cache /cache
-    chmod 0770 /cache
-
-    # This may have been created by the recovery system with odd permissions
-    chown system cache /cache/recovery
-    chmod 0770 /cache/recovery
-
-    #change permissions on vmallocinfo so we can grab it from bugreports
-    chown root log /proc/vmallocinfo
-    chmod 0440 /proc/vmallocinfo
-
-    #change permissions on kmsg & sysrq-trigger so bugreports can grab kthread stacks
-    chown root system /proc/kmsg
-    chmod 0440 /proc/kmsg
-    chown root system /proc/sysrq-trigger
-    chmod 0220 /proc/sysrq-trigger
-
-# create basic filesystem structure
-    mkdir /data/misc 01771 system misc
-    mkdir /data/misc/bluetoothd 0770 bluetooth bluetooth
-    mkdir /data/misc/bluetooth 0770 system system
-    mkdir /data/misc/keystore 0700 keystore keystore
-    mkdir /data/misc/vpn 0770 system system
-    mkdir /data/misc/systemkeys 0700 system system
-    mkdir /data/misc/vpn/profiles 0770 system system
-    # give system access to wpa_supplicant.conf for backup and restore
-    mkdir /data/misc/wifi 0770 wifi wifi
-    chmod 0770 /data/misc/wifi
-    chmod 0660 /data/misc/wifi/wpa_supplicant.conf
-    mkdir /data/local 0771 shell shell
-    mkdir /data/local/tmp 0771 shell shell
-    mkdir /data/data 0771 system system
-    mkdir /data/app-private 0771 system system
-    mkdir /data/app 0771 system system
-    mkdir /data/property 0700 root root
-
-    # create dalvik-cache and double-check the perms
-    mkdir /data/dalvik-cache 0771 system system
-    chown system system /data/dalvik-cache
-    chmod 0771 /data/dalvik-cache
-
-    # create the lost+found directories, so as to enforce our permissions
-    mkdir /data/lost+found 0770
-    mkdir /cache/lost+found 0770
-
-    # double check the perms, in case lost+found already exists, and set owner
-    chown root root /data/lost+found
-    chmod 0770 /data/lost+found
-    chown root root /cache/lost+found
-    chmod 0770 /cache/lost+found
-
-    # create data/drm directory
-    mkdir /data/drm 0774 drm drm
-    chown drm drm /data/drm
-    chmod 0774 /data/drm
-
-on boot
-# basic network init
-    ifup lo
-    hostname localhost
-    domainname localdomain
-
-# set RLIMIT_NICE to allow priorities from 19 to -20
-    setrlimit 13 40 40
-
-# Define the oom_adj values for the classes of processes that can be
-# killed by the kernel.  These are used in ActivityManagerService.
-    setprop ro.FOREGROUND_APP_ADJ 0
-    setprop ro.VISIBLE_APP_ADJ 1
-    setprop ro.PERCEPTIBLE_APP_ADJ 2
-    setprop ro.HEAVY_WEIGHT_APP_ADJ 3
-    setprop ro.SECONDARY_SERVER_ADJ 4
-    setprop ro.BACKUP_APP_ADJ 5
-    setprop ro.HOME_APP_ADJ 6
-    setprop ro.HIDDEN_APP_MIN_ADJ 7
-    setprop ro.EMPTY_APP_ADJ 15
-
-# Define the memory thresholds at which the above process classes will
-# be killed.  These numbers are in pages (4k).
-    setprop ro.FOREGROUND_APP_MEM 2048
-    setprop ro.VISIBLE_APP_MEM 3072
-    setprop ro.PERCEPTIBLE_APP_MEM 4096
-    setprop ro.HEAVY_WEIGHT_APP_MEM 4096
-    setprop ro.SECONDARY_SERVER_MEM 6144
-    setprop ro.BACKUP_APP_MEM 6144
-    setprop ro.HOME_APP_MEM 6144
-    setprop ro.HIDDEN_APP_MEM 7168
-    setprop ro.EMPTY_APP_MEM 8192
-
-# Write value must be consistent with the above properties.
-# Note that the driver only supports 6 slots, so we have combined some of
-# the classes into the same memory level; the associated processes of higher
-# classes will still be killed first.
-    write /sys/module/lowmemorykiller/parameters/adj 0,1,2,4,7,15
-
-    write /proc/sys/vm/overcommit_memory 1
-    write /proc/sys/vm/min_free_order_shift 4
-    write /sys/module/lowmemorykiller/parameters/minfree 2048,3072,4096,6144,7168,8192
-
-    # Set init its forked children's oom_adj.
-    write /proc/1/oom_adj -16
-
-    # Tweak background writeout
-    write /proc/sys/vm/dirty_expire_centisecs 200
-    write /proc/sys/vm/dirty_background_ratio  5
-
-    # Permissions for System Server and daemons.
-    chown radio system /sys/android_power/state
-    chown radio system /sys/android_power/request_state
-    chown radio system /sys/android_power/acquire_full_wake_lock
-    chown radio system /sys/android_power/acquire_partial_wake_lock
-    chown radio system /sys/android_power/release_wake_lock
-    chown radio system /sys/power/state
-    chown radio system /sys/power/wake_lock
-    chown radio system /sys/power/wake_unlock
-    chmod 0660 /sys/power/state
-    chmod 0660 /sys/power/wake_lock
-    chmod 0660 /sys/power/wake_unlock
-    chown system system /sys/class/timed_output/vibrator/enable
-    chown system system /sys/class/leds/keyboard-backlight/brightness
-    chown system system /sys/class/leds/lcd-backlight/brightness
-    chown system system /sys/class/leds/button-backlight/brightness
-    chown system system /sys/class/leds/jogball-backlight/brightness
-    chown system system /sys/class/leds/red/brightness
-    chown system system /sys/class/leds/green/brightness
-    chown system system /sys/class/leds/blue/brightness
-    chown system system /sys/class/leds/red/device/grpfreq
-    chown system system /sys/class/leds/red/device/grppwm
-    chown system system /sys/class/leds/red/device/blink
-    chown system system /sys/class/leds/red/brightness
-    chown system system /sys/class/leds/green/brightness
-    chown system system /sys/class/leds/blue/brightness
-    chown system system /sys/class/leds/red/device/grpfreq
-    chown system system /sys/class/leds/red/device/grppwm
-    chown system system /sys/class/leds/red/device/blink
-    chown system system /sys/class/timed_output/vibrator/enable
-    chown system system /sys/module/sco/parameters/disable_esco
-    chown system system /sys/kernel/ipv4/tcp_wmem_min
-    chown system system /sys/kernel/ipv4/tcp_wmem_def
-    chown system system /sys/kernel/ipv4/tcp_wmem_max
-    chown system system /sys/kernel/ipv4/tcp_rmem_min
-    chown system system /sys/kernel/ipv4/tcp_rmem_def
-    chown system system /sys/kernel/ipv4/tcp_rmem_max
-    chown root radio /proc/cmdline
-
-# Define TCP buffer sizes for various networks
-#   ReadMin, ReadInitial, ReadMax, WriteMin, WriteInitial, WriteMax,
-    setprop net.tcp.buffersize.default 4096,87380,110208,4096,16384,110208
-    setprop net.tcp.buffersize.wifi    4095,87380,110208,4096,16384,110208
-    setprop net.tcp.buffersize.umts    4094,87380,110208,4096,16384,110208
-    setprop net.tcp.buffersize.edge    4093,26280,35040,4096,16384,35040
-    setprop net.tcp.buffersize.gprs    4092,8760,11680,4096,8760,11680
-
-    class_start default
-
-## Daemon processes to be run by init.
-##
-service ueventd /sbin/ueventd
-    critical
-
-service console /system/bin/sh
-    console
-    disabled
-    user shell
-    group log
-
-on property:ro.secure=0
-    start console
-
-# adbd is controlled by the persist.service.adb.enable system property
-service adbd /sbin/adbd
-    disabled
-
-# adbd on at boot in emulator
-on property:ro.kernel.qemu=1
-    start adbd
-
-on property:persist.service.adb.enable=1
-    start adbd
-
-on property:persist.service.adb.enable=0
-    stop adbd
-
-service servicemanager /system/bin/servicemanager
-    user system
-    critical
-    onrestart restart zygote
-    onrestart restart media
-
-service vold /system/bin/vold
-    socket vold stream 0660 root mount
-    ioprio be 2
-
-service netd /system/bin/netd
-    socket netd stream 0660 root system
-    socket dnsproxyd stream 0660 root inet
-
-service debuggerd /system/bin/debuggerd
-
-service ril-daemon /system/bin/rild
-    socket rild stream 660 root radio
-    socket rild-debug stream 660 radio system
-    user root
-    group radio cache inet misc audio sdcard_rw
-
-service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
-    socket zygote stream 666
-    onrestart write /sys/android_power/request_state wake
-    onrestart write /sys/power/state on
-    onrestart restart media
-    onrestart restart netd
-
-service drm /system/bin/drmserver
-    user drm
-    group system root inet
-
-service drmio /system/bin/drmioserver
-    user drmio
-
-service media /system/bin/mediaserver
-    user media
-    group system audio camera graphics inet net_bt net_bt_admin net_raw
-    ioprio rt 4
-
-service bootanim /system/bin/bootanimation
-    user graphics
-    group graphics
-    disabled
-    oneshot
-
-service dbus /system/bin/dbus-daemon --system --nofork
-    socket dbus stream 660 bluetooth bluetooth
-    user bluetooth
-    group bluetooth net_bt_admin
-
-service bluetoothd /system/bin/bluetoothd -n
-    socket bluetooth stream 660 bluetooth bluetooth
-    socket dbus_bluetooth stream 660 bluetooth bluetooth
-    # init.rc does not yet support applying capabilities, so run as root and
-    # let bluetoothd drop uid to bluetooth with the right linux capabilities
-    group bluetooth net_bt_admin misc
-    disabled
-
-service hfag /system/bin/sdptool add --channel=10 HFAG
-    user bluetooth
-    group bluetooth net_bt_admin
-    disabled
-    oneshot
-
-service hsag /system/bin/sdptool add --channel=11 HSAG
-    user bluetooth
-    group bluetooth net_bt_admin
-    disabled
-    oneshot
-
-service opush /system/bin/sdptool add --channel=12 OPUSH
-    user bluetooth
-    group bluetooth net_bt_admin
-    disabled
-    oneshot
-
-service pbap /system/bin/sdptool add --channel=19 PBAP
-    user bluetooth
-    group bluetooth net_bt_admin
-    disabled
-    oneshot
-
-service installd /system/bin/installd
-    socket installd stream 600 system system
-
-service flash_recovery /system/etc/install-recovery.sh
-    oneshot
-
-service racoon /system/bin/racoon
-    socket racoon stream 600 system system
-    # racoon will setuid to vpn after getting necessary resources.
-    group net_admin
-    disabled
-    oneshot
-
-service mtpd /system/bin/mtpd
-    socket mtpd stream 600 system system
-    user vpn
-    group vpn net_admin net_raw
-    disabled
-    oneshot
-
-service keystore /system/bin/keystore /data/misc/keystore
-    user keystore
-    group keystore
-    socket keystore stream 666
-
-service dumpstate /system/bin/dumpstate -s
-    socket dumpstate stream 0660 shell log
-    disabled
-    oneshot
-
-# Enable networking so that adb can connect
-service netcfg /system/bin/netcfg eth0 dhcp
-    oneshot
diff --git a/target/board/vbox_x86/init.vbox_x86.rc b/target/board/vbox_x86/init.vbox_x86.rc
index 4c5d55c..15ca572 100644
--- a/target/board/vbox_x86/init.vbox_x86.rc
+++ b/target/board/vbox_x86/init.vbox_x86.rc
@@ -1,5 +1,12 @@
+on early-init
+    export EXTERNAL_STORAGE /mnt/sdcard
+    mkdir /mnt/sdcard 0000 system system
+    # for backwards compatibility
+    symlink /mnt/sdcard /sdcard
+
 on boot
     setprop ARGH ARGH
+    setprop net.eth0.gw 10.0.2.2
     setprop net.eth0.dns1 10.0.2.3
     setprop net.gprs.local-ip 10.0.2.15
     setprop ro.radio.use-ppp no
@@ -16,8 +23,21 @@
     stop dund
     stop akmd
 
+# start essential services
+    start qemud
+    start goldfish-logcat
+#   start goldfish-setup
+    start netcfg
+
     setprop ro.setupwizard.mode EMULATOR
 
+on fs
+# mount sda (system) and sdb (data) partitions
+    mount ext4 /dev/block/sda6 /system
+    mount ext4 /dev/block/sda6 /system ro remount
+    mount ext4 /dev/block/sdb6 /data nosuid nodev
+    mount ext4 /dev/block/sdb7 /cache nosuid nodev
+
 # enable Google-specific location features,
 # like NetworkLocationProvider and LocationCollector
     setprop ro.com.google.locationfeatures 1
@@ -36,7 +56,21 @@
 # something else.
 
 service goldfish-setup /system/etc/init.goldfish.sh
-   oneshot
+    user root
+    group root
+    oneshot
+
+# The qemu-props program is used to set various system
+# properties on boot. It must be run early during the boot
+# process to avoid race conditions with other daemons that
+# might read them (e.g. surface flinger), so define it in
+# class 'core'
+#
+service qemu-props /system/bin/qemu-props
+    class core
+    user root
+    group root
+    oneshot
 
 service qemud /system/bin/qemud
     socket qemud    stream 666
@@ -46,7 +80,11 @@
 # program to check wether it runs on the emulator
 # if it does, it redirects its output to the device
 # named by the androidboot.console kernel option
-# if not, is simply exit immediately
+# if not, it simply exits immediately
 
 service goldfish-logcat /system/bin/logcat -Q
     oneshot
+
+# Enable networking so that adb can connect
+service netcfg /system/bin/netcfg eth0 dhcp
+    oneshot
diff --git a/target/product/AndroidProducts.mk b/target/product/AndroidProducts.mk
index 220e39a..9279633 100644
--- a/target/product/AndroidProducts.mk
+++ b/target/product/AndroidProducts.mk
@@ -35,7 +35,6 @@
 PRODUCT_MAKEFILES := \
     $(LOCAL_DIR)/core.mk \
     $(LOCAL_DIR)/generic.mk \
-    $(LOCAL_DIR)/generic_armv5.mk \
     $(LOCAL_DIR)/generic_x86.mk \
     $(LOCAL_DIR)/generic_mips.mk \
     $(LOCAL_DIR)/full.mk \
diff --git a/target/product/core.mk b/target/product/core.mk
index 34bad8e..58002a7 100644
--- a/target/product/core.mk
+++ b/target/product/core.mk
@@ -56,9 +56,9 @@
     dexlist \
     dexopt \
     dmtracedump \
+    drmserver \
     dx \
     ext \
-    filterfw \
     framework-res \
     hprof-conv \
     icu.dat \
@@ -67,40 +67,60 @@
     ip-up-vpn \
     ip6tables \
     iptables \
+    keystore \
+    keystore.default \
+    libandroidfw \
     libOpenMAXAL \
     libOpenSLES \
     libaudiopreprocessing \
+    libaudioutils \
     libcrypto \
+    libdownmix \
     libdvm \
+    libdrmframework \
+    libdrmframework_jni \
     libexpat \
     libfilterfw \
     libfilterpack_imageproc \
     libgabi++ \
     libicui18n \
     libicuuc \
+    libjavacore \
+    libkeystore \
+    libmdnssd \
     libnativehelper \
     libnfc_ndef \
     libpowermanager \
     libspeexresampler \
     libsqlite_jni \
     libssl \
-    libstagefright_soft_h264dec \
     libstagefright_soft_aacdec \
+    libstagefright_soft_aacenc \
     libstagefright_soft_amrdec \
+    libstagefright_soft_amrnbenc \
+    libstagefright_soft_amrwbenc \
+    libstagefright_soft_flacenc \
     libstagefright_soft_g711dec \
+    libstagefright_soft_h264dec \
+    libstagefright_soft_h264enc \
     libstagefright_soft_mp3dec \
     libstagefright_soft_mpeg4dec \
+    libstagefright_soft_mpeg4enc \
     libstagefright_soft_vorbisdec \
     libstagefright_soft_vpxdec \
+    libstagefright_soft_rawdec \
     libvariablespeed \
     libwebrtc_audio_preprocessing \
     libwilhelm \
     libz \
+    mdnsd \
+    requestsync \
     screencap \
     sensorservice \
-    drmserver \
-    libdrmframework \
-    libdrmframework_jni
+    lint
+
+PRODUCT_COPY_FILES += \
+    system/core/rootdir/init.usb.rc:root/init.usb.rc \
 
 # host-only dependencies
 ifeq ($(WITH_HOST_DALVIK),true)
@@ -108,5 +128,12 @@
         apache-xml-hostdex \
         bouncycastle-hostdex \
         core-hostdex \
+        libcrypto \
+        libexpat \
+        libicui18n \
+        libicuuc \
+        libjavacore \
+        libssl \
+        libz-host \
         dalvik
 endif
diff --git a/target/product/full.mk b/target/product/full.mk
index 0f1956b..8231e99 100644
--- a/target/product/full.mk
+++ b/target/product/full.mk
@@ -19,9 +19,6 @@
 # build quite specifically for the emulator, and might not be
 # entirely appropriate to inherit from for on-device configurations.
 
-PRODUCT_PACKAGES := \
-    Camera
-
 $(call inherit-product, $(SRC_TARGET_DIR)/product/full_base_telephony.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/board/generic/device.mk)
 
diff --git a/target/product/full_base.mk b/target/product/full_base.mk
index e220778..2c24b1a 100644
--- a/target/product/full_base.mk
+++ b/target/product/full_base.mk
@@ -29,6 +29,16 @@
     VideoEditor \
     WAPPushManager
 
+PRODUCT_PACKAGES += \
+    Galaxy4 \
+    HoloSpiralWallpaper \
+    LiveWallpapers \
+    LiveWallpapersPicker \
+    MagicSmokeWallpapers \
+    NoiseField \
+    PhaseBeam \
+    VisualizationWallpapers
+
 # Additional settings used in all AOSP builds
 PRODUCT_PROPERTY_OVERRIDES := \
     ro.com.android.dateformat=MM-dd-yyyy \
diff --git a/target/product/full_base_telephony.mk b/target/product/full_base_telephony.mk
index c376314..5899c8c 100644
--- a/target/product/full_base_telephony.mk
+++ b/target/product/full_base_telephony.mk
@@ -27,7 +27,7 @@
     ro.com.android.dataroaming=true
 
 PRODUCT_COPY_FILES := \
-    development/data/etc/apns-conf.xml:system/etc/apns-conf.xml
+    device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/full_base.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/telephony.mk)
diff --git a/target/product/full_x86.mk b/target/product/full_x86.mk
index c7a4cfb..d6a169a 100644
--- a/target/product/full_x86.mk
+++ b/target/product/full_x86.mk
@@ -26,9 +26,6 @@
   PRODUCT_PROPERTY_OVERRIDES += net.eth0.startonboot=1
 endif
 
-PRODUCT_PACKAGES := \
-    Camera
-
 $(call inherit-product, $(SRC_TARGET_DIR)/product/full_base.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/board/generic_x86/device.mk)
 
diff --git a/target/product/generic_armv5.mk b/target/product/generic_armv5.mk
deleted file mode 100644
index daa321a..0000000
--- a/target/product/generic_armv5.mk
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# Copyright (C) 2011 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# This is a generic product that isn't specialized for a specific device.
-# It includes the base Android platform.
-
-$(call inherit-product, $(SRC_TARGET_DIR)/product/generic.mk)
-
-# Overrides
-PRODUCT_BRAND := generic_armv5
-PRODUCT_DEVICE := generic_armv5
-PRODUCT_NAME := generic_armv5
diff --git a/target/product/generic_no_telephony.mk b/target/product/generic_no_telephony.mk
index dbdc500..71a86ea 100644
--- a/target/product/generic_no_telephony.mk
+++ b/target/product/generic_no_telephony.mk
@@ -27,8 +27,9 @@
     CertInstaller \
     DrmProvider \
     Email \
-    Exchange \
+    Exchange2 \
     Gallery2 \
+    InputDevices \
     LatinIME \
     Launcher2 \
     Music \
@@ -52,12 +53,19 @@
 PRODUCT_PACKAGES += \
     librs_jni \
     libvideoeditor_jni \
+    libvideoeditor_core \
+    libvideoeditor_osal \
+    libvideoeditor_videofilters \
     libvideoeditorplayer \
-    libvideoeditor_core
 
 PRODUCT_PACKAGES += \
     audio.primary.default \
-    audio_policy.default
+    audio_policy.default \
+    local_time.default \
+    power.default
+
+PRODUCT_PACKAGES += \
+    local_time.default
 
 PRODUCT_COPY_FILES := \
         system/bluetooth/data/audio.conf:system/etc/bluetooth/audio.conf \
@@ -65,9 +73,13 @@
         system/bluetooth/data/blacklist.conf:system/etc/bluetooth/blacklist.conf \
         system/bluetooth/data/input.conf:system/etc/bluetooth/input.conf \
         system/bluetooth/data/network.conf:system/etc/bluetooth/network.conf \
-        frameworks/base/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf
+        frameworks/av/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf
+
+PRODUCT_PROPERTY_OVERRIDES += \
+    ro.carrier=unknown
 
 $(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk)
+$(call inherit-product-if-exists, external/cibu-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/lohit-fonts/fonts.mk)
 $(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)
diff --git a/target/product/large_emu_hw.mk b/target/product/large_emu_hw.mk
index 847e10a..91a9e08 100644
--- a/target/product/large_emu_hw.mk
+++ b/target/product/large_emu_hw.mk
@@ -25,7 +25,6 @@
     Bluetooth \
     Calculator \
     Calendar \
-    Camera \
     CertInstaller \
     DrmProvider \
     Email \
diff --git a/target/product/mini.mk b/target/product/mini.mk
new file mode 100644
index 0000000..8a74428
--- /dev/null
+++ b/target/product/mini.mk
@@ -0,0 +1,207 @@
+# Copyright (C) 2012 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Common configurations for mini_XXX lunch targets
+# This is mainly for creating small system image during early development stage.
+
+PRODUCT_BRAND := mini
+PRODUCT_DEVICE := mini
+PRODUCT_NAME := mini
+
+# add all configurations
+PRODUCT_AAPT_CONFIG := normal ldpi mdpi hdpi xhdpi xxhdpi
+PRODUCT_AAPT_PREF_CONFIG := hdpi
+
+# en_US only
+PRODUCT_LOCALES := en_US
+
+# dummy definitions to use += in later parts
+PRODUCT_PROPERTY_OVERRIDES :=
+PRODUCT_COPY_FILES :=
+
+
+# for CtsVerifier
+PRODUCT_PACKAGES += \
+    com.android.future.usb.accessory
+
+# It does not mean that all features are supproted, but only for meeting
+# configuration requirements for some CTS
+PRODUCT_COPY_FILES += \
+    frameworks/native/data/etc/handheld_core_hardware.xml:system/etc/permissions/handheld_core_hardware.xml \
+    frameworks/native/data/etc/android.hardware.location.gps.xml:system/etc/permissions/android.hardware.location.gps.xml \
+    frameworks/native/data/etc/android.hardware.sensor.light.xml:system/etc/permissions/android.hardware.sensor.light.xml \
+    frameworks/native/data/etc/android.hardware.sensor.barometer.xml:system/etc/permissions/android.hardware.sensor.barometer.xml \
+    frameworks/native/data/etc/android.hardware.sensor.gyroscope.xml:system/etc/permissions/android.hardware.sensor.gyroscope.xml \
+    frameworks/native/data/etc/android.hardware.usb.accessory.xml:system/etc/permissions/android.hardware.usb.accessory.xml
+
+#----------------- originally from core.mk ----------------
+
+PRODUCT_PROPERTY_OVERRIDES += \
+    ro.config.notification_sound=OnTheHunt.ogg \
+    ro.config.alarm_alert=Alarm_Classic.ogg
+
+PRODUCT_PACKAGES += \
+    ApplicationsProvider \
+    ContactsProvider \
+    DefaultContainerService \
+    DownloadProvider \
+    DownloadProviderUi \
+    MediaProvider \
+    PackageInstaller \
+    SettingsProvider \
+    TelephonyProvider \
+    UserDictionaryProvider \
+    apache-xml \
+    bouncycastle \
+    bu \
+    cacerts \
+    com.android.location.provider \
+    com.android.location.provider.xml \
+    core \
+    core-junit \
+    dalvikvm \
+    dexdeps \
+    dexdump \
+    dexlist \
+    dexopt \
+    dmtracedump \
+    drmserver \
+    dx \
+    ext \
+    framework-res \
+    hprof-conv \
+    icu.dat \
+    installd \
+    ip \
+    ip-up-vpn \
+    ip6tables \
+    iptables \
+    keystore \
+    keystore.default \
+    libandroidfw \
+    libOpenMAXAL \
+    libOpenSLES \
+    libaudiopreprocessing \
+    libaudioutils \
+    libcrypto \
+    libdownmix \
+    libdvm \
+    libdrmframework \
+    libdrmframework_jni \
+    libexpat \
+    libfilterfw \
+    libfilterpack_imageproc \
+    libgabi++ \
+    libicui18n \
+    libicuuc \
+    libjavacore \
+    libkeystore \
+    libmdnssd \
+    libnativehelper \
+    libnfc_ndef \
+    libpowermanager \
+    libspeexresampler \
+    libsqlite_jni \
+    libssl \
+    libstagefright_soft_aacdec \
+    libstagefright_soft_aacenc \
+    libstagefright_soft_amrdec \
+    libstagefright_soft_amrnbenc \
+    libstagefright_soft_amrwbenc \
+    libstagefright_soft_flacenc \
+    libstagefright_soft_g711dec \
+    libstagefright_soft_h264dec \
+    libstagefright_soft_h264enc \
+    libstagefright_soft_mp3dec \
+    libstagefright_soft_mpeg4dec \
+    libstagefright_soft_mpeg4enc \
+    libstagefright_soft_vorbisdec \
+    libstagefright_soft_vpxdec \
+    libstagefright_soft_rawdec \
+    libvariablespeed \
+    libwebrtc_audio_preprocessing \
+    libwilhelm \
+    libz \
+    mdnsd \
+    requestsync \
+    screencap \
+    sensorservice \
+    lint
+
+PRODUCT_COPY_FILES += \
+    system/core/rootdir/init.usb.rc:root/init.usb.rc \
+
+#----------------- originally from generic_no_telephony.mk ----------------
+
+PRODUCT_PACKAGES += \
+    Bluetooth \
+    InputDevices \
+    LatinIME \
+    Launcher2 \
+    Phone \
+    Provision \
+    Settings \
+    SystemUI \
+    hostapd \
+    wpa_supplicant.conf
+
+
+PRODUCT_PACKAGES += \
+    icu.dat
+
+PRODUCT_PACKAGES += \
+    librs_jni \
+    libvideoeditor_jni \
+    libvideoeditor_core \
+    libvideoeditor_osal \
+    libvideoeditor_videofilters \
+    libvideoeditorplayer \
+
+PRODUCT_PACKAGES += \
+    audio.primary.default \
+    audio_policy.default \
+    local_time.default \
+    power.default
+
+PRODUCT_PACKAGES += \
+    local_time.default
+
+PRODUCT_COPY_FILES += \
+    system/bluetooth/data/audio.conf:system/etc/bluetooth/audio.conf \
+    system/bluetooth/data/auto_pairing.conf:system/etc/bluetooth/auto_pairing.conf \
+    system/bluetooth/data/blacklist.conf:system/etc/bluetooth/blacklist.conf \
+    system/bluetooth/data/input.conf:system/etc/bluetooth/input.conf \
+    system/bluetooth/data/network.conf:system/etc/bluetooth/network.conf \
+    frameworks/av/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf
+
+PRODUCT_PROPERTY_OVERRIDES += \
+    ro.carrier=unknown
+
+#----------------- originally from full_base.mk ----------------
+
+PRODUCT_PACKAGES += \
+    drmserver \
+    libdrmframework \
+    libdrmframework_jni
+
+
+# Additional settings used in all AOSP builds
+PRODUCT_PROPERTY_OVERRIDES += \
+    ro.com.android.dateformat=MM-dd-yyyy \
+    ro.config.ringtone=Ring_Synth_04.ogg \
+    ro.config.notification_sound=pixiedust.ogg
+
+$(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
+$(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk)
+$(call inherit-product-if-exists, frameworks/base/data/sounds/AudioPackage5.mk)
diff --git a/target/product/sdk.mk b/target/product/sdk.mk
index 99a197c..fceb2e5 100644
--- a/target/product/sdk.mk
+++ b/target/product/sdk.mk
@@ -19,10 +19,9 @@
 
 PRODUCT_PACKAGES := \
 	Calculator \
-	Camera \
 	DeskClock \
 	Email \
-	Exchange \
+	Exchange2 \
 	Gallery \
 	Music \
 	Mms \
@@ -43,6 +42,7 @@
 	SdkSetup \
 	CustomLocale \
 	sqlite3 \
+	InputDevices \
 	LatinIME \
 	CertInstaller \
 	LiveWallpapersPicker \
@@ -60,27 +60,36 @@
 	ConnectivityTest \
 	GpsLocationTest \
 	CalendarProvider \
-	Calendar
+	Calendar \
+	SmokeTest \
+	SmokeTestApp \
+	rild
+
 
 # Define the host tools and libs that are parts of the SDK.
-include sdk/build/product_sdk.mk
-include development/build/product_sdk.mk
+-include sdk/build/product_sdk.mk
+-include development/build/product_sdk.mk
 
 # audio libraries.
 PRODUCT_PACKAGES += \
 	audio.primary.goldfish \
-	audio_policy.default
+	audio_policy.default \
+	local_time.default
 
 PRODUCT_PACKAGE_OVERLAYS := development/sdk_overlay
 
 PRODUCT_COPY_FILES := \
+	device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
 	system/core/rootdir/etc/vold.fstab:system/etc/vold.fstab \
 	frameworks/base/data/sounds/effects/camera_click.ogg:system/media/audio/ui/camera_click.ogg \
 	frameworks/base/data/sounds/effects/VideoRecord.ogg:system/media/audio/ui/VideoRecord.ogg \
-	frameworks/base/data/etc/handheld_core_hardware.xml:system/etc/permissions/handheld_core_hardware.xml \
-	frameworks/base/data/etc/android.hardware.touchscreen.multitouch.jazzhand.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.jazzhand.xml \
-	frameworks/base/data/etc/android.hardware.camera.autofocus.xml:system/etc/permissions/android.hardware.camera.autofocus.xml \
-        frameworks/base/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf
+	frameworks/native/data/etc/handheld_core_hardware.xml:system/etc/permissions/handheld_core_hardware.xml \
+	development/tools/emulator/system/camera/media_profiles.xml:system/etc/media_profiles.xml \
+	development/tools/emulator/system/camera/media_codecs.xml:system/etc/media_codecs.xml \
+	frameworks/native/data/etc/android.hardware.touchscreen.multitouch.jazzhand.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.jazzhand.xml \
+	frameworks/native/data/etc/android.hardware.camera.autofocus.xml:system/etc/permissions/android.hardware.camera.autofocus.xml \
+	frameworks/av/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf \
+	hardware/libhardware_legacy/audio/audio_policy.conf:system/etc/audio_policy.conf
 
 $(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk)
 $(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
diff --git a/target/product/telephony.mk b/target/product/telephony.mk
index a0220de..89ed20a 100644
--- a/target/product/telephony.mk
+++ b/target/product/telephony.mk
@@ -18,6 +18,7 @@
 # to products that have telephony hardware.
 
 PRODUCT_PACKAGES := \
-    Mms
+    Mms \
+    rild
 
 PRODUCT_COPY_FILES := \
diff --git a/tools/adbs b/tools/adbs
index 961169b..598af85 100755
--- a/tools/adbs
+++ b/tools/adbs
@@ -137,11 +137,7 @@
 
   uname = os.uname()[0]
   if uname == "Darwin":
-    proc = os.uname()[-1]
-    if proc == "i386":
-      uname = "darwin-x86"
-    else:
-      uname = "darwin-ppc"
+    uname = "darwin-x86"
   elif uname == "Linux":
     uname = "linux-x86"
   prefix = "./prebuilts/gcc/" + uname + "/arm/arm-linux-androideabi-4.6/bin/"
@@ -149,8 +145,8 @@
 
   if (not os.path.exists(addr2line_cmd)):
     try:
-      prefix = os.environ['ANDROID_BUILD_TOP'] + "/prebuilts/gcc/" + uname + \
-               "/arm/arm-linux-androideabi-4.6/bin/"
+      prefix = os.environ['ANDROID_BUILD_TOP'] + "/prebuilts/gcc/" + \
+               uname + "/arm/arm-linux-androideabi-4.6/bin/"
     except:
       prefix = "";
 
diff --git a/tools/apicheck/Android.mk b/tools/apicheck/Android.mk
index 24f697c..1674a17 100644
--- a/tools/apicheck/Android.mk
+++ b/tools/apicheck/Android.mk
@@ -12,6 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+ifneq ($(TARGET_BUILD_PDK),true)
 LOCAL_PATH := $(call my-dir)
 
 # We use copy-file-to-new-target so that the installed
@@ -36,3 +37,4 @@
 	$(hide) chmod 755 $@
 
 # Apicheck is now part of Doclava -- See external/doclava.
+endif
diff --git a/tools/check_radio_versions.py b/tools/check_radio_versions.py
new file mode 100755
index 0000000..ebe621f
--- /dev/null
+++ b/tools/check_radio_versions.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2012 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import sys
+import os
+
+try:
+  from hashlib import sha1
+except ImportError:
+  from sha import sha as sha1
+
+if len(sys.argv) < 2:
+  sys.exit(0)
+
+build_info = {}
+f = open(sys.argv[1])
+for line in f:
+  line = line.strip()
+  if line.startswith("require"):
+    key, value = line.split()[1].split("=", 1)
+    build_info[key] = value
+f.close()
+
+bad = False
+
+for item in sys.argv[2:]:
+  key, fn = item.split(":", 1)
+
+  values = build_info.get(key, None)
+  if not values:
+    continue
+  values = values.split("|")
+
+  f = open(fn, "rb")
+  digest = sha1(f.read()).hexdigest()
+  f.close()
+
+  versions = {}
+  try:
+    f = open(fn + ".sha1")
+  except IOError:
+    if not bad: print
+    print "*** Error opening \"%s.sha1\"; can't verify %s" % (fn, key)
+    bad = True
+    continue
+  for line in f:
+    line = line.strip()
+    if not line or line.startswith("#"): continue
+    h, v = line.split()
+    versions[h] = v
+
+  if digest not in versions:
+    if not bad: print
+    print "*** SHA-1 hash of \"%s\" doesn't appear in \"%s.sha1\"" % (fn, fn)
+    bad = True
+    continue
+
+  if versions[digest] not in values:
+    if not bad: print
+    print "*** \"%s\" is version %s; not any %s allowed by \"%s\"." % (
+        fn, versions[digest], key, sys.argv[1])
+    bad = True
+
+if bad:
+  print
+  sys.exit(1)
diff --git a/tools/diff_package_overlays.py b/tools/diff_package_overlays.py
new file mode 100755
index 0000000..0e2c773
--- /dev/null
+++ b/tools/diff_package_overlays.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2012 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.
+
+"""
+Prints to stdout the package names that have overlay changes between
+current_overlays.txt and previous_overlays.txt.
+
+Usage: diff_package_overlays.py <current_packages.txt> <current_overlays.txt> <previous_overlays.txt>
+current_packages.txt contains all package names separated by space in the current build.
+This script modfies current_packages.txt if necessary: if there is a package in
+previous_overlays.txt but absent from current_packages.txt, we copy that line
+from previous_overlays.txt over to current_packages.txt. Usually that means we
+just don't care that package in the current build (for example we are switching
+from a full build to a partial build with mm/mmm), and we should carry on the
+previous overlay config so current_overlays.txt always reflects the current
+status of the entire tree.
+
+Format of current_overlays.txt and previous_overlays.txt:
+  <package_name> <resource_overlay> [resource_overlay ...]
+  <package_name> <resource_overlay> [resource_overlay ...]
+  ...
+"""
+
+import sys
+
+def main(argv):
+  if len(argv) != 4:
+    print >> sys.stderr, __doc__
+    sys.exit(1)
+
+  f = open(argv[1])
+  all_packages = set(f.read().split())
+  f.close()
+
+  def load_overlay_config(filename):
+    f = open(filename)
+    result = {}
+    for line in f:
+      line = line.strip()
+      if not line or line.startswith("#"):
+        continue
+      words = line.split()
+      result[words[0]] = " ".join(words[1:])
+    f.close()
+    return result
+
+  current_overlays = load_overlay_config(argv[2])
+  previous_overlays = load_overlay_config(argv[3])
+
+  result = []
+  carryon = []
+  for p in current_overlays:
+    if p not in previous_overlays:
+      result.append(p)
+    elif current_overlays[p] != previous_overlays[p]:
+      result.append(p)
+  for p in previous_overlays:
+    if p not in current_overlays:
+      if p in all_packages:
+        # overlay changed
+        result.append(p)
+      else:
+        # we don't build p in the current build.
+        carryon.append(p)
+
+  # Add carryon to the current overlay config file.
+  if carryon:
+    f = open(argv[2], "a")
+    for p in carryon:
+      f.write(p + " " + previous_overlays[p] + "\n")
+    f.close()
+
+  # Print out the package names that have overlay change.
+  for r in result:
+    print r
+
+if __name__ == "__main__":
+  main(sys.argv)
diff --git a/tools/generate-notice-files.py b/tools/generate-notice-files.py
new file mode 100755
index 0000000..4571b70
--- /dev/null
+++ b/tools/generate-notice-files.py
@@ -0,0 +1,188 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2012 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.
+"""
+Usage: generate-notice-files [plain text output file] [html output file] [file title] [directory of notices]
+
+Generate the Android notice files, including both text and html files.
+
+-h to display this usage message and exit.
+"""
+from collections import defaultdict
+import getopt
+import hashlib
+import itertools
+import os
+import os.path
+import re
+import sys
+
+MD5_BLOCKSIZE = 1024 * 1024
+HTML_ESCAPE_TABLE = {
+    "&": "&amp;",
+    '"': "&quot;",
+    "'": "&apos;",
+    ">": "&gt;",
+    "<": "&lt;",
+    }
+
+try:
+  opts, args = getopt.getopt(sys.argv[1:], "h")
+except getopt.GetoptError, err:
+    print str(err)
+    print __doc__
+    sys.exit(2)
+
+for o, a in opts:
+  if o == "-h":
+    print __doc__
+    sys.exit(2)
+  else:
+    print >> sys.stderr, "unhandled option %s" % (o,)
+
+if len(args) != 4:
+    print """need exactly four arguments, the two output files, the file title
+             and the directory containing notices, not %d""" % (len(args),)
+    print __doc__
+    sys.exit(1)
+
+def hexify(s):
+    return ("%02x"*len(s)) % tuple(map(ord, s))
+
+def md5sum(filename):
+    """Calculate an MD5 of the file given by FILENAME,
+    and return hex digest as a string.
+    Output should be compatible with md5sum command"""
+
+    f = open(filename, "rb")
+    sum = hashlib.md5()
+    while 1:
+        block = f.read(MD5_BLOCKSIZE)
+        if not block:
+            break
+        sum.update(block)
+    f.close()
+    return hexify(sum.digest())
+
+
+def html_escape(text):
+    """Produce entities within text."""
+    return "".join(HTML_ESCAPE_TABLE.get(c,c) for c in text)
+
+HTML_OUTPUT_CSS="""
+<style type="text/css">
+body { padding: 0; font-family: sans-serif; }
+.same-license { background-color: #eeeeee; border-top: 20px solid white; padding: 10px; }
+.label { font-weight: bold; }
+.file-list { margin-left: 1em; color: blue; }
+</style>
+"""
+
+def combine_notice_files_html(file_hash, input_dir, output_filename):
+    """Combine notice files in FILE_HASH and output a HTML version to OUTPUT_FILENAME."""
+
+    SRC_DIR_STRIP_RE = re.compile(input_dir + "(/.*).txt")
+
+    # Set up a filename to row id table (anchors inside tables don't work in
+    # most browsers, but href's to table row ids do)
+    id_table = {}
+    id_count = 0
+    for value in file_hash.values():
+        for filename in value:
+             id_table[filename] = id_count
+        id_count += 1
+
+    # Open the output file, and output the header pieces
+    output_file = open(output_filename, "wb")
+
+    print >> output_file, "<html><head>"
+    print >> output_file, HTML_OUTPUT_CSS
+    print >> output_file, '</head><body topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0">'
+
+    # Output our table of contents
+    print >> output_file, '<div class="toc">'
+    print >> output_file, "<ul>"
+
+    # Flatten the list of lists into a single list of filenames
+    sorted_filenames = sorted(itertools.chain.from_iterable(file_hash.values()))
+
+    # Print out a nice table of contents
+    for filename in sorted_filenames:
+        stripped_filename = SRC_DIR_STRIP_RE.sub(r"\1", filename)
+        print >> output_file, '<li><a href="#id%d">%s</a></li>' % (id_table.get(filename), stripped_filename)
+
+    print >> output_file, "</ul>"
+    print >> output_file, "</div><!-- table of contents -->"
+    # Output the individual notice file lists
+    print >>output_file, '<table cellpadding="0" cellspacing="0" border="0">'
+    for value in file_hash.values():
+        print >> output_file, '<tr id="id%d"><td class="same-license">' % id_table.get(value[0])
+        print >> output_file, '<div class="label">Notices for file(s):</div>'
+        print >> output_file, '<div class="file-list">'
+        for filename in sorted(value):
+            print >> output_file, "%s <br/>" % (SRC_DIR_STRIP_RE.sub(r"\1", filename))
+        print >> output_file, "</div><!-- file-list -->"
+        print >> output_file
+        print >> output_file, '<pre class="license-text">'
+        print >> output_file, html_escape(open(value[0]).read())
+        print >> output_file, "</pre><!-- license-text -->"
+        print >> output_file, "</td></tr><!-- same-license -->"
+        print >> output_file
+        print >> output_file
+        print >> output_file
+
+    # Finish off the file output
+    print >> output_file, "</table>"
+    print >> output_file, "</body></html>"
+    output_file.close()
+
+def combine_notice_files_text(file_hash, input_dir, output_filename, file_title):
+    """Combine notice files in FILE_HASH and output a text version to OUTPUT_FILENAME."""
+
+    SRC_DIR_STRIP_RE = re.compile(input_dir + "(/.*).txt")
+    output_file = open(output_filename, "wb")
+    print >> output_file, file_title
+    for value in file_hash.values():
+      print >> output_file, "============================================================"
+      print >> output_file, "Notices for file(s):"
+      for filename in sorted(value):
+        print >> output_file, SRC_DIR_STRIP_RE.sub(r"\1", filename)
+      print >> output_file, "------------------------------------------------------------"
+      print >> output_file, open(value[0]).read()
+    output_file.close()
+
+def main(args):
+    txt_output_file = args[0]
+    html_output_file = args[1]
+    file_title = args[2]
+
+    # Find all the notice files and md5 them
+    input_dir = os.path.normpath(args[3])
+    files_with_same_hash = defaultdict(list)
+    for root, dir, files in os.walk(input_dir):
+        for file in files:
+            if file.endswith(".txt"):
+                filename = os.path.join(root, file)
+                file_md5sum = md5sum(filename)
+                files_with_same_hash[file_md5sum].append(filename)
+
+
+    print "Combining NOTICE files into HTML"
+    combine_notice_files_html(files_with_same_hash, input_dir, html_output_file)
+    print "Combining NOTICE files into text"
+    combine_notice_files_text(files_with_same_hash, input_dir, txt_output_file, file_title)
+
+if __name__ == "__main__":
+    main(args)
diff --git a/tools/java-event-log-tags.py b/tools/java-event-log-tags.py
index c63fa20..846d9cf 100755
--- a/tools/java-event-log-tags.py
+++ b/tools/java-event-log-tags.py
@@ -26,6 +26,7 @@
 import cStringIO
 import getopt
 import os
+import os.path
 import re
 import sys
 
@@ -144,4 +145,8 @@
 
 buffer.write("}\n");
 
+output_dir = os.path.dirname(output_file)
+if not os.path.exists(output_dir):
+  os.makedirs(output_dir)
+
 event_log_tags.WriteOutput(output_file, buffer)
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
new file mode 100755
index 0000000..a615d1a
--- /dev/null
+++ b/tools/releasetools/build_image.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Build image output_image_file from input_directory and properties_file.
+
+Usage:  build_image input_directory properties_file output_image_file
+
+"""
+import os
+import subprocess
+import sys
+
+
+def BuildImage(in_dir, prop_dict, out_file):
+  """Build an image to out_file from in_dir with property prop_dict.
+
+  Args:
+    in_dir: path of input directory.
+    prop_dict: property dictionary.
+    out_file: path of the output image file.
+
+  Returns:
+    True iff the image is built successfully.
+  """
+  build_command = []
+  fs_type = prop_dict.get("fs_type", "")
+  if fs_type.startswith("ext"):
+    build_command = ["mkuserimg.sh"]
+    if "extfs_sparse_flag" in prop_dict:
+      build_command.append(prop_dict["extfs_sparse_flag"])
+    build_command.extend([in_dir, out_file, fs_type,
+                          prop_dict["mount_point"]])
+    if "partition_size" in prop_dict:
+      build_command.append(prop_dict["partition_size"])
+    if "selinux_fc" in prop_dict:
+      build_command.append(prop_dict["selinux_fc"])
+  else:
+    build_command = ["mkyaffs2image", "-f"]
+    if prop_dict.get("mkyaffs2_extra_flags", None):
+      build_command.extend(prop_dict["mkyaffs2_extra_flags"].split())
+    build_command.append(in_dir)
+    build_command.append(out_file)
+    if "selinux_fc" in prop_dict:
+      build_command.append(prop_dict["selinux_fc"])
+      build_command.append(prop_dict["mount_point"])
+
+  print "Running: ", " ".join(build_command)
+  p = subprocess.Popen(build_command);
+  p.communicate()
+  return p.returncode == 0
+
+
+def ImagePropFromGlobalDict(glob_dict, mount_point):
+  """Build an image property dictionary from the global dictionary.
+
+  Args:
+    glob_dict: the global dictionary from the build system.
+    mount_point: such as "system", "data" etc.
+  """
+  d = {}
+
+  def copy_prop(src_p, dest_p):
+    if src_p in glob_dict:
+      d[dest_p] = str(glob_dict[src_p])
+
+  common_props = (
+      "extfs_sparse_flag",
+      "mkyaffs2_extra_flags",
+      "selinux_fc",
+      )
+  for p in common_props:
+    copy_prop(p, p)
+
+  d["mount_point"] = mount_point
+  if mount_point == "system":
+    copy_prop("fs_type", "fs_type")
+    copy_prop("system_size", "partition_size")
+  elif mount_point == "data":
+    copy_prop("fs_type", "fs_type")
+    copy_prop("userdata_size", "partition_size")
+  elif mount_point == "cache":
+    copy_prop("cache_fs_type", "fs_type")
+    copy_prop("cache_size", "partition_size")
+
+  return d
+
+
+def LoadGlobalDict(filename):
+  """Load "name=value" pairs from filename"""
+  d = {}
+  f = open(filename)
+  for line in f:
+    line = line.strip()
+    if not line or line.startswith("#"):
+      continue
+    k, v = line.split("=", 1)
+    d[k] = v
+  f.close()
+  return d
+
+
+def main(argv):
+  if len(argv) != 3:
+    print __doc__
+    sys.exit(1)
+
+  in_dir = argv[0]
+  glob_dict_file = argv[1]
+  out_file = argv[2]
+
+  glob_dict = LoadGlobalDict(glob_dict_file)
+  image_filename = os.path.basename(out_file)
+  mount_point = ""
+  if image_filename == "system.img":
+    mount_point = "system"
+  elif image_filename == "userdata.img":
+    mount_point = "data"
+  elif image_filename == "cache.img":
+    mount_point = "cache"
+  else:
+    print >> sys.stderr, "error: unknown image file name ", image_filename
+    exit(1)
+
+  image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
+  if not BuildImage(in_dir, image_properties, out_file):
+    print >> sys.stderr, "error: failed to build %s from %s" % (out_file, in_dir)
+    exit(1)
+
+
+if __name__ == '__main__':
+  main(sys.argv[1:])
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 4957354..5e4055a 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -138,6 +138,7 @@
   makeint("blocksize")
   makeint("system_size")
   makeint("userdata_size")
+  makeint("cache_size")
   makeint("recovery_size")
   makeint("boot_size")
 
@@ -195,7 +196,7 @@
   for k, v in sorted(d.items()):
     print "%-25s = (%s) %s" % (k, type(v).__name__, v)
 
-def BuildBootableImage(sourcedir):
+def BuildBootableImage(sourcedir, fs_config_file):
   """Take a kernel, cmdline, and ramdisk directory from the input (in
   'sourcedir'), and turn them into a boot image.  Return the image
   data, or None if sourcedir does not appear to contains files for
@@ -208,8 +209,11 @@
   ramdisk_img = tempfile.NamedTemporaryFile()
   img = tempfile.NamedTemporaryFile()
 
-  p1 = Run(["mkbootfs", os.path.join(sourcedir, "RAMDISK")],
-           stdout=subprocess.PIPE)
+  if os.access(fs_config_file, os.F_OK):
+    cmd = ["mkbootfs", "-f", fs_config_file, os.path.join(sourcedir, "RAMDISK")]
+  else:
+    cmd = ["mkbootfs", os.path.join(sourcedir, "RAMDISK")]
+  p1 = Run(cmd, stdout=subprocess.PIPE)
   p2 = Run(["minigzip"],
            stdin=p1.stdout, stdout=ramdisk_img.file.fileno())
 
@@ -264,7 +268,9 @@
     return File.FromLocalFile(name, prebuilt_path)
   else:
     print "building image from target_files %s..." % (tree_subdir,)
-    return File(name, BuildBootableImage(os.path.join(unpack_dir, tree_subdir)))
+    fs_config = "META/" + tree_subdir.lower() + "_filesystem_config.txt"
+    return File(name, BuildBootableImage(os.path.join(unpack_dir, tree_subdir),
+                                         os.path.join(unpack_dir, fs_config)))
 
 
 def UnzipTemp(filename, pattern=None):
@@ -389,24 +395,27 @@
     if mount_point == "/userdata": mount_point = "/data"
     p = info_dict["fstab"][mount_point]
     fs_type = p.fs_type
-    limit = info_dict.get(p.device + "_size", None)
+    device = p.device
+    if "/" in device:
+      device = device[device.rfind("/")+1:]
+    limit = info_dict.get(device + "_size", None)
   if not fs_type or not limit: return
 
   if fs_type == "yaffs2":
     # image size should be increased by 1/64th to account for the
     # spare area (64 bytes per 2k page)
     limit = limit / 2048 * (2048+64)
-    size = len(data)
-    pct = float(size) * 100.0 / limit
-    msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit)
-    if pct >= 99.0:
-      raise ExternalError(msg)
-    elif pct >= 95.0:
-      print
-      print "  WARNING: ", msg
-      print
-    elif OPTIONS.verbose:
-      print "  ", msg
+  size = len(data)
+  pct = float(size) * 100.0 / limit
+  msg = "%s size (%d) is %.2f%% of limit (%d)" % (target, size, pct, limit)
+  if pct >= 99.0:
+    raise ExternalError(msg)
+  elif pct >= 95.0:
+    print
+    print "  WARNING: ", msg
+    print
+  elif OPTIONS.verbose:
+    print "  ", msg
 
 
 def ReadApkCerts(tf_zip):
@@ -659,6 +668,10 @@
     assertions they like."""
     return self._DoCall("FullOTA_Assertions")
 
+  def FullOTA_InstallBegin(self):
+    """Called at the start of full OTA installation."""
+    return self._DoCall("FullOTA_InstallBegin")
+
   def FullOTA_InstallEnd(self):
     """Called at the end of full OTA installation; typically this is
     used to install the image for the device's baseband processor."""
@@ -670,12 +683,23 @@
     additional assertions they like."""
     return self._DoCall("IncrementalOTA_Assertions")
 
+  def IncrementalOTA_VerifyBegin(self):
+    """Called at the start of the verification phase of incremental
+    OTA installation; additional checks can be placed here to abort
+    the script before any changes are made."""
+    return self._DoCall("IncrementalOTA_VerifyBegin")
+
   def IncrementalOTA_VerifyEnd(self):
     """Called at the end of the verification phase of incremental OTA
     installation; additional checks can be placed here to abort the
     script before any changes are made."""
     return self._DoCall("IncrementalOTA_VerifyEnd")
 
+  def IncrementalOTA_InstallBegin(self):
+    """Called at the start of incremental OTA installation (after
+    verification is complete)."""
+    return self._DoCall("IncrementalOTA_InstallBegin")
+
   def IncrementalOTA_InstallEnd(self):
     """Called at the end of incremental OTA installation; typically
     this is used to install the image for the device's baseband
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index 12bb48b..5672b5a 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -228,20 +228,6 @@
              ",\0".join(['"' + i + '"' for i in sorted(links)]) + ");")
       self.script.append(self._WordWrap(cmd))
 
-  def RetouchBinaries(self, file_list):
-    """Execute the retouch instructions in files listed."""
-    cmd = ('retouch_binaries(' +
-           ', '.join(['"' + i[0] + '", "' + i[1] + '"' for i in file_list]) +
-           ');')
-    self.script.append(self._WordWrap(cmd))
-
-  def UndoRetouchBinaries(self, file_list):
-    """Undo the retouching (retouch to zero offset)."""
-    cmd = ('undo_retouch_binaries(' +
-           ', '.join(['"' + i[0] + '", "' + i[1] + '"' for i in file_list]) +
-           ');')
-    self.script.append(self._WordWrap(cmd))
-
   def AppendExtra(self, extra):
     """Append text verbatim to the output script."""
     self.script.append(extra)
diff --git a/tools/releasetools/img_from_target_files b/tools/releasetools/img_from_target_files
index ad03398..002e6e6 100755
--- a/tools/releasetools/img_from_target_files
+++ b/tools/releasetools/img_from_target_files
@@ -27,10 +27,6 @@
       Include only the bootable images (eg 'boot' and 'recovery') in
       the output.
 
-  -S  (--file_context) <file>
-      the file contexts configuration used to assign SELinux file
-      context attributes.
-
 """
 
 import sys
@@ -51,10 +47,10 @@
 if not hasattr(os, "SEEK_SET"):
   os.SEEK_SET = 0
 
+import build_image
 import common
 
 OPTIONS = common.OPTIONS
-OPTIONS.selinux_fc = None
 
 def AddUserdata(output_zip):
   """Create an empty userdata image and store it in output_zip."""
@@ -69,32 +65,13 @@
   os.mkdir(user_dir)
   img = tempfile.NamedTemporaryFile()
 
-  build_command = []
+  image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict,
+                                                    "data")
   fstab = OPTIONS.info_dict["fstab"]
-  if fstab and fstab["/data"].fs_type.startswith("ext"):
-    build_command = ["mkuserimg.sh"]
-    if "extfs_sparse_flag" in OPTIONS.info_dict:
-      build_command.append(OPTIONS.info_dict["extfs_sparse_flag"])
-    build_command.extend([user_dir, img.name,
-                     fstab["/data"].fs_type, "data"])
-    if "userdata_size" in OPTIONS.info_dict:
-      build_command.append(str(OPTIONS.info_dict["userdata_size"]))
-    if OPTIONS.selinux_fc is not None:
-      build_command.append(OPTIONS.selinux_fc)
-  else:
-    build_command = ["mkyaffs2image", "-f"]
-    extra = OPTIONS.info_dict.get("mkyaffs2_extra_flags", None)
-    if extra:
-      build_command.extend(extra.split())
-    build_command.append(user_dir)
-    build_command.append(img.name)
-    if OPTIONS.selinux_fc is not None:
-      build_command.append(OPTIONS.selinux_fc)
-      build_command.append("/data")
-
-  p = common.Run(build_command);
-  p.communicate()
-  assert p.returncode == 0, "build userdata.img image failed"
+  if fstab:
+    image_props["fs_type" ] = fstab["/data"].fs_type
+  succ = build_image.BuildImage(user_dir, image_props, img.name)
+  assert succ, "build userdata.img image failed"
 
   common.CheckSize(img.name, "userdata.img", OPTIONS.info_dict)
   output_zip.write(img.name, "userdata.img")
@@ -103,6 +80,38 @@
   os.rmdir(temp_dir)
 
 
+def AddCache(output_zip):
+  """Create an empty cache image and store it in output_zip."""
+
+  image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict,
+                                                    "cache")
+  # The build system has to explicitly request for cache.img.
+  if "fs_type" not in image_props:
+    return
+
+  print "creating cache.img..."
+
+  # The name of the directory it is making an image out of matters to
+  # mkyaffs2image.  So we create a temp dir, and within it we create an
+  # empty dir named "cache", and build the image from that.
+  temp_dir = tempfile.mkdtemp()
+  user_dir = os.path.join(temp_dir, "cache")
+  os.mkdir(user_dir)
+  img = tempfile.NamedTemporaryFile()
+
+  fstab = OPTIONS.info_dict["fstab"]
+  if fstab:
+    image_props["fs_type" ] = fstab["/cache"].fs_type
+  succ = build_image.BuildImage(user_dir, image_props, img.name)
+  assert succ, "build cache.img image failed"
+
+  common.CheckSize(img.name, "cache.img", OPTIONS.info_dict)
+  output_zip.write(img.name, "cache.img")
+  img.close()
+  os.rmdir(user_dir)
+  os.rmdir(temp_dir)
+
+
 def AddSystem(output_zip):
   """Turn the contents of SYSTEM into a system image and store it in
   output_zip."""
@@ -125,33 +134,14 @@
     if (e.errno == errno.EEXIST):
       pass
 
-  build_command = []
+  image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict,
+                                                    "system")
   fstab = OPTIONS.info_dict["fstab"]
-  if fstab and fstab["/system"].fs_type.startswith("ext"):
-
-    build_command = ["mkuserimg.sh"]
-    if "extfs_sparse_flag" in OPTIONS.info_dict:
-      build_command.append(OPTIONS.info_dict["extfs_sparse_flag"])
-    build_command.extend([os.path.join(OPTIONS.input_tmp, "system"), img.name,
-                     fstab["/system"].fs_type, "system"])
-    if "system_size" in OPTIONS.info_dict:
-      build_command.append(str(OPTIONS.info_dict["system_size"]))
-    if OPTIONS.selinux_fc is not None:
-      build_command.append(OPTIONS.selinux_fc)
-  else:
-    build_command = ["mkyaffs2image", "-f"]
-    extra = OPTIONS.info_dict.get("mkyaffs2_extra_flags", None)
-    if extra:
-      build_command.extend(extra.split())
-    build_command.append(os.path.join(OPTIONS.input_tmp, "system"))
-    build_command.append(img.name)
-    if OPTIONS.selinux_fc is not None:
-      build_command.append(OPTIONS.selinux_fc)
-      build_command.append("/system")
-
-  p = common.Run(build_command)
-  p.communicate()
-  assert p.returncode == 0, "build system.img image failed"
+  if fstab:
+    image_props["fs_type" ] = fstab["/system"].fs_type
+  succ = build_image.BuildImage(os.path.join(OPTIONS.input_tmp, "system"),
+                                image_props, img.name)
+  assert succ, "build system.img image failed"
 
   img.seek(os.SEEK_SET, 0)
   data = img.read()
@@ -175,17 +165,14 @@
       pass       # deprecated
     if o in ("-z", "--bootable_zip"):
       bootable_only[0] = True
-    if o in ("-S", "--file_context"):
-      OPTIONS.selinux_fc = a
     else:
       return False
     return True
 
   args = common.ParseOptions(argv, __doc__,
-                             extra_opts="b:zS:",
+                             extra_opts="b:z",
                              extra_long_opts=["board_config=",
-                                              "bootable_zip",
-                                              "file_context="],
+                                              "bootable_zip"],
                              extra_option_handler=option_handler)
 
   bootable_only = bootable_only[0]
@@ -208,6 +195,7 @@
   if not bootable_only:
     AddSystem(output_zip)
     AddUserdata(output_zip)
+    AddCache(output_zip)
     CopyInfo(output_zip)
 
   print "cleaning up..."
diff --git a/tools/releasetools/ota_from_target_files b/tools/releasetools/ota_from_target_files
index f838c22..3dcfbee 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -52,10 +52,6 @@
   -a  (--aslr_mode)  <on|off>
       Specify whether to turn on ASLR for the package (on by default).
 
-  -S  (--file_context) <file>
-      the file contexts configuration used to assign SELinux file
-      context attributes
-
 """
 
 import sys
@@ -92,7 +88,6 @@
 OPTIONS.extra_script = None
 OPTIONS.aslr_mode = True
 OPTIONS.worker_threads = 3
-OPTIONS.selinux_fc = None
 
 def MostPopularKey(d, default):
   """Given a dict, return the key corresponding to the largest
@@ -266,15 +261,13 @@
                     substitute=None):
   """Copies files underneath system/ in the input zip to the output
   zip.  Populates the Item class with their metadata, and returns a
-  list of symlinks as well as a list of files that will be retouched.
-  output_zip may be None, in which case the copy is skipped (but the
-  other side effects still happen).  substitute is an optional dict
-  of {output filename: contents} to be output instead of certain input
-  files.
+  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
+  optional dict of {output filename: contents} to be output instead of
+  certain input files.
   """
 
   symlinks = []
-  retouch_files = []
 
   for info in input_zip.infolist():
     if info.filename.startswith("SYSTEM/"):
@@ -292,9 +285,6 @@
             data = substitute[fn]
           else:
             data = input_zip.read(info.filename)
-          if info.filename.startswith("SYSTEM/lib/") and IsRegular(info):
-            retouch_files.append(("/system/" + basefilename,
-                                  common.sha1(data).hexdigest()))
           output_zip.writestr(info2, data)
         if fn.endswith("/"):
           Item.Get(fn[:-1], dir=True)
@@ -302,7 +292,7 @@
           Item.Get(fn, dir=False)
 
   symlinks.sort()
-  return (symlinks, retouch_files)
+  return symlinks
 
 
 def SignOutput(temp_zip_name, output_zip_name):
@@ -388,26 +378,23 @@
 
   AppendAssertions(script, input_zip)
   device_specific.FullOTA_Assertions()
+  device_specific.FullOTA_InstallBegin()
 
   script.ShowProgress(0.5, 0)
 
   if OPTIONS.wipe_user_data:
     script.FormatPartition("/data")
 
-  if OPTIONS.selinux_fc is not None:
-    WritePolicyConfig(OPTIONS.selinux_fc, output_zip)
+  if "selinux_fc" in OPTIONS.info_dict:
+    WritePolicyConfig(OPTIONS.info_dict["selinux_fc"], output_zip)
 
   script.FormatPartition("/system")
   script.Mount("/system")
   script.UnpackPackageDir("recovery", "/system")
   script.UnpackPackageDir("system", "/system")
 
-  (symlinks, retouch_files) = CopySystemFiles(input_zip, output_zip)
+  symlinks = CopySystemFiles(input_zip, output_zip)
   script.MakeSymlinks(symlinks)
-  if OPTIONS.aslr_mode:
-    script.RetouchBinaries(retouch_files)
-  else:
-    script.UndoRetouchBinaries(retouch_files)
 
   boot_img = common.GetBootableImage("boot.img", "boot.img",
                                      OPTIONS.input_tmp, "BOOT")
@@ -450,17 +437,13 @@
   """Load all the files from SYSTEM/... in a given target-files
   ZipFile, and return a dict of {filename: File object}."""
   out = {}
-  retouch_files = []
   for info in z.infolist():
     if info.filename.startswith("SYSTEM/") and not IsSymlink(info):
       basefilename = info.filename[7:]
       fn = "system/" + basefilename
       data = z.read(info.filename)
       out[fn] = common.File(fn, data)
-      if info.filename.startswith("SYSTEM/lib/") and IsRegular(info):
-        retouch_files.append(("/system/" + basefilename,
-                              out[fn].sha1))
-  return (out, retouch_files)
+  return out
 
 
 def GetBuildProp(property, z):
@@ -499,9 +482,9 @@
       info_dict=OPTIONS.info_dict)
 
   print "Loading target..."
-  (target_data, target_retouch_files) = LoadSystemFiles(target_zip)
+  target_data = LoadSystemFiles(target_zip)
   print "Loading source..."
-  (source_data, source_retouch_files) = LoadSystemFiles(source_zip)
+  source_data = LoadSystemFiles(source_zip)
 
   verbatim_targets = []
   patch_list = []
@@ -570,6 +553,8 @@
 
   script.Print("Verifying current system...")
 
+  device_specific.IncrementalOTA_VerifyBegin()
+
   script.ShowProgress(0.1, 0)
   total_verify_size = float(sum([i[2].size for i in patch_list]) + 1)
   if updating_boot:
@@ -605,6 +590,8 @@
 
   script.Comment("---- start making changes here ----")
 
+  device_specific.IncrementalOTA_InstallBegin()
+
   if OPTIONS.wipe_user_data:
     script.Print("Erasing user data...")
     script.FormatPartition("/data")
@@ -671,7 +658,7 @@
 
   script.ShowProgress(0.1, 10)
 
-  (target_symlinks, target_retouch_dummies) = CopySystemFiles(target_zip, None)
+  target_symlinks = CopySystemFiles(target_zip, None)
 
   target_symlinks_d = dict([(i[1], i[0]) for i in target_symlinks])
   temp_script = script.MakeTemporary()
@@ -680,7 +667,7 @@
 
   # Note that this call will mess up the tree of Items, so make sure
   # we're done with it.
-  (source_symlinks, source_retouch_dummies) = CopySystemFiles(source_zip, None)
+  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
@@ -714,10 +701,6 @@
       to_create.append((dest, link))
   script.DeleteFiles([i[1] for i in to_create])
   script.MakeSymlinks(to_create)
-  if OPTIONS.aslr_mode:
-    script.RetouchBinaries(target_retouch_files)
-  else:
-    script.UndoRetouchBinaries(target_retouch_files)
 
   # Now that the symlinks are created, we can set all the
   # permissions.
@@ -764,14 +747,12 @@
         OPTIONS.aslr_mode = False
     elif o in ("--worker_threads"):
       OPTIONS.worker_threads = int(a)
-    elif o in ("-S", "--file_context"):
-      OPTIONS.selinux_fc = a
     else:
       return False
     return True
 
   args = common.ParseOptions(argv, __doc__,
-                             extra_opts="b:k:i:d:wne:a:S:",
+                             extra_opts="b:k:i:d:wne:a:",
                              extra_long_opts=["board_config=",
                                               "package_key=",
                                               "incremental_from=",
@@ -780,7 +761,6 @@
                                               "extra_script=",
                                               "worker_threads=",
                                               "aslr_mode=",
-                                              "file_context=",
                                               ],
                              extra_option_handler=option_handler)
 
diff --git a/tools/signapk/SignApk.java b/tools/signapk/SignApk.java
index c4d73c8..d8d9bf1 100644
--- a/tools/signapk/SignApk.java
+++ b/tools/signapk/SignApk.java
@@ -76,6 +76,8 @@
     private static final String CERT_SF_NAME = "META-INF/CERT.SF";
     private static final String CERT_RSA_NAME = "META-INF/CERT.RSA";
 
+    private static final String OTACERT_NAME = "META-INF/com/android/otacert";
+
     // Files matching this pattern are not copied to the output.
     private static Pattern stripPattern =
             Pattern.compile("^META-INF/(.*)[.](SF|RSA|DSA)$");
@@ -199,6 +201,7 @@
             String name = entry.getName();
             if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) &&
                 !name.equals(CERT_SF_NAME) && !name.equals(CERT_RSA_NAME) &&
+                !name.equals(OTACERT_NAME) &&
                 (stripPattern == null ||
                  !stripPattern.matcher(name).matches())) {
                 InputStream data = jar.getInputStream(entry);
@@ -217,6 +220,39 @@
         return output;
     }
 
+    /**
+     * Add a copy of the public key to the archive; this should
+     * exactly match one of the files in
+     * /system/etc/security/otacerts.zip on the device.  (The same
+     * cert can be extracted from the CERT.RSA file but this is much
+     * easier to get at.)
+     */
+    private static void addOtacert(JarOutputStream outputJar,
+                                   File publicKeyFile,
+                                   long timestamp,
+                                   Manifest manifest)
+        throws IOException, GeneralSecurityException {
+        BASE64Encoder base64 = new BASE64Encoder();
+        MessageDigest md = MessageDigest.getInstance("SHA1");
+
+        JarEntry je = new JarEntry(OTACERT_NAME);
+        je.setTime(timestamp);
+        outputJar.putNextEntry(je);
+        FileInputStream input = new FileInputStream(publicKeyFile);
+        byte[] b = new byte[4096];
+        int read;
+        while ((read = input.read(b)) != -1) {
+            outputJar.write(b, 0, read);
+            md.update(b, 0, read);
+        }
+        input.close();
+
+        Attributes attr = new Attributes();
+        attr.putValue("SHA1-Digest", base64.encode(md.digest()));
+        manifest.getEntries().put(OTACERT_NAME, attr);
+    }
+
+
     /** Write to another stream and also feed it to the Signature object. */
     private static class SignatureOutputStream extends FilterOutputStream {
         private Signature mSignature;
@@ -445,7 +481,8 @@
         FileOutputStream outputFile = null;
 
         try {
-            X509Certificate publicKey = readPublicKey(new File(args[argstart+0]));
+            File publicKeyFile = new File(args[argstart+0]);
+            X509Certificate publicKey = readPublicKey(publicKeyFile);
 
             // Assume the certificate is valid for at least an hour.
             long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;
@@ -464,8 +501,17 @@
 
             JarEntry je;
 
-            // MANIFEST.MF
             Manifest manifest = addDigestsToManifest(inputJar);
+
+            // Everything else
+            copyFiles(manifest, inputJar, outputJar, timestamp);
+
+            // otacert
+            if (signWholeFile) {
+                addOtacert(outputJar, publicKeyFile, timestamp, manifest);
+            }
+
+            // MANIFEST.MF
             je = new JarEntry(JarFile.MANIFEST_NAME);
             je.setTime(timestamp);
             outputJar.putNextEntry(je);
@@ -486,9 +532,6 @@
             outputJar.putNextEntry(je);
             writeSignatureBlock(signature, publicKey, outputJar);
 
-            // Everything else
-            copyFiles(manifest, inputJar, outputJar, timestamp);
-
             outputJar.close();
             outputJar = null;
             outputStream.flush();
diff --git a/tools/zipalign/ZipEntry.cpp b/tools/zipalign/ZipEntry.cpp
index bed0333..d4d366d 100644
--- a/tools/zipalign/ZipEntry.cpp
+++ b/tools/zipalign/ZipEntry.cpp
@@ -42,12 +42,12 @@
     long posn;
     bool hasDD;
 
-    //LOGV("initFromCDE ---\n");
+    //ALOGV("initFromCDE ---\n");
 
     /* read the CDE */
     result = mCDE.read(fp);
     if (result != NO_ERROR) {
-        LOGD("mCDE.read failed\n");
+        ALOGD("mCDE.read failed\n");
         return result;
     }
 
@@ -56,14 +56,14 @@
     /* using the info in the CDE, go load up the LFH */
     posn = ftell(fp);
     if (fseek(fp, mCDE.mLocalHeaderRelOffset, SEEK_SET) != 0) {
-        LOGD("local header seek failed (%ld)\n",
+        ALOGD("local header seek failed (%ld)\n",
             mCDE.mLocalHeaderRelOffset);
         return UNKNOWN_ERROR;
     }
 
     result = mLFH.read(fp);
     if (result != NO_ERROR) {
-        LOGD("mLFH.read failed\n");
+        ALOGD("mLFH.read failed\n");
         return result;
     }
 
@@ -81,7 +81,7 @@
     hasDD = (mLFH.mGPBitFlag & kUsesDataDescr) != 0;
     if (hasDD) {
         // do something clever
-        //LOGD("+++ has data descriptor\n");
+        //ALOGD("+++ has data descriptor\n");
     }
 
     /*
@@ -90,7 +90,7 @@
      * prefer the CDE values.)
      */
     if (!hasDD && !compareHeaders()) {
-        LOGW("WARNING: header mismatch\n");
+        ALOGW("WARNING: header mismatch\n");
         // keep going?
     }
 
@@ -200,7 +200,7 @@
     if (padding <= 0)
         return INVALID_OPERATION;
 
-    //LOGI("HEY: adding %d pad bytes to existing %d in %s\n",
+    //ALOGI("HEY: adding %d pad bytes to existing %d in %s\n",
     //    padding, mLFH.mExtraFieldLength, mCDE.mFileName);
 
     if (mLFH.mExtraFieldLength > 0) {
@@ -280,50 +280,50 @@
 bool ZipEntry::compareHeaders(void) const
 {
     if (mCDE.mVersionToExtract != mLFH.mVersionToExtract) {
-        LOGV("cmp: VersionToExtract\n");
+        ALOGV("cmp: VersionToExtract\n");
         return false;
     }
     if (mCDE.mGPBitFlag != mLFH.mGPBitFlag) {
-        LOGV("cmp: GPBitFlag\n");
+        ALOGV("cmp: GPBitFlag\n");
         return false;
     }
     if (mCDE.mCompressionMethod != mLFH.mCompressionMethod) {
-        LOGV("cmp: CompressionMethod\n");
+        ALOGV("cmp: CompressionMethod\n");
         return false;
     }
     if (mCDE.mLastModFileTime != mLFH.mLastModFileTime) {
-        LOGV("cmp: LastModFileTime\n");
+        ALOGV("cmp: LastModFileTime\n");
         return false;
     }
     if (mCDE.mLastModFileDate != mLFH.mLastModFileDate) {
-        LOGV("cmp: LastModFileDate\n");
+        ALOGV("cmp: LastModFileDate\n");
         return false;
     }
     if (mCDE.mCRC32 != mLFH.mCRC32) {
-        LOGV("cmp: CRC32\n");
+        ALOGV("cmp: CRC32\n");
         return false;
     }
     if (mCDE.mCompressedSize != mLFH.mCompressedSize) {
-        LOGV("cmp: CompressedSize\n");
+        ALOGV("cmp: CompressedSize\n");
         return false;
     }
     if (mCDE.mUncompressedSize != mLFH.mUncompressedSize) {
-        LOGV("cmp: UncompressedSize\n");
+        ALOGV("cmp: UncompressedSize\n");
         return false;
     }
     if (mCDE.mFileNameLength != mLFH.mFileNameLength) {
-        LOGV("cmp: FileNameLength\n");
+        ALOGV("cmp: FileNameLength\n");
         return false;
     }
 #if 0       // this seems to be used for padding, not real data
     if (mCDE.mExtraFieldLength != mLFH.mExtraFieldLength) {
-        LOGV("cmp: ExtraFieldLength\n");
+        ALOGV("cmp: ExtraFieldLength\n");
         return false;
     }
 #endif
     if (mCDE.mFileName != NULL) {
         if (strcmp((char*) mCDE.mFileName, (char*) mLFH.mFileName) != 0) {
-            LOGV("cmp: FileName\n");
+            ALOGV("cmp: FileName\n");
             return false;
         }
     }
@@ -413,7 +413,7 @@
     }
 
     if (ZipEntry::getLongLE(&buf[0x00]) != kSignature) {
-        LOGD("whoops: didn't find expected signature\n");
+        ALOGD("whoops: didn't find expected signature\n");
         result = UNKNOWN_ERROR;
         goto bail;
     }
@@ -506,17 +506,17 @@
  */
 void ZipEntry::LocalFileHeader::dump(void) const
 {
-    LOGD(" LocalFileHeader contents:\n");
-    LOGD("  versToExt=%u gpBits=0x%04x compression=%u\n",
+    ALOGD(" LocalFileHeader contents:\n");
+    ALOGD("  versToExt=%u gpBits=0x%04x compression=%u\n",
         mVersionToExtract, mGPBitFlag, mCompressionMethod);
-    LOGD("  modTime=0x%04x modDate=0x%04x crc32=0x%08lx\n",
+    ALOGD("  modTime=0x%04x modDate=0x%04x crc32=0x%08lx\n",
         mLastModFileTime, mLastModFileDate, mCRC32);
-    LOGD("  compressedSize=%lu uncompressedSize=%lu\n",
+    ALOGD("  compressedSize=%lu uncompressedSize=%lu\n",
         mCompressedSize, mUncompressedSize);
-    LOGD("  filenameLen=%u extraLen=%u\n",
+    ALOGD("  filenameLen=%u extraLen=%u\n",
         mFileNameLength, mExtraFieldLength);
     if (mFileName != NULL)
-        LOGD("  filename: '%s'\n", mFileName);
+        ALOGD("  filename: '%s'\n", mFileName);
 }
 
 
@@ -549,7 +549,7 @@
     }
 
     if (ZipEntry::getLongLE(&buf[0x00]) != kSignature) {
-        LOGD("Whoops: didn't find expected signature\n");
+        ALOGD("Whoops: didn't find expected signature\n");
         result = UNKNOWN_ERROR;
         goto bail;
     }
@@ -675,22 +675,22 @@
  */
 void ZipEntry::CentralDirEntry::dump(void) const
 {
-    LOGD(" CentralDirEntry contents:\n");
-    LOGD("  versMadeBy=%u versToExt=%u gpBits=0x%04x compression=%u\n",
+    ALOGD(" CentralDirEntry contents:\n");
+    ALOGD("  versMadeBy=%u versToExt=%u gpBits=0x%04x compression=%u\n",
         mVersionMadeBy, mVersionToExtract, mGPBitFlag, mCompressionMethod);
-    LOGD("  modTime=0x%04x modDate=0x%04x crc32=0x%08lx\n",
+    ALOGD("  modTime=0x%04x modDate=0x%04x crc32=0x%08lx\n",
         mLastModFileTime, mLastModFileDate, mCRC32);
-    LOGD("  compressedSize=%lu uncompressedSize=%lu\n",
+    ALOGD("  compressedSize=%lu uncompressedSize=%lu\n",
         mCompressedSize, mUncompressedSize);
-    LOGD("  filenameLen=%u extraLen=%u commentLen=%u\n",
+    ALOGD("  filenameLen=%u extraLen=%u commentLen=%u\n",
         mFileNameLength, mExtraFieldLength, mFileCommentLength);
-    LOGD("  diskNumStart=%u intAttr=0x%04x extAttr=0x%08lx relOffset=%lu\n",
+    ALOGD("  diskNumStart=%u intAttr=0x%04x extAttr=0x%08lx relOffset=%lu\n",
         mDiskNumberStart, mInternalAttrs, mExternalAttrs,
         mLocalHeaderRelOffset);
 
     if (mFileName != NULL)
-        LOGD("  filename: '%s'\n", mFileName);
+        ALOGD("  filename: '%s'\n", mFileName);
     if (mFileComment != NULL)
-        LOGD("  comment: '%s'\n", mFileComment);
+        ALOGD("  comment: '%s'\n", mFileComment);
 }
 
diff --git a/tools/zipalign/ZipFile.cpp b/tools/zipalign/ZipFile.cpp
index 62c9383..3994c31 100644
--- a/tools/zipalign/ZipFile.cpp
+++ b/tools/zipalign/ZipFile.cpp
@@ -20,8 +20,8 @@
 
 #define LOG_TAG "zip"
 
-#include <utils/ZipUtils.h>
 #include <utils/Log.h>
+#include <utils/ZipUtils.h>
 
 #include "ZipFile.h"
 
@@ -78,7 +78,7 @@
         newArchive = (access(zipFileName, F_OK) != 0);
         if (!(flags & kOpenCreate) && newArchive) {
             /* not creating, must already exist */
-            LOGD("File %s does not exist", zipFileName);
+            ALOGD("File %s does not exist", zipFileName);
             return NAME_NOT_FOUND;
         }
     }
@@ -96,7 +96,7 @@
     mZipFp = fopen(zipFileName, openflags);
     if (mZipFp == NULL) {
         int err = errno;
-        LOGD("fopen failed: %d\n", err);
+        ALOGD("fopen failed: %d\n", err);
         return errnoToStatus(err);
     }
 
@@ -215,14 +215,14 @@
 
     /* too small to be a ZIP archive? */
     if (fileLength < EndOfCentralDir::kEOCDLen) {
-        LOGD("Length is %ld -- too small\n", (long)fileLength);
+        ALOGD("Length is %ld -- too small\n", (long)fileLength);
         result = INVALID_OPERATION;
         goto bail;
     }
 
     buf = new unsigned char[EndOfCentralDir::kMaxEOCDSearch];
     if (buf == NULL) {
-        LOGD("Failure allocating %d bytes for EOCD search",
+        ALOGD("Failure allocating %d bytes for EOCD search",
              EndOfCentralDir::kMaxEOCDSearch);
         result = NO_MEMORY;
         goto bail;
@@ -236,14 +236,14 @@
         readAmount = (long) fileLength;
     }
     if (fseek(mZipFp, seekStart, SEEK_SET) != 0) {
-        LOGD("Failure seeking to end of zip at %ld", (long) seekStart);
+        ALOGD("Failure seeking to end of zip at %ld", (long) seekStart);
         result = UNKNOWN_ERROR;
         goto bail;
     }
 
     /* read the last part of the file into the buffer */
     if (fread(buf, 1, readAmount, mZipFp) != (size_t) readAmount) {
-        LOGD("short file? wanted %ld\n", readAmount);
+        ALOGD("short file? wanted %ld\n", readAmount);
         result = UNKNOWN_ERROR;
         goto bail;
     }
@@ -253,12 +253,12 @@
         if (buf[i] == 0x50 &&
             ZipEntry::getLongLE(&buf[i]) == EndOfCentralDir::kSignature)
         {
-            LOGV("+++ Found EOCD at buf+%d\n", i);
+            ALOGV("+++ Found EOCD at buf+%d\n", i);
             break;
         }
     }
     if (i < 0) {
-        LOGD("EOCD not found, not Zip\n");
+        ALOGD("EOCD not found, not Zip\n");
         result = INVALID_OPERATION;
         goto bail;
     }
@@ -266,7 +266,7 @@
     /* extract eocd values */
     result = mEOCD.readBuf(buf + i, readAmount - i);
     if (result != NO_ERROR) {
-        LOGD("Failure reading %ld bytes of EOCD values", readAmount - i);
+        ALOGD("Failure reading %ld bytes of EOCD values", readAmount - i);
         goto bail;
     }
     //mEOCD.dump();
@@ -274,7 +274,7 @@
     if (mEOCD.mDiskNumber != 0 || mEOCD.mDiskWithCentralDir != 0 ||
         mEOCD.mNumEntries != mEOCD.mTotalNumEntries)
     {
-        LOGD("Archive spanning not supported\n");
+        ALOGD("Archive spanning not supported\n");
         result = INVALID_OPERATION;
         goto bail;
     }
@@ -294,7 +294,7 @@
      * we're hoping to preserve.
      */
     if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
-        LOGD("Failure seeking to central dir offset %ld\n",
+        ALOGD("Failure seeking to central dir offset %ld\n",
              mEOCD.mCentralDirOffset);
         result = UNKNOWN_ERROR;
         goto bail;
@@ -303,14 +303,14 @@
     /*
      * Loop through and read the central dir entries.
      */
-    LOGV("Scanning %d entries...\n", mEOCD.mTotalNumEntries);
+    ALOGV("Scanning %d entries...\n", mEOCD.mTotalNumEntries);
     int entry;
     for (entry = 0; entry < mEOCD.mTotalNumEntries; entry++) {
         ZipEntry* pEntry = new ZipEntry;
 
         result = pEntry->initFromCDE(mZipFp);
         if (result != NO_ERROR) {
-            LOGD("initFromCDE failed\n");
+            ALOGD("initFromCDE failed\n");
             delete pEntry;
             goto bail;
         }
@@ -325,16 +325,16 @@
     {
         unsigned char checkBuf[4];
         if (fread(checkBuf, 1, 4, mZipFp) != 4) {
-            LOGD("EOCD check read failed\n");
+            ALOGD("EOCD check read failed\n");
             result = INVALID_OPERATION;
             goto bail;
         }
         if (ZipEntry::getLongLE(checkBuf) != EndOfCentralDir::kSignature) {
-            LOGD("EOCD read check failed\n");
+            ALOGD("EOCD read check failed\n");
             result = UNKNOWN_ERROR;
             goto bail;
         }
-        LOGV("+++ EOCD read check passed\n");
+        ALOGV("+++ EOCD read check passed\n");
     }
 
 bail:
@@ -416,7 +416,7 @@
             bool failed = false;
             result = compressFpToFp(mZipFp, inputFp, data, size, &crc);
             if (result != NO_ERROR) {
-                LOGD("compression failed, storing\n");
+                ALOGD("compression failed, storing\n");
                 failed = true;
             } else {
                 /*
@@ -427,7 +427,7 @@
                 long src = inputFp ? ftell(inputFp) : size;
                 long dst = ftell(mZipFp) - startPosn;
                 if (dst + (dst / 10) > src) {
-                    LOGD("insufficient compression (src=%ld dst=%ld), storing\n",
+                    ALOGD("insufficient compression (src=%ld dst=%ld), storing\n",
                         src, dst);
                     failed = true;
                 }
@@ -449,7 +449,7 @@
             }
             if (result != NO_ERROR) {
                 // don't need to truncate; happens in CDE rewrite
-                LOGD("failed copying data in\n");
+                ALOGD("failed copying data in\n");
                 goto bail;
             }
         }
@@ -468,14 +468,14 @@
         scanResult = ZipUtils::examineGzip(inputFp, &method, &uncompressedLen,
                         &compressedLen, &crc);
         if (!scanResult || method != ZipEntry::kCompressDeflated) {
-            LOGD("this isn't a deflated gzip file?");
+            ALOGD("this isn't a deflated gzip file?");
             result = UNKNOWN_ERROR;
             goto bail;
         }
 
         result = copyPartialFpToFp(mZipFp, inputFp, compressedLen, NULL);
         if (result != NO_ERROR) {
-            LOGD("failed copying gzip data in\n");
+            ALOGD("failed copying gzip data in\n");
             goto bail;
         }
     } else {
@@ -603,7 +603,7 @@
     if (copyPartialFpToFp(mZipFp, pSourceZip->mZipFp, copyLen, NULL)
         != NO_ERROR)
     {
-        LOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
+        ALOGW("copy of '%s' failed\n", pEntry->mCDE.mFileName);
         result = UNKNOWN_ERROR;
         goto bail;
     }
@@ -660,7 +660,7 @@
         *pCRC32 = crc32(*pCRC32, tmpBuf, count);
 
         if (fwrite(tmpBuf, 1, count, dstFp) != count) {
-            LOGD("fwrite %d bytes failed\n", (int) count);
+            ALOGD("fwrite %d bytes failed\n", (int) count);
             return UNKNOWN_ERROR;
         }
     }
@@ -682,7 +682,7 @@
     if (size > 0) {
         *pCRC32 = crc32(*pCRC32, (const unsigned char*)data, size);
         if (fwrite(data, 1, size, dstFp) != size) {
-            LOGD("fwrite %d bytes failed\n", (int) size);
+            ALOGD("fwrite %d bytes failed\n", (int) size);
             return UNKNOWN_ERROR;
         }
     }
@@ -716,7 +716,7 @@
 
         count = fread(tmpBuf, 1, readSize, srcFp);
         if ((long) count != readSize) {     // error or unexpected EOF
-            LOGD("fread %d bytes failed\n", (int) readSize);
+            ALOGD("fread %d bytes failed\n", (int) readSize);
             return UNKNOWN_ERROR;
         }
 
@@ -724,7 +724,7 @@
             *pCRC32 = crc32(*pCRC32, tmpBuf, count);
 
         if (fwrite(tmpBuf, 1, count, dstFp) != count) {
-            LOGD("fwrite %d bytes failed\n", (int) count);
+            ALOGD("fwrite %d bytes failed\n", (int) count);
             return UNKNOWN_ERROR;
         }
 
@@ -780,10 +780,10 @@
     if (zerr != Z_OK) {
         result = UNKNOWN_ERROR;
         if (zerr == Z_VERSION_ERROR) {
-            LOGE("Installed zlib is not compatible with linked version (%s)\n",
+            ALOGE("Installed zlib is not compatible with linked version (%s)\n",
                 ZLIB_VERSION);
         } else {
-            LOGD("Call to deflateInit2 failed (zerr=%d)\n", zerr);
+            ALOGD("Call to deflateInit2 failed (zerr=%d)\n", zerr);
         }
         goto bail;
     }
@@ -799,7 +799,7 @@
 
         /* only read if the input buffer is empty */
         if (zstream.avail_in == 0 && !atEof) {
-            LOGV("+++ reading %d bytes\n", (int)kBufSize);
+            ALOGV("+++ reading %d bytes\n", (int)kBufSize);
             if (data) {
                 getSize = size > kBufSize ? kBufSize : size;
                 memcpy(inBuf, data, getSize);
@@ -808,12 +808,12 @@
             } else {
                 getSize = fread(inBuf, 1, kBufSize, srcFp);
                 if (ferror(srcFp)) {
-                    LOGD("deflate read failed (errno=%d)\n", errno);
+                    ALOGD("deflate read failed (errno=%d)\n", errno);
                     goto z_bail;
                 }
             }
             if (getSize < kBufSize) {
-                LOGV("+++  got %d bytes, EOF reached\n",
+                ALOGV("+++  got %d bytes, EOF reached\n",
                     (int)getSize);
                 atEof = true;
             }
@@ -831,7 +831,7 @@
 
         zerr = deflate(&zstream, flush);
         if (zerr != Z_OK && zerr != Z_STREAM_END) {
-            LOGD("zlib deflate call failed (zerr=%d)\n", zerr);
+            ALOGD("zlib deflate call failed (zerr=%d)\n", zerr);
             result = UNKNOWN_ERROR;
             goto z_bail;
         }
@@ -840,11 +840,11 @@
         if (zstream.avail_out == 0 ||
             (zerr == Z_STREAM_END && zstream.avail_out != (uInt) kBufSize))
         {
-            LOGV("+++ writing %d bytes\n", (int) (zstream.next_out - outBuf));
+            ALOGV("+++ writing %d bytes\n", (int) (zstream.next_out - outBuf));
             if (fwrite(outBuf, 1, zstream.next_out - outBuf, dstFp) !=
                 (size_t)(zstream.next_out - outBuf))
             {
-                LOGD("write %d failed in deflate\n",
+                ALOGD("write %d failed in deflate\n",
                     (int) (zstream.next_out - outBuf));
                 goto z_bail;
             }
@@ -931,7 +931,7 @@
      * of wasted space at the end of the file.  Remove it now.
      */
     if (ftruncate(fileno(mZipFp), ftell(mZipFp)) != 0) {
-        LOGW("ftruncate failed %ld: %s\n", ftell(mZipFp), strerror(errno));
+        ALOGW("ftruncate failed %ld: %s\n", ftell(mZipFp), strerror(errno));
         // not fatal
     }
 
@@ -1019,7 +1019,7 @@
                         pEntry->getLFHOffset(), span);
             if (result != NO_ERROR) {
                 /* this is why you use a temp file */
-                LOGE("error during crunch - archive is toast\n");
+                ALOGE("error during crunch - archive is toast\n");
                 return result;
             }
 
@@ -1061,23 +1061,23 @@
                 getSize = n;
 
             if (fseek(fp, (long) src, SEEK_SET) != 0) {
-                LOGD("filemove src seek %ld failed\n", (long) src);
+                ALOGD("filemove src seek %ld failed\n", (long) src);
                 return UNKNOWN_ERROR;
             }
 
             if (fread(readBuf, 1, getSize, fp) != getSize) {
-                LOGD("filemove read %ld off=%ld failed\n",
+                ALOGD("filemove read %ld off=%ld failed\n",
                     (long) getSize, (long) src);
                 return UNKNOWN_ERROR;
             }
 
             if (fseek(fp, (long) dst, SEEK_SET) != 0) {
-                LOGD("filemove dst seek %ld failed\n", (long) dst);
+                ALOGD("filemove dst seek %ld failed\n", (long) dst);
                 return UNKNOWN_ERROR;
             }
 
             if (fwrite(readBuf, 1, getSize, fp) != getSize) {
-                LOGD("filemove write %ld off=%ld failed\n",
+                ALOGD("filemove write %ld off=%ld failed\n",
                     (long) getSize, (long) dst);
                 return UNKNOWN_ERROR;
             }
@@ -1104,7 +1104,7 @@
     struct stat sb;
 
     if (fstat(fd, &sb) < 0) {
-        LOGD("HEY: fstat on fd %d failed\n", fd);
+        ALOGD("HEY: fstat on fd %d failed\n", fd);
         return (time_t) -1;
     }
 
@@ -1129,7 +1129,7 @@
     int fd;
     fd = dup(fileno(mZipFp));
     if (fd < 0) {
-        LOGD("didn't work, errno=%d\n", errno);
+        ALOGD("didn't work, errno=%d\n", errno);
     }
 
     return fd;
@@ -1224,7 +1224,7 @@
 
     if (len < kEOCDLen) {
         /* looks like ZIP file got truncated */
-        LOGD(" Zip EOCD: expected >= %d bytes, found %d\n",
+        ALOGD(" Zip EOCD: expected >= %d bytes, found %d\n",
             kEOCDLen, len);
         return INVALID_OPERATION;
     }
@@ -1245,7 +1245,7 @@
 
     if (mCommentLen > 0) {
         if (kEOCDLen + mCommentLen > len) {
-            LOGD("EOCD(%d) + comment(%d) exceeds len (%d)\n",
+            ALOGD("EOCD(%d) + comment(%d) exceeds len (%d)\n",
                 kEOCDLen, mCommentLen, len);
             return UNKNOWN_ERROR;
         }
@@ -1288,10 +1288,10 @@
  */
 void ZipFile::EndOfCentralDir::dump(void) const
 {
-    LOGD(" EndOfCentralDir contents:\n");
-    LOGD("  diskNum=%u diskWCD=%u numEnt=%u totalNumEnt=%u\n",
+    ALOGD(" EndOfCentralDir contents:\n");
+    ALOGD("  diskNum=%u diskWCD=%u numEnt=%u totalNumEnt=%u\n",
         mDiskNumber, mDiskWithCentralDir, mNumEntries, mTotalNumEntries);
-    LOGD("  centDirSize=%lu centDirOff=%lu commentLen=%u\n",
+    ALOGD("  centDirSize=%lu centDirOff=%lu commentLen=%u\n",
         mCentralDirSize, mCentralDirOffset, mCommentLen);
 }
 
diff --git a/tools/zipalign/ZipFile.h b/tools/zipalign/ZipFile.h
index dbbd072..7877550 100644
--- a/tools/zipalign/ZipFile.h
+++ b/tools/zipalign/ZipFile.h
@@ -57,7 +57,7 @@
     /*
      * Open a new or existing archive.
      */
-    typedef enum {
+    enum {
         kOpenReadOnly   = 0x01,
         kOpenReadWrite  = 0x02,
         kOpenCreate     = 0x04,     // create if it doesn't exist