xref: /linux-6.15/include/linux/overflow.h (revision 08d45ee8)
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 #include <linux/const.h>
8 
9 /*
10  * We need to compute the minimum and maximum values representable in a given
11  * type. These macros may also be useful elsewhere. It would seem more obvious
12  * to do something like:
13  *
14  * #define type_min(T) (T)(is_signed_type(T) ? (T)1 << (8*sizeof(T)-1) : 0)
15  * #define type_max(T) (T)(is_signed_type(T) ? ((T)1 << (8*sizeof(T)-1)) - 1 : ~(T)0)
16  *
17  * Unfortunately, the middle expressions, strictly speaking, have
18  * undefined behaviour, and at least some versions of gcc warn about
19  * the type_max expression (but not if -fsanitize=undefined is in
20  * effect; in that case, the warning is deferred to runtime...).
21  *
22  * The slightly excessive casting in type_min is to make sure the
23  * macros also produce sensible values for the exotic type _Bool. [The
24  * overflow checkers only almost work for _Bool, but that's
25  * a-feature-not-a-bug, since people shouldn't be doing arithmetic on
26  * _Bools. Besides, the gcc builtins don't allow _Bool* as third
27  * argument.]
28  *
29  * Idea stolen from
30  * https://mail-index.netbsd.org/tech-misc/2007/02/05/0000.html -
31  * credit to Christian Biere.
32  */
33 #define __type_half_max(type) ((type)1 << (8*sizeof(type) - 1 - is_signed_type(type)))
34 #define type_max(T) ((T)((__type_half_max(T) - 1) + __type_half_max(T)))
35 #define type_min(T) ((T)((T)-type_max(T)-(T)1))
36 
37 /*
38  * Avoids triggering -Wtype-limits compilation warning,
39  * while using unsigned data types to check a < 0.
40  */
41 #define is_non_negative(a) ((a) > 0 || (a) == 0)
42 #define is_negative(a) (!(is_non_negative(a)))
43 
44 /*
45  * Allows for effectively applying __must_check to a macro so we can have
46  * both the type-agnostic benefits of the macros while also being able to
47  * enforce that the return value is, in fact, checked.
48  */
49 static inline bool __must_check __must_check_overflow(bool overflow)
50 {
51 	return unlikely(overflow);
52 }
53 
54 /**
55  * check_add_overflow() - Calculate addition with overflow checking
56  * @a: first addend
57  * @b: second addend
58  * @d: pointer to store sum
59  *
60  * Returns true on wrap-around, false otherwise.
61  *
62  * *@d holds the results of the attempted addition, regardless of whether
63  * wrap-around occurred.
64  */
65 #define check_add_overflow(a, b, d)	\
66 	__must_check_overflow(__builtin_add_overflow(a, b, d))
67 
68 /**
69  * wrapping_add() - Intentionally perform a wrapping addition
70  * @type: type for result of calculation
71  * @a: first addend
72  * @b: second addend
73  *
74  * Return the potentially wrapped-around addition without
75  * tripping any wrap-around sanitizers that may be enabled.
76  */
77 #define wrapping_add(type, a, b)				\
78 	({							\
79 		type __val;					\
80 		__builtin_add_overflow(a, b, &__val);		\
81 		__val;						\
82 	})
83 
84 /**
85  * wrapping_assign_add() - Intentionally perform a wrapping increment assignment
86  * @var: variable to be incremented
87  * @offset: amount to add
88  *
89  * Increments @var by @offset with wrap-around. Returns the resulting
90  * value of @var. Will not trip any wrap-around sanitizers.
91  *
92  * Returns the new value of @var.
93  */
94 #define wrapping_assign_add(var, offset)				\
95 	({								\
96 		typeof(var) *__ptr = &(var);				\
97 		*__ptr = wrapping_add(typeof(var), *__ptr, offset);	\
98 	})
99 
100 /**
101  * check_sub_overflow() - Calculate subtraction with overflow checking
102  * @a: minuend; value to subtract from
103  * @b: subtrahend; value to subtract from @a
104  * @d: pointer to store difference
105  *
106  * Returns true on wrap-around, false otherwise.
107  *
108  * *@d holds the results of the attempted subtraction, regardless of whether
109  * wrap-around occurred.
110  */
111 #define check_sub_overflow(a, b, d)	\
112 	__must_check_overflow(__builtin_sub_overflow(a, b, d))
113 
114 /**
115  * wrapping_sub() - Intentionally perform a wrapping subtraction
116  * @type: type for result of calculation
117  * @a: minuend; value to subtract from
118  * @b: subtrahend; value to subtract from @a
119  *
120  * Return the potentially wrapped-around subtraction without
121  * tripping any wrap-around sanitizers that may be enabled.
122  */
123 #define wrapping_sub(type, a, b)				\
124 	({							\
125 		type __val;					\
126 		__builtin_sub_overflow(a, b, &__val);		\
127 		__val;						\
128 	})
129 
130 /**
131  * wrapping_assign_sub() - Intentionally perform a wrapping decrement assign
132  * @var: variable to be decremented
133  * @offset: amount to subtract
134  *
135  * Decrements @var by @offset with wrap-around. Returns the resulting
136  * value of @var. Will not trip any wrap-around sanitizers.
137  *
138  * Returns the new value of @var.
139  */
140 #define wrapping_assign_sub(var, offset)				\
141 	({								\
142 		typeof(var) *__ptr = &(var);				\
143 		*__ptr = wrapping_sub(typeof(var), *__ptr, offset);	\
144 	})
145 
146 /**
147  * check_mul_overflow() - Calculate multiplication with overflow checking
148  * @a: first factor
149  * @b: second factor
150  * @d: pointer to store product
151  *
152  * Returns true on wrap-around, false otherwise.
153  *
154  * *@d holds the results of the attempted multiplication, regardless of whether
155  * wrap-around occurred.
156  */
157 #define check_mul_overflow(a, b, d)	\
158 	__must_check_overflow(__builtin_mul_overflow(a, b, d))
159 
160 /**
161  * wrapping_mul() - Intentionally perform a wrapping multiplication
162  * @type: type for result of calculation
163  * @a: first factor
164  * @b: second factor
165  *
166  * Return the potentially wrapped-around multiplication without
167  * tripping any wrap-around sanitizers that may be enabled.
168  */
169 #define wrapping_mul(type, a, b)				\
170 	({							\
171 		type __val;					\
172 		__builtin_mul_overflow(a, b, &__val);		\
173 		__val;						\
174 	})
175 
176 /**
177  * check_shl_overflow() - Calculate a left-shifted value and check overflow
178  * @a: Value to be shifted
179  * @s: How many bits left to shift
180  * @d: Pointer to where to store the result
181  *
182  * Computes *@d = (@a << @s)
183  *
184  * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't
185  * make sense. Example conditions:
186  *
187  * - '@a << @s' causes bits to be lost when stored in *@d.
188  * - '@s' is garbage (e.g. negative) or so large that the result of
189  *   '@a << @s' is guaranteed to be 0.
190  * - '@a' is negative.
191  * - '@a << @s' sets the sign bit, if any, in '*@d'.
192  *
193  * '*@d' will hold the results of the attempted shift, but is not
194  * considered "safe for use" if true is returned.
195  */
196 #define check_shl_overflow(a, s, d) __must_check_overflow(({		\
197 	typeof(a) _a = a;						\
198 	typeof(s) _s = s;						\
199 	typeof(d) _d = d;						\
200 	u64 _a_full = _a;						\
201 	unsigned int _to_shift =					\
202 		is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0;	\
203 	*_d = (_a_full << _to_shift);					\
204 	(_to_shift != _s || is_negative(*_d) || is_negative(_a) ||	\
205 	(*_d >> _to_shift) != _a);					\
206 }))
207 
208 #define __overflows_type_constexpr(x, T) (			\
209 	is_unsigned_type(typeof(x)) ?				\
210 		(x) > type_max(typeof(T)) :			\
211 	is_unsigned_type(typeof(T)) ?				\
212 		(x) < 0 || (x) > type_max(typeof(T)) :		\
213 	(x) < type_min(typeof(T)) || (x) > type_max(typeof(T)))
214 
215 #define __overflows_type(x, T)		({	\
216 	typeof(T) v = 0;			\
217 	check_add_overflow((x), v, &v);		\
218 })
219 
220 /**
221  * overflows_type - helper for checking the overflows between value, variables,
222  *		    or data type
223  *
224  * @n: source constant value or variable to be checked
225  * @T: destination variable or data type proposed to store @x
226  *
227  * Compares the @x expression for whether or not it can safely fit in
228  * the storage of the type in @T. @x and @T can have different types.
229  * If @x is a constant expression, this will also resolve to a constant
230  * expression.
231  *
232  * Returns: true if overflow can occur, false otherwise.
233  */
234 #define overflows_type(n, T)					\
235 	__builtin_choose_expr(__is_constexpr(n),		\
236 			      __overflows_type_constexpr(n, T),	\
237 			      __overflows_type(n, T))
238 
239 /**
240  * castable_to_type - like __same_type(), but also allows for casted literals
241  *
242  * @n: variable or constant value
243  * @T: variable or data type
244  *
245  * Unlike the __same_type() macro, this allows a constant value as the
246  * first argument. If this value would not overflow into an assignment
247  * of the second argument's type, it returns true. Otherwise, this falls
248  * back to __same_type().
249  */
250 #define castable_to_type(n, T)						\
251 	__builtin_choose_expr(__is_constexpr(n),			\
252 			      !__overflows_type_constexpr(n, T),	\
253 			      __same_type(n, T))
254 
255 /**
256  * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
257  * @factor1: first factor
258  * @factor2: second factor
259  *
260  * Returns: calculate @factor1 * @factor2, both promoted to size_t,
261  * with any overflow causing the return value to be SIZE_MAX. The
262  * lvalue must be size_t to avoid implicit type conversion.
263  */
264 static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
265 {
266 	size_t bytes;
267 
268 	if (check_mul_overflow(factor1, factor2, &bytes))
269 		return SIZE_MAX;
270 
271 	return bytes;
272 }
273 
274 /**
275  * size_add() - Calculate size_t addition with saturation at SIZE_MAX
276  * @addend1: first addend
277  * @addend2: second addend
278  *
279  * Returns: calculate @addend1 + @addend2, both promoted to size_t,
280  * with any overflow causing the return value to be SIZE_MAX. The
281  * lvalue must be size_t to avoid implicit type conversion.
282  */
283 static inline size_t __must_check size_add(size_t addend1, size_t addend2)
284 {
285 	size_t bytes;
286 
287 	if (check_add_overflow(addend1, addend2, &bytes))
288 		return SIZE_MAX;
289 
290 	return bytes;
291 }
292 
293 /**
294  * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
295  * @minuend: value to subtract from
296  * @subtrahend: value to subtract from @minuend
297  *
298  * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
299  * with any overflow causing the return value to be SIZE_MAX. For
300  * composition with the size_add() and size_mul() helpers, neither
301  * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
302  * The lvalue must be size_t to avoid implicit type conversion.
303  */
304 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
305 {
306 	size_t bytes;
307 
308 	if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
309 	    check_sub_overflow(minuend, subtrahend, &bytes))
310 		return SIZE_MAX;
311 
312 	return bytes;
313 }
314 
315 /**
316  * array_size() - Calculate size of 2-dimensional array.
317  * @a: dimension one
318  * @b: dimension two
319  *
320  * Calculates size of 2-dimensional array: @a * @b.
321  *
322  * Returns: number of bytes needed to represent the array or SIZE_MAX on
323  * overflow.
324  */
325 #define array_size(a, b)	size_mul(a, b)
326 
327 /**
328  * array3_size() - Calculate size of 3-dimensional array.
329  * @a: dimension one
330  * @b: dimension two
331  * @c: dimension three
332  *
333  * Calculates size of 3-dimensional array: @a * @b * @c.
334  *
335  * Returns: number of bytes needed to represent the array or SIZE_MAX on
336  * overflow.
337  */
338 #define array3_size(a, b, c)	size_mul(size_mul(a, b), c)
339 
340 /**
341  * flex_array_size() - Calculate size of a flexible array member
342  *                     within an enclosing structure.
343  * @p: Pointer to the structure.
344  * @member: Name of the flexible array member.
345  * @count: Number of elements in the array.
346  *
347  * Calculates size of a flexible array of @count number of @member
348  * elements, at the end of structure @p.
349  *
350  * Return: number of bytes needed or SIZE_MAX on overflow.
351  */
352 #define flex_array_size(p, member, count)				\
353 	__builtin_choose_expr(__is_constexpr(count),			\
354 		(count) * sizeof(*(p)->member) + __must_be_array((p)->member),	\
355 		size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
356 
357 /**
358  * struct_size() - Calculate size of structure with trailing flexible array.
359  * @p: Pointer to the structure.
360  * @member: Name of the array member.
361  * @count: Number of elements in the array.
362  *
363  * Calculates size of memory needed for structure of @p followed by an
364  * array of @count number of @member elements.
365  *
366  * Return: number of bytes needed or SIZE_MAX on overflow.
367  */
368 #define struct_size(p, member, count)					\
369 	__builtin_choose_expr(__is_constexpr(count),			\
370 		sizeof(*(p)) + flex_array_size(p, member, count),	\
371 		size_add(sizeof(*(p)), flex_array_size(p, member, count)))
372 
373 /**
374  * struct_size_t() - Calculate size of structure with trailing flexible array
375  * @type: structure type name.
376  * @member: Name of the array member.
377  * @count: Number of elements in the array.
378  *
379  * Calculates size of memory needed for structure @type followed by an
380  * array of @count number of @member elements. Prefer using struct_size()
381  * when possible instead, to keep calculations associated with a specific
382  * instance variable of type @type.
383  *
384  * Return: number of bytes needed or SIZE_MAX on overflow.
385  */
386 #define struct_size_t(type, member, count)					\
387 	struct_size((type *)NULL, member, count)
388 
389 /**
390  * _DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
391  * Enables caller macro to pass (different) initializer.
392  *
393  * @type: structure type name, including "struct" keyword.
394  * @name: Name for a variable to define.
395  * @member: Name of the array member.
396  * @count: Number of elements in the array; must be compile-time const.
397  * @initializer: initializer expression (could be empty for no init).
398  */
399 #define _DEFINE_FLEX(type, name, member, count, initializer)			\
400 	_Static_assert(__builtin_constant_p(count),				\
401 		       "onstack flex array members require compile-time const count"); \
402 	union {									\
403 		u8 bytes[struct_size_t(type, member, count)];			\
404 		type obj;							\
405 	} name##_u initializer;							\
406 	type *name = (type *)&name##_u
407 
408 /**
409  * DEFINE_FLEX() - Define an on-stack instance of structure with a trailing
410  * flexible array member.
411  *
412  * @type: structure type name, including "struct" keyword.
413  * @name: Name for a variable to define.
414  * @member: Name of the array member.
415  * @count: Number of elements in the array; must be compile-time const.
416  *
417  * Define a zeroed, on-stack, instance of @type structure with a trailing
418  * flexible array member.
419  * Use __struct_size(@name) to get compile-time size of it afterwards.
420  */
421 #define DEFINE_FLEX(type, name, member, count)			\
422 	_DEFINE_FLEX(type, name, member, count, = {})
423 
424 #endif /* __LINUX_OVERFLOW_H */
425