Guest User

Alignment check test case

a guest
May 17th, 2017
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <stdlib.h>
  4.  
  5. #define G_UNLIKELY(x) __builtin_expect(!!(x), 0)
  6.  
  7. #define SPICE_STRLOC__(L) #L
  8. #define SPICE_STRLOC_(F,L) F ":" SPICE_STRLOC__(L)
  9. #define SPICE_STRLOC SPICE_STRLOC_(__FILE__, __LINE__)
  10.  
  11.  
  12. void spice_alignment_warning(const char *loc, void *p, unsigned sz)
  13. {
  14.     printf("warning\n");
  15. }
  16. void spice_alignment_debug(const char *loc, void *p, unsigned sz)
  17. {
  18.     printf("debug\n");
  19. }
  20.  
  21. static inline  void *spice_alignment_check(const char *loc,
  22.                                            void *ptr, unsigned sz)
  23. {
  24.     if (G_UNLIKELY(((uintptr_t) ptr & (sz-1U)) != 0))
  25.         spice_alignment_warning(loc, ptr, sz);
  26.     return ptr;
  27.  
  28. }
  29.  
  30. static inline void *spice_alignment_weak_check(const char *loc,
  31.                                                void *ptr, unsigned sz)
  32. {
  33.     if (G_UNLIKELY(((uintptr_t) ptr & (sz-1U)) != 0))
  34.         spice_alignment_debug(loc, ptr, sz);
  35.     return ptr;
  36.  
  37. }
  38. #define SPICE_ALIGNED_CAST(type, value)                                 \
  39.     ((type)spice_alignment_check(SPICE_STRLOC,                          \
  40.                                  (void *)(value), __alignof(type)))
  41.  
  42. #define SPICE_UNALIGNED_CAST(type, value)                               \
  43.     ((type)spice_alignment_weak_check(SPICE_STRLOC,                     \
  44.                                       (void *)(value), __alignof(type)))
  45.  
  46.  
  47.  
  48. int main()
  49. {
  50.     char *buffer = malloc(27);
  51.     int *aligned = SPICE_ALIGNED_CAST(int *, buffer);
  52.     if (buffer == aligned)
  53.         return 0;
  54.     fprintf(stderr, "kaboom\n");
  55.     return 1;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment