add a test/backtrace module and have ASSERT_FAIL dump out a backtrace, also, fix assert_str[n]cmp to handle should_be == NULL
authorTero Marttila <terom@fixme.fi>
Fri, 08 May 2009 00:12:52 +0300
changeset 189 f351facab1f0
parent 188 6fd4706a4180
child 190 69fd25c8484c
add a test/backtrace module and have ASSERT_FAIL dump out a backtrace, also, fix assert_str[n]cmp to handle should_be == NULL
src/test/assert.c
src/test/backtrace.c
src/test/backtrace.h
--- a/src/test/assert.c	Fri May 08 00:12:15 2009 +0300
+++ b/src/test/assert.c	Fri May 08 00:12:52 2009 +0300
@@ -1,9 +1,10 @@
 #include "assert.h"
 #include "util.h"
+#include "backtrace.h"
 
 #include <string.h>
 
-#define ASSERT_FAIL(...) do { log_fatal(__VA_ARGS__); abort(); } while (0)
+#define ASSERT_FAIL(...) do { log_fatal(__VA_ARGS__); test_backtrace(1); abort(); } while (0)
 
 void assert_true (bool cond, const char *msg)
 {
@@ -19,12 +20,18 @@
 
 void assert_strcmp (const char *is, const char *should_be)
 {
+    if (!should_be && !is)
+        return;
+
     if (!is || strcmp(is, should_be))
         ASSERT_FAIL("%s != %s", dump_str(is), dump_str(should_be));
 }
 
 void assert_strncmp (const char *is, const char *should_be, size_t n)
 {   
+    if (!should_be && !is)
+        return;
+
     if (!is || strncmp(is, should_be, n))
         ASSERT_FAIL("%s:%u != %s", dump_strn(is, n), (unsigned) n, dump_strn(should_be, n));
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/test/backtrace.c	Fri May 08 00:12:52 2009 +0300
@@ -0,0 +1,26 @@
+#include "backtrace.h"
+#include "../log.h"
+
+#include <execinfo.h>
+
+void test_backtrace (int skip)
+{
+    void *stacktrace[TEST_BACKTRACE_MAX];
+    char **lines;
+    int count, i;
+    
+    // get the raw stack data
+    if ((count = backtrace(stacktrace, TEST_BACKTRACE_MAX)) >= TEST_BACKTRACE_MAX)
+        log_warn("(backtrace truncated)");
+    
+    // get the textual representation
+    if ((lines = backtrace_symbols(stacktrace, count)) == NULL)
+        return log_warn("(unable to alloc backtrace)");
+
+    // then log_debug it out
+    for (i = skip; i < count; i++)
+        log_debug("%s", lines[i]);
+
+    // release resources
+    free(lines);
+}   
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/test/backtrace.h	Fri May 08 00:12:52 2009 +0300
@@ -0,0 +1,19 @@
+#ifndef TEST_BACKTRACE_H
+#define TEST_BACKTRACE_H
+
+/**
+ * Maximum depth of a backtrace
+ */
+#define TEST_BACKTRACE_MAX 64
+
+/**
+ * Dump out a backtrace via log_debug.
+ *
+ * The backtrace will exclude the \a skip highest levels of the backtrace. This should usually be at least one to not show the
+ * call to test_backtrace itself.
+ *
+ * At most TEST_BACKTRACE_MAX levels of the stack will be printed (this limit includes skip).
+ */
+void test_backtrace (int skip);
+
+#endif /* TEST_BACKTRACE_H */