X-Git-Url: https://ruderich.org/simon/gitweb/?a=blobdiff_plain;f=src%2Fdebug.h;h=911a440fb0f83feb30c039351cd2216a81958c28;hb=2c55827f6f2c231a8f166e015df4c5c3818c8ba4;hp=4dab03c3407600fad3556e498ca921ddf33a370d;hpb=66fb589680db241e916b7f7f43d9e6058dcdb571;p=coloredstderr%2Fcoloredstderr.git diff --git a/src/debug.h b/src/debug.h index 4dab03c..911a440 100644 --- a/src/debug.h +++ b/src/debug.h @@ -20,21 +20,14 @@ #ifndef DEBUG_H #define DEBUG_H 1 -static void debug(const char *format, ...) { +static void debug_write(int fd, int first_call, char const *format, va_list ap) { char buffer[1024]; - /* If the file doesn't exist, do nothing. Prevents writing log files in - * unexpected places. The user must create the file manually. */ - int fd = open(DEBUG_FILE, O_WRONLY | O_APPEND); - if (fd == -1) - return; - - va_list ap; - va_start(ap, format); int written = vsnprintf(buffer, sizeof(buffer), format, ap); - va_end(ap); + if (written < 0) { + return; /* shouldn't happen */ /* Overflow. */ - if ((size_t)written >= sizeof(buffer)) { + } else if ((size_t)written >= sizeof(buffer)) { written = sizeof(buffer) - 1; } @@ -42,13 +35,70 @@ static void debug(const char *format, ...) { DLSYM_FUNCTION(real_write, "write"); DLSYM_FUNCTION(real_close, "close"); - static int first_call = 0; - if (!first_call++) { - char nl = '\n'; + if (first_call) { + char const nl = '\n'; real_write(fd, &nl, 1); } real_write(fd, buffer, (size_t)written); real_close(fd); } +#ifdef DEBUG +static void debug(char const *format, ...) { + va_list ap; + + int saved_errno = errno; + + /* If the file doesn't exist, do nothing. Prevents writing log files in + * unexpected places. The user must create the file manually. */ + int fd = open(DEBUG_FILE, O_WRONLY | O_APPEND); + if (fd == -1) { + errno = saved_errno; + return; + } + + static int call_count = 0; + call_count++; + + va_start(ap, format); + debug_write(fd, call_count == 1, format, ap); + va_end(ap); + + errno = saved_errno; +} +#endif + +static void warning(char const *format, ...) { + va_list ap; + + int saved_errno = errno; + + char const *home = getenv("HOME"); + if (!home) { + errno = saved_errno; + return; + } + + char path[strlen(home) + 1 + strlen(WARNING_FILE) + 1]; + strcpy(path, home); + strcat(path, "/"); + strcat(path, WARNING_FILE); + + /* Create the warning file if it doesn't exist yet. */ + int fd = open(path, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); + if (fd == -1) { + errno = saved_errno; + return; + } + + static int call_count = 0; + call_count++; + + va_start(ap, format); + debug_write(fd, call_count == 1, format, ap); + va_end(ap); + + errno = saved_errno; +} + #endif