#include #include #if !defined(__GNUC__) # include #endif /* !__GNUC__ */ #if defined(__GNUC__) # define START_STACK (0xC000000) #else # if defined(__HP_NC4200) # define START_STACK (0x0013FFFF) # else # define START_STACK (0x0012FFFF) # endif #endif /* __GNUC__ */ #define DEFAULT_MEMSIZE (1024) unsigned long end_stack; void signal_handler( int signo ) { fprintf( stderr, "Guessing end stack: 0x%08x\n", end_stack ); fflush(NULL); exit(0); } #if !defined(__GNUC__) LONG WINAPI unhandled_exception_handler( struct _EXCEPTION_POINTERS *ExceptionInfo ) { fprintf( stderr, "Guessing end stack: 0x%08x\n", end_stack ); fflush(NULL); exit(0); } #endif /* !__GNUC__ */ void attach_signal( void ) { #if !defined(__GNUC__) signal( SIGTERM, signal_handler ); signal( SIGSEGV, signal_handler ); signal( SIGINT, signal_handler ); SetUnhandledExceptionFilter( unhandled_exception_handler ); #else struct sigaction action; stack_t sigstk; if ( (sigstk.ss_sp = (char *) malloc(SIGSTKSZ*2)) == NULL) { fprintf(stderr, "can't alloc alt stack\n"); return; } sigstk.ss_size = SIGSTKSZ*2; sigstk.ss_flags = 0; if (sigaltstack(&sigstk, (stack_t *) 0) < 0) { perror("sigaltstack"); return; } action.sa_handler = &signal_handler; action.sa_flags = SA_RESETHAND | SA_ONSTACK; sigaction(SIGKILL, &action, NULL); sigaction(SIGHUP, &action, NULL); sigaction(SIGINT, &action, NULL); sigaction(SIGQUIT, &action, NULL); sigaction(SIGILL, &action, NULL); sigaction(SIGABRT, &action, NULL); sigaction(SIGFPE, &action, NULL); sigaction(SIGSEGV, &action, NULL); sigaction(SIGTERM, &action, NULL); sigaction(SIGBUS, &action, NULL); sigaction(SIGUSR1, &action, NULL); #endif /* !__GNUC__ */ } void check_stack( void ) { void *p; int array[DEFAULT_MEMSIZE]; end_stack = (unsigned long)&p; check_stack(); } void check_heap( void ) { void *p; void *backup; int i = 0; do { backup = p; p = (char *)malloc(DEFAULT_MEMSIZE); } while ( (unsigned int)p < START_STACK ); fprintf( stderr, "Guessing after heap: 0x%08x\n", backup ); do { p = (char *)malloc(DEFAULT_MEMSIZE*100); if ( p == NULL ) break; backup = p; if ( i < 5 ) { fprintf( stderr, "Guessing %02d's heap: 0x%08x\n", i, backup ); ++i; } } while (1); fprintf( stderr, "...\n"); fprintf( stderr, "Guessing end heap: 0x%08x\n", backup ); } int main(int argc, char *argv[]) { void *p; void *backup; fprintf( stderr, "Guessing start stack: 0x%08x\n", &p ); fprintf( stderr, "Guessing next stack: 0x%08x\n", &backup ); p = (char *)malloc(0); fprintf( stderr, "Guessing start heap: 0x%08x\n", p ); printf( " input 1(stack) or 2(heap): "); switch( getchar() ) { case '1' : attach_signal(); check_stack(); break; case '2' : check_heap(); break; default : fprintf( stderr, "unknown input.\n" ); } return 0; }