Continuing the note series from “Malware Analysis Crash Course” (FLARE/Mandiant) — Chapter 2 covers the Stack, an extremely fundamental structure since almost every function call touches it.
The Stack
The stack is a region of memory that operates as LIFO (Last In, First Out) — temporarily holding data specific to each function call: local variables, parameters, and the return address. On x86, the stack grows toward lower addresses (even though diagrams conventionally draw the “top” at the top).
ESP (Extended Stack Pointer) always automatically points to the current top of the stack. Every stack operation boils down to two things: pushing a value in (PUSH) and popping a value out (POP).
The PUSH Instruction
PUSH always runs in exactly this 2-step sequence, and the order matters:
- Decrement
ESPby 4 first (allocate space) - Then write the operand’s value into the location
ESPnow points to
Equivalent to:
sub esp, 4
mov [esp], <operand>PUSH’s operand can be an immediate, a register, or a value from memory. If you push 1, 2, 3 in sequence, 3 (the last value pushed) ends up on top of the stack. To access earlier pushed values, use a positive offset from ESP (e.g. [esp+4] is the second element from the top).
The POP Instruction
POP does the reverse, also in a strict 2-step order:
- Read the value at the current
ESPlocation, write it to the destination - Increment
ESPby 4 (effectively “freeing” that element)
Equivalent to:
mov <destination>, [esp]
add esp, 4POP’s destination can be any register or memory location. If you push 1, 2, 3 and then pop in sequence, you get them back as 3, 2, 1 — true to LIFO behavior.
Why This Matters for RE
Mastering PUSH/POP (decrement-then-write, read-then-increment) is a hard requirement for understanding two bigger topics in the following chapters:
- Function calls (Chapter 3):
CALLactuallyPUSHes the address of the next instruction (the return address) onto the stack before jumping to the function;RETthenPOPs that address and jumps to it. - Stack frames (Chapter 4): function parameters and local variables are both located relative to
ESP/EBP— correctly understanding how PUSH/POP shiftESPis essential to computing which offset points to which variable.
A pretty common beginner mistake: getting the stack’s growth direction backwards, which leads to miscalculating the offsets when reading [ebp-8] or [ebp+8] (negative is a local variable, positive is a parameter — covered in more detail in Chapter 4).
Next chapter covers Flow Control — JMP, CALL, RET, and how functions calling each other is represented in assembly.