Make export_includes a restat rule

There is currently an intentional incremental rebuild issue with
import_includes.  export_includes might get updated with an identical
version, but we don't want to force everything downstream of it to
rebuild.

When BUILDING_WITH_NINJA==true, only update export_includes if it
changes, and use .KATI_RESTAT to only run downstream rules if it
changes.  import_includes will only be updated if one of the
export_includes files is updated, so object files can have a normal
dependency on import_includes instead of an order-only dependency.
All downstream object files will now be recompiled if their imported
include paths change.

Bug: 25910568
Change-Id: I626f3b24ac02ac1309049cf1ce66cfe8ec816513
diff --git a/core/binary.mk b/core/binary.mk
index 028950a..a62423c 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -1134,7 +1134,11 @@
 # that custom build rules which generate .o files don't consume other generated
 # sources as input (or if they do they take care of that dependency themselves).
 $(normal_objects) : | $(my_generated_sources)
+ifeq ($(BUILDING_WITH_NINJA),true)
+$(all_objects) : $(import_includes)
+else
 $(all_objects) : | $(import_includes)
+endif
 ALL_C_CPP_ETC_OBJECTS += $(all_objects)
 
 
@@ -1307,14 +1311,26 @@
 # generated after the headers, so this is a convenient way to ensure the headers exist.
 $(export_includes) : $(LOCAL_MODULE_MAKEFILE_DEP) $(proto_generated_headers) $(dbus_generated_headers) $(aidl_gen_cpp)
 	@echo Export includes file: $< -- $@
-	$(hide) mkdir -p $(dir $@) && rm -f $@
+	$(hide) mkdir -p $(dir $@) && rm -f $@.tmp
 ifdef my_export_c_include_dirs
 	$(hide) for d in $(PRIVATE_EXPORT_C_INCLUDE_DIRS); do \
-	        echo "-I $$d" >> $@; \
+	        echo "-I $$d" >> $@.tmp; \
 	        done
 else
-	$(hide) touch $@
+	$(hide) touch $@.tmp
 endif
+ifeq ($(BUILDING_WITH_NINJA),true)
+	$(hide) if cmp -s $@.tmp $@ ; then \
+	  rm $@.tmp ; \
+	else \
+	  mv $@.tmp $@ ; \
+	fi
+else
+	mv $@.tmp $@ ;
+endif
+
+# Kati adds restat=1 to ninja. GNU make does nothing for this.
+.KATI_RESTAT: $(export_includes)
 
 # Make sure export_includes gets generated when you are running mm/mmm
 $(LOCAL_BUILT_MODULE) : | $(export_includes)