+/* This file is to be included in ex.c, so the following headers are not mandatory, but it's to make sure that eclipse see them too */
+#include "xbt/ex.h"
+#include "xbt/str.h"
+#include "xbt/module.h" /* xbt_binary_name */
+#include "xbt_modinter.h" /* backtrace initialization headers */
+#ifdef HAVE_MC
+#define UNW_LOCAL_ONLY
+#include <libunwind.h>
+#endif
+/* end of "useless" inclusions */
+
+extern char **environ; /* the environment, as specified by the opengroup */
+
+/* Module creation/destruction: nothing to do on linux */
+void xbt_backtrace_preinit(void)
+{
+}
+
+void xbt_backtrace_postexit(void)
+{
+}
+
+#include <unwind.h>
+struct trace_arg {
+ void **array;
+ int cnt, size;
+};
+
+static _Unwind_Reason_Code
+backtrace_helper (struct _Unwind_Context *ctx, void *a)
+{
+ struct trace_arg *arg = a;
+
+ /* We are first called with address in the __backtrace function.
+ Skip it. */
+ if (arg->cnt != -1)
+ {
+ arg->array[arg->cnt] = (void *) _Unwind_GetIP(ctx);
+
+ /* Check whether we make any progress. */
+ if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt])
+ return _URC_END_OF_STACK;
+ }
+ if (++arg->cnt == arg->size)
+ return _URC_END_OF_STACK;
+ return _URC_NO_REASON;
+}
+
+/** @brief reimplementation of glibc backtrace based directly on gcc library, without implicit malloc
+ *
+ * See http://webloria.loria.fr/~quinson/blog/2012/0208/system_programming_fun_in_SimGrid/
+ * for the motivation behind this function
+ * */
+
+int xbt_backtrace_no_malloc(void **array, int size) {
+
+ int i = 0;
+ for(i=0; i < size; i++)
+ array[i] = NULL;
+
+ struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
+
+ if (size >= 1)
+ _Unwind_Backtrace(backtrace_helper, &arg);
+
+ /* _Unwind_Backtrace on IA-64 seems to put NULL address above
+ _start. Fix it up here. */
+ if (arg.cnt > 1 && arg.array[arg.cnt - 1] == NULL)
+ --arg.cnt;
+ return arg.cnt != -1 ? arg.cnt : 0;
+}
+
+void xbt_backtrace_current(xbt_ex_t * e)
+{
+ e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE);
+ if (e->used == 0) {
+ fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted. Here is a crude dump of the exception that I was trying to build:");
+ fprintf(stderr, "%s(%d) [%s:%d] %s",
+ e->procname, e->pid, e->file, e->line, e->msg);
+ fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory. Please go fix the memleaks\n");
+ exit(1);
+ }
+}
+