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