Merge cherrypicks of ['googleplex-android-review.googlesource.com/26517533'] into sc-v2-platform-release.

Change-Id: Ib91ae5a04da959c23d0f6b01abd6a6f63a15f7e9
diff --git a/include/fmq/MessageQueueBase.h b/include/fmq/MessageQueueBase.h
index b932317..d3c80bb 100644
--- a/include/fmq/MessageQueueBase.h
+++ b/include/fmq/MessageQueueBase.h
@@ -1042,8 +1042,16 @@
 }
 
 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
-size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWriteBytes() const {
-    return mDesc->getSize() - availableToReadBytes();
+inline size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWriteBytes() const {
+    size_t queueSizeBytes = mDesc->getSize();
+    size_t availableBytes = availableToReadBytes();
+    if (queueSizeBytes < availableBytes) {
+        hardware::details::logError(
+                "The write or read pointer has become corrupted. Reading from the queue is no "
+                "longer possible.");
+        return 0;
+    }
+    return queueSizeBytes - availableBytes;
 }
 
 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
@@ -1125,13 +1133,21 @@
 }
 
 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
-size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToReadBytes() const {
+inline size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToReadBytes() const {
     /*
      * This method is invoked by implementations of both read() and write() and
      * hence requires a memory_order_acquired load for both mReadPtr and
      * mWritePtr.
      */
-    return mWritePtr->load(std::memory_order_acquire) - mReadPtr->load(std::memory_order_acquire);
+    uint64_t writePtr = mWritePtr->load(std::memory_order_acquire);
+    uint64_t readPtr = mReadPtr->load(std::memory_order_acquire);
+    if (writePtr < readPtr) {
+        hardware::details::logError(
+                "The write or read pointer has become corrupted. Reading from the queue is no "
+                "longer possible.");
+        return 0;
+    }
+    return writePtr - readPtr;
 }
 
 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>