overflow.h 9.6 KB

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