x64 Assembly Tutorial 26: Intro to the Stack

We will begin looking at the stack today. The stack can come across as somewhat confusing. It can seem that there is some arcane magic about. I think this happens when we introduce the stack along with stack frames. For this reason, I'll not be looking at stack frames yet (besides, stack frames aren't assembly, they're a calling convention!). The stack segment is just a chunk of RAM, same as the data and code segments. The stack's instructions are just MOV instructions that automatically increase or decrease the RSP (Stack Pointer) register. There's nothing else to it. The RSP is used implicitly. You could easily MOV into the stack segment and increment or decrement the RSP yourself. A Stack is a standard data structure which traditionally allows 2 operations, Pushing and Popping. When you want to add a value to the stack you "Push" it and when you want it back off the stack you "Pop" it. Stacks are called LIFO (Last in first out) since the order that items are pushed is the opposite to the order they will be popped out. We will look at PUSH, POP, CALL, RET, PUSHF and POPF. If we execute these instructions with a memory window open to wherever the stack pointer points, we can see exactly what is going on. If you wish to use one of the non-scratch registers in your procedure (say RBX), you could push it (push rbx) first to save its value. When your done in your procedure you can pop this register to restore its value (pop rbx). Always remember that the stack instructions reference RAM and RAM is extremely slow. Don't push and pop in the middle of a tight loop or you'll slow your code down!