]> granicus.if.org Git - strace/commitdiff
defs: add check for argument being array to ARRAY_SIZE macro
authorEugene Syromyatnikov <evgsyr@gmail.com>
Sat, 29 Oct 2016 02:24:08 +0000 (05:24 +0300)
committerEugene Syromyatnikov <evgsyr@gmail.com>
Sun, 30 Oct 2016 21:49:28 +0000 (00:49 +0300)
* 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
gcc_compat.h

diff --git a/defs.h b/defs.h
index 5eb9b1085fe658914e159e0cb41a248cdff46429..b2907403caaf13bfce0eb8d0674eb7f4ae584831 100644 (file)
--- 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
index 908df16c7d3dd96deb6fd6281a4639143577b833..9e6c233f099e9611416229170997069f187d4938 100644 (file)
 # 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