printf: Remove unused 'bprintf'
[drm/drm-misc.git] / include / linux / overflow.h
blob0c7e3dcfe8670cb95f371a6f7d41bb8b63b1786c
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>
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:
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
27 * argument.]
29 * Idea stolen from
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_max(t) __type_max(typeof(t))
36 #define __type_min(T) ((T)((T)-type_max(T)-(T)1))
37 #define type_min(t) __type_min(typeof(t))
40 * Avoids triggering -Wtype-limits compilation warning,
41 * while using unsigned data types to check a < 0.
43 #define is_non_negative(a) ((a) > 0 || (a) == 0)
44 #define is_negative(a) (!(is_non_negative(a)))
47 * Allows for effectively applying __must_check to a macro so we can have
48 * both the type-agnostic benefits of the macros while also being able to
49 * enforce that the return value is, in fact, checked.
51 static inline bool __must_check __must_check_overflow(bool overflow)
53 return unlikely(overflow);
56 /**
57 * check_add_overflow() - Calculate addition with overflow checking
58 * @a: first addend
59 * @b: second addend
60 * @d: pointer to store sum
62 * Returns true on wrap-around, false otherwise.
64 * *@d holds the results of the attempted addition, regardless of whether
65 * wrap-around occurred.
67 #define check_add_overflow(a, b, d) \
68 __must_check_overflow(__builtin_add_overflow(a, b, d))
70 /**
71 * wrapping_add() - Intentionally perform a wrapping addition
72 * @type: type for result of calculation
73 * @a: first addend
74 * @b: second addend
76 * Return the potentially wrapped-around addition without
77 * tripping any wrap-around sanitizers that may be enabled.
79 #define wrapping_add(type, a, b) \
80 ({ \
81 type __val; \
82 __builtin_add_overflow(a, b, &__val); \
83 __val; \
86 /**
87 * wrapping_assign_add() - Intentionally perform a wrapping increment assignment
88 * @var: variable to be incremented
89 * @offset: amount to add
91 * Increments @var by @offset with wrap-around. Returns the resulting
92 * value of @var. Will not trip any wrap-around sanitizers.
94 * Returns the new value of @var.
96 #define wrapping_assign_add(var, offset) \
97 ({ \
98 typeof(var) *__ptr = &(var); \
99 *__ptr = wrapping_add(typeof(var), *__ptr, offset); \
103 * check_sub_overflow() - Calculate subtraction with overflow checking
104 * @a: minuend; value to subtract from
105 * @b: subtrahend; value to subtract from @a
106 * @d: pointer to store difference
108 * Returns true on wrap-around, false otherwise.
110 * *@d holds the results of the attempted subtraction, regardless of whether
111 * wrap-around occurred.
113 #define check_sub_overflow(a, b, d) \
114 __must_check_overflow(__builtin_sub_overflow(a, b, d))
117 * wrapping_sub() - Intentionally perform a wrapping subtraction
118 * @type: type for result of calculation
119 * @a: minuend; value to subtract from
120 * @b: subtrahend; value to subtract from @a
122 * Return the potentially wrapped-around subtraction without
123 * tripping any wrap-around sanitizers that may be enabled.
125 #define wrapping_sub(type, a, b) \
126 ({ \
127 type __val; \
128 __builtin_sub_overflow(a, b, &__val); \
129 __val; \
133 * wrapping_assign_sub() - Intentionally perform a wrapping decrement assign
134 * @var: variable to be decremented
135 * @offset: amount to subtract
137 * Decrements @var by @offset with wrap-around. Returns the resulting
138 * value of @var. Will not trip any wrap-around sanitizers.
140 * Returns the new value of @var.
142 #define wrapping_assign_sub(var, offset) \
143 ({ \
144 typeof(var) *__ptr = &(var); \
145 *__ptr = wrapping_sub(typeof(var), *__ptr, offset); \
149 * check_mul_overflow() - Calculate multiplication with overflow checking
150 * @a: first factor
151 * @b: second factor
152 * @d: pointer to store product
154 * Returns true on wrap-around, false otherwise.
156 * *@d holds the results of the attempted multiplication, regardless of whether
157 * wrap-around occurred.
159 #define check_mul_overflow(a, b, d) \
160 __must_check_overflow(__builtin_mul_overflow(a, b, d))
163 * wrapping_mul() - Intentionally perform a wrapping multiplication
164 * @type: type for result of calculation
165 * @a: first factor
166 * @b: second factor
168 * Return the potentially wrapped-around multiplication without
169 * tripping any wrap-around sanitizers that may be enabled.
171 #define wrapping_mul(type, a, b) \
172 ({ \
173 type __val; \
174 __builtin_mul_overflow(a, b, &__val); \
175 __val; \
179 * check_shl_overflow() - Calculate a left-shifted value and check overflow
180 * @a: Value to be shifted
181 * @s: How many bits left to shift
182 * @d: Pointer to where to store the result
184 * Computes *@d = (@a << @s)
186 * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't
187 * make sense. Example conditions:
189 * - '@a << @s' causes bits to be lost when stored in *@d.
190 * - '@s' is garbage (e.g. negative) or so large that the result of
191 * '@a << @s' is guaranteed to be 0.
192 * - '@a' is negative.
193 * - '@a << @s' sets the sign bit, if any, in '*@d'.
195 * '*@d' will hold the results of the attempted shift, but is not
196 * considered "safe for use" if true is returned.
198 #define check_shl_overflow(a, s, d) __must_check_overflow(({ \
199 typeof(a) _a = a; \
200 typeof(s) _s = s; \
201 typeof(d) _d = d; \
202 unsigned long long _a_full = _a; \
203 unsigned int _to_shift = \
204 is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0; \
205 *_d = (_a_full << _to_shift); \
206 (_to_shift != _s || is_negative(*_d) || is_negative(_a) || \
207 (*_d >> _to_shift) != _a); \
210 #define __overflows_type_constexpr(x, T) ( \
211 is_unsigned_type(typeof(x)) ? \
212 (x) > type_max(T) : \
213 is_unsigned_type(typeof(T)) ? \
214 (x) < 0 || (x) > type_max(T) : \
215 (x) < type_min(T) || (x) > type_max(T))
217 #define __overflows_type(x, T) ({ \
218 typeof(T) v = 0; \
219 check_add_overflow((x), v, &v); \
223 * overflows_type - helper for checking the overflows between value, variables,
224 * or data type
226 * @n: source constant value or variable to be checked
227 * @T: destination variable or data type proposed to store @x
229 * Compares the @x expression for whether or not it can safely fit in
230 * the storage of the type in @T. @x and @T can have different types.
231 * If @x is a constant expression, this will also resolve to a constant
232 * expression.
234 * Returns: true if overflow can occur, false otherwise.
236 #define overflows_type(n, T) \
237 __builtin_choose_expr(__is_constexpr(n), \
238 __overflows_type_constexpr(n, T), \
239 __overflows_type(n, T))
242 * castable_to_type - like __same_type(), but also allows for casted literals
244 * @n: variable or constant value
245 * @T: variable or data type
247 * Unlike the __same_type() macro, this allows a constant value as the
248 * first argument. If this value would not overflow into an assignment
249 * of the second argument's type, it returns true. Otherwise, this falls
250 * back to __same_type().
252 #define castable_to_type(n, T) \
253 __builtin_choose_expr(__is_constexpr(n), \
254 !__overflows_type_constexpr(n, T), \
255 __same_type(n, T))
258 * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
259 * @factor1: first factor
260 * @factor2: second factor
262 * Returns: calculate @factor1 * @factor2, both promoted to size_t,
263 * with any overflow causing the return value to be SIZE_MAX. The
264 * lvalue must be size_t to avoid implicit type conversion.
266 static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
268 size_t bytes;
270 if (check_mul_overflow(factor1, factor2, &bytes))
271 return SIZE_MAX;
273 return bytes;
277 * size_add() - Calculate size_t addition with saturation at SIZE_MAX
278 * @addend1: first addend
279 * @addend2: second addend
281 * Returns: calculate @addend1 + @addend2, both promoted to size_t,
282 * with any overflow causing the return value to be SIZE_MAX. The
283 * lvalue must be size_t to avoid implicit type conversion.
285 static inline size_t __must_check size_add(size_t addend1, size_t addend2)
287 size_t bytes;
289 if (check_add_overflow(addend1, addend2, &bytes))
290 return SIZE_MAX;
292 return bytes;
296 * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
297 * @minuend: value to subtract from
298 * @subtrahend: value to subtract from @minuend
300 * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
301 * with any overflow causing the return value to be SIZE_MAX. For
302 * composition with the size_add() and size_mul() helpers, neither
303 * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
304 * The lvalue must be size_t to avoid implicit type conversion.
306 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
308 size_t bytes;
310 if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
311 check_sub_overflow(minuend, subtrahend, &bytes))
312 return SIZE_MAX;
314 return bytes;
318 * array_size() - Calculate size of 2-dimensional array.
319 * @a: dimension one
320 * @b: dimension two
322 * Calculates size of 2-dimensional array: @a * @b.
324 * Returns: number of bytes needed to represent the array or SIZE_MAX on
325 * overflow.
327 #define array_size(a, b) size_mul(a, b)
330 * array3_size() - Calculate size of 3-dimensional array.
331 * @a: dimension one
332 * @b: dimension two
333 * @c: dimension three
335 * Calculates size of 3-dimensional array: @a * @b * @c.
337 * Returns: number of bytes needed to represent the array or SIZE_MAX on
338 * overflow.
340 #define array3_size(a, b, c) size_mul(size_mul(a, b), c)
343 * flex_array_size() - Calculate size of a flexible array member
344 * within an enclosing structure.
345 * @p: Pointer to the structure.
346 * @member: Name of the flexible array member.
347 * @count: Number of elements in the array.
349 * Calculates size of a flexible array of @count number of @member
350 * elements, at the end of structure @p.
352 * Return: number of bytes needed or SIZE_MAX on overflow.
354 #define flex_array_size(p, member, count) \
355 __builtin_choose_expr(__is_constexpr(count), \
356 (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \
357 size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
360 * struct_size() - Calculate size of structure with trailing flexible array.
361 * @p: Pointer to the structure.
362 * @member: Name of the array member.
363 * @count: Number of elements in the array.
365 * Calculates size of memory needed for structure of @p followed by an
366 * array of @count number of @member elements.
368 * Return: number of bytes needed or SIZE_MAX on overflow.
370 #define struct_size(p, member, count) \
371 __builtin_choose_expr(__is_constexpr(count), \
372 sizeof(*(p)) + flex_array_size(p, member, count), \
373 size_add(sizeof(*(p)), flex_array_size(p, member, count)))
376 * struct_size_t() - Calculate size of structure with trailing flexible array
377 * @type: structure type name.
378 * @member: Name of the array member.
379 * @count: Number of elements in the array.
381 * Calculates size of memory needed for structure @type followed by an
382 * array of @count number of @member elements. Prefer using struct_size()
383 * when possible instead, to keep calculations associated with a specific
384 * instance variable of type @type.
386 * Return: number of bytes needed or SIZE_MAX on overflow.
388 #define struct_size_t(type, member, count) \
389 struct_size((type *)NULL, member, count)
392 * _DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
393 * Enables caller macro to pass (different) initializer.
395 * @type: structure type name, including "struct" keyword.
396 * @name: Name for a variable to define.
397 * @member: Name of the array member.
398 * @count: Number of elements in the array; must be compile-time const.
399 * @initializer: initializer expression (could be empty for no init).
401 #define _DEFINE_FLEX(type, name, member, count, initializer...) \
402 _Static_assert(__builtin_constant_p(count), \
403 "onstack flex array members require compile-time const count"); \
404 union { \
405 u8 bytes[struct_size_t(type, member, count)]; \
406 type obj; \
407 } name##_u initializer; \
408 type *name = (type *)&name##_u
411 * DEFINE_RAW_FLEX() - Define an on-stack instance of structure with a trailing
412 * flexible array member, when it does not have a __counted_by annotation.
414 * @type: structure type name, including "struct" keyword.
415 * @name: Name for a variable to define.
416 * @member: Name of the array member.
417 * @count: Number of elements in the array; must be compile-time const.
419 * Define a zeroed, on-stack, instance of @type structure with a trailing
420 * flexible array member.
421 * Use __struct_size(@name) to get compile-time size of it afterwards.
423 #define DEFINE_RAW_FLEX(type, name, member, count) \
424 _DEFINE_FLEX(type, name, member, count, = {})
427 * DEFINE_FLEX() - Define an on-stack instance of structure with a trailing
428 * flexible array member.
430 * @TYPE: structure type name, including "struct" keyword.
431 * @NAME: Name for a variable to define.
432 * @MEMBER: Name of the array member.
433 * @COUNTER: Name of the __counted_by member.
434 * @COUNT: Number of elements in the array; must be compile-time const.
436 * Define a zeroed, on-stack, instance of @TYPE structure with a trailing
437 * flexible array member.
438 * Use __struct_size(@NAME) to get compile-time size of it afterwards.
440 #define DEFINE_FLEX(TYPE, NAME, MEMBER, COUNTER, COUNT) \
441 _DEFINE_FLEX(TYPE, NAME, MEMBER, COUNT, = { .obj.COUNTER = COUNT, })
443 #endif /* __LINUX_OVERFLOW_H */