From d00b7d1fb949e226b189e7d0047d78531b3264da Mon Sep 17 00:00:00 2001 From: Andy Hung Date: Tue, 29 Jul 2014 12:14:00 -0700 Subject: [PATCH] Add isSafeArraySize for new array size checks Bug: 15328708 Change-Id: I9dfca30745c3e4dda91c3894363462f8631c41a1 --- include/media/stagefright/foundation/ABase.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/include/media/stagefright/foundation/ABase.h b/include/media/stagefright/foundation/ABase.h index 9eceea3fdc..949d49e70f 100644 --- a/include/media/stagefright/foundation/ABase.h +++ b/include/media/stagefright/foundation/ABase.h @@ -22,4 +22,31 @@ name(const name &); \ name &operator=(const name &) +/* Returns true if the size parameter is safe for new array allocation (32-bit) + * + * Example usage: + * + * if (!isSafeArraySize(arraySize)) { + * return BAD_VALUE; + * } + * ... + * uint32_t *myArray = new uint32_t[arraySize]; + * + * There is a bug in gcc versions earlier than 4.8 where the new[] array allocation + * will overflow in the internal 32 bit heap allocation, resulting in an + * underallocated array. This is a security issue that allows potential overwriting + * of other heap data. + * + * An alternative to checking is to create a safe new array template function which + * either throws a std::bad_alloc exception or returns NULL/nullptr_t; NULL considered + * safe since normal access of NULL throws an exception. + * + * https://securityblog.redhat.com/2012/10/31/array-allocation-in-cxx/ + */ +template +bool isSafeArraySize(S size) { + return size >= 0 // in case S is signed, ignored if not. + && size <= 0xffffffff / sizeof(T); // max-unsigned-32-bit-int / element-size. +} + #endif // A_BASE_H_ -- 2.11.0