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