stack lab
overview
To get a better understanding of the stack and how it is utilized in function calls, I wanted to do a little lab to just explore how the stack looks and is interacted with in a live program.
Following the example in 0xinfection.xyz’s page on the stack, I created a small C program to explore some simple stack operations.

analysis
After compiling the program and running it in x32dbg, I once again used the symbols tab to set a breakpoint on our main function.
So to start, I can see that the EBP register, or base pointer register is pushed onto the stack, and then the ESP register value is stored in the EBP register.

Right now I can see that the EBP and ESP registers are different, so lets step over to the next instruction to see what the values change to.

So after stepping into that push instruction at 0x00901400, I can see that the EBP and ESP register values have updated. The EBP register now contains the value 0x006FFE8C, and the ESP register now contains the value 0x006FFE6C.

This makes sense given what I’ve learned about the stack. When the base pointer was pushed onto the stack, it moved the stack pointer downward in memory, so the ESP register was decremented.
Now if I step through one more instruction to the mov instruction at 0x009014001, I can see that the stack and base pointers are now the same, as the stack pointer was moved into the EBP register.

Now looking at the function again, I can see that the ECX or counter register is pushed onto the stack, followed by our two values (5 & 10), and finally the function call to our calculate function.

So because the stack pointer is at 006FFE6C right now, and we’re pushing three times onto the stack, then we should see the stack pointer decrement by 0x12 (4 x 3) resulting in 0x6FFE60.

By looking at the FPU viewer I can see that I was correct, and the stack pointer changed exactly by 12 bytes!
Now we can start looking at how exactly the calculate function uses these values. By jumping to the start of the function, I can see that same pattern I saw in the main function of pushing the EBP register value onto the stack, and then moving the ESP register value into EBP.

For the actual calculation, I can see that the value at EBP + 8 is moved into EAX, the arithmetic register. Based on what I learned in the main function, 0x8 should be the 0xA or 10 value.
So in the main function, after updating the EBP and ESP registers, the program pushed ECX onto the stack, moving it by 4 bytes. Then it pushed the first parameter onto the stack (The A value), which once again moved it by 4 bytes. Finally the second parameter was pushed onto the stack and once again the stack pointer moved by 4 bytes.
When the calculate function is moving the value at EBP + 8 into EAX, it’s moving the first parameter, the A value into the EAX register.
Then the add instruction takes the value in EAX and the value at EBP + C (The second parameter), and returns with EAX containing the result of the operation.