NASM - The Netwide Assembler (original) (raw)
Chapter 5: The NASM Preprocessor
NASM contains a powerful macro processor, which supports conditional assembly, multi-level file inclusion, two forms of macro (single-line and multi-line), and a `context stack' mechanism for extra macro power. Preprocessor directives all begin with a %
sign. As a result, some care needs to be taken when using the %
arithmetic operator to avoid it being confused with a preprocessor directive; it is recommended that it always be surrounded by whitespace.
The NASM preprocessor borrows concepts from both the C preprocessor and the macro facilities of many other assemblers.
5.1. Preprocessor Expansions
The input to the preprocessor is expanded in the following ways in the order specified here.
5.1.1. Continuation Line Collapsing
The preprocessor first collapses all lines which end with a backslash (\
) character into a single line. Thus:
%define THIS_VERY_LONG_MACRO_NAME_IS_DEFINED_TO \ THIS_VALUE
will work like a single-line macro without the backslash-newline sequence.
5.1.2. Comment Removal
After concatenation, comments are removed. Comments begin with the character ;
unless contained inside a quoted string or a handful of other special contexts.
Note that this is applied after continuation lines are collapsed. This means that
add al,'\' ; Add the ASCII code for \
mov [ecx],al ; Save the character
will probably not do what you expect, as the second line will be considered part of the preceeding comment. Although this behavior is sometimes confusing, it is both the behavior of NASM since the very first version as well as the behavior of the C preprocessor.
5.1.3. %line
directives
In this step, %line
directives are processed. Seesection 5.13.1.
5.1.4. Conditionals, Loops and Multi-Line Macro Definitions
In this step, the following preprocessor directives are processed:
- Multi-line macro definitions, specified by the
%macro
and%imacro
directives. The body of a multi-line macro is stored and is not further expanded at this time. Seesection 5.5. - Conditional assembly, specified by the
%if
family of preprocessor directives. Disabled part of the source code are discarded and are not futher expanded. See section 5.6. - Preprocessor loops, specified by the
%rep
preprocessor directive. A preprocessor loop is very similar to a multi-line macro and as such the body is stored and is not futher expanded at this time. Seesection 5.7.
These constructs are required to be balanced, so that the ending of a block can be detected, but no further processing is done at this time; stored blocks will be inserted at this step when they are expanded (see below.)
It is specific to each directive to what extent inline expansions and detokenization are performed for the arguments of the directives.
5.1.5. Directives processing
Remaining preprocessor directives are processed. It is specific to each directive to what extend the above expansions or the ones specified insection 5.1.8 are performed on their arguments.
It is specific to each directive to what extent inline expansions and detokenization are performed for the arguments of the directives.
5.1.6. Inline expansions and other directives
In this step, the following expansions are performed on each line:
- Single-line macros are expanded. See section 5.2.
- Preprocessor functions are expanded. See section 5.4.
- If this line is the result of multi-line macro expansions (see below), the parameters to that macro are expanded at this time. Seesection 5.5.
- Macro indirection, using the
%[
...]
construct, is expanded. See section 5.2.3. - Token concatenation using either the
%+
operator (seesection 5.2.4) or implicitly (seesection 5.2.3 andsection 5.5.9.) - Macro-local labels are converted into unique strings, seesection 5.5.2.
5.1.7. Multi-Line Macro Expansion
In this step, multi-line macros are expanded into new lines of source, like the typical macro feature of many other assemblers. Seesection 5.5.
After expansion, the newly injected lines of source are processed starting with the step defined in section 5.1.4.
5.1.8. Detokenization
In this step, the final line of source code is produced. It performs the following operations:
- Environment variables specified using the
%!
construct are expanded. See section 5.9.2. - Context-local labels are expanded into unique strings. Seesection 5.9.2.
- All tokens are converted to their text representation. Unlike the C preprocessor, the NASM preprocessor does not insert whitespace between adjacent tokens unless present in the source code. Seesection 5.5.9.
The resulting line of text either is sent to the assembler, or, if running in preprocessor-only mode, to the output file (seesection 2.1.22); if necessary prefixed by a newly inserted %line
directive.
5.2. Single-Line Macros
Single-line macros are expanded inline, much like macros in the C preprocessor.
5.2.1. The Normal Way: %define
Single-line macros are defined using the %define
preprocessor directive. The definitions work in a similar way to C; so you can do things like
%define ctrl 0x1F & %define param(a,b) ((a)+(a)*(b))
mov byte [param(2,ebx)], ctrl 'D'
which will expand to
mov byte [(2)+(2)*(ebx)], 0x1F & 'D'
When the expansion of a single-line macro contains tokens which invoke another macro, the expansion is performed at invocation time, not at definition time. Thus the code
%define a(x) 1+b(x) %define b(x) 2*x
mov ax,a(8)
will evaluate in the expected way to mov ax,1+2*8
, even though the macro b
wasn't defined at the time of definition ofa
.
Note that single-line macro argument list cannot be preceded by whitespace. Otherwise it will be treated as an expansion. For example:
%define foo (a,b) ; no arguments, (a,b) is the expansion %define bar(a,b) ; two arguments, empty expansion
Macros defined with %define
are case sensitive: after%define foo bar
, only foo
will expand tobar
: Foo
or FOO
will not. By using%idefine
instead of %define
(the `i' stands for `insensitive') you can define all the case variants of a macro at once, so that %idefine foo bar
would cause foo
,Foo
, FOO
, fOO
and so on all to expand to bar
.
There is a mechanism which detects when a macro call has occurred as a result of a previous expansion of the same macro, to guard against circular references and infinite loops. If this happens, the preprocessor will only expand the first occurrence of the macro. Hence, if you code
%define a(x) 1+a(x)
mov ax,a(3)
the macro a(3)
will expand once, becoming1+a(3)
, and will then expand no further. This behaviour can be useful: see section 11.1 for an example of its use.
You can overload single-line macros: if you write
%define foo(x) 1+x %define foo(x,y) 1+x*y
the preprocessor will be able to handle both types of macro call, by counting the parameters you pass; so foo(3)
will become1+3
whereas foo(ebx,2)
will become1+ebx*2
. However, if you define
%define foo bar
then no other definition of foo
will be accepted: a macro with no parameters prohibits the definition of the same name as a macro_with_ parameters, and vice versa.
This doesn't prevent single-line macros being redefined: you can perfectly well define a macro with
%define foo bar
and then re-define it later in the same source file with
%define foo baz
Then everywhere the macro foo
is invoked, it will be expanded according to the most recent definition. This is particularly useful when defining single-line macros with %assign
(seesection 5.2.8).
The following additional features were added in NASM 2.15:
It is possible to define an empty string instead of an argument name if the argument is never used. For example:
%define ereg(foo,) e %+ foo mov eax,ereg(dx,cx)
A single pair of parentheses is a subcase of a single, unused argument:
%define myreg() eax mov edx,myreg()
This is similar to the behavior of the C preprocessor.
- If declared with an
=
, NASM will expand the argument and then evaluate it as a numeric expression. The name of the argument may optionally be followed by/
followed by a numeric radix character (b
,y
,o
,q
,d
,t
,h
orx
) and/or the lettersu
(unsigned) ors
(signed), in which the number is formatted accordingly, with a radix prefix if a radix letter is specified. For the case of hexadecimal, if the radix letter is in upper case, alphabetic hex digits will be in upper case. - If declared with an
&
, NASM will expand the argument and then turn into a quoted string; if the argument already is a quoted string, it will be quoted again. - If declared with
&&
, NASM will expand the argument and then turn it into a quoted string, but if the argument already is a quoted string, it will not be re-quoted. - If declared with a
+
, it is a greedy or variadic parameter; it will include any subsequent commas and parameters. - If declared with an
!
, NASM will not strip whitespace and braces (potentially useful in conjunction with&
or&&
.)
For example:
%define xyzzy(=expr,&val,=hex/x) expr, str, hex
%define plugh(x) xyzzy(x,x,x)
db plugh(13+5), `\0` ; Expands to: db 18, "13+5", 0x12, `\0`
You can pre-define single-line macros using the `-d' option on the NASM command line: see section 2.1.20.
5.2.2. Resolving %define
: %xdefine
To have a reference to an embedded single-line macro resolved at the time that the embedding macro is defined, as opposed to when the embedding macro is expanded, you need a different mechanism to the one offered by %define
. The solution is to use%xdefine
, or it's case-insensitive counterpart%ixdefine
.
Suppose you have the following code:
%define isTrue 1 %define isFalse isTrue %define isTrue 0
val1: db isFalse
%define isTrue 1
val2: db isFalse
In this case, val1
is equal to 0, and val2
is equal to 1. This is because, when a single-line macro is defined using%define
, it is expanded only when it is called. AsisFalse
expands to isTrue
, the expansion will be the current value of isTrue
. The first time it is called that is 0, and the second time it is 1.
If you wanted isFalse
to expand to the value assigned to the embedded macro isTrue
at the time thatisFalse
was defined, you need to change the above code to use%xdefine
.
%xdefine isTrue 1 %xdefine isFalse isTrue %xdefine isTrue 0
val1: db isFalse
%xdefine isTrue 1
val2: db isFalse
Now, each time that isFalse
is called, it expands to 1, as that is what the embedded macro isTrue
expanded to at the time that isFalse
was defined.
%xdefine
and %ixdefine
supports argument expansion exactly the same way that %define
and%idefine
does.
5.2.3. Macro Indirection: %[
...]
The %[...]
construct can be used to expand macros in contexts where macro expansion would otherwise not occur, including in the names other macros. For example, if you have a set of macros namedFoo16
, Foo32
and Foo64
, you could write:
mov ax,Foo%[__?BITS?__] ; The Foo value
to use the builtin macro __?BITS?__
(seesection 6.3) to automatically select between them. Similarly, the two statements:
%xdefine Bar Quux ; Expands due to %xdefine %define Bar %[Quux] ; Expands due to %[...]
have, in fact, exactly the same effect.
%[...]
concatenates to adjacent tokens in the same way that multi-line macro parameters do, see section 5.5.9 for details.
5.2.4. Concatenating Single Line Macro Tokens: %+
Individual tokens in single line macros can be concatenated, to produce longer tokens for later processing. This can be useful if there are several similar macros that perform similar functions.
Please note that a space is required after %+
, in order to disambiguate it from the syntax %+1
used in multiline macros.
As an example, consider the following:
%define BDASTART 400h ; Start of BIOS data area
struc tBIOSDA ; its structure .COM1addr RESW 1 .COM2addr RESW 1 ; ..and so on endstruc
Now, if we need to access the elements of tBIOSDA in different places, we can end up with:
mov ax,BDASTART + tBIOSDA.COM1addr
mov bx,BDASTART + tBIOSDA.COM2addr
This will become pretty ugly (and tedious) if used in many places, and can be reduced in size significantly by using the following macro:
; Macro to access BIOS variables by their names (from tBDA):
%define BDA(x) BDASTART + tBIOSDA. %+ x
Now the above code can be written as:
mov ax,BDA(COM1addr)
mov bx,BDA(COM2addr)
Using this feature, we can simplify references to a lot of macros (and, in turn, reduce typing errors).
5.2.5. The Macro Name Itself: %?
and %??
The special symbols %?
and %??
can be used to reference the macro name itself inside a macro expansion, this is supported for both single-and multi-line macros. %?
refers to the macro name as invoked, whereas %??
refers to the macro name as declared. The two are always the same for case-sensitive macros, but for case-insensitive macros, they can differ.
For example:
%imacro Foo 0 mov %?,%?? %endmacro
foo
FOO
will expand to:
mov foo,Foo
mov FOO,Foo
These tokens can be used for single-line macros if defined outside any multi-line macros. See below.
5.2.6. The Single-Line Macro Name: %*?
and %*??
If the tokens %?
and %??
are used inside a multi-line macro, they are expanded before any directives are processed. As a result,
%imacro Foo 0 %idefine Bar _%? mov BAR,bAr %endmacro
foo
mov eax,bar
will expand to:
mov _foo,_foo
mov eax,_foo
which may or may not be what you expected. The tokens %*?
and %*??
behave like %?
and %??
but are only expanded inside single-line macros. Thus:
%imacro Foo 0 %idefine Bar _%*? mov BAR,bAr %endmacro
foo
mov eax,bar
will expand to:
mov _BAR,_bAr
mov eax,_bar
The %*?
can be used to make a keyword "disappear", for example in case a new instruction has been used as a label in older code. For example:
%idefine pause $%*? ; Hide the PAUSE instruction
%*?
and %*??
were introduced in NASM 2.15.04.
5.2.7. Undefining Single-Line Macros: %undef
Single-line macros can be removed with the %undef
directive. For example, the following sequence:
%define foo bar %undef foo
mov eax, foo
will expand to the instruction mov eax, foo
, since after%undef
the macro foo
is no longer defined.
Macros that would otherwise be pre-defined can be undefined on the command-line using the `-u' option on the NASM command line: seesection 2.1.21.
5.2.8. Preprocessor Variables: %assign
An alternative way to define single-line macros is by means of the%assign
command (and its case-insensitive counterpart%iassign
, which differs from %assign
in exactly the same way that %idefine
differs from %define
).
%assign
is used to define single-line macros which take no parameters and have a numeric value. This value can be specified in the form of an expression, and it will be evaluated once, when the%assign
directive is processed.
Like %define
, macros defined using %assign
can be re-defined later, so you can do things like
%assign i i+1
to increment the numeric value of a macro.
%assign
is useful for controlling the termination of%rep
preprocessor loops: see section 5.7 for an example of this. Another use for %assign
is given in section 10.4 andsection 11.1.
The expression passed to %assign
is a critical expression (see section 3.8), and must also evaluate to a pure number (rather than a relocatable reference such as a code or data address, or anything involving a register).
See also the %eval()
preprocessor function,section 5.4.7.
5.2.9. Defining Strings: %defstr
%defstr
, and its case-insensitive counterpart%idefstr
, define or redefine a single-line macro without parameters but converts the entire right-hand side, after macro expansion, to a quoted string before definition.
For example:
%defstr test TEST
is equivalent to
%define test 'TEST'
This can be used, for example, with the %!
construct (seesection 5.13.2):
%defstr PATH %!PATH ; The operating system PATH variable
See also the %str()
preprocessor function,section 5.4.20.
5.2.10. Defining Tokens: %deftok
%deftok
, and its case-insensitive counterpart%ideftok
, define or redefine a single-line macro without parameters but converts the second parameter, after string conversion, to a sequence of tokens.
For example:
%deftok test 'TEST'
is equivalent to
%define test TEST
See also the %tok()
preprocessor function,section 5.4.24.
5.2.11. Defining Aliases: %defalias
%defalias
, and its case-insensitive counterpart%idefalias
, define an alias to a macro, i.e. equivalent of a symbolic link.
When used with various macro defining and undefining directives, it affects the aliased macro. This functionality is intended for being able to rename macros while retaining the legacy names.
When an alias is defined, but the aliased macro is then undefined, the aliases can legitimately point to nonexistent macros.
The alias can be undefined using the %undefalias
directive.All aliases can be undefined using the%clear defalias
directive. This includes backwards compatibility aliases defined by NASM itself.
To disable aliases without undefining them, use the%aliases off
directive.
To check whether an alias is defined, regardless of the existence of the aliased macro, use %ifdefalias
.
For example:
%defalias OLD NEW ; OLD and NEW both undefined %define NEW 123 ; OLD and NEW both 123 %undef OLD ; OLD and NEW both undefined %define OLD 456 ; OLD and NEW both 456 %undefalias OLD ; OLD undefined, NEW defined to 456
5.2.12. Conditional Comma Operator: %,
As of version 2.15, NASM has a conditional comma operator%,
that expands to a comma unless followed by a null expansion, which allows suppressing the comma before an empty argument. This is especially useful with greedy single-line macros.
For example, all the expressions below are valid:
%define greedy(a,b,c+) a + 66 %, b * 3 %, c
db greedy(1,2) ; db 1 + 66, 2 * 3
db greedy(1,2,3) ; db 1 + 66, 2 * 3, 3
db greedy(1,2,3,4) ; db 1 + 66, 2 * 3, 3, 4
db greedy(1,2,3,4,5) ; db 1 + 66, 2 * 3, 3, 4, 5
5.3. String Manipulation in Macros
It's often useful to be able to handle strings in macros. NASM supports a few simple string handling macro operators from which more complex operations can be constructed.
All the string operators define or redefine a single-line macro to some value (either a string or a numeric value). When producing a string value, it may change the style of quoting of the input string or strings, and possibly use \
–escapes inside`
–quoted strings.
These directives are also available as preprocessor functions, seesection 5.4.
5.3.1. Concatenating Strings: %strcat
The %strcat
operator concatenates quoted strings and assign them to a single-line macro.
For example:
%strcat alpha "Alpha: ", '12" screen'
... would assign the value 'Alpha: 12" screen'
toalpha
. Similarly:
%strcat beta '"foo"', "'bar'"
... would assign the value `"foo"\\'bar'`
tobeta
.
The use of commas to separate strings is permitted but optional.
The corresponding preprocessor function is %strcat()
, seesection 5.4.21.
5.3.2. String Length: %strlen
The %strlen
operator assigns the length of a string to a macro. For example:
%strlen charcnt 'my string'
In this example, charcnt
would receive the value 9, just as if an %assign
had been used. In this example,'my string'
was a literal string but it could also have been a single-line macro that expands to a string, as in the following example:
%define sometext 'my string' %strlen charcnt sometext
As in the first case, this would result in charcnt
being assigned the value of 9.
The corresponding preprocessor function is %strlen()
, seesection 5.4.22.
5.3.3. Extracting Substrings: %substr
Individual letters or substrings in strings can be extracted using the%substr
operator. An example of its use is probably more useful than the description:
%substr mychar 'xyzw' 1 ; equivalent to %define mychar 'x' %substr mychar 'xyzw' 2 ; equivalent to %define mychar 'y' %substr mychar 'xyzw' 3 ; equivalent to %define mychar 'z' %substr mychar 'xyzw' 2,2 ; equivalent to %define mychar 'yz' %substr mychar 'xyzw' 2,-1 ; equivalent to %define mychar 'yzw' %substr mychar 'xyzw' 2,-2 ; equivalent to %define mychar 'yz'
As with %strlen
(see section 5.3.2), the first parameter is the single-line macro to be created and the second is the string. The third parameter specifies the first character to be selected, and the optional fourth parameter (preceded by comma) is the length. Note that the first index is 1, not 0 and the last index is equal to the value that %strlen
would assign given the same string. Index values out of range result in an empty string. A negative length means "until N-1 characters before the end of string", i.e.-1
means until end of string, -2
until one character before, etc.
The corresponding preprocessor function is %substr()
, seesection 5.4.23, however please note that the default value for the length parameter, if omitted, is -1
rather than 1
for %substr()
.
5.4. Preprocessor Functions
Preprocessor functions are, fundamentally, a kind of built-in single-line macros. They expand to a string depending on its arguments, and can be used in any context where single-line macro expansion would be performed. Preprocessor functions were introduced in NASM 2.16.
Starting with NASM 3.00, the %ifdef
directive or%isdef()
function can also test for the availability of preprocessor functions. They cannot, however, be undefined, aliased or redefined.
5.4.1. %abs()
Function
The %abs()
function evaluates its first argument as an expression, and then emits the absolute value. This will always be emitted as a single token containing a decimal number; no minus sign will be emitted even if the input value is the maximum negative number.
5.4.2. %b2hs()
Function
The %b2hs()
functin takes a quoted string and an optional separator string, and expands to a quoted string containing a packed hexadecimal form of the bytes of the first string, separated by the separator string if applicable. This is the inverse of the%hs2b()
function, see section 5.4.10.
5.4.3. %chr()
Function
The %chr()
function evaluates its arguments as integers, then creates a quoted string out of these integers (mod 256) as bytes.
5.4.4. %cond()
Function
The %cond()
function evaluates its first argument as an expression, then expands to its second argument if true (nonzero), and the third, if present, if false (zero). This is in effect a specialized version of the %sel()
function; %cond(x,y,z)
is equivalent to %sel(1+!(x),y,z)
.
%define a 1 %xdefine astr %cond(a,"true","false") ; %define astr "true"
The argument not selected is never expanded.
5.4.5. %count()
Function
The %count()
function expands to the number of argments passed to the macro. Note that just as for single-line macros,%count()
treats an empty argument list as a single empty argument.
%xdefine empty %count() ; %define empty 1 %xdefine one %count(1) ; %define one 1 %xdefine two %count(5,q) ; %define two 2 %define list a,b,46 %xdefine lc1 %count(list) ; %define lc 1 (just one argument) %xdefine lc2 %count(%[list]) ; %define lc 3 (indirection expands)
5.4.6. %depend()
Function
he %depend()
function takes a quoted string as argument, adds it to the output dependency list generated by the -M
options (see section 2.1.5), and evaluates to the unchanged string.
This is the function equivalent of the %depend
directive, see section 5.8.3.
See also the %pathsearch()
function (section 5.4.16).
5.4.7. %eval()
Function
The %eval()
function evaluates its argument as a numeric expression and expands to the result as an integer constant in much the same way the %assign
directive would, seesection 5.2.8. Unlike %assign
,%eval()
supports more than one argument; if more than one argument is specified, it is expanded to a comma-separated list of values.
%assign a 2 %assign b 3 %defstr what %eval(a+b,a*b) ; equivalent to %define what "5,6"
The expressions passed to %eval()
are critical expressions, see section 3.8.
5.4.8. %find()
and %findi()
Functions
The %find()
and %findi()
functions take an argument followed by an optional list. These are turned into quoted strings if necessary, and then compared as if by the %isidn()
or%isidni()
functions, respectively (seesection 5.6.6) – the%find()
function compares case sensitively, and%findi()
case insensitively.
The functions then expand to 0
if none of the strings in the list match the first string, or the position in the list where the first string was found, where 1
is the first argument in the list, i.e. not including the first argument to the function.
Once a matching argument has been found, no further arguments are expanded.
For example:
db %find(a,b,c,d) ; 0
db %find(a,b,a,c) ; 2
db %find(a) ; 0 (empty list)
5.4.9. %hex()
Function
Equivalent to %eval()
, except that the results generated are given as unsigned hexadecimal, with a 0x
prefix.
5.4.10. %hs2b()
Function
The %hs2b()
function takes one or more quoted strings containing hexadecimal numbers and optional separators (any character that is not a valid hexadecimal digit is considered a separator) and expands to a quoted string containing the bytes encoded in the hexadecimal string. Every pair of hexadecimal digits encodes a byte, but a separator will always terminate the encoding of a byte. Thus, these two statements will produce the same output:
db 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09
db %hs2b("00010203 4 0506 07 8","9")
This can be used to compactly encode long strings of binary data in source code.
5.4.11. %is()
Family Functions
Each %if
conditional assembly family directive (seesection 5.6) has an equivalent%is()
family function, that expands to 1
if the equivalent %if
directive would process as true, and0
if the equivalent %if
directive would process as false.
This includes the %ifn
forms of these directives, which become %isn()
.
; Instead of !%isidn() could have used %isnidn() %if %isdef(foo) && !%isidn(foo,bar) db "foo is defined, but not as 'bar'" %endif
Note that, being functions, the arguments (before expansion) will always need to have balanced parentheses so that the end of the argument list can be defined. This means that the syntax of e.g. %istoken()
and%isidn()
is somewhat stricter than their corresponding%if
directives; it may be necessary to escape the argument to the conditional using {}
:
; Instead of !%isidn() could have used %isnidn() %if %isdef(foo) && !%isidn({foo,)}) db "foo is defined, but not as ')'" %endif
Unlike the C defined()
preprocessor construct, these functions are valid anywhere in the source code, not just in%if
expressions.
5.4.12. %map()
Function
The %map()
function takes as its first parameter the name of a single-line macro, followed by up to two optional colon-separated subparameters:
- The first subparameter, if present, should be a list of macro parameters enclosed in parentheses. Note that
()
represents a one-argument list containing an empty parameter; omit the parentheses to specify no parameters. - The second subparameter, if present, represent the number of group size for additional parameters to the macro (default 1).
Further parameters, if any, are then passed as additional parameters to the given macro for expansion, in sets given by the specified group size, and the results turned into a comma-separated list. If no additional parameters are given, %map()
expands to nothing.
For example:
%define alpha(&x) x %define alpha(&x,y) y dup (x) %define alpha(s,&x,y) y dup (x,s) ; 0 fixed + 1 grouped parameters per call, calls alpha(&x) db %map(alpha,foo,bar,baz,quux) ; 0 fixed + 2 grouped parameters per call, calls alpha(&x,y) db %map(alpha::2,foo,bar,baz,quux) ; 1 fixed + 2 grouped parameters per call, calls alpha(s,&x,y) db %map(alpha:("!"):2,foo,bar,baz,quux)
... expands to:
db 'foo','bar','baz','quux'
db bar dup ('foo'),quux dup ('baz')
db bar dup ('foo',"!"),quux dup ('baz',"!")
As a more complex example, a macro that joins quoted strings together with a user-specified delimiter string:
%define join(sep) '' ; handle the case of zero strings %define _join(sep,str) sep,str ; helper macro %define join(sep,s1,sn+) %strcat(s1, %map(_join:(sep) %, sn))
db join(':')
db join(':','a')
db join(':','a','b')
db join(':','a','b','c')
db join(':','a','b','c','d')
... expands to:
db ''
db 'a'
db 'a:b'
db 'a:b:c'
db 'a:b:c:d'
5.4.13. %null()
Function
The %null()
function ignores its arguments without expanding them, and expands to nothing.
5.4.14. %num()
Function
The %num()
function evaluates its arguments as expressions, and then produces a quoted string encoding the first argument as an_unsigned_ 64-bit integer.
The second argument is the desired number of digits (max 255, default –1).
The third argument is the encoding base (from 2 to 64, default 10); if the base is given as –2, –8, –10, or –16, then0b
, 0q
, 0d
or 0x
is prepended, respectively; all other negative values are disallowed.
Only the first argument is required.
If the number of digits is negative, NASM will add additional digits if needed; if positive the string is truncated to the number of digits specified. 0 is treated as –1, except that the input number 0 always generates an empty string (thus, the first digit will never be zero), even if the base given is negative.
The full 64-symbol set used is, in order:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_
If a signed number needs to be converted to a string, use%abs()
, %cond()
, and %strcat()
to format the signed number string to your specific output requirements.
5.4.15. %ord()
Function
The %ord()
function takes a quoted string, and (like%substr()
, see section 5.4.23) an optional starting index and length, and expands to a comma-separated list of integers corresponding to the bytes of the quoted string. Note that unlike %substr()
the length argument defaults to1
, so if it is not given only a single byte value is expanded.
5.4.16. %pathsearch()
Function
The %pathsearch()
function takes a quoted string as argument, and searches for a file with that name in the include path, then expands to the pathname located, if found, otherwise to the unmodified string.
This is the function equivalent of the %pathsearch
directive, see section 5.8.2.
See also the %depend()
function (section 5.4.6).
5.4.17. %realpath()
Function
The %realpath()
function takes a quoted string as argument, and attempts to convert it to a fully qualified absolute path name if supported by the underlying host operating system.
If successful, it expands to a quoted string with the resulting path name, otherwise to the unmodified string.
The include path is not searched; to search for the file using the include path, use the %pathsearch()
function in conjunction with this function, for example:
%define SOMEREALPATH %realpath(%pathsearch("somefile.asm"))
5.4.18. %sel()
Function
The %sel()
function evaluates its first argument as an expression, then expands to its second argument if 1, the third argument if 2, and so on. If the value is less than 1 or larger than the number of arguments minus one, then the %sel()
function expands to nothing.
%define b 2 %xdefine bstr %sel(b,"one","two","three") ; %define bstr "two"
The arguments not selected are never expanded.
5.4.19. %selbits()
Function
The %selbits()
function returns its first, second, or third argument depending on if the current mode is 16, 32 or 64 bits. If less than three arguments are given, the last argument is considered repeated. Like %cond()
, this is a specialized version of the%sel()
function.
For example:
BITS 64
%define breg %selbits(bx,ebx,rbx) %define vreg %selbits(ax,eax)
mov vreg,[breg] ; mov eax,[rbx]
5.4.20. %str()
Function
The %str()
function converts its argument, including any commas, to a quoted string, similar to the way the %defstr
directive would, see section 5.2.9.
Being a function, the argument will need to have balanced parentheses or be escaped using {}
.
; The following lines are all equivalent %define test 'TEST' %defstr test TEST %xdefine test %str(TEST)
5.4.21. %strcat()
Function
The %strcat()
function concatenates a list of quoted strings, in the same way the %strcat
directive would, seesection 5.3.1.
; The following lines are all equivalent %define alpha 'Alpha: 12" screen' %strcat alpha "Alpha: ", '12" screen' %xdefine alpha %strcat("Alpha: ", '12" screen')
5.4.22. %strlen()
Function
The %strlen()
function expands to the length of a quoted string, in the same way the %strlen
directive would, seesection 5.3.2.
; The following lines are all equivalent %define charcnt 9 %strlen charcnt 'my string' %xdefine charcnt %strlen('my string')
5.4.23. %substr()
Function
The %substr()
function extracts a substring of a quoted string, in the same way the %substr
directive would, seesection 5.3.3. Note that unlike the%substr
directive, commas are required between all parameters, is required after the string argument, and that the default for the length argument, if omitted, is -1
(i.e. the remainder of the string) rather than 1
.
; The following lines are all equivalent %define mychar 'yzw' %substr mychar 'xyzw' 2,-1 %xdefine mychar %substr('xyzw',2,3) %xdefine mychar %substr('xyzw',2,-1) %xdefine mychar %substr('xyzw',2)
5.4.24. %tok()
function
The %tok()
function converts a quoted string into a sequence of tokens, in the same way the %deftok
directive would, see section 5.2.10.
; The following lines are all equivalent %define test TEST %deftok test 'TEST' %define test %tok('TEST')
5.5. Multi-Line Macros: %macro
Multi-line macros much like the type of macro seen in MASM and TASM, and expand to a new set of lines of source code. A multi-line macro definition in NASM looks something like this.
%macro prologue 1
push ebp
mov ebp,esp
sub esp,%1
%endmacro
This defines a C-like function prologue as a macro: so you would invoke the macro with a call such as:
myfunc: prologue 12
which would expand to the three lines of code
myfunc: push ebp mov ebp,esp sub esp,12
The number 1
after the macro name in the%macro
line defines the number of parameters the macroprologue
expects to receive. The use of %1
inside the macro definition refers to the first parameter to the macro call. With a macro taking more than one parameter, subsequent parameters would be referred to as %2
, %3
and so on.
Multi-line macros, like single-line macros, are case-sensitive, unless you define them using the alternative directive %imacro
.
If you need to pass a comma as part of a parameter to a multi-line macro, you can do that by enclosing the entire parameter in braces. So you could code things like:
%macro silly 2
%2: db %1
%endmacro
silly 'a', letter_a ; letter_a: db 'a'
silly 'ab', string_ab ; string_ab: db 'ab'
silly {13,10}, crlf ; crlf: db 13,10
The behavior with regards to empty arguments at the end of multi-line macros before NASM 2.15 was often very strange. For backwards compatibility, NASM attempts to recognize cases where the legacy behavior would give unexpected results, and issues a warning, but largely tries to match the legacy behavior. This can be disabled with the%pragma
(see section 5.12.1):
%pragma preproc sane_empty_expansion
5.5.1. Overloading Multi-Line Macros
As with single-line macros, multi-line macros can be overloaded by defining the same macro name several times with different numbers of parameters. This time, no exception is made for macros with no parameters at all. So you could define
%macro prologue 0
push ebp
mov ebp,esp
%endmacro
to define an alternative form of the function prologue which allocates no local stack space.
Sometimes, however, you might want to `overload' a machine instruction; for example, you might want to define
%macro push 2
push %1
push %2
%endmacro
so that you could code
push ebx ; this line is not a macro call
push eax,ecx ; but this one is
Ordinarily, NASM will give a warning for the first of the above two lines, since push
is now defined to be a macro, and is being invoked with a number of parameters for which no definition has been given. The correct code will still be generated, but the assembler will give a warning. This warning can be disabled by the use of the-w-macro-params
command-line option (seesection 2.1.26).
5.5.2. Macro-Local Labels
NASM allows you to define labels within a multi-line macro definition in such a way as to make them local to the macro call: so calling the same macro multiple times will use a different label each time. You do this by prefixing %%
to the label name. So you can invent an instruction which executes a RET
if the Z
flag is set by doing this:
%macro retz 0
jnz %%skip
ret
%%skip:
%endmacro
You can call this macro as many times as you want, and every time you call it NASM will make up a different `real' name to substitute for the label %%skip
. The names NASM invents are of the form..@2345.skip
, where the number 2345 changes with every macro call. The ..@
prefix prevents macro-local labels from interfering with the local label mechanism, as described insection 3.9. You should avoid defining your own labels in this form (the ..@
prefix, then a number, then another period) in case they interfere with macro-local labels.
These labels are really macro-local tokens, and can be used for other purposes where a token unique to each macro invocation is desired, e.g. to name single-line macros without using the context feature (section 5.9.2).
5.5.3. Greedy Macro Parameters
Occasionally it is useful to define a macro which lumps its entire command line into one parameter definition, possibly after extracting one or two smaller parameters from the front. An example might be a macro to write a text string to a file in MS-DOS, where you might want to be able to write
writefile [filehandle],"hello, world",13,10
NASM allows you to define the last parameter of a macro to be_greedy_, meaning that if you invoke the macro with more parameters than it expects, all the spare parameters get lumped into the last defined one along with the separating commas. So if you code:
%macro writefile 2+
jmp %%endstr
%%str: db %2 %%endstr: mov dx,%%str mov cx,%%endstr-%%str mov bx,%1 mov ah,0x40 int 0x21
%endmacro
then the example call to writefile
above will work as expected: the text before the first comma, [filehandle]
, is used as the first macro parameter and expanded when %1
is referred to, and all the subsequent text is lumped into %2
and placed after the db
.
The greedy nature of the macro is indicated to NASM by the use of the+
sign after the parameter count on the %macro
line.
If you define a greedy macro, you are effectively telling NASM how it should expand the macro given any number of parameters from the actual number specified up to infinity; in this case, for example, NASM now knows what to do when it sees a call to writefile
with 2, 3, 4 or more parameters. NASM will take this into account when overloading macros, and will not allow you to define another form ofwritefile
taking 4 parameters (for example).
Of course, the above macro could have been implemented as a non-greedy macro, in which case the call to it would have had to look like
writefile [filehandle], {"hello, world",13,10}
NASM provides both mechanisms for putting commas in macro parameters, and you choose which one you prefer for each macro definition.
See section 8.3.1 for a better way to write the above macro.
5.5.4. Macro Parameters Range
NASM allows you to expand parameters via special construction%{x:y}
where x
is the first parameter index andy
is the last. Any index can be either negative or positive but must never be zero.
For example
%macro mpar 1-* db %{3:5} %endmacro
mpar 1,2,3,4,5,6
expands to 3,4,5
range.
Even more, the parameters can be reversed so that
%macro mpar 1-* db %{5:3} %endmacro
mpar 1,2,3,4,5,6
expands to 5,4,3
range.
But even this is not the last. The parameters can be addressed via negative indices so NASM will count them reversed. The ones who know Python may see the analogue here.
%macro mpar 1-* db %{-1:-3} %endmacro
mpar 1,2,3,4,5,6
expands to 6,5,4
range.
Note that NASM uses comma to separate parameters being expanded.
By the way, here is a trick – you might use the index%{-1:-1
} which gives you the last argument passed to a macro.
5.5.5. Default Macro Parameters
NASM also allows you to define a multi-line macro with a _range_of allowable parameter counts. If you do this, you can specify defaults for omitted parameters. So, for example:
%macro die 0-1 "Painful program death has occurred."
writefile 2,%1
mov ax,0x4c01
int 0x21
%endmacro
This macro (which makes use of the writefile
macro defined in section 5.5.3) can be called with an explicit error message, which it will display on the error output stream before exiting, or it can be called with no parameters, in which case it will use the default error message supplied in the macro definition.
In general, you supply a minimum and maximum number of parameters for a macro of this type; the minimum number of parameters are then required in the macro call, and then you provide defaults for the optional ones. So if a macro definition began with the line
%macro foobar 1-3 eax,[ebx+2]
then it could be called with between one and three parameters, and%1
would always be taken from the macro call. %2
, if not specified by the macro call, would default to eax
, and%3
if not specified would default to [ebx+2]
.
You can provide extra information to a macro by providing too many default parameters:
%macro quux 1 something
This will trigger a warning by default; seesection 2.1.26 for more information. When quux
is invoked, it receives not one but two parameters. something
can be referred to as %2
. The difference between passing something
this way and writingsomething
in the macro body is that with this waysomething
is evaluated when the macro is defined, not when it is expanded.
You may omit parameter defaults from the macro definition, in which case the parameter default is taken to be blank. This can be useful for macros which can take a variable number of parameters, since the %0
token (see section 5.5.6) allows you to determine how many parameters were really passed to the macro call.
This defaulting mechanism can be combined with the greedy-parameter mechanism; so the die
macro above could be made more powerful, and more useful, by changing the first line of the definition to
%macro die 0-1+ "Painful program death has occurred.",13,10
The maximum parameter count can be infinite, denoted by *
. In this case, of course, it is impossible to provide a full set of default parameters. Examples of this usage are shown insection 5.5.8.
5.5.6. %0
: Macro Parameter Counter
The parameter reference %0
will return a numeric constant giving the number of parameters received, that is, if %0
is n then %
n is the last parameter. %0
is mostly useful for macros that can take a variable number of parameters. It can be used as an argument to %rep
(seesection 5.7) in order to iterate through all the parameters of a macro. Examples are given insection 5.5.8.
5.5.7. %00
: Label Preceding Macro
%00
will return the label preceding the macro invocation, if any. The label must be on the same line as the macro invocation, may be a local label (see section 3.9), and need not end in a colon.
If %00
is present anywhere in the macro body, the label itself will not be emitted by NASM. You can, of course, put%00:
explicitly at the beginning of your macro.
5.5.8. %rotate
: Rotating Macro Parameters
Unix shell programmers will be familiar with the shift
shell command, which allows the arguments passed to a shell script (referenced as $1
, $2
and so on) to be moved left by one place, so that the argument previously referenced as $2
becomes available as $1
, and the argument previously referenced as $1
is no longer available at all.
NASM provides a similar mechanism, in the form of %rotate
. As its name suggests, it differs from the Unix shift
in that no parameters are lost: parameters rotated off the left end of the argument list reappear on the right, and vice versa.
%rotate
is invoked with a single numeric argument (which may be an expression). The macro parameters are rotated to the left by that many places. If the argument to %rotate
is negative, the macro parameters are rotated to the right.
So a pair of macros to save and restore a set of registers might work as follows:
%macro multipush 1-*
%rep %0 push %1 %rotate 1 %endrep
%endmacro
This macro invokes the PUSH
instruction on each of its arguments in turn, from left to right. It begins by pushing its first argument, %1
, then invokes %rotate
to move all the arguments one place to the left, so that the original second argument is now available as %1
. Repeating this procedure as many times as there were arguments (achieved by supplying %0
as the argument to %rep
) causes each argument in turn to be pushed.
Note also the use of *
as the maximum parameter count, indicating that there is no upper limit on the number of parameters you may supply to the multipush
macro.
It would be convenient, when using this macro, to have aPOP
equivalent, which didn't require the arguments to be given in reverse order. Ideally, you would write themultipush
macro call, then cut-and-paste the line to where the pop needed to be done, and change the name of the called macro tomultipop
, and the macro would take care of popping the registers in the opposite order from the one in which they were pushed.
This can be done by the following definition:
%macro multipop 1-*
%rep %0 %rotate -1 pop %1 %endrep
%endmacro
This macro begins by rotating its arguments one place to the_right_, so that the original last argument appears as%1
. This is then popped, and the arguments are rotated right again, so the second-to-last argument becomes %1
. Thus the arguments are iterated through in reverse order.
5.5.9. Concatenating Macro Parameters
NASM can concatenate macro parameters and macro indirection constructs with other surrounding text. This allows you to declare a family of symbols, for example, in a macro definition. If, for example, you wanted to generate a table of key codes along with offsets into the table, you could code something like
%macro keytab_entry 2
keypos%1 equ $-keytab
db %2
%endmacro
keytab: keytab_entry F1,128+1 keytab_entry F2,128+2 keytab_entry Return,13
which would expand to
keytab: keyposF1 equ $-keytab db 128+1 keyposF2 equ $-keytab db 128+2 keyposReturn equ $-keytab db 13
You can just as easily concatenate text on to the other end of a macro parameter, by writing %1foo
.
If you need to append a digit to a macro parameter, for example defining labels foo1
and foo2
when passed the parameter foo
, you can't code %11
because that would be taken as the eleventh macro parameter. Instead, you must code%{1}1
, which will separate the first 1
(giving the number of the macro parameter) from the second (literal text to be concatenated to the parameter).
This concatenation can also be applied to other preprocessor in-line objects, such as macro-local labels (section 5.5.2) and context-local labels (section 5.9.2). In all cases, ambiguities in syntax can be resolved by enclosing everything after the %
sign and before the literal text in braces: so %{%foo}bar
concatenates the textbar
to the end of the real name of the macro-local label%%foo
. (This is unnecessary, since the form NASM uses for the real names of macro-local labels means that the two usages%{%foo}bar
and %%foobar
would both expand to the same thing anyway; nevertheless, the capability is there.)
The single-line macro indirection construct, %[...]
(section 5.2.3), behaves the same way as macro parameters for the purpose of concatenation.
See also the %+
operator, section 5.2.4.
5.5.10. Condition Codes as Macro Parameters
NASM can give special treatment to a macro parameter which contains a condition code. For a start, you can refer to the macro parameter%1
by means of the alternative syntax %+1
, which informs NASM that this macro parameter is supposed to contain a condition code, and will cause the preprocessor to report an error message if the macro is called with a parameter which is not a valid condition code.
Far more usefully, though, you can refer to the macro parameter by means of %-1
, which NASM will expand as the _inverse_condition code. So the retz
macro defined insection 5.5.2 can be replaced by a general conditional-return macro like this:
%macro retc 1
j%-1 %%skip
ret
%%skip:
%endmacro
This macro can now be invoked using calls like retc ne
, which will cause the conditional-jump instruction in the macro expansion to come out as JE
, or retc po
which will make the jump a JPE
.
The %+1
macro-parameter reference is quite happy to interpret the arguments CXZ
and ECXZ
as valid condition codes; however, %-1
will report an error if passed either of these, because no inverse condition code exists.
5.5.11. Disabling Listing Expansion
When NASM is generating a listing file from your program, it will generally expand multi-line macros by means of writing the macro call and then listing each line of the expansion. This allows you to see which instructions in the macro expansion are generating what code; however, for some macros this clutters the listing up unnecessarily.
NASM therefore provides the .nolist
qualifier, which you can include in a macro definition to inhibit the expansion of the macro in the listing file. The .nolist
qualifier comes directly after the number of parameters, like this:
%macro foo 1.nolist
Or like this:
%macro bar 1-5+.nolist a,b,c,d,e,f,g,h
5.5.12. Undefining Multi-Line Macros: %unmacro
, %unimacro
Multi-line macros can be removed with the %unmacro
or%unimacro
directives.
Unlike the %undef
directive, however, these directives take an argument specification, and will only remove exact matches with that argument specification. Furthermore, case sensitive macros have match the directive: a case-sensitive macro has to be removed with%unmacro
, and a case-insensitive one with%unimacro
. This ensures that only the specific macro intended is removed.
For example:
%macro foo 1-3 ; Do something %endmacro %unmacro foo 1-3
removes the previously defined macro foo
, but
%macro bar 1-3 ; Do something %endmacro %unmacro bar 1
does not remove the macro bar
, since the argument specification does not match exactly.
5.5.13. %exitmacro
: Stop Expanding a Multi-Line Macro
If a %exitmacro
directive is encountered, NASM will immediately stop expanding the current multiline macro. This can, for example, be used to avoid unnecessarily deep %if
trees in the case of error conditions, such as:
%macro count_something 2 %if %1 < 0 %warning %?: negative count %exitmacro %endif ; ... do the thing, knowing that %1 >= 0 ... %endmacro
Compare with the %exitrep
directive,section 5.7.
5.6. Conditional Assembly
Similarly to the C preprocessor, NASM allows sections of a source file to be assembled only if certain conditions are met. The general syntax of this feature looks like this:
%if ; some code which only appears if is met %elif ; only appears if is not met but is %else ; this appears if neither nor was met %endif
The inverse forms %ifn
and %elifn
are also supported.
You can have multiple %elif
clauses, or none. The%else
clause is likewise optional.
There are a number of variants of the %if
directive. Each has its corresponding %elif
, %ifn
, and%elifn
directives; for example, the equivalents to the%ifdef
directive are %elifdef
,%ifndef
, and %elifndef
.
Futhermore, each variant of the %if
directive (including%ifn
forms) has a corresponding %is()
preprocessor function (see section 5.4.11.) These are particularly useful for testing multiple conditions at the same time. Unlike the C defined()
preprocessor construct, these functions are valid anywhere in the source code, not just in%if
expressions.
The following descriptions of tests all imply the existence of these alternate forms.
5.6.1. %if
: Testing Arbitrary Numeric Expressions
The conditional-assembly construct %if expr
will cause the subsequent code to be assembled if and only if the value of the numeric expression expr
is non-zero. An example of the use of this feature is in deciding when to break out of a %rep
preprocessor loop: see section 5.7 for a detailed example.
The expression given to %if
is a critical expression (seesection 3.8).
5.6.2. %ifdef
: Testing Single-Line Macro Existence
Beginning a conditional-assembly block with the line%ifdef MACRO
will assemble the subsequent code if, and only if, a single-line macro called MACRO
is defined.
For example, when debugging a program, you might want to write code such as
; perform some function
%ifdef DEBUG writefile 2,"Function performed successfully",13,10 %endif ; go and do something else
Then you could use the command-line option -dDEBUG
to create a version of the program which produced debugging messages, and remove the option to generate the final release version of the program.
From NASM 3.00 onward, %ifdef
can also test for the availability of a preprocessor function, for example:
%ifdef %newfunc db %newfunc(99) ; Generates something magic %else %warning "This version of NASM doesn't support %newfunc()" db -1 ; Feature not supported %endif
or, if the warning is not needed, using the function form:
db %cond(%isdef(%newfunc),%newfunc(99),-1)
It is strongly recommended to use this test instead of relying on NASM version numbers. To make it possible to test that this use of%ifdef
is valid, the macro__?NASM_HAS_IFDIRECTIVE?__
is defined on versions of NASM that support %ifdirective
, %ifusable
,%ifusing
and using %ifdef
to test for preprocessor functions. See section 6.8.
5.6.3. %ifdefalias
: Testing Single-Line Macro Alias Existence
The %ifdefalias
directive operates in the same was as the%ifdef
directive, except it tests for the definition of a single-line macro alias, as defined by %defalias
.
5.6.4. %ifmacro
: Testing Multi-Line Macro Existence
The %ifmacro
directive operates in the same way as the%ifdef
directive, except that it checks for the existence of a multi-line macro.
For example, you may be working with a large project and not have control over the macros in a library. You may want to create a macro with one name if it doesn't already exist, and another name if one with that name does exist.
The %ifmacro
is considered true if defining a macro with the given name and number of arguments would cause a definitions conflict. For example:
%ifmacro MyMacro 1-3
%error "MyMacro 1-3" causes a conflict with an existing macro.
%else
%macro MyMacro 1-3
; insert code to define the macro
%endmacro
%endif
This will create the macro "MyMacro 1-3" if no macro already exists which would conflict with it, and emits a warning if there would be a definition conflict.
5.6.5. %ifctx
: Testing the Context Stack
The conditional-assembly construct %ifctx
will cause the subsequent code to be assembled if and only if the top context on the preprocessor's context stack has the same name as one of the arguments.
For more details of the context stack, seesection 5.9. For a sample use of%ifctx
, see section 5.9.6.
5.6.6. %ifidn
and %ifidni
: Testing Exact Text Identity
The construct %ifidn text1,text2
will cause the subsequent code to be assembled if and only if text1
andtext2
, after expanding single-line macros, are identical pieces of text. Differences in white space are not counted.
%ifidni
is similar to %ifidn
, but is case-insensitive.
For example, the following macro pushes a register or number on the stack, and allows you to treat IP
as a real register:
%macro pushparam 1
%ifidni %1,ip call %%label %%label: %else push %1 %endif
%endmacro
5.6.7. %ifid
, %ifnum
, %ifstr
: Testing Token Types
Some macros will want to perform different tasks depending on whether they are passed a number, a string, or an identifier. For example, a string output macro might want to be able to cope with being passed either a string constant or a pointer to an existing string.
The conditional assembly construct %ifid
, taking one parameter (which may be blank), assembles the subsequent code if and only if the first token in the parameter exists and is an identifier.$
and $$
are not considered identifiers by %ifid
.
%ifnum
works similarly, but tests for the token being an integer numeric constant (not an expression!) possibly preceded by+
or -
; %ifstr
tests for it being a quoted string.
For example, the writefile
macro defined insection 5.5.3 can be extended to take advantage of %ifstr
in the following fashion:
%macro writefile 2-3+
%ifstr %2 jmp %%endstr %if %0 = 3 %%str: db %2,%3 %else %%str: db %2 %endif %%endstr: mov dx,%%str mov cx,%%endstr-%%str %else mov dx,%2 mov cx,%3 %endif mov bx,%1 mov ah,0x40 int 0x21
%endmacro
Then the writefile
macro can cope with being called in either of the following two ways:
writefile [file], strpointer, length
writefile [file], "hello", 13, 10
In the first, strpointer
is used as the address of an already-declared string, and length
is used as its length; in the second, a string is given to the macro, which therefore declares it itself and works out the address and length for itself.
Note the use of %if
inside the %ifstr
: this is to detect whether the macro was passed two arguments (so the string would be a single string constant, and db %2
would be adequate) or more (in which case, all but the first two would be lumped together into%3
, and db %2,%3
would be required).
5.6.8. %iftoken
: Test for a Single Token
Some macros will want to do different things depending on if it is passed a single token (e.g. paste it to something else using%+
) versus a multi-token sequence.
The conditional assembly construct %iftoken
assembles the subsequent code if and only if the expanded parameters consist of exactly one token, possibly surrounded by whitespace.
For example:
%iftoken 1
will assemble the subsequent code, but
%iftoken -1
will not, since -1
contains two tokens: the unary minus operator -
, and the number 1
.
5.6.9. %ifempty
: Test for Empty Expansion
The conditional assembly construct %ifempty
assembles the subsequent code if and only if the expanded parameters do not contain any tokens at all, whitespace excepted.
5.6.10. %ifdirective
: Test If a Directive Is Supported
The conditional assembly construct %ifdirective
assembles the subsequent code if and only if followed by a token that corresponds to a preprocessor directive, assembler directive (seechapter 8) or a pseudo-instruction (seesection 3.2) supported in the current version of NASM.
The argument can be a quoted string to prevent macro expansion, in which case it is unquoted before the test, that is, these two lines do the same thing:
%ifdirective %ifndef
%ifdirective "%ifndef"
Preprocessor directives must be specified with a leading %
sign (except for certain directives in TASM mode); assembler directives_may_ be specified with surrounding brackets []
, but those are not required.
Some assembly directives can be supported in some contexts and not others, for example, most output formats do not support theORG
directive, therefore the result of%ifdirective
may depend on more than just the current version of NASM.
%ifdirective
was introduced in NASM 3.00. It is strongly recommended to use this test instead of relying on NASM version numbers. To make it possible to probe for the existence of this test itself, the macro__?NASM_HAS_IFDIRECTIVE?__
is defined on versions of NASM that support %ifdirective
, %ifusable
,%ifusing
and using %ifdef
to test for preprocessor functions. See section 6.8.
5.6.11. %ifusable
and %ifusing
: Test For Standard Macro Packages
The conditional assembly construct %ifusable
assembles the subsequent code if and only if the following argument would be valid as the argument to %use
(see section 5.8.4), in other words, that a standard macro package with that name is available in the current version of NASM.
The conditional assembly construct %ifusing
assembles the subsequent code if and only if the following argument would be valid as the argument to %use
. It is more or less equivalent to the__?USE_
package?__
standard macros (seesection 6.9) but is potentially more robust.
%ifusing
and %ifusable
were introduced in NASM 3.00. It is strongly recommended to use this test instead of relying on NASM version numbers. To make it possible to probe for the existence of this test itself, the macro __?NASM_HAS_IFDIRECTIVE?__
is defined on versions of NASM that support %ifdirective
,%ifusable
, %ifusing
and using %ifdef
to test for preprocessor functions. Seesection 6.8.
5.6.12. %iffile
: Test If a File Exists
The conditional assembly construct %iffile
assembles the subsequent code if and only if a quoted string is specified which contains the name of a file that is available for NASM to read.
The include path is not searched; to search for the file using the include path, use the %pathsearch()
function in conjunction with this test, for example:
%define MYFILE "file.asm" %iffile %pathsearch(MYFILE) ; ... %endif
5.6.13. %ifenv
: Test If Environment Variable Exists
The conditional assembly construct %ifenv
assembles the subsequent code if and only if the environment variable referenced by the%!
variable directive exists.
Just as for %!
variable the argument should be written as a string if it contains characters that would not be legal in an identifier. See section 5.13.2.
5.6.14. Backwards Compatibility Caveat
Note that NASM before version 3.00 would not handle an unknown%if
–type directive for the purpose of%if
...%endif
balancing. Therefore, something like this would not work:
%ifdef ?NASM_HAS_IFDIRECTIVE? ; NASM 3.00 or later %ifdirective %iffile ; Test for directive %iffile MYFILE incbin MYFILE %endif %endif %endif
This can be worked around by using the %is()
series functions and plain %if
instead:
%ifdef ?NASM_HAS_IFDIRECTIVE? ; NASM 3.00 or later %if %isdef(%isfile) ; Test for function %if %isfile(MYFILE) incbin MYFILE %endif %endif %endif
NASM 3.00 and later treats an unknown preprocessor directive beginning with %if
or %elif
as if it were a known conditional directive for the purpose of%if
...%endif
balancing.
5.7. Preprocessor Loops: %rep
NASM's TIMES
prefix, though useful, cannot be used to invoke a multi-line macro multiple times, because it is processed by NASM after macros have already been expanded. Therefore NASM provides another form of loop, this time at the preprocessor level: %rep
.
The directives %rep
and %endrep
(%rep
takes a numeric argument, which can be an expression;%endrep
takes no arguments) can be used to enclose a chunk of code, which is then replicated as many times as specified by the preprocessor:
%assign i 0 %rep 64 inc word [table+2*i] %assign i i+1 %endrep
This will generate a sequence of 64 INC
instructions, incrementing every word of memory from [table]
to[table+126]
.
For more complex termination conditions, or to break out of a repeat loop part way along, you can use the %exitrep
directive to terminate the loop, like this:
fibonacci: %assign i 0 %assign j 1 %rep 100 %if j > 65535 %exitrep %endif dw j %assign k j+i %assign i j %assign j k %endrep
fib_number equ ($-fibonacci)/2
This produces a list of all the Fibonacci numbers that will fit in 16 bits. Note that a maximum repeat count must still be given to%rep
. This is to prevent the possibility of NASM getting into an infinite loop in the preprocessor, which (on multitasking or multi-user systems) would typically cause all the system memory to be gradually used up and other applications to start crashing.
Note the maximum repeat count is limited to the value specified by the--limit-rep
option or %pragma limit rep
, seesection 2.1.32.
5.8. Source Files and Dependencies
These commands allow you to split your sources into multiple files.
5.8.1. %include
: Including Other Files
Using, once again, a very similar syntax to the C preprocessor, NASM's preprocessor lets you include other source files into your code. This is done by the use of the %include
directive:
%include "macros.mac"
will include the contents of the file macros.mac
into the source file containing the %include
directive.
Include files are searched for in the current directory (the directory you're in when you run NASM, as opposed to the location of the NASM executable or the location of the source file), plus any directories specified on the NASM command line using the -i
option.
The standard C idiom for preventing a file being included more than once is just as applicable in NASM: if the file macros.mac
has the form
%ifndef MACROS_MAC %define MACROS_MAC ; now define some macros %endif
then including the file more than once will not cause errors, because the second time the file is included nothing will happen because the macroMACROS_MAC
will already be defined.
You can force a file to be included even if there is no%include
directive that explicitly includes it, by using the-p
option on the NASM command line (seesection 2.1.19).
5.8.2. %pathsearch
: Search the Include Path
The %pathsearch
directive takes a single-line macro name and a filename, and declare or redefines the specified single-line macro to be the include-path-resolved version of the filename, if the file exists (otherwise, it is passed unchanged.)
For example,
%pathsearch MyFoo "foo.bin"
... with -Ibins/
in the include path may end up defining the macro MyFoo
to be "bins/foo.bin"
.
See also the %pathsearch()
function (section 5.4.16).
5.8.3. %depend
: Add Dependent Files
The %depend
directive takes a filename and adds it to the list of files to be emitted as dependency generation when the-M
options and its relatives (seesection 2.1.5) are used. It produces no output.
This is generally used in conjunction with %pathsearch
. For example, a simplified version of the standard macro wrapper for theINCBIN
directive looks like:
%imacro incbin 1-2+ 0 %pathsearch dep %1 %depend dep incbin dep,%2 %endmacro
This first resolves the location of the file into the macrodep
, then adds it to the dependency lists, and finally issues the assembler-level INCBIN
directive.
See also the %depend()
function (section 5.4.6).
5.8.4. %use
: Include Standard Macro Package
The %use
directive is similar to %include
, but rather than including the contents of a file, it includes a named standard macro package. The standard macro packages are part of NASM, and are described in chapter 7.
Unlike the %include
directive, package names for the%use
directive do not require quotes, but quotes are permitted. In NASM 2.04 and 2.05 the unquoted form would be macro-expanded; this is no longer true. Thus, the following lines are equivalent:
%use altreg %use 'altreg'
Standard macro packages are protected from multiple inclusion. When a standard macro package is used, a testable single-line macro of the form__?USE_
package?__
is also defined, seesection 6.9.
The %ifusable
and %ifusing
directives can be used for the existence and inclusion of a specific standard macro package, see ifusing
.
5.9. The Context Stack
Having labels that are local to a macro definition is sometimes not quite powerful enough: sometimes you want to be able to share labels between several macro calls. An example might be a REPEAT
...UNTIL
loop, in which the expansion of the UNTIL
macro would need to be able to refer to a label which theREPEAT
macro had defined. However, for such a macro you would also want to be able to nest these loops.
NASM provides this level of power by means of a context stack. The preprocessor maintains a stack of contexts, each of which is characterized by a name. You add a new context to the stack using the%push
directive, and remove one using %pop
. You can define labels that are local to a particular context on the stack.
5.9.1. %push
and %pop
: Creating and Removing Contexts
The %push
directive is used to create a new context and place it on the top of the context stack. %push
takes an optional argument, which is the name of the context. For example:
%push foobar
This pushes a new context called foobar
on the stack. You can have several contexts on the stack with the same name: they can still be distinguished. If no name is given, the context is unnamed (this is normally used when both the %push
and the %pop
are inside a single macro definition).
The directive %pop
, taking one optional argument, removes the top context from the context stack and destroys it, along with any labels associated with it. If an argument is given, it must match the name of the current context, otherwise it will issue an error.
5.9.2. Context-Local Labels
Just as the usage %%foo
defines a label which is local to the particular macro call in which it is used, the usage %$foo
is used to define a label which is local to the context on the top of the context stack. So the REPEAT
and UNTIL
example given above could be implemented by means of:
%macro repeat 0
%push repeat
%$begin:
%endmacro
%macro until 1
j%-1 %$begin
%pop
%endmacro
and invoked by means of, for example,
mov di,string
repeat
add di,3
scasb
until e
which would scan every fourth byte of a string in search of the byte inAL
.
If you need to define, or access, labels local to the context_below_ the top one on the stack, you can use %$$foo
, or %$$$foo
for the context below that, and so on.
5.9.3. Context-Local Single-Line Macros
NASM also allows you to define single-line macros which are local to a particular context, in just the same way:
%define %$localmac 3
will define the single-line macro %$localmac
to be local to the top context on the stack. Of course, after a subsequent%push
, it can then still be accessed by the name%$$localmac
.
5.9.4. Context Fall-Through Lookup (deprecated)
Context fall-through lookup (automatic searching of outer contexts) is a feature that was added in NASM version 0.98.03. Unfortunately, this feature is unintuitive and can result in buggy code that would have otherwise been prevented by NASM's error reporting. As a result, this feature has been_deprecated_. NASM version 2.09 will issue a warning when usage of this deprecated feature is detected. Starting with NASM version 2.10, usage of this deprecated feature will simply result in an_expression syntax error_.
An example usage of this deprecated feature follows:
%macro ctxthru 0 %push ctx1 %assign %$external 1 %push ctx2 %assign %$internal 1 mov eax, %$external mov eax, %$internal %pop %pop %endmacro
As demonstrated, %$external
is being defined in thectx1
context and referenced within the ctx2
context. With context fall-through lookup, referencing an undefined context-local macro like this implicitly searches through all outer contexts until a match is made or isn't found in any context. As a result,%$external
referenced within the ctx2
context would implicitly use %$external
as defined inctx1
. Most people would expect NASM to issue an error in this situation because %$external
was never defined withinctx2
and also isn't qualified with the proper context depth,%$$external
.
Here is a revision of the above example with proper context depth:
%macro ctxthru 0 %push ctx1 %assign %$external 1 %push ctx2 %assign %$internal 1 mov eax, %$$external mov eax, %$internal %pop %pop %endmacro
As demonstrated, %$external
is still being defined in thectx1
context and referenced within the ctx2
context. However, the reference to %$external
withinctx2
has been fully qualified with the proper context depth,%$$external
, and thus is no longer ambiguous, unintuitive or erroneous.
5.9.5. %repl
: Renaming a Context
If you need to change the name of the top context on the stack (in order, for example, to have it respond differently to %ifctx
), you can execute a %pop
followed by a %push
; but this will have the side effect of destroying all context-local labels and macros associated with the context that was just popped.
NASM provides the directive %repl
, which _replaces_a context with a different name, without touching the associated macros and labels. So you could replace the destructive code
%pop %push newname
with the non-destructive version %repl newname
.
5.9.6. Example Use of the Context Stack: Block IFs
This example makes use of almost all the context-stack features, including the conditional-assembly construct %ifctx
, to implement a block IF statement as a set of macros.
%macro if 1
%push if
j%-1 %$ifnot
%endmacro
%macro else 0
%ifctx if
%repl else
jmp %$ifend
%$ifnot:
%else
%error "expected if' before
else'"
%endif
%endmacro
%macro endif 0
%ifctx if
%$ifnot:
%pop
%elifctx else
%$ifend:
%pop
%else
%error "expected if' or
else' before `endif'"
%endif
%endmacro
This code is more robust than the REPEAT
andUNTIL
macros given in section 5.9.2, because it uses conditional assembly to check that the macros are issued in the right order (for example, not calling endif
before if
) and issues an %error
if they're not.
In addition, the endif
macro has to be able to cope with the two distinct cases of either directly following an if
, or following an else
. It achieves this, again, by using conditional assembly to do different things depending on whether the context on top of the stack is if
or else
.
The else
macro has to preserve the context on the stack, in order to have the %$ifnot
referred to by the if
macro be the same as the one defined by the endif
macro, but has to change the context's name so that endif
will know there was an intervening else
. It does this by the use of%repl
.
A sample usage of these macros might look like:
cmp ax,bx
if ae
cmp bx,cx
if ae
mov ax,cx
else
mov ax,bx
endif
else
cmp ax,cx
if ae
mov ax,cx
endif
endif
The block-IF
macros handle nesting quite happily, by means of pushing another context, describing the inner if
, on top of the one describing the outer if
; thus else
andendif
always refer to the last unmatched if
orelse
.
5.10. Stack Relative Preprocessor Directives
The following preprocessor directives provide a way to use labels to refer to local variables allocated on the stack.
%arg
(see section 5.10.1)%stacksize
(see section 5.10.2)%local
(see section 5.10.3)
5.10.1. %arg
Directive
The %arg
directive is used to simplify the handling of parameters passed on the stack. Stack based parameter passing is used by many high level languages, including C, C++ and Pascal.
While NASM has macros which attempt to duplicate this functionality (seesection 10.4.5), the syntax is not particularly convenient to use and is not TASM compatible. Here is an example which shows the use of %arg
without any external macros:
some_function:
%push mycontext ; save the current context
%stacksize large ; tell NASM to use bp
%arg i:word, j_ptr:word
mov ax,[i]
mov bx,[j_ptr]
add ax,[bx]
ret
%pop ; restore original context
This is similar to the procedure defined insection 10.4.5 and adds the value in i to the value pointed to by j_ptr and returns the sum in the ax register. See section 5.9.1 for an explanation of push
and pop
and the use of context stacks.
5.10.2. %stacksize
Directive
The %stacksize
directive is used in conjunction with the%arg
(see section 5.10.1) and the %local
(see section 5.10.3) directives. It tells NASM the default size to use for subsequent%arg
and %local
directives. The%stacksize
directive takes one required argument which is one of flat
, flat64
, large
orsmall
.
%stacksize flat
This form causes NASM to use stack-based parameter addressing relative to ebp
and it assumes that a near form of call was used to get to this label (i.e. that eip
is on the stack).
%stacksize flat64
This form causes NASM to use stack-based parameter addressing relative to rbp
and it assumes that a near form of call was used to get to this label (i.e. that rip
is on the stack).
%stacksize large
This form uses bp
to do stack-based parameter addressing and assumes that a far form of call was used to get to this address (i.e. that ip
and cs
are on the stack).
%stacksize small
This form also uses bp
to address stack parameters, but it is different from large
because it also assumes that the old value of bp is pushed onto the stack (i.e. it expects an ENTER
instruction). In other words, it expects that bp
,ip
and cs
are on the top of the stack, underneath any local space which may have been allocated by ENTER
. This form is probably most useful when used in combination with the%local
directive (see section 5.10.3).
5.10.3. %local
Directive
The %local
directive is used to simplify the use of local temporary stack variables allocated in a stack frame. Automatic local variables in C are an example of this kind of variable. The%local
directive is most useful when used with the%stacksize
(see section 5.10.2and is also compatible with the %arg
directive (seesection 5.10.1). It allows simplified reference to variables on the stack which have been allocated typically by using the ENTER
instruction. An example of its use is the following:
silly_swap:
%push mycontext ; save the current context
%stacksize small ; tell NASM to use bp
%assign %$localsize 0 ; see text for explanation
%local old_ax:word, old_dx:word
enter %$localsize,0 ; see text for explanation
mov [old_ax],ax ; swap ax & bx
mov [old_dx],dx ; and swap dx & cx
mov ax,bx
mov dx,cx
mov bx,[old_ax]
mov cx,[old_dx]
leave ; restore old bp
ret ;
%pop ; restore original context
The %$localsize
variable is used internally by the%local
directive and must be defined within the current context before the %local
directive may be used. Failure to do so will result in one expression syntax error for each%local
variable declared. It then may be used in the construction of an appropriately sized ENTER
instruction as shown in the example.
5.11. Reporting User-generated Diagnostics: %error
, %warning
, %fatal
, %note
The preprocessor directive %error
will cause NASM to report an error if it occurs in assembled code. So if other users are going to try to assemble your source files, you can ensure that they define the right macros by means of code like this:
%ifdef F1 ; do some setup %elifdef F2 ; do some different setup %else %error "Neither F1 nor F2 was defined." %endif
Then any user who fails to understand the way your code is supposed to be assembled will be quickly warned of their mistake, rather than having to wait until the program crashes on being run and then not knowing what went wrong.
Similarly, %warning
issues a warning, but allows assembly to continue:
%ifdef F1 ; do some setup %elifdef F2 ; do some different setup %else %warning "Neither F1 nor F2 was defined, assuming F1." %define F1 %endif
User-defined error messages can be suppressed with the-w-user
option, and promoted to errors with-w+error=user
.
%error
and %warning
are issued only on the final assembly pass. This makes them safe to use in conjunction with tests that depend on symbol values.
%fatal
terminates assembly immediately, regardless of pass. This is useful when there is no point in continuing the assembly further, and doing so is likely just going to cause a spew of confusing error messages.
%note
adds an output line to the list file; it does not output anything on the console or error file.
It is optional for the message string after %error
,%warning
, %fatal
, or %note
to be quoted. If it is not, then single-line macros are expanded in it, which can be used to display more information to the user. For example:
%if foo > 64 %assign foo_over foo-64 %error foo is foo_over bytes too large %endif
5.12. %pragma
: Setting Options
The %pragma
directive controls a number of options in NASM. Pragmas are intended to remain backwards compatible, and therefore an unknown %pragma
directive is not an error.
The various pragmas are documented with the options they affect.
The general structure of a NASM pragma is:
%pragma
namespace _directive_[_arguments..._]
Currently defined namespaces are:
ignore
: this%pragma
is unconditionally ignored.preproc
: preprocessor, seesection 5.12.1.limit
: resource limits, seesection 2.1.32.asm
: the parser and assembler proper. Currently no such pragmas are defined.list
: listing options, seesection 2.1.4.file
: general file handling options. Currently no such pragmas are defined.input
: input file handling options. Currently no such pragmas are defined.output
: output format options.debug
: debug format options.
In addition, the name of any output or debug format, and sometimes groups thereof, also constitute %pragma
namespaces. The namespaces output
and debug
simply refer to_any_ output or debug format, respectively.
For example, to prepend an underscore to global symbols regardless of the output format (see section 8.10):
%pragma output gprefix _
... whereas to prepend an underscore to global symbols only when the output is either win32
or win64
:
%pragma win gprefix _
5.12.1. Preprocessor Pragmas
The only preprocessor %pragma
defined as the current version of NASM is:
%pragma preproc sane_empty_expansion
: disables legacy compatibility handling of braceless empty arguments to multi-line macros. See section 5.5 andsection 2.1.26.
5.13. Other Preprocessor Directives
5.13.1. %line
Directive
The %line
directive is used to notify NASM that the input line corresponds to a specific line number in another file. Typically this other file would be an original source file, with the current NASM input being the output of a pre-processor. The %line
directive allows NASM to output messages which indicate the line number of the original source file, instead of the file that is being read by NASM.
This preprocessor directive is not generally used directly by programmers, but may be of interest to preprocessor authors. The usage of the %line
preprocessor directive is as follows:
%line nnn[+mmm] [filename]
In this directive, nnn
identifies the line of the original source file which this line corresponds to. mmm
is an optional parameter which specifies a line increment value; each line of the input file read in is considered to correspond to mmm
lines of the original source file. Finally, filename
is an optional parameter which specifies the file name of the original source file. It may be a quoted string, in which case any additional argument after the quoted string will be ignored.
After reading a %line
preprocessor directive, NASM will report all file name and line numbers relative to the values specified therein.
If the command line option --no-line
is given, all%line
directives are ignored. This may be useful for debugging preprocessed code. See section 2.1.34.
Starting in NASM 2.15, %line
directives are processed before any other processing takes place.
For compatibility with the output from some other preprocessors, including many C preprocessors, a #
character followed by whitespace at the very beginning of a line is also treated as a%line
directive, except that double quotes surrounding the filename are treated like NASM backquotes, with\
–escaped sequences decoded.
5.13.2. %!
variable: Read an Environment Variable.
The %!
variable directive makes it possible to read the value of an environment variable at assembly time. This could, for example, be used to store the contents of an environment variable into a string, which could be used at some other point in your code.
For example, suppose that you have an environment variableFOO
, and you want the contents of FOO
to be embedded in your program as a quoted string. You could do that as follows:
%defstr FOO %!FOO
See section 5.2.9 for notes on the%defstr
directive.
If the name of the environment variable contains non-identifier characters, you can use string quotes to surround the name of the variable, for example:
%defstr C_colon %!'C:'
5.13.3. %clear
: Clear All Macro Definitions
The directive %clear
clears all definitions of a certain type, including the ones defined by NASM itself. This can be useful when preprocessing non-NASM code, or to drop backwards compatibility aliases.
The syntax is:
%clear [global|context] type...
... where context
indicates that this applies to context-local macros only; the default is global
.
type
can be one or more of:
define
single-line macrosdefalias
single-line macro aliases (useful to remove backwards compatibility aliases)alldefine
same asdefine defalias
macro
multi-line macrosall
same asalldefine macro
(default)
In NASM 2.14 and earlier, only the single syntax %clear
was supported, which is equivalent to %clear global all
.