[PATCH 5/8] Add type checking to swap macros

Matt Turner mattst88 at gmail.com
Tue Aug 16 19:58:24 PDT 2011


The original macros are retained (instead of replacing them with inline
functions) because of implicit type promotion. That is, an int16 passed
to an inline function taking int32 would be implicitly promoted to int32
without a warning.

Signed-off-by: Matt Turner <mattst88 at gmail.com>
---
 include/misc.h |   16 ++++++++++++++++
 1 files changed, 16 insertions(+), 0 deletions(-)

diff --git a/include/misc.h b/include/misc.h
index 6034c72..660d265 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -258,6 +258,14 @@ version_compare(uint16_t a_major, uint16_t a_minor,
 #define SwapRestL(stuff) \
     SwapLongs((CARD32 *)(stuff + 1), LengthRestL(stuff))
 
+#ifdef __GNUC__
+void __attribute__((error("wrong sized variable passed to swap"))) wrong_size(void);
+#else
+static inline void wrong_size(void)
+{
+}
+#endif
+
 /* byte swap a 32-bit value */
 static inline void swap_uint32(uint32_t *x)
 {
@@ -270,6 +278,8 @@ static inline void swap_uint32(uint32_t *x)
 }
 
 #define swapl(x) do { \
+		if (sizeof(*(x)) != 4) \
+			wrong_size(); \
 		swap_uint32((uint32_t *)(x)); \
 	} while (0)
 
@@ -282,11 +292,15 @@ static inline void swap_uint16(uint16_t *x)
 }
 
 #define swaps(x) do { \
+		if (sizeof(*(x)) != 2) \
+			wrong_size(); \
 		swap_uint16((uint16_t *)(x)); \
 	} while (0)
 
 /* copy 32-bit value from src to dst byteswapping on the way */
 #define cpswapl(src, dst) { \
+		if (sizeof((src)) != 4 || sizeof((dst)) != 4) \
+			wrong_size(); \
                  ((char *)&(dst))[0] = ((char *) &(src))[3];\
                  ((char *)&(dst))[1] = ((char *) &(src))[2];\
                  ((char *)&(dst))[2] = ((char *) &(src))[1];\
@@ -294,6 +308,8 @@ static inline void swap_uint16(uint16_t *x)
 
 /* copy short from src to dst byteswapping on the way */
 #define cpswaps(src, dst) { \
+		if (sizeof((src)) != 2 || sizeof((dst)) != 2) \
+			wrong_size(); \
 		 ((char *) &(dst))[0] = ((char *) &(src))[1];\
 		 ((char *) &(dst))[1] = ((char *) &(src))[0]; }
 
-- 
1.7.3.4



More information about the xorg-devel mailing list