xref: /linux-6.15/include/linux/overflow.h (revision d70de805)
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  * check_sub_overflow() - Calculate subtraction with overflow checking
86  * @a: minuend; value to subtract from
87  * @b: subtrahend; value to subtract from @a
88  * @d: pointer to store difference
89  *
90  * Returns true on wrap-around, false otherwise.
91  *
92  * *@d holds the results of the attempted subtraction, regardless of whether
93  * wrap-around occurred.
94  */
95 #define check_sub_overflow(a, b, d)	\
96 	__must_check_overflow(__builtin_sub_overflow(a, b, d))
97 
98 /**
99  * wrapping_sub() - Intentionally perform a wrapping subtraction
100  * @type: type for result of calculation
101  * @a: minuend; value to subtract from
102  * @b: subtrahend; value to subtract from @a
103  *
104  * Return the potentially wrapped-around subtraction without
105  * tripping any wrap-around sanitizers that may be enabled.
106  */
107 #define wrapping_sub(type, a, b)				\
108 	({							\
109 		type __val;					\
110 		__builtin_sub_overflow(a, b, &__val);		\
111 		__val;						\
112 	})
113 
114 /**
115  * check_mul_overflow() - Calculate multiplication with overflow checking
116  * @a: first factor
117  * @b: second factor
118  * @d: pointer to store product
119  *
120  * Returns true on wrap-around, false otherwise.
121  *
122  * *@d holds the results of the attempted multiplication, regardless of whether
123  * wrap-around occurred.
124  */
125 #define check_mul_overflow(a, b, d)	\
126 	__must_check_overflow(__builtin_mul_overflow(a, b, d))
127 
128 /**
129  * wrapping_mul() - Intentionally perform a wrapping multiplication
130  * @type: type for result of calculation
131  * @a: first factor
132  * @b: second factor
133  *
134  * Return the potentially wrapped-around multiplication without
135  * tripping any wrap-around sanitizers that may be enabled.
136  */
137 #define wrapping_mul(type, a, b)				\
138 	({							\
139 		type __val;					\
140 		__builtin_mul_overflow(a, b, &__val);		\
141 		__val;						\
142 	})
143 
144 /**
145  * check_shl_overflow() - Calculate a left-shifted value and check overflow
146  * @a: Value to be shifted
147  * @s: How many bits left to shift
148  * @d: Pointer to where to store the result
149  *
150  * Computes *@d = (@a << @s)
151  *
152  * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't
153  * make sense. Example conditions:
154  *
155  * - '@a << @s' causes bits to be lost when stored in *@d.
156  * - '@s' is garbage (e.g. negative) or so large that the result of
157  *   '@a << @s' is guaranteed to be 0.
158  * - '@a' is negative.
159  * - '@a << @s' sets the sign bit, if any, in '*@d'.
160  *
161  * '*@d' will hold the results of the attempted shift, but is not
162  * considered "safe for use" if true is returned.
163  */
164 #define check_shl_overflow(a, s, d) __must_check_overflow(({		\
165 	typeof(a) _a = a;						\
166 	typeof(s) _s = s;						\
167 	typeof(d) _d = d;						\
168 	u64 _a_full = _a;						\
169 	unsigned int _to_shift =					\
170 		is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0;	\
171 	*_d = (_a_full << _to_shift);					\
172 	(_to_shift != _s || is_negative(*_d) || is_negative(_a) ||	\
173 	(*_d >> _to_shift) != _a);					\
174 }))
175 
176 #define __overflows_type_constexpr(x, T) (			\
177 	is_unsigned_type(typeof(x)) ?				\
178 		(x) > type_max(typeof(T)) :			\
179 	is_unsigned_type(typeof(T)) ?				\
180 		(x) < 0 || (x) > type_max(typeof(T)) :		\
181 	(x) < type_min(typeof(T)) || (x) > type_max(typeof(T)))
182 
183 #define __overflows_type(x, T)		({	\
184 	typeof(T) v = 0;			\
185 	check_add_overflow((x), v, &v);		\
186 })
187 
188 /**
189  * overflows_type - helper for checking the overflows between value, variables,
190  *		    or data type
191  *
192  * @n: source constant value or variable to be checked
193  * @T: destination variable or data type proposed to store @x
194  *
195  * Compares the @x expression for whether or not it can safely fit in
196  * the storage of the type in @T. @x and @T can have different types.
197  * If @x is a constant expression, this will also resolve to a constant
198  * expression.
199  *
200  * Returns: true if overflow can occur, false otherwise.
201  */
202 #define overflows_type(n, T)					\
203 	__builtin_choose_expr(__is_constexpr(n),		\
204 			      __overflows_type_constexpr(n, T),	\
205 			      __overflows_type(n, T))
206 
207 /**
208  * castable_to_type - like __same_type(), but also allows for casted literals
209  *
210  * @n: variable or constant value
211  * @T: variable or data type
212  *
213  * Unlike the __same_type() macro, this allows a constant value as the
214  * first argument. If this value would not overflow into an assignment
215  * of the second argument's type, it returns true. Otherwise, this falls
216  * back to __same_type().
217  */
218 #define castable_to_type(n, T)						\
219 	__builtin_choose_expr(__is_constexpr(n),			\
220 			      !__overflows_type_constexpr(n, T),	\
221 			      __same_type(n, T))
222 
223 /**
224  * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
225  * @factor1: first factor
226  * @factor2: second factor
227  *
228  * Returns: calculate @factor1 * @factor2, both promoted to size_t,
229  * with any overflow causing the return value to be SIZE_MAX. The
230  * lvalue must be size_t to avoid implicit type conversion.
231  */
232 static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
233 {
234 	size_t bytes;
235 
236 	if (check_mul_overflow(factor1, factor2, &bytes))
237 		return SIZE_MAX;
238 
239 	return bytes;
240 }
241 
242 /**
243  * size_add() - Calculate size_t addition with saturation at SIZE_MAX
244  * @addend1: first addend
245  * @addend2: second addend
246  *
247  * Returns: calculate @addend1 + @addend2, both promoted to size_t,
248  * with any overflow causing the return value to be SIZE_MAX. The
249  * lvalue must be size_t to avoid implicit type conversion.
250  */
251 static inline size_t __must_check size_add(size_t addend1, size_t addend2)
252 {
253 	size_t bytes;
254 
255 	if (check_add_overflow(addend1, addend2, &bytes))
256 		return SIZE_MAX;
257 
258 	return bytes;
259 }
260 
261 /**
262  * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
263  * @minuend: value to subtract from
264  * @subtrahend: value to subtract from @minuend
265  *
266  * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
267  * with any overflow causing the return value to be SIZE_MAX. For
268  * composition with the size_add() and size_mul() helpers, neither
269  * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
270  * The lvalue must be size_t to avoid implicit type conversion.
271  */
272 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
273 {
274 	size_t bytes;
275 
276 	if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
277 	    check_sub_overflow(minuend, subtrahend, &bytes))
278 		return SIZE_MAX;
279 
280 	return bytes;
281 }
282 
283 /**
284  * array_size() - Calculate size of 2-dimensional array.
285  * @a: dimension one
286  * @b: dimension two
287  *
288  * Calculates size of 2-dimensional array: @a * @b.
289  *
290  * Returns: number of bytes needed to represent the array or SIZE_MAX on
291  * overflow.
292  */
293 #define array_size(a, b)	size_mul(a, b)
294 
295 /**
296  * array3_size() - Calculate size of 3-dimensional array.
297  * @a: dimension one
298  * @b: dimension two
299  * @c: dimension three
300  *
301  * Calculates size of 3-dimensional array: @a * @b * @c.
302  *
303  * Returns: number of bytes needed to represent the array or SIZE_MAX on
304  * overflow.
305  */
306 #define array3_size(a, b, c)	size_mul(size_mul(a, b), c)
307 
308 /**
309  * flex_array_size() - Calculate size of a flexible array member
310  *                     within an enclosing structure.
311  * @p: Pointer to the structure.
312  * @member: Name of the flexible array member.
313  * @count: Number of elements in the array.
314  *
315  * Calculates size of a flexible array of @count number of @member
316  * elements, at the end of structure @p.
317  *
318  * Return: number of bytes needed or SIZE_MAX on overflow.
319  */
320 #define flex_array_size(p, member, count)				\
321 	__builtin_choose_expr(__is_constexpr(count),			\
322 		(count) * sizeof(*(p)->member) + __must_be_array((p)->member),	\
323 		size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
324 
325 /**
326  * struct_size() - Calculate size of structure with trailing flexible array.
327  * @p: Pointer to the structure.
328  * @member: Name of the array member.
329  * @count: Number of elements in the array.
330  *
331  * Calculates size of memory needed for structure of @p followed by an
332  * array of @count number of @member elements.
333  *
334  * Return: number of bytes needed or SIZE_MAX on overflow.
335  */
336 #define struct_size(p, member, count)					\
337 	__builtin_choose_expr(__is_constexpr(count),			\
338 		sizeof(*(p)) + flex_array_size(p, member, count),	\
339 		size_add(sizeof(*(p)), flex_array_size(p, member, count)))
340 
341 /**
342  * struct_size_t() - Calculate size of structure with trailing flexible array
343  * @type: structure type name.
344  * @member: Name of the array member.
345  * @count: Number of elements in the array.
346  *
347  * Calculates size of memory needed for structure @type followed by an
348  * array of @count number of @member elements. Prefer using struct_size()
349  * when possible instead, to keep calculations associated with a specific
350  * instance variable of type @type.
351  *
352  * Return: number of bytes needed or SIZE_MAX on overflow.
353  */
354 #define struct_size_t(type, member, count)					\
355 	struct_size((type *)NULL, member, count)
356 
357 /**
358  * _DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
359  * Enables caller macro to pass (different) initializer.
360  *
361  * @type: structure type name, including "struct" keyword.
362  * @name: Name for a variable to define.
363  * @member: Name of the array member.
364  * @count: Number of elements in the array; must be compile-time const.
365  * @initializer: initializer expression (could be empty for no init).
366  */
367 #define _DEFINE_FLEX(type, name, member, count, initializer)			\
368 	_Static_assert(__builtin_constant_p(count),				\
369 		       "onstack flex array members require compile-time const count"); \
370 	union {									\
371 		u8 bytes[struct_size_t(type, member, count)];			\
372 		type obj;							\
373 	} name##_u initializer;							\
374 	type *name = (type *)&name##_u
375 
376 /**
377  * DEFINE_FLEX() - Define an on-stack instance of structure with a trailing
378  * flexible array member.
379  *
380  * @type: structure type name, including "struct" keyword.
381  * @name: Name for a variable to define.
382  * @member: Name of the array member.
383  * @count: Number of elements in the array; must be compile-time const.
384  *
385  * Define a zeroed, on-stack, instance of @type structure with a trailing
386  * flexible array member.
387  * Use __struct_size(@name) to get compile-time size of it afterwards.
388  */
389 #define DEFINE_FLEX(type, name, member, count)			\
390 	_DEFINE_FLEX(type, name, member, count, = {})
391 
392 #endif /* __LINUX_OVERFLOW_H */
393