overflow.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /* SPDX-License-Identifier: GPL-2.0 OR MIT */
  2. #ifndef __LINUX_OVERFLOW_H
  3. #define __LINUX_OVERFLOW_H
  4. #include <linux/compiler.h>
  5. #include <linux/limits.h>
  6. /*
  7. * In the fallback code below, we need to compute the minimum and
  8. * maximum values representable in a given type. These macros may also
  9. * be useful elsewhere, so we provide them outside the
  10. * COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW block.
  11. *
  12. * It would seem more obvious 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 is_signed_type(type) (((type)(-1)) < (type)1)
  34. #define __type_half_max(type) ((type)1 << (8*sizeof(type) - 1 - is_signed_type(type)))
  35. #define type_max(T) ((T)((__type_half_max(T) - 1) + __type_half_max(T)))
  36. #define type_min(T) ((T)((T)-type_max(T)-(T)1))
  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. * Allows for effectively applying __must_check to a macro so we can have
  45. * both the type-agnostic benefits of the macros while also being able to
  46. * enforce that the return value is, in fact, checked.
  47. */
  48. static inline bool __must_check __must_check_overflow(bool overflow)
  49. {
  50. return unlikely(overflow);
  51. }
  52. #ifdef COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW
  53. /*
  54. * For simplicity and code hygiene, the fallback code below insists on
  55. * a, b and *d having the same type (similar to the min() and max()
  56. * macros), whereas gcc's type-generic overflow checkers accept
  57. * different types. Hence we don't just make check_add_overflow an
  58. * alias for __builtin_add_overflow, but add type checks similar to
  59. * below.
  60. */
  61. #define check_add_overflow(a, b, d) __must_check_overflow(({ \
  62. typeof(a) __a = (a); \
  63. typeof(b) __b = (b); \
  64. typeof(d) __d = (d); \
  65. (void) (&__a == &__b); \
  66. (void) (&__a == __d); \
  67. __builtin_add_overflow(__a, __b, __d); \
  68. }))
  69. #define check_sub_overflow(a, b, d) __must_check_overflow(({ \
  70. typeof(a) __a = (a); \
  71. typeof(b) __b = (b); \
  72. typeof(d) __d = (d); \
  73. (void) (&__a == &__b); \
  74. (void) (&__a == __d); \
  75. __builtin_sub_overflow(__a, __b, __d); \
  76. }))
  77. #define check_mul_overflow(a, b, d) __must_check_overflow(({ \
  78. typeof(a) __a = (a); \
  79. typeof(b) __b = (b); \
  80. typeof(d) __d = (d); \
  81. (void) (&__a == &__b); \
  82. (void) (&__a == __d); \
  83. __builtin_mul_overflow(__a, __b, __d); \
  84. }))
  85. #else
  86. /* Checking for unsigned overflow is relatively easy without causing UB. */
  87. #define __unsigned_add_overflow(a, b, d) ({ \
  88. typeof(a) __a = (a); \
  89. typeof(b) __b = (b); \
  90. typeof(d) __d = (d); \
  91. (void) (&__a == &__b); \
  92. (void) (&__a == __d); \
  93. *__d = __a + __b; \
  94. *__d < __a; \
  95. })
  96. #define __unsigned_sub_overflow(a, b, d) ({ \
  97. typeof(a) __a = (a); \
  98. typeof(b) __b = (b); \
  99. typeof(d) __d = (d); \
  100. (void) (&__a == &__b); \
  101. (void) (&__a == __d); \
  102. *__d = __a - __b; \
  103. __a < __b; \
  104. })
  105. /*
  106. * If one of a or b is a compile-time constant, this avoids a division.
  107. */
  108. #define __unsigned_mul_overflow(a, b, d) ({ \
  109. typeof(a) __a = (a); \
  110. typeof(b) __b = (b); \
  111. typeof(d) __d = (d); \
  112. (void) (&__a == &__b); \
  113. (void) (&__a == __d); \
  114. *__d = __a * __b; \
  115. __builtin_constant_p(__b) ? \
  116. __b > 0 && __a > type_max(typeof(__a)) / __b : \
  117. __a > 0 && __b > type_max(typeof(__b)) / __a; \
  118. })
  119. /*
  120. * For signed types, detecting overflow is much harder, especially if
  121. * we want to avoid UB. But the interface of these macros is such that
  122. * we must provide a result in *d, and in fact we must produce the
  123. * result promised by gcc's builtins, which is simply the possibly
  124. * wrapped-around value. Fortunately, we can just formally do the
  125. * operations in the widest relevant unsigned type (u64) and then
  126. * truncate the result - gcc is smart enough to generate the same code
  127. * with and without the (u64) casts.
  128. */
  129. /*
  130. * Adding two signed integers can overflow only if they have the same
  131. * sign, and overflow has happened iff the result has the opposite
  132. * sign.
  133. */
  134. #define __signed_add_overflow(a, b, d) ({ \
  135. typeof(a) __a = (a); \
  136. typeof(b) __b = (b); \
  137. typeof(d) __d = (d); \
  138. (void) (&__a == &__b); \
  139. (void) (&__a == __d); \
  140. *__d = (u64)__a + (u64)__b; \
  141. (((~(__a ^ __b)) & (*__d ^ __a)) \
  142. & type_min(typeof(__a))) != 0; \
  143. })
  144. /*
  145. * Subtraction is similar, except that overflow can now happen only
  146. * when the signs are opposite. In this case, overflow has happened if
  147. * the result has the opposite sign of a.
  148. */
  149. #define __signed_sub_overflow(a, b, d) ({ \
  150. typeof(a) __a = (a); \
  151. typeof(b) __b = (b); \
  152. typeof(d) __d = (d); \
  153. (void) (&__a == &__b); \
  154. (void) (&__a == __d); \
  155. *__d = (u64)__a - (u64)__b; \
  156. ((((__a ^ __b)) & (*__d ^ __a)) \
  157. & type_min(typeof(__a))) != 0; \
  158. })
  159. /*
  160. * Signed multiplication is rather hard. gcc always follows C99, so
  161. * division is truncated towards 0. This means that we can write the
  162. * overflow check like this:
  163. *
  164. * (a > 0 && (b > MAX/a || b < MIN/a)) ||
  165. * (a < -1 && (b > MIN/a || b < MAX/a) ||
  166. * (a == -1 && b == MIN)
  167. *
  168. * The redundant casts of -1 are to silence an annoying -Wtype-limits
  169. * (included in -Wextra) warning: When the type is u8 or u16, the
  170. * __b_c_e in check_mul_overflow obviously selects
  171. * __unsigned_mul_overflow, but unfortunately gcc still parses this
  172. * code and warns about the limited range of __b.
  173. */
  174. #define __signed_mul_overflow(a, b, d) ({ \
  175. typeof(a) __a = (a); \
  176. typeof(b) __b = (b); \
  177. typeof(d) __d = (d); \
  178. typeof(a) __tmax = type_max(typeof(a)); \
  179. typeof(a) __tmin = type_min(typeof(a)); \
  180. (void) (&__a == &__b); \
  181. (void) (&__a == __d); \
  182. *__d = (u64)__a * (u64)__b; \
  183. (__b > 0 && (__a > __tmax/__b || __a < __tmin/__b)) || \
  184. (__b < (typeof(__b))-1 && (__a > __tmin/__b || __a < __tmax/__b)) || \
  185. (__b == (typeof(__b))-1 && __a == __tmin); \
  186. })
  187. #define check_add_overflow(a, b, d) __must_check_overflow( \
  188. __builtin_choose_expr(is_signed_type(typeof(a)), \
  189. __signed_add_overflow(a, b, d), \
  190. __unsigned_add_overflow(a, b, d)))
  191. #define check_sub_overflow(a, b, d) __must_check_overflow( \
  192. __builtin_choose_expr(is_signed_type(typeof(a)), \
  193. __signed_sub_overflow(a, b, d), \
  194. __unsigned_sub_overflow(a, b, d)))
  195. #define check_mul_overflow(a, b, d) __must_check_overflow( \
  196. __builtin_choose_expr(is_signed_type(typeof(a)), \
  197. __signed_mul_overflow(a, b, d), \
  198. __unsigned_mul_overflow(a, b, d)))
  199. #endif /* COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW */
  200. /** check_shl_overflow() - Calculate a left-shifted value and check overflow
  201. *
  202. * @a: Value to be shifted
  203. * @s: How many bits left to shift
  204. * @d: Pointer to where to store the result
  205. *
  206. * Computes *@d = (@a << @s)
  207. *
  208. * Returns true if '*d' cannot hold the result or when 'a << s' doesn't
  209. * make sense. Example conditions:
  210. * - 'a << s' causes bits to be lost when stored in *d.
  211. * - 's' is garbage (e.g. negative) or so large that the result of
  212. * 'a << s' is guaranteed to be 0.
  213. * - 'a' is negative.
  214. * - 'a << s' sets the sign bit, if any, in '*d'.
  215. *
  216. * '*d' will hold the results of the attempted shift, but is not
  217. * considered "safe for use" if false is returned.
  218. */
  219. #define check_shl_overflow(a, s, d) __must_check_overflow(({ \
  220. typeof(a) _a = a; \
  221. typeof(s) _s = s; \
  222. typeof(d) _d = d; \
  223. u64 _a_full = _a; \
  224. unsigned int _to_shift = \
  225. is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0; \
  226. *_d = (_a_full << _to_shift); \
  227. (_to_shift != _s || is_negative(*_d) || is_negative(_a) || \
  228. (*_d >> _to_shift) != _a); \
  229. }))
  230. /**
  231. * array_size() - Calculate size of 2-dimensional array.
  232. *
  233. * @a: dimension one
  234. * @b: dimension two
  235. *
  236. * Calculates size of 2-dimensional array: @a * @b.
  237. *
  238. * Returns: number of bytes needed to represent the array or SIZE_MAX on
  239. * overflow.
  240. */
  241. static inline __must_check size_t array_size(size_t a, size_t b)
  242. {
  243. size_t bytes;
  244. if (check_mul_overflow(a, b, &bytes))
  245. return SIZE_MAX;
  246. return bytes;
  247. }
  248. /**
  249. * array3_size() - Calculate size of 3-dimensional array.
  250. *
  251. * @a: dimension one
  252. * @b: dimension two
  253. * @c: dimension three
  254. *
  255. * Calculates size of 3-dimensional array: @a * @b * @c.
  256. *
  257. * Returns: number of bytes needed to represent the array or SIZE_MAX on
  258. * overflow.
  259. */
  260. static inline __must_check size_t array3_size(size_t a, size_t b, size_t c)
  261. {
  262. size_t bytes;
  263. if (check_mul_overflow(a, b, &bytes))
  264. return SIZE_MAX;
  265. if (check_mul_overflow(bytes, c, &bytes))
  266. return SIZE_MAX;
  267. return bytes;
  268. }
  269. /*
  270. * Compute a*b+c, returning SIZE_MAX on overflow. Internal helper for
  271. * struct_size() below.
  272. */
  273. static inline __must_check size_t __ab_c_size(size_t a, size_t b, size_t c)
  274. {
  275. size_t bytes;
  276. if (check_mul_overflow(a, b, &bytes))
  277. return SIZE_MAX;
  278. if (check_add_overflow(bytes, c, &bytes))
  279. return SIZE_MAX;
  280. return bytes;
  281. }
  282. /**
  283. * struct_size() - Calculate size of structure with trailing 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 @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. __ab_c_size(count, \
  295. sizeof(*(p)->member) + __must_be_array((p)->member),\
  296. sizeof(*(p)))
  297. /**
  298. * flex_array_size() - Calculate size of a flexible array member
  299. * within an enclosing structure.
  300. *
  301. * @p: Pointer to the structure.
  302. * @member: Name of the flexible array member.
  303. * @count: Number of elements in the array.
  304. *
  305. * Calculates size of a flexible array of @count number of @member
  306. * elements, at the end of structure @p.
  307. *
  308. * Return: number of bytes needed or SIZE_MAX on overflow.
  309. */
  310. #define flex_array_size(p, member, count) \
  311. array_size(count, \
  312. sizeof(*(p)->member) + __must_be_array((p)->member))
  313. #endif /* __LINUX_OVERFLOW_H */