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