xref: /freebsd/sys/compat/linuxkpi/common/include/linux/overflow.h (revision 3208d4ad2b8320a24af4a8293f7fd3ef9c35caa6)
1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 #ifndef _LINUXKPI_LINUX_OVERFLOW_H
3 #define _LINUXKPI_LINUX_OVERFLOW_H
4 
5 #include <linux/compiler.h>
6 #include <linux/limits.h>
7 #ifdef __linux__
8 #include <linux/const.h>
9 #endif
10 
11 /*
12  * We need to compute the minimum and maximum values representable in a given
13  * type. These macros may also be useful elsewhere. It would seem more obvious
14  * to do something like:
15  *
16  * #define type_min(T) (T)(is_signed_type(T) ? (T)1 << (8*sizeof(T)-1) : 0)
17  * #define type_max(T) (T)(is_signed_type(T) ? ((T)1 << (8*sizeof(T)-1)) - 1 : ~(T)0)
18  *
19  * Unfortunately, the middle expressions, strictly speaking, have
20  * undefined behaviour, and at least some versions of gcc warn about
21  * the type_max expression (but not if -fsanitize=undefined is in
22  * effect; in that case, the warning is deferred to runtime...).
23  *
24  * The slightly excessive casting in type_min is to make sure the
25  * macros also produce sensible values for the exotic type _Bool. [The
26  * overflow checkers only almost work for _Bool, but that's
27  * a-feature-not-a-bug, since people shouldn't be doing arithmetic on
28  * _Bools. Besides, the gcc builtins don't allow _Bool* as third
29  * argument.]
30  *
31  * Idea stolen from
32  * https://mail-index.netbsd.org/tech-misc/2007/02/05/0000.html -
33  * credit to Christian Biere.
34  */
35 #define __type_half_max(type) ((type)1 << (8*sizeof(type) - 1 - is_signed_type(type)))
36 #define type_max(T) ((T)((__type_half_max(T) - 1) + __type_half_max(T)))
37 #define type_min(T) ((T)((T)-type_max(T)-(T)1))
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  */
__must_check_overflow(bool overflow)51 static 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 0 on success.
63  *
64  * *@d holds the results of the attempted addition, but is not considered
65  * "safe for use" on a non-zero return value, which indicates that the
66  * sum has overflowed or been truncated.
67  */
68 #define check_add_overflow(a, b, d)	\
69 	__must_check_overflow(__builtin_add_overflow(a, b, d))
70 
71 /**
72  * check_sub_overflow() - Calculate subtraction with overflow checking
73  * @a: minuend; value to subtract from
74  * @b: subtrahend; value to subtract from @a
75  * @d: pointer to store difference
76  *
77  * Returns 0 on success.
78  *
79  * *@d holds the results of the attempted subtraction, but is not considered
80  * "safe for use" on a non-zero return value, which indicates that the
81  * difference has underflowed or been truncated.
82  */
83 #define check_sub_overflow(a, b, d)	\
84 	__must_check_overflow(__builtin_sub_overflow(a, b, d))
85 
86 /**
87  * check_mul_overflow() - Calculate multiplication with overflow checking
88  * @a: first factor
89  * @b: second factor
90  * @d: pointer to store product
91  *
92  * Returns 0 on success.
93  *
94  * *@d holds the results of the attempted multiplication, but is not
95  * considered "safe for use" on a non-zero return value, which indicates
96  * that the product has overflowed or been truncated.
97  */
98 #define check_mul_overflow(a, b, d)	\
99 	__must_check_overflow(__builtin_mul_overflow(a, b, d))
100 
101 /**
102  * check_shl_overflow() - Calculate a left-shifted value and check overflow
103  * @a: Value to be shifted
104  * @s: How many bits left to shift
105  * @d: Pointer to where to store the result
106  *
107  * Computes *@d = (@a << @s)
108  *
109  * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't
110  * make sense. Example conditions:
111  *
112  * - '@a << @s' causes bits to be lost when stored in *@d.
113  * - '@s' is garbage (e.g. negative) or so large that the result of
114  *   '@a << @s' is guaranteed to be 0.
115  * - '@a' is negative.
116  * - '@a << @s' sets the sign bit, if any, in '*@d'.
117  *
118  * '*@d' will hold the results of the attempted shift, but is not
119  * considered "safe for use" if true is returned.
120  */
121 #define check_shl_overflow(a, s, d) __must_check_overflow(({		\
122 	typeof(a) _a = a;						\
123 	typeof(s) _s = s;						\
124 	typeof(d) _d = d;						\
125 	u64 _a_full = _a;						\
126 	unsigned int _to_shift =					\
127 		is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0;	\
128 	*_d = (_a_full << _to_shift);					\
129 	(_to_shift != _s || is_negative(*_d) || is_negative(_a) ||	\
130 	(*_d >> _to_shift) != _a);					\
131 }))
132 
133 #define __overflows_type_constexpr(x, T) (			\
134 	is_unsigned_type(typeof(x)) ?				\
135 		(x) > type_max(typeof(T)) :			\
136 	is_unsigned_type(typeof(T)) ?				\
137 		(x) < 0 || (x) > type_max(typeof(T)) :		\
138 	(x) < type_min(typeof(T)) || (x) > type_max(typeof(T)))
139 
140 #define __overflows_type(x, T)		({	\
141 	typeof(T) v = 0;			\
142 	check_add_overflow((x), v, &v);		\
143 })
144 
145 /**
146  * overflows_type - helper for checking the overflows between value, variables,
147  *		    or data type
148  *
149  * @n: source constant value or variable to be checked
150  * @T: destination variable or data type proposed to store @x
151  *
152  * Compares the @x expression for whether or not it can safely fit in
153  * the storage of the type in @T. @x and @T can have different types.
154  * If @x is a constant expression, this will also resolve to a constant
155  * expression.
156  *
157  * Returns: true if overflow can occur, false otherwise.
158  */
159 #define overflows_type(n, T)					\
160 	__builtin_choose_expr(__is_constexpr(n),		\
161 			      __overflows_type_constexpr(n, T),	\
162 			      __overflows_type(n, T))
163 
164 /**
165  * castable_to_type - like __same_type(), but also allows for casted literals
166  *
167  * @n: variable or constant value
168  * @T: variable or data type
169  *
170  * Unlike the __same_type() macro, this allows a constant value as the
171  * first argument. If this value would not overflow into an assignment
172  * of the second argument's type, it returns true. Otherwise, this falls
173  * back to __same_type().
174  */
175 #define castable_to_type(n, T)						\
176 	__builtin_choose_expr(__is_constexpr(n),			\
177 			      !__overflows_type_constexpr(n, T),	\
178 			      __same_type(n, T))
179 
180 /**
181  * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
182  * @factor1: first factor
183  * @factor2: second factor
184  *
185  * Returns: calculate @factor1 * @factor2, both promoted to size_t,
186  * with any overflow causing the return value to be SIZE_MAX. The
187  * lvalue must be size_t to avoid implicit type conversion.
188  */
size_mul(size_t factor1,size_t factor2)189 static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
190 {
191 	size_t bytes;
192 
193 	if (check_mul_overflow(factor1, factor2, &bytes))
194 		return SIZE_MAX;
195 
196 	return bytes;
197 }
198 
199 /**
200  * size_add() - Calculate size_t addition with saturation at SIZE_MAX
201  * @addend1: first addend
202  * @addend2: second addend
203  *
204  * Returns: calculate @addend1 + @addend2, both promoted to size_t,
205  * with any overflow causing the return value to be SIZE_MAX. The
206  * lvalue must be size_t to avoid implicit type conversion.
207  */
size_add(size_t addend1,size_t addend2)208 static inline size_t __must_check size_add(size_t addend1, size_t addend2)
209 {
210 	size_t bytes;
211 
212 	if (check_add_overflow(addend1, addend2, &bytes))
213 		return SIZE_MAX;
214 
215 	return bytes;
216 }
217 
218 /**
219  * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
220  * @minuend: value to subtract from
221  * @subtrahend: value to subtract from @minuend
222  *
223  * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
224  * with any overflow causing the return value to be SIZE_MAX. For
225  * composition with the size_add() and size_mul() helpers, neither
226  * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
227  * The lvalue must be size_t to avoid implicit type conversion.
228  */
size_sub(size_t minuend,size_t subtrahend)229 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
230 {
231 	size_t bytes;
232 
233 	if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
234 	    check_sub_overflow(minuend, subtrahend, &bytes))
235 		return SIZE_MAX;
236 
237 	return bytes;
238 }
239 
240 /**
241  * array_size() - Calculate size of 2-dimensional array.
242  * @a: dimension one
243  * @b: dimension two
244  *
245  * Calculates size of 2-dimensional array: @a * @b.
246  *
247  * Returns: number of bytes needed to represent the array or SIZE_MAX on
248  * overflow.
249  */
250 #define array_size(a, b)	size_mul(a, b)
251 
252 /**
253  * array3_size() - Calculate size of 3-dimensional array.
254  * @a: dimension one
255  * @b: dimension two
256  * @c: dimension three
257  *
258  * Calculates size of 3-dimensional array: @a * @b * @c.
259  *
260  * Returns: number of bytes needed to represent the array or SIZE_MAX on
261  * overflow.
262  */
263 #define array3_size(a, b, c)	size_mul(size_mul(a, b), c)
264 
265 /**
266  * flex_array_size() - Calculate size of a flexible array member
267  *                     within an enclosing structure.
268  * @p: Pointer to the structure.
269  * @member: Name of the flexible array member.
270  * @count: Number of elements in the array.
271  *
272  * Calculates size of a flexible array of @count number of @member
273  * elements, at the end of structure @p.
274  *
275  * Return: number of bytes needed or SIZE_MAX on overflow.
276  */
277 #define flex_array_size(p, member, count)				\
278 	__builtin_choose_expr(__is_constexpr(count),			\
279 		(count) * sizeof(*(p)->member) + __must_be_array((p)->member),	\
280 		size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
281 
282 /**
283  * struct_size() - Calculate size of structure with trailing flexible array.
284  * @p: Pointer to the structure.
285  * @member: Name of the array member.
286  * @count: Number of elements in the array.
287  *
288  * Calculates size of memory needed for structure of @p followed by an
289  * array of @count number of @member elements.
290  *
291  * Return: number of bytes needed or SIZE_MAX on overflow.
292  */
293 #define struct_size(p, member, count)					\
294 	__builtin_choose_expr(__is_constexpr(count),			\
295 		sizeof(*(p)) + flex_array_size(p, member, count),	\
296 		size_add(sizeof(*(p)), flex_array_size(p, member, count)))
297 
298 /**
299  * struct_size_t() - Calculate size of structure with trailing flexible array
300  * @type: structure type name.
301  * @member: Name of the array member.
302  * @count: Number of elements in the array.
303  *
304  * Calculates size of memory needed for structure @type followed by an
305  * array of @count number of @member elements. Prefer using struct_size()
306  * when possible instead, to keep calculations associated with a specific
307  * instance variable of type @type.
308  *
309  * Return: number of bytes needed or SIZE_MAX on overflow.
310  */
311 #define struct_size_t(type, member, count)					\
312 	struct_size((type *)NULL, member, count)
313 
314 /**
315  * _DEFINE_FLEX() - helper macro for DEFINE_FLEX() family.
316  * Enables caller macro to pass (different) initializer.
317  *
318  * @type: structure type name, including "struct" keyword.
319  * @name: Name for a variable to define.
320  * @member: Name of the array member.
321  * @count: Number of elements in the array; must be compile-time const.
322  * @initializer: initializer expression (could be empty for no init).
323  */
324 #define _DEFINE_FLEX(type, name, member, count, initializer)			\
325 	_Static_assert(__builtin_constant_p(count),				\
326 		       "onstack flex array members require compile-time const count"); \
327 	union {									\
328 		u8 bytes[struct_size_t(type, member, count)];			\
329 		type obj;							\
330 	} name##_u initializer;							\
331 	type *name = (type *)&name##_u
332 
333 /**
334  * DEFINE_FLEX() - Define an on-stack instance of structure with a trailing
335  * flexible array member.
336  *
337  * @type: structure type name, including "struct" keyword.
338  * @name: Name for a variable to define.
339  * @member: Name of the array member.
340  * @count: Number of elements in the array; must be compile-time const.
341  *
342  * Define a zeroed, on-stack, instance of @type structure with a trailing
343  * flexible array member.
344  * Use __struct_size(@name) to get compile-time size of it afterwards.
345  */
346 #define DEFINE_FLEX(type, name, member, count)			\
347 	_DEFINE_FLEX(type, name, member, count, = {})
348 
349 #endif /* _LINUXKPI_LINUX_OVERFLOW_H */
350