Merge "Set -Xdoclint:none"
diff --git a/core/Makefile b/core/Makefile
index c930708..18e01f9 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -122,7 +122,7 @@
   ifneq ($(filter eng.%,$(BUILD_NUMBER)),)
     # Trim down BUILD_FINGERPRINT: the default BUILD_NUMBER makes it easily exceed
     # the Android system property length limit (PROPERTY_VALUE_MAX=92).
-    BF_BUILD_NUMBER := $(USER)$(shell $(DATE) +%m%d%H%M)
+    BF_BUILD_NUMBER := $(shell echo $${USER:0:6})$(shell $(DATE) +%m%d%H%M)
   else
     BF_BUILD_NUMBER := $(BUILD_NUMBER)
   endif
@@ -728,6 +728,9 @@
 endif
 endif
 
+ifneq (true,$(TARGET_USERIMAGES_SPARSE_SQUASHFS_DISABLED))
+  INTERNAL_USERIMAGES_SPARSE_SQUASHFS_FLAG := -s
+endif
 ifeq ($(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE),squashfs)
 INTERNAL_USERIMAGES_DEPS += $(MAKE_SQUASHFS) $(MKSQUASHFSUSERIMG) $(IMG2SIMG)
 endif
@@ -764,6 +767,7 @@
 $(if $(BOARD_OEMIMAGE_PARTITION_SIZE),$(hide) echo "oem_size=$(BOARD_OEMIMAGE_PARTITION_SIZE)" >> $(1))
 $(if $(BOARD_OEMIMAGE_JOURNAL_SIZE),$(hide) echo "oem_journal_size=$(BOARD_OEMIMAGE_JOURNAL_SIZE)" >> $(1))
 $(if $(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG),$(hide) echo "extfs_sparse_flag=$(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG)" >> $(1))
+$(if $(INTERNAL_USERIMAGES_SPARSE_SQUASHFS_FLAG),$(hide) echo "squashfs_sparse_flag=$(INTERNAL_USERIMAGES_SPARSE_SQUASHFS_FLAG)" >> $(1))
 $(hide) echo "selinux_fc=$(SELINUX_FC)" >> $(1)
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_BOOT_SIGNER),$(hide) echo "boot_signer=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_BOOT_SIGNER)" >> $(1))
 $(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY)" >> $(1))
@@ -1393,13 +1397,14 @@
   $(HOST_LIBRARY_PATH)/libcrypto-host$(HOST_SHLIB_SUFFIX) \
   $(HOST_LIBRARY_PATH)/libdivsufsort$(HOST_SHLIB_SUFFIX) \
   $(HOST_LIBRARY_PATH)/libdivsufsort64$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext2fs_host$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext2_blkid_host$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext2_com_err_host$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext2_e2p_host$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext2_profile_host$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext2_quota_host$(HOST_SHLIB_SUFFIX) \
-  $(HOST_LIBRARY_PATH)/libext2_uuid_host$(HOST_SHLIB_SUFFIX)
+  $(HOST_LIBRARY_PATH)/libext2fs-host$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libext2_blkid-host$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libext2_com_err-host$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libext2_e2p-host$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libext2_profile-host$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libext2_quota-host$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libext2_uuid-host$(HOST_SHLIB_SUFFIX) \
+  $(HOST_LIBRARY_PATH)/libconscrypt_openjdk_jni$(HOST_SHLIB_SUFFIX)
 
 .PHONY: otatools
 otatools: $(OTATOOLS)
@@ -1452,14 +1457,11 @@
   fi
 endef
 
-built_ota_tools := \
-    $(call intermediates-dir-for,EXECUTABLES,applypatch,,,$(TARGET_PREFER_32_BIT))/applypatch \
-    $(call intermediates-dir-for,EXECUTABLES,sqlite3,,,$(TARGET_PREFER_32_BIT))/sqlite3
+built_ota_tools :=
 
 # We can't build static executables when SANITIZE_TARGET=address
 ifeq ($(strip $(SANITIZE_TARGET)),)
 built_ota_tools += \
-    $(call intermediates-dir-for,EXECUTABLES,applypatch_static,,,$(TARGET_PREFER_32_BIT))/applypatch_static \
     $(call intermediates-dir-for,EXECUTABLES,updater,,,$(TARGET_PREFER_32_BIT))/updater
 endif
 
@@ -1564,9 +1566,11 @@
 	$(hide) mkdir -p $(zip_root)/OTA
 	$(hide) $(ACP) $(INSTALLED_ANDROID_INFO_TXT_TARGET) $(zip_root)/OTA/
 ifneq ($(AB_OTA_UPDATER),true)
+ifneq ($(built_ota_tools),)
 	$(hide) mkdir -p $(zip_root)/OTA/bin
 	$(hide) $(ACP) $(PRIVATE_OTA_TOOLS) $(zip_root)/OTA/bin/
 endif
+endif
 	@# Files that do not end up in any images, but are necessary to
 	@# build them.
 	$(hide) mkdir -p $(zip_root)/META
diff --git a/core/base_rules.mk b/core/base_rules.mk
index 5ee5edf..7e33660 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -227,6 +227,9 @@
 # dependent binaries of a .toc file will be rebuilt only when the content of
 # the .toc file is changed.
 ###########################################################
+ifndef LOCAL_IS_HOST_MODULE
+# Disable .toc optimization for host modules: we may run the host binaries during the build process
+# and the libraries' implementation matters.
 ifeq ($(LOCAL_MODULE_CLASS),SHARED_LIBRARIES)
 LOCAL_INTERMEDIATE_TARGETS += $(LOCAL_BUILT_MODULE).toc
 $(LOCAL_BUILT_MODULE).toc: $(LOCAL_BUILT_MODULE)
@@ -236,6 +239,7 @@
 # Kati adds restat=1 to ninja. GNU make does nothing for this.
 .KATI_RESTAT: $(LOCAL_BUILT_MODULE).toc
 endif
+endif
 
 ###########################################################
 ## logtags: Add .logtags files to global list
diff --git a/core/binary.mk b/core/binary.mk
index 028950a..4cb62b3 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -75,7 +75,15 @@
   my_ndk_source_root := $(HISTORICAL_NDK_VERSIONS_ROOT)/current/sources
   my_ndk_sysroot := $(HISTORICAL_NDK_VERSIONS_ROOT)/current/platforms/android-$(LOCAL_SDK_VERSION)/arch-$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
   my_ndk_sysroot_include := $(my_ndk_sysroot)/usr/include
-  ifeq (x86_64,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+
+  # x86_64 and and mips64 are both multilib toolchains, so their libraries are
+  # installed in /usr/lib64. Aarch64, on the other hand, is not a multilib
+  # compiler, so its libraries are in /usr/lib.
+  #
+  # Mips32r6 is yet another variation, with libraries installed in libr6.
+  #
+  # For the rest, the libraries are installed simply to /usr/lib.
+  ifneq (,$(filter x86_64 mips64,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)))
     my_ndk_sysroot_lib := $(my_ndk_sysroot)/usr/lib64
   else ifeq (mips32r6,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH_VARIANT))
     my_ndk_sysroot_lib := $(my_ndk_sysroot)/usr/libr6
@@ -85,11 +93,16 @@
 
   # The bionic linker now has support for packed relocations and gnu style
   # hashes (which are much faster!), but shipping to older devices requires
-  # the old style hash and disabling packed relocations.
-  #ifeq ($(shell expr $(LOCAL_SDK_VERSION) >= FIRST_SUPPORTED_VERSION),0)
-    my_ldflags += -Wl,--hash-style=sysv
-    LOCAL_PACK_MODULE_RELOCATIONS := false
-  #endif
+  # the old style hash. Fortunately, we can build with both and it'll work
+  # anywhere.
+  #
+  # This is not currently supported on MIPS architectures.
+  ifeq (,$(filter mips mips64,$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)))
+    my_ldflags += -Wl,--hash-style=both
+  endif
+
+  # We don't want to expose the relocation packer to the NDK just yet.
+  LOCAL_PACK_MODULE_RELOCATIONS := false
 
   # Set up the NDK stl variant. Starting from NDK-r5 the c++ stl resides in a separate location.
   # See ndk/docs/CPLUSPLUS-SUPPORT.html
@@ -106,15 +119,16 @@
   ifeq (,$(LOCAL_NDK_STL_VARIANT))
     LOCAL_NDK_STL_VARIANT := system
   endif
-  ifneq (1,$(words $(filter system stlport_static stlport_shared c++_static c++_shared gnustl_static, $(LOCAL_NDK_STL_VARIANT))))
+  ifneq (1,$(words $(filter none system stlport_static stlport_shared c++_static c++_shared gnustl_static, $(LOCAL_NDK_STL_VARIANT))))
     $(error $(LOCAL_PATH): Unknown LOCAL_NDK_STL_VARIANT $(LOCAL_NDK_STL_VARIANT))
   endif
   ifeq (system,$(LOCAL_NDK_STL_VARIANT))
     my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/system/include
-    # for "system" variant, the shared library exists in the system library and -lstdc++ is added by default.
+    my_system_shared_libraries += libstdc++
   else # LOCAL_NDK_STL_VARIANT is not system
   ifneq (,$(filter stlport_%, $(LOCAL_NDK_STL_VARIANT)))
     my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/stlport/stlport
+    my_system_shared_libraries += libstdc++
     ifeq (stlport_static,$(LOCAL_NDK_STL_VARIANT))
       my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/stlport/libs/$(my_cpu_variant)/libstlport_static.a
     else
@@ -133,11 +147,14 @@
       my_ndk_stl_shared_lib := -lc++_shared
     endif
     my_ndk_stl_cppflags := -std=c++11
-  else
-    # LOCAL_NDK_STL_VARIANT is gnustl_static
+  else # LOCAL_NDK_STL_VARIANT is not c++_* either
+  ifneq (,$(filter gnustl_%, $(LOCAL_NDK_STL_VARIANT)))
     my_ndk_stl_include_path := $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/libs/$(my_cpu_variant)/include \
                                $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/include
     my_ndk_stl_static_lib := $(my_ndk_source_root)/cxx-stl/gnu-libstdc++/$($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_NDK_GCC_VERSION)/libs/$(my_cpu_variant)/libgnustl_static.a
+  else # LOCAL_NDK_STL_VARIANT must be none
+    # Do nothing.
+  endif
   endif
   endif
   endif
@@ -177,6 +194,11 @@
 my_c_includes += $(LOCAL_C_INCLUDES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_C_INCLUDES_$(my_32_64_bit_suffix))
 my_generated_sources += $(LOCAL_GENERATED_SOURCES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_GENERATED_SOURCES_$(my_32_64_bit_suffix))
 
+my_missing_exclude_files := $(filter-out $(my_src_files),$(my_src_files_exclude))
+ifneq ($(my_missing_exclude_files),)
+$(warning Files are listed in LOCAL_SRC_FILES_EXCLUDE but not LOCAL_SRC_FILES)
+$(error $(my_missing_exclude_files))
+endif
 my_src_files := $(filter-out $(my_src_files_exclude),$(my_src_files))
 
 my_clang := $(strip $(LOCAL_CLANG))
@@ -1134,7 +1156,11 @@
 # that custom build rules which generate .o files don't consume other generated
 # sources as input (or if they do they take care of that dependency themselves).
 $(normal_objects) : | $(my_generated_sources)
+ifeq ($(BUILDING_WITH_NINJA),true)
+$(all_objects) : $(import_includes)
+else
 $(all_objects) : | $(import_includes)
+endif
 ALL_C_CPP_ETC_OBJECTS += $(all_objects)
 
 
@@ -1176,7 +1202,7 @@
     $(addprefix $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)OUT_INTERMEDIATE_LIBRARIES)/, \
       $(addsuffix $(so_suffix), \
         $(my_shared_libraries)))
-built_shared_library_tocs := $(addsuffix .toc, $(built_shared_libraries))
+built_shared_library_deps := $(addsuffix .toc, $(built_shared_libraries))
 
 # Add the NDK libraries to the built module dependency
 my_system_shared_libraries_fullpath := \
@@ -1190,7 +1216,13 @@
     $(addprefix $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)OUT_INTERMEDIATE_LIBRARIES)/, \
       $(addsuffix $(so_suffix), \
         $(installed_shared_library_module_names)))
-built_shared_library_tocs := $(addsuffix .toc, $(built_shared_libraries))
+ifdef LOCAL_IS_HOST_MODULE
+# Disable .toc optimization for host modules: we may run the host binaries during the build process
+# and the libraries' implementation matters.
+built_shared_library_deps := $(built_shared_libraries)
+else
+built_shared_library_deps := $(addsuffix .toc, $(built_shared_libraries))
+endif
 my_system_shared_libraries_fullpath :=
 endif
 
@@ -1286,7 +1318,7 @@
 ###########################################################
 # all_libraries is used for the dependencies on LOCAL_BUILT_MODULE.
 all_libraries := \
-    $(built_shared_library_tocs) \
+    $(built_shared_library_deps) \
     $(my_system_shared_libraries_fullpath) \
     $(built_static_libraries) \
     $(built_whole_libraries)
@@ -1307,14 +1339,26 @@
 # generated after the headers, so this is a convenient way to ensure the headers exist.
 $(export_includes) : $(LOCAL_MODULE_MAKEFILE_DEP) $(proto_generated_headers) $(dbus_generated_headers) $(aidl_gen_cpp)
 	@echo Export includes file: $< -- $@
-	$(hide) mkdir -p $(dir $@) && rm -f $@
+	$(hide) mkdir -p $(dir $@) && rm -f $@.tmp
 ifdef my_export_c_include_dirs
 	$(hide) for d in $(PRIVATE_EXPORT_C_INCLUDE_DIRS); do \
-	        echo "-I $$d" >> $@; \
+	        echo "-I $$d" >> $@.tmp; \
 	        done
 else
-	$(hide) touch $@
+	$(hide) touch $@.tmp
 endif
+ifeq ($(BUILDING_WITH_NINJA),true)
+	$(hide) if cmp -s $@.tmp $@ ; then \
+	  rm $@.tmp ; \
+	else \
+	  mv $@.tmp $@ ; \
+	fi
+else
+	mv $@.tmp $@ ;
+endif
+
+# Kati adds restat=1 to ninja. GNU make does nothing for this.
+.KATI_RESTAT: $(export_includes)
 
 # Make sure export_includes gets generated when you are running mm/mmm
 $(LOCAL_BUILT_MODULE) : | $(export_includes)
diff --git a/core/clang/HOST_x86_common.mk b/core/clang/HOST_x86_common.mk
index fc98dd5..8b94209 100644
--- a/core/clang/HOST_x86_common.mk
+++ b/core/clang/HOST_x86_common.mk
@@ -6,6 +6,8 @@
 
 CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CFLAGS := \
   -integrated-as
+
+CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CFLAGS += -fstack-protector-strong
 endif
 
 ifeq ($(HOST_OS),linux)
@@ -16,6 +18,8 @@
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CFLAGS := \
   --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)
 
+CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CFLAGS += -fstack-protector-strong
+
 ifneq ($(strip $($(clang_2nd_arch_prefix)HOST_IS_64_BIT)),)
 CLANG_CONFIG_x86_LINUX_HOST_EXTRA_CPPFLAGS := \
   --gcc-toolchain=$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG) \
diff --git a/core/cleanbuild.mk b/core/cleanbuild.mk
index 7885644..06ceecb 100644
--- a/core/cleanbuild.mk
+++ b/core/cleanbuild.mk
@@ -301,48 +301,6 @@
 force_objclean :=
 
 ###########################################################
-# Clean build tools when swithcing between prebuilt host tools (such as in
-# apps_only build) and tools built from source (platform build).
-previous_prebuilt_tools_config_file := $(HOST_OUT)/previous_prebuilt_tools_config.mk
-ifneq (,$(TARGET_BUILD_APPS)$(filter true,$(TARGET_BUILD_PDK)))
-current_prebuilt_tools := true
-else
-current_prebuilt_tools := false
-endif
-PREVIOUS_PREBUILT_TOOLS :=
--include $(previous_prebuilt_tools_config_file)
-force_tools_clean :=
-ifdef PREVIOUS_PREBUILT_TOOLS
-ifneq ($(PREVIOUS_PREBUILT_TOOLS),$(current_prebuilt_tools))
-force_tools_clean := true
-endif
-endif # else, this is the first build, so no need to clean.
-
-# Write the new state to the file.
-ifneq ($(PREVIOUS_PREBUILT_TOOLS),$(current_prebuilt_tools))
-$(shell \
-  mkdir -p $(dir $(previous_prebuilt_tools_config_file)) && \
-  echo "PREVIOUS_PREBUILT_TOOLS:=$(current_prebuilt_tools)" > \
-    $(previous_prebuilt_tools_config_file))
-endif
-
-ifeq ($(force_tools_clean),true)
-# For this list of prebuilt tools, see prebuilts/sdk/tools/Android.mk.
-tools_clean_files := \
-  $(HOST_OUT_COMMON_INTERMEDIATES)/JAVA_LIBRARIES/signapk_intermediates \
-  $(HOST_OUT_COMMON_INTERMEDIATES)/JAVA_LIBRARIES/dx_intermediates \
-  $(HOST_OUT_COMMON_INTERMEDIATES)/JAVA_LIBRARIES/shrinkedAndroid_intermediates \
-  $(HOST_OUT)/obj*/EXECUTABLES/aapt_intermediates \
-  $(HOST_OUT)/obj*/EXECUTABLES/aidl_intermediates \
-  $(HOST_OUT)/obj*/EXECUTABLES/zipalign_intermediates \
-  $(HOST_OUT)/obj*/lib/libc++$(HOST_SHLIB_SUFFIX) \
-
-$(info *** build type changed, clean host tools...)
-$(info *** rm -rf $(tools_clean_files))
-$(shell rm -rf $(tools_clean_files))
-endif
-
-###########################################################
 
 .PHONY: clean-jack-files
 clean-jack-files: clean-dex-files
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index b5efc71..169e2d2 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -35,7 +35,7 @@
 
 # We expect SSE3 floating point math.
 $(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -msse3 -mfpmath=sse -m32 -Wa,--noexecstack -march=prescott
-$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -m32 -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now
+$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -m32 -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--no-undefined-version
 
 ifneq ($(strip $(BUILD_HOST_static)),)
 # Statically-linked binaries are desirable for sandboxed environment
diff --git a/core/combo/HOST_linux-x86_64.mk b/core/combo/HOST_linux-x86_64.mk
index 9a77324..9766f2b 100644
--- a/core/combo/HOST_linux-x86_64.mk
+++ b/core/combo/HOST_linux-x86_64.mk
@@ -34,7 +34,7 @@
 HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8
 
 HOST_GLOBAL_CFLAGS += -m64 -Wa,--noexecstack
-HOST_GLOBAL_LDFLAGS += -m64 -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now
+HOST_GLOBAL_LDFLAGS += -m64 -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now -Wl,--no-undefined-version
 
 ifneq ($(strip $(BUILD_HOST_static)),)
 # Statically-linked binaries are desirable for sandboxed environment
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index 485e48c..b91e072 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -138,6 +138,7 @@
 			-Wl,--fatal-warnings \
 			-Wl,--icf=safe \
 			-Wl,--hash-style=gnu \
+			-Wl,--no-undefined-version \
 			$(arch_variant_ldflags)
 
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += -mthumb-interwork
diff --git a/core/combo/TARGET_linux-arm64.mk b/core/combo/TARGET_linux-arm64.mk
index 1eb3240..bc89bc9 100644
--- a/core/combo/TARGET_linux-arm64.mk
+++ b/core/combo/TARGET_linux-arm64.mk
@@ -115,6 +115,9 @@
 			-Wl,-maarch64linux \
 			-Wl,--hash-style=gnu \
 			-Wl,--fix-cortex-a53-843419 \
+			-fuse-ld=gold \
+			-Wl,--icf=safe \
+			-Wl,--no-undefined-version \
 			$(arch_variant_ldflags)
 
 # Disable transitive dependency library symbol resolving.
diff --git a/core/combo/TARGET_linux-mips.mk b/core/combo/TARGET_linux-mips.mk
index be05302..186d88f 100644
--- a/core/combo/TARGET_linux-mips.mk
+++ b/core/combo/TARGET_linux-mips.mk
@@ -89,6 +89,7 @@
 			-ffunction-sections \
 			-fdata-sections \
 			-funwind-tables \
+			-fstack-protector-strong \
 			-Wa,--noexecstack \
 			-Werror=format-security \
 			-D_FORTIFY_SOURCE=2 \
@@ -107,6 +108,7 @@
 			-Wl,--build-id=md5 \
 			-Wl,--warn-shared-textrel \
 			-Wl,--fatal-warnings \
+			-Wl,--no-undefined-version \
 			$(arch_variant_ldflags)
 
 # Disable transitive dependency library symbol resolving.
diff --git a/core/combo/TARGET_linux-mips64.mk b/core/combo/TARGET_linux-mips64.mk
index 9704b6b..3e1f61a 100644
--- a/core/combo/TARGET_linux-mips64.mk
+++ b/core/combo/TARGET_linux-mips64.mk
@@ -89,6 +89,7 @@
 			-ffunction-sections \
 			-fdata-sections \
 			-funwind-tables \
+			-fstack-protector-strong \
 			-Wa,--noexecstack \
 			-Werror=format-security \
 			-D_FORTIFY_SOURCE=2 \
@@ -113,6 +114,7 @@
 			-Wl,--build-id=md5 \
 			-Wl,--warn-shared-textrel \
 			-Wl,--fatal-warnings \
+			-Wl,--no-undefined-version \
 			$(arch_variant_ldflags)
 
 # Disable transitive dependency library symbol resolving.
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index c4cb0f8..558ec3b 100644
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -94,7 +94,7 @@
 			-fstrict-aliasing \
 			-funswitch-loops \
 			-funwind-tables \
-			-fstack-protector \
+			-fstack-protector-strong \
 			-m32 \
 			-no-canonical-prefixes \
 			-fno-canonical-system-headers \
@@ -129,6 +129,7 @@
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--fatal-warnings
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--gc-sections
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--hash-style=gnu
+$(combo_2nd_arch_prefix)TARGET_GLOBAL_LDFLAGS += -Wl,--no-undefined-version
 
 $(combo_2nd_arch_prefix)TARGET_C_INCLUDES := \
 	$(libc_root)/arch-x86/include \
diff --git a/core/combo/TARGET_linux-x86_64.mk b/core/combo/TARGET_linux-x86_64.mk
index b7ec50b..12166ec 100644
--- a/core/combo/TARGET_linux-x86_64.mk
+++ b/core/combo/TARGET_linux-x86_64.mk
@@ -94,7 +94,7 @@
 			-fstrict-aliasing \
 			-funswitch-loops \
 			-funwind-tables \
-			-fstack-protector \
+			-fstack-protector-strong \
 			-m64 \
 			-no-canonical-prefixes \
 			-fno-canonical-system-headers
@@ -138,6 +138,7 @@
 TARGET_GLOBAL_LDFLAGS += -Wl,--fatal-warnings
 TARGET_GLOBAL_LDFLAGS += -Wl,--gc-sections
 TARGET_GLOBAL_LDFLAGS += -Wl,--hash-style=gnu
+TARGET_GLOBAL_LDFLAGS += -Wl,--no-undefined-version
 
 TARGET_C_INCLUDES := \
 	$(libc_root)/arch-x86_64/include \
diff --git a/core/config.mk b/core/config.mk
index e615159..556d52b 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -444,6 +444,45 @@
 endif
 endif
 
+#
+# Tools that are prebuilts for TARGET_BUILD_APPS
+#
+
+ACP := $(HOST_OUT_EXECUTABLES)/acp
+AIDL := $(HOST_OUT_EXECUTABLES)/aidl
+AAPT := $(HOST_OUT_EXECUTABLES)/aapt
+ZIPALIGN := $(HOST_OUT_EXECUTABLES)/zipalign
+SIGNAPK_JAR := $(HOST_OUT_JAVA_LIBRARIES)/signapk$(COMMON_JAVA_PACKAGE_SUFFIX)
+SIGNAPK_JNI_LIBRARY_PATH := $(HOST_OUT_SHARED_LIBRARIES)
+LLVM_RS_CC := $(HOST_OUT_EXECUTABLES)/llvm-rs-cc
+BCC_COMPAT := $(HOST_OUT_EXECUTABLES)/bcc_compat
+
+DX := $(HOST_OUT_EXECUTABLES)/dx
+MAINDEXCLASSES := $(HOST_OUT_EXECUTABLES)/mainDexClasses
+
+# Override the definitions above for unbundled and PDK builds
+ifneq (,$(TARGET_BUILD_APPS)$(filter true,$(TARGET_BUILD_PDK)))
+prebuilt_sdk_tools := prebuilts/sdk/tools
+prebuilt_sdk_tools_bin := $(prebuilt_sdk_tools)/$(HOST_OS)/bin
+
+ACP := $(prebuilt_sdk_tools_bin)/acp
+AIDL := $(prebuilt_sdk_tools_bin)/aidl
+AAPT := $(prebuilt_sdk_tools_bin)/aapt
+ZIPALIGN := $(prebuilt_sdk_tools_bin)/zipalign
+SIGNAPK_JAR := $(prebuilt_sdk_tools)/lib/signapk$(COMMON_JAVA_PACKAGE_SUFFIX)
+# Use 64-bit libraries unconditionally because 32-bit JVMs are no longer supported
+SIGNAPK_JNI_LIBRARY_PATH := $(prebuilt_sdk_tools)/$(HOST_OS)/lib64
+
+DX := $(prebuilt_sdk_tools)/dx
+MAINDEXCLASSES := $(prebuilt_sdk_tools)/mainDexClasses
+
+# Don't use prebuilts in PDK
+ifneq ($(TARGET_BUILD_PDK),true)
+LLVM_RS_CC := $(prebuilt_sdk_tools_bin)/llvm-rs-cc
+BCC_COMPAT := $(prebuilt_sdk_tools_bin)/bcc_compat
+endif # TARGET_BUILD_PDK
+endif # TARGET_BUILD_APPS || TARGET_BUILD_PDK
+
 
 # ---------------------------------------------------------------
 # Generic tools.
@@ -463,8 +502,6 @@
 YASM := prebuilts/misc/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)/yasm/yasm
 
 DOXYGEN:= doxygen
-AAPT := $(HOST_OUT_EXECUTABLES)/aapt$(HOST_EXECUTABLE_SUFFIX)
-AIDL := $(HOST_OUT_EXECUTABLES)/aidl$(HOST_EXECUTABLE_SUFFIX)
 AIDL_CPP := $(HOST_OUT_EXECUTABLES)/aidl-cpp$(HOST_EXECUTABLE_SUFFIX)
 ifeq ($(HOST_OS),linux)
 BREAKPAD_DUMP_SYMS := $(HOST_OUT_EXECUTABLES)/dump_syms
@@ -474,7 +511,6 @@
 endif
 PROTOC := $(HOST_OUT_EXECUTABLES)/aprotoc$(HOST_EXECUTABLE_SUFFIX)
 DBUS_GENERATOR := $(HOST_OUT_EXECUTABLES)/dbus-binding-generator
-SIGNAPK_JAR := $(HOST_OUT_JAVA_LIBRARIES)/signapk$(COMMON_JAVA_PACKAGE_SUFFIX)
 MKBOOTFS := $(HOST_OUT_EXECUTABLES)/mkbootfs$(HOST_EXECUTABLE_SUFFIX)
 MINIGZIP := $(HOST_OUT_EXECUTABLES)/minigzip$(HOST_EXECUTABLE_SUFFIX)
 ifeq (,$(strip $(BOARD_CUSTOM_MKBOOTIMG)))
@@ -519,8 +555,6 @@
 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)
-BCC_COMPAT := $(HOST_OUT_EXECUTABLES)/bcc_compat$(HOST_EXECUTABLE_SUFFIX)
 RMTYPEDEFS := $(HOST_OUT_EXECUTABLES)/rmtypedefs
 APPEND2SIMG := $(HOST_OUT_EXECUTABLES)/append2simg
 VERITY_SIGNER := $(HOST_OUT_EXECUTABLES)/verity_signer
@@ -530,12 +564,6 @@
 VBOOT_SIGNER := prebuilts/misc/scripts/vboot_signer/vboot_signer.sh
 FEC := $(HOST_OUT_EXECUTABLES)/fec
 
-# ACP is always for the build OS, not for the host OS
-ACP := $(BUILD_OUT_EXECUTABLES)/acp$(BUILD_EXECUTABLE_SUFFIX)
-
-# dx is java behind a shell script; no .exe necessary.
-DX := $(HOST_OUT_EXECUTABLES)/dx
-ZIPALIGN := $(HOST_OUT_EXECUTABLES)/zipalign$(HOST_EXECUTABLE_SUFFIX)
 ifndef TARGET_BUILD_APPS
 ZIPTIME := $(HOST_OUT_EXECUTABLES)/ziptime$(HOST_EXECUTABLE_SUFFIX)
 endif
@@ -543,6 +571,7 @@
 # ijar converts a .jar file to a smaller .jar file which only has its
 # interfaces.
 IJAR := $(HOST_OUT_EXECUTABLES)/ijar$(BUILD_EXECUTABLE_SUFFIX)
+DEXDUMP := $(HOST_OUT_EXECUTABLES)/dexdump2$(BUILD_EXECUTABLE_SUFFIX)
 
 # relocation packer
 RELOCATION_PACKER := prebuilts/misc/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)/relocation_packer/relocation_packer
@@ -663,6 +692,18 @@
 HOST_CROSS_GLOBAL_CPPFLAGS += $(HOST_CROSS_RELEASE_CPPFLAGS)
 endif
 
+ifdef BRILLO
+# Add a C define that identifies Brillo targets. __BRILLO__ should only be used
+# to differentiate between Brillo and non-Brillo-but-Android environments. Use
+# __ANDROID__ instead to test if something is being built in an Android-derived
+# environment (including Brillo) as opposed to an entirely different
+# environment (e.g. Chrome OS).
+TARGET_GLOBAL_CFLAGS += -D__BRILLO__
+ifdef TARGET_2ND_ARCH
+$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CFLAGS += -D__BRILLO__
+endif
+endif
+
 # allow overriding default Java libraries on a per-target basis
 ifeq ($(TARGET_DEFAULT_JAVA_LIBRARIES),)
   TARGET_DEFAULT_JAVA_LIBRARIES := core-libart core-junit ext framework okhttp
diff --git a/core/cxx_stl_setup.mk b/core/cxx_stl_setup.mk
index be8a711..37be1f7 100644
--- a/core/cxx_stl_setup.mk
+++ b/core/cxx_stl_setup.mk
@@ -104,9 +104,6 @@
     endif
 else ifeq ($(my_cxx_stl),ndk)
     # Using an NDK STL. Handled in binary.mk.
-    ifndef LOCAL_IS_HOST_MODULE
-        my_system_shared_libraries += libstdc++
-    endif
 else ifeq ($(my_cxx_stl),libstdc++)
     # Using bionic's basic libstdc++. Not actually an STL. Only around until the
     # tree is in good enough shape to not need it.
diff --git a/core/definitions.mk b/core/definitions.mk
index 89ffcf7..742a56c 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -1948,9 +1948,9 @@
 endef
 endif
 
-## Rule to creates a table of contents from a .jar file.
+## Rule to create a table of contents from a .jar file.
 ## Must be called with $(eval).
-# $1: A .jar file
+# $(1): A .jar file
 define _transform-jar-to-toc
 $1.toc: $1 | $(IJAR)
 	@echo Generating TOC: $$@
@@ -1959,11 +1959,40 @@
 endef
 
 ## Define a rule which generates .jar.toc and mark it as .KATI_RESTAT.
+# $(1): A .jar file
 define define-jar-to-toc-rule
-$(eval $(call _transform-jar-to-toc,$1))
+$(eval $(call _transform-jar-to-toc,$1))\
 $(eval .KATI_RESTAT: $1.toc)
 endef
 
+ifeq (,$(TARGET_BUILD_APPS))
+
+## Rule to create a table of contents from a .dex file.
+## Must be called with $(eval).
+# $(1): The directory which contains classes*.dex files
+define _transform-dex-to-toc
+$1/classes.dex.toc: PRIVATE_INPUT_DEX_FILES := $1/classes*.dex
+$1/classes.dex.toc: $1/classes.dex $(DEXDUMP)
+	@echo Generating TOC: $$@
+	$(hide) $(DEXDUMP) -l xml $$(PRIVATE_INPUT_DEX_FILES) > $$@.tmp
+	$$(call commit-change-for-toc,$$@)
+endef
+
+## Define a rule which generates .dex.toc and mark it as .KATI_RESTAT.
+# $(1): The directory which contains classes*.dex files
+define define-dex-to-toc-rule
+$(eval $(call _transform-dex-to-toc,$1))\
+$(eval .KATI_RESTAT: $1/classes.dex.toc)
+endef
+
+else
+
+# Turn off .toc optimization for apps build as we cannot build dexdump.
+define define-dex-to-toc-rule
+endef
+
+endif  # TARGET_BUILD_APPS
+
 
 # Invoke Jack to compile java from source to jack files without shrink or obfuscation.
 #
@@ -2165,7 +2194,7 @@
 #
 define sign-package
 $(hide) mv $@ $@.unsigned
-$(hide) java -jar $(SIGNAPK_JAR) \
+$(hide) java -Djava.library.path=$(SIGNAPK_JNI_LIBRARY_PATH) -jar $(SIGNAPK_JAR) \
     $(PRIVATE_CERTIFICATE) $(PRIVATE_PRIVATE_KEY) \
     $(PRIVATE_ADDITIONAL_CERTIFICATES) $@.unsigned $@.signed
 $(hide) mv $@.signed $@
diff --git a/core/dex_preopt_libart.mk b/core/dex_preopt_libart.mk
index 1bd0bd7..3f52876 100644
--- a/core/dex_preopt_libart.mk
+++ b/core/dex_preopt_libart.mk
@@ -11,11 +11,6 @@
 DEX2OAT := $(HOST_OUT_EXECUTABLES)/dex2oatd$(HOST_EXECUTABLE_SUFFIX)
 endif
 
-# By default, do not run rerun dex2oat if the tool changes.
-# Comment out the | to force dex2oat to rerun on after all changes.
-DEX2OAT_DEPENDENCY := art/runtime/oat.cc # dependency on oat version number
-DEX2OAT_DEPENDENCY += art/runtime/image.cc # dependency on image version number
-DEX2OAT_DEPENDENCY += |
 DEX2OAT_DEPENDENCY += $(DEX2OAT)
 
 # Use the first preloaded-classes file in PRODUCT_COPY_FILES.
diff --git a/core/dpi_specific_apk.mk b/core/dpi_specific_apk.mk
index 5d0b5bf..b2a3d64 100644
--- a/core/dpi_specific_apk.mk
+++ b/core/dpi_specific_apk.mk
@@ -48,7 +48,7 @@
 $(built_dpi_apk) : $(R_file_stamp)
 $(built_dpi_apk) : $(all_library_res_package_export_deps)
 $(built_dpi_apk) : $(private_key) $(certificate) $(SIGNAPK_JAR)
-$(built_dpi_apk) : $(AAPT) | $(ZIPALIGN)
+$(built_dpi_apk) : $(AAPT)
 $(built_dpi_apk) : $(all_res_assets) $(jni_shared_libraries) $(full_android_manifest)
 	@echo "target Package: $(PRIVATE_MODULE) ($@)"
 	$(if $(PRIVATE_SOURCE_ARCHIVE),\
@@ -68,7 +68,6 @@
 endif
 endif
 	$(sign-package)
-	$(align-package)
 
 # Set up global variables to register this apk to the higher-level dependency graph.
 ALL_MODULES += $(dpi_apk_name)
diff --git a/core/java.mk b/core/java.mk
index 9bdb77f..f6f52dc 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -658,6 +658,11 @@
 	@echo Building with Jack: $@
 	$(java-to-jack)
 
+# Update timestamps of .toc files for static java libraries so
+# dependents will be always rebuilt.
+$(built_dex).toc: $(full_classes_jack)
+	touch $@
+
 else #LOCAL_IS_STATIC_JAVA_LIBRARY
 $(built_dex_intermediate): PRIVATE_CLASSES_JACK := $(full_classes_jack)
 
@@ -671,6 +676,8 @@
 $(full_classes_jack): $(built_dex_intermediate)
 	$(hide) touch $@
 
+$(call define-dex-to-toc-rule, $(intermediates.COMMON))
+
 endif #LOCAL_IS_STATIC_JAVA_LIBRARY
 
 $(noshrob_classes_jack): PRIVATE_JACK_INTERMEDIATES_DIR := $(intermediates.COMMON)/jack-noshrob-rsc
diff --git a/core/java_common.mk b/core/java_common.mk
index b7f07ab..f11e723 100644
--- a/core/java_common.mk
+++ b/core/java_common.mk
@@ -133,17 +133,23 @@
 #                 be up-to-date.
 ifndef LOCAL_IS_HOST_MODULE
 ifeq ($(LOCAL_SDK_VERSION),)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,core-libart)
+ifeq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
+# No bootclasspath. But we still need "" to prevent javac from using default host bootclasspath.
+my_bootclasspath := ""
+else  # LOCAL_NO_STANDARD_LIBRARIES
+my_bootclasspath := $(call java-lib-files,core-libart)
+endif  # LOCAL_NO_STANDARD_LIBRARIES
 else
 ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),current)
 # LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS.
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,android_stubs_current)
+my_bootclasspath := $(call java-lib-files,android_stubs_current)
 else ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),system_current)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,android_system_stubs_current)
+my_bootclasspath := $(call java-lib-files,android_system_stubs_current)
 else
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,sdk_v$(LOCAL_SDK_VERSION))
+my_bootclasspath := $(call java-lib-files,sdk_v$(LOCAL_SDK_VERSION))
 endif # current or system_current
 endif # LOCAL_SDK_VERSION
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(my_bootclasspath)
 
 full_shared_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 full_java_lib_deps := $(call java-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
@@ -152,7 +158,12 @@
 else # LOCAL_IS_HOST_MODULE
 
 ifeq ($(USE_CORE_LIB_BOOTCLASSPATH),true)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,core-libart-hostdex,$(LOCAL_IS_HOST_MODULE))
+ifeq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
+my_bootclasspath := ""
+else
+my_bootclasspath := $(call java-lib-files,core-libart-hostdex,$(LOCAL_IS_HOST_MODULE))
+endif
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(my_bootclasspath)
 
 full_shared_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 full_java_lib_deps := $(call java-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE)) \
@@ -263,25 +274,39 @@
 
 ifndef LOCAL_IS_HOST_MODULE
 ifeq ($(LOCAL_SDK_VERSION),)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,core-libart)
+ifeq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
+my_bootclasspath :=
 else
+my_bootclasspath := $(call jack-lib-files,core-libart)
+endif
+else  # LOCAL_SDK_VERSION
 ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),current)
 # LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS.
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,android_stubs_current)
+my_bootclasspath := $(call jack-lib-files,android_stubs_current)
 else ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),system_current)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,android_system_stubs_current)
+my_bootclasspath := $(call jack-lib-files,android_system_stubs_current)
 else
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,sdk_v$(LOCAL_SDK_VERSION))
+my_bootclasspath :=$(call jack-lib-files,sdk_v$(LOCAL_SDK_VERSION))
 endif # current or system_current
 endif # LOCAL_SDK_VERSION
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(my_bootclasspath)
 
 full_shared_jack_libs := $(call jack-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 full_jack_lib_deps := $(call jack-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
+# Turn off .toc optimization for apps build as we cannot build dexdump.
+ifeq (,$(TARGET_BUILD_APPS))
+full_jack_lib_deps := $(patsubst %.jack, %.dex.toc, $(full_jack_lib_deps))
+endif
 
 else # LOCAL_IS_HOST_MODULE
 
 ifeq ($(USE_CORE_LIB_BOOTCLASSPATH),true)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,core-libart-hostdex,$(LOCAL_IS_HOST_MODULE))
+ifeq ($(LOCAL_NO_STANDARD_LIBRARIES),true)
+my_bootclasspath :=
+else
+my_bootclasspath := $(call jack-lib-files,core-libart-hostdex,$(LOCAL_IS_HOST_MODULE))
+endif
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(my_bootclasspath)
 full_shared_jack_libs := $(call jack-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 full_jack_lib_deps := $(call jack-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
 else
diff --git a/core/main.mk b/core/main.mk
index d9ff68e..c29731c 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -525,6 +525,9 @@
 # --mindepth=2 makes the prunes not work.
 subdir_makefiles := \
 	$(shell build/tools/findleaves.py $(FIND_LEAVES_EXCLUDES) $(subdirs) Android.mk)
+ifeq ($(USE_SOONG),true)
+subdir_makefiles := $(SOONG_ANDROID_MK) $(subdir_makefiles)
+endif
 
 $(foreach mk, $(subdir_makefiles), $(info including $(mk) ...)$(eval include $(mk)))
 
@@ -866,6 +869,9 @@
 
 .PHONY: checkbuild
 checkbuild: $(modules_to_check) droid_targets
+ifeq ($(USE_SOONG),true)
+checkbuild: checkbuild-soong
+endif
 ifeq (true,$(ANDROID_BUILD_EVERYTHING_BY_DEFAULT))
 droid: checkbuild
 endif
diff --git a/core/ninja.mk b/core/ninja.mk
index 862ed80..750aae5 100644
--- a/core/ninja.mk
+++ b/core/ninja.mk
@@ -118,21 +118,34 @@
 NINJA_MAKEPARALLEL := $(MAKEPARALLEL) --ninja
 endif
 
+ifeq ($(USE_SOONG),true)
+include $(BUILD_SYSTEM)/soong.mk
+
+COMBINED_BUILD_NINJA := $(OUT_DIR)/combined$(KATI_NINJA_SUFFIX).ninja
+
+$(COMBINED_BUILD_NINJA): $(KATI_BUILD_NINJA) $(SOONG_ANDROID_MK)
+	$(hide) echo "builddir = $(OUT_DIR)" > $(COMBINED_BUILD_NINJA)
+	$(hide) echo "subninja $(SOONG_BUILD_NINJA)" >> $(COMBINED_BUILD_NINJA)
+	$(hide) echo "subninja $(KATI_BUILD_NINJA)" >> $(COMBINED_BUILD_NINJA)
+else
+COMBINED_BUILD_NINJA := $(KATI_BUILD_NINJA)
+endif
+
 $(sort $(DEFAULT_GOAL) $(ANDROID_GOALS)) : ninja_wrapper
 	@#empty
 
 .PHONY: ninja_wrapper
-ninja_wrapper: $(KATI_BUILD_NINJA) $(MAKEPARALLEL)
+ninja_wrapper: $(COMBINED_BUILD_NINJA) $(MAKEPARALLEL)
 	@echo Starting build with ninja
-	+$(hide) export NINJA_STATUS="$(NINJA_STATUS)" && source $(KATI_ENV_SH) && $(NINJA_MAKEPARALLEL) $(NINJA) $(NINJA_GOALS) -C $(TOP) -f $(KATI_BUILD_NINJA) $(NINJA_ARGS)
+	+$(hide) export NINJA_STATUS="$(NINJA_STATUS)" && source $(KATI_ENV_SH) && $(NINJA_MAKEPARALLEL) $(NINJA) $(NINJA_GOALS) -C $(TOP) -f $(COMBINED_BUILD_NINJA) $(NINJA_ARGS)
 
 KATI_FIND_EMULATOR := --use_find_emulator
 ifeq ($(KATI_EMULATE_FIND),false)
   KATI_FIND_EMULATOR :=
 endif
-$(KATI_BUILD_NINJA): $(KATI) $(MAKEPARALLEL) FORCE
+$(KATI_BUILD_NINJA): $(KATI) $(MAKEPARALLEL) $(SOONG_ANDROID_MK) FORCE
 	@echo Running kati to generate build$(KATI_NINJA_SUFFIX).ninja...
-	+$(hide) $(KATI_MAKEPARALLEL) $(KATI) --ninja --ninja_dir=$(OUT_DIR) --ninja_suffix=$(KATI_NINJA_SUFFIX) --regen --ignore_dirty=$(OUT_DIR)/% --ignore_optional_include=$(OUT_DIR)/%.P --detect_android_echo $(KATI_FIND_EMULATOR) -f build/core/main.mk $(KATI_GOALS) --gen_all_targets BUILDING_WITH_NINJA=true
+	+$(hide) $(KATI_MAKEPARALLEL) $(KATI) --ninja --ninja_dir=$(OUT_DIR) --ninja_suffix=$(KATI_NINJA_SUFFIX) --regen --ignore_dirty=$(OUT_DIR)/% --no_ignore_dirty=$(SOONG_ANDROID_MK) --ignore_optional_include=$(OUT_DIR)/%.P --detect_android_echo $(KATI_FIND_EMULATOR) -f build/core/main.mk $(KATI_GOALS) --gen_all_targets BUILDING_WITH_NINJA=true SOONG_ANDROID_MK=$(SOONG_ANDROID_MK)
 
 KATI_CXX := $(CLANG_CXX) $(CLANG_HOST_GLOBAL_CFLAGS) $(CLANG_HOST_GLOBAL_CPPFLAGS)
 KATI_LD := $(CLANG_CXX) $(CLANG_HOST_GLOBAL_LDFLAGS)
diff --git a/core/package_internal.mk b/core/package_internal.mk
index cb77e76..f5a00e5 100644
--- a/core/package_internal.mk
+++ b/core/package_internal.mk
@@ -390,7 +390,7 @@
     $(LOCAL_ADDITIONAL_CERTIFICATES), $(c).x509.pem $(c).pk8)
 
 # Define the rule to build the actual package.
-$(LOCAL_BUILT_MODULE): $(AAPT) | $(ZIPALIGN)
+$(LOCAL_BUILT_MODULE): $(AAPT)
 # PRIVATE_JNI_SHARED_LIBRARIES is a list of <abi>:<path_of_built_lib>.
 $(LOCAL_BUILT_MODULE): PRIVATE_JNI_SHARED_LIBRARIES := $(jni_shared_libraries_with_abis)
 # PRIVATE_JNI_SHARED_LIBRARIES_ABI is a list of ABI names.
@@ -439,8 +439,6 @@
 endif
 endif
 	$(sign-package)
-	@# Alignment must happen after all other zip operations.
-	$(align-package)
 
 ###############################
 ## Build dpi-specific apks, if it's apps_only build.
@@ -475,7 +473,7 @@
 installed_apk_splits := $(foreach s,$(my_split_suffixes),$(my_module_path)/$(LOCAL_MODULE)_$(s).apk)
 
 # The splits should have been built in the same command building the base apk.
-# This rule just runs signing and zipalign etc.
+# This rule just runs signing.
 # Note that we explicily check the existence of the split apk and remove the
 # built base apk if the split apk isn't there.
 # That way the build system will rerun the aapt after the user changes the splitting parameters.
@@ -487,7 +485,6 @@
 	  rm $<; exit 1; \
 	fi
 	$(sign-package)
-	$(align-package)
 
 # Rules to install the splits
 $(installed_apk_splits) : $(my_module_path)/$(LOCAL_MODULE)_%.apk : $(built_module_path)/package_%.apk | $(ACP)
diff --git a/core/prebuilt_internal.mk b/core/prebuilt_internal.mk
index aec08ed..b0af228 100644
--- a/core/prebuilt_internal.mk
+++ b/core/prebuilt_internal.mk
@@ -224,8 +224,10 @@
 endif
 endif
 	$(sign-package)
-endif
+	# No need for align-package because sign-package takes care of alignment
+else
 	$(align-package)
+endif
 
 ###############################
 ## Rule to build the odex file
@@ -241,7 +243,7 @@
 built_apk_splits := $(addprefix $(built_module_path)/,$(notdir $(LOCAL_PACKAGE_SPLITS)))
 installed_apk_splits := $(addprefix $(my_module_path)/,$(notdir $(LOCAL_PACKAGE_SPLITS)))
 
-# Rules to sign and zipalign the split apks.
+# Rules to sign the split apks.
 my_src_dir := $(sort $(dir $(LOCAL_PACKAGE_SPLITS)))
 ifneq (1,$(words $(my_src_dir)))
 $(error You must put all the split source apks in the same folder: $(LOCAL_PACKAGE_SPLITS))
@@ -253,7 +255,6 @@
 $(built_apk_splits) : $(built_module_path)/%.apk : $(my_src_dir)/%.apk | $(ACP)
 	$(copy-file-to-new-target)
 	$(sign-package)
-	$(align-package)
 
 # Rules to install the split apks.
 $(installed_apk_splits) : $(my_module_path)/%.apk : $(built_module_path)/%.apk | $(ACP)
@@ -327,6 +328,11 @@
         $(LOCAL_ADDITIONAL_DEPENDENCIES) $(JILL_JAR) $(JACK)
 	$(transform-jar-to-jack)
 
+# Update timestamps of .toc files for prebuilts so dependents will be
+# always rebuilt.
+$(intermediates.COMMON)/classes.dex.toc: $(intermediates.COMMON)/classes.jack
+	touch $@
+
 endif # JAVA_LIBRARIES
 
 $(built_module) : $(LOCAL_MODULE_MAKEFILE_DEP) $(LOCAL_ADDITIONAL_DEPENDENCIES)
diff --git a/core/soong.mk b/core/soong.mk
new file mode 100644
index 0000000..c464ba8
--- /dev/null
+++ b/core/soong.mk
@@ -0,0 +1,61 @@
+SOONG_OUT_DIR := $(OUT_DIR)/soong
+SOONG := $(SOONG_OUT_DIR)/soong
+SOONG_BUILD_NINJA := $(SOONG_OUT_DIR)/build.ninja
+SOONG_ANDROID_MK := $(SOONG_OUT_DIR)/Android.mk
+SOONG_VARIABLES := $(SOONG_OUT_DIR)/soong.variables
+SOONG_IN_MAKE := $(SOONG_OUT_DIR)/.soong.in_make
+
+ifeq (,$(filter /%,$(SOONG_OUT_DIR)))
+SOONG_TOP_RELPATH := $(shell python -c "import os; print os.path.relpath('$(TOP)', '$(SOONG_OUT_DIR)')")
+else
+SOONG_TOP_RELPATH := $(realpath $(TOP))
+endif
+
+# Bootstrap soong.  Run only the first time for clean builds
+$(SOONG):
+	$(hide) mkdir -p $(dir $@)
+	$(hide) cd $(dir $@) && $(SOONG_TOP_RELPATH)/bootstrap.bash
+
+# Create soong.variables with copies of makefile settings.  Runs every build,
+# but only updates soong.variables if it changes
+SOONG_VARIABLES_TMP := $(SOONG_VARIABLES).$$$$
+$(SOONG_VARIABLES): FORCE
+	$(hide) mkdir -p $(dir $@)
+	$(hide) (\
+	echo '{'; \
+	echo '    "Device_uses_jemalloc": $(if $(filter dlmalloc,$(MALLOC_IMPL)),false,true),'; \
+	echo '    "Device_uses_dlmalloc": $(if $(filter dlmalloc,$(MALLOC_IMPL)),true,false),'; \
+	echo '    $(if $(BOARD_MALLOC_ALIGNMENT),"Dlmalloc_alignment": $(BOARD_MALLOC_ALIGNMENT)$(comma),)'; \
+	echo '    "Platform_sdk_version": $(PLATFORM_SDK_VERSION),'; \
+	echo '    "Unbundled_build": $(if $(TARGET_BUILD_APPS),true,false),'; \
+	echo '    "Brillo": $(if $(BRILLO),true,false),'; \
+	echo ''; \
+	echo '    "DeviceName": "$(TARGET_DEVICE)",'; \
+	echo '    "DeviceArch": "$(TARGET_ARCH)",'; \
+	echo '    "DeviceArchVariant": "$(TARGET_ARCH_VARIANT)",'; \
+	echo '    "DeviceCpuVariant": "$(TARGET_CPU_VARIANT)",'; \
+	echo '    "DeviceAbi": ["$(TARGET_CPU_ABI)", "$(TARGET_CPU_ABI2)"],'; \
+	echo '    "DeviceUsesClang": $(if $(USE_CLANG_PLATFORM_BUILD),$(USE_CLANG_PLATFORM_BUILD),false),'; \
+	echo ''; \
+	echo '    "DeviceSecondaryArch": "$(TARGET_2ND_ARCH)",'; \
+	echo '    "DeviceSecondaryArchVariant": "$(TARGET_2ND_ARCH_VARIANT)",'; \
+	echo '    "DeviceSecondaryCpuVariant": "$(TARGET_2ND_CPU_VARIANT)",'; \
+	echo '    "DeviceSecondaryAbi": ["$(TARGET_2ND_CPU_ABI)", "$(TARGET_2ND_CPU_ABI2)"],'; \
+	echo ''; \
+	echo '    "HostArch": "$(HOST_ARCH)",'; \
+	echo '    "HostSecondaryArch": "$(HOST_2ND_ARCH)"'; \
+	echo '}') > $(SOONG_VARIABLES_TMP); \
+	if ! cmp -s $(SOONG_VARIABLES_TMP) $(SOONG_VARIABLES); then \
+	  mv $(SOONG_VARIABLES_TMP) $(SOONG_VARIABLES); \
+	else \
+	  rm $(SOONG_VARIABLES_TMP); \
+	fi
+
+# Tell soong that it is embedded in make
+$(SOONG_IN_MAKE):
+	$(hide) mkdir -p $(dir $@)
+	$(hide) touch $@
+
+# Build an Android.mk listing all soong outputs as prebuilts
+$(SOONG_ANDROID_MK): $(SOONG) $(SOONG_VARIABLES) $(SOONG_IN_MAKE) FORCE
+	$(hide) $(SOONG) $(SOONG_BUILD_NINJA) $(NINJA_ARGS)
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index dcc1e18..8b9bdba 100644
--- a/core/version_defaults.mk
+++ b/core/version_defaults.mk
@@ -43,7 +43,7 @@
   # which is the version that we reveal to the end user.
   # Update this value when the platform version changes (rather
   # than overriding it somewhere else).  Can be an arbitrary string.
-  PLATFORM_VERSION := 6.0
+  PLATFORM_VERSION := 6.0.1
 endif
 
 ifeq "" "$(PLATFORM_SDK_VERSION)"
@@ -104,7 +104,7 @@
   # Can be an arbitrary string, but must be a single word.
   #
   # If there is no $PLATFORM_SECURITY_PATCH set, keep it empty.
-  PLATFORM_SECURITY_PATCH := 2015-10-01
+  PLATFORM_SECURITY_PATCH := 2015-12-01
 endif
 
 ifeq "" "$(PLATFORM_BASE_OS)"
@@ -146,5 +146,5 @@
   # If no BUILD_NUMBER is set, create a useful "I am an engineering build
   # from this date/time" value.  Make it start with a non-digit so that
   # anyone trying to parse it as an integer will probably get "0".
-  BUILD_NUMBER := eng.$(USER).$(shell $(DATE) +%Y%m%d.%H%M%S)
+  BUILD_NUMBER := eng.$(shell echo $${USER:0:6}).$(shell $(DATE) +%Y%m%d.%H%M%S)
 endif
diff --git a/target/board/generic/sepolicy/domain.te b/target/board/generic/sepolicy/domain.te
index c28ca74..201fa86 100644
--- a/target/board/generic/sepolicy/domain.te
+++ b/target/board/generic/sepolicy/domain.te
@@ -1,3 +1,5 @@
 # For /sys/qemu_trace files in the emulator.
 allow domain sysfs_writable:file rw_file_perms;
 allow domain qemu_device:chr_file rw_file_perms;
+
+get_prop(domain, qemu_prop)
diff --git a/target/board/generic/sepolicy/file_contexts b/target/board/generic/sepolicy/file_contexts
index e626d9d..e704a8e 100644
--- a/target/board/generic/sepolicy/file_contexts
+++ b/target/board/generic/sepolicy/file_contexts
@@ -7,6 +7,6 @@
 /dev/ttyGF[0-9]*             u:object_r:serial_device:s0
 /dev/ttyS2                   u:object_r:console_device:s0
 /system/bin/qemud            u:object_r:qemud_exec:s0
-/sys/qemu_trace(/.*)?   --   u:object_r:sysfs_writable:s0
+/sys/qemu_trace(/.*)?        u:object_r:sysfs_writable:s0
 /system/etc/init.goldfish.sh u:object_r:goldfish_setup_exec:s0
 /system/bin/qemu-props       u:object_r:qemu_props_exec:s0
diff --git a/target/board/generic/sepolicy/goldfish_setup.te b/target/board/generic/sepolicy/goldfish_setup.te
index b472d2a..bce196a 100644
--- a/target/board/generic/sepolicy/goldfish_setup.te
+++ b/target/board/generic/sepolicy/goldfish_setup.te
@@ -13,6 +13,8 @@
 allow goldfish_setup self:capability { net_admin net_raw };
 allow goldfish_setup self:udp_socket create_socket_perms;
 
+net_domain(goldfish_setup)
+
 # Set net.eth0.dns*, debug.sf.nobootanimation
 set_prop(goldfish_setup, system_prop)
 set_prop(goldfish_setup, debug_prop)
diff --git a/target/board/generic/sepolicy/netd.te b/target/board/generic/sepolicy/netd.te
new file mode 100644
index 0000000..2b002ec
--- /dev/null
+++ b/target/board/generic/sepolicy/netd.te
@@ -0,0 +1 @@
+dontaudit netd self:capability sys_module;
diff --git a/target/product/embedded.mk b/target/product/embedded.mk
index 0f92a1c..2428585 100644
--- a/target/product/embedded.mk
+++ b/target/product/embedded.mk
@@ -38,6 +38,7 @@
     libFFTEm \
     libGLESv1_CM \
     libGLESv2 \
+    libGLESv3 \
     libbinder \
     libc \
     libcutils \
diff --git a/tools/Android.mk b/tools/Android.mk
index 30febd6..9073ac3 100644
--- a/tools/Android.mk
+++ b/tools/Android.mk
@@ -16,17 +16,4 @@
 
 LOCAL_PATH := $(call my-dir)
 
-ifeq (,$(TARGET_BUILD_APPS))
-
-ifeq ($(TARGET_BUILD_PDK),true)
-include $(filter-out %/acp/Android.mk %/signapk/Android.mk %/zipalign/Android.mk,\
-  $(call all-makefiles-under,$(LOCAL_PATH)))
-else # !PDK
 include $(call all-makefiles-under,$(LOCAL_PATH))
-endif # PDK
-
-else # TARGET_BUILD_APPS
-
-include $(LOCAL_PATH)/apicheck/Android.mk
-
-endif
diff --git a/tools/droiddoc/templates-sac/assets/css/default.css b/tools/droiddoc/templates-sac/assets/css/default.css
index c349c89..9b1fe5a 100644
--- a/tools/droiddoc/templates-sac/assets/css/default.css
+++ b/tools/droiddoc/templates-sac/assets/css/default.css
@@ -2208,6 +2208,7 @@
 #nav-swap {
   height:30px;
   border-top:1px solid #ccc;
+  display: none;
 }
 #nav-swap a {
   display:inline-block;
@@ -2242,6 +2243,10 @@
   margin-left:0;
 }
 
+#nav-tree, #swapper {
+  display: none;
+}
+
 #nav-tree ul {
   list-style:none;
   padding:0;
@@ -2336,11 +2341,13 @@
   border-bottom: 1px solid #CCC;
   background:#e9e9e9;
   background: rgba(0, 0, 0, 0.05); /* matches #nav li.expanded */
+  display: none;
 
 }
 #api-nav-title {
   padding:0 5px;
   white-space:nowrap;
+  display: none;
 }
 
 #api-level-toggle {
@@ -3580,8 +3587,9 @@
   border-color: #33b5e5;
 }
 
+// Fudging this so SAC looks OK
 .develop #header .wrap {
-  border-color: #F80;
+  border-color: #CCC;
 }
 
 .distribute #header .wrap {
@@ -4568,3 +4576,83 @@
 .annotation-message {
   display: block;
 }
+
+.dac-custom-search {
+  background: #fff;
+  margin: 0 -10px;
+  padding: 20px 10px;
+  z-index: 1;
+}
+
+.dac-custom-search .dac-fab, .dac-custom-search .dac-button-social {
+  top: -48px;
+}
+
+.dac-custom-search-section-title {
+  color: #505050;
+}
+
+.dac-custom-search-entry {
+  margin-bottom: 36px;
+  margin-top: 24px;
+  margin-left: 0em;
+}
+
+.dac-custom-search-image {
+  background-size: cover;
+  height: 112px;
+}
+
+.dac-custom-search-title {
+  color: #333;
+  font-size: 14px;
+  font-weight: 700;
+  line-height: 0px;
+  padding: 0;
+  margin: 1em 0em 1em 0em;
+}
+
+.dac-custom-search-title a {
+  color: inherit;
+}
+
+.dac-custom-search-section {
+  color: #999;
+  font-size: 16px;
+  font-variant: small-caps;
+  font-weight: 700;
+  margin: -5px 0 0 0;
+}
+
+.dac-custom-search-snippet {
+  color: #666;
+  margin: 0em 0em .25em 0em;
+}
+
+.dac-custom-search-link {
+  font-weight: 500;
+  word-wrap: break-word;
+  width: 100%;
+}
+
+.dac-custom-search-load-more {
+  background: none;
+  border: none;
+  color: #333;
+  cursor: pointer;
+  display: block;
+  font-size: 14px;
+  font-weight: 700;
+  margin: 75px auto;
+  outline: none;
+  padding: 10px;
+}
+
+.dac-custom-search-load-more:hover {
+  opacity: 0.7;
+}
+
+.dac-custom-search-no-results {
+  color: #999;
+}
+
diff --git a/tools/droiddoc/templates-sac/assets/js/docs.js b/tools/droiddoc/templates-sac/assets/js/docs.js
index 0c93780..195c9e5 100644
--- a/tools/droiddoc/templates-sac/assets/js/docs.js
+++ b/tools/droiddoc/templates-sac/assets/js/docs.js
@@ -1630,7 +1630,10 @@
             } else {
               // otherwise, results are already showing, so allow ajax to auto refresh the results
               // and ignore this Enter press to avoid the reload.
-              return false;
+              // return false;
+              //
+              // For now, we're not using AJAX so we respond to every Enter.
+              return true;
             }
         } else if (kd && gSelectedIndex >= 0) {
             window.location = $("a",$('#search_filtered li')[gSelectedIndex]).attr("href");
@@ -1691,6 +1694,11 @@
 
 
         // Search for Google matches
+        /*
+         *  Commented this out because GOOGLE_DATA not defined for us and code
+         *  causes an error.  This probably has to do with the missing
+         *  gms_lists.js file in SAC. TODO figure it all out.
+         *
         for (var i=0; i<GOOGLE_DATA.length; i++) {
             var s = GOOGLE_DATA[i];
             if (text.length != 0 &&
@@ -1703,6 +1711,7 @@
         for (var i=0; i<gGoogleMatches.length; i++) {
             var s = gGoogleMatches[i];
         }
+        */
 
         highlight_autocomplete_result_labels(text);
         sync_selection_table(toroot);
@@ -1830,81 +1839,138 @@
   $("#search_autocomplete").val("").blur();
 
   // reset the ajax search callback to nothing, so results don't appear unless ENTER
-  searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
+  //  searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
   return false;
 }
 
 
-
 /* ########################################################## */
 /* ################  CUSTOM SEARCH ENGINE  ################## */
 /* ########################################################## */
 
-google.load('search', '1');
-var searchControl;
+// TODO, add localized search.
+function getLangPref() {
+  return "en";
+}
+
+// Package of functions that does custom search, from DAC redesign.
+(function($) {
+  var LANG;
+
+  function getSearchLang() {
+    if (!LANG) {
+      LANG = getLangPref();
+
+      // Fix zh-cn to be zh-CN.
+      LANG = LANG.replace(/-\w+/, function(m) { return m.toUpperCase(); });
+    }
+    return LANG;
+  }
+
+  function customSearch(query, start) {
+    var searchParams = {
+      // Keys for SAC
+      cx:'016258643462168859875:qqpm8fiwgc0',
+      key: 'AIzaSyBOWHD3JAF6Q9LIJ4NiahGAF70W7iDAI9M',
+
+      // Keys for DAC
+      // cx: '000521750095050289010:zpcpi1ea4s8',
+      // key: 'AIzaSyCFhbGnjW06dYwvRCU8h_zjdpS4PYYbEe8',
+
+      q: query,
+      start: start || 1,
+      num: 6,
+      hl: getSearchLang(),
+      fields: 'queries,items(pagemap,link,title,htmlSnippet,formattedUrl)'
+    };
+
+    return $.get('https://content.googleapis.com/customsearch/v1?' +  $.param(searchParams));
+  }
+
+  function renderResults(el, results) {
+    if (!results.items) {
+      el.append($('<div>').text('No results'));
+      return;
+    }
+
+    for (var i = 0; i < results.items.length; i++) {
+      var item = results.items[i];
+      // No thumbnail images in SAC.
+      // var hasImage = item.pagemap && item.pagemap.cse_thumbnail;
+      var sectionMatch = item.link.match(/source\.android\.com\/(\w*)/);
+      var section = (sectionMatch && sectionMatch[1]) || 'blog';
+
+      var entry = $('<div>').addClass('dac-custom-search-entry cols');
+
+// No thumbnail images in SAC.
+//      if (hasImage) {
+//        var image = item.pagemap.cse_thumbnail[0];
+//        entry.append($('<div>').addClass('col-1of6')
+//          .append($('<div>').addClass('dac-custom-search-image').css('background-image', 'url(' + image.src + ')')));
+//      }
+// entry.append($('<div>').addClass(hasImage ? 'col-5of6' : 'col-6of6')
+      entry.append($('<div>')
+        .append($('<p>').addClass('dac-custom-search-section').text(section))
+        .append(
+          $('<a>').text(item.title).attr('href', item.link).wrap('<h2>').parent().addClass('dac-custom-search-title')
+        )
+        .append($('<p>').addClass('dac-custom-search-snippet').html(item.htmlSnippet.replace(/<br>/g, '')))
+        .append($('<a>').addClass('dac-custom-search-link').text(item.formattedUrl).attr('href', item.link)));
+
+      el.append(entry);
+    }
+
+    if (results.queries.nextPage) {
+      var loadMoreButton = $('<button id="dac-custom-search-load-more">')
+        .addClass('dac-custom-search-load-more')
+        .text('Load more')
+        .click(function() {
+          loadMoreResults(el, results);
+        });
+
+      el.append(loadMoreButton);
+    }
+  }
+
+  function loadMoreResults(el, results) {
+    var query = results.queries.request.searchTerms;
+    var start = results.queries.nextPage.startIndex;
+    var loadMoreButton = el.find('#dac-custom-search-load-more');
+
+    loadMoreButton.text('Loading more...');
+
+    customSearch(query, start).then(function(results) {
+      loadMoreButton.remove();
+      renderResults(el, results);
+    });
+  }
+
+  $.fn.customSearch = function(query) {
+    var el = $(this);
+
+    customSearch(query).then(function(results) {
+      el.empty();
+      renderResults(el, results);
+    });
+  };
+})(jQuery);
+
 
 function loadSearchResults() {
-  document.getElementById("search_autocomplete").style.color = "#000";
 
-  // create search control
-  searchControl = new google.search.SearchControl();
-
-  // use our existing search form and use tabs when multiple searchers are used
-  drawOptions = new google.search.DrawOptions();
-  drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
-  drawOptions.setInput(document.getElementById("search_autocomplete"));
-
-  // configure search result options
-  searchOptions = new google.search.SearcherOptions();
-  searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
-
-  // Configure s.a.c searchers
-  sacSiteSearcher = new google.search.WebSearch();
-  sacSiteSearcher.setUserDefinedLabel("All");
-  sacSiteSearcher.setSiteRestriction("http://source.android.com/");
-
-  sourceSearcher = new google.search.WebSearch();
-  sourceSearcher.setUserDefinedLabel("Source");
-  sourceSearcher.setSiteRestriction("http://source.android.com/source/");
-
-  devicesSearcher = new google.search.WebSearch();
-  devicesSearcher.setUserDefinedLabel("Devices");
-  devicesSearcher.setSiteRestriction("http://source.android.com/devices/");
-
-  securitySearcher = new google.search.WebSearch();
-  securitySearcher.setUserDefinedLabel("Security");
-  securitySearcher.setSiteRestriction("http://source.android.com/security/");
-
-  compatibilitySearcher = new google.search.WebSearch();
-  compatibilitySearcher.setUserDefinedLabel("Compatibility");
-  compatibilitySearcher.setSiteRestriction("http://source.android.com/compatibility/");
-
-  // add each searcher to the search control
-  searchControl.addSearcher(sacSiteSearcher, searchOptions);
-  searchControl.addSearcher(sourceSearcher, searchOptions);
-  searchControl.addSearcher(devicesSearcher, searchOptions);
-  searchControl.addSearcher(securitySearcher, searchOptions);
-  searchControl.addSearcher(compatibilitySearcher, searchOptions);
+  // Draw the search results box
+  //searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
+  $(searchResults).append('<div class="leftSearchControl"></div>');
 
 
-  // configure result options
-  searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
-  searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
-  searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
-  searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
-
-  // upon ajax search, refresh the url and search title
-  searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
-    updateResultTitle(query);
-    var query = document.getElementById('search_autocomplete').value;
-    location.hash = 'q=' + query;
-  });
-
-  // draw the search results box
-  searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
+  // Refresh the url and search title
+  var query = document.getElementById('search_autocomplete').value || getQuery(location.hash);
+  updateResultTitle(query);
+  location.hash = 'q=' + query;
 
   // get query and execute the search
-  searchControl.execute(decodeURI(getQuery(location.hash)));
+  //searchControl.execute(decodeURI(getQuery(location.hash)));
+  $(leftSearchControl).customSearch(getQuery(location.hash));
 
   document.getElementById("search_autocomplete").focus();
   addTabListeners();
@@ -1912,7 +1978,9 @@
 // End of loadSearchResults
 
 google.setOnLoadCallback(function(){
-  if (location.hash.indexOf("q=") == -1) {
+
+  var query = decodeURI(getQuery(location.hash));
+  if (location.hash.indexOf("q=") == -1 || query == '') {
     // if there's no query in the url, don't search and make sure results are hidden
     $('#searchResults').hide();
     return;
@@ -1937,7 +2005,8 @@
 
   // Otherwise, we have a search to do
   var query = decodeURI(getQuery(location.hash));
-  searchControl.execute(query);
+  //searchControl.execute(query);
+  $('#leftSearchControl').customSearch(query);
   $('#searchResults').slideDown('slow');
   $("#search_autocomplete").focus();
   $(".search .close").removeClass("hide");
@@ -1946,7 +2015,10 @@
 });
 
 function updateResultTitle(query) {
-  $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
+  $("#searchTitle").html("Results for <em>" + (query) + "</em>");
+// For some reason, the escapeHTML function wasn't working for me.  TODO fix
+// this by copying in a comparable library function.
+//  $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
 }
 
 // forcefully regain key-up event control (previously jacked by search api)
@@ -1991,11 +2063,6 @@
 }
 
 
-
-
-
-
-
 /* ######################################################## */
 /* #################  JAVADOC REFERENCE ################### */
 /* ######################################################## */
@@ -2077,7 +2144,9 @@
 
   // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
   var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
-  selectedLevelItem.setAttribute('selected',true);
+//  Another piece of functionality that we don't use that produces an error.
+//  TODO figure it all out.
+//  selectedLevelItem.setAttribute('selected',true);
 }
 
 function changeApiLevel() {
diff --git a/tools/droiddoc/templates-sdk/sdkpage.cs b/tools/droiddoc/templates-sdk/sdkpage.cs
index 3a3a9a3..47c2992 100644
--- a/tools/droiddoc/templates-sdk/sdkpage.cs
+++ b/tools/droiddoc/templates-sdk/sdkpage.cs
@@ -353,7 +353,7 @@
   <tr>
     <!-- blank TD from Windows rowspan -->
     <td>
-  <a onclick="return onDownload(this,false,true)"
+  <a onclick="return onDownload(this,false,true)" id="win-bundle-notools"
     href="https://dl.google.com/dl/android/studio/install/<?cs var:studio.version ?>/<?cs var:studio.win_notools_exe_download ?>"
     ><?cs var:studio.win_notools_exe_download ?></a><br>(No SDK tools included)
     </td>
@@ -364,7 +364,7 @@
   <tr>
     <!-- blank TD from Windows rowspan -->
     <td>
-  <a onclick="return onDownload(this,false,true)"
+  <a onclick="return onDownload(this,false,true)" id="win-bundle-zip"
     href="https://dl.google.com/dl/android/studio/ide-zips/<?cs var:studio.version ?>/<?cs var:studio.win_bundle_download ?>"
     ><?cs var:studio.win_bundle_download ?></a>
     </td>
diff --git a/tools/ijar/Android.mk b/tools/ijar/Android.mk
index 356e109..8b2a02c 100644
--- a/tools/ijar/Android.mk
+++ b/tools/ijar/Android.mk
@@ -6,9 +6,11 @@
 LOCAL_PATH:= $(call my-dir)
 
 include $(CLEAR_VARS)
-LOCAL_CPP_EXTENSION := cc
+LOCAL_CPP_EXTENSION := .cc
 LOCAL_SRC_FILES := classfile.cc ijar.cc zip.cc
-LOCAL_CFLAGS += -Wall
+LOCAL_CFLAGS += -Wall -Werror
 LOCAL_SHARED_LIBRARIES := libz-host
 LOCAL_MODULE := ijar
+# libc++ is not supported for TARGET_BUILD_APPS builds
+LOCAL_CXX_STL := libstdc++
 include $(BUILD_HOST_EXECUTABLE)
diff --git a/tools/ijar/classfile.cc b/tools/ijar/classfile.cc
index 5d12cc2..e0cf42e 100644
--- a/tools/ijar/classfile.cc
+++ b/tools/ijar/classfile.cc
@@ -483,12 +483,12 @@
     // We keep an entry if the constant referring to the inner class is already
     // kept. Then we mark its outer class and its class name as kept, too, then
     // iterate until a fixed point is reached.
-    int entry_count;
+    size_t entry_count;
     int iteration = 0;
 
     do {
       entry_count = kept_entries.size();
-      for (int i_entry = 0; i_entry < entries_.size(); ++i_entry) {
+      for (size_t i_entry = 0; i_entry < entries_.size(); ++i_entry) {
         Entry* entry = entries_[i_entry];
         if (entry->inner_class_info->Kept() ||
             used_class_names.find(entry->inner_class_info->Display())
@@ -632,7 +632,7 @@
   }
 
   virtual void ExtractClassNames() {
-    for (int i = 0; i < values_.size(); i++) {
+    for (size_t i = 0; i < values_.size(); i++) {
       values_[i]->ExtractClassNames();
     }
   }
@@ -800,8 +800,8 @@
   };
 
   struct EmptyInfo : TargetInfo {
-    void Write(u1 *&p) {}
-    static EmptyInfo *Read(const u1 *&p) {
+    void Write(u1 *&) {}
+    static EmptyInfo *Read(const u1 *&) {
       return new EmptyInfo;
     }
   };
@@ -1007,7 +1007,7 @@
 // compiler to generate warning messages.
 struct DeprecatedAttribute : Attribute {
 
-  static DeprecatedAttribute* Read(const u1 *&p, Constant *attribute_name) {
+  static DeprecatedAttribute* Read(const u1 *&, Constant *attribute_name) {
     DeprecatedAttribute *attr = new DeprecatedAttribute;
     attr->attribute_name_ = attribute_name;
     return attr;
@@ -1041,7 +1041,7 @@
   }
 
   virtual void ExtractClassNames() {
-    for (int i = 0; i < annotations_.size(); i++) {
+    for (size_t i = 0; i < annotations_.size(); i++) {
       annotations_[i]->ExtractClassNames();
     }
   }
@@ -1112,7 +1112,7 @@
 // and RuntimeInvisibleTypeAnnotations.
 struct TypeAnnotationsAttribute : Attribute {
   static TypeAnnotationsAttribute* Read(const u1 *&p, Constant *attribute_name,
-                                        u4 attribute_length) {
+                                        u4) {
     auto attr = new TypeAnnotationsAttribute;
     attr->attribute_name_ = attribute_name;
     u2 num_annotations = get_u2be(p);
@@ -1124,7 +1124,7 @@
   }
 
   virtual void ExtractClassNames() {
-    for (int i = 0; i < type_annotations_.size(); i++) {
+    for (size_t i = 0; i < type_annotations_.size(); i++) {
       type_annotations_[i]->ExtractClassNames();
     }
   }
@@ -1181,7 +1181,7 @@
   }
 
   void ExtractClassNames() {
-    for (int i = 0; i < attributes.size(); i++) {
+    for (size_t i = 0; i < attributes.size(); i++) {
       attributes[i]->ExtractClassNames();
     }
   }
@@ -1739,7 +1739,7 @@
   members.insert(members.end(), fields.begin(), fields.end());
   members.insert(members.end(), methods.begin(), methods.end());
   ExtractClassNames();
-  for (int i = 0; i < members.size(); i++) {
+  for (size_t i = 0; i < members.size(); i++) {
     Member *member = members[i];
     size_t idx = 0;
     devtools_ijar::ExtractClassNames(member->descriptor->Display(), &idx);
diff --git a/tools/releasetools/build_image.py b/tools/releasetools/build_image.py
index cd750e8..2b8d4ee 100755
--- a/tools/releasetools/build_image.py
+++ b/tools/releasetools/build_image.py
@@ -350,7 +350,8 @@
   elif fs_type.startswith("squash"):
     build_command = ["mksquashfsimage.sh"]
     build_command.extend([in_dir, out_file])
-    build_command.extend(["-s"])
+    if "squashfs_sparse_flag" in prop_dict:
+      build_command.extend([prop_dict["squashfs_sparse_flag"]])
     build_command.extend(["-m", prop_dict["mount_point"]])
     if target_out:
       build_command.extend(["-d", target_out])
@@ -478,6 +479,7 @@
 
   common_props = (
       "extfs_sparse_flag",
+      "squashfs_sparse_flag",
       "mkyaffs2_extra_flags",
       "selinux_fc",
       "skip_fsck",
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 2c8bbc6..ee0cdf9 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -44,6 +44,7 @@
 
     self.search_path = platform_search_path.get(sys.platform, None)
     self.signapk_path = "framework/signapk.jar"  # Relative to search_path
+    self.signapk_shared_library_path = "lib64"   # Relative to search_path
     self.extra_signapk_args = []
     self.java_path = "java"  # Use the one on the path by default.
     self.java_args = "-Xmx2048m" # JVM Args
@@ -588,37 +589,29 @@
   return key_passwords
 
 
-def SignFile(input_name, output_name, key, password, align=None,
-             whole_file=False):
+def SignFile(input_name, output_name, key, password, whole_file=False):
   """Sign the input_name zip/jar/apk, producing output_name.  Use the
   given key and password (the latter may be None if the key does not
   have a password.
 
-  If align is an integer > 1, zipalign is run to align stored files in
-  the output zip on 'align'-byte boundaries.
-
   If whole_file is true, use the "-w" option to SignApk to embed a
   signature that covers the whole file in the archive comment of the
   zip file.
   """
 
-  if align == 0 or align == 1:
-    align = None
+  java_library_path = os.path.join(
+      OPTIONS.search_path, OPTIONS.signapk_shared_library_path)
 
-  if align:
-    temp = tempfile.NamedTemporaryFile()
-    sign_name = temp.name
-  else:
-    sign_name = output_name
-
-  cmd = [OPTIONS.java_path, OPTIONS.java_args, "-jar",
+  cmd = [OPTIONS.java_path, OPTIONS.java_args,
+         "-Djava.library.path=" + java_library_path,
+         "-jar",
          os.path.join(OPTIONS.search_path, OPTIONS.signapk_path)]
   cmd.extend(OPTIONS.extra_signapk_args)
   if whole_file:
     cmd.append("-w")
   cmd.extend([key + OPTIONS.public_key_suffix,
               key + OPTIONS.private_key_suffix,
-              input_name, sign_name])
+              input_name, output_name])
 
   p = Run(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
   if password is not None:
@@ -627,13 +620,6 @@
   if p.returncode != 0:
     raise ExternalError("signapk.jar failed: return code %s" % (p.returncode,))
 
-  if align:
-    p = Run(["zipalign", "-f", "-p", str(align), sign_name, output_name])
-    p.communicate()
-    if p.returncode != 0:
-      raise ExternalError("zipalign failed: return code %s" % (p.returncode,))
-    temp.close()
-
 
 def CheckSize(data, target, info_dict):
   """Check the data string passed against the max size limit, if
@@ -738,7 +724,8 @@
   try:
     opts, args = getopt.getopt(
         argv, "hvp:s:x:" + extra_opts,
-        ["help", "verbose", "path=", "signapk_path=", "extra_signapk_args=",
+        ["help", "verbose", "path=", "signapk_path=",
+         "signapk_shared_library_path=", "extra_signapk_args=",
          "java_path=", "java_args=", "public_key_suffix=",
          "private_key_suffix=", "boot_signer_path=", "boot_signer_args=",
          "verity_signer_path=", "verity_signer_args=", "device_specific=",
@@ -759,6 +746,8 @@
       OPTIONS.search_path = a
     elif o in ("--signapk_path",):
       OPTIONS.signapk_path = a
+    elif o in ("--signapk_shared_library_path",):
+      OPTIONS.signapk_shared_library_path = a
     elif o in ("--extra_signapk_args",):
       OPTIONS.extra_signapk_args = shlex.split(a)
     elif o in ("--java_path",):
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index b3785ac..d923cc8 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -284,8 +284,8 @@
     cmd = ['apply_patch("%s",\0"%s",\0%s,\0%d'
            % (srcfile, tgtfile, tgtsha1, tgtsize)]
     for i in range(0, len(patchpairs), 2):
-      cmd.append(',\0%s, package_extract_file("%s")' % patchpairs[i:i+2])
-    cmd.append(');')
+      cmd.append(',\0%s,\0package_extract_file("%s")' % patchpairs[i:i+2])
+    cmd.append(') ||\n    abort("Failed to apply patch to %s");' % (srcfile,))
     cmd = "".join(cmd)
     self.script.append(self.WordWrap(cmd))
 
diff --git a/tools/releasetools/ota_from_target_files.py b/tools/releasetools/ota_from_target_files.py
index fd57b93..5259ede 100755
--- a/tools/releasetools/ota_from_target_files.py
+++ b/tools/releasetools/ota_from_target_files.py
@@ -94,6 +94,11 @@
 
   --gen_verify
       Generate an OTA package that verifies the partitions.
+
+  --log_diff <file>
+      Generate a log file that shows the differences in the source and target
+      builds for an incremental package. This option is only meaningful when
+      -i is specified.
 """
 
 import sys
@@ -137,6 +142,7 @@
 OPTIONS.cache_size = None
 OPTIONS.stash_threshold = 0.8
 OPTIONS.gen_verify = False
+OPTIONS.log_diff = None
 
 def MostPopularKey(d, default):
   """Given a dict, return the key corresponding to the largest
@@ -1566,13 +1572,13 @@
   if OPTIONS.verify and system_diff:
     script.Print("Remounting and verifying system partition files...")
     script.Unmount("/system")
-    script.Mount("/system")
+    script.Mount("/system", recovery_mount_options)
     system_diff.EmitExplicitTargetVerification(script)
 
   if OPTIONS.verify and vendor_diff:
     script.Print("Remounting and verifying vendor partition files...")
     script.Unmount("/vendor")
-    script.Mount("/vendor")
+    script.Mount("/vendor", recovery_mount_options)
     vendor_diff.EmitExplicitTargetVerification(script)
   script.AddToZip(target_zip, output_zip, input_path=OPTIONS.updater_binary)
 
@@ -1631,6 +1637,8 @@
                          "a float" % (a, o))
     elif o == "--gen_verify":
       OPTIONS.gen_verify = True
+    elif o == "--log_diff":
+      OPTIONS.log_diff = a
     else:
       return False
     return True
@@ -1656,7 +1664,8 @@
                                  "verify",
                                  "no_fallback_to_full",
                                  "stash_threshold=",
-                                 "gen_verify"
+                                 "gen_verify",
+                                 "log_diff=",
                              ], extra_option_handler=option_handler)
 
   if len(args) != 2:
@@ -1743,6 +1752,14 @@
       common.DumpInfoDict(OPTIONS.source_info_dict)
     try:
       WriteIncrementalOTAPackage(input_zip, source_zip, output_zip)
+      if OPTIONS.log_diff:
+        out_file = open(OPTIONS.log_diff, 'w')
+        import target_files_diff
+        target_files_diff.recursiveDiff('',
+                                        OPTIONS.source_tmp,
+                                        OPTIONS.input_tmp,
+                                        out_file)
+        out_file.close()
     except ValueError:
       if not OPTIONS.fallback_to_full:
         raise
diff --git a/tools/releasetools/sign_target_files_apks.py b/tools/releasetools/sign_target_files_apks.py
index cbf78a1..baf60f5 100755
--- a/tools/releasetools/sign_target_files_apks.py
+++ b/tools/releasetools/sign_target_files_apks.py
@@ -134,7 +134,7 @@
 
   signed = tempfile.NamedTemporaryFile()
 
-  common.SignFile(unsigned.name, signed.name, keyname, pw, align=4)
+  common.SignFile(unsigned.name, signed.name, keyname, pw)
 
   data = signed.read()
   unsigned.close()
diff --git a/tools/target_files_diff.py b/tools/releasetools/target_files_diff.py
similarity index 100%
rename from tools/target_files_diff.py
rename to tools/releasetools/target_files_diff.py
diff --git a/tools/signapk/Android.mk b/tools/signapk/Android.mk
index 620ccb1..da1501b 100644
--- a/tools/signapk/Android.mk
+++ b/tools/signapk/Android.mk
@@ -21,11 +21,16 @@
 LOCAL_MODULE := signapk
 LOCAL_SRC_FILES := SignApk.java
 LOCAL_JAR_MANIFEST := SignApk.mf
-LOCAL_STATIC_JAVA_LIBRARIES := bouncycastle-host bouncycastle-bcpkix-host
+LOCAL_STATIC_JAVA_LIBRARIES := bouncycastle-host bouncycastle-bcpkix-host conscrypt-host
+LOCAL_REQUIRED_MODULES := libconscrypt_openjdk_jni
 include $(BUILD_HOST_JAVA_LIBRARY)
 
 ifeq ($(TARGET_BUILD_APPS),)
-# The post-build signing tools need signapk.jar, but we don't
-# need this if we're just doing unbundled apps.
-$(call dist-for-goals,droidcore,$(LOCAL_INSTALLED_MODULE))
+# The post-build signing tools need signapk.jar and its shared libraries,
+# but we don't need this if we're just doing unbundled apps.
+my_dist_files := $(LOCAL_INSTALLED_MODULE) \
+    $(HOST_OUT_SHARED_LIBRARIES)/libconscrypt_openjdk_jni$(HOST_SHLIB_SUFFIX)
+
+$(call dist-for-goals,droidcore,$(my_dist_files))
+my_dist_files :=
 endif
diff --git a/tools/signapk/SignApk.java b/tools/signapk/SignApk.java
index 740a343..5afb8d1 100644
--- a/tools/signapk/SignApk.java
+++ b/tools/signapk/SignApk.java
@@ -34,6 +34,7 @@
 import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
 import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
 import org.bouncycastle.util.encoders.Base64;
+import org.conscrypt.OpenSSLProvider;
 
 import java.io.Console;
 import java.io.BufferedReader;
@@ -110,8 +111,6 @@
 
     private static final String OTACERT_NAME = "META-INF/com/android/otacert";
 
-    private static Provider sBouncyCastleProvider;
-
     // bitmasks for which hash algorithms we need the manifest to include.
     private static final int USE_SHA1 = 1;
     private static final int USE_SHA256 = 2;
@@ -451,12 +450,10 @@
 
         CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
         ContentSigner signer = new JcaContentSignerBuilder(getSignatureAlgorithm(publicKey))
-            .setProvider(sBouncyCastleProvider)
             .build(privateKey);
         gen.addSignerInfoGenerator(
             new JcaSignerInfoGeneratorBuilder(
                 new JcaDigestCalculatorProviderBuilder()
-                .setProvider(sBouncyCastleProvider)
                 .build())
             .setDirectSignature(true)
             .build(signer, publicKey));
@@ -476,7 +473,7 @@
      * more efficient.
      */
     private static void copyFiles(Manifest manifest, JarFile in, JarOutputStream out,
-                                  long timestamp, int alignment) throws IOException {
+                                  long timestamp, int defaultAlignment) throws IOException {
         byte[] buffer = new byte[4096];
         int num;
 
@@ -515,6 +512,7 @@
                 offset += 4;
                 firstEntry = false;
             }
+            int alignment = getStoredEntryDataAlignment(name, defaultAlignment);
             if (alignment > 0 && (offset % alignment != 0)) {
                 // Set the "extra data" of the entry to between 1 and
                 // alignment-1 bytes, to make the file data begin at
@@ -555,6 +553,24 @@
         }
     }
 
+    /**
+     * Returns the multiple (in bytes) at which the provided {@code STORED} entry's data must start
+     * relative to start of file or {@code 0} if alignment of this entry's data is not important.
+     */
+    private static int getStoredEntryDataAlignment(String entryName, int defaultAlignment) {
+        if (defaultAlignment <= 0) {
+            return 0;
+        }
+
+        if (entryName.endsWith(".so")) {
+            // Align .so contents to memory page boundary to enable memory-mapped
+            // execution.
+            return 4096;
+        } else {
+            return defaultAlignment;
+        }
+    }
+
     private static class WholeFileSignerOutputStream extends FilterOutputStream {
         private boolean closing = false;
         private ByteArrayOutputStream footer = new ByteArrayOutputStream();
@@ -860,8 +876,13 @@
     public static void main(String[] args) {
         if (args.length < 4) usage();
 
-        sBouncyCastleProvider = new BouncyCastleProvider();
-        Security.addProvider(sBouncyCastleProvider);
+        // Install Conscrypt as the highest-priority provider. Its crypto primitives are faster than
+        // the standard or Bouncy Castle ones.
+        Security.insertProviderAt(new OpenSSLProvider(), 1);
+        // Install Bouncy Castle (as the lowest-priority provider) because Conscrypt does not offer
+        // DSA which may still be needed.
+        // TODO: Stop installing Bouncy Castle provider once DSA is no longer needed.
+        Security.addProvider(new BouncyCastleProvider());
 
         boolean signWholeFile = false;
         String providerClass = null;