am 9b996f80: am eb9b62e0: Merge "Make -rpath-link work with multilib."

* commit '9b996f80a95f48bae153c35bacc0360c004e5258':
  Make -rpath-link work with multilib.
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 5a8ad58..4eec704 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -200,6 +200,12 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/SprintDM.apk)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/etc/omadm)
 
+# GCC 4.8
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/EXECUTABLES)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/lib/*.o)
+
 # KLP I mean KitKat now API 19.
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
@@ -223,6 +229,11 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 
+# L development
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/core/Makefile b/core/Makefile
index 53148bf..42eda82 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -20,7 +20,7 @@
 # src:dest pair is the first one to match the same dest"
 #$(1): the src:dest pair
 define check-product-copy-files
-$(if $(filter %.apk, $(1)),$(error \
+$(if $(filter %.apk, $(call word-colon, 2, $(1))),$(error \
     Prebuilt apk found in PRODUCT_COPY_FILES: $(1), use BUILD_PREBUILT instead!))
 endef
 # filter out the duplicate <source file>:<dest file> pairs.
@@ -385,6 +385,8 @@
   INSTALLED_KERNEL_TARGET :=
 endif
 
+VERITY_SIGNER_CMD := $(HOST_OUT_EXECUTABLES)/verity_signer
+
 # -----------------------------------------------------------------
 # the ramdisk
 INTERNAL_RAMDISK_FILES := $(filter $(TARGET_ROOT_OUT)/%, \
@@ -617,6 +619,10 @@
 endif
 INTERNAL_USERIMAGES_BINARY_PATHS := $(sort $(dir $(INTERNAL_USERIMAGES_DEPS)))
 
+ifeq (true, $(PRODUCT_SUPPORTS_VERITY))
+INTERNAL_USERIMAGES_DEPS += $(HOST_OUT_EXECUTABLES)/verity_signer
+endif
+
 SELINUX_FC := $(TARGET_ROOT_OUT)/file_contexts
 INTERNAL_USERIMAGES_DEPS += $(SELINUX_FC)
 
@@ -829,7 +835,12 @@
 define build-systemimage-target
   @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, skip_fsck=true)
+  $(call generate-userimage-prop-dictionary, $(systemimage_intermediates)/system_image_info.txt, \
+      skip_fsck=true \
+      verity=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY) \
+      verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_PARTITION) \
+      verity_key=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY) \
+      verity_signer_cmd=$(VERITY_SIGNER_CMD))
   $(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)
@@ -1281,6 +1292,7 @@
 	$(hide) echo "multistage_support=1" >> $(zip_root)/META/misc_info.txt
 	$(hide) echo "update_rename_support=1" >> $(zip_root)/META/misc_info.txt
 	$(call generate-userimage-prop-dictionary, $(zip_root)/META/misc_info.txt)
+	$(hide) ./build/tools/releasetools/make_recovery_patch $(zip_root) $(zip_root)
 	@# Zip everything up, preserving symlinks
 	$(hide) (cd $(zip_root) && zip -qry ../$(notdir $@) .)
 	@# Run fs_config on all the system, boot ramdisk, and recovery ramdisk files in the zip, and save the output
@@ -1315,6 +1327,7 @@
 	@echo "Package OTA: $@"
 	$(hide) MKBOOTIMG=$(BOARD_CUSTOM_MKBOOTIMG) \
 	   ./build/tools/releasetools/ota_from_target_files -v \
+	   --block \
 	   -p $(HOST_OUT) \
 	   -k $(KEY_CERT_PAIR) \
 	   $(BUILT_TARGET_FILES_PACKAGE) $@
@@ -1333,18 +1346,10 @@
 
 INTERNAL_UPDATE_PACKAGE_TARGET := $(PRODUCT_OUT)/$(name).zip
 
-ifeq ($(TARGET_RELEASETOOLS_EXTENSIONS),)
-# default to common dir for device vendor
-$(INTERNAL_UPDATE_PACKAGE_TARGET): extensions := $(TARGET_DEVICE_DIR)/../common
-else
-$(INTERNAL_UPDATE_PACKAGE_TARGET): extensions := $(TARGET_RELEASETOOLS_EXTENSIONS)
-endif
-
 $(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(DISTTOOLS)
 	@echo "Package: $@"
 	$(hide) MKBOOTIMG=$(BOARD_CUSTOM_MKBOOTIMG) \
 	   ./build/tools/releasetools/img_from_target_files -v \
-	   -s $(extensions) \
 	   -p $(HOST_OUT) \
 	   $(BUILT_TARGET_FILES_PACKAGE) $@
 
@@ -1439,7 +1444,7 @@
 # the dependency will be set up later in build/core/main.mk.
 $(EMMA_META_ZIP) :
 	@echo "Collecting Emma coverage meta files."
-	$(hide) find $(TARGET_COMMON_OUT_ROOT) -name "coverage.em" | \
+	$(hide) find $(TARGET_COMMON_OUT_ROOT) $(HOST_COMMON_OUT_ROOT) -name "coverage.em" | \
 		zip -@ -q $@
 
 endif # EMMA_INSTRUMENT=true
@@ -1455,7 +1460,8 @@
 	@echo "Packaging Proguard obfuscation dictionary files."
 	$(hide) dict_files=`find $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS -name proguard_dictionary`; \
 		if [ -n "$$dict_files" ]; then \
-		  zip -q $@ $$dict_files; \
+		  unobfuscated_jars=$${dict_files//proguard_dictionary/classes.jar}; \
+		  zip -q $@ $$dict_files $$unobfuscated_jars; \
 		else \
 		  touch $(dir $@)/dummy; \
 		  (cd $(dir $@) && zip -q $(notdir $@) dummy); \
diff --git a/core/binary.mk b/core/binary.mk
index e22cd84..6438137 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -427,6 +427,8 @@
 
 proto_generated_headers := $(patsubst %.pb.cc,%.pb.h, $(proto_generated_cc_sources))
 $(proto_generated_headers): $(proto_generated_cc_sources_dir)/%.pb.h: $(proto_generated_cc_sources_dir)/%.pb.cc
+	# This is just a dummy rule to make sure gmake doesn't skip updating the dependents.
+	@echo "Updated header file $<."
 
 $(proto_generated_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
 $(proto_generated_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
diff --git a/core/build_id.mk b/core/build_id.mk
index aaf4185..221a2f3 100644
--- a/core/build_id.mk
+++ b/core/build_id.mk
@@ -18,6 +18,6 @@
 # (like "CRB01").  It must be a single word, and is
 # capitalized by convention.
 
-BUILD_ID := OPENMASTER
+BUILD_ID := MASTER
 
 DISPLAY_BUILD_NUMBER := true
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index c36e0cb..87c608a 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -143,6 +143,7 @@
 LOCAL_POST_INSTALL_CMD:=
 LOCAL_DIST_BUNDLED_BINARIES:=
 LOCAL_HAL_STATIC_LIBRARIES:=
+LOCAL_RMTYPEDEFS:=
 LOCAL_NO_SYNTAX_CHECK:=
 LOCAL_NO_STATIC_ANALYZER:=
 LOCAL_32_BIT_ONLY:= # '',true
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index 213cae2..da1b70a 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -114,7 +114,7 @@
 # into no-op in some builds while mesg is defined earlier. So we explicitly
 # disable "-Wunused-but-set-variable" here.
 ifneq ($(filter 4.6 4.6.% 4.7 4.7.% 4.8, $($(combo_2nd_arch_prefix)TARGET_GCC_VERSION)),)
-$(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += -Wno-unused-but-set-variable -fno-builtin-sin \
+$(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += -fno-builtin-sin \
 			-fno-strict-volatile-bitfields
 endif
 
diff --git a/core/combo/include/arch/darwin-x86/AndroidConfig.h b/core/combo/include/arch/darwin-x86/AndroidConfig.h
index 012f014..121bba3 100644
--- a/core/combo/include/arch/darwin-x86/AndroidConfig.h
+++ b/core/combo/include/arch/darwin-x86/AndroidConfig.h
@@ -56,13 +56,6 @@
 #define HAVE_FORKEXEC
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-/* #define HAVE_OOM_ADJ */
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/combo/include/arch/freebsd-x86/AndroidConfig.h b/core/combo/include/arch/freebsd-x86/AndroidConfig.h
index 6f50918..120f484 100644
--- a/core/combo/include/arch/freebsd-x86/AndroidConfig.h
+++ b/core/combo/include/arch/freebsd-x86/AndroidConfig.h
@@ -61,13 +61,6 @@
 #define HAVE_FORKEXEC
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-/* #define HAVE_OOM_ADJ */
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/combo/include/arch/linux-arm/AndroidConfig.h b/core/combo/include/arch/linux-arm/AndroidConfig.h
index 9257d3e..28d0d30 100644
--- a/core/combo/include/arch/linux-arm/AndroidConfig.h
+++ b/core/combo/include/arch/linux-arm/AndroidConfig.h
@@ -69,13 +69,6 @@
 #define HAVE_FORKEXEC
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-#define HAVE_OOM_ADJ
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/combo/include/arch/linux-mips/AndroidConfig.h b/core/combo/include/arch/linux-mips/AndroidConfig.h
index e24f3ea..8bfbe9f 100644
--- a/core/combo/include/arch/linux-mips/AndroidConfig.h
+++ b/core/combo/include/arch/linux-mips/AndroidConfig.h
@@ -69,13 +69,6 @@
 #define HAVE_FORKEXEC
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-#define HAVE_OOM_ADJ
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/combo/include/arch/linux-ppc/AndroidConfig.h b/core/combo/include/arch/linux-ppc/AndroidConfig.h
index a12ef47..24b0da5 100644
--- a/core/combo/include/arch/linux-ppc/AndroidConfig.h
+++ b/core/combo/include/arch/linux-ppc/AndroidConfig.h
@@ -56,13 +56,6 @@
 #define HAVE_FORKEXEC
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-#define HAVE_OOM_ADJ
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/combo/include/arch/linux-x86/AndroidConfig.h b/core/combo/include/arch/linux-x86/AndroidConfig.h
index 2db66a2..359cfb9 100644
--- a/core/combo/include/arch/linux-x86/AndroidConfig.h
+++ b/core/combo/include/arch/linux-x86/AndroidConfig.h
@@ -56,13 +56,6 @@
 #define HAVE_FORKEXEC
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-#define HAVE_OOM_ADJ
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/combo/include/arch/target_linux-x86/AndroidConfig.h b/core/combo/include/arch/target_linux-x86/AndroidConfig.h
index 25a1f5d..bbb36fc 100644
--- a/core/combo/include/arch/target_linux-x86/AndroidConfig.h
+++ b/core/combo/include/arch/target_linux-x86/AndroidConfig.h
@@ -55,13 +55,6 @@
 #define HAVE_FORKEXEC
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-#define HAVE_OOM_ADJ
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/combo/include/arch/windows/AndroidConfig.h b/core/combo/include/arch/windows/AndroidConfig.h
index 0a52674..204740d 100644
--- a/core/combo/include/arch/windows/AndroidConfig.h
+++ b/core/combo/include/arch/windows/AndroidConfig.h
@@ -83,13 +83,6 @@
 #endif
 
 /*
- * Process out-of-memory adjustment.  Set if running on Linux,
- * where we can write to /proc/<pid>/oom_adj to modify the out-of-memory
- * badness adjustment.
- */
-/* #define HAVE_OOM_ADJ */
-
-/*
  * IPC model.  Choose one:
  *
  * HAVE_SYSV_IPC - use the classic SysV IPC mechanisms (semget, shmget).
diff --git a/core/config.mk b/core/config.mk
index 7fcc171..c422bc8 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -337,6 +337,7 @@
 LLVM_RS_CC := $(HOST_OUT_EXECUTABLES)/llvm-rs-cc$(HOST_EXECUTABLE_SUFFIX)
 BCC_COMPAT := $(HOST_OUT_EXECUTABLES)/bcc_compat$(HOST_EXECUTABLE_SUFFIX)
 LINT := prebuilts/sdk/tools/lint
+RMTYPEDEFS := $(HOST_OUT_EXECUTABLES)/rmtypedefs
 
 # ACP is always for the build OS, not for the host OS
 ACP := $(BUILD_OUT_EXECUTABLES)/acp$(BUILD_EXECUTABLE_SUFFIX)
diff --git a/core/definitions.mk b/core/definitions.mk
index 526b479..f64fc31 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -1240,11 +1240,11 @@
 	-Wl,-rpath-link=$(HOST_OUT_INTERMEDIATE_LIBRARIES) \
 	-Wl,-rpath,\$$ORIGIN/../lib \
 	-shared -Wl,-soname,$(notdir $@) \
-	$(PRIVATE_LDFLAGS) \
 	$(HOST_GLOBAL_LD_DIRS) \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	   $(PRIVATE_HOST_GLOBAL_LDFLAGS) \
 	) \
+	$(PRIVATE_LDFLAGS) \
 	$(PRIVATE_ALL_OBJECTS) \
 	-Wl,--whole-archive \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_WHOLE_STATIC_LIBRARIES)) \
@@ -1395,11 +1395,11 @@
 	-Wl,-rpath-link=$(HOST_OUT_INTERMEDIATE_LIBRARIES) \
 	-Wl,-rpath,\$$ORIGIN/../lib \
 	$(HOST_GLOBAL_LD_DIRS) \
-	$(PRIVATE_LDFLAGS) \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 		$(PRIVATE_HOST_GLOBAL_LDFLAGS) \
 		-fPIE -pie \
 	) \
+	$(PRIVATE_LDFLAGS) \
 	-o $@ \
 	$(PRIVATE_LDLIBS)
 endef
@@ -1533,7 +1533,7 @@
 $(call unzip-jar-files,$(PRIVATE_STATIC_JAVA_LIBRARIES),$(PRIVATE_CLASS_INTERMEDIATES_DIR))
 $(call dump-words-to-file,$(PRIVATE_JAVA_SOURCES),$(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list)
 $(hide) if [ -d "$(PRIVATE_SOURCE_INTERMEDIATES_DIR)" ]; then \
-	    find $(PRIVATE_SOURCE_INTERMEDIATES_DIR) -name '*.java' >> $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list; \
+          find $(PRIVATE_SOURCE_INTERMEDIATES_DIR) -name '*.java' >> $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list; \
 fi
 $(hide) tr ' ' '\n' < $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list \
     | sort -u > $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq
@@ -1562,8 +1562,13 @@
     $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
         -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))) \
     | xargs rm -rf)
-$(hide) jar $(if $(strip $(PRIVATE_JAR_MANIFEST)),-cfm,-cf) \
-    $@ $(PRIVATE_JAR_MANIFEST) -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .
+$(if $(PRIVATE_RMTYPEDEFS), $(hide) $(RMTYPEDEFS) -v $(PRIVATE_CLASS_INTERMEDIATES_DIR))
+$(if $(PRIVATE_JAR_MANIFEST), \
+    $(hide) sed -e 's/%BUILD_NUMBER%/$(BUILD_NUMBER)/' \
+            $(PRIVATE_JAR_MANIFEST) > $(dir $@)/manifest.mf && \
+        jar -cfm $@ $(dir $@)/manifest.mf \
+            -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) ., \
+    $(hide) jar -cf $@ -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .)
 endef
 
 define transform-java-to-classes.jar
@@ -1613,8 +1618,13 @@
     $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
         -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))) \
     | xargs rm -rf)
-$(hide) jar $(if $(strip $(PRIVATE_JAR_MANIFEST)),-cfm,-cf) \
-    $@ $(PRIVATE_JAR_MANIFEST) -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .
+$(if $(PRIVATE_RMTYPEDEFS), $(hide) $(RMTYPEDEFS) -v $(PRIVATE_CLASS_INTERMEDIATES_DIR))
+$(if $(PRIVATE_JAR_MANIFEST), \
+    $(hide) sed -e 's/%BUILD_NUMBER%/$(BUILD_NUMBER)/' \
+            $(PRIVATE_JAR_MANIFEST) > $(dir $@)/manifest.mf && \
+        jar -cfm $@ $(dir $@)/manifest.mf \
+            -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) ., \
+    $(hide) jar -cf $@ -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .)
 $(hide) mv $(PRIVATE_CLASS_INTERMEDIATES_DIR)/newstamp $(PRIVATE_CLASS_INTERMEDIATES_DIR)/stamp
 endef
 
@@ -1636,9 +1646,10 @@
 define transform-classes.jar-to-dex
 @echo "target Dex: $(PRIVATE_MODULE)"
 @mkdir -p $(dir $@)
+$(hide) rm -f $(dir $@)/classes*.dex
 $(hide) $(DX) \
     $(if $(findstring windows,$(HOST_OS)),,-JXms16M -JXmx2048M) \
-    --dex --output=$@ \
+    --dex --output=$(dir $@) \
     $(incremental_dex) \
     $(if $(NO_OPTIMIZE_DX), \
         --no-optimize) \
@@ -1698,11 +1709,7 @@
 
 #TODO: update the manifest to point to the dex file
 define add-dex-to-package
-$(if $(filter classes.dex,$(notdir $(PRIVATE_DEX_FILE))),\
-$(hide) zip -qj $@ $(PRIVATE_DEX_FILE),\
-$(hide) _adtp_classes_dex=$(dir $(PRIVATE_DEX_FILE))classes.dex; \
-cp $(PRIVATE_DEX_FILE) $$_adtp_classes_dex && \
-zip -qj $@ $$_adtp_classes_dex && rm -f $$_adtp_classes_dex)
+$(hide) zip -qj $@ $(dir $(PRIVATE_DEX_FILE))/classes*.dex
 endef
 
 # Add java resources added by the current module.
diff --git a/core/droiddoc.mk b/core/droiddoc.mk
index 93b56d4..d8e9251 100644
--- a/core/droiddoc.mk
+++ b/core/droiddoc.mk
@@ -52,12 +52,7 @@
 endif
 
 
-$(full_target): PRIVATE_BOOTCLASSPATH :=
-ifeq ($(BUILD_OS),linux)
-# You have to set bootclasspath for javadoc manually on linux since Java 6.
-host_jdk_rt_jar := $(dir $(HOST_JDK_TOOLS_JAR))../jre/lib/rt.jar
-$(full_target): PRIVATE_BOOTCLASSPATH := $(host_jdk_rt_jar)
-endif
+$(full_target): PRIVATE_BOOTCLASSPATH := $(call java-lib-files, core)
 
 ifneq ($(LOCAL_IS_HOST_MODULE),true)
 
@@ -202,6 +197,7 @@
                 -J-Xmx1024m \
                 $(PRIVATE_PROFILING_OPTIONS) \
                 $(addprefix -classpath ,$(PRIVATE_CLASSPATH)) \
+                $(addprefix -bootclasspath ,$(PRIVATE_BOOTCLASSPATH)) \
                 -sourcepath $(PRIVATE_SOURCE_PATH)$(addprefix :,$(PRIVATE_CLASSPATH)) \
                 -d $(PRIVATE_OUT_DIR) \
                 -quiet \
diff --git a/core/envsetup.mk b/core/envsetup.mk
index 4cb389b..b2122e9 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -207,6 +207,7 @@
 HOST_OUT_INTERMEDIATE_LIBRARIES := $(HOST_OUT_INTERMEDIATES)/lib
 HOST_OUT_NOTICE_FILES := $(HOST_OUT_INTERMEDIATES)/NOTICE_FILES
 HOST_OUT_COMMON_INTERMEDIATES := $(HOST_COMMON_OUT_ROOT)/obj
+HOST_OUT_FAKE := $(HOST_OUT)/fake_packages
 
 HOST_OUT_GEN := $(HOST_OUT)/gen
 HOST_OUT_COMMON_GEN := $(HOST_COMMON_OUT_ROOT)/gen
diff --git a/core/host_java_library.mk b/core/host_java_library.mk
index e5ebb11..2a8f18f 100644
--- a/core/host_java_library.mk
+++ b/core/host_java_library.mk
@@ -20,21 +20,64 @@
 
 #######################################
 include $(BUILD_SYSTEM)/host_java_library_common.mk
+#######################################
+
+# Enable emma instrumentation only if the module asks so.
+ifeq (true,$(LOCAL_EMMA_INSTRUMENT))
+ifneq (true,$(EMMA_INSTRUMENT))
+LOCAL_EMMA_INSTRUMENT :=
+endif
+endif
+
+full_classes_compiled_jar := $(intermediates.COMMON)/classes-full-debug.jar
+emma_intermediates_dir := $(intermediates.COMMON)/emma_out
+# emma is hardcoded to use the leaf name of its input for the output file --
+# only the output directory can be changed
+full_classes_emma_jar := $(emma_intermediates_dir)/lib/$(notdir $(full_classes_compiled_jar))
+
+LOCAL_INTERMEDIATE_TARGETS += \
+    $(full_classes_compiled_jar) \
+    $(full_classes_emma_jar)
+
+#######################################
 include $(BUILD_SYSTEM)/base_rules.mk
 #######################################
 
-$(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
+ifeq (true,$(LOCAL_EMMA_INSTRUMENT))
+$(full_classes_emma_jar): PRIVATE_EMMA_COVERAGE_FILE := $(intermediates.COMMON)/coverage.em
+$(full_classes_emma_jar): PRIVATE_EMMA_INTERMEDIATES_DIR := $(emma_intermediates_dir)
+ifdef LOCAL_EMMA_COVERAGE_FILTER
+$(full_classes_emma_jar): PRIVATE_EMMA_COVERAGE_FILTER := $(LOCAL_EMMA_COVERAGE_FILTER)
+else
+# by default, avoid applying emma instrumentation onto emma classes itself,
+# otherwise there will be exceptions thrown
+$(full_classes_emma_jar): PRIVATE_EMMA_COVERAGE_FILTER := *,-emma,-emmarun,-com.vladium.*
+endif
+# this rule will generate both $(PRIVATE_EMMA_COVERAGE_FILE) and
+# $(full_classes_emma_jar)
+$(full_classes_emma_jar) : $(full_classes_compiled_jar) | $(EMMA_JAR)
+	$(transform-classes.jar-to-emma)
 
-java_alternative_checked_module :=
+$(LOCAL_BUILT_MODULE) : $(full_classes_emma_jar)
+	@echo Copying: $@
+	$(hide) $(ACP) -fp $< $@
+
+else # LOCAL_EMMA_INSTRUMENT
+# Directly build into LOCAL_BUILT_MODULE.
+full_classes_compiled_jar := $(LOCAL_BUILT_MODULE)
+endif # LOCAL_EMMA_INSTRUMENT
+
+$(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
 
 # 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))
 
-$(LOCAL_BUILT_MODULE): PRIVATE_JAVA_LAYERS_FILE := $(layers_file)
-$(LOCAL_BUILT_MODULE): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
-$(LOCAL_BUILT_MODULE): PRIVATE_JAR_EXCLUDE_FILES :=
-$(LOCAL_BUILT_MODULE): PRIVATE_JAVA_LAYERS_FILE := $(layers_file)
-$(LOCAL_BUILT_MODULE): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) \
+$(full_classes_compiled_jar): PRIVATE_JAVA_LAYERS_FILE := $(layers_file)
+$(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
+$(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES :=
+$(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES :=
+$(full_classes_compiled_jar): PRIVATE_RMTYPEDEFS :=
+$(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) \
 		$(jar_manifest_file) $(proto_java_sources_file_stamp) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-host-java-to-package)
diff --git a/core/java.mk b/core/java.mk
index 8863ac2..824ae6a 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -72,10 +72,10 @@
 # Choose leaf name for the compiled jar file.
 ifeq ($(LOCAL_EMMA_INSTRUMENT),true)
 full_classes_compiled_jar_leaf := classes-no-debug-var.jar
-built_dex_intermediate_leaf := classes-no-local.dex
+built_dex_intermediate_leaf := no-local
 else
 full_classes_compiled_jar_leaf := classes-full-debug.jar
-built_dex_intermediate_leaf := classes-with-local.dex
+built_dex_intermediate_leaf := with-local
 endif
 
 ifeq ($(LOCAL_PROGUARD_ENABLED),disabled)
@@ -96,7 +96,7 @@
 # only the output directory can be changed
 full_classes_emma_jar := $(emma_intermediates_dir)/lib/$(jarjar_leaf)
 full_classes_proguard_jar := $(intermediates.COMMON)/$(proguard_jar_leaf)
-built_dex_intermediate := $(intermediates.COMMON)/$(built_dex_intermediate_leaf)
+built_dex_intermediate := $(intermediates.COMMON)/$(built_dex_intermediate_leaf)/classes.dex
 full_classes_stubs_jar := $(intermediates.COMMON)/stubs.jar
 
 ifeq ($(LOCAL_MODULE_CLASS)$(LOCAL_SRC_FILES)$(LOCAL_STATIC_JAVA_LIBRARIES)$(LOCAL_SOURCE_FILES_ALL_GENERATED),APPS)
@@ -321,6 +321,10 @@
 $(full_classes_compiled_jar): PRIVATE_JAVA_LAYERS_FILE := $(layers_file)
 $(full_classes_compiled_jar): PRIVATE_WARNINGS_ENABLE := $(LOCAL_WARNINGS_ENABLE)
 
+ifdef LOCAL_RMTYPEDEFS
+$(full_classes_compiled_jar): | $(RMTYPEDEFS)
+endif
+
 # 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,
@@ -328,6 +332,7 @@
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES := $(LOCAL_JAR_EXCLUDE_FILES)
 $(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES := $(LOCAL_JAR_PACKAGES)
+$(full_classes_compiled_jar): PRIVATE_RMTYPEDEFS := $(LOCAL_RMTYPEDEFS)
 $(full_classes_compiled_jar): PRIVATE_DONT_DELETE_JAR_META_INF := $(LOCAL_DONT_DELETE_JAR_META_INF)
 $(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) \
         $(jar_manifest_file) $(layers_file) $(RenderScript_file_stamp) \
@@ -470,7 +475,9 @@
 	$(transform-classes.jar-to-dex)
 $(built_dex): $(built_dex_intermediate) | $(ACP)
 	@echo Copying: $@
-	$(hide) $(ACP) -fp $< $@
+	$(hide) mkdir -p $(dir $@)
+	$(hide) rm -f $(dir $@)/classes*.dex
+	$(hide) $(ACP) -fp $(dir $<)/classes*.dex $(dir $@)
 ifneq ($(GENERATE_DEX_DEBUG),)
 	$(install-dex-debug)
 endif
diff --git a/core/main.mk b/core/main.mk
index f6ab3ff..ca10610 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -151,20 +151,22 @@
 endif
 endif
 
+java_version_str := $(shell java -version 2>&1)
+javac_version_str := $(shell javac -version 2>&1)
+
+# Check for the current jdk
 ifeq ($(requires_openjdk), true)
-ifeq ($(shell java -version 2>&1 | grep -i openjdk),)
+# The user asked for java7 openjdk, so check that the host
+# java version is really openjdk
+ifeq ($(shell echo '$(java_version_str)' | grep -i openjdk),)
 $(info ************************************************************)
-$(info You are attempting to build with an unsupported JDK.)
-$(info $(space))
-$(info This build requires OpenJDK, but you are using:)
-$(info $(shell java -version 2>&1 | head -n 2).)
-$(info Please follow the machine setup instructions at)
-$(info $(space)$(space)$(space)$(space)https://source.android.com/source/download.html)
+$(info You asked for an OpenJDK 7 build but your version is)
+$(info $(java_version_str).)
 $(info ************************************************************)
 $(error stop)
 endif # java version is not OpenJdk
 else # if requires_openjdk
-ifneq ($(shell java -version 2>&1 | grep -i openjdk),)
+ifneq ($(shell echo '$(java_version_str)' | grep -i openjdk),)
 $(info ************************************************************)
 $(info You are attempting to build with an unsupported JDK.)
 $(info $(space))
@@ -180,12 +182,14 @@
 # EXPERIMENTAL_USE_JAVA7 is set, 1.6 otherwise.
 ifneq ($(EXPERIMENTAL_USE_JAVA7),)
 required_version := "1.7.x"
-java_version := $(shell java -version 2>&1 | head -n 1 | grep '^java .*[ "]1\.7[\. "$$]')
-javac_version := $(shell javac -version 2>&1 | head -n 1 | grep '[ "]1\.7[\. "$$]')
+required_javac_version := "1.7"
+java_version := $(shell echo '$(java_version_str)' | grep '^java .*[ "]1\.7[\. "$$]')
+javac_version := $(shell echo '$(javac_version_str)' | grep '[ "]1\.7[\. "$$]')
 else # if EXPERIMENTAL_USE_JAVA7
 required_version := "1.6.x"
-java_version := $(shell java -version 2>&1 | head -n 1 | grep '^java .*[ "]1\.6[\. "$$]')
-javac_version := $(shell javac -version 2>&1 | head -n 1 | grep '[ "]1\.6[\. "$$]')
+required_javac_version := "1.6"
+java_version := $(shell echo '$(java_version_str)' | grep '^java .*[ "]1\.6[\. "$$]')
+javac_version := $(shell echo '$(javac_version_str)' | head -n 1 | grep '[ "]1\.6[\. "$$]')
 endif # if EXPERIMENTAL_USE_JAVA7
 
 ifeq ($(strip $(java_version)),)
@@ -193,7 +197,7 @@
 $(info You are attempting to build with the incorrect version)
 $(info of java.)
 $(info $(space))
-$(info Your version is: $(shell java -version 2>&1 | head -n 1).)
+$(info Your version is: $(java_version_str).)
 $(info The required version is: $(required_version))
 $(info $(space))
 $(info Please follow the machine setup instructions at)
@@ -208,8 +212,8 @@
 $(info You are attempting to build with the incorrect version)
 $(info of javac.)
 $(info $(space))
-$(info Your version is: $(shell javac -version 2>&1 | head -n 1).)
-$(info The required version is: $(required_java_version))
+$(info Your version is: $(javac_version_str).)
+$(info The required version is: $(required_javac_version))
 $(info $(space))
 $(info Please follow the machine setup instructions at)
 $(info $(space)$(space)$(space)$(space)https://source.android.com/source/download.html)
@@ -217,6 +221,7 @@
 $(error stop)
 endif
 
+
 ifndef BUILD_EMULATOR
 ifeq (darwin,$(HOST_OS))
 GCC_REALPATH = $(realpath $(shell which $(HOST_CC)))
@@ -956,6 +961,7 @@
   $(foreach f,$(INSTALLED_RADIOIMAGE_TARGET), \
     $(call dist-for-goals, droidcore, $(f)))
 
+  ifneq ($(ANDROID_BUILD_EMBEDDED),true)
   ifneq ($(TARGET_BUILD_PDK),true)
     $(call dist-for-goals, droidcore, \
       $(APPS_ZIP) \
@@ -963,6 +969,7 @@
       $(PACKAGE_STATS_FILE) \
     )
   endif
+  endif
 
   ifeq ($(EMMA_INSTRUMENT),true)
     $(EMMA_META_ZIP) : $(INSTALLED_SYSTEMIMAGE)
diff --git a/core/pathmap.mk b/core/pathmap.mk
index b619d0f..8e441c4 100644
--- a/core/pathmap.mk
+++ b/core/pathmap.mk
@@ -114,15 +114,24 @@
         v13
 
 #
+# A list of all source roots under frameworks/support.
+#
+FRAMEWORKS_MULTIDEX_SUBDIRS := \
+        multidex \
+        multidex/instrumentation
+
+#
 # A version of FRAMEWORKS_SUPPORT_SUBDIRS that is expanded to full paths from
 # the root of the tree.
 #
 FRAMEWORKS_SUPPORT_JAVA_SRC_DIRS := \
-	$(addprefix frameworks/support/,$(FRAMEWORKS_SUPPORT_SUBDIRS))
+	$(addprefix frameworks/support/,$(FRAMEWORKS_SUPPORT_SUBDIRS)) \
+        $(addprefix frameworks/,$(FRAMEWORKS_MULTIDEX_SUBDIRS))
 
 #
 # A list of support library modules.
 #
 FRAMEWORKS_SUPPORT_JAVA_LIBRARIES := \
-    $(foreach dir,$(FRAMEWORKS_SUPPORT_SUBDIRS),android-support-$(subst /,-,$(dir)))
+    $(foreach dir,$(FRAMEWORKS_SUPPORT_SUBDIRS),android-support-$(subst /,-,$(dir))) \
+    $(foreach dir,$(FRAMEWORKS_MULTIDEX_SUBDIRS),android-support-$(subst /,-,$(dir)))
 
diff --git a/core/product.mk b/core/product.mk
index 3b6b27e..eb4771c 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -100,6 +100,9 @@
     PRODUCT_RUNTIMES \
     PRODUCT_BOOT_JARS \
     PRODUCT_DEX_PREOPT_IMAGE_IN_DATA \
+    PRODUCT_SUPPORTS_VERITY \
+    PRODUCT_VERITY_PARTITION \
+    PRODUCT_VERITY_SIGNING_KEY
 
 define dump-product
 $(info ==== $(1) ====)\
diff --git a/core/product_config.mk b/core/product_config.mk
index 61bdfb4..171c394 100644
--- a/core/product_config.mk
+++ b/core/product_config.mk
@@ -319,8 +319,10 @@
 # Everyone gets nodpi assets which are density-independent.
 PRODUCT_AAPT_CONFIG += nodpi
 
+# Keep a copy of the space-separated config
+PRODUCT_AAPT_CONFIG_SP := $(PRODUCT_AAPT_CONFIG)
+
 # Convert spaces to commas.
-comma := ,
 PRODUCT_AAPT_CONFIG := \
     $(subst $(space),$(comma),$(strip $(PRODUCT_AAPT_CONFIG)))
 PRODUCT_AAPT_PREF_CONFIG := \
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index 4929abb..eedbfd2 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 := KKWT
+  PLATFORM_VERSION := L
 endif
 
 ifeq "" "$(PLATFORM_SDK_VERSION)"
diff --git a/target/product/AndroidProducts.mk b/target/product/AndroidProducts.mk
index fc407d3..265f244 100644
--- a/target/product/AndroidProducts.mk
+++ b/target/product/AndroidProducts.mk
@@ -62,6 +62,5 @@
     $(LOCAL_DIR)/vbox_x86.mk \
     $(LOCAL_DIR)/sdk.mk \
     $(LOCAL_DIR)/sdk_x86.mk \
-    $(LOCAL_DIR)/sdk_mips.mk \
-    $(LOCAL_DIR)/large_emu_hw.mk
+    $(LOCAL_DIR)/sdk_mips.mk
 endif
diff --git a/target/product/base.mk b/target/product/base.mk
index 68e3ff3..657d88c 100644
--- a/target/product/base.mk
+++ b/target/product/base.mk
@@ -34,6 +34,7 @@
     framework2 \
     fsck_msdos \
     ime \
+    inputflinger \
     javax.obex \
     libandroid \
     libandroid_runtime \
@@ -47,6 +48,7 @@
     libeffectproxy \
     libeffects \
     libinput \
+    libinputflinger \
     libiprouteutil \
     libjni_latinime \
     libjnigraphics \
@@ -78,6 +80,7 @@
     libutils \
     libvisualizer \
     libvorbisidec \
+    libwifi-service \
     media \
     media_cmd \
     mediaserver \
diff --git a/target/product/core.mk b/target/product/core.mk
index c5ef2aa..71d2d6f 100644
--- a/target/product/core.mk
+++ b/target/product/core.mk
@@ -22,15 +22,31 @@
 PRODUCT_PACKAGES += \
     BasicDreams \
     Browser \
+    Calculator \
+    Calendar \
+    CalendarProvider \
+    CertInstaller \
     Contacts \
+    DeskClock \
     DocumentsUI \
     DownloadProviderUi \
+    Email \
+    Exchange2 \
     ExternalStorageProvider \
+    FusedLocation \
+    InputDevices \
     KeyChain \
+    Keyguard \
+    LatinIME \
+    Launcher2 \
     PicoTts \
     PacProcessor \
+    PrintSpooler \
     ProxyHandler \
+    QuickSearchBox \
+    Settings \
     SharedStorageBackup \
+    TeleService \
     VpnDialogs
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core_base.mk)
diff --git a/target/product/core_base.mk b/target/product/core_base.mk
index 658e502..7e8615e 100644
--- a/target/product/core_base.mk
+++ b/target/product/core_base.mk
@@ -39,7 +39,6 @@
     libportable \
     libpowermanager \
     libspeexresampler \
-    libstagefright_chromium_http \
     libstagefright_soft_aacdec \
     libstagefright_soft_aacenc \
     libstagefright_soft_amrdec \
@@ -64,7 +63,8 @@
     requestsync \
     screenrecord \
     telephony-common \
-    voip-common
+    voip-common \
+    wifi-service
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core_minimal.mk)
 # Override the PRODUCT_BOOT_JARS set in core_minimal.mk. The order matters.
@@ -83,4 +83,5 @@
     android.policy \
     services \
     apache-xml \
-    webviewchromium
+    webviewchromium \
+    wifi-service
diff --git a/target/product/core_minimal.mk b/target/product/core_minimal.mk
index 1b75909..6a316af 100644
--- a/target/product/core_minimal.mk
+++ b/target/product/core_minimal.mk
@@ -53,10 +53,12 @@
     libfilterfw \
     libsqlite_jni \
     libwilhelm \
+    logd \
     make_ext4fs \
     screencap \
     sensorservice \
-    uiautomator
+    uiautomator \
+    uncrypt
 
 # The order of PRODUCT_BOOT_JARS matters.
 PRODUCT_BOOT_JARS := \
@@ -71,9 +73,10 @@
     android.policy \
     services \
     apache-xml \
-    webviewchromium
+    webviewchromium \
+    wifi-service
 
-PRODUCT_RUNTIMES := runtime_libdvm_default
-PRODUCT_RUNTIMES += runtime_libart
+PRODUCT_RUNTIMES := runtime_libart_default
+PRODUCT_RUNTIMES += runtime_libdvm
 
 $(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
diff --git a/target/product/core_tiny.mk b/target/product/core_tiny.mk
index 02140af..41508d9 100644
--- a/target/product/core_tiny.mk
+++ b/target/product/core_tiny.mk
@@ -20,21 +20,12 @@
     Bluetooth \
     CertInstaller \
     FusedLocation \
-    InputDevices \
-    bluetooth-health \
-    hostapd \
-    wpa_supplicant.conf
+    InputDevices
 
 PRODUCT_PACKAGES += \
-    audio \
     clatd \
     clatd.conf \
-    dhcpcd.conf \
-    network \
-    pand \
-    pppd \
-    sdptool \
-    wpa_supplicant
+    pppd
 
 PRODUCT_PACKAGES += \
     audio.primary.default \
@@ -70,7 +61,8 @@
     make_ext4fs \
     screencap \
     sensorservice \
-    uiautomator
+    uiautomator \
+    uncrypt
 
 # The order matters
 PRODUCT_BOOT_JARS := \
@@ -91,11 +83,10 @@
 PRODUCT_PROPERTY_OVERRIDES += \
     ro.carrier=unknown
 
+$(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
 $(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk)
 
 # Overrides
 PRODUCT_BRAND := tiny
 PRODUCT_DEVICE := tiny
 PRODUCT_NAME := core_tiny
-
-$(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
diff --git a/target/product/generic_no_telephony.mk b/target/product/generic_no_telephony.mk
index 2e0dffc..33a1dde 100644
--- a/target/product/generic_no_telephony.mk
+++ b/target/product/generic_no_telephony.mk
@@ -17,33 +17,15 @@
 # This is a generic phone product that isn't specialized for a specific device.
 # It includes the base Android platform.
 
-PRODUCT_POLICY := android.policy_phone
-
 PRODUCT_PACKAGES := \
-    DeskClock \
     Bluetooth \
-    Calculator \
-    Calendar \
     Camera2 \
-    CertInstaller \
-    Email \
-    Exchange2 \
-    FusedLocation \
     Gallery2 \
-    InputDevices \
-    Keyguard \
-    LatinIME \
-    Launcher2 \
     Music \
     MusicFX \
     OneTimeInitializer \
-    PrintSpooler \
     Provision \
-    QuickSearchBox \
-    Settings \
     SystemUI \
-    TeleService \
-    CalendarProvider \
     WallpaperCropper
 
 PRODUCT_PACKAGES += \
diff --git a/target/product/large_emu_hw.mk b/target/product/large_emu_hw.mk
deleted file mode 100644
index a918c1d..0000000
--- a/target/product/large_emu_hw.mk
+++ /dev/null
@@ -1,52 +0,0 @@
-#
-# Copyright (C) 2007 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 for devices with large display but not specialized
-# for a specific device. It includes the base Android platform.
-
-PRODUCT_POLICY := android.policy_mid
-
-PRODUCT_PACKAGES := \
-    CarHome \
-    DeskClock \
-    Bluetooth \
-    Calculator \
-    Calendar \
-    CertInstaller \
-    Email \
-    Exchange2 \
-    Gallery2 \
-    LatinIME \
-    Launcher2 \
-    Music \
-    Provision \
-    QuickSearchBox \
-    Settings \
-    Sync \
-    Updater \
-    CalendarProvider \
-    SyncProvider \
-    bluetooth-health \
-    hostapd \
-    wpa_supplicant.conf
-
-
-$(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)
-
-# Overrides
-PRODUCT_BRAND := generic
-PRODUCT_DEVICE := generic
-PRODUCT_NAME := large_emu_hw
diff --git a/target/product/sdk.mk b/target/product/sdk.mk
index 5bbdc82..15fa1f7 100644
--- a/target/product/sdk.mk
+++ b/target/product/sdk.mk
@@ -14,56 +14,38 @@
 # limitations under the License.
 #
 
-PRODUCT_POLICY := android.policy_phone
 PRODUCT_PROPERTY_OVERRIDES :=
 
 PRODUCT_PACKAGES := \
-	Calculator \
-	DeskClock \
-	Email \
-	Exchange2 \
-	FusedLocation \
-	Gallery \
-	Keyguard \
-	Music \
-	Mms \
-	OpenWnn \
-	PrintSpooler \
-	libWnnEngDic \
-	libWnnJpnDic \
-	libwnndict \
-	TeleService \
-	PinyinIME \
-	Protips \
-	SoftKeyboard \
-	SystemUI \
-	Launcher2 \
+	ApiDemos \
+	CubeLiveWallpapers \
+	CustomLocale \
 	Development \
 	DevelopmentSettings \
+	Dialer \
+	EmulatorSmokeTests \
 	Fallback \
-	Settings \
-	SdkSetup \
-	CustomLocale \
-	sqlite3 \
-	InputDevices \
-	LatinIME \
-	CertInstaller \
-	LiveWallpapersPicker \
-	ApiDemos \
+	Gallery \
 	GestureBuilder \
-	CubeLiveWallpapers \
-	QuickSearchBox \
-	WidgetPreview \
+	LegacyCamera \
 	librs_jni \
-	ConnectivityTest \
-	GpsLocationTest \
-	CalendarProvider \
-	Calendar \
+	libwnndict \
+	libWnnEngDic \
+	libWnnJpnDic \
+	LiveWallpapersPicker \
+	Mms \
+	Music \
+	OpenWnn \
+	PinyinIME \
+	Protips \
+	rild \
+	SdkSetup \
 	SmokeTest \
 	SmokeTestApp \
-	rild \
-	LegacyCamera \
-	Dialer
+	SoftKeyboard \
+	sqlite3 \
+	SystemUI \
+	WidgetPreview
 
 # Define the host tools and libs that are parts of the SDK.
 -include sdk/build/product_sdk.mk
@@ -100,14 +82,17 @@
 $(call inherit-product-if-exists, frameworks/webview/chromium/chromium.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)
 
-# Overrides
-PRODUCT_BRAND := generic
-PRODUCT_NAME := sdk
-PRODUCT_DEVICE := generic
+# include available languages for TTS in the system image
+-include external/svox/pico/lang/PicoLangDeDeInSystem.mk
+-include external/svox/pico/lang/PicoLangEnGBInSystem.mk
+-include external/svox/pico/lang/PicoLangEnUsInSystem.mk
+-include external/svox/pico/lang/PicoLangEsEsInSystem.mk
+-include external/svox/pico/lang/PicoLangFrFrInSystem.mk
+-include external/svox/pico/lang/PicoLangItItInSystem.mk
 
 # locale + densities. en_US is both first and in alphabetical order to
 # ensure this is the default locale.
-PRODUCT_LOCALES = \
+PRODUCT_LOCALES := \
 	en_US \
 	ldpi \
 	hdpi \
@@ -171,10 +156,7 @@
 	zh_CN \
 	zh_TW
 
-# include available languages for TTS in the system image
--include external/svox/pico/lang/PicoLangDeDeInSystem.mk
--include external/svox/pico/lang/PicoLangEnGBInSystem.mk
--include external/svox/pico/lang/PicoLangEnUsInSystem.mk
--include external/svox/pico/lang/PicoLangEsEsInSystem.mk
--include external/svox/pico/lang/PicoLangFrFrInSystem.mk
--include external/svox/pico/lang/PicoLangItItInSystem.mk
+# Overrides
+PRODUCT_BRAND := generic
+PRODUCT_NAME := sdk
+PRODUCT_DEVICE := generic
diff --git a/target/product/sdk_x86.mk b/target/product/sdk_x86.mk
index 873d0c0..6c5e746 100644
--- a/target/product/sdk_x86.mk
+++ b/target/product/sdk_x86.mk
@@ -19,7 +19,7 @@
 # build quite specifically for the emulator, and might not be
 # entirely appropriate to inherit from for on-device configurations.
 
-include $(SRC_TARGET_DIR)/product/sdk.mk
+$(call inherit-product, $(SRC_TARGET_DIR)/product/sdk.mk)
 
 # Overrides
 PRODUCT_BRAND := generic_x86
diff --git a/target/product/security/Android.mk b/target/product/security/Android.mk
new file mode 100644
index 0000000..5a40397
--- /dev/null
+++ b/target/product/security/Android.mk
@@ -0,0 +1,12 @@
+LOCAL_PATH:= $(call my-dir)
+
+#######################################
+# verity_key
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := verity_key
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT)
+
+include $(BUILD_PREBUILT)
diff --git a/tools/droiddoc/templates-ds/package.cs b/tools/droiddoc/templates-ds/package.cs
index ea3e4f4..d67d5d9 100644
--- a/tools/droiddoc/templates-ds/package.cs
+++ b/tools/droiddoc/templates-ds/package.cs
@@ -45,6 +45,7 @@
   <?cs /if ?>
 <?cs /def ?>
 
+<?cs call:class_table("Annotations", package.annotations) ?>
 <?cs call:class_table("Interfaces", package.interfaces) ?>
 <?cs call:class_table("Classes", package.classes) ?>
 <?cs call:class_table("Enums", package.enums) ?>
diff --git a/tools/droiddoc/templates-pdk/head_tag.cs b/tools/droiddoc/templates-pdk/head_tag.cs
index 0ecda7b..a61cadb 100644
--- a/tools/droiddoc/templates-pdk/head_tag.cs
+++ b/tools/droiddoc/templates-pdk/head_tag.cs
@@ -27,6 +27,17 @@
 if:resources ?>
 <script src="<?cs var:toroot ?>resources/resources-data.js" type="text/javascript"></script><?cs 
 /if ?>
+<script type="text/javascript">
+  var _gaq = _gaq || [];
+  _gaq.push(['_setAccount', 'UA-10664927-1']);
+  _gaq.push(['_trackPageview']);
+
+  (function() {
+    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+  })();
+</script>
 <noscript>
   <style type="text/css">
     html,body{overflow:auto;}
@@ -37,4 +48,4 @@
     #resize-packages-nav{border-bottom:3px solid #666;}
   </style>
 </noscript>
-</head>
\ No newline at end of file
+</head>
diff --git a/tools/droiddoc/templates-pdk/trailer.cs b/tools/droiddoc/templates-pdk/trailer.cs
index 155ba58..46c7bbc 100644
--- a/tools/droiddoc/templates-pdk/trailer.cs
+++ b/tools/droiddoc/templates-pdk/trailer.cs
@@ -1,11 +1,19 @@
 </div> <!-- end body-content --> <?cs # normally opened by header.cs ?>
-
 <script type="text/javascript">
 init(); /* initialize android-developer-docs.js */
-var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
-document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
 </script>
-<script type="text/javascript">
-var pageTracker = _gat._getTracker("UA-5831155-1");
-pageTracker._trackPageview();
-</script>
\ No newline at end of file
+<!--
+    Copyright 2013 The Android Open Source Project
+
+    Licensed under the Apache License, Version 2.0 (the "License");
+    you may not use this file except in compliance with the License.
+    You may obtain a copy of the License at
+
+        http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
diff --git a/tools/droiddoc/templates-sac/designpage.cs b/tools/droiddoc/templates-sac/designpage.cs
index c714a74..c5f03ff 100644
--- a/tools/droiddoc/templates-sac/designpage.cs
+++ b/tools/droiddoc/templates-sac/designpage.cs
@@ -86,14 +86,5 @@
 
       </div>
     </div>
-
-    <script type="text/javascript">
-    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
-    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
-    </script>
-    <script type="text/javascript">
-    var pageTracker = _gat._getTracker("UA-5831155-1");
-    pageTracker._trackPageview();
-    </script>
   </body>
 </html>
diff --git a/tools/droiddoc/templates-sac/head_tag.cs b/tools/droiddoc/templates-sac/head_tag.cs
index 2d64e4f..9fca488 100644
--- a/tools/droiddoc/templates-sac/head_tag.cs
+++ b/tools/droiddoc/templates-sac/head_tag.cs
@@ -48,7 +48,7 @@
 
 <script type="text/javascript">
   var _gaq = _gaq || [];
-  _gaq.push(['_setAccount', 'UA-5831155-1']);
+  _gaq.push(['_setAccount', 'UA-45455297-1']);
   _gaq.push(['_trackPageview']);
 
   (function() {
@@ -57,4 +57,4 @@
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
   })();
 </script>
-</head>
\ No newline at end of file
+</head>
diff --git a/tools/droiddoc/templates-sac/package.cs b/tools/droiddoc/templates-sac/package.cs
index 99eaff2..abd49f1 100644
--- a/tools/droiddoc/templates-sac/package.cs
+++ b/tools/droiddoc/templates-sac/package.cs
@@ -45,6 +45,7 @@
   <?cs /if ?>
 <?cs /def ?>
 
+<?cs call:class_table("Annotations", package.annotations) ?>
 <?cs call:class_table("Interfaces", package.interfaces) ?>
 <?cs call:class_table("Classes", package.classes) ?>
 <?cs call:class_table("Enums", package.enums) ?>
diff --git a/tools/droiddoc/templates-sdk/assets/css/resourcecards.css b/tools/droiddoc/templates-sdk/assets/css/resourcecards.css
new file mode 100644
index 0000000..1222b04
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/css/resourcecards.css
@@ -0,0 +1,371 @@
+/* content layout */
+.resource-widget.resource-flow-layout {
+  display: inline-block;
+  margin-right: -20px;
+  /* clearfix idiom */ }
+  .resource-widget.resource-flow-layout.col-1 {
+    width: 60px; }
+  .resource-widget.resource-flow-layout.col-2 {
+    width: 120px; }
+  .resource-widget.resource-flow-layout.col-3 {
+    width: 180px; }
+  .resource-widget.resource-flow-layout.col-4 {
+    width: 240px; }
+  .resource-widget.resource-flow-layout.col-5 {
+    width: 300px; }
+  .resource-widget.resource-flow-layout.col-6 {
+    width: 360px; }
+  .resource-widget.resource-flow-layout.col-7 {
+    width: 420px; }
+  .resource-widget.resource-flow-layout.col-8 {
+    width: 480px; }
+  .resource-widget.resource-flow-layout.col-9 {
+    width: 540px; }
+  .resource-widget.resource-flow-layout.col-10 {
+    width: 600px; }
+  .resource-widget.resource-flow-layout.col-11 {
+    width: 660px; }
+  .resource-widget.resource-flow-layout.col-12 {
+    width: 720px; }
+  .resource-widget.resource-flow-layout.col-13 {
+    width: 780px; }
+  .resource-widget.resource-flow-layout.col-14 {
+    width: 840px; }
+  .resource-widget.resource-flow-layout.col-15 {
+    width: 900px; }
+  .resource-widget.resource-flow-layout.col-16 {
+    width: 960px; }
+  .resource-widget.resource-flow-layout:after {
+    content: ".";
+    display: block;
+    height: 0;
+    clear: both;
+    visibility: hidden; }
+  * html .resource-widget.resource-flow-layout {
+    height: 1px; }
+
+.resource-card {
+  /* stuff that applies to all cards */
+  display: -webkit-flex;
+  -webkit-transform: translateZ(0);
+  float: left;
+  position: relative;
+  margin-right: 20px;
+  margin-bottom: 20px;
+  background-color: #fff;
+  border-radius: 2px;
+  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.25);
+  opacity: 0.8;
+  overflow: hidden;
+  transition: 0.4s box-shadow ease, 0.4s opacity ease;
+  /* card templates */
+  /* specific cards and customizations */ }
+  .resource-card .photo {
+    position: relative;
+    background-color: #eee;
+    background-size: cover;
+    background-repeat: no-repeat;
+    background-position: 50% 50%; }
+  .resource-card.nophoto .photo:after {
+    content: '';
+    display: block;
+    position: absolute;
+    left: 20px;
+    top: 20px;
+    right: 20px;
+    bottom: 20px;
+    opacity: 0.2;
+    background-position: center center;
+    background-repeat: no-repeat;
+    background-size: contain; }
+  .resource-card .icon {
+    background-position: center center;
+    background-repeat: no-repeat;
+    background-size: contain;
+    opacity: 0;
+    transition: 0.4s ease; }
+  .resource-card:hover .icon {
+    opacity: 0.2; }
+  .resource-card:hover {
+    opacity: 1;
+    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.5); }
+  .resource-card.resource-card-youtube.nophoto .photo:after, .resource-card.resource-card-youtube .icon {
+    background-image: url(../images/card_video.png); }
+  .resource-card.resource-card-samples.nophoto .photo:after, .resource-card.resource-card-samples .icon {
+    background-image: url(../images/card_sample.png); }
+  .resource-card.resource-card-blog.nophoto .photo:after, .resource-card.resource-card-blog .icon {
+    background-image: url(../images/card_post.png); }
+  .resource-card.resource-card-training.nophoto .photo:after, .resource-card.resource-card-training .icon {
+    background-image: url(../images/card_training.png); }
+  .resource-card .resource-card-text {
+    color: #333333; }
+  .resource-card .title {
+    /*font-weight: 700;*/
+    font-family: 'Roboto Condensed'; }
+  .resource-card .subtitle {
+    font-family: 'Roboto Condensed';
+    text-transform: uppercase;
+    opacity: 0.3; }
+  .resource-card .abstract {
+    font-weight: 300;
+    font-family: 'Roboto'; }
+  .resource-card.resource-card-12x7 {
+    width: 700px;
+    height: 400px;
+    -webkit-flex-direction: column; }
+    .resource-card.resource-card-12x7 .photo {
+      -webkit-flex: 1 1 auto;
+      border-bottom: 1px solid #ddd; }
+    .resource-card.resource-card-12x7 .resource-card-text {
+      margin: 20px;
+      padding-right: 88px; }
+    .resource-card.resource-card-12x7 .icon {
+      position: absolute;
+      right: 20px;
+      bottom: 20px;
+      width: 48px;
+      height: 48px; }
+    .resource-card.resource-card-12x7 .title {
+      font-size: 36px;
+      line-height: 35px;
+      max-height: 70px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical; }
+    .resource-card.resource-card-12x7 .subtitle {
+      font-size: 18px;
+      line-height: 20px;
+      max-height: 20px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 1;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      margin-top: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-12x7:hover .subtitle {
+      margin-top: 10px;
+      max-height: 20px; }
+    .resource-card.resource-card-12x7 .abstract {
+      font-size: 18px;
+      margin-top: 0;
+      line-height: 25px;
+      max-height: 75px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 3;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-12x7:hover .abstract {
+      margin-top: 20px;
+      max-height: 75px; }
+  .resource-card.resource-card-8x6 {
+    width: 460px;
+    height: 340px;
+    -webkit-flex-direction: column; }
+    .resource-card.resource-card-8x6 .photo {
+      -webkit-flex: 1 1 auto;
+      border-bottom: 1px solid #ddd; }
+    .resource-card.resource-card-8x6 .resource-card-text {
+      margin: 20px;
+      padding-right: 88px; }
+    .resource-card.resource-card-8x6 .icon {
+      position: absolute;
+      right: 20px;
+      bottom: 20px;
+      width: 48px;
+      height: 48px; }
+    .resource-card.resource-card-8x6 .title {
+      font-size: 36px;
+      line-height: 35px;
+      max-height: 70px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical; }
+    .resource-card.resource-card-8x6 .subtitle {
+      font-size: 18px;
+      line-height: 20px;
+      max-height: 20px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 1;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      margin-top: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-8x6:hover .subtitle {
+      margin-top: 10px;
+      max-height: 20px; }
+    .resource-card.resource-card-8x6 .abstract {
+      font-size: 18px;
+      margin-top: 0;
+      line-height: 25px;
+      max-height: 75px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 3;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-8x6:hover .abstract {
+      margin-top: 20px;
+      max-height: 75px; }
+    .resource-card.resource-card-8x6 .icon {
+      width: 32px;
+      height: 32px; }
+    .resource-card.resource-card-8x6 .title {
+      font-size: 24px;
+      line-height: 25px;
+      max-height: 50px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical; }
+    .resource-card.resource-card-8x6 .abstract {
+      font-size: 16px;
+      margin-top: 10px;
+      line-height: 20px;
+      max-height: 60px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 3;
+      -webkit-box-orient: vertical; }
+    .resource-card.resource-card-8x6 .subtitle {
+      font-size: 16px;
+      line-height: 20px;
+      max-height: 20px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 1;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      margin-top: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-8x6:hover .subtitle {
+      margin-top: 10px;
+      max-height: 20px; }
+    .resource-card.resource-card-8x6 .abstract {
+      font-size: 16px;
+      margin-top: 0;
+      line-height: 20px;
+      max-height: 60px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 3;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-8x6:hover .abstract {
+      margin-top: 10px;
+      max-height: 60px; }
+  .resource-card.resource-card-6x4 {
+    width: 340px;
+    height: 220px;
+    -webkit-flex-direction: column; }
+    .resource-card.resource-card-6x4 .photo {
+      -webkit-flex: 1 1 auto;
+      border-bottom: 1px solid #ddd; }
+    .resource-card.resource-card-6x4 .resource-card-text {
+      margin: 10px;
+      padding-right: 26px; }
+    .resource-card.resource-card-6x4 .icon {
+      position: absolute;
+      right: 10px;
+      bottom: 10px;
+      width: 16px;
+      height: 16px; }
+    .resource-card.resource-card-6x4 .title {
+      font-size: 16px;
+      line-height: 20px;
+      max-height: 40px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical; }
+    .resource-card.resource-card-6x4 .subtitle {
+      font-size: 13px;
+      line-height: 15px;
+      max-height: 30px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      margin-top: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-6x4:hover .subtitle {
+      max-height: 30px; }
+    .resource-card.resource-card-6x4 .abstract {
+      display: none; }
+    .resource-card.resource-card-6x4 .abstract {
+      font-size: 13px;
+      margin-top: 0;
+      line-height: 15px;
+      max-height: 30px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      display: block;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-6x4:hover .abstract {
+      margin-top: 10px;
+      max-height: 30px; }
+  .resource-card.resource-card-4x3 {
+    width: 220px;
+    height: 160px;
+    -webkit-flex-direction: column; }
+    .resource-card.resource-card-4x3 .photo {
+      -webkit-flex: 1 1 auto;
+      border-bottom: 1px solid #ddd; }
+    .resource-card.resource-card-4x3 .resource-card-text {
+      margin: 10px;
+      padding-right: 26px; }
+    .resource-card.resource-card-4x3 .icon {
+      position: absolute;
+      right: 10px;
+      bottom: 10px;
+      width: 16px;
+      height: 16px; }
+    .resource-card.resource-card-4x3 .title {
+      font-size: 16px;
+      line-height: 20px;
+      max-height: 40px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical; }
+    .resource-card.resource-card-4x3 .subtitle {
+      font-size: 13px;
+      line-height: 15px;
+      max-height: 30px;
+      text-overflow: ellipsis;
+      display: -webkit-box;
+      overflow: hidden;
+      -webkit-line-clamp: 2;
+      -webkit-box-orient: vertical;
+      max-height: 0;
+      margin-top: 0;
+      transition: 0.4s ease; }
+    .resource-card.resource-card-4x3:hover .subtitle {
+      max-height: 30px; }
+    .resource-card.resource-card-4x3 .abstract {
+      display: none; }
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_post.png b/tools/droiddoc/templates-sdk/assets/images/card_post.png
new file mode 100644
index 0000000..e061ee9
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/card_post.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_sample.png b/tools/droiddoc/templates-sdk/assets/images/card_sample.png
new file mode 100644
index 0000000..3dc36e0
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/card_sample.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_training.png b/tools/droiddoc/templates-sdk/assets/images/card_training.png
new file mode 100644
index 0000000..5bb7c81
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/card_training.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/card_video.png b/tools/droiddoc/templates-sdk/assets/images/card_video.png
new file mode 100644
index 0000000..807c0af
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/card_video.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/js/jd_tag_helpers.js b/tools/droiddoc/templates-sdk/assets/js/jd_tag_helpers.js
new file mode 100644
index 0000000..d179cbc
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/js/jd_tag_helpers.js
@@ -0,0 +1,106 @@
+function mergeArrays() {
+  var arr = arguments[0] || [];
+  for (var i = 1; i < arguments.length; i++) {
+    arr = arr.concat(arguments[i]);
+  }
+  return arr;
+}
+
+var ALL_RESOURCES = mergeArrays(
+  DESIGN_RESOURCES,
+  DISTRIBUTE_RESOURCES,
+  GOOGLE_RESOURCES,
+  GUIDE_RESOURCES,
+  SAMPLES_RESOURCES,
+  TOOLS_RESOURCES,
+  TRAINING_RESOURCES,
+  YOUTUBE_RESOURCES,
+  BLOGGER_RESOURCES
+);
+
+for (var i = 0; i < ALL_RESOURCES.length; i++) {
+  ALL_RESOURCES[i].index = i;
+}
+
+function mergeMaps() {
+  var allRes = {};
+  var offset = 0;
+
+  for (var i = 0; i < arguments.length; i++) {
+    var r = arguments[i];
+    for (var tag in r.map) {
+      allRes[tag] = allRes[tag] || [];
+      allRes[tag] = allRes[tag].concat(r.map[tag].map(function(i){ return ALL_RESOURCES[i + offset]; }));
+    }
+    offset += r.arr.length;
+  }
+
+  return allRes;
+}
+
+function setFromArray(arr) {
+  arr = arr || [];
+  var set = {};
+  for (var i = 0; i < arr.length; i++) {
+    set[arr[i]] = true;
+  }
+  return set;
+}
+
+function buildResourceLookupMap(resourceDict) {
+  var map = {};
+  for (var key in resourceDict) {
+    var dictForKey = {};
+    var srcArr = resourceDict[key];
+    for (var i = 0; i < srcArr.length; i++) {
+      dictForKey[srcArr[i].index] = true;
+    }
+    map[key] = dictForKey;
+  }
+  return map;
+}
+
+// Type lookups
+
+var ALL_RESOURCES_BY_TYPE = {
+  'design': DESIGN_RESOURCES,
+  'distribute': DISTRIBUTE_RESOURCES,
+  'google': GOOGLE_RESOURCES,
+  'guide': GUIDE_RESOURCES,
+  'samples': SAMPLES_RESOURCES,
+  'tools': TOOLS_RESOURCES,
+  'training': TRAINING_RESOURCES,
+  'youtube': YOUTUBE_RESOURCES,
+  'blog': BLOGGER_RESOURCES
+};
+var IS_RESOURCE_OF_TYPE = buildResourceLookupMap(ALL_RESOURCES_BY_TYPE);
+
+// Tag lookups
+
+var ALL_RESOURCES_BY_TAG = mergeMaps(
+  {map:DESIGN_BY_TAG,arr:DESIGN_RESOURCES},
+  {map:DISTRIBUTE_BY_TAG,arr:DISTRIBUTE_RESOURCES},
+  {map:GOOGLE_BY_TAG,arr:GOOGLE_RESOURCES},
+  {map:GUIDE_BY_TAG,arr:GUIDE_RESOURCES},
+  {map:SAMPLES_BY_TAG,arr:SAMPLES_RESOURCES},
+  {map:TOOLS_BY_TAG,arr:TOOLS_RESOURCES},
+  {map:TRAINING_BY_TAG,arr:TRAINING_RESOURCES},
+  {map:YOUTUBE_BY_TAG,arr:YOUTUBE_RESOURCES},
+  {map:BLOGGER_BY_TAG,arr:BLOGGER_RESOURCES}
+);
+var IS_RESOURCE_TAGGED = buildResourceLookupMap(ALL_RESOURCES_BY_TAG);
+
+// Language lookups
+
+var ALL_RESOURCES_BY_LANG = {};
+for (var i = 0; i < ALL_RESOURCES.length; i++) {
+  var res = ALL_RESOURCES[i];
+  var lang = res.lang;
+  if (!lang) {
+    continue;
+  }
+
+  ALL_RESOURCES_BY_LANG[lang] = ALL_RESOURCES_BY_LANG[lang] || [];
+  ALL_RESOURCES_BY_LANG[lang].push(res);
+}
+var IS_RESOURCE_IN_LANG = buildResourceLookupMap(ALL_RESOURCES_BY_LANG);
\ No newline at end of file
diff --git a/tools/droiddoc/templates-sdk/assets/js/resourcecards.js b/tools/droiddoc/templates-sdk/assets/js/resourcecards.js
new file mode 100644
index 0000000..fbba201
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/js/resourcecards.js
@@ -0,0 +1,244 @@
+// Requires jd_tag_helpers.js and the data JS to be loaded.
+
+$(document).ready(function() {
+  $('.resource-widget').each(function() {
+    initResourceWidget(this);
+  });
+});
+
+
+function initResourceWidget(widget) {
+  var $widget = $(widget);
+  var isFlow, isCarousel;
+  isFlow = $widget.hasClass('resource-flow-layout');
+  if (!isFlow) {
+    isCarousel = $widget.hasClass('resource-carousel-layout');
+  }
+
+  // find size of widget by pulling out its class name
+  var sizeCols = 1;
+  var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
+  if (m) {
+    sizeCols = parseInt(m[1], 10);
+  }
+
+  var opts = {
+    source: $widget.data('source'),
+    cardSizes: ($widget.data('cardsizes') || '').split(','),
+    maxResults: parseInt($widget.data('maxresults') || '100'),
+    itemsPerPage: $widget.data('itemsperpage'),
+    sortOrder: $widget.data('sortorder'),
+    query: $widget.data('query'),
+    collectionId: $widget.data('collectionid'),
+    sizeCols: sizeCols
+  };
+
+  // run the search for the set of resources to show
+  var resources = buildResourceList(opts);
+
+  if (isFlow) {
+    drawResourcesFlowWidget($widget, opts, resources);
+  }
+}
+
+
+function drawResourcesFlowWidget($widget, opts, resources) {
+  $widget.empty();
+  var cardSizes = opts.cardSizes || ['4x3'];
+
+  for (var i = 0; i < resources.length; i++) {
+    var resource = resources[i];
+
+    var cardSize = i >= cardSizes.length ? cardSizes[cardSizes.length - 1] : cardSizes[i];
+    cardSize = cardSize.replace(/^\s+|\s+$/,'');
+
+    var $card = $('<a>')
+        .addClass('resource-card resource-card-' + cardSize + ' resource-card-' + resource.type)
+        .attr('href', resource.url);
+
+    $('<img>')
+        .addClass('photo')
+        .attr('src', resource.image || '')
+        .appendTo($card);
+
+    var subtitle = resource.type;
+    if (resource.timestamp) {
+      var d = new Date(resource.timestamp);
+      // TODO: localize, humanize
+      subtitle = (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear() + ' on ' + subtitle;
+    }
+
+    $('<div>')
+        .addClass('resource-card-text')
+        .append($('<div>').addClass('icon'))
+        .append($('<div>').addClass('title').text(resource.title))
+        .append($('<div>').addClass('subtitle').text(subtitle))
+        .append($('<div>').addClass('abstract').text(resource.summary))
+        .appendTo($card);
+
+    $card.appendTo($widget);
+  }
+
+  $widget.find('.resource-card .photo').each(function() {
+    var src = $(this).attr('src');
+    if (!src) {
+      $(this).parents('.resource-card').addClass('nophoto');
+      $(this).replaceWith($('<div>')
+          .addClass('photo'));
+    } else {
+      $(this).replaceWith($('<div>')
+          .addClass('photo')
+          .css('background-image', 'url(' + $(this).attr('src') + ')'));
+    }
+  });
+}
+
+
+function buildResourceList(opts) {
+  var maxResults = opts.maxResults || 100;
+
+  switch (opts.source) {
+    case 'query':
+      var query = opts.query || '';
+      var expressions = parseResourceQuery(query);
+      var alreadyAddedResources = {};
+      var allResources = [];
+      for (var i = 0; i < expressions.length; i++) {
+        var clauses = expressions[i];
+
+        // build initial set of resources from first clause
+        var firstClause = clauses[0];
+        var resources = [];
+        switch (firstClause.attr) {
+          case 'type':
+            resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
+            break;
+          case 'lang':
+            resources = ALL_RESOURCES_BY_LANG[firstClause.value];
+            break;
+          case 'tag':
+            resources = ALL_RESOURCES_BY_TAG[firstClause.value];
+            break;
+        }
+        resources = resources || [];
+
+        // use additional clauses to filter corpus
+        if (clauses.length > 1) {
+          var otherClauses = clauses.slice(1);
+          resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
+        }
+
+        // filter out resources already added
+        if (i > 1) {
+          resources = resources.filter(getResourceNotAlreadyAddedFilter(alreadyAddedResources));
+        }
+
+        allResources = allResources.concat(resources);
+        if (allResources.length > maxResults) {
+          break;
+        }
+      }
+      if (opts.sortOrder) {
+        var attr = opts.sortOrder;
+        var desc = attr.charAt(0) == '-';
+        if (desc) {
+          attr = attr.substring(1);
+        }
+        allResources = allResources.sort(function(x,y) {
+          return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
+        });
+      }
+      return allResources.slice(0, maxResults);
+
+    case 'related':
+      // TODO
+      break;
+
+    case 'collection':
+      // TODO
+      break;
+  }
+}
+
+
+function getResourceNotAlreadyAddedFilter(addedResources) {
+  return function(x) {
+    return !!addedResources[x];
+  };
+}
+
+
+function getResourceMatchesClausesFilter(clauses) {
+  return function(x) {
+    return doesResourceMatchClauses(x, clauses);
+  };
+}
+
+
+function doesResourceMatchClauses(resource, clauses) {
+  for (var i = 0; i < clauses.length; i++) {
+    var map;
+    switch (clauses[i].attr) {
+      case 'type':
+        map = IS_RESOURCE_OF_TYPE[clauses[i].value];
+        break;
+      case 'lang':
+        map = IS_RESOURCE_IN_LANG[clauses[i].value];
+        break;
+      case 'tag':
+        map = IS_RESOURCE_TAGGED[clauses[i].value];
+        break;
+    }
+
+    if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
+      return false;
+    }
+  }
+  return true;
+}
+
+
+function parseResourceQuery(query) {
+  // Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
+  var expressions = [];
+  var expressionStrs = query.split(',') || [];
+  for (var i = 0; i < expressionStrs.length; i++) {
+    var expr = expressionStrs[i] || '';
+
+    // Break expression into clauses (clause e.g. 'tag:foo')
+    var clauses = [];
+    var clauseStrs = expr.split(/(?=[\+\-])/);
+    for (var j = 0; j < clauseStrs.length; j++) {
+      var clauseStr = clauseStrs[j] || '';
+
+      // Get attribute and value from clause (e.g. attribute='tag', value='foo')
+      var parts = clauseStr.split(':');
+      var clause = {};
+
+      clause.attr = parts[0].replace(/\s+/g,'');
+      if (clause.attr) {
+        if (clause.attr.charAt(0) == '+') {
+          clause.attr = clause.attr.substring(1);
+        } else if (clause.attr.charAt(0) == '-') {
+          clause.negative = true;
+          clause.attr = clause.attr.substring(1);
+        }
+      }
+
+      if (parts.length > 1) {
+        clause.value = parts[1].replace(/\s+/g,'');
+      }
+
+      clauses.push(clause);
+    }
+
+    if (!clauses.length) {
+      continue;
+    }
+
+    expressions.push(clauses);
+  }
+
+  return expressions;
+}
+
diff --git a/tools/droiddoc/templates-sdk/customizations.cs b/tools/droiddoc/templates-sdk/customizations.cs
index ed57f1c..52b7224 100644
--- a/tools/droiddoc/templates-sdk/customizations.cs
+++ b/tools/droiddoc/templates-sdk/customizations.cs
@@ -247,6 +247,7 @@
 <?cs 
             if:subcount(class.package) ?>
             <ul>
+              <?cs call:list("Annotations", class.package.annotations) ?>
               <?cs call:list("Interfaces", class.package.interfaces) ?>
               <?cs call:list("Classes", class.package.classes) ?>
               <?cs call:list("Enums", class.package.enums) ?>
@@ -255,6 +256,7 @@
             </ul><?cs 
             elif:subcount(package) ?>
             <ul>
+              <?cs call:class_link_list("Annotations", package.annotations) ?>
               <?cs call:class_link_list("Interfaces", package.interfaces) ?>
               <?cs call:class_link_list("Classes", package.classes) ?>
               <?cs call:class_link_list("Enums", package.enums) ?>
diff --git a/tools/droiddoc/templates-sdk/head_tag.cs b/tools/droiddoc/templates-sdk/head_tag.cs
index 54de169..2d4664c 100644
--- a/tools/droiddoc/templates-sdk/head_tag.cs
+++ b/tools/droiddoc/templates-sdk/head_tag.cs
@@ -55,6 +55,13 @@
 </script>
 <script src="<?cs var:toroot ?>assets/js/docs.js" type="text/javascript"></script>
 
+<!-- RESOURCES LIBRARY -->
+<script src="<?cs if:android.whichdoc != 'online' ?>http:<?cs /if ?>//androiddevdocs-staging.appspot.com/ytblogger_lists_unified.js" type="text/javascript"></script>
+<script src="<?cs var:toroot ?>jd_lists_unified.js" type="text/javascript"></script>
+<script src="<?cs var:toroot ?>assets/js/jd_tag_helpers.js" type="text/javascript"></script>
+<link href="<?cs var:toroot ?>assets/css/resourcecards.css"  rel="stylesheet" type="text/css" />
+<script src="<?cs var:toroot ?>assets/js/resourcecards.js" type="text/javascript"></script>
+
 <script type="text/javascript">
   var _gaq = _gaq || [];
   _gaq.push(['_setAccount', 'UA-5831155-1']);
diff --git a/tools/droiddoc/templates-sdk/package.cs b/tools/droiddoc/templates-sdk/package.cs
index 99eaff2..abd49f1 100644
--- a/tools/droiddoc/templates-sdk/package.cs
+++ b/tools/droiddoc/templates-sdk/package.cs
@@ -45,6 +45,7 @@
   <?cs /if ?>
 <?cs /def ?>
 
+<?cs call:class_table("Annotations", package.annotations) ?>
 <?cs call:class_table("Interfaces", package.interfaces) ?>
 <?cs call:class_table("Classes", package.classes) ?>
 <?cs call:class_table("Enums", package.enums) ?>
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
index f8f2ada..ffda6cf 100755
--- a/tools/releasetools/build_image.py
+++ b/tools/releasetools/build_image.py
@@ -24,6 +24,8 @@
 import os.path
 import subprocess
 import sys
+import commands
+import shutil
 
 def RunCommand(cmd):
   """ Echo and run the given command
@@ -38,6 +40,170 @@
   p.communicate()
   return p.returncode
 
+def GetVerityTreeSize(partition_size):
+  cmd = "system/extras/verity/build_verity_tree.py -s %d"
+  cmd %= partition_size
+  status, output = commands.getstatusoutput(cmd)
+  if status:
+    print output
+    return False, 0
+  return True, int(output)
+
+def GetVerityMetadataSize(partition_size):
+  cmd = "system/extras/verity/build_verity_metadata.py -s %d"
+  cmd %= partition_size
+  status, output = commands.getstatusoutput(cmd)
+  if status:
+    print output
+    return False, 0
+  return True, int(output)
+
+def AdjustPartitionSizeForVerity(partition_size):
+  """Modifies the provided partition size to account for the verity metadata.
+
+  This information is used to size the created image appropriately.
+  Args:
+    partition_size: the size of the partition to be verified.
+  Returns:
+    The size of the partition adjusted for verity metadata.
+  """
+  success, verity_tree_size = GetVerityTreeSize(partition_size)
+  if not success:
+    return 0;
+  success, verity_metadata_size = GetVerityMetadataSize(partition_size)
+  if not success:
+    return 0
+  return partition_size - verity_tree_size - verity_metadata_size
+
+def BuildVerityTree(unsparse_image_path, verity_image_path, partition_size, prop_dict):
+  cmd = ("system/extras/verity/build_verity_tree.py %s %s %d" %
+            (unsparse_image_path, verity_image_path, partition_size))
+  print cmd
+  status, output = commands.getstatusoutput(cmd)
+  if status:
+    print "Could not build verity tree! Error: %s" % output
+    return False
+  root, salt = output.split()
+  prop_dict["verity_root_hash"] = root
+  prop_dict["verity_salt"] = salt
+  return True
+
+def BuildVerityMetadata(image_size, verity_metadata_path, root_hash, salt,
+                        block_device, signer_path, key):
+  cmd = ("system/extras/verity/build_verity_metadata.py %s %s %s %s %s %s %s" %
+              (image_size,
+              verity_metadata_path,
+              root_hash,
+              salt,
+              block_device,
+              signer_path,
+              key))
+  print cmd
+  status, output = commands.getstatusoutput(cmd)
+  if status:
+    print "Could not build verity metadata! Error: %s" % output
+    return False
+  return True
+
+def Append2Simg(sparse_image_path, unsparse_image_path, error_message):
+  """Appends the unsparse image to the given sparse image.
+
+  Args:
+    sparse_image_path: the path to the (sparse) image
+    unsparse_image_path: the path to the (unsparse) image
+  Returns:
+    True on success, False on failure.
+  """
+  cmd = "append2simg %s %s"
+  cmd %= (sparse_image_path, unsparse_image_path)
+  print cmd
+  status, output = commands.getstatusoutput(cmd)
+  if status:
+    print "%s: %s" % (error_message, output)
+    return False
+  return True
+
+def BuildVerifiedImage(data_image_path, verity_image_path, verity_metadata_path):
+  if not Append2Simg(data_image_path, verity_metadata_path, "Could not append verity metadata!"):
+    return False
+  if not Append2Simg(data_image_path, verity_image_path, "Could not append verity tree!"):
+    return False
+  return True
+
+def UnsparseImage(sparse_image_path, replace=True):
+  img_dir = os.path.dirname(sparse_image_path)
+  unsparse_image_path = "unsparse_" + os.path.basename(sparse_image_path)
+  unsparse_image_path = os.path.join(img_dir, unsparse_image_path)
+  if os.path.exists(unsparse_image_path):
+    if replace:
+      os.unlink(unsparse_image_path)
+    else:
+      return True, unsparse_image_path
+  inflate_command = ["simg2img", sparse_image_path, unsparse_image_path]
+  exit_code = RunCommand(inflate_command)
+  if exit_code != 0:
+    os.remove(unsparse_image_path)
+    return False, None
+  return True, unsparse_image_path
+
+def MakeVerityEnabledImage(out_file, prop_dict):
+  """Creates an image that is verifiable using dm-verity.
+
+  Args:
+    out_file: the location to write the verifiable image at
+    prop_dict: a dictionary of properties required for image creation and verification
+  Returns:
+    True on success, False otherwise.
+  """
+  # get properties
+  image_size = prop_dict["partition_size"]
+  part_size = int(prop_dict["original_partition_size"])
+  block_dev = prop_dict["verity_block_device"]
+  signer_key = prop_dict["verity_key"]
+  signer_path = prop_dict["verity_signer_cmd"]
+
+  # make a tempdir
+  tempdir_name = os.path.join(os.path.dirname(out_file), "verity_images")
+  if os.path.exists(tempdir_name):
+    shutil.rmtree(tempdir_name)
+  os.mkdir(tempdir_name)
+
+  # get partial image paths
+  verity_image_path = os.path.join(tempdir_name, "verity.img")
+  verity_metadata_path = os.path.join(tempdir_name, "verity_metadata.img")
+  success, unsparse_image_path = UnsparseImage(out_file)
+  if not success:
+    shutil.rmtree(tempdir_name)
+    return False
+
+  # build the verity tree and get the root hash and salt
+  if not BuildVerityTree(unsparse_image_path, verity_image_path, part_size, prop_dict):
+    shutil.rmtree(tempdir_name)
+    return False
+
+  # build the metadata blocks
+  root_hash = prop_dict["verity_root_hash"]
+  salt = prop_dict["verity_salt"]
+  if not BuildVerityMetadata(image_size,
+                              verity_metadata_path,
+                              root_hash,
+                              salt,
+                              block_dev,
+                              signer_path,
+                              signer_key):
+    shutil.rmtree(tempdir_name)
+    return False
+
+  # build the full verified image
+  if not BuildVerifiedImage(out_file,
+                            verity_image_path,
+                            verity_metadata_path):
+    shutil.rmtree(tempdir_name)
+    return False
+
+  shutil.rmtree(tempdir_name)
+  return True
+
 def BuildImage(in_dir, prop_dict, out_file):
   """Build an image to out_file from in_dir with property prop_dict.
 
@@ -52,6 +218,16 @@
   build_command = []
   fs_type = prop_dict.get("fs_type", "")
   run_fsck = False
+
+  # adjust the partition size to make room for the hashes if this is to be verified
+  if prop_dict.get("verity") == "true":
+    partition_size = int(prop_dict.get("partition_size"))
+    adjusted_size = AdjustPartitionSizeForVerity(partition_size)
+    if not adjusted_size:
+      return False
+    prop_dict["partition_size"] = str(adjusted_size)
+    prop_dict["original_partition_size"] = str(partition_size)
+
   if fs_type.startswith("ext"):
     build_command = ["mkuserimg.sh"]
     if "extfs_sparse_flag" in prop_dict:
@@ -59,8 +235,9 @@
       run_fsck = True
     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"])
+    build_command.append(prop_dict["partition_size"])
+    if "timestamp" in prop_dict:
+      build_command.extend(["-T", str(prop_dict["timestamp"])])
     if "selinux_fc" in prop_dict:
       build_command.append(prop_dict["selinux_fc"])
   else:
@@ -77,14 +254,14 @@
   if exit_code != 0:
     return False
 
+  # create the verified image if this is to be verified
+  if prop_dict.get("verity") == "true":
+    if not MakeVerityEnabledImage(out_file, prop_dict):
+      return False
+
   if run_fsck and prop_dict.get("skip_fsck") != "true":
-    # Inflate the sparse image
-    unsparse_image = os.path.join(
-        os.path.dirname(out_file), "unsparse_" + os.path.basename(out_file))
-    inflate_command = ["simg2img", out_file, unsparse_image]
-    exit_code = RunCommand(inflate_command)
-    if exit_code != 0:
-      os.remove(unsparse_image)
+    success, unsparse_image = UnsparseImage(out_file, replace=False)
+    if not success:
       return False
 
     # Run e2fsck on the inflated image file
@@ -104,6 +281,10 @@
     mount_point: such as "system", "data" etc.
   """
   d = {}
+  if "build.prop" in glob_dict:
+    bp = glob_dict["build.prop"]
+    if "ro.build.date.utc" in bp:
+      d["timestamp"] = bp["ro.build.date.utc"]
 
   def copy_prop(src_p, dest_p):
     if src_p in glob_dict:
@@ -114,6 +295,10 @@
       "mkyaffs2_extra_flags",
       "selinux_fc",
       "skip_fsck",
+      "verity",
+      "verity_block_device",
+      "verity_key",
+      "verity_signer_cmd"
       )
   for p in common_props:
     copy_prop(p, p)
diff --git a/tools/releasetools/check_target_files_signatures b/tools/releasetools/check_target_files_signatures
index 45d30a6..b2f46c1 100755
--- a/tools/releasetools/check_target_files_signatures
+++ b/tools/releasetools/check_target_files_signatures
@@ -41,8 +41,8 @@
 
 import sys
 
-if sys.hexversion < 0x02040000:
-  print >> sys.stderr, "Python 2.4 or newer is required."
+if sys.hexversion < 0x02070000:
+  print >> sys.stderr, "Python 2.7 or newer is required."
   sys.exit(1)
 
 import os
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index f179717..b7e18fa 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -84,13 +84,25 @@
       pass
 
 
-def LoadInfoDict(zip):
+def LoadInfoDict(input):
   """Read and parse the META/misc_info.txt key/value pairs from the
   input target files and return a dict."""
 
+  def read_helper(fn):
+    if isinstance(input, zipfile.ZipFile):
+      return input.read(fn)
+    else:
+      path = os.path.join(input, *fn.split("/"))
+      try:
+        with open(path) as f:
+          return f.read()
+      except IOError, e:
+        if e.errno == errno.ENOENT:
+          raise KeyError(fn)
+
   d = {}
   try:
-    for line in zip.read("META/misc_info.txt").split("\n"):
+    for line in read_helper("META/misc_info.txt").split("\n"):
       line = line.strip()
       if not line or line.startswith("#"): continue
       k, v = line.split("=", 1)
@@ -105,20 +117,20 @@
 
   if "mkyaffs2_extra_flags" not in d:
     try:
-      d["mkyaffs2_extra_flags"] = zip.read("META/mkyaffs2-extra-flags.txt").strip()
+      d["mkyaffs2_extra_flags"] = read_helper("META/mkyaffs2-extra-flags.txt").strip()
     except KeyError:
       # ok if flags don't exist
       pass
 
   if "recovery_api_version" not in d:
     try:
-      d["recovery_api_version"] = zip.read("META/recovery-api-version.txt").strip()
+      d["recovery_api_version"] = read_helper("META/recovery-api-version.txt").strip()
     except KeyError:
       raise ValueError("can't find recovery API version in input target-files")
 
   if "tool_extensions" not in d:
     try:
-      d["tool_extensions"] = zip.read("META/tool-extensions.txt").strip()
+      d["tool_extensions"] = read_helper("META/tool-extensions.txt").strip()
     except KeyError:
       # ok if extensions don't exist
       pass
@@ -127,7 +139,7 @@
     d["fstab_version"] = "1"
 
   try:
-    data = zip.read("META/imagesizes.txt")
+    data = read_helper("META/imagesizes.txt")
     for line in data.split("\n"):
       if not line: continue
       name, value = line.split(" ", 1)
@@ -152,13 +164,13 @@
   makeint("boot_size")
   makeint("fstab_version")
 
-  d["fstab"] = LoadRecoveryFSTab(zip, d["fstab_version"])
-  d["build.prop"] = LoadBuildProp(zip)
+  d["fstab"] = LoadRecoveryFSTab(read_helper, d["fstab_version"])
+  d["build.prop"] = LoadBuildProp(read_helper)
   return d
 
-def LoadBuildProp(zip):
+def LoadBuildProp(read_helper):
   try:
-    data = zip.read("SYSTEM/build.prop")
+    data = read_helper("SYSTEM/build.prop")
   except KeyError:
     print "Warning: could not find SYSTEM/build.prop in %s" % zip
     data = ""
@@ -171,14 +183,14 @@
     d[name] = value
   return d
 
-def LoadRecoveryFSTab(zip, fstab_version):
+def LoadRecoveryFSTab(read_helper, fstab_version):
   class Partition(object):
     pass
 
   try:
-    data = zip.read("RECOVERY/RAMDISK/etc/recovery.fstab")
+    data = read_helper("RECOVERY/RAMDISK/etc/recovery.fstab")
   except KeyError:
-    print "Warning: could not find RECOVERY/RAMDISK/etc/recovery.fstab in %s." % zip
+    print "Warning: could not find RECOVERY/RAMDISK/etc/recovery.fstab"
     data = ""
 
   if fstab_version == 1:
@@ -342,9 +354,12 @@
   else:
     print "building image from target_files %s..." % (tree_subdir,)
     fs_config = "META/" + tree_subdir.lower() + "_filesystem_config.txt"
-    return File(name, BuildBootableImage(os.path.join(unpack_dir, tree_subdir),
-                                         os.path.join(unpack_dir, fs_config),
-                                         info_dict))
+    data = BuildBootableImage(os.path.join(unpack_dir, tree_subdir),
+                              os.path.join(unpack_dir, fs_config),
+                              info_dict)
+    if data:
+      return File(name, data)
+    return None
 
 
 def UnzipTemp(filename, pattern=None):
@@ -725,11 +740,14 @@
     return result
 
 
-def ZipWriteStr(zip, filename, data, perms=0644):
+def ZipWriteStr(zip, filename, data, perms=0644, compression=None):
   # use a fixed timestamp so the output is repeatable.
   zinfo = zipfile.ZipInfo(filename=filename,
                           date_time=(2009, 1, 1, 0, 0, 0))
-  zinfo.compress_type = zip.compression
+  if compression is None:
+    zinfo.compress_type = zip.compression
+  else:
+    zinfo.compress_type = compression
   zinfo.external_attr = perms << 16
   zip.writestr(zinfo, data)
 
@@ -756,6 +774,7 @@
           if x == ".py":
             f = b
           info = imp.find_module(f, [d])
+        print "loaded device-specific extensions from", path
         self.module = imp.load_module("device_specific", *info)
       except ImportError:
         print "unable to load device-specific module; assuming none"
@@ -834,8 +853,8 @@
     t.flush()
     return t
 
-  def AddToZip(self, z):
-    ZipWriteStr(z, self.name, self.data)
+  def AddToZip(self, z, compression=None):
+    ZipWriteStr(z, self.name, self.data, compression=compression)
 
 DIFF_PROGRAM_BY_EXT = {
     ".gz" : "imgdiff",
@@ -972,3 +991,95 @@
       save = True
   cert = "".join(cert).decode('base64')
   return cert
+
+def XDelta3(source_path, target_path, output_path):
+  diff_program = ["xdelta3", "-0", "-B", str(64<<20), "-e", "-f", "-s"]
+  diff_program.append(source_path)
+  diff_program.append(target_path)
+  diff_program.append(output_path)
+  p = Run(diff_program, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+  p.communicate()
+  assert p.returncode == 0, "Couldn't produce patch"
+
+def XZ(path):
+  compress_program = ["xz", "-zk", "-9", "--check=crc32"]
+  compress_program.append(path)
+  p = Run(compress_program, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+  p.communicate()
+  assert p.returncode == 0, "Couldn't compress patch"
+
+def MakeSystemPatch(source_file, target_file):
+  with tempfile.NamedTemporaryFile() as output_file:
+    XDelta3(source_file.name, target_file.name, output_file.name)
+    XZ(output_file.name)
+    with open(output_file.name + ".xz") as patch_file:
+      patch_data = patch_file.read()
+      os.unlink(patch_file.name)
+      return File("system.img.p", patch_data)
+
+def MakeRecoveryPatch(input_dir, output_sink, recovery_img, boot_img,
+                      info_dict=None):
+  """Generate a binary patch that creates the recovery image starting
+  with the boot image.  (Most of the space in these images is just the
+  kernel, which is identical for the two, so the resulting patch
+  should be efficient.)  Add it to the output zip, along with a shell
+  script that is run from init.rc on first boot to actually do the
+  patching and install the new recovery image.
+
+  recovery_img and boot_img should be File objects for the
+  corresponding images.  info should be the dictionary returned by
+  common.LoadInfoDict() on the input target_files.
+  """
+
+  if info_dict is None:
+    info_dict = OPTIONS.info_dict
+
+  diff_program = ["imgdiff"]
+  path = os.path.join(input_dir, "SYSTEM", "etc", "recovery-resource.dat")
+  if os.path.exists(path):
+    diff_program.append("-b")
+    diff_program.append(path)
+    bonus_args = "-b /system/etc/recovery-resource.dat"
+  else:
+    bonus_args = ""
+
+  d = Difference(recovery_img, boot_img, diff_program=diff_program)
+  _, _, patch = d.ComputePatch()
+  output_sink("recovery-from-boot.p", patch)
+
+  boot_type, boot_device = GetTypeAndDevice("/boot", info_dict)
+  recovery_type, recovery_device = GetTypeAndDevice("/recovery", info_dict)
+
+  sh = """#!/system/bin/sh
+if ! applypatch -c %(recovery_type)s:%(recovery_device)s:%(recovery_size)d:%(recovery_sha1)s; then
+  applypatch %(bonus_args)s %(boot_type)s:%(boot_device)s:%(boot_size)d:%(boot_sha1)s %(recovery_type)s:%(recovery_device)s %(recovery_sha1)s %(recovery_size)d %(boot_sha1)s:/system/recovery-from-boot.p && log -t recovery "Installing new recovery image: succeeded" || log -t recovery "Installing new recovery image: failed"
+else
+  log -t recovery "Recovery image already installed"
+fi
+""" % { 'boot_size': boot_img.size,
+        'boot_sha1': boot_img.sha1,
+        'recovery_size': recovery_img.size,
+        'recovery_sha1': recovery_img.sha1,
+        'boot_type': boot_type,
+        'boot_device': boot_device,
+        'recovery_type': recovery_type,
+        'recovery_device': recovery_device,
+        'bonus_args': bonus_args,
+        }
+
+  # The install script location moved from /system/etc to /system/bin
+  # in the L release.  Parse the init.rc file to find out where the
+  # target-files expects it to be, and put it there.
+  sh_location = "etc/install-recovery.sh"
+  try:
+    with open(os.path.join(input_dir, "BOOT", "RAMDISK", "init.rc")) as f:
+      for line in f:
+        m = re.match("^service flash_recovery /system/(\S+)\s*$", line)
+        if m:
+          sh_location = m.group(1)
+          print "putting script in", sh_location
+          break
+  except (OSError, IOError), e:
+    print "failed to read init.rc: %s" % (e,)
+
+  output_sink(sh_location, sh)
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index 426b713..a5340a0 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -81,6 +81,18 @@
            ) % (" or ".join(fp),)
     self.script.append(cmd)
 
+  def AssertRecoveryFingerprint(self, *fp):
+    """Assert that the current recovery build fingerprint is one of *fp."""
+    if not fp:
+      raise ValueError("must specify some fingerprints")
+    cmd = (
+           ' ||\n    '.join([('getprop("ro.build.fingerprint") == "%s"')
+                        % i for i in fp]) +
+           ' ||\n    abort("Package expects build fingerprint of %s; this '
+           'device has " + getprop("ro.build.fingerprint") + ".");'
+           ) % (" or ".join(fp),)
+    self.script.append(cmd)
+
   def AssertOlderBuild(self, timestamp, timestamp_text):
     """Assert that the build on the device is older (or the same as)
     the given timestamp."""
@@ -296,3 +308,8 @@
       data = open(os.path.join(input_path, "updater")).read()
     common.ZipWriteStr(output_zip, "META-INF/com/google/android/update-binary",
                        data, perms=0755)
+
+  def Syspatch(self, filename, size, target_sha, source_sha, patchfile):
+    """Applies a compressed binary patch to a block device."""
+    call = 'syspatch("%s", "%s", "%s", "%s", "%s");'
+    self.script.append(call % (filename, size, target_sha, source_sha, patchfile))
diff --git a/tools/releasetools/img_from_target_files b/tools/releasetools/img_from_target_files
new file mode 120000
index 0000000..afaf24b
--- /dev/null
+++ b/tools/releasetools/img_from_target_files
@@ -0,0 +1 @@
+img_from_target_files.py
\ No newline at end of file
diff --git a/tools/releasetools/img_from_target_files b/tools/releasetools/img_from_target_files.py
similarity index 89%
rename from tools/releasetools/img_from_target_files
rename to tools/releasetools/img_from_target_files.py
index e894c42..bd11a45 100755
--- a/tools/releasetools/img_from_target_files
+++ b/tools/releasetools/img_from_target_files.py
@@ -31,8 +31,8 @@
 
 import sys
 
-if sys.hexversion < 0x02040000:
-  print >> sys.stderr, "Python 2.4 or newer is required."
+if sys.hexversion < 0x02070000:
+  print >> sys.stderr, "Python 2.7 or newer is required."
   sys.exit(1)
 
 import errno
@@ -53,10 +53,14 @@
 OPTIONS = common.OPTIONS
 
 
-def AddSystem(output_zip):
+def AddSystem(output_zip, sparse=True):
   """Turn the contents of SYSTEM into a system image and store it in
   output_zip."""
+  data = BuildSystem(OPTIONS.input_tmp, OPTIONS.info_dict, sparse=sparse)
+  common.ZipWriteStr(output_zip, "system.img", data)
 
+
+def BuildSystem(input_dir, info_dict, sparse=True):
   print "creating system.img..."
 
   img = tempfile.NamedTemporaryFile()
@@ -65,8 +69,8 @@
   # mkyaffs2image.  It wants "system" but we have a directory named
   # "SYSTEM", so create a symlink.
   try:
-    os.symlink(os.path.join(OPTIONS.input_tmp, "SYSTEM"),
-               os.path.join(OPTIONS.input_tmp, "system"))
+    os.symlink(os.path.join(input_dir, "SYSTEM"),
+               os.path.join(input_dir, "system"))
   except OSError, e:
       # bogus error on my mac version?
       #   File "./build/tools/releasetools/img_from_target_files", line 86, in AddSystem
@@ -75,21 +79,29 @@
     if (e.errno == errno.EEXIST):
       pass
 
-  image_props = build_image.ImagePropFromGlobalDict(OPTIONS.info_dict,
-                                                    "system")
-  fstab = OPTIONS.info_dict["fstab"]
+  image_props = build_image.ImagePropFromGlobalDict(info_dict, "system")
+  fstab = info_dict["fstab"]
   if fstab:
     image_props["fs_type" ] = fstab["/system"].fs_type
-  succ = build_image.BuildImage(os.path.join(OPTIONS.input_tmp, "system"),
+  succ = build_image.BuildImage(os.path.join(input_dir, "system"),
                                 image_props, img.name)
   assert succ, "build system.img image failed"
 
-  img.seek(os.SEEK_SET, 0)
-  data = img.read()
-  img.close()
+  if sparse:
+    img.seek(os.SEEK_SET, 0)
+    data = img.read()
+    img.close()
+  else:
+    success, name = build_image.UnsparseImage(img.name, replace=False)
+    if not success:
+      assert False, "unsparsing system.img failed"
+    try:
+      with open(name) as f:
+        data = f.read()
+    finally:
+      os.unlink(name)
 
-  common.CheckSize(data, "system.img", OPTIONS.info_dict)
-  common.ZipWriteStr(output_zip, "system.img", data)
+  return data
 
 
 def AddVendor(output_zip):
diff --git a/tools/releasetools/make_recovery_patch b/tools/releasetools/make_recovery_patch
new file mode 100755
index 0000000..08d1450
--- /dev/null
+++ b/tools/releasetools/make_recovery_patch
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import sys
+
+if sys.hexversion < 0x02070000:
+  print >> sys.stderr, "Python 2.7 or newer is required."
+  sys.exit(1)
+
+import os
+import common
+
+OPTIONS = common.OPTIONS
+
+def main(argv):
+  # def option_handler(o, a):
+  #   return False
+
+  args = common.ParseOptions(argv, __doc__)
+  input_dir, output_dir = args
+
+  OPTIONS.info_dict = common.LoadInfoDict(input_dir)
+
+  recovery_img = common.GetBootableImage("recovery.img", "recovery.img",
+                                         input_dir, "RECOVERY")
+  boot_img = common.GetBootableImage("boot.img", "boot.img",
+                                     input_dir, "BOOT")
+
+  if not recovery_img or not boot_img:
+    sys.exit(0)
+
+  def output_sink(fn, data):
+    with open(os.path.join(output_dir, "SYSTEM", *fn.split("/")), "wb") as f:
+      f.write(data)
+
+  common.MakeRecoveryPatch(input_dir, output_sink, recovery_img, boot_img)
+
+
+if __name__ == '__main__':
+  main(sys.argv[1:])
diff --git a/tools/releasetools/ota_from_target_files b/tools/releasetools/ota_from_target_files
index 8d3f6ce..1afc640 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -57,12 +57,17 @@
       first, so that any changes made to the system partition are done
       using the new recovery (new kernel, etc.).
 
+  --block
+      Generate a block-based OTA if possible.  Will fall back to a
+      file-based OTA if the target_files is older and doesn't support
+      block-based OTAs.
+
 """
 
 import sys
 
-if sys.hexversion < 0x02040000:
-  print >> sys.stderr, "Python 2.4 or newer is required."
+if sys.hexversion < 0x02070000:
+  print >> sys.stderr, "Python 2.7 or newer is required."
   sys.exit(1)
 
 import copy
@@ -80,7 +85,9 @@
   from sha import sha as sha1
 
 import common
+import img_from_target_files
 import edify_generator
+import build_image
 
 OPTIONS = common.OPTIONS
 OPTIONS.package_key = None
@@ -95,6 +102,7 @@
 OPTIONS.worker_threads = 3
 OPTIONS.two_step = False
 OPTIONS.no_signing = False
+OPTIONS.block_based = False
 
 def MostPopularKey(d, default):
   """Given a dict, return the key corresponding to the largest
@@ -352,58 +360,12 @@
   script.AssertDevice(device)
 
 
-def MakeRecoveryPatch(input_tmp, output_zip, recovery_img, boot_img):
-  """Generate a binary patch that creates the recovery image starting
-  with the boot image.  (Most of the space in these images is just the
-  kernel, which is identical for the two, so the resulting patch
-  should be efficient.)  Add it to the output zip, along with a shell
-  script that is run from init.rc on first boot to actually do the
-  patching and install the new recovery image.
-
-  recovery_img and boot_img should be File objects for the
-  corresponding images.  info should be the dictionary returned by
-  common.LoadInfoDict() on the input target_files.
-
-  Returns an Item for the shell script, which must be made
-  executable.
-  """
-
-  diff_program = ["imgdiff"]
-  path = os.path.join(input_tmp, "SYSTEM", "etc", "recovery-resource.dat")
-  if os.path.exists(path):
-    diff_program.append("-b")
-    diff_program.append(path)
-    bonus_args = "-b /system/etc/recovery-resource.dat"
-  else:
-    bonus_args = ""
-
-  d = common.Difference(recovery_img, boot_img, diff_program=diff_program)
-  _, _, patch = d.ComputePatch()
-  common.ZipWriteStr(output_zip, "recovery/recovery-from-boot.p", patch)
-  Item.Get("system/recovery-from-boot.p", dir=False)
-
-  boot_type, boot_device = common.GetTypeAndDevice("/boot", OPTIONS.info_dict)
-  recovery_type, recovery_device = common.GetTypeAndDevice("/recovery", OPTIONS.info_dict)
-
-  sh = """#!/system/bin/sh
-if ! applypatch -c %(recovery_type)s:%(recovery_device)s:%(recovery_size)d:%(recovery_sha1)s; then
-  log -t recovery "Installing new recovery image"
-  applypatch %(bonus_args)s %(boot_type)s:%(boot_device)s:%(boot_size)d:%(boot_sha1)s %(recovery_type)s:%(recovery_device)s %(recovery_sha1)s %(recovery_size)d %(boot_sha1)s:/system/recovery-from-boot.p
-else
-  log -t recovery "Recovery image already installed"
-fi
-""" % { 'boot_size': boot_img.size,
-        'boot_sha1': boot_img.sha1,
-        'recovery_size': recovery_img.size,
-        'recovery_sha1': recovery_img.sha1,
-        'boot_type': boot_type,
-        'boot_device': boot_device,
-        'recovery_type': recovery_type,
-        'recovery_device': recovery_device,
-        'bonus_args': bonus_args,
-        }
-  common.ZipWriteStr(output_zip, "recovery/etc/install-recovery.sh", sh)
-  return Item.Get("system/etc/install-recovery.sh", dir=False)
+def HasRecoveryPatch(target_files_zip):
+  try:
+    target_files_zip.getinfo("SYSTEM/recovery-from-boot.p")
+    return True
+  except KeyError:
+    return False
 
 
 def WriteFullOTAPackage(input_zip, output_zip):
@@ -429,6 +391,9 @@
       metadata=metadata,
       info_dict=OPTIONS.info_dict)
 
+  has_recovery_patch = HasRecoveryPatch(input_zip)
+  block_based = OPTIONS.block_based and has_recovery_patch
+
   if not OPTIONS.omit_prereq:
     ts = GetBuildProp("ro.build.date.utc", OPTIONS.info_dict)
     ts_text = GetBuildProp("ro.build.date", OPTIONS.info_dict)
@@ -478,37 +443,51 @@
 
   device_specific.FullOTA_InstallBegin()
 
-  script.ShowProgress(0.5, 0)
+  system_progress = 0.75
 
   if OPTIONS.wipe_user_data:
+    system_progress -= 0.1
+    script.ShowProgress(0.1, 10)
     script.FormatPartition("/data")
 
   if "selinux_fc" in OPTIONS.info_dict:
     WritePolicyConfig(OPTIONS.info_dict["selinux_fc"], output_zip)
 
-  script.FormatPartition("/system")
-  script.Mount("/system")
-  script.UnpackPackageDir("recovery", "/system")
-  script.UnpackPackageDir("system", "/system")
+  script.ShowProgress(system_progress, 30)
+  if block_based:
+    img_from_target_files.AddSystem(output_zip, sparse=False)
+    script.WriteRawImage("/system", "system.img")
+  else:
+    script.FormatPartition("/system")
+    script.Mount("/system")
+    if not has_recovery_patch:
+      script.UnpackPackageDir("recovery", "/system")
+    script.UnpackPackageDir("system", "/system")
 
-  symlinks = CopySystemFiles(input_zip, output_zip)
-  script.MakeSymlinks(symlinks)
+    symlinks = CopySystemFiles(input_zip, output_zip)
+    script.MakeSymlinks(symlinks)
 
   boot_img = common.GetBootableImage("boot.img", "boot.img",
                                      OPTIONS.input_tmp, "BOOT")
-  MakeRecoveryPatch(OPTIONS.input_tmp, output_zip, recovery_img, boot_img)
 
-  Item.GetMetadata(input_zip)
-  Item.Get("system").SetPermissions(script)
+  if not has_recovery_patch:
+    def output_sink(fn, data):
+      common.ZipWriteStr(output_zip, "recovery/" + fn, data)
+      Item.Get("system/" + fn, dir=False)
+
+    common.MakeRecoveryPatch(OPTIONS.input_tmp, output_sink,
+                             recovery_img, boot_img)
+
+    Item.GetMetadata(input_zip)
+    Item.Get("system").SetPermissions(script)
 
   common.CheckSize(boot_img.data, "boot.img", OPTIONS.info_dict)
   common.ZipWriteStr(output_zip, "boot.img", boot_img.data)
-  script.ShowProgress(0.2, 0)
 
-  script.ShowProgress(0.2, 10)
+  script.ShowProgress(0.05, 5)
   script.WriteRawImage("/boot", "boot.img")
 
-  script.ShowProgress(0.1, 0)
+  script.ShowProgress(0.2, 10)
   device_specific.FullOTA_InstallEnd()
 
   if OPTIONS.extra_script is not None:
@@ -573,7 +552,214 @@
     known_paths.add(path)
     dirs.pop()
 
+def WriteBlockIncrementalOTAPackage(target_zip, source_zip, output_zip):
+  source_version = OPTIONS.source_info_dict["recovery_api_version"]
+  target_version = OPTIONS.target_info_dict["recovery_api_version"]
+
+  if source_version == 0:
+    print ("WARNING: generating edify script for a source that "
+           "can't install it.")
+  script = edify_generator.EdifyGenerator(source_version,
+                                          OPTIONS.target_info_dict)
+
+  metadata = {"pre-device": GetBuildProp("ro.product.device",
+                                         OPTIONS.source_info_dict),
+              "post-timestamp": GetBuildProp("ro.build.date.utc",
+                                             OPTIONS.target_info_dict),
+              }
+
+  device_specific = common.DeviceSpecificParams(
+      source_zip=source_zip,
+      source_version=source_version,
+      target_zip=target_zip,
+      target_version=target_version,
+      output_zip=output_zip,
+      script=script,
+      metadata=metadata,
+      info_dict=OPTIONS.info_dict)
+
+  source_fp = GetBuildProp("ro.build.fingerprint", OPTIONS.source_info_dict)
+  target_fp = GetBuildProp("ro.build.fingerprint", OPTIONS.target_info_dict)
+  metadata["pre-build"] = source_fp
+  metadata["post-build"] = target_fp
+
+  source_boot = common.GetBootableImage(
+      "/tmp/boot.img", "boot.img", OPTIONS.source_tmp, "BOOT",
+      OPTIONS.source_info_dict)
+  target_boot = common.GetBootableImage(
+      "/tmp/boot.img", "boot.img", OPTIONS.target_tmp, "BOOT")
+  updating_boot = (not OPTIONS.two_step and
+                   (source_boot.data != target_boot.data))
+
+  source_recovery = common.GetBootableImage(
+      "/tmp/recovery.img", "recovery.img", OPTIONS.source_tmp, "RECOVERY",
+      OPTIONS.source_info_dict)
+  target_recovery = common.GetBootableImage(
+      "/tmp/recovery.img", "recovery.img", OPTIONS.target_tmp, "RECOVERY")
+  updating_recovery = (source_recovery.data != target_recovery.data)
+
+  with tempfile.NamedTemporaryFile() as src_file:
+    with tempfile.NamedTemporaryFile() as tgt_file:
+      print "building source system image..."
+      src_file = tempfile.NamedTemporaryFile()
+      src_data = img_from_target_files.BuildSystem(
+          OPTIONS.source_tmp, OPTIONS.source_info_dict, sparse=False)
+      src_sys_sha1 = sha1(src_data).hexdigest()
+      print "source system sha1:", src_sys_sha1
+      src_file.write(src_data)
+      src_data = None
+
+      print "building target system image..."
+      tgt_file = tempfile.NamedTemporaryFile()
+      tgt_data = img_from_target_files.BuildSystem(
+          OPTIONS.target_tmp, OPTIONS.target_info_dict, sparse=False)
+      tgt_sys_sha1 = sha1(tgt_data).hexdigest()
+      print "target system sha1:", tgt_sys_sha1
+      tgt_sys_len = len(tgt_data)
+      tgt_file.write(tgt_data)
+      tgt_data = None
+
+      system_type, system_device = common.GetTypeAndDevice("/system", OPTIONS.info_dict)
+      system_patch = common.MakeSystemPatch(src_file, tgt_file)
+      system_patch.AddToZip(output_zip, compression=zipfile.ZIP_STORED)
+
+  AppendAssertions(script, OPTIONS.target_info_dict)
+  device_specific.IncrementalOTA_Assertions()
+
+  # Two-step incremental package strategy (in chronological order,
+  # which is *not* the order in which the generated script has
+  # things):
+  #
+  # if stage is not "2/3" or "3/3":
+  #    do verification on current system
+  #    write recovery image to boot partition
+  #    set stage to "2/3"
+  #    reboot to boot partition and restart recovery
+  # else if stage is "2/3":
+  #    write recovery image to recovery partition
+  #    set stage to "3/3"
+  #    reboot to recovery partition and restart recovery
+  # else:
+  #    (stage must be "3/3")
+  #    perform update:
+  #       patch system files, etc.
+  #       force full install of new boot image
+  #       set up system to update recovery partition on first boot
+  #    complete script normally (allow recovery to mark itself finished and reboot)
+
+  if OPTIONS.two_step:
+    if not OPTIONS.info_dict.get("multistage_support", None):
+      assert False, "two-step packages not supported by this build"
+    fs = OPTIONS.info_dict["fstab"]["/misc"]
+    assert fs.fs_type.upper() == "EMMC", \
+        "two-step packages only supported on devices with EMMC /misc partitions"
+    bcb_dev = {"bcb_dev": fs.device}
+    common.ZipWriteStr(output_zip, "recovery.img", target_recovery.data)
+    script.AppendExtra("""
+if get_stage("%(bcb_dev)s", "stage") == "2/3" then
+""" % bcb_dev)
+    script.AppendExtra("sleep(20);\n");
+    script.WriteRawImage("/recovery", "recovery.img")
+    script.AppendExtra("""
+set_stage("%(bcb_dev)s", "3/3");
+reboot_now("%(bcb_dev)s", "recovery");
+else if get_stage("%(bcb_dev)s", "stage") != "3/3" then
+""" % bcb_dev)
+
+  script.Print("Verifying current system...")
+
+  device_specific.IncrementalOTA_VerifyBegin()
+
+  script.AssertRecoveryFingerprint(source_fp, target_fp)
+
+  if updating_boot:
+    d = common.Difference(target_boot, source_boot)
+    _, _, d = d.ComputePatch()
+    print "boot      target: %d  source: %d  diff: %d" % (
+        target_boot.size, source_boot.size, len(d))
+
+    common.ZipWriteStr(output_zip, "patch/boot.img.p", d)
+
+    boot_type, boot_device = common.GetTypeAndDevice("/boot", OPTIONS.info_dict)
+
+    script.PatchCheck("%s:%s:%d:%s:%d:%s" %
+                      (boot_type, boot_device,
+                       source_boot.size, source_boot.sha1,
+                       target_boot.size, target_boot.sha1))
+
+  device_specific.IncrementalOTA_VerifyEnd()
+
+  if OPTIONS.two_step:
+    script.WriteRawImage("/boot", "recovery.img")
+    script.AppendExtra("""
+set_stage("%(bcb_dev)s", "2/3");
+reboot_now("%(bcb_dev)s", "");
+else
+""" % bcb_dev)
+
+  script.Comment("---- start making changes here ----")
+
+  device_specific.IncrementalOTA_InstallBegin()
+
+  if OPTIONS.wipe_user_data:
+    script.Print("Erasing user data...")
+    script.FormatPartition("/data")
+
+  script.Print("Patching system image...")
+  script.Syspatch(system_device,
+                  OPTIONS.info_dict["system_size"],
+                  tgt_sys_sha1,
+                  src_sys_sha1,
+                  system_patch.name)
+
+  if OPTIONS.two_step:
+    common.ZipWriteStr(output_zip, "boot.img", target_boot.data)
+    script.WriteRawImage("/boot", "boot.img")
+    print "writing full boot image (forced by two-step mode)"
+
+  if not OPTIONS.two_step:
+    if updating_boot:
+      # Produce the boot image by applying a patch to the current
+      # contents of the boot partition, and write it back to the
+      # partition.
+      script.Print("Patching boot image...")
+      script.ApplyPatch("%s:%s:%d:%s:%d:%s"
+                        % (boot_type, boot_device,
+                           source_boot.size, source_boot.sha1,
+                           target_boot.size, target_boot.sha1),
+                        "-",
+                        target_boot.size, target_boot.sha1,
+                        source_boot.sha1, "patch/boot.img.p")
+      print "boot image changed; including."
+    else:
+      print "boot image unchanged; skipping."
+
+  # Do device-specific installation (eg, write radio image).
+  device_specific.IncrementalOTA_InstallEnd()
+
+  if OPTIONS.extra_script is not None:
+    script.AppendExtra(OPTIONS.extra_script)
+
+  if OPTIONS.two_step:
+    script.AppendExtra("""
+set_stage("%(bcb_dev)s", "");
+endif;
+endif;
+""" % bcb_dev)
+
+  script.SetProgress(1)
+  script.AddToZip(target_zip, output_zip)
+  WriteMetadata(metadata, output_zip)
+
 def WriteIncrementalOTAPackage(target_zip, source_zip, output_zip):
+  target_has_recovery_patch = HasRecoveryPatch(target_zip)
+  source_has_recovery_patch = HasRecoveryPatch(source_zip)
+
+  if (OPTIONS.block_based and
+      target_has_recovery_patch and
+      source_has_recovery_patch):
+    return WriteBlockIncrementalOTAPackage(target_zip, source_zip, output_zip)
+
   source_version = OPTIONS.source_info_dict["recovery_api_version"]
   target_version = OPTIONS.target_info_dict["recovery_api_version"]
 
@@ -744,9 +930,6 @@
   device_specific.IncrementalOTA_VerifyBegin()
 
   script.ShowProgress(0.1, 0)
-  total_verify_size = float(sum([i[1].size for i in patch_list]) + 1)
-  if updating_boot:
-    total_verify_size += source_boot.size
   so_far = 0
 
   for tf, sf, size, patch_sha in patch_list:
@@ -754,7 +937,6 @@
       script.SkipNextActionIfTargetExists(tf.name, tf.sha1)
     script.PatchCheck("/"+sf.name, tf.sha1, sf.sha1)
     so_far += sf.size
-    script.SetProgress(so_far / total_verify_size)
 
   if updating_boot:
     d = common.Difference(target_boot, source_boot)
@@ -771,7 +953,6 @@
                        source_boot.size, source_boot.sha1,
                        target_boot.size, target_boot.sha1))
     so_far += source_boot.size
-    script.SetProgress(so_far / total_verify_size)
 
   if patch_list or updating_recovery or updating_boot:
     script.CacheFreeSpaceCheck(largest_source_size)
@@ -854,10 +1035,15 @@
     # For older builds where recovery-resource.dat is not present, we
     # use only the boot image as the source.
 
-    MakeRecoveryPatch(OPTIONS.target_tmp, output_zip,
-                      target_recovery, target_boot)
-    script.DeleteFiles(["/system/recovery-from-boot.p",
-                        "/system/etc/install-recovery.sh"])
+    if not target_has_recovery_patch:
+      def output_sink(fn, data):
+        common.ZipWriteStr(output_zip, "recovery/" + fn, data)
+        Item.Get("system/" + fn, dir=False)
+
+      common.MakeRecoveryPatch(OPTIONS.target_tmp, output_sink,
+                               target_recovery, target_boot)
+      script.DeleteFiles(["/system/recovery-from-boot.p",
+                          "/system/etc/install-recovery.sh"])
     print "recovery image changed; including as patch from boot."
   else:
     print "recovery image unchanged; skipping."
@@ -889,7 +1075,7 @@
     script.Print("Unpacking new files...")
     script.UnpackPackageDir("system", "/system")
 
-  if updating_recovery:
+  if updating_recovery and not target_has_recovery_patch:
     script.Print("Unpacking new recovery...")
     script.UnpackPackageDir("recovery", "/system")
 
@@ -969,8 +1155,10 @@
       OPTIONS.worker_threads = int(a)
     elif o in ("-2", "--two_step"):
       OPTIONS.two_step = True
-    elif o in ("--no_signing"):
+    elif o == "--no_signing":
       OPTIONS.no_signing = True
+    elif o == "--block":
+      OPTIONS.block_based = True
     else:
       return False
     return True
@@ -987,6 +1175,7 @@
                                               "aslr_mode=",
                                               "two_step",
                                               "no_signing",
+                                              "block",
                                               ],
                              extra_option_handler=option_handler)
 
@@ -1015,11 +1204,23 @@
     print "--- target info ---"
     common.DumpInfoDict(OPTIONS.info_dict)
 
+  # If the caller explicitly specified the device-specific extensions
+  # path via -s/--device_specific, use that.  Otherwise, use
+  # META/releasetools.py if it is present in the target target_files.
+  # Otherwise, take the path of the file from 'tool_extensions' in the
+  # info dict and look for that in the local filesystem, relative to
+  # the current directory.
+
   if OPTIONS.device_specific is None:
-    OPTIONS.device_specific = OPTIONS.info_dict.get("tool_extensions", None)
+    from_input = os.path.join(OPTIONS.input_tmp, "META", "releasetools.py")
+    if os.path.exists(from_input):
+      print "(using device-specific extensions from target_files)"
+      OPTIONS.device_specific = from_input
+    else:
+      OPTIONS.device_specific = OPTIONS.info_dict.get("tool_extensions", None)
+
   if OPTIONS.device_specific is not None:
-    OPTIONS.device_specific = os.path.normpath(OPTIONS.device_specific)
-    print "using device-specific extensions in", OPTIONS.device_specific
+    OPTIONS.device_specific = os.path.abspath(OPTIONS.device_specific)
 
   if OPTIONS.no_signing:
     output_zip = zipfile.ZipFile(args[1], "w", compression=zipfile.ZIP_DEFLATED)
diff --git a/tools/releasetools/sign_target_files_apks b/tools/releasetools/sign_target_files_apks
index ab24706..5398cec 100755
--- a/tools/releasetools/sign_target_files_apks
+++ b/tools/releasetools/sign_target_files_apks
@@ -67,8 +67,8 @@
 
 import sys
 
-if sys.hexversion < 0x02040000:
-  print >> sys.stderr, "Python 2.4 or newer is required."
+if sys.hexversion < 0x02070000:
+  print >> sys.stderr, "Python 2.7 or newer is required."
   sys.exit(1)
 
 import base64
@@ -77,6 +77,7 @@
 import errno
 import os
 import re
+import shutil
 import subprocess
 import tempfile
 import zipfile
@@ -139,14 +140,40 @@
   return data
 
 
-def SignApks(input_tf_zip, output_tf_zip, apk_key_map, key_passwords):
+def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
+                       apk_key_map, key_passwords):
   maxsize = max([len(os.path.basename(i.filename))
                  for i in input_tf_zip.infolist()
                  if i.filename.endswith('.apk')])
+  rebuild_recovery = False
+
+  tmpdir = tempfile.mkdtemp()
+  def write_to_temp(fn, attr, data):
+    fn = os.path.join(tmpdir, fn)
+    if fn.endswith("/"):
+      fn = os.path.join(tmpdir, fn)
+      os.mkdir(fn)
+    else:
+      d = os.path.dirname(fn)
+      if d and not os.path.exists(d):
+        os.makedirs(d)
+
+      if attr >> 16 == 0xa1ff:
+        os.symlink(data, fn)
+      else:
+        with open(fn, "wb") as f:
+          f.write(data)
 
   for info in input_tf_zip.infolist():
     data = input_tf_zip.read(info.filename)
     out_info = copy.copy(info)
+
+    if (info.filename.startswith("BOOT/") or
+        info.filename.startswith("RECOVERY/") or
+        info.filename.startswith("META/") or
+        info.filename == "SYSTEM/etc/recovery-resource.dat"):
+      write_to_temp(info.filename, info.external_attr, data)
+
     if info.filename.endswith(".apk"):
       name = os.path.basename(info.filename)
       key = apk_key_map[name]
@@ -163,14 +190,43 @@
       print "rewriting %s:" % (info.filename,)
       new_data = RewriteProps(data)
       output_tf_zip.writestr(out_info, new_data)
+      if info.filename == "RECOVERY/RAMDISK/default.prop":
+        write_to_temp(info.filename, info.external_attr, new_data)
     elif info.filename.endswith("mac_permissions.xml"):
       print "rewriting %s with new keys." % (info.filename,)
       new_data = ReplaceCerts(data)
       output_tf_zip.writestr(out_info, new_data)
+    elif info.filename in ("SYSTEM/recovery-from-boot.p",
+                           "SYSTEM/bin/install-recovery.sh"):
+      rebuild_recovery = True
+    elif (OPTIONS.replace_ota_keys and
+          info.filename in ("RECOVERY/RAMDISK/res/keys",
+                            "SYSTEM/etc/security/otacerts.zip")):
+      # don't copy these files if we're regenerating them below
+      pass
     else:
       # a non-APK file; copy it verbatim
       output_tf_zip.writestr(out_info, data)
 
+  if OPTIONS.replace_ota_keys:
+    new_recovery_keys = ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
+    if new_recovery_keys:
+      write_to_temp("RECOVERY/RAMDISK/res/keys", 0755 << 16, new_recovery_keys)
+
+  if rebuild_recovery:
+    recovery_img = common.GetBootableImage(
+        "recovery.img", "recovery.img", tmpdir, "RECOVERY", info_dict=misc_info)
+    boot_img = common.GetBootableImage(
+        "boot.img", "boot.img", tmpdir, "BOOT", info_dict=misc_info)
+
+    def output_sink(fn, data):
+      output_tf_zip.writestr("SYSTEM/"+fn, data)
+
+    common.MakeRecoveryPatch(tmpdir, output_sink, recovery_img, boot_img,
+                             info_dict=misc_info)
+
+  shutil.rmtree(tmpdir)
+
 
 def ReplaceCerts(data):
   """Given a string of data, replace all occurences of a set
@@ -265,7 +321,8 @@
   for k in keylist:
     m = re.match(r"^(.*)\.x509\.pem$", k)
     if not m:
-      raise common.ExternalError("can't parse \"%s\" from META/otakeys.txt" % (k,))
+      raise common.ExternalError(
+          "can't parse \"%s\" from META/otakeys.txt" % (k,))
     k = m.group(1)
     mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
 
@@ -287,10 +344,11 @@
                   os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")]
                  + mapped_keys + extra_recovery_keys,
                  stdout=subprocess.PIPE)
-  data, _ = p.communicate()
+  new_recovery_keys, _ = p.communicate()
   if p.returncode != 0:
     raise common.ExternalError("failed to run dumpkeys")
-  common.ZipWriteStr(output_tf_zip, "RECOVERY/RAMDISK/res/keys", data)
+  common.ZipWriteStr(output_tf_zip, "RECOVERY/RAMDISK/res/keys",
+                     new_recovery_keys)
 
   # SystemUpdateActivity uses the x509.pem version of the keys, but
   # put into a zipfile system/etc/security/otacerts.zip.
@@ -304,6 +362,8 @@
   common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
                      tempfile.getvalue())
 
+  return new_recovery_keys
+
 
 def BuildKeyMap(misc_info, key_mapping_options):
   for s, d in key_mapping_options:
@@ -375,10 +435,8 @@
   CheckAllApksSigned(input_zip, apk_key_map)
 
   key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
-  SignApks(input_zip, output_zip, apk_key_map, key_passwords)
-
-  if OPTIONS.replace_ota_keys:
-    ReplaceOtaKeys(input_zip, output_zip, misc_info)
+  ProcessTargetFiles(input_zip, output_zip, misc_info,
+                     apk_key_map, key_passwords)
 
   input_zip.close()
   output_zip.close()