1 /* 2 * Copyright (C) 2011 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 __SHARE_ALLOC_H_ 18 #define __SHARE_ALLOC_H_ 19 20 #include <limits.h> 21 22 // malloc(n floor 1) 23 static inline void *safe_malloc_(size_t n) 24 { 25 // dlmalloc is already safe 26 return malloc(n); 27 } 28 29 // malloc(n1 * n2) then memset to zero 30 static inline void *safe_calloc_(size_t n1, size_t n2) 31 { 32 // dlcalloc is already safe 33 return calloc(n1, n2); 34 } 35 36 // malloc(n1 + n2) 37 static inline void *safe_malloc_add_2op_(size_t n1, size_t n2) 38 { 39 unsigned long long n = n1 + n2; 40 size_t ns = n; 41 // check for overflow 42 return n == ns ? malloc(ns) : NULL; 43 } 44 45 // malloc(n1 * n2) 46 static inline void *safe_malloc_mul_2op_(size_t n1, size_t n2) 47 { 48 unsigned long long n = n1 * n2; 49 size_t ns = n; 50 // check for overflow 51 return n == ns ? malloc(ns) : NULL; 52 } 53 54 // malloc(n1 * (n2 + n3)) 55 static inline void *safe_malloc_muladd2_(size_t n1, size_t n2, size_t n3) 56 { 57 unsigned long long n = n1 * (n2 + n3); 58 size_t ns = n; 59 // check for overflow 60 return n == ns ? malloc(ns) : NULL; 61 } 62 63 // realloc(ptr, n1 * n2) 64 static inline void *safe_realloc_mul_2op_(void *ptr, size_t n1, size_t n2) 65 { 66 unsigned long long n = n1 * n2; 67 size_t ns = n; 68 // check for overflow 69 return n == ns ? realloc(ptr, ns) : NULL; 70 } 71 72 #endif // __SHARE_ALLOC_H_ 73