Merge "Add bootsigner path as an option"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index bfa236c..74e7c43 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -334,6 +334,26 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 
+# Adding dalvik.vm.usejit
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
+# Rename dalvik.vm.usejit to debug.dalvik.vm.usejit
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
+# Revert rename dalvik.vm.usejit to debug.dalvik.vm.usejit
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
+# Change from interpret-only to verify-at-runtime.
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/root/default.prop)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/recovery/root/default.prop)
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/core/Makefile b/core/Makefile
index 90785d5..d13d325 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -487,23 +487,7 @@
 INSTALLED_BOOTIMAGE_TARGET := $(PRODUCT_OUT)/boot.img
 
 ifeq ($(TARGET_BOOTIMAGE_USE_EXT2),true)
-tmp_dir_for_image := $(call intermediates-dir-for,EXECUTABLES,boot_img)/bootimg
-INTERNAL_BOOTIMAGE_ARGS += --tmpdir $(tmp_dir_for_image)
-INTERNAL_BOOTIMAGE_ARGS += --genext2fs $(MKEXT2IMG)
-
-ifeq ($(TARGET_BOOTIMAGE_USE_EXTLINUX),true)
-INTERNAL_BOOTIMAGE_ARGS += --extlinuxconf $(TARGET_BOOTIMAGE_EXTLINUX_CONFIG)
-endif
-
-$(INSTALLED_BOOTIMAGE_TARGET): $(MKEXT2IMG) $(INTERNAL_BOOTIMAGE_FILES)
-	$(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)
-
+$(error TARGET_BOOTIMAGE_USE_EXT2 is not supported anymore)
 else ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY)) # TARGET_BOOTIMAGE_USE_EXT2 != true
 
 $(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(BOOT_SIGNER)
@@ -519,7 +503,22 @@
 	$(BOOT_SIGNER) /boot $(INSTALLED_BOOTIMAGE_TARGET) $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).pk8 $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem $(INSTALLED_BOOTIMAGE_TARGET)
 	$(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE))
 
-else # PRODUCT_SUPPORTS_VERITY != true
+else ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)) # PRODUCT_SUPPORTS_VERITY != true
+
+$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(VBOOT_SIGNER)
+	$(call pretty,"Target boot image: $@")
+	$(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@.unsigned
+	$(VBOOT_SIGNER) $(FUTILITY) $@.unsigned $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbpubk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbprivk $@.keyblock $@
+	$(hide) $(call assert-max-image-size,$@,$(BOARD_BOOTIMAGE_PARTITION_SIZE))
+
+.PHONY: bootimage-nodeps
+bootimage-nodeps: $(MKBOOTIMG) $(VBOOT_SIGNER)
+	@echo "make $@: ignoring dependencies"
+	$(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET).unsigned
+	$(VBOOT_SIGNER) $(FUTILITY) $(INSTALLED_BOOTIMAGE_TARGET).unsigned $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbpubk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbprivk $(INSTALLED_BOOTIMAGE_TARGET).keyblock $(INSTALLED_BOOTIMAGE_TARGET)
+	$(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE))
+
+else # PRODUCT_SUPPORTS_VBOOT != true
 
 $(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES)
 	$(call pretty,"Target boot image: $@")
@@ -697,6 +696,10 @@
 endif
 endif
 
+ifeq ($(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE),squashfs)
+INTERNAL_USERIMAGES_DEPS += $(MAKE_SQUASHFS) $(MKSQUASHFSUSERIMG)
+endif
+
 INTERNAL_USERIMAGES_BINARY_PATHS := $(sort $(dir $(INTERNAL_USERIMAGES_DEPS)))
 
 ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY))
@@ -711,6 +714,7 @@
 define generate-userimage-prop-dictionary
 $(if $(INTERNAL_USERIMAGES_EXT_VARIANT),$(hide) echo "fs_type=$(INTERNAL_USERIMAGES_EXT_VARIANT)" >> $(1))
 $(if $(BOARD_SYSTEMIMAGE_PARTITION_SIZE),$(hide) echo "system_size=$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)" >> $(1))
+$(if $(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "system_fs_type=$(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE)" >> $(1))
 $(if $(BOARD_SYSTEMIMAGE_JOURNAL_SIZE),$(hide) echo "system_journal_size=$(BOARD_SYSTEMIMAGE_JOURNAL_SIZE)" >> $(1))
 $(if $(BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "userdata_fs_type=$(BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE)" >> $(1))
 $(if $(BOARD_USERDATAIMAGE_PARTITION_SIZE),$(hide) echo "userdata_size=$(BOARD_USERDATAIMAGE_PARTITION_SIZE)" >> $(1))
@@ -728,6 +732,9 @@
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity_signer_cmd=$(VERITY_SIGNER)" >> $(1))
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_VERITY_PARTITION),$(hide) echo "system_verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_VERITY_PARTITION)" >> $(1))
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_VERITY_PARTITION),$(hide) echo "vendor_verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_VERITY_PARTITION)" >> $(1))
+$(if $(filter true,$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)),\
+    $(hide) echo "system_root_image=true" >> $(1);\
+    echo "ramdisk_dir=$(TARGET_ROOT_OUT)" >> $(1))
 $(if $(2),$(hide) $(foreach kv,$(2),echo "$(kv)" >> $(1);))
 endef
 
@@ -739,12 +746,14 @@
 
 INSTALLED_RECOVERYIMAGE_TARGET := $(PRODUCT_OUT)/recovery.img
 
+INTERNAL_RECOVERYIMAGE_FILES := $(filter $(TARGET_RECOVERY_OUT)/%, \
+    $(ALL_DEFAULT_INSTALLED_MODULES))
+
 recovery_initrc := $(call include-path-for, recovery)/etc/init.rc
 recovery_sepolicy := $(call intermediates-dir-for,ETC,sepolicy.recovery)/sepolicy.recovery
 recovery_kernel := $(INSTALLED_KERNEL_TARGET) # same as a non-recovery system
 recovery_ramdisk := $(PRODUCT_OUT)/ramdisk-recovery.img
 recovery_build_prop := $(INSTALLED_BUILD_PROP_TARGET)
-recovery_binary := $(call intermediates-dir-for,EXECUTABLES,recovery,,,$(TARGET_PREFER_32_BIT))/recovery
 recovery_resources_common := $(call include-path-for, recovery)/res
 
 # Set recovery_density to the density bucket of the device.
@@ -831,18 +840,16 @@
 # $(1): output file
 define build-recoveryimage-target
   @echo ----- Making recovery image ------
-  $(hide) rm -rf $(TARGET_RECOVERY_OUT)
   $(hide) mkdir -p $(TARGET_RECOVERY_OUT)
   $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/etc $(TARGET_RECOVERY_ROOT_OUT)/tmp
   @echo Copying baseline ramdisk...
-  $(hide) cp -R $(TARGET_ROOT_OUT) $(TARGET_RECOVERY_OUT)
+  $(hide) rsync -a $(TARGET_ROOT_OUT) $(TARGET_RECOVERY_OUT) # "cp -Rf" fails to overwrite broken symlinks on Mac.
   @echo Modifying ramdisk contents...
   $(hide) rm -f $(TARGET_RECOVERY_ROOT_OUT)/init*.rc
   $(hide) cp -f $(recovery_initrc) $(TARGET_RECOVERY_ROOT_OUT)/
   $(hide) rm -f $(TARGET_RECOVERY_ROOT_OUT)/sepolicy
   $(hide) cp -f $(recovery_sepolicy) $(TARGET_RECOVERY_ROOT_OUT)/sepolicy
-  $(hide) -cp $(TARGET_ROOT_OUT)/init.recovery.*.rc $(TARGET_RECOVERY_ROOT_OUT)/
-  $(hide) cp -f $(recovery_binary) $(TARGET_RECOVERY_ROOT_OUT)/sbin/
+  $(hide) cp $(TARGET_ROOT_OUT)/init.recovery.*.rc $(TARGET_RECOVERY_ROOT_OUT)/ | true # Ignore error when the src file doesn't exist.
   $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/res
   $(hide) rm -rf $(TARGET_RECOVERY_ROOT_OUT)/res/*
   $(hide) cp -rf $(recovery_resources_common)/* $(TARGET_RECOVERY_ROOT_OUT)/res
@@ -865,7 +872,7 @@
 $(INSTALLED_RECOVERYIMAGE_TARGET): $(MKBOOTFS) $(MKBOOTIMG) $(MINIGZIP) \
 		$(INSTALLED_RAMDISK_TARGET) \
 		$(INSTALLED_BOOTIMAGE_TARGET) \
-		$(recovery_binary) \
+		$(INTERNAL_RECOVERYIMAGE_FILES) \
 		$(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \
 		$(INSTALLED_2NDBOOTLOADER_TARGET) \
 		$(recovery_build_prop) $(recovery_resource_deps) \
@@ -914,6 +921,7 @@
     $(PDK_FUSION_SYSIMG_FILES) \
     $(RECOVERY_RESOURCE_ZIP))
 
+
 FULL_SYSTEMIMAGE_DEPS := $(INTERNAL_SYSTEMIMAGE_FILES) $(INTERNAL_USERIMAGES_DEPS)
 # -----------------------------------------------------------------
 # installed file list
@@ -1427,7 +1435,7 @@
 	$(hide) mkdir -p $(zip_root)/META
 	$(hide) $(ACP) $(APKCERTS_FILE) $(zip_root)/META/apkcerts.txt
 	$(hide) if test -e $(tool_extensions)/releasetools.py; then $(ACP) $(tool_extensions)/releasetools.py $(zip_root)/META/; fi
-	$(hide)	echo "$(PRODUCT_OTA_PUBLIC_KEYS)" > $(zip_root)/META/otakeys.txt
+	$(hide) echo "$(PRODUCT_OTA_PUBLIC_KEYS)" > $(zip_root)/META/otakeys.txt
 	$(hide) echo "recovery_api_version=$(PRIVATE_RECOVERY_API_VERSION)" > $(zip_root)/META/misc_info.txt
 	$(hide) echo "fstab_version=$(PRIVATE_RECOVERY_FSTAB_VERSION)" >> $(zip_root)/META/misc_info.txt
 ifdef BOARD_FLASH_BLOCK_SIZE
@@ -1605,10 +1613,10 @@
 		  unobfuscated_jars=$${dict_files//proguard_dictionary/classes.jar}; \
 		  zip -q $@ $$dict_files $$unobfuscated_jars; \
 		else \
-		  touch $(dir $@)/dummy; \
-		  (cd $(dir $@) && zip -q $(notdir $@) dummy); \
-		  zip -qd $@ dummy; \
-		  rm $(dir $@)/dummy; \
+		  touch $(dir $@)/zipdummy; \
+		  (cd $(dir $@) && zip -q $(notdir $@) zipdummy); \
+		  zip -qd $@ zipdummy; \
+		  rm $(dir $@)/zipdummy; \
 		fi
 
 endif # TARGET_BUILD_APPS
diff --git a/core/base_rules.mk b/core/base_rules.mk
index f33ebf1..1a2dc5e 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -43,13 +43,6 @@
 
 my_module_tags := $(LOCAL_MODULE_TAGS)
 
-LOCAL_JACK_ENABLED := $(strip $(LOCAL_JACK_ENABLED))
-ifneq ($(LOCAL_JACK_ENABLED),full)
-ifneq ($(LOCAL_JACK_ENABLED),incremental)
-LOCAL_JACK_ENABLED :=
-endif
-endif
-
 ###########################################################
 ## Validate and define fallbacks for input LOCAL_* variables.
 ###########################################################
@@ -123,6 +116,8 @@
     partition_tag := _VENDOR
   else ifeq (true,$(LOCAL_OEM_MODULE))
     partition_tag := _OEM
+  else ifeq (true,$(LOCAL_ODM_MODULE))
+    partition_tag := _ODM
   else
     # The definition of should-install-to-system will be different depending
     # on which goal (e.g., sdk or just droid) is being built.
diff --git a/core/binary.mk b/core/binary.mk
index 56f8da8..d0b4496 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -483,6 +483,7 @@
 # This is just a dummy rule to make sure gmake doesn't skip updating the dependents.
 $(rs_generated_cpps) : $(RenderScript_file_stamp)
 	@echo "Updated RS generated cpp file $@."
+	$(hide) touch $@
 
 my_c_includes += $(renderscript_intermediate)
 my_generated_sources += $(rs_generated_cpps)
@@ -535,6 +536,7 @@
 # This is just a dummy rule to make sure gmake doesn't skip updating the dependents.
 $(proto_generated_headers): $(proto_generated_cc_sources_dir)/%.pb.h: $(proto_generated_cc_sources_dir)/%.pb.cc
 	@echo "Updated header file $@."
+	$(hide) touch $@
 
 $(my_prefix)_$(LOCAL_MODULE_CLASS)_$(LOCAL_MODULE)_proto_defined := true
 endif  # transform-proto-to-cc rule included only once
@@ -645,16 +647,33 @@
 
 # we also do this on host modules, even though
 # it's not really arm, because there are files that are shared.
-cpp_arm_sources    := $(patsubst %$(LOCAL_CPP_EXTENSION).arm,%$(LOCAL_CPP_EXTENSION),$(filter %$(LOCAL_CPP_EXTENSION).arm,$(my_src_files)))
-cpp_arm_objects    := $(addprefix $(intermediates)/,$(cpp_arm_sources:$(LOCAL_CPP_EXTENSION)=.o))
+cpp_arm_sources := $(patsubst %$(LOCAL_CPP_EXTENSION).arm,%$(LOCAL_CPP_EXTENSION),$(filter %$(LOCAL_CPP_EXTENSION).arm,$(my_src_files)))
+dotdot_arm_sources := $(filter ../%,$(cpp_arm_sources))
+cpp_arm_sources := $(filter-out ../%,$(cpp_arm_sources))
+cpp_arm_objects := $(addprefix $(intermediates)/,$(cpp_arm_sources:$(LOCAL_CPP_EXTENSION)=.o))
 
-cpp_normal_sources := $(filter %$(LOCAL_CPP_EXTENSION),$(my_src_files))
+# For source files starting with ../, we remove all the ../ in the object file path,
+# to avoid object file escaping the intermediate directory.
+dotdot_arm_objects :=
+$(foreach s,$(dotdot_arm_sources),\
+  $(eval $(call compile-dotdot-cpp-file,$(s),\
+  $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+  dotdot_arm_objects)))
+
+dotdot_sources := $(filter ../%$(LOCAL_CPP_EXTENSION),$(my_src_files))
+dotdot_objects :=
+$(foreach s,$(dotdot_sources),\
+  $(eval $(call compile-dotdot-cpp-file,$(s),\
+    $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+    dotdot_objects)))
+
+cpp_normal_sources := $(filter-out ../%,$(filter %$(LOCAL_CPP_EXTENSION),$(my_src_files)))
 cpp_normal_objects := $(addprefix $(intermediates)/,$(cpp_normal_sources:$(LOCAL_CPP_EXTENSION)=.o))
 
-$(cpp_arm_objects):    PRIVATE_ARM_MODE := $(arm_objects_mode)
-$(cpp_arm_objects):    PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
-$(cpp_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
-$(cpp_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
+$(dotdot_arm_objects) $(cpp_arm_objects): PRIVATE_ARM_MODE := $(arm_objects_mode)
+$(dotdot_arm_objects) $(cpp_arm_objects): PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
+$(dotdot_objects) $(cpp_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
+$(dotdot_objects) $(cpp_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
 
 cpp_objects        := $(cpp_arm_objects) $(cpp_normal_objects)
 
@@ -667,6 +686,8 @@
 -include $(cpp_objects:%.o=%.P)
 endif
 
+cpp_objects += $(dotdot_arm_objects) $(dotdot_objects)
+
 ###########################################################
 ## C++: Compile generated .cpp files to .o.
 ###########################################################
@@ -723,16 +744,33 @@
 ## C: Compile .c files to .o.
 ###########################################################
 
-c_arm_sources    := $(patsubst %.c.arm,%.c,$(filter %.c.arm,$(my_src_files)))
-c_arm_objects    := $(addprefix $(intermediates)/,$(c_arm_sources:.c=.o))
+c_arm_sources := $(patsubst %.c.arm,%.c,$(filter %.c.arm,$(my_src_files)))
+dotdot_arm_sources := $(filter ../%,$(c_arm_sources))
+c_arm_sources := $(filter-out ../%,$(c_arm_sources))
+c_arm_objects := $(addprefix $(intermediates)/,$(c_arm_sources:.c=.o))
 
-c_normal_sources := $(filter %.c,$(my_src_files))
+# For source files starting with ../, we remove all the ../ in the object file path,
+# to avoid object file escaping the intermediate directory.
+dotdot_arm_objects :=
+$(foreach s,$(dotdot_arm_sources),\
+  $(eval $(call compile-dotdot-c-file,$(s),\
+    $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+    dotdot_arm_objects)))
+
+dotdot_sources := $(filter ../%.c, $(my_src_files))
+dotdot_objects :=
+$(foreach s, $(dotdot_sources),\
+  $(eval $(call compile-dotdot-c-file,$(s),\
+    $(yacc_cpps) $(proto_generated_headers) $(my_additional_dependencies),\
+    dotdot_objects)))
+
+c_normal_sources := $(filter-out ../%,$(filter %.c,$(my_src_files)))
 c_normal_objects := $(addprefix $(intermediates)/,$(c_normal_sources:.c=.o))
 
-$(c_arm_objects):    PRIVATE_ARM_MODE := $(arm_objects_mode)
-$(c_arm_objects):    PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
-$(c_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
-$(c_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
+$(dotdot_arm_objects) $(c_arm_objects): PRIVATE_ARM_MODE := $(arm_objects_mode)
+$(dotdot_arm_objects) $(c_arm_objects): PRIVATE_ARM_CFLAGS := $(arm_objects_cflags)
+$(dotdot_objects) $(c_normal_objects): PRIVATE_ARM_MODE := $(normal_objects_mode)
+$(dotdot_objects) $(c_normal_objects): PRIVATE_ARM_CFLAGS := $(normal_objects_cflags)
 
 c_objects        := $(c_arm_objects) $(c_normal_objects)
 
@@ -743,6 +781,8 @@
 -include $(c_objects:%.o=%.P)
 endif
 
+c_objects += $(dotdot_arm_objects) $(dotdot_objects)
+
 ###########################################################
 ## C: Compile generated .c files to .o.
 ###########################################################
@@ -780,8 +820,16 @@
 ###########################################################
 
 asm_sources_S := $(filter %.S,$(my_src_files))
+dotdot_sources := $(filter ../%,$(asm_sources_S))
+asm_sources_S := $(filter-out ../%,$(asm_sources_S))
 asm_objects_S := $(addprefix $(intermediates)/,$(asm_sources_S:.S=.o))
 
+dotdot_objects_S :=
+$(foreach s,$(dotdot_sources),\
+  $(eval $(call compile-dotdot-s-file,$(s),\
+    $(my_additional_dependencies),\
+    dotdot_objects_S)))
+
 ifneq ($(strip $(asm_objects_S)),)
 $(asm_objects_S): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.S \
     $(my_additional_dependencies)
@@ -790,20 +838,26 @@
 endif
 
 asm_sources_s := $(filter %.s,$(my_src_files))
+dotdot_sources := $(filter ../%,$(asm_sources_s))
+asm_sources_s := $(filter-out ../%,$(asm_sources_s))
 asm_objects_s := $(addprefix $(intermediates)/,$(asm_sources_s:.s=.o))
 
+dotdot_objects_s :=
+$(foreach s,$(dotdot_sources),\
+  $(eval $(call compile-dotdot-s-file-no-deps,$(s),\
+    $(my_additional_dependencies),\
+    dotdot_objects_s)))
+
 ifneq ($(strip $(asm_objects_s)),)
 $(asm_objects_s): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.s \
     $(my_additional_dependencies)
 	$(transform-$(PRIVATE_HOST)s-to-o-no-deps)
--include $(asm_objects_s:%.o=%.P)
 endif
 
-asm_objects := $(asm_objects_S) $(asm_objects_s)
+asm_objects := $(dotdot_objects_S) $(dotdot_objects_s) $(asm_objects_S) $(asm_objects_s)
 
 
-# .asm for x86 needs to be compiled with yasm.
-ifeq (x86,$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+# .asm for x86/x86_64 needs to be compiled with yasm.
 asm_sources_asm := $(filter %.asm,$(my_src_files))
 ifneq ($(strip $(asm_sources_asm)),)
 asm_objects_asm := $(addprefix $(intermediates)/,$(asm_sources_asm:.asm=.o))
@@ -813,7 +867,6 @@
 
 asm_objects += $(asm_objects_asm)
 endif
-endif
 
 
 ##########################################################
diff --git a/core/clang/TARGET_x86.mk b/core/clang/TARGET_x86.mk
index a6b2a6f..3ba34ae 100644
--- a/core/clang/TARGET_x86.mk
+++ b/core/clang/TARGET_x86.mk
@@ -18,7 +18,15 @@
   $(CLANG_CONFIG_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_TARGET_EXTRA_CFLAGS) \
   $(CLANG_CONFIG_x86_EXTRA_CFLAGS) \
-  $(CLANG_CONFIG_x86_TARGET_EXTRA_ASFLAGS)
+  $(CLANG_CONFIG_x86_TARGET_EXTRA_ASFLAGS) \
+  -fno-optimize-sibling-calls \
+  -mstackrealign
+
+# http://llvm.org/bugs/show_bug.cgi?id=15086,
+# llvm tail call optimization is wrong for x86.
+# -mstackrealign is needed to realign stack in native code
+# that could be called from JNI, so that movaps instruction
+# will work on assumed stack aligned local variables.
 
 CLANG_CONFIG_x86_TARGET_EXTRA_CONLYFLAGS := \
   $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
diff --git a/core/clang/config.mk b/core/clang/config.mk
index 91073ba..a39095e 100644
--- a/core/clang/config.mk
+++ b/core/clang/config.mk
@@ -58,9 +58,14 @@
   -finline-limit=64 \
   -fno-canonical-system-headers \
   -fno-tree-sra \
+  -fprefetch-loop-arrays \
   -funswitch-loops \
+  -Werror=unused-but-set-variable \
+  -Werror=unused-but-set-parameter \
   -Wmaybe-uninitialized \
   -Wno-error=maybe-uninitialized \
+  -Wno-error=unused-but-set-variable \
+  -Wno-error=unused-but-set-parameter \
   -Wno-free-nonheap-object \
   -Wno-literal-suffix \
   -Wno-maybe-uninitialized \
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index d6441bb..876698a 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -20,6 +20,7 @@
 LOCAL_MODULE_CLASS:=
 LOCAL_MODULE_SUFFIX:=
 LOCAL_PACKAGE_NAME:=
+LOCAL_PAGE_ALIGN_JNI_SHARED_LIBRARIES:=
 LOCAL_OVERRIDES_PACKAGES:=
 LOCAL_EXPORT_PACKAGE_RESOURCES:=
 LOCAL_MANIFEST_PACKAGE_NAME:=
@@ -96,6 +97,7 @@
 LOCAL_STRIP_MODULE:=
 LOCAL_JNI_SHARED_LIBRARIES:=
 LOCAL_JNI_SHARED_LIBRARIES_ABI:=
+LOCAL_JNI_SHARED_LIBRARIES_ZIP_OPTIONS:=
 LOCAL_PREBUILT_JNI_LIBS:=
 LOCAL_JAR_MANIFEST:=
 LOCAL_INSTRUMENTATION_FOR:=
@@ -111,6 +113,7 @@
 LOCAL_JACK_VM_ARGS := $(DEFAULT_JACK_VM_ARGS)
 LOCAL_JACK_EXTRA_ARGS := $(DEFAULT_JACK_EXTRA_ARGS)
 LOCAL_JACK_FLAGS:=
+LOCAL_JILL_FLAGS:=
 LOCAL_CERTIFICATE:=
 LOCAL_SDK_VERSION:=
 LOCAL_SDK_RES_VERSION:=
@@ -142,6 +145,7 @@
 LOCAL_NO_CRT:=
 LOCAL_PROPRIETARY_MODULE:=
 LOCAL_OEM_MODULE:=
+LOCAL_ODM_MODULE:=
 LOCAL_PRIVILEGED_MODULE:=
 LOCAL_MODULE_OWNER:=
 LOCAL_CTS_TEST_PACKAGE:=
diff --git a/core/combo/TARGET_linux-arm64.mk b/core/combo/TARGET_linux-arm64.mk
index abd8e3a..07a1de9 100644
--- a/core/combo/TARGET_linux-arm64.mk
+++ b/core/combo/TARGET_linux-arm64.mk
@@ -91,6 +91,7 @@
 TARGET_GLOBAL_CFLAGS += \
     -Werror=pointer-to-int-cast \
     -Werror=int-to-pointer-cast \
+    -Werror=implicit-function-declaration \
 
 TARGET_GLOBAL_CFLAGS += -fno-strict-volatile-bitfields
 
diff --git a/core/combo/TARGET_linux-mips64.mk b/core/combo/TARGET_linux-mips64.mk
index 5c5610e..c6f9f29 100644
--- a/core/combo/TARGET_linux-mips64.mk
+++ b/core/combo/TARGET_linux-mips64.mk
@@ -96,6 +96,12 @@
 			-include $(android_config_h) \
 			-I $(dir $(android_config_h))
 
+# Help catch common 32/64-bit errors.
+TARGET_GLOBAL_CFLAGS += \
+    -Werror=pointer-to-int-cast \
+    -Werror=int-to-pointer-cast \
+    -Werror=implicit-function-declaration \
+
 ifneq ($(ARCH_MIPS_PAGE_SHIFT),)
 TARGET_GLOBAL_CFLAGS += -DPAGE_SHIFT=$(ARCH_MIPS_PAGE_SHIFT)
 endif
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index e22500e..f17a514 100644
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -147,3 +147,5 @@
 $(combo_2nd_arch_prefix)TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libm
 
 $(combo_2nd_arch_prefix)TARGET_LINKER := /system/bin/linker
+
+$(combo_2nd_arch_prefix)TARGET_GLOBAL_YASM_FLAGS := -f elf32 -m x86
diff --git a/core/combo/TARGET_linux-x86_64.mk b/core/combo/TARGET_linux-x86_64.mk
index ae17c72..2adb157 100644
--- a/core/combo/TARGET_linux-x86_64.mk
+++ b/core/combo/TARGET_linux-x86_64.mk
@@ -97,6 +97,7 @@
 TARGET_GLOBAL_CFLAGS += \
     -Werror=pointer-to-int-cast \
     -Werror=int-to-pointer-cast \
+    -Werror=implicit-function-declaration \
 
 android_config_h := $(call select-android-config-h,target_linux-x86)
 TARGET_ANDROID_CONFIG_CFLAGS := -include $(android_config_h) -I $(dir $(android_config_h))
@@ -116,6 +117,9 @@
 ifeq ($(ARCH_X86_HAVE_SSE4_2),true)
     TARGET_GLOBAL_CFLAGS += -msse4.2
 endif
+ifeq ($(ARCH_X86_HAVE_POPCNT),true)
+    TARGET_GLOBAL_CFLAGS += -mpopcnt
+endif
 ifeq ($(ARCH_X86_HAVE_AVX),true)
     TARGET_GLOBAL_CFLAGS += -mavx
 endif
@@ -152,3 +156,5 @@
 TARGET_DEFAULT_SYSTEM_SHARED_LIBRARIES := libc libm
 
 TARGET_LINKER := /system/bin/linker64
+
+TARGET_GLOBAL_YASM_FLAGS := -f elf64 -m amd64
diff --git a/core/combo/arch/x86_64/x86_64.mk b/core/combo/arch/x86_64/x86_64.mk
index 9d2b620..08dd9cd 100755
--- a/core/combo/arch/x86_64/x86_64.mk
+++ b/core/combo/arch/x86_64/x86_64.mk
@@ -8,6 +8,9 @@
 ARCH_X86_HAVE_SSSE3 := true
 ARCH_X86_HAVE_MOVBE := false # Only supported on Atom.
 ARCH_X86_HAVE_POPCNT := true
+ARCH_X86_HAVE_SSE4 := true
+ARCH_X86_HAVE_SSE4_1 := true
+ARCH_X86_HAVE_SSE4_2 := true
 
 
 # CFLAGS for this arch
diff --git a/core/combo/include/arch/windows/AndroidConfig.h b/core/combo/include/arch/windows/AndroidConfig.h
index 346ba89..e7eb837 100644
--- a/core/combo/include/arch/windows/AndroidConfig.h
+++ b/core/combo/include/arch/windows/AndroidConfig.h
@@ -58,19 +58,19 @@
 /* TODO: replace references to this. */
 #define HAVE_WIN32_IPC
 
+#ifdef __CYGWIN__
+#error "CYGWIN is unsupported for platform builds"
+#endif
+
 /*
  * Define this if you build against MSVCRT.DLL
  */
-#ifndef __CYGWIN__
-#  define HAVE_MS_C_RUNTIME
-#endif
+#define HAVE_MS_C_RUNTIME
 
 /*
  * Define this if we want to use WinSock.
  */
-#ifndef __CYGWIN__
 #define HAVE_WINSOCK
-#endif
 
 /*
  * We need to choose between 32-bit and 64-bit off_t.  All of our code should
@@ -95,16 +95,6 @@
 #define OS_PATH_SEPARATOR '\\'
 
 /*
- * Define if <winsock2.h> exists.
- * Only MinGW has it.
- */
-#ifdef USE_MINGW
-#define HAVE_WINSOCK2_H 1
-#else
-/* #define HAVE_WINSOCK2_H */
-#endif
-
-/*
  * Various definitions missing in MinGW
  */
 #ifdef USE_MINGW
diff --git a/core/combo/javac.mk b/core/combo/javac.mk
index fb43ea4..82cbb43 100644
--- a/core/combo/javac.mk
+++ b/core/combo/javac.mk
@@ -9,6 +9,11 @@
 #   COMMON_JAVAC -- Java compiler command with common arguments
 #
 
+ifndef ANDROID_COMPILE_WITH_JACK
+# Defines if compilation with jack is enabled by default.
+ANDROID_COMPILE_WITH_JACK := true
+endif
+
 common_jdk_flags := -source 1.7 -target 1.7 -Xmaxerrs 9999999
 
 # Use the indexer wrapper to index the codebase instead of the javac compiler
diff --git a/core/config.mk b/core/config.mk
index add068e..c3877ee 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -83,6 +83,7 @@
 BUILD_DROIDDOC:= $(BUILD_SYSTEM)/droiddoc.mk
 BUILD_COPY_HEADERS := $(BUILD_SYSTEM)/copy_headers.mk
 BUILD_NATIVE_TEST := $(BUILD_SYSTEM)/native_test.mk
+BUILD_NATIVE_BENCHMARK := $(BUILD_SYSTEM)/native_benchmark.mk
 BUILD_HOST_NATIVE_TEST := $(BUILD_SYSTEM)/host_native_test.mk
 
 BUILD_SHARED_TEST_LIBRARY := $(BUILD_SYSTEM)/shared_test_lib.mk
@@ -95,8 +96,6 @@
 BUILD_HOST_DALVIK_STATIC_JAVA_LIBRARY := $(BUILD_SYSTEM)/host_dalvik_static_java_library.mk
 
 
--include cts/build/config.mk
-
 # ###############################################################
 # Parse out any modifier targets.
 # ###############################################################
@@ -118,6 +117,12 @@
 COMMON_GLOBAL_CPPFLAGS:= $(COMMON_GLOBAL_CFLAGS) -Wsign-promo -std=gnu++11
 COMMON_RELEASE_CPPFLAGS:= $(COMMON_RELEASE_CFLAGS)
 
+GLOBAL_CFLAGS_NO_OVERRIDE :=  \
+    -Werror=int-to-pointer-cast \
+    -Werror=pointer-to-int-cast \
+
+GLOBAL_CPPFLAGS_NO_OVERRIDE :=
+
 # Set the extensions used for various packages
 COMMON_PACKAGE_SUFFIX := .zip
 COMMON_JAVA_PACKAGE_SUFFIX := .jar
@@ -129,6 +134,12 @@
 # TODO: do symbol compression
 TARGET_COMPRESS_MODULE_SYMBOLS := false
 
+ifdef TMPDIR
+JAVA_TMPDIR_ARG := -Djava.io.tmpdir=$(TMPDIR)
+else
+JAVA_TMPDIR_ARG :=
+endif
+
 # ###############################################################
 # Include sub-configuration files
 # ###############################################################
@@ -392,12 +403,17 @@
 endif
 APICHECK := $(HOST_OUT_EXECUTABLES)/apicheck$(HOST_EXECUTABLE_SUFFIX)
 FS_GET_STATS := $(HOST_OUT_EXECUTABLES)/fs_get_stats$(HOST_EXECUTABLE_SUFFIX)
-MKEXT2IMG := $(HOST_OUT_EXECUTABLES)/genext2fs$(HOST_EXECUTABLE_SUFFIX)
 MAKE_EXT4FS := $(HOST_OUT_EXECUTABLES)/make_ext4fs$(HOST_EXECUTABLE_SUFFIX)
 MKEXTUSERIMG := $(HOST_OUT_EXECUTABLES)/mkuserimg.sh
+ifeq ($(HOST_OS),linux)
+MAKE_SQUASHFS := $(HOST_OUT_EXECUTABLES)/mksquashfs$(HOST_EXECUTABLE_SUFFIX)
+MKSQUASHFSUSERIMG := $(HOST_OUT_EXECUTABLES)/mksquashfsimage.sh
+else
+MAKE_SQUASHFS :=
+MKSQUASHFSUSERIMG :=
+endif
 MAKE_F2FS := $(HOST_OUT_EXECUTABLES)/make_f2fs$(HOST_EXECUTABLE_SUFFIX)
 MKF2FSUSERIMG := $(HOST_OUT_EXECUTABLES)/mkf2fsuserimg.sh
-MKEXT2BOOTIMG := external/genext2fs/mkbootimg_ext2.sh
 SIMG2IMG := $(HOST_OUT_EXECUTABLES)/simg2img$(HOST_EXECUTABLE_SUFFIX)
 E2FSCK := $(HOST_OUT_EXECUTABLES)/e2fsck$(HOST_EXECUTABLE_SUFFIX)
 MKTARBALL := build/tools/mktarball.sh
@@ -420,7 +436,7 @@
 # $(1): vm arguments
 # $(2): jack perf arguments
 define call-jack
-$(JACK_VM) $(1) -cp $(JACK_JAR) com.android.jack.Main $(2)
+$(JACK_VM) $(1) $(JAVA_TMPDIR_ARG) -jar $(JACK_JAR) $(2)
 endef
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_VM_ARGS := $(DEFAULT_JACK_VM_ARGS)
 ifneq ($(ANDROID_JACK_VM_ARGS),)
@@ -431,9 +447,12 @@
 ifneq ($(ANDROID_JACK_EXTRA_ARGS),)
 DEFAULT_JACK_EXTRA_ARGS := $(ANDROID_JACK_EXTRA_ARGS)
 else
-DEFAULT_JACK_EXTRA_ARGS := -D sched.runner=single-threaded --sanity-checks off
+DEFAULT_JACK_EXTRA_ARGS := --sanity-checks off
 endif
-JILL := java -Xmx3500m -cp $(JILL_JAR) com.android.jill.Main
+# Turn off jack warnings by default.
+DEFAULT_JACK_EXTRA_ARGS += --verbose error
+
+JILL := java -Xmx3500m -jar $(JILL_JAR)
 PROGUARD := external/proguard/bin/proguard.sh
 JAVATAGS := build/tools/java-event-log-tags.py
 LLVM_RS_CC := $(HOST_OUT_EXECUTABLES)/llvm-rs-cc$(HOST_EXECUTABLE_SUFFIX)
@@ -444,6 +463,8 @@
 VERITY_SIGNER := $(HOST_OUT_EXECUTABLES)/verity_signer
 BUILD_VERITY_TREE := $(HOST_OUT_EXECUTABLES)/build_verity_tree
 BOOT_SIGNER := $(HOST_OUT_EXECUTABLES)/boot_signer
+FUTILITY := prebuilts/misc/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)/futility/futility
+VBOOT_SIGNER := prebuilts/misc/scripts/vboot_signer/vboot_signer.sh
 
 # ACP is always for the build OS, not for the host OS
 ACP := $(BUILD_OUT_EXECUTABLES)/acp$(BUILD_EXECUTABLE_SUFFIX)
@@ -567,7 +588,15 @@
 
 # Flags for DEX2OAT
 DEX2OAT_TARGET_ARCH := $(TARGET_ARCH)
+ifeq ($(TARGET_CPU_VARIANT),)
+ifeq ($(TARGET_ARCH_VARIANT),)
+DEX2OAT_TARGET_CPU_VARIANT := default
+else
+DEX2OAT_TARGET_CPU_VARIANT := $(TARGET_ARCH_VARIANT)
+endif
+else
 DEX2OAT_TARGET_CPU_VARIANT := $(TARGET_CPU_VARIANT)
+endif
 DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES := default
 
 ifdef TARGET_2ND_ARCH
diff --git a/core/configure_local_jack.mk b/core/configure_local_jack.mk
new file mode 100644
index 0000000..98b13d2
--- /dev/null
+++ b/core/configure_local_jack.mk
@@ -0,0 +1,30 @@
+#
+# Copyright (C) 2008 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.
+#
+
+ifdef ANDROID_FORCE_JACK_ENABLED
+LOCAL_JACK_ENABLED := $(ANDROID_FORCE_JACK_ENABLED)
+endif
+LOCAL_JACK_ENABLED := $(strip $(LOCAL_JACK_ENABLED))
+ifneq ($(LOCAL_JACK_ENABLED),full)
+ifneq ($(LOCAL_JACK_ENABLED),incremental)
+ifdef LOCAL_JACK_ENABLED
+ifneq ($(LOCAL_JACK_ENABLED),disabled)
+$(error $(LOCAL_PATH): invalid LOCAL_JACK_ENABLED "$(LOCAL_JACK_ENABLED)" for $(LOCAL_MODULE))
+endif
+endif
+LOCAL_JACK_ENABLED :=
+endif
+endif
diff --git a/core/cxx_stl_setup.mk b/core/cxx_stl_setup.mk
index 0f574d2..63e2069 100644
--- a/core/cxx_stl_setup.mk
+++ b/core/cxx_stl_setup.mk
@@ -10,6 +10,11 @@
         # Platform code. Select the appropriate STL.
         ifndef USE_MINGW
             my_cxx_stl := libc++
+            ifdef LOCAL_IS_HOST_MODULE
+                ifneq (,$(BUILD_HOST_static))
+                    my_cxx_stl := libc++_static
+                endif
+            endif
         else
             # libc++ is not supported on mingw.
             my_cxx_stl := libstdc++
@@ -21,6 +26,26 @@
     my_cxx_stl := $(strip $(LOCAL_CXX_STL))
 endif
 
+# Yes, this is actually what the clang driver does.
+HOST_linux_dynamic_gcclibs := -lgcc_s -lgcc -lc -lgcc_s -lgcc
+HOST_linux_static_gcclibs := -Wl,--start-group -lgcc -lgcc_eh -lc -Wl,--end-group
+HOST_darwin_dynamic_gcclibs := -lc -lSystem
+HOST_darwin_static_gcclibs := NO_STATIC_HOST_BINARIES_ON_DARWIN
+
+my_link_type := dynamic
+ifdef LOCAL_IS_HOST_MODULE
+    ifneq (,$(BUILD_HOST_static))
+        my_link_type := static
+    endif
+    ifeq (-static,$(filter -static,$(my_ldflags)))
+        my_link_type := static
+    endif
+else
+    ifeq (true,$(LOCAL_FORCE_STATIC_EXECUTABLE))
+        my_link_type := static
+    endif
+endif
+
 ifneq ($(filter $(my_cxx_stl),libc++ libc++_static),)
     my_cflags += -D_USING_LIBCXX
     my_c_includes += external/libcxx/include
@@ -28,12 +53,18 @@
         my_shared_libraries += libc++
     else
         my_static_libraries += libc++_static
+        ifndef LOCAL_IS_HOST_MODULE
+            ifeq ($(LOCAL_FORCE_STATIC_EXECUTABLE),true)
+                my_static_libraries += libm libc libdl
+            endif
+        endif
     endif
 
     ifdef LOCAL_IS_HOST_MODULE
         my_cppflags += -nostdinc++
         my_ldflags += -nodefaultlibs
-        my_ldlibs += -lc -lm -lpthread
+        my_ldlibs += -lpthread -lm
+        my_ldlibs += $($(my_prefix)$(HOST_OS)_$(my_link_type)_gcclibs)
     endif
 else ifneq ($(filter $(my_cxx_stl),stlport stlport_static),)
     ifndef LOCAL_IS_HOST_MODULE
@@ -61,7 +92,8 @@
 else ifeq ($(my_cxx_stl),none)
     ifdef LOCAL_IS_HOST_MODULE
         my_cppflags += -nostdinc++
-        my_ldflags += -nodefaultlibs -lc -lm
+        my_ldflags += -nodefaultlibs
+        my_ldlibs += $($(my_prefix)$(HOST_OS)_$(my_link_type)_gcclibs)
     endif
 else
     $(error $(my_cxx_stl) is not a supported STL.)
diff --git a/core/definitions.mk b/core/definitions.mk
index a0af072..a833edc 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -923,7 +923,7 @@
 	$(dir $@)/$(notdir $(<:.bc=.o)) \
 	$(RS_PREBUILT_COMPILER_RT) \
 	-o $@ $(TARGET_GLOBAL_LDFLAGS) -Wl,--hash-style=sysv -L prebuilts/gcc/ \
-	-L $(TARGET_OUT_INTERMEDIATE_LIBRARIES) $(RS_PREBUILT_LIBPATH) \
+	$(RS_PREBUILT_LIBPATH) -L $(TARGET_OUT_INTERMEDIATE_LIBRARIES) \
 	-lRSSupport -lm -lc
 endef
 
@@ -1028,6 +1028,8 @@
 	$(PRIVATE_CFLAGS) \
 	$(PRIVATE_CPPFLAGS) \
 	$(PRIVATE_DEBUG_CFLAGS) \
+	$(GLOBAL_CFLAGS_NO_OVERRIDE) \
+	$(GLOBAL_CPPFLAGS_NO_OVERRIDE) \
 	-MD -MF $(patsubst %.o,%.d,$@) -o $@ $<
 $(transform-d-to-p)
 endef
@@ -1060,7 +1062,11 @@
 
 define transform-c-to-o-no-deps
 @echo "target $(PRIVATE_ARM_MODE) C: $(PRIVATE_MODULE) <= $<"
-$(call transform-c-or-s-to-o-no-deps, $(PRIVATE_CFLAGS) $(PRIVATE_CONLYFLAGS) $(PRIVATE_DEBUG_CFLAGS))
+$(call transform-c-or-s-to-o-no-deps, \
+    $(PRIVATE_CFLAGS) \
+    $(PRIVATE_CONLYFLAGS) \
+    $(PRIVATE_DEBUG_CFLAGS) \
+    $(GLOBAL_CFLAGS_NO_OVERRIDE))
 endef
 
 define transform-s-to-o-no-deps
@@ -1083,7 +1089,7 @@
 @mkdir -p $(dir $@)
 $(hide) $(YASM) \
     $(addprefix -I , $(PRIVATE_C_INCLUDES)) \
-    -f elf32 -m x86 \
+    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_YASM_FLAGS) \
     $(PRIVATE_ASFLAGS) \
     -o $@ $<
 endef
@@ -1190,6 +1196,64 @@
 $(transform-d-to-p)
 endef
 
+
+###########################################################
+## Rules to compile a single C/C++ source with ../ in the path
+###########################################################
+# Replace "../" in object paths with $(DOTDOT_REPLACEMENT).
+DOTDOT_REPLACEMENT := dotdot/
+
+## Rule to compile a C++ source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the C++ source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-cpp-file
+o := $(intermediates)/$(patsubst %$(LOCAL_CPP_EXTENSION),%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)cpp-to-o)
+-include $$(o:%.o=%.P)
+$(3) += $$(o)
+endef
+
+## Rule to compile a C source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the C source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-c-file
+o := $(intermediates)/$(patsubst %.c,%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)c-to-o)
+-include $$(o:%.o=%.P)
+$(3) += $$(o)
+endef
+
+## Rule to compile a .S source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the .S source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-s-file
+o := $(intermediates)/$(patsubst %.S,%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)s-to-o)
+-include $$(o:%.o=%.P)
+$(3) += $$(o)
+endef
+
+## Rule to compile a .s source file with ../ in the path.
+## Must be called with $(eval).
+# $(1): the .s source file in LOCAL_SRC_FILES.
+# $(2): the additional dependencies.
+# $(3): the variable name to collect the output object file.
+define compile-dotdot-s-file-no-deps
+o := $(intermediates)/$(patsubst %.s,%.o,$(subst ../,$(DOTDOT_REPLACEMENT),$(1)))
+$$(o) : $(TOPDIR)$(LOCAL_PATH)/$(1) $(2)
+	$$(transform-$$(PRIVATE_HOST)s-to-o-no-deps)
+$(3) += $$(o)
+endef
+
 ###########################################################
 ## Commands for running ar
 ###########################################################
@@ -1783,7 +1847,7 @@
 
 define transform-jar-to-jack
 	$(hide) mkdir -p $(dir $@)
-	$(JILL) --output $@.tmpjill.jack $<
+	$(JILL) $(PRIVATE_JILL_FLAGS) --output $@.tmpjill.jack $<
 	$(hide) mkdir -p $@.tmpjill.res
 	$(hide) $(call unzip-jar-files,$<,$@.tmpjill.res)
 	$(hide) find $@.tmpjill.res -iname "*.class" -delete
@@ -1953,10 +2017,10 @@
 # $(1) package to create
 define create-empty-package-at
 @mkdir -p $(dir $(1))
-$(hide) touch $(dir $(1))dummy
-$(hide) (cd $(dir $(1)) && jar cf $(notdir $(1)) dummy)
-$(hide) zip -qd $(1) dummy
-$(hide) rm $(dir $(1))dummy
+$(hide) touch $(dir $(1))zipdummy
+$(hide) (cd $(dir $(1)) && jar cf $(notdir $(1)) zipdummy)
+$(hide) zip -qd $(1) zipdummy
+$(hide) rm $(dir $(1))zipdummy
 endef
 
 # Create a mostly-empty .jar file that we'll add to later.
@@ -2018,7 +2082,7 @@
 $(foreach abi,$(PRIVATE_JNI_SHARED_LIBRARIES_ABI),\
   $(call _add-jni-shared-libs-to-package-per-abi,$(abi),\
     $(patsubst $(abi):%,%,$(filter $(abi):%,$(PRIVATE_JNI_SHARED_LIBRARIES)))))
-$(hide) (cd $(dir $@) && zip -r $(notdir $@) lib)
+$(hide) (cd $(dir $@) && zip -r $(PRIVATE_JNI_SHARED_LIBRARIES_ZIP_OPTIONS) $(notdir $@) lib)
 $(hide) rm -rf $(dir $@)lib
 endef
 
@@ -2059,12 +2123,15 @@
 $(hide) mv $@.signed $@
 endef
 
-# Align STORED entries of a package on 4-byte boundaries
-# to make them easier to mmap.
+# Align STORED entries of a package on 4-byte boundaries to make them easier to mmap.
 #
 define align-package
 $(hide) mv $@ $@.unaligned
-$(hide) $(ZIPALIGN) -f 4 $@.unaligned $@.aligned
+$(hide) $(ZIPALIGN) \
+    -f \
+    $(if $(findstring true, $(PRIVATE_PAGE_ALIGN_JNI_SHARED_LIBRARIES)),-p ,) \
+    4 \
+    $@.unaligned $@.aligned
 $(hide) mv $@.aligned $@
 endef
 
diff --git a/core/dex_preopt_libart.mk b/core/dex_preopt_libart.mk
index 9dc8af3..fb62e0c 100644
--- a/core/dex_preopt_libart.mk
+++ b/core/dex_preopt_libart.mk
@@ -62,7 +62,7 @@
 # $(1): the arch name.
 # $(2): the full path (including file name) of the corresponding .jar or .apk.
 define get-odex-file-path
-$(dir $(2))$(1)/$(basename $(notdir $(2))).odex
+$(dir $(2))oat/$(1)/$(basename $(notdir $(2))).odex
 endef
 
 # Returns the path to the image file (such as "/system/framework/<arch>/boot.art"
@@ -106,5 +106,6 @@
 	--instruction-set-variant=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT) \
 	--instruction-set-features=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) \
 	--include-patch-information --runtime-arg -Xnorelocate --no-include-debug-symbols \
+	--abort-on-hard-verifier-error \
 	$(PRIVATE_DEX_PREOPT_FLAGS)
 endef
diff --git a/core/dex_preopt_odex_install.mk b/core/dex_preopt_odex_install.mk
index aef5cd1..73c8146 100644
--- a/core/dex_preopt_odex_install.mk
+++ b/core/dex_preopt_odex_install.mk
@@ -53,7 +53,14 @@
 installed_odex += $($(TARGET_2ND_ARCH_VAR_PREFIX)DEFAULT_DEX_PREOPT_INSTALLED_IMAGE)
 else  # boot jar
 ifeq ($(LOCAL_MODULE_CLASS),JAVA_LIBRARIES)
-# For a Java library, we build odex for both 1st arch and 2nd arch, if we have one.
+# For a Java library, by default we build odex for both 1st arch and 2nd arch.
+# But it can be overridden with "LOCAL_MULTILIB := first".
+ifneq (,$(filter $(PRODUCT_SYSTEM_SERVER_JARS),$(LOCAL_MODULE)))
+# For system server jars, we build for only "first".
+my_module_multilib := first
+else
+my_module_multilib := $(LOCAL_MULTILIB)
+endif
 # #################################################
 # Odex for the 1st arch
 my_2nd_arch_prefix :=
@@ -61,8 +68,10 @@
 # #################################################
 # Odex for the 2nd arch
 ifdef TARGET_2ND_ARCH
+ifneq (first,$(my_module_multilib))
 my_2nd_arch_prefix := $(TARGET_2ND_ARCH_VAR_PREFIX)
 include $(BUILD_SYSTEM)/setup_one_odex.mk
+endif  # my_module_multilib is not first.
 endif  # TARGET_2ND_ARCH
 # #################################################
 else  # must be APPS
diff --git a/core/dpi_specific_apk.mk b/core/dpi_specific_apk.mk
index a05380f..3790744 100644
--- a/core/dpi_specific_apk.mk
+++ b/core/dpi_specific_apk.mk
@@ -30,14 +30,18 @@
 $(built_dpi_apk): PRIVATE_ADDITIONAL_CERTIFICATES := $(foreach c,\
     $(LOCAL_ADDITIONAL_CERTIFICATES), $(c).x509.pem $(c).pk8)
 
+$(built_dpi_apk): PRIVATE_SOURCE_ARCHIVE :=
 ifneq ($(full_classes_jar),)
 $(built_dpi_apk): PRIVATE_DEX_FILE := $(built_dex)
+ifndef LOCAL_JACK_ENABLED
 # Use the jarjar processed arhive as the initial package file.
 $(built_dpi_apk): PRIVATE_SOURCE_ARCHIVE := $(full_classes_jarjar_jar)
+else
+$(built_dpi_apk): PRIVATE_JACK_INTERMEDIATES_DIR := $(intermediates.COMMON)/jack-rsc
+endif # LOCAL_JACK_ENABLED
 $(built_dpi_apk): $(built_dex)
 else
 $(built_dpi_apk): PRIVATE_DEX_FILE :=
-$(built_dpi_apk): PRIVATE_SOURCE_ARCHIVE :=
 endif # full_classes_jar
 
 # Set up dependenncies and the build recipe.
@@ -56,6 +60,9 @@
 endif
 ifneq ($(full_classes_jar),)
 	$(add-dex-to-package)
+ifdef LOCAL_JACK_ENABLED
+	$(add-carried-jack-resources)
+endif
 endif
 	$(sign-package)
 	$(align-package)
diff --git a/core/envsetup.mk b/core/envsetup.mk
index 43774ea..ee04557 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -72,6 +72,10 @@
   HOST_ARCH := x86_64
   HOST_2ND_ARCH := x86
   HOST_IS_64_BIT := true
+else
+ifneq (,$(findstring x86,$(UNAME)))
+$(error Building on a 32-bit x86 host is not supported: $(UNAME)!)
+endif
 endif
 
 BUILD_ARCH := $(HOST_ARCH)
@@ -107,6 +111,7 @@
 TARGET_COPY_OUT_SYSTEM := system
 TARGET_COPY_OUT_DATA := data
 TARGET_COPY_OUT_OEM := oem
+TARGET_COPY_OUT_ODM := odm
 TARGET_COPY_OUT_ROOT := root
 TARGET_COPY_OUT_RECOVERY := recovery
 ###########################################
@@ -341,7 +346,7 @@
 
 TARGET_OUT_OEM := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_OEM)
 TARGET_OUT_OEM_EXECUTABLES := $(TARGET_OUT_OEM)/bin
-ifneq ($(filter %64,$(TARGET_ARCH)),)
+ifeq ($(TARGET_IS_64_BIT),true)
 TARGET_OUT_OEM_SHARED_LIBRARIES := $(TARGET_OUT_OEM)/lib64
 else
 TARGET_OUT_OEM_SHARED_LIBRARIES := $(TARGET_OUT_OEM)/lib
@@ -355,6 +360,20 @@
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_OEM_SHARED_LIBRARIES := $(TARGET_OUT_OEM)/lib
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_OEM_APPS := $(TARGET_OUT_OEM_APPS)
 
+TARGET_OUT_ODM := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_ODM)
+TARGET_OUT_ODM_EXECUTABLES := $(TARGET_OUT_ODM)/bin
+ifeq ($(TARGET_IS_64_BIT),true)
+TARGET_OUT_ODM_SHARED_LIBRARIES := $(TARGET_OUT_ODM)/lib64
+else
+TARGET_OUT_ODM_SHARED_LIBRARIES := $(TARGET_OUT_ODM)/lib
+endif
+TARGET_OUT_ODM_APPS := $(TARGET_OUT_ODM)/app
+TARGET_OUT_ODM_ETC := $(TARGET_OUT_ODM)/etc
+
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_ODM_EXECUTABLES := $(TARGET_OUT_ODM_EXECUTABLES)
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_ODM_SHARED_LIBRARIES := $(TARGET_OUT_ODM)/lib
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_ODM_APPS := $(TARGET_OUT_ODM_APPS)
+
 TARGET_OUT_UNSTRIPPED := $(PRODUCT_OUT)/symbols
 TARGET_OUT_EXECUTABLES_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)/system/bin
 TARGET_OUT_SHARED_LIBRARIES_UNSTRIPPED := $(TARGET_OUT_UNSTRIPPED)/system/lib
diff --git a/core/executable_prefer_symlink.mk b/core/executable_prefer_symlink.mk
index 2326e83..fc97ad3 100644
--- a/core/executable_prefer_symlink.mk
+++ b/core/executable_prefer_symlink.mk
@@ -39,7 +39,10 @@
   endif
 endif
 
-$(my_symlink): $(LOCAL_INSTALLED_MODULE) $(LOCAL_MODULE_MAKEFILE)
+# $(my_symlink) doesn't need to depend on $(PRIVATE_SRC_BINARY_NAME): we can generate symlink to nonexistent file.
+# If you add the dependency, make would compare the timestamp of a file against that of its symlink:
+# they are always equal, because make follows symlink.
+$(my_symlink): $(LOCAL_MODULE_MAKEFILE)
 	@echo "Symlink: $@ -> $(PRIVATE_SRC_BINARY_NAME)"
 	@mkdir -p $(dir $@)
 	@rm -rf $@
diff --git a/core/host_dalvik_java_library.mk b/core/host_dalvik_java_library.mk
index f5da638..9ee1183 100644
--- a/core/host_dalvik_java_library.mk
+++ b/core/host_dalvik_java_library.mk
@@ -133,7 +133,11 @@
 	@echo Building with Jack: $@
 	$(jack-java-to-dex)
 
+# $(full_classes_jack) is just by-product of $(built_dex).
+# The dummy command was added because, without it, make misses the fact the $(built_dex) also
+# change $(full_classes_jack).
 $(full_classes_jack): $(built_dex)
+	$(hide) touch $@
 
 $(LOCAL_BUILT_MODULE): PRIVATE_DEX_FILE := $(built_dex)
 $(LOCAL_BUILT_MODULE): $(built_dex) $(java_resource_sources)
diff --git a/core/host_dalvik_static_java_library.mk b/core/host_dalvik_static_java_library.mk
index bdce583..410b251 100644
--- a/core/host_dalvik_static_java_library.mk
+++ b/core/host_dalvik_static_java_library.mk
@@ -21,6 +21,8 @@
 #
 ifeq ($(HOST_OS),linux)
 
+LOCAL_UNINSTALLABLE_MODULE := true
+LOCAL_IS_STATIC_JAVA_LIBRARY := true
 USE_CORE_LIB_BOOTCLASSPATH := true
 LOCAL_JAVA_LIBRARIES += core-libart-hostdex
 
@@ -51,5 +53,5 @@
 	$(java-to-jack)
 
 USE_CORE_LIB_BOOTCLASSPATH :=
-
+LOCAL_IS_STATIC_JAVA_LIBRARY :=
 endif
diff --git a/core/host_java_library.mk b/core/host_java_library.mk
index b751c5f..513d185 100644
--- a/core/host_java_library.mk
+++ b/core/host_java_library.mk
@@ -58,13 +58,13 @@
 $(full_classes_emma_jar) : $(full_classes_compiled_jar) | $(EMMA_JAR)
 	$(transform-classes.jar-to-emma)
 
-$(LOCAL_BUILT_MODULE) : $(full_classes_emma_jar)
+$(built_javalib_jar) : $(full_classes_emma_jar)
 	@echo Copying: $@
 	$(hide) $(ACP) -fp $< $@
 
 else # LOCAL_EMMA_INSTRUMENT
-# Directly build into LOCAL_BUILT_MODULE.
-full_classes_compiled_jar := $(LOCAL_BUILT_MODULE)
+# Directly build into $(built_javalib_jar).
+full_classes_compiled_jar := $(built_javalib_jar)
 endif # LOCAL_EMMA_INSTRUMENT
 
 $(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
diff --git a/core/host_java_library_common.mk b/core/host_java_library_common.mk
index cd9e679..35a6e28 100644
--- a/core/host_java_library_common.mk
+++ b/core/host_java_library_common.mk
@@ -23,6 +23,22 @@
 LOCAL_IS_HOST_MODULE := true
 LOCAL_BUILT_MODULE_STEM := javalib.jar
 
+intermediates := $(call local-intermediates-dir)
+intermediates.COMMON := $(call local-intermediates-dir,COMMON)
+
+built_javalib_jar := $(intermediates)/javalib.jar
+
+#################################
+include $(BUILD_SYSTEM)/configure_local_jack.mk
+#################################
+
+ifdef LOCAL_JACK_ENABLED
+ifdef LOCAL_IS_STATIC_JAVA_LIBRARY
+LOCAL_BUILT_MODULE_STEM := classes.jack
+LOCAL_INTERMEDIATE_TARGETS += $(built_javalib_jar)
+endif
+endif
+
 # base_rules.mk looks at this
 all_res_assets :=
 
@@ -34,14 +50,15 @@
   ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
     LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-nano
   else
-    LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-lite
+    ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),full)
+      LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-full
+    else
+      LOCAL_JAVA_LIBRARIES += host-libprotobuf-java-lite
+    endif
   endif
 endif
 endif
 
-intermediates := $(call local-intermediates-dir)
-intermediates.COMMON := $(call local-intermediates-dir,COMMON)
-
 LOCAL_INTERMEDIATE_SOURCE_DIR := $(intermediates.COMMON)/src
 LOCAL_JAVA_LIBRARIES := $(sort $(LOCAL_JAVA_LIBRARIES))
 
diff --git a/core/install_jni_libs_internal.mk b/core/install_jni_libs_internal.mk
index 944420b..c28bb15 100644
--- a/core/install_jni_libs_internal.mk
+++ b/core/install_jni_libs_internal.mk
@@ -100,9 +100,15 @@
 my_prebuilt_jni_libs := $(addprefix $(LOCAL_PATH)/, \
     $(filter-out @%, $(my_prebuilt_jni_libs)))
 ifdef my_prebuilt_jni_libs
+ifdef my_embed_jni
+# Embed my_prebuilt_jni_libs to the apk
+my_jni_shared_libraries += $(my_prebuilt_jni_libs)
+else # not my_embed_jni
+# Install my_prebuilt_jni_libs as separate files.
 $(foreach lib, $(my_prebuilt_jni_libs), \
     $(eval $(call copy-one-file, $(lib), $(my_app_lib_path)/$(notdir $(lib)))))
 
 $(LOCAL_INSTALLED_MODULE) : | $(addprefix $(my_app_lib_path)/, $(notdir $(my_prebuilt_jni_libs)))
+endif  # my_embed_jni
 endif  # inner my_prebuilt_jni_libs
 endif  # outer my_prebuilt_jni_libs
diff --git a/core/java.mk b/core/java.mk
index d4f0039..1494c4b 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -220,6 +220,11 @@
 
 # We don't need the .so files in bundled branches
 # Prevent these from showing up on the device
+# One exception is librsjni.so, which is needed for
+# both native path and compat path.
+rs_jni_lib := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/librsjni.so
+LOCAL_JNI_SHARED_LIBRARIES += librsjni
+
 ifneq (,$(TARGET_BUILD_APPS)$(FORCE_BUILD_RS_COMPAT))
 
 rs_compatibility_jni_libs := $(addprefix \
@@ -229,8 +234,7 @@
 $(rs_generated_bc) : $(RenderScript_file_stamp)
 
 rs_support_lib := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/libRSSupport.so
-rs_jni_lib := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/librsjni.so
-LOCAL_JNI_SHARED_LIBRARIES += libRSSupport librsjni
+LOCAL_JNI_SHARED_LIBRARIES += libRSSupport
 
 rs_support_io_lib :=
 # check if the target api level support USAGE_IO
@@ -534,17 +538,14 @@
 endif
 
 findbugs_xml := $(intermediates.COMMON)/findbugs.xml
-$(findbugs_xml) : PRIVATE_JAR_FILE := $(full_classes_jar)
 $(findbugs_xml) : PRIVATE_AUXCLASSPATH := $(addprefix -auxclasspath ,$(strip \
 								$(call normalize-path-list,$(filter %.jar,\
 										$(full_java_libs)))))
-# We can't depend directly on full_classes_jar because the PRIVATE_
-# vars won't be set up correctly.
-$(findbugs_xml) : $(LOCAL_BUILT_MODULE)
+$(findbugs_xml) : $(full_classes_jar)
 	@echo Findbugs: $@
 	$(hide) $(FINDBUGS) -textui -effort:min -xml:withMessages \
 		$(PRIVATE_AUXCLASSPATH) \
-		$(PRIVATE_JAR_FILE) \
+		$< \
 		> $@
 
 ALL_FINDBUGS_FILES += $(findbugs_xml)
@@ -610,8 +611,12 @@
 	@echo Building with Jack: $@
 	$(jack-java-to-dex)
 
+# $(full_classes_jack) is just by-product of $(built_dex_intermediate).
+# The dummy command was added because, without it, make misses the fact the $(built_dex) also
+# change $(full_classes_jack).
 $(full_classes_jack): $(built_dex_intermediate)
-# nothing to do it's built as a side effect of $(built_dex_intermediate)
+	$(hide) touch $@
+
 endif #LOCAL_IS_STATIC_JAVA_LIBRARY
 
 $(noshrob_classes_jack): PRIVATE_JACK_INTERMEDIATES_DIR := $(intermediates.COMMON)/jack-noshrob-rsc
diff --git a/core/java_library.mk b/core/java_library.mk
index 5ba8267..5a2d19b 100644
--- a/core/java_library.mk
+++ b/core/java_library.mk
@@ -24,10 +24,20 @@
 
 LOCAL_BUILT_MODULE_STEM := javalib.jar
 
+#################################
+include $(BUILD_SYSTEM)/configure_local_jack.mk
+#################################
+
+ifdef LOCAL_JACK_ENABLED
+ifdef LOCAL_IS_STATIC_JAVA_LIBRARY
+LOCAL_BUILT_MODULE_STEM := classes.jack
+endif
+endif
+
 intermediates.COMMON := $(call local-intermediates-dir,COMMON)
 
 # This file will be the one that other modules should depend on.
-common_javalib.jar := $(intermediates.COMMON)/$(LOCAL_BUILT_MODULE_STEM)
+common_javalib.jar := $(intermediates.COMMON)/javalib.jar
 LOCAL_INTERMEDIATE_TARGETS += $(common_javalib.jar)
 
 ifeq ($(LOCAL_PROGUARD_ENABLED),disabled)
@@ -59,7 +69,11 @@
 	@echo "target Static Jar: $(PRIVATE_MODULE) ($@)"
 	$(copy-file-to-target)
 
-$(LOCAL_BUILT_MODULE): $(common_javalib.jar)
+ifdef LOCAL_JACK_ENABLED
+$(LOCAL_BUILT_MODULE) : $(full_classes_jack)
+else
+$(LOCAL_BUILT_MODULE) : $(common_javalib.jar)
+endif
 	$(copy-file-to-target)
 
 else # !LOCAL_IS_STATIC_JAVA_LIBRARY
diff --git a/core/main.mk b/core/main.mk
index d23c762..7350f99 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -93,6 +93,9 @@
 # and host information.
 include $(BUILD_SYSTEM)/config.mk
 
+# CTS-specific config.
+-include cts/build/config.mk
+
 # This allows us to force a clean build - included after the config.mk
 # environment setup is done, but before we generate any dependencies.  This
 # file does the rm -rf inline so the deps which are all done below will
@@ -385,11 +388,12 @@
           ro.setupwizard.mode=OPTIONAL
 endif
 ifndef is_sdk_build
-  # Don't even verify the image on eng builds to speed startup
-  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.image-dex2oat-filter=verify-none
-  # Don't compile apps on eng builds to speed startup
-  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.dex2oat-filter=interpret-only
+  # Don't verify or compile the image on eng builds to speed startup.
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.image-dex2oat-filter=verify-at-runtime
+  # Don't verify or compile apps on eng builds to speed startup.
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.dex2oat-filter=verify-at-runtime
 endif
+  ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.usejit=true
 endif
 
 ## sdk ##
diff --git a/core/native_benchmark.mk b/core/native_benchmark.mk
new file mode 100644
index 0000000..431e40a
--- /dev/null
+++ b/core/native_benchmark.mk
@@ -0,0 +1,12 @@
+###########################################
+## A thin wrapper around BUILD_EXECUTABLE
+## Common flags for native benchmarks are added.
+###########################################
+
+LOCAL_STATIC_LIBRARIES += libbenchmark
+
+ifndef LOCAL_MODULE_PATH
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
+endif
+
+include $(BUILD_EXECUTABLE)
diff --git a/core/notice_files.mk b/core/notice_files.mk
index e63cd84..43a5435 100644
--- a/core/notice_files.mk
+++ b/core/notice_files.mk
@@ -43,7 +43,7 @@
       # javalib.jar is the default name for the build module (and isn't meaningful)
       # If that's what we have, substitute the module name instead.  These files
       # aren't included on the device, so this name is synthetic anyway.
-      ifeq ($(module_leaf),javalib.jar)
+      ifneq ($(filter javalib.jar classes.jack,$(module_leaf)),)
         module_leaf := $(LOCAL_MODULE).jar
       endif
       module_installed_filename := \
diff --git a/core/package_internal.mk b/core/package_internal.mk
index 3c488f6..134445b 100644
--- a/core/package_internal.mk
+++ b/core/package_internal.mk
@@ -57,12 +57,9 @@
 endif
 LOCAL_MODULE_CLASS := APPS
 
-LOCAL_JACK_ENABLED := $(strip $(LOCAL_JACK_ENABLED))
-ifneq ($(LOCAL_JACK_ENABLED),full)
-ifneq ($(LOCAL_JACK_ENABLED),incremental)
-LOCAL_JACK_ENABLED :=
-endif
-endif
+#################################
+include $(BUILD_SYSTEM)/configure_local_jack.mk
+#################################
 
 # Package LOCAL_MODULE_TAGS default to optional
 LOCAL_MODULE_TAGS := $(strip $(LOCAL_MODULE_TAGS))
@@ -395,6 +392,8 @@
 $(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES := $(jni_shared_libraries_with_abis)
 # PRIVATE_JNI_SHARED_LIBRARIES_ABI is a list of ABI names.
 $(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES_ABI := $(jni_shared_libraries_abis)
+$(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES_ZIP_OPTIONS := $(LOCAL_JNI_SHARED_LIBRARIES_ZIP_OPTIONS)
+$(LOCAL_BUILT_MODULE): PRIVATE_PAGE_ALIGN_JNI_SHARED_LIBRARIES := $(LOCAL_PAGE_ALIGN_JNI_SHARED_LIBRARIES)
 ifneq ($(TARGET_BUILD_APPS),)
     # Include all resources for unbundled apps.
     LOCAL_AAPT_INCLUDE_ALL_RESOURCES := true
@@ -524,7 +523,7 @@
 	@rm -rf $(dir $@) && mkdir -p $(dir $@)
 	$(hide) cp $< $@
 	$(hide) zip -d $@ $(foreach f,$(PRIVATE_JNI_SHARED_LIBRARIES),\*/$(f))
-	$(call align-package)
+	$(align-package)
 
 $(call dist-for-goals, apps_only, $(apk_jni_stripped):$(dist_subdir)/$(LOCAL_PACKAGE_NAME).apk)
 
diff --git a/core/prebuilt_internal.mk b/core/prebuilt_internal.mk
index 2a28da3..59e3816 100644
--- a/core/prebuilt_internal.mk
+++ b/core/prebuilt_internal.mk
@@ -190,6 +190,7 @@
 include $(BUILD_SYSTEM)/dex_preopt_odex_install.mk
 #######################################
 # Sign and align non-presigned .apks.
+$(built_module) : PRIVATE_PAGE_ALIGN_JNI_SHARED_LIBRARIES := $(LOCAL_PAGE_ALIGN_JNI_SHARED_LIBRARIES)
 $(built_module) : $(my_prebuilt_src_file) | $(ACP) $(ZIPALIGN) $(SIGNAPK_JAR)
 	$(transform-prebuilt-to-target)
 ifdef extracted_jni_libs
@@ -300,6 +301,7 @@
 endif # TARGET JAVA_LIBRARIES
 
 ifeq ($(LOCAL_MODULE_CLASS),JAVA_LIBRARIES)
+$(intermediates.COMMON)/classes.jack : PRIVATE_JILL_FLAGS:=$(LOCAL_JILL_FLAGS)
 $(intermediates.COMMON)/classes.jack : $(my_prebuilt_src_file) $(LOCAL_MODULE_MAKEFILE) \
         $(LOCAL_ADDITIONAL_DEPENDENCIES) $(JILL_JAR) $(JACK_JAR)
 	$(transform-jar-to-jack)
diff --git a/core/product.mk b/core/product.mk
index 13324dd..77e053f 100644
--- a/core/product.mk
+++ b/core/product.mk
@@ -97,10 +97,12 @@
     PRODUCT_RESTRICT_VENDOR_FILES \
     PRODUCT_VENDOR_KERNEL_HEADERS \
     PRODUCT_BOOT_JARS \
+    PRODUCT_SUPPORTS_VBOOT \
     PRODUCT_SUPPORTS_VERITY \
     PRODUCT_OEM_PROPERTIES \
     PRODUCT_SYSTEM_PROPERTY_BLACKLIST \
     PRODUCT_SYSTEM_SERVER_JARS \
+    PRODUCT_VBOOT_SIGNING_KEY \
     PRODUCT_VERITY_SIGNING_KEY \
     PRODUCT_SYSTEM_VERITY_PARTITION \
     PRODUCT_VENDOR_VERITY_PARTITION \
@@ -252,6 +254,7 @@
 	BOARD_BOOTIMAGE_PARTITION_SIZE \
 	BOARD_RECOVERYIMAGE_PARTITION_SIZE \
 	BOARD_SYSTEMIMAGE_PARTITION_SIZE \
+	BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE \
 	BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE \
 	BOARD_USERDATAIMAGE_PARTITION_SIZE \
 	BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE \
@@ -267,6 +270,10 @@
 	WITH_DEXPREOPT \
 	WITH_DEXPREOPT_BOOT_IMG_ONLY
 
+_product_stash_var_list += \
+	GLOBAL_CFLAGS_NO_OVERRIDE \
+	GLOBAL_CPPFLAGS_NO_OVERRIDE \
+
 #
 # Stash values of the variables in _product_stash_var_list.
 # $(1): Renamed prefix
diff --git a/core/static_java_library.mk b/core/static_java_library.mk
index c5d1b46..9b7b46a 100644
--- a/core/static_java_library.mk
+++ b/core/static_java_library.mk
@@ -59,6 +59,10 @@
 
 LOCAL_PROGUARD_FLAGS := $(addprefix -include ,$(proguard_options_file)) $(LOCAL_PROGUARD_FLAGS)
 
+#################################
+include $(BUILD_SYSTEM)/configure_local_jack.mk
+#################################
+
 ifdef LOCAL_JACK_ENABLED
 ifndef LOCAL_JACK_PROGUARD_FLAGS
     LOCAL_JACK_PROGUARD_FLAGS := $(LOCAL_PROGUARD_FLAGS)
diff --git a/core/tasks/build_custom_images.mk b/core/tasks/build_custom_images.mk
new file mode 100644
index 0000000..8ebf89b
--- /dev/null
+++ b/core/tasks/build_custom_images.mk
@@ -0,0 +1,64 @@
+#
+# Copyright (C) 2015 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Build additional images requested by the product makefile.
+# This script gives the ability to build multiple additional images and you can
+# configure what modules/files to include in each image.
+# 1. Define PRODUCT_CUSTOM_IMAGE_MAKEFILES in your product makefile.
+#    PRODUCT_CUSTOM_IMAGE_MAKEFILES is a list of makefiles.
+#    Each makefile configures an image.
+#    For image configuration makefile foo/bar/xyz.mk, the built image file name
+#    will be xyz.img. So make sure they won't conflict.
+# 2. In each image's configuration makefile, you can define variables:
+#   - CUSTOM_IMAGE_MOUNT_POINT, the mount point, such as "oem", "odm" etc.
+#   - CUSTOM_IMAGE_PARTITION_SIZE
+#   - CUSTOM_IMAGE_FILE_SYSTEM_TYPE
+#   - CUSTOM_IMAGE_DICT_FILE, a text file defines a dictionary accepted by
+#     BuildImage() in tools/releasetools/build_image.py.
+#   - CUSTOM_IMAGE_MODULES, a list of module names you want to include in
+#     the image; Not only the module itself will be installed to proper path in
+#     the image, you can also piggyback additional files/directories with the
+#     module's LOCAL_PICKUP_FILES.
+#   - CUSTOM_IMAGE_COPY_FILES, a list of "<src>:<dest>" to be copied to the
+#     image. <dest> is relativ to the root of the image.
+#   - CUSTOM_IMAGE_SELINUX, set to "true" if the image supports selinux.
+#   - CUSTOM_IMAGE_SUPPORT_VERITY, set to "true" if the product supports verity.
+#   - CUSTOM_IMAGE_VERITY_BLOCK_DEVICE
+#
+# To build all those images, run "make custom_images".
+
+ifneq ($(filter $(MAKECMDGOALS),custom_images),)
+
+.PHONY: custom_images
+
+custom_image_parameter_variables := \
+  CUSTOM_IMAGE_MOUNT_POINT \
+  CUSTOM_IMAGE_PARTITION_SIZE \
+  CUSTOM_IMAGE_FILE_SYSTEM_TYPE \
+  CUSTOM_IMAGE_DICT_FILE \
+  CUSTOM_IMAGE_MODULES \
+  CUSTOM_IMAGE_COPY_FILES \
+  CUSTOM_IMAGE_SELINUX \
+  CUSTOM_IMAGE_SUPPORT_VERITY \
+  CUSTOM_IMAGE_VERITY_BLOCK_DEVICE \
+
+# We don't expect product makefile to inherit/override PRODUCT_CUSTOM_IMAGE_MAKEFILES,
+# so we don't put it in the _product_var_list.
+$(foreach mk, $(PRODUCT_CUSTOM_IMAGE_MAKEFILES),\
+  $(eval my_custom_imag_makefile := $(mk))\
+  $(eval include $(BUILD_SYSTEM)/tasks/tools/build_custom_image.mk))
+
+endif
diff --git a/core/tasks/cts.mk b/core/tasks/cts.mk
index 2ce5dbc..2506766 100644
--- a/core/tasks/cts.mk
+++ b/core/tasks/cts.mk
@@ -21,7 +21,7 @@
 HOSTTESTLIB_JAR := $(HOST_OUT_JAVA_LIBRARIES)/hosttestlib.jar
 TF_JAR := $(HOST_OUT_JAVA_LIBRARIES)/tradefed-prebuilt.jar
 CTS_TF_JAR := $(HOST_OUT_JAVA_LIBRARIES)/cts-tradefed.jar
-CTS_TF_EXEC_PATH := $(HOST_OUT_EXECUTABLES)/cts-tradefed
+CTS_TF_EXEC_PATH ?= $(HOST_OUT_EXECUTABLES)/cts-tradefed
 CTS_TF_README_PATH := $(cts_tools_src_dir)/tradefed-host/README
 
 VMTESTSTF_INTERMEDIATES :=$(call intermediates-dir-for,JAVA_LIBRARIES,vm-tests-tf,HOST)
@@ -60,7 +60,7 @@
 
 
 CTS_TEST_JAR_LIST := \
-        cts-junit \
+	cts-junit \
 	CtsJdwp
 
 # Depend on the full package paths rather than the phony targets to avoid
@@ -69,21 +69,28 @@
 CTS_TEST_JAR_FILES := $(foreach c,$(CTS_TEST_JAR_LIST),$(call intermediates-dir-for,JAVA_LIBRARIES,$(c))/javalib.jar)
 
 -include cts/CtsTestCaseList.mk
-CTS_CASE_LIST := $(CTS_CORE_CASE_LIST) $(CTS_TEST_CASE_LIST)
 
 # A module may have mutliple installed files (e.g. split apks)
 CTS_CASE_LIST_APKS :=
-CTS_CASE_LIST_APKS_DIR := $(cts_dir)/$(cts_name)/repository/testcases/
-$(foreach m, $(CTS_CASE_LIST),\
+$(foreach m, $(CTS_TEST_CASE_LIST),\
+  $(foreach fp, $(ALL_MODULES.$(m).BUILT_INSTALLED),\
+    $(eval pair := $(subst :,$(space),$(fp)))\
+    $(eval CTS_CASE_LIST_APKS += $(CTS_TESTCASES_OUT)/$(notdir $(word 2,$(pair))))))\
+$(foreach m, $(CTS_CORE_CASE_LIST),\
   $(foreach fp, $(ALL_MODULES.$(m).BUILT_INSTALLED),\
     $(eval pair := $(subst :,$(space),$(fp)))\
     $(eval built := $(word 1,$(pair)))\
-    $(eval installed := $(CTS_CASE_LIST_APKS_DIR)/$(notdir $(word 2,$(pair))))\
+    $(eval installed := $(CTS_TESTCASES_OUT)/$(notdir $(word 2,$(pair))))\
     $(eval $(call copy-one-file, $(built), $(installed)))\
     $(eval CTS_CASE_LIST_APKS += $(installed))))
 
+CTS_CASE_LIST_JARS :=
+$(foreach m, $(CTS_TEST_JAR_LIST),\
+  $(eval CTS_CASE_LIST_JARS += $(CTS_TESTCASES_OUT)/$(m).jar))
+
 DEFAULT_TEST_PLAN := $(cts_dir)/$(cts_name)/resource/plans
-$(cts_dir)/all_cts_files_stamp: $(CTS_CORE_CASES) $(CTS_TEST_CASES) $(CTS_CASE_LIST_APKS) $(JUNIT_HOST_JAR) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(VMTESTSTF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(ACP) $(CTS_TEST_JAR_FILES)
+$(cts_dir)/all_cts_files_stamp: $(CTS_CORE_CASES) $(CTS_TEST_JAR_FILES) $(CTS_TEST_CASES) $(CTS_CASE_LIST_APKS) $(CTS_CASE_LIST_JARS) $(JUNIT_HOST_JAR) $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(VMTESTSTF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(ADDITIONAL_TF_JARS) $(ACP)
+
 # Make necessary directory for CTS
 	$(hide) mkdir -p $(TMP_DIR)
 	$(hide) mkdir -p $(PRIVATE_DIR)/docs
@@ -91,11 +98,8 @@
 	$(hide) mkdir -p $(PRIVATE_DIR)/repository/testcases
 	$(hide) mkdir -p $(PRIVATE_DIR)/repository/plans
 # Copy executable and JARs to CTS directory
-	$(hide) $(ACP) -fp $(VMTESTSTF_JAR) $(PRIVATE_DIR)/repository/testcases
-	$(hide) $(ACP) -fp $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(CTS_TF_README_PATH) $(PRIVATE_DIR)/tools
-# Change mode of the executables
-	$(foreach jar,$(CTS_TEST_JAR_LIST),$(call copy-testcase-jar,$(jar)))
-	$(foreach testcase,$(CTS_TEST_CASES),$(call copy-testcase,$(testcase)))
+	$(hide) $(ACP) -fp $(VMTESTSTF_JAR) $(CTS_TESTCASES_OUT)
+	$(hide) $(ACP) -fp $(HOSTTESTLIB_JAR) $(CTS_HOST_LIBRARY_JARS) $(TF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(ADDITIONAL_TF_JARS) $(CTS_TF_README_PATH) $(PRIVATE_DIR)/tools
 	$(hide) touch $@
 
 # Generate the test descriptions for the core-tests
@@ -341,8 +345,7 @@
 # Generate the default test plan for User.
 # Usage: buildCts.py <testRoot> <ctsOutputDir> <tempDir> <androidRootDir> <docletPath>
 
-$(DEFAULT_TEST_PLAN): $(cts_dir)/all_cts_files_stamp $(cts_tools_src_dir)/utils/buildCts.py $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(CTS_CORE_XMLS) $(CTS_TEST_XMLS) $(CORE_VM_TEST_TF_DESC) | $(ACP)
-	$(hide) $(ACP) -fp $(CTS_CORE_XMLS) $(CTS_TEST_XMLS) $(CORE_VM_TEST_TF_DESC) $(PRIVATE_DIR)/repository/testcases
+$(DEFAULT_TEST_PLAN): $(cts_dir)/all_cts_files_stamp $(cts_tools_src_dir)/utils/buildCts.py $(HOST_OUT_JAVA_LIBRARIES)/descGen.jar $(CTS_CORE_XMLS) $(CTS_TEST_XMLS) $(CORE_VM_TEST_TF_DESC)
 	$(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 $@
@@ -364,16 +367,3 @@
 cts: $(INTERNAL_CTS_TARGET) adb
 $(call dist-for-goals,cts,$(INTERNAL_CTS_TARGET))
 
-
-define copy-testcase
-
-$(hide) $(ACP) -fp $(1) $(PRIVATE_DIR)/repository/testcases/$(notdir $1)
-
-endef
-
-define copy-testcase-jar
-
-$(hide) $(ACP) -fp $(call intermediates-dir-for,JAVA_LIBRARIES,$(1))/javalib.jar \
-	$(PRIVATE_DIR)/repository/testcases/$(1).jar
-
-endef
diff --git a/core/tasks/tools/build_custom_image.mk b/core/tasks/tools/build_custom_image.mk
new file mode 100644
index 0000000..e59ed42
--- /dev/null
+++ b/core/tasks/tools/build_custom_image.mk
@@ -0,0 +1,115 @@
+#
+# Copyright (C) 2015 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.
+#
+
+
+# Define rule to build one custom image.
+# Input variables: my_custom_imag_makefile
+
+$(call clear-var-list, $(custom_image_parameter_variables))
+
+include $(my_custom_imag_makefile)
+
+my_custom_image_name := $(basename $(notdir $(my_custom_imag_makefile)))
+
+intermediates := $(call intermediates-dir-for,PACKAGING,$(my_custom_image_name))
+my_built_custom_image := $(intermediates)/$(my_custom_image_name).img
+my_staging_dir := $(intermediates)/$(CUSTOM_IMAGE_MOUNT_POINT)
+
+# Collect CUSTOM_IMAGE_MODULES's installd files and their PICKUP_FILES.
+my_built_modules :=
+my_copy_pairs :=
+my_pickup_files :=
+
+$(foreach m,$(CUSTOM_IMAGE_MODULES),\
+  $(eval _pickup_files := $(strip $(ALL_MODULES.$(m).PICKUP_FILES)\
+    $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).PICKUP_FILES)))\
+  $(eval _built_files := $(strip $(ALL_MODULES.$(m).BUILT_INSTALLED)\
+    $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).BUILT_INSTALLED)))\
+  $(if $(_pickup_files)$(_built_files),,\
+    $(warning Unknown installed file for module '$(m)'))\
+  $(eval my_pickup_files += $(_pickup_files))\
+  $(foreach i, $(_built_files),\
+    $(eval bui_ins := $(subst :,$(space),$(i)))\
+    $(eval ins := $(word 2,$(bui_ins)))\
+    $(if $(filter $(TARGET_OUT_ROOT)/%,$(ins)),\
+      $(eval bui := $(word 1,$(bui_ins)))\
+      $(eval my_built_modules += $(bui))\
+      $(eval my_copy_dest := $(patsubst $(PRODUCT_OUT)/%,%,$(ins)))\
+      $(eval my_copy_dest := $(subst /,$(space),$(my_copy_dest)))\
+      $(eval my_copy_dest := $(wordlist 2,999,$(my_copy_dest)))\
+      $(eval my_copy_dest := $(subst $(space),/,$(my_copy_dest)))\
+      $(eval my_copy_pairs += $(bui):$(my_staging_dir)/$(my_copy_dest)))\
+  ))
+
+# Collect CUSTOM_IMAGE_COPY_FILES.
+my_image_copy_files :=
+$(foreach f,$(CUSTOM_IMAGE_COPY_FILES),\
+  $(eval pair := $(subst :,$(space),$(f)))\
+  $(eval src := $(word 1,$(pair)))\
+  $(eval my_image_copy_files += $(src))\
+  $(eval my_copy_pairs += $(src):$(my_staging_dir)/$(word 2,$(pair))))
+
+$(my_built_custom_image): PRIVATE_INTERMEDIATES := $(intermediates)
+$(my_built_custom_image): PRIVATE_MOUNT_POINT := $(CUSTOM_IMAGE_MOUNT_POINT)
+$(my_built_custom_image): PRIVATE_PARTITION_SIZE := $(CUSTOM_IMAGE_PARTITION_SIZE)
+$(my_built_custom_image): PRIVATE_FILE_SYSTEM_TYPE := $(CUSTOM_IMAGE_FILE_SYSTEM_TYPE)
+$(my_built_custom_image): PRIVATE_STAGING_DIR := $(my_staging_dir)
+$(my_built_custom_image): PRIVATE_COPY_PAIRS := $(my_copy_pairs)
+$(my_built_custom_image): PRIVATE_PICKUP_FILES := $(my_pickup_files)
+$(my_built_custom_image): PRIVATE_SELINUX := $(CUSTOM_IMAGE_SELINUX)
+$(my_built_custom_image): PRIVATE_SUPPORT_VERITY := $(CUSTOM_IMAGE_SUPPORT_VERITY)
+$(my_built_custom_image): PRIVATE_VERITY_KEY := $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY)
+$(my_built_custom_image): PRIVATE_VERITY_BLOCK_DEVICE := $(CUSTOM_IMAGE_VERITY_BLOCK_DEVICE)
+$(my_built_custom_image): PRIVATE_DICT_FILE := $(CUSTOM_IMAGE_DICT_FILE)
+$(my_built_custom_image): $(INTERNAL_USERIMAGES_DEPS) $(my_built_modules) $(my_image_copy_files) \
+  $(CUSTOM_IMAGE_DICT_FILE)
+	@echo "Build image $@"
+	$(hide) rm -rf $(PRIVATE_INTERMEDIATES) && mkdir -p $(PRIVATE_INTERMEDIATES)
+	$(hide) rm -rf $(PRIVATE_STAGING_DIR) && mkdir -p $(PRIVATE_STAGING_DIR)
+	# Copy all the files.
+	$(hide) $(foreach p,$(PRIVATE_COPY_PAIRS),\
+	          $(eval pair := $(subst :,$(space),$(p)))\
+	          mkdir -p $(dir $(word 2,$(pair)));\
+	          cp -Rf $(word 1,$(pair)) $(word 2,$(pair));)
+	$(if $($(PRIVATE_PICKUP_FILES)),$(hide) cp -Rf $(PRIVATE_PICKUP_FILES) $(PRIVATE_STAGING_DIR))
+	# Generate the dict.
+	$(hide) echo "# For all accepted properties, see BuildImage() in tools/releasetools/build_image.py" > $(PRIVATE_INTERMEDIATES)/image_info.txt
+	$(hide) echo "mount_point=$(PRIVATE_MOUNT_POINT)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt
+	$(hide) echo "fs_type=$(PRIVATE_FILE_SYSTEM_TYPE)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt
+	$(hide) echo "partition_size=$(PRIVATE_PARTITION_SIZE)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt
+	$(if $(PRIVATE_SELINUX),$(hide) echo "selinux_fc=$(SELINUX_FC)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt)
+	$(if $(PRIVATE_SUPPORT_VERITY),\
+	  $(hide) echo "verity=$(PRIVATE_SUPPORT_VERITY)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt;\
+	    echo "verity_key=$(PRIVATE_VERITY_KEY)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt;\
+	    echo "verity_signer_cmd=$(VERITY_SIGNER)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt;\
+	    echo "verity_block_device=$(PRIVATE_VERITY_BLOCK_DEVICE)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt)
+	$(if $(PRIVATE_DICT_FILE),\
+	  $(hide) echo "# Properties from $(PRIVATE_DICT_FILE)" >> $(PRIVATE_INTERMEDIATES)/image_info.txt;\
+	    cat $(PRIVATE_DICT_FILE) >> $(PRIVATE_INTERMEDIATES)/image_info.txt)
+	# Generate the image.
+	$(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \
+	  ./build/tools/releasetools/build_image.py \
+	  $(PRIVATE_STAGING_DIR) $(PRIVATE_INTERMEDIATES)/image_info.txt $@
+
+my_installed_custom_image := $(PRODUCT_OUT)/$(notdir $(my_built_custom_image))
+$(my_installed_custom_image) : $(my_built_custom_image)
+	$(call copy-file-to-new-target-with-cp)
+
+.PHONY: $(my_custom_image_name)
+custom_images $(my_custom_image_name) : $(my_installed_custom_image)
+
+# Archive the built image.
+$(call dist-for-goals, $(my_custom_image_name) custom_images,$(my_installed_custom_image))
diff --git a/envsetup.sh b/envsetup.sh
index 766ddb4..d91b0b3 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -761,7 +761,7 @@
                 MAKEFILE="$MAKEFILE $MFILE"
             else
                 case $DIR in
-                  showcommands | snod | dist | incrementaljavac) ARGS="$ARGS $DIR";;
+                  showcommands | snod | dist | incrementaljavac | *=*) ARGS="$ARGS $DIR";;
                   GET-INSTALL-PATH) GET_INSTALL_PATH=$DIR;;
                   *) echo "No Android.mk in $DIR."; return 1;;
                 esac
@@ -817,7 +817,7 @@
         fi
       else
         case $DIR in
-          showcommands | snod | dist | incrementaljavac) ARGS="$ARGS $DIR";;
+          showcommands | snod | dist | incrementaljavac | *=*) ARGS="$ARGS $DIR";;
           *) echo "Couldn't find directory $DIR"; return 1;;
         esac
       fi
@@ -1035,18 +1035,6 @@
     fi
 }
 
-function gdbwrapper()
-{
-    local GDB_CMD="$1"
-    shift 1
-    $GDB_CMD -x "$@"
-}
-
-function get_symbols_directory()
-{
-    echo $(get_abs_build_var TARGET_OUT_UNSTRIPPED)
-}
-
 # Read the ELF header from /proc/$PID/exe to determine if the process is
 # 64-bit.
 function is64bit()
@@ -1063,291 +1051,6 @@
     fi
 }
 
-function adb_get_product_device() {
-  local candidate=`adb shell getprop ro.product.device | sed s/.$//`
-  if [ -z $candidate ]; then
-    candidate=`adb shell getprop ro.hardware | sed s/.$//`
-  fi
-  echo $candidate
-}
-
-# returns 0 when process is not traced
-function adb_get_traced_by() {
-  echo `adb shell cat /proc/$1/status | grep -e "^TracerPid:" | sed "s/^TracerPid:\t//" | sed s/.$//`
-}
-
-function gdbclient() {
-  # TODO:
-  # 1. Check for ANDROID_SERIAL/multiple devices
-  local PROCESS_NAME="n/a"
-  local PID=$1
-  local PORT=5039
-  if [ -z "$PID" ]; then
-    echo "Usage: gdbclient <pid|processname> [port number]"
-    return -1
-  fi
-  local DEVICE=$(adb_get_product_device)
-
-  if [ -z "$DEVICE" ]; then
-    echo "Error: Unable to get device name. Please check if device is connected and ANDROID_SERIAL is set."
-    return -2
-  fi
-
-  if [ -n "$2" ]; then
-    PORT=$2
-  fi
-
-  local ROOT=$(gettop)
-  if [ -z "$ROOT" ]; then
-    # This is for the situation with downloaded symbols (from the build server)
-    # we check if they are available.
-    ROOT=`realpath .`
-  fi
-
-  local OUT_ROOT="$ROOT/out/target/product/$DEVICE"
-  local SYMBOLS_DIR="$OUT_ROOT/symbols"
-  local IS_TAPAS_USER="$(get_build_var TARGET_BUILD_APPS)"
-  local TAPAS_SYMBOLS_DIR=
-
-  if [ $IS_TAPAS_USER ]; then
-    TAPAS_SYMBOLS_DIR=$(get_symbols_directory)
-  fi
-
-  if [ ! -d $SYMBOLS_DIR ]; then
-    if [ $IS_TAPAS_USER ]; then
-      mkdir -p $SYMBOLS_DIR/system/bin
-    else
-      echo "Error: couldn't find symbols: $SYMBOLS_DIR does not exist or is not a directory."
-      return -3
-    fi
-  fi
-
-  # let's figure out which executable we are about to debug
-
-  # check if user specified a name -> resolve to pid
-  if [[ ! "$PID" =~ ^[0-9]+$ ]] ; then
-    PROCESS_NAME=$PID
-    PID=$(pid --exact $PROCESS_NAME)
-    if [ -z "$PID" ]; then
-      echo "Error: couldn't resolve pid by process name: $PROCESS_NAME"
-      return -4
-    else
-      echo "Resolved pid for $PROCESS_NAME is $PID"
-    fi
-  fi
-
-  local EXE=`adb shell readlink /proc/$PID/exe | sed s/.$//`
-
-  if [ -z "$EXE" ]; then
-    echo "Error: no such pid=$PID - is process still alive?"
-    return -4
-  fi
-
-  local LOCAL_EXE_PATH=$SYMBOLS_DIR$EXE
-
-  if [ ! -f $LOCAL_EXE_PATH ]; then
-    if [ $IS_TAPAS_USER ]; then
-      adb pull $EXE $LOCAL_EXE_PATH
-    else
-      echo "Error: unable to find symbols for executable $EXE: file $LOCAL_EXE_PATH does not exist"
-      return -5
-    fi
-  fi
-
-  local USE64BIT=""
-
-  if [[ "$(file $LOCAL_EXE_PATH)" =~ 64-bit ]]; then
-    USE64BIT="64"
-  fi
-
-  # and now linker for tapas users...
-  if [ -n "$IS_TAPAS_USER" -a ! -f "$SYMBOLS_DIR/system/bin/linker$USE64BIT" ]; then
-    adb pull /system/bin/linker$USE64BIT $SYMBOLS_DIR/system/bin/linker$USE64BIT
-  fi
-
-  local GDB=
-  local GDB64=
-  local CPU_ABI=`adb shell getprop ro.product.cpu.abilist | sed s/.$//`
-  # TODO: we assume these are available via $PATH
-  if [[ $CPU_ABI =~ (^|,)arm64 ]]; then
-    GDB=arm-linux-androideabi-gdb
-    GDB64=aarch64-linux-android-gdb
-  elif [[ $CPU_ABI =~ (^|,)arm ]]; then
-    GDB=arm-linux-androideabi-gdb
-  elif [[ $CPU_ABI =~ (^|,)x86_64 ]]; then
-    GDB=x86_64-linux-android-gdb
-  elif [[ $CPU_ABI =~ (^|,)x86 ]]; then
-    GDB=x86_64-linux-android-gdb
-  elif [[ $CPU_ABI =~ (^|,)mips64 ]]; then
-    GDB=mipsel-linux-android-gdb
-    GDB64=mips64el-linux-android-gdb
-  elif [[ $CPU_ABI =~ (^|,)mips ]]; then
-    GDB=mipsel-linux-android-gdb
-  else
-    echo "Error: unrecognized cpu.abilist: $CPU_ABI"
-    return -6
-  fi
-
-  # TODO: check if tracing process is gdbserver and not some random strace...
-  if [ "$(adb_get_traced_by $PID)" -eq 0 ]; then
-    # start gdbserver
-    echo "Starting gdbserver..."
-    # TODO: check if adb is already listening $PORT
-    # to avoid unnecessary calls
-    echo ". adb forward for port=$PORT..."
-    adb forward tcp:$PORT tcp:$PORT
-    echo ". starting gdbserver to attach to pid=$PID..."
-    adb shell gdbserver$USE64BIT :$PORT --attach $PID &
-    echo ". give it couple of seconds to start..."
-    sleep 2
-    echo ". done"
-  else
-    echo "It looks like gdbserver is already attached to $PID (process is traced), trying to connect to it using local port=$PORT"
-    adb forward tcp:$PORT tcp:$PORT
-  fi
-
-  local OUT_SO_SYMBOLS=$SYMBOLS_DIR/system/lib$USE64BIT
-  local TAPAS_OUT_SO_SYMBOLS=$TAPAS_SYMBOLS_DIR/system/lib$USE64BIT
-  local OUT_VENDOR_SO_SYMBOLS=$SYMBOLS_DIR/vendor/lib$USE64BIT
-  local ART_CMD=""
-
-  local SOLIB_SYSROOT=$SYMBOLS_DIR
-  local SOLIB_SEARCHPATH=$OUT_SO_SYMBOLS:$OUT_SO_SYMBOLS/hw:$OUT_SO_SYMBOLS/ssl/engines:$OUT_SO_SYMBOLS/drm:$OUT_SO_SYMBOLS/egl:$OUT_SO_SYMBOLS/soundfx:$OUT_VENDOR_SO_SYMBOLS:$OUT_VENDOR_SO_SYMBOLS/hw:$OUT_VENDOR_SO_SYMBOLS/egl
-
-  if [ $IS_TAPAS_USER ]; then
-    SOLIB_SYSROOT=$TAPAS_SYMBOLS_DIR:$SOLIB_SYSROOT
-    SOLIB_SEARCHPATH=$TAPAS_OUT_SO_SYMBOLS:$SOLIB_SEARCHPATH
-  fi
-
-  echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $SOLIB_SYSROOT"
-  echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $SOLIB_SEARCHPATH"
-  local DALVIK_GDB_SCRIPT=$ROOT/development/scripts/gdb/dalvik.gdb
-  if [ -f $DALVIK_GDB_SCRIPT ]; then
-    echo >>"$OUT_ROOT/gdbclient.cmds" "source $DALVIK_GDB_SCRIPT"
-    ART_CMD="art-on"
-  else
-    echo "Warning: couldn't find $DALVIK_GDB_SCRIPT - ART debugging options will not be available"
-  fi
-  echo >>"$OUT_ROOT/gdbclient.cmds" "target remote :$PORT"
-  if [[ $EXE =~ (^|/)(app_process|dalvikvm)(|32|64)$ ]]; then
-    echo >> "$OUT_ROOT/gdbclient.cmds" $ART_CMD
-  fi
-
-  echo >>"$OUT_ROOT/gdbclient.cmds" ""
-
-  local WHICH_GDB=$GDB
-
-  if [ -n "$USE64BIT" -a -n "$GDB64" ]; then
-    WHICH_GDB=$GDB64
-  fi
-
-  gdbwrapper $WHICH_GDB "$OUT_ROOT/gdbclient.cmds" "$LOCAL_EXE_PATH"
-}
-
-# gdbclient now determines whether the user wants to debug a 32-bit or 64-bit
-# executable, set up the approriate gdbserver, then invokes the proper host
-# gdb.
-function gdbclient_old()
-{
-   local OUT_ROOT=$(get_abs_build_var PRODUCT_OUT)
-   local OUT_SYMBOLS=$(get_abs_build_var TARGET_OUT_UNSTRIPPED)
-   local OUT_SO_SYMBOLS=$(get_abs_build_var TARGET_OUT_SHARED_LIBRARIES_UNSTRIPPED)
-   local OUT_VENDOR_SO_SYMBOLS=$(get_abs_build_var TARGET_OUT_VENDOR_SHARED_LIBRARIES_UNSTRIPPED)
-   local OUT_EXE_SYMBOLS=$(get_symbols_directory)
-   local PREBUILTS=$(get_abs_build_var ANDROID_PREBUILTS)
-   local ARCH=$(get_build_var TARGET_ARCH)
-   local GDB
-   case "$ARCH" in
-       arm) GDB=arm-linux-androideabi-gdb;;
-       arm64) GDB=arm-linux-androideabi-gdb; GDB64=aarch64-linux-android-gdb;;
-       mips|mips64) GDB=mips64el-linux-android-gdb;;
-       x86) GDB=x86_64-linux-android-gdb;;
-       x86_64) GDB=x86_64-linux-android-gdb;;
-       *) echo "Unknown arch $ARCH"; return 1;;
-   esac
-
-   if [ "$OUT_ROOT" -a "$PREBUILTS" ]; then
-       local EXE="$1"
-       if [ "$EXE" ] ; then
-           EXE=$1
-           if [[ $EXE =~ ^[^/].* ]] ; then
-               EXE="system/bin/"$EXE
-           fi
-       else
-           EXE="app_process"
-       fi
-
-       local PORT="$2"
-       if [ "$PORT" ] ; then
-           PORT=$2
-       else
-           PORT=":5039"
-       fi
-
-       local PID="$3"
-       if [ "$PID" ] ; then
-           if [[ ! "$PID" =~ ^[0-9]+$ ]] ; then
-               PID=`pid $3`
-               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}'`
-                   if [[ ! "$PID" =~ ^[0-9]+$ ]]
-                   then
-                       echo "Couldn't resolve '$3' to single PID"
-                       return 1
-                   else
-                       echo ""
-                       echo "WARNING: multiple processes matching '$3' observed, using root process"
-                       echo ""
-                   fi
-               fi
-           fi
-           adb forward "tcp$PORT" "tcp$PORT"
-           local USE64BIT="$(is64bit $PID)"
-           adb shell gdbserver$USE64BIT $PORT --attach $PID &
-           sleep 2
-       else
-               echo ""
-               echo "If you haven't done so already, do this first on the device:"
-               echo "    gdbserver $PORT /system/bin/$EXE"
-                   echo " or"
-               echo "    gdbserver $PORT --attach <PID>"
-               echo ""
-       fi
-
-       OUT_SO_SYMBOLS=$OUT_SO_SYMBOLS$USE64BIT
-       OUT_VENDOR_SO_SYMBOLS=$OUT_VENDOR_SO_SYMBOLS$USE64BIT
-
-       echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $OUT_SYMBOLS"
-       echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $OUT_SO_SYMBOLS:$OUT_SO_SYMBOLS/hw:$OUT_SO_SYMBOLS/ssl/engines:$OUT_SO_SYMBOLS/drm:$OUT_SO_SYMBOLS/egl:$OUT_SO_SYMBOLS/soundfx:$OUT_VENDOR_SO_SYMBOLS:$OUT_VENDOR_SO_SYMBOLS/hw:$OUT_VENDOR_SO_SYMBOLS/egl"
-       echo >>"$OUT_ROOT/gdbclient.cmds" "source $ANDROID_BUILD_TOP/development/scripts/gdb/dalvik.gdb"
-       echo >>"$OUT_ROOT/gdbclient.cmds" "target remote $PORT"
-       # Enable special debugging for ART processes.
-       if [[ $EXE =~ (^|/)(app_process|dalvikvm)(|32|64)$ ]]; then
-          echo >> "$OUT_ROOT/gdbclient.cmds" "art-on"
-       fi
-       echo >>"$OUT_ROOT/gdbclient.cmds" ""
-
-       local WHICH_GDB=
-       # 64-bit exe found
-       if [ "$USE64BIT" != "" ] ; then
-           WHICH_GDB=$ANDROID_TOOLCHAIN/$GDB64
-       # 32-bit exe / 32-bit platform
-       elif [ "$(get_build_var TARGET_2ND_ARCH)" = "" ]; then
-           WHICH_GDB=$ANDROID_TOOLCHAIN/$GDB
-       # 32-bit exe / 64-bit platform
-       else
-           WHICH_GDB=$ANDROID_TOOLCHAIN_2ND_ARCH/$GDB
-       fi
-
-       gdbwrapper $WHICH_GDB "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
-  else
-       echo "Unable to determine build system output dir."
-   fi
-
-}
-
 case `uname -s` in
     Darwin)
         function sgrep()
@@ -1399,6 +1102,11 @@
     find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -name sepolicy -type d -print0 | xargs -0 grep --color -n -r --exclude-dir=\.git "$@"
 }
 
+function rcgrep()
+{
+    find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.rc*" -print0 | xargs -0 grep --color -n "$@"
+}
+
 case `uname -s` in
     Darwin)
         function mgrep()
@@ -1739,19 +1447,21 @@
     local hours=$(($tdiff / 3600 ))
     local mins=$((($tdiff % 3600) / 60))
     local secs=$(($tdiff % 60))
+    local ncolors=$(tput colors 2>/dev/null)
+    if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then
+        color_failed="\e[0;31m"
+        color_success="\e[0;32m"
+        color_reset="\e[00m"
+    else
+        color_failed=""
+        color_success=""
+        color_reset=""
+    fi
     echo
     if [ $ret -eq 0 ] ; then
-        if [ $(uname) != "Darwin" ]; then
-            echo -n -e "\e[0;32m#### make completed successfully "
-        else
-            echo -n -e "#### make completed successfully "
-        fi
+        echo -n -e "${color_success}#### make completed successfully "
     else
-        if [ $(uname) != "Darwin" ]; then
-            echo -n -e "\e[0;31m#### make failed to build some targets "
-        else
-            echo -n -e "#### make failed to build some targets "
-        fi
+        echo -n -e "${color_failed}#### make failed to build some targets "
     fi
     if [ $hours -gt 0 ] ; then
         printf "(%02g:%02g:%02g (hh:mm:ss))" $hours $mins $secs
@@ -1760,9 +1470,7 @@
     elif [ $secs -gt 0 ] ; then
         printf "(%s seconds)" $secs
     fi
-    if [ $(uname) != "Darwin" ]; then
-        echo -e " ####\e[00m"
-    fi
+    echo -e " ####${color_reset}"
     echo
     return $ret
 }
diff --git a/target/board/generic/sepolicy/goldfish_logcat.te b/target/board/generic/sepolicy/goldfish_logcat.te
index 34ef280..a785355 100644
--- a/target/board/generic/sepolicy/goldfish_logcat.te
+++ b/target/board/generic/sepolicy/goldfish_logcat.te
@@ -1,6 +1,5 @@
 # goldfish-logcat service:  runs logcat -Q
 type goldfish_logcat, domain;
-permissive_or_unconfined(goldfish_logcat)
 
 domain_auto_trans(init, logcat_exec, goldfish_logcat)
 
diff --git a/target/board/generic/sepolicy/goldfish_setup.te b/target/board/generic/sepolicy/goldfish_setup.te
index 786c1c2..584731e 100644
--- a/target/board/generic/sepolicy/goldfish_setup.te
+++ b/target/board/generic/sepolicy/goldfish_setup.te
@@ -1,7 +1,6 @@
 # goldfish-setup service: runs init.goldfish.sh script
 type goldfish_setup, domain;
 type goldfish_setup_exec, exec_type, file_type;
-permissive_or_unconfined(goldfish_setup)
 
 init_daemon_domain(goldfish_setup)
 
diff --git a/target/board/generic/sepolicy/qemu_props.te b/target/board/generic/sepolicy/qemu_props.te
index ade111d..05c7461 100644
--- a/target/board/generic/sepolicy/qemu_props.te
+++ b/target/board/generic/sepolicy/qemu_props.te
@@ -1,7 +1,6 @@
 # qemu-props service:  Sets system properties on boot.
 type qemu_props, domain;
 type qemu_props_exec, exec_type, file_type;
-permissive_or_unconfined(qemu_props)
 
 init_daemon_domain(qemu_props)
 
diff --git a/target/board/generic/sepolicy/qemud.te b/target/board/generic/sepolicy/qemud.te
index b6a35d3..41f2065 100644
--- a/target/board/generic/sepolicy/qemud.te
+++ b/target/board/generic/sepolicy/qemud.te
@@ -3,7 +3,6 @@
 type qemud_exec, exec_type, file_type;
 
 init_daemon_domain(qemud)
-permissive_or_unconfined(qemud)
 
 # Access /dev/ttyS1.
 allow qemud serial_device:chr_file rw_file_perms;
diff --git a/target/board/generic_arm64/BoardConfig.mk b/target/board/generic_arm64/BoardConfig.mk
index 8afd5a8..c98624d 100644
--- a/target/board/generic_arm64/BoardConfig.mk
+++ b/target/board/generic_arm64/BoardConfig.mk
@@ -76,7 +76,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 943718400
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 1073741824
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
diff --git a/target/board/generic_armv5/BoardConfig.mk b/target/board/generic_armv5/BoardConfig.mk
index 95fb559..016937a 100644
--- a/target/board/generic_armv5/BoardConfig.mk
+++ b/target/board/generic_armv5/BoardConfig.mk
@@ -19,6 +19,5 @@
 TARGET_ARCH_VARIANT := armv5te
 TARGET_CPU_ABI := armeabi
 TARGET_CPU_ABI2 :=
-ARCH_ARM_HAVE_TLS_REGISTER := false
 
 WITH_DEXPREOPT := false
diff --git a/target/board/generic_mips/BoardConfig.mk b/target/board/generic_mips/BoardConfig.mk
index 736ad7f..b40f9ba 100644
--- a/target/board/generic_mips/BoardConfig.mk
+++ b/target/board/generic_mips/BoardConfig.mk
@@ -53,7 +53,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 1073741824
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
diff --git a/target/board/generic_mips64/BoardConfig.mk b/target/board/generic_mips64/BoardConfig.mk
index caebacc..2097635 100644
--- a/target/board/generic_mips64/BoardConfig.mk
+++ b/target/board/generic_mips64/BoardConfig.mk
@@ -65,8 +65,8 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 786432000
-BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 1101004800
+BOARD_USERDATAIMAGE_PARTITION_SIZE := 734003200
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
 BOARD_FLASH_BLOCK_SIZE := 512
diff --git a/target/board/generic_x86_64/BoardConfig.mk b/target/board/generic_x86_64/BoardConfig.mk
index c4fd958..192bbb2 100755
--- a/target/board/generic_x86_64/BoardConfig.mk
+++ b/target/board/generic_x86_64/BoardConfig.mk
@@ -41,7 +41,7 @@
 USE_OPENGL_RENDERER := true
 
 TARGET_USERIMAGES_USE_EXT4 := true
-BOARD_SYSTEMIMAGE_PARTITION_SIZE := 943718400 # 900MB
+BOARD_SYSTEMIMAGE_PARTITION_SIZE := 1073741824 # 1GB
 BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800
 BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
 BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
diff --git a/target/product/base.mk b/target/product/base.mk
index 3f0e7da..2d72961 100644
--- a/target/product/base.mk
+++ b/target/product/base.mk
@@ -38,7 +38,6 @@
     fsck_msdos \
     ime \
     input \
-    inputflinger \
     javax.obex \
     libandroid \
     libandroid_runtime \
@@ -67,6 +66,9 @@
     libnetlink \
     libnetutils \
     libpdfium \
+    libradio \
+    libradioservice \
+    libradio_metadata \
     libreference-ril \
     libreverbwrapper \
     libril \
@@ -97,7 +99,6 @@
     monkey \
     mtpd \
     ndc \
-    netcfg \
     netd \
     ping \
     ping6 \
@@ -110,6 +111,7 @@
     sdcard \
     services \
     settings \
+    sgdisk \
     svc \
     tc \
     vdc \
diff --git a/target/product/core_tiny.mk b/target/product/core_tiny.mk
index f66db8c..3547641 100644
--- a/target/product/core_tiny.mk
+++ b/target/product/core_tiny.mk
@@ -112,6 +112,7 @@
 $(call inherit-product, $(SRC_TARGET_DIR)/product/runtime_libart.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/base.mk)
 $(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk)
+$(call inherit-product-if-exists, external/roboto-fonts/fonts.mk)
 
 # Overrides
 PRODUCT_BRAND := tiny
diff --git a/target/product/embedded.mk b/target/product/embedded.mk
index 56a5f97..96c0b77 100644
--- a/target/product/embedded.mk
+++ b/target/product/embedded.mk
@@ -63,6 +63,7 @@
     logwrapper \
     mkshrc \
     reboot \
+    recovery \
     service \
     servicemanager \
     sh \
diff --git a/target/product/emulator.mk b/target/product/emulator.mk
index 3a8a4aa..d9ff62e 100644
--- a/target/product/emulator.mk
+++ b/target/product/emulator.mk
@@ -40,11 +40,13 @@
     camera.goldfish.jpeg \
     lights.goldfish \
     gps.goldfish \
+    fingerprint.goldfish \
     sensors.goldfish \
     e2fsck \
     audio.primary.goldfish \
     vibrator.goldfish \
     power.goldfish \
+    fingerprint.ranchu \
     sensors.ranchu
 
 
diff --git a/target/product/full_base_telephony.mk b/target/product/full_base_telephony.mk
index 2fd2ce8..9a2c63a 100644
--- a/target/product/full_base_telephony.mk
+++ b/target/product/full_base_telephony.mk
@@ -19,9 +19,6 @@
 # build quite specifically for the emulator, and might not be
 # entirely appropriate to inherit from for on-device configurations.
 
-PRODUCT_PACKAGES := \
-    VoiceDialer
-
 PRODUCT_PROPERTY_OVERRIDES := \
     keyguard.no_require_sim=true \
     ro.com.android.dataroaming=true
diff --git a/target/product/generic_no_telephony.mk b/target/product/generic_no_telephony.mk
index dd18fab..91d856d 100644
--- a/target/product/generic_no_telephony.mk
+++ b/target/product/generic_no_telephony.mk
@@ -63,6 +63,7 @@
 $(call inherit-product-if-exists, external/lohit-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/noto-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/naver-fonts/fonts.mk)
+$(call inherit-product-if-exists, external/roboto-fonts/fonts.mk)
 $(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
 $(call inherit-product-if-exists, frameworks/webview/chromium/chromium.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)
diff --git a/target/product/sdk_base.mk b/target/product/sdk_base.mk
index 451c0b7..0fa6e08 100644
--- a/target/product/sdk_base.mk
+++ b/target/product/sdk_base.mk
@@ -83,6 +83,7 @@
 $(call inherit-product-if-exists, external/google-fonts/cutive-mono/fonts.mk)
 $(call inherit-product-if-exists, external/noto-fonts/fonts.mk)
 $(call inherit-product-if-exists, external/naver-fonts/fonts.mk)
+$(call inherit-product-if-exists, external/roboto-fonts/fonts.mk)
 $(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk)
 $(call inherit-product-if-exists, frameworks/webview/chromium/chromium.mk)
 $(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk)
diff --git a/target/product/telephony.mk b/target/product/telephony.mk
index da1497d..6852084 100644
--- a/target/product/telephony.mk
+++ b/target/product/telephony.mk
@@ -19,6 +19,7 @@
 
 PRODUCT_PACKAGES := \
     Dialer \
+    CallLogBackup \
     Mms \
     rild
 
diff --git a/target/product/vboot.mk b/target/product/vboot.mk
new file mode 100644
index 0000000..e4b1144
--- /dev/null
+++ b/target/product/vboot.mk
@@ -0,0 +1,24 @@
+#
+# Copyright (C) 2015 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 dependencies necessary for verified boot
+
+PRODUCT_SUPPORTS_VBOOT := true
+
+# The dev key is used to sign boot and recovery images.
+# We expect this file to exist with the suffixes ".vbprivk" and ".vbpupk".
+# TODO: find a proper location for this
+PRODUCT_VBOOT_SIGNING_KEY := external/vboot_reference/tests/devkeys/kernel_data_key
diff --git a/tools/droiddoc/templates-sdk/docpage.cs b/tools/droiddoc/templates-sdk/docpage.cs
index d064222..09d48c8 100644
--- a/tools/droiddoc/templates-sdk/docpage.cs
+++ b/tools/droiddoc/templates-sdk/docpage.cs
@@ -195,8 +195,8 @@
 <?cs include:"trailer.cs" ?>
   <script src="https://developer.android.com/ytblogger_lists_unified.js" type="text/javascript"></script>
   <script src="<?cs var:toroot ?>jd_lists_unified.js?v=8" type="text/javascript"></script>
-  <script src="<?cs var:toroot ?>jd_extras.js?v=9" type="text/javascript"></script>
-  <script src="<?cs var:toroot ?>jd_collections.js?v=9" type="text/javascript"></script>
+  <script src="<?cs var:toroot ?>jd_extras.js?v=10" type="text/javascript"></script>
+  <script src="<?cs var:toroot ?>jd_collections.js?v=10" type="text/javascript"></script>
   <script src="<?cs var:toroot ?>jd_tag_helpers.js?v=5" type="text/javascript"></script>
 
 </body>
diff --git a/tools/releasetools/add_img_to_target_files.py b/tools/releasetools/add_img_to_target_files.py
index 8bbe452..b3d2ede 100755
--- a/tools/releasetools/add_img_to_target_files.py
+++ b/tools/releasetools/add_img_to_target_files.py
@@ -135,11 +135,20 @@
   fc_config = os.path.join(input_dir, "BOOT/RAMDISK/file_contexts")
   if not os.path.exists(fc_config): fc_config = None
 
+  # Override values loaded from info_dict.
+  if fs_config:
+    image_props["fs_config"] = fs_config
+  if fc_config:
+    image_props["selinux_fc"] = fc_config
+  if block_list:
+    image_props["block_list"] = block_list
+  if image_props.get("system_root_image") == "true":
+    image_props["ramdisk_dir"] = os.path.join(input_dir, "BOOT/RAMDISK")
+    image_props["ramdisk_fs_config"] = os.path.join(
+        input_dir, "META/boot_filesystem_config.txt")
+
   succ = build_image.BuildImage(os.path.join(input_dir, what),
-                                image_props, img,
-                                fs_config=fs_config,
-                                fc_config=fc_config,
-                                block_list=block_list)
+                                image_props, img)
   assert succ, "build " + what + ".img image failed"
 
   return img
diff --git a/tools/releasetools/blockimgdiff.py b/tools/releasetools/blockimgdiff.py
index 0646c5f..5b5c4cc 100644
--- a/tools/releasetools/blockimgdiff.py
+++ b/tools/releasetools/blockimgdiff.py
@@ -140,8 +140,11 @@
     self.style = style
     self.intact = (getattr(tgt_ranges, "monotonic", False) and
                    getattr(src_ranges, "monotonic", False))
-    self.goes_before = {}
-    self.goes_after = {}
+
+    # We use OrderedDict rather than dict so that the output is repeatable;
+    # otherwise it would depend on the hash values of the Transfer objects.
+    self.goes_before = OrderedDict()
+    self.goes_after = OrderedDict()
 
     self.stash_before = []
     self.use_stash = []
@@ -294,6 +297,8 @@
       if stashed_blocks > max_stashed_blocks:
         max_stashed_blocks = stashed_blocks
 
+      free_string = []
+
       if self.version == 1:
         src_string = xf.src_ranges.to_string_raw()
       elif self.version >= 2:
@@ -306,7 +311,6 @@
 
         size = xf.src_ranges.size()
         src_string = [str(size)]
-        free_string = []
 
         unstashed_src_ranges = xf.src_ranges
         mapped_stashes = []
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
index 1692f96..97353df 100755
--- a/tools/releasetools/build_image.py
+++ b/tools/releasetools/build_image.py
@@ -198,25 +198,39 @@
   shutil.rmtree(tempdir_name, ignore_errors=True)
   return True
 
-def BuildImage(in_dir, prop_dict, out_file,
-               fs_config=None,
-               fc_config=None,
-               block_list=None):
+def BuildImage(in_dir, prop_dict, out_file):
   """Build an image to out_file from in_dir with property prop_dict.
 
   Args:
     in_dir: path of input directory.
     prop_dict: property dictionary.
     out_file: path of the output image file.
-    fs_config: path to the fs_config file (typically
-      META/filesystem_config.txt).  If None then the configuration in
-      the local client will be used.
-    fc_config: path to the SELinux file_contexts file.  If None then
-      the value from prop_dict['selinux_fc'] will be used.
 
   Returns:
     True iff the image is built successfully.
   """
+  # system_root_image=true: build a system.img that combines the contents of /system
+  # and the ramdisk, and can be mounted at the root of the file system.
+  origin_in = in_dir
+  fs_config = prop_dict.get("fs_config")
+  if (prop_dict.get("system_root_image") == "true"
+      and prop_dict["mount_point"] == "system"):
+    in_dir = tempfile.mkdtemp()
+    # Change the mount point to "/"
+    prop_dict["mount_point"] = "/"
+    if fs_config:
+      # We need to merge the fs_config files of system and ramdisk.
+      fd, merged_fs_config = tempfile.mkstemp(prefix="root_fs_config",
+                                              suffix=".txt")
+      os.close(fd)
+      with open(merged_fs_config, "w") as fw:
+        if "ramdisk_fs_config" in prop_dict:
+          with open(prop_dict["ramdisk_fs_config"]) as fr:
+            fw.writelines(fr.readlines())
+        with open(fs_config) as fr:
+          fw.writelines(fr.readlines())
+      fs_config = merged_fs_config
+
   build_command = []
   fs_type = prop_dict.get("fs_type", "")
   run_fsck = False
@@ -244,15 +258,19 @@
       build_command.extend(["-j", prop_dict["journal_size"]])
     if "timestamp" in prop_dict:
       build_command.extend(["-T", str(prop_dict["timestamp"])])
-    if fs_config is not None:
+    if fs_config:
       build_command.extend(["-C", fs_config])
-    if block_list is not None:
-      build_command.extend(["-B", block_list])
+    if "block_list" in prop_dict:
+      build_command.extend(["-B", prop_dict["block_list"]])
     build_command.extend(["-L", prop_dict["mount_point"]])
-    if fc_config is not None:
-      build_command.append(fc_config)
-    elif "selinux_fc" in prop_dict:
+    if "selinux_fc" in prop_dict:
       build_command.append(prop_dict["selinux_fc"])
+  elif fs_type.startswith("squash"):
+    build_command = ["mksquashfsimage.sh"]
+    build_command.extend([in_dir, out_file])
+    build_command.extend(["-m", prop_dict["mount_point"]])
+    if "selinux_fc" in prop_dict:
+      build_command.extend(["-c", prop_dict["selinux_fc"]])
   elif fs_type.startswith("f2fs"):
     build_command = ["mkf2fsuserimg.sh"]
     build_command.extend([out_file, prop_dict["partition_size"]])
@@ -266,7 +284,23 @@
       build_command.append(prop_dict["selinux_fc"])
       build_command.append(prop_dict["mount_point"])
 
-  exit_code = RunCommand(build_command)
+  if in_dir != origin_in:
+    # Construct a staging directory of the root file system.
+    ramdisk_dir = prop_dict.get("ramdisk_dir")
+    if ramdisk_dir:
+      shutil.rmtree(in_dir)
+      shutil.copytree(ramdisk_dir, in_dir, symlinks=True)
+    staging_system = os.path.join(in_dir, "system")
+    shutil.rmtree(staging_system, ignore_errors=True)
+    shutil.copytree(origin_in, staging_system, symlinks=True)
+  try:
+    exit_code = RunCommand(build_command)
+  finally:
+    if in_dir != origin_in:
+      # Clean up temporary directories and files.
+      shutil.rmtree(in_dir, ignore_errors=True)
+      if fs_config:
+        os.remove(fs_config)
   if exit_code != 0:
     return False
 
@@ -321,9 +355,13 @@
   d["mount_point"] = mount_point
   if mount_point == "system":
     copy_prop("fs_type", "fs_type")
+    # Copy the generic sysetem fs type first, override with specific one if available.
+    copy_prop("system_fs_type", "fs_type")
     copy_prop("system_size", "partition_size")
     copy_prop("system_journal_size", "journal_size")
     copy_prop("system_verity_block_device", "verity_block_device")
+    copy_prop("system_root_image","system_root_image")
+    copy_prop("ramdisk_dir","ramdisk_dir")
   elif mount_point == "data":
     # Copy the generic fs type first, override with specific one if available.
     copy_prop("fs_type", "fs_type")
@@ -369,23 +407,28 @@
   out_file = argv[2]
 
   glob_dict = LoadGlobalDict(glob_dict_file)
-  image_filename = os.path.basename(out_file)
-  mount_point = ""
-  if image_filename == "system.img":
-    mount_point = "system"
-  elif image_filename == "userdata.img":
-    mount_point = "data"
-  elif image_filename == "cache.img":
-    mount_point = "cache"
-  elif image_filename == "vendor.img":
-    mount_point = "vendor"
-  elif image_filename == "oem.img":
-    mount_point = "oem"
+  if "mount_point" in glob_dict:
+    # The caller knows the mount point and provides a dictionay needed by BuildImage().
+    image_properties = glob_dict
   else:
-    print >> sys.stderr, "error: unknown image file name ", image_filename
-    exit(1)
+    image_filename = os.path.basename(out_file)
+    mount_point = ""
+    if image_filename == "system.img":
+      mount_point = "system"
+    elif image_filename == "userdata.img":
+      mount_point = "data"
+    elif image_filename == "cache.img":
+      mount_point = "cache"
+    elif image_filename == "vendor.img":
+      mount_point = "vendor"
+    elif image_filename == "oem.img":
+      mount_point = "oem"
+    else:
+      print >> sys.stderr, "error: unknown image file name ", image_filename
+      exit(1)
 
-  image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
+    image_properties = ImagePropFromGlobalDict(glob_dict, mount_point)
+
   if not BuildImage(in_dir, image_properties, out_file):
     print >> sys.stderr, "error: failed to build %s from %s" % (out_file, in_dir)
     exit(1)
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index d411cc9..0c0da77 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -801,8 +801,10 @@
   saved_zip64_limit = zipfile.ZIP64_LIMIT
   zipfile.ZIP64_LIMIT = (1 << 32) - 1
 
-  compress_type = compress_type or zip_file.compression
-  arcname = arcname or filename
+  if compress_type is None:
+    compress_type = zip_file.compression
+  if arcname is None:
+    arcname = filename
 
   saved_stat = os.stat(filename)
 
@@ -1066,20 +1068,22 @@
 
 
 class BlockDifference:
-  def __init__(self, partition, tgt, src=None, check_first_block=False):
+  def __init__(self, partition, tgt, src=None, check_first_block=False, version=None):
     self.tgt = tgt
     self.src = src
     self.partition = partition
     self.check_first_block = check_first_block
 
-    version = 1
-    if OPTIONS.info_dict:
-      version = max(
-          int(i) for i in
-          OPTIONS.info_dict.get("blockimgdiff_versions", "1").split(","))
+    if version is None:
+      version = 1
+      if OPTIONS.info_dict:
+        version = max(
+            int(i) for i in
+            OPTIONS.info_dict.get("blockimgdiff_versions", "1").split(","))
+    self.version = version
 
     b = blockimgdiff.BlockImageDiff(tgt, src, threads=OPTIONS.worker_threads,
-                                    version=version)
+                                    version=self.version)
     tmpdir = tempfile.mkdtemp()
     OPTIONS.tempfiles.append(tmpdir)
     self.path = os.path.join(tmpdir, partition)
@@ -1102,21 +1106,34 @@
     if not self.src:
       script.Print("Image %s will be patched unconditionally." % (partition,))
     else:
-      script.AppendExtra(('if block_image_verify("%s", '
-                          'package_extract_file("%s.transfer.list"), '
-                          '"%s.new.dat", "%s.patch.dat") then') %
-                         (self.device, partition, partition, partition))
-      script.Print("Verified %s image..." % (partition,))
+      if self.version >= 3:
+        script.AppendExtra(('if block_image_verify("%s", '
+                            'package_extract_file("%s.transfer.list"), '
+                            '"%s.new.dat", "%s.patch.dat") then') %
+                           (self.device, partition, partition, partition))
+      else:
+        script.AppendExtra('if range_sha1("%s", "%s") == "%s" then' %
+                            (self.device, self.src.care_map.to_string_raw(),
+                            self.src.TotalSha1()))
+      script.Print('Verified %s image...' % (partition,))
       script.AppendExtra('else');
 
+      # When generating incrementals for the system and vendor partitions,
+      # explicitly check the first block (which contains the superblock) of
+      # the partition to see if it's what we expect. If this check fails,
+      # give an explicit log message about the partition having been
+      # remounted R/W (the most likely explanation) and the need to flash to
+      # get OTAs working again.
       if self.check_first_block:
         self._CheckFirstBlock(script)
 
-      script.AppendExtra(('(range_sha1("%s", "%s") == "%s") ||\n'
-                          '  abort("%s partition has unexpected contents");\n'
-                          'endif;') %
-                         (self.device, self.tgt.care_map.to_string_raw(),
-                          self.tgt.TotalSha1(), self.partition))
+      # Abort the OTA update. Note that the incremental OTA cannot be applied
+      # even if it may match the checksum of the target partition.
+      # a) If version < 3, operations like move and erase will make changes
+      #    unconditionally and damage the partition.
+      # b) If version >= 3, it won't even reach here.
+      script.AppendExtra(('abort("%s partition has unexpected contents");\n'
+                          'endif;') % (partition,))
 
   def _WriteUpdate(self, script, output_zip):
     ZipWrite(output_zip,
@@ -1148,14 +1165,11 @@
   def _CheckFirstBlock(self, script):
     r = RangeSet((0, 1))
     srchash = self._HashBlocks(self.src, r);
-    tgthash = self._HashBlocks(self.tgt, r);
 
     script.AppendExtra(('(range_sha1("%s", "%s") == "%s") || '
-                        '(range_sha1("%s", "%s") == "%s") || '
                         'abort("%s has been remounted R/W; '
                         'reflash device to reenable OTA updates");')
                        % (self.device, r.to_string_raw(), srchash,
-                          self.device, r.to_string_raw(), tgthash,
                           self.device))
 
 DataImage = blockimgdiff.DataImage
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index e52c264..934d751 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -74,11 +74,11 @@
       raise ValueError("must specify an OEM property")
     if not value:
       raise ValueError("must specify the OEM value")
-    cmd = ('file_getprop("/oem/oem.prop", "%s") == "%s" || '
-           'abort("This package expects the value \\"%s\\"  for '
-           '\\"%s\\" on the OEM partition; '
-           'this has value \\"" + file_getprop("/oem/oem.prop") + "\\".");'
-           ) % (name, value, name, value)
+    cmd = ('file_getprop("/oem/oem.prop", "{name}") == "{value}" || '
+           'abort("This package expects the value \\"{value}\\" for '
+           '\\"{name}\\" on the OEM partition; this has value \\"" + '
+           'file_getprop("/oem/oem.prop", "{name}") + "\\".");'
+           ).format(name=name, value=value)
     self.script.append(cmd)
 
   def AssertSomeFingerprint(self, *fp):
diff --git a/tools/releasetools/img_from_target_files.py b/tools/releasetools/img_from_target_files.py
index a9d4cbe..4dda0b7 100755
--- a/tools/releasetools/img_from_target_files.py
+++ b/tools/releasetools/img_from_target_files.py
@@ -141,7 +141,13 @@
 
   finally:
     print "cleaning up..."
+    # http://b/18015246
+    # See common.py for context.  zipfile also refers to ZIP64_LIMIT during
+    # close() when it writes out the central directory.
+    saved_zip64_limit = zipfile.ZIP64_LIMIT
+    zipfile.ZIP64_LIMIT = (1 << 32) - 1
     output_zip.close()
+    zipfile.ZIP64_LIMIT = saved_zip64_limit
     shutil.rmtree(OPTIONS.input_tmp)
 
   print "done."
diff --git a/tools/releasetools/ota_from_target_files b/tools/releasetools/ota_from_target_files
index 6517bf3..b71baf9 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -349,8 +349,9 @@
   partition = itemset.partition
 
   for info in input_zip.infolist():
-    if info.filename.startswith(partition.upper() + "/"):
-      basefilename = info.filename[7:]
+    prefix = partition.upper() + "/"
+    if info.filename.startswith(prefix):
+      basefilename = info.filename[len(prefix):]
       if IsSymlink(info):
         symlinks.append((input_zip.read(info.filename),
                          "/" + partition + "/" + basefilename))
@@ -663,7 +664,7 @@
   prefix = partition.upper() + "/"
   for info in z.infolist():
     if info.filename.startswith(prefix) and not IsSymlink(info):
-      basefilename = info.filename[7:]
+      basefilename = info.filename[len(prefix):]
       fn = partition + "/" + basefilename
       data = z.read(info.filename)
       out[fn] = common.File(fn, data)
@@ -738,8 +739,16 @@
 
   system_src = GetImage("system", OPTIONS.source_tmp, OPTIONS.source_info_dict)
   system_tgt = GetImage("system", OPTIONS.target_tmp, OPTIONS.target_info_dict)
+
+  blockimgdiff_version = 1
+  if OPTIONS.info_dict:
+    blockimgdiff_version = max(
+        int(i) for i in
+        OPTIONS.info_dict.get("blockimgdiff_versions", "1").split(","))
+
   system_diff = common.BlockDifference("system", system_tgt, system_src,
-                                       check_first_block=True)
+                                       check_first_block=True,
+                                       version=blockimgdiff_version)
 
   if HasVendorPartition(target_zip):
     if not HasVendorPartition(source_zip):
@@ -747,7 +756,8 @@
     vendor_src = GetImage("vendor", OPTIONS.source_tmp, OPTIONS.source_info_dict)
     vendor_tgt = GetImage("vendor", OPTIONS.target_tmp, OPTIONS.target_info_dict)
     vendor_diff = common.BlockDifference("vendor", vendor_tgt, vendor_src,
-                                         check_first_block=True)
+                                         check_first_block=True,
+                                         version=blockimgdiff_version)
   else:
     vendor_diff = None
 
@@ -808,11 +818,22 @@
   device_specific.IncrementalOTA_VerifyBegin()
 
   if oem_props is None:
-    script.AssertSomeFingerprint(source_fp, target_fp)
+    # When blockimgdiff version is less than 3 (non-resumable block-based OTA),
+    # patching on a device that's already on the target build will damage the
+    # system. Because operations like move don't check the block state, they
+    # always apply the changes unconditionally.
+    if blockimgdiff_version <= 2:
+      script.AssertSomeFingerprint(source_fp)
+    else:
+      script.AssertSomeFingerprint(source_fp, target_fp)
   else:
-    script.AssertSomeThumbprint(
-        GetBuildProp("ro.build.thumbprint", OPTIONS.target_info_dict),
-        GetBuildProp("ro.build.thumbprint", OPTIONS.source_info_dict))
+    if blockimgdiff_version <= 2:
+      script.AssertSomeThumbprint(
+          GetBuildProp("ro.build.thumbprint", OPTIONS.source_info_dict))
+    else:
+      script.AssertSomeThumbprint(
+          GetBuildProp("ro.build.thumbprint", OPTIONS.target_info_dict),
+          GetBuildProp("ro.build.thumbprint", OPTIONS.source_info_dict))
 
   if updating_boot:
     boot_type, boot_device = common.GetTypeAndDevice("/boot", OPTIONS.info_dict)
diff --git a/tools/releasetools/test_common.py b/tools/releasetools/test_common.py
index f163f92..5fdc132 100644
--- a/tools/releasetools/test_common.py
+++ b/tools/releasetools/test_common.py
@@ -62,6 +62,7 @@
       new_stat = os.stat(test_file_name)
       self.assertEqual(int(old_stat.st_mode), int(new_stat.st_mode))
       self.assertEqual(int(old_stat.st_mtime), int(new_stat.st_mtime))
+      self.assertIsNone(zip_file.testzip())
 
       zip_file.close()
       zip_file = zipfile.ZipFile(zip_file_name, "r")
@@ -71,6 +72,7 @@
       mode = (info.external_attr >> 16) & 0o777
       self.assertEqual(mode, expected_mode)
       self.assertEqual(zip_file.read(arcname), contents)
+      self.assertIsNone(zip_file.testzip())
     finally:
       os.remove(test_file_name)
       os.remove(zip_file_name)
diff --git a/tools/signapk/SignApk.java b/tools/signapk/SignApk.java
index d020736..88f486a 100644
--- a/tools/signapk/SignApk.java
+++ b/tools/signapk/SignApk.java
@@ -35,6 +35,7 @@
 import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
 import org.bouncycastle.util.encoders.Base64;
 
+import java.io.Console;
 import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -166,18 +167,17 @@
     }
 
     /**
-     * Reads the password from stdin and returns it as a string.
+     * Reads the password from console and returns it as a string.
      *
      * @param keyFile The file containing the private key.  Used to prompt the user.
      */
     private static String readPassword(File keyFile) {
-        // TODO: use Console.readPassword() when it's available.
-        System.out.print("Enter password for " + keyFile + " (password will not be hidden): ");
-        System.out.flush();
-        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
-        try {
-            return stdin.readLine();
-        } catch (IOException ex) {
+        Console console;
+        char[] pwd;
+        if((console = System.console()) != null &&
+           (pwd = console.readPassword("[%s]", "Enter password for " + keyFile)) != null){
+            return String.valueOf(pwd);
+        } else {
             return null;
         }
     }
diff --git a/tools/zipalign/README.txt b/tools/zipalign/README.txt
index 9c7d07e..0b80b35 100644
--- a/tools/zipalign/README.txt
+++ b/tools/zipalign/README.txt
@@ -5,6 +5,7 @@
 
   -c : check alignment only (does not modify file)
   -f : overwrite existing outfile.zip
+  -p : page align stored shared object files
   -v : verbose output
   <align> is in bytes, e.g. "4" provides 32-bit alignment
   infile.zip is an existing Zip archive
@@ -33,3 +34,7 @@
 
 You can use the "-c" flag to test whether a zip archive is properly aligned.
 
+The "-p" flag aligns any file with a ".so" extension, and which is stored
+uncompressed in the zip archive, to a 4096-byte page boundary.  This
+facilitates directly loading shared libraries from inside a zip archive.
+
diff --git a/tools/zipalign/ZipAlign.cpp b/tools/zipalign/ZipAlign.cpp
index dc2826b..a2dfd02 100644
--- a/tools/zipalign/ZipAlign.cpp
+++ b/tools/zipalign/ZipAlign.cpp
@@ -32,20 +32,39 @@
     fprintf(stderr, "Zip alignment utility\n");
     fprintf(stderr, "Copyright (C) 2009 The Android Open Source Project\n\n");
     fprintf(stderr,
-        "Usage: zipalign [-f] [-v] [-z] <align> infile.zip outfile.zip\n"
+        "Usage: zipalign [-f] [-p] [-v] [-z] <align> infile.zip outfile.zip\n"
         "       zipalign -c [-v] <align> infile.zip\n\n" );
     fprintf(stderr,
         "  <align>: alignment in bytes, e.g. '4' provides 32-bit alignment\n");
     fprintf(stderr, "  -c: check alignment only (does not modify file)\n");
     fprintf(stderr, "  -f: overwrite existing outfile.zip\n");
+    fprintf(stderr, "  -p: page align stored shared object files\n");
     fprintf(stderr, "  -v: verbose output\n");
     fprintf(stderr, "  -z: recompress using Zopfli\n");
 }
 
+static int getAlignment(bool pageAlignSharedLibs, int defaultAlignment,
+    ZipEntry* pEntry) {
+
+    static const int kPageAlignment = 4096;
+
+    if (!pageAlignSharedLibs) {
+        return defaultAlignment;
+    }
+
+    const char* ext = strrchr(pEntry->getFileName(), '.');
+    if (ext && strcmp(ext, ".so") == 0) {
+        return kPageAlignment;
+    }
+
+    return defaultAlignment;
+}
+
 /*
  * Copy all entries from "pZin" to "pZout", aligning as needed.
  */
-static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment, bool zopfli)
+static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment, bool zopfli,
+    bool pageAlignSharedLibs)
 {
     int numEntries = pZin->getNumEntries();
     ZipEntry* pEntry;
@@ -75,13 +94,15 @@
                 status = pZout->add(pZin, pEntry, padding, &pNewEntry);
             }
         } else {
+            const int alignTo = getAlignment(pageAlignSharedLibs, alignment, pEntry);
+
             /*
              * Copy the entry, adjusting as required.  We assume that the
              * file position in the new file will be equal to the file
              * position in the original.
              */
             long newOffset = pEntry->getFileOffset() + bias;
-            padding = (alignment - (newOffset % alignment)) % alignment;
+            padding = (alignTo - (newOffset % alignTo)) % alignTo;
 
             //printf("--- %s: orig at %ld(+%d) len=%ld, adding pad=%d\n",
             //    pEntry->getFileName(), (long) pEntry->getFileOffset(),
@@ -105,7 +126,7 @@
  * output file exists and "force" wasn't specified.
  */
 static int process(const char* inFileName, const char* outFileName,
-    int alignment, bool force, bool zopfli)
+    int alignment, bool force, bool zopfli, bool pageAlignSharedLibs)
 {
     ZipFile zin, zout;
 
@@ -136,7 +157,7 @@
         return 1;
     }
 
-    int result = copyAndAlign(&zin, &zout, alignment, zopfli);
+    int result = copyAndAlign(&zin, &zout, alignment, zopfli, pageAlignSharedLibs);
     if (result != 0) {
         printf("zipalign: failed rewriting '%s' to '%s'\n",
             inFileName, outFileName);
@@ -147,7 +168,8 @@
 /*
  * Verify the alignment of a zip archive.
  */
-static int verify(const char* fileName, int alignment, bool verbose)
+static int verify(const char* fileName, int alignment, bool verbose,
+    bool pageAlignSharedLibs)
 {
     ZipFile zipFile;
     bool foundBad = false;
@@ -172,11 +194,12 @@
             }
         } else {
             long offset = pEntry->getFileOffset();
-            if ((offset % alignment) != 0) {
+            const int alignTo = getAlignment(pageAlignSharedLibs, alignment, pEntry);
+            if ((offset % alignTo) != 0) {
                 if (verbose) {
                     printf("%8ld %s (BAD - %ld)\n",
                         (long) offset, pEntry->getFileName(),
-                        offset % alignment);
+                        offset % alignTo);
                 }
                 foundBad = true;
             } else {
@@ -204,6 +227,7 @@
     bool force = false;
     bool verbose = false;
     bool zopfli = false;
+    bool pageAlignSharedLibs = false;
     int result = 1;
     int alignment;
     char* endp;
@@ -233,6 +257,9 @@
             case 'z':
                 zopfli = true;
                 break;
+            case 'p':
+                pageAlignSharedLibs = true;
+                break;
             default:
                 fprintf(stderr, "ERROR: unknown flag -%c\n", *cp);
                 wantUsage = true;
@@ -260,14 +287,15 @@
 
     if (check) {
         /* check existing archive for correct alignment */
-        result = verify(argv[1], alignment, verbose);
+        result = verify(argv[1], alignment, verbose, pageAlignSharedLibs);
     } else {
         /* create the new archive */
-        result = process(argv[1], argv[2], alignment, force, zopfli);
+        result = process(argv[1], argv[2], alignment, force, zopfli, pageAlignSharedLibs);
 
         /* trust, but verify */
-        if (result == 0)
-            result = verify(argv[2], alignment, verbose);
+        if (result == 0) {
+            result = verify(argv[2], alignment, verbose, pageAlignSharedLibs);
+        }
     }
 
 bail: