You are on page 1of 50

Chapter 6 procedure macros and

structure
Stack Operations
Runtime Stack
PUSH Operation
POP Operation
PUSH and POP Instructions
Using PUSH and POP
Example: Reversing a String
Related Instructions

2 Web site Examples


Runtime Stack
Imagine a stack of plates . . .
plates are only added to the top
plates are only removed from the top
LIFO structure

3 Web site Examples


Runtime Stack
Managed by the CPU, using two registers
SS (stack segment)
ESP (stack pointer) *

* SP in Real-address mode
4 Web site Examples
PUSH Operation (1 of 2)
A 32-bit push operation decrements the stack pointer
by 4 and copies a value into the location pointed to by
the stack pointer.

5 Web site Examples


PUSH Operation (2 of 2)
Same stack after pushing two more integers:

The stack grows downward. The area below ESP is


always available (unless the stack has overflowed).

6 Web site Examples


POP Operation
 Copies value at stack[ESP] into a register or variable.
 Adds n to ESP, where n is either 2 or 4.
 value of n depends on the attribute of the operand receiving the data

7 Web site Examples


PUSH and POP Instructions
PUSH syntax:
PUSH r/m16
PUSH r/m32
PUSH imm32
POP syntax:
POP r/m16
POP r/m32

8 Web site Examples


Using PUSH and POP
Save and restore registers when they contain important
values. PUSH and POP instructions occur in the opposite
order.
push esi ; push registers
push ecx
push ebx

mov esi,OFFSET dwordVal ; display some memory


mov ecx,LENGTHOF dwordVal
mov ebx,TYPE dwordVal
call DumpMem

pop ebx ; restore registers


pop ecx
pop esi

9 Web site Examples


Example: Nested Loop
When creating a nested loop, push the outer loop counter
before entering the inner loop:

mov ecx,100 ; set outer loop count


L1: ; begin the outer loop
push ecx ; save outer loop count

mov ecx,20 ; set inner loop count


L2: ; begin the inner loop
;
;
loop L2 ; repeat the inner loop

pop ecx ; restore outer loop count


loop L1 ; repeat the outer loop

10 Web site Examples


Related Instructions
PUSHFD and POPFD
push and pop the EFLAGS register
PUSHAD pushes the 32-bit general-purpose registers
on the stack
order: EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI
POPAD pops the same registers off the stack in
reverse order
PUSHA and POPA do the same for 16-bit registers

11 Web site Examples


Defining and Using Procedures
Creating Procedures
Documenting Procedures
Example: SumOf Procedure
CALL and RET Instructions
Nested Procedure Calls
Local and Global Labels
Procedure Parameters
Flowchart Symbols
USES Operator

12 Web site Examples


Creating Procedures
 Large problems can be divided into smaller tasks to make
them more manageable
 A named block of statements that ends in a return statement
 Declared using PROC and ENDP directives
 Must be assigned a name (valid identifier)
 A procedure is the ASM equivalent of a Java or C++ function
 Following is an assembly language procedure named sample:

sample PROC
.
.
ret
sample ENDP

13 Web site Examples


Documenting Procedures
Suggested documentation for each procedure:

 A description of all tasks accomplished by the procedure.


 Receives: A list of input parameters; state their usage and
requirements.
 Returns: A description of values returned by the procedure.
 Requires: Optional list of requirements called preconditions that must
be satisfied before the procedure is called.

If a procedure is called without its preconditions satisfied,


it will probably not produce the expected output.

14 Web site Examples


Example: SumOf Procedure
;---------------------------------------------------------
SumOf PROC
;
; Calculates and returns the sum of three 32-bit integers.
; Receives: EAX, EBX, ECX, the three integers. May be
; signed or unsigned.
; Returns: EAX = sum, and the status flags (Carry,
; Overflow, etc.) are changed.
; Requires: nothing
;---------------------------------------------------------
add eax,ebx
add eax,ecx
ret
SumOf ENDP

15 Web site Examples


CALL and RET Instructions
The CALL instruction calls a procedure
pushes offset of next instruction on the stack
copies the address of the called procedure into EIP
 The RET instruction returns from a procedure
pops top of stack into EIP

16 Web site Examples


CALL-RET Example (1 of 2)
main PROC
00000020 call MySub
0000025 is the offset of
00000025 mov eax,ebx
the instruction
.
immediately following
the CALL instruction .
main ENDP

MySub PROC
00000040 is the offset of 00000040 mov eax,edx
the first instruction .
inside MySub .
ret
MySub ENDP

17 Web site Examples


CALL-RET Example (2 of 2)
The CALL instruction
pushes 00000025 onto
the stack, and loads
00000040 into EIP

The RET instruction


pops 00000025 from
the stack into EIP

(stack shown before RET executes)

18 Web site Examples


Nested Procedure Calls

By the time Sub3 is called,


the stack contains all three
return addresses:

19 Web site Examples


Local and Global Labels
A local label is visible only to statements inside the same
procedure. A global label is visible everywhere. Global
label identified by double colon (::)
main PROC
jmp L2 ; error
L1:: ; global label
exit
main ENDP

sub2 PROC
L2: ; local label
jmp L1 ; ok
ret
sub2 ENDP

Not good to jump or loop outside the current procedure,


could corrupt runtime stack.
20 Web site Examples
Stack Frames
Stack Parameters
Local Variables
ENTER and LEAVE Instructions
LOCAL Directive

21 Web site Examples


Basic Concepts
Argument – value passed to a procedure by a
calling program
Parameter – value received by the called
procedures
Two basic types of procedure parameters
- Register parameter
- Stack parameter

22 Web site Examples


Register parameter
Used by Irvine32 and Irvine 16 libraries
Existing register contents often must be saved before
they can be loaded with argument value
Example – call dumpMem
pushad
mov esi,OFFSET array
mov ecx,LENGTHOF array
mov ebx,TYPE array
call DumpMem
popad

23 Web site Examples


Stack Parameters
Used by all high-level languages
More convenient than register parameters
The required arguments must be pushed on the stack
by a called program
Example – call DumpMem

push TYPE array


push LENGTHOF array
push OFFSET array
call DumpMem

24 Web site Examples



Stack Frame
Also known as an activation record
Area of the stack set aside for a procedure's return
address, passed parameters, saved registers, and local
variables
Created by the following steps:
Calling program pushes arguments on the stack and calls
the procedure.
The called procedure pushes EBP on the stack, and sets
EBP to ESP.
If local variables are needed, a constant is subtracted
from ESP to make room on the stack.

25 Web site Examples


EBP and ESP Registers
EBP is often called the base pointer or frame pointer
because it holds the base address of the stack frame.
EBP does not change value during the procedure.
EBP must be restored to its original value when a
procedure returns.
ESP register addresses data on the stack
ESP is often called the extended stack pointer register

26 Web site Examples


Stack
.data
Frame Example
sum DWORD ?
.code
push 6 ; second argument
push 5 ; first argument
call AddTwo ; EAX = sum
mov sum,eax ; save the sum

AddTwo PROC
push ebp
mov ebp,esp
.
.

27 Web site Examples



Explicit Access to Stack Parameters
A procedure can explicitly access stack parameters using
constant offsets from EBP
Example: [ebp + 8]
The AddTwo procedure can add two arguments’ values
and store the sum in EAX
AddTwo PROC
push ebp
mov ebp,esp ; base of stack frame
mov eax, [ebp + 12] ; second argument
add eax, [ebp + 8] ; first argument
pop ebp
ret 8 ; clean up the stack
AddTwo ENDP

28 Web site Examples


RET Instruction
Return from subroutine
Pops stack into the instruction pointer (EIP or IP).
Control transfers to the target address.
Syntax:
RET
RET n
Optional operand n causes n bytes to be added to the
stack pointer after EIP (or IP) is assigned a value.
After adding n to the stack pointer, reset it to the value
it had before the arguments were pushed on the stack
by the calling program

29 Web site Examples


Passing Arguments
Passing by Value
A copy of a variable’s value is passed to the
procedure
To protect the arguments against being changed
by the called procedure
The argument is a variable
Passing by Reference
The address of a variable is passed to procedure
The called procedure can modify the variable’s
contents via the address

30 Web site Examples


Passing Arguments by Reference (1 of
2)
The ArrayFill procedure fills an array with 16-bit
random integers
The calling program passes the address of the array,
along with a count of the number of array elements:

.data
count = 100
array WORD count DUP(?)
.code
push OFFSET array
push COUNT
call ArrayFill

31 Web site Examples


Passing Arguments by Reference (2 of
2)
ArrayFill can reference an array without knowing the array's
name:

ArrayFill PROC
push ebp
mov ebp,esp
pushad
mov esi,[ebp+12]
mov ecx,[ebp+8]
.
.

ESI points to the beginning of the array, so it's easy to use a


loop to access each array element.

32 Web site Examples



Local Variables
To explicitly create local variables, subtract their total
size from ESP.
The following example creates and initializes two 32-
bit local variables (we'll call them locA and locB):
MySub PROC
push ebp
mov ebp,esp
sub esp,8
mov [ebp-4],123456h ; locA
mov [ebp-8],0 ; locB
.
.

33 Web site Examples



LEA Instruction
The LEA instruction returns offsets of both direct and
indirect operands.
OFFSET operator can only return constant offsets.
LEA is required when obtaining the offset of a stack
parameter or local variable. For example:
CopyString PROC,
count:DWORD
LOCAL temp[20]:BYTE

mov edi,OFFSET count ; invalid operand


mov esi,OFFSET temp ; invalid operand
lea edi,count ; ok
lea esi,temp ; ok

34 Web site Examples


Example: Exchanging Two Integers
The Swap procedure exchanges the values of two 32-bit
integers. pValX and pValY do not change values, but the
integers they point to are modified.

Swap PROC USES eax esi edi,


pValX:PTR DWORD, ; pointer to first
integer
pValY:PTR DWORD ; pointer to second
integer

mov esi,pValX ; get pointers


mov edi,pValY
mov eax,[esi] ; get first integer
xchg eax,[edi] ; exchange with second
mov [esi],eax ; replace first integer
ret
Swap ENDP

35 Web site Examples


ENTER and LEAVE
ENTER instruction creates stack frame for a called
procedure
pushes EBP on the stack
sets EBP to the base of the stack frame
reserves space for local variables
LEAVE instruction terminates the stack frame for a
procedure
Reverse the action of a previous ENTER instruction
Restore ESP and ESP to the values were assigned when
the procedure was called

36 Web site Examples


LOCAL Directive
A local variable is created, used, and destroyed
within a single procedure
The LOCAL directive declares a list of local
variables
immediately follows the PROC directive
each variable is assigned a type
Syntax:
 LOCAL varlist

Example:
MySub PROC
LOCAL var1:BYTE, var2:WORD, var3:SDWORD

37 Web site Examples


Recursion
What is recursion?
Recursively Calculating a Sum
Calculating a Factorial

38 Web site Examples


What is Recursion?
The process created when . . .
A procedure calls itself
Procedure A calls procedure B, which in turn calls
procedure A
Using a graph in which each node is a procedure and
each edge is a procedure call, recursion forms a cycle:

39 Web site Examples


Recursively Calculating a Sum
The CalcSum procedure recursively calculates the sum of an
array of integers. Receives: ECX = count. Returns: EAX = sum
CalcSum PROC
cmp ecx,0 ; check counter value
jz L2 ; quit if zero
add
sum eax,ecx ; otherwise, add to
dec ecx ; decrement counter
call CalcSum ; recursive call
L2: ret
CalcSum ENDP

Stack frame:

40 Web site Examples


Macros
A macro is a named block of assembly language
statements.
Once defined, it can be invoked (called) one or more
times.
During the assembler's preprocessing step, each macro
call is expanded into a copy of the macro.
The expanded code is passed to the assembly step,
where it is checked for correctness.

41 Web site Examples


Defining Macros
A macro must be defined before it can be used.
Parameters are optional.
Each parameter follows the rules for identifiers. It is a
string that is assigned a value when the macro is invoked.
Syntax:

macroName MACRO [parameter-1, parameter-


2,...]
statement-list
ENDM
42 Web site Examples
mPutChar Macro
Writes a single character to standard
output. mPutchar MACRO char
push eax
Definition: mov al,char
call WriteChar
pop eax
ENDM

Invocation: .code
mPutchar 'A'

1 push eax viewed in


Expansion: 1 mov al,'A' the listing
1 call WriteChar
1 pop eax file

43 Web site Examples


Structure
 A structure is a template or pattern given to a logically
related group of variables. The variables in a structure are
called fields.
 Program statements can access the structure as a single
entity, or they can access individual fields. Structures often
contain fields of different types.
 A structure is defined using the STRUCT and ENDS
directives. Inside the structure, fields are defined using the
same syntax as for ordinary variables. Structures can contain
virtually any number of fields:
name STRUCT
field-declarations name
ENDS

44 Web site Examples


Field Initializers
When structure fields have initializers, the values are
assigned when structure variables are created. You can
use various types of field initializers:
Undefined: The ? operator leaves the field contents
undefined.
String literals: Character strings enclosed in quotation
marks.
Integers: Integer constants and integer expressions.
Arrays: The DUP operator can initialize array
elements.

45 Web site Examples


The following Employee structure describes employee
information, with fields such as ID number, last name,
years of service, and an array of salary history values.
The following definition must appear prior to the
declaration of
Employee
variables:
Employee STRUCT
IdNum BYTE "000000000"
LastName BYTE 30 DUP(0)
Years WORD 0
SalaryHistory DWORD 0,0,0,0
Employee ENDS

46 Web site Examples


Declaring Structure Variables
Syntax:
Identifier structureType <initializer-list>
.data
point1 COORD <5,10> ; X = 5, Y = 10
point2 COORD <20> ; X = 20, Y = ?
point3 COORD <> ; X = ?, Y = ?
worker Employee <> ; (default initializers)
person1 Employee <"555223333">
person3 Employee <,"dJones">

47 Web site Examples


Referencing Structure Variables
References to named structure members require a
structure variable as a qualifier. The following
constant expressions can be generated at assembly
time, using the
Employee
structure:
TYPE Employee.SalaryHistory ; 4
LENGTHOF Employee.SalaryHistory ; 4
SIZEOF Employee.SalaryHistory ; 16
TYPE Employee.Years ; 2

48 Web site Examples


Program example
TITLE Structures (ShowTime.ASM)
INCLUDE Irvine32.inc
.data
sysTime SYSTEMTIME <>
XYPos COORD <10,5>
consoleHandle DWORD ?
colonStr BYTE ":",0
.code
main PROC
; Get the standard output handle for the Win32 Console.
INVOKE GetStdHandle, STD_OUTPUT_HANDLE
mov consoleHandle,eax
; Set the cursor position and get the system time.
INVOKE SetConsoleCursorPosition, consoleHandle, XYPos
INVOKE GetLocalTime, ADDR sysTime

49 Web site Examples


Cont….
; Display the system time (hh:mm:ss).
movzx eax,sysTime.wHour ; hours
call WriteDec
mov edx,OFFSET colonStr ; ":"
call WriteString
movzx eax,sysTime.wMinute ; minutes
call WriteDec
call WriteString
movzx eax,sysTime.wSecond ; seconds
call WriteDec
call Crlf
call WaitMsg ; "Press any key..."
exit
main ENDP
END main

50 Web site Examples

You might also like