1 /* 2 * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com> 3 * 4 * libcbor is free software; you can redistribute it and/or modify 5 * it under the terms of the MIT license. See LICENSE for details. 6 */ 7 8 #include "memory_utils.h" 9 #include "cbor/common.h" 10 11 // TODO: Consider builtins 12 // (https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html) 13 14 /** Highest on bit position */ 15 size_t _cbor_highest_bit(size_t number) { 16 size_t bit = 0; 17 while (number != 0) { 18 bit++; 19 number >>= 1; 20 } 21 22 return bit; 23 } 24 25 bool _cbor_safe_to_multiply(size_t a, size_t b) { 26 if (a <= 1 || b <= 1) return true; 27 return _cbor_highest_bit(a) + _cbor_highest_bit(b) <= sizeof(size_t) * 8; 28 } 29 30 bool _cbor_safe_to_add(size_t a, size_t b) { 31 // Unsigned integer overflow doesn't constitute UB 32 size_t sum = a + b; 33 return sum >= a && sum >= b; 34 } 35 36 size_t _cbor_safe_signaling_add(size_t a, size_t b) { 37 if (a == 0 || b == 0) return 0; 38 if (_cbor_safe_to_add(a, b)) return a + b; 39 return 0; 40 } 41 42 void* _cbor_alloc_multiple(size_t item_size, size_t item_count) { 43 if (_cbor_safe_to_multiply(item_size, item_count)) { 44 return _cbor_malloc(item_size * item_count); 45 } else { 46 return NULL; 47 } 48 } 49 50 void* _cbor_realloc_multiple(void* pointer, size_t item_size, 51 size_t item_count) { 52 if (_cbor_safe_to_multiply(item_size, item_count)) { 53 return _cbor_realloc(pointer, item_size * item_count); 54 } else { 55 return NULL; 56 } 57 } 58