Skip to content
This repository has been archived by the owner on Nov 21, 2022. It is now read-only.

Commit

Permalink
minmax: sanity check constant bounds when clamping
Browse files Browse the repository at this point in the history
The clamp family of functions only makes sense if hi>=lo.  If hi and lo
are compile-time constants, then raise a build error.  Doing so has
already caught buggy code.  This also introduces the infrastructure to
improve the clamping function in subsequent commits.

Link: https://lkml.kernel.org/r/[email protected]
Signed-off-by: Jason A. Donenfeld <[email protected]>
Reviewed-by: Andy Shevchenko <[email protected]>
Cc: Kees Cook <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
  • Loading branch information
zx2c4 authored and akpm00 committed Nov 15, 2022
1 parent 1f2e79e commit abb4014
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions include/linux/minmax.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,28 @@
__cmp(x, y, op), \
__cmp_once(x, y, __UNIQUE_ID(__x), __UNIQUE_ID(__y), op))

#define __clamp(val, lo, hi) \
__cmp(__cmp(val, lo, >), hi, <)

#define __clamp_once(val, lo, hi, unique_val, unique_lo, unique_hi) ({ \
typeof(val) unique_val = (val); \
typeof(lo) unique_lo = (lo); \
typeof(hi) unique_hi = (hi); \
__clamp(unique_val, unique_lo, unique_hi); })

#define __clamp_input_check(lo, hi) \
(BUILD_BUG_ON_ZERO(__builtin_choose_expr( \
__is_constexpr((lo) > (hi)), (lo) > (hi), false)))

#define __careful_clamp(val, lo, hi) ({ \
__clamp_input_check(lo, hi) + \
__builtin_choose_expr(__typecheck(val, lo) && __typecheck(val, hi) && \
__typecheck(hi, lo) && __is_constexpr(val) && \
__is_constexpr(lo) && __is_constexpr(hi), \
__clamp(val, lo, hi), \
__clamp_once(val, lo, hi, __UNIQUE_ID(__val), \
__UNIQUE_ID(__lo), __UNIQUE_ID(__hi))); })

/**
* min - return minimum of two values of the same or compatible types
* @x: first value
Expand Down Expand Up @@ -86,7 +108,7 @@
* This macro does strict typechecking of @lo/@hi to make sure they are of the
* same type as @val. See the unnecessary pointer comparisons.
*/
#define clamp(val, lo, hi) min((typeof(val))max(val, lo), hi)
#define clamp(val, lo, hi) __careful_clamp(val, lo, hi)

/*
* ..and if you can't take the strict
Expand Down Expand Up @@ -121,7 +143,7 @@
* This macro does no typechecking and uses temporary variables of type
* @type to make all the comparisons.
*/
#define clamp_t(type, val, lo, hi) min_t(type, max_t(type, val, lo), hi)
#define clamp_t(type, val, lo, hi) __careful_clamp((type)(val), (type)(lo), (type)(hi))

/**
* clamp_val - return a value clamped to a given range using val's type
Expand Down

0 comments on commit abb4014

Please sign in to comment.