#include #include #include #include /* Log levels */ #define LOG_DEFAULT LOG_INFO typedef enum { LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, } log_t; /* Globals */ int loglevel; /* Helper functions */ static void message(int level, const char *prefix, const char *fmt, va_list ap) { if (level >= LOG_DEFAULT-loglevel) { fprintf(stderr, "%s: ", prefix); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); } } /* Mesage functions */ void debug(const char *fmt, ...) { va_list ap; va_start(ap, fmt); message(LOG_DEBUG, "debug", fmt, ap); va_end(ap); } void info(const char *fmt, ...) { va_list ap; va_start(ap, fmt); message(LOG_INFO, "info", fmt, ap); va_end(ap); } void warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); message(LOG_WARN, "warning", fmt, ap); va_end(ap); } void error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); message(LOG_ERROR, "error", fmt, ap); va_end(ap); exit(1); } /* Hex dump */ void hexdump(const char *label, const char *prefix, const uint8_t *data, int len, ...) { va_list ap; va_start(ap, len); if (!label) label = ""; if (!prefix) prefix = "%04x: "; vprintf(label, ap); for (int i = 0; i < len; i++) { if ((i % 16) == 0) { printf("\n"); printf(prefix, i); } else if ((i % 8) == 0) { printf(" "); } else if ((i % 2) == 0) { printf(" "); } printf("%02hhx", data[i]); } printf("\n"); va_end(ap); } /* Misc */ void *alloc0(int size) { void *out = calloc(1, size); if (!out) error("Alloc failed"); return out; }