Skip to content

Instantly share code, notes, and snippets.

@pablogsal
Created October 18, 2018 15:27
Show Gist options
  • Save pablogsal/131fbeada11797de42299ffc3f204a4b to your computer and use it in GitHub Desktop.
Save pablogsal/131fbeada11797de42299ffc3f204a4b to your computer and use it in GitHub Desktop.
#include <execinfo.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
static volatile int party = 1;
static void full_write(int fd, const char *buf, size_t len)
{
while (len > 0) {
ssize_t ret = write(fd, buf, len);
if ((ret == -1) && (errno != EINTR))
break;
buf += (size_t) ret;
len -= (size_t) ret;
}
}
void print_backtrace(void* p2)
{
party = 0;
static const char start[] = "BACKTRACE ------------\n";
static const char end[] = "----------------------\n";
void *bt[1024];
int bt_size;
char **bt_syms;
int i;
bt_size = backtrace(bt, 1024);
bt_syms = backtrace_symbols(bt, bt_size);
full_write(STDERR_FILENO, start, strlen(start));
for (i = 1; i < bt_size; i++) {
size_t len = strlen(bt_syms[i]);
full_write(STDERR_FILENO, bt_syms[i], len);
full_write(STDERR_FILENO, "\n", 1);
}
full_write(STDERR_FILENO, end, strlen(end));
free(bt_syms);
party = 1;
}
static void mtrace_init(void)
{
real_malloc = dlsym(RTLD_NEXT, "malloc");
if (NULL == real_malloc) {
fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
}
}
void *malloc(size_t size)
{
if(real_malloc==NULL) {
mtrace_init();
}
void *p = NULL;
fprintf(stderr, "malloc(%d) = ", size);
if(party){
print_backtrace(real_malloc);
}
p = real_malloc(size);
fprintf(stderr, "%p\n", p);
return p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment