07 Procedures
07 Procedures
PROCEDURES
Computer Organization and
Assembly Language
POP Operation
Related Instructions
10 top
9
8
7
6
5
4
3
2
1 bottom
00001000 00000006
ESP
00000FFC
00000FF8
00000FF4
00000FF0
* SP in Real-address mode
Stack Addressing Computer Organization and Assembly Language – NUCES -slide 4
PUSH OPERATION
A 32-bit push operation decrements the stack pointer by 4
and copies a value into the location pointed to by the stack
pointer.
BEFORE AFTER
00000FF8 00000FF8
00000FF4 00000FF4
00000FF0 00000FF0
PUSH 0A5h
Stack Addressing Computer Organization and Assembly Language – NUCES -slide 5
PUSH OPERATION (CONT.)
Same stack after pushing two more integers:
Offset
00001000 00000006
00000FFC 000000A5
00000FF8 00000001
The stack grows downward. The area below ESP is always available
(unless the stack has overflowed).
BEFORE AFTER
00000FF0 00000FF0
Pop EAX
EAX = 00000002
Stack Addressing Computer Organization and Assembly Language – NUCES -slide 7
PUSH AND POP INSTRUCTIONS
PUSH syntax:
PUSH r/m16
PUSH r/m32
PUSH imm32
POP syntax:
POP r/m16
POP r/m32
To pass arguments
Procedure Parameters
USES Operator
sample PROC
.
.
ret
sample ENDP
MySub PROC
00000040 is the offset 00000040 mov eax,edx
.
of the first instruction
.
inside MySub
ret
MySub ENDP
Sub1 PROC
.
.
call Sub2
ret
Sub1 ENDP (ret to main)
Sub3 PROC
.
.
ret
Sub3 ENDP
main PROC
jmp L2 ; error
L1:: ; global label
exit
main ENDP
sub2 PROC
L2: ; local label
jmp L1 ; ok
ret
sub2 ENDP
Call-by-reference
Receives pointers
Directly manipulates parameter storage
What if you wanted to calculate the sum of two or three arrays within
the same program?
ArraySum PROC
; Receives: ESI points to an array of doublewords,
; ECX = number of array elements.
; Returns: EAX = sum
;-----------------------------------------------------
mov eax,0 ; set the sum to zero
ret
ArraySum ENDP
Call-by-value
SumOf PROC ; sum of three integers
add eax,ebx ; 2
add eax,ecx ; 3
ret
SumOf ENDP
Stack Addressing Computer Organization and Assembly Language – NUCES -slide 24
PROS AND CONS OF THE REGISTER METHOD
Advantages
Convenient and easier
Faster
Disadvantages
Only a few parameters can be passed using the register
method
Only a small number of registers are available
push number1
push number2
call sum
push EBP
mov EBP,ESP
Stack Addressing Computer Organization and Assembly Language – NUCES -slide 28
CLEARING THE STACK PARAMETERS
of parameters
Called procedure
Code becomes modular (parameter clearing is done in
only one place)
Cannot be used with variable number of parameters
Called procedure
Preferred method as the code becomes modular (state
preservation is done only once and in one place)
Avoids the program maintenance problems mentioned
Chapter#8
Kip R. Irvine
7th edition