The stack can be visualized as a stack of memory objects. As things are added to the stack, they are added in last, and when they are removed the last item in the stack is removed first. In other words a stack is based on Last In First Out.
RSP is a pointer that points to the top of the stack (last item added to the memory stack.)
The SP in RSP mean “Stack Pointer.”
PUSH and POP
In Assembly Language there are two main functions that deal with the stack:
Push is an Assembly action that adds an item to the stack (which would go to the top.)
Pop is an Assembly action that removes an item from the stack (the last item added.)
In GDB you can monitor the stack by defining a hook-stop. In our case the commands below will show the top 4 values on the stack:
>> define hook-stop
>> x/4xg $rsp
Now when we step through the running of the application, we’ll see the last (top) of the stack in the output window, like so:
The instructor (Vivek Ramachandran) provided some source code to illustrate the stack (see below.)
; Filename: MovingData.nasm ; Author: Vivek Ramachandran ; Website: http://securitytube.net ; Training: http://securitytube-training.com ; ; ; Purpose: Stack instructions in 64-bit CPU global _start section .text _start: mov rax, 0x1122334455667788 push rax push sample push qword [sample] pop r15 pop r14 pop rbx ; exit the program gracefully mov rax, 0x3c mov rdi, 0 syscall section .data sample: db 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22
The script starts with adding a value to the RAX register (0x1122334455667788.)
Next a push command is made, which pushes the value in RAX to the top of the stack.
As seen above, our first instruction set the RAX register with 0x1122334455667788. The second instruction then pushed that value to the top of the stack (see the bottom pane.)
After that, the next instruction pushes a value of 0x6000d8 to the top of the stack (in the code it was the push of the label’s register value or push sample.)
Great, the next instruction is to push the value of that register value (i.e. push qword [sample]) and the value for sample is 0x2211ffeeddccbbaa.
As we can see above this value was directly added to the stack. Now for the pop commands…
The first pop is instructing a removal of the last item (at the top) of the stack to be removed and put into register R15 (i.e. pop r15.)
Sure enough, in the above screenshot we can see that the stack has updated (lower window pane) to now have the value 0x2211ffeeddccbbaa removed (now the top of the stack is 0x00000000006000d8. Also, r15 was updated to the previous top of the stack’s value (0x2211ffeeddccbbaa.)
The remaining pop instructions move an item from the top of the stack to r14, and then again they pop the top item into rbx.
The remaining functions simply close down the script.
Vivek’s script works really well at illustrating the nature of push and pop in Assembly.