Re: [PATCH v3] kernel.h: Skip single-eval logic on literals in min()/max()

From: Andrew Morton
Date: Mon Mar 12 2018 - 18:55:35 EST


On Fri, 9 Mar 2018 17:30:15 -0800 Kees Cook <keescook@xxxxxxxxxxxx> wrote:

> > It's one reason why I wondered if simplifying the expression to have
> > just that single __builtin_constant_p() might not end up working..
>
> Yeah, it seems like it doesn't bail out as "false" for complex
> expressions given to __builtin_constant_p().
>
> If no magic solution, then which of these?
>
> - go back to my original "multi-eval max only for constants" macro (meh)
> - add gcc version checks around this and similarly for -Wvla in the future (eww)
> - raise gcc version (yikes)

Replacing the __builtin_choose_expr() with ?: works of course. What
will be the runtime effects?

I tried replacing

__builtin_choose_expr(__builtin_constant_p(x) &&
__builtin_constant_p(y),

with

__builtin_choose_expr(__builtin_constant_p(x + y),

but no success.

I'm not sure what else to try to trick gcc into working.

--- a/include/linux/kernel.h~kernelh-skip-single-eval-logic-on-literals-in-min-max-v3-fix
+++ a/include/linux/kernel.h
@@ -804,13 +804,10 @@ static inline void ftrace_dump(enum ftra
* accidental VLA.
*/
#define __min(t1, t2, x, y) \
- __builtin_choose_expr(__builtin_constant_p(x) && \
- __builtin_constant_p(y), \
- (t1)(x) < (t2)(y) ? (t1)(x) : (t2)(y), \
- __single_eval_min(t1, t2, \
- __UNIQUE_ID(min1_), \
- __UNIQUE_ID(min2_), \
- x, y))
+ ((__builtin_constant_p(x) && __builtin_constant_p(y)) ? \
+ ((t1)(x) < (t2)(y) ? (t1)(x) : (t2)(y)) : \
+ (__single_eval_min(t1, t2, __UNIQUE_ID(min1_), \
+ __UNIQUE_ID(min2_), x, y)))

/**
* min - return minimum of two values of the same or compatible types
@@ -826,13 +823,11 @@ static inline void ftrace_dump(enum ftra
max1 > max2 ? max1 : max2; })

#define __max(t1, t2, x, y) \
- __builtin_choose_expr(__builtin_constant_p(x) && \
- __builtin_constant_p(y), \
- (t1)(x) > (t2)(y) ? (t1)(x) : (t2)(y), \
- __single_eval_max(t1, t2, \
- __UNIQUE_ID(max1_), \
- __UNIQUE_ID(max2_), \
- x, y))
+ ((__builtin_constant_p(x) && __builtin_constant_p(y)) ? \
+ ((t1)(x) > (t2)(y) ? (t1)(x) : (t2)(y)) : \
+ (__single_eval_max(t1, t2, __UNIQUE_ID(max1_), \
+ __UNIQUE_ID(max2_), x, y)))
+
/**
* max - return maximum of two values of the same or compatible types
* @x: first value
_