1 - Memory Declarations and Sections

NASM Program Structure

A typical NASM program consists of three main sections:

SectionPurpose
.dataStores initialized variables
.bssStores uninitialized variables
.textContains the executable code

Example structure:

section .data
    ; initialized variables
 
section .bss
    ; uninitialized variables
 
section .text
global _start
_start:
    ; program instructions

Data Section (.data)

The .data section stores variables that have initial values.

Example:

section .data
    is_single db 1
    year dw 2002
    age dd 22
    phone_no dq 9051765425

Data Definition Directives

DirectiveMeaningSize
dbDefine Byte1 byte
dwDefine Word2 bytes
ddDefine Doubleword4 bytes
dqDefine Quadword8 bytes

Example Variables

VariableDirectiveSizeValue
is_singledb1 byte1
yeardw2 bytes2002
agedd4 bytes22
phone_nodq8 bytes9051765425

BSS Section (.bss)

BSS stands for Block Started by Symbol. The .bss section stores uninitialized variables.

.data stores initialized values in the executable file, while .bss only records the amount of memory needed and the OS allocates it when the program loads.

Example:

section .bss
    var1 resb 3
    var2 resw 2
    var3 resd 2
    var4 resq 3

Memory Reservation Directives

DirectiveMeaning
resbReserve bytes
reswReserve words
resdReserve doublewords
resqReserve quadwords

Example Allocations

VariableDirectiveAllocation
var1resb 33 bytes
var2resw 22 words = 4 bytes
var3resd 22 doublewords = 8 bytes
var4resq 33 quadwords = 24 bytes

Global Variables

Variables defined in .data and .bss are static by default.

To make them accessible outside the file, use the global directive.

Example:

global initialised_static_var
global uninitialised_static_var
section .data
    initialised_static_var db 1
section .bss
    uninitialised_static_var resw 2

Code Section (.text)

The .text section contains executable instructions.

Program execution starts at the _start label.

Example:

section .text
    global _start
 
_start:
    MOV eax, 0x1
    MOV ebx, 0x69
    INT 0x80

Explanation

InstructionMeaning
MOV eax, 0x1Sets syscall number for exit
MOV ebx, 0x69Exit code
INT 0x80Triggers Linux system call

INT 0x80 invokes the Linux kernel syscall handler based on the value stored in the EAX register.

Why Does dw Mean 2 Bytes?

The term word historically refers to the natural register size of the CPU.

However in x86:

TermSize
Byte8 bits
Word16 bits
Doubleword32 bits
Quadword64 bits

This convention exists because the earliest x86 processors were 16-bit, and Intel kept the naming consistent even after the architecture evolved to 32-bit and 64-bit processors.

Summary

  • Code File

  • .data → initialized variables
  • .bss → uninitialized variables
  • .text → executable code
  • db, dw, dd, dq define memory with values
  • resb, resw, resd, resq reserve memory at runtime without initialization
  • global makes symbols accessible outside the file
  • _start is the entry point for the program