Exiting the Procedure

Before you exit your assembly-language procedure, you must perform several steps to restore the calling program's environment. Some of these steps are dependent on actions you took in allocating space for local variables and preserving registers.

You must follow these steps (if appropriate to your procedure) in the order shown:

1.If you saved any of the registers SS, DS, SI, or DI, they must be popped off the stack in the reverse order from which they were saved. If you pop these registers in any other order, your program will behave incorrectly.

2.If you allocated local data space at the beginning of the procedure, you must restore SP with the instruction mov sp,bp.

3.Restore BP with the instruction pop bp. This step is always necessary.

4.Return to the calling program by issuing the ret instruction.

The following example shows the simplest possible entry and exit sequence. In the entry sequence, no registers are saved and no local data space is allocated.

push bp

mov bp,sp ; Set up the new stack frame.

.

.

.

pop bp ; Restore the caller's stack frame.

ret

The following example shows an entry and exit sequence for a procedure that saves SI and DI and allocates local data space on the stack.

push bp

mov bp,sp ; Establish local stack frame.

sub sp,4 ; Allocate space for local data.

push si ; Preserve the SI and DI registers.

push di

.

.

.

pop di ; Pop saved registers.

pop si

mov sp,bp ; Free local data space.

pop bp ; Restore old stack frame.

ret