Merge remote-tracking branch 'goog/ics-aah-exp'
diff --git a/CleanSpec.mk b/CleanSpec.mk
index d103aa6..1d9b9bb 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -107,6 +107,16 @@
 $(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)
 
 # ************************************************
diff --git a/core/Makefile b/core/Makefile
index 81699ee..173932c 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,7 +28,8 @@
     $(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))) \
         $(eval ALL_DEFAULT_INSTALLED_MODULES += $(_fulldest)) \
@@ -405,6 +408,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.
@@ -553,7 +561,7 @@
 # make the target NOTICE files depend on this particular file too, which will
 # then be in the right directory for the find in combine-notice-files to work.
 $(kernel_notice_file): \
-	    prebuilt/$(TARGET_PREBUILT_TAG)/kernel/LINUX_KERNEL_COPYING \
+	    prebuilts/qemu-kernel/arm/LINUX_KERNEL_COPYING \
 	    | $(ACP)
 	@echo Copying: $@
 	$(hide) mkdir -p $(dir $@)
@@ -603,27 +611,27 @@
 
 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))
-  $(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))
+endef
 
 # -----------------------------------------------------------------
 # Recovery image
 
 # If neither TARGET_NO_KERNEL nor TARGET_NO_RECOVERY are true
-ifeq (,$(filter true, $(TARGET_NO_KERNEL) $(TARGET_NO_RECOVERY) $(BUILD_TINY_ANDROID)))
+ifeq (,$(filter true, $(TARGET_NO_KERNEL) $(TARGET_NO_RECOVERY) $(BUILD_TINY_ANDROID) $(BUILD_PDK)))
 
 INSTALLED_RECOVERYIMAGE_TARGET := $(PRODUCT_OUT)/recovery.img
 
@@ -740,10 +748,18 @@
 #
 
 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))
+
+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)
 # -----------------------------------------------------------------
@@ -769,28 +785,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))
-    $(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,$@)
 
@@ -829,6 +836,12 @@
 	$(call build-systemimage-target,$(INSTALLED_SYSTEMIMAGE))
 	$(hide) $(call assert-max-image-size,$(INSTALLED_SYSTEMIMAGE),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE),yaffs)
 
+ifneq (,$(filter systemimage-nodeps snod, $(MAKECMDGOALS)))
+ifeq (true,$(WITH_DEXPREOPT))
+$(warning Warning: with dexpreopt enabled, you may need a full rebuild.)
+endif
+endif
+
 #######
 ## system tarball
 define build-systemtarball-target
@@ -888,30 +901,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)
-    $(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) \
@@ -944,6 +956,38 @@
 
 
 # -----------------------------------------------------------------
+# 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
@@ -1024,6 +1068,7 @@
 		$(INSTALLED_RECOVERYIMAGE_TARGET) \
 		$(INSTALLED_SYSTEMIMAGE) \
 		$(INSTALLED_USERDATAIMAGE_TARGET) \
+		$(INSTALLED_CACHEIMAGE_TARGET) \
 		$(INSTALLED_ANDROID_INFO_TXT_TARGET) \
 		$(built_ota_tools) \
 		$(APKCERTS_FILE) \
@@ -1100,23 +1145,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
@@ -1193,7 +1227,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)
@@ -1206,25 +1240,14 @@
 $(BUILT_TESTS_ZIP_PACKAGE): intermediates := $(intermediates)
 $(BUILT_TESTS_ZIP_PACKAGE): zip_root := $(intermediates)/$(name)
 
-# Depending on the dependencies of system image and userdata image.
-# But we don't need to really create them.
+# Depending on the images guarantees that the underlying
 # directories are up-to-date.
 $(BUILT_TESTS_ZIP_PACKAGE): \
-		$(FULL_SYSTEMIMAGE_DEPS) \
-		$(INTERNAL_USERDATAIMAGE_FILES) \
-		| $(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)
@@ -1242,6 +1265,12 @@
           $(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
+
 # -----------------------------------------------------------------
 # A zip of the symbols directory.  Keep the full paths to make it
 # more obvious where these files came from.
@@ -1297,7 +1326,7 @@
 
 INTERNAL_EMULATOR_PACKAGE_FILES += \
         $(HOST_OUT_EXECUTABLES)/emulator$(HOST_EXECUTABLE_SUFFIX) \
-        prebuilt/android-$(TARGET_ARCH)/kernel/kernel-qemu \
+        prebuilts/qemu-kernel/$(TARGET_ARCH)/kernel-qemu \
         $(INSTALLED_RAMDISK_TARGET) \
 		$(INSTALLED_SYSTEMIMAGE) \
 		$(INSTALLED_USERDATAIMAGE_TARGET)
@@ -1311,11 +1340,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
@@ -1368,6 +1399,12 @@
 ifneq (,$(strip $(wildcard sdk/build/tools.$(TARGET_ARCH).atree)))
   sdk_tools_atree_files += sdk/build/tools.$(TARGET_ARCH).atree
 endif
+ifneq (,$(strip $(wildcard sdk/build/tools.$(HOST_OS).atree)))
+  sdk_tools_atree_files += sdk/build/tools.$(HOST_OS).atree
+endif
+ifneq (,$(strip $(wildcard sdk/build/tools.$(HOST_OS)-$(HOST_ARCH).atree)))
+  sdk_tools_atree_files += sdk/build/tools.$(HOST_OS)-$(HOST_ARCH).atree
+endif
 
 sdk_atree_files := \
 	$(atree_dir)/sdk.exclude.atree \
@@ -1430,6 +1467,7 @@
 			-I $(TARGET_COMMON_OUT_ROOT) \
 			-v "PLATFORM_NAME=android-$(PLATFORM_VERSION)" \
 			-v "OUT_DIR=$(OUT_DIR)" \
+			-v "HOST_OUT=$(HOST_OUT)" \
 			-v "TARGET_ARCH=$(TARGET_ARCH)" \
 			-v "TARGET_CPU_ABI=$(TARGET_CPU_ABI)" \
 			-v "DLL_EXTENSION=$(HOST_SHLIB_SUFFIX)" \
diff --git a/core/armelf.x b/core/armelf.x
index d38dc1d..b484776 100644
--- a/core/armelf.x
+++ b/core/armelf.x
@@ -93,10 +93,16 @@
   .preinit_array     : { KEEP (*(.preinit_array)) }
   PROVIDE (__preinit_array_end = .);
   PROVIDE (__init_array_start = .);
-  .init_array     : { KEEP (*(.init_array)) }
+  .init_array     : {
+    KEEP (*(SORT(.init_array.*)))
+    KEEP (*(.init_array))
+  }
   PROVIDE (__init_array_end = .);
   PROVIDE (__fini_array_start = .);
-  .fini_array     : { KEEP (*(.fini_array)) }
+  .fini_array     : {
+    KEEP (*(.fini_array))
+    KEEP (*(SORT(.fini_array.*)))
+  }
   PROVIDE (__fini_array_end = .);
   .ctors          :
   {
diff --git a/core/armelflib.x b/core/armelflib.x
index 0150e02..ec7abd5 100644
--- a/core/armelflib.x
+++ b/core/armelflib.x
@@ -59,10 +59,16 @@
   .preinit_array     : { KEEP (*(.preinit_array)) }
   PROVIDE (__preinit_array_end = .);
   PROVIDE (__init_array_start = .);
-  .init_array     : { KEEP (*(.init_array)) }
+  .init_array     : {
+     KEEP (*(SORT(.init_array.*)))
+     KEEP (*(.init_array))
+   }
   PROVIDE (__init_array_end = .);
   PROVIDE (__fini_array_start = .);
-  .fini_array     : { KEEP (*(.fini_array)) }
+  .fini_array     : {
+    KEEP (*(.fini_array))
+    KEEP (*(SORT(.fini_array.*)))
+  }
   PROVIDE (__fini_array_end = .);
   .ctors          :
   {
diff --git a/core/base_rules.mk b/core/base_rules.mk
index 242b53d..38c2c10 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -110,8 +110,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
 
 #
@@ -381,7 +383,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), \
@@ -587,6 +589,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..e729164 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -571,7 +571,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), \
diff --git a/core/build_id.mk b/core/build_id.mk
index 70bd235..40bb35d 100644
--- a/core/build_id.mk
+++ b/core/build_id.mk
@@ -23,7 +23,7 @@
 # (like "TC1-RC5").  It must be a single word, and is
 # capitalized by convention.
 #
-BUILD_ID := MR1
+BUILD_ID := MASTER
 
 # DISPLAY_BUILD_NUMBER should only be set for development branches,
 # If set, the BUILD_NUMBER (cl) is appended to the BUILD_ID for
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index c6fd06b..63f44b3 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -58,7 +58,6 @@
 LOCAL_INTERMEDIATE_SOURCE_DIR:=
 LOCAL_JAVACFLAGS:=
 LOCAL_JAVA_LIBRARIES:=
-LOCAL_JAVA_LAYERS_FILE:=
 LOCAL_NO_STANDARD_LIBRARIES:=
 LOCAL_CLASSPATH:=
 LOCAL_DROIDDOC_USE_STANDARD_DOCLET:=
@@ -108,6 +107,7 @@
 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
@@ -115,7 +115,9 @@
 LOCAL_PROTOC_FLAGS:=
 LOCAL_NO_CRT:=
 LOCAL_PROPRIETARY_MODULE:=
+LOCAL_MODULE_OWNER:=
 LOCAL_CTS_TEST_PACKAGE:=
+LOCAL_CTS_TEST_RUNNER:=
 
 # 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 544a29e..198c53f 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
 
 # Use the Mac OSX SDK 10.5 if the build host is 10.6
 build_mac_version := $(shell sw_vers -productVersion)
@@ -53,32 +59,58 @@
 
 HOST_GLOBAL_CFLAGS += \
 	-include $(call select-android-config-h,darwin-x86)
-HOST_RUN_RANLIB_AFTER_COPYING := true
+ifneq ($(filter 10.7.%, $(build_mac_version)),)
+       HOST_RUN_RANLIB_AFTER_COPYING := false
+else
+       HOST_RUN_RANLIB_AFTER_COPYING := true
+       PRE_LION_DYNAMIC_LINKER_OPTIONS := -Wl,-dynamic
+endif
 HOST_GLOBAL_ARFLAGS := cqs
 
 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 $@ \
-        -Wl,-dynamic -headerpad_max_install_names \
+        $(PRE_LION_DYNAMIC_LINKER_OPTIONS) -headerpad_max_install_names \
         $(HOST_GLOBAL_LD_DIRS) \
         $(HOST_GLOBAL_LDFLAGS) \
         $(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index 5ae4972..6cee6ea 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -33,26 +33,32 @@
 # LOCAL_CC and LOCAL_CXX to override this.
 #
 ifeq ($(TARGET_PRODUCT),sdk)
-HOST_SDK_TOOLCHAIN_PREFIX := prebuilt/linux-x86/toolchain/i686-linux-glibc2.7-4.4.3/bin/i686-linux
+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)))
-HOST_CC  := $(HOST_SDK_TOOLCHAIN_PREFIX)-gcc
-HOST_CXX := $(HOST_SDK_TOOLCHAIN_PREFIX)-g++
-HOST_AR  := $(HOST_SDK_TOOLCHAIN_PREFIX)-ar
-endif # $(HOST_SDK_TOOLCHAIN_PREFIX)-gcc exists
+ifneq (,$(strip $(wildcard $(HOST_SDK_TOOLCHAIN_PREFIX)/gcc)))
+HOST_CC  := $(HOST_SDK_TOOLCHAIN_PREFIX)/gcc
+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 += \
 	-include $(call select-android-config-h,linux-x86)
 
 # Disable new longjmp in glibc 2.11 and later. See bug 2967937.
-HOST_GLOBAL_CFLAGS += -D_FORTIFY_SOURCE=0
+HOST_GLOBAL_CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0
 
 HOST_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
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 8c89143..711041d 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 := \
-	prebuilt/$(HOST_PREBUILT_TAG)/toolchain/arm-linux-androideabi-4.4.x/bin/arm-linux-androideabi-
+TARGET_TOOLCHAIN_ROOT := prebuilt/$(HOST_PREBUILT_TAG)/toolchain/arm-linux-androideabi-4.4.x
+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 \
@@ -114,11 +114,13 @@
 			-include $(android_config_h) \
 			-I $(arch_include_dir)
 
-# This warning causes dalvik not to build with gcc 4.6 and -Werror.
+# This warning causes dalvik not to build with gcc 4.6.x and -Werror.
 # We cannot turn it off blindly since the option is not available
-# in gcc-4.4.x
-ifneq ($(filter 4.6.0%, $(shell $(TARGET_CC) --version)),)
-TARGET_GLOBAL_CFLAGS += -Wno-unused-but-set-variable
+# in gcc-4.4.x.  We also want to disable sincos optimization globally
+# by turning off the builtin sin function.
+ifneq ($(filter 4.6.%, $(shell $(TARGET_CC) --version)),)
+TARGET_GLOBAL_CFLAGS += -Wno-unused-but-set-variable -fno-builtin-sin \
+			-fno-strict-volatile-bitfields
 endif
 
 # This is to avoid the dreaded warning compiler message:
@@ -266,7 +268,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 \
@@ -287,7 +289,7 @@
 endef
 
 define transform-o-to-static-executable-inner
-$(hide) $(PRIVATE_CXX) -nostdlib -Bstatic -Wl,-T,$(BUILD_SYSTEM)/armelf.x \
+$(hide) $(PRIVATE_CXX) -nostdlib -Bstatic \
     -Wl,--gc-sections \
 	-o $@ \
 	$(TARGET_GLOBAL_LD_DIRS) \
diff --git a/core/combo/TARGET_linux-sh.mk b/core/combo/TARGET_linux-sh.mk
index b8e00dd..88c6215 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 0fb6edc..9e1d4bd 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 := \
-	prebuilt/$(HOST_PREBUILT_TAG)/toolchain/i686-android-linux-4.4.3/bin/i686-android-linux-
+TARGET_TOOLCHAIN_ROOT := prebuilts/gcc/$(HOST_PREBUILT_TAG)/x86/i686-android-linux-4.4.3
+TARGET_TOOLS_PREFIX := $(TARGET_TOOLCHAIN_ROOT)/bin/i686-android-linux-
 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,27 +96,48 @@
 			-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)
-    TARGET_GLOBAL_CFLAGS += -march=atom -mstackrealign -DUSE_SSSE3 -DUSE_SSE2 -mfpmath=sse
-else
-    TARGET_GLOBAL_CFLAGS += -march=i686
+# 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
+
+# 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,--gc-sections
 
@@ -158,6 +191,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) \
@@ -187,3 +221,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 d486ed3..56ef97e 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -29,9 +29,11 @@
 	$(TOPDIR)hardware/libhardware_legacy/include \
 	$(TOPDIR)hardware/ril/include \
 	$(TOPDIR)dalvik/libnativehelper/include \
+	$(TOPDIR)frameworks/native/include \
+	$(TOPDIR)frameworks/native/opengl/include \
 	$(TOPDIR)frameworks/base/include \
 	$(TOPDIR)frameworks/base/opengl/include \
-    $(TOPDIR)frameworks/base/native/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.
 # ###############################################################
@@ -147,6 +151,33 @@
 TARGET_DEVICE_DIR := $(patsubst %/,%,$(dir $(board_config_mk)))
 board_config_mk :=
 
+# pull in device specific kernel headers. Files should be in
+# $(TARGET_DEVICE_DIR)/kernel-headers, e.g.
+# $(TARGET_DEVICE_DIR)/kernel-headers/linux/
+# $(TARGET_DEVICE_DIR)/kernel-headers/media/
+# $(TARGET_DEVICE_DIR)/kernel-headers/video/
+# etc.
+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))
@@ -169,6 +200,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
 
@@ -318,7 +357,8 @@
 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_OUT_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
@@ -339,8 +379,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.
diff --git a/core/definitions.mk b/core/definitions.mk
index 867575a..0b7092f 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
 ###########################################################
@@ -691,7 +694,7 @@
 endef
 
 define get-package-overrides
-$(strip $(sort $(call _get-package-overrides,$(1))))
+$(sort $(strip $(call _get-package-overrides,$(1))))
 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
@@ -890,7 +894,7 @@
 	$(PRIVATE_CFLAGS) \
 	$(PRIVATE_CPPFLAGS) \
 	$(PRIVATE_DEBUG_CFLAGS) \
-	-MD -o $@ $<
+	-MD -MF $(patsubst %.o,%.d,$@) -o $@ $<
 $(transform-d-to-p)
 endef
 
@@ -917,7 +921,7 @@
 	$(PRIVATE_CFLAGS) \
 	$(1) \
 	$(PRIVATE_DEBUG_CFLAGS) \
-	-MD -o $@ $<
+	-MD -MF $(patsubst %.o,%.d,$@) -o $@ $<
 endef
 
 define transform-c-to-o-no-deps
@@ -978,7 +982,7 @@
 	$(PRIVATE_CFLAGS) \
 	$(PRIVATE_CPPFLAGS) \
 	$(PRIVATE_DEBUG_CFLAGS) \
-	-MD -o $@ $<
+	-MD -MF $(patsubst %.o,%.d,$@) -o $@ $<
 $(transform-d-to-p)
 endef
 
@@ -1004,7 +1008,7 @@
 	$(PRIVATE_CFLAGS) \
 	$(1) \
 	$(PRIVATE_DEBUG_CFLAGS) \
-	-MD -o $@ $<
+	-MD -MF $(patsubst %.o,%.d,$@) -o $@ $<
 endef
 
 define transform-host-c-to-o-no-deps
@@ -1104,7 +1108,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 ; \
@@ -1292,13 +1296,6 @@
 ifneq ($(HOST_CUSTOM_LD_COMMAND),true)
 define transform-host-o-to-executable-inner
 $(hide) $(PRIVATE_CXX) \
-	-Wl,-rpath-link=$(HOST_OUT_INTERMEDIATE_LIBRARIES) \
-	-Wl,-rpath,\$$ORIGIN/../lib \
-	$(HOST_GLOBAL_LD_DIRS) \
-	$(PRIVATE_LDFLAGS) \
-	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
-		$(HOST_GLOBAL_LDFLAGS) \
-	) \
 	$(PRIVATE_ALL_OBJECTS) \
 	-Wl,--whole-archive \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
@@ -1307,6 +1304,13 @@
 	$(call normalize-host-libraries,$(PRIVATE_ALL_STATIC_LIBRARIES)) \
 	$(if $(PRIVATE_GROUP_STATIC_LIBRARIES),-Wl$(comma)--end-group) \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
+	-Wl,-rpath-link=$(HOST_OUT_INTERMEDIATE_LIBRARIES) \
+	-Wl,-rpath,\$$ORIGIN/../lib \
+	$(HOST_GLOBAL_LD_DIRS) \
+	$(PRIVATE_LDFLAGS) \
+	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
+		$(HOST_GLOBAL_LDFLAGS) \
+	) \
 	-o $@ \
 	$(PRIVATE_LDLIBS)
 endef
@@ -1444,7 +1448,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,11 +1459,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 )
-$(if $(PRIVATE_JAVA_LAYERS_FILE), $(hide) build/tools/java-layers.py \
-    $(PRIVATE_JAVA_LAYERS_FILE) \@$(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq,)
+    || ( 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
@@ -1527,7 +1535,7 @@
 @echo "target Dex: $(PRIVATE_MODULE)"
 @mkdir -p $(dir $@)
 $(hide) $(DX) \
-    $(if $(findstring windows,$(HOST_OS)),,-JXms16M -JXmx1536M) \
+    $(if $(findstring windows,$(HOST_OS)),,-JXms16M -JXmx2048M) \
     --dex --output=$@ \
     $(incremental_dex) \
     $(if $(NO_OPTIMIZE_DX), \
@@ -1867,7 +1875,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; \
@@ -1879,6 +1886,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; \
@@ -1919,6 +1927,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
diff --git a/core/dumpvar.mk b/core/dumpvar.mk
index e0de464..87f7086 100644
--- a/core/dumpvar.mk
+++ b/core/dumpvar.mk
@@ -3,13 +3,23 @@
 # what to add to the path given the config we have chosen.
 ifeq ($(CALLED_FROM_SETUP),true)
 
+ifneq ($(filter /%,$(HOST_OUT_EXECUTABLES)),)
+ABP:=$(HOST_OUT_EXECUTABLES)
+else
 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)/prebuilt/$(HOST_PREBUILT_TAG)/toolchain/arm-linux-androideabi-4.4.x/bin),)
 	# this should be copied to HOST_OUT_EXECUTABLES instead
 	ABP:=$(ABP):$(PWD)/prebuilt/$(HOST_PREBUILT_TAG)/toolchain/arm-linux-androideabi-4.4.x/bin
 endif
+
+# Add the x86 toolchain bin dir if it actually exists
+ifneq ($(wildcard $(PWD)/prebuilts/gcc/$(HOST_PREBUILT_TAG)/x86/i686-android-linux-4.4.3/bin),)
+	# this should be copied to HOST_OUT_EXECUTABLES instead
+	ABP:=$(ABP):$(PWD)/prebuilts/gcc//$(HOST_PREBUILT_TAG)/x86/i686-android-linux-4.4.3/bin
+endif
 ANDROID_BUILD_PATHS := $(ABP)
 ANDROID_PREBUILTS := prebuilt/$(HOST_PREBUILT_TAG)
 
@@ -38,7 +48,11 @@
   absolute_dumpvar := $(strip $(filter abs-%,$(dumpvar_goals)))
   ifdef absolute_dumpvar
     dumpvar_goals := $(patsubst abs-%,%,$(dumpvar_goals))
-    DUMPVAR_VALUE := $(PWD)/$($(dumpvar_goals))
+    ifneq ($(filter /%,$($(dumpvar_goals))),)
+      DUMPVAR_VALUE := $($(dumpvar_goals))
+    else
+      DUMPVAR_VALUE := $(PWD)/$($(dumpvar_goals))
+    endif
     dumpvar_target := dumpvar-abs-$(dumpvar_goals)
   else
     DUMPVAR_VALUE := $($(dumpvar_goals))
@@ -59,6 +73,7 @@
 
 
 ifneq ($(PRINT_BUILD_CONFIG),)
+HOST_OS_EXTRA:=$(shell python -c "import platform; print(platform.platform())")
 $(info ============================================)
 $(info   PLATFORM_VERSION_CODENAME=$(PLATFORM_VERSION_CODENAME))
 $(info   PLATFORM_VERSION=$(PLATFORM_VERSION))
@@ -70,7 +85,9 @@
 $(info   TARGET_ARCH_VARIANT=$(TARGET_ARCH_VARIANT))
 $(info   HOST_ARCH=$(HOST_ARCH))
 $(info   HOST_OS=$(HOST_OS))
+$(info   HOST_OS_EXTRA=$(HOST_OS_EXTRA))
 $(info   HOST_BUILD_TYPE=$(HOST_BUILD_TYPE))
 $(info   BUILD_ID=$(BUILD_ID))
+$(info   OUT_DIR=$(OUT_DIR))
 $(info ============================================)
 endif
diff --git a/core/envsetup.mk b/core/envsetup.mk
index 6cd42c8..9cc32c3 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
@@ -133,7 +141,11 @@
 # figure out the output directories
 
 ifeq (,$(strip $(OUT_DIR)))
+ifeq (,$(strip $(OUT_DIR_COMMON_BASE)))
 OUT_DIR := $(TOPDIR)out
+else
+OUT_DIR := $(OUT_DIR_COMMON_BASE)/$(notdir $(PWD))
+endif
 endif
 
 DEBUG_OUT_DIR := $(OUT_DIR)/debug
@@ -179,10 +191,11 @@
 
 TARGET_OUT_INTERMEDIATES := $(PRODUCT_OUT)/obj
 TARGET_OUT_HEADERS:= $(TARGET_OUT_INTERMEDIATES)/include
+TARGET_OUT_KERNEL_HEADERS:= $(TARGET_OUT_INTERMEDIATES)/kernel-headers
 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
@@ -195,7 +208,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)
@@ -206,7 +219,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
@@ -221,13 +236,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
diff --git a/core/find-jdk-tools-jar.sh b/core/find-jdk-tools-jar.sh
index e1278c3..f150a9a 100755
--- a/core/find-jdk-tools-jar.sh
+++ b/core/find-jdk-tools-jar.sh
@@ -1,3 +1,4 @@
+#!/bin/sh
 if [ "x$ANDROID_JAVA_HOME" != x ] && [ -e "$ANDROID_JAVA_HOME/lib/tools.jar" ] ; then
     echo $ANDROID_JAVA_HOME/lib/tools.jar
 else
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/java.mk b/core/java.mk
index 0c51da3..38fd6f2 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -5,7 +5,7 @@
 
 # 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
 
@@ -152,11 +152,16 @@
 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)),)
 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 := \
@@ -171,6 +176,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 +220,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.
@@ -238,19 +244,14 @@
 	$(hide) $(ACP) -fp $(PRIVATE_SOURCE_FILE) $@
 ALL_MODULES.$(LOCAL_MODULE).STUBS := $(full_classes_stubs_jar)
 
-# The layers file allows you to enforce a layering between java packages.
-# Run build/tools/java-layers.py for more details.
-layers_file := $(addprefix $(LOCAL_PATH)/, $(LOCAL_JAVA_LAYERS_FILE))
-$(full_classes_compiled_jar): PRIVATE_JAVA_LAYERS_FILE := $(layers_file)
-
 # Compile the java files to a .jar file.
 # This intentionally depends on java_sources, not all_java_sources.
 # 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): $(java_sources) $(java_resource_sources) $(full_java_lib_deps)\
-                            $(jar_manifest_file) $(layers_file) \
-                            $(RenderScript_file_stamp) $(proto_java_sources_file_stamp)
+$(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)
 
 # All of the rules after full_classes_compiled_jar are very unlikely
diff --git a/core/java_library.mk b/core/java_library.mk
index fa40c0e..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 :=
@@ -90,6 +92,7 @@
 $(built_odex) : $(common_javalib.jar) | $(DEXPREOPT) $(DEXOPT)
 	@echo "Dexpreopt Jar: $(PRIVATE_MODULE) ($@)"
 	$(hide) rm -f $@
+	@mkdir -p $(dir $@)
 	$(call dexpreopt-one-file,$<,$@)
 
 $(LOCAL_BUILT_MODULE) : $(common_javalib.jar) | $(ACP) $(AAPT)
diff --git a/core/legacy_prebuilts.mk b/core/legacy_prebuilts.mk
index 41943b1..c25880d 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 \
diff --git a/core/main.mk b/core/main.mk
index 89cbc63..ab9d52d 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -37,15 +37,20 @@
 #TOPDIR := $(TOP)/
 #endif
 
-# check for broken versions of make
+# Check for broken versions of make.
+# (Allow any version under Cygwin since we don't actually build the platform there.)
+ifeq (,$(findstring CYGWIN,$(shell uname -sm)))
 ifeq (0,$(shell expr $$(echo $(MAKE_VERSION) | sed "s/[^0-9\.].*//") = 3.81))
+ifeq (0,$(shell expr $$(echo $(MAKE_VERSION) | sed "s/[^0-9\.].*//") = 3.82))
 $(warning ********************************************************************************)
 $(warning *  You are using version $(MAKE_VERSION) of make.)
-$(warning *  Android can only be built by version 3.81.)
+$(warning *  Android can only be built by versions 3.81 and 3.82.)
 $(warning *  see http://source.android.com/source/download.html)
 $(warning ********************************************************************************)
 $(error stopping)
 endif
+endif
+endif
 
 TOP := .
 TOPDIR :=
@@ -178,7 +183,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 \
@@ -202,6 +207,32 @@
 $(error stopping)
 endif
 
+# -----------------------------------------------------------------
+# The pdk (Platform Development Kit) build
+# pdk_eng : for building binary blob necessary for pdk_rel build
+# pdk_rel : HAL build for chipset vendors
+
+PDK_BUILD_TYPE:= $(filter pdk_eng pdk_rel,$(MAKECMDGOALS))
+ifeq (2,$(words $(PDK_BUILD_TYPE)))
+  $(error You can't build pdk_eng and pdk_rel in the same run.)
+endif
+ifneq ($(PDK_BUILD_TYPE),)
+  $(info PDK build type $(PDK_BUILD_TYPE))
+  BUILD_PDK:= true
+  include pdk/build/pdk.mk
+  # force droid target
+  MAKECMDGOALS:= $(subst $(PDK_BUILD_TYPE),droid,$(MAKECMDGOALS))
+ifeq ($(PDK_BUILD_TYPE), pdk_eng)
+  .PHONY: pdk_eng
+  pdk_eng: droid pdk_bin_zip
+
+else  # pdk_rel
+  .PHONY: pdk_rel
+  pdk_rel: droid
+
+endif # pdk_rel
+endif # PDK_BUILD_TYPE
+# -----------------------------------------------------------------
 ###
 ### In this section we set up the things that are different
 ### between the build variants
@@ -271,11 +302,13 @@
 
 ifeq ($(TARGET_BUILD_VARIANT),eng)
 tags_to_install := user debug eng
+ifneq ($(filter ro.setupwizard.mode=ENABLED, $(call collapse-pairs, $(ADDITIONAL_BUILD_PROPERTIES))),)
   # Don't require the setup wizard on eng builds
   ADDITIONAL_BUILD_PROPERTIES := $(filter-out ro.setupwizard.mode=%,\
           $(call collapse-pairs, $(ADDITIONAL_BUILD_PROPERTIES))) \
           ro.setupwizard.mode=OPTIONAL
 endif
+endif
 
 ## tests ##
 
@@ -387,74 +420,8 @@
 endif
 
 ifeq ($(SDK_ONLY),true)
-
-# ----- SDK for Windows ------
-# These configure the build targets that are available for the SDK under Windows.
-# The first section defines all the C/C++ tools that can be compiled in C/C++,
-# the second section defines all the Java ones (assuming javac is available.)
-
-subdirs := \
-	prebuilt \
-	build/libs/host \
-	build/tools/zipalign \
-	dalvik/dexdump \
-	dalvik/libdex \
-	dalvik/tools/dmtracedump \
-	dalvik/tools/hprof-conv \
-	development/host \
-	development/tools/etc1tool \
-	development/tools/line_endings \
-	development/tools/emulator/opengl \
-	external/clang \
-	external/easymock \
-	external/expat \
-	external/libpng \
-	external/llvm \
-	external/qemu \
-	external/sqlite/dist \
-	external/zlib \
-	frameworks/base \
-	frameworks/compile \
-	sdk/avdlauncher \
-	sdk/emulator/mksdcard \
-	sdk/sdklauncher \
-	system/core/adb \
-	system/core/fastboot \
-	system/core/libcutils \
-	system/core/liblog \
-	system/core/libzipfile
-
-# The following can only be built if "javac" is available.
-# This check is used when building parts of the SDK under Cygwin.
-ifneq (,$(shell which javac 2>/dev/null))
-subdirs += \
-	build/tools/signapk \
-	dalvik/dx \
-	libcore \
-	sdk/archquery \
-	sdk/androidprefs \
-	sdk/apkbuilder \
-	sdk/assetstudio \
-	sdk/common \
-	sdk/ddms \
-	sdk/hierarchyviewer2 \
-	sdk/ide_common \
-	sdk/jarutils \
-	sdk/layoutlib_api \
-	sdk/layoutopt \
-	sdk/ninepatch \
-	sdk/rule_api \
-	sdk/lint \
-	sdk/sdkstats \
-	sdk/sdkmanager \
-	sdk/swtmenubar \
-	sdk/traceview \
-	development/apps \
-	development/tools/mkstubs \
-	packages
-else
-$(warning SDK_ONLY: javac not available.)
-endif
+include $(TOPDIR)sdk/build/sdk_only_whitelist.mk
+include $(TOPDIR)development/build/sdk_only_whitelist.mk
 
 # Exclude tools/acp when cross-compiling windows under linux
 ifeq ($(findstring Linux,$(UNAME)),)
@@ -475,23 +442,24 @@
 	build/libs \
 	build/target \
 	build/tools/acp \
+	external/gcc-demangle \
 	external/mksh \
 	external/yaffs2 \
 	external/zlib
 else	# !BUILD_TINY_ANDROID
-
-ifneq ($(TARGET_SUBDIRS),)
-subdirs := $(TARGET_SUBDIRS)
-else
+ifneq ($(BUILD_PDK),)
+subdirs := $(BUILD_PDK_SUBDIRS)
+FULL_BUILD := true
+else # Normal droid build
 #
 # Typical build; include any Android.mk files we can find.
 #
 subdirs := $(TOP)
 
-endif	# !TARGET_SUBDIRS
-
 FULL_BUILD := true
 
+endif  # !BUILD_PDK
+
 endif	# !BUILD_TINY_ANDROID
 
 endif	# !SDK_ONLY
@@ -752,12 +720,18 @@
 .PHONY: userdatatarball
 userdatatarball: $(INSTALLED_USERDATATARBALL_TARGET)
 
+.PHONY: cacheimage
+cacheimage: $(INSTALLED_CACHEIMAGE_TARGET)
+
 .PHONY: bootimage
 bootimage: $(INSTALLED_BOOTIMAGE_TARGET)
 
 ifeq ($(BUILD_TINY_ANDROID), true)
 INSTALLED_RECOVERYIMAGE_TARGET :=
 endif
+ifneq ($(BUILD_PDK),)
+INSTALLED_RECOVERYIMAGE_TARGET :=
+endif
 
 # Build files and then package it into the rom formats
 .PHONY: droidcore
@@ -766,6 +740,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.
@@ -822,8 +797,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/pathmap.mk b/core/pathmap.mk
index 60fbfd2..235f775 100644
--- a/core/pathmap.mk
+++ b/core/pathmap.mk
@@ -34,6 +34,7 @@
     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 \
@@ -47,8 +48,13 @@
     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 \
+    audio-effects:system/media/audio_effects/include \
+    audio-utils:system/media/audio_utils/include \
+    wilhelm:system/media/wilhelm/include \
+    wilhelm-ut:system/media/wilhelm/src/ut \
     speex:external/speex/include
 
 #
diff --git a/core/product.mk b/core/product.mk
index 4d4c983..b001ca2 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -84,7 +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
@@ -200,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 \
@@ -228,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 \
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/static_java_library.mk b/core/static_java_library.mk
index 93d770a..0b2f63b 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -21,5 +21,88 @@
 
 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.
+LOCAL_JAR_EXCLUDE_FILES := 'R.class' 'R$$*.class' 'Manifest.class' 'Manifest$$*.class'
+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)),)
+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/tasks/apicheck.mk b/core/tasks/apicheck.mk
index 96e0f44..b3d800b 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) $(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
index 2cbea87..6757194 100644
--- a/core/tasks/factory_ramdisk.mk
+++ b/core/tasks/factory_ramdisk.mk
@@ -60,10 +60,6 @@
 
 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
 
diff --git a/core/tasks/vendor_module_check.mk b/core/tasks/vendor_module_check.mk
new file mode 100644
index 0000000..c2d6c78
--- /dev/null
+++ b/core/tasks/vendor_module_check.mk
@@ -0,0 +1,79 @@
+#
+# 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 := \
+	broadcom \
+	csr \
+	imgtec \
+	invensense \
+	nxp \
+	samsung \
+	ti
+
+
+ifneq (,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_RESTRICT_VENDOR_FILES))
+
+_check_modules := $(sort $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES))
+
+# expand with the required modules
+# $(1) the module name set to expand
+define _expand_required_modules
+$(eval _erm_new_modules:=)\
+$(foreach m, $(1), $(eval r:=$(ALL_MODULES.$(m).REQUIRED))\
+  $(if $(r), $(if $(filter $(_check_modules), $(r)),,\
+    $(eval _check_modules := $(_check_modules) $(r))\
+    $(eval _erm_new_modules := $(_erm_new_modules) $(r)))))\
+$(if $(_erm_new_modules), $(call _expand_required_modules, $(_erm_new_modules)))
+endef
+
+$(call _expand_required_modules, $(_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, $(_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, $(_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
+
+endif
diff --git a/core/user_tags.mk b/core/user_tags.mk
index 2e7017e..53f0ee2 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 \
@@ -171,7 +171,6 @@
 	layoutlib_api \
 	layoutlib_create \
 	layoutlib_utils \
-	layoutopt \
 	liba2dp \
 	libabi \
 	libandroid \
@@ -472,7 +471,6 @@
 	sig-create \
 	signapk \
 	signature-tools \
-	simg2img \
 	spec-progress \
 	sqlite3 \
 	stack_dump \
@@ -494,7 +492,6 @@
 	traceview \
 	tune2fs \
 	tune2fs_host \
-	uix \
 	usbtest \
 	vdc \
 	vm-tests \
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index bff8ef9..c97306c 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
+  PLATFORM_VERSION := JellyBean
 endif
 
 ifeq "" "$(PLATFORM_SDK_VERSION)"
@@ -59,7 +59,7 @@
 ifeq "" "$(PLATFORM_VERSION_CODENAME)"
   # This is the current development code-name, if the build is not a final
   # release build.  If this is a final release build, it is simply "REL".
-  PLATFORM_VERSION_CODENAME := REL
+  PLATFORM_VERSION_CODENAME := JellyBean
 endif
 
 ifeq "" "$(DEFAULT_APP_TARGET_SDK)"
diff --git a/envsetup.sh b/envsetup.sh
index bab2d25..f11763a 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.
@@ -146,6 +146,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
@@ -502,8 +506,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"
@@ -611,12 +615,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`
@@ -643,7 +652,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
@@ -704,6 +713,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-android-linux-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
@@ -744,7 +761,7 @@
        echo >>"$OUT_ROOT/gdbclient.cmds" "target remote $PORT"
        echo >>"$OUT_ROOT/gdbclient.cmds" ""
 
-       arm-linux-androideabi-gdb -x "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
+       $GDB -x "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
   else
        echo "Unable to determine build system output dir."
    fi
@@ -908,7 +925,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()
@@ -1007,7 +1024,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 57e60d3..bc999fa 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..ca18365 100644
--- a/target/board/generic/device.mk
+++ b/target/board/generic/device.mk
@@ -26,6 +26,8 @@
     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 \
+    development/tools/emulator/system/camera/media_codecs.xml:system/etc/media_codecs.xml \
 
 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/device.mk b/target/board/generic_x86/device.mk
index 0dd2bc0..3a1d2f0 100644
--- a/target/board/generic_x86/device.mk
+++ b/target/board/generic_x86/device.mk
@@ -26,3 +26,4 @@
     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 \
+    development/tools/emulator/system/camera/media_codecs.xml:system/etc/media_codecs.xml \
diff --git a/target/board/vbox_x86/device.mk b/target/board/vbox_x86/device.mk
index 66a6e84..a650ed6 100644
--- a/target/board/vbox_x86/device.mk
+++ b/target/board/vbox_x86/device.mk
@@ -24,12 +24,13 @@
     ro.ril.gprsclass=10 \
     ro.adb.qemud=1
 
-LOCAL_KERNEL := prebuilt/android-x86/kernel/kernel-vbox
+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 \
     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 \
     build/target/board/vbox_x86/init.rc:root/init.rc \
     build/target/board/vbox_x86/init.vbox_x86.rc:root/init.vbox_x86.rc \
     $(LOCAL_KERNEL):kernel
diff --git a/target/product/AndroidProducts.mk b/target/product/AndroidProducts.mk
index e77c783..44b9000 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)/full.mk \
     $(LOCAL_DIR)/full_x86.mk \
diff --git a/target/product/core.mk b/target/product/core.mk
index abb2d9f..f655904 100644
--- a/target/product/core.mk
+++ b/target/product/core.mk
@@ -67,9 +67,11 @@
     ip-up-vpn \
     ip6tables \
     iptables \
+    libandroidfw \
     libOpenMAXAL \
     libOpenSLES \
     libaudiopreprocessing \
+    libaudioutils \
     libcrypto \
     libdvm \
     libexpat \
@@ -84,10 +86,13 @@
     libspeexresampler \
     libsqlite_jni \
     libssl \
-    libstagefright_soft_h264dec \
     libstagefright_soft_aacdec \
+    libstagefright_soft_aacenc \
     libstagefright_soft_amrdec \
+    libstagefright_soft_amrnbenc \
+    libstagefright_soft_amrwbenc \
     libstagefright_soft_g711dec \
+    libstagefright_soft_h264dec \
     libstagefright_soft_mp3dec \
     libstagefright_soft_mpeg4dec \
     libstagefright_soft_vorbisdec \
@@ -96,8 +101,11 @@
     libwebrtc_audio_preprocessing \
     libwilhelm \
     libz \
+    requestsync \
     screencap \
-    sensorservice
+    sensorservice \
+    lint
+
 
 # host-only dependencies
 ifeq ($(WITH_HOST_DALVIK),true)
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_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 a39f05a..2a65adf 100644
--- a/target/product/generic_no_telephony.mk
+++ b/target/product/generic_no_telephony.mk
@@ -21,7 +21,6 @@
 
 PRODUCT_PACKAGES := \
     DeskClock \
-    AlarmProvider \
     Bluetooth \
     Calculator \
     Calendar \
@@ -54,11 +53,14 @@
     librs_jni \
     libvideoeditor_jni \
     libvideoeditorplayer \
-    libvideoeditor_core
+    libvideoeditor_core \
+    libdownmix
 
 PRODUCT_PACKAGES += \
     audio.primary.default \
-    audio_policy.default
+    audio_policy.default \
+    local_time.default \
+    power.default
 
 PRODUCT_PACKAGES += \
     local_time.default
diff --git a/target/product/large_emu_hw.mk b/target/product/large_emu_hw.mk
index 15b1bed..91a9e08 100644
--- a/target/product/large_emu_hw.mk
+++ b/target/product/large_emu_hw.mk
@@ -22,11 +22,9 @@
 PRODUCT_PACKAGES := \
     CarHome \
     DeskClock \
-    AlarmProvider \
     Bluetooth \
     Calculator \
     Calendar \
-    Camera \
     CertInstaller \
     DrmProvider \
     Email \
diff --git a/target/product/locales_full.mk b/target/product/locales_full.mk
index 1031303..8b8ab05 100644
--- a/target/product/locales_full.mk
+++ b/target/product/locales_full.mk
@@ -1,3 +1,3 @@
-PRODUCT_LOCALES := cs_CZ da_DK de_AT de_CH de_DE de_LI el_GR en_AU en_CA en_GB en_NZ en_SG en_US es_ES fr_CA fr_CH fr_BE fr_FR it_CH it_IT ja_JP ko_KR nb_NO nl_BE nl_NL pl_PL pt_PT ru_RU sv_SE tr_TR zh_CN zh_HK zh_TW am_ET hi_IN
+PRODUCT_LOCALES := en_US cs_CZ da_DK de_AT de_CH de_DE de_LI el_GR en_AU en_CA en_GB en_NZ en_SG es_ES fr_CA fr_CH fr_BE fr_FR it_CH it_IT ja_JP ko_KR nb_NO nl_BE nl_NL pl_PL pt_PT ru_RU sv_SE tr_TR zh_CN zh_HK zh_TW am_ET hi_IN
 
 $(call inherit-product, build/target/product/languages_full.mk)
diff --git a/target/product/sdk.mk b/target/product/sdk.mk
index 1a71bf1..7287664 100644
--- a/target/product/sdk.mk
+++ b/target/product/sdk.mk
@@ -19,7 +19,6 @@
 
 PRODUCT_PACKAGES := \
 	Calculator \
-	Camera \
 	DeskClock \
 	Email \
 	Exchange \
@@ -77,7 +76,6 @@
 	ddms \
 	hierarchyviewer \
 	draw9patch \
-	layoutopt \
 	traceview \
 	android \
 	dexdump \
@@ -88,6 +86,7 @@
 # See development/build/sdk.atree
 PRODUCT_PACKAGES += \
 	androidprefs \
+	annotations \
 	sdkstats \
 	archquery \
 	ddms \
@@ -95,14 +94,15 @@
 	ddmuilib \
 	draw9patch \
 	hierarchyviewer \
-	layoutopt \
-	uix \
 	traceview \
 	anttasks \
+	ide_common \
 	sdklib \
 	sdkuilib \
 	sdkmanager \
 	swtmenubar \
+	rule_api \
+	assetstudio \
 	swing-worker-1.1 \
 	groovy-all-1.7.0 \
 	commons-compress-1.0 \
@@ -130,7 +130,8 @@
 # audio libraries.
 PRODUCT_PACKAGES += \
 	audio.primary.goldfish \
-	audio_policy.default
+	audio_policy.default \
+	local_time.default
 
 PRODUCT_PACKAGE_OVERLAYS := development/sdk_overlay
 
diff --git a/tools/adbs b/tools/adbs
index b571d48..1a400f7 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 = "./prebuilt/" + uname + "/toolchain/arm-linux-androideabi-4.4.x/bin/"
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/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/java-layers.py b/tools/java-layers.py
deleted file mode 100755
index b3aec2b..0000000
--- a/tools/java-layers.py
+++ /dev/null
@@ -1,257 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import re
-import sys
-
-def fail_with_usage():
-  sys.stderr.write("usage: java-layers.py DEPENDENCY_FILE SOURCE_DIRECTORIES...\n")
-  sys.stderr.write("\n")
-  sys.stderr.write("Enforces layering between java packages.  Scans\n")
-  sys.stderr.write("DIRECTORY and prints errors when the packages violate\n")
-  sys.stderr.write("the rules defined in the DEPENDENCY_FILE.\n")
-  sys.stderr.write("\n")
-  sys.stderr.write("Prints a warning when an unknown package is encountered\n")
-  sys.stderr.write("on the assumption that it should fit somewhere into the\n")
-  sys.stderr.write("layering.\n")
-  sys.stderr.write("\n")
-  sys.stderr.write("DEPENDENCY_FILE format\n")
-  sys.stderr.write("  - # starts comment\n")
-  sys.stderr.write("  - Lines consisting of two java package names:  The\n")
-  sys.stderr.write("    first package listed must not contain any references\n")
-  sys.stderr.write("    to any classes present in the second package, or any\n")
-  sys.stderr.write("    of its dependencies.\n")
-  sys.stderr.write("  - Lines consisting of one java package name:  The\n")
-  sys.stderr.write("    packge is assumed to be a high level package and\n")
-  sys.stderr.write("    nothing may depend on it.\n")
-  sys.stderr.write("  - Lines consisting of a dash (+) followed by one java\n")
-  sys.stderr.write("    package name: The package is considered a low level\n")
-  sys.stderr.write("    package and may not import any of the other packages\n")
-  sys.stderr.write("    listed in the dependency file.\n")
-  sys.stderr.write("  - Lines consisting of a plus (-) followed by one java\n")
-  sys.stderr.write("    package name: The package is considered \'legacy\'\n")
-  sys.stderr.write("    and excluded from errors.\n")
-  sys.stderr.write("\n")
-  sys.exit(1)
-
-class Dependency:
-  def __init__(self, filename, lineno, lower, top, lowlevel, legacy):
-    self.filename = filename
-    self.lineno = lineno
-    self.lower = lower
-    self.top = top
-    self.lowlevel = lowlevel
-    self.legacy = legacy
-    self.uppers = []
-    self.transitive = set()
-
-  def matches(self, imp):
-    for d in self.transitive:
-      if imp.startswith(d):
-        return True
-    return False
-
-class Dependencies:
-  def __init__(self, deps):
-    def recurse(obj, dep, visited):
-      global err
-      if dep in visited:
-        sys.stderr.write("%s:%d: Circular dependency found:\n"
-            % (dep.filename, dep.lineno))
-        for v in visited:
-          sys.stderr.write("%s:%d:    Dependency: %s\n"
-              % (v.filename, v.lineno, v.lower))
-        err = True
-        return
-      visited.append(dep)
-      for upper in dep.uppers:
-        obj.transitive.add(upper)
-        if upper in deps:
-          recurse(obj, deps[upper], visited)
-    self.deps = deps
-    self.parts = [(dep.lower.split('.'),dep) for dep in deps.itervalues()]
-    # transitive closure of dependencies
-    for dep in deps.itervalues():
-      recurse(dep, dep, [])
-    # disallow everything from the low level components
-    for dep in deps.itervalues():
-      if dep.lowlevel:
-        for d in deps.itervalues():
-          if dep != d and not d.legacy:
-            dep.transitive.add(d.lower)
-    # disallow the 'top' components everywhere but in their own package
-    for dep in deps.itervalues():
-      if dep.top and not dep.legacy:
-        for d in deps.itervalues():
-          if dep != d and not d.legacy:
-            d.transitive.add(dep.lower)
-    for dep in deps.itervalues():
-      dep.transitive = set([x+"." for x in dep.transitive])
-    if False:
-      for dep in deps.itervalues():
-        print "-->", dep.lower, "-->", dep.transitive
-
-  # Lookup the dep object for the given package.  If pkg is a subpackage
-  # of one with a rule, that one will be returned.  If no matches are found,
-  # None is returned.
-  def lookup(self, pkg):
-    # Returns the number of parts that match
-    def compare_parts(parts, pkg):
-      if len(parts) > len(pkg):
-        return 0
-      n = 0
-      for i in range(0, len(parts)):
-        if parts[i] != pkg[i]:
-          return 0
-        n = n + 1
-      return n
-    pkg = pkg.split(".")
-    matched = 0
-    result = None
-    for (parts,dep) in self.parts:
-      x = compare_parts(parts, pkg)
-      if x > matched:
-        matched = x
-        result = dep
-    return result
-
-def parse_dependency_file(filename):
-  global err
-  f = file(filename)
-  lines = f.readlines()
-  f.close()
-  def lineno(s, i):
-    i[0] = i[0] + 1
-    return (i[0],s)
-  n = [0]
-  lines = [lineno(x,n) for x in lines]
-  lines = [(n,s.split("#")[0].strip()) for (n,s) in lines]
-  lines = [(n,s) for (n,s) in lines if len(s) > 0]
-  lines = [(n,s.split()) for (n,s) in lines]
-  deps = {}
-  for n,words in lines:
-    if len(words) == 1:
-      lower = words[0]
-      top = True
-      legacy = False
-      lowlevel = False
-      if lower[0] == '+':
-        lower = lower[1:]
-        top = False
-        lowlevel = True
-      elif lower[0] == '-':
-        lower = lower[1:]
-        legacy = True
-      if lower in deps:
-        sys.stderr.write(("%s:%d: Package '%s' already defined on"
-            + " line %d.\n") % (filename, n, lower, deps[lower].lineno))
-        err = True
-      else:
-        deps[lower] = Dependency(filename, n, lower, top, lowlevel, legacy)
-    elif len(words) == 2:
-      lower = words[0]
-      upper = words[1]
-      if lower in deps:
-        dep = deps[lower]
-        if dep.top:
-          sys.stderr.write(("%s:%d: Can't add dependency to top level package "
-            + "'%s'\n") % (filename, n, lower))
-          err = True
-      else:
-        dep = Dependency(filename, n, lower, False, False, False)
-        deps[lower] = dep
-      dep.uppers.append(upper)
-    else:
-      sys.stderr.write("%s:%d: Too many words on line starting at \'%s\'\n" % (
-          filename, n, words[2]))
-      err = True
-  return Dependencies(deps)
-
-def find_java_files(srcs):
-  result = []
-  for d in srcs:
-    if d[0] == '@':
-      f = file(d[1:])
-      result.extend([fn for fn in [s.strip() for s in f.readlines()]
-          if len(fn) != 0])
-      f.close()
-    else:
-      for root, dirs, files in os.walk(d):
-        result.extend([os.sep.join((root,f)) for f in files
-            if f.lower().endswith(".java")])
-  return result
-
-COMMENTS = re.compile("//.*?\n|/\*.*?\*/", re.S)
-PACKAGE = re.compile("package\s+(.*)")
-IMPORT = re.compile("import\s+(.*)")
-
-def examine_java_file(deps, filename):
-  global err
-  # Yes, this is a crappy java parser.  Write a better one if you want to.
-  f = file(filename)
-  text = f.read()
-  f.close()
-  text = COMMENTS.sub("", text)
-  index = text.find("{")
-  if index < 0:
-    sys.stderr.write(("%s: Error: Unable to parse java. Can't find class "
-        + "declaration.\n") % filename)
-    err = True
-    return
-  text = text[0:index]
-  statements = [s.strip() for s in text.split(";")]
-  # First comes the package declaration.  Then iterate while we see import
-  # statements.  Anything else is either bad syntax that we don't care about
-  # because the compiler will fail, or the beginning of the class declaration.
-  m = PACKAGE.match(statements[0])
-  if not m:
-    sys.stderr.write(("%s: Error: Unable to parse java. Missing package "
-        + "statement.\n") % filename)
-    err = True
-    return
-  pkg = m.group(1)
-  imports = []
-  for statement in statements[1:]:
-    m = IMPORT.match(statement)
-    if not m:
-      break
-    imports.append(m.group(1))
-  # Do the checking
-  if False:
-    print filename
-    print "'%s' --> %s" % (pkg, imports)
-  dep = deps.lookup(pkg)
-  if not dep:
-    sys.stderr.write(("%s: Error: Package does not appear in dependency file: "
-      + "%s\n") % (filename, pkg))
-    err = True
-    return
-  for imp in imports:
-    if dep.matches(imp):
-      sys.stderr.write("%s: Illegal import in package '%s' of '%s'\n"
-          % (filename, pkg, imp))
-      err = True
-
-err = False
-
-def main(argv):
-  if len(argv) < 3:
-    fail_with_usage()
-  deps = parse_dependency_file(argv[1])
-
-  if err:
-    sys.exit(1)
-
-  java = find_java_files(argv[2:])
-  for filename in java:
-    examine_java_file(deps, filename)
-
-  if err:
-    sys.stderr.write("%s: Using this file as dependency file.\n" % argv[1])
-    sys.exit(1)
-
-  sys.exit(0)
-
-if __name__ == "__main__":
-  main(sys.argv)
-
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
new file mode 100755
index 0000000..15acddc
--- /dev/null
+++ b/tools/releasetools/build_image.py
@@ -0,0 +1,139 @@
+#!/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"])
+  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)
+
+  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",
+      )
+  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..8196b3c 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")
 
@@ -389,24 +390,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 +663,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 +678,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 d7b924b..8c31927 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 c5b9886..002e6e6 100755
--- a/tools/releasetools/img_from_target_files
+++ b/tools/releasetools/img_from_target_files
@@ -47,6 +47,7 @@
 if not hasattr(os, "SEEK_SET"):
   os.SEEK_SET = 0
 
+import build_image
 import common
 
 OPTIONS = common.OPTIONS
@@ -64,27 +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"]))
-  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)
-
-  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")
@@ -93,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."""
@@ -115,28 +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"]))
-  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)
-
-  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()
@@ -190,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 1514ea7..7e855ce 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -48,9 +48,6 @@
 
   -e  (--extra_script)  <file>
       Insert the contents of file at the end of the update script.
-
-  -a  (--aslr_mode)  <on|off>
-      Specify whether to turn on ASLR for the package (on by default).
 """
 
 import sys
@@ -260,15 +257,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/"):
@@ -286,9 +281,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)
@@ -296,7 +288,7 @@
           Item.Get(fn, dir=False)
 
   symlinks.sort()
-  return (symlinks, retouch_files)
+  return symlinks
 
 
 def SignOutput(temp_zip_name, output_zip_name):
@@ -382,6 +374,7 @@
 
   AppendAssertions(script, input_zip)
   device_specific.FullOTA_Assertions()
+  device_specific.FullOTA_InstallBegin()
 
   script.ShowProgress(0.5, 0)
 
@@ -393,12 +386,8 @@
   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")
@@ -439,17 +428,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):
@@ -488,9 +473,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 = []
@@ -559,6 +544,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:
@@ -594,6 +581,8 @@
 
   script.Comment("---- start making changes here ----")
 
+  device_specific.IncrementalOTA_InstallBegin()
+
   if OPTIONS.wipe_user_data:
     script.Print("Erasing user data...")
     script.FormatPartition("/data")
@@ -660,7 +649,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()
@@ -669,7 +658,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
@@ -703,10 +692,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.
diff --git a/tools/zipalign/Android.mk b/tools/zipalign/Android.mk
index 9763bd2..8ed60df 100644
--- a/tools/zipalign/Android.mk
+++ b/tools/zipalign/Android.mk
@@ -15,6 +15,7 @@
 LOCAL_C_INCLUDES += external/zlib
 
 LOCAL_STATIC_LIBRARIES := \
+	libandroidfw \
 	libutils \
 	libcutils
 
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..8057068 100644
--- a/tools/zipalign/ZipFile.cpp
+++ b/tools/zipalign/ZipFile.cpp
@@ -20,7 +20,7 @@
 
 #define LOG_TAG "zip"
 
-#include <utils/ZipUtils.h>
+#include <androidfw/ZipUtils.h>
 #include <utils/Log.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