Created
August 2, 2025 09:41
-
-
Save hackeris/db2d3be52fdc252f6584f8e6d15ed66b to your computer and use it in GitHub Desktop.
sigsegv.c
This file contains hidden or 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <signal.h> | |
#include <ucontext.h> | |
#include <unistd.h> | |
void sigsegv_handler(int signum, siginfo_t *info, void *context); | |
int main() { | |
struct sigaction sa; | |
sa.sa_flags = SA_SIGINFO; | |
sa.sa_sigaction = sigsegv_handler; | |
sigemptyset(&sa.sa_mask); | |
if (sigaction(SIGSEGV, &sa, NULL) == -1) { | |
perror("failed to install SIGSEGV handler"); | |
return 1; | |
} | |
int *ptr = NULL; | |
*ptr = 42; | |
return 0; | |
} | |
void sigsegv_handler(int signum, siginfo_t *info, void *context) { | |
ucontext_t *uc = (ucontext_t *)context; | |
unsigned char *fault_pc; | |
#if defined(__aarch64__) | |
fault_pc = (unsigned char *)uc->uc_mcontext.pc; | |
#else | |
fault_pc = (unsigned char *)uc->uc_mcontext.gregs[REG_RIP]; | |
#endif | |
const char msg[] = "SIGSEGV, pc = 0x"; | |
write(STDERR_FILENO, msg, sizeof(msg)-1); | |
char hex[20]; | |
hex[0] = '0'; | |
hex[1] = 'x'; | |
for (int i = 0; i < 16; i++) { | |
int nibble = ((unsigned long long)fault_pc >> (60 - 4*i)) & 0xF; | |
hex[i+2] = nibble < 10 ? '0' + nibble : 'a' + nibble - 10; | |
} | |
hex[18] = '\n'; | |
hex[19] = '\0'; | |
write(STDERR_FILENO, hex, 19); | |
for (int i = 0; i < 64; i += 1) { | |
printf("%02x ", fault_pc[i]); | |
} | |
printf("\n"); | |
printf("offset from main: 0x%ld\n", fault_pc - (unsigned char*) main); | |
signal(SIGSEGV, SIG_DFL); | |
raise(SIGSEGV); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment