You are on page 1of 8

Presentation Outline

Stack and Procedures


 Runtime Stack
 Stack Operations
Computer Organization  Defining and Using Procedures
&  Program Design Using Procedures
Assembly Language Programming

Dr Adnan Gutub
aagutub ‘at’ uqu.edu.sa
[Adapted from slides of Dr. Kip Irvine: Assembly Language for Intel-Based Computers]
Most Slides contents have been arranged by Dr Muhamed Mudawar & Dr Aiman El-Maleh from Computer Engineering Dept. at KFUPM
Stack and Procedures Computer Organization & Assembly Language Programming slide ٢/46

What is a Stack? Runtime Stack


 Stack is a Last-In-First-Out (LIFO) data structure  Runtime stack: array of consecutive memory locations
 Analogous to a stack of plates in a cafeteria  Managed by the processor using two registers
 Plate on Top of Stack is directly accessible  Stack Segment register SS
 Two basic stack operations  Not modified in protected mode, SS points to segment descriptor

 Push: inserts a new element on top of the stack  Stack Pointer register ESP
 Pop: deletes top element from the stack  For 16-bit real-address mode programs, SP register is used

 View the stack as a linear array of elements  ESP register points to the top of stack
 Insertion and deletion is restricted to one end of array  Always points to last data item placed on the stack

 Stack has a maximum capacity  Only words and doublewords can be pushed and popped
 When stack is full, no element can be pushed  But not single bytes

 When stack is empty, no element can be popped  Stack grows downward toward lower memory addresses
Stack and Procedures Computer Organization & Assembly Language Programming slide ٣/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٤/46

Runtime Stack Allocation Presentation Outline


 .STACK directive specifies a runtime stack
 Operating system allocates memory for the stack  Runtime Stack
high
 Runtime stack is initially empty ESP = 0012FFC4 address  Stack Operations
?
 The stack size can change dynamically at runtime ?  Defining and Using Procedures
?
 Stack pointer ESP ?  Program Design Using Procedures
?
?
 ESP is initialized by the operating system ?
?
 Typical initial value of ESP = 0012FFC4h .
.
.
 The stack grows downwards ?
 The memory below ESP is free low
address
 ESP is decremented to allocate stack memory
Stack and Procedures Computer Organization & Assembly Language Programming slide ٥/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٦/46

١
Stack Instructions Push Instruction
 Two basic stack instructions:  Push source32 (r/m32 or imm32)
 push source  ESP is first decremented by 4
 pop destination  ESP = ESP – 4 (stack grows by 4 bytes)
 Source can be a word (16 bits) or doubleword (32 bits)  32-bit source is then copied onto the stack at the new ESP
 General-purpose register  [ESP] = source32
 Segment register: CS, DS, SS, ES, FS, GS  Push source16 (r/m16)
 Memory operand, memory-to-stack transfer is allowed  ESP is first decremented by 2
 Immediate value  ESP = ESP – 2 (stack grows by 2 bytes)
 Destination can be also a word or doubleword  16-bit source is then copied on top of stack at the new ESP
 General-purpose register  [ESP] = source16

 Segment register, except that pop CS is NOT allowed  Operating system puts a limit on the stack capacity
 Memory, stack-to-memory transfer is allowed  Push can cause a Stack Overflow (stack cannot grow)
Stack and Procedures Computer Organization & Assembly Language Programming slide ٧/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٨/46

Examples on the Push Instruction Pop Instruction


 Suppose we execute:  Pop dest32 (r/m32)
The stack grows
 PUSH EAX ; EAX = 125C80FFh  32-bit doubleword at ESP is first copied into dest32
downwards
 PUSH EBX ; EBX = 2Eh  dest32 = [ESP]
The area below
 PUSH ECX ; ECX = 9B61Dh  ESP is then incremented by 4
ESP is free
 ESP = ESP + 4 (stack shrinks by 4 bytes)
BEFORE AFTER  Pop dest16 (r/m16)
0012FFC4 ESP 0012FFC4  16-bit word at ESP is first copied into dest16
0012FFC0 125C80FF
0012FFC0  dest16 = [ESP]
0012FFBC 0012FFBC 0000002E
 ESP is then incremented by 2
0012FFB8 0012FFB8 0009B61D ESP  ESP = ESP + 2 (stack shrinks by 2 bytes)
0012FFB4 0012FFB4
 Popping from an empty stack causes a stack underflow
Stack and Procedures Computer Organization & Assembly Language Programming slide ٩/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ١٠/46

Examples on the Pop Instruction Uses of the Runtime Stack


 Runtime Stack can be utilized for
 Suppose we execute: The stack shrinks
 Temporary storage of data and registers
 POP SI ; SI = B61Dh upwards
 Transfer of program control in procedures and interrupts
 POP DI ; DI = 0009h The area at & above
 Parameter passing during a procedure call
ESP is allocated
 Allocating local variables used inside procedures
BEFORE AFTER
 Stack can be used as temporary storage of data
0012FFC4 0012FFC4

0012FFC0 125C80FF 0012FFC0 125C80FF  Example: exchanging two variables in a data segment

0012FFBC 0000002E 0012FFBC 0000002E push var1 ; var1 is pushed


ESP
push var2 ; var2 is pushed
0012FFB8 0009B61D ESP 0012FFB8 0009B61D
pop var1 ; var1 = var2 on stack
0012FFB4 0012FFB4
pop var2 ; var2 = var1 on stack

Stack and Procedures Computer Organization & Assembly Language Programming slide ١١/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ١٢/46

٢
Temporary Storage of Registers Example: Nested Loop
 Stack is often used to free a set of registers When writing a nested loop, push the outer loop counter
push EBX ; save EBX ECX before entering the inner loop, and restore ECX after
push ECX ; save ECX exiting the inner loop and before repeating the outer loop
. . .
mov ecx, 100 ; set outer loop count
; EBX and ECX can now be modified
L1: . . . ; begin the outer loop
. . . push ecx ; save outer loop count
pop ECX ; restore ECX first, then
pop EBX ; restore EBX mov ecx, 20 ; set inner loop count
L2: . . . ; begin the inner loop
. . . ; inner loop
 Example on moving DX:AX into EBX loop L2 ; repeat the inner loop
push DX ; push most significant word first
. . . ; outer loop
push AX ; then push least significant word pop ecx ; restore outer loop count
pop EBX ; EBX = DX:AX loop L1 ; repeat the outer loop

Stack and Procedures Computer Organization & Assembly Language Programming slide ١٣/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ١٤/46

Push/Pop All Registers Stack Instructions on Flags


 pushad  Special Stack instructions for pushing and popping flags
 Pushes all the 32-bit general-purpose registers
 pushfd
 EAX, ECX, EDX, EBX, ESP, EBP, ESI, and EDI in this order
 Initial ESP value (before pushad) is pushed  Push the 32-bit EFLAGS
 ESP = ESP – 32  popfd
 pusha
 Pop the 32-bit EFLAGS
 Same as pushad but pushes all 16-bit registers AX through DI
 ESP = ESP – 16  No operands are required
 popad  Useful for saving and restoring the flags
 Pops into registers EDI through EAX in reverse order of pushad
 ESP is not read from stack. It is computed as: ESP = ESP + 32  For 16-bit programs use pushf and popf
 popa  Push and Pop the 16-bit FLAG register
 Same as popad but pops into 16-bit registers. ESP = ESP + 16
Stack and Procedures Computer Organization & Assembly Language Programming slide ١٥/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ١٦/46

Next . . . Procedures
 A procedure is a logically self-contained unit of code
 Called sometimes a function, subprogram, or subroutine
 Runtime Stack
 Receives a list of parameters, also called arguments
 Stack Operations
 Performs computation and returns results
 Defining and Using Procedures  Plays an important role in modular program development
 Program Design Using Procedures  Example of a procedure (called function) in C language
int sumof ( int x,int y,int z ) {
Result type int temp; Formal parameter list
temp = x + y + z;
return temp;
Return function result
}
 The above function sumof can be called as follows:
sum = sumof( num1,num2,num3 ); Actual parameter list
Stack and Procedures Computer Organization & Assembly Language Programming slide ١٧/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ١٨/46

٣
Defining a Procedure in Assembly Documenting Procedures
 Assembler provides two directives to define procedures  Suggested Documentation for Each Procedure:
 PROC to define name of procedure and mark its beginning  Does: Describe the task accomplished by the procedure
 ENDP to mark end of procedure
 Receives: Describe the input parameters
 A typical procedure definition is
 Returns: Describe the values returned by the procedure
procedure_name PROC  Requires: List of requirements called preconditions
. . .
; procedure body  Preconditions
. . .  Must be satisfied before the procedure is called
procedure_name ENDP  If a procedure is called without its preconditions satisfied, it will
probably not produce the expected output
 procedure_name should match in PROC and ENDP

Stack and Procedures Computer Organization & Assembly Language Programming slide ١٩/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٠/46

Example of a Procedure Definition The Call Instruction


 The sumof procedure receives three integer parameters  To invoke a procedure, the call instruction is used
 Assumed to be in EAX, EBX, and ECX  The call instruction has the following format
 Computes and returns result in register EAX
call procedure_name
;------------------------------------------------
; Sumof: Calculates the sum of three integers  Example on calling the procedure sumof
; Receives: EAX, EBX, ECX, the three integers  Caller passes actual parameters in EAX, EBX, and ECX
; Returns: EAX = sum
; Requires: nothing  Before calling procedure sumof
;------------------------------------------------
mov EAX, num1 ; pass first parameter in EAX
sumof PROC
add EAX, EBX ; EAX = EAX + second number mov EBX, num2 ; pass second parameter in EBX
add EAX, ECX ; EAX = EAX + third number mov ECX, num3 ; pass third parameter in ECX
ret ; return to caller call sumof ; result is in EAX
sumof ENDP mov sum, EAX ; save result in variable sum
 The ret instruction returns control to the caller  call sumof will call the procedure sumof
Stack and Procedures Computer Organization & Assembly Language Programming slide ٢١/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٢/46

How a Procedure Call / Return Works Details of CALL and Return


 How does a procedure know where to return? Address Machine Code Assembly Language IP-relative call
.CODE EIP = 00401036
 There can be multiple calls to same procedure in a program + 0000004B
main PROC
 Procedure has to return differently for different calls 00401020 A1 00405000 mov EAX, num1 EIP = 00401081
00401025 8B 1D 00405004 mov EBX, num2
 It knows by saving the return address (RA) on the stack 0040102B 8B 0D 00405008 mov ECX, num3
Before Call
ESP = 0012FFC4
 This is the address of next instruction after call 00401031 E8 0000004B call sumof
After Call
00401036 A3 0040500C mov sum, EAX
 The call instruction does the following . . . . . . . . .
ESP = 0012FFC0
exit After Ret (Return)
 Pushes the return address on the stack ESP = 0012FFC4
main ENDP
 Jumps into the first instruction inside procedure
sumof PROC
Runtime Stack

 ESP = ESP – 4; [ESP] = RA; EIP = procedure address 00401081 03 C3 add EAX, EBX ESP
Allocated
ESP RA=00401036
 The ret (return) instruction does the following 00401083 03 C1 add EAX, ECX
00401085 C3 ret Free Area
 Pops return address from stack sumof ENDP
 Jumps to return address: EIP = [ESP]; ESP = ESP + 4 END main
Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٣/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٤/46

٤
Don’t Mess Up the Stack ! Nested Procedure Calls
 Just before returning from a procedure main PROC
.
 Make sure the stack pointer ESP is pointing at return address .
call Sub1 By the time Sub3 is called, the stack
exit contains all three return addresses
 Example of a messed-up procedure main ENDP

 Pushes EAX on the stack before returning Sub1 PROC


. return address of call Sub1
.
 Stack pointer ESP is NOT pointing at return address! call Sub2
ret return address of call Sub2
main PROC Stack Sub1 ENDP
call messedup return address of call Sub3 ESP
Sub2 PROC
. . . high addr .
.
exit Used call Sub3
ESP
main ENDP Return Addr
ret
ESP Sub2 ENDP
messedup PROC ESP EAX Value Where to return?
Sub3 PROC
push EAX Free Area
EAX value is NOT .
ret .
the return address! ret
messedup ENDP Sub3 ENDP

Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٥/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٦/46

Parameter Passing Passing Parameters in Registers


 Parameter passing in assembly language is different ;-----------------------------------------------------
; ArraySum: Computes the sum of an array of integers
 More complicated than that used in a high-level language
; Receives: ESI = pointer to an array of doublewords
 In assembly language ; ECX = number of array elements
; Returns: EAX = sum
 Place all required parameters in an accessible storage area ;-----------------------------------------------------
 Then call the procedure ArraySum PROC
mov eax,0 ; set the sum to zero
 Two types of storage areas used L1: add eax, [esi] ; add each integer to sum
add esi, 4 ; point to next integer
 Registers: general-purpose registers are used (register method) loop L1 ; repeat for array size
 Memory: stack is used (stack method) ret
ArraySum ENDP
 Two common mechanisms of parameter passing
 Pass-by-value: parameter value is passed ESI: Reference parameter = array address
 Pass-by-reference: address of parameter is passed ECX: Value parameter = count of array elements

Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٧/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٨/46

Preserving Registers Example on Preserving Registers


 Need to preserve the registers across a procedure call ;-----------------------------------------------------
 Stack can be used to preserve register values ; ArraySum: Computes the sum of an array of integers
; Receives: ESI = pointer to an array of doublewords
 Which registers should be saved? ; ECX = number of array elements
; Returns: EAX = sum
 Those registers that are modified by the called procedure ;-----------------------------------------------------
 But still used by the calling procedure ArraySum PROC
push esi ; save esi, it is modified
 We can save all registers using pusha if we need most of them push ecx ; save ecx, it is modified
 However, better to save only needed registers when they are few mov eax,0 ; set the sum to zero
L1: add eax, [esi] ; add each integer to sum
 Who should preserve the registers? add esi, 4 ; point to next integer
loop L1 ; repeat for array size
 Calling procedure: saves and frees registers that it uses
pop ecx ; restore registers
 Registers are saved before procedure call and restored after return pop esi ; in reverse order
ret
 Called procedure: preferred method for modular code No need to save EAX. Why?
ArraySum ENDP
 Register preservation is done in one place only (inside procedure)
Stack and Procedures Computer Organization & Assembly Language Programming slide ٢٩/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٠/46

٥
USES Operator Next . . .
 The USES operator simplifies the writing of a procedure
 Registers are frequently modified by procedures  Runtime Stack
 Just list the registers that should be preserved after USES
 Stack Operations
 Assembler will generate the push and pop instructions
 Defining and Using Procedures
ArraySum PROC
ArraySum PROC USES esi ecx push esi  Program Design Using Procedures
mov eax,0 push ecx
L1: add eax, [esi] mov eax,0
add esi, 4 L1: add eax, [esi]
loop L1 add esi, 4
ret loop L1
ArraySum ENDP pop ecx
pop esi
ret
ArraySum ENDP
Stack and Procedures Computer Organization & Assembly Language Programming slide ٣١/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٢/46

Program Design using Procedures Structure Chart


 Program Design involves the Following: Summation
Program (main)
 Break large tasks into smaller ones
 Use a hierarchical structure based on procedure calls
Clrscr PromptForIntegers ArraySum DisplaySum
 Test individual procedures separately

Integer Summation Program: WriteString ReadInt WriteString WriteInt


WriteInt

Write a program that prompts the user for multiple 32-bit integers,
stores them in an array, calculates the array sum, and displays the
sum on the screen. Structure Chart
Above diagram is called a structure chart
1. Prompt user for multiple integers
Main steps: 2. Calculate the sum of the array Describes program structure, division into procedure, and call sequence

3. Display the sum Link library procedures are shown in grey


Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٣/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٤/46

Integer Summation Program – 1 of 4 Integer Summation Program – 2 of 4


INCLUDE Irvine32.inc ;-----------------------------------------------------
; PromptForIntegers: Read input integers from the user
ArraySize EQU 5
; Receives: ESI = pointer to the array
.DATA ; ECX = array size
prompt1 BYTE "Enter a signed integer: ",0 ; Returns: Fills the array with the user input
prompt2 BYTE "The sum of the integers is: ",0 ;-----------------------------------------------------
array DWORD ArraySize DUP(?) PromptForIntegers PROC USES ecx edx esi
mov edx, OFFSET prompt1
.CODE
L1:
main PROC
call WriteString ; display prompt1
call Clrscr ; clear the screen
call ReadInt ; read integer into EAX
mov esi, OFFSET array
call Crlf ; go to next output line
mov ecx, ArraySize
mov [esi], eax ; store integer in array
call PromptForIntegers ; store input integers in array
add esi, 4 ; advance array pointer
call ArraySum ; calculate the sum of array
loop L1
call DisplaySum ; display the sum
exit ret
main ENDP PromptForIntegers ENDP
Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٥/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٦/46

٦
Integer Summation Program – 3 of 4 Integer Summation Program – 4 of 4
;----------------------------------------------------- ;-----------------------------------------------------
; ArraySum: Calculates the sum of an array of integers ; DisplaySum: Displays the sum on the screen
; Receives: ESI = pointer to the array, ; Receives: EAX = the sum
; ECX = array size ; Returns: nothing
; Returns: EAX = sum of the array elements ;-----------------------------------------------------
;-----------------------------------------------------
DisplaySum PROC
ArraySum PROC USES esi ecx
mov edx, OFFSET prompt2
mov eax,0 ; set the sum to zero
call WriteString ; display prompt2
L1:
call WriteInt ; display sum in EAX
add eax, [esi] ; add each integer to sum
add esi, 4 ; point to next integer call Crlf
loop L1 ; repeat for array size ret
DisplaySum ENDP
ret ; sum is in EAX END main
ArraySum ENDP

Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٧/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٨/46

Sample Output Parameter Passing Through Stack


 Parameters can be saved on the stack before a
Enter a signed integer: 550 procedure is called.
Enter a signed integer: -23  The called procedure can easily access the parameters
Enter a signed integer: -96 using either the ESP or EBP registers without altering
Enter a signed integer: 20 ESP register.
Enter a signed integer: 7  Example
Then, the assembly language
The sum of the integers is: +458 Suppose you want to code fragment looks like:
implement the following mov i, 25
pseudo-code: mov j, 4
i = 25; push 1
j = 4; push j
Test(i, j, 1); push i
call Test

Stack and Procedures Computer Organization & Assembly Language Programming slide ٣٩/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٤٠/46

Parameter Passing Through Stack Call & Return Instructions


Instruction Operand Note
Example: Accessing parameters on the CALL label name
Push IP
IP= IP + displacement relative to next instruction
stack
Test PROC Lower Address Push IP
CALL r/m IP = [r/m]
mov AX, [ESP + 4] ;get i
Push CS
add AX, [ESP + 8] ;add j ESP CALL label name (FAR) Push IP
sub AX, [ESP + 12] ;subtract parm 3 CS:IP=address of label name
ESP+4
(1) from sum Push CS
ESP+8 CALL m (FAR) Push IP
ret CS:IP= [m]
Test ENDP ESP+12
RET Pop IP
Pop IP
RET imm SP = SP + imm
Higher Address
Pop IP
RET (FAR) Pop CS
Pop IP
RET imm (FAR) Pop CS
SP = SP + imm

Stack and Procedures Computer Organization & Assembly Language Programming slide ٤١/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٤٢/46

٧
Freeing Passed Parameters From Stack Local Variables
 Use RET N instruction to free parameters from stack  Local variables are dynamic data whose values must be
preserved over the lifetime of the procedure, but not
Example: Accessing parameters on the beyond its termination.
stack
Test PROC  At the termination of the procedure, the current
mov AX, [ESP + 4] ;get i environment disappears and the previous environment
add AX, [ESP + 8] ;add j must be restored.
sub AX, [ESP + 12] ;subtract parm. 3
(1) from sum  Space for local variables can be reserved by subtracting
ret 12 the required number of bytes from ESP.
Test ENDP
 Offsets from ESP are used to address local variables.

Stack and Procedures Computer Organization & Assembly Language Programming slide ٤٣/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٤٤/46

Local Variables Summary


 Procedure – Named block of executable code
Pseudo-code (Java-like) Assembly Language
 CALL: call a procedure, push return address on top of stack
Test PROC  RET: pop the return address and return from procedure
push EBP
mov EBP, ESP  Preserve registers across procedure calls
sub ESP, 4
void Test(int i){
push EAX
 Runtime stack – LIFO structure – Grows downwards
int k;
mov DWORD PTR [EBP-4], 9  Holds return addresses, saved registers, etc.
mov EAX, [EBP + 8]
k = i+9;  PUSH – insert value on top of stack, decrement ESP
add [EBP-4], EAX
……
……  POP – remove top value of stack, increment ESP
}
pop EAX
mov ESP, EBP
pop EBP
ret 4
Test ENDP

Stack and Procedures Computer Organization & Assembly Language Programming slide ٤٥/46 Stack and Procedures Computer Organization & Assembly Language Programming slide ٤٦/46

You might also like