Detailed Explanation of Memory Segments in Assembly Language

Concept of Memory Segments

In assembly language, memory segments are logical divisions of system memory, with each segment designated for specific types of data storage. This segmentation model enhances the clarity and security of program organization.

Basic Types of Memory Segments

1. Code Segment

Stores the instruction code of the program.

; Using section keyword
section .text
    global _start

_start:
    mov eax, 4          ; System call number (sys_write)
    mov ebx, 1          ; File descriptor (stdout)
    mov ecx, msg        ; Message address
    mov edx, len        ; Message length
    int 0x80            ; Call kernel

    mov eax, 1          ; System call number (sys_exit)
    mov ebx, 0          ; Exit status
    int 0x80            ; Call kernel

; Using segment keyword (same effect)
segment .text
    global _start2

_start2:
    ; Other code...

2. Data Segment

Stores initialized data.

section .data
    ; Various data definition examples

    ; String data
    msg db 'Hello, World!', 0xA    ; String + newline
    len equ $ - msg                ; Calculate string length

    ; Numeric data
    number1 dw 100                 ; 16-bit word
    number2 dd 2000                ; 32-bit double word
    number3 dq 30000               ; 64-bit quad word

    ; Array data
    array db 1, 2, 3, 4, 5         ; Byte array
    word_array dw 10, 20, 30       ; Word array

    ; Constant definition
    MAX_SIZE equ 100               ; Constant

section .data
    ; Can have multiple data segments
    prompt db 'Enter your name: ', 0
    prompt_len equ $ - prompt

3. BSS Segment (Block Started by Symbol)

Stores uninitialized data.

section .bss
    ; Buffer definition examples

    buffer resb 100          ; Reserve 100 bytes
    input resb 256           ; Input buffer

    ; Numeric buffer
    number resw 1            ; Reserve 1 word
    result resd 1            ; Reserve 1 double word
    large_buffer resq 10     ; Reserve 10 quad words

    ; Array buffer
    array_buf resb 50        ; 50-byte array
    word_buf resw 20         ; 20-word array

4. Stack Segment

Used for function calls, local variables, and temporary data storage.

section .text
global _start

_start:
    ; Stack operation example

    ; Save register values to stack
    push eax
    push ebx
    push ecx

    ; Set up stack frame
    mov ebp, esp            ; Save current stack pointer

    ; Allocate space for local variables on the stack
    sub esp, 16             ; Allocate 16 bytes of local space

    ; Use local variables
    mov dword [ebp-4], 10   ; Local variable 1
    mov dword [ebp-8], 20   ; Local variable 2

    ; Restore stack
    add esp, 16             ; Free local space

    ; Restore register values
    pop ecx
    pop ebx
    pop eax

Complete Example Program for Memory Segments

; Complete example of memory segment usage
section .data                   ; Data segment
    welcome db 'Memory Segment Demo', 0xA, 0
    welcome_len equ $ - welcome

    number1 dd 100
    number2 dd 200
    result_msg db 'Result: ', 0
    result_len equ $ - result_msg
    newline db 0xA, 0

section .bss                    ; BSS segment
    result resd 1               ; Result storage
    buffer resb 10              ; Output buffer

section .text                   ; Code segment
    global _start

_start:
    ; Display welcome message
    mov eax, 4
    mov ebx, 1
    mov ecx, welcome
    mov edx, welcome_len
    int 0x80

    ; Calculate the sum of two numbers
    mov eax, [number1]         ; Load number1 from data segment
    add eax, [number2]         ; Add number2
    mov [result], eax          ; Store result in BSS segment

    ; Display result message
    mov eax, 4
    mov ebx, 1
    mov ecx, result_msg
    mov edx, result_len
    int 0x80

    ; Convert number to string and display
    call number_to_string

    ; Display newline
    mov eax, 4
    mov ebx, 1
    mov ecx, newline
    mov edx, 1
    int 0x80

    ; Exit program
    mov eax, 1
    mov ebx, 0
    int 0x80

; Number to string function (using stack)
number_to_string:
    push ebp
    mov ebp, esp
    sub esp, 12                ; Local variable space

    mov eax, [result]          ; Number to convert
    mov edi, buffer + 9        ; End of buffer
    mov byte [edi], 0          ; String terminator
    mov ecx, 10                ; Divisor

.convert_loop:
    dec edi
    xor edx, edx
    div ecx                    ; eax = quotient, edx = remainder
    add dl, '0'                ; Convert to ASCII
    mov [edi], dl              ; Store character
    test eax, eax              ; Check if done
    jnz .convert_loop

    ; Display converted number
    mov eax, 4
    mov ebx, 1
    mov ecx, edi               ; Start of string
    mov edx, buffer + 10       ; Calculate length
    sub edx, edi
    int 0x80

    mov esp, ebp
    pop ebp
    ret

Detailed Example of Stack Operations

section .data
    stack_demo db 'Stack Operation Demo', 0xA, 0
    stack_demo_len equ $ - stack_demo

section .text
    global _start

_start:
    ; Display demo information
    mov eax, 4
    mov ebx, 1
    mov ecx, stack_demo
    mov edx, stack_demo_len
    int 0x80

    ; Demonstrate basic stack operations
    call stack_operations

    ; Demonstrate stack usage in function calls
    mov eax, 10
    mov ebx, 20
    call add_numbers           ; Call function, parameters passed via registers

    ; Exit
    mov eax, 1
    mov ebx, 0
    int 0x80

; Stack operation demonstration
stack_operations:
    push ebp
    mov ebp, esp

    ; Save register state
    push eax
    push ebx
    push ecx
    push edx

    ; Create local variables on the stack
    sub esp, 16                ; Allocate 16 bytes of local space

    ; Initialize local variables
    mov dword [ebp-4], 100     ; Local variable 1
    mov dword [ebp-8], 200     ; Local variable 2
    mov dword [ebp-12], 0      ; Local variable 3

    ; Use local variables for calculations
    mov eax, [ebp-4]
    add eax, [ebp-8]
    mov [ebp-12], eax

    ; Clean up local variable space
    add esp, 16

    ; Restore register state
    pop edx
    pop ecx
    pop ebx
    pop eax

    pop ebp
    ret

; Function example: adding two numbers
add_numbers:
    ; eax = first number, ebx = second number
    ; Return value in eax

    push ebp
    mov ebp, esp

    ; Save modified registers (except eax, as it is the return value)
    push ebx

    ; Perform addition
    add eax, ebx

    ; Restore registers
    pop ebx

    pop ebp
    ret

Example of Using Multiple Data Segments

; Using multiple data segments
section .data
    segment1_data:
        msg1 db 'Message from segment 1', 0xA, 0
        len1 equ $ - msg1

section .data
    segment2_data:
        msg2 db 'Message from segment 2', 0xA, 0
        len2 equ $ - msg2

section .bss
    segment1_bss:
        buf1 resb 64

section .bss
    segment2_bss:
        buf2 resb 64

section .text
    global _start

_start:
    ; Use first data segment
    mov eax, 4
    mov ebx, 1
    mov ecx, msg1
    mov edx, len1
    int 0x80

    ; Use second data segment
    mov eax, 4
    mov ebx, 1
    mov ecx, msg2
    mov edx, len2
    int 0x80

    ; Use BSS segment buffer
    mov edi, buf1
    mov esi, msg1
    call copy_string

    ; Exit
    mov eax, 1
    mov ebx, 0
    int 0x80

; String copy function
copy_string:
    push ebp
    mov ebp, esp
    push esi
    push edi

.copy_loop:
    mov al, [esi]
    mov [edi], al
    inc esi
    inc edi
    test al, al
    jnz .copy_loop

    pop edi
    pop esi
    pop ebp
    ret

Summary of Memory Segments

Main Uses of Each Segment:

Segment Type Keyword Main Use Characteristics
Code Segment <span>.text</span> Stores program instructions Read-only, fixed size
Data Segment <span>.data</span> Stores initialized data Readable and writable, fixed size
BSS Segment <span>.bss</span> Stores uninitialized data Readable and writable, zero-initialized
Stack Segment (implicit) Function calls, local variables Dynamically growing, last in first out

Best Practices:

  1. Code Segment: Only include executable instructions, keep it concise
  2. Data Segment: For constants and initialized variables
  3. BSS Segment: For large buffers and uninitialized data
  4. Stack: For function parameters, return addresses, and local variables

Considerations:

  • Using <span>section</span> or <span>segment</span> keywords has the same effect
  • Data segment and BSS segment allocate memory at program load
  • The stack segment is managed automatically by the operating system
  • Proper use of each segment can enhance program security and efficiency

By organizing memory segments effectively, one can create assembly programs that are well-structured, easy to maintain, while improving memory usage efficiency and program performance.

Leave a Comment