1 #ifndef DEBUG_H 2 #define DEBUG_H 3 4 #include <stdlib.h> 5 #include <stdio.h> 6 7 #define unlikely(expr) __builtin_expect (expr, 0) 8 #define likely(expr) __builtin_expect (expr, 1) 9 10 #ifdef DEBUG 11 12 #define FAILIF(cond, msg...) do { \ 13 if (unlikely(cond)) { \ 14 fprintf(stderr, "%s(%d): ", __FILE__, __LINE__); \ 15 fprintf(stderr, ##msg); \ 16 exit(1); \ 17 } \ 18 } while(0) 19 20 /* Debug enabled */ 21 #define ASSERT(x) do { \ 22 if (unlikely(!(x))) { \ 23 fprintf(stderr, \ 24 "ASSERTION FAILURE %s:%d: [%s]\n", \ 25 __FILE__, __LINE__, #x); \ 26 exit(1); \ 27 } \ 28 } while(0) 29 30 #else 31 32 #define FAILIF(cond, msg...) do { \ 33 if (unlikely(cond)) { \ 34 fprintf(stderr, ##msg); \ 35 exit(1); \ 36 } \ 37 } while(0) 38 39 /* No debug */ 40 #define ASSERT(x) do { } while(0) 41 42 #endif/* DEBUG */ 43 44 #define FAILIF_LIBELF(cond, function) \ 45 FAILIF(cond, "%s(): %s\n", #function, elf_errmsg(elf_errno())); 46 47 static inline void *MALLOC(unsigned int size) { 48 void *m = malloc(size); 49 FAILIF(NULL == m, "malloc(%d) failed!\n", size); 50 return m; 51 } 52 53 static inline void *CALLOC(unsigned int num_entries, unsigned int entry_size) { 54 void *m = calloc(num_entries, entry_size); 55 FAILIF(NULL == m, "calloc(%d, %d) failed!\n", num_entries, entry_size); 56 return m; 57 } 58 59 static inline void *REALLOC(void *ptr, unsigned int size) { 60 void *m = realloc(ptr, size); 61 FAILIF(NULL == m, "realloc(%p, %d) failed!\n", ptr, size); 62 return m; 63 } 64 65 static inline void FREE(void *ptr) { 66 free(ptr); 67 } 68 69 static inline void FREEIF(void *ptr) { 70 if (ptr) FREE(ptr); 71 } 72 73 #define PRINT(x...) do { \ 74 extern int quiet_flag; \ 75 if(likely(!quiet_flag)) \ 76 fprintf(stdout, ##x); \ 77 } while(0) 78 79 #define ERROR PRINT 80 81 #define INFO(x...) do { \ 82 extern int verbose_flag; \ 83 if(unlikely(verbose_flag)) \ 84 fprintf(stdout, ##x); \ 85 } while(0) 86 87 /* Prints a hex and ASCII dump of the selected buffer to the selected stream. */ 88 int dump_hex_buffer(FILE *s, void *b, size_t l, size_t elsize); 89 90 #endif/*DEBUG_H*/ 91