1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 #ifndef __LINUX_OVERFLOW_H
3 #define __LINUX_OVERFLOW_H
4
5 #include <stdbool.h>
6 #include <stdint.h>
7
8 #define likely(x) __builtin_expect(!!(x), 1)
9 #define unlikely(x) __builtin_expect(!!(x), 0)
10
11 #define __must_check __attribute__((__warn_unused_result__))
12
13 /*
14 * We need to compute the minimum and maximum values representable in a given
15 * type. These macros may also be useful elsewhere. It would seem more obvious
16 * to do something like:
17 *
18 * #define type_min(T) (T)(is_signed_type(T) ? (T)1 << (8*sizeof(T)-1) : 0)
19 * #define type_max(T) (T)(is_signed_type(T) ? ((T)1 << (8*sizeof(T)-1)) - 1 : ~(T)0)
20 *
21 * Unfortunately, the middle expressions, strictly speaking, have
22 * undefined behaviour, and at least some versions of gcc warn about
23 * the type_max expression (but not if -fsanitize=undefined is in
24 * effect; in that case, the warning is deferred to runtime...).
25 *
26 * The slightly excessive casting in type_min is to make sure the
27 * macros also produce sensible values for the exotic type _Bool. [The
28 * overflow checkers only almost work for _Bool, but that's
29 * a-feature-not-a-bug, since people shouldn't be doing arithmetic on
30 * _Bools. Besides, the gcc builtins don't allow _Bool* as third
31 * argument.]
32 *
33 * Idea stolen from
34 * https://mail-index.netbsd.org/tech-misc/2007/02/05/0000.html -
35 * credit to Christian Biere.
36 */
37 #define is_signed_type(type) (((type)(-1)) < (type)1)
38 #define __type_half_max(type) ((type)1 << (8*sizeof(type) - 1 - is_signed_type(type)))
39 #define type_max(T) ((T)((__type_half_max(T) - 1) + __type_half_max(T)))
40 #define type_min(T) ((T)((T)-type_max(T)-(T)1))
41
42 /*
43 * Avoids triggering -Wtype-limits compilation warning,
44 * while using unsigned data types to check a < 0.
45 */
46 #define is_non_negative(a) ((a) > 0 || (a) == 0)
47 #define is_negative(a) (!(is_non_negative(a)))
48
49 /*
50 * Allows for effectively applying __must_check to a macro so we can have
51 * both the type-agnostic benefits of the macros while also being able to
52 * enforce that the return value is, in fact, checked.
53 */
__must_check_overflow(bool overflow)54 static inline bool __must_check __must_check_overflow(bool overflow)
55 {
56 return unlikely(overflow);
57 }
58
59 /*
60 * For simplicity and code hygiene, the fallback code below insists on
61 * a, b and *d having the same type (similar to the min() and max()
62 * macros), whereas gcc's type-generic overflow checkers accept
63 * different types. Hence we don't just make check_add_overflow an
64 * alias for __builtin_add_overflow, but add type checks similar to
65 * below.
66 */
67 #define check_add_overflow(a, b, d) __must_check_overflow(({ \
68 typeof(a) __a = (a); \
69 typeof(b) __b = (b); \
70 typeof(d) __d = (d); \
71 (void) (&__a == &__b); \
72 (void) (&__a == __d); \
73 __builtin_add_overflow(__a, __b, __d); \
74 }))
75
76 #define check_sub_overflow(a, b, d) __must_check_overflow(({ \
77 typeof(a) __a = (a); \
78 typeof(b) __b = (b); \
79 typeof(d) __d = (d); \
80 (void) (&__a == &__b); \
81 (void) (&__a == __d); \
82 __builtin_sub_overflow(__a, __b, __d); \
83 }))
84
85 #define check_mul_overflow(a, b, d) __must_check_overflow(({ \
86 typeof(a) __a = (a); \
87 typeof(b) __b = (b); \
88 typeof(d) __d = (d); \
89 (void) (&__a == &__b); \
90 (void) (&__a == __d); \
91 __builtin_mul_overflow(__a, __b, __d); \
92 }))
93
94 /** check_shl_overflow() - Calculate a left-shifted value and check overflow
95 *
96 * @a: Value to be shifted
97 * @s: How many bits left to shift
98 * @d: Pointer to where to store the result
99 *
100 * Computes *@d = (@a << @s)
101 *
102 * Returns true if '*d' cannot hold the result or when 'a << s' doesn't
103 * make sense. Example conditions:
104 * - 'a << s' causes bits to be lost when stored in *d.
105 * - 's' is garbage (e.g. negative) or so large that the result of
106 * 'a << s' is guaranteed to be 0.
107 * - 'a' is negative.
108 * - 'a << s' sets the sign bit, if any, in '*d'.
109 *
110 * '*d' will hold the results of the attempted shift, but is not
111 * considered "safe for use" if true is returned.
112 */
113 #define check_shl_overflow(a, s, d) __must_check_overflow(({ \
114 typeof(a) _a = a; \
115 typeof(s) _s = s; \
116 typeof(d) _d = d; \
117 u64 _a_full = _a; \
118 unsigned int _to_shift = \
119 is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0; \
120 *_d = (_a_full << _to_shift); \
121 (_to_shift != _s || is_negative(*_d) || is_negative(_a) || \
122 (*_d >> _to_shift) != _a); \
123 }))
124
125 /**
126 * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
127 *
128 * @factor1: first factor
129 * @factor2: second factor
130 *
131 * Returns: calculate @factor1 * @factor2, both promoted to size_t,
132 * with any overflow causing the return value to be SIZE_MAX. The
133 * lvalue must be size_t to avoid implicit type conversion.
134 */
size_mul(size_t factor1,size_t factor2)135 static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
136 {
137 size_t bytes;
138
139 if (check_mul_overflow(factor1, factor2, &bytes))
140 return SIZE_MAX;
141
142 return bytes;
143 }
144
145 /**
146 * size_add() - Calculate size_t addition with saturation at SIZE_MAX
147 *
148 * @addend1: first addend
149 * @addend2: second addend
150 *
151 * Returns: calculate @addend1 + @addend2, both promoted to size_t,
152 * with any overflow causing the return value to be SIZE_MAX. The
153 * lvalue must be size_t to avoid implicit type conversion.
154 */
size_add(size_t addend1,size_t addend2)155 static inline size_t __must_check size_add(size_t addend1, size_t addend2)
156 {
157 size_t bytes;
158
159 if (check_add_overflow(addend1, addend2, &bytes))
160 return SIZE_MAX;
161
162 return bytes;
163 }
164
165 /**
166 * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
167 *
168 * @minuend: value to subtract from
169 * @subtrahend: value to subtract from @minuend
170 *
171 * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
172 * with any overflow causing the return value to be SIZE_MAX. For
173 * composition with the size_add() and size_mul() helpers, neither
174 * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
175 * The lvalue must be size_t to avoid implicit type conversion.
176 */
size_sub(size_t minuend,size_t subtrahend)177 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
178 {
179 size_t bytes;
180
181 if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
182 check_sub_overflow(minuend, subtrahend, &bytes))
183 return SIZE_MAX;
184
185 return bytes;
186 }
187
188 /**
189 * array_size() - Calculate size of 2-dimensional array.
190 *
191 * @a: dimension one
192 * @b: dimension two
193 *
194 * Calculates size of 2-dimensional array: @a * @b.
195 *
196 * Returns: number of bytes needed to represent the array or SIZE_MAX on
197 * overflow.
198 */
199 #define array_size(a, b) size_mul(a, b)
200
201 /**
202 * array3_size() - Calculate size of 3-dimensional array.
203 *
204 * @a: dimension one
205 * @b: dimension two
206 * @c: dimension three
207 *
208 * Calculates size of 3-dimensional array: @a * @b * @c.
209 *
210 * Returns: number of bytes needed to represent the array or SIZE_MAX on
211 * overflow.
212 */
213 #define array3_size(a, b, c) size_mul(size_mul(a, b), c)
214
215 /**
216 * flex_array_size() - Calculate size of a flexible array member
217 * within an enclosing structure.
218 *
219 * @p: Pointer to the structure.
220 * @member: Name of the flexible array member.
221 * @count: Number of elements in the array.
222 *
223 * Calculates size of a flexible array of @count number of @member
224 * elements, at the end of structure @p.
225 *
226 * Return: number of bytes needed or SIZE_MAX on overflow.
227 */
228 #define flex_array_size(p, member, count) \
229 __builtin_choose_expr(__is_constexpr(count), \
230 (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \
231 size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
232
233 /**
234 * struct_size() - Calculate size of structure with trailing flexible array.
235 *
236 * @p: Pointer to the structure.
237 * @member: Name of the array member.
238 * @count: Number of elements in the array.
239 *
240 * Calculates size of memory needed for structure @p followed by an
241 * array of @count number of @member elements.
242 *
243 * Return: number of bytes needed or SIZE_MAX on overflow.
244 */
245 #define struct_size(p, member, count) \
246 __builtin_choose_expr(__is_constexpr(count), \
247 sizeof(*(p)) + flex_array_size(p, member, count), \
248 size_add(sizeof(*(p)), flex_array_size(p, member, count)))
249
250 #endif /* __LINUX_OVERFLOW_H */
251