Stack
Last updated
Last updated
A few things to consider in Stack data structure:
LIFO (Last in, First out)(As shown in above image, last object/entry pushed, is the first one to be taken out)
Grows from Higher to lower address(In above image, Object 1 will have address as x+2, Object 2 will have address as x+1, and Object 3 will have address as x, where x can be understood as a placeholder for specific address.)
ESP and EBP are two registers specific for stack only. EBP contains base address of the stack, i.e where in memory the stack is present, and ESP points to the top of Stack, so that newer object/entry knows where to get stored). With each stack instruction ESP values get updated.
Push and Pop instructions are used to place a value inside stack and remove value from stack respectively. Other Stack instructions are call, leave, enter, ret.
Used by process/thread to store temporary data such as Local variables and arguments.
Lets understand this with a code (stack.nasm)
Loading the compiled program in gdb.
Here, in define hook-stop, we will also look the top 8 bytes on the stack. (x/8xb $esp)
Start the execution and analysing how data is getting stored and removed from stack.
Storing the values from register into stack using PUSH. (One the right side, a simpler way of stack storage is also shown, below)
Lets look into a few important things:
AL/AH are 1 byte register, AX is 2 byte and EAX is 4 byte.
Pushing EAX will push 4 bytes into stack. If data inside register is less than 4 byte, 0 (zero’s) are used as padding (EAX has 0x10 inside it, on pushing the data in stack, 0x00000010 will be pushed)
Pushing CX will push 2 bytes into stack.
Now, time to Pop the values out.
Since edx, ecx, ebx are 4 byte (32 bit) registers, they will be taking 4 bytes from top of the stack during pop instruction (specified using different colours).
Visualizing data in different format, after being pushed.
Lets dive deeper and look on how registers and memory is used to operate on data.
Instructions are divided into following category which we are going to cover.
Moving Data
Arithmetic Instructions
Control Instructions
Loop Instruction
Logical Instruction
Functions
Strings