+/* internal signal lists */
+static int sigerr[] = { SIG_FOR_TIMER, SIGSEGV, SIGFPE, SIGILL, SIGBUS, 0 };
+static int sigterm[] = { SIGINT, SIGABRT, SIGTERM, 0 };
+static int exiting = 0;
+static int enabled = 0;
+
+/*
+ * Dumps the current stack
+ */
+static void dumpstack(int crop, int signum)
+{
+ int idx, count, rc;
+ void *addresses[100];
+ char **locations;
+ char buffer[8000];
+ size_t pos, length;
+
+ count = backtrace(addresses, sizeof addresses / sizeof *addresses);
+ if (count <= crop)
+ crop = 0;
+ count -= crop;
+ locations = backtrace_symbols(&addresses[crop], count);
+ if (locations == NULL)
+ ERROR("can't get the backtrace (returned %d addresses)", count);
+ else {
+ length = sizeof buffer - 1;
+ pos = 0;
+ idx = 0;
+ while (pos < length && idx < count) {
+ rc = snprintf(&buffer[pos], length - pos, " [%d/%d] %s\n", idx + 1, count, locations[idx]);
+ pos += rc >= 0 ? rc : 0;
+ idx++;
+ }
+ buffer[length] = 0;
+ if (signum)
+ ERROR("BACKTRACE due to signal %s/%d:\n%s", strsignal(signum), signum, buffer);
+ else
+ ERROR("BACKTRACE:\n%s", buffer);
+ free(locations);
+ }
+}
+
+static void safe_dumpstack_cb(int signum, void *closure)
+{
+ int *args = closure;
+ if (signum)
+ ERROR("Can't provide backtrace: raised signal %s", strsignal(signum));
+ else
+ dumpstack(args[0], args[1]);
+}
+
+static void safe_dumpstack(int crop, int signum)
+{
+ int args[2] = { crop + 3, signum };
+
+ in_safe_dumpstack = 1;
+ sig_monitor(0, safe_dumpstack_cb, args);
+ in_safe_dumpstack = 0;
+}
+