Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
0002 #ifndef __LINUX_OVERFLOW_H
0003 #define __LINUX_OVERFLOW_H
0004 
0005 #include <linux/compiler.h>
0006 #include <linux/limits.h>
0007 #include <linux/const.h>
0008 
0009 /*
0010  * We need to compute the minimum and maximum values representable in a given
0011  * type. These macros may also be useful elsewhere. It would seem more obvious
0012  * to do something like:
0013  *
0014  * #define type_min(T) (T)(is_signed_type(T) ? (T)1 << (8*sizeof(T)-1) : 0)
0015  * #define type_max(T) (T)(is_signed_type(T) ? ((T)1 << (8*sizeof(T)-1)) - 1 : ~(T)0)
0016  *
0017  * Unfortunately, the middle expressions, strictly speaking, have
0018  * undefined behaviour, and at least some versions of gcc warn about
0019  * the type_max expression (but not if -fsanitize=undefined is in
0020  * effect; in that case, the warning is deferred to runtime...).
0021  *
0022  * The slightly excessive casting in type_min is to make sure the
0023  * macros also produce sensible values for the exotic type _Bool. [The
0024  * overflow checkers only almost work for _Bool, but that's
0025  * a-feature-not-a-bug, since people shouldn't be doing arithmetic on
0026  * _Bools. Besides, the gcc builtins don't allow _Bool* as third
0027  * argument.]
0028  *
0029  * Idea stolen from
0030  * https://mail-index.netbsd.org/tech-misc/2007/02/05/0000.html -
0031  * credit to Christian Biere.
0032  */
0033 #define __type_half_max(type) ((type)1 << (8*sizeof(type) - 1 - is_signed_type(type)))
0034 #define type_max(T) ((T)((__type_half_max(T) - 1) + __type_half_max(T)))
0035 #define type_min(T) ((T)((T)-type_max(T)-(T)1))
0036 
0037 /*
0038  * Avoids triggering -Wtype-limits compilation warning,
0039  * while using unsigned data types to check a < 0.
0040  */
0041 #define is_non_negative(a) ((a) > 0 || (a) == 0)
0042 #define is_negative(a) (!(is_non_negative(a)))
0043 
0044 /*
0045  * Allows for effectively applying __must_check to a macro so we can have
0046  * both the type-agnostic benefits of the macros while also being able to
0047  * enforce that the return value is, in fact, checked.
0048  */
0049 static inline bool __must_check __must_check_overflow(bool overflow)
0050 {
0051     return unlikely(overflow);
0052 }
0053 
0054 /*
0055  * For simplicity and code hygiene, the fallback code below insists on
0056  * a, b and *d having the same type (similar to the min() and max()
0057  * macros), whereas gcc's type-generic overflow checkers accept
0058  * different types. Hence we don't just make check_add_overflow an
0059  * alias for __builtin_add_overflow, but add type checks similar to
0060  * below.
0061  */
0062 #define check_add_overflow(a, b, d) __must_check_overflow(({    \
0063     typeof(a) __a = (a);            \
0064     typeof(b) __b = (b);            \
0065     typeof(d) __d = (d);            \
0066     (void) (&__a == &__b);          \
0067     (void) (&__a == __d);           \
0068     __builtin_add_overflow(__a, __b, __d);  \
0069 }))
0070 
0071 #define check_sub_overflow(a, b, d) __must_check_overflow(({    \
0072     typeof(a) __a = (a);            \
0073     typeof(b) __b = (b);            \
0074     typeof(d) __d = (d);            \
0075     (void) (&__a == &__b);          \
0076     (void) (&__a == __d);           \
0077     __builtin_sub_overflow(__a, __b, __d);  \
0078 }))
0079 
0080 #define check_mul_overflow(a, b, d) __must_check_overflow(({    \
0081     typeof(a) __a = (a);            \
0082     typeof(b) __b = (b);            \
0083     typeof(d) __d = (d);            \
0084     (void) (&__a == &__b);          \
0085     (void) (&__a == __d);           \
0086     __builtin_mul_overflow(__a, __b, __d);  \
0087 }))
0088 
0089 /** check_shl_overflow() - Calculate a left-shifted value and check overflow
0090  *
0091  * @a: Value to be shifted
0092  * @s: How many bits left to shift
0093  * @d: Pointer to where to store the result
0094  *
0095  * Computes *@d = (@a << @s)
0096  *
0097  * Returns true if '*d' cannot hold the result or when 'a << s' doesn't
0098  * make sense. Example conditions:
0099  * - 'a << s' causes bits to be lost when stored in *d.
0100  * - 's' is garbage (e.g. negative) or so large that the result of
0101  *   'a << s' is guaranteed to be 0.
0102  * - 'a' is negative.
0103  * - 'a << s' sets the sign bit, if any, in '*d'.
0104  *
0105  * '*d' will hold the results of the attempted shift, but is not
0106  * considered "safe for use" if true is returned.
0107  */
0108 #define check_shl_overflow(a, s, d) __must_check_overflow(({        \
0109     typeof(a) _a = a;                       \
0110     typeof(s) _s = s;                       \
0111     typeof(d) _d = d;                       \
0112     u64 _a_full = _a;                       \
0113     unsigned int _to_shift =                    \
0114         is_non_negative(_s) && _s < 8 * sizeof(*d) ? _s : 0;    \
0115     *_d = (_a_full << _to_shift);                   \
0116     (_to_shift != _s || is_negative(*_d) || is_negative(_a) ||  \
0117     (*_d >> _to_shift) != _a);                  \
0118 }))
0119 
0120 /**
0121  * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
0122  *
0123  * @factor1: first factor
0124  * @factor2: second factor
0125  *
0126  * Returns: calculate @factor1 * @factor2, both promoted to size_t,
0127  * with any overflow causing the return value to be SIZE_MAX. The
0128  * lvalue must be size_t to avoid implicit type conversion.
0129  */
0130 static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
0131 {
0132     size_t bytes;
0133 
0134     if (check_mul_overflow(factor1, factor2, &bytes))
0135         return SIZE_MAX;
0136 
0137     return bytes;
0138 }
0139 
0140 /**
0141  * size_add() - Calculate size_t addition with saturation at SIZE_MAX
0142  *
0143  * @addend1: first addend
0144  * @addend2: second addend
0145  *
0146  * Returns: calculate @addend1 + @addend2, both promoted to size_t,
0147  * with any overflow causing the return value to be SIZE_MAX. The
0148  * lvalue must be size_t to avoid implicit type conversion.
0149  */
0150 static inline size_t __must_check size_add(size_t addend1, size_t addend2)
0151 {
0152     size_t bytes;
0153 
0154     if (check_add_overflow(addend1, addend2, &bytes))
0155         return SIZE_MAX;
0156 
0157     return bytes;
0158 }
0159 
0160 /**
0161  * size_sub() - Calculate size_t subtraction with saturation at SIZE_MAX
0162  *
0163  * @minuend: value to subtract from
0164  * @subtrahend: value to subtract from @minuend
0165  *
0166  * Returns: calculate @minuend - @subtrahend, both promoted to size_t,
0167  * with any overflow causing the return value to be SIZE_MAX. For
0168  * composition with the size_add() and size_mul() helpers, neither
0169  * argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
0170  * The lvalue must be size_t to avoid implicit type conversion.
0171  */
0172 static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
0173 {
0174     size_t bytes;
0175 
0176     if (minuend == SIZE_MAX || subtrahend == SIZE_MAX ||
0177         check_sub_overflow(minuend, subtrahend, &bytes))
0178         return SIZE_MAX;
0179 
0180     return bytes;
0181 }
0182 
0183 /**
0184  * array_size() - Calculate size of 2-dimensional array.
0185  *
0186  * @a: dimension one
0187  * @b: dimension two
0188  *
0189  * Calculates size of 2-dimensional array: @a * @b.
0190  *
0191  * Returns: number of bytes needed to represent the array or SIZE_MAX on
0192  * overflow.
0193  */
0194 #define array_size(a, b)    size_mul(a, b)
0195 
0196 /**
0197  * array3_size() - Calculate size of 3-dimensional array.
0198  *
0199  * @a: dimension one
0200  * @b: dimension two
0201  * @c: dimension three
0202  *
0203  * Calculates size of 3-dimensional array: @a * @b * @c.
0204  *
0205  * Returns: number of bytes needed to represent the array or SIZE_MAX on
0206  * overflow.
0207  */
0208 #define array3_size(a, b, c)    size_mul(size_mul(a, b), c)
0209 
0210 /**
0211  * flex_array_size() - Calculate size of a flexible array member
0212  *                     within an enclosing structure.
0213  *
0214  * @p: Pointer to the structure.
0215  * @member: Name of the flexible array member.
0216  * @count: Number of elements in the array.
0217  *
0218  * Calculates size of a flexible array of @count number of @member
0219  * elements, at the end of structure @p.
0220  *
0221  * Return: number of bytes needed or SIZE_MAX on overflow.
0222  */
0223 #define flex_array_size(p, member, count)               \
0224     __builtin_choose_expr(__is_constexpr(count),            \
0225         (count) * sizeof(*(p)->member) + __must_be_array((p)->member),  \
0226         size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
0227 
0228 /**
0229  * struct_size() - Calculate size of structure with trailing flexible array.
0230  *
0231  * @p: Pointer to the structure.
0232  * @member: Name of the array member.
0233  * @count: Number of elements in the array.
0234  *
0235  * Calculates size of memory needed for structure @p followed by an
0236  * array of @count number of @member elements.
0237  *
0238  * Return: number of bytes needed or SIZE_MAX on overflow.
0239  */
0240 #define struct_size(p, member, count)                   \
0241     __builtin_choose_expr(__is_constexpr(count),            \
0242         sizeof(*(p)) + flex_array_size(p, member, count),   \
0243         size_add(sizeof(*(p)), flex_array_size(p, member, count)))
0244 
0245 #endif /* __LINUX_OVERFLOW_H */