xalloc-oversized.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* xalloc-oversized.h -- memory allocation size checking
  2. Copyright (C) 1990-2000, 2003-2004, 2006-2016 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #ifndef XALLOC_OVERSIZED_H_
  14. #define XALLOC_OVERSIZED_H_
  15. #include <stddef.h>
  16. #include <stdint.h>
  17. /* Default for (non-Clang) compilers that lack __has_builtin. */
  18. #ifndef __has_builtin
  19. # define __has_builtin(x) 0
  20. #endif
  21. /* True if N * S would overflow in a size_t calculation,
  22. or would generate a value larger than PTRDIFF_MAX.
  23. This expands to a constant expression if N and S are both constants.
  24. By gnulib convention, SIZE_MAX represents overflow in size
  25. calculations, so the conservative size_t-based dividend to use here
  26. is SIZE_MAX - 1. */
  27. #define __xalloc_oversized(n, s) \
  28. ((size_t) (PTRDIFF_MAX < SIZE_MAX ? PTRDIFF_MAX : SIZE_MAX - 1) / (s) < (n))
  29. #if PTRDIFF_MAX < SIZE_MAX
  30. typedef ptrdiff_t __xalloc_count_type;
  31. #else
  32. typedef size_t __xalloc_count_type;
  33. #endif
  34. /* Return 1 if an array of N objects, each of size S, cannot exist
  35. reliably due to size or ptrdiff_t arithmetic overflow. S must be
  36. positive and N must be nonnegative. This is a macro, not a
  37. function, so that it works correctly even when SIZE_MAX < N. */
  38. #if 7 <= __GNUC__ || __has_builtin (__builtin_add_overflow_p)
  39. # define xalloc_oversized(n, s) \
  40. __builtin_mul_overflow_p (n, s, (__xalloc_count_type) 1)
  41. #elif ((5 <= __GNUC__ \
  42. || (__has_builtin (__builtin_mul_overflow) \
  43. && __has_builtin (__builtin_constant_p))) \
  44. && !__STRICT_ANSI__)
  45. # define xalloc_oversized(n, s) \
  46. (__builtin_constant_p (n) && __builtin_constant_p (s) \
  47. ? __xalloc_oversized (n, s) \
  48. : ({ __xalloc_count_type __xalloc_count; \
  49. __builtin_mul_overflow (n, s, &__xalloc_count); }))
  50. /* Other compilers use integer division; this may be slower but is
  51. more portable. */
  52. #else
  53. # define xalloc_oversized(n, s) __xalloc_oversized (n, s)
  54. #endif
  55. #endif /* !XALLOC_OVERSIZED_H_ */