commit b893f8927db48af928fead395ecb6f6935faa7df
parent cb6d26f99634fdc14f69290877e73f937e87d171
Author: Robert Russell <robertrussell.72001@gmail.com>
Date: Thu, 23 Feb 2023 23:32:56 -0800
Add debug utils
Diffstat:
3 files changed, 48 insertions(+), 0 deletions(-)
diff --git a/Makefile b/Makefile
@@ -6,6 +6,7 @@ SRC =\
src/alloc.c\
src/bench.c\
src/bits.c\
+ src/debug.c\
src/error.c\
src/log.c\
src/str.c\
@@ -23,6 +24,7 @@ librcx.a: $(SRC:.c=.o)
src/alloc.o: src/alloc.c inc/alloc.h inc/def.h inc/log.h inc/rcx.h inc/internal/util.h config.mk
src/bench.o: src/bench.c inc/bench.h inc/def.h inc/log.h inc/rcx.h config.mk
src/bits.o: src/bits.c inc/bits.h inc/def.h inc/rcx.h config.mk
+src/debug.o: src/debug.c inc/debug.h inc/def.h inc/rcx.h config.mk
src/error.o: src/error.c inc/def.h inc/error.h inc/log.h inc/rcx.h config.mk
src/log.o: src/log.c inc/def.h inc/log.h inc/rcx.h config.mk
src/opt.o: src/opt.c inc/def.h inc/opt.h inc/rcx.h config.mk
diff --git a/inc/debug.h b/inc/debug.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include <stdnoreturn.h>
+
+#include "def.h"
+
+/* require is like assert from assert.h, but it never gets disabled and it
+ * takes an optional message like C11's static_assert. */
+#define require(cond, ...) ((void)((cond) || (throw( \
+ "Assertion failed [%s:%d]: %s\n", \
+ __FILE__, __LINE__, VA_DEFAULT(,##__VA_ARGS__, #cond) \
+ ), 0)))
+
+/* Replace standard assert with version that accepts an optional message. */
+#ifdef NDEBUG
+#define assert(cond, ...) ((void)0)
+#else
+#define assert require
+#endif
+
+/* Print the given formatted message to stderr followed by a newline,
+ * and then abort. */
+noreturn void throw(char *fmt, ...);
+
diff --git a/src/debug.c b/src/debug.c
@@ -0,0 +1,22 @@
+#define _POSIX_C_SOURCE 199506L /* flockfile, funlockfile */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "debug.h"
+#include "rcx.h"
+
+noreturn void
+throw(char *fmt, ...) {
+ va_list args;
+ va_start(args, fmt);
+
+ flockfile(stderr);
+ vfprintf(stderr, fmt, args);
+ fputc('\n', stderr);
+ funlockfile(stderr);
+
+ va_end(args);
+
+ abort();
+}