Re: [PATCH] bitfield.h: don't compile-time validate _val in FIELD_FIT

From: Alex Elder
Date: Tue Jul 07 2020 - 18:43:09 EST


On 7/7/20 4:16 PM, Nick Desaulniers wrote:
> From: Jakub Kicinski <kuba@xxxxxxxxxx>
>
> When ur_load_imm_any() is inlined into jeq_imm(), it's possible for the
> compiler to deduce a case where _val can only have the value of -1 at
> compile time. Specifically,
>
> /* struct bpf_insn: _s32 imm */
> u64 imm = insn->imm; /* sign extend */
> if (imm >> 32) { /* non-zero only if insn->imm is negative */
> /* inlined from ur_load_imm_any */
> u32 __imm = imm >> 32; /* therefore, always 0xffffffff */
> if (__builtin_constant_p(__imm) && __imm > 255)
> compiletime_assert_XXX()
>
> This can result in tripping a BUILD_BUG_ON() in __BF_FIELD_CHECK() that
> checks that a given value is representable in one byte (interpreted as
> unsigned).

Why does FIELD_FIT() pass an unsigned long long value as the second
argument to __BF_FIELD_CHECK()? Could it pass (typeof(_mask))0 instead?
It wouldn't fix this particular case, because UR_REG_IMM_MAX is also
defined with that type. But (without working through this in more
detail) it seems like there might be a solution that preserves the
compile-time checking.

A second comment about this is that it might be nice to break
__BF_FIELD_CHECK() into the parts that verify the mask (which
could be used by FIELD_FIT() here) and the parts that verify
other things.

That's all--just questions, I have no problem with the patch...

-Alex




> FIELD_FIT() should return true or false at runtime for whether a value
> can fit for not. Don't break the build over a value that's too large for
> the mask. We'd prefer to keep the inlining and compiler optimizations
> though we know this case will always return false.
>
> Cc: stable@xxxxxxxxxxxxxxx
> Link: https://lore.kernel.org/kernel-hardening/CAK7LNASvb0UDJ0U5wkYYRzTAdnEs64HjXpEUL7d=V0CXiAXcNw@xxxxxxxxxxxxxx/
> Reported-by: Masahiro Yamada <masahiroy@xxxxxxxxxx>
> Debugged-by: Sami Tolvanen <samitolvanen@xxxxxxxxxx>
> Signed-off-by: Jakub Kicinski <kuba@xxxxxxxxxx>
> Signed-off-by: Nick Desaulniers <ndesaulniers@xxxxxxxxxx>
> ---
> include/linux/bitfield.h | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/include/linux/bitfield.h b/include/linux/bitfield.h
> index 48ea093ff04c..4e035aca6f7e 100644
> --- a/include/linux/bitfield.h
> +++ b/include/linux/bitfield.h
> @@ -77,7 +77,7 @@
> */
> #define FIELD_FIT(_mask, _val) \
> ({ \
> - __BF_FIELD_CHECK(_mask, 0ULL, _val, "FIELD_FIT: "); \
> + __BF_FIELD_CHECK(_mask, 0ULL, 0ULL, "FIELD_FIT: "); \
> !((((typeof(_mask))_val) << __bf_shf(_mask)) & ~(_mask)); \
> })
>
>