]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blobdiff - src/debug.h
Add more error checks.
[coloredstderr/coloredstderr.git] / src / debug.h
index aebd88c29342815c8f6773aa08f81068f2bb999b..5e5cc6d937ef55e7e73de1f62310183daa40bb8a 100644 (file)
@@ -24,8 +24,10 @@ static void debug_write(int fd, int first_call, char const *format, va_list ap)
     char buffer[1024];
 
     int written = vsnprintf(buffer, sizeof(buffer), format, 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;
     }
 
@@ -41,13 +43,17 @@ static void debug_write(int fd, int first_call, char const *format, va_list ap)
     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;
     }
 
@@ -57,13 +63,19 @@ static void debug(char const *format, ...) {
     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;
     }
 
@@ -75,6 +87,7 @@ static void warning(char const *format, ...) {
     /* 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;
     }
 
@@ -84,6 +97,8 @@ static void warning(char const *format, ...) {
     va_start(ap, format);
     debug_write(fd, call_count == 1, format, ap);
     va_end(ap);
+
+    errno = saved_errno;
 }
 
 #endif