Merge tag 'fbdev-for-6.4-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/deller...
[linux-block.git] / include / linux / overflow.h
CommitLineData
f0907827
RV
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>
a4947e84 6#include <linux/limits.h>
230f6fa2 7#include <linux/const.h>
f0907827
RV
8
9/*
4eb6bd55
ND
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:
f0907827
RV
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 */
f0907827
RV
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
dc7fe518
LR
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)))
f0907827 43
9b80e4c4
KC
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 */
49static inline bool __must_check __must_check_overflow(bool overflow)
50{
51 return unlikely(overflow);
52}
53
31970608
KC
54/**
55 * check_add_overflow() - Calculate addition with overflow checking
d219d2a9
KC
56 * @a: first addend
57 * @b: second addend
58 * @d: pointer to store sum
59 *
60 * Returns 0 on success.
61 *
62 * *@d holds the results of the attempted addition, but is not considered
63 * "safe for use" on a non-zero return value, which indicates that the
64 * sum has overflowed or been truncated.
f0907827 65 */
d219d2a9
KC
66#define check_add_overflow(a, b, d) \
67 __must_check_overflow(__builtin_add_overflow(a, b, d))
f0907827 68
31970608
KC
69/**
70 * check_sub_overflow() - Calculate subtraction with overflow checking
d219d2a9
KC
71 * @a: minuend; value to subtract from
72 * @b: subtrahend; value to subtract from @a
73 * @d: pointer to store difference
74 *
75 * Returns 0 on success.
76 *
77 * *@d holds the results of the attempted subtraction, but is not considered
78 * "safe for use" on a non-zero return value, which indicates that the
79 * difference has underflowed or been truncated.
80 */
81#define check_sub_overflow(a, b, d) \
82 __must_check_overflow(__builtin_sub_overflow(a, b, d))
f0907827 83
31970608
KC
84/**
85 * check_mul_overflow() - Calculate multiplication with overflow checking
d219d2a9
KC
86 * @a: first factor
87 * @b: second factor
88 * @d: pointer to store product
89 *
90 * Returns 0 on success.
91 *
92 * *@d holds the results of the attempted multiplication, but is not
93 * considered "safe for use" on a non-zero return value, which indicates
94 * that the product has overflowed or been truncated.
95 */
96#define check_mul_overflow(a, b, d) \
97 __must_check_overflow(__builtin_mul_overflow(a, b, d))
f0907827 98
31970608
KC
99/**
100 * check_shl_overflow() - Calculate a left-shifted value and check overflow
0c668477
JG
101 * @a: Value to be shifted
102 * @s: How many bits left to shift
103 * @d: Pointer to where to store the result
104 *
105 * Computes *@d = (@a << @s)
106 *
31970608 107 * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't
0c668477 108 * make sense. Example conditions:
0c668477 109 *
31970608
KC
110 * - '@a << @s' causes bits to be lost when stored in *@d.
111 * - '@s' is garbage (e.g. negative) or so large that the result of
112 * '@a << @s' is guaranteed to be 0.
113 * - '@a' is negative.
114 * - '@a << @s' sets the sign bit, if any, in '*@d'.
115 *
116 * '*@d' will hold the results of the attempted shift, but is not
4578be13 117 * considered "safe for use" if true is returned.
0c668477 118 */
9b80e4c4 119#define check_shl_overflow(a, s, d) __must_check_overflow(({ \
0c668477
JG
120 typeof(a) _a = a; \
121 typeof(s) _s = s; \
122 typeof(d) _d = d; \
123 u64 _a_full = _a; \
124 unsigned int _to_shift = \
dc7fe518 125 is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0; \
0c668477 126 *_d = (_a_full << _to_shift); \
dc7fe518
LR
127 (_to_shift != _s || is_negative(*_d) || is_negative(_a) || \
128 (*_d >> _to_shift) != _a); \
9b80e4c4 129}))
0c668477 130
4b21d25b
KC
131#define __overflows_type_constexpr(x, T) ( \
132 is_unsigned_type(typeof(x)) ? \
133 (x) > type_max(typeof(T)) : \
134 is_unsigned_type(typeof(T)) ? \
135 (x) < 0 || (x) > type_max(typeof(T)) : \
136 (x) < type_min(typeof(T)) || (x) > type_max(typeof(T)))
137
138#define __overflows_type(x, T) ({ \
139 typeof(T) v = 0; \
140 check_add_overflow((x), v, &v); \
141})
142
143/**
144 * overflows_type - helper for checking the overflows between value, variables,
145 * or data type
146 *
147 * @n: source constant value or variable to be checked
148 * @T: destination variable or data type proposed to store @x
149 *
150 * Compares the @x expression for whether or not it can safely fit in
151 * the storage of the type in @T. @x and @T can have different types.
152 * If @x is a constant expression, this will also resolve to a constant
153 * expression.
154 *
155 * Returns: true if overflow can occur, false otherwise.
156 */
157#define overflows_type(n, T) \
158 __builtin_choose_expr(__is_constexpr(n), \
159 __overflows_type_constexpr(n, T), \
160 __overflows_type(n, T))
161
162/**
163 * castable_to_type - like __same_type(), but also allows for casted literals
164 *
165 * @n: variable or constant value
166 * @T: variable or data type
167 *
168 * Unlike the __same_type() macro, this allows a constant value as the
169 * first argument. If this value would not overflow into an assignment
170 * of the second argument's type, it returns true. Otherwise, this falls
171 * back to __same_type().
172 */
173#define castable_to_type(n, T) \
174 __builtin_choose_expr(__is_constexpr(n), \
175 !__overflows_type_constexpr(n, T), \
176 __same_type(n, T))
177
610b15c5 178/**
e1be43d9 179 * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
e1be43d9
KC
180 * @factor1: first factor
181 * @factor2: second factor
610b15c5 182 *
e1be43d9
KC
183 * Returns: calculate @factor1 * @factor2, both promoted to size_t,
184 * with any overflow causing the return value to be SIZE_MAX. The
185 * lvalue must be size_t to avoid implicit type conversion.
610b15c5 186 */
e1be43d9 187static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
610b15c5
KC
188{
189 size_t bytes;
190
e1be43d9 191 if (check_mul_overflow(factor1, factor2, &bytes))
610b15c5
KC
192 return SIZE_MAX;
193
194 return bytes;
195}
196
197/**
e1be43d9 198 * size_add() - Calculate size_t addition with saturation at SIZE_MAX
e1be43d9
KC
199 * @addend1: first addend
200 * @addend2: second addend
610b15c5 201 *
e1be43d9
KC
202 * Returns: calculate @addend1 + @addend2, both promoted to size_t,
203 * with any overflow causing the return value to be SIZE_MAX. The
204 * lvalue must be size_t to avoid implicit type conversion.
610b15c5 205 */
e1be43d9 206static inline size_t __must_check size_add(size_t addend1, size_t addend2)
610b15c5
KC
207{
208 size_t bytes;
209
e1be43d9 210 if (check_add_overflow(addend1, addend2, &bytes))
610b15c5
KC
211 return SIZE_MAX;
212
213 return bytes;
214}
215
e1be43d9
KC
216/**
217 * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
e1be43d9
KC
218 * @minuend: value to subtract from
219 * @subtrahend: value to subtract from @minuend
220 *
221 * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
222 * with any overflow causing the return value to be SIZE_MAX. For
223 * composition with the size_add() and size_mul() helpers, neither
224 * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
225 * The lvalue must be size_t to avoid implicit type conversion.
e0478542 226 */
e1be43d9 227static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
610b15c5
KC
228{
229 size_t bytes;
230
e1be43d9
KC
231 if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
232 check_sub_overflow(minuend, subtrahend, &bytes))
610b15c5
KC
233 return SIZE_MAX;
234
235 return bytes;
236}
237
238/**
e1be43d9 239 * array_size() - Calculate size of 2-dimensional array.
e1be43d9
KC
240 * @a: dimension one
241 * @b: dimension two
610b15c5 242 *
e1be43d9
KC
243 * Calculates size of 2-dimensional array: @a * @b.
244 *
245 * Returns: number of bytes needed to represent the array or SIZE_MAX on
246 * overflow.
610b15c5 247 */
e1be43d9
KC
248#define array_size(a, b) size_mul(a, b)
249
250/**
251 * array3_size() - Calculate size of 3-dimensional array.
e1be43d9
KC
252 * @a: dimension one
253 * @b: dimension two
254 * @c: dimension three
255 *
256 * Calculates size of 3-dimensional array: @a * @b * @c.
257 *
258 * Returns: number of bytes needed to represent the array or SIZE_MAX on
259 * overflow.
260 */
261#define array3_size(a, b, c) size_mul(size_mul(a, b), c)
610b15c5 262
b19d57d0
GS
263/**
264 * flex_array_size() - Calculate size of a flexible array member
265 * within an enclosing structure.
b19d57d0
GS
266 * @p: Pointer to the structure.
267 * @member: Name of the flexible array member.
268 * @count: Number of elements in the array.
269 *
270 * Calculates size of a flexible array of @count number of @member
271 * elements, at the end of structure @p.
272 *
273 * Return: number of bytes needed or SIZE_MAX on overflow.
274 */
275#define flex_array_size(p, member, count) \
230f6fa2
KC
276 __builtin_choose_expr(__is_constexpr(count), \
277 (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \
278 size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
e1be43d9
KC
279
280/**
281 * struct_size() - Calculate size of structure with trailing flexible array.
e1be43d9
KC
282 * @p: Pointer to the structure.
283 * @member: Name of the array member.
284 * @count: Number of elements in the array.
285 *
286 * Calculates size of memory needed for structure @p followed by an
287 * array of @count number of @member elements.
288 *
289 * Return: number of bytes needed or SIZE_MAX on overflow.
290 */
291#define struct_size(p, member, count) \
230f6fa2
KC
292 __builtin_choose_expr(__is_constexpr(count), \
293 sizeof(*(p)) + flex_array_size(p, member, count), \
294 size_add(sizeof(*(p)), flex_array_size(p, member, count)))
b19d57d0 295
f0907827 296#endif /* __LINUX_OVERFLOW_H */