23.03.2013 Views

Quick introduction to reverse engineering for beginners

Quick introduction to reverse engineering for beginners

Quick introduction to reverse engineering for beginners

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1.2 Stack<br />

Stack — is one of the most fundamental things in computer science. 6 .<br />

Technically, this is just memory block in process memory + ESP register as a pointer within this block.<br />

Most frequently used stack access instructions are PUSH and POP. PUSH subtracting ESP by 4 and then<br />

writing contents of its sole operand <strong>to</strong> the memory address pointing by ESP.<br />

POP is <strong>reverse</strong> operation: get a data from memory pointing by ESP and then add 4 <strong>to</strong> ESP. Of course, this<br />

is <strong>for</strong> 32-bit environment. 8 will be here instead of 4 in x64 environment.<br />

After stack allocation, ESP pointing <strong>to</strong> the end of stack. PUSH increasing ESP, and POP decreasing. The<br />

end of stack is actually at the beginning of allocated <strong>for</strong> stack memory block. It seems strange, but it is so.<br />

What stack is used <strong>for</strong>?<br />

1.2.1 Save return address where function should return control after execution<br />

While calling another function by CALL instruction, the address of point exactly after CALL instruction is<br />

saved <strong>to</strong> stack, and then unconditional jump <strong>to</strong> the address from CALL operand is executed.<br />

CALL is PUSH address_after_call / JMP operand instructions pair equivalent.<br />

RET is fetching value from stack and jump <strong>to</strong> it — it is POP tmp / JMP tmp instructions pair equivalent.<br />

Stack overflow is simple, just run eternal recursion:<br />

void f()<br />

{<br />

f();<br />

};<br />

MSVC 2008 reporting about problem:<br />

c:\tmp6>cl ss.cpp /Fass.asm<br />

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 <strong>for</strong> 80x86<br />

Copyright (C) Microsoft Corporation. All rights reserved.<br />

ss.cpp<br />

c:\tmp6\ss.cpp(4) : warning C4717: ’f’ : recursive on all control paths, function will<br />

cause runtime stack overflow<br />

... but generates right code anyway:<br />

?f@@YAXXZ PROC ; f<br />

; File c:\tmp6\ss.cpp<br />

; Line 2<br />

push ebp<br />

mov ebp, esp<br />

; Line 3<br />

call ?f@@YAXXZ ; f<br />

; Line 4<br />

pop ebp<br />

ret 0<br />

?f@@YAXXZ ENDP ; f<br />

... Also, if we turn on optimization (/Ox option), the optimized code will not overflow stack, but will<br />

work correctly 7 :<br />

?f@@YAXXZ PROC ; f<br />

; File c:\tmp6\ss.cpp<br />

; Line 2<br />

6 http://en.wikipedia.org/wiki/Call_stack<br />

7 irony here<br />

4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!