From 03dbd6757d043581b5d250107b6f1cda6ae203a9 Mon Sep 17 00:00:00 2001
From: Frederik Deweerdt <fdeweerdt@fastly.com>
Date: Wed, 25 Oct 2017 13:52:28 -0700
Subject: [PATCH] Autodetect backtrace and backtrace_symbols_fd

---
 CMakeLists.txt | 13 +++++++++++++
 src/main.c     | 10 ++++++----
 2 files changed, 19 insertions(+), 4 deletions(-)

--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -58,6 +58,19 @@ __sync_add_and_fetch(&a, 1);
 return 0;
 }" ARCH_SUPPORTS_64BIT_ATOMICS)
 
+CHECK_C_SOURCE_COMPILES("
+#include <execinfo.h>
+int main(void) {
+void *p[10];
+int ret = backtrace(p, 10);
+backtrace_symbols_fd(p, ret, 2);
+return 0;
+}" LIBC_HAS_BACKTRACE)
+
+IF (LIBC_HAS_BACKTRACE)
+    ADD_DEFINITIONS("-DLIBC_HAS_BACKTRACE")
+ENDIF ()
+
 SET(WITH_BUNDLED_SSL_DEFAULT "ON")
 IF ((NOT UNIX) OR CYGWIN)
     SET(WITH_BUNDLED_SSL_DEFAULT "OFF")
--- a/src/main.c
+++ b/src/main.c
@@ -48,7 +48,7 @@
 #include <openssl/crypto.h>
 #include <openssl/err.h>
 #include <openssl/ssl.h>
-#ifdef __GLIBC__
+#ifdef LIBC_HAS_BACKTRACE
 #include <execinfo.h>
 #endif
 #if H2O_USE_PICOTLS
@@ -1436,7 +1436,8 @@ static void on_sigterm(int signo)
     notify_all_threads();
 }
 
-#ifdef __GLIBC__
+#ifdef LIBC_HAS_BACKTRACE
+
 static int popen_crash_handler(void)
 {
     char *cmd_fullpath = h2o_configurator_get_cmd_path(conf.crash_handler), *argv[] = {cmd_fullpath, NULL};
@@ -1488,13 +1489,14 @@ static void on_sigfatal(int signo)
 
     raise(signo);
 }
-#endif
+
+#endif /* LIBC_HAS_BACKTRACE */
 
 static void setup_signal_handlers(void)
 {
     h2o_set_signal_handler(SIGTERM, on_sigterm);
     h2o_set_signal_handler(SIGPIPE, SIG_IGN);
-#ifdef __GLIBC__
+#ifdef LIBC_HAS_BACKTRACE
     if ((crash_handler_fd = popen_crash_handler()) == -1)
         crash_handler_fd = 2;
     h2o_set_signal_handler(SIGABRT, on_sigfatal);
