Last active
June 2, 2023 08:39
-
-
Save mmozeiko/f43694df8bfd5fd2e20a6aaa28b50179 to your computer and use it in GitHub Desktop.
linux call stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// gcc -g demo.c -ldl | |
#define _GNU_SOURCE | |
#include <stdio.h> | |
#include <dlfcn.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <signal.h> | |
#include <unistd.h> | |
#include <execinfo.h> | |
static void handler(int sig, siginfo_t* info, void* arg) | |
{ | |
fprintf(stderr, "%s (%d)\n", strsignal(sig), sig); | |
void* addr[1024]; | |
int count = backtrace(addr, sizeof(addr)/sizeof(*addr)); | |
for (int i = 2; i < count; i++) | |
{ | |
Dl_info dinfo; | |
if (!dladdr(addr[i], &dinfo)) | |
{ | |
printf("[0x%016lx]: ???\n", (uintptr_t)addr[i]); | |
continue; | |
} | |
addr[i] = (void*)((uintptr_t)addr[i] - (uintptr_t)dinfo.dli_fbase); | |
char cmd[256]; | |
sprintf(cmd, "addr2line -e %s -f 0x%016lx", dinfo.dli_fname, (uintptr_t)addr[i]); | |
char symbol[256]; | |
char location[256]; | |
FILE* f = popen(cmd, "r"); | |
if (f) | |
{ | |
size_t idx = 0; | |
fgets(symbol, sizeof(symbol), f); | |
fgets(location, sizeof(location), f); | |
if (strncmp(symbol, "??", 2) == 0) | |
{ | |
symbol[0] = 0; | |
} | |
else | |
{ | |
symbol[strlen(symbol)-1] = 0; | |
} | |
if (strncmp(location, "??:", 3) == 0) | |
{ | |
location[0] = 0; | |
} | |
else | |
{ | |
location[strlen(location)-1] = 0; | |
} | |
pclose(f); | |
} | |
else | |
{ | |
symbol[0] = 0; | |
location[0] = 0; | |
} | |
printf("[0x%016lx]: <%s> %s\n", (uintptr_t)addr[i], symbol[0] ? symbol : dinfo.dli_sname, location[0] ? location : dinfo.dli_fname); | |
} | |
_exit(EXIT_FAILURE); | |
} | |
void foo() | |
{ | |
int* p = 0; | |
*p = 1; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
struct sigaction h = { | |
.sa_sigaction = handler, | |
.sa_flags = SA_SIGINFO, | |
}; | |
sigfillset(&h.sa_mask); | |
sigaction(SIGILL, &h, NULL); | |
sigaction(SIGTRAP, &h, NULL); | |
sigaction(SIGABRT, &h, NULL); | |
sigaction(SIGFPE, &h, NULL); | |
sigaction(SIGBUS, &h, NULL); | |
sigaction(SIGSEGV, &h, NULL); | |
sigaction(SIGQUIT, &h, NULL); | |
foo(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment