2
$\begingroup$

Are data and return addresses both pushed on the same stack space? If yes, couldn't this piece of code cause problems:

CALL r1 //the PC is now the contents of register 1, return address is pushed on the stack.  
POP r2  //pop the top of the stack and put the data in register 2.  
RET     //return from subroutine

The POP instruction would delete the return address of the subroutine so the RET instruction will return to the wrong location.

$\endgroup$
1
$\begingroup$

Yes, they are stored on the same stack. Yes, that sequence of code could cause problems. It is up to the compiler (or the assembly language programmer) not to do that.

A compiler will typically ensure that the start of the function pushes some number of words (say $n$ words), and that the end of the function pops off exactly as much as was pushed -- no more, and no less. As long as you do that, the return address will be left undisturbed and the RET will return back to right after the CALL. If you don't follow that kind of convention, then all sorts of strange things can happen, exactly as you say -- so make sure you follow the convention.

| cite | improve this answer | |
$\endgroup$
0
$\begingroup$

That's exactly what can be exploited using buffer overflows. If you overwrite the return address of a function by writing beyond the bounds of, e.g., a vulnerable array, you can control where the function returns to.

The OS kernels try to prevent parts of this by randomizing the memory locations where your code is loaded to, for instance. So you can't simply jump into arbitrary piece of your code, but then again there is Return-Oriented Programming (ROP). In ROP, you return to other parts of the exploited code, because the relative addresses of different functions within the same program are the same, and you can address other functions in the code by debugging them to get the relative addresses and then use pointer arithmetic.

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ But are they stored on the same place? for example if I PUSH something on the stack at place X, will the return address of a CALL instruction be at X+1? $\endgroup$ – model world Feb 15 '15 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.