coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

strengthening ARRAY_CARDINALITY


From: Eric Blake
Subject: strengthening ARRAY_CARDINALITY
Date: Thu, 19 Jan 2017 15:52:56 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.6.0

On the qemu list, it was pointed out that code that uses
ARRAY_CARDINALITY() might still compile even after it has been
refactored to use a pointer (probably conversion of an array into
dynamic allocation), but that you can add a compile-time check with
new-enough gcc/clang to catch this.

I'm also wondering if we should promote ARRAY_CARDINALITY into a
full-fledged gnulib module (several gnulib files define it in .c files,
but leave projects to re-define their own; coreutils' is in system.h).

The qemu list spells their macro ARRAY_SIZE, and
QEMU_BUILD_BUG_ON_ZERO(x) is equivalent to our verify_expr(!x, 0), but
I'm wondering if we should similarly strengthen coreutils' macro (with
appropriate guards for new-enough gcc, since we target more compilers
than qemu):

https://lists.gnu.org/archive/html/qemu-devel/2017-01/msg04118.html

+/*
+ * &(x)[0] is always a pointer - if it's same type as x then the
argument is a
+ * pointer, not an array.
+ */
+#define QEMU_IS_ARRAY(x) (!__builtin_types_compatible_p(typeof(x), \
+                                                        typeof(&(x)[0])))
 #ifndef ARRAY_SIZE
-#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
+#define ARRAY_SIZE(x) ((sizeof(x) / sizeof((x)[0])) + \
+                       QEMU_BUILD_BUG_ON_ZERO(!QEMU_IS_ARRAY(x)))
 #endif
-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]