GNU Linux-libre 4.14.262-gnu1
[releases.git] / include / linux / overflow.h
1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 #ifndef __LINUX_OVERFLOW_H
3 #define __LINUX_OVERFLOW_H
4
5 #include <linux/compiler.h>
6 #include <linux/limits.h>
7
8 /*
9  * In the fallback code below, we need to compute the minimum and
10  * maximum values representable in a given type. These macros may also
11  * be useful elsewhere, so we provide them outside the
12  * COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW block.
13  *
14  * It would seem more obvious to do something like
15  *
16  * #define type_min(T) (T)(is_signed_type(T) ? (T)1 << (8*sizeof(T)-1) : 0)
17  * #define type_max(T) (T)(is_signed_type(T) ? ((T)1 << (8*sizeof(T)-1)) - 1 : ~(T)0)
18  *
19  * Unfortunately, the middle expressions, strictly speaking, have
20  * undefined behaviour, and at least some versions of gcc warn about
21  * the type_max expression (but not if -fsanitize=undefined is in
22  * effect; in that case, the warning is deferred to runtime...).
23  *
24  * The slightly excessive casting in type_min is to make sure the
25  * macros also produce sensible values for the exotic type _Bool. [The
26  * overflow checkers only almost work for _Bool, but that's
27  * a-feature-not-a-bug, since people shouldn't be doing arithmetic on
28  * _Bools. Besides, the gcc builtins don't allow _Bool* as third
29  * argument.]
30  *
31  * Idea stolen from
32  * https://mail-index.netbsd.org/tech-misc/2007/02/05/0000.html -
33  * credit to Christian Biere.
34  */
35 #define is_signed_type(type)       (((type)(-1)) < (type)1)
36 #define __type_half_max(type) ((type)1 << (8*sizeof(type) - 1 - is_signed_type(type)))
37 #define type_max(T) ((T)((__type_half_max(T) - 1) + __type_half_max(T)))
38 #define type_min(T) ((T)((T)-type_max(T)-(T)1))
39
40
41 #ifdef COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW
42 /*
43  * For simplicity and code hygiene, the fallback code below insists on
44  * a, b and *d having the same type (similar to the min() and max()
45  * macros), whereas gcc's type-generic overflow checkers accept
46  * different types. Hence we don't just make check_add_overflow an
47  * alias for __builtin_add_overflow, but add type checks similar to
48  * below.
49  */
50 #define check_add_overflow(a, b, d) ({          \
51         typeof(a) __a = (a);                    \
52         typeof(b) __b = (b);                    \
53         typeof(d) __d = (d);                    \
54         (void) (&__a == &__b);                  \
55         (void) (&__a == __d);                   \
56         __builtin_add_overflow(__a, __b, __d);  \
57 })
58
59 #define check_sub_overflow(a, b, d) ({          \
60         typeof(a) __a = (a);                    \
61         typeof(b) __b = (b);                    \
62         typeof(d) __d = (d);                    \
63         (void) (&__a == &__b);                  \
64         (void) (&__a == __d);                   \
65         __builtin_sub_overflow(__a, __b, __d);  \
66 })
67
68 #define check_mul_overflow(a, b, d) ({          \
69         typeof(a) __a = (a);                    \
70         typeof(b) __b = (b);                    \
71         typeof(d) __d = (d);                    \
72         (void) (&__a == &__b);                  \
73         (void) (&__a == __d);                   \
74         __builtin_mul_overflow(__a, __b, __d);  \
75 })
76
77 #else
78
79
80 /* Checking for unsigned overflow is relatively easy without causing UB. */
81 #define __unsigned_add_overflow(a, b, d) ({     \
82         typeof(a) __a = (a);                    \
83         typeof(b) __b = (b);                    \
84         typeof(d) __d = (d);                    \
85         (void) (&__a == &__b);                  \
86         (void) (&__a == __d);                   \
87         *__d = __a + __b;                       \
88         *__d < __a;                             \
89 })
90 #define __unsigned_sub_overflow(a, b, d) ({     \
91         typeof(a) __a = (a);                    \
92         typeof(b) __b = (b);                    \
93         typeof(d) __d = (d);                    \
94         (void) (&__a == &__b);                  \
95         (void) (&__a == __d);                   \
96         *__d = __a - __b;                       \
97         __a < __b;                              \
98 })
99 /*
100  * If one of a or b is a compile-time constant, this avoids a division.
101  */
102 #define __unsigned_mul_overflow(a, b, d) ({             \
103         typeof(a) __a = (a);                            \
104         typeof(b) __b = (b);                            \
105         typeof(d) __d = (d);                            \
106         (void) (&__a == &__b);                          \
107         (void) (&__a == __d);                           \
108         *__d = __a * __b;                               \
109         __builtin_constant_p(__b) ?                     \
110           __b > 0 && __a > type_max(typeof(__a)) / __b : \
111           __a > 0 && __b > type_max(typeof(__b)) / __a;  \
112 })
113
114 /*
115  * For signed types, detecting overflow is much harder, especially if
116  * we want to avoid UB. But the interface of these macros is such that
117  * we must provide a result in *d, and in fact we must produce the
118  * result promised by gcc's builtins, which is simply the possibly
119  * wrapped-around value. Fortunately, we can just formally do the
120  * operations in the widest relevant unsigned type (u64) and then
121  * truncate the result - gcc is smart enough to generate the same code
122  * with and without the (u64) casts.
123  */
124
125 /*
126  * Adding two signed integers can overflow only if they have the same
127  * sign, and overflow has happened iff the result has the opposite
128  * sign.
129  */
130 #define __signed_add_overflow(a, b, d) ({       \
131         typeof(a) __a = (a);                    \
132         typeof(b) __b = (b);                    \
133         typeof(d) __d = (d);                    \
134         (void) (&__a == &__b);                  \
135         (void) (&__a == __d);                   \
136         *__d = (u64)__a + (u64)__b;             \
137         (((~(__a ^ __b)) & (*__d ^ __a))        \
138                 & type_min(typeof(__a))) != 0;  \
139 })
140
141 /*
142  * Subtraction is similar, except that overflow can now happen only
143  * when the signs are opposite. In this case, overflow has happened if
144  * the result has the opposite sign of a.
145  */
146 #define __signed_sub_overflow(a, b, d) ({       \
147         typeof(a) __a = (a);                    \
148         typeof(b) __b = (b);                    \
149         typeof(d) __d = (d);                    \
150         (void) (&__a == &__b);                  \
151         (void) (&__a == __d);                   \
152         *__d = (u64)__a - (u64)__b;             \
153         ((((__a ^ __b)) & (*__d ^ __a))         \
154                 & type_min(typeof(__a))) != 0;  \
155 })
156
157 /*
158  * Signed multiplication is rather hard. gcc always follows C99, so
159  * division is truncated towards 0. This means that we can write the
160  * overflow check like this:
161  *
162  * (a > 0 && (b > MAX/a || b < MIN/a)) ||
163  * (a < -1 && (b > MIN/a || b < MAX/a) ||
164  * (a == -1 && b == MIN)
165  *
166  * The redundant casts of -1 are to silence an annoying -Wtype-limits
167  * (included in -Wextra) warning: When the type is u8 or u16, the
168  * __b_c_e in check_mul_overflow obviously selects
169  * __unsigned_mul_overflow, but unfortunately gcc still parses this
170  * code and warns about the limited range of __b.
171  */
172
173 #define __signed_mul_overflow(a, b, d) ({                               \
174         typeof(a) __a = (a);                                            \
175         typeof(b) __b = (b);                                            \
176         typeof(d) __d = (d);                                            \
177         typeof(a) __tmax = type_max(typeof(a));                         \
178         typeof(a) __tmin = type_min(typeof(a));                         \
179         (void) (&__a == &__b);                                          \
180         (void) (&__a == __d);                                           \
181         *__d = (u64)__a * (u64)__b;                                     \
182         (__b > 0   && (__a > __tmax/__b || __a < __tmin/__b)) ||        \
183         (__b < (typeof(__b))-1  && (__a > __tmin/__b || __a < __tmax/__b)) || \
184         (__b == (typeof(__b))-1 && __a == __tmin);                      \
185 })
186
187
188 #define check_add_overflow(a, b, d)                                     \
189         __builtin_choose_expr(is_signed_type(typeof(a)),                \
190                         __signed_add_overflow(a, b, d),                 \
191                         __unsigned_add_overflow(a, b, d))
192
193 #define check_sub_overflow(a, b, d)                                     \
194         __builtin_choose_expr(is_signed_type(typeof(a)),                \
195                         __signed_sub_overflow(a, b, d),                 \
196                         __unsigned_sub_overflow(a, b, d))
197
198 #define check_mul_overflow(a, b, d)                                     \
199         __builtin_choose_expr(is_signed_type(typeof(a)),                \
200                         __signed_mul_overflow(a, b, d),                 \
201                         __unsigned_mul_overflow(a, b, d))
202
203
204 #endif /* COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW */
205
206 /** check_shl_overflow() - Calculate a left-shifted value and check overflow
207  *
208  * @a: Value to be shifted
209  * @s: How many bits left to shift
210  * @d: Pointer to where to store the result
211  *
212  * Computes *@d = (@a << @s)
213  *
214  * Returns true if '*d' cannot hold the result or when 'a << s' doesn't
215  * make sense. Example conditions:
216  * - 'a << s' causes bits to be lost when stored in *d.
217  * - 's' is garbage (e.g. negative) or so large that the result of
218  *   'a << s' is guaranteed to be 0.
219  * - 'a' is negative.
220  * - 'a << s' sets the sign bit, if any, in '*d'.
221  *
222  * '*d' will hold the results of the attempted shift, but is not
223  * considered "safe for use" if false is returned.
224  */
225 #define check_shl_overflow(a, s, d) ({                                  \
226         typeof(a) _a = a;                                               \
227         typeof(s) _s = s;                                               \
228         typeof(d) _d = d;                                               \
229         u64 _a_full = _a;                                               \
230         unsigned int _to_shift =                                        \
231                 _s >= 0 && _s < 8 * sizeof(*d) ? _s : 0;                \
232         *_d = (_a_full << _to_shift);                                   \
233         (_to_shift != _s || *_d < 0 || _a < 0 ||                        \
234                 (*_d >> _to_shift) != _a);                              \
235 })
236
237 /**
238  * array_size() - Calculate size of 2-dimensional array.
239  *
240  * @a: dimension one
241  * @b: dimension two
242  *
243  * Calculates size of 2-dimensional array: @a * @b.
244  *
245  * Returns: number of bytes needed to represent the array or SIZE_MAX on
246  * overflow.
247  */
248 static inline __must_check size_t array_size(size_t a, size_t b)
249 {
250         size_t bytes;
251
252         if (check_mul_overflow(a, b, &bytes))
253                 return SIZE_MAX;
254
255         return bytes;
256 }
257
258 /**
259  * array3_size() - Calculate size of 3-dimensional array.
260  *
261  * @a: dimension one
262  * @b: dimension two
263  * @c: dimension three
264  *
265  * Calculates size of 3-dimensional array: @a * @b * @c.
266  *
267  * Returns: number of bytes needed to represent the array or SIZE_MAX on
268  * overflow.
269  */
270 static inline __must_check size_t array3_size(size_t a, size_t b, size_t c)
271 {
272         size_t bytes;
273
274         if (check_mul_overflow(a, b, &bytes))
275                 return SIZE_MAX;
276         if (check_mul_overflow(bytes, c, &bytes))
277                 return SIZE_MAX;
278
279         return bytes;
280 }
281
282 static inline __must_check size_t __ab_c_size(size_t n, size_t size, size_t c)
283 {
284         size_t bytes;
285
286         if (check_mul_overflow(n, size, &bytes))
287                 return SIZE_MAX;
288         if (check_add_overflow(bytes, c, &bytes))
289                 return SIZE_MAX;
290
291         return bytes;
292 }
293
294 /**
295  * struct_size() - Calculate size of structure with trailing array.
296  * @p: Pointer to the structure.
297  * @member: Name of the array member.
298  * @n: Number of elements in the array.
299  *
300  * Calculates size of memory needed for structure @p followed by an
301  * array of @n @member elements.
302  *
303  * Return: number of bytes needed or SIZE_MAX on overflow.
304  */
305 #define struct_size(p, member, n)                                       \
306         __ab_c_size(n,                                                  \
307                     sizeof(*(p)->member) + __must_be_array((p)->member),\
308                     sizeof(*(p)))
309
310 #endif /* __LINUX_OVERFLOW_H */