TExcelTAD
Home › x86-64 Assembly › Macros

Macros

You have typed the four-line write system call many times by now. A macro gives such a pattern a name. Unlike a procedure, a macro is expanded by NASM at assembly time: every use is replaced by a copy of its body, so there is no call, no ret and no stack involved.

Single-line macros with %define

%define name text replaces name by text everywhere after it. It can take parameters in parentheses:

nasm · try it yourself
%define SYS_WRITE   1
%define SYS_EXIT    60
%define STDOUT      1
%define square(x)   ((x) * (x))

section .text
global _start
_start:
    mov edi, square(12)         ; NASM computes 144 at assembly time
    call print_uint
    mov edi, square(3 + 4)      ; ((3 + 4) * (3 + 4)) = 49
    call print_uint

    mov eax, SYS_EXIT
    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
144
49

Note: The parentheses in ((x) * (x)) matter, exactly as with C's #define. Without them, square(3 + 4) would expand to 3 + 4 * 3 + 4 = 19.

Multi-line macros with %macro

A multi-line macro has a name and a parameter count, and its parameters are referred to as %1, %2, …:

nasm
%macro name number_of_parameters
    ; body using %1, %2, ...
%endmacro

Here are two macros that make programs read almost like a high-level language:

nasm · try it yourself
%macro print 2                  ; print address, length
    mov eax, 1
    mov edi, 1
    mov rsi, %1
    mov edx, %2
    syscall
%endmacro

%macro exit 1                   ; exit status
    mov eax, 60
    mov edi, %1
    syscall
%endmacro

section .data
line1:  db "Macros expand", 10
len1    equ $ - line1
line2:  db "at assembly time", 10
len2    equ $ - line2

section .text
global _start
_start:
    print line1, len1
    print line2, len2
    exit 0
Macros expand
at assembly time

Strings as macro arguments

A macro can define its own data. This println macro takes a string literal, places it in .rodata under a unique label, and prints it. %% creates a macro-local label: every expansion gets a fresh name, so the macro can be used many times without "label redefined" errors:

nasm · try it yourself
%macro println 1
    section .rodata
    %%text: db %1, 10           ; a unique label for each use
    %%len   equ $ - %%text
    section .text
    mov eax, 1
    mov edi, 1
    mov rsi, %%text
    mov edx, %%len
    syscall
%endmacro

section .text
global _start
_start:
    println "First line"
    println "Second line"
    println "No data section needed"

    mov eax, 60
    xor edi, edi
    syscall
First line
Second line
No data section needed

Variable numbers of arguments

A parameter count like 1-* means "one or more". %0 is the number of arguments passed, and %rotate 1 shifts them so that %1 becomes the next one. Combined with %rep (which repeats a block a fixed number of times), a macro can push any number of registers:

nasm · try it yourself
%macro multipush 1-*
    %rep %0
        push %1
        %rotate 1
    %endrep
%endmacro

%macro multipop 1-*
    %rep %0
        %rotate -1              ; walk backwards: pop in reverse order
        pop %1
    %endrep
%endmacro

section .text
global _start
_start:
    mov ebx, 1
    mov r12d, 2
    mov r13d, 3
    multipush rbx, r12, r13     ; push rbx / push r12 / push r13
    xor ebx, ebx                ; clobber them all
    xor r12d, r12d
    xor r13d, r13d
    multipop rbx, r12, r13      ; pop r13 / pop r12 / pop rbx

    mov rdi, rbx
    call print_uint
    mov rdi, r12
    call print_uint
    mov rdi, r13
    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
1
2
3

Default parameters

%macro name 0-1 default makes the parameter optional with a default value:

nasm
%macro exit 0-1 0               ; exit, or exit <status>; default 0
    mov eax, 60
    mov edi, %1
    syscall
%endmacro

Macros or procedures?

Macro Procedure
when it "runs" assembly time (text is copied) run time (call/ret)
code size grows with each use one copy
speed no call overhead a call and return per use
arguments any text: registers, constants, strings registers or stack, by convention
local labels need %% ordinary .labels work
can be called from C no yes

A good rule: macros for short, repetitive syntax (system calls, prologues, data definitions), procedures for anything with real logic.

Seeing what a macro produced

NASM can show you the source after preprocessing, which is the best way to debug a misbehaving macro:

bash
nasm -E prog.asm            # print the preprocessed source
nasm -f elf64 -l prog.lst prog.asm   # a listing also shows the expansions

Test yourself

When is a NASM macro expanded?

  1. Every time the program runs
  2. At assembly time, when NASM processes the source
  3. At link time
  4. When it is called with call

Why does a macro that defines a label use %%name instead of name?

  1. It's faster
  2. So each expansion gets a unique label and repeated uses don't clash
  3. To make it global
  4. Because labels can't contain letters

In %macro print 2, how does the body refer to the second argument?

  1. $2
  2. %2
  3. arg2
  4. [2]