Macros
Defining a macro
A macro is a text template the assembler expands at assembly time. %macro names it and gives the parameter count, %endmacro closes it:
%macro WRITE 2 mov rax, 1 mov rdi, 1 mov rsi, %1 mov rdx, %2 syscall %endmacro WRITE msg, len
Parameters
Parameters are %1 through %n. The assembler pastes them into the template as text, so they can be registers, constants, or expressions:
%macro ADD3 3 mov rax, %1 add rax, %2 add rax, %3 %endmacro ADD3 10, 20, 30 ; rax = 60
Local labels
Labels inside a macro expand once per use, which clashes. The %% prefix makes a label local to one expansion, so two calls of the same macro never see each other's labels. NASM assembles %%loop into a unique label for every call.
%macro COUNTDOWN 1 mov rcx, %1 %%loop: dec rcx jnz %%loop %endmacro COUNTDOWN 5 COUNTDOWN 3
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What closes a macro definition?
Answer
%endmacro
%macro opens the template and %endmacro closes it.
-
How is the first parameter of a macro written inside its body?
Answer
%1
Parameters are %1 through %n, pasted into the body as text.
-
What does the
%%prefix on a macro label do?Answer
It makes the label local to one expansion
Without it, two expansions would define the same label and the assembler would refuse the second.
-
When does a macro expand?
Answer
At assembly time
The assembler pastes the body into the source, so there is no call at run time.
-
What can a macro parameter be?
Answer
A register, a constant or an expression
The parameter is text, so the caller decides what it stands for.
-
What does the parameter count after
%macro WRITE 2mean?Answer
The macro takes two arguments
A call with another number of arguments is an error.
-
What does this program print?
default rel %macro WRITE 2 mov rax, 1 mov rdi, 1 mov rsi, %1 mov rdx, %2 syscall %endmacro section .data msg db "M", 10 section .text global _start _start: WRITE msg, 2 mov rax, 60 xor rdi, rdi syscallAnswer
M
The macro becomes the five instructions of the write, and the buffer is M plus a newline.
-
What exit status does this program return?
%macro ADD3 3 mov rax, %1 add rax, %2 add rax, %3 %endmacro section .text global _start _start: ADD3 10, 20, 30 mov rdi, rax mov rax, 60 syscallAnswer
60
The macro adds 10, 20 and 30 into rax, and that value becomes the status.
-
Why do two calls of a macro with an ordinary label fail?
Answer
The label is defined twice in the expanded source
Each expansion pastes the same label, and a label can be defined only once; %% gives each expansion its own name.
-
Does a macro call cost a CALL and a RET at run time?
Answer
No, the body is pasted into the program
The expansion is ordinary instructions with no call overhead.
The snippets on this page are fragments, not whole programs: they show macro definitions. They were assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev