1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef A_BASE_H_
18 
19 #define A_BASE_H_
20 
21 #ifndef ARRAY_SIZE
22 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
23 #endif
24 
25 #define DISALLOW_EVIL_CONSTRUCTORS(name) \
26     name(const name &); \
27     name &operator=(const name &) /* NOLINT */
28 
29 /* Returns true if the size parameter is safe for new array allocation (32-bit)
30  *
31  * Example usage:
32  *
33  * if (!isSafeArraySize<uint32_t>(arraySize)) {
34  *     return BAD_VALUE;
35  * }
36  * ...
37  * uint32_t *myArray = new uint32_t[arraySize];
38  *
39  * There is a bug in gcc versions earlier than 4.8 where the new[] array allocation
40  * will overflow in the internal 32 bit heap allocation, resulting in an
41  * underallocated array. This is a security issue that allows potential overwriting
42  * of other heap data.
43  *
44  * An alternative to checking is to create a safe new array template function which
45  * either throws a std::bad_alloc exception or returns NULL/nullptr_t; NULL considered
46  * safe since normal access of NULL throws an exception.
47  *
48  * https://securityblog.redhat.com/2012/10/31/array-allocation-in-cxx/
49  */
50 template <typename T, typename S>
isSafeArraySize(S size)51 bool isSafeArraySize(S size) {
52     return size >= 0                            // in case S is signed, ignored if not.
53             && size <= 0xffffffff / sizeof(T);  // max-unsigned-32-bit-int / element-size.
54 }
55 
56 #endif  // A_BASE_H_
57