Skip to content

Instantly share code, notes, and snippets.

@scottt
Created December 15, 2012 00:46
Show Gist options
  • Save scottt/4290049 to your computer and use it in GitHub Desktop.
Save scottt/4290049 to your computer and use it in GitHub Desktop.
#include <strings.h>
#include <stdio.h>
#include <execinfo.h>
struct stack_frame {
struct stack_frame *prev;
void *return_addr;
} __attribute__((packed));
typedef struct stack_frame stack_frame;
__attribute__((noinline, noclone))
void backtrace_from_fp(void **buf, int size)
{
int i;
stack_frame *fp;
__asm__("movl %%ebp, %[fp]" : /* output */ [fp] "=r" (fp));
for(i = 0; i < size && fp != NULL; fp = fp->prev, i++)
buf[i] = fp->return_addr;
}
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
enum {
N = 100,
};
void *trace_buf[N];
__attribute__((optimize("no-omit-frame-pointer", "O0"), noinline, noclone))
void h(void)
{
int i;
bzero(trace_buf, ARRAY_SIZE(trace_buf));
backtrace_from_fp(trace_buf, ARRAY_SIZE(trace_buf));
printf("backtrace_from_fp:\n");
/* skipping trace_buf[0] since we're calling my_backtrace() and backtrace()
* from different places within this function */
for (i = 1; i < ARRAY_SIZE(trace_buf); i++) {
if (!trace_buf[i])
break;
printf("%p\n", trace_buf[i]);
}
printf("\nbacktrace:\n");
backtrace(trace_buf, ARRAY_SIZE(trace_buf));
for (i = 1; i < ARRAY_SIZE(trace_buf); i++) {
if (!trace_buf[i])
break;
printf("%p\n", trace_buf[i]);
}
}
__attribute__((optimize("no-omit-frame-pointer", "O0"), noinline, noclone))
void f(void)
{
h();
}
__attribute__((optimize("no-omit-frame-pointer", "O0"), noinline, noclone)
void g(void)
{
f();
}
int main()
{
g();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment