Merge cherrypicks of [2780928, 2780896, 2781450, 2781451, 2781452, 2781453, 2781454, 2781169, 2781470, 2781471, 2781472, 2781473, 2781474, 2780929, 2781185, 2781490, 2781491, 2781492, 2781493, 2781494, 2781495, 2781496, 2781497, 2781437, 2781498, 2781499, 2781500, 2781501, 2781502, 2781503, 2781504, 2781505, 2781506, 2781507, 2780897, 2780898, 2780899, 2780900, 2780901, 2781475, 2781476, 2781477, 2781478, 2781186, 2781511, 2781512, 2781630] into nyc-bugfix-release

Change-Id: I7d10db3433dbdf7d861277d41fc060b96507d222
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index 986ee72..49097ce 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -386,6 +386,14 @@
   const uint8_t* const cd_end = cd_ptr + cd_length;
   const uint8_t* ptr = cd_ptr;
   for (uint16_t i = 0; i < num_entries; i++) {
+    if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
+      ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
+#if defined(__ANDROID__)
+      android_errorWriteLog(0x534e4554, "36392138");
+#endif
+      return -1;
+    }
+
     const CentralDirectoryRecord* cdr =
         reinterpret_cast<const CentralDirectoryRecord*>(ptr);
     if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
@@ -393,11 +401,6 @@
       return -1;
     }
 
-    if (ptr + sizeof(CentralDirectoryRecord) > cd_end) {
-      ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
-      return -1;
-    }
-
     const off64_t local_header_offset = cdr->local_file_header_offset;
     if (local_header_offset >= archive->directory_offset) {
       ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,