Merge cherrypicks of [2307556, 2307630, 2307631, 2307557, 2307632, 2307656, 2307743, 2307635, 2307799, 2307577, 2307800, 2307707, 2307803, 2307781, 2307773, 2307637, 2307804, 2307618, 2307734, 2307708, 2307805, 2307709, 2307806, 2307820, 2307746, 2307774, 2307839, 2307735, 2307782, 2307808, 2307840, 2307738, 2307783, 2307749, 2307775, 2307860, 2307899, 2307822, 2307823, 2307880, 2307778, 2307825, 2307882, 2307787, 2307919, 2307844, 2307905, 2307883, 2307829, 2307907, 2307832, 2307944, 2307945, 2307911] into nyc-mr2-pixel-monthly-release

Change-Id: I28eae9950c92e96e8d5a9ec0ae450f7bdfb0b28f
diff --git a/libs/gui/IGraphicBufferProducer.cpp b/libs/gui/IGraphicBufferProducer.cpp
index f4ba3bf..1a08130 100644
--- a/libs/gui/IGraphicBufferProducer.cpp
+++ b/libs/gui/IGraphicBufferProducer.cpp
@@ -26,6 +26,7 @@
 #include <binder/Parcel.h>
 #include <binder/IInterface.h>
 
+#include <gui/BufferQueueDefs.h>
 #include <gui/IGraphicBufferProducer.h>
 #include <gui/IProducerListener.h>
 
@@ -203,8 +204,16 @@
         if (result != NO_ERROR) {
             return result;
         }
+
         *slot = reply.readInt32();
         result = reply.readInt32();
+        if (result == NO_ERROR &&
+                (*slot < 0 || *slot >= BufferQueueDefs::NUM_BUFFER_SLOTS)) {
+            ALOGE("attachBuffer returned invalid slot %d", *slot);
+            android_errorWriteLog(0x534e4554, "37478824");
+            return UNKNOWN_ERROR;
+        }
+
         return result;
     }
 
diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp
index 0838290..5a2ca8d 100644
--- a/libs/gui/Surface.cpp
+++ b/libs/gui/Surface.cpp
@@ -306,6 +306,12 @@
         return result;
     }
 
+    if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
+        ALOGE("dequeueBuffer: IGraphicBufferProducer returned invalid slot number %d", buf);
+        android_errorWriteLog(0x534e4554, "36991414"); // SafetyNet logging
+        return FAILED_TRANSACTION;
+    }
+
     Mutex::Autolock lock(mMutex);
 
     sp<GraphicBuffer>& gbuf(mSlots[buf].buffer);
diff --git a/libs/ui/Fence.cpp b/libs/ui/Fence.cpp
index 7cf8233..5531b23 100644
--- a/libs/ui/Fence.cpp
+++ b/libs/ui/Fence.cpp
@@ -162,7 +162,7 @@
         return INVALID_OPERATION;
     }
 
-    if (size < 1) {
+    if (size < getFlattenedSize()) {
         return NO_MEMORY;
     }