/* gcc -g [ -D_REENTRANT ] stacktest.c [ -lpthread ] -o stacktest */ #include #include #include #include #include #ifdef _REENTRANT #include #endif /* the alternative stack reference */ static stack_t ss; /* this function does nasty things */ static void overflow(void) { overflow(); } /* test entry point */ static void* threadEntry(void* parg) { struct rlimit rlim; /* setup alternative strack for the current thread */ ss.ss_flags = 0; ss.ss_size = SIGSTKSZ; ss.ss_sp = malloc(ss.ss_size); if (ss.ss_sp == NULL) { abort(); } if (sigaltstack(&ss, NULL) == -1) { abort(); } /* print current stack limit */ if (getrlimit(RLIMIT_STACK, &rlim) == 0) { const unsigned long page_size = (unsigned long) sysconf(_SC_PAGE_SIZE); const unsigned long stack_bottom = (((unsigned long)&rlim-rlim.rlim_cur+page_size-1)/page_size)*page_size; printf("bottom of stack==%p, alternative_stack==%p\n", (void*)stack_bottom, (void*)ss.ss_sp); } /* do something very nasty */ overflow(); /* we may not reach this point */ return NULL; } /* SEGV handler */ static void saHandler(int code, siginfo_t *si, void *sc_) { void *kenny = (void*) &code; ucontext_t * const sc = (ucontext_t*) sc_; printf("SEGV==%p; sp==%p; current stack is the %s\n", (void*)si->si_addr, (void*)((ucontext_t*)sc_)->uc_stack.ss_sp, ( kenny >= ss.ss_sp && kenny < ss.ss_sp + SIGSTKSZ ) ? "alternate stack" : "original stack"); abort(); } /* main entry point */ int main(void) { /* catch SEGV with SA_ONSTACK enabled */ struct sigaction s; memset(&s, 0, sizeof(s)); sigemptyset(&s.sa_mask); s.sa_flags = SA_SIGINFO | SA_ONSTACK; s.sa_sigaction = saHandler; if(sigaction (SIGSEGV, &s, NULL)) { abort(); } #ifdef _REENTRANT /* threaded version */ { pthread_t t; pthread_create(&t, NULL, threadEntry, NULL); pause(); /* wait (almost) endlessly */ } #else /* single threaded version */ (void) threadEntry(NULL); #endif /* not reached */ abort(); return 0; }