Chapter 8
Chapter 8
8.1 Introduction
Different names:
o C/C++ ➔ Functions
o Java ➔ Methods
o MASM ➔ Procedures
It contains:
o Passed arguments
o Return address
o Local variables
o Saved registers
1. Push arguments.
1. Passing by Value
Example:
push val2
push val1
call AddTwo
val2
val1
Equivalent C++:
2. Passing by Reference
Example:
call Swap
Equivalent C++:
Swap(&val1, &val2);
3. Passing Arrays
Example:
call ArrayFill
Why?
Passing the whole array by value would be very slow and waste stack
space.
Super Summary Table 🔥
What is
Type Example C++ Version
Pushed?
Stack Frames, and Calling Conventions (Irvine Chapter 8.2.3 & 8.2.4)
o Restore EBP.
o RET to caller.
AddTwo PROC
push ebp
pop ebp
ret
AddTwo ENDP
✅ Result is returned in EAX.
2. Base-Offset Addressing
Example offsets:
After calling a function, you must remove the parameters from the
stack.
Otherwise:
Example mistake:
push 6
push 5
call AddTwo
Correct ways:
Example:
push 6
push 5
call AddTwo
Example:
AddTwo PROC
push ebp
pop ebp
AddTwo ENDP
C Calling STDCALL
Feature
Convention Convention
Callee (inside
Who cleans the stack? Caller
function)
C Calling STDCALL
Feature
Convention Convention
✅ Final Tip:
A typical stack frame after push ebp and mov ebp, esp looks like:
Stack Content Address
Parameter (from
[ebp + 8]
caller)
📦 Local Variables
Example (C++):
int x = 10;
int y = 20;
Assembly equivalent:
asm
CopyEdit
push ebp
pop ebp
ret
✅ Important: Reset ESP before popping EBP to safely destroy local variables.
✨ Using Names for Local Variables
asm
CopyEdit
mov X_local, 10
mov Y_local, 20
🔗 Reference Parameters
Example:
cmp ecx, 0
L1:
call RandomRange
loop L1
L2:
pop ebp
✅ Key Point: Handle pointer + loop carefully when working with arrays.
LEA Instruction
Example:
✅ Key Point: Can't use OFFSET for runtime stack addresses — only LEA.
ENTER automatically:
1. push ebp
Syntax:
Example (equivalent):
enter 8, 0
; same as:
push ebp
sub esp, 8
leave
; same as:
pop ebp
⚡ TL;DR (Summary)
Reference
Access via [ebp+offset]
Parameters
o Shows:
Passed parameters
Return address
Local variables
Saved registers
WriteStackFrame PROTO,
✨ Example Program:
main PROC
exit
main ENDP
assembly
CopyEdit
; Define counts
PARAMS = 2
LOCALS = 2
SAVED_REGS = 2
mov a, 0AAAAh
mov b, 0BBBBh
Addre
Value Description
ss
0000222 ebp+1
2nd parameter (y)
2 2
0000111
ebp+8 1st parameter (x)
1
0040108
ebp+4 Return address
3
0012FFF
ebp+0 Saved EBP
0
0000AAA
ebp-4 Local variable (a)
A
0000BBB
ebp-8 Local variable (b)
B
EAEAEAE
ebp-12 Saved EAX
A
🧠 Extra Tip:
WriteStackFrameName PROTO,
numParam:DWORD,
numLocalVal:DWORD,
numSavedReg:DWORD,
File: Irvine32.asm
Path: C:\Irvine\Examples\Lib32
🎯 Summary:
✅ True/False Questions:
1. True
o A stack frame always has the caller’s return address and the
subroutine’s local variables.
2. True
3. True
4. False
5. True
✍ Short Answer:
A:
🎯 Quick Summary: