Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

minmax: relax check to allow comparison between unsigned arguments and signed constants

Allow (for example) min(unsigned_var, 20).

The opposite min(signed_var, 20u) is still errored.

Since a comparison between signed and unsigned never makes the unsigned
value negative it is only necessary to adjust the __types_ok() test.

Link: https://lkml.kernel.org/r/633b64e2f39e46bb8234809c5595b8c7@AcuMS.aculab.com
Signed-off-by: David Laight <david.laight@aculab.com>
Cc: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Cc: Christoph Hellwig <hch@infradead.org>
Cc: Jason A. Donenfeld <Jason@zx2c4.com>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>

authored by

David Laight and committed by
Andrew Morton
867046cc 4ead534f

+17 -7
+17 -7
include/linux/minmax.h
··· 10 10 /* 11 11 * min()/max()/clamp() macros must accomplish three things: 12 12 * 13 - * - avoid multiple evaluations of the arguments (so side-effects like 13 + * - Avoid multiple evaluations of the arguments (so side-effects like 14 14 * "x++" happen only once) when non-constant. 15 - * - perform signed v unsigned type-checking (to generate compile 16 - * errors instead of nasty runtime surprises). 17 - * - retain result as a constant expressions when called with only 15 + * - Retain result as a constant expressions when called with only 18 16 * constant expressions (to avoid tripping VLA warnings in stack 19 17 * allocation usage). 18 + * - Perform signed v unsigned type-checking (to generate compile 19 + * errors instead of nasty runtime surprises). 20 + * - Unsigned char/short are always promoted to signed int and can be 21 + * compared against signed or unsigned arguments. 22 + * - Unsigned arguments can be compared against non-negative signed constants. 23 + * - Comparison of a signed argument against an unsigned constant fails 24 + * even if the constant is below __INT_MAX__ and could be cast to int. 20 25 */ 21 26 #define __typecheck(x, y) \ 22 27 (!!(sizeof((typeof(x) *)1 == (typeof(y) *)1))) ··· 31 26 __builtin_choose_expr(__is_constexpr(is_signed_type(typeof(x))), \ 32 27 is_signed_type(typeof(x)), 0) 33 28 34 - #define __types_ok(x, y) \ 35 - (__is_signed(x) == __is_signed(y) || \ 36 - __is_signed((x) + 0) == __is_signed((y) + 0)) 29 + /* True for a non-negative signed int constant */ 30 + #define __is_noneg_int(x) \ 31 + (__builtin_choose_expr(__is_constexpr(x) && __is_signed(x), x, -1) >= 0) 32 + 33 + #define __types_ok(x, y) \ 34 + (__is_signed(x) == __is_signed(y) || \ 35 + __is_signed((x) + 0) == __is_signed((y) + 0) || \ 36 + __is_noneg_int(x) || __is_noneg_int(y)) 37 37 38 38 #define __cmp_op_min < 39 39 #define __cmp_op_max >