From e8ff555b95baab66cc7d060c1e7f9fdd49d3802f Mon Sep 17 00:00:00 2001 From: Matt Turner Date: Tue, 16 Aug 2011 19:07:24 -0400 Subject: [PATCH] Add type checking to swap macros 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. Reviewed-by: Peter Harris Signed-off-by: Matt Turner --- include/misc.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/include/misc.h b/include/misc.h index 99046ae76..ac27a81f3 100644 --- a/include/misc.h +++ b/include/misc.h @@ -255,6 +255,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) { @@ -267,6 +275,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) @@ -279,11 +289,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];\ @@ -291,6 +305,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]; }