Merge "Add suffix .so to use directly libart.so"
diff --git a/core/LINUX_KERNEL_COPYING b/core/LINUX_KERNEL_COPYING
new file mode 100644
index 0000000..ca442d3
--- /dev/null
+++ b/core/LINUX_KERNEL_COPYING
@@ -0,0 +1,356 @@
+
+   NOTE! This copyright does *not* cover user programs that use kernel
+ services by normal system calls - this is merely considered normal use
+ of the kernel, and does *not* fall under the heading of "derived work".
+ Also note that the GPL below is copyrighted by the Free Software
+ Foundation, but the instance of code that it refers to (the Linux
+ kernel) is copyrighted by me and others who actually wrote it.
+
+ Also note that the only valid version of the GPL as far as the kernel
+ is concerned is _this_ particular version of the license (ie v2, not
+ v2.2 or v3.x or whatever), unless explicitly otherwise stated.
+
+			Linus Torvalds
+
+----------------------------------------
+
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                       51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/core/Makefile b/core/Makefile
index 5011940..237d5d1 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -664,7 +664,7 @@
 # make the target NOTICE files depend on this particular file too, which will
 # then be in the right directory for the find in combine-notice-files to work.
 $(kernel_notice_file): \
-	    prebuilts/qemu-kernel/arm/LINUX_KERNEL_COPYING \
+	    $(BUILD_SYSTEM)/LINUX_KERNEL_COPYING \
 	    | $(ACP)
 	@echo Copying: $@
 	$(hide) mkdir -p $(dir $@)
@@ -1630,6 +1630,8 @@
 	$(hide) for part in $(AB_OTA_PARTITIONS); do \
 	  echo "$${part}" >> $(zip_root)/META/ab_partitions.txt; \
 	done
+	@# Include the build type in META/misc_info.txt so the server can easily differentiate production builds.
+	$(hide) echo "build_type=$(TARGET_BUILD_VARIANT)" >> $(zip_root)/META/misc_info.txt
 ifdef OSRELEASED_DIRECTORY
 	$(hide) $(ACP) $(TARGET_OUT_ETC)/$(OSRELEASED_DIRECTORY)/product_id $(zip_root)/META/product_id.txt
 	$(hide) $(ACP) $(TARGET_OUT_ETC)/$(OSRELEASED_DIRECTORY)/product_version $(zip_root)/META/product_version.txt
diff --git a/core/base_rules.mk b/core/base_rules.mk
index a0a3582..42dfc1b 100644
--- a/core/base_rules.mk
+++ b/core/base_rules.mk
@@ -221,6 +221,33 @@
 LOCAL_INTERMEDIATE_TARGETS += $(LOCAL_BUILT_MODULE)
 
 ###########################################################
+## Create .toc files from shared objects to reduce unnecessary rebuild
+# .toc files have the list of external dynamic symbols without their addresses.
+# For ninja build, .toc files will be updated only when the content of .toc
+# files are changed. As .KATI_RESTAT is specified to .toc files, dependent
+# binaries of a .toc file will be rebuilt only when the content of
+# the .toc file is changed.
+###########################################################
+ifeq ($(LOCAL_MODULE_CLASS),SHARED_LIBRARIES)
+LOCAL_INTERMEDIATE_TARGETS += $(LOCAL_BUILT_MODULE).toc
+$(LOCAL_BUILT_MODULE).toc: $(LOCAL_BUILT_MODULE)
+ifeq ($(BUILDING_WITH_NINJA),true)
+	$(call $(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)transform-shared-lib-to-toc,$<,$@.tmp)
+	$(hide) if cmp -s $@.tmp $@ ; then \
+		  rm $@.tmp ; \
+		else \
+		  mv $@.tmp $@ ; \
+		fi
+else
+	@# make doesn't support restat. We always update .toc files so the dependents will always be updated too.
+	$(call $(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)transform-shared-lib-to-toc,$<,$@)
+endif
+
+# Kati adds restat=1 to ninja. GNU make does nothing for this.
+.KATI_RESTAT: $(LOCAL_BUILT_MODULE).toc
+endif
+
+###########################################################
 ## logtags: Add .logtags files to global list
 ###########################################################
 
diff --git a/core/binary.mk b/core/binary.mk
index e9b2265..d3b536d 100644
--- a/core/binary.mk
+++ b/core/binary.mk
@@ -1175,6 +1175,7 @@
     $(addprefix $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)OUT_INTERMEDIATE_LIBRARIES)/, \
       $(addsuffix $(so_suffix), \
         $(my_shared_libraries)))
+built_shared_library_tocs := $(addsuffix .toc, $(built_shared_libraries))
 
 # Add the NDK libraries to the built module dependency
 my_system_shared_libraries_fullpath := \
@@ -1188,6 +1189,8 @@
     $(addprefix $($(LOCAL_2ND_ARCH_VAR_PREFIX)$(my_prefix)OUT_INTERMEDIATE_LIBRARIES)/, \
       $(addsuffix $(so_suffix), \
         $(installed_shared_library_module_names)))
+built_shared_library_tocs := $(addsuffix .toc, $(built_shared_libraries))
+my_system_shared_libraries_fullpath :=
 endif
 
 built_static_libraries := \
@@ -1282,7 +1285,8 @@
 ###########################################################
 # all_libraries is used for the dependencies on LOCAL_BUILT_MODULE.
 all_libraries := \
-    $(built_shared_libraries) \
+    $(built_shared_library_tocs) \
+    $(my_system_shared_libraries_fullpath) \
     $(built_static_libraries) \
     $(built_whole_libraries)
 
diff --git a/core/clang/config.mk b/core/clang/config.mk
index 0c5e963..03e8dd5 100644
--- a/core/clang/config.mk
+++ b/core/clang/config.mk
@@ -1,7 +1,6 @@
 ## Clang configurations.
 
-LLVM_PREBUILTS_VERSION := 3.6
-FORCE_BUILD_SANITIZER_SHARED_OBJECTS := true
+LLVM_PREBUILTS_VERSION := 3.8
 LLVM_PREBUILTS_PATH := prebuilts/clang/host/$(BUILD_OS)-x86/$(LLVM_PREBUILTS_VERSION)/bin
 LLVM_RTLIB_PATH := $(LLVM_PREBUILTS_PATH)/../lib/clang/$(LLVM_PREBUILTS_VERSION)/lib/linux/
 
diff --git a/core/combo/HOST_CROSS_windows-x86.mk b/core/combo/HOST_CROSS_windows-x86.mk
index c5a713c..c2a65bc 100644
--- a/core/combo/HOST_CROSS_windows-x86.mk
+++ b/core/combo/HOST_CROSS_windows-x86.mk
@@ -40,6 +40,13 @@
 $(combo_var_prefix)CC := $(TOOLS_PREFIX)gcc
 $(combo_var_prefix)CXX := $(TOOLS_PREFIX)g++
 $(combo_var_prefix)AR := $(TOOLS_PREFIX)ar
+$(combo_var_prefix)NM := $(TOOLS_PREFIX)nm
+$(combo_var_prefix)OBJDUMP := $(TOOLS_PREFIX)objdump
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(hide) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)OBJDUMP) -x $(1) | grep "^Name" | cut -f3 -d" " > $(2)
+$(hide) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)NM) -g -f p $(1) | cut -f1-2 -d" " >> $(2)
+endef
 
 $(combo_var_prefix)GLOBAL_LDFLAGS += \
     --enable-stdcall-fixup
diff --git a/core/combo/HOST_darwin-x86.mk b/core/combo/HOST_darwin-x86.mk
index 85c883c..fc56e52 100644
--- a/core/combo/HOST_darwin-x86.mk
+++ b/core/combo/HOST_darwin-x86.mk
@@ -36,6 +36,10 @@
 $(combo_2nd_arch_prefix)HOST_CC  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)-gcc
 $(combo_2nd_arch_prefix)HOST_CXX := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)-g++
 
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_macho,$(1),$(2))
+endef
+
 # gcc location for clang; to be updated when clang is updated
 # HOST_TOOLCHAIN_ROOT is a Darwin-specific define
 $(combo_2nd_arch_prefix)HOST_TOOLCHAIN_FOR_CLANG := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_ROOT)
diff --git a/core/combo/HOST_darwin-x86_64.mk b/core/combo/HOST_darwin-x86_64.mk
index 93a1b3e..251455f 100644
--- a/core/combo/HOST_darwin-x86_64.mk
+++ b/core/combo/HOST_darwin-x86_64.mk
@@ -36,6 +36,10 @@
 HOST_CC  := $(HOST_TOOLCHAIN_PREFIX)-gcc
 HOST_CXX := $(HOST_TOOLCHAIN_PREFIX)-g++
 
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_macho,$(1),$(2))
+endef
+
 # gcc location for clang; to be updated when clang is updated
 # HOST_TOOLCHAIN_ROOT is a Darwin-specific define
 HOST_TOOLCHAIN_FOR_CLANG := $(HOST_TOOLCHAIN_ROOT)
diff --git a/core/combo/HOST_linux-x86.mk b/core/combo/HOST_linux-x86.mk
index 4caf607..b5efc71 100644
--- a/core/combo/HOST_linux-x86.mk
+++ b/core/combo/HOST_linux-x86.mk
@@ -23,6 +23,12 @@
 $(combo_2nd_arch_prefix)HOST_CC  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)gcc
 $(combo_2nd_arch_prefix)HOST_CXX := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)g++
 $(combo_2nd_arch_prefix)HOST_AR  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)ar
+$(combo_2nd_arch_prefix)HOST_READELF  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)readelf
+$(combo_2nd_arch_prefix)HOST_NM  := $($(combo_2nd_arch_prefix)HOST_TOOLCHAIN_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 # 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
diff --git a/core/combo/HOST_linux-x86_64.mk b/core/combo/HOST_linux-x86_64.mk
index 3708137..9a77324 100644
--- a/core/combo/HOST_linux-x86_64.mk
+++ b/core/combo/HOST_linux-x86_64.mk
@@ -23,6 +23,12 @@
 HOST_CC  := $(HOST_TOOLCHAIN_PREFIX)gcc
 HOST_CXX := $(HOST_TOOLCHAIN_PREFIX)g++
 HOST_AR  := $(HOST_TOOLCHAIN_PREFIX)ar
+HOST_READELF  := $(HOST_TOOLCHAIN_PREFIX)readelf
+HOST_NM  := $(HOST_TOOLCHAIN_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 # 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
diff --git a/core/combo/TARGET_linux-arm.mk b/core/combo/TARGET_linux-arm.mk
index 5f0f1d2..485e48c 100644
--- a/core/combo/TARGET_linux-arm.mk
+++ b/core/combo/TARGET_linux-arm.mk
@@ -63,6 +63,11 @@
 $(combo_2nd_arch_prefix)TARGET_LD := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)ld
 $(combo_2nd_arch_prefix)TARGET_READELF := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)readelf
 $(combo_2nd_arch_prefix)TARGET_STRIP := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)strip
+$(combo_2nd_arch_prefix)TARGET_NM := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 $(combo_2nd_arch_prefix)TARGET_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
 
diff --git a/core/combo/TARGET_linux-arm64.mk b/core/combo/TARGET_linux-arm64.mk
index b213ea7..18bdbe7 100644
--- a/core/combo/TARGET_linux-arm64.mk
+++ b/core/combo/TARGET_linux-arm64.mk
@@ -63,6 +63,11 @@
 TARGET_LD := $(TARGET_TOOLS_PREFIX)ld
 TARGET_READELF := $(TARGET_TOOLS_PREFIX)readelf
 TARGET_STRIP := $(TARGET_TOOLS_PREFIX)strip
+TARGET_NM := $(TARGET_TOOLS_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 TARGET_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
 
@@ -110,6 +115,8 @@
 			-Wl,-maarch64linux \
 			-Wl,--hash-style=gnu \
 			-Wl,--fix-cortex-a53-843419 \
+			-fuse-ld=gold \
+			-Wl,--icf=safe \
 			$(arch_variant_ldflags)
 
 # Disable transitive dependency library symbol resolving.
diff --git a/core/combo/TARGET_linux-mips.mk b/core/combo/TARGET_linux-mips.mk
index 8e117eb..be05302 100644
--- a/core/combo/TARGET_linux-mips.mk
+++ b/core/combo/TARGET_linux-mips.mk
@@ -63,6 +63,11 @@
 $(combo_2nd_arch_prefix)TARGET_LD := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)ld
 $(combo_2nd_arch_prefix)TARGET_READELF := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)readelf
 $(combo_2nd_arch_prefix)TARGET_STRIP := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)strip
+$(combo_2nd_arch_prefix)TARGET_NM := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 $(combo_2nd_arch_prefix)TARGET_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
 
diff --git a/core/combo/TARGET_linux-mips64.mk b/core/combo/TARGET_linux-mips64.mk
index 565083a..9704b6b 100644
--- a/core/combo/TARGET_linux-mips64.mk
+++ b/core/combo/TARGET_linux-mips64.mk
@@ -63,6 +63,11 @@
 TARGET_LD := $(TARGET_TOOLS_PREFIX)ld
 TARGET_READELF := $(TARGET_TOOLS_PREFIX)readelf
 TARGET_STRIP := $(TARGET_TOOLS_PREFIX)strip
+TARGET_NM := $(TARGET_TOOLS_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 TARGET_NO_UNDEFINED_LDFLAGS := -Wl,--no-undefined
 
diff --git a/core/combo/TARGET_linux-x86.mk b/core/combo/TARGET_linux-x86.mk
index 5fff641..c4cb0f8 100644
--- a/core/combo/TARGET_linux-x86.mk
+++ b/core/combo/TARGET_linux-x86.mk
@@ -56,6 +56,11 @@
 $(combo_2nd_arch_prefix)TARGET_LD := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)ld
 $(combo_2nd_arch_prefix)TARGET_READELF := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)readelf
 $(combo_2nd_arch_prefix)TARGET_STRIP := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)strip
+$(combo_2nd_arch_prefix)TARGET_NM := $($(combo_2nd_arch_prefix)TARGET_TOOLS_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 ifneq ($(wildcard $($(combo_2nd_arch_prefix)TARGET_CC)),)
 $(combo_2nd_arch_prefix)TARGET_LIBGCC := \
diff --git a/core/combo/TARGET_linux-x86_64.mk b/core/combo/TARGET_linux-x86_64.mk
index cacfae1..b7ec50b 100644
--- a/core/combo/TARGET_linux-x86_64.mk
+++ b/core/combo/TARGET_linux-x86_64.mk
@@ -56,6 +56,11 @@
 TARGET_LD := $(TARGET_TOOLS_PREFIX)ld
 TARGET_READELF := $(TARGET_TOOLS_PREFIX)readelf
 TARGET_STRIP := $(TARGET_TOOLS_PREFIX)strip
+TARGET_NM := $(TARGET_TOOLS_PREFIX)nm
+
+define $(combo_var_prefix)transform-shared-lib-to-toc
+$(call _gen_toc_command_for_elf,$(1),$(2))
+endef
 
 ifneq ($(wildcard $(TARGET_CC)),)
 TARGET_LIBGCC := \
diff --git a/core/config.mk b/core/config.mk
index 5678a83..49810ee 100644
--- a/core/config.mk
+++ b/core/config.mk
@@ -281,6 +281,18 @@
 endif
 TARGET_CPU_ABI2 := $(strip $(TARGET_CPU_ABI2))
 
+# Commands to generate .toc file common to ELF .so files.
+define _gen_toc_command_for_elf
+$(hide) ($($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)READELF) -d $(1) | grep SONAME || echo "No SONAME for $1") > $(2)
+$(hide) $($(PRIVATE_2ND_ARCH_VAR_PREFIX)$(PRIVATE_PREFIX)NM) -gD -f p $(1) | cut -f1-2 -d" " >> $(2)
+endef
+
+# Commands to generate .toc file from Darwin dynamic library.
+define _gen_toc_command_for_macho
+$(hide) otool -l $(1) | grep LC_ID_DYLIB -A 5 > $(2)
+$(hide) nm -gP $(1) | cut -f1-2 -d" " | grep -v U$$ >> $(2)
+endef
+
 combo_target := HOST_
 combo_2nd_arch_prefix :=
 include $(BUILD_SYSTEM)/combo/select.mk
diff --git a/core/config_sanitizers.mk b/core/config_sanitizers.mk
index 7189338..df52e72 100644
--- a/core/config_sanitizers.mk
+++ b/core/config_sanitizers.mk
@@ -84,7 +84,7 @@
 endif
 
 ifneq ($(my_sanitize),)
-  fsanitize_arg := $(subst $(space),$(comma),$(my_sanitize)),
+  fsanitize_arg := $(subst $(space),$(comma),$(my_sanitize))
   my_cflags += -fsanitize=$(fsanitize_arg)
 
   ifdef LOCAL_IS_HOST_MODULE
@@ -92,8 +92,10 @@
     my_ldflags += -fsanitize=$(fsanitize_arg)
     my_ldlibs += -lrt -ldl
   else
-    my_cflags += -fsanitize-undefined-trap-on-error
-    my_cflags += -ftrap-function=abort
+    ifeq ($(filter address,$(my_sanitize)),)
+      my_cflags += -fsanitize-trap=all
+      my_cflags += -ftrap-function=abort
+    endif
     my_shared_libraries += libdl
   endif
 endif
diff --git a/core/definitions.mk b/core/definitions.mk
index 5a6a411..1c8f41a 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -1516,7 +1516,6 @@
 $(transform-o-to-shared-lib-inner)
 endef
 
-
 ###########################################################
 ## Commands for filtering a target executable or library
 ###########################################################
diff --git a/core/package_internal.mk b/core/package_internal.mk
index a2cbe31..cb77e76 100644
--- a/core/package_internal.mk
+++ b/core/package_internal.mk
@@ -176,7 +176,7 @@
 ifeq (true,$(EMMA_INSTRUMENT))
 ifndef LOCAL_EMMA_INSTRUMENT
 # No emma for test apks.
-ifeq (,$(filer tests,$(LOCAL_MODULE_TAGS))$(LOCAL_INSTRUMENTATION_FOR))
+ifeq (,$(LOCAL_INSTRUMENTATION_FOR))
 LOCAL_EMMA_INSTRUMENT := true
 endif # No test apk
 endif # LOCAL_EMMA_INSTRUMENT is not set
diff --git a/envsetup.sh b/envsetup.sh
index c3e467c..45f70b3 100644
--- a/envsetup.sh
+++ b/envsetup.sh
@@ -1520,7 +1520,8 @@
         echo ""
         echo "ALL DATA ON THE DEVICE WILL BE IRREVOCABLY ERASED."
         echo ""
-        read -p "Are you sure you want to do this (yes/no)? "
+        echo -n "Are you sure you want to do this (yes/no)? "
+        read
         if [[ "${REPLY}" != "yes" ]] ; then
             echo "Not taking any action. Exiting." >&2
             return 1
diff --git a/target/board/generic/sepolicy/property_contexts b/target/board/generic/sepolicy/property_contexts
index f4653c0..152f0c8 100644
--- a/target/board/generic/sepolicy/property_contexts
+++ b/target/board/generic/sepolicy/property_contexts
@@ -1,3 +1,5 @@
 qemu.                   u:object_r:qemu_prop:s0
+emu.                    u:object_r:qemu_prop:s0
+emulator.               u:object_r:qemu_prop:s0
 radio.noril             u:object_r:radio_noril_prop:s0
 opengles.               u:object_r:opengles_prop:s0
diff --git a/tools/generate-notice-files.py b/tools/generate-notice-files.py
index 4571b70..5b13bf5 100755
--- a/tools/generate-notice-files.py
+++ b/tools/generate-notice-files.py
@@ -99,7 +99,7 @@
     # most browsers, but href's to table row ids do)
     id_table = {}
     id_count = 0
-    for value in file_hash.values():
+    for value in file_hash:
         for filename in value:
              id_table[filename] = id_count
         id_count += 1
@@ -116,7 +116,7 @@
     print >> output_file, "<ul>"
 
     # Flatten the list of lists into a single list of filenames
-    sorted_filenames = sorted(itertools.chain.from_iterable(file_hash.values()))
+    sorted_filenames = sorted(itertools.chain.from_iterable(file_hash))
 
     # Print out a nice table of contents
     for filename in sorted_filenames:
@@ -127,11 +127,11 @@
     print >> output_file, "</div><!-- table of contents -->"
     # Output the individual notice file lists
     print >>output_file, '<table cellpadding="0" cellspacing="0" border="0">'
-    for value in file_hash.values():
+    for value in file_hash:
         print >> output_file, '<tr id="id%d"><td class="same-license">' % id_table.get(value[0])
         print >> output_file, '<div class="label">Notices for file(s):</div>'
         print >> output_file, '<div class="file-list">'
-        for filename in sorted(value):
+        for filename in value:
             print >> output_file, "%s <br/>" % (SRC_DIR_STRIP_RE.sub(r"\1", filename))
         print >> output_file, "</div><!-- file-list -->"
         print >> output_file
@@ -154,10 +154,10 @@
     SRC_DIR_STRIP_RE = re.compile(input_dir + "(/.*).txt")
     output_file = open(output_filename, "wb")
     print >> output_file, file_title
-    for value in file_hash.values():
+    for value in file_hash:
       print >> output_file, "============================================================"
       print >> output_file, "Notices for file(s):"
-      for filename in sorted(value):
+      for filename in value:
         print >> output_file, SRC_DIR_STRIP_RE.sub(r"\1", filename)
       print >> output_file, "------------------------------------------------------------"
       print >> output_file, open(value[0]).read()
@@ -178,11 +178,12 @@
                 file_md5sum = md5sum(filename)
                 files_with_same_hash[file_md5sum].append(filename)
 
+    filesets = [sorted(files_with_same_hash[md5]) for md5 in sorted(files_with_same_hash.keys())]
 
     print "Combining NOTICE files into HTML"
-    combine_notice_files_html(files_with_same_hash, input_dir, html_output_file)
+    combine_notice_files_html(filesets, input_dir, html_output_file)
     print "Combining NOTICE files into text"
-    combine_notice_files_text(files_with_same_hash, input_dir, txt_output_file, file_title)
+    combine_notice_files_text(filesets, input_dir, txt_output_file, file_title)
 
 if __name__ == "__main__":
     main(args)
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 1295230..872dd4c 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -1085,6 +1085,9 @@
     processor."""
     return self._DoCall("IncrementalOTA_InstallEnd")
 
+  def VerifyOTA_Assertions(self):
+    return self._DoCall("VerifyOTA_Assertions")
+
 class File(object):
   def __init__(self, name, data):
     self.name = name
@@ -1279,6 +1282,25 @@
     self._WriteUpdate(script, output_zip)
     self._WritePostInstallVerifyScript(script)
 
+  def WriteStrictVerifyScript(self, script):
+    """Verify all the blocks in the care_map, including clobbered blocks.
+
+    This differs from the WriteVerifyScript() function: a) it prints different
+    error messages; b) it doesn't allow half-way updated images to pass the
+    verification."""
+
+    partition = self.partition
+    script.Print("Verifying %s..." % (partition,))
+    ranges = self.tgt.care_map
+    ranges_str = ranges.to_string_raw()
+    script.AppendExtra('range_sha1("%s", "%s") == "%s" && '
+                       'ui_print("    Verified.") || '
+                       'ui_print("\\"%s\\" has unexpected contents.");' % (
+                       self.device, ranges_str,
+                       self.tgt.TotalSha1(include_clobbered_blocks=True),
+                       self.device))
+    script.AppendExtra("")
+
   def WriteVerifyScript(self, script):
     partition = self.partition
     if not self.src:
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index a4fc0b3..b3785ac 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -152,6 +152,15 @@
         "".join([', "%s"' % (i,) for i in sha1]) +
         ') || abort("\\"%s\\" has unexpected contents.");' % (filename,))
 
+  def Verify(self, filename):
+    """Check that the given file (or MTD reference) has one of the
+    given hashes (encoded in the filename)."""
+    self.script.append(
+        'apply_patch_check("{filename}") && '
+        'ui_print("    Verified.") || '
+        'ui_print("\\"{filename}\\" has unexpected contents.");'.format(
+            filename=filename))
+
   def FileCheck(self, filename, *sha1):
     """Check that the given file (or MTD reference) has one of the
     given *sha1 hashes."""
diff --git a/tools/releasetools/ota_from_target_files.py b/tools/releasetools/ota_from_target_files.py
index e019b1e..fd57b93 100755
--- a/tools/releasetools/ota_from_target_files.py
+++ b/tools/releasetools/ota_from_target_files.py
@@ -91,6 +91,9 @@
   --stash_threshold <float>
       Specifies the threshold that will be used to compute the maximum
       allowed stash size (defaults to 0.8).
+
+  --gen_verify
+      Generate an OTA package that verifies the partitions.
 """
 
 import sys
@@ -133,6 +136,7 @@
 # Stash size cannot exceed cache_size * threshold.
 OPTIONS.cache_size = None
 OPTIONS.stash_threshold = 0.8
+OPTIONS.gen_verify = False
 
 def MostPopularKey(d, default):
   """Given a dict, return the key corresponding to the largest
@@ -984,6 +988,79 @@
   WriteMetadata(metadata, output_zip)
 
 
+def WriteVerifyPackage(input_zip, output_zip):
+  script = edify_generator.EdifyGenerator(3, OPTIONS.info_dict)
+
+  oem_props = OPTIONS.info_dict.get("oem_fingerprint_properties")
+  recovery_mount_options = OPTIONS.info_dict.get(
+      "recovery_mount_options")
+  oem_dict = None
+  if oem_props is not None and len(oem_props) > 0:
+    if OPTIONS.oem_source is None:
+      raise common.ExternalError("OEM source required for this build")
+    script.Mount("/oem", recovery_mount_options)
+    oem_dict = common.LoadDictionaryFromLines(
+        open(OPTIONS.oem_source).readlines())
+
+  target_fp = CalculateFingerprint(oem_props, oem_dict, OPTIONS.info_dict)
+  metadata = {
+      "post-build": target_fp,
+      "pre-device": GetOemProperty("ro.product.device", oem_props, oem_dict,
+                                   OPTIONS.info_dict),
+      "post-timestamp": GetBuildProp("ro.build.date.utc", OPTIONS.info_dict),
+  }
+
+  device_specific = common.DeviceSpecificParams(
+      input_zip=input_zip,
+      input_version=OPTIONS.info_dict["recovery_api_version"],
+      output_zip=output_zip,
+      script=script,
+      input_tmp=OPTIONS.input_tmp,
+      metadata=metadata,
+      info_dict=OPTIONS.info_dict)
+
+  AppendAssertions(script, OPTIONS.info_dict, oem_dict)
+
+  script.Print("Verifying device images against %s..." % target_fp)
+  script.AppendExtra("")
+
+  script.Print("Verifying boot...")
+  boot_img = common.GetBootableImage(
+      "boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
+  boot_type, boot_device = common.GetTypeAndDevice(
+      "/boot", OPTIONS.info_dict)
+  script.Verify("%s:%s:%d:%s" % (
+      boot_type, boot_device, boot_img.size, boot_img.sha1))
+  script.AppendExtra("")
+
+  script.Print("Verifying recovery...")
+  recovery_img = common.GetBootableImage(
+      "recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
+  recovery_type, recovery_device = common.GetTypeAndDevice(
+      "/recovery", OPTIONS.info_dict)
+  script.Verify("%s:%s:%d:%s" % (
+      recovery_type, recovery_device, recovery_img.size, recovery_img.sha1))
+  script.AppendExtra("")
+
+  system_tgt = GetImage("system", OPTIONS.input_tmp, OPTIONS.info_dict)
+  system_tgt.ResetFileMap()
+  system_diff = common.BlockDifference("system", system_tgt, src=None)
+  system_diff.WriteStrictVerifyScript(script)
+
+  if HasVendorPartition(input_zip):
+    vendor_tgt = GetImage("vendor", OPTIONS.input_tmp, OPTIONS.info_dict)
+    vendor_tgt.ResetFileMap()
+    vendor_diff = common.BlockDifference("vendor", vendor_tgt, src=None)
+    vendor_diff.WriteStrictVerifyScript(script)
+
+  # Device specific partitions, such as radio, bootloader and etc.
+  device_specific.VerifyOTA_Assertions()
+
+  script.SetProgress(1.0)
+  script.AddToZip(input_zip, output_zip, input_path=OPTIONS.updater_binary)
+  WriteMetadata(metadata, output_zip)
+
+
 class FileDifference(object):
   def __init__(self, partition, source_zip, target_zip, output_zip):
     self.deferred_patch_list = None
@@ -1552,6 +1629,8 @@
       except ValueError:
         raise ValueError("Cannot parse value %r for option %r - expecting "
                          "a float" % (a, o))
+    elif o == "--gen_verify":
+      OPTIONS.gen_verify = True
     else:
       return False
     return True
@@ -1577,6 +1656,7 @@
                                  "verify",
                                  "no_fallback_to_full",
                                  "stash_threshold=",
+                                 "gen_verify"
                              ], extra_option_handler=option_handler)
 
   if len(args) != 2:
@@ -1618,57 +1698,61 @@
     raise common.ExternalError(
         "--- target build has specified no recovery ---")
 
-  while True:
+  # Use the default key to sign the package if not specified with package_key.
+  if not OPTIONS.no_signing:
+    if OPTIONS.package_key is None:
+      OPTIONS.package_key = OPTIONS.info_dict.get(
+          "default_system_dev_certificate",
+          "build/target/product/security/testkey")
 
-    if OPTIONS.no_signing:
-      if os.path.exists(args[1]):
-        os.unlink(args[1])
-      output_zip = zipfile.ZipFile(args[1], "w",
-                                   compression=zipfile.ZIP_DEFLATED)
-    else:
-      temp_zip_file = tempfile.NamedTemporaryFile()
-      output_zip = zipfile.ZipFile(temp_zip_file, "w",
-                                   compression=zipfile.ZIP_DEFLATED)
+  # Set up the output zip. Create a temporary zip file if signing is needed.
+  if OPTIONS.no_signing:
+    if os.path.exists(args[1]):
+      os.unlink(args[1])
+    output_zip = zipfile.ZipFile(args[1], "w",
+                                 compression=zipfile.ZIP_DEFLATED)
+  else:
+    temp_zip_file = tempfile.NamedTemporaryFile()
+    output_zip = zipfile.ZipFile(temp_zip_file, "w",
+                                 compression=zipfile.ZIP_DEFLATED)
 
-    cache_size = OPTIONS.info_dict.get("cache_size", None)
-    if cache_size is None:
-      print "--- can't determine the cache partition size ---"
-    OPTIONS.cache_size = cache_size
+  cache_size = OPTIONS.info_dict.get("cache_size", None)
+  if cache_size is None:
+    print "--- can't determine the cache partition size ---"
+  OPTIONS.cache_size = cache_size
 
-    if OPTIONS.incremental_source is None:
+  # Generate a verify package.
+  if OPTIONS.gen_verify:
+    WriteVerifyPackage(input_zip, output_zip)
+
+  # Generate a full OTA.
+  elif OPTIONS.incremental_source is None:
+    WriteFullOTAPackage(input_zip, output_zip)
+
+  # Generate an incremental OTA. It will fall back to generate a full OTA on
+  # failure unless no_fallback_to_full is specified.
+  else:
+    print "unzipping source target-files..."
+    OPTIONS.source_tmp, source_zip = common.UnzipTemp(
+        OPTIONS.incremental_source)
+    OPTIONS.target_info_dict = OPTIONS.info_dict
+    OPTIONS.source_info_dict = common.LoadInfoDict(source_zip,
+                                                   OPTIONS.source_tmp)
+    if OPTIONS.verbose:
+      print "--- source info ---"
+      common.DumpInfoDict(OPTIONS.source_info_dict)
+    try:
+      WriteIncrementalOTAPackage(input_zip, source_zip, output_zip)
+    except ValueError:
+      if not OPTIONS.fallback_to_full:
+        raise
+      print "--- failed to build incremental; falling back to full ---"
+      OPTIONS.incremental_source = None
       WriteFullOTAPackage(input_zip, output_zip)
-      if OPTIONS.package_key is None:
-        OPTIONS.package_key = OPTIONS.info_dict.get(
-            "default_system_dev_certificate",
-            "build/target/product/security/testkey")
-      common.ZipClose(output_zip)
-      break
 
-    else:
-      print "unzipping source target-files..."
-      OPTIONS.source_tmp, source_zip = common.UnzipTemp(
-          OPTIONS.incremental_source)
-      OPTIONS.target_info_dict = OPTIONS.info_dict
-      OPTIONS.source_info_dict = common.LoadInfoDict(source_zip,
-                                                     OPTIONS.source_tmp)
-      if OPTIONS.package_key is None:
-        OPTIONS.package_key = OPTIONS.source_info_dict.get(
-            "default_system_dev_certificate",
-            "build/target/product/security/testkey")
-      if OPTIONS.verbose:
-        print "--- source info ---"
-        common.DumpInfoDict(OPTIONS.source_info_dict)
-      try:
-        WriteIncrementalOTAPackage(input_zip, source_zip, output_zip)
-        common.ZipClose(output_zip)
-        break
-      except ValueError:
-        if not OPTIONS.fallback_to_full:
-          raise
-        print "--- failed to build incremental; falling back to full ---"
-        OPTIONS.incremental_source = None
-        common.ZipClose(output_zip)
+  common.ZipClose(output_zip)
 
+  # Sign the generated zip package unless no_signing is specified.
   if not OPTIONS.no_signing:
     SignOutput(temp_zip_file.name, args[1])
     temp_zip_file.close()
diff --git a/tools/zipalign/ZipEntry.cpp b/tools/zipalign/ZipEntry.cpp
index b2270cb..a13b8d1 100644
--- a/tools/zipalign/ZipEntry.cpp
+++ b/tools/zipalign/ZipEntry.cpp
@@ -26,6 +26,7 @@
 #include <stdio.h>
 #include <string.h>
 #include <assert.h>
+#include <inttypes.h>
 
 using namespace android;
 
@@ -56,7 +57,7 @@
     /* using the info in the CDE, go load up the LFH */
     posn = ftell(fp);
     if (fseek(fp, mCDE.mLocalHeaderRelOffset, SEEK_SET) != 0) {
-        ALOGD("local header seek failed (%ld)\n",
+        ALOGD("local header seek failed (%" PRIu32 ")\n",
             mCDE.mLocalHeaderRelOffset);
         return UNKNOWN_ERROR;
     }
@@ -123,12 +124,12 @@
     mCDE.mExternalAttrs = 0x81b60020;   // matches what WinZip does
 
     if (mCDE.mFileNameLength > 0) {
-        mCDE.mFileName = new unsigned char[mCDE.mFileNameLength+1];
+        mCDE.mFileName = new uint8_t[mCDE.mFileNameLength+1];
         strcpy((char*) mCDE.mFileName, fileName);
     }
     if (mCDE.mFileCommentLength > 0) {
         /* TODO: stop assuming null-terminated ASCII here? */
-        mCDE.mFileComment = new unsigned char[mCDE.mFileCommentLength+1];
+        mCDE.mFileComment = new uint8_t[mCDE.mFileCommentLength+1];
         strcpy((char*) mCDE.mFileComment, comment);
     }
 
@@ -150,20 +151,20 @@
     memcpy(&mCDE, &pEntry->mCDE, sizeof(mCDE));
 
     if (mCDE.mFileNameLength > 0) {
-        mCDE.mFileName = new unsigned char[mCDE.mFileNameLength+1];
+        mCDE.mFileName = new uint8_t[mCDE.mFileNameLength+1];
         if (mCDE.mFileName == NULL)
             return NO_MEMORY;
         strcpy((char*) mCDE.mFileName, (char*)pEntry->mCDE.mFileName);
     }
     if (mCDE.mFileCommentLength > 0) {
-        mCDE.mFileComment = new unsigned char[mCDE.mFileCommentLength+1];
+        mCDE.mFileComment = new uint8_t[mCDE.mFileCommentLength+1];
         if (mCDE.mFileComment == NULL)
             return NO_MEMORY;
         strcpy((char*) mCDE.mFileComment, (char*)pEntry->mCDE.mFileComment);
     }
     if (mCDE.mExtraFieldLength > 0) {
         /* we null-terminate this, though it may not be a string */
-        mCDE.mExtraField = new unsigned char[mCDE.mExtraFieldLength+1];
+        mCDE.mExtraField = new uint8_t[mCDE.mExtraFieldLength+1];
         if (mCDE.mExtraField == NULL)
             return NO_MEMORY;
         memcpy(mCDE.mExtraField, pEntry->mCDE.mExtraField,
@@ -180,7 +181,7 @@
     assert(mLFH.mExtraField == NULL);
     mLFH.mExtraFieldLength = pEntry->mLFH.mExtraFieldLength;
     if (mLFH.mExtraFieldLength > 0) {
-        mLFH.mExtraField = new unsigned char[mLFH.mExtraFieldLength+1];
+        mLFH.mExtraField = new uint8_t[mLFH.mExtraFieldLength+1];
         if (mLFH.mExtraField == NULL)
             return NO_MEMORY;
         memcpy(mLFH.mExtraField, pEntry->mLFH.mExtraField,
@@ -205,9 +206,9 @@
 
     if (mLFH.mExtraFieldLength > 0) {
         /* extend existing field */
-        unsigned char* newExtra;
+        uint8_t* newExtra;
 
-        newExtra = new unsigned char[mLFH.mExtraFieldLength + padding];
+        newExtra = new uint8_t[mLFH.mExtraFieldLength + padding];
         if (newExtra == NULL)
             return NO_MEMORY;
         memset(newExtra + mLFH.mExtraFieldLength, 0, padding);
@@ -218,7 +219,7 @@
         mLFH.mExtraFieldLength += padding;
     } else {
         /* create new field */
-        mLFH.mExtraField = new unsigned char[padding];
+        mLFH.mExtraField = new uint8_t[padding];
         memset(mLFH.mExtraField, 0, padding);
         mLFH.mExtraFieldLength = padding;
     }
@@ -246,7 +247,7 @@
 
     delete[] mLFH.mFileName;
     if (mLFH.mFileNameLength > 0) {
-        mLFH.mFileName = new unsigned char[mLFH.mFileNameLength+1];
+        mLFH.mFileName = new uint8_t[mLFH.mFileNameLength+1];
         strcpy((char*) mLFH.mFileName, (const char*) mCDE.mFileName);
     } else {
         mLFH.mFileName = NULL;
@@ -256,7 +257,7 @@
 /*
  * Set some information about a file after we add it.
  */
-void ZipEntry::setDataInfo(long uncompLen, long compLen, unsigned long crc32,
+void ZipEntry::setDataInfo(long uncompLen, long compLen, uint32_t crc32,
     int compressionMethod)
 {
     mCDE.mCompressionMethod = compressionMethod;
@@ -360,7 +361,7 @@
     struct tm tmResult;
 #endif
     time_t even;
-    unsigned short zdate, ztime;
+    uint16_t zdate, ztime;
 
     struct tm* ptm;
 
@@ -402,7 +403,7 @@
 status_t ZipEntry::LocalFileHeader::read(FILE* fp)
 {
     status_t result = NO_ERROR;
-    unsigned char buf[kLFHLen];
+    uint8_t buf[kLFHLen];
 
     assert(mFileName == NULL);
     assert(mExtraField == NULL);
@@ -433,7 +434,7 @@
 
     /* grab filename */
     if (mFileNameLength != 0) {
-        mFileName = new unsigned char[mFileNameLength+1];
+        mFileName = new uint8_t[mFileNameLength+1];
         if (mFileName == NULL) {
             result = NO_MEMORY;
             goto bail;
@@ -447,7 +448,7 @@
 
     /* grab extra field */
     if (mExtraFieldLength != 0) {
-        mExtraField = new unsigned char[mExtraFieldLength+1];
+        mExtraField = new uint8_t[mExtraFieldLength+1];
         if (mExtraField == NULL) {
             result = NO_MEMORY;
             goto bail;
@@ -468,7 +469,7 @@
  */
 status_t ZipEntry::LocalFileHeader::write(FILE* fp)
 {
-    unsigned char buf[kLFHLen];
+    uint8_t buf[kLFHLen];
 
     ZipEntry::putLongLE(&buf[0x00], kSignature);
     ZipEntry::putShortLE(&buf[0x04], mVersionToExtract);
@@ -507,13 +508,13 @@
 void ZipEntry::LocalFileHeader::dump(void) const
 {
     ALOGD(" LocalFileHeader contents:\n");
-    ALOGD("  versToExt=%u gpBits=0x%04x compression=%u\n",
+    ALOGD("  versToExt=%" PRIu16 " gpBits=0x%04" PRIx16 " compression=%" PRIu16 "\n",
         mVersionToExtract, mGPBitFlag, mCompressionMethod);
-    ALOGD("  modTime=0x%04x modDate=0x%04x crc32=0x%08lx\n",
+    ALOGD("  modTime=0x%04" PRIx16 " modDate=0x%04" PRIx16 " crc32=0x%08" PRIx32 "\n",
         mLastModFileTime, mLastModFileDate, mCRC32);
-    ALOGD("  compressedSize=%lu uncompressedSize=%lu\n",
+    ALOGD("  compressedSize=%" PRIu32 " uncompressedSize=%" PRIu32 "\n",
         mCompressedSize, mUncompressedSize);
-    ALOGD("  filenameLen=%u extraLen=%u\n",
+    ALOGD("  filenameLen=%" PRIu16 " extraLen=%" PRIu16 "\n",
         mFileNameLength, mExtraFieldLength);
     if (mFileName != NULL)
         ALOGD("  filename: '%s'\n", mFileName);
@@ -536,7 +537,7 @@
 status_t ZipEntry::CentralDirEntry::read(FILE* fp)
 {
     status_t result = NO_ERROR;
-    unsigned char buf[kCDELen];
+    uint8_t buf[kCDELen];
 
     /* no re-use */
     assert(mFileName == NULL);
@@ -575,7 +576,7 @@
 
     /* grab filename */
     if (mFileNameLength != 0) {
-        mFileName = new unsigned char[mFileNameLength+1];
+        mFileName = new uint8_t[mFileNameLength+1];
         if (mFileName == NULL) {
             result = NO_MEMORY;
             goto bail;
@@ -589,7 +590,7 @@
 
     /* read "extra field" */
     if (mExtraFieldLength != 0) {
-        mExtraField = new unsigned char[mExtraFieldLength+1];
+        mExtraField = new uint8_t[mExtraFieldLength+1];
         if (mExtraField == NULL) {
             result = NO_MEMORY;
             goto bail;
@@ -604,7 +605,7 @@
 
     /* grab comment, if any */
     if (mFileCommentLength != 0) {
-        mFileComment = new unsigned char[mFileCommentLength+1];
+        mFileComment = new uint8_t[mFileCommentLength+1];
         if (mFileComment == NULL) {
             result = NO_MEMORY;
             goto bail;
@@ -626,7 +627,7 @@
  */
 status_t ZipEntry::CentralDirEntry::write(FILE* fp)
 {
-    unsigned char buf[kCDELen];
+    uint8_t buf[kCDELen];
 
     ZipEntry::putLongLE(&buf[0x00], kSignature);
     ZipEntry::putShortLE(&buf[0x04], mVersionMadeBy);
@@ -676,15 +677,15 @@
 void ZipEntry::CentralDirEntry::dump(void) const
 {
     ALOGD(" CentralDirEntry contents:\n");
-    ALOGD("  versMadeBy=%u versToExt=%u gpBits=0x%04x compression=%u\n",
+    ALOGD("  versMadeBy=%" PRIu16 " versToExt=%" PRIu16 " gpBits=0x%04" PRIx16 " compression=%" PRIu16 "\n",
         mVersionMadeBy, mVersionToExtract, mGPBitFlag, mCompressionMethod);
-    ALOGD("  modTime=0x%04x modDate=0x%04x crc32=0x%08lx\n",
+    ALOGD("  modTime=0x%04" PRIx16 " modDate=0x%04" PRIx16 " crc32=0x%08" PRIx32 "\n",
         mLastModFileTime, mLastModFileDate, mCRC32);
-    ALOGD("  compressedSize=%lu uncompressedSize=%lu\n",
+    ALOGD("  compressedSize=%" PRIu32 " uncompressedSize=%" PRIu32 "\n",
         mCompressedSize, mUncompressedSize);
-    ALOGD("  filenameLen=%u extraLen=%u commentLen=%u\n",
+    ALOGD("  filenameLen=%" PRIu16 " extraLen=%" PRIu16 " commentLen=%" PRIu16 "\n",
         mFileNameLength, mExtraFieldLength, mFileCommentLength);
-    ALOGD("  diskNumStart=%u intAttr=0x%04x extAttr=0x%08lx relOffset=%lu\n",
+    ALOGD("  diskNumStart=%" PRIu16 " intAttr=0x%04" PRIx16 " extAttr=0x%08" PRIx32 " relOffset=%" PRIu32 "\n",
         mDiskNumberStart, mInternalAttrs, mExternalAttrs,
         mLocalHeaderRelOffset);
 
diff --git a/tools/zipalign/ZipEntry.h b/tools/zipalign/ZipEntry.h
index 7f721b4..129a759 100644
--- a/tools/zipalign/ZipEntry.h
+++ b/tools/zipalign/ZipEntry.h
@@ -25,6 +25,7 @@
 #include <utils/Errors.h>
 
 #include <stdlib.h>
+#include <stdint.h>
 #include <stdio.h>
 
 namespace android {
@@ -85,7 +86,7 @@
     /*
      * Return the data CRC.
      */
-    unsigned long getCRC32(void) const { return mCDE.mCRC32; }
+    uint32_t getCRC32(void) const { return mCDE.mCRC32; }
 
     /*
      * Return file modification time in UNIX seconds-since-epoch.
@@ -108,21 +109,21 @@
      * Some basic functions for raw data manipulation.  "LE" means
      * Little Endian.
      */
-    static inline unsigned short getShortLE(const unsigned char* buf) {
+    static inline uint16_t getShortLE(const uint8_t* buf) {
         return buf[0] | (buf[1] << 8);
     }
-    static inline unsigned long getLongLE(const unsigned char* buf) {
+    static inline uint32_t getLongLE(const uint8_t* buf) {
         return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
     }
-    static inline void putShortLE(unsigned char* buf, short val) {
-        buf[0] = (unsigned char) val;
-        buf[1] = (unsigned char) (val >> 8);
+    static inline void putShortLE(uint8_t* buf, uint16_t val) {
+        buf[0] = (uint8_t) val;
+        buf[1] = (uint8_t) (val >> 8);
     }
-    static inline void putLongLE(unsigned char* buf, long val) {
-        buf[0] = (unsigned char) val;
-        buf[1] = (unsigned char) (val >> 8);
-        buf[2] = (unsigned char) (val >> 16);
-        buf[3] = (unsigned char) (val >> 24);
+    static inline void putLongLE(uint8_t* buf, uint32_t val) {
+        buf[0] = (uint8_t) val;
+        buf[1] = (uint8_t) (val >> 8);
+        buf[2] = (uint8_t) (val >> 16);
+        buf[3] = (uint8_t) (val >> 24);
     }
 
     /* defined for Zip archives */
@@ -177,7 +178,7 @@
     /*
      * Set information about the data for this entry.
      */
-    void setDataInfo(long uncompLen, long compLen, unsigned long crc32,
+    void setDataInfo(long uncompLen, long compLen, uint32_t crc32,
         int compressionMethod);
 
     /*
@@ -195,7 +196,7 @@
      * the current file.
      */
     void setLFHOffset(off_t offset) {
-        mCDE.mLocalHeaderRelOffset = (long) offset;
+        mCDE.mLocalHeaderRelOffset = (uint32_t) offset;
     }
 
     /* mark for deletion; used by ZipFile::remove() */
@@ -240,19 +241,19 @@
         status_t read(FILE* fp);
         status_t write(FILE* fp);
 
-        // unsigned long mSignature;
-        unsigned short  mVersionToExtract;
-        unsigned short  mGPBitFlag;
-        unsigned short  mCompressionMethod;
-        unsigned short  mLastModFileTime;
-        unsigned short  mLastModFileDate;
-        unsigned long   mCRC32;
-        unsigned long   mCompressedSize;
-        unsigned long   mUncompressedSize;
-        unsigned short  mFileNameLength;
-        unsigned short  mExtraFieldLength;
-        unsigned char*  mFileName;
-        unsigned char*  mExtraField;
+        // uint32_t mSignature;
+        uint16_t mVersionToExtract;
+        uint16_t mGPBitFlag;
+        uint16_t mCompressionMethod;
+        uint16_t mLastModFileTime;
+        uint16_t mLastModFileDate;
+        uint32_t mCRC32;
+        uint32_t mCompressedSize;
+        uint32_t mUncompressedSize;
+        uint16_t mFileNameLength;
+        uint16_t mExtraFieldLength;
+        uint8_t* mFileName;
+        uint8_t* mExtraField;
 
         enum {
             kSignature      = 0x04034b50,
@@ -298,26 +299,26 @@
         status_t read(FILE* fp);
         status_t write(FILE* fp);
 
-        // unsigned long mSignature;
-        unsigned short  mVersionMadeBy;
-        unsigned short  mVersionToExtract;
-        unsigned short  mGPBitFlag;
-        unsigned short  mCompressionMethod;
-        unsigned short  mLastModFileTime;
-        unsigned short  mLastModFileDate;
-        unsigned long   mCRC32;
-        unsigned long   mCompressedSize;
-        unsigned long   mUncompressedSize;
-        unsigned short  mFileNameLength;
-        unsigned short  mExtraFieldLength;
-        unsigned short  mFileCommentLength;
-        unsigned short  mDiskNumberStart;
-        unsigned short  mInternalAttrs;
-        unsigned long   mExternalAttrs;
-        unsigned long   mLocalHeaderRelOffset;
-        unsigned char*  mFileName;
-        unsigned char*  mExtraField;
-        unsigned char*  mFileComment;
+        // uint32_t mSignature;
+        uint16_t mVersionMadeBy;
+        uint16_t mVersionToExtract;
+        uint16_t mGPBitFlag;
+        uint16_t mCompressionMethod;
+        uint16_t mLastModFileTime;
+        uint16_t mLastModFileDate;
+        uint32_t mCRC32;
+        uint32_t mCompressedSize;
+        uint32_t mUncompressedSize;
+        uint16_t mFileNameLength;
+        uint16_t mExtraFieldLength;
+        uint16_t mFileCommentLength;
+        uint16_t mDiskNumberStart;
+        uint16_t mInternalAttrs;
+        uint32_t mExternalAttrs;
+        uint32_t mLocalHeaderRelOffset;
+        uint8_t* mFileName;
+        uint8_t* mExtraField;
+        uint8_t* mFileComment;
 
         void dump(void) const;
 
diff --git a/tools/zipalign/ZipFile.cpp b/tools/zipalign/ZipFile.cpp
index 3c5ec15..7c3ff37 100644
--- a/tools/zipalign/ZipFile.cpp
+++ b/tools/zipalign/ZipFile.cpp
@@ -34,6 +34,7 @@
 #include <sys/stat.h>
 #include <errno.h>
 #include <assert.h>
+#include <inttypes.h>
 
 using namespace android;
 
@@ -206,7 +207,7 @@
 status_t ZipFile::readCentralDir(void)
 {
     status_t result = NO_ERROR;
-    unsigned char* buf = NULL;
+    uint8_t* buf = NULL;
     off_t fileLength, seekStart;
     long readAmount;
     int i;
@@ -222,7 +223,7 @@
         goto bail;
     }
 
-    buf = new unsigned char[EndOfCentralDir::kMaxEOCDSearch];
+    buf = new uint8_t[EndOfCentralDir::kMaxEOCDSearch];
     if (buf == NULL) {
         ALOGD("Failure allocating %d bytes for EOCD search",
              EndOfCentralDir::kMaxEOCDSearch);
@@ -296,7 +297,7 @@
      * we're hoping to preserve.
      */
     if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
-        ALOGD("Failure seeking to central dir offset %ld\n",
+        ALOGD("Failure seeking to central dir offset %" PRIu32 "\n",
              mEOCD.mCentralDirOffset);
         result = UNKNOWN_ERROR;
         goto bail;
@@ -305,7 +306,7 @@
     /*
      * Loop through and read the central dir entries.
      */
-    ALOGV("Scanning %d entries...\n", mEOCD.mTotalNumEntries);
+    ALOGV("Scanning %" PRIu16 " entries...\n", mEOCD.mTotalNumEntries);
     int entry;
     for (entry = 0; entry < mEOCD.mTotalNumEntries; entry++) {
         ZipEntry* pEntry = new ZipEntry;
@@ -325,7 +326,7 @@
      * If all went well, we should now be back at the EOCD.
      */
     {
-        unsigned char checkBuf[4];
+        uint8_t checkBuf[4];
         if (fread(checkBuf, 1, 4, mZipFp) != 4) {
             ALOGD("EOCD check read failed\n");
             result = INVALID_OPERATION;
@@ -365,7 +366,7 @@
     status_t result = NO_ERROR;
     long lfhPosn, startPosn, endPosn, uncompressedLen;
     FILE* inputFp = NULL;
-    unsigned long crc;
+    uint32_t crc;
     time_t modWhen;
 
     if (mReadOnly)
@@ -466,14 +467,16 @@
         bool scanResult;
         int method;
         long compressedLen;
+        unsigned long longcrc;
 
         scanResult = ZipUtils::examineGzip(inputFp, &method, &uncompressedLen,
-                        &compressedLen, &crc);
+                        &compressedLen, &longcrc);
         if (!scanResult || method != ZipEntry::kCompressDeflated) {
             ALOGD("this isn't a deflated gzip file?");
             result = UNKNOWN_ERROR;
             goto bail;
         }
+        crc = longcrc;
 
         result = copyPartialFpToFp(mZipFp, inputFp, compressedLen, NULL);
         if (result != NO_ERROR) {
@@ -710,7 +713,7 @@
             goto bail;
         }
         long startPosn = ftell(mZipFp);
-        unsigned long crc;
+        uint32_t crc;
         if (compressFpToFp(mZipFp, NULL, buf, uncompressedLen, &crc) != NO_ERROR) {
             ALOGW("recompress of '%s' failed\n", pEntry->mCDE.mFileName);
             result = UNKNOWN_ERROR;
@@ -780,9 +783,9 @@
  * On exit, "srcFp" will be seeked to the end of the file, and "dstFp"
  * will be seeked immediately past the data.
  */
-status_t ZipFile::copyFpToFp(FILE* dstFp, FILE* srcFp, unsigned long* pCRC32)
+status_t ZipFile::copyFpToFp(FILE* dstFp, FILE* srcFp, uint32_t* pCRC32)
 {
-    unsigned char tmpBuf[32768];
+    uint8_t tmpBuf[32768];
     size_t count;
 
     *pCRC32 = crc32(0L, Z_NULL, 0);
@@ -811,7 +814,7 @@
  * On exit, "dstFp" will be seeked immediately past the data.
  */
 status_t ZipFile::copyDataToFp(FILE* dstFp,
-    const void* data, size_t size, unsigned long* pCRC32)
+    const void* data, size_t size, uint32_t* pCRC32)
 {
     size_t count;
 
@@ -836,9 +839,9 @@
  * will be seeked immediately past the data just written.
  */
 status_t ZipFile::copyPartialFpToFp(FILE* dstFp, FILE* srcFp, long length,
-    unsigned long* pCRC32)
+    uint32_t* pCRC32)
 {
-    unsigned char tmpBuf[32768];
+    uint8_t tmpBuf[32768];
     size_t count;
 
     if (pCRC32 != NULL)
@@ -846,7 +849,7 @@
 
     while (length) {
         long readSize;
-        
+
         readSize = sizeof(tmpBuf);
         if (readSize > length)
             readSize = length;
@@ -878,15 +881,15 @@
  * will be seeked immediately past the compressed data.
  */
 status_t ZipFile::compressFpToFp(FILE* dstFp, FILE* srcFp,
-    const void* data, size_t size, unsigned long* pCRC32)
+    const void* data, size_t size, uint32_t* pCRC32)
 {
     status_t result = NO_ERROR;
     const size_t kBufSize = 1024 * 1024;
-    unsigned char* inBuf = NULL;
-    unsigned char* outBuf = NULL;
+    uint8_t* inBuf = NULL;
+    uint8_t* outBuf = NULL;
     size_t outSize = 0;
     bool atEof = false;     // no feof() aviailable yet
-    unsigned long crc;
+    uint32_t crc;
     ZopfliOptions options;
     unsigned char bp = 0;
 
@@ -902,7 +905,7 @@
         /*
          * Create an input buffer and an output buffer.
          */
-        inBuf = new unsigned char[kBufSize];
+        inBuf = new uint8_t[kBufSize];
         if (inBuf == NULL) {
             result = NO_MEMORY;
             goto bail;
@@ -1128,7 +1131,7 @@
     if (dst == src || n <= 0)
         return NO_ERROR;
 
-    unsigned char readBuf[32768];
+    uint8_t readBuf[32768];
 
     if (dst < src) {
         /* shift stuff toward start of file; must read from start */
@@ -1294,7 +1297,7 @@
  * "buf" should be positioned at the EOCD signature, and should contain
  * the entire EOCD area including the comment.
  */
-status_t ZipFile::EndOfCentralDir::readBuf(const unsigned char* buf, int len)
+status_t ZipFile::EndOfCentralDir::readBuf(const uint8_t* buf, int len)
 {
     /* don't allow re-use */
     assert(mComment == NULL);
@@ -1322,11 +1325,11 @@
 
     if (mCommentLen > 0) {
         if (kEOCDLen + mCommentLen > len) {
-            ALOGD("EOCD(%d) + comment(%d) exceeds len (%d)\n",
+            ALOGD("EOCD(%d) + comment(%" PRIu16 ") exceeds len (%d)\n",
                 kEOCDLen, mCommentLen, len);
             return UNKNOWN_ERROR;
         }
-        mComment = new unsigned char[mCommentLen];
+        mComment = new uint8_t[mCommentLen];
         memcpy(mComment, buf + kEOCDLen, mCommentLen);
     }
 
@@ -1338,7 +1341,7 @@
  */
 status_t ZipFile::EndOfCentralDir::write(FILE* fp)
 {
-    unsigned char buf[kEOCDLen];
+    uint8_t buf[kEOCDLen];
 
     ZipEntry::putLongLE(&buf[0x00], kSignature);
     ZipEntry::putShortLE(&buf[0x04], mDiskNumber);
@@ -1366,9 +1369,9 @@
 void ZipFile::EndOfCentralDir::dump(void) const
 {
     ALOGD(" EndOfCentralDir contents:\n");
-    ALOGD("  diskNum=%u diskWCD=%u numEnt=%u totalNumEnt=%u\n",
+    ALOGD("  diskNum=%" PRIu16 " diskWCD=%" PRIu16 " numEnt=%" PRIu16 " totalNumEnt=%" PRIu16 "\n",
         mDiskNumber, mDiskWithCentralDir, mNumEntries, mTotalNumEntries);
-    ALOGD("  centDirSize=%lu centDirOff=%lu commentLen=%u\n",
+    ALOGD("  centDirSize=%" PRIu32 " centDirOff=%" PRIu32 " commentLen=%" PRIu32 "\n",
         mCentralDirSize, mCentralDirOffset, mCommentLen);
 }
 
diff --git a/tools/zipalign/ZipFile.h b/tools/zipalign/ZipFile.h
index b99cda5..b0bafe9 100644
--- a/tools/zipalign/ZipFile.h
+++ b/tools/zipalign/ZipFile.h
@@ -194,18 +194,18 @@
             delete[] mComment;
         }
 
-        status_t readBuf(const unsigned char* buf, int len);
+        status_t readBuf(const uint8_t* buf, int len);
         status_t write(FILE* fp);
 
-        //unsigned long   mSignature;
-        unsigned short  mDiskNumber;
-        unsigned short  mDiskWithCentralDir;
-        unsigned short  mNumEntries;
-        unsigned short  mTotalNumEntries;
-        unsigned long   mCentralDirSize;
-        unsigned long   mCentralDirOffset;      // offset from first disk
-        unsigned short  mCommentLen;
-        unsigned char*  mComment;
+        //uint32_t mSignature;
+        uint16_t mDiskNumber;
+        uint16_t mDiskWithCentralDir;
+        uint16_t mNumEntries;
+        uint16_t mTotalNumEntries;
+        uint32_t mCentralDirSize;
+        uint32_t mCentralDirOffset;      // offset from first disk
+        uint16_t mCommentLen;
+        uint8_t* mComment;
 
         enum {
             kSignature      = 0x06054b50,
@@ -235,18 +235,18 @@
         ZipEntry** ppEntry);
 
     /* copy all of "srcFp" into "dstFp" */
-    status_t copyFpToFp(FILE* dstFp, FILE* srcFp, unsigned long* pCRC32);
+    status_t copyFpToFp(FILE* dstFp, FILE* srcFp, uint32_t* pCRC32);
     /* copy all of "data" into "dstFp" */
     status_t copyDataToFp(FILE* dstFp,
-        const void* data, size_t size, unsigned long* pCRC32);
+        const void* data, size_t size, uint32_t* pCRC32);
     /* copy some of "srcFp" into "dstFp" */
     status_t copyPartialFpToFp(FILE* dstFp, FILE* srcFp, long length,
-        unsigned long* pCRC32);
+        uint32_t* pCRC32);
     /* like memmove(), but on parts of a single file */
     status_t filemove(FILE* fp, off_t dest, off_t src, size_t n);
     /* compress all of "srcFp" into "dstFp", using Deflate */
     status_t compressFpToFp(FILE* dstFp, FILE* srcFp,
-        const void* data, size_t size, unsigned long* pCRC32);
+        const void* data, size_t size, uint32_t* pCRC32);
 
     /* get modification date from a file descriptor */
     time_t getModTime(int fd);
diff --git a/tools/ziptime/ZipEntry.cpp b/tools/ziptime/ZipEntry.cpp
index bdbdd32..51ce09f 100644
--- a/tools/ziptime/ZipEntry.cpp
+++ b/tools/ziptime/ZipEntry.cpp
@@ -23,6 +23,7 @@
 #include <stdio.h>
 #include <string.h>
 #include <assert.h>
+#include <inttypes.h>
 
 using namespace android;
 
@@ -55,7 +56,7 @@
     /* using the info in the CDE, go load up the LFH */
     posn = ftell(fp);
     if (fseek(fp, mCDE.mLocalHeaderRelOffset, SEEK_SET) != 0) {
-        LOG("local header seek failed (%ld)\n",
+        LOG("local header seek failed (%" PRIu32 ")\n",
             mCDE.mLocalHeaderRelOffset);
         return -1;
     }
@@ -86,7 +87,7 @@
 status_t ZipEntry::LocalFileHeader::rewrite(FILE* fp)
 {
     status_t result = 0;
-    unsigned char buf[kLFHLen];
+    uint8_t buf[kLFHLen];
 
     if (fread(buf, 1, kLFHLen, fp) != kLFHLen)
         return -1;
@@ -124,8 +125,8 @@
 status_t ZipEntry::CentralDirEntry::rewrite(FILE* fp)
 {
     status_t result = 0;
-    unsigned char buf[kCDELen];
-    unsigned short fileNameLength, extraFieldLength, fileCommentLength;
+    uint8_t buf[kCDELen];
+    uint16_t fileNameLength, extraFieldLength, fileCommentLength;
 
     if (fread(buf, 1, kCDELen, fp) != kCDELen)
         return -1;
diff --git a/tools/ziptime/ZipEntry.h b/tools/ziptime/ZipEntry.h
index beea20c..26bf596 100644
--- a/tools/ziptime/ZipEntry.h
+++ b/tools/ziptime/ZipEntry.h
@@ -23,6 +23,7 @@
 #define __LIBS_ZIPENTRY_H
 
 #include <stdlib.h>
+#include <stdint.h>
 #include <stdio.h>
 
 typedef int status_t;
@@ -49,15 +50,15 @@
      * Some basic functions for raw data manipulation.  "LE" means
      * Little Endian.
      */
-    static inline unsigned short getShortLE(const unsigned char* buf) {
+    static inline uint16_t getShortLE(const uint8_t* buf) {
         return buf[0] | (buf[1] << 8);
     }
-    static inline unsigned long getLongLE(const unsigned char* buf) {
+    static inline uint32_t getLongLE(const uint8_t* buf) {
         return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
     }
-    static inline void putShortLE(unsigned char* buf, short val) {
-        buf[0] = (unsigned char) val;
-        buf[1] = (unsigned char) (val >> 8);
+    static inline void putShortLE(uint8_t* buf, uint16_t val) {
+        buf[0] = (uint8_t) val;
+        buf[1] = (uint8_t) (val >> 8);
     }
 
 protected:
@@ -99,7 +100,7 @@
 
         status_t rewrite(FILE* fp);
 
-        unsigned long   mLocalHeaderRelOffset;
+        uint32_t mLocalHeaderRelOffset;
 
         enum {
             kSignature      = 0x02014b50,
diff --git a/tools/ziptime/ZipFile.cpp b/tools/ziptime/ZipFile.cpp
index c4c898e..1d111af 100644
--- a/tools/ziptime/ZipFile.cpp
+++ b/tools/ziptime/ZipFile.cpp
@@ -24,6 +24,7 @@
 #include <sys/stat.h>
 #include <errno.h>
 #include <assert.h>
+#include <inttypes.h>
 
 using namespace android;
 
@@ -72,7 +73,7 @@
 status_t ZipFile::rewriteCentralDir(void)
 {
     status_t result = 0;
-    unsigned char* buf = NULL;
+    uint8_t* buf = NULL;
     off_t fileLength, seekStart;
     long readAmount;
     int i;
@@ -88,7 +89,7 @@
         goto bail;
     }
 
-    buf = new unsigned char[EndOfCentralDir::kMaxEOCDSearch];
+    buf = new uint8_t[EndOfCentralDir::kMaxEOCDSearch];
     if (buf == NULL) {
         LOG("Failure allocating %d bytes for EOCD search",
              EndOfCentralDir::kMaxEOCDSearch);
@@ -152,7 +153,7 @@
      * we're hoping to preserve.
      */
     if (fseek(mZipFp, mEOCD.mCentralDirOffset, SEEK_SET) != 0) {
-        LOG("Failure seeking to central dir offset %ld\n",
+        LOG("Failure seeking to central dir offset %" PRIu32 "\n",
              mEOCD.mCentralDirOffset);
         result = -1;
         goto bail;
@@ -179,7 +180,7 @@
     /*
      * If all went well, we should now be back at the EOCD.
      */
-    unsigned char checkBuf[4];
+    uint8_t checkBuf[4];
     if (fread(checkBuf, 1, 4, mZipFp) != 4) {
         LOG("EOCD check read failed\n");
         result = -1;
@@ -208,9 +209,9 @@
  * "buf" should be positioned at the EOCD signature, and should contain
  * the entire EOCD area including the comment.
  */
-status_t ZipFile::EndOfCentralDir::readBuf(const unsigned char* buf, int len)
+status_t ZipFile::EndOfCentralDir::readBuf(const uint8_t* buf, int len)
 {
-    unsigned short diskNumber, diskWithCentralDir, numEntries;
+    uint16_t diskNumber, diskWithCentralDir, numEntries;
 
     if (len < kEOCDLen) {
         /* looks like ZIP file got truncated */
diff --git a/tools/ziptime/ZipFile.h b/tools/ziptime/ZipFile.h
index 50ca923..b049e05 100644
--- a/tools/ziptime/ZipFile.h
+++ b/tools/ziptime/ZipFile.h
@@ -51,10 +51,10 @@
     public:
         EndOfCentralDir(void) : mTotalNumEntries(0), mCentralDirOffset(0) {}
 
-        status_t readBuf(const unsigned char* buf, int len);
+        status_t readBuf(const uint8_t* buf, int len);
 
-        unsigned short  mTotalNumEntries;
-        unsigned long   mCentralDirOffset;      // offset from first disk
+        uint16_t mTotalNumEntries;
+        uint32_t mCentralDirOffset;      // offset from first disk
 
         enum {
             kSignature      = 0x06054b50,