TExcelTAD
Home › x86-64 Assembly › The Preprocessor

The Preprocessor

Before NASM assembles a single instruction, its preprocessor runs over the source. Besides macros, it offers assembly-time variables, loops, conditionals and file inclusion. These features generate code and data for you — lookup tables, unrolled loops, debug-only checks — at no cost at run time.

%assign: numeric variables

%define stores text; %assign evaluates an expression and stores the number, and it can be reassigned. That makes it the loop variable of the preprocessor:

nasm
%assign n 5
%assign n n * 2         ; n is now 10

%rep: generating repetitive code and data

%rep count … %endrep repeats a block. With %assign inside, every repetition can be different. Here NASM builds a table of the first 12 squares while assembling, so the program only has to look values up:

nasm · try it yourself
section .data
squares:
%assign i 0
%rep 12
    dq i * i
    %assign i i + 1
%endrep
SQUARE_COUNT equ ($ - squares) / 8

section .text
global _start
_start:
    mov rdi, squares
    mov esi, SQUARE_COUNT
    call print_array

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_array: print rsi unsigned quadwords starting at rdi on one line ----
print_array:
    push rbx
    push r12
    mov rbx, rdi            ; rbx = address of the next element
    mov r12, rsi            ; r12 = elements left
    sub rsp, 32             ; digit buffer, as in print_uint
.element:
    test r12, r12
    jz .finish
    mov rax, [rbx]          ; the number to convert
    lea rsi, [rsp + 31]
    mov byte [rsi], ' '     ; a space after each number ...
    cmp r12, 1
    jne .convert
    mov byte [rsi], 10      ; ... except the last one, which ends the line
.convert:
    mov ecx, 10
.digit:
    xor edx, edx
    div rcx
    add dl, '0'
    dec rsi
    mov [rsi], dl
    test rax, rax
    jnz .digit
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; length of digits + separator
    mov eax, 1
    mov edi, 1
    syscall
    add rbx, 8              ; next quadword
    dec r12
    jmp .element
.finish:
    add rsp, 32
    pop r12
    pop rbx
    ret
0 1 4 9 16 25 36 49 64 81 100 121

%rep also unrolls loops. This sums the elements of an array without any loop instructions at run time — NASM writes out all eight adds:

nasm · try it yourself
section .data
values: dq 5, 10, 15, 20, 25, 30, 35, 40

section .text
global _start
_start:
    xor eax, eax
%assign k 0
%rep 8
    add rax, [values + k * 8]
    %assign k k + 1
%endrep
    mov rdi, rax
    call print_uint

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
180

Conditional assembly

%if, %elif, %else and %endif include or skip source lines depending on an assembly-time expression. %ifdef NAME tests whether a symbol was %defined — the classic way to switch debug output on and off. On the command line, nasm -DDEBUG defines DEBUG without editing the file.

nasm · try it yourself
%define DEBUG                   ; remove this line for a "release" build
%define VERSION 3

%macro println 1
    section .rodata
    %%text: db %1, 10
    %%len   equ $ - %%text
    section .text
    mov eax, 1
    mov edi, 1
    mov rsi, %%text
    mov edx, %%len
    syscall
%endmacro

section .text
global _start
_start:
%ifdef DEBUG
    println "[debug] starting up"
%endif

%if VERSION >= 3
    println "new feature enabled"
%else
    println "old behaviour"
%endif

    println "done"
    mov eax, 60
    xor edi, edi
    syscall
[debug] starting up
new feature enabled
done

Code inside a false %if is not assembled at all: it costs nothing in the program.

Errors and warnings at assembly time

%error stops assembly with a message, which lets you check assumptions early. For example, make sure a buffer is big enough for a structure:

nasm · try it yourself
BUFFER_SIZE equ 16
RECORD_SIZE equ 24

%if RECORD_SIZE > BUFFER_SIZE
    %error "the buffer is too small for one record"
%endif

section .text
global _start
_start:
    mov eax, 60
    xor edi, edi
    syscall
<source>:5: error: the buffer is too small for one record

%warning prints a message but continues.

String and token tools

Directive Effect
%strlen len 'text' len = 4
%substr c 'hello' 1 c = 'h' (1-based)
%strcat s 'ab', 'cd' s = 'abcd'
%xdefine like %define, but expands the value immediately
%undef name forget a definition
%include "file.inc" paste another source file here

%include is how larger projects share macros and constants: put SYS_WRITE equ 1, your print/exit macros and struc definitions into syscalls.inc and include it from every file.

nasm
; syscalls.inc
%ifndef SYSCALLS_INC            ; include guard: only once per file
%define SYSCALLS_INC
SYS_WRITE   equ 1
SYS_EXIT    equ 60
%endif

Test yourself

What is the difference between %define and %assign?

  1. None
  2. %define stores text; %assign evaluates a numeric expression and can be reassigned
  3. %assign only works with strings
  4. %define is evaluated at run time

What does %rep 4 ... %endrep do?

  1. Loops 4 times at run time
  2. Pastes the enclosed lines 4 times at assembly time
  3. Reserves 4 bytes
  4. Repeats the next instruction with rep

How can you enable a %ifdef DEBUG block without editing the source?

  1. nasm -DDEBUG ...
  2. ld --debug
  3. ./prog DEBUG
  4. It's impossible