Date post: | 03-Jun-2018 |
Category: |
Documents |
Upload: | mafuzal-hoque |
View: | 235 times |
Download: | 0 times |
of 36
8/12/2019 Part11 Subroutines
1/36
Subroutines
(Irvine Edition IV : Section 5.5)
SYSC3006 1
8/12/2019 Part11 Subroutines
2/36
- A sequence of instructions that can be called from various
laces in the ro ram
- Allows the same operation to be performed with differentparameters
-
divide-and-conquer approach
- Simplifies testing and maintenance: separation of concerns-
hiding
- -
, , ,method
-In assembly languages, they are called : subroutine
SYSC3006 2
8/12/2019 Part11 Subroutines
3/36
u rout nes are a orm o contro ow Control is passed to the activity
The activity is executed
.
.
.
program s ar
subroutine_x
next instruction subroutine_x.
.
.
.
.
.
.
.
SYSC3006 3
Program flow during a subroutine call
8/12/2019 Part11 Subroutines
4/36
Multiple Subroutine Calls
program
firstmulti le
activity:
nvoca oninvocation
points ???
donesecond
invocation how can the activity
know which one to
return to?
Durin invocation the invocation oint must be saved.
SYSC3006 4
During return, the invocation point must be restored.
8/12/2019 Part11 Subroutines
5/36
Machine Level Implementation of Subroutines
CALL target ; invoke target subroutine
xecu on eman cs:
1. Save the return address (address of next instruction) on
run-t me stac
PUSH IPIP value AFTER
fetching CALL
instruction!
2. Transfer control to activity
JMP target
RET ; return from subroutineExecution Semantics:
1. Return control to address currently saved on top of stack
SYSC3006 5
POP IP
8/12/2019 Part11 Subroutines
6/36
Subroutine Processingprogram
activity:
CALL activity
after fetch
CALL activity
Next:RET
PUSH IPJMP activity RET
POP IPafter execution
IP == activity
Next
SP old topafter execution
IP = = Next
old top
SP
Next
old top
Stack
N.B. Only works ifres onsibilit of
Stack
SYSC3006 6
of stack when RET is
executed !!!
subroutine !!
8/12/2019 Part11 Subroutines
7/36
program
CALL
Next1:activity1:
CALL
Next2:
activity2:
RETRET
Next1
Next2
Next1 Runtime Stack
SYSC3006 7
old top old top old top
8/12/2019 Part11 Subroutines
8/36
Assembly Support : PROC Directive
Informally, a subroutine is any namedsequence of instructions
Intel Assembly has additional directives that provide morestructure for encapsulation of the subroutine
. code . code
EXTRN subr : PROC subr PROC NEAR
Subroutine
MOV AX, @dat a PUSH BP
MOV DS, AX MOV BP, SP
CALL subr POP BP
MOV AX, 4C00 RET
I NT 21h subr ENDP
SYSC3006 8
mai n ENDP END
END mai n
8/12/2019 Part11 Subroutines
9/36
Issues in Subroutine Calls
We shall define subroutines using C-like prototypes
Return TYPE name Argument list : type name
voi d di spl ay ( wor d number , byt e base)/ / Di spl ay t he gi ven number/ / base = 0 f or bi nar y, =1 f or HEX
byt e absol ut eVal ue ( word number )
/ / Ret ur n t he absol ut e val ue of t he gi vennum er
bool ean get Swi t ches ( byt e &set t i ngs )swi t ches and t r ue i f t he swi t chesbounced.
SYSC3006 9
8/12/2019 Part11 Subroutines
10/36
Issues in Subroutine Calls : Scope and Arguments
unsi gned i nt di spl ayAddr ess;
i nt mai n ( )
Global variable
{i nt number = 5, number 2 = 6;di spl ay ( number 2, 0) ; number2 is a PARAMETER
}
voi d di spl ay ( wor d number , byt e base)
number is an ARGUMENTLocal
variable
i nt di vi sor , di gi t ;i f ( base == 0) di vi sor = 2 ; di spl ay i n bi n
di gi t = number / di vi sor ;
SYSC3006 10
}
8/12/2019 Part11 Subroutines
11/36
8/12/2019 Part11 Subroutines
12/36
Implementing Parameter Passing
Parameters can be passed in various ways :1. Global Variables
. eg sters
3. On the stack.
Global Variables
The parameter is a shared (static) memory variable (in DS!)
Parameters is passed when Callerputs the value in the variable
SYSC3006 12
.
8/12/2019 Part11 Subroutines
13/36
Parameter Passin usin Global Variables
Cal l er MOV Value, 245
C prototype: void activity(word aValue). dat a
Value DW ?
CALL act i vi t y. . .
MOV AX, Value
. . .RET
act i vi t y ENDP
Passin arameters via lobal variables is NOT widel used in ractice
Consider nested subroutines (eg. a subroutine that calls itself)
Consider large programs with many subroutines, each with many
SYSC3006 13
However, sometimes it is the only way (eg. interrupts), later!
8/12/2019 Part11 Subroutines
14/36
Parameter Passin usin Re isters
Parameters can alternativelybe passed in registers
Each parameter is assigned to a particular register
Caller would load the registers with appropriate values
Callee would read re isters to et the value.
Register Parameters are used in DOS function call
MOV AH, 9 ; AH = OS Function (9=Print) ,
INT 21h ; Call DOS function
Advantage : Little overhead since values are in registers Disadvantage : There is a finite numberof registers
What to do if more arameters than re isters?
SYSC3006 14
8/12/2019 Part11 Subroutines
15/36
POLICY for SYSC-3006
Parameters can alternativelybe passed on the runtime stack
Callerpushes the parameters onto the stack
Callee indexes into stack to access arguments
Cal l er MOV DX, 245
PUSH DX
. . .Cal l ee act i vi t y PROC
MOV AX, [BP + ? ]. . .RET
Indirect addressing!
SYSC3006 15
act i vi t y ENDP
8/12/2019 Part11 Subroutines
16/36
Why does SYSC-3006 use Parameter Passing via Stack ?
Lets look at nested subroutine calls again
{
{
void sub1(word value)
{
}}su va ue
}
Return to sub2
Return to sub1
490
3Return to sub1
Stack frame
SYSC3006 16
245
245 Return to main
245
8/12/2019 Part11 Subroutines
17/36
SYSC-3006 Subroutine Policies Register Save/Restore
Problem : Subroutines need to use registers. What if the registerscontain values that are needed by the caller upon return?
Solutions: Assign responsibility to either caller or callee
1. Caller has the responsibility to save all useful values beforecallin the subroutine.
The callee is then free to use any register
Upon return, the caller restores the useful values.
restore it to its original value before returning.
Caller is guaranteed that its registers are the same before
. More efficient because subroutine knows what registers ituses.
SYSC3006 17
o cy : o ut on w t one except on : e reg ster s useto pass out return TYPE cannot be preserved
8/12/2019 Part11 Subroutines
18/36
SYSC-3006 Subroutine Policies Local Variables
Problem : Subroutines often have local variables that exist only for theduration of the subroutine.
Example
double average (double array[], int number)
{
double total = 0;
for (int i=0; i< number; i++ )
{ Local Variables
total += array[I];
}
double result = total / number;
return result;}
SYSC-3006 Polic : Local variables are maintained as re ister
SYSC3006 18
variables or by using the stack as a temporary storage buffer.
8/12/2019 Part11 Subroutines
19/36
SYSC-3006 Subroutine Policies Parameter Passing
3006 Policy : Parameters shall be passed on the stack.
The caller must ush the arameters on the stack beforecalling
With multiple parameters, parameters are pushed fromri ht-to-left
The caller must remove the parameters from the stack uponreturn.
base is in AL
Example: voi d di spl ay ( wor d number , byt e base)
Caller: MOV AL, 0 ; bi naryByteparameters are passed
in LSB of a word
PUSH XPUSH [ BX+SI ]CALL di spl ay
Parameters can be cleared by
POPin or b sim l ad ustin the
SYSC3006 19
,SP. Why ADD ? Why 4 ?
numberis at address (BX+SI)
8/12/2019 Part11 Subroutines
20/36
-
The callee must index into the stackto access the parameter
values usin a stack frame .
A stack frame is a consistent view of the stack upon
eg nn ng e core co e o e su rou ne.
It provides a uniform method for accessing parameters
passed on the stack using BP based indirect addressingregardless of the number of arguments and/or the
number of registers saved/restored by the subroutine
SYSC3006 20
8/12/2019 Part11 Subroutines
21/36
-
anySub pr oc
PUSH BP
MOV BP, SP; PUSH any r egi st er s used
Stan ar Entry Co e
i s done
; POP al l r egi st er s t hat wer e saved; n r ever se or er
POP BP
RET
Standard Exit Code
anySub endp
SYSC3006 21
8/12/2019 Part11 Subroutines
22/36
-
The stack frame associated with the subroutine skeleton
After saving registers
old BP
saved registersSP
BP
BP constant
BP + 0PUSH BP
arguments
return address BP + 2
BP + 4 or moreCaller
Callee ,
After PUSH BPBP+4 is always the
leftmost argument
SYSC3006 22
8/12/2019 Part11 Subroutines
23/36
-
Example : Recall our previous example
,
Call set up: (By the caller)
MOV AL, 0 ; Base = binary
PUSH AX
PUSH [BX + SI] ; Value to display
CALL Display16return address
?
SP
After CALL
,Value = mem[BX+SI]
Base = 0
SPAfter PUSH [BX + SI] (& after RET in sub)
SPAfter PUSH AX
SYSC3006 23
,
8/12/2019 Part11 Subroutines
24/36
SYSC-3006 Subroutine Policies Stack Frame
Subroutine Implementation ( In body of Display )
di spl ay PROC
PUSH BP
MOV BP, SP
PUSH AX
PUSH BX
SPsaved value of AXsaved value of BX
; Get val ue
MOV AX, [ BP + 4]
; i f ( base == bi nar ) Value
return address
old BPBP
BP + 2
BP + 4
SP
MOV BL, [ BP+6]
CMP BL, 0
Base BP + 6
POP BXPOP AX
SYSC3006 24
RET
di spl ay ENDP
8/12/2019 Part11 Subroutines
25/36
Issue :pass by value vs. pass by reference
Definition : Pass by value
The argument is a copy of the value of interest
In high-level languages like C++, pass-by-value is the default
way to pass simple variables (primitive types like int, char,float)
Example : Pass-by-Value 245
return a ressSP
0
myValue dw 245
int myValue; MOV AL,0
display( myValue, 0 ); PUSH myValue
CALL display
Content of myValueis PUSHed but not
the address!
SYSC3006 25
ADD SP, 4
8/12/2019 Part11 Subroutines
26/36
Issue : pass by value vs. pass by reference
When passing-by-value : Inside the subroutine, arguments passed in the
stackcan be treated like local variables
The variable is local and exists ONLY during the subroutineexecution
y
Consequence : Any modifications to the arguments on the
stack are not persistent and cannot be seen by the caller
SP
saved value of AX
saved value of BXIn Previous DisplayExample
- The subroutine can change the copyof MyValue
SP
245
return address
oBP
BP + 2
BP + 4
MOV [BP + 4], AX- The change will be made to the
copy on the stack, and not to the
SYSC3006 26
0BP + 6.
8/12/2019 Part11 Subroutines
27/36
Issue : pass by value vs. pass by reference
Definition : Pass by reference
The argument is the address of a memory variable
The purpose of subroutine is to modify callers variables
To pass large composite structures that would require too muchme space on e s ac passe - y-va ue.
In high-level languages,
Default : Pass-by-value i nt val ue; Pass-by-reference requires additional syntax : & operator.
i nt val ue;
SYSC3006 27
8/12/2019 Part11 Subroutines
28/36
Issue : pass by value vs. pass by reference
Example : Pass by reference
void SortArray ( int & SortMe[ ], int Size );
; array declaration
X DW
DW
. . .
SizeOfX DW
Caller :
PUSH SizeOfX
MOV AX, OFFSET XPUSH AX
CALL SortArra
pass offset of array X
why not: PUSH X????
SYSC3006 28
ADD SP, 4
8/12/2019 Part11 Subroutines
29/36
Issue : pass by value vs. pass by reference
Example : Pass by reference
SP saved registers
address of X
return address
BP + 2
BP + 4a ee : ns e e su rou ne or rray:
MOV BX, [ BP + 4 ] ; get array address
copy of
SizeOfX
BP + 6
MOV SI, 0 ; array n ex = 0. . .
MOV AX, [ BX + SI ] ; get array element
SYSC3006 29
8/12/2019 Part11 Subroutines
30/36
SYSC-3006 Subroutine Policies Return Types
Subroutines can return information to the caller in two ways
1. Return (a) value(s) in (a) variable(s) that is (are) passed-by-
2. Return a value via the subroutines return type
Example :bool ean AbsVal ue( i nt & X, i nt Y ) ;
where boolean is usually a byte, with 0 = false,
non-zero = rue
SYSC3006 30
8/12/2019 Part11 Subroutines
31/36
SYSC-3006 Subroutine Policies Return Types
Passing the return type back from the subroutine to the callercould be done in any of the three ways used to pass parametersin .
Global variables (same troubles as before)
On the stack
, ,could allocate an extra word in stack before call
SUB SP, 2
Via registers (There is only one return type, need only oneregister)
SYSC3006 31
8/12/2019 Part11 Subroutines
32/36
-
Return-Value POLICY in SYSC-3006 (same as most High Level
Languages)
return 8-bit value in AL
return 16-bit value in AX
return 32-bit value in DX:AX (as with 32-bit values for DIV
instruction)
Implications of Return-Value Policy
do not save/restore register(s) used for return-value
t e purpose o t e su rout ne s to return a va ue n t e reg ster s if 8-bit value (returned in AL) subroutine is not responsible for
persistence of AH value
SYSC3006 32
8/12/2019 Part11 Subroutines
33/36
Are the SYSC-3006 Subroutine Policies Practical ?
Is it worth the effort to understand the 3006 Subroutine policies ?
The policies follow industry practices for compiler-writing
INVOKE
, ,
PUSH 256
CALL display
INVOKE display, ADDR myValue, 0 generates PUSH 0
PUSH offset myValue
sp ay
An alternate form of RET
RET immediate Add the immediate value to SP after
SYSC3006 33
8/12/2019 Part11 Subroutines
34/36
8/12/2019 Part11 Subroutines
35/36
xamp e : versus su rou nes The PROC modifier influences how a subroutine is called
near Sub PROC NEAR
RET
f ar Sub PROC FAR
RETExecution : POP IP Execution : POP
near u
ar u
Execution : PUSH IP Execution : PUSH CS:IP
1. How does the program know if it is NEAR or FAR ?
2. Dont we need different RET statements ?
IP= nearSub CS:IP = farSub
3. Draw a picture of a FAR stack frame?Which is pushed first:CS or IP?4. Can a subroutine be both NEAR and FAR ?
SYSC3006 35
.
8/12/2019 Part11 Subroutines
36/36
NEAR versus FAR subroutines
0000 .code
0000 main PROC
0000 E8 0004 CALL nearsub E8 CALL
0003 0E E8 0001 CALL farsub
0007 main ENDP
0E PUSH CS
; NEAR subr out i ne0007 nearsub PROC NEAR
0007 C3 RET C3
RET (NEAR)0008 nearsub ENDP
; FAR subr out i ne
Intra-segment
0008 CB RET
0009 farsub ENDP
CB RET (FAR)
Inter-segment
SYSC3006 36