xalloc-oversized.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* xalloc-oversized.h -- memory allocation size checking
  2. Copyright (C) 1990-2000, 2003-2004, 2006-2021 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 Lesser 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 Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser 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 does not fit into both ptrdiff_t and size_t.
  18. S must be positive and N must be nonnegative.
  19. This expands to a constant expression if N and S are both constants.
  20. By gnulib convention, SIZE_MAX represents overflow in size_t
  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_t;
  27. #else
  28. typedef size_t xalloc_count_t;
  29. #endif
  30. /* Return 1 if an array of N objects, each of size S, cannot exist reliably
  31. because its total size in bytes exceeds MIN (PTRDIFF_MAX, SIZE_MAX).
  32. N must be nonnegative, S must be positive, and either N or S should be
  33. of type ptrdiff_t or size_t or wider. This is a macro, not a function,
  34. so that it works even if an argument exceeds MAX (PTRDIFF_MAX, SIZE_MAX). */
  35. #if 7 <= __GNUC__ && !defined __clang__
  36. # define xalloc_oversized(n, s) \
  37. __builtin_mul_overflow_p (n, s, (xalloc_count_t) 1)
  38. #elif 5 <= __GNUC__ && !defined __ICC && !__STRICT_ANSI__
  39. # define xalloc_oversized(n, s) \
  40. (__builtin_constant_p (n) && __builtin_constant_p (s) \
  41. ? __xalloc_oversized (n, s) \
  42. : ({ xalloc_count_t __xalloc_count; \
  43. __builtin_mul_overflow (n, s, &__xalloc_count); }))
  44. /* Other compilers use integer division; this may be slower but is
  45. more portable. */
  46. #else
  47. # define xalloc_oversized(n, s) __xalloc_oversized (n, s)
  48. #endif
  49. #endif /* !XALLOC_OVERSIZED_H_ */