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#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
22
23#define DISALLOW_EVIL_CONSTRUCTORS(name) \
24    name(const name &); \
25    name &operator=(const name &)
26
27/* Returns true if the size parameter is safe for new array allocation (32-bit)
28 *
29 * Example usage:
30 *
31 * if (!isSafeArraySize<uint32_t>(arraySize)) {
32 *     return BAD_VALUE;
33 * }
34 * ...
35 * uint32_t *myArray = new uint32_t[arraySize];
36 *
37 * There is a bug in gcc versions earlier than 4.8 where the new[] array allocation
38 * will overflow in the internal 32 bit heap allocation, resulting in an
39 * underallocated array. This is a security issue that allows potential overwriting
40 * of other heap data.
41 *
42 * An alternative to checking is to create a safe new array template function which
43 * either throws a std::bad_alloc exception or returns NULL/nullptr_t; NULL considered
44 * safe since normal access of NULL throws an exception.
45 *
46 * https://securityblog.redhat.com/2012/10/31/array-allocation-in-cxx/
47 */
48template <typename T, typename S>
49bool isSafeArraySize(S size) {
50    return size >= 0                            // in case S is signed, ignored if not.
51            && size <= 0xffffffff / sizeof(T);  // max-unsigned-32-bit-int / element-size.
52}
53
54#endif  // A_BASE_H_
55