am 72e9dab0: am 7b954f4c: Merge "Add the search path for libgcc.a and crt*.o."

* commit '72e9dab0127e4200d5770d0fa7944fc0db29632b':
  Add the search path for libgcc.a and crt*.o.
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 30ebdea..877c690 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -168,15 +168,39 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 
-# So...  funny story.  Recall when I mentioned above the
-# "JB MR2" thing?  I didn't mean that.  In fact, while I was
-# writing JB MR, my head was thinking 4.2, and things got
-# cross-wired as they are wont to do, and we ended up with
-# JB MR2, which didn't actually exist.
-#
-# Well, didn't exist then.
-#
-# Now it does.  Say hi, JB MR2!
+# And on to KLP...
+$(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/*)
+
+# KLP now based off API 18.
+$(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/*)
+
+# Clean up around the /system/app -> /system/priv-app migration
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
+
+# Clean up old location of generated Java files from aidl
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src)
+
+# Clean up ApplicationsProvider which is being removed.
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/ApplicationsProvider_intermediates)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/priv-app/ApplicationsProvider.apk)
+
+# Clean up Moto OMA DM client which isn't ready yet.
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.omadm.plugin.dev_intermediates)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.omadm.plugin.diagmon_intermediates)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.omadm.pluginhelper_intermediates)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.omadm.plugin_intermediates)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.omadm.service.api_intermediates)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/DMService_intermediates)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/SprintDM_intermediates)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/priv-app/DMService.apk)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/SprintDM.apk)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/etc/omadm)
+
+# 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/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
diff --git a/buildspec.mk.default b/buildspec.mk.default
index 2f84016..d14208e 100644
--- a/buildspec.mk.default
+++ b/buildspec.mk.default
@@ -93,15 +93,15 @@
 #NO_FALLBACK_FONT:=true
 endif
 
-# To enable instrumentation in webcore based apps like gmail and
-# the browser, define WEBCORE_INSTRUMENTATION:=true
-ifndef WEBCORE_INSTRUMENTATION
-#WEBCORE_INSTRUMENTATION:=true
-endif
-
-# To disable SVG in webcore define ENABLE_SVG:=false
-ifndef ENABLE_SVG
-#ENABLE_SVG:=false
+# OVERRIDE_RUNTIMES allows you to locally override PRODUCT_RUNTIMES.
+#
+# To only build ART, use "runtime_libart_default"
+# To use Dalvik but also include ART, use "runtime_libdvm_default runtime_libart"
+# To use ART but also include Dalvik, use "runtime_libart_default runtime_libdvm"
+ifndef OVERRIDE_RUNTIMES
+#OVERRIDE_RUNTIMES:=runtime_libart_default
+#OVERRIDE_RUNTIMES:=runtime_libdvm_default runtime_libart
+#OVERRIDE_RUNTIMES:=runtime_libart_default runtime_libdvm
 endif
 
 # when the build system changes such that this file must be updated, this
diff --git a/core/Makefile b/core/Makefile
index 556fe0d..fca06fa 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -96,10 +96,11 @@
 # Both of these tags will be removed and replaced with "release-keys"
 # when the target-files is signed in a post-build step.
 ifeq ($(DEFAULT_SYSTEM_DEV_CERTIFICATE),build/target/product/security/testkey)
-BUILD_VERSION_TAGS += test-keys
+BUILD_KEYS := test-keys
 else
-BUILD_VERSION_TAGS += dev-keys
+BUILD_KEYS := dev-keys
 endif
+BUILD_VERSION_TAGS += $(BUILD_KEYS)
 BUILD_VERSION_TAGS := $(subst $(space),$(comma),$(sort $(BUILD_VERSION_TAGS)))
 
 # A human-readable string that descibes this build in detail.
@@ -121,9 +122,9 @@
 
   # Dev. branches should have DISPLAY_BUILD_NUMBER set
   ifeq "true" "$(DISPLAY_BUILD_NUMBER)"
-    BUILD_DISPLAY_ID := $(BUILD_ID).$(BUILD_NUMBER)
+    BUILD_DISPLAY_ID := $(BUILD_ID).$(BUILD_NUMBER) $(BUILD_KEYS)
   else
-    BUILD_DISPLAY_ID := $(BUILD_ID)
+    BUILD_DISPLAY_ID := $(BUILD_ID) $(BUILD_KEYS)
   endif
 else
   # Non-user builds should show detailed build information
@@ -384,6 +385,10 @@
 	$(call pretty,"Target ram disk: $@")
 	$(hide) $(MKBOOTFS) $(TARGET_ROOT_OUT) | $(MINIGZIP) > $@
 
+.PHONY: ramdisk-nodeps
+ramdisk-nodeps: $(MKBOOTFS) | $(MINIGZIP)
+	@echo "make $@: ignoring dependencies"
+	$(hide) $(MKBOOTFS) $(TARGET_ROOT_OUT) | $(MINIGZIP) > $(INSTALLED_RAMDISK_TARGET)
 
 ifneq ($(strip $(TARGET_NO_KERNEL)),true)
 
@@ -421,12 +426,24 @@
 	$(call pretty,"Target boot image: $@")
 	$(hide) $(MKEXT2BOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) --output $@
 
+.PHONY: bootimage-nodeps
+bootimage-nodeps: $(MKEXT2IMG)
+	@echo "make $@: ignoring dependencies"
+	$(hide) $(MKEXT2BOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET)
+
 else # TARGET_BOOTIMAGE_USE_EXT2 != true
 
 $(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES)
 	$(call pretty,"Target boot image: $@")
 	$(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@
 	$(hide) $(call assert-max-image-size,$@,$(BOARD_BOOTIMAGE_PARTITION_SIZE),raw)
+
+.PHONY: bootimage-nodeps
+bootimage-nodeps: $(MKBOOTIMG)
+	@echo "make $@: ignoring dependencies"
+	$(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET)
+	$(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE),raw)
+
 endif # TARGET_BOOTIMAGE_USE_EXT2
 
 else	# TARGET_NO_KERNEL
@@ -490,6 +507,7 @@
 tools_notice_file_txt := $(HOST_OUT_INTERMEDIATES)/NOTICE.txt
 tools_notice_file_html := $(HOST_OUT_INTERMEDIATES)/NOTICE.html
 
+ifndef TARGET_BUILD_APPS
 kernel_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/kernel.txt
 pdk_fusion_notice_files := $(filter $(TARGET_OUT_NOTICE_FILES)/%, $(ALL_PDK_FUSION_FILES))
 
@@ -522,6 +540,7 @@
 ifeq ($(ONE_SHOT_MAKEFILE),)
 ALL_DEFAULT_INSTALLED_MODULES += $(installed_notice_html_gz)
 endif
+endif  # TARGET_BUILD_APPS
 
 # The kernel isn't really a module, so to get its module file in there, we
 # make the target NOTICE files depend on this particular file too, which will
@@ -875,6 +894,11 @@
 #######
 ## platform.zip: system, plus other files to be used in PDK fusion build,
 ## in a zip file
+##
+## PDK_PLATFORM_ZIP_PRODUCT_BINARIES is used to store specified files to platform.zip.
+## The variable will be typically set from BoardConfig.mk.
+## Files under out dir will be rejected to prevent possible conflicts with other rules.
+PDK_PLATFORM_ZIP_PRODUCT_BINARIES := $(filter-out $(OUT_DIR)/%,$(PDK_PLATFORM_ZIP_PRODUCT_BINARIES))
 INSTALLED_PLATFORM_ZIP := $(PRODUCT_OUT)/platform.zip
 $(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_SYSTEMIMAGE_FILES)
 	$(call pretty,"Platform zip package: $(INSTALLED_PLATFORM_ZIP)")
@@ -886,7 +910,9 @@
 ifeq (true,$(PLATFORM_ZIP_ADD_JAVA))
 	$(hide) cd $(OUT_DIR) && zip -qry $(patsubst $(OUT_DIR)/%,%,$@) $(PDK_PLATFORM_JAVA_ZIP_CONTENTS)
 endif
-
+ifneq ($(PDK_PLATFORM_ZIP_PRODUCT_BINARIES),)
+	$(hide) zip -qry $@ $(PDK_PLATFORM_ZIP_PRODUCT_BINARIES)
+endif
 
 .PHONY: platform
 platform: $(INSTALLED_PLATFORM_ZIP)
@@ -1147,6 +1173,7 @@
 		$(INSTALLED_CACHEIMAGE_TARGET) \
 		$(INSTALLED_VENDORIMAGE_TARGET) \
 		$(INSTALLED_ANDROID_INFO_TXT_TARGET) \
+		$(SELINUX_FC) \
 		$(built_ota_tools) \
 		$(APKCERTS_FILE) \
 		$(HOST_OUT_EXECUTABLES)/fs_config \
@@ -1234,13 +1261,14 @@
 	$(hide) echo "extra_recovery_keys=$(PRODUCT_EXTRA_RECOVERY_KEYS)" >> $(zip_root)/META/misc_info.txt
 endif
 	$(hide) echo 'mkbootimg_args=$(BOARD_MKBOOTIMG_ARGS)' >> $(zip_root)/META/misc_info.txt
+	$(hide) echo "use_set_metadata=1" >> $(zip_root)/META/misc_info.txt
 	$(call generate-userimage-prop-dictionary, $(zip_root)/META/misc_info.txt)
 	@# Zip everything up, preserving symlinks
 	$(hide) (cd $(zip_root) && zip -qry ../$(notdir $@) .)
 	@# Run fs_config on all the system, boot ramdisk, and recovery ramdisk files in the zip, and save the output
-	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="SYSTEM/" } /^SYSTEM\// {print "system/" $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config > $(zip_root)/META/filesystem_config.txt
-	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="BOOT/RAMDISK/" } /^BOOT\/RAMDISK\// {print $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config > $(zip_root)/META/boot_filesystem_config.txt
-	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="RECOVERY/RAMDISK/" } /^RECOVERY\/RAMDISK\// {print $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config > $(zip_root)/META/recovery_filesystem_config.txt
+	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="SYSTEM/" } /^SYSTEM\// {print "system/" $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config -C -S $(SELINUX_FC) > $(zip_root)/META/filesystem_config.txt
+	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="BOOT/RAMDISK/" } /^BOOT\/RAMDISK\// {print $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config -C -S $(SELINUX_FC) > $(zip_root)/META/boot_filesystem_config.txt
+	$(hide) zipinfo -1 $@ | awk 'BEGIN { FS="RECOVERY/RAMDISK/" } /^RECOVERY\/RAMDISK\// {print $$2}' | $(HOST_OUT_EXECUTABLES)/fs_config -C -S $(SELINUX_FC) > $(zip_root)/META/recovery_filesystem_config.txt
 	$(hide) (cd $(zip_root) && zip -q ../$(notdir $@) META/*filesystem_config.txt)
 
 .PHONY: target-files-package
@@ -1398,6 +1426,27 @@
 
 endif # EMMA_INSTRUMENT=true
 
+#------------------------------------------------------------------
+# A zip of Proguard obfuscation dictionary files.
+# Only for apps_only build.
+#
+ifdef TARGET_BUILD_APPS
+PROGUARD_DICT_ZIP := $(PRODUCT_OUT)/$(TARGET_PRODUCT)-proguard-dict-$(FILE_NAME_TAG).zip
+# the dependency will be set up later in build/core/main.mk.
+$(PROGUARD_DICT_ZIP) :
+	@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; \
+		else \
+		  touch $(dir $@)/dummy; \
+		  (cd $(dir $@) && zip -q $(notdir $@) dummy); \
+		  zip -qd $@ dummy; \
+		  rm $(dir $@)/dummy; \
+		fi
+
+endif # TARGET_BUILD_APPS
+
 # -----------------------------------------------------------------
 # dalvik something
 .PHONY: dalvikfiles
@@ -1587,16 +1636,18 @@
 $(INTERNAL_FINDBUGS_HTML_TARGET): $(INTERNAL_FINDBUGS_XML_TARGET)
 	@echo ConvertXmlToText: $@
 	$(hide) prebuilt/common/findbugs/bin/convertXmlToText -html:fancy.xsl \
-	$(INTERNAL_FINDBUGS_XML_TARGET)	> $@
+	$(INTERNAL_FINDBUGS_XML_TARGET) > $@
 
 # -----------------------------------------------------------------
 # Findbugs
 
 # -----------------------------------------------------------------
 # These are some additional build tasks that need to be run.
+ifneq ($(dont_bother),true)
 include $(sort $(wildcard $(BUILD_SYSTEM)/tasks/*.mk))
 -include $(sort $(wildcard vendor/*/build/tasks/*.mk))
 -include $(sort $(wildcard device/*/build/tasks/*.mk))
+endif
 
 # -----------------------------------------------------------------
 # Create SDK repository packages. Must be done after tasks/* since
diff --git a/core/base_rules.mk b/core/base_rules.mk
index f6497da..36f36c1 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -98,23 +98,27 @@
 endif
 
 ifneq (true,$(LOCAL_UNINSTALLABLE_MODULE))
-ifdef LOCAL_IS_HOST_MODULE
-  partition_tag :=
-else
-ifeq (true,$(LOCAL_PROPRIETARY_MODULE))
-  partition_tag := _VENDOR
-else
-  # The definition of should-install-to-system will be different depending
-  # on which goal (e.g., sdk or just droid) is being built.
-  partition_tag := $(if $(call should-install-to-system,$(LOCAL_MODULE_TAGS)),,_DATA)
-endif
-endif
-
 LOCAL_MODULE_PATH := $(strip $(LOCAL_MODULE_PATH))
 ifeq ($(LOCAL_MODULE_PATH),)
-  LOCAL_MODULE_PATH := $($(my_prefix)OUT$(partition_tag)_$(LOCAL_MODULE_CLASS))
+  ifdef LOCAL_IS_HOST_MODULE
+    partition_tag :=
+  else
+  ifeq (true,$(LOCAL_PROPRIETARY_MODULE))
+    partition_tag := _VENDOR
+  else
+    # The definition of should-install-to-system will be different depending
+    # on which goal (e.g., sdk or just droid) is being built.
+    partition_tag := $(if $(call should-install-to-system,$(LOCAL_MODULE_TAGS)),,_DATA)
+  endif
+  endif
+  install_path_var := $(my_prefix)OUT$(partition_tag)_$(LOCAL_MODULE_CLASS)
+  ifeq (true,$(LOCAL_PRIVILEGED_MODULE))
+    install_path_var := $(install_path_var)_PRIVILEGED
+  endif
+
+  LOCAL_MODULE_PATH := $($(install_path_var))
   ifeq ($(strip $(LOCAL_MODULE_PATH)),)
-    $(error $(LOCAL_PATH): unhandled LOCAL_MODULE_CLASS "$(LOCAL_MODULE_CLASS)")
+    $(error $(LOCAL_PATH): unhandled install path "$(install_path_var)")
   endif
 endif
 endif # not LOCAL_UNINSTALLABLE_MODULE
@@ -137,15 +141,16 @@
 ###########################################################
 # Pick a name for the intermediate and final targets
 ###########################################################
-LOCAL_MODULE_STEM := $(strip $(LOCAL_MODULE_STEM))
-ifeq ($(LOCAL_MODULE_STEM),)
+ifndef LOCAL_MODULE_STEM
   LOCAL_MODULE_STEM := $(LOCAL_MODULE)
 endif
-LOCAL_INSTALLED_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
 
-LOCAL_BUILT_MODULE_STEM := $(strip $(LOCAL_BUILT_MODULE_STEM))
-ifeq ($(LOCAL_BUILT_MODULE_STEM),)
-  LOCAL_BUILT_MODULE_STEM := $(LOCAL_INSTALLED_MODULE_STEM)
+ifndef LOCAL_BUILT_MODULE_STEM
+  LOCAL_BUILT_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
+endif
+
+ifndef LOCAL_INSTALLED_MODULE_STEM
+  LOCAL_INSTALLED_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
 endif
 
 # OVERRIDE_BUILT_MODULE_PATH is only allowed to be used by the
@@ -181,9 +186,6 @@
 aidl_java_sources := $(patsubst %.aidl,%.java,$(addprefix $(intermediates.COMMON)/src/, $(aidl_sources)))
 aidl_sources := $(addprefix $(TOP_DIR)$(LOCAL_PATH)/, $(aidl_sources))
 
-ifeq (,$(TARGET_BUILD_APPS))
-LOCAL_AIDL_INCLUDES += $(FRAMEWORKS_BASE_JAVA_SRC_DIRS)
-endif
 aidl_preprocess_import :=
 LOCAL_SDK_VERSION:=$(strip $(LOCAL_SDK_VERSION))
 ifdef LOCAL_SDK_VERSION
@@ -193,6 +195,9 @@
 else
   aidl_preprocess_import := $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_VERSION)/framework.aidl
 endif # !current
+else
+# build against the platform.
+LOCAL_AIDL_INCLUDES += $(FRAMEWORKS_BASE_JAVA_SRC_DIRS)
 endif # LOCAL_SDK_VERSION
 $(aidl_java_sources): PRIVATE_AIDL_FLAGS := -b $(addprefix -p,$(aidl_preprocess_import)) -I$(LOCAL_PATH) -I$(LOCAL_PATH)/src $(addprefix -I,$(LOCAL_AIDL_INCLUDES))
 
@@ -349,8 +354,11 @@
 endif # java_resource_file_groups
 
 ## PRIVATE java vars ######################################
-
-ifneq ($(strip $(all_java_sources)$(all_res_assets))$(LOCAL_STATIC_JAVA_LIBRARIES),)
+# LOCAL_SOURCE_FILES_ALL_GENERATED is set only if the module does not have static source files,
+# but generated source files in its LOCAL_INTERMEDIATE_SOURCE_DIR.
+# You have to set up the dependency in some other way.
+need_compile_java := $(strip $(all_java_sources)$(all_res_assets))$(LOCAL_STATIC_JAVA_LIBRARIES)$(filter true,$(LOCAL_SOURCE_FILES_ALL_GENERATED))
+ifdef need_compile_java
 
 full_static_java_libs := \
     $(foreach lib,$(LOCAL_STATIC_JAVA_LIBRARIES), \
@@ -388,19 +396,20 @@
 ifeq ($(LOCAL_BUILD_HOST_DEX),true)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,core-hostdex,$(LOCAL_IS_HOST_MODULE))
 
-full_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
+full_shared_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 full_java_lib_deps := $(call java-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 else
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH :=
 
-full_java_libs := $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/,$(addsuffix $(COMMON_JAVA_PACKAGE_SUFFIX),$(LOCAL_JAVA_LIBRARIES)))
-full_java_lib_deps := $(full_java_libs)
+full_shared_java_libs := $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/,\
+    $(addsuffix $(COMMON_JAVA_PACKAGE_SUFFIX),$(LOCAL_JAVA_LIBRARIES)))
+full_java_lib_deps := $(full_shared_java_libs)
 endif # LOCAL_BUILD_HOST_DEX
 else
-full_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
+full_shared_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 full_java_lib_deps := $(call java-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 endif # !LOCAL_IS_HOST_MODULE
-full_java_libs += $(full_static_java_libs) $(LOCAL_CLASSPATH)
+full_java_libs := $(full_shared_java_libs) $(full_static_java_libs) $(LOCAL_CLASSPATH)
 full_java_lib_deps += $(full_static_java_libs) $(LOCAL_CLASSPATH)
 
 # This is set by packages that are linking to other packages that export
@@ -413,6 +422,7 @@
               APPS,$(lib),,COMMON)/classes.jar)
 
   # link against the jar with full original names (before proguard processing).
+  full_shared_java_libs += $(link_apk_libraries)
   full_java_libs += $(link_apk_libraries)
   full_java_lib_deps += $(link_apk_libraries)
 endif
@@ -427,14 +437,12 @@
         $(LOCAL_PATH): Multiple LOCAL_INSTRUMENTATION_FOR members defined)
   endif
 
-  link_instr_intermediates_dir := $(call intermediates-dir-for, \
-      APPS,$(LOCAL_INSTRUMENTATION_FOR))
   link_instr_intermediates_dir.COMMON := $(call intermediates-dir-for, \
       APPS,$(LOCAL_INSTRUMENTATION_FOR),,COMMON)
-
   # link against the jar with full original names (before proguard processing).
-  full_java_libs += $(link_instr_intermediates_dir.COMMON)/classes.jar
-  full_java_lib_deps += $(link_instr_intermediates_dir.COMMON)/classes.jar
+  link_instr_classes_jar := $(link_instr_intermediates_dir.COMMON)/classes.jar
+  full_java_libs += $(link_instr_classes_jar)
+  full_java_lib_deps += $(link_instr_classes_jar)
 endif
 
 jar_manifest_file :=
@@ -445,7 +453,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAR_MANIFEST :=
 endif
 
-endif
+endif  # need_compile_java
 
 
 ###########################################################
@@ -543,20 +551,16 @@
 ## CHECK_BUILD goals
 ###########################################################
 
+ifdef java_alternative_checked_module
+  LOCAL_CHECKED_MODULE := $(java_alternative_checked_module)
+endif
+
 # If nobody has defined a more specific module for the
 # checked modules, use LOCAL_BUILT_MODULE.
 ifndef LOCAL_CHECKED_MODULE
   LOCAL_CHECKED_MODULE := $(LOCAL_BUILT_MODULE)
 endif
 
-need_compile_java :=
-ifdef java_alternative_checked_module
-ifneq (,$(strip $(all_java_sources)$(full_static_java_libs))$(filter true,$(LOCAL_SOURCE_FILES_ALL_GENERATED)))
-  need_compile_java := true
-  LOCAL_CHECKED_MODULE := $(java_alternative_checked_module)
-endif
-endif
-
 # If they request that this module not be checked, then don't.
 # PLEASE DON'T SET THIS.  ANY PLACES THAT SET THIS WITHOUT
 # GOOD REASON WILL HAVE IT REMOVED.
diff --git a/core/binary.mk b/core/binary.mk
index 71c49ed..8685060 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -90,6 +90,15 @@
 endif
 endif
 
+# Add static HAL libraries
+ifdef LOCAL_HAL_STATIC_LIBRARIES
+$(foreach lib, $(LOCAL_HAL_STATIC_LIBRARIES), \
+    $(eval b_lib := $(filter $(lib).%,$(BOARD_HAL_STATIC_LIBRARIES)))\
+    $(if $(b_lib), $(eval LOCAL_STATIC_LIBRARIES += $(b_lib)),\
+                   $(eval LOCAL_STATIC_LIBRARIES += $(lib).default)))
+b_lib :=
+endif
+
 ifeq ($(strip $(LOCAL_ADDRESS_SANITIZER)),true)
   LOCAL_CLANG := true
   LOCAL_CFLAGS += $(ADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS)
@@ -147,21 +156,17 @@
 ifdef LOCAL_SDK_VERSION
 my_target_project_includes :=
 my_target_c_includes := $(my_ndk_stl_include_path) $(my_ndk_version_root)/usr/include
-
-# filter out including of AndroidConfig.h in system/core.
-TARGET_GLOBAL_CFLAGS_NO_ANDCONF ?= $(subst $(TARGET_ANDROID_CONFIG_CFLAGS),,\
-    $(TARGET_GLOBAL_CFLAGS))
-my_target_global_cflags := $(TARGET_GLOBAL_CFLAGS_NO_ANDCONF)
 else
 my_target_project_includes := $(TARGET_PROJECT_INCLUDES)
 my_target_c_includes := $(TARGET_C_INCLUDES)
-ifeq ($(strip $(LOCAL_CLANG)),true)
-my_target_c_includes += $(CLANG_CONFIG_EXTRA_TARGET_C_INCLUDES)
+endif # LOCAL_SDK_VERSION
+
+ifeq ($(LOCAL_CLANG),true)
 my_target_global_cflags := $(TARGET_GLOBAL_CLANG_FLAGS)
+my_target_c_includes += $(CLANG_CONFIG_EXTRA_TARGET_C_INCLUDES)
 else
 my_target_global_cflags := $(TARGET_GLOBAL_CFLAGS)
 endif # LOCAL_CLANG
-endif # LOCAL_SDK_VERSION
 
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_PROJECT_INCLUDES := $(my_target_project_includes)
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_TARGET_C_INCLUDES := $(my_target_c_includes)
@@ -627,7 +632,7 @@
 
 # some rules depend on asm_objects being first.  If your code depends on
 # being first, it's reasonable to require it to be assembly
-all_objects := \
+normal_objects := \
     $(asm_objects) \
     $(cpp_objects) \
     $(gen_cpp_objects) \
@@ -638,8 +643,9 @@
     $(yacc_objects) \
     $(lex_objects) \
     $(proto_generated_objects) \
-    $(addprefix $(TOPDIR)$(LOCAL_PATH)/,$(LOCAL_PREBUILT_OBJ_FILES)) \
-    $(gen_o_objects)
+    $(addprefix $(TOPDIR)$(LOCAL_PATH)/,$(LOCAL_PREBUILT_OBJ_FILES))
+
+all_objects := $(normal_objects) $(gen_o_objects)
 
 LOCAL_C_INCLUDES += $(TOPDIR)$(LOCAL_PATH) $(intermediates)
 
@@ -647,9 +653,12 @@
   LOCAL_C_INCLUDES += $(JNI_H_INCLUDE)
 endif
 
-# .o files need to be filtered out of LOCAL_GENERATED_SOURCES
-# to avoid creating circular dependencies.
-$(all_objects) : | $(filter-out %.o,$(LOCAL_GENERATED_SOURCES)) $(import_includes)
+# all_objects includes gen_o_objects which were part of LOCAL_GENERATED_SOURCES;
+# use normal_objects here to avoid creating circular dependencies. This assumes
+# that custom build rules which generate .o files don't consume other generated
+# sources as input (or if they do they take care of that dependency themselves).
+$(normal_objects) : | $(LOCAL_GENERATED_SOURCES)
+$(all_objects) : | $(import_includes)
 ALL_C_CPP_ETC_OBJECTS += $(all_objects)
 
 ###########################################################
diff --git a/core/build_id.mk b/core/build_id.mk
index e954794..64ad133 100644
--- a/core/build_id.mk
+++ b/core/build_id.mk
@@ -13,20 +13,11 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
-
-#
-# Defines branch-specific values.
-#
-
 # BUILD_ID is usually used to specify the branch name
 # (like "MAIN") or a branch name and a release candidate
-# (like "TC1-RC5").  It must be a single word, and is
+# (like "CRB01").  It must be a single word, and is
 # capitalized by convention.
-#
-BUILD_ID := OPENMASTER
 
-# DISPLAY_BUILD_NUMBER should only be set for development branches,
-# If set, the BUILD_NUMBER (cl) is appended to the BUILD_ID for
-# a more descriptive BUILD_ID_DISPLAY, otherwise BUILD_ID_DISPLAY
-# is the same as BUILD_ID
+BUILD_ID := KK
+
 DISPLAY_BUILD_NUMBER := true
diff --git a/core/cleanbuild.mk b/core/cleanbuild.mk
index 1d17f77..fa67332 100644
--- a/core/cleanbuild.mk
+++ b/core/cleanbuild.mk
@@ -14,7 +14,7 @@
 #
 
 # Don't bother with the cleanspecs if you are running mm/mmm
-ifndef ONE_SHOT_MAKEFILE
+ifeq ($(ONE_SHOT_MAKEFILE)$(dont_bother),)
 
 INTERNAL_CLEAN_STEPS :=
 
@@ -100,7 +100,7 @@
 INTERNAL_CLEAN_STEPS :=
 INTERNAL_CLEAN_BUILD_VERSION :=
 
-endif  # ifndef ONE_SHOT_MAKEFILE
+endif  # if not ONE_SHOT_MAKEFILE dont_bother
 
 # Since products and build variants (unfortunately) share the same
 # PRODUCT_OUT staging directory, things can get out of sync if different
@@ -182,6 +182,7 @@
 	$(PRODUCT_OUT)/*.txt \
 	$(PRODUCT_OUT)/*.xlb \
 	$(PRODUCT_OUT)/*.zip \
+	$(PRODUCT_OUT)/kernel \
 	$(PRODUCT_OUT)/data \
 	$(PRODUCT_OUT)/obj/APPS \
 	$(PRODUCT_OUT)/obj/NOTICE_FILES \
diff --git a/core/cleanspec.mk b/core/cleanspec.mk
index d4a8eed..500ce54 100644
--- a/core/cleanspec.mk
+++ b/core/cleanspec.mk
@@ -64,6 +64,6 @@
 # ************************************************
 
 subdir_cleanspecs := \
-    $(shell build/tools/findleaves.py --prune=out --prune=.repo --prune=.git . CleanSpec.mk)
+    $(shell build/tools/findleaves.py --prune=$(OUT_DIR) --prune=.repo --prune=.git . CleanSpec.mk)
 include $(subdir_cleanspecs)
 subdir_cleanspecs :=
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index 7530ea8..0a3517b 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -11,6 +11,7 @@
 LOCAL_BUILT_MODULE_STEM:=
 OVERRIDE_BUILT_MODULE_PATH:=
 LOCAL_INSTALLED_MODULE:=
+LOCAL_INSTALLED_MODULE_STEM:=
 LOCAL_UNINSTALLABLE_MODULE:=
 LOCAL_INTERMEDIATE_TARGETS:=
 LOCAL_UNSTRIPPED_PATH:=
@@ -102,7 +103,7 @@
 LOCAL_SDK_RES_VERSION:=
 LOCAL_NDK_STL_VARIANT:=
 LOCAL_EMMA_INSTRUMENT:=
-LOCAL_PROGUARD_ENABLED:= # '',full,custom,nosystem,disabled
+LOCAL_PROGUARD_ENABLED:= # '',full,custom,nosystem,disabled,obfuscation,optimization
 LOCAL_PROGUARD_FLAGS:=
 LOCAL_PROGUARD_FLAG_FILES:=
 LOCAL_EMMA_COVERAGE_FILTER:=
@@ -123,12 +124,14 @@
 LOCAL_PROTO_JAVA_OUTPUT_PARAMS:=
 LOCAL_NO_CRT:=
 LOCAL_PROPRIETARY_MODULE:=
+LOCAL_PRIVILEGED_MODULE:=
 LOCAL_MODULE_OWNER:=
 LOCAL_CTS_TEST_PACKAGE:=
 LOCAL_CTS_TEST_RUNNER:=
 LOCAL_CLANG:=
 LOCAL_ADDRESS_SANITIZER:=
 LOCAL_JAR_EXCLUDE_FILES:=
+LOCAL_JAR_PACKAGES:=
 LOCAL_LINT_FLAGS:=
 LOCAL_SOURCE_FILES_ALL_GENERATED:= # '',true
 # Don't delete the META_INF dir when merging static Java libraries.
@@ -137,6 +140,7 @@
 LOCAL_PREBUILT_MODULE_FILE:=
 LOCAL_POST_INSTALL_CMD:=
 LOCAL_DIST_BUNDLED_BINARIES:=
+LOCAL_HAL_STATIC_LIBRARIES:=
 LOCAL_NO_SYNTAX_CHECK:=
 LOCAL_NO_STATIC_ANALYZER:=
 
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index 48f4898..8d012f3 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -93,6 +93,8 @@
   TARGET_thumb_CFLAGS += -marm -fno-omit-frame-pointer
 endif
 
+android_config_h := $(call select-android-config-h,linux-arm)
+
 TARGET_GLOBAL_CFLAGS += \
 			-msoft-float -fpic -fPIE \
 			-ffunction-sections \
@@ -103,11 +105,9 @@
 			-Werror=format-security \
 			-D_FORTIFY_SOURCE=2 \
 			-fno-short-enums \
-			$(arch_variant_cflags)
-
-android_config_h := $(call select-android-config-h,linux-arm)
-TARGET_ANDROID_CONFIG_CFLAGS := -include $(android_config_h) -I $(dir $(android_config_h))
-TARGET_GLOBAL_CFLAGS += $(TARGET_ANDROID_CONFIG_CFLAGS)
+			$(arch_variant_cflags) \
+			-include $(android_config_h) \
+			-I $(dir $(android_config_h))
 
 # The "-Wunused-but-set-variable" option often breaks projects that enable
 # "-Wall -Werror" due to a commom idiom "ALOGV(mesg)" where ALOGV is turned
diff --git a/core/combo/TARGET_linux-mips.mk b/core/combo/TARGET_linux-mips.mk
index de7ca5c..ba6e8cd 100644
--- a/core/combo/TARGET_linux-mips.mk
+++ b/core/combo/TARGET_linux-mips.mk
@@ -80,6 +80,8 @@
   TARGET_mips_CFLAGS += -fno-omit-frame-pointer
 endif
 
+android_config_h := $(call select-android-config-h,linux-mips)
+
 TARGET_GLOBAL_CFLAGS += \
 			$(TARGET_mips_CFLAGS) \
 			-Ulinux -U__unix -U__unix__ -Umips \
@@ -90,11 +92,9 @@
 			-Wa,--noexecstack \
 			-Werror=format-security \
 			-D_FORTIFY_SOURCE=2 \
-			$(arch_variant_cflags)
-
-android_config_h := $(call select-android-config-h,linux-mips)
-TARGET_ANDROID_CONFIG_CFLAGS := -include $(android_config_h) -I $(dir $(android_config_h))
-TARGET_GLOBAL_CFLAGS += $(TARGET_ANDROID_CONFIG_CFLAGS)
+			$(arch_variant_cflags) \
+			-include $(android_config_h) \
+			-I $(dir $(android_config_h))
 
 # This warning causes dalvik not to build with gcc 4.6+ and -Werror.
 # We cannot turn it off blindly since the option is not available
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index a6f9862..bcad1d3 100755
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -115,6 +115,8 @@
 endif
 KERNEL_HEADERS := $(KERNEL_HEADERS_COMMON) $(KERNEL_HEADERS_ARCH)
 
+android_config_h := $(call select-android-config-h,target_linux-x86)
+
 TARGET_GLOBAL_CFLAGS += \
 			-O2 \
 			-Ulinux \
@@ -132,11 +134,9 @@
 			-funswitch-loops \
 			-funwind-tables \
 			-fstack-protector \
-			-m32
-
-android_config_h := $(call select-android-config-h,target_linux-x86)
-TARGET_ANDROID_CONFIG_CFLAGS := -include $(android_config_h) -I $(dir $(android_config_h))
-TARGET_GLOBAL_CFLAGS += $(TARGET_ANDROID_CONFIG_CFLAGS)
+			-m32 \
+			-include $(android_config_h) \
+			-I $(dir $(android_config_h))
 
 # XXX: Not sure this is still needed. Must check with our toolchains.
 TARGET_GLOBAL_CPPFLAGS += \
diff --git a/core/combo/arch/arm/armv7-a-neon.mk b/core/combo/arch/arm/armv7-a-neon.mk
index 208c24c..1105330 100644
--- a/core/combo/arch/arm/armv7-a-neon.mk
+++ b/core/combo/arch/arm/armv7-a-neon.mk
@@ -9,12 +9,16 @@
 ifeq ($(TARGET_CPU_VARIANT),$(filter $(TARGET_CPU_VARIANT),cortex-a15 krait))
 	arch_variant_cflags := -mcpu=cortex-a15
 else
+ifeq ($(strip $(TARGET_CPU_VARIANT)),cortex-a8)
+	arch_variant_cflags := -mcpu=cortex-a8
+else
 ifeq ($(strip $(TARGET_CPU_VARIANT)),cortex-a7)
 	arch_variant_cflags := -mcpu=cortex-a7
 else
 	arch_variant_cflags := -march=armv7-a
 endif
 endif
+endif
 
 arch_variant_cflags += \
     -mfloat-abi=softfp \
diff --git a/core/config.mk b/core/config.mk
index 2a84b34..b6111f2 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -123,7 +123,7 @@
 
 # ---------------------------------------------------------------
 # Try to include buildspec.mk, which will try to set stuff up.
-# If this file doesn't exist, the environemnt variables will
+# If this file doesn't exist, the environment variables will
 # be used, and if that doesn't work, then the default is an
 # arm build
 ifndef ANDROID_BUILDSPEC
@@ -159,6 +159,26 @@
 TARGET_DEVICE_DIR := $(patsubst %/,%,$(dir $(board_config_mk)))
 board_config_mk :=
 
+# Perhaps we should move this block to build/core/Makefile,
+# once we don't have TARGET_NO_KERNEL reference in AndroidBoard.mk/Android.mk.
+ifneq ($(strip $(TARGET_NO_BOOTLOADER)),true)
+  INSTALLED_BOOTLOADER_MODULE := $(PRODUCT_OUT)/bootloader
+  ifeq ($(strip $(TARGET_BOOTLOADER_IS_2ND)),true)
+    INSTALLED_2NDBOOTLOADER_TARGET := $(PRODUCT_OUT)/2ndbootloader
+  else
+    INSTALLED_2NDBOOTLOADER_TARGET :=
+  endif
+else
+  INSTALLED_BOOTLOADER_MODULE :=
+  INSTALLED_2NDBOOTLOADER_TARGET :=
+endif # TARGET_NO_BOOTLOADER
+ifneq ($(strip $(TARGET_NO_KERNEL)),true)
+  INSTALLED_KERNEL_TARGET := $(PRODUCT_OUT)/kernel
+else
+  INSTALLED_KERNEL_TARGET :=
+endif
+
+
 # The build system exposes several variables for where to find the kernel
 # headers:
 #   TARGET_DEVICE_KERNEL_HEADERS is automatically created for the current
@@ -443,6 +463,11 @@
 TARGET_GLOBAL_CFLAGS += $(TARGET_RELEASE_CFLAGS)
 TARGET_GLOBAL_CPPFLAGS += $(TARGET_RELEASE_CPPFLAGS)
 
+# allow overriding default Java libraries on a per-target basis
+ifeq ($(TARGET_DEFAULT_JAVA_LIBRARIES),)
+  TARGET_DEFAULT_JAVA_LIBRARIES := core core-junit ext framework framework2
+endif
+
 # define llvm tools and global flags
 include $(BUILD_SYSTEM)/llvm_config.mk
 
diff --git a/core/copy_headers.mk b/core/copy_headers.mk
index dac07d5..e16560f 100644
--- a/core/copy_headers.mk
+++ b/core/copy_headers.mk
@@ -15,7 +15,9 @@
 $(foreach header,$(LOCAL_COPY_HEADERS), \
   $(eval _chFrom := $(LOCAL_PATH)/$(header)) \
   $(eval _chTo := \
-      $($(my_prefix)OUT_HEADERS)/$(LOCAL_COPY_HEADERS_TO)/$(notdir $(header))) \
+      $(if $(LOCAL_COPY_HEADERS_TO),\
+        $($(my_prefix)OUT_HEADERS)/$(LOCAL_COPY_HEADERS_TO)/$(notdir $(header)),\
+        $($(my_prefix)OUT_HEADERS)/$(notdir $(header)))) \
   $(eval $(call copy-one-header,$(_chFrom),$(_chTo))) \
   $(eval all_copied_headers: $(_chTo)) \
  )
diff --git a/core/definitions.mk b/core/definitions.mk
index 3d19e72..290bb2f 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -147,7 +147,7 @@
 # $(1): directory to search under
 # Ignores $(1)/Android.mk
 define first-makefiles-under
-$(shell build/tools/findleaves.py --prune=out --prune=.repo --prune=.git \
+$(shell build/tools/findleaves.py --prune=$(OUT_DIR) --prune=.repo --prune=.git \
         --mindepth=2 $(1) Android.mk)
 endef
 
@@ -1511,6 +1511,10 @@
     -name $(word 1, $(PRIVATE_JAR_EXCLUDE_FILES)) \
     $(addprefix -o -name , $(wordlist 2, 999, $(PRIVATE_JAR_EXCLUDE_FILES))) \
     | xargs rm -rf)
+$(if $(PRIVATE_JAR_PACKAGES), $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -mindepth 1 -type d \
+    $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
+        -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))) \
+    | xargs rm -rf)
 $(hide) jar $(if $(strip $(PRIVATE_JAR_MANIFEST)),-cfm,-cf) \
     $@ $(PRIVATE_JAR_MANIFEST) -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .
 endef
@@ -1558,6 +1562,10 @@
     -name $(word 1, $(PRIVATE_JAR_EXCLUDE_FILES)) \
     $(addprefix -o -name , $(wordlist 2, 999, $(PRIVATE_JAR_EXCLUDE_FILES))) \
     | xargs rm -rf)
+$(if $(PRIVATE_JAR_PACKAGES), $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -mindepth 1 -type d \
+    $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
+        -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))) \
+    | xargs rm -rf)
 $(hide) jar $(if $(strip $(PRIVATE_JAR_MANIFEST)),-cfm,-cf) \
     $@ $(PRIVATE_JAR_MANIFEST) -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .
 $(hide) mv $(PRIVATE_CLASS_INTERMEDIATES_DIR)/newstamp $(PRIVATE_CLASS_INTERMEDIATES_DIR)/stamp
@@ -1716,35 +1724,6 @@
 endef
 
 ###########################################################
-## Obfuscate a jar file
-###########################################################
-
-# PRIVATE_KEEP_FILE is a file containing a list of classes
-# PRIVATE_INTERMEDIATES_DIR is a directory we can use for temporary files
-# The module using this must depend on
-#        $(HOST_OUT_JAVA_LIBRARIES)/proguard-4.0.1.jar
-define obfuscate-jar
-@echo "Obfuscate jar: $(notdir $@) ($@)"
-@mkdir -p $(dir $@)
-@rm -f $@
-@mkdir -p $(PRIVATE_INTERMEDIATES_DIR)
-$(hide) sed -e 's/^/-keep class /' < $(PRIVATE_KEEP_FILE) > \
-		$(PRIVATE_INTERMEDIATES_DIR)/keep.pro
-$(hide) java -Xmx512M -jar $(HOST_OUT_JAVA_LIBRARIES)/proguard-4.0.1.jar \
-		-injars $< \
-		-outjars $@ \
-		-target 1.5 \
-		-dontnote -dontwarn \
-		-printmapping $(PRIVATE_INTERMEDIATES_DIR)/out.map \
-		-forceprocessing \
-		-renamesourcefileattribute SourceFile \
-		-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,*Annotation*,EnclosingMethod \
-		-repackageclasses \
-		-keepclassmembers "class * { public protected *; }" \
-		@$(PRIVATE_INTERMEDIATES_DIR)/keep.pro
-endef
-
-###########################################################
 ## Commands for copying files
 ###########################################################
 
@@ -1887,34 +1866,11 @@
 ###########################################################
 ## Commands to call Proguard
 ###########################################################
-
-# Command to copy the file with acp, if proguard is disabled.
-define proguard-disabled-commands
-@echo Copying: $@
-$(hide) $(ACP) -fp $< $@
-endef
-
-# Command to call Proguard
-# $(1): extra flags for instrumentation.
-define proguard-enabled-commands
-@echo Proguard: $@
-$(hide) $(PROGUARD) -injars $< -outjars $@ $(PRIVATE_PROGUARD_FLAGS) $(1)
-endef
-
-# Figure out the proguard dictionary file of the module that is instrumentationed for.
-define get-instrumentation-proguard-flags
-$(if $(PRIVATE_INSTRUMENTATION_FOR),$(if $(ALL_MODULES.$(PRIVATE_INSTRUMENTATION_FOR).PROGUARD_ENABLED),-applymapping $(call intermediates-dir-for,APPS,$(PRIVATE_INSTRUMENTATION_FOR),,COMMON)/proguard_dictionary))
-endef
-
 define transform-jar-to-proguard
-$(eval _instrumentation_proguard_flags:=$(call get-instrumentation-proguard-flags))
-$(eval _enable_proguard:=$(PRIVATE_PROGUARD_ENABLED)$(_instrumentation_proguard_flags))
-$(if $(_enable_proguard),$(call proguard-enabled-commands,$(_instrumentation_proguard_flags)),$(call proguard-disabled-commands))
-$(eval _instrumentation_proguard_flags:=)
-$(eval _enable_proguard:=)
+@echo Proguard: $@
+$(hide) $(PROGUARD) -injars $< -outjars $@ $(PRIVATE_PROGUARD_FLAGS)
 endef
 
-
 ###########################################################
 ## Stuff source generated from one-off tools
 ###########################################################
diff --git a/core/dex_preopt.mk b/core/dex_preopt.mk
index 0c9904a..e2e76b8 100644
--- a/core/dex_preopt.mk
+++ b/core/dex_preopt.mk
@@ -3,9 +3,9 @@
 #
 ####################################
 
-# TODO: replace it with device's BOOTCLASSPATH
-DEXPREOPT_BOOT_JARS := core:conscrypt:okhttp:core-junit:bouncycastle:ext:framework:telephony-common:voip-common:mms-common:android.policy:services:apache-xml
+DEXPREOPT_BOOT_JARS := $(PRODUCT_BOOT_JARS)
 DEXPREOPT_BOOT_JARS_MODULES := $(subst :, ,$(DEXPREOPT_BOOT_JARS))
+PRODUCT_BOOTCLASSPATH := $(subst $(space),:,$(foreach m,$(DEXPREOPT_BOOT_JARS_MODULES),/system/framework/$(m).jar))
 
 DEXPREOPT_BUILD_DIR := $(OUT_DIR)
 DEXPREOPT_PRODUCT_DIR := $(patsubst $(DEXPREOPT_BUILD_DIR)/%,%,$(PRODUCT_OUT))/dex_bootjars
@@ -56,7 +56,9 @@
 
 $(_dbj_jar_no_dex) : $(_dbj_src_jar) | $(ACP) $(AAPT)
 	$$(call copy-file-to-target)
+ifneq ($(DEX_PREOPT_DEFAULT),nostripping)
 	$$(call dexpreopt-remove-classes.dex,$$@)
+endif
 
 $(eval _dbj_jar :=)
 $(eval _dbj_odex :=)
diff --git a/core/droiddoc.mk b/core/droiddoc.mk
index 8a5c556..0d3094d 100644
--- a/core/droiddoc.mk
+++ b/core/droiddoc.mk
@@ -69,7 +69,7 @@
     LOCAL_JAVA_LIBRARIES := sdk_v$(LOCAL_SDK_VERSION) $(LOCAL_JAVA_LIBRARIES)
   endif
 else
-  LOCAL_JAVA_LIBRARIES := core ext framework $(LOCAL_JAVA_LIBRARIES)
+  LOCAL_JAVA_LIBRARIES := core ext framework framework2 $(LOCAL_JAVA_LIBRARIES)
 endif  # LOCAL_SDK_VERSION
 LOCAL_JAVA_LIBRARIES := $(sort $(LOCAL_JAVA_LIBRARIES))
 
diff --git a/core/dynamic_binary.mk b/core/dynamic_binary.mk
index 6ede57f..7778477 100644
--- a/core/dynamic_binary.mk
+++ b/core/dynamic_binary.mk
@@ -26,12 +26,17 @@
 # TODO: This duplicates logic from base_rules.mk because we need to
 #       know its results before base_rules.mk is included.
 #       Consolidate the duplicates.
-LOCAL_MODULE_STEM := $(strip $(LOCAL_MODULE_STEM))
-ifeq ($(LOCAL_MODULE_STEM),)
+ifndef LOCAL_MODULE_STEM
   LOCAL_MODULE_STEM := $(LOCAL_MODULE)
 endif
-LOCAL_INSTALLED_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
-LOCAL_BUILT_MODULE_STEM := $(LOCAL_INSTALLED_MODULE_STEM)
+
+ifndef LOCAL_BUILT_MODULE_STEM
+  LOCAL_BUILT_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
+endif
+
+ifndef LOCAL_INSTALLED_MODULE_STEM
+  LOCAL_INSTALLED_MODULE_STEM := $(LOCAL_MODULE_STEM)$(LOCAL_MODULE_SUFFIX)
+endif
 
 # base_rules.make defines $(intermediates), but we need its value
 # before we include base_rules.  Make a guess, and verify that
@@ -90,7 +95,7 @@
 ## Store a copy with symbols for symbolic debugging
 ###########################################################
 symbolic_input := $(compress_output)
-symbolic_output := $(LOCAL_UNSTRIPPED_PATH)/$(LOCAL_BUILT_MODULE_STEM)
+symbolic_output := $(LOCAL_UNSTRIPPED_PATH)/$(LOCAL_INSTALLED_MODULE_STEM)
 $(symbolic_output) : $(symbolic_input) | $(ACP)
 	@echo "target Symbolic: $(PRIVATE_MODULE) ($@)"
 	$(copy-file-to-target)
diff --git a/core/envsetup.mk b/core/envsetup.mk
index f861586..8ac437e 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -196,6 +196,7 @@
 TARGET_OUT_SHARED_LIBRARIES:= $(TARGET_OUT)/lib
 TARGET_OUT_JAVA_LIBRARIES:= $(TARGET_OUT)/framework
 TARGET_OUT_APPS:= $(TARGET_OUT)/app
+TARGET_OUT_APPS_PRIVILEGED := $(TARGET_OUT)/priv-app
 TARGET_OUT_KEYLAYOUT := $(TARGET_OUT)/usr/keylayout
 TARGET_OUT_KEYCHARS := $(TARGET_OUT)/usr/keychars
 TARGET_OUT_ETC := $(TARGET_OUT)/etc
@@ -211,6 +212,7 @@
 TARGET_OUT_DATA_KEYCHARS := $(TARGET_OUT_KEYCHARS)
 TARGET_OUT_DATA_ETC := $(TARGET_OUT_ETC)
 TARGET_OUT_DATA_NATIVE_TESTS := $(TARGET_OUT_DATA)/nativetest
+TARGET_OUT_DATA_FAKE := $(TARGET_OUT_DATA)/fake_packages
 
 TARGET_OUT_CACHE := $(PRODUCT_OUT)/cache
 
diff --git a/core/help.mk b/core/help.mk
index 9e37f82..6e0b2c0 100644
--- a/core/help.mk
+++ b/core/help.mk
@@ -14,13 +14,6 @@
 # limitations under the License.
 #
 
-ifeq ($(MAKECMDGOALS),help)
-dont_bother := true
-endif
-ifeq ($(MAKECMDGOALS),out)
-dont_bother := true
-endif
-
 .PHONY: help
 help:
 	@echo
@@ -39,4 +32,3 @@
 .PHONY: out
 out:
 	@echo "I'm sure you're nice and all, but no thanks."
-
diff --git a/core/host_java_library.mk b/core/host_java_library.mk
index 02274e4..391050c 100644
--- a/core/host_java_library.mk
+++ b/core/host_java_library.mk
@@ -23,14 +23,32 @@
 LOCAL_IS_HOST_MODULE := true
 LOCAL_BUILT_MODULE_STEM := javalib.jar
 
-ifeq ($(LOCAL_BUILD_HOST_DEX),true)
-ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
-  LOCAL_JAVA_LIBRARIES := $(sort core-hostdex $(LOCAL_JAVA_LIBRARIES))
+# base_rules.mk looks at this
+all_res_assets :=
+
+proto_sources := $(filter %.proto,$(LOCAL_SRC_FILES))
+ifneq ($(proto_sources),)
+ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),micro)
+    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-2.3.0-micro
+else
+  ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
+    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-2.3.0-nano
+  else
+    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-2.3.0-lite
+  endif
+endif
 endif
 
 intermediates := $(call local-intermediates-dir)
 intermediates.COMMON := $(call local-intermediates-dir,COMMON)
 
+LOCAL_INTERMEDIATE_SOURCE_DIR := $(intermediates.COMMON)/src
+
+ifeq ($(LOCAL_BUILD_HOST_DEX),true)
+ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
+  LOCAL_JAVA_LIBRARIES +=  core-hostdex
+endif
+
 full_classes_compiled_jar := $(intermediates.COMMON)/classes-full-debug.jar
 full_classes_jarjar_jar := $(intermediates.COMMON)/classes-jarjar.jar
 full_classes_jar := $(intermediates.COMMON)/classes.jar
@@ -42,13 +60,15 @@
     $(full_classes_jar) \
     $(built_dex)
 
-LOCAL_INTERMEDIATE_SOURCE_DIR := $(intermediates.COMMON)/src
 # See comment in java.mk
 java_alternative_checked_module := $(full_classes_compiled_jar)
-
 endif # LOCAL_BUILD_HOST_DEX
 
+LOCAL_JAVA_LIBRARIES := $(sort $(LOCAL_JAVA_LIBRARIES))
+
+#######################################
 include $(BUILD_SYSTEM)/base_rules.mk
+#######################################
 
 $(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
 
@@ -70,13 +90,13 @@
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES :=
 $(full_classes_compiled_jar): $(java_sources) $(java_resource_sources) $(full_java_lib_deps) \
-        $(jar_manifest_file) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+        $(jar_manifest_file) $(proto_java_sources_file_stamp) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-host-java-to-package)
 
 # Run jarjar if necessary, otherwise just copy the file.
 ifneq ($(strip $(LOCAL_JARJAR_RULES)),)
 $(full_classes_jarjar_jar): PRIVATE_JARJAR_RULES := $(LOCAL_JARJAR_RULES)
-$(full_classes_jarjar_jar): $(full_classes_compiled_jar) | $(JARJAR)
+$(full_classes_jarjar_jar): $(full_classes_compiled_jar) $(LOCAL_JARJAR_RULES) | $(JARJAR)
 	@echo JarJar: $@
 	$(hide) java -jar $(JARJAR) process $(PRIVATE_JARJAR_RULES) $< $@
 else
@@ -109,6 +129,6 @@
 $(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) \
-		$(jar_manifest_file) $(LOCAL_ADDITIONAL_DEPENDENCIES)
+		$(jar_manifest_file) $(proto_java_sources_file_stamp) $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-host-java-to-package)
 endif  # LOCAL_BUILD_HOST_DEX
diff --git a/core/java.mk b/core/java.mk
index f43bf3b..f237965 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -12,16 +12,6 @@
 endif # !PDK_JAVA
 endif #PDK
 
-
-# Make sure there's something to build.
-# It's possible to build a package that doesn't contain any classes.
-# LOCAL_SOURCE_FILES_ALL_GENERATED is set only if the module does not have static source files,
-# but generated source files in its LOCAL_INTERMEDIATE_SOURCE_DIR.
-# You have to set up the dependency in some other way.
-ifeq (,$(strip $(LOCAL_SRC_FILES)$(all_res_assets)$(LOCAL_STATIC_JAVA_LIBRARIES))$(filter true,$(LOCAL_SOURCE_FILES_ALL_GENERATED)))
-$(warning $(LOCAL_PATH): Target java module does not define any source or resource files)
-endif
-
 LOCAL_NO_STANDARD_LIBRARIES:=$(strip $(LOCAL_NO_STANDARD_LIBRARIES))
 LOCAL_SDK_VERSION:=$(strip $(LOCAL_SDK_VERSION))
 
@@ -43,7 +33,7 @@
   endif
 else
   ifneq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
-    LOCAL_JAVA_LIBRARIES := core core-junit ext framework $(LOCAL_JAVA_LIBRARIES)
+    LOCAL_JAVA_LIBRARIES := $(TARGET_DEFAULT_JAVA_LIBRARIES) $(LOCAL_JAVA_LIBRARIES)
   endif
 endif
 
@@ -88,23 +78,14 @@
 built_dex_intermediate_leaf := classes-with-local.dex
 endif
 
-LOCAL_PROGUARD_ENABLED:=$(strip $(LOCAL_PROGUARD_ENABLED))
 ifeq ($(LOCAL_PROGUARD_ENABLED),disabled)
 LOCAL_PROGUARD_ENABLED :=
 endif
 
-# By giving different file name, files can be updated correctly when switching
-# between builds with and without Proguard enabled.
-# Note that ANY intermediate targets between the proguard and
-# the final built_dex should be differently named!
 ifdef LOCAL_PROGUARD_ENABLED
 proguard_jar_leaf := proguard.classes.jar
-built_dex_intermediate_leaf := proguard.$(built_dex_intermediate_leaf)
-built_dex_leaf := proguard.classes.dex
 else
 proguard_jar_leaf := noproguard.classes.jar
-built_dex_intermediate_leaf := noproguard.$(built_dex_intermediate_leaf)
-built_dex_leaf := noproguard.classes.dex
 endif
 
 full_classes_compiled_jar := $(intermediates.COMMON)/$(full_classes_compiled_jar_leaf)
@@ -118,9 +99,14 @@
 built_dex_intermediate := $(intermediates.COMMON)/$(built_dex_intermediate_leaf)
 full_classes_stubs_jar := $(intermediates.COMMON)/stubs.jar
 
-# full_classes_jar and built_dex are cleared below, and re-set if we really need them.
+ifeq ($(LOCAL_MODULE_CLASS)$(LOCAL_SRC_FILES)$(LOCAL_STATIC_JAVA_LIBRARIES)$(LOCAL_SOURCE_FILES_ALL_GENERATED),APPS)
+# If this is an apk without any Java code (e.g. framework-res), we should skip compiling Java.
+full_classes_jar :=
+built_dex :=
+else
 full_classes_jar := $(intermediates.COMMON)/classes.jar
-built_dex := $(intermediates.COMMON)/$(built_dex_leaf)
+built_dex := $(intermediates.COMMON)/classes.dex
+endif
 
 LOCAL_INTERMEDIATE_TARGETS += \
     $(full_classes_compiled_jar) \
@@ -249,7 +235,11 @@
 # to fail except for bugs in their respective tools.  If you would
 # like to run these rules, add the "all" modifier goal to the make
 # command line.
+ifdef full_classes_jar
 java_alternative_checked_module := $(full_classes_compiled_jar)
+else
+java_alternative_checked_module :=
+endif
 
 # TODO: It looks like the only thing we need from base_rules is
 # all_java_sources.  See if we can get that by adding a
@@ -262,6 +252,13 @@
 
 java_alternative_checked_module :=
 
+# Make sure there's something to build.
+ifdef full_classes_jar
+ifndef need_compile_java
+$(error $(LOCAL_PATH): Target java module does not define any source or resource files)
+endif
+endif
+
 # Install the RS compatibility libraries to /system/lib/ if necessary
 ifdef rs_compatibility_jni_libs
 installed_rs_compatibility_jni_libs := $(addprefix $(TARGET_OUT_SHARED_LIBRARIES)/,\
@@ -297,19 +294,7 @@
 # properly.
 $(cleantarget): PRIVATE_CLEAN_FILES += $(intermediates.COMMON)
 
-# If the module includes java code (i.e., it's not framework-res), compile it.
-full_classes_jar :=
-built_dex :=
-# need_compile_java is set in base_rules.mk
-ifeq ($(need_compile_java),true)
-
-# If LOCAL_BUILT_MODULE_STEM wasn't overridden by our caller,
-# full_classes_jar will be the same module as LOCAL_BUILT_MODULE.
-# Otherwise, the caller will define it as a prerequisite of
-# LOCAL_BUILT_MODULE, so it will inherit the necessary PRIVATE_*
-# variable definitions.
-full_classes_jar := $(intermediates.COMMON)/classes.jar
-built_dex := $(intermediates.COMMON)/$(built_dex_leaf)
+ifdef full_classes_jar
 
 # Droiddoc isn't currently able to generate stubs for modules, so we're just
 # allowing it to use the classes.jar as the "stubs" that would be use to link
@@ -337,6 +322,7 @@
 # via deps on the target that generates the sources.
 $(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES := $(LOCAL_JAR_EXCLUDE_FILES)
+$(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES := $(LOCAL_JAR_PACKAGES)
 $(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) \
@@ -348,7 +334,7 @@
 # Run jarjar if necessary, otherwise just copy the file.
 ifneq ($(strip $(LOCAL_JARJAR_RULES)),)
 $(full_classes_jarjar_jar): PRIVATE_JARJAR_RULES := $(LOCAL_JARJAR_RULES)
-$(full_classes_jarjar_jar): $(full_classes_compiled_jar) | $(JARJAR)
+$(full_classes_jarjar_jar): $(full_classes_compiled_jar) $(LOCAL_JARJAR_RULES) | $(JARJAR)
 	@echo JarJar: $@
 	$(hide) java -jar $(JARJAR) process $(PRIVATE_JARJAR_RULES) $< $@
 else
@@ -386,42 +372,75 @@
 	$(hide) $(ACP) -fp $< $@
 
 # Run proguard if necessary, otherwise just copy the file.
+ifdef LOCAL_PROGUARD_ENABLED
+ifneq ($(filter-out full custom nosystem obfuscation optimization,$(LOCAL_PROGUARD_ENABLED)),)
+    $(warning while processing: $(LOCAL_MODULE))
+    $(error invalid value for LOCAL_PROGUARD_ENABLED: $(LOCAL_PROGUARD_ENABLED))
+endif
 proguard_dictionary := $(intermediates.COMMON)/proguard_dictionary
-# Proguard doesn't like a class in both library and the jar to be processed.
-proguard_full_java_libs := $(filter-out $(full_static_java_libs),$(full_java_libs))
-proguard_flags := $(addprefix -libraryjars ,$(proguard_full_java_libs)) \
+proguard_flags := $(addprefix -libraryjars ,$(full_shared_java_libs)) \
                   -forceprocessing \
                   -printmapping $(proguard_dictionary)
-ifneq ($(LOCAL_PROGUARD_ENABLED),nosystem)
+
+ifeq ($(filter nosystem,$(LOCAL_PROGUARD_ENABLED)),)
 proguard_flags += -include $(BUILD_SYSTEM)/proguard.flags
 ifeq ($(LOCAL_EMMA_INSTRUMENT),true)
 proguard_flags += -include $(BUILD_SYSTEM)/proguard.emma.flags
 endif
 # If this is a test package, add proguard keep flags for tests.
-ifneq ($(strip $(LOCAL_INSTRUMENTATION_FOR)$(filter tests,$(LOCAL_MODULE_TAGS))$(filter android.test.runner,$(LOCAL_JAVA_LIBRARIES))),)
-proguard_flags := $(proguard_flags) -include $(BUILD_SYSTEM)/proguard_tests.flags
+ifneq ($(LOCAL_INSTRUMENTATION_FOR)$(filter tests,$(LOCAL_MODULE_TAGS)),)
+proguard_flags += -include $(BUILD_SYSTEM)/proguard_tests.flags
 endif # test package
-else  # LOCAL_PROGUARD_ENABLED is nosystem
-proguard_flags += -include $(BUILD_SYSTEM)/proguard_basic_keeps.flags
-endif # LOCAL_PROGUARD_ENABLED is not nosystem
+ifeq ($(filter obfuscation,$(LOCAL_PROGUARD_ENABLED)),)
+# By default no obfuscation
+proguard_flags += -dontobfuscate
+endif  # No obfuscation
+ifeq ($(filter optimization,$(LOCAL_PROGUARD_ENABLED)),)
+# By default no optimization
+proguard_flags += -dontoptimize
+endif  # No optimization
 
-ifneq ($(LOCAL_PROGUARD_ENABLED),)
-ifeq ($(filter full custom nosystem, $(LOCAL_PROGUARD_ENABLED)),)
-    $(warning while processing: $(LOCAL_MODULE))
-    $(error invalid value for LOCAL_PROGUARD_ENABLED: $(LOCAL_PROGUARD_ENABLED))
-endif # not a legal value
-endif # LOCAL_PROGUARD_ENABLED
+ifdef LOCAL_INSTRUMENTATION_FOR
+ifeq ($(filter obfuscation,$(LOCAL_PROGUARD_ENABLED)),)
+# If no obfuscation, link in the instrmented package's classes.jar as a library.
+# link_instr_classes_jar is defined in base_rule.mk
+proguard_flags += -libraryjars $(link_instr_classes_jar)
+else # obfuscation
+# If obfuscation is enabled, the main app must be obfuscated too.
+# We need to run obfuscation using the main app's dictionary,
+# and treat the main app's class.jar as injars instead of libraryjars.
+proguard_flags := -injars  $(link_instr_classes_jar) \
+    -outjars $(intermediates.COMMON)/proguard.$(LOCAL_INSTRUMENTATION_FOR).jar \
+    -include $(link_instr_intermediates_dir.COMMON)/proguard_options \
+    -applymapping $(link_instr_intermediates_dir.COMMON)/proguard_dictionary \
+    -verbose \
+    $(proguard_flags)
+
+# Sometimes (test + main app) uses different keep rules from the main app -
+# apply the main app's dictionary anyway.
+proguard_flags += -ignorewarnings
+
+# Make sure we run Proguard on the main app first
+$(full_classes_proguard_jar) : $(link_instr_intermediates_dir.COMMON)/proguard.classes.jar
+
+endif # no obfuscation
+endif # LOCAL_INSTRUMENTATION_FOR
+endif  # LOCAL_PROGUARD_ENABLED is not nosystem
 
 proguard_flag_files := $(addprefix $(LOCAL_PATH)/, $(LOCAL_PROGUARD_FLAG_FILES))
 LOCAL_PROGUARD_FLAGS += $(addprefix -include , $(proguard_flag_files))
 
-$(full_classes_proguard_jar): PRIVATE_PROGUARD_ENABLED:=$(LOCAL_PROGUARD_ENABLED)
 $(full_classes_proguard_jar): PRIVATE_PROGUARD_FLAGS := $(proguard_flags) $(LOCAL_PROGUARD_FLAGS)
-$(full_classes_proguard_jar): PRIVATE_INSTRUMENTATION_FOR:=$(strip $(LOCAL_INSTRUMENTATION_FOR))
 $(full_classes_proguard_jar) : $(full_classes_jar) $(proguard_flag_files) | $(ACP) $(PROGUARD)
 	$(call transform-jar-to-proguard)
 
-ALL_MODULES.$(LOCAL_MODULE).PROGUARD_ENABLED:=$(LOCAL_PROGUARD_ENABLED)
+else  # LOCAL_PROGUARD_ENABLED not defined
+$(full_classes_proguard_jar) : $(full_classes_jar)
+	@echo Copying: $@
+	$(hide) $(ACP) -fp $< $@
+
+endif # LOCAL_PROGUARD_ENABLED defined
+
 
 # Override PRIVATE_INTERMEDIATES_DIR so that install-dex-debug
 # will work even when intermediates != intermediates.COMMON.
@@ -472,4 +491,4 @@
 
 $(LOCAL_MODULE)-findbugs : $(findbugs_html)
 
-endif
+endif  # full_classes_jar is defined
diff --git a/core/java_library.mk b/core/java_library.mk
index 67c1bcb..4c6b652 100644
--- a/core/java_library.mk
+++ b/core/java_library.mk
@@ -18,10 +18,9 @@
 ifneq (,$(LOCAL_RESOURCE_DIR))
 $(error $(LOCAL_PATH): Target java libraries may not set LOCAL_RESOURCE_DIR)
 endif
-endif
-
-#xxx base_rules.mk looks at this
+# base_rules.mk looks at this
 all_res_assets :=
+endif
 
 LOCAL_BUILT_MODULE_STEM := javalib.jar
 
@@ -41,7 +40,7 @@
 ifeq (,$(TARGET_BUILD_APPS))
 ifeq (,$(LOCAL_APK_LIBRARIES))
 ifndef LOCAL_DEX_PREOPT
-LOCAL_DEX_PREOPT := true
+LOCAL_DEX_PREOPT := $(DEX_PREOPT_DEFAULT)
 endif
 endif
 endif
diff --git a/core/legacy_prebuilts.mk b/core/legacy_prebuilts.mk
index f767644..c477900 100644
--- a/core/legacy_prebuilts.mk
+++ b/core/legacy_prebuilts.mk
@@ -34,8 +34,6 @@
 	cdt.bin \
 	chat-ril \
 	cpcap-key.kl \
-	data \
-	dev \
 	egl.cfg \
 	firmware_error.565 \
 	firmware_install.565 \
@@ -45,13 +43,11 @@
 	gps.stingray.so \
 	gralloc.omap3.so \
 	gralloc.tegra.so \
-	hosts \
 	hwcomposer.tegra.so \
 	ime \
 	init.goldfish.rc \
 	init.goldfish.sh \
 	init.olympus.rc \
-	init.rc \
 	init.sholes.rc \
 	init.stingray.rc \
 	input \
@@ -76,23 +72,18 @@
 	pm \
 	pppd-ril \
 	pppd-ril.options \
-	proc \
 	qwerty.kl \
 	radio.img \
 	rdl.bin \
 	RFFspeed_501.bmd \
 	RFFstd_501.bmd \
 	savebpver \
-	sbin \
 	sholes-keypad.kl \
 	suplcerts.bks \
 	svc \
-	sys \
-	system \
 	tcmd \
 	ueventd.goldfish.rc \
 	ueventd.olympus.rc \
-	ueventd.rc \
 	ueventd.stingray.rc \
 	vold.fstab \
 	wl1271.bin
diff --git a/core/main.mk b/core/main.mk
index 282d9c3..d424b25 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -71,6 +71,22 @@
 .PHONY: FORCE
 FORCE:
 
+# These goals don't need to collect and include Android.mks/CleanSpec.mks
+# in the source tree.
+dont_bother_goals := clean clobber dataclean installclean \
+    help out \
+    snod systemimage-nodeps \
+    stnod systemtarball-nodeps \
+    userdataimage-nodeps userdatatarball-nodeps \
+    cacheimage-nodeps \
+    vendorimage-nodeps \
+    ramdisk-nodeps \
+    bootimage-nodeps
+
+ifneq ($(filter $(dont_bother_goals), $(MAKECMDGOALS)),)
+dont_bother := true
+endif
+
 # Targets that provide quick help on the build system.
 include $(BUILD_SYSTEM)/help.mk
 
@@ -84,21 +100,6 @@
 # be generated correctly
 include $(BUILD_SYSTEM)/cleanbuild.mk
 
-# These targets are going to delete stuff, don't bother including
-# the whole directory tree if that's all we're going to do
-ifeq ($(MAKECMDGOALS),clean)
-dont_bother := true
-endif
-ifeq ($(MAKECMDGOALS),clobber)
-dont_bother := true
-endif
-ifeq ($(MAKECMDGOALS),dataclean)
-dont_bother := true
-endif
-ifeq ($(MAKECMDGOALS),installclean)
-dont_bother := true
-endif
-
 # Include the google-specific config
 -include vendor/google/build/config.mk
 
@@ -183,6 +184,7 @@
 $(error stop)
 endif
 
+ifndef BUILD_EMULATOR
 ifeq (darwin,$(HOST_OS))
 GCC_REALPATH = $(realpath $(shell which $(HOST_CC)))
 ifneq ($(findstring llvm-gcc,$(GCC_REALPATH)),)
@@ -199,10 +201,11 @@
 else   # HOST_OS is not darwin
   BUILD_EMULATOR := true
 endif  # HOST_OS is darwin
+endif
 
 $(shell echo 'VERSIONS_CHECKED := $(VERSION_CHECK_SEQUENCE_NUMBER)' \
         > $(OUT_DIR)/versions_checked.mk)
-$(shell echo 'BUILD_EMULATOR := $(BUILD_EMULATOR)' \
+$(shell echo 'BUILD_EMULATOR ?= $(BUILD_EMULATOR)' \
         >> $(OUT_DIR)/versions_checked.mk)
 endif
 
@@ -357,7 +360,7 @@
 sdk_repo_goal := $(strip $(filter sdk_repo,$(MAKECMDGOALS)))
 MAKECMDGOALS := $(strip $(filter-out sdk_repo,$(MAKECMDGOALS)))
 
-ifneq ($(words $(filter-out $(INTERNAL_MODIFIER_TARGETS),$(MAKECMDGOALS))),1)
+ifneq ($(words $(filter-out $(INTERNAL_MODIFIER_TARGETS) checkbuild,$(MAKECMDGOALS))),1)
 $(error The 'sdk' target may not be specified with any other targets)
 endif
 
@@ -414,8 +417,6 @@
 endif
 
 # Bring in all modules that need to be built.
-ifneq ($(dont_bother),true)
-
 ifeq ($(HOST_OS)-$(HOST_ARCH),darwin-ppc)
 SDK_ONLY := true
 $(info Building the SDK under darwin-ppc is actually obsolete and unsupported.)
@@ -468,8 +469,15 @@
 NOTICE-HOST-%: ;
 NOTICE-TARGET-%: ;
 
+# A helper goal printing out install paths
+.PHONY: GET-INSTALL-PATH
+GET-INSTALL-PATH:
+	@$(foreach m, $(ALL_MODULES), $(if $(ALL_MODULES.$(m).INSTALLED), \
+		echo 'INSTALL-PATH: $(m) $(ALL_MODULES.$(m).INSTALLED)';))
+
 else # ONE_SHOT_MAKEFILE
 
+ifneq ($(dont_bother),true)
 #
 # Include all of the makefiles in the system
 #
@@ -477,9 +485,11 @@
 # Can't use first-makefiles-under here because
 # --mindepth=2 makes the prunes not work.
 subdir_makefiles := \
-	$(shell build/tools/findleaves.py --prune=out --prune=.repo --prune=.git $(subdirs) Android.mk)
+	$(shell build/tools/findleaves.py --prune=$(OUT_DIR) --prune=.repo --prune=.git $(subdirs) Android.mk)
 
-include $(subdir_makefiles)
+$(foreach mk, $(subdir_makefiles), $(info including $(mk) ...)$(eval include $(mk)))
+
+endif # dont_bother
 
 endif # ONE_SHOT_MAKEFILE
 
@@ -510,16 +520,6 @@
 # All module makefiles have been included at this point.
 # -------------------------------------------------------------------
 
-# -------------------------------------------------------------------
-# Include any makefiles that must happen after the module makefiles
-# have been included.
-# TODO: have these files register themselves via a global var rather
-# than hard-coding the list here.
-ifdef FULL_BUILD
-  # Only include this during a full build, otherwise we can't be
-  # guaranteed that any policies were included.
-  -include frameworks/policies/base/PolicyConfig.mk
-endif
 
 # -------------------------------------------------------------------
 # Fix up CUSTOM_MODULES to refer to installed files rather than
@@ -682,8 +682,6 @@
 modules_to_install := $(sort $(ALL_DEFAULT_INSTALLED_MODULES))
 ALL_DEFAULT_INSTALLED_MODULES :=
 
-endif # dont_bother
-
 
 # These are additional goals that we build, in order to make sure that there
 # is as little code as possible in the tree that doesn't build.
@@ -810,7 +808,7 @@
   # For uninstallable modules such as static Java library, we have to dist the built file,
   # as <module_name>.<suffix>
   apps_only_dist_built_files := $(foreach m,$(unbundled_build_modules),$(if $(ALL_MODULES.$(m).INSTALLED),,\
-      $(ALL_MODULES.$(m).BUILT):$(m)$(suffix $(ALL_MODULES.$(m).BUILT))))
+      $(if $(ALL_MODULES.$(m).BUILT),$(ALL_MODULES.$(m).BUILT):$(m)$(suffix $(ALL_MODULES.$(m).BUILT)))))
   $(call dist-for-goals,apps_only, $(apps_only_dist_built_files))
 
   ifeq ($(EMMA_INSTRUMENT),true)
@@ -819,11 +817,23 @@
     $(call dist-for-goals,apps_only, $(EMMA_META_ZIP))
   endif
 
+  $(PROGUARD_DICT_ZIP) : $(apps_only_installed_files)
+  $(call dist-for-goals,apps_only, $(PROGUARD_DICT_ZIP))
+
 .PHONY: apps_only
 apps_only: $(unbundled_build_modules)
 
 droid: apps_only
 
+# Combine the NOTICE files for a apps_only build
+$(eval $(call combine-notice-files, \
+    $(target_notice_file_txt), \
+    $(target_notice_file_html), \
+    "Notices for files for apps:", \
+    $(TARGET_OUT_NOTICE_FILES), \
+    $(apps_only_installed_files)))
+
+
 else # TARGET_BUILD_APPS
   $(call dist-for-goals, droidcore, \
     $(INTERNAL_UPDATE_PACKAGE_TARGET) \
diff --git a/core/multi_prebuilt.mk b/core/multi_prebuilt.mk
index 50a4a38..be60e2f 100644
--- a/core/multi_prebuilt.mk
+++ b/core/multi_prebuilt.mk
@@ -14,6 +14,11 @@
 # limitations under the License.
 #
 
+ifneq ($(LOCAL_MODULE)$(LOCAL_MODULE_CLASS),)
+$(error $(LOCAL_PATH): LOCAL_MODULE or LOCAL_MODULE_CLASS not needed by \
+  BUILD_MULTI_PREBUILT, use BUILD_PREBUILT instead!)
+endif
+
 # Save these before they get cleared by CLEAR_VARS.
 prebuilt_static_libs := $(filter %.a,$(LOCAL_PREBUILT_LIBS))
 prebuilt_shared_libs := $(filter-out %.a,$(LOCAL_PREBUILT_LIBS))
diff --git a/core/notice_files.mk b/core/notice_files.mk
index 7e61c1e..5af0113 100644
--- a/core/notice_files.mk
+++ b/core/notice_files.mk
@@ -73,6 +73,19 @@
 $(LOCAL_INSTALLED_MODULE): | $(installed_notice_file)
 endif
 
+# To facilitate collecting NOTICE files for apps_only build,
+# we install the NOTICE file even if a module gets built but not installed,
+# because shared jni libraries won't be installed to the system image.
+ifdef TARGET_BUILD_APPS
+# for static Java libraries, we don't need to even build LOCAL_BUILT_MODULE,
+# but just javalib.jar in the common intermediate dir.
+ifeq ($(LOCAL_MODULE_CLASS),JAVA_LIBRARIES)
+$(intermediates.COMMON)/javalib.jar : | $(installed_notice_file)
+else
+$(LOCAL_BUILT_MODULE): | $(installed_notice_file)
+endif  # JAVA_LIBRARIES
+endif  # TARGET_BUILD_APPS
+
 else
 # NOTICE file does not exist
 installed_notice_file :=
diff --git a/core/package.mk b/core/package.mk
index 36fb54c..551028c 100644
--- a/core/package.mk
+++ b/core/package.mk
@@ -131,12 +131,9 @@
 LOCAL_PROGUARD_ENABLED:=$(strip $(LOCAL_PROGUARD_ENABLED))
 ifndef LOCAL_PROGUARD_ENABLED
 ifneq ($(DISABLE_PROGUARD),true)
-ifneq ($(filter user userdebug, $(TARGET_BUILD_VARIANT)),)
-    # turn on Proguard by default for user & userdebug build
     LOCAL_PROGUARD_ENABLED :=full
 endif
 endif
-endif
 ifeq ($(LOCAL_PROGUARD_ENABLED),disabled)
     # the package explicitly request to disable proguard.
     LOCAL_PROGUARD_ENABLED :=
@@ -156,7 +153,7 @@
 ifeq (,$(LOCAL_APK_LIBRARIES))
 ifneq (,$(LOCAL_SRC_FILES))
 ifndef LOCAL_DEX_PREOPT
-LOCAL_DEX_PREOPT := true
+LOCAL_DEX_PREOPT := $(DEX_PREOPT_DEFAULT)
 endif
 endif
 endif
@@ -483,3 +480,6 @@
 lintall : lint-$(LOCAL_PACKAGE_NAME)
 
 endif # skip_definition
+
+# Reset internal variables.
+all_res_assets :=
diff --git a/core/pathmap.mk b/core/pathmap.mk
index 7024e3e..5dfc543 100644
--- a/core/pathmap.mk
+++ b/core/pathmap.mk
@@ -34,7 +34,6 @@
     frameworks-native:frameworks/native/include \
     graphics:external/skia/include/core \
     libc:bionic/libc/include \
-    libdrm1:frameworks/base/media/libdrm/mobile1/include \
     libhardware:hardware/libhardware/include \
     libhardware_legacy:hardware/libhardware_legacy/include \
     libhost:build/libs/host/include \
@@ -76,11 +75,6 @@
 # A list of all source roots under frameworks/base, which will be
 # built into the android.jar.
 #
-# Note - "common" is included here, even though it is also built
-# into a static library (android-common) for unbundled use.  This
-# is so common and the other framework libraries can have mutual
-# interdependencies.
-#
 FRAMEWORKS_BASE_SUBDIRS := \
 	$(addsuffix /java, \
 	    core \
@@ -115,6 +109,7 @@
         v7/gridlayout \
         v7/appcompat \
         v7/mediarouter \
+        v8/renderscript \
         v13
 
 #
diff --git a/core/pdk_config.mk b/core/pdk_config.mk
index 41a82d4..9590d70 100644
--- a/core/pdk_config.mk
+++ b/core/pdk_config.mk
@@ -47,10 +47,12 @@
 	target/common/obj/JAVA_LIBRARIES/core-junit_intermediates \
 	target/common/obj/JAVA_LIBRARIES/ext_intermediates \
 	target/common/obj/JAVA_LIBRARIES/framework_intermediates \
+	target/common/obj/JAVA_LIBRARIES/framework2_intermediates \
 	target/common/obj/JAVA_LIBRARIES/android.test.runner_intermediates \
 	target/common/obj/JAVA_LIBRARIES/telephony-common_intermediates \
 	target/common/obj/JAVA_LIBRARIES/voip-common_intermediates \
-	target/common/obj/JAVA_LIBRARIES/mms-common_intermediates
+	target/common/obj/JAVA_LIBRARIES/mms-common_intermediates \
+	target/common/obj/JAVA_LIBRARIES/android-ex-camera2_intermediates
 # not java libraries
 PDK_PLATFORM_JAVA_ZIP_CONTENTS := \
 	target/common/obj/APPS/framework-res_intermediates/package-export.apk \
@@ -117,9 +119,14 @@
 
 ifeq (true,$(TARGET_BUILD_PDK_JAVA_PLATFORM))
 
+PDK_FUSION_OUT_DIR := $(OUT_DIR)
+ifeq (debug,$(TARGET_BUILD_TYPE))
+PDK_FUSION_OUT_DIR := $(DEBUG_OUT_DIR)
+endif
+
 define JAVA_dependency_template
-$(OUT_DIR)/$(strip $(1)): $(_pdk_fusion_intermediates)/$(strip $(1)) $(OUT_DIR)/$(strip $(2)) \
-  $(_pdk_fusion_stamp)
+$(PDK_FUSION_OUT_DIR)/$(strip $(1)): $(_pdk_fusion_intermediates)/$(strip $(1)) \
+  $(PDK_FUSION_OUT_DIR)/$(strip $(2)) $(_pdk_fusion_stamp)
 	@mkdir -p $$(dir $$@)
 	$(hide) cp -fpPR $$< $$@
 endef
diff --git a/core/phony_package.mk b/core/phony_package.mk
index 70b6aac..b534335 100644
--- a/core/phony_package.mk
+++ b/core/phony_package.mk
@@ -7,7 +7,7 @@
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
-$(LOCAL_BUILT_MODULE):
+$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(hide) echo "Fake: $@"
 	$(hide) mkdir -p $(dir $@)
 	$(hide) touch $@
diff --git a/core/prebuilt.mk b/core/prebuilt.mk
index 197b54a..e34fa55 100644
--- a/core/prebuilt.mk
+++ b/core/prebuilt.mk
@@ -16,6 +16,9 @@
 $(error dont use LOCAL_PREBUILT_JAVA_LIBRARIES anymore LOCAL_PATH=$(LOCAL_PATH))
 endif
 
+# Not much sense to check build prebuilts
+LOCAL_DONT_CHECK_MODULE := true
+
 ifdef LOCAL_PREBUILT_MODULE_FILE
 my_prebuilt_src_file := $(LOCAL_PREBUILT_MODULE_FILE)
 else
diff --git a/core/product.mk b/core/product.mk
index bbd0c31..a2f4abc 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -95,7 +95,9 @@
     PRODUCT_RESTRICT_VENDOR_FILES \
     PRODUCT_VENDOR_KERNEL_HEADERS \
     PRODUCT_FACTORY_RAMDISK_MODULES \
-    PRODUCT_FACTORY_BUNDLE_MODULES
+    PRODUCT_FACTORY_BUNDLE_MODULES \
+    PRODUCT_RUNTIMES \
+    PRODUCT_BOOT_JARS
 
 
 define dump-product
@@ -207,6 +209,7 @@
 
 
 _product_stash_var_list := $(_product_var_list) \
+	PRODUCT_BOOTCLASSPATH \
 	TARGET_ARCH \
 	TARGET_ARCH_VARIANT \
 	TARGET_CPU_VARIANT \
@@ -235,9 +238,6 @@
 	BOARD_KERNEL_CMDLINE \
 	BOARD_KERNEL_BASE \
 	BOARD_HAVE_BLUETOOTH \
-	BOARD_HAVE_BLUETOOTH_BCM \
-	BOARD_HAVE_BLUETOOTH_QCOM \
-	BOARD_VENDOR_QCOM_AMSS_VERSION \
 	BOARD_VENDOR_USE_AKMD \
 	BOARD_EGL_CFG \
 	BOARD_BOOTIMAGE_PARTITION_SIZE \
@@ -248,8 +248,6 @@
 	BOARD_CACHEIMAGE_PARTITION_SIZE \
 	BOARD_FLASH_BLOCK_SIZE \
 	BOARD_SYSTEMIMAGE_PARTITION_SIZE \
-	BOARD_VENDOR_QCOM_GPS_LOC_API_HARDWARE \
-	BOARD_VENDOR_QCOM_GPS_LOC_API_AMSS_VERSION \
 	BOARD_INSTALLER_CMDLINE \
 
 
diff --git a/core/product_config.mk b/core/product_config.mk
index bfbdf78..e4b68cf 100644
--- a/core/product_config.mk
+++ b/core/product_config.mk
@@ -246,6 +246,31 @@
 all_product_makefiles :=
 all_product_configs :=
 
+
+#############################################################################
+# TODO: Remove this hack once only 1 runtime is left.
+# Include the runtime product makefile based on the product's PRODUCT_RUNTIMES
+$(call clear-var-list, $(_product_var_list))
+
+# Set PRODUCT_RUNTIMES, allowing buildspec to override using OVERRIDE_RUNTIMES
+product_runtimes := $(sort $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_RUNTIMES))
+ifneq ($(OVERRIDE_RUNTIMES),)
+  $(info Overriding PRODUCT_RUNTIMES=$(product_runtimes) with $(OVERRIDE_RUNTIMES))
+  product_runtimes := $(OVERRIDE_RUNTIMES)
+endif
+$(foreach runtime, $(product_runtimes), $(eval include $(SRC_TARGET_DIR)/product/$(runtime).mk))
+$(foreach v, $(_product_var_list), $(if $($(v)),\
+    $(eval PRODUCTS.$(INTERNAL_PRODUCT).$(v) += $(sort $($(v))))))
+
+$(call clear-var-list, $(_product_var_list))
+# Now we can assign to PRODUCT_RUNTIMES
+PRODUCT_RUNTIMES := $(product_runtimes)
+product_runtimes :=
+#############################################################################
+
+# A list of module names of BOOTCLASSPATH (jar files)
+PRODUCT_BOOT_JARS := $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_BOOT_JARS)
+
 # Find the device that this product maps to.
 TARGET_DEVICE := $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEVICE)
 
diff --git a/core/proguard.flags b/core/proguard.flags
index 1e3951b..0641627 100644
--- a/core/proguard.flags
+++ b/core/proguard.flags
@@ -1,9 +1,10 @@
+# We have moved -dontobfuscate and -dontoptimize to the makefiles.
 # dex does not like code run through proguard optimize and preverify steps.
--dontoptimize
+# -dontoptimize
 -dontpreverify
 
 # Don't obfuscate. We only need dead code striping.
--dontobfuscate
+# -dontobfuscate
 
 # Add this flag in your package's own configuration if it's needed.
 #-flattenpackagehierarchy
diff --git a/core/proguard_basic_keeps.flags b/core/proguard_basic_keeps.flags
index 0ce81ef..af0e05d 100644
--- a/core/proguard_basic_keeps.flags
+++ b/core/proguard_basic_keeps.flags
@@ -1,7 +1,6 @@
 # see http://sourceforge.net/tracker/?func=detail&aid=2787465&group_id=54750&atid=474707
 -optimizations !code/simplification/arithmetic
 -optimizations !code/simplification/cast
--allowaccessmodification
 
 # To prevent name conflict in incremental obfuscation.
 -useuniqueclassmembernames
diff --git a/core/proguard_tests.flags b/core/proguard_tests.flags
index f4063d6..4481a1b 100644
--- a/core/proguard_tests.flags
+++ b/core/proguard_tests.flags
@@ -1,5 +1,9 @@
 # Keep everything for tests
--dontshrink -dontobfuscate
+-dontshrink
+
+# But we may want to obfuscate if the main app gets obfuscated.
+# This flag has been moved to the makefiles.
+#-dontobfuscate
 
 #-keep class * extends junit.framework.TestCase {
 #  public void test*();
diff --git a/core/static_java_library.mk b/core/static_java_library.mk
index c3c5c86..f95a382 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -59,6 +59,8 @@
 endif  # all_resources
 endif  # LOCAL_RESOURCE_DIR
 
+all_res_assets := $(all_resources)
+
 include $(BUILD_SYSTEM)/java_library.mk
 
 ifneq (,$(all_resources))
@@ -124,4 +126,6 @@
 
 endif  # $(all_resources) not empty
 
+# Reset internal variables.
+all_res_assets :=
 LOCAL_IS_STATIC_JAVA_LIBRARY :=
diff --git a/core/tasks/cts.mk b/core/tasks/cts.mk
index c1f1d2a..ed8c125 100644
--- a/core/tasks/cts.mk
+++ b/core/tasks/cts.mk
@@ -46,10 +46,9 @@
 CTS_CASE_LIST := $(CTS_CORE_CASE_LIST) $(CTS_TEST_CASE_LIST)
 
 DEFAULT_TEST_PLAN := $(cts_dir)/$(cts_name)/resource/plans
-
+CTS_TEST_CASE_LIST_FILES := $(foreach c, $(CTS_TEST_CASE_LIST), $(call intermediates-dir-for,APPS,$(c))/package.apk)
 $(cts_dir)/all_cts_files_stamp: PRIVATE_JUNIT_HOST_JAR := $(junit_host_jar)
-
-$(cts_dir)/all_cts_files_stamp: $(CTS_CORE_CASES) $(CTS_TEST_CASES) $(CTS_TEST_CASE_LIST) $(junit_host_jar) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(VMTESTSTF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(ACP)
+$(cts_dir)/all_cts_files_stamp: $(CTS_CORE_CASES) $(CTS_TEST_CASES) $(CTS_TEST_CASE_LIST_FILES) $(junit_host_jar) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(VMTESTSTF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(ACP)
 # Make necessary directory for CTS
 	$(hide) rm -rf $(PRIVATE_CTS_DIR)
 	$(hide) mkdir -p $(TMP_DIR)
@@ -108,32 +107,52 @@
 # build system requires that dependencies use javalib.jar.  If
 # javalib.jar is up-to-date, then classes.jar is as well.  Depending
 # on classes.jar will build the files incorrectly.
-$(CTS_CORE_XMLS): $(CTS_CORE_CASES) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(HOST_OUT_JAVA_LIBRARIES)/junit.jar $(CORE_INTERMEDIATES)/javalib.jar $(BOUNCYCASTLE_INTERMEDIATES)/javalib.jar $(APACHEXML_INTERMEDIATES)/javalib.jar $(OKHTTP_INTERMEDIATES)/javalib.jar $(SQLITEJDBC_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(CORETESTS_INTERMEDIATES)/javalib.jar $(CONSCRYPTTESTS_INTERMEDIATES)/javalib.jar | $(ACP)
+CTS_CORE_XMLS_DEPS := $(CTS_CORE_CASES) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(HOST_OUT_JAVA_LIBRARIES)/junit.jar $(CORE_INTERMEDIATES)/javalib.jar $(BOUNCYCASTLE_INTERMEDIATES)/javalib.jar $(APACHEXML_INTERMEDIATES)/javalib.jar $(OKHTTP_INTERMEDIATES)/javalib.jar $(SQLITEJDBC_INTERMEDIATES)/javalib.jar $(JUNIT_INTERMEDIATES)/javalib.jar $(CORETESTS_INTERMEDIATES)/javalib.jar $(CONSCRYPTTESTS_INTERMEDIATES)/javalib.jar | $(ACP)
+
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.dalvik.xml: $(CTS_CORE_XMLS_DEPS)
 	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.dalvik,\
 		cts/tests/core/libcore/dalvik/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,dalvik,\
 		libcore/expectations)
+
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.com.xml: $(CTS_CORE_XMLS_DEPS)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.com,\
 		cts/tests/core/libcore/com/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,com,\
 		libcore/expectations)
+
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.conscrypt.xml: $(CTS_CORE_XMLS_DEPS)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.conscrypt,\
 		cts/tests/core/libcore/conscrypt/AndroidManifest.xml,\
 		$(CONSCRYPTTESTS_INTERMEDIATES)/javalib.jar,,\
 		libcore/expectations)
+
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.sun.xml: $(CTS_CORE_XMLS_DEPS)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.sun,\
 		cts/tests/core/libcore/sun/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,sun,\
 		libcore/expectations)
+
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.tests.xml: $(CTS_CORE_XMLS_DEPS)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.tests,\
 		cts/tests/core/libcore/tests/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,tests,\
 		libcore/expectations)
+
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.org.xml: $(CTS_CORE_XMLS_DEPS)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.org,\
 		cts/tests/core/libcore/org/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,org,\
 		libcore/expectations)
+
+$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.libcore.xml: $(CTS_CORE_XMLS_DEPS)
+	$(hide) mkdir -p $(CTS_TESTCASES_OUT)
 	$(call generate-core-test-description,$(CTS_TESTCASES_OUT)/android.core.tests.libcore.package.libcore,\
 		cts/tests/core/libcore/libcore/AndroidManifest.xml,\
 		$(CORETESTS_INTERMEDIATES)/javalib.jar,libcore,\
@@ -166,6 +185,7 @@
 	$(hide) $(ACP) -fp $(CTS_CORE_XMLS) $(CTS_TEST_XMLS) $(CORE_VM_TEST_TF_DESC) $(PRIVATE_DIR)/repository/testcases
 	$(hide) $(cts_tools_src_dir)/utils/buildCts.py cts/tests/tests/ $(PRIVATE_DIR) $(TMP_DIR) \
 		$(TOP) $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar
+	$(hide) mkdir -p $(dir $@) && touch $@
 
 # Package CTS and clean up.
 #
diff --git a/core/tasks/product-graph.mk b/core/tasks/product-graph.mk
index 1ccb20b..fcec277 100644
--- a/core/tasks/product-graph.mk
+++ b/core/tasks/product-graph.mk
@@ -51,26 +51,33 @@
 
 really_all_products := $(call gather-all-products)
 
+open_parethesis := (
+close_parenthesis := )
+
+# Emit properties of a product node to a file.
+# $(1) the product
+# $(2) the output file
+define emit-product-node-props
+$(hide) echo \"$(1)\" [ \
+label=\"$(dir $(1))\\n$(notdir $(1))\\n\\n$(subst $(close_parenthesis),,$(subst $(open_parethesis),,$(PRODUCTS.$(strip $(1)).PRODUCT_MODEL)))\\n$(PRODUCTS.$(strip $(1)).PRODUCT_DEVICE)\" \
+$(if $(filter $(1),$(PRIVATE_PRODUCTS_FILTER)), style=\"filled\" fillcolor=\"#FFFDB0\",) \
+fontcolor=\"darkblue\" href=\"products/$(1).html\" \
+] >> $(2)
+
+endef
+
 $(products_graph): PRIVATE_PRODUCTS := $(really_all_products)
 $(products_graph): PRIVATE_PRODUCTS_FILTER := $(products_list)
 
 $(products_graph): $(this_makefile)
 	@echo Product graph DOT: $@ for $(PRIVATE_PRODUCTS_FILTER)
-	$(hide) ( \
-		echo 'digraph {'; \
-		echo 'graph [ ratio=.5 ];'; \
-		$(foreach p,$(PRIVATE_PRODUCTS), \
-			$(foreach d,$(PRODUCTS.$(strip $(p)).INHERITS_FROM), echo \"$(d)\" -\> \"$(p)\";)) \
-		$(foreach prod, $(PRIVATE_PRODUCTS), \
-			echo \"$(prod)\" [ \
-					label=\"$(dir $(prod))\\n$(notdir $(prod))\\n\\n$(PRODUCTS.$(strip $(prod)).PRODUCT_MODEL)\\n$(PRODUCTS.$(strip $(prod)).PRODUCT_DEVICE)\" \
-					$(if $(filter $(prod),$(PRIVATE_PRODUCTS_FILTER)), style=\"filled\" fillcolor=\"#FFFDB0\",) \
-					fontcolor=\"darkblue\" href=\"products/$(prod).html\" \
-				];) \
-		echo '}' \
-	) \
-	| ./build/tools/filter-product-graph.py $(PRIVATE_PRODUCTS_FILTER) \
-	> $@
+	$(hide) echo 'digraph {' > $@.in
+	$(hide) echo 'graph [ ratio=.5 ];' >> $@.in
+	$(hide) $(foreach p,$(PRIVATE_PRODUCTS), \
+	  $(foreach d,$(PRODUCTS.$(strip $(p)).INHERITS_FROM), echo \"$(d)\" -\> \"$(p)\" >> $@.in;))
+	$(foreach p,$(PRIVATE_PRODUCTS),$(call emit-product-node-props,$(p),$@.in))
+	$(hide) echo '}' >> $@.in
+	$(hide) ./build/tools/filter-product-graph.py $(PRIVATE_PRODUCTS_FILTER) < $@.in > $@
 
 # Evaluates to the name of the product file
 # $(1) product file
@@ -137,4 +144,3 @@
 	dot -Tsvg -Nshape=box -o $@ $<
 
 product-graph: $(products_pdf) $(products_svg)
-
diff --git a/core/tasks/vendor_module_check.mk b/core/tasks/vendor_module_check.mk
index fcf2bbe..c51a40c 100644
--- a/core/tasks/vendor_module_check.mk
+++ b/core/tasks/vendor_module_check.mk
@@ -85,10 +85,12 @@
 
 $(foreach m, $(_vendor_check_modules), \
   $(if $(filter vendor/%, $(ALL_MODULES.$(m).PATH)),\
-    $(if $(filter $(TARGET_OUT_VENDOR)/%, $(ALL_MODULES.$(m).INSTALLED)),,\
-      $(error Error: vendor module "$(m)" in $(ALL_MODULES.$(m).PATH) \
-        in product "$(TARGET_PRODUCT)" being installed to \
-        $(ALL_MODULES.$(m).INSTALLED) which is not in the vendor tree))))
+    $(if $(filter-out FAKE, $(ALL_MODULES.$(m).CLASS)),\
+      $(if $(filter-out ,$(ALL_MODULES.$(m).INSTALLED)),\
+        $(if $(filter $(TARGET_OUT_VENDOR)/% $(HOST_OUT)/%, $(ALL_MODULES.$(m).INSTALLED)),,\
+          $(error Error: vendor module "$(m)" in $(ALL_MODULES.$(m).PATH) \
+            in product "$(TARGET_PRODUCT)" being installed to \
+            $(ALL_MODULES.$(m).INSTALLED) which is not in the vendor tree))))))
 
 endif
 
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index b9e1456..faa12d2 100644
--- a/core/version_defaults.mk
+++ b/core/version_defaults.mk
@@ -41,7 +41,7 @@
   # which is the version that we reveal to the end user.
   # Update this value when the platform version changes (rather
   # than overriding it somewhere else).  Can be an arbitrary string.
-  PLATFORM_VERSION := 4.3.2.1.000.000
+  PLATFORM_VERSION := 4.4
 endif
 
 ifeq "" "$(PLATFORM_SDK_VERSION)"
@@ -53,7 +53,7 @@
   # intermediate builds).  During development, this number remains at the
   # SDK version the branch is based on and PLATFORM_VERSION_CODENAME holds
   # the code-name of the new development work.
-  PLATFORM_SDK_VERSION := 18
+  PLATFORM_SDK_VERSION := 19
 endif
 
 ifeq "" "$(PLATFORM_VERSION_CODENAME)"
diff --git a/envsetup.sh b/envsetup.sh
index 2ae7cb8..33d73f1 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -661,6 +661,9 @@
     else
         # Find the closest Android.mk file.
         local M=$(findmakefile)
+        local MODULES=
+        local GET_INSTALL_PATH=
+        local ARGS=
         # Remove the path to top as the makefilepath needs to be relative
         local M=`echo $M|sed 's:'$T'/::'`
         if [ ! "$T" ]; then
@@ -668,7 +671,19 @@
         elif [ ! "$M" ]; then
             echo "Couldn't locate a makefile from the current directory."
         else
-            ONE_SHOT_MAKEFILE=$M $DRV make -C $T -f build/core/main.mk all_modules $@
+            for ARG in $@; do
+                case $ARG in
+                  GET-INSTALL-PATH) GET_INSTALL_PATH=$ARG;;
+                esac
+            done
+            if [ -n "$GET_INSTALL_PATH" ]; then
+              MODULES=
+              ARGS=GET-INSTALL-PATH
+            else
+              MODULES=all_modules
+              ARGS=$@
+            fi
+            ONE_SHOT_MAKEFILE=$M $DRV make -C $T -f build/core/main.mk $MODULES $ARGS
         fi
     fi
 }
@@ -682,6 +697,7 @@
         local MODULES=
         local ARGS=
         local DIR TO_CHOP
+        local GET_INSTALL_PATH=
         local DASH_ARGS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
         local DIRS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
         for DIR in $DIRS ; do
@@ -691,10 +707,10 @@
             fi
             DIR=`echo $DIR | sed -e 's/:.*//' -e 's:/$::'`
             if [ -f $DIR/Android.mk ]; then
-                TO_CHOP=`(\cd -P -- $T && pwd -P) | wc -c | tr -d ' '`
-                TO_CHOP=`expr $TO_CHOP + 1`
-                START=`PWD= /bin/pwd`
-                MFILE=`echo $START | cut -c${TO_CHOP}-`
+                local TO_CHOP=`(\cd -P -- $T && pwd -P) | wc -c | tr -d ' '`
+                local TO_CHOP=`expr $TO_CHOP + 1`
+                local START=`PWD= /bin/pwd`
+                local MFILE=`echo $START | cut -c${TO_CHOP}-`
                 if [ "$MFILE" = "" ] ; then
                     MFILE=$DIR/Android.mk
                 else
@@ -702,20 +718,17 @@
                 fi
                 MAKEFILE="$MAKEFILE $MFILE"
             else
-                if [ "$DIR" = snod ]; then
-                    ARGS="$ARGS snod"
-                elif [ "$DIR" = showcommands ]; then
-                    ARGS="$ARGS showcommands"
-                elif [ "$DIR" = dist ]; then
-                    ARGS="$ARGS dist"
-                elif [ "$DIR" = incrementaljavac ]; then
-                    ARGS="$ARGS incrementaljavac"
-                else
-                    echo "No Android.mk in $DIR."
-                    return 1
-                fi
+                case $DIR in
+                  showcommands | snod | dist | incrementaljavac) ARGS="$ARGS $DIR";;
+                  GET-INSTALL-PATH) GET_INSTALL_PATH=$DIR;;
+                  *) echo "No Android.mk in $DIR."; return 1;;
+                esac
             fi
         done
+        if [ -n "$GET_INSTALL_PATH" ]; then
+          ARGS=$GET_INSTALL_PATH
+          MODULES=
+        fi
         ONE_SHOT_MAKEFILE="$MAKEFILE" $DRV make -C $T -f build/core/main.mk $DASH_ARGS $MODULES $ARGS
     else
         echo "Couldn't locate the top of the tree.  Try setting TOP."
@@ -800,15 +813,50 @@
     echo "can't find Android.mk"
 }
 
+# simplified version of ps; output in the form
+# <pid> <procname>
+function qpid() {
+    local prepend=''
+    local append=''
+    if [ "$1" = "--exact" ]; then
+        prepend=' '
+        append='$'
+        shift
+    elif [ "$1" = "--help" -o "$1" = "-h" ]; then
+		echo "usage: qpid [[--exact] <process name|pid>"
+		return 255
+	fi
+
+    local EXE="$1"
+    if [ "$EXE" ] ; then
+		qpid | \grep "$prepend$EXE$append"
+	else
+		adb shell ps \
+			| tr -d '\r' \
+			| sed -e 1d -e 's/^[^ ]* *\([0-9]*\).* \([^ ]*\)$/\1 \2/'
+	fi
+}
+
 function pid()
 {
-   local EXE="$1"
-   if [ "$EXE" ] ; then
-       local PID=`adb shell ps | fgrep $1 | sed -e 's/[^ ]* *\([0-9]*\).*/\1/'`
-       echo "$PID"
-   else
-       echo "usage: pid name"
-   fi
+    local prepend=''
+    local append=''
+    if [ "$1" = "--exact" ]; then
+        prepend=' '
+        append='$'
+        shift
+    fi
+    local EXE="$1"
+    if [ "$EXE" ] ; then
+        local PID=`adb shell ps \
+            | tr -d '\r' \
+            | \grep "$prepend$EXE$append" \
+            | sed -e 's/^[^ ]* *\([0-9]*\).*$/\1/'`
+        echo "$PID"
+    else
+        echo "usage: pid [--exact] <process name>"
+		return 255
+    fi
 }
 
 # systemstack - dump the current stack trace of all threads in the system process
@@ -823,31 +871,45 @@
     if [[ $1 =~ ^[0-9]+$ ]] ; then
         local PID="$1"
     elif [ "$1" ] ; then
-        local PID=$(pid $1)
+        local PIDLIST="$(pid $1)"
+        if [[ $PIDLIST =~ ^[0-9]+$ ]] ; then
+            local PID="$PIDLIST"
+        elif [ "$PIDLIST" ] ; then
+            echo "more than one process: $1"
+        else
+            echo "no such process: $1"
+        fi
     else
         echo "usage: stacks [pid|process name]"
     fi
 
     if [ "$PID" ] ; then
-        local TRACES=/data/anr/traces.txt
-        local ORIG=/data/anr/traces.orig
-        local TMP=/data/anr/traces.tmp
+        # Determine whether the process is native
+        if adb shell ls -l /proc/$PID/exe | grep -q /system/bin/app_process ; then
+            # Dump stacks of Dalvik process
+            local TRACES=/data/anr/traces.txt
+            local ORIG=/data/anr/traces.orig
+            local TMP=/data/anr/traces.tmp
 
-        # Keep original traces to avoid clobbering
-        adb shell mv $TRACES $ORIG
+            # Keep original traces to avoid clobbering
+            adb shell mv $TRACES $ORIG
 
-        # Make sure we have a usable file
-        adb shell touch $TRACES
-        adb shell chmod 666 $TRACES
+            # Make sure we have a usable file
+            adb shell touch $TRACES
+            adb shell chmod 666 $TRACES
 
-        # Dump stacks and wait for dump to finish
-        adb shell kill -3 $PID
-        adb shell notify $TRACES
+            # Dump stacks and wait for dump to finish
+            adb shell kill -3 $PID
+            adb shell notify $TRACES >/dev/null
 
-        # Restore original stacks, and show current output
-        adb shell mv $TRACES $TMP
-        adb shell mv $ORIG $TRACES
-        adb shell cat $TMP | less -S
+            # Restore original stacks, and show current output
+            adb shell mv $TRACES $TMP
+            adb shell mv $ORIG $TRACES
+            adb shell cat $TMP
+        else
+            # Dump stacks of native process
+            adb shell debuggerd -b $PID
+        fi
     fi
 }
 
@@ -894,7 +956,7 @@
                if [[ ! "$PID" =~ ^[0-9]+$ ]] ; then
                    # that likely didn't work because of returning multiple processes
                    # try again, filtering by root processes (don't contain colon)
-                   PID=`adb shell ps | grep $3 | grep -v ":" | awk '{print $2}'`
+                   PID=`adb shell ps | \grep $3 | \grep -v ":" | awk '{print $2}'`
                    if [[ ! "$PID" =~ ^[0-9]+$ ]]
                    then
                        echo "Couldn't resolve '$3' to single PID"
@@ -920,6 +982,7 @@
 
        echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $OUT_SYMBOLS"
        echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $OUT_SO_SYMBOLS:$OUT_SO_SYMBOLS/hw:$OUT_SO_SYMBOLS/ssl/engines:$OUT_SO_SYMBOLS/drm:$OUT_SO_SYMBOLS/egl:$OUT_SO_SYMBOLS/soundfx"
+       echo >>"$OUT_ROOT/gdbclient.cmds" "source $ANDROID_BUILD_TOP/development/scripts/gdb/dalvik.gdb"
        echo >>"$OUT_ROOT/gdbclient.cmds" "target remote $PORT"
        echo >>"$OUT_ROOT/gdbclient.cmds" ""
 
@@ -1086,7 +1149,7 @@
     fi
 
     # issue "am" command to cause the hprof dump
-    local sdcard=$(adb shell echo -n '$EXTERNAL_STORAGE')
+    local sdcard=$(adb ${adbOptions} shell echo -n '$EXTERNAL_STORAGE')
     local devFile=$sdcard/hprof-$targetPid
     #local devFile=/data/local/hprof-$targetPid
     echo "Poking $targetPid and waiting for data..."
diff --git a/libs/host/Android.mk b/libs/host/Android.mk
index 9900f59..74afa55 100644
--- a/libs/host/Android.mk
+++ b/libs/host/Android.mk
@@ -2,8 +2,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-	CopyFile.c \
-	pseudolocalize.cpp
+	CopyFile.c
 
 ifeq ($(HOST_OS),cygwin)
 LOCAL_CFLAGS += -DWIN32_EXE
diff --git a/libs/host/include/host/pseudolocalize.h b/libs/host/include/host/pseudolocalize.h
deleted file mode 100644
index 94cb034..0000000
--- a/libs/host/include/host/pseudolocalize.h
+++ /dev/null
@@ -1,9 +0,0 @@
-#ifndef HOST_PSEUDOLOCALIZE_H
-#define HOST_PSEUDOLOCALIZE_H
-
-#include <string>
-
-std::string pseudolocalize_string(const std::string& source);
-
-#endif // HOST_PSEUDOLOCALIZE_H
-
diff --git a/libs/host/pseudolocalize.cpp b/libs/host/pseudolocalize.cpp
deleted file mode 100644
index a2b3c2f..0000000
--- a/libs/host/pseudolocalize.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-#include <host/pseudolocalize.h>
-
-using namespace std;
-
-static const char*
-pseudolocalize_char(char c)
-{
-    switch (c) {
-        case 'a':   return "\xc4\x83";
-        case 'b':   return "\xcf\x84";
-        case 'c':   return "\xc4\x8b";
-        case 'd':   return "\xc4\x8f";
-        case 'e':   return "\xc4\x99";
-        case 'f':   return "\xc6\x92";
-        case 'g':   return "\xc4\x9d";
-        case 'h':   return "\xd1\x9b";
-        case 'i':   return "\xcf\x8a";
-        case 'j':   return "\xc4\xb5";
-        case 'k':   return "\xc4\xb8";
-        case 'l':   return "\xc4\xba";
-        case 'm':   return "\xe1\xb8\xbf";
-        case 'n':   return "\xd0\xb8";
-        case 'o':   return "\xcf\x8c";
-        case 'p':   return "\xcf\x81";
-        case 'q':   return "\x51";
-        case 'r':   return "\xd2\x91";
-        case 's':   return "\xc5\xa1";
-        case 't':   return "\xd1\x82";
-        case 'u':   return "\xce\xb0";
-        case 'v':   return "\x56";
-        case 'w':   return "\xe1\xba\x85";
-        case 'x':   return "\xd1\x85";
-        case 'y':   return "\xe1\xbb\xb3";
-        case 'z':   return "\xc5\xba";
-        case 'A':   return "\xc3\x85";
-        case 'B':   return "\xce\xb2";
-        case 'C':   return "\xc4\x88";
-        case 'D':   return "\xc4\x90";
-        case 'E':   return "\xd0\x84";
-        case 'F':   return "\xce\x93";
-        case 'G':   return "\xc4\x9e";
-        case 'H':   return "\xc4\xa6";
-        case 'I':   return "\xd0\x87";
-        case 'J':   return "\xc4\xb5";
-        case 'K':   return "\xc4\xb6";
-        case 'L':   return "\xc5\x81";
-        case 'M':   return "\xe1\xb8\xbe";
-        case 'N':   return "\xc5\x83";
-        case 'O':   return "\xce\x98";
-        case 'P':   return "\xcf\x81";
-        case 'Q':   return "\x71";
-        case 'R':   return "\xd0\xaf";
-        case 'S':   return "\xc8\x98";
-        case 'T':   return "\xc5\xa6";
-        case 'U':   return "\xc5\xa8";
-        case 'V':   return "\xce\xbd";
-        case 'W':   return "\xe1\xba\x84";
-        case 'X':   return "\xc3\x97";
-        case 'Y':   return "\xc2\xa5";
-        case 'Z':   return "\xc5\xbd";
-        default:    return NULL;
-    }
-}
-
-/**
- * Converts characters so they look like they've been localized.
- *
- * Note: This leaves escape sequences untouched so they can later be
- * processed by ResTable::collectString in the normal way.
- */
-string
-pseudolocalize_string(const string& source)
-{
-    const char* s = source.c_str();
-    string result;
-    const size_t I = source.length();
-    for (size_t i=0; i<I; i++) {
-        char c = s[i];
-        if (c == '\\') {
-            if (i<I-1) {
-                result += '\\';
-                i++;
-                c = s[i];
-                switch (c) {
-                    case 'u':
-                        // this one takes up 5 chars
-                        result += string(s+i, 5);
-                        i += 4;
-                        break;
-                    case 't':
-                    case 'n':
-                    case '#':
-                    case '@':
-                    case '?':
-                    case '"':
-                    case '\'':
-                    case '\\':
-                    default:
-                        result += c;
-                        break;
-                }
-            } else {
-                result += c;
-            }
-        } else {
-            const char* p = pseudolocalize_char(c);
-            if (p != NULL) {
-                result += p;
-            } else {
-                result += c;
-            }
-        }
-    }
-
-    //printf("result=\'%s\'\n", result.c_str());
-    return result;
-}
-
-
diff --git a/target/board/Android.mk b/target/board/Android.mk
index 7d94ee0..f8ecc4e 100644
--- a/target/board/Android.mk
+++ b/target/board/Android.mk
@@ -2,24 +2,6 @@
 # Set up product-global definitions and include product-specific rules.
 #
 
-ifneq ($(strip $(TARGET_NO_BOOTLOADER)),true)
-  INSTALLED_BOOTLOADER_MODULE := $(PRODUCT_OUT)/bootloader
-  ifeq ($(strip $(TARGET_BOOTLOADER_IS_2ND)),true)
-    INSTALLED_2NDBOOTLOADER_TARGET := $(PRODUCT_OUT)/2ndbootloader
-  else
-    INSTALLED_2NDBOOTLOADER_TARGET :=
-  endif
-else
-  INSTALLED_BOOTLOADER_MODULE :=
-  INSTALLED_2NDBOOTLOADER_TARGET :=
-endif	# TARGET_NO_BOOTLOADER
-
-ifneq ($(strip $(TARGET_NO_KERNEL)),true)
-  INSTALLED_KERNEL_TARGET := $(PRODUCT_OUT)/kernel
-else
-  INSTALLED_KERNEL_TARGET :=
-endif
-
 -include $(TARGET_DEVICE_DIR)/AndroidBoard.mk
 
 # Generate a file that contains various information about the
diff --git a/target/board/generic/BoardConfig.mk b/target/board/generic/BoardConfig.mk
index 3bd4f31..60decfb 100644
--- a/target/board/generic/BoardConfig.mk
+++ b/target/board/generic/BoardConfig.mk
@@ -45,6 +45,28 @@
 # the GLES renderer disables itself if host GL acceleration isn't available.
 USE_OPENGL_RENDERER := true
 
+# Set the phase offset of the system's vsync event relative to the hardware
+# vsync. The system's vsync event drives Choreographer and SurfaceFlinger's
+# rendering. This value is the number of nanoseconds after the hardware vsync
+# that the system vsync event will occur.
+#
+# This phase offset allows adjustment of the minimum latency from application
+# wake-up (by Choregographer) time to the time at which the resulting window
+# image is displayed.  This value may be either positive (after the HW vsync)
+# or negative (before the HW vsync).  Setting it to 0 will result in a
+# minimum latency of two vsync periods because the app and SurfaceFlinger
+# will run just after the HW vsync.  Setting it to a positive number will
+# result in the minimum latency being:
+#
+#     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
+#
+# Note that reducing this latency makes it more likely for the applications
+# to not have their window content image ready in time.  When this happens
+# the latency will end up being an additional vsync period, and animations
+# will hiccup.  Therefore, this latency should be tuned somewhat
+# conservatively (or at least with awareness of the trade-off being made).
+VSYNC_EVENT_PHASE_OFFSET_NS := 0
+
 TARGET_USERIMAGES_USE_EXT4 := true
 BOARD_SYSTEMIMAGE_PARTITION_SIZE := 576716800
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 209715200
diff --git a/target/board/vbox_x86/BoardConfig.mk b/target/board/vbox_x86/BoardConfig.mk
index 80a9077..815ad9e 100644
--- a/target/board/vbox_x86/BoardConfig.mk
+++ b/target/board/vbox_x86/BoardConfig.mk
@@ -9,7 +9,6 @@
 TARGET_HARDWARE_3D := false
 BOARD_USES_GENERIC_AUDIO := true
 USE_CAMERA_STUB := true
-TARGET_PROVIDES_INIT_RC := true
 TARGET_CPU_ABI := x86
 TARGET_USERIMAGES_USE_EXT4 := true
 TARGET_BOOTIMAGE_USE_EXT2 := true
diff --git a/target/board/vbox_x86/device.mk b/target/board/vbox_x86/device.mk
index 2bb96b9..a44a87f 100644
--- a/target/board/vbox_x86/device.mk
+++ b/target/board/vbox_x86/device.mk
@@ -30,7 +30,6 @@
     device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
     device/generic/goldfish/camera/media_profiles.xml:system/etc/media_profiles.xml \
     device/generic/goldfish/camera/media_codecs.xml:system/etc/media_codecs.xml \
-    system/core/rootdir/init.rc:root/init.rc \
     build/target/board/vbox_x86/init.vbox_x86.rc:root/init.vbox_x86.rc \
     $(LOCAL_KERNEL):kernel
 
diff --git a/target/product/base.mk b/target/product/base.mk
index ebb341c..0959fb4 100644
--- a/target/product/base.mk
+++ b/target/product/base.mk
@@ -23,6 +23,7 @@
     android.test.runner \
     app_process \
     applypatch \
+    blkid \
     bmgr \
     bugreport \
     content \
@@ -42,20 +43,21 @@
     libbundlewrapper \
     libcamera_client \
     libcameraservice \
-    libchromium_net \
     libdl \
-    libdrm1 \
-    libdrm1_jni \
+    libeffectproxy \
     libeffects \
+    libinput \
     libiprouteutil \
     libjni_latinime \
     libjnigraphics \
+    libldnhncr \
     libmedia \
     libmedia_jni \
     libmediaplayerservice \
     libmtp \
     libnetlink \
     libnetutils \
+    libpac \
     libreference-ril \
     libreverbwrapper \
     libril \
@@ -72,7 +74,6 @@
     libstagefright_foundation \
     libstagefright_omx \
     libstagefright_yuv \
-    libsystem_server \
     libusbhost \
     libutils \
     libvisualizer \
@@ -99,7 +100,6 @@
     services \
     settings \
     svc \
-    system_server \
     tc \
     vdc \
     vold \
diff --git a/target/product/core.mk b/target/product/core.mk
index d503ddc..c5ef2aa 100644
--- a/target/product/core.mk
+++ b/target/product/core.mk
@@ -19,79 +19,18 @@
 # devices (including non-phones and non-tablets), modify
 # core_minimal.mk instead.
 
-PRODUCT_PROPERTY_OVERRIDES := \
-    ro.config.notification_sound=OnTheHunt.ogg \
-    ro.config.alarm_alert=Alarm_Classic.ogg
-
 PRODUCT_PACKAGES += \
     BasicDreams \
     Browser \
     Contacts \
-    ContactsProvider \
-    DefaultContainerService \
-    Home \
+    DocumentsUI \
+    DownloadProviderUi \
+    ExternalStorageProvider \
     KeyChain \
     PicoTts \
+    PacProcessor \
+    ProxyHandler \
     SharedStorageBackup \
-    TelephonyProvider \
-    UserDictionaryProvider \
-    VpnDialogs \
-    atrace \
-    libandroidfw \
-    libaudiopreprocessing \
-    libaudioutils \
-    libbcc \
-    libfilterpack_imageproc \
-    libgabi++ \
-    libkeystore \
-    libmdnssd \
-    libnfc_ndef \
-    libportable \
-    libpowermanager \
-    libspeexresampler \
-    libstagefright_chromium_http \
-    libstagefright_soft_aacdec \
-    libstagefright_soft_aacenc \
-    libstagefright_soft_amrdec \
-    libstagefright_soft_amrnbenc \
-    libstagefright_soft_amrwbenc \
-    libstagefright_soft_flacenc \
-    libstagefright_soft_g711dec \
-    libstagefright_soft_gsmdec \
-    libstagefright_soft_h264dec \
-    libstagefright_soft_h264enc \
-    libstagefright_soft_mp3dec \
-    libstagefright_soft_mpeg4dec \
-    libstagefright_soft_mpeg4enc \
-    libstagefright_soft_rawdec \
-    libstagefright_soft_vorbisdec \
-    libstagefright_soft_vpxdec \
-    libstagefright_soft_vpxenc \
-    libvariablespeed \
-    libwebrtc_audio_preprocessing \
-    mdnsd \
-    mms-common \
-    okhttp \
-    requestsync \
-    telephony-common \
-    voip-common
+    VpnDialogs
 
-# host-only dependencies
-ifeq ($(WITH_HOST_DALVIK),true)
-    PRODUCT_PACKAGES += \
-        apache-xml-hostdex \
-        bouncycastle-hostdex \
-        conscrypt-hostdex \
-        core-hostdex \
-        okhttp-hostdex \
-        libcrypto \
-        libexpat \
-        libicui18n \
-        libicuuc \
-        libjavacore \
-        libssl \
-        libz-host \
-        dalvik
-endif
-
-$(call inherit-product, $(SRC_TARGET_DIR)/product/core_minimal.mk)
+$(call inherit-product, $(SRC_TARGET_DIR)/product/core_base.mk)
diff --git a/target/product/core_base.mk b/target/product/core_base.mk
new file mode 100644
index 0000000..cde2b85
--- /dev/null
+++ b/target/product/core_base.mk
@@ -0,0 +1,71 @@
+#
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Note that components added here will be also shared in PDK. Components
+# that should not be in PDK should be added in lower level like core.mk.
+
+PRODUCT_PROPERTY_OVERRIDES := \
+    ro.config.notification_sound=OnTheHunt.ogg \
+    ro.config.alarm_alert=Alarm_Classic.ogg
+
+PRODUCT_PACKAGES += \
+    ContactsProvider \
+    DefaultContainerService \
+    Home \
+    TelephonyProvider \
+    UserDictionaryProvider \
+    atrace \
+    libandroidfw \
+    libaudiopreprocessing \
+    libaudioutils \
+    libbcc \
+    libfilterpack_imageproc \
+    libgabi++ \
+    libkeystore \
+    libmdnssd \
+    libnfc_ndef \
+    libportable \
+    libpowermanager \
+    libspeexresampler \
+    libstagefright_chromium_http \
+    libstagefright_soft_aacdec \
+    libstagefright_soft_aacenc \
+    libstagefright_soft_amrdec \
+    libstagefright_soft_amrnbenc \
+    libstagefright_soft_amrwbenc \
+    libstagefright_soft_flacenc \
+    libstagefright_soft_g711dec \
+    libstagefright_soft_gsmdec \
+    libstagefright_soft_h264dec \
+    libstagefright_soft_h264enc \
+    libstagefright_soft_mp3dec \
+    libstagefright_soft_mpeg4dec \
+    libstagefright_soft_mpeg4enc \
+    libstagefright_soft_rawdec \
+    libstagefright_soft_vorbisdec \
+    libstagefright_soft_vpxdec \
+    libstagefright_soft_vpxenc \
+    libvariablespeed \
+    libwebrtc_audio_preprocessing \
+    mdnsd \
+    mms-common \
+    requestsync \
+    screenrecord \
+    telephony-common \
+    voip-common
+
+$(call inherit-product, $(SRC_TARGET_DIR)/product/core_minimal.mk)
+# Override the PRODUCT_BOOT_JARS set in core_minimal.mk
+PRODUCT_BOOT_JARS := core:conscrypt:okhttp:core-junit:bouncycastle:ext:framework:framework2:telephony-common:voip-common:mms-common:android.policy:services:apache-xml:webviewchromium
diff --git a/target/product/core_minimal.mk b/target/product/core_minimal.mk
index 4c2cdfb..fc2fc80 100644
--- a/target/product/core_minimal.mk
+++ b/target/product/core_minimal.mk
@@ -23,35 +23,18 @@
 PRODUCT_NAME := core
 
 PRODUCT_PACKAGES += \
-    ApplicationsProvider \
     BackupRestoreConfirmation \
     DownloadProvider \
-    DownloadProviderUi \
     HTMLViewer \
     MediaProvider \
     PackageInstaller \
     SettingsProvider \
     Shell \
-    apache-xml \
-    bouncycastle \
     bu \
-    cacerts \
     com.android.location.provider \
     com.android.location.provider.xml \
-    conscrypt \
-    core \
-    core-junit \
-    dalvikvm \
-    dexdeps \
-    dexdump \
-    dexlist \
-    dexopt \
-    dmtracedump \
     drmserver \
-    dx \
-    ext \
     framework-res \
-    hprof-conv \
     installd \
     ip \
     ip-up-vpn \
@@ -61,24 +44,20 @@
     keystore.default \
     libOpenMAXAL \
     libOpenSLES \
-    libcrypto \
     libdownmix \
-    libdvm \
     libdrmframework \
     libdrmframework_jni \
-    libexpat \
     libfilterfw \
-    libicui18n \
-    libicuuc \
-    libjavacore \
-    libnativehelper \
     libsqlite_jni \
-    libssl \
     libwilhelm \
-    libz \
     make_ext4fs \
     screencap \
     sensorservice \
     uiautomator
 
+PRODUCT_BOOT_JARS := core:conscrypt:okhttp:core-junit:bouncycastle:ext:framework:framework2:android.policy:services:apache-xml:webviewchromium
+
+PRODUCT_RUNTIMES := runtime_libdvm_default
+PRODUCT_RUNTIMES += runtime_libart
+
 $(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
diff --git a/target/product/embedded.mk b/target/product/embedded.mk
index 0830101..11e02ae 100644
--- a/target/product/embedded.mk
+++ b/target/product/embedded.mk
@@ -26,7 +26,10 @@
     dumpsys \
     gralloc.default \
     gzip \
+    healthd \
     init \
+    init.environ.rc \
+    init.rc \
     input \
     libEGL \
     libETC1 \
@@ -58,6 +61,7 @@
     linker \
     logcat \
     logwrapper \
+    reboot \
     service \
     servicemanager \
     surfaceflinger \
@@ -71,6 +75,9 @@
     property_contexts \
     mac_permissions.xml
 
+
 PRODUCT_COPY_FILES += \
     system/core/rootdir/init.usb.rc:root/init.usb.rc \
     system/core/rootdir/init.trace.rc:root/init.trace.rc \
+    system/core/rootdir/ueventd.rc:root/ueventd.rc \
+    system/core/rootdir/etc/hosts:system/etc/hosts
diff --git a/target/product/full_base.mk b/target/product/full_base.mk
index b2e3189..059697e 100644
--- a/target/product/full_base.mk
+++ b/target/product/full_base.mk
@@ -49,6 +49,9 @@
 # Put en_US first in the list, so make it default.
 PRODUCT_LOCALES := en_US
 
+# Include drawables for all densities
+PRODUCT_AAPT_CONFIG := normal hdpi xhdpi xxhdpi
+
 # Get some sounds
 $(call inherit-product-if-exists, frameworks/base/data/sounds/AllAudio.mk)
 
diff --git a/target/product/generic_no_telephony.mk b/target/product/generic_no_telephony.mk
index f225673..1155b4e 100644
--- a/target/product/generic_no_telephony.mk
+++ b/target/product/generic_no_telephony.mk
@@ -24,27 +24,30 @@
     Bluetooth \
     Calculator \
     Calendar \
+    Camera2 \
     CertInstaller \
-    DrmProvider \
     Email \
     Exchange2 \
     FusedLocation \
     Gallery2 \
     InputDevices \
+    Keyguard \
     LatinIME \
     Launcher2 \
     Music \
     MusicFX \
     OneTimeInitializer \
+    PrintSpooler \
     Provision \
-    Phone \
     QuickSearchBox \
     Settings \
     SystemUI \
+    TeleService \
     CalendarProvider \
     bluetooth-health \
     hostapd \
-    wpa_supplicant.conf
+    wpa_supplicant.conf \
+    WallpaperCropper
 
 PRODUCT_PACKAGES += \
     audio \
diff --git a/target/product/languages_full.mk b/target/product/languages_full.mk
index 9f6c9ca..4cddc06 100644
--- a/target/product/languages_full.mk
+++ b/target/product/languages_full.mk
@@ -21,4 +21,4 @@
 
 # These are all the locales that have translations and are displayable
 # by TextView in this branch.
-PRODUCT_LOCALES := en_US fr_FR it_IT es_ES de_DE nl_NL cs_CZ pl_PL ja_JP zh_TW zh_CN ru_RU ko_KR nb_NO es_US da_DK el_GR tr_TR pt_PT pt_BR rm_CH sv_SE bg_BG ca_ES en_GB fi_FI hi_IN hr_HR hu_HU in_ID iw_IL lt_LT lv_LV ro_RO sk_SK sl_SI sr_RS uk_UA vi_VN tl_PH ar_EG fa_IR th_TH sw_TZ ms_MY af_ZA zu_ZA am_ET hi_IN en_XA ar_XB fr_CA
+PRODUCT_LOCALES := en_US en_IN fr_FR it_IT es_ES et_EE de_DE nl_NL cs_CZ pl_PL ja_JP zh_TW zh_CN zh_HK ru_RU ko_KR nb_NO es_US da_DK el_GR tr_TR pt_PT pt_BR rm_CH sv_SE bg_BG ca_ES en_GB fi_FI hi_IN hr_HR hu_HU in_ID iw_IL lt_LT lv_LV ro_RO sk_SK sl_SI sr_RS uk_UA vi_VN tl_PH ar_EG fa_IR th_TH sw_TZ ms_MY af_ZA zu_ZA am_ET hi_IN en_XA ar_XB fr_CA km_KH lo_LA ne_NP si_LK mn_MN hy_AM az_AZ ka_GE
diff --git a/target/product/large_emu_hw.mk b/target/product/large_emu_hw.mk
index 8a070b1..a918c1d 100644
--- a/target/product/large_emu_hw.mk
+++ b/target/product/large_emu_hw.mk
@@ -26,7 +26,6 @@
     Calculator \
     Calendar \
     CertInstaller \
-    DrmProvider \
     Email \
     Exchange2 \
     Gallery2 \
diff --git a/target/product/mini.mk b/target/product/mini.mk
deleted file mode 100644
index c1074f7..0000000
--- a/target/product/mini.mk
+++ /dev/null
@@ -1,226 +0,0 @@
-# Copyright (C) 2012 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Common configurations for mini_XXX lunch targets
-# This is mainly for creating small system image during early development stage.
-
-PRODUCT_BRAND := mini
-PRODUCT_DEVICE := mini
-PRODUCT_NAME := mini
-
-# add all configurations
-PRODUCT_AAPT_CONFIG := normal ldpi mdpi hdpi xhdpi xxhdpi
-PRODUCT_AAPT_PREF_CONFIG := hdpi
-
-# en_US only
-PRODUCT_LOCALES := en_US
-
-# dummy definitions to use += in later parts
-PRODUCT_PROPERTY_OVERRIDES :=
-PRODUCT_COPY_FILES :=
-
-
-# for CtsVerifier
-PRODUCT_PACKAGES += \
-    com.android.future.usb.accessory
-
-# It does not mean that all features are supproted, but only for meeting
-# configuration requirements for some CTS
-PRODUCT_COPY_FILES += \
-    frameworks/native/data/etc/handheld_core_hardware.xml:system/etc/permissions/handheld_core_hardware.xml \
-    frameworks/native/data/etc/android.hardware.location.gps.xml:system/etc/permissions/android.hardware.location.gps.xml \
-    frameworks/native/data/etc/android.hardware.sensor.light.xml:system/etc/permissions/android.hardware.sensor.light.xml \
-    frameworks/native/data/etc/android.hardware.sensor.barometer.xml:system/etc/permissions/android.hardware.sensor.barometer.xml \
-    frameworks/native/data/etc/android.hardware.sensor.gyroscope.xml:system/etc/permissions/android.hardware.sensor.gyroscope.xml \
-    frameworks/native/data/etc/android.hardware.usb.accessory.xml:system/etc/permissions/android.hardware.usb.accessory.xml
-
-#----------------- originally from core.mk ----------------
-
-PRODUCT_PROPERTY_OVERRIDES += \
-    ro.config.notification_sound=OnTheHunt.ogg \
-    ro.config.alarm_alert=Alarm_Classic.ogg
-
-# Please keep this list sorted alphabetically
-PRODUCT_PACKAGES += \
-    ApplicationsProvider \
-    ContactsProvider \
-    DefaultContainerService \
-    DownloadProvider \
-    DownloadProviderUi \
-    MediaProvider \
-    PackageInstaller \
-    SettingsProvider \
-    Shell \
-    TelephonyProvider \
-    UserDictionaryProvider \
-    apache-xml \
-    audio \
-    bouncycastle \
-    bu \
-    cacerts \
-    com.android.location.provider \
-    com.android.location.provider.xml \
-    conscrypt \
-    core \
-    core-junit \
-    dalvikvm \
-    dexdeps \
-    dexdump \
-    dexlist \
-    dexopt \
-    dmtracedump \
-    drmserver \
-    dx \
-    ext \
-    framework-res \
-    hprof-conv \
-    installd \
-    ip \
-    ip-up-vpn \
-    ip6tables \
-    iptables \
-    keystore \
-    keystore.default \
-    libandroidfw \
-    libOpenMAXAL \
-    libOpenSLES \
-    libaudiopreprocessing \
-    libaudioutils \
-    libbcc \
-    libcrypto \
-    libdownmix \
-    libdvm \
-    libdrmframework \
-    libdrmframework_jni \
-    libexpat \
-    libfilterfw \
-    libfilterpack_imageproc \
-    libgabi++ \
-    libicui18n \
-    libicuuc \
-    libjavacore \
-    libkeystore \
-    libmdnssd \
-    libnativehelper \
-    libnfc_ndef \
-    libportable \
-    libpowermanager \
-    libspeexresampler \
-    libsqlite_jni \
-    libssl \
-    libstagefright \
-    libstagefright_chromium_http \
-    libstagefright_soft_aacdec \
-    libstagefright_soft_aacenc \
-    libstagefright_soft_amrdec \
-    libstagefright_soft_amrnbenc \
-    libstagefright_soft_amrwbenc \
-    libstagefright_soft_flacenc \
-    libstagefright_soft_g711dec \
-    libstagefright_soft_gsmdec \
-    libstagefright_soft_h264dec \
-    libstagefright_soft_h264enc \
-    libstagefright_soft_mp3dec \
-    libstagefright_soft_mpeg4dec \
-    libstagefright_soft_mpeg4enc \
-    libstagefright_soft_vorbisdec \
-    libstagefright_soft_vpxdec \
-    libstagefright_soft_rawdec \
-    libvariablespeed \
-    libwebrtc_audio_preprocessing \
-    libwilhelm \
-    libz \
-    mdnsd \
-    network \
-    okhttp \
-    pand \
-    requestsync \
-    screencap \
-    sdptool \
-    sensorservice \
-    lint \
-    telephony-common \
-    voip-common \
-    mms-common
-
-PRODUCT_COPY_FILES += \
-    system/core/rootdir/init.usb.rc:root/init.usb.rc \
-
-#----------------- originally from generic_no_telephony.mk ----------------
-
-PRODUCT_PACKAGES += \
-    Bluetooth \
-    FusedLocation \
-    InputDevices \
-    LatinIME \
-    Phone \
-    Provision \
-    hostapd \
-    wpa_supplicant.conf
-
-PRODUCT_PACKAGES += \
-    librs_jni \
-    libvideoeditor_jni \
-    libvideoeditor_core \
-    libvideoeditor_osal \
-    libvideoeditor_videofilters \
-    libvideoeditorplayer \
-
-PRODUCT_PACKAGES += \
-    audio.primary.default \
-    audio_policy.default \
-    local_time.default \
-    power.default
-
-PRODUCT_PACKAGES += \
-    local_time.default
-
-PRODUCT_COPY_FILES += \
-    frameworks/av/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf
-
-PRODUCT_PROPERTY_OVERRIDES += \
-    ro.carrier=unknown
-
-#----------------- originally from full_base.mk ----------------
-
-PRODUCT_PACKAGES += \
-    drmserver \
-    libdrmframework \
-    libdrmframework_jni \
-    WAPPushManager
-
-
-# Additional settings used in all AOSP builds
-PRODUCT_PROPERTY_OVERRIDES += \
-    ro.com.android.dateformat=MM-dd-yyyy \
-    ro.config.ringtone=Ring_Synth_04.ogg \
-    ro.config.notification_sound=pixiedust.ogg
-
-$(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
-$(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
-$(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk)
-$(call inherit-product-if-exists, frameworks/base/data/sounds/AudioPackage5.mk)
-
-#----------------- For PDK ------------------------------
-PRODUCT_PACKAGES += \
-    TestingCamera \
-    Home \
-    SystemUI \
-    Settings \
-    libsurfaceflinger_ddmconnection
-
-# This is not necessary for mini, but is for mini-emulator as it should
-# be included in platform.zip
-PRODUCT_PACKAGES += camera.goldfish.jpeg
-
diff --git a/target/product/runtime_common.mk b/target/product/runtime_common.mk
new file mode 100644
index 0000000..faa6fe8
--- /dev/null
+++ b/target/product/runtime_common.mk
@@ -0,0 +1,58 @@
+#
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Common runtime modules for both Dalvik and ART
+
+PRODUCT_PACKAGES += \
+    apache-xml \
+    bouncycastle \
+    cacerts \
+    conscrypt \
+    core-junit \
+    dalvikvm \
+    dexdeps \
+    dexdump \
+    dexlist \
+    dmtracedump \
+    dx \
+    ext \
+    hprof-conv \
+    libcrypto \
+    libexpat \
+    libicui18n \
+    libicuuc \
+    libjavacore \
+    libnativehelper \
+    libssl \
+    libz \
+    okhttp
+
+# host-only dependencies
+ifeq ($(WITH_HOST_DALVIK),true)
+    PRODUCT_PACKAGES += \
+        apache-xml-hostdex \
+        bouncycastle-hostdex \
+        conscrypt-hostdex \
+        dalvik \
+        libcrypto-host \
+        libexpat-host \
+        libicui18n-host \
+        libicuuc-host \
+        libjavacore \
+        libssl-host \
+        libz-host \
+        okhttp-hostdex
+endif
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
new file mode 100644
index 0000000..5fddc3f
--- /dev/null
+++ b/target/product/runtime_libart.mk
@@ -0,0 +1,34 @@
+#
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Provides a functioning ART environment without Android frameworks
+
+PRODUCT_PACKAGES += \
+        core-libart \
+        libart \
+        dex2oat \
+        oatdump
+
+# host-only dependencies
+ifeq ($(WITH_HOST_DALVIK),true)
+    PRODUCT_PACKAGES += \
+        core-libart-hostdex
+endif
+
+# We currently don't suport DEX_PREOPT for art
+DEX_PREOPT_DEFAULT := nostripping
+
+include $(SRC_TARGET_DIR)/product/runtime_common.mk
diff --git a/target/product/runtime_libart_default.mk b/target/product/runtime_libart_default.mk
new file mode 100644
index 0000000..575ca04
--- /dev/null
+++ b/target/product/runtime_libart_default.mk
@@ -0,0 +1,22 @@
+#
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Set ART as the default runtime environment
+
+PRODUCT_PROPERTY_OVERRIDES += \
+    persist.sys.dalvik.vm.lib=libart.so
+
+include $(SRC_TARGET_DIR)/product/runtime_libart.mk
diff --git a/target/product/runtime_libdvm.mk b/target/product/runtime_libdvm.mk
new file mode 100644
index 0000000..42e86ed
--- /dev/null
+++ b/target/product/runtime_libdvm.mk
@@ -0,0 +1,35 @@
+#
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Provides a functioning Dalvik environment without Android frameworks
+
+PRODUCT_PACKAGES += \
+    core \
+    libdvm \
+    dexopt
+
+# host-only dependencies
+ifeq ($(WITH_HOST_DALVIK),true)
+    PRODUCT_PACKAGES += \
+        core-hostdex
+endif
+
+# If runtime_libart has disabled, do not override
+ifndef DEX_PREOPT_DEFAULT
+DEX_PREOPT_DEFAULT := true
+endif
+
+include $(SRC_TARGET_DIR)/product/runtime_common.mk
diff --git a/target/product/runtime_libdvm_default.mk b/target/product/runtime_libdvm_default.mk
new file mode 100644
index 0000000..3ae4130
--- /dev/null
+++ b/target/product/runtime_libdvm_default.mk
@@ -0,0 +1,22 @@
+#
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Set Dalvik as the default runtime environment
+
+PRODUCT_PROPERTY_OVERRIDES += \
+    persist.sys.dalvik.vm.lib=libdvm.so
+
+include $(SRC_TARGET_DIR)/product/runtime_libdvm.mk
diff --git a/target/product/sdk.mk b/target/product/sdk.mk
index c0f8472..bc59782 100644
--- a/target/product/sdk.mk
+++ b/target/product/sdk.mk
@@ -24,13 +24,15 @@
 	Exchange2 \
 	FusedLocation \
 	Gallery \
+	Keyguard \
 	Music \
 	Mms \
 	OpenWnn \
+	PrintSpooler \
 	libWnnEngDic \
 	libWnnJpnDic \
 	libwnndict \
-	Phone \
+	TeleService \
 	PinyinIME \
 	Protips \
 	SoftKeyboard \
@@ -38,7 +40,6 @@
 	Launcher2 \
 	Development \
 	DevelopmentSettings \
-	DrmProvider \
 	Fallback \
 	Settings \
 	SdkSetup \
diff --git a/tools/Android.mk b/tools/Android.mk
index f646c37..30febd6 100644
--- a/tools/Android.mk
+++ b/tools/Android.mk
@@ -14,10 +14,10 @@
 # limitations under the License.
 #
 
-ifeq (,$(TARGET_BUILD_APPS))
-
 LOCAL_PATH := $(call my-dir)
 
+ifeq (,$(TARGET_BUILD_APPS))
+
 ifeq ($(TARGET_BUILD_PDK),true)
 include $(filter-out %/acp/Android.mk %/signapk/Android.mk %/zipalign/Android.mk,\
   $(call all-makefiles-under,$(LOCAL_PATH)))
@@ -25,4 +25,8 @@
 include $(call all-makefiles-under,$(LOCAL_PATH))
 endif # PDK
 
+else # TARGET_BUILD_APPS
+
+include $(LOCAL_PATH)/apicheck/Android.mk
+
 endif
diff --git a/tools/droiddoc/templates-pdk/components/masthead.cs b/tools/droiddoc/templates-pdk/components/masthead.cs
index e11c63c..a581618 100644
--- a/tools/droiddoc/templates-pdk/components/masthead.cs
+++ b/tools/droiddoc/templates-pdk/components/masthead.cs
@@ -2,7 +2,7 @@
 def:custom_masthead() ?>
   <div id="header">
       <div id="headerLeft">
-          <a href="<?cs var:toroot?>" tabindex="-1"><img
+          <a href="<?cs var:toroot ?>guide/getting_started.html"><img
               src="<?cs var:toroot ?>assets/images/open_source.png" alt="Android Open Source Project" /></a>
        
       </div>
@@ -16,4 +16,4 @@
           </div>
       </div><!-- headerRight -->
   </div><!-- header --><?cs 
-/def ?><?cs # custom_masthead ?>
\ No newline at end of file
+/def ?><?cs # custom_masthead ?>
diff --git a/tools/droiddoc/templates-sdk/assets/css/default.css b/tools/droiddoc/templates-sdk/assets/css/default.css
index 3bfb687..36c3cc4 100644
--- a/tools/droiddoc/templates-sdk/assets/css/default.css
+++ b/tools/droiddoc/templates-sdk/assets/css/default.css
@@ -305,6 +305,8 @@
       position: absolute;
       top: 0;
       right: 0; }
+    #nav .nav-section-header.empty {
+      padding:0; }
     #nav .nav-section-header.empty:after {
       display: none; }
     /* nested nav headers */
@@ -338,7 +340,7 @@
       width: 34px;
       height: 34px; }
   #nav li.expanded li ul.tree-list-children {
-    padding:0;
+    padding: 0;
   }
   #nav li.expanded li ul.tree-list-children .tree-list-children {
     padding:0 0 0 10px;
@@ -470,6 +472,10 @@
       height: 10px;
       display: inline-block;
       margin-left: 5px; }
+    .prev-page-link.inline:before {
+      content: none; }
+    .next-page-link.inline:after {
+      content: none; }
 
 
   .training-nav-top a {
@@ -854,7 +860,20 @@
   .framed-nexus4-port-216 img {
     width: 216px;
     height: 360px; }
+    
+.framed-nexus5-port-span-5 {
+  background: transparent url(../images/styles/device_nexus5_blank_port_span5.png) no-repeat
+  scroll top left;
+  padding: 52px 33px 69px 31px;
+  overflow: hidden;
+}
 
+.framed-nexus5-port-span-5,
+.framed-nexus5-port-span-5 video,
+.framed-nexus5-port-span-5 img {
+  width: 216px;
+  height: 384px;
+}
 
 /* landing page disclosures */
 .landing-page-link {
@@ -2358,6 +2377,7 @@
 #jd-content img.toggle-content-img {
   margin:0 5px 5px 0;
 }
+
 div.toggle-content-toggleme {
   padding:0 0 0 15px;
 }
@@ -2443,6 +2463,167 @@
   background-position: -10px 0;
 }
 
+
+/* --------------------------------------------------------------------------
+Styles for samples project trees and code browsing in resources tab 
+*/
+
+#codesample-wrapper {
+  width:1000px;
+  overflow:visible;
+}
+pre#codesample-block {
+  float:left;
+  overflow:visible;
+  background:transparent;
+  border:none;
+}
+pre#codesample-block .code-line:hover {
+  background:#e7e7e7;
+}
+pre#codesample-line-numbers {
+  float:left;
+  width:2em;
+  background:transparent;
+  border:none;
+  border-right:1px solid #ccc;
+  padding-left:0;
+  font-family:monospace;
+  text-align:right;
+  -webkit-touch-callout: none;
+  -webkit-user-select: none;
+  -khtml-user-select: none;
+  -moz-user-select: -moz-none;
+  -ms-user-select: none;
+  user-select: none;
+}
+pre#codesample-line-numbers a {
+  color:#999;
+}
+pre#codesample-line-numbers.hidden {
+  display:none;
+}
+pre#codesample-block span.code-line {
+  width:100%;
+  display:inline-block;
+}
+
+.structure-dir {
+background-image:url(../../assets/images/folder.png);
+background-repeat:no-repeat;
+background-position:16px 2px;
+  margin:.25em 0 0 0;
+  padding:0 0 0 0;
+}
+
+.structure-toggleme {
+  margin:0 0 0 3em;
+  padding:0 0 0 0;
+  text-decoration:none;
+}
+
+.structure-java{
+background-image:url(../../assets/images/file-java.png);
+background-repeat:no-repeat;
+background-position:0px 2px;
+  margin:.3em 0 0 0;
+  padding:.3em 0 .3em 22px;
+}
+
+.structure-file {
+background-image:url(../../assets/images/file-generic.png);
+background-repeat:no-repeat;
+background-position:0px 2px;
+  margin:.3em 0 0 0;
+  padding:.3em 0 .3em 22px;
+}
+
+.structure-xml {
+background-image:url(../../assets/images/file-xml.png);
+background-repeat:no-repeat;
+background-position:0px 2px;
+  margin:.3em 0 0 0;
+  padding:.3em 0 .25em 22px;
+}
+
+.structure-img {
+background-image:url(../../assets/images/file-image.png);
+background-repeat:no-repeat;
+background-position:0px 2px;
+  margin:.3em 0 0 0;
+  padding:.3em 0 .25em 22px;
+}
+
+.structure-manifest {
+background-image:url(../../assets/images/file-manifest.png);
+background-repeat:no-repeat;
+  margin:.0 0 0 1.25em;
+  padding:0 0 0 22px;
+  text-decoration:none;
+}
+
+#jd-content .structure-toggle-img {
+  margin:.5em 0 0 0;
+padding-right:2.1em;
+}
+
+.dirInfo {
+  margin-left:2em;
+}
+
+.structure-dir a {
+  text-decoration:none;
+}
+
+.structure-manifest a {
+  text-decoration: none;
+}
+.structure-file a {
+  text-decoration: none;
+}
+
+.sampleEmbed {
+  background-color:rgb(249, 249, 249);
+}
+
+.sampleEmbed ol.lineNumbers {
+  list-style-type: decimal;
+  padding-left:1em;
+}
+
+.sampleEmbed ol.lineNumbers li {
+border-left:1px solid #ddd;
+border-right:1px solid #ddd;
+color:gray;
+background-color:#f7f7f7;
+margin:0 0 0 24px;
+padding: 2px 2px 2px 6px;
+}
+
+.sampleEmbed ol.lineNumbers li:hover {
+background: #efefef;
+}
+
+.samples-nav li a {
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+/* --------------------------------------------------------------------------
+Styles for raw formatted line numbers (not used with listformatted version)
+div.sampleLine div.lineNumber {
+  display: inline;
+}
+div.sampleLine div.lineCode {
+  display: inline;
+  padding-left:6px;
+}
+div.sampleLine {
+  padding:0;
+  margin:0;
+}*/
+
 /* --------------------------------------------------------------------------
 Butterbar
 */
@@ -2489,10 +2670,10 @@
 .caption {
   margin: 0.5em 0 2em 0;
   color: #000;
-  font-size: 11.5px;
+  font-size: 11.5px; 
 }
 
-.nolist {
+.nolist, .nolist ul, .nolist ol {
   list-style:none;
   margin-left:0;
 }
@@ -4196,7 +4377,6 @@
 
 .jspPane {
   position: absolute;
-  overflow: hidden;
   width:100% !important; /* to avoid cut-off api names in reference in horiz scroll */
 }
 
diff --git a/tools/droiddoc/templates-sdk/assets/images/file-generic.png b/tools/droiddoc/templates-sdk/assets/images/file-generic.png
new file mode 100644
index 0000000..1802457
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/file-generic.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/file-image.png b/tools/droiddoc/templates-sdk/assets/images/file-image.png
new file mode 100644
index 0000000..d3aec46
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/file-image.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/file-java.png b/tools/droiddoc/templates-sdk/assets/images/file-java.png
new file mode 100644
index 0000000..ec85e4b
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/file-java.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/file-manifest.png b/tools/droiddoc/templates-sdk/assets/images/file-manifest.png
new file mode 100644
index 0000000..332d066
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/file-manifest.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/file-xml.png b/tools/droiddoc/templates-sdk/assets/images/file-xml.png
new file mode 100644
index 0000000..3dd21b6
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/file-xml.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/folder.png b/tools/droiddoc/templates-sdk/assets/images/folder.png
new file mode 100644
index 0000000..44c6100
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/folder.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/images/styles/device_nexus5_blank_port_span5.png b/tools/droiddoc/templates-sdk/assets/images/styles/device_nexus5_blank_port_span5.png
new file mode 100644
index 0000000..df35117
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/assets/images/styles/device_nexus5_blank_port_span5.png
Binary files differ
diff --git a/tools/droiddoc/templates-sdk/assets/js/docs.js b/tools/droiddoc/templates-sdk/assets/js/docs.js
index fa7554b..1659cc6 100644
--- a/tools/droiddoc/templates-sdk/assets/js/docs.js
+++ b/tools/droiddoc/templates-sdk/assets/js/docs.js
@@ -183,12 +183,13 @@
         $("#nav-x li.google a").addClass("selected");
       } else {
         $("#nav-x li.reference a").addClass("selected");
-        changeApiLevel();  // turn things grey
       }
     } else if ((rootDir == "tools") || (rootDir == "sdk")) {
       $("#nav-x li.tools a").addClass("selected");
     } else if ($("body").hasClass("google")) {
       $("#nav-x li.google a").addClass("selected");
+    } else if ($("body").hasClass("samples")) {
+      $("#nav-x li.samples a").addClass("selected");
     }
 
   // highlight Distribute tab
@@ -352,35 +353,9 @@
     $('.jd-descr').append($olClasses);
   }
 
-
-
-
   // Set up expand/collapse behavior
-  $('#nav li.nav-section .nav-section-header').click(function() {
-    var section = $(this).closest('li.nav-section');
-    if (section.hasClass('expanded')) {
-    /* hide me */
-    //  if (section.hasClass('selected') || section.find('li').hasClass('selected')) {
-   //   /* but not if myself or my descendents are selected */
-   //     return;
-    //  }
-      section.children('ul').slideUp(250, function() {
-        section.closest('li').removeClass('expanded');
-        resizeNav();
-      });
-    } else {
-    /* show me */
-      // first hide all other siblings
-      var $others = $('li.nav-section.expanded', $(this).closest('ul'));
-      $others.removeClass('expanded').children('ul').slideUp(250);
+  initExpandableNavItems("#nav");
 
-      // now expand me
-      section.closest('li').addClass('expanded');
-      section.children('ul').slideDown(250, function() {
-        resizeNav();
-      });
-    }
-  });
 
   $(".scroll-pane").scroll(function(event) {
       event.preventDefault();
@@ -474,13 +449,6 @@
   }
 
 
-  // Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
-  // from the page)
-  $('.nav-section-header').find('a:eq(0)').click(function(evt) {
-    window.location.href = $(this).attr('href');
-    return false;
-  });
-
   // Set up play-on-hover <video> tags.
   $('video.play-on-hover').bind('click', function(){
     $(this).get(0).load(); // in case the video isn't seekable
@@ -585,12 +553,56 @@
 // END of the onload event
 
 
+function initExpandableNavItems(rootTag) {
+  $(rootTag + ' li.nav-section .nav-section-header').click(function() {
+    var section = $(this).closest('li.nav-section');
+    if (section.hasClass('expanded')) {
+    /* hide me and descendants */
+      section.find('ul').slideUp(250, function() {
+        // remove 'expanded' class from my section and any children
+        section.closest('li').removeClass('expanded');
+        $('li.nav-section', section).removeClass('expanded');
+        resizeNav();
+      });
+    } else {
+    /* show me */
+      // first hide all other siblings
+      var $others = $('li.nav-section.expanded', $(this).closest('ul'));
+      $others.removeClass('expanded').children('ul').slideUp(250);
+
+      // now expand me
+      section.closest('li').addClass('expanded');
+      section.children('ul').slideDown(250, function() {
+        resizeNav();
+      });
+    }
+  });
+
+  // Stop expand/collapse behavior when clicking on nav section links
+  // (since we're navigating away from the page)
+  // This selector captures the first instance of <a>, but not those with "#" as the href.
+  $('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
+    window.location.href = $(this).attr('href');
+    return false;
+  });
+}
+
+/** Highlight the current page in sidenav, expanding children as appropriate */
 function highlightSidenav() {
-  // select current page in sidenav and header, and set up prev/next links if they exist
-  var $selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
+  // if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
+  if ($("ul#nav li.selected").length) {
+    unHighlightSidenav();
+  }
+  // look for URL in sidenav, including the hash
+  var $selNavLink = $('#nav').find('a[href="' + mPagePath + location.hash + '"]');
+
+  // If the selNavLink is still empty, look for it without the hash
+  if ($selNavLink.length == 0) {
+    $selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
+  }
+
   var $selListItem;
   if ($selNavLink.length) {
-
     // Find this page's <li> in sidenav and set selected
     $selListItem = $selNavLink.closest('li');
     $selListItem.addClass('selected');
@@ -603,6 +615,10 @@
   }
 }
 
+function unHighlightSidenav() {
+  $("ul#nav li.selected").removeClass("selected");
+  $('ul#nav li.nav-section.expanded').removeClass('expanded').children('ul').hide();
+}
 
 function toggleFullscreen(enable) {
   var delay = 20;
@@ -641,13 +657,6 @@
   $('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
 }
 
-
-
-
-
-
-
-
 // TODO: use $(document).ready instead
 function addLoadEvent(newfun) {
   var current = window.onload;
@@ -671,10 +680,10 @@
 }
 
 
-addLoadEvent( function() {
+$(document).ready(function() {
   $("pre:not(.no-pretty-print)").addClass("prettyprint");
   prettyPrint();
-} );
+});
 
 
 
@@ -825,14 +834,13 @@
       // If no selected item found, exit
       return;
     }
-
-    var selectedOffset = $selected.offset().top; // measure offset from top, relative to entire page
-    if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up any
-                                               // items more than 80% down the nav
-      // scroll the item up by an amount 125px less than the window height (account for site header)
-      // and then multiply nav height by .8 to match the 80% threshold used above
-      api.scrollTo(0, selectedOffset - 125 - ($nav.height() * .8), false);
-
+    // get the selected item's offset from its container nav by measuring the item's offset
+    // relative to the document then subtract the container nav's offset relative to the document
+    var selectedOffset = $selected.offset().top - $nav.offset().top;
+    if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
+                                               // if it's more than 80% down the nav
+      // scroll the item up by an amount equal to 80% the container nav's height
+      api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
     }
   }
 }
@@ -1128,18 +1136,20 @@
 /* Used to hide and reveal supplemental content, such as long code samples.
    See the companion CSS in android-developer-docs.css */
 function toggleContent(obj) {
-  var div = $(obj.parentNode.parentNode);
-  var toggleMe = $(".toggle-content-toggleme",div);
+  var div = $(obj).closest(".toggle-content");
+  var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
   if (div.hasClass("closed")) { // if it's closed, open it
     toggleMe.slideDown();
-    $(".toggle-content-text", obj).toggle();
+    $(".toggle-content-text:eq(0)", obj).toggle();
     div.removeClass("closed").addClass("open");
-    $(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot
+    $(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
                   + "assets/images/triangle-opened.png");
   } else { // if it's open, close it
     toggleMe.slideUp('fast', function() {  // Wait until the animation is done before closing arrow
-      $(".toggle-content-text", obj).toggle();
+      $(".toggle-content-text:eq(0)", obj).toggle();
       div.removeClass("open").addClass("closed");
+      div.find(".toggle-content").removeClass("open").addClass("closed")
+              .find(".toggle-content-toggleme").hide();
       $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
                   + "assets/images/triangle-closed.png");
     });
@@ -2146,6 +2156,12 @@
 
 // when an event on the browser history occurs (back, forward, load) requery hash and do search
 $(window).hashchange( function(){
+  // Handle hash changes in the samples browser
+  if ($("body").hasClass("samples") && location.href.indexOf("/samples/index.html") != -1) {
+    showSamples();
+    highlightSidenav();
+    resizeNav();
+  }
   // Exit if the hash isn't a search query or there's an error in the query
   if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
     // If the results pane is open, close it.
@@ -2232,10 +2248,10 @@
 /* ######################################################## */
 
 /* Initialize some droiddoc stuff, but only if we're in the reference */
-if (location.pathname.indexOf("/reference")) {
-  if(!location.pathname.indexOf("/reference-gms/packages.html")
-    && !location.pathname.indexOf("/reference-gcm/packages.html")
-    && !location.pathname.indexOf("/reference/com/google") == 0) {
+if (location.pathname.indexOf("/reference") == 0) {
+  if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
+    && !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
+    && !(location.pathname.indexOf("/reference/com/google") == 0)) {
     $(document).ready(function() {
       // init available apis based on user pref
       changeApiLevel();
@@ -2579,6 +2595,13 @@
   }
 }
 
+
+
+
+
+
+
+
 /* TODO: eliminate redundancy with non-google functions */
 function init_google_navtree(navtree_id, toroot, root_nodes)
 {
@@ -2664,6 +2687,72 @@
           node_data[2], node_data[3]);
   }
 }
+
+
+
+
+
+
+/****** NEW version of script to build google and sample navs dynamically ******/
+// TODO: update Google reference docs to tolerate this new implementation
+
+var NODE_NAME = 0;
+var NODE_HREF = 1;
+var NODE_GROUP = 2;
+var NODE_TAGS = 3;
+var NODE_CHILDREN = 4;
+
+function init_google_navtree2(navtree_id, data)
+{
+  var $containerUl = $("#"+navtree_id);
+  for (var i in data) {
+    var node_data = data[i];
+    $containerUl.append(new_google_node2(node_data));
+  }
+
+  initExpandableNavItems("#"+navtree_id);
+}
+
+function new_google_node2(node_data)
+{
+  var linkText = node_data[NODE_NAME];
+  if(linkText.match("^"+"com.google.android")=="com.google.android"){
+    linkText = linkText.substr(19, linkText.length);
+  }
+  var $li = $('<li>');
+  var $a;
+  if (node_data[NODE_HREF] != null) {
+    $a = $('<a href="' + toRoot + node_data[NODE_HREF] + '">' + linkText + '</a>');
+  } else {
+    $a = $('<a href="#" onclick="return false;">' + linkText + '/</a>');
+  }
+  var $childUl = $('<ul>');
+  if (node_data[NODE_CHILDREN] != null) {
+    $li.addClass("nav-section");
+    $a = $('<div class="nav-section-header">').append($a);
+    if (node_data[NODE_HREF] == null) $a.addClass('empty');
+
+    for (var i in node_data[NODE_CHILDREN]) {
+      var child_node_data = node_data[NODE_CHILDREN][i];
+      $childUl.append(new_google_node2(child_node_data));
+    }
+    $li.append($childUl);
+  }
+  $li.prepend($a);
+
+  return $li;
+}
+
+
+
+
+
+
+
+
+
+
+
 function showGoogleRefTree() {
   init_default_google_navtree(toRoot);
   init_default_gcm_navtree(toRoot);
@@ -2693,6 +2782,22 @@
   });
 }
 
+function showSamplesRefTree() {
+  init_default_samples_navtree(toRoot);
+}
+
+function init_default_samples_navtree(toroot) {
+  // load json file for navtree data
+  $.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
+      // when the file is loaded, initialize the tree
+      if(jqxhr.status === 200) {
+          init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
+          highlightSidenav();
+          resizeNav();
+      }
+  });
+}
+
 /* TOGGLE INHERITED MEMBERS */
 
 /* Toggle an inherited class (arrow toggle)
@@ -2786,3 +2891,62 @@
     ensureAllInheritedExpanded();
   }
 });
+
+
+
+
+
+
+/* On-demand functions */
+
+/** Move sample code line numbers out of PRE block and into non-copyable column */
+function initCodeLineNumbers() {
+  var numbers = $("#codesample-block a.number");
+  if (numbers.length) {
+    $("#codesample-line-numbers").removeClass("hidden").append(numbers);
+  }
+
+  $(document).ready(function() {
+    // select entire line when clicked
+    $("span.code-line").click(function() {
+      if (!shifted) {
+        selectText(this);
+      }
+    });
+    // invoke line link on double click
+    $(".code-line").dblclick(function() {
+      document.location.hash = $(this).attr('id');
+    });
+    // highlight the line when hovering on the number
+    $("#codesample-line-numbers a.number").mouseover(function() {
+      var id = $(this).attr('href');
+      $(id).css('background','#e7e7e7');
+    });
+    $("#codesample-line-numbers a.number").mouseout(function() {
+      var id = $(this).attr('href');
+      $(id).css('background','none');
+    });
+  });
+}
+
+// create SHIFT key binder to avoid the selectText method when selecting multiple lines
+var shifted = false;
+$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
+
+// courtesy of jasonedelman.com
+function selectText(element) {
+    var doc = document
+        , range, selection
+    ;
+    if (doc.body.createTextRange) { //ms
+        range = doc.body.createTextRange();
+        range.moveToElementText(element);
+        range.select();
+    } else if (window.getSelection) { //all others
+        selection = window.getSelection();        
+        range = doc.createRange();
+        range.selectNodeContents(element);
+        selection.removeAllRanges();
+        selection.addRange(range);
+    }
+}
diff --git a/tools/droiddoc/templates-sdk/components/masthead.cs b/tools/droiddoc/templates-sdk/components/masthead.cs
index 4f3273c..f3eb401 100644
--- a/tools/droiddoc/templates-sdk/components/masthead.cs
+++ b/tools/droiddoc/templates-sdk/components/masthead.cs
@@ -188,6 +188,10 @@
                         </li>
                         <li><a href="<?cs var:toroot ?>google/index.html">Google Services</a>
                         </li>
+                        <?cs if:android.hasSamples ?>
+                          <li><a href="<?cs var:toroot ?>samples/index.html">Samples</a>
+                          </li>
+                        <?cs /if ?>
                       </ul>
                     </li>
                     <li class="distribute last">
@@ -214,7 +218,7 @@
   </div>
     
     
-  <?cs if:training || guide || reference || tools || develop || google ?>
+  <?cs if:training || guide || reference || tools || develop || google || samples ?>
     <!-- Secondary x-nav -->
     <div id="nav-x">
         <div class="wrap">
@@ -254,6 +258,11 @@
                 <li class="google"><a href="<?cs var:toroot ?>google/index.html"
                   >Google Services</a>
                 </li>
+                <?cs if:android.hasSamples ?>
+                  <li class="samples"><a href="<?cs var:toroot ?>samples/index.html"
+                    >Samples</a>
+                  </li>
+                <?cs /if ?>
             </ul>
         </div>
         
diff --git a/tools/droiddoc/templates-sdk/customizations.cs b/tools/droiddoc/templates-sdk/customizations.cs
index 33edbde..985f059 100644
--- a/tools/droiddoc/templates-sdk/customizations.cs
+++ b/tools/droiddoc/templates-sdk/customizations.cs
@@ -135,6 +135,30 @@
 <?cs /def ?>
 
 <?cs
+def:samples_nav() ?>
+  <div class="wrap clearfix" id="body-content">
+    <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
+      <div id="devdoc-nav" class="scroll-pane">
+<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
+
+<?cs
+        include:"../../../../frameworks/base/docs/html/samples/samples_toc.cs" ?>
+
+
+      </div>
+      <script type="text/javascript">
+       showSamplesRefTree();
+
+      </script>
+    </div> <!-- end side-nav -->
+    <script>
+      $(document).ready(function() {
+        scrollIntoView("devdoc-nav");
+        });
+    </script>
+<?cs /def ?>
+
+<?cs
 def:google_nav() ?>
   <div class="wrap clearfix" id="body-content">
     <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
@@ -177,28 +201,7 @@
         });
     </script>
 <?cs /def ?>
-<?cs
-def:dist_more_nav() ?>
-  <div class="wrap clearfix" id="body-content">
-    <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
-      <div id="devdoc-nav" class="scroll-pane">
-<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
 
-
-<?cs 
-        include:"../../../../frameworks/base/docs/html/distribute/more/more_toc.cs" ?>
-        
-
-      </div>
-    </div> <!-- end side-nav -->
-    <script>
-      $(document).ready(function() {
-        scrollIntoView("devdoc-nav");
-        });
-    </script>
-:
-
-<?cs /def ?>
 <?cs # The default side navigation for the reference docs ?><?cs 
 def:default_left_nav() ?>
 <?cs if:reference.gcm || reference.gms ?>
@@ -322,6 +325,8 @@
     call:tools_nav() ?><?cs
   elif:google ?><?cs 
     call:google_nav() ?><?cs 
+  elif:samples ?><?cs
+    call:samples_nav() ?><?cs
   elif:more ?><?cs 
     call:dist_more_nav() ?><?cs
   elif:distribute ?><?cs 
diff --git a/tools/droiddoc/templates-sdk/docpage.cs b/tools/droiddoc/templates-sdk/docpage.cs
index 90e663b..6faac04 100644
--- a/tools/droiddoc/templates-sdk/docpage.cs
+++ b/tools/droiddoc/templates-sdk/docpage.cs
@@ -3,7 +3,7 @@
 <html<?cs if:devsite ?> devsite<?cs /if ?>>
 <?cs include:"head_tag.cs" ?>
 <body class="gc-documentation <?cs if:(google || reference.gms || reference.gcm) ?>google<?cs /if ?>
-  <?cs if:(guide||develop||training||reference||tools||sdk) ?>develop<?cs if:guide ?> guide<?cs /if ?><?cs
+  <?cs if:(guide||develop||training||reference||tools||sdk||samples) ?>develop<?cs if:guide ?> guide<?cs /if ?><?cs if:samples ?> samples<?cs /if ?><?cs
   elif:about ?>about<?cs
   elif:design ?>design<?cs
   elif:distribute ?>distribute<?cs
@@ -130,7 +130,7 @@
         </div>
         <?cs if:!fullscreen ?>
         <div class="paging-links layout-content-col col-4">
-          <?cs if:(design||training||guide||walkthru) && !page.landing && !page.trainingcourse && !footer.hide ?>
+          <?cs if:(design||training||walkthru) && !page.landing && !page.trainingcourse && !footer.hide ?>
             <a href="#" class="prev-page-link hide"
                 zh-tw-lang="上一堂課"
                 zh-cn-lang="上一课"
diff --git a/tools/droiddoc/templates-sdk/head_tag.cs b/tools/droiddoc/templates-sdk/head_tag.cs
index 9778389..379829c 100644
--- a/tools/droiddoc/templates-sdk/head_tag.cs
+++ b/tools/droiddoc/templates-sdk/head_tag.cs
@@ -1,8 +1,9 @@
 <head>
-<?cs ####### If building devsite, add some meta data needed for when generating the top nav ######### ?>
+<?cs
+  ####### If building devsite, add some meta data needed for when generating the top nav ######### ?>
 <?cs
   if:devsite ?><?cs
-    if:guide||develop||training||reference||tools||sdk||google
+    if:guide||develop||training||reference||tools||sdk||google||samples
       ?><meta name="top_category" value="develop" /><?cs
     elif:google
       ?><meta name="top_category" value="google" /><?cs
@@ -11,12 +12,17 @@
     /if ?>
   <?cs
   /if
-?><?cs # END if/else devsite ?>
-
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-<?cs if:page.metaDescription ?>
-<meta name="Description" content="<?cs var:page.metaDescription ?>">
-<?cs /if ?>
+?><?cs
+  # END if/else devsite ?>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta name="viewport" content="width=device-width" />
+<?cs
+  if:page.metaDescription ?>
+<meta name="Description" content="<?cs var:page.metaDescription ?>"><?cs
+  /if ?><?cs
+  if:page.customHeadTag ?>
+<?cs var:page.customHeadTag ?><?cs
+  /if ?>
 <link rel="shortcut icon" type="image/x-icon" href="<?cs var:toroot ?>favicon.ico" />
 <title><?cs 
   if:page.title ?><?cs 
diff --git a/tools/droiddoc/templates-sdk/sample.cs b/tools/droiddoc/templates-sdk/sample.cs
new file mode 100644
index 0000000..a8eaf8c
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/sample.cs
@@ -0,0 +1,99 @@
+<?cs include:"doctype.cs" ?>
+<?cs include:"macros.cs" ?>
+<html<?cs if:devsite ?> devsite<?cs /if ?>>
+<?cs include:"head_tag.cs" ?>
+<body class="gc-documentation develop samples" itemscope itemtype="http://schema.org/Article">
+<?cs include:"header.cs" ?>
+
+<div <?cs if:fullpage
+?>class="fullpage"<?cs elif:design||tools||about||sdk||distribute
+?>class="col-13" id="doc-col"<?cs else 
+?>class="col-12" id="doc-col"<?cs /if ?> >
+
+<!-- start breadcrumb block -->
+<div id="api-info-block">
+  <div class="sum-details-links">
+
+  <!-- related links -->
+  <a href="<?cs var:toroot ?>samples/<?cs var:projectDir ?>/index.html">Overview</a>
+  &#124; <a href="<?cs var:toroot ?>samples/<?cs var:projectDir ?>/project.html">Project</a>
+  &#124; <a href="<?cs var:toroot ?>downloads/samples/<?cs var:projectDir ?>.zip">Download</a>
+
+  </div><!-- end sum-details-links -->
+  <div class="api-level">
+  Other info
+  </div>
+</div> <!-- end api-info-block -->
+
+<div id="jd-header" style="border:0;">
+
+<div id="pathCrumb">
+<?cs each:item = parentdirs ?>
+  <?cs if:pathCrumbLinks
+    ?><a href="<?cs var:toroot ?><?cs var:item.Link ?>"><?cs var:item.Name ?></a> / 
+  <?cs else
+    ?><?cs var:item.Name ?> / <?cs /if ?>
+<?cs /each ?>
+</div>
+
+  <h1 itemprop="name"><?cs var:page.title ?></h1>
+</div>
+<!-- end breadcrumb block -->
+
+
+<?cs # THIS IS THE MAIN DOC CONTENT ?>
+<div id="jd-content">
+
+<?cs if:android.whichdoc == "online" ?>
+
+<?cs # If this is the online docs, build the src code navigation links ?>
+
+
+<?cs var:summary ?>
+
+<!-- begin file contents -->
+<div id="codesample-wrapper">
+<pre id="codesample-line-numbers" class="no-pretty-print hidden"></pre>
+<pre id="codesample-block"><?cs var:fileContents ?></pre>
+</div>
+
+<h3 id="file-location" style="clear:left">Source file location</h3>
+<p>The file containing the source code shown below is located in the corresponding directory in 
+<code>&lt;sdk&gt;/samples/android-&lt;version&gt;/...</code></p>
+
+
+<!-- end file contents -->
+<script type="text/javascript">
+  initCodeLineNumbers();
+</script>
+
+
+
+
+<?cs else ?><?cs
+  # else, this means it's offline docs,
+          so don't show src links (we dont have the pages!) ?>
+
+<p>You can find the source code for this sample in your SDK at:</p>
+<p style="margin-left:2em">
+<code><em>&lt;sdk&gt;</em>/samples/android-<em>&lt;version&gt;</em>/</code>
+</p>
+
+<?cs /if ?><?cs # end if/else online docs ?>
+
+  </div> <!-- end jd-content -->
+
+<?cs include:"footer.cs" ?>
+</div><!-- end doc-content -->
+
+<?cs include:"trailer.cs" ?>
+
+</body>
+</html>
+
+
+
+
+
+
+
diff --git a/tools/droiddoc/templates-sdk/sampleindex.cs b/tools/droiddoc/templates-sdk/sampleindex.cs
index a173363..077b3d5 100644
--- a/tools/droiddoc/templates-sdk/sampleindex.cs
+++ b/tools/droiddoc/templates-sdk/sampleindex.cs
@@ -1,53 +1,99 @@
 <?cs include:"doctype.cs" ?>
 <?cs include:"macros.cs" ?>
-<?cs set:resources="true" ?>
 <html<?cs if:devsite ?> devsite<?cs /if ?>>
 <?cs include:"head_tag.cs" ?>
+<body class="gc-documentation develop samples" itemscope itemtype="http://schema.org/Article">
 <?cs include:"header.cs" ?>
-<body class="gc-documentation">
 
+<div <?cs if:fullpage
+?>class="fullpage"<?cs elif:design||tools||about||sdk||distribute
+?>class="col-13" id="doc-col"<?cs else 
+?>class="col-12" id="doc-col"<?cs /if ?> >
 
-<a name="top"></a>
-<div class="g-unit" id="doc-content">
- <div id="jd-header" class="guide-header">
-    <span class="crumb">
-      <a href="<?cs var:toroot ?>resources/browser.html?tag=sample">Sample Code</a> >
-    </span>
-  <h1><?cs var:page.title ?></h1>
- </div>
+<!-- start breadcrumb block -->
+<div id="api-info-block">
+<div class="sum-details-links">
 
+<!-- related links -->
+<?cs if:projectStructure ?>
+<a href="<?cs var:toroot ?>samples/<?cs var:projectDir ?>/index.html">Overview</a>
+&#124; Project<?cs else ?>Overview
+&#124; <a href="<?cs var:toroot ?>samples/<?cs var:projectDir ?>/project.html">Project</a>
+<?cs /if ?>
+&#124; <a href="<?cs var:toroot ?>downloads/samples/<?cs var:projectDir ?>.zip">Download</a>
+
+</div><!-- end sum-details-links -->
+<div class="api-level">
+  Other info
+</div>
+</div><!-- end breadcurmb block -->
+
+<h1 itemprop="name"><?cs var:projectDir ?></h1>
+  
 <div id="jd-content">
-<p><a href="../index.html">&larr; Back</a></p>
+<?cs def:display_files(files) ?>
 
-<?cs var:summary ?>
+    <?cs each:file = files ?>
+        <?cs if:file.Type != "dir" ?>
+            <div class="structure-<?cs var:file.Type ?>">
+            <a href="<?cs var:toroot ?><?cs var:file.Href ?>"><?cs var:file.Name ?></a>
+            </div>
+        <?cs else ?>
+            <div class="toggle-content opened structure-dir">
+               <a href="#" onclick="return toggleContent(this)">
+               <img src="<?cs var:toroot ?>assets/images/triangle-opened.png"
+                  class="toggle-content-img structure-toggle-img" height="9px" width="9px" />
+               <?cs var:file.Name ?></a><?cs 
+                  if:file.SummaryFlag == "true" ?><span class="dirInfo"
+                    >[&nbsp;<a href="file.SummaryHref">Info</a>&nbsp;]</a></span><?cs 
+                  /if ?>
+               <div class="toggle-content-toggleme structure-toggleme"> 
+            <?cs if:file.Sub.0.Name ?>
+                 <?cs call:display_files(file.Sub) ?>
+            <?cs /if ?>
+               </div> <?cs # /toggleme ?>
+            </div> <?cs # /toggle-content ?>
+         <?cs /if ?>
+    <?cs /each ?>
+<?cs /def ?>
 
-  <?cs if:subcount(subdirs) ?>
-      <h2>Subdirectories</h2>
-      <ul class="nolist">
-      <?cs each:dir=subdirs ?>
-        <li><a href="<?cs var:dir.name ?>/index.html"><?cs
-          var:dir.name ?>/</a></li>
-      <?cs /each ?>
-      </ul>
-  <?cs /if ?>
+<?cs if:android.whichdoc == "online" ?>
+  <?cs # If this is the online docs, build the src code navigation links ?>
 
-  <?cs if:subcount(files) ?>
-      <h2>Files</h2>
-      <ul class="nolist">
-      <?cs each:file=files ?>
-        <li><a href="<?cs var:file.href ?>"><?cs
-          var:file.name ?></a></li>
-      <?cs /each ?>
-      </ul>
-  <?cs /if ?>
+  <?cs if:projectStructure ?>
 
-</div><!-- end jd-content -->
+    <?cs call:display_files(Files) ?>
+
+  <?cs else ?> <?cs # else not project structure doc ?>
+
+    <?cs var:summary ?>
+
+    <?cs # Remove project structure from landing pages for now
+         # <h2>Project Structure</h2>
+         # <p>Decide what to do with this ...</p>
+         # <?cs call:display_files(Files) ?>
+
+  <?cs /if ?> <?cs # end if projectStructure ?>
+
+<?cs else ?><?cs
+  # else, this means it's offline docs,
+          so don't show src links (we dont have the pages!) ?>
+
+<p>You can find the source code for this sample in your SDK at:</p>
+<p style="margin-left:2em">
+<code><em>&lt;sdk&gt;</em>/samples/android-<em>&lt;version&gt;</em>/</code>
+</p>
+
+<?cs /if ?><?cs # end if/else online docs ?>
+
+  </div> <!-- end jd-content -->
 
 <?cs include:"footer.cs" ?>
-
 </div><!-- end doc-content -->
 
 <?cs include:"trailer.cs" ?>
 
 </body>
 </html>
+
+
diff --git a/tools/droiddoc/templates-sdk/samples_navtree_data.cs b/tools/droiddoc/templates-sdk/samples_navtree_data.cs
new file mode 100644
index 0000000..24ac7b7
--- /dev/null
+++ b/tools/droiddoc/templates-sdk/samples_navtree_data.cs
@@ -0,0 +1,3 @@
+var SAMPLES_NAVTREE_DATA =
+<?cs var:reference_tree ?>
+;
diff --git a/tools/fs_config/Android.mk b/tools/fs_config/Android.mk
index 5ef32dd..02deabb 100644
--- a/tools/fs_config/Android.mk
+++ b/tools/fs_config/Android.mk
@@ -17,6 +17,7 @@
 
 LOCAL_SRC_FILES := fs_config.c
 LOCAL_MODULE := fs_config
+LOCAL_STATIC_LIBRARIES := libselinux
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 
 include $(BUILD_HOST_EXECUTABLE)
diff --git a/tools/fs_config/fs_config.c b/tools/fs_config/fs_config.c
index f6760cc..f594c1e 100644
--- a/tools/fs_config/fs_config.c
+++ b/tools/fs_config/fs_config.c
@@ -15,10 +15,16 @@
  */
 
 #include <stdio.h>
+#include <stdlib.h>
 #include <sys/stat.h>
 #include <errno.h>
 #include <unistd.h>
 #include <string.h>
+#include <inttypes.h>
+
+#include <selinux/selinux.h>
+#include <selinux/label.h>
+#include <selinux/android.h>
 
 #include "private/android_filesystem_config.h"
 
@@ -27,21 +33,67 @@
 // filename along with its desired uid, gid, and mode (in octal).
 // The leading slash should be stripped from the input.
 //
+// After the first 4 columns, optional key=value pairs are emitted
+// for each file.  Currently, the following keys are supported:
+// * -S: selabel=[selinux_label]
+// * -C: capabilities=[hex capabilities value]
+//
 // Example input:
 //
-//    system/etc/dbus.conf
-//    data/app/
+//      system/etc/dbus.conf
+//      data/app/
 //
 // Output:
 //
-//    system/etc/dbus.conf 1002 1002 440
-//    data/app 1000 1000 771
+//      system/etc/dbus.conf 1002 1002 440
+//      data/app 1000 1000 771
+//
+//   or if, for example, -S is used:
+//
+//      system/etc/dbus.conf 1002 1002 440 selabel=u:object_r:system_file:s0
+//      data/app 1000 1000 771 selabel=u:object_r:apk_data_file:s0
 //
 // Note that the output will omit the trailing slash from
 // directories.
 
+static struct selabel_handle* get_sehnd(const char* context_file) {
+  struct selinux_opt seopts[] = { { SELABEL_OPT_PATH, context_file } };
+  struct selabel_handle* sehnd = selabel_open(SELABEL_CTX_FILE, seopts, 1);
+
+  if (!sehnd) {
+    perror("error running selabel_open");
+    exit(EXIT_FAILURE);
+  }
+  return sehnd;
+}
+
+static void usage() {
+  fprintf(stderr, "Usage: fs_config [-S context_file] [-C]\n");
+}
+
 int main(int argc, char** argv) {
   char buffer[1024];
+  const char* context_file = NULL;
+  struct selabel_handle* sehnd = NULL;
+  int print_capabilities = 0;
+  int opt;
+  while((opt = getopt(argc, argv, "CS:")) != -1) {
+    switch(opt) {
+    case 'C':
+      print_capabilities = 1;
+      break;
+    case 'S':
+      context_file = optarg;
+      break;
+    default:
+      usage();
+      exit(EXIT_FAILURE);
+    }
+  }
+
+  if (context_file != NULL) {
+    sehnd = get_sehnd(context_file);
+  }
 
   while (fgets(buffer, 1023, stdin) != NULL) {
     int is_dir = 0;
@@ -64,7 +116,40 @@
     unsigned uid = 0, gid = 0, mode = 0;
     uint64_t capabilities;
     fs_config(buffer, is_dir, &uid, &gid, &mode, &capabilities);
-    printf("%s %d %d %o\n", buffer, uid, gid, mode);
+    printf("%s %d %d %o", buffer, uid, gid, mode);
+
+    if (sehnd != NULL) {
+      size_t buffer_strlen = strnlen(buffer, sizeof(buffer));
+      if (buffer_strlen >= sizeof(buffer)) {
+        fprintf(stderr, "non null terminated buffer, aborting\n");
+        exit(EXIT_FAILURE);
+      }
+      size_t full_name_size = buffer_strlen + 2;
+      char* full_name = (char*) malloc(full_name_size);
+      if (full_name == NULL) {
+        perror("malloc");
+        exit(EXIT_FAILURE);
+      }
+
+      full_name[0] = '/';
+      strncpy(full_name + 1, buffer, full_name_size - 1);
+      full_name[full_name_size - 1] = '\0';
+
+      char* secontext;
+      if (selabel_lookup(sehnd, &secontext, full_name, ( mode | (is_dir ? S_IFDIR : S_IFREG)))) {
+        secontext = strdup("u:object_r:unlabeled:s0");
+      }
+
+      printf(" selabel=%s", secontext);
+      free(full_name);
+      freecon(secontext);
+    }
+
+    if (print_capabilities) {
+      printf(" capabilities=0x%" PRIx64, capabilities);
+    }
+
+    printf("\n");
   }
   return 0;
 }
diff --git a/tools/releasetools/check_target_files_signatures b/tools/releasetools/check_target_files_signatures
index 45d30a6..ae372ba 100755
--- a/tools/releasetools/check_target_files_signatures
+++ b/tools/releasetools/check_target_files_signatures
@@ -135,7 +135,7 @@
 
     for i in to_load:
       f = open(i)
-      cert = common.ParseCertificate(f.read())
+      cert = ParseCertificate(f.read())
       f.close()
       name, _ = os.path.splitext(i)
       name, _ = os.path.splitext(name)
@@ -144,6 +144,21 @@
 ALL_CERTS = CertDB()
 
 
+def ParseCertificate(data):
+  """Parse a PEM-format certificate."""
+  cert = []
+  save = False
+  for line in data.split("\n"):
+    if "--END CERTIFICATE--" in line:
+      break
+    if save:
+      cert.append(line)
+    if "--BEGIN CERTIFICATE--" in line:
+      save = True
+  cert = "".join(cert).decode('base64')
+  return cert
+
+
 def CertFromPKCS7(data, filename):
   """Read the cert out of a PKCS#7-format file (which is what is
   stored in a signed .apk)."""
@@ -160,7 +175,7 @@
       AddProblem("error reading cert:\n" + err)
       return None
 
-    cert = common.ParseCertificate(out)
+    cert = ParseCertificate(out)
     if not cert:
       AddProblem("error parsing cert output")
       return None
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index f179717..95d01e0 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -957,18 +957,3 @@
     return PARTITION_TYPES[fstab[mount_point].fs_type], fstab[mount_point].device
   else:
     return None
-
-
-def ParseCertificate(data):
-  """Parse a PEM-format certificate."""
-  cert = []
-  save = False
-  for line in data.split("\n"):
-    if "--END CERTIFICATE--" in line:
-      break
-    if save:
-      cert.append(line)
-    if "--BEGIN CERTIFICATE--" in line:
-      save = True
-  cert = "".join(cert).decode('base64')
-  return cert
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index 5672b5a..2c3b9e7 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -72,24 +72,31 @@
     """Assert that the current system build fingerprint is one of *fp."""
     if not fp:
       raise ValueError("must specify some fingerprints")
-    cmd = ('assert(' +
-           ' ||\0'.join([('file_getprop("/system/build.prop", '
+    cmd = (
+           ' ||\n    '.join([('file_getprop("/system/build.prop", '
                          '"ro.build.fingerprint") == "%s"')
                         % i for i in fp]) +
-           ');')
-    self.script.append(self._WordWrap(cmd))
+           ' ||\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):
+  def AssertOlderBuild(self, timestamp, timestamp_text):
     """Assert that the build on the device is older (or the same as)
     the given timestamp."""
-    self.script.append(('assert(!less_than_int(%s, '
-                        'getprop("ro.build.date.utc")));') % (timestamp,))
+    self.script.append(
+        ('(!less_than_int(%s, getprop("ro.build.date.utc"))) || '
+         'abort("Can\'t install this package (%s) over newer '
+         'build (" + getprop("ro.build.date") + ").");'
+         ) % (timestamp, timestamp_text))
 
   def AssertDevice(self, device):
     """Assert that the device identifier is the given string."""
-    cmd = ('assert(getprop("ro.product.device") == "%s" ||\0'
-           'getprop("ro.build.product") == "%s");' % (device, device))
-    self.script.append(self._WordWrap(cmd))
+    cmd = ('getprop("ro.product.device") == "%s" || '
+           'abort("This package is for \\"%s\\" devices; '
+           'this is a \\"" + getprop("ro.product.device") + "\\".");'
+           ) % (device, device)
+    self.script.append(cmd)
 
   def AssertSomeBootloader(self, *bootloaders):
     """Asert that the bootloader version is one of *bootloaders."""
@@ -115,9 +122,10 @@
     """Check that the given file (or MTD reference) has one of the
     given *sha1 hashes, checking the version saved in cache if the
     file does not match."""
-    self.script.append('assert(apply_patch_check("%s"' % (filename,) +
-                       "".join([', "%s"' % (i,) for i in sha1]) +
-                       '));')
+    self.script.append(
+        'apply_patch_check("%s"' % (filename,) +
+        "".join([', "%s"' % (i,) for i in sha1]) +
+        ') || abort("\\"%s\\" has unexpected contents.");' % (filename,))
 
   def FileCheck(self, filename, *sha1):
     """Check that the given file (or MTD reference) has one of the
@@ -129,7 +137,8 @@
   def CacheFreeSpaceCheck(self, amount):
     """Check that there's at least 'amount' space that can be made
     available on /cache."""
-    self.script.append("assert(apply_patch_space(%d));" % (amount,))
+    self.script.append(('apply_patch_space(%d) || abort("Not enough free space '
+                        'on /system to apply patches.");') % (amount,))
 
   def Mount(self, mount_point):
     """Mount the partition with the given mount_point."""
@@ -208,14 +217,33 @@
       else:
         raise ValueError("don't know how to write \"%s\" partitions" % (p.fs_type,))
 
-  def SetPermissions(self, fn, uid, gid, mode):
+  def SetPermissions(self, fn, uid, gid, mode, selabel, capabilities):
     """Set file ownership and permissions."""
-    self.script.append('set_perm(%d, %d, 0%o, "%s");' % (uid, gid, mode, fn))
+    if not self.info.get("use_set_metadata", False):
+      self.script.append('set_perm(%d, %d, 0%o, "%s");' % (uid, gid, mode, fn))
+    else:
+      if capabilities is None: capabilities = "0x0"
+      cmd = 'set_metadata("%s", "uid", %d, "gid", %d, "mode", 0%o, ' \
+          '"capabilities", %s' % (fn, uid, gid, mode, capabilities)
+      if selabel is not None:
+        cmd += ', "selabel", "%s"' % ( selabel )
+      cmd += ');'
+      self.script.append(cmd)
 
-  def SetPermissionsRecursive(self, fn, uid, gid, dmode, fmode):
+  def SetPermissionsRecursive(self, fn, uid, gid, dmode, fmode, selabel, capabilities):
     """Recursively set path ownership and permissions."""
-    self.script.append('set_perm_recursive(%d, %d, 0%o, 0%o, "%s");'
-                       % (uid, gid, dmode, fmode, fn))
+    if not self.info.get("use_set_metadata", False):
+      self.script.append('set_perm_recursive(%d, %d, 0%o, 0%o, "%s");'
+                         % (uid, gid, dmode, fmode, fn))
+    else:
+      if capabilities is None: capabilities = "0x0"
+      cmd = 'set_metadata_recursive("%s", "uid", %d, "gid", %d, ' \
+          '"dmode", 0%o, "fmode", 0%o, "capabilities", %s' \
+          % (fn, uid, gid, dmode, fmode, capabilities)
+      if selabel is not None:
+        cmd += ', "selabel", "%s"' % ( selabel )
+      cmd += ');'
+      self.script.append(cmd)
 
   def MakeSymlinks(self, symlink_list):
     """Create symlinks, given a list of (dest, link) pairs."""
diff --git a/tools/releasetools/ota_from_target_files b/tools/releasetools/ota_from_target_files
index e0d5d91..a6b9b69 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -117,6 +117,8 @@
     self.uid = None
     self.gid = None
     self.mode = None
+    self.selabel = None
+    self.capabilities = None
     self.dir = dir
 
     if name:
@@ -147,82 +149,88 @@
   @classmethod
   def GetMetadata(cls, input_zip):
 
-    try:
-      # See if the target_files contains a record of what the uid,
-      # gid, and mode is supposed to be.
-      output = input_zip.read("META/filesystem_config.txt")
-    except KeyError:
-      # Run the external 'fs_config' program to determine the desired
-      # uid, gid, and mode for every Item object.  Note this uses the
-      # one in the client now, which might not be the same as the one
-      # used when this target_files was built.
-      p = common.Run(["fs_config"], stdin=subprocess.PIPE,
-                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-      suffix = { False: "", True: "/" }
-      input = "".join(["%s%s\n" % (i.name, suffix[i.dir])
-                       for i in cls.ITEMS.itervalues() if i.name])
-      output, error = p.communicate(input)
-      assert not error
+    # The target_files contains a record of what the uid,
+    # gid, and mode are supposed to be.
+    output = input_zip.read("META/filesystem_config.txt")
 
     for line in output.split("\n"):
       if not line: continue
-      name, uid, gid, mode = line.split()
+      columns = line.split()
+      name, uid, gid, mode = columns[:4]
+      selabel = None
+      capabilities = None
+
+      # After the first 4 columns, there are a series of key=value
+      # pairs. Extract out the fields we care about.
+      for element in columns[4:]:
+        key, value = element.split("=")
+        if key == "selabel":
+          selabel = value
+        if key == "capabilities":
+          capabilities = value
+
       i = cls.ITEMS.get(name, None)
       if i is not None:
         i.uid = int(uid)
         i.gid = int(gid)
         i.mode = int(mode, 8)
+        i.selabel = selabel
+        i.capabilities = capabilities
         if i.dir:
           i.children.sort(key=lambda i: i.name)
 
     # set metadata for the files generated by this script.
     i = cls.ITEMS.get("system/recovery-from-boot.p", None)
-    if i: i.uid, i.gid, i.mode = 0, 0, 0644
+    if i: i.uid, i.gid, i.mode, i.selabel, i.capabilities = 0, 0, 0644, None, None
     i = cls.ITEMS.get("system/etc/install-recovery.sh", None)
-    if i: i.uid, i.gid, i.mode = 0, 0, 0544
+    if i: i.uid, i.gid, i.mode, i.selabel, i.capabilities = 0, 0, 0544, None, None
 
   def CountChildMetadata(self):
-    """Count up the (uid, gid, mode) tuples for all children and
-    determine the best strategy for using set_perm_recursive and
+    """Count up the (uid, gid, mode, selabel, capabilities) tuples for
+    all children and determine the best strategy for using set_perm_recursive and
     set_perm to correctly chown/chmod all the files to their desired
     values.  Recursively calls itself for all descendants.
 
-    Returns a dict of {(uid, gid, dmode, fmode): count} counting up
+    Returns a dict of {(uid, gid, dmode, fmode, selabel, capabilities): count} counting up
     all descendants of this node.  (dmode or fmode may be None.)  Also
     sets the best_subtree of each directory Item to the (uid, gid,
-    dmode, fmode) tuple that will match the most descendants of that
-    Item.
+    dmode, fmode, selabel, capabilities) tuple that will match the most
+    descendants of that Item.
     """
 
     assert self.dir
-    d = self.descendants = {(self.uid, self.gid, self.mode, None): 1}
+    d = self.descendants = {(self.uid, self.gid, self.mode, None, self.selabel, self.capabilities): 1}
     for i in self.children:
       if i.dir:
         for k, v in i.CountChildMetadata().iteritems():
           d[k] = d.get(k, 0) + v
       else:
-        k = (i.uid, i.gid, None, i.mode)
+        k = (i.uid, i.gid, None, i.mode, i.selabel, i.capabilities)
         d[k] = d.get(k, 0) + 1
 
-    # Find the (uid, gid, dmode, fmode) tuple that matches the most
-    # descendants.
+    # Find the (uid, gid, dmode, fmode, selabel, capabilities)
+    # tuple that matches the most descendants.
 
     # First, find the (uid, gid) pair that matches the most
     # descendants.
     ug = {}
-    for (uid, gid, _, _), count in d.iteritems():
+    for (uid, gid, _, _, _, _), count in d.iteritems():
       ug[(uid, gid)] = ug.get((uid, gid), 0) + count
     ug = MostPopularKey(ug, (0, 0))
 
-    # Now find the dmode and fmode that match the most descendants
-    # with that (uid, gid), and choose those.
+    # Now find the dmode, fmode, selabel, and capabilities that match
+    # the most descendants with that (uid, gid), and choose those.
     best_dmode = (0, 0755)
     best_fmode = (0, 0644)
+    best_selabel = (0, None)
+    best_capabilities = (0, None)
     for k, count in d.iteritems():
       if k[:2] != ug: continue
       if k[2] is not None and count >= best_dmode[0]: best_dmode = (count, k[2])
       if k[3] is not None and count >= best_fmode[0]: best_fmode = (count, k[3])
-    self.best_subtree = ug + (best_dmode[1], best_fmode[1])
+      if k[4] is not None and count >= best_selabel[0]: best_selabel = (count, k[4])
+      if k[5] is not None and count >= best_capabilities[0]: best_capabilities = (count, k[5])
+    self.best_subtree = ug + (best_dmode[1], best_fmode[1], best_selabel[1], best_capabilities[1])
 
     return d
 
@@ -234,7 +242,7 @@
     self.CountChildMetadata()
 
     def recurse(item, current):
-      # current is the (uid, gid, dmode, fmode) tuple that the current
+      # current is the (uid, gid, dmode, fmode, selabel, capabilities) tuple that the current
       # item (and all its children) have already been set to.  We only
       # need to issue set_perm/set_perm_recursive commands if we're
       # supposed to be something different.
@@ -244,17 +252,21 @@
           current = item.best_subtree
 
         if item.uid != current[0] or item.gid != current[1] or \
-           item.mode != current[2]:
-          script.SetPermissions("/"+item.name, item.uid, item.gid, item.mode)
+           item.mode != current[2] or item.selabel != current[4] or \
+           item.capabilities != current[5]:
+          script.SetPermissions("/"+item.name, item.uid, item.gid,
+                                item.mode, item.selabel, item.capabilities)
 
         for i in item.children:
           recurse(i, current)
       else:
         if item.uid != current[0] or item.gid != current[1] or \
-               item.mode != current[3]:
-          script.SetPermissions("/"+item.name, item.uid, item.gid, item.mode)
+               item.mode != current[3] or item.selabel != current[4] or \
+               item.capabilities != current[5]:
+          script.SetPermissions("/"+item.name, item.uid, item.gid,
+                                item.mode, item.selabel, item.capabilities)
 
-    recurse(self, (-1, -1, -1, -1))
+    recurse(self, (-1, -1, -1, -1, None, None))
 
 
 def CopySystemFiles(input_zip, output_zip=None,
@@ -387,7 +399,8 @@
 
   if not OPTIONS.omit_prereq:
     ts = GetBuildProp("ro.build.date.utc", OPTIONS.info_dict)
-    script.AssertOlderBuild(ts)
+    ts_text = GetBuildProp("ro.build.date", OPTIONS.info_dict)
+    script.AssertOlderBuild(ts, ts_text)
 
   AppendAssertions(script, OPTIONS.info_dict)
   device_specific.FullOTA_Assertions()
@@ -732,7 +745,7 @@
   for item in deferred_patch_list:
     fn, tf, sf, size, _ = item
     script.ApplyPatch("/"+fn, "-", tf.size, tf.sha1, sf.sha1, "patch/"+fn+".p")
-  script.SetPermissions("/system/build.prop", 0, 0, 0644)
+  script.SetPermissions("/system/build.prop", 0, 0, 0644, None, None)
 
   script.AddToZip(target_zip, output_zip)
   WriteMetadata(metadata, output_zip)
diff --git a/tools/releasetools/sign_target_files_apks b/tools/releasetools/sign_target_files_apks
index fe6f820..5556573 100755
--- a/tools/releasetools/sign_target_files_apks
+++ b/tools/releasetools/sign_target_files_apks
@@ -71,10 +71,8 @@
   print >> sys.stderr, "Python 2.4 or newer is required."
   sys.exit(1)
 
-import base64
 import cStringIO
 import copy
-import errno
 import os
 import re
 import subprocess
@@ -163,45 +161,11 @@
       print "rewriting %s:" % (info.filename,)
       new_data = RewriteProps(data)
       output_tf_zip.writestr(out_info, 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)
     else:
       # a non-APK file; copy it verbatim
       output_tf_zip.writestr(out_info, data)
 
 
-def ReplaceCerts(data):
-  """Given a string of data, replace all occurences of a set
-  of X509 certs with a newer set of X509 certs and return
-  the updated data string."""
-  for old, new in OPTIONS.key_map.iteritems():
-    try:
-      if OPTIONS.verbose:
-        print "    Replacing %s.x509.pem with %s.x509.pem" % (old, new)
-      f = open(old + ".x509.pem")
-      old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
-      f.close()
-      f = open(new + ".x509.pem")
-      new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
-      f.close()
-      # Only match entire certs.
-      pattern = "\\b"+old_cert16+"\\b"
-      (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
-      if OPTIONS.verbose:
-        print "    Replaced %d occurence(s) of %s.x509.pem with " \
-            "%s.x509.pem" % (num, old, new)
-    except IOError, e:
-      if (e.errno == errno.ENOENT and not OPTIONS.verbose):
-        continue
-
-      print "    Error accessing %s. %s. Skip replacing %s.x509.pem " \
-          "with %s.x509.pem." % (e.filename, e.strerror, old, new)
-
-  return data
-
-
 def EditTags(tags):
   """Given a string containing comma-separated tags, apply the edits
   specified in OPTIONS.tag_changes and return the updated string."""
@@ -232,6 +196,11 @@
         value = " ".join(pieces)
       elif key == "ro.build.tags":
         value = EditTags(value)
+      elif key == "ro.build.display.id":
+        # change, eg, "JWR66N dev-keys" to "JWR66N"
+        value = value.split()
+        if len(value) == 2 and value[1].endswith("-keys"):
+          value = value[0]
       line = key + "=" + value
     if line != original_line:
       print "  replace: ", original_line
diff --git a/tools/zipalign/Android.mk b/tools/zipalign/Android.mk
index 5542280..708c8bf 100644
--- a/tools/zipalign/Android.mk
+++ b/tools/zipalign/Android.mk
@@ -15,6 +15,7 @@
 LOCAL_C_INCLUDES += external/zlib
 
 LOCAL_STATIC_LIBRARIES := \
+	libandroidfw \
 	libutils \
 	libcutils \
 	liblog
diff --git a/tools/zipalign/ZipFile.cpp b/tools/zipalign/ZipFile.cpp
index 3994c31..8057068 100644
--- a/tools/zipalign/ZipFile.cpp
+++ b/tools/zipalign/ZipFile.cpp
@@ -20,8 +20,8 @@
 
 #define LOG_TAG "zip"
 
+#include <androidfw/ZipUtils.h>
 #include <utils/Log.h>
-#include <utils/ZipUtils.h>
 
 #include "ZipFile.h"