libutils: fix overflow in SharedBuffer
See
https://code.google.com/p/android/issues/detail?id=181910
Bug: 22952485
Change-Id: Idcc7e581a69436c8a623659fbd9add9e5f0d4c74
diff --git a/libutils/SharedBuffer.cpp b/libutils/SharedBuffer.cpp
index 3555fb7..c4ca0e0 100644
--- a/libutils/SharedBuffer.cpp
+++ b/libutils/SharedBuffer.cpp
@@ -17,6 +17,7 @@
#include <stdlib.h>
#include <string.h>
+#include <log/log.h>
#include <utils/SharedBuffer.h>
#include <utils/Atomic.h>
@@ -26,6 +27,11 @@
SharedBuffer* SharedBuffer::alloc(size_t size)
{
+ // Don't overflow if the combined size of the buffer / header is larger than
+ // size_max.
+ LOG_ALWAYS_FATAL_IF((size >= (SIZE_MAX - sizeof(SharedBuffer))),
+ "Invalid buffer size %zu", size);
+
SharedBuffer* sb = static_cast<SharedBuffer *>(malloc(sizeof(SharedBuffer) + size));
if (sb) {
sb->mRefs = 1;
@@ -52,7 +58,7 @@
memcpy(sb->data(), data(), size());
release();
}
- return sb;
+ return sb;
}
SharedBuffer* SharedBuffer::editResize(size_t newSize) const
@@ -60,6 +66,11 @@
if (onlyOwner()) {
SharedBuffer* buf = const_cast<SharedBuffer*>(this);
if (buf->mSize == newSize) return buf;
+ // Don't overflow if the combined size of the new buffer / header is larger than
+ // size_max.
+ LOG_ALWAYS_FATAL_IF((newSize >= (SIZE_MAX - sizeof(SharedBuffer))),
+ "Invalid buffer size %zu", newSize);
+
buf = (SharedBuffer*)realloc(buf, sizeof(SharedBuffer) + newSize);
if (buf != NULL) {
buf->mSize = newSize;