ret and retf Instructions
<span>call</span> and <span>ret</span> are transfer instructions that control the program flow by modifying the IP (Instruction Pointer) or simultaneously modifying both the CS (Code Segment Register) and IP. These instructions are typically used together to implement the design of subroutines (functions).
ret Instruction
<span>ret</span> (return) instruction pops data from the stack to modify the content of IP, achieving a near transfer (intra-segment transfer).
The operations performed by the CPU when executing the <span>ret</span> instruction are:
<span>(IP) = ((ss)*16 + (sp))</span>– Pops the word data from the top of the stack into IP<span>(sp) = (sp) + 2</span>– Increments the stack pointer by 2
In assembly pseudocode, this is equivalent to:
pop IP
retf Instruction
<span>retf</span> (return far) instruction pops data from the stack to modify both CS and IP, achieving a far transfer (inter-segment transfer).
The operations performed by the CPU when executing the <span>retf</span> instruction are:
<span>(IP) = ((ss)*16 + (sp))</span>– Pops the word data from the top of the stack into IP<span>(sp) = (sp) + 2</span>– Increments the stack pointer by 2<span>(CS) = ((ss)*16 + (sp))</span>– Pops the new top word data into CS<span>(sp) = (sp) + 2</span>– Increments the stack pointer again by 2
In assembly pseudocode, this is equivalent to:
pop IP
pop CS
Example Program Analysis
assume cs:code
stack segment
db 16 dup(0) ; Define 16 bytes of stack space, initialized to 0
stack ends
code segment
start:
mov ax, stack
mov ss, ax ; Set stack segment
mov sp, 16 ; Set stack pointer
mov ax, 0 ; Push 0 onto the stack
push ax
ret ; Execute ret instruction
mov ax, 4c00h
int 21h
code ends
end start
In this example:
- The program first sets the stack segment (SS) and stack pointer (SP)
- Pushed 0 onto the stack
- When executing the
<span>ret</span>instruction:
- Pops 0 from the top of the stack into the IP register
- SP increments by 2
<span>mov ax, stack</span>)Key Points Summary
<span>ret</span>is used for near returns, modifying only IP;<span>retf</span>is used for far returns, modifying both CS and IP- Both achieve the setting of return addresses through stack operations
<span>ret</span>is equivalent to<span>pop IP</span>, while<span>retf</span>is equivalent to<span>pop IP</span>followed by<span>pop CS</span>- Subroutines are typically called using
<span>call</span>, and returned using<span>ret</span>or<span>retf</span>, both must be used in matching pairs
Understanding the coordination of <span>call</span> and <span>ret</span>/<span>retf</span> is fundamental to mastering subroutine calls in assembly language.