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.
CodePudding user response:
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:
- where
backtrace
should return, - where
sec
should return, - where
first
should return, and - where
main
should return.
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?
CodePudding user response:
Easiest option here would probably be using exit()
in first()
:
void first()
{
printf("print this from first");
sec();
exit(0);
printf("dont print this");
}
Now if you don't want to edit first()
at all, you're gonna have to use goto. (3/10 do not recommend)