From 48252db2a25ebf891131dafdbb1b68ded8f47947 Mon Sep 17 00:00:00 2001 From: Eugene Syromyatnikov Date: Sat, 29 Oct 2016 05:24:08 +0300 Subject: [PATCH] defs: add check for argument being array to ARRAY_SIZE macro * gcc_compat.h [GNUC_PREREQ(3, 0)] (BUILD_BUG_ON_ZERO): New macro. (SAME_TYPE, MUST_BE_ARRAY): Likewise. * defs.h (ARRAY_SIZE): Add MUST_BE_ARRAY for build-time type check. --- defs.h | 2 +- gcc_compat.h | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/defs.h b/defs.h index 5eb9b108..b2907403 100644 --- a/defs.h +++ b/defs.h @@ -73,7 +73,7 @@ extern char *stpcpy(char *dst, const char *src); (offsetof(type, member) + sizeof(((type *)NULL)->member)) #endif -#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]) + MUST_BE_ARRAY(a)) /* macros */ #ifndef MAX diff --git a/gcc_compat.h b/gcc_compat.h index 908df16c..9e6c233f 100644 --- a/gcc_compat.h +++ b/gcc_compat.h @@ -52,6 +52,16 @@ # define ATTRIBUTE_PACKED /* empty */ #endif +#if GNUC_PREREQ(3, 0) +# define SAME_TYPE(x, y) __builtin_types_compatible_p(typeof(x), typeof(y)) +# define BUILD_BUG_ON_ZERO(expr) (sizeof(int[-1 + 2 * !!(expr)]) * 0) +/* &(a)[0] is a pointer and not an array, shouldn't be treated as the same */ +# define MUST_BE_ARRAY(a) BUILD_BUG_ON_ZERO(!SAME_TYPE((a), &(a)[0])) +#else +# define SAME_TYPE(x, y) 0 +# define MUST_BE_ARRAY(a) 0 +#endif + #if GNUC_PREREQ(3, 0) # define ATTRIBUTE_MALLOC __attribute__((__malloc__)) #else -- 2.40.0