/* * stack_pointer.c / ver 0x01 | (C)opyleft 2008 by oozie | http://blog.ooz.ie/ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Illustrates stack movement by reading ESP register on an x86_32 architecture. * * The program is considered free software; you can redistribute and/or modify * it under the terms of the GNU General Public License version 3 or any later * version, as published by the Free Software Foundation; If you do modify it, * please leave the information about the author unchanged. The full text of * latest GPL licence is available at http://www.gnu.org/licences/gpl.txt */ #include #include #include #define MAX_FRAMES 0x10 #define MID_MSG1 " -> way to the bottom of the stack (via recursive calls)" #define MID_MSG2 " <- way back to the top of the stack (via returns)" char *spaces; void r(int i) { int esp; char *space_ptr=spaces; asm ( "movl %%esp, %0;" : "=r"(esp) ); space_ptr+=i*sizeof(char); printf("%s-> calling r(%i), esp = 0x%x\n", space_ptr, i, esp); if (i) r(i-1); else printf("%s%s\n%s%s\n", space_ptr, MID_MSG1, space_ptr, MID_MSG2); printf("%s<- returning from r(%i), esp = 0x%x\n", space_ptr, i, esp); return; } int main(void) { /* Allocating a string of spaces and terminating with \0 */ spaces=(char *)malloc(sizeof(char)*MAX_FRAMES); memset(spaces, ' ', MAX_FRAMES*sizeof(char)); spaces[MAX_FRAMES]=0; printf("Starting a recursive call of a function on the top of the stack...\n"); /* Called function will iterate MAX_FRAMES times */ r(MAX_FRAMES); printf("Last return brought us back to the top of stack stack\n"); return 0; }