(eglot--track-changes-signal): Improve last fix (bug#70541)
[emacs.git] / lib / xalloc-oversized.h
blob7f30f83e7693b65e4a611abde3d3df818e7f5d47
1 /* xalloc-oversized.h -- memory allocation size checking
3 Copyright (C) 1990-2000, 2003-2004, 2006-2024 Free Software Foundation, Inc.
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.
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.
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/>. */
18 #ifndef XALLOC_OVERSIZED_H_
19 #define XALLOC_OVERSIZED_H_
21 #include <stddef.h>
22 #include <stdint.h>
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 && (PTRDIFF_MAX < SIZE_MAX ? PTRDIFF_MAX : SIZE_MAX - 1) / (s) < (n))
34 /* Return 1 if and only if an array of N objects, each of size S,
35 cannot exist reliably because its total size in bytes would exceed
36 MIN (PTRDIFF_MAX, SIZE_MAX - 1).
38 N and S should be nonnegative and free of side effects.
40 Warning: (xalloc_oversized (N, S) ? NULL : malloc (N * S)) can
41 misbehave if N and S are both narrower than ptrdiff_t and size_t,
42 and can be rewritten as (xalloc_oversized (N, S) ? NULL
43 : malloc (N * (size_t) S)).
45 This is a macro, not a function, so that it works even if an
46 argument exceeds MAX (PTRDIFF_MAX, SIZE_MAX). */
47 #if 7 <= __GNUC__ && !defined __clang__ && PTRDIFF_MAX < SIZE_MAX
48 # define xalloc_oversized(n, s) \
49 __builtin_mul_overflow_p (n, s, (ptrdiff_t) 1)
50 #elif 5 <= __GNUC__ && !defined __ICC && PTRDIFF_MAX < SIZE_MAX
51 # define xalloc_oversized(n, s) \
52 (__builtin_constant_p (n) && __builtin_constant_p (s) \
53 ? __xalloc_oversized (n, s) \
54 : __extension__ \
55 ({ ptrdiff_t __xalloc_count; \
56 __builtin_mul_overflow (n, s, &__xalloc_count); }))
58 /* Other compilers use integer division; this may be slower but is
59 more portable. */
60 #else
61 # define xalloc_oversized(n, s) __xalloc_oversized (n, s)
62 #endif
64 #endif /* !XALLOC_OVERSIZED_H_ */