From a1b37d0f37a8941ce78ead019d974c6e75c61be1 Mon Sep 17 00:00:00 2001
From: taehoon <taehoon@falinux.com>
Date: Fri, 20 Sep 2019 12:30:55 +0900
Subject: [PATCH] =?UTF-8?q?assert=EC=97=90=20backtrace=20=EC=B6=94?=
 =?UTF-8?q?=EA=B0=80?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

원본: https://github.com/mct/junkdrawer/blob/master/c/assert-backtrace.c
---
 c/assert-backtrace.c | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 66 insertions(+)
 create mode 100644 c/assert-backtrace.c

diff --git a/c/assert-backtrace.c b/c/assert-backtrace.c
new file mode 100644
index 0000000..9b08517
--- /dev/null
+++ b/c/assert-backtrace.c
@@ -0,0 +1,66 @@
+// vim:set ts=4 sw=4 ai et:
+#include <stdio.h>
+#include <execinfo.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <assert.h>
+/*
+
+Compile with "-rdynamic" to include function names in the backtrace output
+
+Example output:
+
+$ gcc -rdynamic -Werror assert-backtrace.c && ./a.out
+Backtrace:
+
+   1   a.out(quux+0x9) [0x55d540c74cd4]
+   2   a.out(qux+0xe) [0x55d540c74d08]
+   3   a.out(baz+0xe) [0x55d540c74d19]
+   4   a.out(bar+0xe) [0x55d540c74d2a]
+   5   a.out(foo+0xe) [0x55d540c74d3b]
+   6   a.out(main+0x19) [0x55d540c74d57]
+   7   /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7) [0x7fdc6b424b97]
+   8   a.out(_start+0x2a) [0x55d540c74a5a]
+
+a.out: assert-backtrace.c:57: quux: Assertion `0 && "test assertion" || printbt()' failed.
+Aborted (core dumped)
+
+*/
+
+#define assert_bt(...) assert(__VA_ARGS__ || printbt())
+#define STACK_DEPTH   20
+int printbt(void)
+{
+    void *buffer[STACK_DEPTH];
+    char **strings;
+    int size, i;
+
+    size = backtrace(buffer, STACK_DEPTH);
+    strings = backtrace_symbols(buffer, size);
+
+    fprintf(stderr, "Backtrace:\n\n");
+
+    for (i = 1; i < size; i++) {
+        if (strings[i][0] == '.' && strings[i][1] == '/')
+            strings[i] += 2;
+
+        fprintf(stderr, " %3d   %s\n", i, strings[i]);
+    }
+
+    fprintf(stderr, "\n");
+
+    return 0;
+}
+
+void quux() { assert_bt(0 && "test assertion"); }
+void qux() { quux(); }
+void baz() { qux(); }
+void bar() { baz(); }
+void foo() { bar(); }
+
+int main(int argc, char **argv)
+{
+    foo();
+    return 0;
+}
-- 
2.1.4