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_min(T) ((T)((T)-type_max(T)-(T)1)) 36 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))) 43 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 */ 49 static inline bool __must_check __must_check_overflow(bool overflow) 50 { 51 return unlikely(overflow); 52 } 53 54 /** 55 * check_add_overflow() - Calculate addition with overflow checking 56 * @a: first addend 57 * @b: second addend 58 * @d: pointer to store sum 59 * 60 * Returns true on wrap-around, false otherwise. 61 * 62 * *@d holds the results of the attempted addition, regardless of whether 63 * wrap-around occurred. 64 */ 65 #define check_add_overflow(a, b, d) \ 66 __must_check_overflow(__builtin_add_overflow(a, b, d)) 67 68 /** 69 * check_sub_overflow() - Calculate subtraction with overflow checking 70 * @a: minuend; value to subtract from 71 * @b: subtrahend; value to subtract from @a 72 * @d: pointer to store difference 73 * 74 * Returns true on wrap-around, false otherwise. 75 * 76 * *@d holds the results of the attempted subtraction, regardless of whether 77 * wrap-around occurred. 78 */ 79 #define check_sub_overflow(a, b, d) \ 80 __must_check_overflow(__builtin_sub_overflow(a, b, d)) 81 82 /** 83 * check_mul_overflow() - Calculate multiplication with overflow checking 84 * @a: first factor 85 * @b: second factor 86 * @d: pointer to store product 87 * 88 * Returns true on wrap-around, false otherwise. 89 * 90 * *@d holds the results of the attempted multiplication, regardless of whether 91 * wrap-around occurred. 92 */ 93 #define check_mul_overflow(a, b, d) \ 94 __must_check_overflow(__builtin_mul_overflow(a, b, d)) 95 96 /** 97 * check_shl_overflow() - Calculate a left-shifted value and check overflow 98 * @a: Value to be shifted 99 * @s: How many bits left to shift 100 * @d: Pointer to where to store the result 101 * 102 * Computes *@d = (@a << @s) 103 * 104 * Returns true if '*@d' cannot hold the result or when '@a << @s' doesn't 105 * make sense. Example conditions: 106 * 107 * - '@a << @s' causes bits to be lost when stored in *@d. 108 * - '@s' is garbage (e.g. negative) or so large that the result of 109 * '@a << @s' is guaranteed to be 0. 110 * - '@a' is negative. 111 * - '@a << @s' sets the sign bit, if any, in '*@d'. 112 * 113 * '*@d' will hold the results of the attempted shift, but is not 114 * considered "safe for use" if true is returned. 115 */ 116 #define check_shl_overflow(a, s, d) __must_check_overflow(({ \ 117 typeof(a) _a = a; \ 118 typeof(s) _s = s; \ 119 typeof(d) _d = d; \ 120 u64 _a_full = _a; \ 121 unsigned int _to_shift = \ 122 is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0; \ 123 *_d = (_a_full << _to_shift); \ 124 (_to_shift != _s || is_negative(*_d) || is_negative(_a) || \ 125 (*_d >> _to_shift) != _a); \ 126 })) 127 128 #define __overflows_type_constexpr(x, T) ( \ 129 is_unsigned_type(typeof(x)) ? \ 130 (x) > type_max(typeof(T)) : \ 131 is_unsigned_type(typeof(T)) ? \ 132 (x) < 0 || (x) > type_max(typeof(T)) : \ 133 (x) < type_min(typeof(T)) || (x) > type_max(typeof(T))) 134 135 #define __overflows_type(x, T) ({ \ 136 typeof(T) v = 0; \ 137 check_add_overflow((x), v, &v); \ 138 }) 139 140 /** 141 * overflows_type - helper for checking the overflows between value, variables, 142 * or data type 143 * 144 * @n: source constant value or variable to be checked 145 * @T: destination variable or data type proposed to store @x 146 * 147 * Compares the @x expression for whether or not it can safely fit in 148 * the storage of the type in @T. @x and @T can have different types. 149 * If @x is a constant expression, this will also resolve to a constant 150 * expression. 151 * 152 * Returns: true if overflow can occur, false otherwise. 153 */ 154 #define overflows_type(n, T) \ 155 __builtin_choose_expr(__is_constexpr(n), \ 156 __overflows_type_constexpr(n, T), \ 157 __overflows_type(n, T)) 158 159 /** 160 * castable_to_type - like __same_type(), but also allows for casted literals 161 * 162 * @n: variable or constant value 163 * @T: variable or data type 164 * 165 * Unlike the __same_type() macro, this allows a constant value as the 166 * first argument. If this value would not overflow into an assignment 167 * of the second argument's type, it returns true. Otherwise, this falls 168 * back to __same_type(). 169 */ 170 #define castable_to_type(n, T) \ 171 __builtin_choose_expr(__is_constexpr(n), \ 172 !__overflows_type_constexpr(n, T), \ 173 __same_type(n, T)) 174 175 /** 176 * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX 177 * @factor1: first factor 178 * @factor2: second factor 179 * 180 * Returns: calculate @factor1 * @factor2, both promoted to size_t, 181 * with any overflow causing the return value to be SIZE_MAX. The 182 * lvalue must be size_t to avoid implicit type conversion. 183 */ 184 static inline size_t __must_check size_mul(size_t factor1, size_t factor2) 185 { 186 size_t bytes; 187 188 if (check_mul_overflow(factor1, factor2, &bytes)) 189 return SIZE_MAX; 190 191 return bytes; 192 } 193 194 /** 195 * size_add() - Calculate size_t addition with saturation at SIZE_MAX 196 * @addend1: first addend 197 * @addend2: second addend 198 * 199 * Returns: calculate @addend1 + @addend2, both promoted to size_t, 200 * with any overflow causing the return value to be SIZE_MAX. The 201 * lvalue must be size_t to avoid implicit type conversion. 202 */ 203 static inline size_t __must_check size_add(size_t addend1, size_t addend2) 204 { 205 size_t bytes; 206 207 if (check_add_overflow(addend1, addend2, &bytes)) 208 return SIZE_MAX; 209 210 return bytes; 211 } 212 213 /** 214 * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX 215 * @minuend: value to subtract from 216 * @subtrahend: value to subtract from @minuend 217 * 218 * Returns: calculate @minuend - @subtrahend, both promoted to size_t, 219 * with any overflow causing the return value to be SIZE_MAX. For 220 * composition with the size_add() and size_mul() helpers, neither 221 * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX). 222 * The lvalue must be size_t to avoid implicit type conversion. 223 */ 224 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend) 225 { 226 size_t bytes; 227 228 if (minuend == SIZE_MAX || subtrahend == SIZE_MAX || 229 check_sub_overflow(minuend, subtrahend, &bytes)) 230 return SIZE_MAX; 231 232 return bytes; 233 } 234 235 /** 236 * array_size() - Calculate size of 2-dimensional array. 237 * @a: dimension one 238 * @b: dimension two 239 * 240 * Calculates size of 2-dimensional array: @a * @b. 241 * 242 * Returns: number of bytes needed to represent the array or SIZE_MAX on 243 * overflow. 244 */ 245 #define array_size(a, b) size_mul(a, b) 246 247 /** 248 * array3_size() - Calculate size of 3-dimensional array. 249 * @a: dimension one 250 * @b: dimension two 251 * @c: dimension three 252 * 253 * Calculates size of 3-dimensional array: @a * @b * @c. 254 * 255 * Returns: number of bytes needed to represent the array or SIZE_MAX on 256 * overflow. 257 */ 258 #define array3_size(a, b, c) size_mul(size_mul(a, b), c) 259 260 /** 261 * flex_array_size() - Calculate size of a flexible array member 262 * within an enclosing structure. 263 * @p: Pointer to the structure. 264 * @member: Name of the flexible array member. 265 * @count: Number of elements in the array. 266 * 267 * Calculates size of a flexible array of @count number of @member 268 * elements, at the end of structure @p. 269 * 270 * Return: number of bytes needed or SIZE_MAX on overflow. 271 */ 272 #define flex_array_size(p, member, count) \ 273 __builtin_choose_expr(__is_constexpr(count), \ 274 (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \ 275 size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member))) 276 277 /** 278 * struct_size() - Calculate size of structure with trailing flexible array. 279 * @p: Pointer to the structure. 280 * @member: Name of the array member. 281 * @count: Number of elements in the array. 282 * 283 * Calculates size of memory needed for structure of @p followed by an 284 * array of @count number of @member elements. 285 * 286 * Return: number of bytes needed or SIZE_MAX on overflow. 287 */ 288 #define struct_size(p, member, count) \ 289 __builtin_choose_expr(__is_constexpr(count), \ 290 sizeof(*(p)) + flex_array_size(p, member, count), \ 291 size_add(sizeof(*(p)), flex_array_size(p, member, count))) 292 293 /** 294 * struct_size_t() - Calculate size of structure with trailing flexible array 295 * @type: structure type name. 296 * @member: Name of the array member. 297 * @count: Number of elements in the array. 298 * 299 * Calculates size of memory needed for structure @type followed by an 300 * array of @count number of @member elements. Prefer using struct_size() 301 * when possible instead, to keep calculations associated with a specific 302 * instance variable of type @type. 303 * 304 * Return: number of bytes needed or SIZE_MAX on overflow. 305 */ 306 #define struct_size_t(type, member, count) \ 307 struct_size((type *)NULL, member, count) 308 309 /** 310 * _DEFINE_FLEX() - helper macro for DEFINE_FLEX() family. 311 * Enables caller macro to pass (different) initializer. 312 * 313 * @type: structure type name, including "struct" keyword. 314 * @name: Name for a variable to define. 315 * @member: Name of the array member. 316 * @count: Number of elements in the array; must be compile-time const. 317 * @initializer: initializer expression (could be empty for no init). 318 */ 319 #define _DEFINE_FLEX(type, name, member, count, initializer) \ 320 _Static_assert(__builtin_constant_p(count), \ 321 "onstack flex array members require compile-time const count"); \ 322 union { \ 323 u8 bytes[struct_size_t(type, member, count)]; \ 324 type obj; \ 325 } name##_u initializer; \ 326 type *name = (type *)&name##_u 327 328 /** 329 * DEFINE_FLEX() - Define an on-stack instance of structure with a trailing 330 * flexible array member. 331 * 332 * @type: structure type name, including "struct" keyword. 333 * @name: Name for a variable to define. 334 * @member: Name of the array member. 335 * @count: Number of elements in the array; must be compile-time const. 336 * 337 * Define a zeroed, on-stack, instance of @type structure with a trailing 338 * flexible array member. 339 * Use __struct_size(@name) to get compile-time size of it afterwards. 340 */ 341 #define DEFINE_FLEX(type, name, member, count) \ 342 _DEFINE_FLEX(type, name, member, count, = {}) 343 344 #endif /* __LINUX_OVERFLOW_H */ 345