cstack-frame

How go back to another stack frame? C


EDIT: thank alot

Im understanding now that I should use gdb

I ask for understand how stack frame working and how change things

exit(0) and goto its not option

How can change that fun 'sec' will return to main? the output will be:

print start main
print this from first
print this from sec
print exit main
void sec() 
{
    
   /*change only here */
   printf("print this from sec");
}
void first() 
{
    printf("print this from first");
    sec();
    printf("dont print this");
}
 
int main() {
    
    printf("print start main");
    first();
    printf("print exit main\n");
    
    return 0;
}

I dont want add asm code, only C. I try to find the address of the rbp but I dont know how.


Solution

  • Disclaimer: this code should not exist. It is non-portable, makes a lot of assumptions, and relies on a gaping UB. Nevertheless,

    #include <execinfo.h>
    
    void sec() 
    {
        /*change only here */
        void * bt[4];
        int size = backtrace(bt, 4);
    
        while (bt[size] != bt[1])
            size++;
        bt[size++] = bt[2];
    
        while (bt[size] != bt[2])
            size++;
        bt[size] = bt[3];
        printf("print this from sec");
    }
    

    backtrace return an array of four pointers:

    The following two loops go up the stack looking for those addresses, and patches them to point to next frame.

    Try to comment out the second loop, and observe that print exit main is printed twice. Do you see why?