Re: [PATCH] compiler.h: fix error in BUILD_BUG_ON() reporting
From: Joe Perches
Date: Tue Mar 31 2020 - 14:22:06 EST
On Tue, 2020-03-31 at 13:26 +0200, Vegard Nossum wrote:
> compiletime_assert() uses __LINE__ to create a unique function name.
> This means that if you have more than one BUILD_BUG_ON() in the same
> source line (which can happen if they appear e.g. in a macro), then
> the error message from the compiler might output the wrong condition.
>
> For this source file:
>
> #include <linux/build_bug.h>
>
> #define macro() \
> BUILD_BUG_ON(1); \
> BUILD_BUG_ON(0);
>
> void foo()
> {
> macro();
> }
>
> gcc would output:
>
> ./include/linux/compiler.h:350:38: error: call to â__compiletime_assert_9â declared with attribute error: BUILD_BUG_ON failed: 0
> _compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)
>
> However, it was not the BUILD_BUG_ON(0) that failed, so it should say 1
> instead of 0. With this patch, we use __COUNTER__ instead of __LINE__, so
> each BUILD_BUG_ON() gets a different function name and the correct
> condition is printed:
>
> ./include/linux/compiler.h:350:38: error: call to â__compiletime_assert_0â declared with attribute error: BUILD_BUG_ON failed: 1
> _compiletime_assert(condition, msg, __compiletime_assert_, __COUNTER__)
[]
> diff --git a/include/linux/compiler.h b/include/linux/compiler.h
[]
> @@ -347,7 +347,7 @@ static inline void *offset_to_ptr(const int *off)
> * compiler has support to do so.
> */
> #define compiletime_assert(condition, msg) \
> - _compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)
> + _compiletime_assert(condition, msg, __compiletime_assert_, __COUNTER__)
This might be better using something like __LINE__ ## _ ## __COUNTER__
as line # is somewhat useful to identify the specific assert in a file.