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  * Avoids triggering -Wtype-limits compilation warning,
42  * while using unsigned data types to check a < 0.
43  */
44 #define is_non_negative(a) ((a) > 0 || (a) == 0)
45 #define is_negative(a) (!(is_non_negative(a)))
46 
47 #ifdef COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW
48 /*
49  * For simplicity and code hygiene, the fallback code below insists on
50  * a, b and *d having the same type (similar to the min() and max()
51  * macros), whereas gcc's type-generic overflow checkers accept
52  * different types. Hence we don't just make check_add_overflow an
53  * alias for __builtin_add_overflow, but add type checks similar to
54  * below.
55  */
56 #define check_add_overflow(a, b, d) ({		\
57 	typeof(a) __a = (a);			\
58 	typeof(b) __b = (b);			\
59 	typeof(d) __d = (d);			\
60 	(void) (&__a == &__b);			\
61 	(void) (&__a == __d);			\
62 	__builtin_add_overflow(__a, __b, __d);	\
63 })
64 
65 #define check_sub_overflow(a, b, d) ({		\
66 	typeof(a) __a = (a);			\
67 	typeof(b) __b = (b);			\
68 	typeof(d) __d = (d);			\
69 	(void) (&__a == &__b);			\
70 	(void) (&__a == __d);			\
71 	__builtin_sub_overflow(__a, __b, __d);	\
72 })
73 
74 #define check_mul_overflow(a, b, d) ({		\
75 	typeof(a) __a = (a);			\
76 	typeof(b) __b = (b);			\
77 	typeof(d) __d = (d);			\
78 	(void) (&__a == &__b);			\
79 	(void) (&__a == __d);			\
80 	__builtin_mul_overflow(__a, __b, __d);	\
81 })
82 
83 #else
84 
85 
86 /* Checking for unsigned overflow is relatively easy without causing UB. */
87 #define __unsigned_add_overflow(a, b, d) ({	\
88 	typeof(a) __a = (a);			\
89 	typeof(b) __b = (b);			\
90 	typeof(d) __d = (d);			\
91 	(void) (&__a == &__b);			\
92 	(void) (&__a == __d);			\
93 	*__d = __a + __b;			\
94 	*__d < __a;				\
95 })
96 #define __unsigned_sub_overflow(a, b, d) ({	\
97 	typeof(a) __a = (a);			\
98 	typeof(b) __b = (b);			\
99 	typeof(d) __d = (d);			\
100 	(void) (&__a == &__b);			\
101 	(void) (&__a == __d);			\
102 	*__d = __a - __b;			\
103 	__a < __b;				\
104 })
105 /*
106  * If one of a or b is a compile-time constant, this avoids a division.
107  */
108 #define __unsigned_mul_overflow(a, b, d) ({		\
109 	typeof(a) __a = (a);				\
110 	typeof(b) __b = (b);				\
111 	typeof(d) __d = (d);				\
112 	(void) (&__a == &__b);				\
113 	(void) (&__a == __d);				\
114 	*__d = __a * __b;				\
115 	__builtin_constant_p(__b) ?			\
116 	  __b > 0 && __a > type_max(typeof(__a)) / __b : \
117 	  __a > 0 && __b > type_max(typeof(__b)) / __a;	 \
118 })
119 
120 /*
121  * For signed types, detecting overflow is much harder, especially if
122  * we want to avoid UB. But the interface of these macros is such that
123  * we must provide a result in *d, and in fact we must produce the
124  * result promised by gcc's builtins, which is simply the possibly
125  * wrapped-around value. Fortunately, we can just formally do the
126  * operations in the widest relevant unsigned type (u64) and then
127  * truncate the result - gcc is smart enough to generate the same code
128  * with and without the (u64) casts.
129  */
130 
131 /*
132  * Adding two signed integers can overflow only if they have the same
133  * sign, and overflow has happened iff the result has the opposite
134  * sign.
135  */
136 #define __signed_add_overflow(a, b, d) ({	\
137 	typeof(a) __a = (a);			\
138 	typeof(b) __b = (b);			\
139 	typeof(d) __d = (d);			\
140 	(void) (&__a == &__b);			\
141 	(void) (&__a == __d);			\
142 	*__d = (u64)__a + (u64)__b;		\
143 	(((~(__a ^ __b)) & (*__d ^ __a))	\
144 		& type_min(typeof(__a))) != 0;	\
145 })
146 
147 /*
148  * Subtraction is similar, except that overflow can now happen only
149  * when the signs are opposite. In this case, overflow has happened if
150  * the result has the opposite sign of a.
151  */
152 #define __signed_sub_overflow(a, b, d) ({	\
153 	typeof(a) __a = (a);			\
154 	typeof(b) __b = (b);			\
155 	typeof(d) __d = (d);			\
156 	(void) (&__a == &__b);			\
157 	(void) (&__a == __d);			\
158 	*__d = (u64)__a - (u64)__b;		\
159 	((((__a ^ __b)) & (*__d ^ __a))		\
160 		& type_min(typeof(__a))) != 0;	\
161 })
162 
163 /*
164  * Signed multiplication is rather hard. gcc always follows C99, so
165  * division is truncated towards 0. This means that we can write the
166  * overflow check like this:
167  *
168  * (a > 0 && (b > MAX/a || b < MIN/a)) ||
169  * (a < -1 && (b > MIN/a || b < MAX/a) ||
170  * (a == -1 && b == MIN)
171  *
172  * The redundant casts of -1 are to silence an annoying -Wtype-limits
173  * (included in -Wextra) warning: When the type is u8 or u16, the
174  * __b_c_e in check_mul_overflow obviously selects
175  * __unsigned_mul_overflow, but unfortunately gcc still parses this
176  * code and warns about the limited range of __b.
177  */
178 
179 #define __signed_mul_overflow(a, b, d) ({				\
180 	typeof(a) __a = (a);						\
181 	typeof(b) __b = (b);						\
182 	typeof(d) __d = (d);						\
183 	typeof(a) __tmax = type_max(typeof(a));				\
184 	typeof(a) __tmin = type_min(typeof(a));				\
185 	(void) (&__a == &__b);						\
186 	(void) (&__a == __d);						\
187 	*__d = (u64)__a * (u64)__b;					\
188 	(__b > 0   && (__a > __tmax/__b || __a < __tmin/__b)) ||	\
189 	(__b < (typeof(__b))-1  && (__a > __tmin/__b || __a < __tmax/__b)) || \
190 	(__b == (typeof(__b))-1 && __a == __tmin);			\
191 })
192 
193 
194 #define check_add_overflow(a, b, d)					\
195 	__builtin_choose_expr(is_signed_type(typeof(a)),		\
196 			__signed_add_overflow(a, b, d),			\
197 			__unsigned_add_overflow(a, b, d))
198 
199 #define check_sub_overflow(a, b, d)					\
200 	__builtin_choose_expr(is_signed_type(typeof(a)),		\
201 			__signed_sub_overflow(a, b, d),			\
202 			__unsigned_sub_overflow(a, b, d))
203 
204 #define check_mul_overflow(a, b, d)					\
205 	__builtin_choose_expr(is_signed_type(typeof(a)),		\
206 			__signed_mul_overflow(a, b, d),			\
207 			__unsigned_mul_overflow(a, b, d))
208 
209 
210 #endif /* COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW */
211 
212 /** check_shl_overflow() - Calculate a left-shifted value and check overflow
213  *
214  * @a: Value to be shifted
215  * @s: How many bits left to shift
216  * @d: Pointer to where to store the result
217  *
218  * Computes *@d = (@a << @s)
219  *
220  * Returns true if '*d' cannot hold the result or when 'a << s' doesn't
221  * make sense. Example conditions:
222  * - 'a << s' causes bits to be lost when stored in *d.
223  * - 's' is garbage (e.g. negative) or so large that the result of
224  *   'a << s' is guaranteed to be 0.
225  * - 'a' is negative.
226  * - 'a << s' sets the sign bit, if any, in '*d'.
227  *
228  * '*d' will hold the results of the attempted shift, but is not
229  * considered "safe for use" if false is returned.
230  */
231 #define check_shl_overflow(a, s, d) ({					\
232 	typeof(a) _a = a;						\
233 	typeof(s) _s = s;						\
234 	typeof(d) _d = d;						\
235 	u64 _a_full = _a;						\
236 	unsigned int _to_shift =					\
237 		is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0;	\
238 	*_d = (_a_full << _to_shift);					\
239 	(_to_shift != _s || is_negative(*_d) || is_negative(_a) ||	\
240 	(*_d >> _to_shift) != _a);					\
241 })
242 
243 /**
244  * array_size() - Calculate size of 2-dimensional array.
245  *
246  * @a: dimension one
247  * @b: dimension two
248  *
249  * Calculates size of 2-dimensional array: @a * @b.
250  *
251  * Returns: number of bytes needed to represent the array or SIZE_MAX on
252  * overflow.
253  */
array_size(size_t a,size_t b)254 static inline __must_check size_t array_size(size_t a, size_t b)
255 {
256 	size_t bytes;
257 
258 	if (check_mul_overflow(a, b, &bytes))
259 		return SIZE_MAX;
260 
261 	return bytes;
262 }
263 
264 /**
265  * array3_size() - Calculate size of 3-dimensional array.
266  *
267  * @a: dimension one
268  * @b: dimension two
269  * @c: dimension three
270  *
271  * Calculates size of 3-dimensional array: @a * @b * @c.
272  *
273  * Returns: number of bytes needed to represent the array or SIZE_MAX on
274  * overflow.
275  */
array3_size(size_t a,size_t b,size_t c)276 static inline __must_check size_t array3_size(size_t a, size_t b, size_t c)
277 {
278 	size_t bytes;
279 
280 	if (check_mul_overflow(a, b, &bytes))
281 		return SIZE_MAX;
282 	if (check_mul_overflow(bytes, c, &bytes))
283 		return SIZE_MAX;
284 
285 	return bytes;
286 }
287 
__ab_c_size(size_t n,size_t size,size_t c)288 static inline __must_check size_t __ab_c_size(size_t n, size_t size, size_t c)
289 {
290 	size_t bytes;
291 
292 	if (check_mul_overflow(n, size, &bytes))
293 		return SIZE_MAX;
294 	if (check_add_overflow(bytes, c, &bytes))
295 		return SIZE_MAX;
296 
297 	return bytes;
298 }
299 
300 /**
301  * struct_size() - Calculate size of structure with trailing array.
302  * @p: Pointer to the structure.
303  * @member: Name of the array member.
304  * @n: Number of elements in the array.
305  *
306  * Calculates size of memory needed for structure @p followed by an
307  * array of @n @member elements.
308  *
309  * Return: number of bytes needed or SIZE_MAX on overflow.
310  */
311 #define struct_size(p, member, n)					\
312 	__ab_c_size(n,							\
313 		    sizeof(*(p)->member) + __must_be_array((p)->member),\
314 		    sizeof(*(p)))
315 
316 #endif /* __LINUX_OVERFLOW_H */
317