The Stack

From SkullSecurity
Jump to navigation Jump to search
Assembly Language Tutorial
Please choose a tutorial page:

The stack is, at best, a difficult concept to understand. However, understanding the stack is essential to reverse engineering code.

The stack register, esp, is basically a register that points to an arbitrary location in memory called "the stack". The stack is just a really big section of memory where temporary data can be stored and retrieved. When a function is called, some stack space is allocated to the function, and when a function returns the stack should be in the same state it started in.

The stack always grows downwards, towards lower values. The esp register always points to the lowest value on the stack. Anything below esp is considered free memory that can be overwritten.

The stack stores function parameters, local variables, and the return address of every function.

Function Parameters

When a function is called, its parameters are typically stored on the stack before making the call. Here is an example of a function call in C:

func(1, 2, 3); 

And here is the equivalent call in assembly:

push 3
push 2
push 1
call func
add esp, 0Ch

The parameters are put on the stack, then the function is called. The function has to know it's getting 3 parameters, which is why function parameters have to be declared in C.

After the function returns, the stack pointer is still 12 bytes ahead of where it started. In order to restore the stack to where it used to be, 12 (0x0c) has to be added to the stack pointer. The three pushes, of 4 bytes each, mean that a total of 12 was subtracted from the stack.

Here is what the initial stack looked like (with ?'s representing unknown stack values):

esp ?
esp - 4 ?
esp - 8 ?
esp - 8 ?
esp - 8 ?

Note that the same 5 32-bit stack values are shown in all these examples, with the stack pointer at the left moved.

call and ret Revisited

Local Variables

Frame Pointer

Balance

Questions

Feel free to edit this section and post questions, I'll do my best to answer them. But you may need to contact me to let me know that a question exists.