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_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))
38
39/*
40 * Avoids triggering -Wtype-limits compilation warning,
41 * while using unsigned data types to check a < 0.
42 */
43#define is_non_negative(a) ((a) > 0 || (a) == 0)
44#define is_negative(a) (!(is_non_negative(a)))
45
46/*
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.
50 */
51static inline bool __must_check __must_check_overflow(bool overflow)
52{
53 return unlikely(overflow);
54}
55
56/**
57 * check_add_overflow() - Calculate addition with overflow checking
58 * @a: first addend
59 * @b: second addend
60 * @d: pointer to store sum
61 *
62 * Returns true on wrap-around, false otherwise.
63 *
64 * *@d holds the results of the attempted addition, regardless of whether
65 * wrap-around occurred.
66 */
67#define check_add_overflow(a, b, d) \
68 __must_check_overflow(__builtin_add_overflow(a, b, d))
69
70/**
71 * wrapping_add() - Intentionally perform a wrapping addition
72 * @type: type for result of calculation
73 * @a: first addend
74 * @b: second addend
75 *
76 * Return the potentially wrapped-around addition without
77 * tripping any wrap-around sanitizers that may be enabled.
78 */
79#define wrapping_add(type, a, b) \
80 ({ \
81 type __val; \
82 __builtin_add_overflow(a, b, &__val); \
83 __val; \
84 })
85
86/**
87 * wrapping_assign_add() - Intentionally perform a wrapping increment assignment
88 * @var: variable to be incremented
89 * @offset: amount to add
90 *
91 * Increments @var by @offset with wrap-around. Returns the resulting
92 * value of @var. Will not trip any wrap-around sanitizers.
93 *
94 * Returns the new value of @var.
95 */
96#define wrapping_assign_add(var, offset) \
97 ({ \
98 typeof(var) *__ptr = &(var); \
99 *__ptr = wrapping_add(typeof(var), *__ptr, offset); \
100 })
101
102/**
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
107 *
108 * Returns true on wrap-around, false otherwise.
109 *
110 * *@d holds the results of the attempted subtraction, regardless of whether
111 * wrap-around occurred.
112 */
113#define check_sub_overflow(a, b, d) \
114 __must_check_overflow(__builtin_sub_overflow(a, b, d))
115
116/**
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
121 *
122 * Return the potentially wrapped-around subtraction without
123 * tripping any wrap-around sanitizers that may be enabled.
124 */
125#define wrapping_sub(type, a, b) \
126 ({ \
127 type __val; \
128 __builtin_sub_overflow(a, b, &__val); \
129 __val; \
130 })
131
132/**
133 * wrapping_assign_sub() - Intentionally perform a wrapping decrement assign
134 * @var: variable to be decremented
135 * @offset: amount to subtract
136 *
137 * Decrements @var by @offset with wrap-around. Returns the resulting
138 * value of @var. Will not trip any wrap-around sanitizers.
139 *
140 * Returns the new value of @var.
141 */
142#define wrapping_assign_sub(var, offset) \
143 ({ \
144 typeof(var) *__ptr = &(var); \
145 *__ptr = wrapping_sub(typeof(var), *__ptr, offset); \
146 })
147
148/**
149 * check_mul_overflow() - Calculate multiplication with overflow checking
150 * @a: first factor
151 * @b: second factor
152 * @d: pointer to store product
153 *
154 * Returns true on wrap-around, false otherwise.
155 *
156 * *@d holds the results of the attempted multiplication, regardless of whether
157 * wrap-around occurred.
158 */
159#define check_mul_overflow(a, b, d) \
160 __must_check_overflow(__builtin_mul_overflow(a, b, d))
161
162/**
163 * wrapping_mul() - Intentionally perform a wrapping multiplication
164 * @type: type for result of calculation
165 * @a: first factor
166 * @b: second factor
167 *
168 * Return the potentially wrapped-around multiplication without
169 * tripping any wrap-around sanitizers that may be enabled.
170 */
171#define wrapping_mul(type, a, b) \
172 ({ \
173 type __val; \
174 __builtin_mul_overflow(a, b, &__val); \
175 __val; \
176 })
177
178/**
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
183 *
184 * Computes *@d = (@a << @s)
185 *
186 * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't
187 * make sense. Example conditions:
188 *
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'.
194 *
195 * '*@d' will hold the results of the attempted shift, but is not
196 * considered "safe for use" if true is returned.
197 */
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); \
208}))
209
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))
216
217#define __overflows_type(x, T) ({ \
218 typeof(T) v = 0; \
219 check_add_overflow((x), v, &v); \
220})
221
222/**
223 * overflows_type - helper for checking the overflows between value, variables,
224 * or data type
225 *
226 * @n: source constant value or variable to be checked
227 * @T: destination variable or data type proposed to store @x
228 *
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.
233 *
234 * Returns: true if overflow can occur, false otherwise.
235 */
236#define overflows_type(n, T) \
237 __builtin_choose_expr(__is_constexpr(n), \
238 __overflows_type_constexpr(n, T), \
239 __overflows_type(n, T))
240
241/**
242 * range_overflows() - Check if a range is out of bounds
243 * @start: Start of the range.
244 * @size: Size of the range.
245 * @max: Exclusive upper boundary.
246 *
247 * A strict check to determine if the range [@start, @start + @size) is
248 * invalid with respect to the allowable range [0, @max). Any range
249 * starting at or beyond @max is considered an overflow, even if @size is 0.
250 *
251 * Returns: true if the range is out of bounds.
252 */
253#define range_overflows(start, size, max) ({ \
254 typeof(start) start__ = (start); \
255 typeof(size) size__ = (size); \
256 typeof(max) max__ = (max); \
257 (void)(&start__ == &size__); \
258 (void)(&start__ == &max__); \
259 start__ >= max__ || size__ > max__ - start__; \
260})
261
262/**
263 * range_overflows_t() - Check if a range is out of bounds
264 * @type: Data type to use.
265 * @start: Start of the range.
266 * @size: Size of the range.
267 * @max: Exclusive upper boundary.
268 *
269 * Same as range_overflows() but forcing the parameters to @type.
270 *
271 * Returns: true if the range is out of bounds.
272 */
273#define range_overflows_t(type, start, size, max) \
274 range_overflows((type)(start), (type)(size), (type)(max))
275
276/**
277 * range_end_overflows() - Check if a range's endpoint is out of bounds
278 * @start: Start of the range.
279 * @size: Size of the range.
280 * @max: Exclusive upper boundary.
281 *
282 * Checks only if the endpoint of a range (@start + @size) exceeds @max.
283 * Unlike range_overflows(), a zero-sized range at the boundary (@start == @max)
284 * is not considered an overflow. Useful for iterator-style checks.
285 *
286 * Returns: true if the endpoint exceeds the boundary.
287 */
288#define range_end_overflows(start, size, max) ({ \
289 typeof(start) start__ = (start); \
290 typeof(size) size__ = (size); \
291 typeof(max) max__ = (max); \
292 (void)(&start__ == &size__); \
293 (void)(&start__ == &max__); \
294 start__ > max__ || size__ > max__ - start__; \
295})
296
297/**
298 * range_end_overflows_t() - Check if a range's endpoint is out of bounds
299 * @type: Data type to use.
300 * @start: Start of the range.
301 * @size: Size of the range.
302 * @max: Exclusive upper boundary.
303 *
304 * Same as range_end_overflows() but forcing the parameters to @type.
305 *
306 * Returns: true if the endpoint exceeds the boundary.
307 */
308#define range_end_overflows_t(type, start, size, max) \
309 range_end_overflows((type)(start), (type)(size), (type)(max))
310
311/**
312 * castable_to_type - like __same_type(), but also allows for casted literals
313 *
314 * @n: variable or constant value
315 * @T: variable or data type
316 *
317 * Unlike the __same_type() macro, this allows a constant value as the
318 * first argument. If this value would not overflow into an assignment
319 * of the second argument's type, it returns true. Otherwise, this falls
320 * back to __same_type().
321 */
322#define castable_to_type(n, T) \
323 __builtin_choose_expr(__is_constexpr(n), \
324 !__overflows_type_constexpr(n, T), \
325 __same_type(n, T))
326
327/**
328 * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
329 * @factor1: first factor
330 * @factor2: second factor
331 *
332 * Returns: calculate @factor1 * @factor2, both promoted to size_t,
333 * with any overflow causing the return value to be SIZE_MAX. The
334 * lvalue must be size_t to avoid implicit type conversion.
335 */
336static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
337{
338 size_t bytes;
339
340 if (check_mul_overflow(factor1, factor2, &bytes))
341 return SIZE_MAX;
342
343 return bytes;
344}
345
346/**
347 * size_add() - Calculate size_t addition with saturation at SIZE_MAX
348 * @addend1: first addend
349 * @addend2: second addend
350 *
351 * Returns: calculate @addend1 + @addend2, both promoted to size_t,
352 * with any overflow causing the return value to be SIZE_MAX. The
353 * lvalue must be size_t to avoid implicit type conversion.
354 */
355static inline size_t __must_check size_add(size_t addend1, size_t addend2)
356{
357 size_t bytes;
358
359 if (check_add_overflow(addend1, addend2, &bytes))
360 return SIZE_MAX;
361
362 return bytes;
363}
364
365/**
366 * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
367 * @minuend: value to subtract from
368 * @subtrahend: value to subtract from @minuend
369 *
370 * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
371 * with any overflow causing the return value to be SIZE_MAX. For
372 * composition with the size_add() and size_mul() helpers, neither
373 * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
374 * The lvalue must be size_t to avoid implicit type conversion.
375 */
376static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
377{
378 size_t bytes;
379
380 if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
381 check_sub_overflow(minuend, subtrahend, &bytes))
382 return SIZE_MAX;
383
384 return bytes;
385}
386
387/**
388 * array_size() - Calculate size of 2-dimensional array.
389 * @a: dimension one
390 * @b: dimension two
391 *
392 * Calculates size of 2-dimensional array: @a * @b.
393 *
394 * Returns: number of bytes needed to represent the array or SIZE_MAX on
395 * overflow.
396 */
397#define array_size(a, b) size_mul(a, b)
398
399/**
400 * array3_size() - Calculate size of 3-dimensional array.
401 * @a: dimension one
402 * @b: dimension two
403 * @c: dimension three
404 *
405 * Calculates size of 3-dimensional array: @a * @b * @c.
406 *
407 * Returns: number of bytes needed to represent the array or SIZE_MAX on
408 * overflow.
409 */
410#define array3_size(a, b, c) size_mul(size_mul(a, b), c)
411
412/**
413 * flex_array_size() - Calculate size of a flexible array member
414 * within an enclosing structure.
415 * @p: Pointer to the structure.
416 * @member: Name of the flexible array member.
417 * @count: Number of elements in the array.
418 *
419 * Calculates size of a flexible array of @count number of @member
420 * elements, at the end of structure @p.
421 *
422 * Return: number of bytes needed or SIZE_MAX on overflow.
423 */
424#define flex_array_size(p, member, count) \
425 __builtin_choose_expr(__is_constexpr(count), \
426 (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \
427 size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
428
429/**
430 * struct_size() - Calculate size of structure with trailing flexible array.
431 * @p: Pointer to the structure.
432 * @member: Name of the array member.
433 * @count: Number of elements in the array.
434 *
435 * Calculates size of memory needed for structure of @p followed by an
436 * array of @count number of @member elements.
437 *
438 * Return: number of bytes needed or SIZE_MAX on overflow.
439 */
440#define struct_size(p, member, count) \
441 __builtin_choose_expr(__is_constexpr(count), \
442 sizeof(*(p)) + flex_array_size(p, member, count), \
443 size_add(sizeof(*(p)), flex_array_size(p, member, count)))
444
445/**
446 * struct_size_t() - Calculate size of structure with trailing flexible array
447 * @type: structure type name.
448 * @member: Name of the array member.
449 * @count: Number of elements in the array.
450 *
451 * Calculates size of memory needed for structure @type followed by an
452 * array of @count number of @member elements. Prefer using struct_size()
453 * when possible instead, to keep calculations associated with a specific
454 * instance variable of type @type.
455 *
456 * Return: number of bytes needed or SIZE_MAX on overflow.
457 */
458#define struct_size_t(type, member, count) \
459 struct_size((type *)NULL, member, count)
460
461/**
462 * __DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
463 * Enables caller macro to pass arbitrary trailing expressions
464 *
465 * @type: structure type name, including "struct" keyword.
466 * @name: Name for a variable to define.
467 * @member: Name of the array member.
468 * @count: Number of elements in the array; must be compile-time const.
469 * @trailer: Trailing expressions for attributes and/or initializers.
470 */
471#define __DEFINE_FLEX(type, name, member, count, trailer...) \
472 _Static_assert(__builtin_constant_p(count), \
473 "onstack flex array members require compile-time const count"); \
474 union { \
475 u8 bytes[struct_size_t(type, member, count)]; \
476 type obj; \
477 } name##_u trailer; \
478 type *name = (type *)&name##_u
479
480/**
481 * _DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
482 * Enables caller macro to pass (different) initializer.
483 *
484 * @type: structure type name, including "struct" keyword.
485 * @name: Name for a variable to define.
486 * @member: Name of the array member.
487 * @count: Number of elements in the array; must be compile-time const.
488 * @initializer: Initializer expression (e.g., pass `= { }` at minimum).
489 */
490#define _DEFINE_FLEX(type, name, member, count, initializer...) \
491 __DEFINE_FLEX(type, name, member, count, = { .obj initializer })
492
493/**
494 * DEFINE_RAW_FLEX() - Define an on-stack instance of structure with a trailing
495 * flexible array member, when it does not have a __counted_by annotation.
496 *
497 * @type: structure type name, including "struct" keyword.
498 * @name: Name for a variable to define.
499 * @member: Name of the array member.
500 * @count: Number of elements in the array; must be compile-time const.
501 *
502 * Define a zeroed, on-stack, instance of @type structure with a trailing
503 * flexible array member.
504 * Use __struct_size(@name) to get compile-time size of it afterwards.
505 * Use __member_size(@name->member) to get compile-time size of @name members.
506 * Use STACK_FLEX_ARRAY_SIZE(@name, @member) to get compile-time number of
507 * elements in array @member.
508 */
509#define DEFINE_RAW_FLEX(type, name, member, count) \
510 __DEFINE_FLEX(type, name, member, count, = { })
511
512/**
513 * DEFINE_FLEX() - Define an on-stack instance of structure with a trailing
514 * flexible array member.
515 *
516 * @TYPE: structure type name, including "struct" keyword.
517 * @NAME: Name for a variable to define.
518 * @MEMBER: Name of the array member.
519 * @COUNTER: Name of the __counted_by member.
520 * @COUNT: Number of elements in the array; must be compile-time const.
521 *
522 * Define a zeroed, on-stack, instance of @TYPE structure with a trailing
523 * flexible array member.
524 * Use __struct_size(@NAME) to get compile-time size of it afterwards.
525 * Use __member_size(@NAME->member) to get compile-time size of @NAME members.
526 * Use STACK_FLEX_ARRAY_SIZE(@name, @member) to get compile-time number of
527 * elements in array @member.
528 */
529#define DEFINE_FLEX(TYPE, NAME, MEMBER, COUNTER, COUNT) \
530 _DEFINE_FLEX(TYPE, NAME, MEMBER, COUNT, = { .COUNTER = COUNT, })
531
532/**
533 * STACK_FLEX_ARRAY_SIZE() - helper macro for DEFINE_FLEX() family.
534 * Returns the number of elements in @array.
535 *
536 * @name: Name for a variable defined in DEFINE_RAW_FLEX()/DEFINE_FLEX().
537 * @array: Name of the array member.
538 */
539#define STACK_FLEX_ARRAY_SIZE(name, array) \
540 (__member_size((name)->array) / sizeof(*(name)->array) + \
541 __must_be_array((name)->array))
542
543#endif /* __LINUX_OVERFLOW_H */
544