Function stacks, code sections and other misc hackery!

S

sukrit.mehra

Hi People,

Few of my colleuages were flexing their C muscles and they asked me
this question.

void Function(void);

int main(void)
{
int x=5;
Function();
x=10;

printf("%d", x);

return 0;
}



What would be the defination of Function such that printf prints 5
instead of 10?

Possibilities:
1. Write a macro to replace defination of printf. Not a neat solution,
so ignore!

2. The whole code would be loaded in the RAM somewhere, so all we have
to do is change the line x = 10 to x = 5 in the code section. So we
need address of that paritcular instruction. Can such a thing be done?
Also, are Code Sections usuaully RO? Is it architecture specific?
Compiler/LInker Specific?

3. This is the best solution, it's code is given below. Basically i
still don't fully understand it and the person who gave this to me,
doesn't want me to understand :)

void Function(void)
{
int i;
int *j=&i;//J points to i
*(j+2)+=7;//increment the value(return address) at j+2th loc by 7
//How do we know j+2 is the return address
//Why increment by 7?
//Basically what are the magic numbers?

}

What I can figure out is that they are playing with the return address
of the function and changing it to point to some other instruction. But
how? What is the strucutre of C's function stack? Where is the return
address stored? Is it complier specific? If yes, how to find such
details?


Thanks for your time!

Regards
Sukrit
 
M

Malcolm

void Function(void)
{
int i;
int *j=&i;//J points to i
*(j+2)+=7;//increment the value(return address) at j+2th loc by 7
//How do we know j+2 is the return address
//Why increment by 7?
//Basically what are the magic numbers?

}

What I can figure out is that they are playing with the return address
of the function and changing it to point to some other instruction. But
how? What is the strucutre of C's function stack? Where is the return
address stored? Is it complier specific? If yes, how to find such
details?
They are making a write in memory that the function doesn't own. That is
undefined behaviour.

On the particular system they are using the result of the undefined
behaviour may well be to corrupt the function return address, causing a few
instructions to be skipped. Undefined behaviour can be anything, including
execution of wrong machiune instructions .
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top