Sie sind auf Seite 1von 21

Overview

• Stack Operations
• Defining and Using Procedures
• Stack frames,, p
parameters and local variables
Procedure • Recursion
• Related directives
Computer
p Organization
g z and Assemblyy Languages
g g
Yung-Yu Chuang

with slides by Kip Irvine


2

Stacks
• LIFO (Last-In, First-Out) data structure.
• push/pop
h/ operations
i
• You probably have had experiences on
implementing it in high-level languages.
Stack operations • Here,, we concentrate on runtime stack,,
directly supported by hardware in the CPU.
It is essential for calling
g and returning
g from
procedures.

4
Runtime stack PUSH and POP instructions
• Managed by the CPU, using two registers • PUSH syntax:
– SS (stack
( t k segment) t) – PUSH r/m16
– ESP (stack pointer) * : point to the top of the stack – PUSH r/m32
usually
ll modified
difi d by
b CALL,
CALL RETRET, PUSH and d POP – PUSH imm32
• POP syntax:
y
SS – POP r/m16

ESP stack /
– POP r/m32
segment

memory
* SP in Real-address mode
5 6

PUSH operation (1 of 2) PUSH operation (2 of 2)


• A push operation decrements the stack pointer by 2 or • The same stack after pushing two more integers:
4 (depending on operands) and copies a value into the
location pointed to by the stack pointer. 0FEC 0FEC

0FF0 0FF0
0FEC 0FEC
0FF4 ESP 0FF4
0FF0 0FF0 00000002
ESP 0FF8 0FF8
0FF4 0FF4 00000001 00000001
PUSH 0A5h 0FFC 0FFC
0FF8 0FF8 000000A5 000000A5
1000 1000
0FFC ESP 0FFC 00000006 00000006
000000A5
ESP 1000 1000
00000006 00000006 PUSH 01h PUSH 02h

7 8
POP operation When to use stacks
• Copies value at stack[ESP] into a register or variable. • Temporary save area for registers
• Adds n to ESP,
ESP where n is either 2 or 44, depending on • T save return address
To dd ffor CALL
the attribute of the operand receiving the data
• To pass arguments
0FEC 0FEC • Local variables
0FF0 0FF0 • Applications which have LIFO nature
nature, such as
ESP 0FF4 0FF4 reversing a string
00000002
0FF8
00000001
ESP 0FF8
00000001
0FFC 0FFC
000000A5 000000A5
1000 1000
00000006 00000006
POP EAX
EAX=00000002
9 10

Example of using stacks Example: Nested Loop


Save and restore registers when they contain important When creating a nested loop, push the outer loop counter
values. Note that the PUSH and POP instructions are in before entering the inner loop:
the opposite order:
mov ecx,100 ; set outer loop count
push esi ; push registers L1: ; begin the outer loop
push ecx push ecx ; save outer loop count
push ebx
mov ecx,20 ; set inner loop count
mov esi,OFFSET dwordVal ; starting OFFSET L2: ; begin the inner loop
mov ecx,LENGTHOF dwordVal; number of units ;
mov ebx,TYPE dwordVal ;size of a doubleword ;
call DumpMem ; display memory loop
p L2 ; repeat
p the inner loop
p
pop ebx ; opposite order pop ecx ; restore outer loop count
pop
p p ecx loop L1 ; repeat the outer loop
pop esi
11 12
Example: reversing a string Example: reversing a string
.data ; Pop the name from the stack, in reverse,
aName BYTE "Abraham
Abraham Lincoln
Lincoln",0
,0 ; and store in the aName array.
y
nameSize = ($ - aName) – 1 mov ecx,nameSize
mov esi,0
.code L2:
main PROC pop eax ; get character
; Push
P h th
the name on th
the stack.
t k mov aName[esi]
aName[esi],al
al ; store in string
mov ecx,nameSize inc esi
mov esi,0 p L2
Loop
L1:
movzx eax,aName[esi] ; get character exit
push eax ; push on stack main
i ENDP
inc esi END main
L
Loop L1
13 14

Related instructions Example


• PUSHFD and POPFD MySub PROC
– push and pop the EFLAGS register pushad
– LAHF, SAHF are other ways to save flags ...
; modify some register
• PUSHAD pushes the 32-bit general-purpose
...
registers on the stack in the following order
popad Do not use this if your procedure uses
– EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI
ret registers for return values
• POPAD ppops
p the same registers
g off the stack in
M S b ENDP
MySub
reverse order
– PUSHA and POPA do the same for 16-bit registers
g

15 16
Creating Procedures
• Large problems can be divided into smaller
tasks to make them more manageable
• A procedure is the ASM equivalent of a Java or
C++ function
• Following is an assembly language procedure
Defining and using procedures named sample:
sample PROC
.
.
et
ret
sample ENDP

A named
d block
bl k off statements
t t t th
thatt ends
d with
ith a return.
t
18

Documenting procedures Example: SumOf procedure


Suggested documentation for each procedure: ;-----------------------------------------------
• A description of all tasks accomplished by the SumOf PROC
procedure. ;
; Calculates and returns the sum of three 32-bit
• Receives: A list of input parameters; state their ; integers
integers.
usage and requirements. ; Receives: EAX, EBX, ECX, the three integers.
; May be signed or unsigned.
• Returns: A description of values returned by the ; Returns:
R t EAX = sum, andd th
the status
t t fl
flags
procedure. ; (Carry, Overflow, etc.) are changed.
; Requires: nothing
• Requires: Optional list of requirements called ;-----------------------------------------------
preconditions that must be satisfied before the add eax,ebx
procedure is called.
called add eax,ecx
ret
For example, a procedure of drawing lines could assume SumOf ENDP
th t di
that display
l adapter
d t iis already
l d iin graphics
hi mode.d
19 20
CALL and RET instructions CALL-RET example (1 of 2)
• The CALL instruction calls a procedure main PROC
– pushes offset of next instruction on the stack 00000020 call
ll M
MySub
S b
0000025 is the offset 00000025 mov eax,ebx
– copies the address of the called procedure into EIP of the instruction .
• The RET instruction returns from a procedure immediately following
.
the CALL instruction
– pops top of stack into EIP main ENDP
• We used jl and jr in our toy computer for
MySub PROC
CALL and RET,, BL and MOV PC, , LR in ARM. 00000040 iis th
the offset
ff t 00000040 mov eax,edx
d
of the first instruction .
inside MySub
.
ret
MySub ENDP

21 22

CALL-RET example (2 of 2) Nested procedure calls


main PROC
The CALL instruction 00000040 .
pushes 00000025 onto ESP .

the stack, and loads 00000025 EIP 0050


call Sub1
exit
00000040 into EIP main ENDP

0100 Sub1 PROC


.
.
call Sub2
0150 ret EIP
Sub1 ENDP

The RET instruction 0200 Sub2 PROC


.
00000025
pops 00000025 from .
the stack into EIP 00000025 EIP 0250
call Sub3
ret
ESP Sub2 ENDP

0300 Sub3 PROC


.

Stack
.
ret
Sub3 ENDP
23 24
Local and global labels Procedure parameters (1 of 3)
A local label is visible only to statements inside the same
procedure. A g
p global label is visible everywhere.
y
• A good procedure might be usable in many
different programs
diff
main PROC
jmp L2 ; error! • Parameters help to make procedures flexible
L1:: ; global label because parameter values can change at
exit runtime
main ENDP
• General registers can be used to pass
sub2 PROC parameters
L2: ; local label
jmp L1 ; ok
ret
sub2 ENDP
25 26

Procedure parameters (2 of 3) Procedure parameters (3 of 3)


The ArraySum procedure calculates the sum of an array. This version returns the sum of any doubleword array
It makes two references to specific
p variable names: whose address is in ESI.
S The sum is returned in EAX:
ArraySum PROC ArraySum PROC
mov esi,0 ; array index ; Recevies: ESI points to an array of doublewords,
mov eax,0 ; set the sum to zero ; ECX = number of array elements.
; Returns: EAX = sum
L1: ;
;------------------------------------------------
add eax,myArray[esi] ; add each integer to sum push esi
add esi,4 ; point to next integer push ecx
l
loop L1 ; repeat
t f
for array size
i mov eax
eax,00 ; set the sum to zero
L1: add eax,[esi] ; add each integer to sum
mov theSum,eax ; store the sum add esi,4 ; point to next integer
ret loop L1 ; repeat for arra
array si
size
e
ArraySum ENDP pop ecx
pop esi
ret
27 ArraySum ENDP 28
Calling ArraySum USES operator
.data • Lists the registers that will be saved (to avoid
array DWORD 10000h,
10000h 20000h
20000h, 30000h
30000h, 40000h side effects) (return register shouldn
shouldn’tt be saved)
theSum DWORD ? ArraySum PROC USES esi ecx
.code
code ,
mov eax,0 ; set the sum to zero
...
main PROC
mov esi OFFSET array
esi, MASM generates the following code:
ArraySum PROC
mov ecx, LENGTHOF array push esi
call
ll A
ArraySum
S pushh ecx
.
mov theSum, eax .
pop ecx
pop esi
ret
ArraySum ENDP
29 30

Stack frame
• Also known as an activation record
• Area
A off the
h stack k set aside
id ffor a procedure's
d '
return address, passed parameters, saved
registers,
i t and
d llocall variables
i bl
Stack frames, parameters and • Created by the following steps:
local variables – Calling procedure pushes arguments on the stack
and calls the procedure.
– The subroutine is called,
called causing the return
address to be pushed on the stack.
– The called procedure pushes EBP on the stack, and
sets
t EBP to
t ESP
ESP.
– If local variables are needed, a constant is
subtracted from ESP to make room on the stack.
– The registers needed to be saved are pushed.
32
Stack frame Explicit access to stack parameters
ESP ESP • A procedure can explicitly access stack
saved
registers
parameters
t using
i constant
t t offsets
ff t ffrom EBP.
EBP
EBP ebp – Example: [ebp + 8]
local • EBP is often called the base pointer or frame
[EBP-4]
[EBP 4]
variables pointer because it holds the base address of the
p
ebp
EBP
ebp
stack frame.
[EBP+4]
ret addr • EBP does not change value during the
[EBP+8] procedure.
parameters ebp
• EBP must be restored to its original value when
ap
procedure returns.
33 34

Parameters Parameters
• Two types: register parameters and stack call by value call by reference
parameters.
parameters i t sum=AddTwo(a,
int AddT ( b)
b); int
i t sum=AddTwo(&a,
AddT (& &b);
&b)
• Stack parameters are more convenient than .date
register
i t parameters.
t a DWORD 5
b DWORD 6
p
pushad p
push TYPE array
y
mov esi,OFFSET array push LENGTHOF array push b push OFFSET b
mov ecx,LENGTHOF array push OFFSET array push a push OFFSET a
mov ebx,TYPE array call DumpMem call
ll AddTwo
dd call
ll AddTwo
dd
call DumpMem
popad ESP ESP
5 offset(a)
register parameters stack parameters
6 offset(b)
( )

35 36
Stack frame example Stack frame example
.data AddTwo PROC
sum DWORD ? push ebp
.code mov ebp,esp ; base of stack frame
push 6
p ; second argument
g mov eax,[ebp + 12] ; second argument (6)
push 5 ; first argument add eax,[ebp + 8] ; first argument (5)
call AddTwo ; EAX = sum pop
p p ebp
p
mov sum,eax ; save the sum
ret 8 ; clean up the stack
AddTwo PROC AddTwo ENDP ; EAX contains the sum
push ebp EBP EBP
ebp
ebp
mov ebp,esp Who should be responsible to
rett addr
dd [EBP+4]
. remove arguments? It depends ret addr [EBP+4]
. 5 [EBP+8] on the language model. 5 [EBP+8]
6 [EBP+12]
6 [EBP+12]
ESP 37 38

RET Instruction Passing arguments by reference


• Return from subroutine • The ArrayFill procedure fills an array with
• Pops stack into the instruction pointer (EIP or 16 bit random integers
16-bit
IP). Control transfers to the target address. • The calling program passes the address of the
• Syntax: array, along
l with
ith a countt off th
the number
b off
– RET array elements:
– RET n
.data
• Optional operand n causes n bytes to be added count = 100
to the stack pointer after EIP (or IP) is assigned array WORD count DUP(?)
( )
a value. .code
push OFFSET array
push COUNT
call ArrayFill

39 40
Passing arguments by reference Passing 8-bit and 16-bit arguments
ArrayFill can reference an array without • When passing stack arguments, it is best to
knowing the array
array'ss name: push 32-bit
32 bit operands to keep ESP aligned on a
doubleword boundary.
ArrayFill
y PROC
EBP Uppercase PROC push ‘x’ ; error
push ebp ebp
mov ebp,esp push ebp Call Uppercase
ret addr [EBP+4] mov ebp, esp
pushad
h d mov al, [ebp+8]
mov esi,[ebp+12] count [EBP+8]
cmp al, ‘a’
.data
mov ecx
ecx,[ebp+8]
[ebp+8] offset(array)
ff t( ) [EBP+12] jb L1
charVal BYTE ‘x’
. cmp al, ‘z’
.code
. ja L1
, charVal
movzx eax,
subb al,
l 32
push eax
L1: pop ebp
Call Uppercase
ret 4
Uppercase ENDP
41 42

Saving and restoring registers Local variables


• When using stack parameters, avoid USES. • The variables defined in the data segment can
MySub2
M S b2 PROC USES ec
ecx, ed
edx MySub2 PROC be taken as static global variables.
variables
push ebp push ecx
mov ebp, esp
mov eax, [ebp+8]
push
p edx visibility=the
visibility the whole program
push ebp
pop ebp mov ebp, esp lifetime=program duration
ret 4 mov eax, [ebp+8]
MySub2 ENDP pop ebp
pop edx • A local variable is created, used, and destroyed
ESP,EBP
ebp pop ecx within a single procedure (block)
ret 4
edx
MySub2 ENDP • Advantages of local variables:
ecx [EBP 8]
[EBP+8] – Restricted access: easy to debug,
debug less error prone
– Efficient memory usage
ret addr
– Same names can be used in two different procedures
parameter [EBP+16]
43 – Essential for recursion 44
Creating local variables Local variables
• Local variables are created on the runtime • They can’t be initialized at assembly time but
stack usually above EBP.
stack, EBP can be assigned to default values at runtime.
runtime
• To explicitly create local variables, subtract
th i total
their t t l size
i ffrom ESP
ESP. MySub PROC
push ebp
20
void MySub() mov ebp, esp
{ sub esp, 8
MySub PROC 10
[EBP-8] int X=10; mov DWORD PTR [ebp-4], 10
push ebp mov DWORD PTR [
[ebp-8],
p ], 20 EBP
int Y=20;
mov ebp,esp [EBP-4] ... ... ESP
ESP return
sub esp,8 EBP } mov esp, ebp
address
ebp
p pop ebp
mov [ebp
[ebp-4],123456h
4] 123456h
ret
mov [ebp-8],0 [EBP+4] ret addr
. MySub ENDP
stack EBP


. [EBP+8]
45 46

Local variables LEA instruction (load effective address)

X_local EQU DWORD PTR [ebp-4]


• The LEA instruction returns offsets of both
Y_local EQU DWORD PTR [ebp-8] direct and indirect operands at run time.
time
– OFFSET only returns constant offsets (assemble time).
MySub PROC
push ebp
• LEA is
i required
i d when
h obtaining
bt i i th the offset
ff t off a
mov ebp, esp stack parameter or local variable. For example:
sub esp, 8 CopyString PROC,
X_local,
mov DWORD PTR 10
[ebp-4], 10 count:DWORD
Y
Y_local,
local
mov DWORD PTR 20
[ebp
[ebp-8],
8] 20 LOCAL temp[20]:BYTE
[20]
...
mov esp, ebp mov edi
edi,OFFSET
OFFSET count; invalid operand
pop ebp mov esi,OFFSET temp ; invalid operand
ret lea edi,count ; ok
MySub ENDP lea esi,temp ; ok
47 48
LEA example ENTER and LEAVE
void makeArray() makeArray PROC • ENTER instruction creates stack frame for a
{ push ebp called procedure
char myString[30]; mov ebp, esp – pushes EBP on the stack push ebp
for (int i=0; i<30; i++) sub esp, 32
m String[i] ‘*’
myString[i]=‘*’; lea esi
esi, [ebp
[ebp-30]
30] – set EBP to the base of stack frame mov ebp, esp
} mov ecx, 30 – reserves space for local variables sub esp, n
L1: mov BYTE PTR [esi], ‘*’
inc esi
• ENTER nbytes, nestinglevel
loop L1 – nbytes (for local variables) is rounded up to a
add esp 32 multiple of 4 to keep ESP on a doubleword boundary
pop ebp – nestinglevel: 0 for now
ret
y ENDP
makeArray MySub PROC MySub PROC
enter 8,0 push ebp
mov ebp,esp
49
sub esp,8 50

ENTER and LEAVE LOCAL directive


• LEAVE reverses the action of a previous ENTER • The LOCAL directive declares a list of local
instruction.
instruction variables
i bl
– immediately follows the PROC directive
MySub PROC MySub
y PROC
enter 8, 0 push ebp – each variable is assigned a type
. mov ebp, esp • Syntax:
. sub esp, 8 LOCAL varlist
. .
. . Example:
a ple:
leave mov esp, ebp MySub PROC
ret pop
p p ebpp LOCAL var1:BYTE,
var1:BYTE var2:WORD,
var2:WORD var3:SDWORD
MySub ENDP ret
MySub ENDP

51 52
MASM-generated code Non-Doubleword Local Variables
BubbleSort PROC
• Local variables can be different sizes
LOCAL temp:DWORD,
p , SwapFlag:BYTE
p g
. . . • How are they created in the stack by LOCAL
ret directive:
B bbl S t ENDP
BubbleSort
– 8-bit: assigned to next available byte
MASM generates the following code: – 16-bit: assigned to next even (word) boundary
BubbleSort PROC – 32-bit: assigned to next doubleword boundary
push ebp
mov ebp
ebp,esp
esp
add esp,0FFFFFFF8h ; add -8 to ESP
. . .
mov esp,ebp
pop ebp
ret
BubbleSort ENDP 53 54

MASM-generated code Reserving stack space


ESP [EBP-8]
• .STACK 4096
b1 calls
• Sub1 ll Sub2,
b2 Sub2b2 calls
ll Sub3,
b3 how
h many
SwapFlag
p g
bytes will you need in the stack?
[EBP 4]
[EBP-4] Sub1 PROC
temp
LOCAL array1[50]:DWORD ; 200 bytes

EBP Sub2 PROC


ebp
LOCAL array2[80]:WORD ; 160 bytes

Sub3 PROC
mov eax,
, temp
p mov eax,
, [
[ebp-4]
p ] LOCAL array3[300]:WORD ; 300 bytes
mov bl, SwapFlag mov bl, [ebp-5] 660+8(ret addr)+saved registers…
55 56
Recursion
• The process created when . . .
– A procedure
d calls
ll it
itself
lf
– Procedure A calls procedure B, which in turn
calls procedure A
• Using a graph in which each node is a
Recursion procedure
d and
d eachh edge
dg is
i a procedure
d call,
ll
recursion forms a cycle:

E B

D C
58

Calculating a factorial Calculating a factorial


This function calculates the factorial of integer n. Factorial PROC
push ebp
A new value of n is saved in each stack frame: mov ebp,esp
int factorial(int n)
recursive calls backing up mov eax,[ebp+8] ; get n
5! = 5 * 4! 5 * 24 = 120 cmp
p eax,0 ; n > 0?
{ ja L1 ; yes: continue
if (n == 0) mov eax,1 ; no: return 1
4! = 4 * 3! 4 * 6 = 24
return 1; jmp
j p L2
else L1:dec eax
3! = 3 * 2! 3*2=6
return n*factorial(n-1); push eax ; Factorial(n-1)
} call Factorial
2! = 2 * 1! 2*1=2
ReturnFact:
1! = 1 * 0! 1*1=1 mov ebx,[ebp+8] ; get n
factorial(5); mul ebx ; edx:eax=eax*ebx
0! = 1 1=1
(base case) L2:pop ebp ; return EAX
ret 4 ; clean up stack
59 Factorial ENDP 60
push 12
Calculating a factorial call Factorial
Factorial PROC
push ebp
mov ebp,esp ebp
mov eax,[ebp+8] ret Factorial
cmp
p eax,0
ja L1 0
mov eax,1
Related directives


jmp
j p L2
L1:dec eax
push eax ebp
call Factorial rett Factorial
F t i l
ReturnFact: 11
mov
o eb
ebx,[ebp+8]
,[ebp 8]
mul ebx ebp

L2:pop ebp ret main


ret 4 12
Factorial ENDP 61

.MODEL directive Memory models


• .MODEL directive specifies a program's memory • A program's memory model determines the
model
d l and
d model
d l options
ti (l
(language-specifier).
ifi ) number and sizes of code and data segments.
segments
• Syntax: • Real-address mode supports tiny, small,
.MODEL memorymodel [,modeloptions] medium,
di compact,
t llarge, and
dhhuge models.
d l
• Protected mode supports only the flat model.
• memorymodel can be one of the following:
– tiny, small, medium, compact, large, huge, or flat Small model: code < 64 KB, data (including stack) < 64 KB.
All offsets are 16 bits.
• modeloptions includes
i l d theh llanguage specifier:
ifi
– procedure naming scheme Flat model: single
g segment
g for code and data,, up
p to 4 GB.
– parameter passing conventions All offsets are 32 bits.

• .MODEL flat, STDCALL


63 64
Language specifiers INVOKE directive
• STDCALL (used when calling Windows functions) • The INVOKE directive is a powerful replacement
– procedure arguments pushed on stack in reverse for Intel
Intel’ss CALL instruction that lets you pass
order (right to left) multiple arguments
– called procedure cleans up the stack
@ (for
– _name@nn (f example,
l _AddTwo@8)
dd @8) • Syntax:
• C INVOKE procedureName [, argumentList]
– procedure arguments pushed on stack in reverse • ArgumentList is an optional comma
comma-delimited
delimited
order (right to left) list of procedure arguments
– calling program cleans up the stack (variable number
off parameters suchh as printf)) • Arguments can be:
– _name (for example, _AddTwo) – immediate values and integer expressions
• PASCAL – variable names
– arguments pushed in forward order (left to right) – address and ADDR expressions
– called procedure cleans up the stack – g
register names
• BASIC, FORTRAN, SYSCALL 65 66

INVOKE examples INVOKE example


.data .data
y
byteVal BYTE 10 val1 DWORD 12345h
wordVal WORD 1000h
val2 DWORD 23456h
.code
; direct
di t operands:
d .code
code
INVOKE Sub1,byteVal,wordVal INVOKE AddTwo, val1, val2

; address of variable:
INVOKE Sub2,ADDR byteVal push val1
push
h val2
l2
; register name, integer expression: call AddTwo
INVOKE Sub3,eax,(10 * 20)

; address expression (indirect operand):


INVOKE Sub4,[ebx]
67 68
ADDR operator ADDR example
• Returns a near or far pointer to a variable, .data
depending on which memory model your A
Array DWORD 20 DUP(?)
program uses: .code
• Small model: returns 16-bit
16 bit offset ...
INVOKE Swap, ADDR Array, ADDR [Array+4]
• Large model: returns 32-bit segment/offset
• Flat
Fl model:
d l returns 32
32-bit
bi offset
ff
• Simple example: push OFFSET Array+4
.data push OFFSET Array
myWord WORD ? Call Swap
.code
INVOKE mySub,ADDR myWord

69 70

PROC directive PROC example


• The PROC directive declares a procedure with • The AddTwo procedure receives two integers and
an optional list of named parameters.
parameters returns their sum in EAX.
EAX
• Syntax: • C++ programs typically return 32-bit integers from
label PROC [attributes] [USES] paramList functions in EAX
EAX.
•paramList is a list of parameters separated by AddTwo PROC,
, AddTwo PROC,
,
commas. Each parameter has the following val1:DWORD, push ebp
syntax: val2:DWORD mov ebp, esp
mov eax, dword ptr [ebp+8]
8
paramName:type
mov eax,val1 add eax, dword ptr [ebp+0Ch]
type must either be one of the standard ASM types (BYTE, leave
add eax
eax,val2
val2
SBYTE, WORD, etc.), or it can be a pointer to one of ret 8
ret
these types. AddTwo ENDP
AddTwo ENDP
• Example: foo PROC C USES eax, param1:DWORD
71 72
PROC example PROTO directive
Read_File PROC USES eax, ebx, • Creates a procedure prototype
pBuffer:PTR BYTE
LOCAL fileHandle:DWORD • Syntax:
S
Read_File PROC – label PROTO paramList
o
mov es
esi,
, p
pBuffer
u e
pushh ebp
b
mov fileHandle, eax
mov ebp, esp
• Every procedure called by the INVOKE directive
.
.
add esp, 0FFFFFFFCh must have a prototype
push eax
ret
push ebx • A complete procedure definition can also serve
Read_File ENDP
mov esi, dword ptr [ebp+8] as its own prototype
p yp
mov dword ptr [ebp-4], eax
.
.
pop ebx
pop eax
ret
Read_File ENDP
73 74

PROTO directive PROTO example


• Standard configuration: PROTO appears at top of the • Prototype for the ArraySum procedure,
program listing,
li ti INVOKE appears in
i the
th code
d segment, t showing
h i itsi parameter li list:
and the procedure implementation occurs later in
the program: ArraySum PROTO,
ptrArray:PTR DWORD, ; points to the array
MySub PROTO ; procedure prototype szArray:DWORD ; array size
.code
INVOKE MySub ; procedure call
ArraySum PROC USES esi, ecx,
ptrArray:PTR DWORD, ; points to the array
MySub PROC ; procedure implementation szArray:DWORD ; array size
.
.
M S b ENDP
MySub
75 76
Multimodule programs
• A multimodule program is a program whose
source code has been divided up into separate
ASM files.
• Each ASM file (module) is assembled into a
Multimodule programs separate OBJ file.
file
• All OBJ files belonging to the same program
are linked
li k d using
i ththe li
link
k utility
tilit iinto
t a single
i l
EXE file.
– This process is called static linking

78

Advantages Creating a multimodule program


• Large programs are easier to write, maintain, • Here are some basic steps to follow when
and debug when divided into separate source creating
ti a multimodule
lti d l program:
code modules. – Create the main module
• When
Wh changing
h i a li
line off code,
d only
l it
its – Create a separate source code module for each
enclosing module needs to be assembled procedure or set of related procedures
again Linking assembled modules requires
again.
– Create an include file that contains procedure
little time.
prototypes for external procedures (ones that are
• A module
d l can bbe a container
t i ffor llogically
i ll called between modules)
related code and data – Use the INCLUDE directive to make your procedure
• encapsulation: procedures and variables are prototypes available to each module
automatically hidden in a module unless you
declare them public
79 80
Multimodule programs INCLUDE file
• MySub PROC PRIVATE The sum.inc file contains prototypes for external
sub1 PROC PUBLIC u ct o s that
functions t at a
are
e not
ot in tthe
e Irvine32
v e3 llibrary:
b a y:

INCLUDE Irvine32.inc
• EXTERN sub1@0:PROC
PromptForIntegers PROTO,
ptrPrompt:PTR BYTE, ; prompt string
• PUBLIC count
count, SYM1 ptrArray:PTR
t A PTR DWORD
DWORD, ; points
i t tto th
the array
arraySize:DWORD ; size of the array
SYM1=10
.data
d t ArraySum PROTO,
count DWORD 0 ptrArray:PTR DWORD, ; points to the array
count:DWORD ; size of the array

• EXTERN name:type DisplaySum PROTO,


ptrPrompt:PTR BYTE, ; prompt string
theSum:DWORD ; sum of the array
81 82

Main.asm
TITLE Integer Summation Program

INCLUDE sum.inc

.code
code
main PROC
call Clrscr

INVOKE PromptForIntegers,
ADDR prompt1,
ADDR array,
array
Count

...
call Crlf
INVOKE ExitProcess,0
main ENDP
END main
83

Das könnte Ihnen auch gefallen