xalloc-oversized.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* xalloc-oversized.h -- memory allocation size checking
  2. Copyright (C) 1990-2000, 2003-2004, 2006-2020 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 <https://www.gnu.org/licenses/>. */
  13. #ifndef XALLOC_OVERSIZED_H_
  14. #define XALLOC_OVERSIZED_H_
  15. #include <stddef.h>
  16. #include <stdint.h>
  17. /* True if N * S would overflow in a size_t calculation,
  18. or would generate a value larger than PTRDIFF_MAX.
  19. This expands to a constant expression if N and S are both constants.
  20. By gnulib convention, SIZE_MAX represents overflow in size
  21. calculations, so the conservative size_t-based dividend to use here
  22. is SIZE_MAX - 1. */
  23. #define __xalloc_oversized(n, s) \
  24. ((size_t) (PTRDIFF_MAX < SIZE_MAX ? PTRDIFF_MAX : SIZE_MAX - 1) / (s) < (n))
  25. #if PTRDIFF_MAX < SIZE_MAX
  26. typedef ptrdiff_t __xalloc_count_type;
  27. #else
  28. typedef size_t __xalloc_count_type;
  29. #endif
  30. /* Return 1 if an array of N objects, each of size S, cannot exist
  31. reliably due to size or ptrdiff_t arithmetic overflow. S must be
  32. positive and N must be nonnegative. This is a macro, not a
  33. function, so that it works correctly even when SIZE_MAX < N. */
  34. #if 7 <= __GNUC__ && !defined __clang__
  35. # define xalloc_oversized(n, s) \
  36. __builtin_mul_overflow_p (n, s, (__xalloc_count_type) 1)
  37. #elif 5 <= __GNUC__ && !defined __ICC && !__STRICT_ANSI__
  38. # define xalloc_oversized(n, s) \
  39. (__builtin_constant_p (n) && __builtin_constant_p (s) \
  40. ? __xalloc_oversized (n, s) \
  41. : ({ __xalloc_count_type __xalloc_count; \
  42. __builtin_mul_overflow (n, s, &__xalloc_count); }))
  43. /* Other compilers use integer division; this may be slower but is
  44. more portable. */
  45. #else
  46. # define xalloc_oversized(n, s) __xalloc_oversized (n, s)
  47. #endif
  48. #endif /* !XALLOC_OVERSIZED_H_ */