Monday, 17 March 2025

Procedure and Macro in Assembly Language Program

Procedure and Macro in Assembly Language

In assembly language programming, procedures and macros are two techniques used to structure and reuse code. They help in modularizing the program, reducing redundancy, and improving readability. However, they work differently in execution.


1. Procedure in Assembly Language

A procedure (also called a subroutine or function) is a block of code that performs a specific task. It is defined once and can be called multiple times in the program.

Key Features of Procedures

  • Uses CALL and RET instructions.
  • Saves memory by reusing code.
  • Allows parameter passing via registers, stack, or memory.
  • Helps in modularizing the program.

Syntax of a Procedure

Procedure_Name PROC   ; Procedure declaration

    ; Procedure body (set of instructions)

    RET               ; Return to the caller

Procedure_Name ENDP   ; End of the procedure

Example of a Procedure

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Hello, World!$"

.CODE

MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

   

    CALL DISPLAY_MSG   ; Calling the procedure

    MOV AH, 4CH

    INT 21H           ; Exit program

MAIN ENDP

 

DISPLAY_MSG PROC

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RET               ; Return to caller

DISPLAY_MSG ENDP

END MAIN

Explanation:

  • The DISPLAY_MSG procedure prints "Hello, World!".
  • The CALL DISPLAY_MSG statement invokes the procedure.
  • The RET instruction returns control back to the main program.

Advantages and Disadvantages of Procedures in Assembly Language

Advantages of Procedures

  1. Code Reusability

    • Procedures allow you to write a block of code once and reuse it multiple times, reducing redundancy.
  2. Memory Efficiency

    • Since procedures are stored separately and called when needed, they help save memory compared to macros, which expand inline.
  3. Modular Programming

    • They help break large programs into smaller, manageable units, making the code more readable and easier to debug.
  4. Parameter Passing

    • Procedures can accept parameters via registers, memory, or the stack, making them flexible for different tasks.
  5. Easy Maintenance

    • If a bug is found in a procedure, fixing it in one place updates all calls to it, simplifying debugging and modifications.
  6. Stack-Based Execution

    • Since procedures use the stack to store return addresses and parameters, they allow recursion and structured programming.

Disadvantages of Procedures

  1. Execution Overhead

    • Every procedure call involves pushing/popping return addresses on the stack and jumping to another location in memory, which adds some execution time.
  2. More Instructions

    • Calling and returning from a procedure involves additional instructions (CALL, RET, PUSH, POP), which can slow down execution compared to inline macros.
  3. Complex Debugging

    • If a program has many procedures, debugging can be challenging since execution control jumps across different locations in memory.
  4. Extra Stack Usage

    • Each procedure call consumes stack space for storing return addresses and parameters, which can be problematic in memory-constrained systems.
  5. Not Suitable for Small Repetitive Tasks

    • If a simple task (like printing a character) is implemented as a procedure, the overhead of calling and returning may outweigh its benefits.

When to Use Procedures?

✔ When memory optimization is needed.
✔ When modularity and reusability are important.
✔ When writing large programs that require structured programming.

Near and Far Procedures in Assembly Language

In assembly language programming, procedures (subroutines) can be classified into Near Procedures and Far Procedures based on the memory addressing mode.


1. Near Procedure

A near procedure is a procedure that is located within the same code segment as the calling function. Since it resides in the same segment, only the offset address is required to call and return from the procedure.

Key Features:

  • The procedure is within the same code segment (CS).
  • Only the offset is pushed onto the stack when calling the procedure.
  • Faster execution due to fewer memory operations.
  • Uses CALL (near) and RET instructions.
  • Suitable for small programs or procedures that are called frequently.

Syntax:

Procedure_Name PROC NEAR

    ; Procedure body

    RET   ; Near return

Procedure_Name ENDP

Example of a Near Procedure

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Near Procedure Example!$"

.CODE


MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

   

    CALL PRINT_MSG   ; Calling a near procedure

    MOV AH, 4CH

    INT 21H

MAIN ENDP


PRINT_MSG PROC NEAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RET   ; Return within the same segment

PRINT_MSG ENDP


END MAIN

Explanation:

  • PRINT_MSG is a near procedure because it resides in the same segment as MAIN.
  • When CALL PRINT_MSG is executed, only the offset address is pushed onto the stack.
  • RET retrieves the offset from the stack and returns to the calling function.

2. Far Procedure

A far procedure is a procedure located in a different segment from the calling function. Since it resides in a different segment, both the segment and offset addresses must be stored on the stack.

Key Features:

  • The procedure is in a different code segment.
  • Both segment and offset addresses are pushed onto the stack.
  • Uses CALL FAR and RET FAR instructions.
  • Slightly slower than near procedures due to additional memory operations.
  • Useful in large programs with multiple code segments.

Syntax:

Procedure_Name PROC FAR

    ; Procedure body

    RET   ; Far return

Procedure_Name ENDP

Example of a Far Procedure

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Far Procedure Example!$"

.CODE


MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

   

    CALL FAR PTR PRINT_MSG   ; Calling a far procedure

    MOV AH, 4CH

    INT 21H

MAIN ENDP


; Assume this procedure is in another segment

PRINT_MSG PROC FAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RETF   ; Far return

PRINT_MSG ENDP

 

END MAIN

Explanation:

  • PRINT_MSG is a far procedure, meaning it is in a different code segment.
  • CALL FAR PTR PRINT_MSG is used to explicitly call a far procedure.
  • When calling the procedure, both the segment and offset are pushed onto the stack.
  • RETF is used to return, which pops both segment and offset from the stack.

Difference Between Near and Far Procedures

Feature

Near Procedure

Far Procedure

Memory Location

Same code segment

Different code segment

Stack Storage

Only offset address is pushed

Both segment and offset addresses are pushed

Speed

Faster (

Directives for Procedures in Assembly Language

In assembly language, directives are special instructions that provide guidance to the assembler on how to process the program. When working with procedures, we use certain directives to define, call, and manage procedures efficiently.


1. PROC Directive

The PROC directive is used to define a procedure. It indicates the beginning of a procedure and specifies whether it is NEAR or FAR.

Syntax:

Procedure_Name PROC [NEAR | FAR]

    ; Procedure body

    RET

Procedure_Name ENDP

Example:

PRINT_MSG PROC NEAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RET

PRINT_MSG ENDP

✔ NEAR: Procedure is in the same code segment.
✔ FAR: Procedure is in a different segment.


2. ENDP Directive

The ENDP directive marks the end of a procedure definition. It must match a corresponding PROC directive.

Example:

SUM PROC NEAR

    ; Procedure body

    RET

SUM ENDP


3. CALL Directive

The CALL instruction is used to invoke a procedure. It pushes the return address onto the stack and jumps to the procedure.

Types of CALL:

  • CALL Procedure_Name → Calls a near procedure (same segment).
  • CALL FAR PTR Procedure_Name → Calls a far procedure (different segment).

Example:

CALL PRINT_MSG  ; Calls the procedure


4. RET Directive

The RET instruction is used to return from a procedure.

  • For near procedures, it pops the offset address from the stack.
  • For far procedures, it pops both the segment and offset addresses from the stack.

Example:

RET   ; Return from a near procedure

RETF  ; Return from a far procedure


5. FAR PTR and NEAR PTR Directives

When calling a procedure, you may need to explicitly specify whether it is near or far.

Example:

CALL NEAR PTR SUM      ; Calls a near procedure

CALL FAR PTR DISPLAY   ; Calls a far procedure


6. PUBLIC and EXTRN Directives

These directives are used when working with procedures in separate files.

  • PUBLIC → Declares a procedure so it can be accessed from other files.
  • EXTRN → Declares an external procedure (defined in another file).

Example (File 1 - Procedure Definition):

PUBLIC PRINT_MSG   ; Make procedure accessible to other files

PRINT_MSG PROC FAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RETF

PRINT_MSG ENDP

Example (File 2 - Calling External Procedure):

EXTRN PRINT_MSG: FAR  ; Declare external procedure

 

CALL PRINT_MSG        ; Call procedure from another file


7. END Directive

The END directive marks the end of the program. It tells the assembler that no more instructions follow.

Example:

END MAIN


Summary Table:

Directive

Description

PROC

Defines a procedure (NEAR/FAR)

ENDP

Marks the end of a procedure

CALL

Calls a procedure

RET / RETF

Returns from a procedure (near/far)

FAR PTR / NEAR PTR

Specifies procedure type in calls

PUBLIC

Makes procedure accessible in other files

EXTRN

Declares an external procedure

END

Marks the end of the program

Parameter Passing in Procedure

In assembly language, parameter passing in procedures (subroutines) can be done using different methods, depending on the architecture and calling conventions. The main methods are:

1. Passing Parameters via Registers

  • The fastest method since registers are directly accessible.
  • Common in modern RISC architectures (e.g., ARM, x86-64).
  • Example (x86-32, NASM syntax):

    mov eax, 5 ; First parameter mov ebx, 10 ; Second parameter call my_proc

    my_proc: add eax, ebx ; Perform operation ret

2. Passing Parameters via the Stack

  • Common in C-style calling conventions.
  • Parameters are pushed onto the stack before calling the procedure.
  • Used in x86 (cdecl, stdcall, etc.).
  • Example:

    push 5 ; First parameter push 10 ; Second parameter call my_proc add esp, 8 ; Clean up the stack (2 * 4 bytes) my_proc: push ebp ; Preserve base pointer mov ebp, esp ; New stack frame mov eax, [ebp+8] ; First parameter mov ebx, [ebp+12] ; Second parameter add eax, ebx pop ebp ; Restore base pointer ret

3. Passing Parameters via Global Memory

  • Uses memory locations or global variables to store parameters.
  • Useful when passing large amounts of data.
  • Example:

    section .data param1 dd 5 param2 dd 10 section .text mov eax, [param1] mov ebx, [param2] call my_proc my_proc: add eax, ebx ret

4. Passing Parameters via Parameter Blocks (Structs in Memory)

  • Useful for passing multiple parameters in a structured way.
  • Example (using a stack-based parameter block):

    section .data paramBlock dd 5, 10 ; Store parameters in memory section .text mov esi, paramBlock ; Load address of parameter block call my_proc my_proc: mov eax, [esi] ; Load first parameter mov ebx, [esi+4] ; Load second parameter add eax, ebx ret 

Each method has trade-offs in terms of speed and memory usage, and the best choice depends on the specific assembly language and architecture being used. Let me know if you need examples for a specific processor (x86, ARM, etc.). 


2. Macro in Assembly Language

A macro is a sequence of instructions that is defined once and can be used multiple times in a program. Unlike procedures, macros are expanded inline at the place of invocation.

Key Features of Macros

  • No CALL or RET instructions.
  • Faster execution as code is inserted directly.
  • Increases program size due to inlining.
  • Does not use stack for parameter passing.

Syntax of a Macro

MACRO_NAME MACRO PARAMETERS

    ; Macro body (set of instructions)

ENDM

Example of a Macro

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Hello, Macro!$"

.CODE

PRINT MACRO MESSAGE

    MOV DX, OFFSET MESSAGE

    MOV AH, 09H

    INT 21H

ENDM

 

MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

 

    PRINT MSG    ; Using the macro

    MOV AH, 4CH

    INT 21H

MAIN ENDP

END MAIN

Explanation:

  • The PRINT macro is defined to print a string.
  • When PRINT MSG is called, the assembler replaces it with the macro body.

Differences Between Procedures and Macros

Feature

Procedure

Macro

Call Type

Uses CALL and RET

Expands inline (no CALL)

Memory Usage

Uses less memory (reusable)

Increases code size (expands every time)

Execution Speed

Slower due to call/return overhead

Faster due to inlining

Parameter Passing

Uses stack, registers, or memory

Uses direct substitution

Best For

Large and reusable code blocks

Small repetitive tasks


When to Use What?

  • Use procedures when you need to reuse code multiple times and optimize memory.
  • Use macros when you need fast execution and short repetitive code.

Different assemblers provide different directives for defining macros. Below are some common directives used in macros:


The MACRO directive is used in MASM (Microsoft Macro Assembler) and TASM (Turbo Assembler) to define a reusable block of code, similar to a function but expanded inline at assembly time.


Syntax

macro_name MACRO [parameter1, parameter2, ...] ; Macro body (set of instructions) ENDM
  • macro_name → Name of the macro.
  • MACRO → Defines the start of the macro.
  • ENDM → Marks the end of the macro.

Example 1: Simple Macro (No Parameters)


DISPLAY_HELLO MACRO mov dx, OFFSET message ; Load message address mov ah, 09h ; DOS print string function int 21h ; Call DOS interrupt ENDM .DATA message db "Hello, Assembly!", "$" .CODE DISPLAY_HELLO ; Macro call (expands inline)
  • The macro DISPLAY_HELLO prints a message.
  • ENDM marks the end of the macro definition.
  • When called, the macro expands inline, replacing DISPLAY_HELLO with its body.

Example 2: Macro with Parameters


ADD_NUMS MACRO num1, num2 mov ax, num1 add ax, num2 ENDM .CODE ADD_NUMS 5, 10 ; Expands to `mov ax, 5` and `add ax, 10`
  • The macro takes two parameters and adds them.
  • During assembly, ADD_NUMS 5, 10 expands into:

    mov ax, 5 add ax, 10

Example 3: Macro with Multiple Instructions

PRINT_MSG MACRO msg mov dx, OFFSET msg mov ah, 09h int 21h ENDM .DATA msg1 db "Hello, World!$", 0 msg2 db "Assembly is fun!$", 0 .CODE PRINT_MSG msg1 PRINT_MSG msg2
  • The macro is used twice to print different messages.
  • The inline expansion makes execution faster but increases code size.

ENDM
Directive in Assembly Language

The ENDM directive is used to mark the end of a macro definition in assembly language. It is commonly used in assemblers like MASM (Microsoft Macro Assembler) and TASM (Turbo Assembler).


Syntax

macro_name MACRO [parameters] ; Macro body ENDM

Key Differences Between Macros and Procedures

Feature

Macros

Procedures

Expansion

Inline

Call/Return

Speed

Faster (no call overhead)

Slower (due to stack operations)

Code Size

Larger (each call expands code)

Smaller (single copy in memory)

Parameter Passing

Through macro arguments

Via registers or stack

Macros are ideal for small, frequently used code snippets, while procedures are better for large reusable blocks.

 

No comments:

Post a Comment

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...