1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 #ifndef __LINUX_OVERFLOW_H
3 #define __LINUX_OVERFLOW_H
5 #include <linux/compiler.h>
6 #include <linux/limits.h>
7 #include <linux/const.h>
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:
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)
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...).
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
30 * https://mail-index.netbsd.org/tech-misc/2007/02/05/0000.html -
31 * credit to Christian Biere.
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))
38 * Avoids triggering -Wtype-limits compilation warning,
39 * while using unsigned data types to check a < 0.
41 #define is_non_negative(a) ((a) > 0 || (a) == 0)
42 #define is_negative(a) (!(is_non_negative(a)))
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.
49 static inline bool __must_check __must_check_overflow(bool overflow)
51 return unlikely(overflow);
55 * check_add_overflow() - Calculate addition with overflow checking
58 * @d: pointer to store sum
60 * Returns true on wrap-around, false otherwise.
62 * *@d holds the results of the attempted addition, regardless of whether
63 * wrap-around occurred.
65 #define check_add_overflow(a, b, d) \
66 __must_check_overflow(__builtin_add_overflow(a, b, d))
69 * wrapping_add() - Intentionally perform a wrapping addition
70 * @type: type for result of calculation
74 * Return the potentially wrapped-around addition without
75 * tripping any wrap-around sanitizers that may be enabled.
77 #define wrapping_add(type, a, b) \
80 __builtin_add_overflow(a, b, &__val); \
85 * wrapping_assign_add() - Intentionally perform a wrapping increment assignment
86 * @var: variable to be incremented
87 * @offset: amount to add
89 * Increments @var by @offset with wrap-around. Returns the resulting
90 * value of @var. Will not trip any wrap-around sanitizers.
92 * Returns the new value of @var.
94 #define wrapping_assign_add(var, offset) \
96 typeof(var) *__ptr = &(var); \
97 *__ptr = wrapping_add(typeof(var), *__ptr, offset); \
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
106 * Returns true on wrap-around, false otherwise.
108 * *@d holds the results of the attempted subtraction, regardless of whether
109 * wrap-around occurred.
111 #define check_sub_overflow(a, b, d) \
112 __must_check_overflow(__builtin_sub_overflow(a, b, d))
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
120 * Return the potentially wrapped-around subtraction without
121 * tripping any wrap-around sanitizers that may be enabled.
123 #define wrapping_sub(type, a, b) \
126 __builtin_sub_overflow(a, b, &__val); \
131 * wrapping_assign_sub() - Intentionally perform a wrapping decrement assign
132 * @var: variable to be decremented
133 * @offset: amount to subtract
135 * Decrements @var by @offset with wrap-around. Returns the resulting
136 * value of @var. Will not trip any wrap-around sanitizers.
138 * Returns the new value of @var.
140 #define wrapping_assign_sub(var, offset) \
142 typeof(var) *__ptr = &(var); \
143 *__ptr = wrapping_sub(typeof(var), *__ptr, offset); \
147 * check_mul_overflow() - Calculate multiplication with overflow checking
150 * @d: pointer to store product
152 * Returns true on wrap-around, false otherwise.
154 * *@d holds the results of the attempted multiplication, regardless of whether
155 * wrap-around occurred.
157 #define check_mul_overflow(a, b, d) \
158 __must_check_overflow(__builtin_mul_overflow(a, b, d))
161 * wrapping_mul() - Intentionally perform a wrapping multiplication
162 * @type: type for result of calculation
166 * Return the potentially wrapped-around multiplication without
167 * tripping any wrap-around sanitizers that may be enabled.
169 #define wrapping_mul(type, a, b) \
172 __builtin_mul_overflow(a, b, &__val); \
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
182 * Computes *@d = (@a << @s)
184 * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't
185 * make sense. Example conditions:
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'.
193 * '*@d' will hold the results of the attempted shift, but is not
194 * considered "safe for use" if true is returned.
196 #define check_shl_overflow(a, s, d) __must_check_overflow(({ \
200 unsigned long long _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); \
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)))
215 #define __overflows_type(x, T) ({ \
217 check_add_overflow((x), v, &v); \
221 * overflows_type - helper for checking the overflows between value, variables,
224 * @n: source constant value or variable to be checked
225 * @T: destination variable or data type proposed to store @x
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
232 * Returns: true if overflow can occur, false otherwise.
234 #define overflows_type(n, T) \
235 __builtin_choose_expr(__is_constexpr(n), \
236 __overflows_type_constexpr(n, T), \
237 __overflows_type(n, T))
240 * castable_to_type - like __same_type(), but also allows for casted literals
242 * @n: variable or constant value
243 * @T: variable or data type
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().
250 #define castable_to_type(n, T) \
251 __builtin_choose_expr(__is_constexpr(n), \
252 !__overflows_type_constexpr(n, T), \
256 * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
257 * @factor1: first factor
258 * @factor2: second factor
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.
264 static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
268 if (check_mul_overflow(factor1, factor2, &bytes))
275 * size_add() - Calculate size_t addition with saturation at SIZE_MAX
276 * @addend1: first addend
277 * @addend2: second addend
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.
283 static inline size_t __must_check size_add(size_t addend1, size_t addend2)
287 if (check_add_overflow(addend1, addend2, &bytes))
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
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.
304 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
308 if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
309 check_sub_overflow(minuend, subtrahend, &bytes))
316 * array_size() - Calculate size of 2-dimensional array.
320 * Calculates size of 2-dimensional array: @a * @b.
322 * Returns: number of bytes needed to represent the array or SIZE_MAX on
325 #define array_size(a, b) size_mul(a, b)
328 * array3_size() - Calculate size of 3-dimensional array.
331 * @c: dimension three
333 * Calculates size of 3-dimensional array: @a * @b * @c.
335 * Returns: number of bytes needed to represent the array or SIZE_MAX on
338 #define array3_size(a, b, c) size_mul(size_mul(a, b), c)
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.
347 * Calculates size of a flexible array of @count number of @member
348 * elements, at the end of structure @p.
350 * Return: number of bytes needed or SIZE_MAX on overflow.
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)))
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.
363 * Calculates size of memory needed for structure of @p followed by an
364 * array of @count number of @member elements.
366 * Return: number of bytes needed or SIZE_MAX on overflow.
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)))
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.
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.
384 * Return: number of bytes needed or SIZE_MAX on overflow.
386 #define struct_size_t(type, member, count) \
387 struct_size((type *)NULL, member, count)
390 * _DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
391 * Enables caller macro to pass (different) initializer.
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).
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"); \
403 u8 bytes[struct_size_t(type, member, count)]; \
405 } name##_u initializer; \
406 type *name = (type *)&name##_u
409 * DEFINE_FLEX() - Define an on-stack instance of structure with a trailing
410 * flexible array member.
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.
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.
421 #define DEFINE_FLEX(type, name, member, count) \
422 _DEFINE_FLEX(type, name, member, count, = {})
424 #endif /* __LINUX_OVERFLOW_H */