Merge "Allow USE_GOMA=true without explicit USE_NINJA=true"
diff --git a/core/Makefile b/core/Makefile
index 89d0431..0f200f9 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -1250,6 +1250,13 @@
 # platform.zip depends on $(INTERNAL_VENDORIMAGE_FILES).
 $(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_VENDORIMAGE_FILES)
 
+INSTALLED_FILES_FILE_VENDOR := $(PRODUCT_OUT)/installed-files-vendor.txt
+$(INSTALLED_FILES_FILE_VENDOR) : $(INTERNAL_VENDORIMAGE_FILES)
+	@echo Installed file list: $@
+	@mkdir -p $(dir $@)
+	@rm -f $@
+	$(hide) build/tools/fileslist.py $(TARGET_OUT_VENDOR) > $@
+
 vendorimage_intermediates := \
     $(call intermediates-dir-for,PACKAGING,vendor)
 BUILT_VENDORIMAGE_TARGET := $(PRODUCT_OUT)/vendor.img
@@ -1267,7 +1274,7 @@
 
 # We just build this directly to the install location.
 INSTALLED_VENDORIMAGE_TARGET := $(BUILT_VENDORIMAGE_TARGET)
-$(INSTALLED_VENDORIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) $(INTERNAL_VENDORIMAGE_FILES)
+$(INSTALLED_VENDORIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) $(INTERNAL_VENDORIMAGE_FILES) $(INSTALLED_FILES_FILE_VENDOR)
 	$(build-vendorimage-target)
 
 .PHONY: vendorimage-nodeps
@@ -1285,6 +1292,30 @@
 # -----------------------------------------------------------------
 # host tools needed to build dist and OTA packages
 
+build_ota_package := true
+ifeq ($(TARGET_SKIP_OTA_PACKAGE),true)
+build_ota_package := false
+endif
+ifeq ($(BUILD_OS),darwin)
+build_ota_package := false
+endif
+ifneq ($(strip $(SANITIZE_TARGET)),)
+build_ota_package := false
+endif
+ifeq ($(TARGET_PRODUCT),sdk)
+build_ota_package := false
+endif
+ifneq ($(filter generic%,$(TARGET_DEVICE)),)
+build_ota_package := false
+endif
+ifeq ($(TARGET_NO_KERNEL),true)
+build_ota_package := false
+endif
+ifeq ($(recovery_fstab),)
+build_ota_package := false
+endif
+
+ifeq ($(build_ota_package),true)
 OTATOOLS :=  $(HOST_OUT_EXECUTABLES)/minigzip \
   $(HOST_OUT_EXECUTABLES)/aapt \
   $(HOST_OUT_EXECUTABLES)/mkbootfs \
@@ -1343,6 +1374,7 @@
 .PHONY: otatools-package
 otatools-package: $(BUILT_OTATOOLS_PACKAGE)
 
+endif # build_ota_package
 
 # -----------------------------------------------------------------
 # A zip of the directories that map to the target filesystem.
@@ -1376,7 +1408,7 @@
     $(call intermediates-dir-for,EXECUTABLES,sqlite3,,,$(TARGET_PREFER_32_BIT))/sqlite3
 
 # We can't build static executables when SANITIZE_TARGET=address
-ifneq (address,$(SANITIZE_TARGET))
+ifeq ($(strip $(SANITIZE_TARGET)),)
 built_ota_tools += \
     $(call intermediates-dir-for,EXECUTABLES,check_prereq,,,$(TARGET_PREFER_32_BIT))/check_prereq \
     $(call intermediates-dir-for,EXECUTABLES,applypatch_static,,,$(TARGET_PREFER_32_BIT))/applypatch_static \
@@ -1519,7 +1551,7 @@
 	# OTA scripts are only interested in fingerprint related properties
 	$(hide) echo "oem_fingerprint_properties=$(OEM_THUMBPRINT_PROPERTIES)" >> $(zip_root)/META/misc_info.txt
 endif
-ifeq ($(SANITIZE_TARGET),address)
+ifneq ($(strip $(SANITIZE_TARGET)),)
 	# We need to create userdata.img with real data because the instrumented libraries are in userdata.img.
 	$(hide) echo "userdata_img_with_data=true" >> $(zip_root)/META/misc_info.txt
 endif
@@ -1554,26 +1586,6 @@
 $(call dist-for-goals, target-files-package, $(BUILT_TARGET_FILES_PACKAGE))
 endif
 
-build_ota_package := true
-ifeq ($(BUILD_OS),darwin)
-build_ota_package := false
-endif
-ifeq ($(SANITIZE_TARGET),address)
-build_ota_package := false
-endif
-ifeq ($(TARGET_PRODUCT),sdk)
-build_ota_package := false
-endif
-ifneq ($(filter generic%,$(TARGET_DEVICE)),)
-build_ota_package := false
-endif
-ifeq ($(TARGET_NO_KERNEL),true)
-build_ota_package := false
-endif
-ifeq ($(recovery_fstab),)
-build_ota_package := false
-endif
-
 ifeq ($(build_ota_package),true)
 # -----------------------------------------------------------------
 # OTA update package
diff --git a/core/base_rules.mk b/core/base_rules.mk
index b936859..21b59a3 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -34,14 +34,27 @@
   ifneq ($(LOCAL_IS_HOST_MODULE),true)
     $(error $(LOCAL_PATH): LOCAL_IS_HOST_MODULE must be "true" or empty, not "$(LOCAL_IS_HOST_MODULE)")
   endif
-  my_prefix := HOST_
+  ifeq ($(LOCAL_HOST_PREFIX),)
+    my_prefix := HOST_
+  else
+    my_prefix := $(LOCAL_HOST_PREFIX)
+  endif
   my_host := host-
 else
   my_prefix := TARGET_
   my_host :=
 endif
 
+ifeq ($(my_prefix),HOST_CROSS_)
+  my_host_cross := true
+else
+  my_host_cross :=
+endif
+
 my_module_tags := $(LOCAL_MODULE_TAGS)
+ifeq ($(my_host_cross),true)
+  my_module_tags :=
+endif
 
 ###########################################################
 ## Validate and define fallbacks for input LOCAL_* variables.
@@ -150,15 +163,18 @@
 my_register_name := $(LOCAL_MODULE)$($(my_prefix)2ND_ARCH_MODULE_SUFFIX)
 endif
 endif
+ifeq ($(my_host_cross),true)
+  my_register_name := host_cross_$(LOCAL_MODULE)
+endif
 # Make sure that this IS_HOST/CLASS/MODULE combination is unique.
 module_id := MODULE.$(if \
-    $(LOCAL_IS_HOST_MODULE),HOST,TARGET).$(LOCAL_MODULE_CLASS).$(my_register_name)
+    $(LOCAL_IS_HOST_MODULE),$($(my_prefix)OS),TARGET).$(LOCAL_MODULE_CLASS).$(my_register_name)
 ifdef $(module_id)
 $(error $(LOCAL_PATH): $(module_id) already defined by $($(module_id)))
 endif
 $(module_id) := $(LOCAL_PATH)
 
-intermediates := $(call local-intermediates-dir,,$(LOCAL_2ND_ARCH_VAR_PREFIX))
+intermediates := $(call local-intermediates-dir,,$(LOCAL_2ND_ARCH_VAR_PREFIX),$(my_host_cross))
 intermediates.COMMON := $(call local-intermediates-dir,COMMON)
 generated_sources_dir := $(call local-generated-sources-dir)
 
@@ -194,297 +210,19 @@
 # Assemble the list of targets to create PRIVATE_ variables for.
 LOCAL_INTERMEDIATE_TARGETS += $(LOCAL_BUILT_MODULE)
 
-
 ###########################################################
-## AIDL: Compile .aidl files to .java
-###########################################################
-
-aidl_sources := $(filter %.aidl,$(LOCAL_SRC_FILES))
-
-ifneq ($(strip $(aidl_sources)),)
-
-aidl_java_sources := $(patsubst %.aidl,%.java,$(addprefix $(intermediates.COMMON)/src/, $(aidl_sources)))
-aidl_sources := $(addprefix $(TOP_DIR)$(LOCAL_PATH)/, $(aidl_sources))
-
-aidl_preprocess_import :=
-LOCAL_SDK_VERSION:=$(strip $(LOCAL_SDK_VERSION))
-ifdef LOCAL_SDK_VERSION
-ifneq ($(filter current system_current, $(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS)),)
-  # LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS
-  aidl_preprocess_import := $(TARGET_OUT_COMMON_INTERMEDIATES)/framework.aidl
-else
-  aidl_preprocess_import := $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_VERSION)/framework.aidl
-endif # not current or system_current
-else
-# build against the platform.
-LOCAL_AIDL_INCLUDES += $(FRAMEWORKS_BASE_JAVA_SRC_DIRS)
-endif # LOCAL_SDK_VERSION
-$(aidl_java_sources): PRIVATE_AIDL_FLAGS := -b $(addprefix -p,$(aidl_preprocess_import)) -I$(LOCAL_PATH) -I$(LOCAL_PATH)/src $(addprefix -I,$(LOCAL_AIDL_INCLUDES))
-
-$(aidl_java_sources): $(intermediates.COMMON)/src/%.java: \
-        $(TOPDIR)$(LOCAL_PATH)/%.aidl \
-        $(LOCAL_MODULE_MAKEFILE) \
-        $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-        $(AIDL) \
-        $(aidl_preprocess_import)
-	$(transform-aidl-to-java)
--include $(aidl_java_sources:%.java=%.P)
-
-else
-aidl_java_sources :=
-endif
-
-###########################################################
-## logtags: Add .logtags files to global list, emit java source
+## logtags: Add .logtags files to global list
 ###########################################################
 
 logtags_sources := $(filter %.logtags,$(LOCAL_SRC_FILES))
 
 ifneq ($(strip $(logtags_sources)),)
-
 event_log_tags := $(addprefix $(LOCAL_PATH)/,$(logtags_sources))
-
-# Emit a java source file with constants for the tags, if
-# LOCAL_MODULE_CLASS is "APPS" or "JAVA_LIBRARIES".
-ifneq ($(filter $(LOCAL_MODULE_CLASS),APPS JAVA_LIBRARIES),)
-
-logtags_java_sources := $(patsubst %.logtags,%.java,$(addprefix $(intermediates.COMMON)/src/, $(logtags_sources)))
-logtags_sources := $(addprefix $(TOP_DIR)$(LOCAL_PATH)/, $(logtags_sources))
-
-$(logtags_java_sources): $(intermediates.COMMON)/src/%.java: $(TOPDIR)$(LOCAL_PATH)/%.logtags $(TARGET_OUT_COMMON_INTERMEDIATES)/all-event-log-tags.txt
-	$(transform-logtags-to-java)
-
-endif
-
 else
-logtags_java_sources :=
 event_log_tags :=
 endif
 
 ###########################################################
-## .proto files: Compile proto files to .java
-###########################################################
-proto_sources := $(filter %.proto,$(LOCAL_SRC_FILES))
-# Because names of the .java files compiled from .proto files are unknown until the
-# .proto files are compiled, we use a timestamp file as depedency.
-proto_java_sources_file_stamp :=
-ifneq ($(proto_sources),)
-proto_sources_fullpath := $(addprefix $(TOP_DIR)$(LOCAL_PATH)/, $(proto_sources))
-# By putting the generated java files into $(LOCAL_INTERMEDIATE_SOURCE_DIR), they will be
-# automatically found by the java compiling function transform-java-to-classes.jar.
-ifneq ($(LOCAL_INTERMEDIATE_SOURCE_DIR),)
-proto_java_intemediate_dir := $(LOCAL_INTERMEDIATE_SOURCE_DIR)/proto
-else
-# LOCAL_INTERMEDIATE_SOURCE_DIR may be not defined in non-java modules.
-proto_java_intemediate_dir := $(intermediates)/proto
-endif
-proto_java_sources_file_stamp := $(proto_java_intemediate_dir)/Proto.stamp
-proto_java_sources_dir := $(proto_java_intemediate_dir)/src
-
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_INCLUDES := $(TOP)
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_SRC_FILES := $(proto_sources_fullpath)
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_DIR := $(proto_java_sources_dir)
-ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),micro)
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javamicro_out
-else
-  ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javanano_out
-  else
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --java_out
-  endif
-endif
-$(proto_java_sources_file_stamp): PRIVATE_PROTOC_FLAGS := $(LOCAL_PROTOC_FLAGS)
-$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_PARAMS := $(LOCAL_PROTO_JAVA_OUTPUT_PARAMS)
-$(proto_java_sources_file_stamp) : $(proto_sources_fullpath) $(PROTOC)
-	$(call transform-proto-to-java)
-
-#TODO: protoc should output the dependencies introduced by imports.
-
-LOCAL_INTERMEDIATE_TARGETS += $(proto_java_sources_file_stamp)
-endif # proto_sources
-
-
-###########################################################
-## Java: Compile .java files to .class
-###########################################################
-#TODO: pull this into java.make once host and target are combined
-
-java_sources := $(addprefix $(TOP_DIR)$(LOCAL_PATH)/, $(filter %.java,$(LOCAL_SRC_FILES))) $(aidl_java_sources) $(logtags_java_sources) \
-                $(filter %.java,$(LOCAL_GENERATED_SOURCES))
-all_java_sources := $(java_sources) $(addprefix $($(my_prefix)OUT_COMMON_INTERMEDIATES)/, $(filter %.java,$(LOCAL_INTERMEDIATE_SOURCES)))
-
-## Java resources #########################################
-
-# Look for resource files in any specified directories.
-# Non-java and non-doc files will be picked up as resources
-# and included in the output jar file.
-java_resource_file_groups :=
-
-LOCAL_JAVA_RESOURCE_DIRS := $(strip $(LOCAL_JAVA_RESOURCE_DIRS))
-ifneq ($(LOCAL_JAVA_RESOURCE_DIRS),)
-  # This makes a list of words like
-  #     <dir1>::<file1>:<file2> <dir2>::<file1> <dir3>:
-  # where each of the files is relative to the directory it's grouped with.
-  # Directories that don't contain any resource files will result in groups
-  # that end with a colon, and they are stripped out in the next step.
-  java_resource_file_groups += \
-    $(foreach dir,$(LOCAL_JAVA_RESOURCE_DIRS), \
-	$(subst $(space),:,$(strip \
-		$(TOP_DIR)$(LOCAL_PATH)/$(dir): \
-	    $(patsubst ./%,%,$(shell cd $(TOP_DIR)$(LOCAL_PATH)/$(dir) && \
-		find . \
-		    -type d -a -name ".svn" -prune -o \
-		    -type f \
-			-a \! -name "*.java" \
-			-a \! -name "package.html" \
-			-a \! -name "overview.html" \
-			-a \! -name ".*.swp" \
-			-a \! -name ".DS_Store" \
-			-a \! -name "*~" \
-			-print \
-		    )) \
-	)) \
-    )
-  java_resource_file_groups := $(filter-out %:,$(java_resource_file_groups))
-endif # LOCAL_JAVA_RESOURCE_DIRS
-
-LOCAL_JAVA_RESOURCE_FILES := $(strip $(LOCAL_JAVA_RESOURCE_FILES))
-ifneq ($(LOCAL_JAVA_RESOURCE_FILES),)
-  java_resource_file_groups += \
-    $(foreach f,$(LOCAL_JAVA_RESOURCE_FILES), \
-	$(patsubst %/,%,$(dir $(f)))::$(notdir $(f)) \
-     )
-endif # LOCAL_JAVA_RESOURCE_FILES
-
-ifdef java_resource_file_groups
-  # The full paths to all resources, used for dependencies.
-  java_resource_sources := \
-    $(foreach group,$(java_resource_file_groups), \
-	$(addprefix $(word 1,$(subst :,$(space),$(group)))/, \
-	    $(wordlist 2,9999,$(subst :,$(space),$(group))) \
-	) \
-    )
-  # The arguments to jar that will include these files in a jar file.
-  # Quote the file name to handle special characters (such as #) correctly.
-  extra_jar_args := \
-    $(foreach group,$(java_resource_file_groups), \
-	$(addprefix -C "$(word 1,$(subst :,$(space),$(group)))" , \
-	    $(foreach w, $(wordlist 2,9999,$(subst :,$(space),$(group))), "$(w)" ) \
-	) \
-    )
-  java_resource_file_groups :=
-else
-  java_resource_sources :=
-  extra_jar_args :=
-endif # java_resource_file_groups
-
-## PRIVATE java vars ######################################
-# LOCAL_SOURCE_FILES_ALL_GENERATED is set only if the module does not have static source files,
-# but generated source files in its LOCAL_INTERMEDIATE_SOURCE_DIR.
-# You have to set up the dependency in some other way.
-need_compile_java := $(strip $(all_java_sources)$(all_res_assets))$(LOCAL_STATIC_JAVA_LIBRARIES)$(filter true,$(LOCAL_SOURCE_FILES_ALL_GENERATED))
-ifdef need_compile_java
-
-full_static_java_libs := \
-    $(foreach lib,$(LOCAL_STATIC_JAVA_LIBRARIES), \
-      $(call intermediates-dir-for, \
-        JAVA_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),COMMON)/javalib.jar)
-
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_INSTALL_DIR := $(dir $(LOCAL_INSTALLED_MODULE))
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CLASS_INTERMEDIATES_DIR := $(intermediates)/classes
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_SOURCE_INTERMEDIATES_DIR := $(intermediates)/src
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAVA_SOURCES := $(all_java_sources)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAVA_OBJECTS := $(patsubst %.java,%.class,$(LOCAL_SRC_FILES))
-ifeq ($(my_prefix),TARGET_)
-ifeq ($(LOCAL_SDK_VERSION),)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -bootclasspath $(call java-lib-files,core-libart)
-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)
-else ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),system_current)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -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))
-endif # current or system_current
-endif # LOCAL_SDK_VERSION
-endif # TARGET_
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RESOURCE_DIR := $(LOCAL_RESOURCE_DIR)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_ASSET_DIR := $(LOCAL_ASSET_DIR)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_STATIC_JAVA_LIBRARIES := $(full_static_java_libs)
-
-# full_java_libs: The list of files that should be used as the classpath.
-#                 Using this list as a dependency list WILL NOT WORK.
-# full_java_lib_deps: Should be specified as a prerequisite of this module
-#                 to guarantee that the files in full_java_libs will
-#                 be up-to-date.
-ifdef 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))
-
-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)) \
-    $(full_shared_java_libs)
-else
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH :=
-
-full_shared_java_libs := $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/,\
-    $(addsuffix $(COMMON_JAVA_PACKAGE_SUFFIX),$(LOCAL_JAVA_LIBRARIES)))
-full_java_lib_deps := $(full_shared_java_libs)
-endif # USE_CORE_LIB_BOOTCLASSPATH
-else # !LOCAL_IS_HOST_MODULE
-full_shared_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
-full_java_lib_deps := $(call java-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
-endif # !LOCAL_IS_HOST_MODULE
-full_java_libs := $(full_shared_java_libs) $(full_static_java_libs) $(LOCAL_CLASSPATH)
-full_java_lib_deps += $(full_static_java_libs) $(LOCAL_CLASSPATH)
-
-# This is set by packages that are linking to other packages that export
-# shared libraries, allowing them to make use of the code in the linked apk.
-apk_libraries := $(sort $(LOCAL_APK_LIBRARIES) $(LOCAL_RES_LIBRARIES))
-ifneq ($(apk_libraries),)
-  link_apk_libraries := \
-      $(foreach lib,$(apk_libraries), \
-        $(call intermediates-dir-for, \
-              APPS,$(lib),,COMMON)/classes.jar)
-
-  # link against the jar with full original names (before proguard processing).
-  full_shared_java_libs += $(link_apk_libraries)
-  full_java_libs += $(link_apk_libraries)
-  full_java_lib_deps += $(link_apk_libraries)
-endif
-
-# This is set by packages that contain instrumentation, allowing them to
-# link against the package they are instrumenting.  Currently only one such
-# package is allowed.
-LOCAL_INSTRUMENTATION_FOR := $(strip $(LOCAL_INSTRUMENTATION_FOR))
-ifdef LOCAL_INSTRUMENTATION_FOR
-  ifneq ($(words $(LOCAL_INSTRUMENTATION_FOR)),1)
-    $(error \
-        $(LOCAL_PATH): Multiple LOCAL_INSTRUMENTATION_FOR members defined)
-  endif
-
-  link_instr_intermediates_dir.COMMON := $(call intermediates-dir-for, \
-      APPS,$(LOCAL_INSTRUMENTATION_FOR),,COMMON)
-  # link against the jar with full original names (before proguard processing).
-  link_instr_classes_jar := $(link_instr_intermediates_dir.COMMON)/classes.jar
-  full_java_libs += $(link_instr_classes_jar)
-  full_java_lib_deps += $(link_instr_classes_jar)
-endif
-
-endif  # need_compile_java
-
-# We may want to add jar manifest or jar resource files even if there is no java code at all.
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_EXTRA_JAR_ARGS := $(extra_jar_args)
-jar_manifest_file :=
-ifneq ($(strip $(LOCAL_JAR_MANIFEST)),)
-jar_manifest_file := $(LOCAL_PATH)/$(LOCAL_JAR_MANIFEST)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAR_MANIFEST := $(jar_manifest_file)
-else
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAR_MANIFEST :=
-endif
-
-###########################################################
 ## make clean- targets
 ###########################################################
 cleantarget := clean-$(my_register_name)
@@ -500,35 +238,12 @@
 ###########################################################
 ## Common definitions for module.
 ###########################################################
-
-# aapt doesn't accept multiple --extra-packages flags.
-# We have to collapse them into a single --extra-packages flag here.
-LOCAL_AAPT_FLAGS := $(strip $(LOCAL_AAPT_FLAGS))
-ifdef LOCAL_AAPT_FLAGS
-ifeq ($(filter 0 1,$(words $(filter --extra-packages,$(LOCAL_AAPT_FLAGS)))),)
-aapt_flags := $(subst --extra-packages$(space),--extra-packages@,$(LOCAL_AAPT_FLAGS))
-aapt_flags_extra_packages := $(patsubst --extra-packages@%,%,$(filter --extra-packages@%,$(aapt_flags)))
-aapt_flags_extra_packages := $(sort $(subst :,$(space),$(aapt_flags_extra_packages)))
-LOCAL_AAPT_FLAGS := $(filter-out --extra-packages@%,$(aapt_flags)) \
-    --extra-packages $(subst $(space),:,$(aapt_flags_extra_packages))
-aapt_flags_extra_packages :=
-aapt_flags :=
-endif
-endif
-
-# Propagate local configuration options to this target.
 $(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_PATH:=$(LOCAL_PATH)
-$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_AAPT_FLAGS:= $(LOCAL_AAPT_FLAGS) $(PRODUCT_AAPT_FLAGS)
-$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_JAVA_LIBRARIES:= $(LOCAL_JAVA_LIBRARIES)
-$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_MANIFEST_PACKAGE_NAME:= $(LOCAL_MANIFEST_PACKAGE_NAME)
-$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_MANIFEST_INSTRUMENTATION_FOR:= $(LOCAL_MANIFEST_INSTRUMENTATION_FOR)
-
-$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_ALL_JAVA_LIBRARIES:= $(full_java_libs)
 $(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_IS_HOST_MODULE := $(LOCAL_IS_HOST_MODULE)
 $(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_HOST:= $(my_host)
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_PREFIX := $(my_prefix)
 
 $(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_INTERMEDIATES_DIR:= $(intermediates)
-
 $(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_2ND_ARCH_VAR_PREFIX := $(LOCAL_2ND_ARCH_VAR_PREFIX)
 
 # Tell the module and all of its sub-modules who it is.
@@ -540,6 +255,15 @@
 .PHONY: $(my_register_name)
 $(my_register_name): $(LOCAL_BUILT_MODULE) $(LOCAL_INSTALLED_MODULE)
 
+# Set up phony targets that covers all modules under the given paths.
+# This allows us to build everything in given paths by running mmma/mma.
+my_path_components := $(subst /,$(space),$(LOCAL_PATH))
+my_path_prefix := MODULES-IN
+$(foreach c, $(my_path_components),\
+  $(eval my_path_prefix := $(my_path_prefix)-$(c))\
+  $(eval .PHONY : $(my_path_prefix))\
+  $(eval $(my_path_prefix) : $(my_register_name)))
+
 ###########################################################
 ## Module installation rule
 ###########################################################
@@ -593,8 +317,6 @@
 # checked modules, use LOCAL_BUILT_MODULE.
 ifdef LOCAL_CHECKED_MODULE
   my_checked_module := $(LOCAL_CHECKED_MODULE)
-else ifdef java_alternative_checked_module
-  my_checked_module := $(java_alternative_checked_module)
 else
   my_checked_module := $(LOCAL_BUILT_MODULE)
 endif
@@ -645,13 +367,15 @@
 ALL_MODULES.$(my_register_name).PICKUP_FILES := \
     $(ALL_MODULES.$(my_register_name).PICKUP_FILES) $(LOCAL_PICKUP_FILES)
 endif
+my_required_modules := $(LOCAL_REQUIRED_MODULES) \
+    $(LOCAL_REQUIRED_MODULES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+ifdef LOCAL_IS_HOST_MODULE
+my_required_modules += $(LOCAL_REQUIRED_MODULES_$($(my_prefix)OS))
+endif
 ALL_MODULES.$(my_register_name).REQUIRED := \
-    $(strip $(ALL_MODULES.$(my_register_name).REQUIRED) $(LOCAL_REQUIRED_MODULES) \
-      $(LOCAL_REQUIRED_MODULES_$(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)))
+    $(strip $(ALL_MODULES.$(my_register_name).REQUIRED) $(my_required_modules))
 ALL_MODULES.$(my_register_name).EVENT_LOG_TAGS := \
     $(ALL_MODULES.$(my_register_name).EVENT_LOG_TAGS) $(event_log_tags)
-ALL_MODULES.$(my_register_name).INTERMEDIATE_SOURCE_DIR := \
-    $(ALL_MODULES.$(my_register_name).INTERMEDIATE_SOURCE_DIR) $(LOCAL_INTERMEDIATE_SOURCE_DIR)
 ALL_MODULES.$(my_register_name).MAKEFILE := \
     $(ALL_MODULES.$(my_register_name).MAKEFILE) $(LOCAL_MODULE_MAKEFILE)
 ifdef LOCAL_MODULE_OWNER
@@ -661,9 +385,7 @@
 ifdef LOCAL_2ND_ARCH_VAR_PREFIX
 ALL_MODULES.$(my_register_name).FOR_2ND_ARCH := true
 endif
-ifdef aidl_sources
-ALL_MODULES.$(my_register_name).AIDL_FILES := $(aidl_sources)
-endif
+ALL_MODULES.$(my_register_name).FOR_HOST_CROSS := $(my_host_cross)
 
 INSTALLABLE_FILES.$(LOCAL_INSTALLED_MODULE).MODULE := $(my_register_name)
 
@@ -718,89 +440,7 @@
 endif
 
 ###########################################################
-# JACK
-###########################################################
-ifdef LOCAL_JACK_ENABLED
-ifdef need_compile_java
-
-full_static_jack_libs := \
-    $(foreach lib,$(LOCAL_STATIC_JAVA_LIBRARIES), \
-      $(call intermediates-dir-for, \
-        JAVA_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),COMMON)/classes.jack)
-
-ifeq ($(my_prefix),TARGET_)
-ifeq ($(LOCAL_SDK_VERSION),)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,core-libart)
-else
-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)
-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)
-else
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,sdk_v$(LOCAL_SDK_VERSION))
-endif # current or system_current
-endif # LOCAL_SDK_VERSION
-endif # TARGET_
-
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_STATIC_JACK_LIBRARIES := $(full_static_jack_libs)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_VM_ARGS := $(LOCAL_JACK_VM_ARGS)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_EXTRA_ARGS := $(LOCAL_JACK_EXTRA_ARGS)
-
-ifdef 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))
-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
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES :=
-full_shared_jack_libs := $(call jack-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
-full_jack_lib_deps := $(full_shared_jack_libs)
-endif # USE_CORE_LIB_BOOTCLASSPATH
-else # !LOCAL_IS_HOST_MODULE
-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))
-endif # !LOCAL_IS_HOST_MODULE
-full_jack_libs := $(full_shared_jack_libs) $(full_static_jack_libs) $(LOCAL_JACK_CLASSPATH)
-full_jack_lib_deps += $(full_static_jack_libs) $(LOCAL_JACK_CLASSPATH)
-
-# This is set by packages that are linking to other packages that export
-# shared libraries, allowing them to make use of the code in the linked apk.
-ifneq ($(apk_libraries),)
-  link_apk_jack_libraries := \
-      $(foreach lib,$(apk_libraries), \
-        $(call intermediates-dir-for, \
-              APPS,$(lib),,COMMON)/classes.jack)
-
-  # link against the jar with full original names (before proguard processing).
-  full_shared_jack_libs += $(link_apk_jack_libraries)
-  full_jack_libs += $(link_apk_jack_libraries)
-  full_jack_lib_deps += $(link_apk_jack_libraries)
-endif
-
-# This is set by packages that contain instrumentation, allowing them to
-# link against the package they are instrumenting.  Currently only one such
-# package is allowed.
-ifdef LOCAL_INSTRUMENTATION_FOR
-
-   # link against the jar with full original names (before proguard processing).
-   link_instr_classes_jack := $(link_instr_intermediates_dir.COMMON)/classes.noshrob.jack
-   full_jack_libs += $(link_instr_classes_jack)
-   full_jack_lib_deps += $(link_instr_classes_jack)
-endif
-
-endif  # need_compile_java
-
-# Propagate local configuration options to this target.
-$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_ALL_JACK_LIBRARIES:= $(full_jack_libs)
-$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_JARJAR_RULES := $(LOCAL_JARJAR_RULES)
-
-endif # LOCAL_JACK_ENABLED
-
-###########################################################
 ## NOTICE files
 ###########################################################
 
 include $(BUILD_NOTICE_FILE)
-
-#:vi noexpandtab
diff --git a/core/binary.mk b/core/binary.mk
index 01c8858..093cc38 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -145,7 +145,7 @@
 # MinGW spits out warnings about -fPIC even for -fpie?!) being ignored because
 # all code is position independent, and then those warnings get promoted to
 # errors.
-ifndef USE_MINGW
+ifneq ($($(my_prefix)OS),windows)
 ifeq ($(LOCAL_MODULE_CLASS),EXECUTABLES)
 my_cflags += -fpie
 else
@@ -153,6 +153,19 @@
 endif
 endif
 
+ifdef LOCAL_IS_HOST_MODULE
+my_src_files += $(LOCAL_SRC_FILES_$($(my_prefix)OS)) $(LOCAL_SRC_FILES_$($(my_prefix)OS)_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
+my_static_libraries += $(LOCAL_STATIC_LIBRARIES_$($(my_prefix)OS))
+my_shared_libraries += $(LOCAL_SHARED_LIBRARIES_$($(my_prefix)OS))
+my_cflags += $(LOCAL_CFLAGS_$($(my_prefix)OS))
+my_cppflags += $(LOCAL_CPPFLAGS_$($(my_prefix)OS))
+my_ldflags += $(LOCAL_LDFLAGS_$($(my_prefix)OS))
+my_ldlibs += $(LOCAL_LDLIBS_$($(my_prefix)OS))
+my_asflags += $(LOCAL_ASFLAGS_$($(my_prefix)OS))
+my_c_includes += $(LOCAL_C_INCLUDES_$($(my_prefix)OS))
+my_generated_sources += $(LOCAL_GENERATED_SOURCES_$($(my_prefix)OS))
+endif
+
 my_src_files += $(LOCAL_SRC_FILES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_SRC_FILES_$(my_32_64_bit_suffix))
 my_shared_libraries += $(LOCAL_SHARED_LIBRARIES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_SHARED_LIBRARIES_$(my_32_64_bit_suffix))
 my_cflags += $(LOCAL_CFLAGS_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_CFLAGS_$(my_32_64_bit_suffix))
@@ -173,11 +186,16 @@
 # clang is enabled by default for host builds
 # enable it unless we've specifically disabled clang above
 ifdef LOCAL_IS_HOST_MODULE
-    ifneq ($(HOST_OS),windows)
+    ifneq ($($(my_prefix)OS),windows)
     ifeq ($(my_clang),)
         my_clang := true
     endif
     endif
+# Add option to make clang the default for device build
+else ifeq ($(USE_CLANG_PLATFORM_BUILD),true)
+    ifeq ($(my_clang),)
+        my_clang := true
+    endif
 endif
 
 my_cpp_std_version := -std=gnu++14
@@ -196,12 +214,6 @@
 
 my_cppflags := $(my_cpp_std_version) $(my_cppflags)
 
-# Add option to make clang the default for device build
-ifeq ($(USE_CLANG_PLATFORM_BUILD),true)
-    ifeq ($(my_clang),)
-        my_clang := true
-    endif
-endif
 
 # arch-specific static libraries go first so that generic ones can depend on them
 my_static_libraries := $(LOCAL_STATIC_LIBRARIES_$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)) $(LOCAL_STATIC_LIBRARIES_$(my_32_64_bit_suffix)) $(my_static_libraries)
@@ -222,10 +234,6 @@
 
 include $(BUILD_SYSTEM)/config_sanitizers.mk
 
-ifeq ($(strip $($(LOCAL_2ND_ARCH_VAR_PREFIX)WITHOUT_$(my_prefix)CLANG)),true)
-  my_clang :=
-endif
-
 # Add in libcompiler_rt for all regular device builds
 ifeq (,$(LOCAL_SDK_VERSION)$(WITHOUT_LIBCOMPILER_RT))
   my_static_libraries += $(COMPILER_RT_CONFIG_EXTRA_STATIC_LIBRARIES)
@@ -294,17 +302,17 @@
 else # LOCAL_IS_HOST_MODULE
 
 ifeq ($(my_clang),true)
-my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_CFLAGS)
-my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_CONLYFLAGS)
-my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_CPPFLAGS)
-my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_HOST_GLOBAL_LDFLAGS)
-my_host_c_includes := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_C_INCLUDES)
+my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CFLAGS)
+my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CONLYFLAGS)
+my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_CPPFLAGS)
+my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)CLANG_$(my_prefix)GLOBAL_LDFLAGS)
+my_host_c_includes := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
 else
-my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CFLAGS)
-my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CONLYFLAGS)
-my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CPPFLAGS)
-my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LDFLAGS)
-my_host_c_includes := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_C_INCLUDES)
+my_host_global_cflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)GLOBAL_CFLAGS)
+my_host_global_conlyflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)GLOBAL_CONLYFLAGS)
+my_host_global_cppflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)GLOBAL_CPPFLAGS)
+my_host_global_ldflags := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)GLOBAL_LDFLAGS)
+my_host_c_includes := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)C_INCLUDES)
 endif # my_clang
 
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_HOST_C_INCLUDES := $(my_host_c_includes)
@@ -605,13 +613,13 @@
     my_static_libraries += libprotobuf-c-nano
 else ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),full)
     ifdef LOCAL_SDK_VERSION
-        my_static_libraries += libprotobuf-cpp-full
+        my_static_libraries += libprotobuf-cpp-full-ndk
     else
         my_shared_libraries += libprotobuf-cpp-full
     endif
 else
     ifdef LOCAL_SDK_VERSION
-        my_static_libraries += libprotobuf-cpp-lite
+        my_static_libraries += libprotobuf-cpp-lite-ndk
     else
         my_shared_libraries += libprotobuf-cpp-lite
     endif
@@ -919,6 +927,20 @@
 endif
 
 ###########################################################
+## ObjC++: Compile .mm files to .o
+###########################################################
+
+objcpp_sources := $(filter %.mm,$(my_src_files))
+objcpp_objects := $(addprefix $(intermediates)/,$(objcpp_sources:.mm=.o))
+
+ifneq ($(strip $(objcpp_objects)),)
+$(objcpp_objects): $(intermediates)/%.o: $(TOPDIR)$(LOCAL_PATH)/%.mm $(yacc_cpps) $(proto_generated_headers) \
+    $(my_additional_dependencies)
+	$(transform-$(PRIVATE_HOST)mm-to-o)
+-include $(objcpp_objects:%.o=%.P)
+endif
+
+###########################################################
 ## AS: Compile .S files to .o.
 ###########################################################
 
@@ -1002,9 +1024,9 @@
 import_includes := $(intermediates)/import_includes
 import_includes_deps := $(strip \
     $(foreach l, $(installed_shared_library_module_names), \
-      $(call intermediates-dir-for,SHARED_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX))/export_includes) \
+      $(call intermediates-dir-for,SHARED_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX),$(my_host_cross))/export_includes) \
     $(foreach l, $(my_static_libraries) $(my_whole_static_libraries), \
-      $(call intermediates-dir-for,STATIC_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX))/export_includes))
+      $(call intermediates-dir-for,STATIC_LIBRARIES,$(l),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX),$(my_host_cross))/export_includes))
 $(import_includes): PRIVATE_IMPORT_EXPORT_INCLUDES := $(import_includes_deps)
 $(import_includes) : $(LOCAL_MODULE_MAKEFILE) $(import_includes_deps)
 	@echo Import includes file: $@
@@ -1031,6 +1053,7 @@
     $(c_objects) \
     $(gen_c_objects) \
     $(objc_objects) \
+    $(objcpp_objects) \
     $(yacc_objects) \
     $(lex_objects) \
     $(proto_generated_objects) \
@@ -1109,7 +1132,7 @@
 built_static_libraries := \
     $(foreach lib,$(my_static_libraries), \
       $(call intermediates-dir-for, \
-        STATIC_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX))/$(lib)$(a_suffix))
+        STATIC_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX),$(my_host_cross))/$(lib)$(a_suffix))
 
 ifdef LOCAL_SDK_VERSION
 built_static_libraries += $(my_ndk_stl_static_lib)
@@ -1118,7 +1141,7 @@
 built_whole_libraries := \
     $(foreach lib,$(my_whole_static_libraries), \
       $(call intermediates-dir-for, \
-        STATIC_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX))/$(lib)$(a_suffix))
+        STATIC_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),,$(LOCAL_2ND_ARCH_VAR_PREFIX),$(my_host_cross))/$(lib)$(a_suffix))
 
 # We don't care about installed static libraries, since the
 # libraries have already been linked into the module at that point.
diff --git a/core/build-system.html b/core/build-system.html
index caade58..3f638c3 100644
--- a/core/build-system.html
+++ b/core/build-system.html
@@ -462,26 +462,17 @@
 <p>Sometimes you need to set flags specifically for different platforms.  Here
 is a list of which values the different build-system defined variables will be
 set to and some examples.</p>
-<p>For a device build, <code>TARGET_OS</code> is <code>linux</code> (we're using
-linux!), and <code>TARGET_ARCH</code> is <code>arm</code>.</p>
-<p>For a simulator build, <code>TARGET_OS</code> and <code>TARGET_ARCH</code>
-are set to the same as <code>HOST_OS</code> and <code>HOST_ARCH</code> are
-on your platform.  <code>TARGET_PRODUCT</code> is the name of the target
-hardware/product you are building for.  The value <code>sim</code> is used
-for the simulator.  We haven't thought through the full extent of customization
-that will happen here, but likely there will be additional UI configurations
-specified here as well.</p>
 <table cellspacing=25>
 <tr>
     <td valign=top align=center>
         <b>HOST_OS</b><br/>
         linux<br/>
-        darwin<br/>
-        (cygwin)
+        darwin
     </td>
     <td valign=top align=center>
         <b>HOST_ARCH</b><br/>
-        x86
+        x86<br/>
+        x86_64
     </td>
     <td valign=top align=center>
         <b>HOST_BUILD_TYPE</b><br/>
@@ -491,42 +482,40 @@
 </tr>
 <tr>
     <td valign=top align=center>
-        <b>TARGET_OS</b><br/>
-        linux<br/>
-        darwin<br/>
-        (cygwin)
-    </td>
-    <td valign=top align=center>
         <b>TARGET_ARCH</b><br/>
         arm<br/>
-        x86
+        arm64<br/>
+        mips<br/>
+        mips64<br/>
+        x86<br/>
+        x86_64
     </td>
     <td valign=top align=center>
         <b>TARGET_BUILD_TYPE</b><br/>
         release<br/>
         debug
     </td>
-    <td valign=top align=center>
-        <b>TARGET_PRODUCT</b><br/>
-        sim<br/>
-        dream<br/>
-        sooner
-    </td>
 </tr>
 </table>
 
+<p>There are also special variables to use instead of conditionals. Many of the
+normal variables (LOCAL_SRC_FILES, LOCAL_CFLAGS, etc) can be conditionally added
+to with _{arch} _{32|64}, and for the host, _{os}.</p>
+
 <h4>Some Examples</h4>
 <pre>ifeq ($(TARGET_BUILD_TYPE),release)
 LOCAL_CFLAGS += -DNDEBUG=1
 endif
 
+LOCAL_CFLAGS_arm += -DTARGET_IS_ARM
+
+LOCAL_CFLAGS_64 += -DBIG_POINTER
+
 # from libutils
-ifeq ($(TARGET_OS),linux)
 # Use the futex based mutex and condition variable
 # implementation from android-arm because it's shared mem safe
-LOCAL_SRC_FILES += futex_synchro.c
-LOCAL_LDLIBS += -lrt -ldl
-endif
+LOCAL_SRC_FILES_linux += futex_synchro.c
+LOCAL_LDLIBS_linux += -lrt -ldl
 
 </pre>
 
@@ -554,7 +543,7 @@
 the unstripped executables so GDB can find the symbols.
 <code>LOCAL_UNSTRIPPED_PATH</code> is not necessary if you only specified
 <code>LOCAL_MODULE_RELATIVE_PATH</code>.</p>
-<p>Look in <code>config/envsetup.make</code> for all of the variables defining
+<p>Look in <code>core/envsetup.mk</code> for all of the variables defining
 places to build things.</p>
 <p>FYI: If you're installing an executable to /sbin, you probably also want to
 set <code>LOCAL_FORCE_STATIC_EXCUTABLE := true</code> in your Android.mk, which
@@ -587,6 +576,11 @@
     and definitions that are specific to either the host or the target builds.
     Do not set variables that start with HOST_ or TARGET_ in your makefiles.
     </li>
+    <li><b>HOST_CROSS_</b> - These contain the directories and definitions that
+    are specific to cross-building host binaries. The common case is building
+    windows host tools on linux. Do not set variables that start with
+    HOST_CROSS_ in your makefiles.
+    </li>
     <li><b>BUILD_</b> and <b>CLEAR_VARS</b> - These contain the names of
     well-defined template makefiles to include.  Some examples are CLEAR_VARS
     and BUILD_HOST_PACKAGE.</li>
@@ -773,13 +767,13 @@
 </code></p>
 
 <h4>LOCAL_PREBUILT_EXECUTABLES</h4>
-<p>When including $(BUILD_PREBUILT) or $(BUILD_HOST_PREBUILT), set these to
-executables that you want copied.  They're located automatically into the
+<p>When including $(BUILD_MULTI_PREBUILT) or $(BUILD_HOST_PREBUILT), set these
+to executables that you want copied.  They're located automatically into the
 right bin directory.</p>
 
 <h4>LOCAL_PREBUILT_LIBS</h4>
-<p>When including $(BUILD_PREBUILT) or $(BUILD_HOST_PREBUILT), set these to
-libraries that you want copied.  They're located automatically into the
+<p>When including $(BUILD_MULTI_PREBUILT) or $(BUILD_HOST_PREBUILT), set these
+to libraries that you want copied.  They're located automatically into the
 right lib directory.</p>
 
 <h4>LOCAL_SHARED_LIBRARIES</h4>
@@ -836,6 +830,16 @@
 the relative path.</p>
 <p>See <a href="#moving-modules">Putting modules elsewhere</a> for more.</p>
 
+<h4>LOCAL_MODULE_HOST_OS</h4>
+<p>This specifies which OSes are supported by this host module. It is not used
+for target builds. The accepted values here are combinations of
+<code>linux</code>, <code>darwin</code>, and <code>windows</code>. By default,
+linux and darwin(MacOS) are considered to be supported. If a module should
+build under windows, you must specify windows, and any others to be supported.
+Some examples:</p>
+<p><code>LOCAL_MODULE_HOST_OS := linux<br/>
+LOCAL_MODULE_HOST_OS := darwin linux windows</code></p>
+
 <h4>LOCAL_UNSTRIPPED_PATH</h4>
 <p>Instructs the build system to put the unstripped version of the module
 somewhere other than what's normal for its type.  Usually, you override this
@@ -878,10 +882,10 @@
 If you make a change that requires an update, you need to update two places
 so this message will be printed.
 <ul>
-    <li>In config/envsetup.make, increment the
+    <li>In core/envsetup.mk, increment the
         CORRECT_BUILD_ENV_SEQUENCE_NUMBER definition.</li>
     <li>In buildspec.mk.default, update the BUILD_ENV_SEQUENCE_DUMBER
-        definition to match the one in config/envsetup.make</li>
+        definition to match the one in core/envsetup.mk</li>
 </ul>
 The scripts automatically get the value from the build system, so they will
 trigger the warning as well.
@@ -900,53 +904,39 @@
 for some other dependency that isn't created automatically.</p>
 
 <h4>LOCAL_BUILT_MODULE</h4>
+<p class=warning>This should not be used, since multiple binaries are now
+created from a single module defintiion.</p>
 <p>When a module is built, the module is created in an intermediate
 directory then copied to its final location.  LOCAL_BUILT_MODULE is
 the full path to the intermediate file.  See LOCAL_INSTALLED_MODULE
 for the path to the final installed location of the module.</p>
 
-<h4>LOCAL_HOST</h4>
-<p>Set by the host_xxx.make includes to tell base_rules.make and the other
-includes that we're building for the host.  Kenneth did this as part of
-openbinder, and I would like to clean it up so the rules, includes and
-definitions aren't duplicated for host and target.</p>
+<h4>LOCAL_IS_HOST_MODULE</h4>
+<p>Set by the host_xxx.mk includes to tell base_rules.mk and the other
+includes that we're building for the host.</p>
 
 <h4>LOCAL_INSTALLED_MODULE</h4>
+<p class=warning>This should not be used, since multiple binaries are now
+created from a single module defintiion.</p>
 <p>The fully qualified path name of the final location of the module.
 See LOCAL_BUILT_MODULE for the location of the intermediate file that
 the make rules should actually be constructing.</p>
 
-<h4>LOCAL_REPLACE_VARS</h4>
-<p>Used in some stuff remaining from the openbinder for building scripts
-with particular values set,</p>
-
-<h4>LOCAL_SCRIPTS</h4>
-<p>Used in some stuff remaining from the openbinder build system that we
-might find handy some day.</p>
-
 <h4>LOCAL_MODULE_CLASS</h4>
 <p>Which kind of module this is.  This variable is used to construct other
-variable names used to locate the modules.  See base_rules.make and
-envsetup.make.</p>
-
-<h4>LOCAL_MODULE_NAME</h4>
-<p>Set to the leaf name of the LOCAL_BUILT_MODULE.  I'm not sure,
-but it looks like it's just used in the WHO_AM_I variable to identify
-in the pretty printing what's being built.</p>
+variable names used to locate the modules.  See base_rules.mk and
+envsetup.mk.</p>
 
 <h4>LOCAL_MODULE_SUFFIX</h4>
 <p>The suffix that will be appended to <code>LOCAL_MODULE</code> to form
 <code>LOCAL_MODULE_NAME</code>.  For example, .so, .a, .dylib.</p>
 
 <h4>LOCAL_STRIP_MODULE</h4>
-<p>Calculated in base_rules.make to determine if this module should actually
-be stripped or not, based on whether <code>LOCAL_STRIPPABLE_MODULE</code>
-is set, and whether the combo is configured to ever strip modules.  With
-Iliyan's stripping tool, this might change.</p>
-
-<h4>LOCAL_STRIPPABLE_MODULE</h4>
-<p>Set by the include makefiles if that type of module is strippable. 
-Executables and shared libraries are.</p>
+<p>If set to true (the default), the binary will be stripped and a debug
+link will be set up so that GDB will still work. If set to no_debuglink,
+the binary will be stripped, but no debug link will be added. If set to
+keep_symbols, it will strip the debug information, but keep the symbol table.
+Any other value will prevent stripping.</p>
 
 <h4>LOCAL_SYSTEM_SHARED_LIBRARIES</h4>
 <p>Used while building the base libraries: libc, libm, libdl.  Usually
diff --git a/core/ccache.mk b/core/ccache.mk
index 34e5e1c..c99d933 100644
--- a/core/ccache.mk
+++ b/core/ccache.mk
@@ -37,11 +37,6 @@
   export CCACHE_CPP2 := true
 
   CCACHE_HOST_TAG := $(HOST_PREBUILT_TAG)
-  # If we are cross-compiling Windows binaries on Linux
-  # then use the linux ccache binary instead.
-  ifeq ($(HOST_OS)-$(BUILD_OS),windows-linux)
-    CCACHE_HOST_TAG := linux-$(HOST_PREBUILT_ARCH)
-  endif
   ccache := prebuilts/misc/$(CCACHE_HOST_TAG)/ccache/ccache
   # Check that the executable is here.
   ccache := $(strip $(wildcard $(ccache)))
diff --git a/core/clang/HOST_CROSS_windows.mk b/core/clang/HOST_CROSS_windows.mk
new file mode 100644
index 0000000..74adb58
--- /dev/null
+++ b/core/clang/HOST_CROSS_windows.mk
@@ -0,0 +1,56 @@
+
+include $(BUILD_SYSTEM)/clang/x86.mk
+
+CLANG_CONFIG_x86_HOST_CROSS_TRIPLE := i686-pc-mingw32
+
+CLANG_CONFIG_x86_HOST_CROSS_EXTRA_ASFLAGS := \
+  $(CLANG_CONFIG_EXTRA_ASFLAGS) \
+  $(CLANG_CONFIG_HOST_CROSS_EXTRA_ASFLAGS) \
+  $(CLANG_CONFIG_x86_EXTRA_ASFLAGS) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_COMBO_EXTRA_ASFLAGS) \
+  -target $(CLANG_CONFIG_x86_HOST_CROSS_TRIPLE)
+
+CLANG_CONFIG_x86_HOST_CROSS_EXTRA_CFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CFLAGS) \
+  $(CLANG_CONFIG_HOST_CROSS_EXTRA_CFLAGS) \
+  $(CLANG_CONFIG_x86_EXTRA_CFLAGS) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_COMBO_EXTRA_CFLAGS) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_EXTRA_ASFLAGS)
+
+CLANG_CONFIG_x86_HOST_CROSS_EXTRA_CONLYFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_HOST_CROSS_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_EXTRA_CONLYFLAGS) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_COMBO_EXTRA_CONLYFLAGS)
+
+CLANG_CONFIG_x86_HOST_CROSS_EXTRA_CPPFLAGS := \
+  $(CLANG_CONFIG_EXTRA_CPPFLAGS) \
+  $(CLANG_CONFIG_HOST_CROSS_EXTRA_CPPFLAGS) \
+  $(CLANG_CONFIG_x86_EXTRA_CPPFLAGS) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_COMBO_EXTRA_CPPFLAGS) \
+  -target $(CLANG_CONFIG_x86_HOST_CROSS_TRIPLE)
+
+CLANG_CONFIG_x86_HOST_CROSS_EXTRA_LDFLAGS := \
+  $(CLANG_CONFIG_EXTRA_LDFLAGS) \
+  $(CLANG_CONFIG_HOST_CROSS_EXTRA_LDFLAGS) \
+  $(CLANG_CONFIG_x86_EXTRA_LDFLAGS) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_COMBO_EXTRA_LDFLAGS) \
+  -target $(CLANG_CONFIG_x86_HOST_CROSS_TRIPLE)
+
+CLANG_HOST_CROSS_GLOBAL_CFLAGS := \
+  $(call convert-to-host-clang-flags,$(HOST_CROSS_GLOBAL_CFLAGS)) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_EXTRA_CFLAGS)
+
+CLANG_HOST_CROSS_GLOBAL_CONLYFLAGS := \
+  $(call convert-to-host-clang-flags,$(HOST_CROSS_GLOBAL_CONLYFLAGS)) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_EXTRA_CONLYFLAGS)
+
+CLANG_HOST_CROSS_GLOBAL_CPPFLAGS := \
+  $(call convert-to-host-clang-flags,$(HOST_CROSS_GLOBAL_CPPFLAGS)) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_EXTRA_CPPFLAGS)
+
+CLANG_HOST_CROSS_GLOBAL_LDFLAGS := \
+  $(call convert-to-host-clang-flags,$(HOST_CROSS_GLOBAL_LDFLAGS)) \
+  $(CLANG_CONFIG_x86_HOST_CROSS_EXTRA_LDFLAGS)
+
+HOST_CROSS_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-i686.a
diff --git a/core/clang/HOST_x86.mk b/core/clang/HOST_x86.mk
index f14a9c3..0ec64ad 100644
--- a/core/clang/HOST_x86.mk
+++ b/core/clang/HOST_x86.mk
@@ -16,9 +16,6 @@
 CLANG_CONFIG_x86_HOST_COMBO_EXTRA_CPPFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CPPFLAGS)
 CLANG_CONFIG_x86_HOST_COMBO_EXTRA_LDFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_LDFLAGS)
 endif
-ifeq ($(HOST_OS),windows)
-CLANG_CONFIG_x86_HOST_TRIPLE := i686-pc-mingw32
-endif
 
 CLANG_CONFIG_x86_HOST_EXTRA_ASFLAGS := \
   $(CLANG_CONFIG_EXTRA_ASFLAGS) \
diff --git a/core/clang/HOST_x86_64.mk b/core/clang/HOST_x86_64.mk
index 1211e73..d46cb67 100644
--- a/core/clang/HOST_x86_64.mk
+++ b/core/clang/HOST_x86_64.mk
@@ -16,9 +16,6 @@
 CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_CPPFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_CPPFLAGS)
 CLANG_CONFIG_x86_64_HOST_COMBO_EXTRA_LDFLAGS := $(CLANG_CONFIG_x86_DARWIN_HOST_EXTRA_LDFLAGS)
 endif
-ifeq ($(HOST_OS),windows)
-CLANG_CONFIG_x86_64_HOST_TRIPLE := x86_64-pc-mingw64
-endif
 
 CLANG_CONFIG_x86_64_HOST_EXTRA_ASFLAGS := \
   $(CLANG_CONFIG_EXTRA_ASFLAGS) \
diff --git a/core/clang/HOST_x86_common.mk b/core/clang/HOST_x86_common.mk
index 74b5a69..fc98dd5 100644
--- a/core/clang/HOST_x86_common.mk
+++ b/core/clang/HOST_x86_common.mk
@@ -48,7 +48,3 @@
   -L$($(clang_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG)/x86_64-linux/lib32/
 endif
 endif  # Linux
-
-ifeq ($(HOST_OS),windows)
-# nothing required here yet
-endif
diff --git a/core/clang/TARGET_x86.mk b/core/clang/TARGET_x86.mk
index 6922f97..f982439 100644
--- a/core/clang/TARGET_x86.mk
+++ b/core/clang/TARGET_x86.mk
@@ -71,3 +71,8 @@
 $(clang_2nd_arch_prefix)RS_COMPAT_TRIPLE := i686-linux-android
 
 $(clang_2nd_arch_prefix)TARGET_LIBPROFILE_RT := $(LLVM_RTLIB_PATH)/libclang_rt.profile-i686-android.a
+
+# Address sanitizer clang config
+$(clang_2nd_arch_prefix)ADDRESS_SANITIZER_RUNTIME_LIBRARY := libclang_rt.asan-i686-android
+$(clang_2nd_arch_prefix)ADDRESS_SANITIZER_RPATH := /data/vendor/lib:/$(TARGET_COPY_OUT_VENDOR)/lib:/data/lib
+$(clang_2nd_arch_prefix)ADDRESS_SANITIZER_LINKER := /system/bin/linker_asan
diff --git a/core/clang/arm.mk b/core/clang/arm.mk
index 6b3d7c1..e66aa6c 100644
--- a/core/clang/arm.mk
+++ b/core/clang/arm.mk
@@ -10,11 +10,6 @@
   CLANG_CONFIG_arm_EXTRA_CFLAGS += -mcpu=krait -mfpu=neon-vfpv4
 endif
 
-ifeq ($(HOST_OS),darwin)
-  # Darwin is really bad at dealing with idiv/sdiv. Don't use krait on Darwin.
-  CLANG_CONFIG_arm_EXTRA_CFLAGS += -mcpu=cortex-a9
-endif
-
 CLANG_CONFIG_arm_EXTRA_CPPFLAGS :=
 
 CLANG_CONFIG_arm_EXTRA_LDFLAGS :=
diff --git a/core/clang/config.mk b/core/clang/config.mk
index e747362..ae5df08 100644
--- a/core/clang/config.mk
+++ b/core/clang/config.mk
@@ -1,11 +1,5 @@
 ## Clang configurations.
 
-# WITHOUT_CLANG covers both HOST and TARGET
-ifeq ($(WITHOUT_CLANG),true)
-WITHOUT_TARGET_CLANG := true
-WITHOUT_HOST_CLANG := true
-endif
-
 LLVM_PREBUILTS_VERSION := 3.6
 LLVM_PREBUILTS_PATH := prebuilts/clang/$(BUILD_OS)-x86/host/$(LLVM_PREBUILTS_VERSION)/bin
 LLVM_RTLIB_PATH := $(LLVM_PREBUILTS_PATH)/../lib/clang/$(LLVM_PREBUILTS_VERSION)/lib/linux/
@@ -33,7 +27,8 @@
   -Werror=int-conversion
 
 # Disable overly aggressive warning for macros defined with a leading underscore
-# This happens in AndroidConfig.h, which is included nearly everywhere.
+# This used to happen in AndroidConfig.h, which was included everywhere.
+# TODO: can we remove this now?
 CLANG_CONFIG_EXTRA_CFLAGS += \
   -Wno-reserved-id-macro
 
@@ -83,6 +78,12 @@
 CLANG_CONFIG_HOST_EXTRA_CPPFLAGS :=
 CLANG_CONFIG_HOST_EXTRA_LDFLAGS :=
 
+# Clang flags for all host cross rules
+CLANG_CONFIG_HOST_CROSS_EXTRA_ASFLAGS :=
+CLANG_CONFIG_HOST_CROSS_EXTRA_CFLAGS :=
+CLANG_CONFIG_HOST_CROSS_EXTRA_CPPFLAGS :=
+CLANG_CONFIG_HOST_CROSS_EXTRA_LDFLAGS :=
+
 # Clang flags for all target rules
 CLANG_CONFIG_TARGET_EXTRA_ASFLAGS :=
 CLANG_CONFIG_TARGET_EXTRA_CFLAGS := -nostdlibinc
@@ -125,6 +126,10 @@
 include $(BUILD_SYSTEM)/clang/HOST_$(HOST_2ND_ARCH).mk
 endif
 
+ifdef HOST_CROSS_OS
+include $(BUILD_SYSTEM)/clang/HOST_CROSS_$(HOST_CROSS_OS).mk
+endif
+
 # TARGET config
 clang_2nd_arch_prefix :=
 include $(BUILD_SYSTEM)/clang/TARGET_$(TARGET_ARCH).mk
diff --git a/core/clear_vars.mk b/core/clear_vars.mk
index c42a8e0..d0d4ff9 100644
--- a/core/clear_vars.mk
+++ b/core/clear_vars.mk
@@ -173,6 +173,13 @@
 LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH:=
 LOCAL_MODULE_UNSUPPORTED_TARGET_ARCH_WARN:=
 LOCAL_MODULE_HOST_ARCH:=
+LOCAL_MODULE_HOST_ARCH_WARN:=
+LOCAL_MODULE_UNSUPPORTED_HOST_ARCH:=
+LOCAL_MODULE_UNSUPPORTED_HOST_ARCH_WARN:=
+LOCAL_MODULE_HOST_CROSS_ARCH:=
+LOCAL_MODULE_HOST_CROSS_ARCH_WARN:=
+LOCAL_MODULE_UNSUPPORTED_HOST_CROSS_ARCH:=
+LOCAL_MODULE_UNSUPPORTED_HOST_CROSS_ARCH_WARN:=
 LOCAL_NO_FPIE :=
 LOCAL_CXX_STL := default
 LOCAL_NATIVE_COVERAGE :=
@@ -182,6 +189,7 @@
 LOCAL_SANITIZE_RECOVER:=
 LOCAL_DBUS_PROXY_PREFIX:=
 LOCAL_INIT_RC:=
+LOCAL_MODULE_HOST_OS:=
 
 # arch specific variables
 LOCAL_SRC_FILES_$(TARGET_ARCH):=
@@ -255,6 +263,40 @@
 LOCAL_CLANG_$(HOST_2ND_ARCH):=
 endif
 
+LOCAL_SRC_FILES_$(HOST_OS):=
+LOCAL_STATIC_LIBRARIES_$(HOST_OS):=
+LOCAL_SHARED_LIBRARIES_$(HOST_OS):=
+LOCAL_CFLAGS_$(HOST_OS):=
+LOCAL_CPPFLAGS_$(HOST_OS):=
+LOCAL_LDFLAGS_$(HOST_OS):=
+LOCAL_LDLIBS_$(HOST_OS):=
+LOCAL_ASFLAGS_$(HOST_OS):=
+LOCAL_C_INCLUDES_$(HOST_OS):=
+LOCAL_GENERATED_SOURCES_$(HOST_OS):=
+LOCAL_REQUIRED_MODULES_$(HOST_OS):=
+
+ifdef HOST_CROSS_OS
+LOCAL_SRC_FILES_$(HOST_CROSS_OS):=
+LOCAL_STATIC_LIBRARIES_$(HOST_CROSS_OS):=
+LOCAL_SHARED_LIBRARIES_$(HOST_CROSS_OS):=
+LOCAL_CFLAGS_$(HOST_CROSS_OS):=
+LOCAL_CPPFLAGS_$(HOST_CROSS_OS):=
+LOCAL_LDFLAGS_$(HOST_CROSS_OS):=
+LOCAL_LDLIBS_$(HOST_CROSS_OS):=
+LOCAL_ASFLAGS_$(HOST_CROSS_OS):=
+LOCAL_C_INCLUDES_$(HOST_CROSS_OS):=
+LOCAL_GENERATED_SOURCES_$(HOST_CROSS_OS):=
+LOCAL_REQUIRED_MODULES_$(HOST_CROSS_OS):=
+endif
+
+LOCAL_SRC_FILES_$(HOST_OS)_$(HOST_ARCH):=
+ifdef HOST_2ND_ARCH
+LOCAL_SRC_FILES_$(HOST_OS)_$(HOST_2ND_ARCH):=
+endif
+ifdef HOST_CROSS_OS
+LOCAL_SRC_FILES_$(HOST_CROSS_OS)_$(HOST_CROSS_ARCH):=
+endif
+
 LOCAL_SRC_FILES_32:=
 LOCAL_SRC_FILES_64:=
 LOCAL_SHARED_LIBRARIES_32:=
diff --git a/core/combo/HOST_CROSS_windows-x86.mk b/core/combo/HOST_CROSS_windows-x86.mk
new file mode 100644
index 0000000..f509594
--- /dev/null
+++ b/core/combo/HOST_CROSS_windows-x86.mk
@@ -0,0 +1,55 @@
+#
+# Copyright (C) 2006 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.
+#
+
+# Settings to use MinGW as a cross-compiler under Linux
+# Included by combo/select.make
+
+$(combo_var_prefix)GLOBAL_CFLAGS += -DUSE_MINGW -DWIN32_LEAN_AND_MEAN
+$(combo_var_prefix)GLOBAL_CFLAGS += -Wno-unused-parameter
+$(combo_var_prefix)GLOBAL_CFLAGS += --sysroot=prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/x86_64-w64-mingw32
+$(combo_var_prefix)GLOBAL_CFLAGS += -m32
+$(combo_var_prefix)GLOBAL_LDFLAGS += -m32
+TOOLS_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/bin/x86_64-w64-mingw32-
+$(combo_var_prefix)C_INCLUDES += prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/x86_64-w64-mingw32/include
+$(combo_var_prefix)C_INCLUDES += prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/lib/gcc/x86_64-w64-mingw32/4.8.3/include
+$(combo_var_prefix)GLOBAL_LD_DIRS += -Lprebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/x86_64-w64-mingw32/lib32
+
+# Workaround differences in inttypes.h between host and target.
+# See bug 12708004.
+$(combo_var_prefix)GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
+# Use C99-compliant printf functions (%zd).
+$(combo_var_prefix)GLOBAL_CFLAGS += -D__USE_MINGW_ANSI_STDIO=1
+# Admit to using >= Win2K.
+$(combo_var_prefix)GLOBAL_CFLAGS += -D_WIN32_WINNT=0x0500
+# Get 64-bit off_t and related functions.
+$(combo_var_prefix)GLOBAL_CFLAGS += -D_FILE_OFFSET_BITS=64
+
+$(combo_var_prefix)CC := $(TOOLS_PREFIX)gcc
+$(combo_var_prefix)CXX := $(TOOLS_PREFIX)g++
+$(combo_var_prefix)AR := $(TOOLS_PREFIX)ar
+
+$(combo_var_prefix)GLOBAL_LDFLAGS += \
+    --enable-stdcall-fixup
+
+ifneq ($(strip $(BUILD_HOST_static)),)
+# Statically-linked binaries are desirable for sandboxed environment
+$(combo_var_prefix)GLOBAL_LDFLAGS += -static
+endif # BUILD_HOST_static
+
+$(combo_var_prefix)SHLIB_SUFFIX := .dll
+$(combo_var_prefix)EXECUTABLE_SUFFIX := .exe
+
+$(combo_var_prefix)IS_64_BIT :=
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index 6ea526c..4caf607 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -25,7 +25,7 @@
 $(combo_2nd_arch_prefix)HOST_AR  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)ar
 
 # gcc location for clang; to be updated when clang is updated
-$(combo_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8/
+$(combo_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8
 
 # We expect SSE3 floating point math.
 $(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -msse3 -mfpmath=sse -m32 -Wa,--noexecstack -march=prescott
diff --git a/core/combo/HOST_linux-x86_64.mk b/core/combo/HOST_linux-x86_64.mk
index 13e1e8a..3708137 100644
--- a/core/combo/HOST_linux-x86_64.mk
+++ b/core/combo/HOST_linux-x86_64.mk
@@ -25,7 +25,7 @@
 HOST_AR  := $(HOST_TOOLCHAIN_PREFIX)ar
 
 # gcc location for clang; to be updated when clang is updated
-HOST_TOOLCHAIN_FOR_CLANG := prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.15-4.8/
+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
diff --git a/core/combo/HOST_windows-x86.mk b/core/combo/HOST_windows-x86.mk
deleted file mode 100644
index 30c1c75..0000000
--- a/core/combo/HOST_windows-x86.mk
+++ /dev/null
@@ -1,62 +0,0 @@
-#
-# Copyright (C) 2006 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.
-#
-
-# Settings to use MinGW as a cross-compiler under Linux
-# Included by combo/select.make
-
-HOST_ACP_UNAVAILABLE := true
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -DUSE_MINGW -DWIN32_LEAN_AND_MEAN
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -Wno-unused-parameter
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += --sysroot=prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/x86_64-w64-mingw32
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -m32
-$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -m32
-TOOLS_PREFIX := prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/bin/x86_64-w64-mingw32-
-$(combo_2nd_arch_prefix)HOST_C_INCLUDES += prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/x86_64-w64-mingw32/include
-$(combo_2nd_arch_prefix)HOST_C_INCLUDES += prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/lib/gcc/x86_64-w64-mingw32/4.8.3/include
-$(combo_2nd_arch_prefix)HOST_GLOBAL_LD_DIRS += -Lprebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8/x86_64-w64-mingw32/lib32
-
-# Workaround differences in inttypes.h between host and target.
-# See bug 12708004.
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
-# Use C99-compliant printf functions (%zd).
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -D__USE_MINGW_ANSI_STDIO=1
-# Admit to using >= Win2K.
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -D_WIN32_WINNT=0x0500
-# Get 64-bit off_t and related functions.
-$(combo_2nd_arch_prefix)HOST_GLOBAL_CFLAGS += -D_FILE_OFFSET_BITS=64
-
-$(combo_2nd_arch_prefix)HOST_CC := $(TOOLS_PREFIX)gcc$(TOOLS_EXE_SUFFIX)
-$(combo_2nd_arch_prefix)HOST_CXX := $(TOOLS_PREFIX)g++$(TOOLS_EXE_SUFFIX)
-$(combo_2nd_arch_prefix)HOST_AR := $(TOOLS_PREFIX)ar$(TOOLS_EXE_SUFFIX)
-
-$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += \
-    --enable-stdcall-fixup
-
-ifneq ($(strip $(BUILD_HOST_static)),)
-# Statically-linked binaries are desirable for sandboxed environment
-$(combo_2nd_arch_prefix)HOST_GLOBAL_LDFLAGS += -static
-endif # BUILD_HOST_static
-
-############################################################
-## Macros after this line are shared by the 64-bit config.
-
-HOST_SHLIB_SUFFIX := .dll
-HOST_EXECUTABLE_SUFFIX := .exe
-
-# $(1): The file to check
-define get-file-size
-stat --format "%s" "$(1)" | tr -d '\n'
-endef
diff --git a/core/combo/HOST_windows-x86_64.mk b/core/combo/HOST_windows-x86_64.mk
deleted file mode 100644
index 49b74e2..0000000
--- a/core/combo/HOST_windows-x86_64.mk
+++ /dev/null
@@ -1,45 +0,0 @@
-#
-# Copyright (C) 2006 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.
-#
-
-# Settings to use MinGW as a cross-compiler under Linux
-# Included by combo/select.make
-
-# right now we get these from the environment, but we should
-# pick them from the tree somewhere
-TOOLS_PREFIX := /usr/bin/amd64-mingw32msvc-
-
-HOST_ACP_UNAVAILABLE := true
-HOST_GLOBAL_CFLAGS += -DUSE_MINGW
-HOST_C_INCLUDES += /usr/lib/gcc/amd64-mingw32msvc/4.4.2/include
-HOST_GLOBAL_LD_DIRS += -L/usr/amd64-mingw32msvc/lib
-
-# Workaround differences in inttypes.h between host and target.
-# See bug 12708004.
-HOST_GLOBAL_CFLAGS += -D__STDC_FORMAT_MACROS -D__STDC_CONSTANT_MACROS
-# Use C99-compliant printf functions (%zd).
-HOST_GLOBAL_CFLAGS += -D__USE_MINGW_ANSI_STDIO=1
-# Admit to using >= Win2K.
-HOST_GLOBAL_CFLAGS += -D_WIN32_WINNT=0x0500
-
-HOST_CC := $(TOOLS_PREFIX)gcc$(TOOLS_EXE_SUFFIX)
-HOST_CXX := $(TOOLS_PREFIX)g++$(TOOLS_EXE_SUFFIX)
-HOST_AR := $(TOOLS_PREFIX)ar$(TOOLS_EXE_SUFFIX)
-
-HOST_GLOBAL_LDFLAGS += --enable-stdcall-fixup
-ifneq ($(strip $(BUILD_HOST_static)),)
-# Statically-linked binaries are desirable for sandboxed environment
-HOST_GLOBAL_LDFLAGS += -static
-endif # BUILD_HOST_static
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index 7818e3e..5f0f1d2 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -20,8 +20,7 @@
 # You can set TARGET_ARCH_VARIANT to use an arch version other
 # than ARMv5TE. Each value should correspond to a file named
 # $(BUILD_COMBOS)/arch/<name>.mk which must contain
-# makefile variable definitions similar to the preprocessor
-# defines in build/core/combo/include/arch/<combo>/AndroidConfig.h. Their
+# makefile variable definitions. Their
 # purpose is to allow module Android.mk files to selectively compile
 # different versions of code based upon the funtionality and
 # instructions available in a given architecture version.
@@ -92,8 +91,6 @@
   $(combo_2nd_arch_prefix)TARGET_thumb_CFLAGS += -marm -fno-omit-frame-pointer
 endif
 
-android_config_h := $(call select-android-config-h,linux-arm)
-
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += \
 			-msoft-float \
 			-ffunction-sections \
@@ -107,8 +104,6 @@
 			-no-canonical-prefixes \
 			-fno-canonical-system-headers \
 			$(arch_variant_cflags) \
-			-include $(android_config_h) \
-			-I $(dir $(android_config_h))
 
 # The "-Wunused-but-set-variable" option often breaks projects that enable
 # "-Wall -Werror" due to a commom idiom "ALOGV(mesg)" where ALOGV is turned
@@ -171,6 +166,7 @@
 endif
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
+KERNEL_HEADERS_COMMON += $(libc_root)/kernel/common
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-$(TARGET_$(combo_2nd_arch_prefix)ARCH)
 KERNEL_HEADERS := $(KERNEL_HEADERS_COMMON) $(KERNEL_HEADERS_ARCH)
 
diff --git a/core/combo/TARGET_linux-arm64.mk b/core/combo/TARGET_linux-arm64.mk
index 863befe..b213ea7 100644
--- a/core/combo/TARGET_linux-arm64.mk
+++ b/core/combo/TARGET_linux-arm64.mk
@@ -20,8 +20,7 @@
 # You can set TARGET_ARCH_VARIANT to use an arch version other
 # than ARMv5TE. Each value should correspond to a file named
 # $(BUILD_COMBOS)/arch/<name>.mk which must contain
-# makefile variable definitions similar to the preprocessor
-# defines in build/core/combo/include/arch/<combo>/AndroidConfig.h. Their
+# makefile variable definitions. Their
 # purpose is to allow module Android.mk files to selectively compile
 # different versions of code based upon the funtionality and
 # instructions available in a given architecture version.
@@ -70,8 +69,6 @@
 TARGET_GLOBAL_CFLAGS += \
     -fno-strict-aliasing \
 
-android_config_h := $(call select-android-config-h,linux-arm64)
-
 TARGET_GLOBAL_CFLAGS += \
 			-fstack-protector \
 			-ffunction-sections \
@@ -84,8 +81,6 @@
 			-no-canonical-prefixes \
 			-fno-canonical-system-headers \
 			$(arch_variant_cflags) \
-			-include $(android_config_h) \
-			-I $(dir $(android_config_h))
 
 # Help catch common 32/64-bit errors.
 TARGET_GLOBAL_CFLAGS += \
@@ -142,6 +137,7 @@
 	-print-file-name=libgcov.a)
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
+KERNEL_HEADERS_COMMON += $(libc_root)/kernel/common
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-$(TARGET_ARCH)
 KERNEL_HEADERS := $(KERNEL_HEADERS_COMMON) $(KERNEL_HEADERS_ARCH)
 
diff --git a/core/combo/TARGET_linux-mips.mk b/core/combo/TARGET_linux-mips.mk
index 66461d9..8e117eb 100644
--- a/core/combo/TARGET_linux-mips.mk
+++ b/core/combo/TARGET_linux-mips.mk
@@ -20,8 +20,7 @@
 # You can set TARGET_ARCH_VARIANT to use an arch version other
 # than mips32r2-fp. Each value should correspond to a file named
 # $(BUILD_COMBOS)/arch/<name>.mk which must contain
-# makefile variable definitions similar to the preprocessor
-# defines in build/core/combo/include/arch/<combo>/AndroidConfig.h. Their
+# makefile variable definitions. Their
 # purpose is to allow module Android.mk files to selectively compile
 # different versions of code based upon the funtionality and
 # instructions available in a given architecture version.
@@ -79,8 +78,6 @@
   TARGET_mips_CFLAGS += -fno-omit-frame-pointer
 endif
 
-android_config_h := $(call select-android-config-h,linux-mips)
-
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += \
 			$(TARGET_mips_CFLAGS) \
 			-U__unix -U__unix__ -Umips \
@@ -93,8 +90,6 @@
 			-no-canonical-prefixes \
 			-fno-canonical-system-headers \
 			$(arch_variant_cflags) \
-			-include $(android_config_h) \
-			-I $(dir $(android_config_h))
 
 ifneq ($(ARCH_MIPS_PAGE_SHIFT),)
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += -DPAGE_SHIFT=$(ARCH_MIPS_PAGE_SHIFT)
@@ -145,6 +140,7 @@
 endif
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
+KERNEL_HEADERS_COMMON += $(libc_root)/kernel/common
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-mips # mips covers both mips and mips64.
 KERNEL_HEADERS := $(KERNEL_HEADERS_COMMON) $(KERNEL_HEADERS_ARCH)
 
diff --git a/core/combo/TARGET_linux-mips64.mk b/core/combo/TARGET_linux-mips64.mk
index 7aaded5..565083a 100644
--- a/core/combo/TARGET_linux-mips64.mk
+++ b/core/combo/TARGET_linux-mips64.mk
@@ -20,8 +20,7 @@
 # You can set TARGET_ARCH_VARIANT to use an arch version other
 # than mips64r6. Each value should correspond to a file named
 # $(BUILD_COMBOS)/arch/<name>.mk which must contain
-# makefile variable definitions similar to the preprocessor
-# defines in build/core/combo/include/arch/<combo>/AndroidConfig.h. Their
+# makefile variable definitions. Their
 # purpose is to allow module Android.mk files to selectively compile
 # different versions of code based upon the funtionality and
 # instructions available in a given architecture version.
@@ -79,8 +78,6 @@
   TARGET_mips_CFLAGS += -fno-omit-frame-pointer
 endif
 
-android_config_h := $(call select-android-config-h,linux-mips64)
-
 TARGET_GLOBAL_CFLAGS += \
 			$(TARGET_mips_CFLAGS) \
 			-U__unix -U__unix__ -Umips \
@@ -93,8 +90,6 @@
 			-no-canonical-prefixes \
 			-fno-canonical-system-headers \
 			$(arch_variant_cflags) \
-			-include $(android_config_h) \
-			-I $(dir $(android_config_h))
 
 # Help catch common 32/64-bit errors.
 TARGET_GLOBAL_CFLAGS += \
@@ -151,6 +146,7 @@
 endif
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
+KERNEL_HEADERS_COMMON += $(libc_root)/kernel/common
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-mips
 # TODO: perhaps use $(libc_root)/kernel/uapi/asm-$(TARGET_ARCH) instead of asm-mips ?
 KERNEL_HEADERS := $(KERNEL_HEADERS_COMMON) $(KERNEL_HEADERS_ARCH)
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index 0b87920..5fff641 100644
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -72,11 +72,10 @@
 libm_root := bionic/libm
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
+KERNEL_HEADERS_COMMON += $(libc_root)/kernel/common
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-x86 # x86 covers both x86 and x86_64.
 KERNEL_HEADERS := $(KERNEL_HEADERS_COMMON) $(KERNEL_HEADERS_ARCH)
 
-android_config_h := $(call select-android-config-h,target_linux-x86)
-
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += \
 			-O2 \
 			-Wa,--noexecstack \
@@ -94,8 +93,6 @@
 			-m32 \
 			-no-canonical-prefixes \
 			-fno-canonical-system-headers \
-			-include $(android_config_h) \
-			-I $(dir $(android_config_h))
 
 $(combo_2nd_arch_prefix)TARGET_GLOBAL_CFLAGS += $(arch_variant_cflags)
 
diff --git a/core/combo/TARGET_linux-x86_64.mk b/core/combo/TARGET_linux-x86_64.mk
index bf443b3..cacfae1 100644
--- a/core/combo/TARGET_linux-x86_64.mk
+++ b/core/combo/TARGET_linux-x86_64.mk
@@ -72,6 +72,7 @@
 libm_root := bionic/libm
 
 KERNEL_HEADERS_COMMON := $(libc_root)/kernel/uapi
+KERNEL_HEADERS_COMMON += $(libc_root)/kernel/common
 KERNEL_HEADERS_ARCH   := $(libc_root)/kernel/uapi/asm-x86 # x86 covers both x86 and x86_64.
 KERNEL_HEADERS := $(KERNEL_HEADERS_COMMON) $(KERNEL_HEADERS_ARCH)
 
@@ -99,10 +100,6 @@
     -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))
-TARGET_GLOBAL_CFLAGS += $(TARGET_ANDROID_CONFIG_CFLAGS)
-
 TARGET_GLOBAL_CFLAGS += $(arch_variant_cflags)
 
 ifeq ($(ARCH_X86_HAVE_SSSE3),true)   # yes, really SSSE3, not SSE3!
diff --git a/core/combo/include/arch/linux-arm/AndroidConfig.h b/core/combo/include/arch/linux-arm/AndroidConfig.h
deleted file mode 100644
index 030a628..0000000
--- a/core/combo/include/arch/linux-arm/AndroidConfig.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-/*
- * Android config -- "android-arm".  Used for ARM device builds.
- */
-#ifndef _ANDROID_CONFIG_H
-#define _ANDROID_CONFIG_H
-
-/*
- * ===========================================================================
- *                              !!! IMPORTANT !!!
- * ===========================================================================
- *
- * This file is included by ALL C/C++ source files.  Don't put anything in
- * here unless you are absolutely certain it can't go anywhere else.
- *
- * Any C++ stuff must be wrapped with "#ifdef __cplusplus".  Do not use "//"
- * comments.
- */
-
-/*
- * Define if we're running on *our* linux on device or emulator.
- */
-#define HAVE_ANDROID_OS 1
-
-#endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/linux-arm64/AndroidConfig.h b/core/combo/include/arch/linux-arm64/AndroidConfig.h
deleted file mode 100644
index a969ab7..0000000
--- a/core/combo/include/arch/linux-arm64/AndroidConfig.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Android config -- "android-aarch64".  Used for ARM aarch64 device builds.
- */
-#ifndef _ANDROID_CONFIG_H
-#define _ANDROID_CONFIG_H
-
-/*
- * ===========================================================================
- *                              !!! IMPORTANT !!!
- * ===========================================================================
- *
- * This file is included by ALL C/C++ source files.  Don't put anything in
- * here unless you are absolutely certain it can't go anywhere else.
- *
- * Any C++ stuff must be wrapped with "#ifdef __cplusplus".  Do not use "//"
- * comments.
- */
-
-/*
- * Define if we're running on *our* linux on device or emulator.
- */
-#define HAVE_ANDROID_OS 1
-
-#endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/linux-mips/AndroidConfig.h b/core/combo/include/arch/linux-mips/AndroidConfig.h
deleted file mode 100644
index 6e46f8a..0000000
--- a/core/combo/include/arch/linux-mips/AndroidConfig.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-/*
- * Android config -- "android-mips".  Used for MIPS device builds.
- */
-#ifndef _ANDROID_CONFIG_H
-#define _ANDROID_CONFIG_H
-
-/*
- * ===========================================================================
- *                              !!! IMPORTANT !!!
- * ===========================================================================
- *
- * This file is included by ALL C/C++ source files.  Don't put anything in
- * here unless you are absolutely certain it can't go anywhere else.
- *
- * Any C++ stuff must be wrapped with "#ifdef __cplusplus".  Do not use "//"
- * comments.
- */
-
-/*
- * Define if we're running on *our* linux on device or emulator.
- */
-#define HAVE_ANDROID_OS 1
-
-#endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/linux-mips64/AndroidConfig.h b/core/combo/include/arch/linux-mips64/AndroidConfig.h
deleted file mode 100644
index d4143a7..0000000
--- a/core/combo/include/arch/linux-mips64/AndroidConfig.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Android config -- "android-mips64".  Used for MIPS device builds.
- */
-#ifndef _ANDROID_CONFIG_H
-#define _ANDROID_CONFIG_H
-
-/*
- * ===========================================================================
- *                              !!! IMPORTANT !!!
- * ===========================================================================
- *
- * This file is included by ALL C/C++ source files.  Don't put anything in
- * here unless you are absolutely certain it can't go anywhere else.
- *
- * Any C++ stuff must be wrapped with "#ifdef __cplusplus".  Do not use "//"
- * comments.
- */
-
-/*
- * Define if we're running on *our* linux on device or emulator.
- */
-#define HAVE_ANDROID_OS 1
-
-#endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/include/arch/target_linux-x86/AndroidConfig.h b/core/combo/include/arch/target_linux-x86/AndroidConfig.h
deleted file mode 100644
index 90d5f00..0000000
--- a/core/combo/include/arch/target_linux-x86/AndroidConfig.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2005 The Android Open Source Project
- *
- * Android config -- "target_linux-x86".  Used for x86 linux target devices.
- */
-#ifndef _ANDROID_CONFIG_H
-#define _ANDROID_CONFIG_H
-
-/*
- * ===========================================================================
- *                              !!! IMPORTANT !!!
- * ===========================================================================
- *
- * This file is included by ALL C/C++ source files.  Don't put anything in
- * here unless you are absolutely certain it can't go anywhere else.
- *
- * Any C++ stuff must be wrapped with "#ifdef __cplusplus".  Do not use "//"
- * comments.
- */
-
-/*
- * Define if we're running on *our* linux on device or emulator.
- */
-#define HAVE_ANDROID_OS 1
-
-#endif /* _ANDROID_CONFIG_H */
diff --git a/core/combo/javac.mk b/core/combo/javac.mk
index e3838a6..d00f541 100644
--- a/core/combo/javac.mk
+++ b/core/combo/javac.mk
@@ -35,6 +35,8 @@
     $(info CUSTOM_JAVA_COMPILER=eclipse)
 endif
 
+GLOBAL_JAVAC_DEBUG_FLAGS := -g
+
 HOST_JAVAC ?= $(COMMON_JAVAC)
 TARGET_JAVAC ?= $(COMMON_JAVAC)
 
diff --git a/core/config.mk b/core/config.mk
index 3c53d61..12308fd 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -23,6 +23,10 @@
 
 
 endef
+# The pound character "#"
+define pound
+#
+endef
 # Unfortunately you can't simply define backslash as \ or \\.
 backslash := \a
 backslash := $(patsubst %a,%,$(backslash))
@@ -116,8 +120,8 @@
 COMMON_GLOBAL_CFLAGS:= -DANDROID -fmessage-length=0 -W -Wall -Wno-unused -Winit-self -Wpointer-arith
 COMMON_RELEASE_CFLAGS:= -DNDEBUG -UDEBUG
 
-COMMON_GLOBAL_CPPFLAGS:= $(COMMON_GLOBAL_CFLAGS) -Wsign-promo
-COMMON_RELEASE_CPPFLAGS:= $(COMMON_RELEASE_CFLAGS)
+COMMON_GLOBAL_CPPFLAGS:= -Wsign-promo
+COMMON_RELEASE_CPPFLAGS:=
 
 GLOBAL_CFLAGS_NO_OVERRIDE := \
     -Werror=int-to-pointer-cast \
@@ -177,7 +181,6 @@
 
 ifeq ($(OVERRIDE_C_DATE_TIME),true)
 COMMON_GLOBAL_CFLAGS += -Wno-builtin-macro-redefined -D__DATE__="\"$(BUILD_DATETIME_C_DATE)\"" -D__TIME__=\"$(BUILD_DATETIME_C_TIME)\"
-COMMON_GLOBAL_CPPFLAGS += -Wno-builtin-macro-redefined -D__DATE__="\"$(BUILD_DATETIME_C_DATE)\"" -D__TIME__=\"$(BUILD_DATETIME_C_TIME)\"
 endif
 
 # The build system exposes several variables for where to find the kernel
@@ -246,11 +249,6 @@
 endif
 TARGET_CPU_ABI2 := $(strip $(TARGET_CPU_ABI2))
 
-# $(1): os/arch
-define select-android-config-h
-build/core/combo/include/arch/$(1)/AndroidConfig.h
-endef
-
 combo_target := HOST_
 combo_2nd_arch_prefix :=
 include $(BUILD_SYSTEM)/combo/select.mk
@@ -262,6 +260,13 @@
 include $(BUILD_SYSTEM)/combo/select.mk
 endif
 
+# Load the windows cross compiler under Linux
+ifdef HOST_CROSS_OS
+combo_target := HOST_CROSS_
+combo_2nd_arch_prefix :=
+include $(BUILD_SYSTEM)/combo/select.mk
+endif
+
 # on windows, the tools have .exe at the end, and we depend on the
 # host config stuff being done first
 
@@ -418,6 +423,12 @@
 DOXYGEN:= doxygen
 AAPT := $(HOST_OUT_EXECUTABLES)/aapt$(HOST_EXECUTABLE_SUFFIX)
 AIDL := $(HOST_OUT_EXECUTABLES)/aidl$(HOST_EXECUTABLE_SUFFIX)
+ifeq ($(HOST_OS),linux)
+BREAKPAD_DUMP_SYMS := $(HOST_OUT_EXECUTABLES)/dump_syms
+else
+# For non-supported hosts, do not generate breakpad symbols.
+BREAKPAD_GENERATE_SYMBOLS := false
+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)
@@ -576,7 +587,6 @@
 # sure to only specify them for the target compilers checked in to
 # the source tree.
 TARGET_GLOBAL_CFLAGS += $(TARGET_ERROR_FLAGS)
-TARGET_GLOBAL_CPPFLAGS += $(TARGET_ERROR_FLAGS)
 
 HOST_GLOBAL_CFLAGS += $(HOST_RELEASE_CFLAGS)
 HOST_GLOBAL_CPPFLAGS += $(HOST_RELEASE_CPPFLAGS)
@@ -592,7 +602,6 @@
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_LD_DIRS += -L$($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_PROJECT_INCLUDES := $(TARGET_PROJECT_INCLUDES)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CFLAGS += $(TARGET_ERROR_FLAGS)
-$(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CPPFLAGS += $(TARGET_ERROR_FLAGS)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CFLAGS += $($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_RELEASE_CFLAGS)
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_GLOBAL_CPPFLAGS += $($(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_RELEASE_CPPFLAGS)
 endif
@@ -608,6 +617,17 @@
 $(HOST_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_CPPFLAGS += $($(HOST_2ND_ARCH_VAR_PREFIX)HOST_RELEASE_CPPFLAGS)
 endif
 
+ifdef HOST_CROSS_OS
+HOST_CROSS_GLOBAL_CFLAGS += $(COMMON_GLOBAL_CFLAGS)
+HOST_CROSS_RELEASE_CFLAGS += $(COMMON_RELEASE_CFLAGS)
+HOST_CROSS_GLOBAL_CPPFLAGS += $(COMMON_GLOBAL_CPPFLAGS)
+HOST_CROSS_RELEASE_CPPFLAGS += $(COMMON_RELEASE_CPPFLAGS)
+HOST_CROSS_GLOBAL_LD_DIRS += -L$(HOST_CROSS_OUT_INTERMEDIATE_LIBRARIES)
+HOST_CROSS_PROJECT_INCLUDES:= $(SRC_HEADERS) $(SRC_HOST_HEADERS) $(HOST_CROSS_OUT_HEADERS)
+HOST_CROSS_GLOBAL_CFLAGS += $(HOST_CROSS_RELEASE_CFLAGS)
+HOST_CROSS_GLOBAL_CPPFLAGS += $(HOST_CROSS_RELEASE_CPPFLAGS)
+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/config_sanitizers.mk b/core/config_sanitizers.mk
index 1efc932..7189338 100644
--- a/core/config_sanitizers.mk
+++ b/core/config_sanitizers.mk
@@ -75,6 +75,14 @@
   my_sanitize := $(CLANG_DEFAULT_UB_CHECKS)
 endif
 
+ifneq ($(filter coverage,$(my_sanitize)),)
+  ifeq ($(filter address,$(my_sanitize)),)
+    $(error $(LOCAL_PATH): $(LOCAL_MODULE): Use of 'coverage' also requires 'address')
+  endif
+  my_cflags += -fsanitize-coverage=edge,indirect-calls,8bit-counters,trace-cmp
+  my_sanitize := $(filter-out coverage,$(my_sanitize))
+endif
+
 ifneq ($(my_sanitize),)
   fsanitize_arg := $(subst $(space),$(comma),$(my_sanitize)),
   my_cflags += -fsanitize=$(fsanitize_arg)
diff --git a/core/cxx_stl_setup.mk b/core/cxx_stl_setup.mk
index f150714..be8a711 100644
--- a/core/cxx_stl_setup.mk
+++ b/core/cxx_stl_setup.mk
@@ -1,6 +1,6 @@
 #############################################################
 ## Set up flags based on LOCAL_CXX_STL.
-## Input variables: LOCAL_CXX_STL
+## Input variables: LOCAL_CXX_STL, my_prefix
 ## Output variables: My_cflags, my_c_includes, my_shared_libraries, etc.
 #############################################################
 
@@ -14,7 +14,7 @@
                 my_cxx_stl := libc++_static
             endif
 
-            ifdef USE_MINGW
+            ifeq ($($(my_prefix)OS),windows)
                 # libc++ is not supported on mingw.
                 my_cxx_stl := libstdc++
             endif
@@ -36,13 +36,25 @@
         # the two options use different names for the STLs.
         $(error $(LOCAL_PATH): $(LOCAL_MODULE): Must use LOCAL_NDK_STL_VARIANT rather than LOCAL_CXX_STL for NDK binaries)
     endif
+    ifdef LOCAL_IS_HOST_MODULE
+        ifeq ($($(my_prefix)OS),windows)
+            ifneq ($(filter $(my_cxx_stl),libc++ libc++_static),)
+                # libc++ is not supported on mingw.
+                my_cxx_stl := libstdc++
+            endif
+        endif
+    endif
 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
+linux_dynamic_gcclibs := -lgcc_s -lgcc -lc -lgcc_s -lgcc
+linux_static_gcclibs := -Wl,--start-group -lgcc -lgcc_eh -lc -Wl,--end-group
+darwin_dynamic_gcclibs := -lc -lSystem
+darwin_static_gcclibs := NO_STATIC_HOST_BINARIES_ON_DARWIN
+windows_dynamic_gcclibs := \
+    -lmsvcr110 -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcrt -ladvapi32 \
+    -lshell32 -luser32 -lkernel32 -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcrt
+windows_static_gcclibs := NO_STATIC_HOST_BINARIES_ON_WINDOWS
 
 my_link_type := dynamic
 ifdef LOCAL_IS_HOST_MODULE
@@ -60,7 +72,6 @@
 
 ifneq ($(filter $(my_cxx_stl),libc++ libc++_static),)
     my_cflags += -D_USING_LIBCXX
-    my_c_includes += external/libcxx/include
 
     # Note that the structure of this means that LOCAL_CXX_STL := libc++ will
     # use the static libc++ for static executables.
@@ -78,7 +89,7 @@
         my_cppflags += -nostdinc++
         my_ldflags += -nodefaultlibs
         my_ldlibs += -lpthread -lm
-        my_ldlibs += $($(my_prefix)$(HOST_OS)_$(my_link_type)_gcclibs)
+        my_ldlibs += $($($(my_prefix)OS)_$(my_link_type)_gcclibs)
     else
         ifeq (arm,$($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH))
             my_static_libraries += libunwind_llvm
@@ -108,7 +119,7 @@
     ifdef LOCAL_IS_HOST_MODULE
         my_cppflags += -nostdinc++
         my_ldflags += -nodefaultlibs
-        my_ldlibs += $($(my_prefix)$(HOST_OS)_$(my_link_type)_gcclibs)
+        my_ldlibs += $($($(my_prefix)OS)_$(my_link_type)_gcclibs)
     endif
 else
     $(error $(LOCAL_PATH): $(LOCAL_MODULE): $(my_cxx_stl) is not a supported STL.)
diff --git a/core/definitions.mk b/core/definitions.mk
index 79831e0..af3929e 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -87,11 +87,17 @@
 $(TARGET_2ND_ARCH_VAR_PREFIX)TARGET_DEPENDENCIES_ON_SHARED_LIBRARIES :=
 HOST_DEPENDENCIES_ON_SHARED_LIBRARIES :=
 $(HOST_2ND_ARCH_VAR_PREFIX)HOST_DEPENDENCIES_ON_SHARED_LIBRARIES :=
+HOST_CROSS_DEPENDENCIES_ON_SHARED_LIBRARIES :=
 
 # Generated class file names for Android resource.
 # They are escaped and quoted so can be passed safely to a bash command.
 ANDROID_RESOURCE_GENERATED_CLASSES := 'R.class' 'R$$*.class' 'Manifest.class' 'Manifest$$*.class'
 
+# Display names for various build targets
+TARGET_DISPLAY := target
+HOST_DISPLAY := host
+HOST_CROSS_DISPLAY := host cross
+
 ###########################################################
 ## Debugging; prints a variable list to stdout
 ###########################################################
@@ -181,10 +187,10 @@
 ###########################################################
 
 define all-java-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) -name "*.java" -and -not -name ".*") \
- )
+ ))
 endef
 
 ###########################################################
@@ -203,10 +209,10 @@
 ###########################################################
 
 define all-c-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) -name "*.c" -and -not -name ".*") \
- )
+ ))
 endef
 
 ###########################################################
@@ -225,10 +231,10 @@
 ###########################################################
 
 define all-Iaidl-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) -name "I*.aidl" -and -not -name ".*") \
- )
+ ))
 endef
 
 ###########################################################
@@ -246,10 +252,10 @@
 ###########################################################
 
 define all-logtags-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) -name "*.logtags" -and -not -name ".*") \
-  )
+  ))
 endef
 
 ###########################################################
@@ -259,10 +265,10 @@
 ###########################################################
 
 define all-proto-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) -name "*.proto" -and -not -name ".*") \
-  )
+  ))
 endef
 
 ###########################################################
@@ -272,10 +278,10 @@
 ###########################################################
 
 define all-renderscript-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) \( -name "*.rs" -or -name "*.fs" \) -and -not -name ".*") \
-  )
+  ))
 endef
 
 ###########################################################
@@ -285,10 +291,10 @@
 ###########################################################
 
 define all-S-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) -name "*.S" -and -not -name ".*") \
- )
+ ))
 endef
 
 ###########################################################
@@ -298,10 +304,10 @@
 ###########################################################
 
 define all-html-files-under
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
           find -L $(1) -name "*.html" -and -not -name ".*") \
- )
+ ))
 endef
 
 ###########################################################
@@ -319,7 +325,7 @@
 ###########################################################
 
 define find-subdir-files
-$(patsubst ./%,%,$(shell cd $(LOCAL_PATH) ; find -L $(1)))
+$(sort $(patsubst ./%,%,$(shell cd $(LOCAL_PATH) ; find -L $(1))))
 endef
 
 ###########################################################
@@ -331,8 +337,8 @@
 ###########################################################
 
 define find-subdir-subdir-files
-$(filter-out $(patsubst %,$(1)/%,$(3)),$(patsubst ./%,%,$(shell cd \
-            $(LOCAL_PATH) ; find -L $(1) -maxdepth 1 -name $(2))))
+$(sort $(filter-out $(patsubst %,$(1)/%,$(3)),$(patsubst ./%,%,$(shell cd \
+            $(LOCAL_PATH) ; find -L $(1) -maxdepth 1 -name $(2)))))
 endef
 
 ###########################################################
@@ -341,10 +347,10 @@
 ###########################################################
 
 define find-subdir-assets
-$(if $(1),$(patsubst ./%,%, \
+$(sort $(if $(1),$(patsubst ./%,%, \
 	$(shell if [ -d $(1) ] ; then cd $(1) ; find ./ -not -name '.*' -and -type f -and -not -type l ; fi)), \
 	$(warning Empty argument supplied to find-subdir-assets) \
-)
+))
 endef
 
 ###########################################################
@@ -369,10 +375,10 @@
 ###########################################################
 
 define find-files-in-subdirs
-$(patsubst ./%,%, \
+$(sort $(patsubst ./%,%, \
   $(shell cd $(1) ; \
           find -L $(3) -name $(2) -and -not -name ".*") \
- )
+ ))
 endef
 
 ###########################################################
@@ -422,7 +428,8 @@
 # $(2): target name, like "NotePad"
 # $(3): if non-empty, this is a HOST target.
 # $(4): if non-empty, force the intermediates to be COMMON
-# $(5): if non-empty, force the intermedistes to be for the 2nd arch
+# $(5): if non-empty, force the intermediates to be for the 2nd arch
+# $(6): if non-empty, force the intermediates to be for the host cross os
 define intermediates-dir-for
 $(strip \
     $(eval _idfClass := $(strip $(1))) \
@@ -431,7 +438,7 @@
     $(eval _idfName := $(strip $(2))) \
     $(if $(_idfName),, \
         $(error $(LOCAL_PATH): Name not defined in call to intermediates-dir-for)) \
-    $(eval _idfPrefix := $(if $(strip $(3)),HOST,TARGET)) \
+    $(eval _idfPrefix := $(if $(strip $(3)),$(if $(strip $(6)),HOST_CROSS,HOST),TARGET)) \
     $(eval _idf2ndArchPrefix := $(if $(strip $(5)),$(TARGET_2ND_ARCH_VAR_PREFIX))) \
     $(if $(filter $(_idfPrefix)-$(_idfClass),$(COMMON_MODULE_CLASSES))$(4), \
         $(eval _idfIntBase := $($(_idfPrefix)_OUT_COMMON_INTERMEDIATES)) \
@@ -449,13 +456,14 @@
 #
 # $(1): if non-empty, force the intermediates to be COMMON
 # $(2): if non-empty, force the intermediates to be for the 2nd arch
+# $(3): if non-empty, force the intermediates to be for the host cross os
 define local-intermediates-dir
 $(strip \
     $(if $(strip $(LOCAL_MODULE_CLASS)),, \
         $(error $(LOCAL_PATH): LOCAL_MODULE_CLASS not defined before call to local-intermediates-dir)) \
     $(if $(strip $(LOCAL_MODULE)),, \
         $(error $(LOCAL_PATH): LOCAL_MODULE not defined before call to local-intermediates-dir)) \
-    $(call intermediates-dir-for,$(LOCAL_MODULE_CLASS),$(LOCAL_MODULE),$(LOCAL_IS_HOST_MODULE),$(1),$(2)) \
+    $(call intermediates-dir-for,$(LOCAL_MODULE_CLASS),$(LOCAL_MODULE),$(LOCAL_IS_HOST_MODULE),$(1),$(2),$(3)) \
 )
 endef
 
@@ -1106,7 +1114,7 @@
 ###########################################################
 
 define transform-host-cpp-to-o
-@echo "host C++: $(PRIVATE_MODULE) <= $<"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) C++: $(PRIVATE_MODULE) <= $<"
 @mkdir -p $(dir $@)
 $(hide) $(PRIVATE_CXX) \
 	$(addprefix -I , $(PRIVATE_C_INCLUDES)) \
@@ -1114,7 +1122,7 @@
 	$(addprefix -isystem ,\
 	    $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	        $(filter-out $(PRIVATE_C_INCLUDES), \
-	            $(HOST_PROJECT_INCLUDES) \
+	            $($(PRIVATE_PREFIX)PROJECT_INCLUDES) \
 	            $(PRIVATE_HOST_C_INCLUDES)))) \
 	-c \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
@@ -1144,7 +1152,7 @@
 	$(addprefix -isystem ,\
 	    $(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	        $(filter-out $(PRIVATE_C_INCLUDES), \
-	            $(HOST_PROJECT_INCLUDES) \
+	            $($(PRIVATE_PREFIX)PROJECT_INCLUDES) \
 	            $(PRIVATE_HOST_C_INCLUDES)))) \
 	-c \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
@@ -1157,12 +1165,12 @@
 endef
 
 define transform-host-c-to-o-no-deps
-@echo "host C: $(PRIVATE_MODULE) <= $<"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) C: $(PRIVATE_MODULE) <= $<"
 $(call transform-host-c-or-s-to-o-no-deps, $(PRIVATE_CFLAGS) $(PRIVATE_CONLYFLAGS) $(PRIVATE_DEBUG_CFLAGS))
 endef
 
 define transform-host-s-to-o-no-deps
-@echo "host asm: $(PRIVATE_MODULE) <= $<"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) asm: $(PRIVATE_MODULE) <= $<"
 $(call transform-host-c-or-s-to-o-no-deps, $(PRIVATE_ASFLAGS))
 endef
 
@@ -1181,7 +1189,7 @@
 ###########################################################
 
 define transform-host-m-to-o-no-deps
-@echo "host ObjC: $(PRIVATE_MODULE) <= $<"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) ObjC: $(PRIVATE_MODULE) <= $<"
 $(call transform-host-c-or-s-to-o-no-deps, $(PRIVATE_CFLAGS) $(PRIVATE_DEBUG_CFLAGS))
 endef
 
@@ -1190,6 +1198,14 @@
 $(transform-d-to-p)
 endef
 
+###########################################################
+## Commands for running gcc to compile a host Objective-C++ file
+###########################################################
+
+define transform-host-mm-to-o
+$(transform-host-cpp-to-o)
+endef
+
 
 ###########################################################
 ## Rules to compile a single C/C++ source with ../ in the path
@@ -1338,19 +1354,19 @@
     lib_to_include=$$ldir/$(notdir $(1)); \
     filelist=; \
     subdir=0; \
-    for f in `$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) t $(1) | \grep '\.o$$'`; do \
+    for f in `$($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)AR) t $(1) | \grep '\.o$$'`; do \
         if [ -e $$ldir/$$f ]; then \
            mkdir $$ldir/$$subdir; \
            ext=$$subdir/; \
            subdir=$$((subdir+1)); \
-           $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) m $$lib_to_include $$f; \
+           $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)AR) m $$lib_to_include $$f; \
         else \
            ext=; \
         fi; \
-        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) p $$lib_to_include $$f > $$ldir/$$ext$$f; \
+        $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)AR) p $$lib_to_include $$f > $$ldir/$$ext$$f; \
         filelist="$$filelist $$ldir/$$ext$$f"; \
     done ; \
-    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_ARFLAGS) \
+    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)AR) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)GLOBAL_ARFLAGS) \
         $(PRIVATE_ARFLAGS) $@ $$filelist
 
 endef
@@ -1364,12 +1380,12 @@
 # Explicitly delete the archive first so that ar doesn't
 # try to add to an existing archive.
 define transform-host-o-to-static-lib
-@echo "host StaticLib: $(PRIVATE_MODULE) ($@)"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) StaticLib: $(PRIVATE_MODULE) ($@)"
 @mkdir -p $(dir $@)
 @rm -f $@
 $(extract-and-include-host-whole-static-libs)
-$(call split-long-arguments,$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_AR) \
-    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_ARFLAGS) \
+$(call split-long-arguments,$($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)AR) \
+    $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)GLOBAL_ARFLAGS) \
     $(PRIVATE_ARFLAGS) $@,$(PRIVATE_ALL_OBJECTS))
 endef
 
@@ -1383,11 +1399,11 @@
 ifneq ($(HOST_CUSTOM_LD_COMMAND),true)
 define transform-host-o-to-shared-lib-inner
 $(hide) $(PRIVATE_CXX) \
-	-Wl,-rpath-link=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES) \
-	-Wl,-rpath,\$$ORIGIN/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES)) \
-	-Wl,-rpath,\$$ORIGIN/$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES)) \
+	-Wl,-rpath-link=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_INTERMEDIATE_LIBRARIES) \
+	-Wl,-rpath,\$$ORIGIN/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_SHARED_LIBRARIES)) \
+	-Wl,-rpath,\$$ORIGIN/$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_SHARED_LIBRARIES)) \
 	-shared -Wl,-soname,$(notdir $@) \
-	$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LD_DIRS) \
+	$($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)GLOBAL_LD_DIRS) \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 	   $(PRIVATE_HOST_GLOBAL_LDFLAGS) \
 	) \
@@ -1408,13 +1424,13 @@
 endif
 
 define transform-host-o-to-shared-lib
-@echo "host SharedLib: $(PRIVATE_MODULE) ($@)"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) SharedLib: $(PRIVATE_MODULE) ($@)"
 @mkdir -p $(dir $@)
 $(transform-host-o-to-shared-lib-inner)
 endef
 
 define transform-host-o-to-package
-@echo "host Package: $(PRIVATE_MODULE) ($@)"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) Package: $(PRIVATE_MODULE) ($@)"
 @mkdir -p $(dir $@)
 $(transform-host-o-to-shared-lib-inner)
 endef
@@ -1582,8 +1598,8 @@
 else
 HOST_FPIE_FLAGS := -pie
 # Force the correct entry point to workaround a bug in binutils that manifests with -pie
-ifeq ($(HOST_OS),windows)
-HOST_FPIE_FLAGS += -Wl,-e_mainCRTStartup
+ifeq ($(HOST_CROSS_OS),windows)
+HOST_CROSS_FPIE_FLAGS += -Wl,-e_mainCRTStartup
 endif
 endif
 
@@ -1600,10 +1616,10 @@
 	$(if $(filter true,$(NATIVE_COVERAGE)),-lgcov) \
 	$(if $(filter true,$(NATIVE_COVERAGE)),$(PRIVATE_HOST_LIBPROFILE_RT)) \
 	$(call normalize-host-libraries,$(PRIVATE_ALL_SHARED_LIBRARIES)) \
-	-Wl,-rpath-link=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES) \
-	-Wl,-rpath,\$$ORIGIN/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES)) \
-	-Wl,-rpath,\$$ORIGIN/$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_OUT_SHARED_LIBRARIES)) \
-	$($(PRIVATE_2ND_ARCH_VAR_PREFIX)HOST_GLOBAL_LD_DIRS) \
+	-Wl,-rpath-link=$($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_INTERMEDIATE_LIBRARIES) \
+	-Wl,-rpath,\$$ORIGIN/../$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_SHARED_LIBRARIES)) \
+	-Wl,-rpath,\$$ORIGIN/$(notdir $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OUT_SHARED_LIBRARIES)) \
+	$($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)GLOBAL_LD_DIRS) \
 	$(if $(PRIVATE_NO_DEFAULT_COMPILER_FLAGS),, \
 		$(PRIVATE_HOST_GLOBAL_LDFLAGS) \
 	) \
@@ -1614,7 +1630,7 @@
 endif
 
 define transform-host-o-to-executable
-@echo "host Executable: $(PRIVATE_MODULE) ($@)"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) Executable: $(PRIVATE_MODULE) ($@)"
 @mkdir -p $(dir $@)
 $(transform-host-o-to-executable-inner)
 endef
@@ -1624,6 +1640,13 @@
 ## Commands for running javac to make .class files
 ###########################################################
 
+# Add BUILD_NUMBER to apps default version name if it's unbundled build.
+ifdef TARGET_BUILD_APPS
+APPS_DEFAULT_VERSION_NAME := $(PLATFORM_VERSION)-$(BUILD_NUMBER_FROM_FILE)
+else
+APPS_DEFAULT_VERSION_NAME := $(PLATFORM_VERSION)
+endif
+
 # TODO: Right now we generate the asset resources twice, first as part
 # of generating the Java classes, then at the end when packaging the final
 # assets.  This should be changed to do one of two things: (1) Don't generate
@@ -1650,19 +1673,13 @@
     $(addprefix --min-sdk-version , $(PRIVATE_DEFAULT_APP_TARGET_SDK)) \
     $(addprefix --target-sdk-version , $(PRIVATE_DEFAULT_APP_TARGET_SDK)) \
     $(if $(filter --version-code,$(PRIVATE_AAPT_FLAGS)),,--version-code $(PLATFORM_SDK_VERSION)) \
-    $(if $(filter --version-name,$(PRIVATE_AAPT_FLAGS)),,--version-name $(PLATFORM_VERSION)-$(BUILD_NUMBER_FROM_FILE)) \
+    $(if $(filter --version-name,$(PRIVATE_AAPT_FLAGS)),,--version-name $(APPS_DEFAULT_VERSION_NAME)) \
     $(addprefix --rename-manifest-package , $(PRIVATE_MANIFEST_PACKAGE_NAME)) \
     $(addprefix --rename-instrumentation-target-package , $(PRIVATE_MANIFEST_INSTRUMENTATION_FOR))
 endef
 
 xlint_unchecked := -Xlint:unchecked
 
-ifeq (true, $(ENABLE_INCREMENTALJAVAC))
-incremental_dex := --incremental
-else
-incremental_dex :=
-endif
-
 # emit-line, <word list>, <output file>
 define emit-line
    $(if $(1),echo -n '$(strip $(1)) ' >> $(2))
@@ -1740,7 +1757,6 @@
     | sort -u > $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq
 $(hide) if [ -s $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq ] ; then \
     $(1) -encoding UTF-8 \
-    $(strip $(PRIVATE_JAVAC_DEBUG_FLAGS)) \
     $(if $(findstring true,$(PRIVATE_WARNINGS_ENABLE)),$(xlint_unchecked),) \
     $(2) \
     $(addprefix -classpath ,$(strip \
@@ -1819,7 +1835,6 @@
 fi; \
 $(call call-jack,$(PRIVATE_JACK_VM_ARGS),$(PRIVATE_JACK_EXTRA_ARGS)) \
     $(strip $(PRIVATE_JACK_FLAGS)) \
-    $(strip $(PRIVATE_JACK_DEBUG_FLAGS)) \
     $(if $(NO_OPTIMIZE_DX), \
         -D jack.dex.optimize="false") \
     $(if $(PRIVATE_RMTYPEDEFS), \
@@ -1899,7 +1914,6 @@
 fi; \
 $(call call-jack,$(PRIVATE_JACK_VM_ARGS),$(PRIVATE_JACK_EXTRA_ARGS)) \
     $(strip $(PRIVATE_JACK_FLAGS)) \
-    $(strip $(PRIVATE_JACK_DEBUG_FLAGS)) \
     $(if $(NO_OPTIMIZE_DX), \
         -D jack.dex.optimize="false") \
     $(addprefix --classpath ,$(strip \
@@ -1923,69 +1937,6 @@
 $(if $(PRIVATE_JAR_MANIFEST), $(hide) echo unsupported options JAR_MANIFEST in $@; exit 53)
 endef
 
-# Override the above definitions if we want to do incremetal javac
-ifeq (true, $(ENABLE_INCREMENTALJAVAC))
-define compile-java
-$(hide) mkdir -p $(dir $@)
-$(hide) mkdir -p $(PRIVATE_CLASS_INTERMEDIATES_DIR)
-$(hide) touch $(PRIVATE_CLASS_INTERMEDIATES_DIR)/newstamp
-$(call unzip-jar-files,$(PRIVATE_STATIC_JAVA_LIBRARIES),$(PRIVATE_CLASS_INTERMEDIATES_DIR))
-$(hide) if [ -e $(PRIVATE_CLASS_INTERMEDIATES_DIR)/stamp ] ; then \
-        newerFlag=$$(echo -n "-newer $(PRIVATE_CLASS_INTERMEDIATES_DIR)/stamp") ; \
-    fi ; \
-    find $(PRIVATE_JAVA_SOURCES) $$newerFlag > $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list ; \
-    if [ -d "$(PRIVATE_SOURCE_INTERMEDIATES_DIR)" ]; then \
-        find $(PRIVATE_SOURCE_INTERMEDIATES_DIR) -name '*.java' $$newerFlag >> $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list; \
-    fi
-$(hide) tr ' ' '\n' < $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list \
-    | sort -u > $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq
-@echo "(Incremental) build source files:"
-@cat $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq
-$(hide) if [ -s $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq ] ; then \
-    $(1) -encoding UTF-8 \
-    $(strip $(PRIVATE_JAVAC_DEBUG_FLAGS)) \
-    $(if $(findstring true,$(PRIVATE_WARNINGS_ENABLE)),$(xlint_unchecked),) \
-    $(2) \
-    $(addprefix -classpath ,$(strip \
-        $(call normalize-path-list,$(PRIVATE_ALL_JAVA_LIBRARIES) $(PRIVATE_CLASS_INTERMEDIATES_DIR)))) \
-    $(if $(findstring true,$(PRIVATE_WARNINGS_ENABLE)),$(xlint_unchecked),) \
-    -extdirs "" -d $(PRIVATE_CLASS_INTERMEDIATES_DIR) \
-    $(PRIVATE_JAVACFLAGS) \
-    \@$(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq \
-    || ( exit 41 ) \
-fi
-$(hide) rm -f $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list
-$(hide) rm -f $(PRIVATE_CLASS_INTERMEDIATES_DIR)/java-source-list-uniq
-$(hide) rm -f $@
-$(if $(PRIVATE_JAR_EXCLUDE_FILES), $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) \
-    -name $(word 1, $(PRIVATE_JAR_EXCLUDE_FILES)) \
-    $(addprefix -o -name , $(wordlist 2, 999, $(PRIVATE_JAR_EXCLUDE_FILES))) \
-    | xargs rm -rf)
-$(if $(PRIVATE_JAR_PACKAGES), \
-    $(hide) find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -mindepth 1 -type f \
-        $(foreach pkg, $(PRIVATE_JAR_PACKAGES), \
-            -not -path $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))/\*) -delete ; \
-        find $(PRIVATE_CLASS_INTERMEDIATES_DIR) -empty -delete)
-$(if $(PRIVATE_JAR_EXCLUDE_PACKAGES), $(hide) rm -rf \
-    $(foreach pkg, $(PRIVATE_JAR_EXCLUDE_PACKAGES), \
-        $(PRIVATE_CLASS_INTERMEDIATES_DIR)/$(subst .,/,$(pkg))))
-$(if $(PRIVATE_RMTYPEDEFS), $(hide) $(RMTYPEDEFS) -v $(PRIVATE_CLASS_INTERMEDIATES_DIR))
-$(if $(PRIVATE_JAR_MANIFEST), \
-    $(hide) sed -e "s/%BUILD_NUMBER%/$(BUILD_NUMBER_FROM_FILE)/" \
-            $(PRIVATE_JAR_MANIFEST) > $(dir $@)/manifest.mf && \
-        jar -cfm $@ $(dir $@)/manifest.mf \
-            -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) ., \
-    $(hide) jar -cf $@ -C $(PRIVATE_CLASS_INTERMEDIATES_DIR) .)
-$(if $(PRIVATE_EXTRA_JAR_ARGS),$(call add-java-resources-to,$@))
-$(hide) mv $(PRIVATE_CLASS_INTERMEDIATES_DIR)/newstamp $(PRIVATE_CLASS_INTERMEDIATES_DIR)/stamp
-endef
-
-define transform-java-to-classes.jar
-@echo "target Java: $(PRIVATE_MODULE) ($(PRIVATE_CLASS_INTERMEDIATES_DIR))"
-$(call compile-java,$(TARGET_JAVAC),$(PRIVATE_BOOTCLASSPATH))
-endef
-endif # ENABLE_INCREMENTALJAVAC
-
 define transform-classes.jar-to-emma
 $(hide) java -classpath $(EMMA_JAR) emma instr -outmode fullcopy -outfile \
     $(PRIVATE_EMMA_COVERAGE_FILE) -ip $< -d $(PRIVATE_EMMA_INTERMEDIATES_DIR) \
@@ -2001,7 +1952,6 @@
 $(hide) $(DX) \
     -JXms16M -JXmx2048M \
     --dex --output=$(dir $@) \
-    $(incremental_dex) \
     $(if $(NO_OPTIMIZE_DX), \
         --no-optimize) \
     $(if $(GENERATE_DEX_DEBUG), \
@@ -2074,7 +2024,7 @@
     $(addprefix --target-sdk-version , $(PRIVATE_DEFAULT_APP_TARGET_SDK)) \
     $(if $(filter --product,$(PRIVATE_AAPT_FLAGS)),,$(addprefix --product , $(TARGET_AAPT_CHARACTERISTICS))) \
     $(if $(filter --version-code,$(PRIVATE_AAPT_FLAGS)),,--version-code $(PLATFORM_SDK_VERSION)) \
-    $(if $(filter --version-name,$(PRIVATE_AAPT_FLAGS)),,--version-name $(PLATFORM_VERSION)-$(BUILD_NUMBER_FROM_FILE)) \
+    $(if $(filter --version-name,$(PRIVATE_AAPT_FLAGS)),,--version-name $(APPS_DEFAULT_VERSION_NAME)) \
     $(addprefix --rename-manifest-package , $(PRIVATE_MANIFEST_PACKAGE_NAME)) \
     $(addprefix --rename-instrumentation-target-package , $(PRIVATE_MANIFEST_INSTRUMENTATION_FOR)) \
     -F $@
@@ -2178,7 +2128,7 @@
 # Note: we intentionally don't clean PRIVATE_CLASS_INTERMEDIATES_DIR
 # in transform-java-to-classes for the sake of vm-tests.
 define transform-host-java-to-package
-@echo "host Java: $(PRIVATE_MODULE) ($(PRIVATE_CLASS_INTERMEDIATES_DIR))"
+@echo "$($(PRIVATE_PREFIX)DISPLAY) Java: $(PRIVATE_MODULE) ($(PRIVATE_CLASS_INTERMEDIATES_DIR))"
 $(call compile-java,$(HOST_JAVAC),$(PRIVATE_BOOTCLASSPATH))
 endef
 
diff --git a/core/droiddoc.mk b/core/droiddoc.mk
index aae2aba..893461a 100644
--- a/core/droiddoc.mk
+++ b/core/droiddoc.mk
@@ -23,6 +23,7 @@
 LOCAL_IS_HOST_MODULE := $(call true-or-empty,$(LOCAL_IS_HOST_MODULE))
 ifeq ($(LOCAL_IS_HOST_MODULE),true)
 my_prefix := HOST_
+LOCAL_HOST_PREFIX :=
 else
 my_prefix := TARGET_
 endif
diff --git a/core/dumpvar.mk b/core/dumpvar.mk
index 510bc7d..c7fb8db 100644
--- a/core/dumpvar.mk
+++ b/core/dumpvar.mk
@@ -80,6 +80,7 @@
 $(info   HOST_ARCH=$(HOST_ARCH))
 $(info   HOST_OS=$(HOST_OS))
 $(info   HOST_OS_EXTRA=$(HOST_OS_EXTRA))
+$(info   HOST_CROSS_OS=$(HOST_CROSS_OS))
 $(info   HOST_BUILD_TYPE=$(HOST_BUILD_TYPE))
 $(info   BUILD_ID=$(BUILD_ID))
 $(info   OUT_DIR=$(OUT_DIR))
diff --git a/core/dynamic_binary.mk b/core/dynamic_binary.mk
index 38c0cbe..240415d 100644
--- a/core/dynamic_binary.mk
+++ b/core/dynamic_binary.mk
@@ -86,6 +86,20 @@
 	@echo "target Symbolic: $(PRIVATE_MODULE) ($@)"
 	$(copy-file-to-target)
 
+###########################################################
+## Store breakpad symbols
+###########################################################
+
+ifeq ($(BREAKPAD_GENERATE_SYMBOLS),true)
+my_breakpad_path := $(PRODUCT_OUT)/breakpad/$(patsubst $(PRODUCT_OUT)/%,%,$(my_module_path))
+breakpad_input := $(relocation_packer_output)
+breakpad_output := $(my_breakpad_path)/$(my_installed_module_stem).sym
+$(breakpad_output) : $(breakpad_input) | $(BREAKPAD_DUMP_SYMS)
+	@echo "target breakpad: $(PRIVATE_MODULE) ($@)"
+	@mkdir -p $(dir $@)
+	$(hide) $(BREAKPAD_DUMP_SYMS) -c $< > $@
+$(LOCAL_BUILT_MODULE) : $(breakpad_output)
+endif
 
 ###########################################################
 ## Strip
@@ -143,5 +157,6 @@
 
 $(cleantarget): PRIVATE_CLEAN_FILES += \
     $(linked_module) \
+    $(breakpad_output) \
     $(symbolic_output) \
     $(strip_output)
diff --git a/core/envsetup.mk b/core/envsetup.mk
index c76e9a6..51a2fb3 100644
--- a/core/envsetup.mk
+++ b/core/envsetup.mk
@@ -52,12 +52,11 @@
 # BUILD_OS is the real host doing the build.
 BUILD_OS := $(HOST_OS)
 
-# Under Linux, if USE_MINGW is set, we change HOST_OS to Windows to build the
-# Windows SDK. Only a subset of tools and SDK will manage to build properly.
+HOST_CROSS_OS :=
+# We can cross-build Windows binaries on Linux
 ifeq ($(HOST_OS),linux)
-ifdef USE_MINGW
-  HOST_OS := windows
-endif
+HOST_CROSS_OS := windows
+HOST_CROSS_ARCH := x86
 endif
 
 ifeq ($(HOST_OS),)
@@ -128,11 +127,6 @@
 $(error must be empty or one of: eng user userdebug)
 endif
 
-ifdef USE_MINGW
-# We only build sdk host tools in the MinGW windows build.
-# Build it as 32-bit as well.
-HOST_PREFER_32_BIT := true
-endif
 SDK_HOST_ARCH := x86
 
 # Boards may be defined under $(SRC_TARGET_DIR)/board/$(TARGET_DEVICE)
@@ -213,8 +207,12 @@
 HOST_OUT_release := $(HOST_OUT_ROOT_release)/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
 HOST_OUT_debug := $(HOST_OUT_ROOT_debug)/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
 HOST_OUT := $(HOST_OUT_$(HOST_BUILD_TYPE))
+# TODO: remove
+BUILD_OUT := $(HOST_OUT)
 
-BUILD_OUT := $(OUT_DIR)/host/$(BUILD_OS)-$(HOST_PREBUILT_ARCH)
+HOST_CROSS_OUT_release := $(HOST_OUT_ROOT_release)/windows-$(HOST_PREBUILT_ARCH)
+HOST_CROSS_OUT_debug := $(HOST_OUT_ROOT_debug)/windows-$(HOST_PREBUILT_ARCH)
+HOST_CROSS_OUT := $(HOST_CROSS_OUT_$(HOST_BUILD_TYPE))
 
 TARGET_PRODUCT_OUT_ROOT := $(TARGET_OUT_ROOT)/product
 
@@ -232,6 +230,9 @@
 HOST_OUT_JAVA_LIBRARIES := $(HOST_OUT)/framework
 HOST_OUT_SDK_ADDON := $(HOST_OUT)/sdk_addon
 
+HOST_CROSS_OUT_EXECUTABLES := $(HOST_CROSS_OUT)/bin
+HOST_CROSS_OUT_SHARED_LIBRARIES := $(HOST_CROSS_OUT)/lib
+
 HOST_OUT_INTERMEDIATES := $(HOST_OUT)/obj
 HOST_OUT_HEADERS := $(HOST_OUT_INTERMEDIATES)/include
 HOST_OUT_INTERMEDIATE_LIBRARIES := $(HOST_OUT_INTERMEDIATES)/lib
@@ -239,9 +240,16 @@
 HOST_OUT_COMMON_INTERMEDIATES := $(HOST_COMMON_OUT_ROOT)/obj
 HOST_OUT_FAKE := $(HOST_OUT)/fake_packages
 
+HOST_CROSS_OUT_INTERMEDIATES := $(HOST_CROSS_OUT)/obj
+HOST_CROSS_OUT_HEADERS := $(HOST_CROSS_OUT_INTERMEDIATES)/include
+HOST_CROSS_OUT_INTERMEDIATE_LIBRARIES := $(HOST_CROSS_OUT_INTERMEDIATES)/lib
+HOST_CROSS_OUT_NOTICE_FILES := $(HOST_CROSS_OUT_INTERMEDIATES)/NOTICE_FILES
+
 HOST_OUT_GEN := $(HOST_OUT)/gen
 HOST_OUT_COMMON_GEN := $(HOST_COMMON_OUT_ROOT)/gen
 
+HOST_CROSS_OUT_GEN := $(HOST_CROSS_OUT)/gen
+
 # Out for HOST_2ND_ARCH
 HOST_2ND_ARCH_VAR_PREFIX := 2ND_
 HOST_2ND_ARCH_MODULE_SUFFIX := _32
@@ -268,7 +276,7 @@
 TARGET_OUT_COMMON_GEN := $(TARGET_COMMON_OUT_ROOT)/gen
 
 TARGET_OUT := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_SYSTEM)
-ifeq ($(SANITIZE_TARGET),address)
+ifneq ($(filter address,$(SANITIZE_TARGET)),)
 target_out_shared_libraries_base := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_DATA)
 else
 target_out_shared_libraries_base := $(TARGET_OUT)
@@ -325,7 +333,7 @@
 TARGET_OUT_CACHE := $(PRODUCT_OUT)/cache
 
 TARGET_OUT_VENDOR := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_VENDOR)
-ifeq ($(SANITIZE_TARGET),address)
+ifneq ($(filter address,$(SANITIZE_TARGET)),)
 target_out_vendor_shared_libraries_base := $(PRODUCT_OUT)/$(TARGET_COPY_OUT_DATA)/vendor
 else
 target_out_vendor_shared_libraries_base := $(TARGET_OUT_VENDOR)
diff --git a/core/executable.mk b/core/executable.mk
index 0ce400c..70ef0d9 100644
--- a/core/executable.mk
+++ b/core/executable.mk
@@ -7,7 +7,7 @@
 # LOCAL_MODULE_STEM_64
 
 my_skip_this_target :=
-ifeq (address,$(strip $(SANITIZE_TARGET)))
+ifneq ($(filter address,$(SANITIZE_TARGET)),)
   ifeq (true,$(LOCAL_FORCE_STATIC_EXECUTABLE))
     my_skip_this_target := true
   else ifeq (false, $(LOCAL_CLANG))
diff --git a/core/fuzz_test.mk b/core/fuzz_test.mk
index 065cc03..fc582b3 100644
--- a/core/fuzz_test.mk
+++ b/core/fuzz_test.mk
@@ -7,7 +7,7 @@
     $(error $(LOCAL_PATH): $(LOCAL_MODULE): NDK fuzz tests are not supported.)
 endif
 
-LOCAL_CFLAGS += -fsanitize-coverage=edge,indirect-calls,8bit-counters
+LOCAL_CFLAGS += -fsanitize-coverage=edge,indirect-calls,8bit-counters,trace-cmp
 LOCAL_STATIC_LIBRARIES += libLLVMFuzzer
 
 ifdef LOCAL_MODULE_PATH
diff --git a/core/goma.mk b/core/goma.mk
index 5b5830c..ff95d5a 100644
--- a/core/goma.mk
+++ b/core/goma.mk
@@ -26,6 +26,16 @@
     endif
   endif
 
+  # Goma requires a lot of processes and file descriptors.
+  ifeq ($(shell echo $$(($$(ulimit -u) < 2500 || $$(ulimit -n) < 16000))),1)
+    $(warning Max user processes and/or open files are insufficient)
+    ifeq ($(shell uname),Darwin)
+      $(error See go/ma/how-to-use-goma/how-to-use-goma-for-android to relax the limit)
+    else
+      $(error Adjust the limit by ulimit -u and ulimit -n)
+    endif
+  endif
+
   ifdef GOMA_DIR
     goma_dir := $(GOMA_DIR)
   else
diff --git a/core/host_dalvik_java_library.mk b/core/host_dalvik_java_library.mk
index 4814d70..aa700e1 100644
--- a/core/host_dalvik_java_library.mk
+++ b/core/host_dalvik_java_library.mk
@@ -45,30 +45,27 @@
     $(built_dex)
 
 # See comment in java.mk
-java_alternative_checked_module := $(full_classes_compiled_jar)
+ifndef LOCAL_CHECKED_MODULE
+LOCAL_CHECKED_MODULE := $(full_classes_compiled_jar)
+endif
 
 #######################################
 include $(BUILD_SYSTEM)/base_rules.mk
 #######################################
+java_sources := $(addprefix $(LOCAL_PATH)/, $(filter %.java,$(LOCAL_SRC_FILES))) \
+                $(filter %.java,$(LOCAL_GENERATED_SOURCES))
+all_java_sources := $(java_sources)
 
-$(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
-
-java_alternative_checked_module :=
+include $(BUILD_SYSTEM)/java_common.mk
 
 # The layers file allows you to enforce a layering between java packages.
 # Run build/tools/java-layers.py for more details.
 layers_file := $(addprefix $(LOCAL_PATH)/, $(LOCAL_JAVA_LAYERS_FILE))
 
-$(LOCAL_INTERMEDIATE_TARGETS): \
-	PRIVATE_CLASS_INTERMEDIATES_DIR := $(intermediates.COMMON)/classes
-$(LOCAL_INTERMEDIATE_TARGETS): \
-	PRIVATE_SOURCE_INTERMEDIATES_DIR := $(LOCAL_INTERMEDIATE_SOURCE_DIR)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RMTYPEDEFS :=
-
 $(cleantarget): PRIVATE_CLEAN_FILES += $(intermediates.COMMON)
 
 $(full_classes_compiled_jar): PRIVATE_JAVA_LAYERS_FILE := $(layers_file)
-$(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
+$(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(GLOBAL_JAVAC_DEBUG_FLAGS) $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES :=
 $(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES :=
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_PACKAGES :=
@@ -123,10 +120,9 @@
 $(LOCAL_INTERMEDIATE_TARGETS): \
 	PRIVATE_JACK_INCREMENTAL_DIR :=
 endif
-$(LOCAL_INTERMEDIATE_TARGETS):  PRIVATE_JACK_DEBUG_FLAGS := -g
 
 $(built_dex): PRIVATE_CLASSES_JACK := $(full_classes_jack)
-$(built_dex): PRIVATE_JACK_FLAGS := $(LOCAL_JACK_FLAGS)
+$(built_dex): PRIVATE_JACK_FLAGS := $(GLOBAL_JAVAC_DEBUG_FLAGS) $(LOCAL_JACK_FLAGS)
 $(built_dex): $(java_sources) $(java_resource_sources) $(full_jack_lib_deps) \
         $(jar_manifest_file) $(proto_java_sources_file_stamp) $(LOCAL_MODULE_MAKEFILE) \
         $(LOCAL_MODULE_MAKEFILE) $(LOCAL_ADDITIONAL_DEPENDENCIES) $(JACK_JAR) $(JACK_LAUNCHER_JAR)
diff --git a/core/host_dalvik_static_java_library.mk b/core/host_dalvik_static_java_library.mk
index 90bcc12..c6ba915 100644
--- a/core/host_dalvik_static_java_library.mk
+++ b/core/host_dalvik_static_java_library.mk
@@ -34,7 +34,7 @@
 include $(BUILD_SYSTEM)/host_java_library.mk
 # proguard is not supported
 # *.proto files are not supported
-$(full_classes_jack): PRIVATE_JACK_FLAGS := $(LOCAL_JACK_FLAGS)
+$(full_classes_jack): PRIVATE_JACK_FLAGS := $(GLOBAL_JAVAC_DEBUG_FLAGS) $(LOCAL_JACK_FLAGS)
 $(full_classes_jack): PRIVATE_JARJAR_RULES := $(LOCAL_JARJAR_RULES)
 $(full_classes_jack): \
 	PRIVATE_JACK_INTERMEDIATES_DIR := $(intermediates.COMMON)/jack-rsc
diff --git a/core/host_executable.mk b/core/host_executable.mk
index 0091f3f..bc55ef9 100644
--- a/core/host_executable.mk
+++ b/core/host_executable.mk
@@ -1,5 +1,6 @@
-
+LOCAL_IS_HOST_MODULE := true
 my_prefix := HOST_
+LOCAL_HOST_PREFIX :=
 include $(BUILD_SYSTEM)/multilib.mk
 
 ifndef LOCAL_MODULE_HOST_ARCH
@@ -50,5 +51,30 @@
 LOCAL_2ND_ARCH_VAR_PREFIX :=
 endif  # HOST_2ND_ARCH
 
+ifdef HOST_CROSS_OS
+my_prefix := HOST_CROSS_
+LOCAL_HOST_PREFIX := $(my_prefix)
+include $(BUILD_SYSTEM)/module_arch_supported.mk
+ifeq ($(my_module_arch_supported),true)
+# Build for Windows
+OVERRIDE_BUILT_MODULE_PATH :=
+# we don't want others using the cross compiled version
+saved_LOCAL_BUILT_MODULE := $(LOCAL_BUILT_MODULE)
+saved_LOCAL_INSTALLED_MODULE := $(LOCAL_INSTALLED_MODULE)
+LOCAL_BUILT_MODULE :=
+LOCAL_INSTALLED_MODULE :=
+LOCAL_INTERMEDIATE_TARGETS :=
+
+ifeq ($(LOCAL_NO_FPIE),)
+LOCAL_LDFLAGS += $(HOST_CROSS_FPIE_FLAGS)
+endif
+
+include $(BUILD_SYSTEM)/host_executable_internal.mk
+LOCAL_BUILT_MODULE := $(saved_LOCAL_BUILT_MODULE)
+LOCAL_INSTALLED_MODULE := $(saved_LOCAL_INSTALLED_MODULE)
+endif
+LOCAL_HOST_PREFIX :=
+endif
+
 LOCAL_NO_2ND_ARCH_MODULE_SUFFIX :=
 my_module_arch_supported :=
diff --git a/core/host_executable_internal.mk b/core/host_executable_internal.mk
index 0c0ac3d..b682ffd 100644
--- a/core/host_executable_internal.mk
+++ b/core/host_executable_internal.mk
@@ -5,12 +5,11 @@
 ## None.
 ###########################################################
 
-LOCAL_IS_HOST_MODULE := true
 ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
 LOCAL_MODULE_CLASS := EXECUTABLES
 endif
 ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
-LOCAL_MODULE_SUFFIX := $(HOST_EXECUTABLE_SUFFIX)
+LOCAL_MODULE_SUFFIX := $($(my_prefix)EXECUTABLE_SUFFIX)
 endif
 
 $(call host-executable-hook)
@@ -27,7 +26,7 @@
 
 include $(BUILD_SYSTEM)/binary.mk
 
-my_host_libprofile_rt := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_LIBPROFILE_RT)
+my_host_libprofile_rt := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)LIBPROFILE_RT)
 $(LOCAL_BUILT_MODULE): PRIVATE_HOST_LIBPROFILE_RT := $(my_host_libprofile_rt)
 
 $(LOCAL_BUILT_MODULE): $(all_objects) $(all_libraries)
diff --git a/core/host_fuzz_test.mk b/core/host_fuzz_test.mk
index e917959..cc7baad 100644
--- a/core/host_fuzz_test.mk
+++ b/core/host_fuzz_test.mk
@@ -3,7 +3,7 @@
 ## Common flags for host fuzz tests are added.
 ################################################
 
-LOCAL_CFLAGS += -fsanitize-coverage=edge,indirect-calls,8bit-counters
+LOCAL_CFLAGS += -fsanitize-coverage=edge,indirect-calls,8bit-counters,trace-cmp
 LOCAL_STATIC_LIBRARIES += libLLVMFuzzer
 
 include $(BUILD_HOST_EXECUTABLE)
diff --git a/core/host_java_library.mk b/core/host_java_library.mk
index 47189d7..0a1119f 100644
--- a/core/host_java_library.mk
+++ b/core/host_java_library.mk
@@ -43,7 +43,11 @@
 include $(BUILD_SYSTEM)/base_rules.mk
 #######################################
 
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RMTYPEDEFS :=
+java_sources := $(addprefix $(LOCAL_PATH)/, $(filter %.java,$(LOCAL_SRC_FILES))) \
+                $(filter %.java,$(LOCAL_GENERATED_SOURCES))
+all_java_sources := $(java_sources)
+
+include $(BUILD_SYSTEM)/java_common.mk
 
 ifeq (true,$(LOCAL_EMMA_INSTRUMENT))
 $(full_classes_emma_jar): PRIVATE_EMMA_COVERAGE_FILE := $(intermediates.COMMON)/coverage.em
@@ -69,14 +73,12 @@
 full_classes_compiled_jar := $(built_javalib_jar)
 endif # LOCAL_EMMA_INSTRUMENT
 
-$(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
-
 # The layers file allows you to enforce a layering between java packages.
 # Run build/tools/java-layers.py for more details.
 layers_file := $(addprefix $(LOCAL_PATH)/, $(LOCAL_JAVA_LAYERS_FILE))
 
 $(full_classes_compiled_jar): PRIVATE_JAVA_LAYERS_FILE := $(layers_file)
-$(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
+$(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(GLOBAL_JAVAC_DEBUG_FLAGS) $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES :=
 $(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES :=
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_PACKAGES :=
diff --git a/core/host_shared_library.mk b/core/host_shared_library.mk
index e840780..49000a4 100644
--- a/core/host_shared_library.mk
+++ b/core/host_shared_library.mk
@@ -1,4 +1,6 @@
+LOCAL_IS_HOST_MODULE := true
 my_prefix := HOST_
+LOCAL_HOST_PREFIX :=
 include $(BUILD_SYSTEM)/multilib.mk
 
 ifndef LOCAL_MODULE_HOST_ARCH
@@ -34,6 +36,26 @@
 LOCAL_2ND_ARCH_VAR_PREFIX :=
 endif  # HOST_2ND_ARCH
 
+ifdef HOST_CROSS_OS
+my_prefix := HOST_CROSS_
+LOCAL_HOST_PREFIX := $(my_prefix)
+include $(BUILD_SYSTEM)/module_arch_supported.mk
+ifeq ($(my_module_arch_supported),true)
+# Build for Windows
+OVERRIDE_BUILT_MODULE_PATH :=
+LOCAL_BUILT_MODULE :=
+LOCAL_MODULE_SUFFIX :=
+# We don't want makefiles using the cross-compiled host tool
+saved_LOCAL_INSTALLED_MODULE := $(LOCAL_INSTALLED_MODULE)
+LOCAL_INSTALLED_MODULE :=
+LOCAL_INTERMEDIATE_TARGETS :=
+
+include $(BUILD_SYSTEM)/host_shared_library_internal.mk
+LOCAL_INSTALLED_MODULE := $(saved_LOCAL_INSTALLED_MODULE)
+endif
+LOCAL_HOST_PREFIX :=
+endif
+
 my_module_arch_supported :=
 
 ###########################################################
diff --git a/core/host_shared_library_internal.mk b/core/host_shared_library_internal.mk
index 645098a..740c941 100644
--- a/core/host_shared_library_internal.mk
+++ b/core/host_shared_library_internal.mk
@@ -7,13 +7,11 @@
 ## LOCAL_MODULE_SUFFIX will be set for you.
 ###########################################################
 
-LOCAL_IS_HOST_MODULE := true
-
 ifeq ($(strip $(LOCAL_MODULE_CLASS)),)
 LOCAL_MODULE_CLASS := SHARED_LIBRARIES
 endif
 ifeq ($(strip $(LOCAL_MODULE_SUFFIX)),)
-LOCAL_MODULE_SUFFIX := $(HOST_SHLIB_SUFFIX)
+LOCAL_MODULE_SUFFIX := $($(my_prefix)SHLIB_SUFFIX)
 endif
 ifneq ($(strip $(OVERRIDE_BUILT_MODULE_PATH)),)
 $(error $(LOCAL_PATH): Illegal use of OVERRIDE_BUILT_MODULE_PATH)
@@ -36,11 +34,11 @@
 
 # Put the built modules of all shared libraries in a common directory
 # to simplify the link line.
-OVERRIDE_BUILT_MODULE_PATH := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)
+OVERRIDE_BUILT_MODULE_PATH := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)OUT_INTERMEDIATE_LIBRARIES)
 
 include $(BUILD_SYSTEM)/binary.mk
 
-my_host_libprofile_rt := $($(LOCAL_2ND_ARCH_VAR_PREFIX)HOST_LIBPROFILE_RT)
+my_host_libprofile_rt := $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)LIBPROFILE_RT)
 $(LOCAL_BUILD_MODULE): PRIVATE_HOST_LIBPROFILE_RT := $(my_host_libprofile_rt)
 
 $(LOCAL_BUILT_MODULE): \
diff --git a/core/host_static_library.mk b/core/host_static_library.mk
index 52c42ef..aa8c0e3 100644
--- a/core/host_static_library.mk
+++ b/core/host_static_library.mk
@@ -1,4 +1,6 @@
+LOCAL_IS_HOST_MODULE := true
 my_prefix := HOST_
+LOCAL_HOST_PREFIX :=
 include $(BUILD_SYSTEM)/multilib.mk
 
 ifndef LOCAL_MODULE_HOST_ARCH
@@ -34,6 +36,22 @@
 LOCAL_2ND_ARCH_VAR_PREFIX :=
 endif  # HOST_2ND_ARCH
 
+ifdef HOST_CROSS_OS
+my_prefix := HOST_CROSS_
+LOCAL_HOST_PREFIX := $(my_prefix)
+include $(BUILD_SYSTEM)/module_arch_supported.mk
+ifeq ($(my_module_arch_supported),true)
+# Build for Windows
+OVERRIDE_BUILT_MODULE_PATH :=
+LOCAL_BUILT_MODULE :=
+LOCAL_INSTALLED_MODULE :=
+LOCAL_INTERMEDIATE_TARGETS :=
+
+include $(BUILD_SYSTEM)/host_static_library_internal.mk
+endif
+LOCAL_HOST_PREFIX :=
+endif
+
 my_module_arch_supported :=
 
 ###########################################################
diff --git a/core/host_static_library_internal.mk b/core/host_static_library_internal.mk
index a533cf5..3946aa7 100644
--- a/core/host_static_library_internal.mk
+++ b/core/host_static_library_internal.mk
@@ -18,8 +18,6 @@
 endif
 LOCAL_UNINSTALLABLE_MODULE := true
 
-LOCAL_IS_HOST_MODULE := true
-
 include $(BUILD_SYSTEM)/binary.mk
 
 $(LOCAL_BUILT_MODULE): $(built_whole_libraries)
diff --git a/core/host_test_internal.mk b/core/host_test_internal.mk
index e0070c1..06949ed 100644
--- a/core/host_test_internal.mk
+++ b/core/host_test_internal.mk
@@ -2,12 +2,11 @@
 ## Shared definitions for all host test compilations.
 #####################################################
 
-ifeq ($(HOST_OS),windows)
-LOCAL_CFLAGS += -DGTEST_OS_WINDOWS
-else
-LOCAL_CFLAGS += -DGTEST_OS_LINUX
-LOCAL_LDLIBS += -lpthread
-endif
+LOCAL_CFLAGS_windows += -DGTEST_OS_WINDOWS
+LOCAL_CFLAGS_linux += -DGTEST_OS_LINUX
+LOCAL_LDLIBS_linux += -lpthread
+LOCAL_CFLAGS_darwin += -DGTEST_OS_LINUX
+LOCAL_LDLIBS_darwin += -lpthread
 
 LOCAL_CFLAGS += -DGTEST_HAS_STD_STRING -O0 -g
 LOCAL_C_INCLUDES +=  external/gtest/include
diff --git a/core/java.mk b/core/java.mk
index f295973..f3b57b8 100644
--- a/core/java.mk
+++ b/core/java.mk
@@ -1,3 +1,4 @@
+# Target Java.
 # Requires:
 # LOCAL_MODULE_SUFFIX
 # LOCAL_MODULE_CLASS
@@ -265,26 +266,80 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_INTERMEDIATE_SOURCE_DIR)/renderscript/res $(LOCAL_RESOURCE_DIR)
 endif
 
+
+###########################################################
+## AIDL: Compile .aidl files to .java
+###########################################################
+aidl_sources := $(filter %.aidl,$(LOCAL_SRC_FILES))
+
+ifneq ($(strip $(aidl_sources)),)
+aidl_java_sources := $(patsubst %.aidl,%.java,$(addprefix $(intermediates.COMMON)/src/, $(aidl_sources)))
+aidl_sources := $(addprefix $(LOCAL_PATH)/, $(aidl_sources))
+
+aidl_preprocess_import :=
+ifdef LOCAL_SDK_VERSION
+ifneq ($(filter current system_current, $(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS)),)
+  # LOCAL_SDK_VERSION is current and no TARGET_BUILD_APPS
+  aidl_preprocess_import := $(TARGET_OUT_COMMON_INTERMEDIATES)/framework.aidl
+else
+  aidl_preprocess_import := $(HISTORICAL_SDK_VERSIONS_ROOT)/$(LOCAL_SDK_VERSION)/framework.aidl
+endif # not current or system_current
+else
+# build against the platform.
+LOCAL_AIDL_INCLUDES += $(FRAMEWORKS_BASE_JAVA_SRC_DIRS)
+endif # LOCAL_SDK_VERSION
+$(aidl_java_sources): PRIVATE_AIDL_FLAGS := -b $(addprefix -p,$(aidl_preprocess_import)) -I$(LOCAL_PATH) -I$(LOCAL_PATH)/src $(addprefix -I,$(LOCAL_AIDL_INCLUDES))
+
+$(aidl_java_sources): $(intermediates.COMMON)/src/%.java: \
+        $(LOCAL_PATH)/%.aidl \
+        $(LOCAL_MODULE_MAKEFILE) \
+        $(LOCAL_ADDITIONAL_DEPENDENCIES) \
+        $(AIDL) \
+        $(aidl_preprocess_import)
+	$(transform-aidl-to-java)
+-include $(aidl_java_sources:%.java=%.P)
+
+else
+aidl_java_sources :=
+endif
+
+##########################################
+
 # All of the rules after full_classes_compiled_jar are very unlikely
 # to fail except for bugs in their respective tools.  If you would
 # like to run these rules, add the "all" modifier goal to the make
 # command line.
+ifndef LOCAL_CHECKED_MODULE
 ifdef full_classes_jar
-java_alternative_checked_module := $(full_classes_compiled_jar)
-else
-java_alternative_checked_module :=
+LOCAL_CHECKED_MODULE := $(full_classes_compiled_jar)
 endif
-
-# TODO: It looks like the only thing we need from base_rules is
-# all_java_sources.  See if we can get that by adding a
-# common_java.mk, and moving the include of base_rules.mk to
-# after all the declarations.
+endif
 
 #######################################
 include $(BUILD_SYSTEM)/base_rules.mk
 #######################################
 
-java_alternative_checked_module :=
+###########################################################
+## logtags: emit java source
+###########################################################
+ifneq ($(strip $(logtags_sources)),)
+
+logtags_java_sources := $(patsubst %.logtags,%.java,$(addprefix $(intermediates.COMMON)/src/, $(logtags_sources)))
+logtags_sources := $(addprefix $(LOCAL_PATH)/, $(logtags_sources))
+
+$(logtags_java_sources): $(intermediates.COMMON)/src/%.java: $(LOCAL_PATH)/%.logtags $(TARGET_OUT_COMMON_INTERMEDIATES)/all-event-log-tags.txt
+	$(transform-logtags-to-java)
+
+else
+logtags_java_sources :=
+endif
+
+##########################################
+java_sources := $(addprefix $(LOCAL_PATH)/, $(filter %.java,$(LOCAL_SRC_FILES))) $(aidl_java_sources) $(logtags_java_sources) \
+                $(filter %.java,$(LOCAL_GENERATED_SOURCES))
+all_java_sources := $(java_sources) $(addprefix $(TARGET_OUT_COMMON_INTERMEDIATES)/, $(filter %.java,$(LOCAL_INTERMEDIATE_SOURCES)))
+
+include $(BUILD_SYSTEM)/java_common.mk
 
 #######################################
 # defines built_odex along with rule to install odex
@@ -320,16 +375,6 @@
 endif
 endif
 
-# We use intermediates.COMMON because the classes.jar/.dex files will be
-# common even if LOCAL_BUILT_MODULE isn't.
-#
-# Override some target variables that base_rules set up for us.
-$(LOCAL_INTERMEDIATE_TARGETS): \
-	PRIVATE_CLASS_INTERMEDIATES_DIR := $(intermediates.COMMON)/classes
-$(LOCAL_INTERMEDIATE_TARGETS): \
-	PRIVATE_SOURCE_INTERMEDIATES_DIR := $(LOCAL_INTERMEDIATE_SOURCE_DIR)
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RMTYPEDEFS := $(LOCAL_RMTYPEDEFS)
-
 # Since we're using intermediates.COMMON, make sure that it gets cleaned
 # properly.
 $(cleantarget): PRIVATE_CLEAN_FILES += $(intermediates.COMMON)
@@ -364,7 +409,7 @@
 # This intentionally depends on java_sources, not all_java_sources.
 # Deps for generated source files must be handled separately,
 # via deps on the target that generates the sources.
-$(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(LOCAL_JAVACFLAGS)
+$(full_classes_compiled_jar): PRIVATE_JAVACFLAGS := $(GLOBAL_JAVAC_DEBUG_FLAGS) $(LOCAL_JAVACFLAGS)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_FILES := $(LOCAL_JAR_EXCLUDE_FILES)
 $(full_classes_compiled_jar): PRIVATE_JAR_PACKAGES := $(LOCAL_JAR_PACKAGES)
 $(full_classes_compiled_jar): PRIVATE_JAR_EXCLUDE_PACKAGES := $(LOCAL_JAR_EXCLUDE_PACKAGES)
@@ -381,8 +426,6 @@
         $(LOCAL_ADDITIONAL_DEPENDENCIES)
 	$(transform-java-to-classes.jar)
 
-$(full_classes_compiled_jar): PRIVATE_JAVAC_DEBUG_FLAGS := -g
-
 # Run jarjar if necessary, otherwise just copy the file.
 ifneq ($(strip $(LOCAL_JARJAR_RULES)),)
 $(full_classes_jarjar_jar): PRIVATE_JARJAR_RULES := $(LOCAL_JARJAR_RULES)
@@ -574,8 +617,6 @@
 endif
 
 ifdef full_classes_jar
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_DEBUG_FLAGS := -g
-
 ifdef LOCAL_PROGUARD_ENABLED
 
 ifndef LOCAL_JACK_PROGUARD_FLAGS
@@ -591,7 +632,7 @@
 $(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_PROGUARD_FLAGS :=
 endif # LOCAL_PROGUARD_ENABLED defined
 
-$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_FLAGS := $(LOCAL_JACK_FLAGS)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_FLAGS := $(GLOBAL_JAVAC_DEBUG_FLAGS) $(LOCAL_JACK_FLAGS)
 
 jack_all_deps := $(java_sources) $(java_resource_sources) $(full_jack_lib_deps) \
         $(jar_manifest_file) $(layers_file) $(RenderScript_file_stamp) $(proguard_flag_files) \
diff --git a/core/java_common.mk b/core/java_common.mk
new file mode 100644
index 0000000..2195691
--- /dev/null
+++ b/core/java_common.mk
@@ -0,0 +1,328 @@
+# Common to host and target Java modules.
+
+###########################################################
+## .proto files: Compile proto files to .java
+###########################################################
+proto_sources := $(filter %.proto,$(LOCAL_SRC_FILES))
+# Because names of the .java files compiled from .proto files are unknown until the
+# .proto files are compiled, we use a timestamp file as depedency.
+proto_java_sources_file_stamp :=
+ifneq ($(proto_sources),)
+proto_sources_fullpath := $(addprefix $(LOCAL_PATH)/, $(proto_sources))
+
+# By putting the generated java files into $(LOCAL_INTERMEDIATE_SOURCE_DIR), they will be
+# automatically found by the java compiling function transform-java-to-classes.jar.
+proto_java_intemediate_dir := $(LOCAL_INTERMEDIATE_SOURCE_DIR)/proto
+proto_java_sources_file_stamp := $(proto_java_intemediate_dir)/Proto.stamp
+proto_java_sources_dir := $(proto_java_intemediate_dir)/src
+
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_INCLUDES := $(TOP)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_SRC_FILES := $(proto_sources_fullpath)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_DIR := $(proto_java_sources_dir)
+ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),micro)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javamicro_out
+else
+  ifeq ($(LOCAL_PROTOC_OPTIMIZE_TYPE),nano)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --javanano_out
+  else
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_OPTION := --java_out
+  endif
+endif
+$(proto_java_sources_file_stamp): PRIVATE_PROTOC_FLAGS := $(LOCAL_PROTOC_FLAGS)
+$(proto_java_sources_file_stamp): PRIVATE_PROTO_JAVA_OUTPUT_PARAMS := $(LOCAL_PROTO_JAVA_OUTPUT_PARAMS)
+$(proto_java_sources_file_stamp) : $(proto_sources_fullpath) $(PROTOC)
+	$(call transform-proto-to-java)
+
+#TODO: protoc should output the dependencies introduced by imports.
+endif # proto_sources
+
+#########################################
+## Java resources
+
+# Look for resource files in any specified directories.
+# Non-java and non-doc files will be picked up as resources
+# and included in the output jar file.
+java_resource_file_groups :=
+
+LOCAL_JAVA_RESOURCE_DIRS := $(strip $(LOCAL_JAVA_RESOURCE_DIRS))
+ifneq ($(LOCAL_JAVA_RESOURCE_DIRS),)
+  # This makes a list of words like
+  #     <dir1>::<file1>:<file2> <dir2>::<file1> <dir3>:
+  # where each of the files is relative to the directory it's grouped with.
+  # Directories that don't contain any resource files will result in groups
+  # that end with a colon, and they are stripped out in the next step.
+  java_resource_file_groups += \
+    $(foreach dir,$(LOCAL_JAVA_RESOURCE_DIRS), \
+	$(subst $(space),:,$(strip \
+		$(LOCAL_PATH)/$(dir): \
+	    $(patsubst ./%,%,$(shell cd $(LOCAL_PATH)/$(dir) && \
+		find . \
+		    -type d -a -name ".svn" -prune -o \
+		    -type f \
+			-a \! -name "*.java" \
+			-a \! -name "package.html" \
+			-a \! -name "overview.html" \
+			-a \! -name ".*.swp" \
+			-a \! -name ".DS_Store" \
+			-a \! -name "*~" \
+			-print \
+		    )) \
+	)) \
+    )
+  java_resource_file_groups := $(filter-out %:,$(java_resource_file_groups))
+endif # LOCAL_JAVA_RESOURCE_DIRS
+
+LOCAL_JAVA_RESOURCE_FILES := $(strip $(LOCAL_JAVA_RESOURCE_FILES))
+ifneq ($(LOCAL_JAVA_RESOURCE_FILES),)
+  java_resource_file_groups += \
+    $(foreach f,$(LOCAL_JAVA_RESOURCE_FILES), \
+	$(patsubst %/,%,$(dir $(f)))::$(notdir $(f)) \
+     )
+endif # LOCAL_JAVA_RESOURCE_FILES
+
+ifdef java_resource_file_groups
+  # The full paths to all resources, used for dependencies.
+  java_resource_sources := \
+    $(foreach group,$(java_resource_file_groups), \
+	$(addprefix $(word 1,$(subst :,$(space),$(group)))/, \
+	    $(wordlist 2,9999,$(subst :,$(space),$(group))) \
+	) \
+    )
+  # The arguments to jar that will include these files in a jar file.
+  # Quote the file name to handle special characters (such as #) correctly.
+  extra_jar_args := \
+    $(foreach group,$(java_resource_file_groups), \
+	$(addprefix -C "$(word 1,$(subst :,$(space),$(group)))" , \
+	    $(foreach w, $(wordlist 2,9999,$(subst :,$(space),$(group))), "$(w)" ) \
+	) \
+    )
+  java_resource_file_groups :=
+else
+  java_resource_sources :=
+  extra_jar_args :=
+endif # java_resource_file_groups
+
+######################################
+## PRIVATE java vars
+# LOCAL_SOURCE_FILES_ALL_GENERATED is set only if the module does not have static source files,
+# but generated source files in its LOCAL_INTERMEDIATE_SOURCE_DIR.
+# You have to set up the dependency in some other way.
+need_compile_java := $(strip $(all_java_sources)$(all_res_assets)$(java_resource_sources))$(LOCAL_STATIC_JAVA_LIBRARIES)$(filter true,$(LOCAL_SOURCE_FILES_ALL_GENERATED))
+ifdef need_compile_java
+
+full_static_java_libs := \
+    $(foreach lib,$(LOCAL_STATIC_JAVA_LIBRARIES), \
+      $(call intermediates-dir-for, \
+        JAVA_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),COMMON)/javalib.jar)
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_STATIC_JAVA_LIBRARIES := $(full_static_java_libs)
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RESOURCE_DIR := $(LOCAL_RESOURCE_DIR)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_ASSET_DIR := $(LOCAL_ASSET_DIR)
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_CLASS_INTERMEDIATES_DIR := $(intermediates.COMMON)/classes
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_SOURCE_INTERMEDIATES_DIR := $(intermediates.COMMON)/src
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAVA_SOURCES := $(all_java_sources)
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_RMTYPEDEFS := $(LOCAL_RMTYPEDEFS)
+
+# full_java_libs: The list of files that should be used as the classpath.
+#                 Using this list as a dependency list WILL NOT WORK.
+# full_java_lib_deps: Should be specified as a prerequisite of this module
+#                 to guarantee that the files in full_java_libs will
+#                 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)
+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)
+else ifeq ($(LOCAL_SDK_VERSION)$(TARGET_BUILD_APPS),system_current)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH := -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))
+endif # current or system_current
+endif # LOCAL_SDK_VERSION
+
+full_shared_java_libs := $(call java-lib-files,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
+full_java_lib_deps := $(call java-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
+
+else # LOCAL_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))
+
+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)) \
+    $(full_shared_java_libs)
+else
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH :=
+
+full_shared_java_libs := $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/,\
+    $(addsuffix $(COMMON_JAVA_PACKAGE_SUFFIX),$(LOCAL_JAVA_LIBRARIES)))
+full_java_lib_deps := $(full_shared_java_libs)
+endif # USE_CORE_LIB_BOOTCLASSPATH
+endif # !LOCAL_IS_HOST_MODULE
+
+full_java_libs := $(full_shared_java_libs) $(full_static_java_libs) $(LOCAL_CLASSPATH)
+full_java_lib_deps := $(full_java_lib_deps) $(full_static_java_libs) $(LOCAL_CLASSPATH)
+
+ifndef LOCAL_IS_HOST_MODULE
+# This is set by packages that are linking to other packages that export
+# shared libraries, allowing them to make use of the code in the linked apk.
+apk_libraries := $(sort $(LOCAL_APK_LIBRARIES) $(LOCAL_RES_LIBRARIES))
+ifneq ($(apk_libraries),)
+  link_apk_libraries := \
+      $(foreach lib,$(apk_libraries), \
+        $(call intermediates-dir-for, \
+              APPS,$(lib),,COMMON)/classes.jar)
+
+  # link against the jar with full original names (before proguard processing).
+  full_shared_java_libs += $(link_apk_libraries)
+  full_java_libs += $(link_apk_libraries)
+  full_java_lib_deps += $(link_apk_libraries)
+endif
+
+# This is set by packages that contain instrumentation, allowing them to
+# link against the package they are instrumenting.  Currently only one such
+# package is allowed.
+LOCAL_INSTRUMENTATION_FOR := $(strip $(LOCAL_INSTRUMENTATION_FOR))
+ifdef LOCAL_INSTRUMENTATION_FOR
+  ifneq ($(words $(LOCAL_INSTRUMENTATION_FOR)),1)
+    $(error \
+        $(LOCAL_PATH): Multiple LOCAL_INSTRUMENTATION_FOR members defined)
+  endif
+
+  link_instr_intermediates_dir.COMMON := $(call intermediates-dir-for, \
+      APPS,$(LOCAL_INSTRUMENTATION_FOR),,COMMON)
+  # link against the jar with full original names (before proguard processing).
+  link_instr_classes_jar := $(link_instr_intermediates_dir.COMMON)/classes.jar
+  full_java_libs += $(link_instr_classes_jar)
+  full_java_lib_deps += $(link_instr_classes_jar)
+endif  # LOCAL_INSTRUMENTATION_FOR
+endif  # LOCAL_IS_HOST_MODULE
+
+endif  # need_compile_java
+
+# We may want to add jar manifest or jar resource files even if there is no java code at all.
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_EXTRA_JAR_ARGS := $(extra_jar_args)
+jar_manifest_file :=
+ifneq ($(strip $(LOCAL_JAR_MANIFEST)),)
+jar_manifest_file := $(LOCAL_PATH)/$(LOCAL_JAR_MANIFEST)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAR_MANIFEST := $(jar_manifest_file)
+else
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JAR_MANIFEST :=
+endif
+
+##########################################################
+ifndef LOCAL_IS_HOST_MODULE
+## AAPT Flags
+# aapt doesn't accept multiple --extra-packages flags.
+# We have to collapse them into a single --extra-packages flag here.
+LOCAL_AAPT_FLAGS := $(strip $(LOCAL_AAPT_FLAGS))
+ifdef LOCAL_AAPT_FLAGS
+ifeq ($(filter 0 1,$(words $(filter --extra-packages,$(LOCAL_AAPT_FLAGS)))),)
+aapt_flags := $(subst --extra-packages$(space),--extra-packages@,$(LOCAL_AAPT_FLAGS))
+aapt_flags_extra_packages := $(patsubst --extra-packages@%,%,$(filter --extra-packages@%,$(aapt_flags)))
+aapt_flags_extra_packages := $(sort $(subst :,$(space),$(aapt_flags_extra_packages)))
+LOCAL_AAPT_FLAGS := $(filter-out --extra-packages@%,$(aapt_flags)) \
+    --extra-packages $(subst $(space),:,$(aapt_flags_extra_packages))
+aapt_flags_extra_packages :=
+aapt_flags :=
+endif
+endif
+
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_AAPT_FLAGS := $(LOCAL_AAPT_FLAGS) $(PRODUCT_AAPT_FLAGS)
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_MANIFEST_PACKAGE_NAME := $(LOCAL_MANIFEST_PACKAGE_NAME)
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_MANIFEST_INSTRUMENTATION_FOR := $(LOCAL_MANIFEST_INSTRUMENTATION_FOR)
+
+ifdef aidl_sources
+ALL_MODULES.$(my_register_name).AIDL_FILES := $(aidl_sources)
+endif
+endif  # !LOCAL_IS_HOST_MODULE
+
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_ALL_JAVA_LIBRARIES := $(full_java_libs)
+
+ALL_MODULES.$(my_register_name).INTERMEDIATE_SOURCE_DIR := \
+    $(ALL_MODULES.$(my_register_name).INTERMEDIATE_SOURCE_DIR) $(LOCAL_INTERMEDIATE_SOURCE_DIR)
+
+###########################################################
+# JACK
+###########################################################
+ifdef LOCAL_JACK_ENABLED
+ifdef need_compile_java
+
+full_static_jack_libs := \
+    $(foreach lib,$(LOCAL_STATIC_JAVA_LIBRARIES), \
+      $(call intermediates-dir-for, \
+        JAVA_LIBRARIES,$(lib),$(LOCAL_IS_HOST_MODULE),COMMON)/classes.jack)
+
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_STATIC_JACK_LIBRARIES := $(full_static_jack_libs)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_VM_ARGS := $(LOCAL_JACK_VM_ARGS)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_JACK_EXTRA_ARGS := $(LOCAL_JACK_EXTRA_ARGS)
+
+ifndef LOCAL_IS_HOST_MODULE
+ifeq ($(LOCAL_SDK_VERSION),)
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,core-libart)
+else
+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)
+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)
+else
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES := $(call jack-lib-files,sdk_v$(LOCAL_SDK_VERSION))
+endif # current or system_current
+endif # LOCAL_SDK_VERSION
+
+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 # 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))
+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
+$(LOCAL_INTERMEDIATE_TARGETS): PRIVATE_BOOTCLASSPATH_JAVA_LIBRARIES :=
+full_shared_jack_libs := $(call jack-lib-deps,$(LOCAL_JAVA_LIBRARIES),$(LOCAL_IS_HOST_MODULE))
+full_jack_lib_deps := $(full_shared_jack_libs)
+endif # USE_CORE_LIB_BOOTCLASSPATH
+endif # !LOCAL_IS_HOST_MODULE
+full_jack_libs := $(full_shared_jack_libs) $(full_static_jack_libs) $(LOCAL_JACK_CLASSPATH)
+full_jack_lib_deps += $(full_static_jack_libs) $(LOCAL_JACK_CLASSPATH)
+
+ifndef LOCAL_IS_HOST_MODULE
+# This is set by packages that are linking to other packages that export
+# shared libraries, allowing them to make use of the code in the linked apk.
+ifneq ($(apk_libraries),)
+  link_apk_jack_libraries := \
+      $(foreach lib,$(apk_libraries), \
+        $(call intermediates-dir-for, \
+              APPS,$(lib),,COMMON)/classes.jack)
+
+  # link against the jar with full original names (before proguard processing).
+  full_shared_jack_libs += $(link_apk_jack_libraries)
+  full_jack_libs += $(link_apk_jack_libraries)
+  full_jack_lib_deps += $(link_apk_jack_libraries)
+endif
+
+# This is set by packages that contain instrumentation, allowing them to
+# link against the package they are instrumenting.  Currently only one such
+# package is allowed.
+ifdef LOCAL_INSTRUMENTATION_FOR
+   # link against the jar with full original names (before proguard processing).
+   link_instr_classes_jack := $(link_instr_intermediates_dir.COMMON)/classes.noshrob.jack
+   full_jack_libs += $(link_instr_classes_jack)
+   full_jack_lib_deps += $(link_instr_classes_jack)
+endif  # LOCAL_INSTRUMENTATION_FOR
+endif  # !LOCAL_IS_HOST_MODULE
+
+# Propagate local configuration options to this target.
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_ALL_JACK_LIBRARIES:= $(full_jack_libs)
+$(LOCAL_INTERMEDIATE_TARGETS) : PRIVATE_JARJAR_RULES := $(LOCAL_JARJAR_RULES)
+
+endif  # need_compile_java
+endif # LOCAL_JACK_ENABLED
diff --git a/core/main.mk b/core/main.mk
index f9bd3f8..f860f54 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -92,9 +92,15 @@
 # and host information.
 include $(BUILD_SYSTEM)/config.mk
 
-ifeq ($(USE_NINJA),true)
+ifneq ($(USE_NINJA),false)
+# Mark this is a ninja build.
+$(shell mkdir -p $(OUT_DIR) && touch $(OUT_DIR)/ninja_build)
 include build/core/ninja.mk
 else # !USE_NINJA
+ifeq ($(MAKELEVEL),0)
+# Remove ninja build mark if it exists.
+$(shell rm -f $(OUT_DIR)/ninja_build)
+endif
 
 # Write the build number to a file so it can be read back in
 # without changing the command line every time.  Avoids rebuilds
@@ -249,23 +255,7 @@
 # These are the modifier targets that don't do anything themselves, but
 # change the behavior of the build.
 # (must be defined before including definitions.make)
-INTERNAL_MODIFIER_TARGETS := showcommands all incrementaljavac
-
-.PHONY: incrementaljavac
-incrementaljavac: ;
-
-# WARNING:
-# ENABLE_INCREMENTALJAVAC should NOT be enabled by default, because change of
-# a Java source file won't trigger rebuild of its dependent Java files.
-# You can only enable it by adding "incrementaljavac" to your make command line.
-# You are responsible for the correctness of the incremental build.
-# This may decrease incremental build time dramatically for large Java libraries,
-# such as core.jar, framework.jar, etc.
-ENABLE_INCREMENTALJAVAC :=
-ifneq (,$(filter incrementaljavac, $(MAKECMDGOALS)))
-ENABLE_INCREMENTALJAVAC := true
-MAKECMDGOALS := $(filter-out incrementaljavac, $(MAKECMDGOALS))
-endif
+INTERNAL_MODIFIER_TARGETS := showcommands all
 
 # EMMA_INSTRUMENT_STATIC merges the static emma library to each emma-enabled module.
 ifeq (true,$(EMMA_INSTRUMENT_STATIC))
@@ -465,16 +455,6 @@
 $(INTERNAL_MODIFIER_TARGETS): $(DEFAULT_GOAL)
 endif
 
-# Bring in all modules that need to be built.
-ifeq ($(HOST_OS),windows)
-SDK_ONLY := true
-endif
-
-ifeq ($(SDK_ONLY),true)
-include $(TOPDIR)sdk/build/windows_sdk_whitelist.mk
-include $(TOPDIR)development/build/windows_sdk_whitelist.mk
-
-else	# !SDK_ONLY
 #
 # Typical build; include any Android.mk files we can find.
 #
@@ -482,8 +462,6 @@
 
 FULL_BUILD := true
 
-endif	# !SDK_ONLY
-
 # Before we go and include all of the module makefiles, stash away
 # the PRODUCT_* values so that later we can verify they are not modified.
 stash_product_vars:=true
@@ -595,6 +573,8 @@
     $(m))))
 endef
 
+# If a module is for a cross host os, the required modules must be for
+# that OS too.
 # If a module is built for 32-bit, the required modules must be 32-bit too;
 # Otherwise if the module is an exectuable or shared library,
 #   the required modules must be 64-bit;
@@ -602,6 +582,8 @@
 $(foreach m,$(ALL_MODULES),\
   $(eval r := $(ALL_MODULES.$(m).REQUIRED))\
   $(if $(r),\
+    $(if $(ALL_MODULES.$(m).FOR_HOST_CROSS),\
+      $(eval r := $(addprefix host_cross_,$(r))))\
     $(if $(ALL_MODULES.$(m).FOR_2ND_ARCH),\
       $(eval r_r := $(call get-32-bit-modules-if-we-can,$(r))),\
       $(if $(filter EXECUTABLES SHARED_LIBRARIES,$(ALL_MODULES.$(m).CLASS)),\
@@ -624,32 +606,40 @@
     $(eval r := $(call module-installed-files,$(r))) \
     $(eval t_m := $(filter $(TARGET_OUT_ROOT)/%, $(ALL_MODULES.$(m).INSTALLED))) \
     $(eval h_m := $(filter $(HOST_OUT_ROOT)/%, $(ALL_MODULES.$(m).INSTALLED))) \
+    $(eval hc_m := $(filter $(HOST_CROSS_OUT_ROOT)/%, $(ALL_MODULES.$(m).INSTALLED))) \
     $(eval t_r := $(filter $(TARGET_OUT_ROOT)/%, $(r))) \
     $(eval h_r := $(filter $(HOST_OUT_ROOT)/%, $(r))) \
+    $(eval hc_r := $(filter $(HOST_CROSS_OUT_ROOT)/%, $(r))) \
     $(eval t_m := $(filter-out $(t_r), $(t_m))) \
     $(eval h_m := $(filter-out $(h_r), $(h_m))) \
+    $(eval hc_m := $(filter-out $(hc_r), $(hc_m))) \
     $(if $(t_m), $(eval $(call add-required-deps, $(t_m),$(t_r)))) \
     $(if $(h_m), $(eval $(call add-required-deps, $(h_m),$(h_r)))) \
+    $(if $(hc_m), $(eval $(call add-required-deps, $(hc_m),$(hc_r)))) \
    ) \
  )
 
 t_m :=
 h_m :=
+hc_m :=
 t_r :=
 h_r :=
+hc_r :=
 
 # Establish the dependecies on the shared libraries.
 # It also adds the shared library module names to ALL_MODULES.$(m).REQUIRED,
 # so they can be expanded to product_MODULES later.
-# $(1): TARGET_ or HOST_.
+# $(1): TARGET_ or HOST_ or HOST_CROSS_.
 # $(2): non-empty for 2nd arch.
+# $(3): non-empty for host cross compile.
 define resolve-shared-libs-depes
 $(foreach m,$($(if $(2),$($(1)2ND_ARCH_VAR_PREFIX))$(1)DEPENDENCIES_ON_SHARED_LIBRARIES),\
   $(eval p := $(subst :,$(space),$(m)))\
   $(eval mod := $(firstword $(p)))\
   $(eval deps := $(subst $(comma),$(space),$(lastword $(p))))\
   $(if $(2),$(eval deps := $(addsuffix $($(1)2ND_ARCH_MODULE_SUFFIX),$(deps))))\
-  $(eval r := $(filter $($(1)OUT_ROOT)/%,$(call module-installed-files,\
+  $(if $(3),$(eval deps := $(addprefix host_cross_,$(deps))))\
+  $(eval r := $(filter $($(1)OUT)/%,$(call module-installed-files,\
     $(deps))))\
   $(eval $(call add-required-deps,$(word 2,$(p)),$(r)))\
   $(eval ALL_MODULES.$(mod).REQUIRED += $(deps)))
@@ -663,6 +653,9 @@
 ifdef HOST_2ND_ARCH
 $(call resolve-shared-libs-depes,HOST_,true)
 endif
+ifdef HOST_CROSS_OS
+$(call resolve-shared-libs-depes,HOST_CROSS_,,true)
+endif
 
 m :=
 r :=
@@ -903,7 +896,8 @@
 	$(INSTALLED_USERDATAIMAGE_TARGET) \
 	$(INSTALLED_CACHEIMAGE_TARGET) \
 	$(INSTALLED_VENDORIMAGE_TARGET) \
-	$(INSTALLED_FILES_FILE)
+	$(INSTALLED_FILES_FILE) \
+	$(INSTALLED_FILES_FILE_VENDOR)
 
 # dist_files only for putting your library into the dist directory with a full build.
 .PHONY: dist_files
@@ -961,6 +955,7 @@
     $(BUILT_OTATOOLS_PACKAGE) \
     $(SYMBOLS_ZIP) \
     $(INSTALLED_FILES_FILE) \
+    $(INSTALLED_FILES_FILE_VENDOR) \
     $(INSTALLED_BUILD_PROP_TARGET) \
     $(BUILT_TARGET_FILES_PACKAGE) \
     $(INSTALLED_ANDROID_INFO_TXT_TARGET) \
diff --git a/core/module_arch_supported.mk b/core/module_arch_supported.mk
index a5e4a7c..9f05060 100644
--- a/core/module_arch_supported.mk
+++ b/core/module_arch_supported.mk
@@ -8,6 +8,8 @@
 ## LOCAL_MODULE_$(my_prefix)ARCH_WARN
 ## LOCAL_MODULE_UNSUPPORTED_$(my_prefix)ARCH
 ## LOCAL_MODULE_UNSUPPORTED_$(my_prefix)ARCH_WARN
+## LOCAL_IS_HOST_MODULE
+## LOCAL_MODULE_HOST_OS
 ##
 ## Inputs from build system:
 ## $(my_prefix)IS_64_BIT
@@ -58,3 +60,14 @@
 my_module_arch_supported := false
 $(warning $(LOCAL_MODULE): architecture $($(my_prefix)$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH) unsupported)
 endif
+
+ifdef LOCAL_IS_HOST_MODULE
+ifneq (,$(LOCAL_MODULE_HOST_OS))
+  ifeq (,$(filter $($(my_prefix)OS),$(LOCAL_MODULE_HOST_OS)))
+    my_module_arch_supported := false
+  endif
+else ifeq ($($(my_prefix)OS),windows)
+  # If LOCAL_MODULE_HOST_OS is empty, only linux and darwin are supported
+  my_module_arch_supported := false
+endif
+endif
diff --git a/core/multilib.mk b/core/multilib.mk
index e0615b2..a3ced65 100644
--- a/core/multilib.mk
+++ b/core/multilib.mk
@@ -13,11 +13,3 @@
 $(error $(LOCAL_PATH): Invalid LOCAL_MULTILIB specified for module $(LOCAL_MODULE))
 endif
 endif # my_module_multilib defined
-
-# Windows is a special case. Linux and Darwin are both multilib builds, but we
-# don't have a 64-bit Windows build, so make sure it's not a multilib build.
-ifdef LOCAL_IS_HOST_MODULE
-ifeq ($(HOST_OS),windows)
-my_module_multilib := 32
-endif
-endif
diff --git a/core/ninja.mk b/core/ninja.mk
index 3dcc65c..b9a0cec 100644
--- a/core/ninja.mk
+++ b/core/ninja.mk
@@ -1,9 +1,99 @@
 KATI ?= $(HOST_OUT_EXECUTABLES)/ckati
+MAKEPARALLEL ?= $(HOST_OUT_EXECUTABLES)/makeparallel
 
-KATI_OUTPUTS := $(PRODUCT_OUT)/build.ninja $(PRODUCT_OUT)/ninja.sh
+KATI_OUTPUT_PATTERNS := $(PRODUCT_OUT)/build%.ninja $(PRODUCT_OUT)/ninja%.sh
 NINJA_GOALS := fastincremental generateonly droid showcommands
+# A list of goals which affect parsing of make.
+PARSE_TIME_MAKE_GOALS := \
+	$(PARSE_TIME_MAKE_GOALS) \
+	$(dont_bother_goals) \
+	tests \
+	APP-% \
+	DUMP_% \
+	ECLIPSE-% \
+	PRODUCT-% \
+	boottarball-nodeps \
+	btnod \
+	build-art% \
+	build_kernel-nodeps \
+	checkbuild \
+	clean-oat% \
+	continuous_instrumentation_tests \
+	continuous_native_tests \
+	cts \
+	custom_images \
+	deps-license \
+	dicttool_aosp \
+	dist \
+	dump-products \
+	dumpvar-% \
+	eng \
+	fusion \
+	oem_image \
+	online-system-api-sdk-docs \
+	pdk \
+	platform \
+	platform-java \
+	product-graph \
+	samplecode \
+	sdk \
+	sdk_addon \
+	sdk_repo \
+	snod \
+	stnod \
+	systemimage-nodeps \
+	systemtarball-nodeps \
+	target-files-package \
+	test-art% \
+	user \
+	userdataimage \
+	userdebug \
+	valgrind-test-art% \
+	win_sdk \
+	winsdk-tools
 
-ANDROID_TARGETS := $(filter-out $(KATI_OUTPUTS) $(NINJA_GOALS),$(ORIGINAL_MAKECMDGOALS))
+-include vendor/google/build/ninja_config.mk
+
+ANDROID_TARGETS := $(filter-out $(KATI_OUTPUT_PATTERNS) $(NINJA_GOALS),$(ORIGINAL_MAKECMDGOALS))
+EXTRA_TARGETS := $(filter-out $(KATI_OUTPUT_PATTERNS) $(NINJA_GOALS),$(filter-out $(ORIGINAL_MAKECMDGOALS),$(MAKECMDGOALS)))
+KATI_TARGETS := $(if $(filter $(PARSE_TIME_MAKE_GOALS),$(ANDROID_TARGETS)),$(ANDROID_TARGETS),)
+
+define replace_space_and_slash
+$(subst /,_,$(subst $(space),_,$(sort $1)))
+endef
+
+KATI_NINJA_SUFFIX :=
+ifneq ($(KATI_TARGETS),)
+KATI_NINJA_SUFFIX := $(KATI_NINJA_SUFFIX)-$(call replace_space_and_slash,$(KATI_TARGETS))
+endif
+ifneq ($(ONE_SHOT_MAKEFILE),)
+KATI_NINJA_SUFFIX := $(KATI_NINJA_SUFFIX)-mmm-$(call replace_space_and_slash,$(ONE_SHOT_MAKEFILE))
+endif
+ifneq ($(BUILD_MODULES_IN_PATHS),)
+KATI_NINJA_SUFFIX := $(KATI_NINJA_SUFFIX)-mmma-$(call replace_space_and_slash,$(BUILD_MODULES_IN_PATHS))
+endif
+
+my_checksum_suffix :=
+ifneq ($(KATI_NINJA_SUFFIX),)
+my_ninja_suffix_too_long := $(filter 1, $(shell v='$(KATI_NINJA_SUFFIX)' && echo $$(($${$(pound)v} > 64))))
+ifneq ($(my_ninja_suffix_too_long),)
+# Replace the suffix with a checksum if it gets too long.
+my_checksum_suffix := $(KATI_NINJA_SUFFIX)
+KATI_NINJA_SUFFIX := -$(word 1, $(shell echo $(my_checksum_suffix) | $(MD5SUM)))
+endif
+endif
+
+KATI_BUILD_NINJA := $(PRODUCT_OUT)/build$(KATI_NINJA_SUFFIX).ninja
+KATI_NINJA_SH := $(PRODUCT_OUT)/ninja$(KATI_NINJA_SUFFIX).sh
+
+# Write out a file mapping checksum to the real suffix.
+ifneq ($(my_checksum_suffix),)
+my_ninja_suffix_file := $(basename $(KATI_BUILD_NINJA)).suf
+$(shell mkdir -p $(dir $(my_ninja_suffix_file)) && \
+    echo $(my_checksum_suffix) > $(my_ninja_suffix_file))
+endif
+
+KATI_OUTPUTS := $(KATI_BUILD_NINJA) $(KATI_NINJA_SH)
 
 ifeq (,$(NINJA_STATUS))
 NINJA_STATUS := [%p %s/%t]$(space)
@@ -15,16 +105,22 @@
 showcommands: droid
 endif
 
+ifdef KATI_REMOTE_NUM_JOBS_FLAG
+KATI_MAKEPARALLEL := $(MAKEPARALLEL)
+else
+NINJA_MAKEPARALLEL := $(MAKEPARALLEL) --ninja
+endif
+
 ifeq (,$(filter generateonly,$(ORIGINAL_MAKECMDGOALS)))
-fastincremental droid $(ANDROID_TARGETS): ninja.intermediate
+fastincremental droid $(ANDROID_TARGETS) $(EXTRA_TARGETS): ninja.intermediate
 	@#empty
 
 .INTERMEDIATE: ninja.intermediate
-ninja.intermediate: $(KATI_OUTPUTS)
+ninja.intermediate: $(KATI_OUTPUTS) $(MAKEPARALLEL)
 	@echo Starting build with ninja
-	$(hide) PATH=prebuilts/ninja/$(HOST_PREBUILT_TAG)/:$$PATH NINJA_STATUS="$(NINJA_STATUS)" $(PRODUCT_OUT)/ninja.sh -C $(TOP) $(NINJA_ARGS) $(ANDROID_TARGETS)
+	+$(hide) PATH=prebuilts/ninja/$(HOST_PREBUILT_TAG)/:$$PATH NINJA_STATUS="$(NINJA_STATUS)" $(NINJA_MAKEPARALLEL) $(KATI_NINJA_SH) -C $(TOP) $(NINJA_ARGS) $(ANDROID_TARGETS)
 else
-generateonly droid $(ANDROID_TARGETS): $(KATI_OUTPUTS)
+generateonly droid $(ANDROID_TARGETS) $(EXTRA_TARGETS): $(KATI_OUTPUTS)
 	@#empty
 endif
 
@@ -35,12 +131,11 @@
 $(KATI_OUTPUTS): kati.intermediate $(KATI_FORCE)
 
 .INTERMEDIATE: kati.intermediate
-kati.intermediate: $(KATI)
-	@echo Running kati to generate build.ninja...
-	@#TODO: use separate ninja file for mm or single target build
-	$(hide) $(KATI) --ninja --ninja_dir=$(PRODUCT_OUT) --regen --ignore_dirty=$(OUT_DIR)/% --ignore_optional_include=$(OUT_DIR)/%.P --detect_android_echo --use_find_emulator $(KATI_REMOTE_NUM_JOBS_FLAG) -f build/core/main.mk $(ANDROID_TARGETS) USE_NINJA=false
+kati.intermediate: $(KATI) $(MAKEPARALLEL)
+	@echo Running kati to generate build$(KATI_NINJA_SUFFIX).ninja...
+	+$(hide) $(KATI_MAKEPARALLEL) $(KATI) --ninja --ninja_dir=$(PRODUCT_OUT) --ninja_suffix=$(KATI_NINJA_SUFFIX) --regen --ignore_dirty=$(OUT_DIR)/% --ignore_optional_include=$(OUT_DIR)/%.P --detect_android_echo --use_find_emulator $(KATI_REMOTE_NUM_JOBS_FLAG) -f build/core/main.mk $(or $(KATI_TARGETS),--gen_all_phony_targets) USE_NINJA=false
 
-KATI_CXX := $(CLANG_CXX) $(CLANG_HOST_GLOBAL_CPPFLAGS)
+KATI_CXX := $(CLANG_CXX) $(CLANG_HOST_GLOBAL_CFLAGS) $(CLANG_HOST_GLOBAL_CPPFLAGS)
 KATI_LD := $(CLANG_CXX) $(CLANG_HOST_GLOBAL_LDFLAGS)
 # Build static ckati. Unfortunately Mac OS X doesn't officially support static exectuables.
 ifeq ($(BUILD_OS),linux)
@@ -51,5 +146,16 @@
 KATI_BIN_PATH := $(HOST_OUT_EXECUTABLES)
 include build/kati/Makefile.ckati
 
+MAKEPARALLEL_CXX := $(CLANG_CXX) $(CLANG_HOST_GLOBAL_CPPFLAGS)
+MAKEPARALLEL_LD := $(CLANG_CXX) $(CLANG_HOST_GLOBAL_LDFLAGS)
+# Build static makeparallel. Unfortunately Mac OS X doesn't officially support static exectuables.
+ifeq ($(BUILD_OS),linux)
+MAKEPARALLEL_LD += -static
+endif
+
+MAKEPARALLEL_INTERMEDIATES_PATH := $(HOST_OUT_INTERMEDIATES)/EXECUTABLES/makeparallel_intermediates
+MAKEPARALLEL_BIN_PATH := $(HOST_OUT_EXECUTABLES)
+include build/tools/makeparallel/Makefile
+
 .PHONY: FORCE
 FORCE:
diff --git a/core/notice_files.mk b/core/notice_files.mk
index 43a5435..cf2dad6 100644
--- a/core/notice_files.mk
+++ b/core/notice_files.mk
@@ -14,6 +14,7 @@
 # so my_prefix is not set at this point.
 ifeq ($(LOCAL_IS_HOST_MODULE),true)
   my_prefix := HOST_
+  LOCAL_HOST_PREFIX :=
 else
   my_prefix := TARGET_
 endif
@@ -56,6 +57,7 @@
 
 # In case it's actually a host file
 module_installed_filename := $(patsubst $(HOST_OUT)%,%,$(module_installed_filename))
+module_installed_filename := $(patsubst $(HOST_CROSS_OUT)%,%,$(module_installed_filename))
 
 installed_notice_file := $($(my_prefix)OUT_NOTICE_FILES)/src/$(module_installed_filename).txt
 
diff --git a/core/pathmap.mk b/core/pathmap.mk
index 38306f4..190aed3 100644
--- a/core/pathmap.mk
+++ b/core/pathmap.mk
@@ -39,9 +39,6 @@
     frameworks-native:frameworks/native/include \
     libhardware:hardware/libhardware/include \
     libhardware_legacy:hardware/libhardware_legacy/include \
-    libhost:build/libs/host/include \
-    libnativehelper:libnativehelper/include \
-    libpagemap:system/extras/libpagemap/include \
     libril:hardware/ril/include \
     opengl-tests-includes:frameworks/native/opengl/tests/include \
     recovery:bootable/recovery \
@@ -69,7 +66,7 @@
 # Many modules expect to be able to say "#include <jni.h>",
 # so make it easy for them to find the correct path.
 #
-JNI_H_INCLUDE := $(call include-path-for,libnativehelper)/nativehelper
+JNI_H_INCLUDE := libnativehelper/include/nativehelper
 
 #
 # A list of all source roots under frameworks/base, which will be
diff --git a/core/prebuilt.mk b/core/prebuilt.mk
index d3f9d1a..ed25f71 100644
--- a/core/prebuilt.mk
+++ b/core/prebuilt.mk
@@ -8,6 +8,7 @@
 
 ifdef LOCAL_IS_HOST_MODULE
   my_prefix := HOST_
+  LOCAL_HOST_PREFIX :=
 else
   my_prefix := TARGET_
 endif
@@ -52,4 +53,26 @@
 
 LOCAL_2ND_ARCH_VAR_PREFIX :=
 
+ifdef LOCAL_IS_HOST_MODULE
+ifdef HOST_CROSS_OS
+ifneq (,$(filter EXECUTABLES STATIC_LIBRARIES SHARED_LIBRARIES,$(LOCAL_MODULE_CLASS)))
+my_prefix := HOST_CROSS_
+LOCAL_HOST_PREFIX := $(my_prefix)
+include $(BUILD_SYSTEM)/module_arch_supported.mk
+ifeq ($(my_module_arch_supported),true)
+# host cross compilation is supported
+OVERRIDE_BUILT_MODULE_PATH :=
+LOCAL_BUILT_MODULE :=
+LOCAL_INSTALLED_MODULE :=
+LOCAL_MODULE_STEM :=
+LOCAL_BUILT_MODULE_STEM :=
+LOCAL_INSTALLED_MODULE_STEM :=
+LOCAL_INTERMEDIATE_TARGETS :=
+include $(BUILD_SYSTEM)/prebuilt_internal.mk
+endif
+LOCAL_HOST_PREFIX :=
+endif
+endif
+endif
+
 my_module_arch_supported :=
diff --git a/core/shared_library.mk b/core/shared_library.mk
index 71a3bb2..73aca78c 100644
--- a/core/shared_library.mk
+++ b/core/shared_library.mk
@@ -9,13 +9,13 @@
 ifeq ($(my_module_multilib),both)
 ifneq ($(LOCAL_MODULE_PATH),)
 ifneq ($(TARGET_2ND_ARCH),)
-$(warning $(LOCAL_MODULE): LOCAL_MODULE_PATH for shared libraries is unsupported in multiarch builds, use LOCAL_MODULE_RELATIVE_PATH instead)
+$(error $(LOCAL_MODULE): LOCAL_MODULE_PATH for shared libraries is unsupported in multiarch builds, use LOCAL_MODULE_RELATIVE_PATH instead)
 endif
 endif
 
 ifneq ($(LOCAL_UNSTRIPPED_PATH),)
 ifneq ($(TARGET_2ND_ARCH),)
-$(warning $(LOCAL_MODULE): LOCAL_UNSTRIPPED_PATH for shared libraries is unsupported in multiarch builds)
+$(error $(LOCAL_MODULE): LOCAL_UNSTRIPPED_PATH for shared libraries is unsupported in multiarch builds)
 endif
 endif
 endif # my_module_multilib == both
diff --git a/envsetup.sh b/envsetup.sh
index 3c29e88..c24e1f0 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -161,23 +161,8 @@
         export ANDROID_TOOLCHAIN_2ND_ARCH=$gccprebuiltdir/$toolchaindir2
     fi
 
-    unset ANDROID_KERNEL_TOOLCHAIN_PATH
-    case $ARCH in
-        arm)
-            # Legacy toolchain configuration used for ARM kernel compilation
-            toolchaindir=arm/arm-eabi-$targetgccversion/bin
-            if [ -d "$gccprebuiltdir/$toolchaindir" ]; then
-                 export ARM_EABI_TOOLCHAIN="$gccprebuiltdir/$toolchaindir"
-                 ANDROID_KERNEL_TOOLCHAIN_PATH="$ARM_EABI_TOOLCHAIN":
-            fi
-            ;;
-        *)
-            # No need to set ARM_EABI_TOOLCHAIN for other ARCHs
-            ;;
-    esac
-
     export ANDROID_DEV_SCRIPTS=$T/development/scripts:$T/prebuilts/devtools/tools:$T/external/selinux/prebuilts/bin
-    export ANDROID_BUILD_PATHS=$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_TOOLCHAIN:$ANDROID_TOOLCHAIN_2ND_ARCH:$ANDROID_KERNEL_TOOLCHAIN_PATH$ANDROID_DEV_SCRIPTS:
+    export ANDROID_BUILD_PATHS=$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_TOOLCHAIN:$ANDROID_TOOLCHAIN_2ND_ARCH:$ANDROID_DEV_SCRIPTS:
 
     # If prebuilts/android-emulator/<system>/ exists, prepend it to our PATH
     # to ensure that the corresponding 'emulator' binaries are used.
@@ -198,7 +183,7 @@
     fi
 
     export PATH=$ANDROID_BUILD_PATHS$PATH
-    export PYTHONPATH=$T/system/core:$PYTHONPATH
+    export PYTHONPATH=$T/development/python-packages:$PYTHONPATH
 
     unset ANDROID_JAVA_TOOLCHAIN
     unset ANDROID_PRE_BUILD_PATHS
@@ -766,7 +751,7 @@
                 MAKEFILE="$MAKEFILE $MFILE"
             else
                 case $DIR in
-                  showcommands | snod | dist | incrementaljavac) ARGS="$ARGS $DIR";;
+                  showcommands | snod | dist | *=*) ARGS="$ARGS $DIR";;
                   GET-INSTALL-PATH) GET_INSTALL_PATH=$DIR;;
                   *) echo "No Android.mk in $DIR."; return 1;;
                 esac
@@ -795,7 +780,10 @@
       return 1
     fi
     local MY_PWD=`PWD= /bin/pwd|sed 's:'$T'/::'`
-    $DRV make -C $T -f build/core/main.mk $@ all_modules BUILD_MODULES_IN_PATHS="$MY_PWD"
+    local MODULES_IN_PATHS=MODULES-IN-$MY_PWD
+    # Convert "/" to "-".
+    MODULES_IN_PATHS=${MODULES_IN_PATHS//\//-}
+    $DRV make -C $T -f build/core/main.mk $@ $MODULES_IN_PATHS
   fi
 }
 
@@ -813,23 +801,27 @@
       MY_PWD=`echo $MY_PWD|sed 's:'$T'/::'`
     fi
     local DIR=
-    local MODULE_PATHS=
+    local MODULES_IN_PATHS=
     local ARGS=
     for DIR in $DIRS ; do
       if [ -d $DIR ]; then
-        if [ "$MY_PWD" = "" ]; then
-          MODULE_PATHS="$MODULE_PATHS $DIR"
-        else
-          MODULE_PATHS="$MODULE_PATHS $MY_PWD/$DIR"
+        # Remove the leading ./ and trailing / if any exists.
+        DIR=${DIR#./}
+        DIR=${DIR%/}
+        if [ "$MY_PWD" != "" ]; then
+          DIR=$MY_PWD/$DIR
         fi
+        MODULES_IN_PATHS="$MODULES_IN_PATHS MODULES-IN-$DIR"
       else
         case $DIR in
-          showcommands | snod | dist | incrementaljavac) ARGS="$ARGS $DIR";;
+          showcommands | snod | dist | *=*) ARGS="$ARGS $DIR";;
           *) echo "Couldn't find directory $DIR"; return 1;;
         esac
       fi
     done
-    $DRV make -C $T -f build/core/main.mk $DASH_ARGS $ARGS all_modules BUILD_MODULES_IN_PATHS="$MODULE_PATHS"
+    # Convert "/" to "-".
+    MODULES_IN_PATHS=${MODULES_IN_PATHS//\//-}
+    $DRV make -C $T -f build/core/main.mk $DASH_ARGS $ARGS $MODULES_IN_PATHS
   else
     echo "Couldn't locate the top of the tree.  Try setting TOP."
     return 1
diff --git a/libs/host/Android.mk b/libs/host/Android.mk
index 821f9b8..7eb3aa1 100644
--- a/libs/host/Android.mk
+++ b/libs/host/Android.mk
@@ -1,17 +1,13 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
 LOCAL_SRC_FILES:= \
     CopyFile.c
 
-ifeq ($(HOST_OS),darwin)
-LOCAL_CFLAGS += -DMACOSX_RSRC
-endif
-ifeq ($(HOST_OS),linux)
-endif
+LOCAL_CFLAGS_darwin += -DMACOSX_RSRC
 
 LOCAL_MODULE:= libhost
+LOCAL_MODULE_HOST_OS := darwin linux windows
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
 LOCAL_CXX_STL := none
 
diff --git a/target/product/core_tiny.mk b/target/product/core_tiny.mk
index 39789d9..4abe386 100644
--- a/target/product/core_tiny.mk
+++ b/target/product/core_tiny.mk
@@ -56,6 +56,7 @@
     iptables \
     keystore \
     keystore.default \
+    ld.mc \
     libOpenMAXAL \
     libOpenSLES \
     libdownmix \
diff --git a/target/product/embedded.mk b/target/product/embedded.mk
index 468fbe5..aac931d 100644
--- a/target/product/embedded.mk
+++ b/target/product/embedded.mk
@@ -89,6 +89,5 @@
 
 PRODUCT_COPY_FILES += \
     system/core/rootdir/init.usb.rc:root/init.usb.rc \
-    system/core/rootdir/init.trace.rc:root/init.trace.rc \
     system/core/rootdir/ueventd.rc:root/ueventd.rc \
     system/core/rootdir/etc/hosts:system/etc/hosts
diff --git a/target/product/runtime_libart.mk b/target/product/runtime_libart.mk
index a35122b..c177981 100644
--- a/target/product/runtime_libart.mk
+++ b/target/product/runtime_libart.mk
@@ -18,6 +18,7 @@
 
 PRODUCT_PACKAGES += \
     apache-xml \
+    ahat \
     bouncycastle \
     cacerts \
     conscrypt \
diff --git a/tools/makeparallel/.gitignore b/tools/makeparallel/.gitignore
new file mode 100644
index 0000000..a7d6181
--- /dev/null
+++ b/tools/makeparallel/.gitignore
@@ -0,0 +1,4 @@
+makeparallel
+*.o
+*.d
+test.out
diff --git a/tools/makeparallel/Makefile b/tools/makeparallel/Makefile
new file mode 100644
index 0000000..4e79708
--- /dev/null
+++ b/tools/makeparallel/Makefile
@@ -0,0 +1,92 @@
+# Copyright 2015 Google Inc. All rights reserved
+#
+# 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.
+
+# Find source file location from path to this Makefile
+MAKEPARALLEL_SRC_PATH := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
+ifndef MAKEPARALLEL_SRC_PATH
+  MAKEPARALLEL_SRC_PATH := .
+endif
+
+# Set defaults if they weren't set by the including Makefile
+MAKEPARALLEL_CXX ?= $(CXX)
+MAKEPARALLEL_LD ?= $(CXX)
+MAKEPARALLEL_INTERMEDIATES_PATH ?= .
+MAKEPARALLEL_BIN_PATH ?= .
+
+MAKEPARALLEL_CXX_SRCS := \
+	makeparallel.cpp
+
+MAKEPARALLEL_CXXFLAGS := -Wall -Werror -MMD -MP
+
+MAKEPARALLEL_CXX_SRCS := $(addprefix $(MAKEPARALLEL_SRC_PATH)/,\
+	$(MAKEPARALLEL_CXX_SRCS))
+
+MAKEPARALLEL_CXX_OBJS := $(patsubst $(MAKEPARALLEL_SRC_PATH)/%.cpp,$(MAKEPARALLEL_INTERMEDIATES_PATH)/%.o,$(MAKEPARALLEL_CXX_SRCS))
+
+MAKEPARALLEL := $(MAKEPARALLEL_BIN_PATH)/makeparallel
+
+ifeq ($(shell uname),Linux)
+MAKEPARALLEL_LIBS := -lrt -lpthread
+endif
+
+# Rule to build makeparallel into MAKEPARALLEL_BIN_PATH
+$(MAKEPARALLEL): $(MAKEPARALLEL_CXX_OBJS)
+	@mkdir -p $(dir $@)
+	$(MAKEPARALLEL_LD) -std=c++11 $(MAKEPARALLEL_CXXFLAGS) -o $@ $^ $(MAKEPARALLEL_LIBS)
+
+# Rule to build source files into object files in MAKEPARALLEL_INTERMEDIATES_PATH
+$(MAKEPARALLEL_CXX_OBJS): $(MAKEPARALLEL_INTERMEDIATES_PATH)/%.o: $(MAKEPARALLEL_SRC_PATH)/%.cpp
+	@mkdir -p $(dir $@)
+	$(MAKEPARALLEL_CXX) -c -std=c++11 $(MAKEPARALLEL_CXXFLAGS) -o $@ $<
+
+makeparallel_clean:
+	rm -rf $(MAKEPARALLEL)
+	rm -rf $(MAKEPARALLEL_INTERMEDIATES_PATH)/*.o
+	rm -rf $(MAKEPARALLEL_INTERMEDIATES_PATH)/*.d
+
+.PHONY: makeparallel_clean
+
+-include $(MAKEPARALLEL_INTERMEDIATES_PATH)/*.d
+
+.PHONY: makeparallel_test
+MAKEPARALLEL_TEST := MAKEFLAGS= MAKELEVEL= MAKEPARALLEL=$(MAKEPARALLEL) $(MAKE) -f Makefile.test test
+MAKEPARALLEL_NINJA_TEST := MAKEFLAGS= MAKELEVEL= MAKEPARALLEL="$(MAKEPARALLEL) --ninja" $(MAKE) -f Makefile.test test
+makeparallel_test: $(MAKEPARALLEL)
+	@EXPECTED="-j1234" $(MAKEPARALLEL_TEST) -j1234
+	@EXPECTED="-j123"  $(MAKEPARALLEL_TEST) -j123
+	@EXPECTED="-j1"    $(MAKEPARALLEL_TEST) -j1
+	@EXPECTED="-j1"    $(MAKEPARALLEL_TEST)
+
+	@EXPECTED="-j1234" $(MAKEPARALLEL_NINJA_TEST) -j1234
+	@EXPECTED="-j123"  $(MAKEPARALLEL_NINJA_TEST) -j123
+	@EXPECTED="-j1"    $(MAKEPARALLEL_NINJA_TEST) -j1
+	@EXPECTED="-j1"    $(MAKEPARALLEL_NINJA_TEST)
+	@EXPECTED=""       $(MAKEPARALLEL_NINJA_TEST) -j
+	@EXPECTED=""       $(MAKEPARALLEL_NINJA_TEST) -j -l
+
+	@EXPECTED="-j1234" $(MAKEPARALLEL_TEST) --no-print-directory -j1234
+	@EXPECTED="-j1234" $(MAKEPARALLEL_TEST) --no-print-directory -k -j1234
+	@EXPECTED="-j1234" $(MAKEPARALLEL_TEST) -k -j1234
+	@EXPECTED="-j1234" $(MAKEPARALLEL_TEST) -j1234 -k
+	@EXPECTED="-j1234" $(MAKEPARALLEL_TEST) -kt -j1234
+
+	@EXPECTED="-j1234"     $(MAKEPARALLEL_NINJA_TEST) --no-print-directory -j1234
+	@EXPECTED="-j1234 -k0" $(MAKEPARALLEL_NINJA_TEST) --no-print-directory -k -j1234
+	@EXPECTED="-j1234 -k0" $(MAKEPARALLEL_NINJA_TEST) -k -j1234
+	@EXPECTED="-j1234 -k0" $(MAKEPARALLEL_NINJA_TEST) -j1234 -k
+	@EXPECTED="-j1234 -k0" $(MAKEPARALLEL_NINJA_TEST) -kt -j1234
+
+	@EXPECTED="-j1"    $(MAKEPARALLEL_TEST) A=-j1234
+	@EXPECTED="-j1"    $(MAKEPARALLEL_TEST) A\ -j1234=-j1234
+	@EXPECTED="-j1234" $(MAKEPARALLEL_TEST) A\ -j1234=-j1234 -j1234
diff --git a/tools/makeparallel/Makefile.test b/tools/makeparallel/Makefile.test
new file mode 100644
index 0000000..91aacf7
--- /dev/null
+++ b/tools/makeparallel/Makefile.test
@@ -0,0 +1,12 @@
+MAKEPARALLEL ?= ./makeparallel
+
+.PHONY: test
+test:
+	@+echo MAKEFLAGS=$${MAKEFLAGS};              \
+	result=$$($(MAKEPARALLEL) echo);             \
+	echo result: $${result};                     \
+	if [ "$${result}" = "$(EXPECTED)" ]; then    \
+	  echo SUCCESS && echo;                      \
+	else                                         \
+	  echo FAILED expected $(EXPECTED) && false; \
+	fi
diff --git a/tools/makeparallel/README.md b/tools/makeparallel/README.md
new file mode 100644
index 0000000..2e5fbf9
--- /dev/null
+++ b/tools/makeparallel/README.md
@@ -0,0 +1,54 @@
+<!---
+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.
+-->
+
+makeparallel
+============
+makeparallel communicates with the [GNU make jobserver](http://make.mad-scientist.net/papers/jobserver-implementation/)
+in order claim all available jobs, and then passes the number of jobs
+claimed to a subprocess with `-j<jobs>`.
+
+The number of available jobs is determined by reading tokens from the jobserver
+until a read would block.  If the makeparallel rule is the only one running the
+number of jobs will be the total size of the jobserver pool, i.e. the value
+passed to make with `-j`.  Any jobs running in parallel with with the
+makeparellel rule will reduce the measured value, and thus reduce the
+parallelism available to the subprocess.
+
+To run a multi-thread or multi-process binary inside GNU make using
+makeparallel, add
+```Makefile
+	+makeparallel subprocess arguments
+```
+to a rule.  For example, to wrap ninja in make, use something like:
+```Makefile
+	+makeparallel ninja -f build.ninja
+```
+
+To determine the size of the jobserver pool, add
+```Makefile
+	+makeparallel echo > make.jobs
+```
+to a rule that is guarantee to run alone (i.e. all other rules are either
+dependencies of the makeparallel rule, or the depend on the makeparallel
+rule.  The output file will contain the `-j<num>` flag passed to the parent
+make process, or `-j1` if no flag was found.  Since GNU make will run
+makeparallel during the execution phase, after all variables have been
+set and evaluated, it is not possible to get the output of makeparallel
+into a make variable.  Instead, use a shell substitution to read the output
+file directly in a recipe.  For example:
+```Makefile
+	echo Make was started with $$(cat make.jobs)
+```
diff --git a/tools/makeparallel/makeparallel.cpp b/tools/makeparallel/makeparallel.cpp
new file mode 100644
index 0000000..7dd0ceb
--- /dev/null
+++ b/tools/makeparallel/makeparallel.cpp
@@ -0,0 +1,361 @@
+// 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.
+
+// makeparallel communicates with the GNU make jobserver
+// (http://make.mad-scientist.net/papers/jobserver-implementation/)
+// in order claim all available jobs, and then passes the number of jobs
+// claimed to a subprocess with -j<jobs>.
+
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <string>
+#include <vector>
+
+#ifdef __linux__
+#include <error.h>
+#endif
+
+#ifdef __APPLE__
+#include <err.h>
+#define error(code, eval, fmt, ...) errc(eval, code, fmt, ##__VA_ARGS__)
+// Darwin does not interrupt syscalls by default.
+#define TEMP_FAILURE_RETRY(exp) (exp)
+#endif
+
+// Throw an error if fd is not valid.
+static void CheckFd(int fd) {
+  int ret = fcntl(fd, F_GETFD);
+  if (ret < 0) {
+    if (errno == EBADF) {
+      error(errno, 0, "no jobserver pipe, prefix recipe command with '+'");
+    } else {
+      error(errno, errno, "fnctl failed");
+    }
+  }
+}
+
+// Extract flags from MAKEFLAGS that need to be propagated to subproccess
+static std::vector<std::string> ReadMakeflags() {
+  std::vector<std::string> args;
+
+  const char* makeflags_env = getenv("MAKEFLAGS");
+  if (makeflags_env == nullptr) {
+    return args;
+  }
+
+  // The MAKEFLAGS format is pretty useless.  The first argument might be empty
+  // (starts with a leading space), or it might be a set of one-character flags
+  // merged together with no leading space, or it might be a variable
+  // definition.
+
+  std::string makeflags = makeflags_env;
+
+  // Split makeflags into individual args on spaces.  Multiple spaces are
+  // elided, but an initial space will result in a blank arg.
+  size_t base = 0;
+  size_t found;
+  do {
+    found = makeflags.find_first_of(" ", base);
+    args.push_back(makeflags.substr(base, found - base));
+    base = found + 1;
+  } while (found != makeflags.npos);
+
+  // Drop the first argument if it is empty
+  while (args.size() > 0 && args[0].size() == 0) {
+	  args.erase(args.begin());
+  }
+
+  // Prepend a - to the first argument if it does not have one and is not a
+  // variable definition
+  if (args.size() > 0 && args[0][0] != '-') {
+    if (args[0].find('=') == makeflags.npos) {
+      args[0] = '-' + args[0];
+    }
+  }
+
+  return args;
+}
+
+static bool ParseMakeflags(std::vector<std::string>& args,
+    int* in_fd, int* out_fd, bool* parallel, bool* keep_going) {
+
+  std::vector<char*> getopt_argv;
+  // getopt starts reading at argv[1]
+  getopt_argv.reserve(args.size() + 1);
+  getopt_argv.push_back(strdup(""));
+  for (std::string& v : args) {
+    getopt_argv.push_back(strdup(v.c_str()));
+  }
+
+  opterr = 0;
+  optind = 1;
+  while (1) {
+    const static option longopts[] = {
+        {"jobserver-fds", required_argument, 0, 0},
+        {0, 0, 0, 0},
+    };
+    int longopt_index = 0;
+
+    int c = getopt_long(getopt_argv.size(), getopt_argv.data(), "kj",
+        longopts, &longopt_index);
+
+    if (c == -1) {
+      break;
+    }
+
+    switch (c) {
+    case 0:
+      switch (longopt_index) {
+      case 0:
+      {
+        // jobserver-fds
+        if (sscanf(optarg, "%d,%d", in_fd, out_fd) != 2) {
+          error(EXIT_FAILURE, 0, "incorrect format for --jobserver-fds: %s", optarg);
+        }
+        // TODO: propagate in_fd, out_fd
+        break;
+      }
+      default:
+        abort();
+      }
+      break;
+    case 'j':
+      *parallel = true;
+      break;
+    case 'k':
+      *keep_going = true;
+      break;
+    case '?':
+      // ignore unknown arguments
+      break;
+    default:
+      abort();
+    }
+  }
+
+  for (char *v : getopt_argv) {
+    free(v);
+  }
+
+  return true;
+}
+
+// Read a single byte from fd, with timeout in milliseconds.  Returns true if
+// a byte was read, false on timeout.  Throws away the read value.
+// Non-reentrant, uses timer and signal handler global state, plus static
+// variable to communicate with signal handler.
+//
+// Uses a SIGALRM timer to fire a signal after timeout_ms that will interrupt
+// the read syscall if it hasn't yet completed.  If the timer fires before the
+// read the read could block forever, so read from a dup'd fd and close it from
+// the signal handler, which will cause the read to return EBADF if it occurs
+// after the signal.
+// The dup/read/close combo is very similar to the system described to avoid
+// a deadlock between SIGCHLD and read at
+// http://make.mad-scientist.net/papers/jobserver-implementation/
+static bool ReadByteTimeout(int fd, int timeout_ms) {
+  // global variable to communicate with the signal handler
+  static int dup_fd = -1;
+
+  // dup the fd so the signal handler can close it without losing the real one
+  dup_fd = dup(fd);
+  if (dup_fd < 0) {
+    error(errno, errno, "dup failed");
+  }
+
+  // set up a signal handler that closes dup_fd on SIGALRM
+  struct sigaction action = {};
+  action.sa_flags = SA_SIGINFO,
+  action.sa_sigaction = [](int, siginfo_t*, void*) {
+    close(dup_fd);
+  };
+  struct sigaction oldaction = {};
+  int ret = sigaction(SIGALRM, &action, &oldaction);
+  if (ret < 0) {
+    error(errno, errno, "sigaction failed");
+  }
+
+  // queue a SIGALRM after timeout_ms
+  const struct itimerval timeout = {{}, {0, timeout_ms * 1000}};
+  ret = setitimer(ITIMER_REAL, &timeout, NULL);
+  if (ret < 0) {
+    error(errno, errno, "setitimer failed");
+  }
+
+  // start the blocking read
+  char buf;
+  int read_ret = read(dup_fd, &buf, 1);
+  int read_errno = errno;
+
+  // cancel the alarm in case it hasn't fired yet
+  const struct itimerval cancel = {};
+  ret = setitimer(ITIMER_REAL, &cancel, NULL);
+  if (ret < 0) {
+    error(errno, errno, "reset setitimer failed");
+  }
+
+  // remove the signal handler
+  ret = sigaction(SIGALRM, &oldaction, NULL);
+  if (ret < 0) {
+    error(errno, errno, "reset sigaction failed");
+  }
+
+  // clean up the dup'd fd in case the signal never fired
+  close(dup_fd);
+  dup_fd = -1;
+
+  if (read_ret == 0) {
+    error(EXIT_FAILURE, 0, "EOF on jobserver pipe");
+  } else if (read_ret > 0) {
+    return true;
+  } else if (read_errno == EINTR || read_errno == EBADF) {
+    return false;
+  } else {
+    error(read_errno, read_errno, "read failed");
+  }
+  abort();
+}
+
+// Measure the size of the jobserver pool by reading from in_fd until it blocks
+static int GetJobserverTokens(int in_fd) {
+  int tokens = 0;
+  pollfd pollfds[] = {{in_fd, POLLIN, 0}};
+  int ret;
+  while ((ret = TEMP_FAILURE_RETRY(poll(pollfds, 1, 0))) != 0) {
+    if (ret < 0) {
+      error(errno, errno, "poll failed");
+    } else if (pollfds[0].revents != POLLIN) {
+      error(EXIT_FAILURE, 0, "unexpected event %d\n", pollfds[0].revents);
+    }
+
+    // There is probably a job token in the jobserver pipe.  There is a chance
+    // another process reads it first, which would cause a blocking read to
+    // block forever (or until another process put a token back in the pipe).
+    // The file descriptor can't be set to O_NONBLOCK as that would affect
+    // all users of the pipe, including the parent make process.
+    // ReadByteTimeout emulates a non-blocking read on a !O_NONBLOCK socket
+    // using a SIGALRM that fires after a short timeout.
+    bool got_token = ReadByteTimeout(in_fd, 10);
+    if (!got_token) {
+      // No more tokens
+      break;
+    } else {
+      tokens++;
+    }
+  }
+
+  // This process implicitly gets a token, so pool size is measured size + 1
+  return tokens;
+}
+
+// Return tokens to the jobserver pool.
+static void PutJobserverTokens(int out_fd, int tokens) {
+  // Return all the tokens to the pipe
+  char buf = '+';
+  for (int i = 0; i < tokens; i++) {
+    int ret = TEMP_FAILURE_RETRY(write(out_fd, &buf, 1));
+    if (ret < 0) {
+      error(errno, errno, "write failed");
+    } else if (ret == 0) {
+      error(EXIT_FAILURE, 0, "EOF on jobserver pipe");
+    }
+  }
+}
+
+int main(int argc, char* argv[]) {
+  int in_fd = -1;
+  int out_fd = -1;
+  bool parallel = false;
+  bool keep_going = false;
+  bool ninja = false;
+  int tokens = 0;
+
+  if (argc > 1 && strcmp(argv[1], "--ninja") == 0) {
+    ninja = true;
+    argv++;
+    argc--;
+  }
+
+  const char* path = argv[1];
+  std::vector<char*> args(&argv[1], &argv[argc]);
+
+  std::vector<std::string> makeflags = ReadMakeflags();
+  if (ParseMakeflags(makeflags, &in_fd, &out_fd, &parallel, &keep_going)) {
+    if (in_fd >= 0 && out_fd >= 0) {
+      CheckFd(in_fd);
+      CheckFd(out_fd);
+      fcntl(in_fd, F_SETFD, FD_CLOEXEC);
+      fcntl(out_fd, F_SETFD, FD_CLOEXEC);
+      tokens = GetJobserverTokens(in_fd);
+    }
+  }
+
+  std::string jarg = "-j" + std::to_string(tokens + 1);
+
+  if (ninja) {
+    if (!parallel) {
+      // ninja is parallel by default, pass -j1 to disable parallelism if make wasn't parallel
+      args.push_back(strdup("-j1"));
+    } else if (tokens > 0) {
+      args.push_back(strdup(jarg.c_str()));
+    }
+    if (keep_going) {
+      args.push_back(strdup("-k0"));
+    }
+  } else {
+    args.push_back(strdup(jarg.c_str()));
+  }
+
+  args.push_back(nullptr);
+
+  pid_t pid = fork();
+  if (pid < 0) {
+    error(errno, errno, "fork failed");
+  } else if (pid == 0) {
+    // child
+    int ret = execvp(path, args.data());
+    if (ret < 0) {
+      error(errno, errno, "exec failed");
+    }
+    abort();
+  }
+
+  // parent
+  siginfo_t status = {};
+  int exit_status = 0;
+  int ret = waitid(P_PID, pid, &status, WEXITED);
+  if (ret < 0) {
+    error(errno, errno, "waitpid failed");
+  } else if (status.si_code == CLD_EXITED) {
+    exit_status = status.si_status;
+  } else {
+    exit_status = -(status.si_status);
+  }
+
+  if (tokens > 0) {
+    PutJobserverTokens(out_fd, tokens);
+  }
+  exit(exit_status);
+}
diff --git a/tools/releasetools/blockimgdiff.py b/tools/releasetools/blockimgdiff.py
index c7a9e2b..42007eb 100644
--- a/tools/releasetools/blockimgdiff.py
+++ b/tools/releasetools/blockimgdiff.py
@@ -106,11 +106,13 @@
     assert not (trim and pad)
 
     partial = len(self.data) % self.blocksize
+    padded = False
     if partial > 0:
       if trim:
         self.data = self.data[:-partial]
       elif pad:
         self.data += '\0' * (self.blocksize - partial)
+        padded = True
       else:
         raise ValueError(("data for DataImage must be multiple of %d bytes "
                           "unless trim or pad is specified") %
@@ -120,14 +122,23 @@
 
     self.total_blocks = len(self.data) / self.blocksize
     self.care_map = RangeSet(data=(0, self.total_blocks))
-    self.clobbered_blocks = RangeSet()
+    # When the last block is padded, we always write the whole block even for
+    # incremental OTAs. Because otherwise the last block may get skipped if
+    # unchanged for an incremental, but would fail the post-install
+    # verification if it has non-zero contents in the padding bytes.
+    # Bug: 23828506
+    if padded:
+      clobbered_blocks = [self.total_blocks-1, self.total_blocks]
+    else:
+      clobbered_blocks = []
+    self.clobbered_blocks = clobbered_blocks
     self.extended = RangeSet()
 
     zero_blocks = []
     nonzero_blocks = []
     reference = '\0' * self.blocksize
 
-    for i in range(self.total_blocks):
+    for i in range(self.total_blocks-1 if padded else self.total_blocks):
       d = self.data[i*self.blocksize : (i+1)*self.blocksize]
       if d == reference:
         zero_blocks.append(i)
@@ -136,17 +147,25 @@
         nonzero_blocks.append(i)
         nonzero_blocks.append(i+1)
 
-    self.file_map = {"__ZERO": RangeSet(zero_blocks),
-                     "__NONZERO": RangeSet(nonzero_blocks)}
+    assert zero_blocks or nonzero_blocks or clobbered_blocks
+
+    self.file_map = dict()
+    if zero_blocks:
+      self.file_map["__ZERO"] = RangeSet(data=zero_blocks)
+    if nonzero_blocks:
+      self.file_map["__NONZERO"] = RangeSet(data=nonzero_blocks)
+    if clobbered_blocks:
+      self.file_map["__COPY"] = RangeSet(data=clobbered_blocks)
 
   def ReadRangeSet(self, ranges):
     return [self.data[s*self.blocksize:e*self.blocksize] for (s, e) in ranges]
 
   def TotalSha1(self, include_clobbered_blocks=False):
-    # DataImage always carries empty clobbered_blocks, so
-    # include_clobbered_blocks can be ignored.
-    assert self.clobbered_blocks.size() == 0
-    return sha1(self.data).hexdigest()
+    if not include_clobbered_blocks:
+      ranges = self.care_map.subtract(self.clobbered_blocks)
+      return sha1(self.ReadRangeSet(ranges)).hexdigest()
+    else:
+      return sha1(self.data).hexdigest()
 
 
 class Transfer(object):
@@ -492,6 +511,7 @@
     # Zero out extended blocks as a workaround for bug 20881595.
     if self.tgt.extended:
       out.append("zero %s\n" % (self.tgt.extended.to_string_raw(),))
+      total += self.tgt.extended.size()
 
     # We erase all the blocks on the partition that a) don't contain useful
     # data in the new image and b) will not be touched by dm-verity.
@@ -502,7 +522,7 @@
       out.append("erase %s\n" % (new_dontcare.to_string_raw(),))
 
     out.insert(0, "%d\n" % (self.version,))   # format version number
-    out.insert(1, str(total) + "\n")
+    out.insert(1, "%d\n" % (total,))
     if self.version >= 2:
       # version 2 only: after the total block count, we give the number
       # of stash slots needed, and the maximum size needed (in blocks)
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index d56c0fd..0678a13 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -159,11 +159,12 @@
     # to build images than the one running on device, such as when enabling
     # system_root_image. In that case, we must have the one for image
     # generation copied to META/.
-    fc_config = os.path.join(input_dir, "META", "file_contexts.bin")
+    fc_basename = os.path.basename(d.get("selinux_fc", "file_contexts"))
+    fc_config = os.path.join(input_dir, "META", fc_basename)
     if d.get("system_root_image") == "true":
       assert os.path.exists(fc_config)
     if not os.path.exists(fc_config):
-      fc_config = os.path.join(input_dir, "BOOT", "RAMDISK", "file_contexts.bin")
+      fc_config = os.path.join(input_dir, "BOOT", "RAMDISK", fc_basename)
       if not os.path.exists(fc_config):
         fc_config = None
 
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index 8964720..a4fc0b3 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -243,6 +243,15 @@
     cmd = "delete(" + ",\0".join(['"%s"' % (i,) for i in file_list]) + ");"
     self.script.append(self.WordWrap(cmd))
 
+  def DeleteFilesIfNotMatching(self, file_list):
+    """Delete the file in file_list if not matching the checksum."""
+    if not file_list:
+      return
+    for name, sha1 in file_list:
+      cmd = ('sha1_check(read_file("{name}"), "{sha1}") || '
+             'delete("{name}");'.format(name=name, sha1=sha1))
+      self.script.append(self.WordWrap(cmd))
+
   def RenameFile(self, srcfile, tgtfile):
     """Moves a file from one location to another."""
     if self.info.get("update_rename_support", False):
@@ -254,7 +263,7 @@
     """Prepend an action with an apply_patch_check in order to
        skip the action if the file exists.  Used when a patch
        is later renamed."""
-    cmd = ('sha1_check(read_file("%s"), %s) || ' % (tgtfile, tgtsha1))
+    cmd = ('sha1_check(read_file("%s"), %s) ||' % (tgtfile, tgtsha1))
     self.script.append(self.WordWrap(cmd))
 
   def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
diff --git a/tools/releasetools/ota_from_target_files.py b/tools/releasetools/ota_from_target_files.py
index c074f10..d686004 100755
--- a/tools/releasetools/ota_from_target_files.py
+++ b/tools/releasetools/ota_from_target_files.py
@@ -1072,11 +1072,13 @@
       script.FileCheck(tf.name, tf.sha1)
 
   def RemoveUnneededFiles(self, script, extras=()):
-    script.DeleteFiles(
-        ["/" + i[0] for i in self.verbatim_targets] +
-        ["/" + i for i in sorted(self.source_data)
-         if i not in self.target_data and i not in self.renames] +
-        list(extras))
+    file_list = ["/" + i[0] for i in self.verbatim_targets]
+    file_list += ["/" + i for i in self.source_data
+                  if i not in self.target_data and i not in self.renames]
+    file_list += list(extras)
+    # Sort the list in descending order, which removes all the files first
+    # before attempting to remove the folder. (Bug: 22960996)
+    script.DeleteFiles(sorted(file_list, reverse=True))
 
   def TotalPatchSize(self):
     return sum(i[1].size for i in self.patch_list)
@@ -1394,11 +1396,36 @@
   # Delete all the symlinks in source that aren't in target.  This
   # needs to happen before verbatim files are unpacked, in case a
   # symlink in the source is replaced by a real file in the target.
-  to_delete = []
+
+  # If a symlink in the source will be replaced by a regular file, we cannot
+  # delete the symlink/file in case the package gets applied again. For such
+  # a symlink, we prepend a sha1_check() to detect if it has been updated.
+  # (Bug: 23646151)
+  replaced_symlinks = dict()
+  if system_diff:
+    for i in system_diff.verbatim_targets:
+      replaced_symlinks["/%s" % (i[0],)] = i[2]
+  if vendor_diff:
+    for i in vendor_diff.verbatim_targets:
+      replaced_symlinks["/%s" % (i[0],)] = i[2]
+
+  if system_diff:
+    for tf in system_diff.renames.values():
+      replaced_symlinks["/%s" % (tf.name,)] = tf.sha1
+  if vendor_diff:
+    for tf in vendor_diff.renames.values():
+      replaced_symlinks["/%s" % (tf.name,)] = tf.sha1
+
+  always_delete = []
+  may_delete = []
   for dest, link in source_symlinks:
     if link not in target_symlinks_d:
-      to_delete.append(link)
-  script.DeleteFiles(to_delete)
+      if link in replaced_symlinks:
+        may_delete.append((link, replaced_symlinks[link]))
+      else:
+        always_delete.append(link)
+  script.DeleteFiles(always_delete)
+  script.DeleteFilesIfNotMatching(may_delete)
 
   if system_diff.verbatim_targets:
     script.Print("Unpacking new system files...")
diff --git a/tools/releasetools/rangelib.py b/tools/releasetools/rangelib.py
index 373bbed..975a48a 100644
--- a/tools/releasetools/rangelib.py
+++ b/tools/releasetools/rangelib.py
@@ -24,12 +24,13 @@
   lots of runs."""
 
   def __init__(self, data=None):
-    # TODO(tbao): monotonic is broken when passing in a tuple.
     self.monotonic = False
     if isinstance(data, str):
       self._parse_internal(data)
     elif data:
+      assert len(data) % 2 == 0
       self.data = tuple(self._remove_pairs(data))
+      self.monotonic = all(x < y for x, y in zip(self.data, self.data[1:]))
     else:
       self.data = ()
 
@@ -39,8 +40,10 @@
 
   def __eq__(self, other):
     return self.data == other.data
+
   def __ne__(self, other):
     return self.data != other.data
+
   def __nonzero__(self):
     return bool(self.data)
 
@@ -74,9 +77,9 @@
     monotonic = True
     for p in text.split():
       if "-" in p:
-        s, e = p.split("-")
-        data.append(int(s))
-        data.append(int(e)+1)
+        s, e = (int(x) for x in p.split("-"))
+        data.append(s)
+        data.append(e+1)
         if last <= s <= e:
           last = e
         else:
@@ -95,6 +98,9 @@
 
   @staticmethod
   def _remove_pairs(source):
+    """Remove consecutive duplicate items to simplify the result.
+
+    [1, 2, 2, 5, 5, 10] will become [1, 10]."""
     last = None
     for i in source:
       if i == last:
@@ -117,6 +123,7 @@
     return " ".join(out)
 
   def to_string_raw(self):
+    assert self.data
     return str(len(self.data)) + "," + ",".join(str(i) for i in self.data)
 
   def union(self, other):
diff --git a/tools/releasetools/test_rangelib.py b/tools/releasetools/test_rangelib.py
index bf2b640..7debe66 100644
--- a/tools/releasetools/test_rangelib.py
+++ b/tools/releasetools/test_rangelib.py
@@ -44,6 +44,7 @@
 
   def test_size(self):
     self.assertEqual(RangeSet("10-19 30-34").size(), 15)
+    self.assertEqual(RangeSet("").size(), 0)
 
   def test_map_within(self):
     self.assertEqual(RangeSet("0-9").map_within(RangeSet("3-4")),
@@ -74,3 +75,51 @@
     self.assertEqual(RangeSet("10-19 30-39").extend(4), RangeSet("6-23 26-43"))
     self.assertEqual(RangeSet("10-19 30-39").extend(10), RangeSet("0-49"))
 
+  def test_equality(self):
+    self.assertTrue(RangeSet("") == RangeSet(""))
+    self.assertTrue(RangeSet("3") == RangeSet("3"))
+    self.assertTrue(RangeSet("3 5") == RangeSet("5 3"))
+    self.assertTrue(
+        RangeSet("10-19 30-39") == RangeSet("30-32 10-14 33-39 15-19"))
+    self.assertTrue(RangeSet("") != RangeSet("3"))
+    self.assertTrue(RangeSet("10-19") != RangeSet("10-19 20"))
+
+    self.assertFalse(RangeSet(""))
+    self.assertTrue(RangeSet("3"))
+
+  def test_init(self):
+    self.assertIsNotNone(RangeSet(""))
+    self.assertIsNotNone(RangeSet("3"))
+    self.assertIsNotNone(RangeSet("3 5"))
+    self.assertIsNotNone(RangeSet("10 19 30-39"))
+
+    with self.assertRaises(AssertionError):
+      RangeSet(data=[0])
+
+  def test_str(self):
+    self.assertEqual(str(RangeSet("0-9")), "0-9")
+    self.assertEqual(str(RangeSet("2-10 12")), "2-10 12")
+    self.assertEqual(str(RangeSet("11 2-10 12 1 0")), "0-12")
+    self.assertEqual(str(RangeSet("")), "empty")
+
+  def test_to_string_raw(self):
+    self.assertEqual(RangeSet("0-9").to_string_raw(), "2,0,10")
+    self.assertEqual(RangeSet("2-10 12").to_string_raw(), "4,2,11,12,13")
+    self.assertEqual(RangeSet("11 2-10 12 1 0").to_string_raw(), "2,0,13")
+
+    with self.assertRaises(AssertionError):
+      RangeSet("").to_string_raw()
+
+  def test_monotonic(self):
+    self.assertTrue(RangeSet("0-9").monotonic)
+    self.assertTrue(RangeSet("2-9").monotonic)
+    self.assertTrue(RangeSet("2-9 30 31 35").monotonic)
+    self.assertTrue(RangeSet("").monotonic)
+    self.assertTrue(RangeSet("0-4 5-9").monotonic)
+    self.assertFalse(RangeSet("5-9 0-4").monotonic)
+
+    self.assertTrue(RangeSet(data=[0, 10]).monotonic)
+    self.assertTrue(RangeSet(data=[0, 10, 15, 20]).monotonic)
+    self.assertTrue(RangeSet(data=[2, 9, 30, 31, 31, 32, 35, 36]).monotonic)
+    self.assertTrue(RangeSet(data=[0, 5, 5, 10]).monotonic)
+    self.assertFalse(RangeSet(data=[5, 10, 0, 5]).monotonic)
diff --git a/tools/zipalign/Android.mk b/tools/zipalign/Android.mk
index 4194f81..8c0240a 100644
--- a/tools/zipalign/Android.mk
+++ b/tools/zipalign/Android.mk
@@ -22,20 +22,17 @@
 	liblog \
 	libzopfli
 
-ifeq ($(HOST_OS),linux)
-LOCAL_LDLIBS += -lrt
-endif
+LOCAL_LDLIBS_linux += -lrt
 
-ifdef USE_MINGW
-LOCAL_STATIC_LIBRARIES += libz
-else
-LOCAL_LDLIBS += -lz
-endif
+LOCAL_STATIC_LIBRARIES_windows += libz
+LOCAL_LDLIBS_linux += -lz
+LOCAL_LDLIBS_darwin += -lz
 
 ifneq ($(strip $(BUILD_HOST_static)),)
 LOCAL_LDLIBS += -lpthread
 endif # BUILD_HOST_static
 
 LOCAL_MODULE := zipalign
+LOCAL_MODULE_HOST_OS := darwin linux windows
 
 include $(BUILD_HOST_EXECUTABLE)