There are four steps that need to be accomplished in order to call and return from a procedure:
| Save the return address
|
| Procedure call
|
| Execute procedure
|
| Return execution to the saved return address.
|
As an illustration, Calling to and returning from a procedure may be depicted as:
Procedure call and return mechanism |
.CODE
.
.
.
lea AX, rtn1 ; AX=address of return point
push AX ; save AX into the stack
jmp subrtn ; goto the procedure part
rtn1: ; return point
.
.
; program halts
subrtn:
.
.
pop BX ; read the return address
jmp BX ; go back to the return point
|
Assembly-language procedures are similar to functions,subroutines,and
procedures in high-level languages such as Java, C,FORTRAN,and Pascal. Two
instructions control the use of assembly-language procedures. CALL pushes the
return address onto the stack and transfers control to a procedure, and RET
pops the return address off the stack and returns control to that location.
Subroutine call and return instruction usage |
.CODE
.
.
.
call subrtn
; code here that would be executed following the return
.
.
; program halts
subrtn PROC
.
.
ret
subrtn ENDP
|
Instruction | Operand | Note
| CALL | label name | Push IP IP= IP + displacement relative to next instruction
| CALL | r/m | Push IP IP = [r/m]
| CALL | label name (FAR) | Push CS Push IP CS:IP=address of label name
| CALL | m (FAR) | Push CS Push IP CS:IP= [m]
| RET | | Pop IP
| RET | imm | Pop IP SP = SP + imm
| RET | (FAR) | Pop IP Pop CS
| RET | imm (FAR) | Pop IP Pop CS SP = SP + imm |
|
Assembler Directives for Procedures
MASM provides two directives to define procedures:PROC and ENDP. The PROC and ENDP directives mark the beginning and end of a procedure.
 Defining Subroutine |
The basic syntax for PROC is:
label PROC [NEAR | FAR]
.
.
.
RET [constant]
label ENDP
| In a NEAR procedure, both calling and called procedures are in the same code segment.
| | Called and calling procedures are in two different segments in a FAR procedure.
| | PROC and ENDP do not actually generate any code; they are directives, not instructions.
| | PROC and ENDP control the type of RET instruction used in a given subroutine.
| | If the operand to a PROC directive is NEAR then all RET instructions between that PROC directive and the corresponding ENDP directive are assembled as near returns.
| | If, on the other hand, the operand to a PROC directive is FAR, then all RET instructions within that procedure are assembled as far return.
| | If the PROC directive is without any operand, the assembler automatically makes the procedure near or far according to the memory model selected with the .MODEL directive.
| Tiny-, small-, and compact-model program have near calls.
| | Medium-, large-, and huge-model programs have far calls.
|
|
|
Example: TestSub is near-callable |
.MODEL SMALL
.
.
.
TestSub PROC
.
.
ret
TestSub ENDP
|
Example: TestSub is far-callable |
.MODEL LARGE
.
.
.
TestSub PROC
.
.
ret
TestSub ENDP
|