// $Id: nasm-preprocessor.txt 2217 2009-07-24 17:47:49Z peter $
[[nasm-preprocessor]]
== The NASM Preprocessor

////
 <chapterinfo>
  <authorgroup>
   <corpauthor>The NASM Development Team</corpauthor>

   <author>
    <firstname>Peter</firstname>
    <surname>Johnson</surname>
    <contrib>Updated for Yasm context by </contrib>
   </author>
  </authorgroup>
 </chapterinfo>
////

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.

The preprocessor collapses all lines which end with a backslash (\)
character into a single line.  Thus:

[source]
----
%define THIS_VERY_LONG_MACRO_NAME_IS_DEFINED_TO \
          THIS_VALUE
----

will work like a single-line macro without the backslash-newline
sequence.

[[nasm-single-line-macros]]
=== Single-Line Macros

[[nasm-macro-define]]
==== 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

[source]
----
%define ctrl    0x1F &
%define param(a,b) ((a)+(a)*(b))

        mov     byte [param(2,ebx)], ctrl 'D'
----

which will expand to

[source]
----
        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

[source]
----
%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 of `a`.

Macros defined with `%define` are ((case sensitive)): after `%define
foo bar`, only `foo` will expand to `bar`: `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

[source]
----
%define a(x)    1+a(x)

        mov     ax,a(3)
----

the macro `a(3)` will expand once, becoming `1+a(3)`, and will then
expand no further. This behaviour can be useful.

indexterm:[overloading,single-line macros]
You can overload single-line macros: if you write

[source]
----
%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 become `1+3`
whereas `foo(ebx,2)` will become `1+ebx*2`. However, if you define

[source]
----
%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

[source]
----
%define foo bar
----

and then re-define it later in the same source file with

[source]
----
%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` (see
<<nasm-macro-assign>>).

You can ((pre-define)) single-line macros using the ""-D"" option on
the Yasm command line: see <<yasm-option-d>>.

[[nasm-macro-xdefine]]
==== Enhancing %define: `%xdefine`

indexterm:[case sensitive]
To have a reference to an embedded single-line macro resolved at the
time that it is embedded, as opposed to when the calling macro is
expanded, you need a different mechanism to the one offered by
`%define`. The solution is to use ((`%xdefine`)), or its
case-insensitive counterpart ((`%xidefine`)).

Suppose you have the following code:

[source]
----
%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. As `isFalse` 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 that `isFalse` was defined, you
need to change the above code to use `%xdefine`.

[source]
----
%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.

[[nasm-macro-single-concat]]
==== Concatenating Single Line Macro Tokens: `%+`

indexterm:[`%+`]
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.

As an example, consider the following:

[source]
----
%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:

[source]
----
        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:

[source]
----
; Macro to access BIOS variables by their names (from tBDA):

%define BDA(x)  BDASTART + tBIOSDA. %+ x
----

Now the above code can be written as:

[source]
----
        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).

[[nasm-macro-undef]]
==== Undefining macros: `%undef`

Single-line macros can be removed with the ((`%undef`)) command.  For
example, the following sequence:

[source]
----
%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 Yasm command line: see
<<yasm-option-u>>.

[[nasm-macro-assign]]
==== Preprocessor Variables: `%assign`

indexterm:[Preprocessor Variables]
indexterm:[case sensitive]
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

[source]
----
%assign i i+1
----

to increment the numeric value of a macro.

`%assign` is useful for controlling the termination of `%rep`
preprocessor loops: see <<nasm-macro-rep>> for an example of this.

The expression passed to `%assign` is a ((critical expression)) (see
<<nasm-crit>>), 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).

[[nasm-strlen]]
=== String Handling in Macros

indexterm:[String Handling in Macros]
It's often useful to be able to handle strings in macros.  NASM
supports two simple string handling macro operators from which more
complex operations can be constructed.

[[nasm-macro-strlen]]
==== String Length: `%strlen`

indexterm:[String Length]
The ((`%strlen`)) macro is like `%assign` macro in that it creates (or
redefines) a numeric value to a macro. The difference is that with
`%strlen`, the numeric value is the length of a string. An example of
the use of this would be:

[source]
----
%strlen charcnt 'my string'
----

In this example, `charcnt` would receive the value 8, 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:

[source]
----
%define sometext 'my string'
%strlen charcnt sometext
----

As in the first case, this would result in `charcnt` being assigned
the value of 8.

[[nasm-macro-substr]]
==== Sub-strings: `%substr`

indexterm:[Sub-strings]
Individual letters in strings can be extracted using ((`%substr`)).
An example of its use is probably more useful than the description:

[source]
----
%substr mychar  'xyz' 1         ; equivalent to %define mychar 'x'
%substr mychar  'xyz' 2         ; equivalent to %define mychar 'y'
%substr mychar  'xyz' 3         ; equivalent to %define mychar 'z'
----

In this example, mychar gets the value of `'y'`. As with `%strlen`
(see <<nasm-macro-strlen>>), the first parameter is the single-line
macro to be created and the second is the string. The third parameter
specifies which character is to be selected. 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.

[[nasm-multi-line-macros]]
=== Multi-Line Macros

indexterm:[Multi-Line Macros]
indexterm:[`%imacro`]
indexterm:[`%macro`]
Multi-line macros are much more like the type of macro seen in MASM
and TASM: a multi-line macro definition in NASM looks something like
this.

[source]
----
%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

[source]
----
myfunc:   prologue 12
----

which would expand to the three lines of code

[source]
----
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 macro `prologue` 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`.

indexterm:[braces,around macro parameters]
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

[source]
----
%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
----

[[nasm-macro-overloading]]
==== Overloading Multi-Line Macros

indexterm:[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

[source]
----
%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

[source]
----
%macro  push 2

        push    %1
        push    %2

%endmacro
----

so that you could code

[source]
----
        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
%-wno-macro-params% command-line option (see
<<yasm-warning-options>>).

[[nasm-macro-local]]
==== Macro-Local Labels

indexterm:[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:

[source]
----
%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 in <<nasm-local-label>>. 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.

[[nasm-macro-greedy]]
==== Greedy Macro Parameters

indexterm:[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

[source]
----
        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:

[source]
----
%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`.

indexterm:[+ modifier]
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 of
`writefile` 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

[source]
----
        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 <<nasm-directive-section-macro>> for a better way to write the
above macro.

[[nasm-macro-default]]
==== Default Macro Parameters

indexterm:[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:

[source]
----
%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
<<nasm-macro-greedy>>) 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

[source]
----
%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 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 <<nasm-macro-percent0>>) 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

[source]
----
%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 in
<<nasm-macro-rotate>>.

[[nasm-macro-percent0]]
==== `%0`: Macro Parameter Counter

indexterm:[counting macro parameters]
For a macro which can take a variable number of parameters, the
parameter reference ((`%0`)) will return a numeric constant giving the
number of parameters passed to the macro. This can be used as an
argument to `%rep` (see <<nasm-macro-rep>>) in order to iterate
through all the parameters of a macro.  Examples are given in
<<nasm-macro-rotate>>.

[[nasm-macro-rotate]]
==== `%rotate`: Rotating Macro Parameters

indexterm:[Rotating Macro Parameters]
indexterm:[shift command]
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.

indexterm:[iterating over macro parameters]
So a pair of macros to save and restore a set of registers might work
as follows:

[source]
----
%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 a `POP`
equivalent, which _didn't_ require the arguments to be given in
reverse order. Ideally, you would write the `multipush` macro call,
then cut-and-paste the line to where the pop needed to be done, and
change the name of the called macro to `multipop`, 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:

[source]
----
%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.

[[nasm-macro-concat]]
==== Concatenating Macro Parameters

indexterm:[Concatenating Macro Parameters]
NASM can concatenate macro parameters on to other text surrounding
them. 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

[source]
----
%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

[source]
----
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`.

indexterm:[braces,after % sign]
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 (<<nasm-macro-local>>) and
context-local labels (<<nasm-macro-context-local>>). 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 text `bar` 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.)

[[nasm-macro-cc]]
==== Condition Codes as Macro Parameters

indexterm:[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 in <<nasm-macro-local>> can be
replaced by a general ((conditional-return macro)) like this:

[source]
----
%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.

[[nasm-macro-nolist]]
==== Disabling Listing Expansion

indexterm:[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:

[source]
----
%macro foo 1.nolist
----

Or like this:

[source]
----
%macro bar 1-5+.nolist a,b,c,d,e,f,g,h
----

[[nasm-macro-conditional]]
=== Conditional Assembly

indexterm:[Conditional Assembly]
indexterm:[`%if`]
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:

[source]
----
%if<condition>
    ; some code which only appears if <condition> is met
%elif<condition2>
    ; only appears if <condition> is not met but <condition2> is
%else
    ; this appears if neither <condition> nor <condition2> was met
%endif
----

The ((`%else`)) clause is optional, as is the ((`%elif`)) clause.  You
can have more than one `%elif` clause as well.

[[nasm-macro-ifdef]]
==== `%ifdef`: Testing Single-Line Macro Existence

indexterm:[`%ifdef`]
indexterm:[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.  If not, then the `%elif` and `%else`
blocks (if any) will be processed instead.

For example, when debugging a program, you might want to write code
such as

[source]
----
          ; 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 `-D DEBUG` to create a
version of the program which produced debugging messages, and remove
the option to generate the final release version of the program.

You can test for a macro _not_ being defined by using ((`%ifndef`))
instead of `%ifdef`. You can also test for macro definitions in
`%elif` blocks by using ((`%elifdef`)) and ((`%elifndef`)).

[[nasm-macro-ifmacro]]
==== `%ifmacro`: Testing Multi-Line Macro Existence

indexterm:[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:

[source]
----
%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.

You can test for the macro not existing by using the ((`%ifnmacro`))
instead of `%ifmacro`. Additional tests can be performed in `%elif`
blocks by using ((`%elifmacro`)) and ((`%elifnmacro`)).

[[nasm-macro-ifctx]]
==== `%ifctx`: Testing the Context Stack

indexterm:[`%ifctx`]
indexterm:[testing,context stack]
The conditional-assembly construct `%ifctx ctxname` will cause the
subsequent code to be assembled if and only if the top context on the
preprocessor's context stack has the name `ctxname`. As with `%ifdef`,
the inverse and `%elif` forms ((`%ifnctx`)), ((`%elifctx`)) and
((`%elifnctx`)) are also supported.

For more details of the context stack, see
<<nasm-macro-context-stack>>. For a sample use of `%ifctx`, see
<<nasm-macro-block-if>>.

[[nasm-macro-if]]
==== `%if`: Testing Arbitrary Numeric Expressions

indexterm:[`%if`]
indexterm:[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 <<nasm-macro-rep>> for a detailed example.

The expression given to `%if`, and its counterpart ((`%elif`)), is a
critical expression (see <<nasm-crit>>).

`%if` extends the normal NASM expression syntax, by providing a set of
((relational operators)) which are not normally available in
expressions. The operators ((`=`)), ((`<`)), ((`>`)), ((`<=`)),
((`>=`)) and ((`<>`)) test equality, less-than, greater-than,
less-or-equal, greater-or-equal and not-equal respectively. The C-like
forms ((`==`)) and ((`!=`)) are supported as alternative forms of `=`
and `<>`. In addition, low-priority logical operators ((`&&`)),
((`^^`)) and ((`||`)) are provided, supplying ((logical AND)),
((logical XOR)) and ((logical OR)). These work like the C logical
operators (although C has no logical XOR), in that they always return
either 0 or 1, and treat any non-zero input as 1 (so that `^^`, for
example, returns 1 if exactly one of its inputs is zero, and 0
otherwise).  The relational operators also return 1 for true and 0 for
false.

[[nasm-macro-ifidn]]
==== `%ifidn` and `%ifidni`: Testing Exact Text Identity

indexterm:[`%ifidn`]
indexterm:[testing,exact text identity]
The construct `%ifidn text1,text2` will cause the subsequent code to
be assembled if and only if `text1` and `text2`, after expanding
single-line macros, are identical pieces of text.  Differences in
white space are not counted.

indexterm:[case-insensitive]
((`%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:

[source]
----
%macro  pushparam 1

  %ifidni %1,ip
        call    %%label
  %%label:
  %else
        push    %1
  %endif

%endmacro
----

Like most other `%if` constructs, `%ifidn` has a counterpart
((`%elifidn`)), and negative forms ((`%ifnidn`)) and ((`%elifnidn`)).
Similarly, `%ifidni` has counterparts ((`%elifidni`)), ((`%ifnidni`))
and ((`%elifnidni`)).

[[nasm-macro-iftyp]]
==== `%ifid`, `%ifnum`, `%ifstr`: Testing Token Types

indexterm:[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.
((`%ifnum`)) works similarly, but tests for the token being a numeric
constant; ((`%ifstr`)) tests for it being a string.

For example, the `writefile` macro defined in <<nasm-macro-greedy>>
can be extended to take advantage of `%ifstr` in the following
fashion:

[source]
----
%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:

[source]
----
        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).

indexterm:[`%ifnid`]
indexterm:[`%elifid`]
indexterm:[`%elifnid`]
indexterm:[`%ifnnum`]
indexterm:[`%elifnum`]
indexterm:[`%elifnnum`]
indexterm:[`%ifnstr`]
indexterm:[`%elifstr`]
indexterm:[`%elifnstr`]
The usual `%elifXXX`, `%ifnXXX` and `%elifnXXX` versions exist for
each of `%ifid`, `%ifnum` and `%ifstr`.

[[nasm-macro-error]]
==== `%error`: Reporting User-Defined Errors

indexterm:[User-Defined Errors]
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:

[source]
----
%ifdef SOME_MACRO
    ; do some setup
%elifdef SOME_OTHER_MACRO
    ; do some different setup
%else
    %error Neither SOME_MACRO nor SOME_OTHER_MACRO 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.

[[nasm-macro-rep]]
=== Preprocessor Loops

indexterm:[Preprocessor Loops]
indexterm:[repeating code]
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:

[source]
----
%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:

[source]
----
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.

[[nasm-include]]
=== Including Other Files

indexterm:[Including Other Files]
Using, once again, a very similar syntax to the C preprocessor, the
NASM preprocessor lets you include other source files into your code.
This is done by the use of the ((`%include`)) directive:

[source]
----
%include "macros.mac"
----

will include the contents of the file `macros.mac` into the source
file containing the `%include` directive.

indexterm:[searching for include files]
Include files are first searched for relative to the directory
containing the source file that is performing the inclusion, and then
relative to any directories specified on the Yasm command line using
the `-I` option (see <<yasm-option-i>>), in the order given on the
command line (any relative paths on the Yasm command line are relative
to the current working directory, e.g. where Yasm is being run from).
While this search strategy does not match traditional NASM behavior,
it does match the behavior of most C compilers and better handles
relative pathnames.

The standard C idiom for preventing a file being included more than
once is just as applicable in the NASM preprocessor: if the file
`macros.mac` has the form

[source]
----
%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
macro `MACROS_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 Yasm command line (see <<yasm-option-p>>).

[[nasm-macro-context-stack]]
=== The Context Stack

indexterm:[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 `REPEAT` macro would need
to be able to refer to a label which the `UNTIL` macro had defined.
However, for such a macro you would also want to be able to nest these
loops.

The NASM preprocessor provides this level of power by means of a
_context stack_.  The preprocessor maintains a stack of _contexts_,
each of which is characterised 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.

[[nasm-macro-pushpop]]
==== `%push` and `%pop`: Creating and Removing Contexts

indexterm:[creating contexts]
The ((`%push`)) directive is used to create a new context and place it
on the top of the context stack.  `%push` requires one argument, which
is the name of the context. For example:

[source]
----
%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.

indexterm:[removing contexts]
The directive ((`%pop`)), requiring no arguments, removes the top
context from the context stack and destroys it, along with any labels
associated with it.

[[nasm-macro-context-local]]
==== Context-Local Labels

indexterm:[Context-Local Labels]

indexterm:[`%$`]
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:

[source]
----
%macro repeat 0

    %push   repeat
    %$begin:

%endmacro

%macro until 1

        j%-1    %$begin
    %pop

%endmacro
----

and invoked by means of, for example,

[source]
----
        mov     cx,string
        repeat
        add     cx,3
        scasb
        until   e
----

which would scan every fourth byte of a string in search of the byte
in `AL`.

indexterm:[+++<literal>%$$</literal>+++]
If you need to define, or access, labels local to the context _below_
the top one on the stack, you can use +++<literal>%$$foo</literal>+++,
or +++<literal>%$$$foo</literal>+++ for the context below that, and so
on.

[[nasm-macro-context-define]]
==== Context-Local Single-Line Macros

indexterm:[Context-Local Single-Line Macros]
The NASM preprocessor also allows you to define single-line macros
which are local to a particular context, in just the same way:

[source]
----
%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`.

[[nasm-macro-repl]]
==== `%repl`: Renaming a Context

indexterm:[renaming contexts]
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.

The NASM preprocessor 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

[source]
----
%pop
%push   newname
----

with the non-destructive version `%repl newname`.

[[nasm-macro-block-if]]
==== Example Use of the Context Stack: Block IFs

indexterm:[Context Stack]
indexterm:[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.

[source]
----
%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` and `UNTIL` macros given in
<<nasm-macro-context-local>>, 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 a `%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:

[source]
----
        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` and `endif` always refer to the
last unmatched `if` or `else`.

[[nasm-stdmac]]
=== Standard Macros

indexterm:[Standard Macros]
Yasm defines a set of standard macros in the NASM preprocessor which
are already defined when it starts to process any source file. If you
really need a program to be assembled with no pre-defined macros, you
can use the ((`%clear`)) directive to empty the preprocessor of
everything.

indexterm:[user-level assembler directives]
Most user-level NASM syntax directives (see <<nasm-directives>>) are
implemented as macros which invoke primitive directives; these are
described in <<nasm-directives>>.  The rest of the standard macro set
is described here.

[[nasm-stdmac-version]]
==== `__YASM_MAJOR__`, etc: Yasm Version

indexterm:[Yasm Version]
The single-line macros ((`__YASM_MAJOR__`)), ((`__YASM_MINOR__`)), and
((`__YASM_SUBMINOR__`)) expand to the major, minor, and subminor parts
of the ((version number of Yasm)) being used.  In addition,
((`__YASM_VER__`)) expands to a string representation of the Yasm
version and ((`__YASM_VERSION_ID__`)) expands to a 32-bit BCD-encoded
representation of the Yasm version, with the major version in the most
significant 8 bits, followed by the 8-bit minor version and 8-bit
subminor version, and 0 in the least significant 8 bits.  For example,
under Yasm 0.5.1, `__YASM_MAJOR__` would be defined to be 0,
`__YASM_MINOR__` would be defined as 5, `__YASM_SUBMINOR__` would be
defined as 1, `__YASM_VER__` would be defined as `"0.5.1"`, and
`__YASM_VERSION_ID__` would be defined as `000050100h`.

In addition, the single line macro ((`__YASM_BUILD__`)) expands to the
Yasm ""build"" number, typically the Subversion changeset number.  It
should be seen as less significant than the subminor version, and is
generally only useful in discriminating between Yasm nightly snapshots
or pre-release (e.g. release candidate) Yasm versions.

[[nasm-stdmac-fileline]]
==== `__FILE__` and `__LINE__`: File Name and Line Number

Like the C preprocessor, the NASM preprocessor allows the user to find
out the file name and line number containing the current instruction.
The macro ((`__FILE__`)) expands to a string constant giving the name
of the current input file (which may change through the course of
assembly if `%include` directives are used), and ((`__LINE__`))
expands to a numeric constant giving the current line number in the
input file.

These macros could be used, for example, to communicate debugging
information to a macro, since invoking `__LINE__` inside a macro
definition (either single-line or multi-line) will return the line
number of the macro _call_, rather than _definition_. So to determine
where in a piece of code a crash is occurring, for example, one could
write a routine `stillhere`, which is passed a line number in `EAX`
and outputs something like ""line 155: still here"". You could then
write a macro

[source]
----
%macro notdeadyet 0
        push    eax
        mov     eax, __LINE__
        call    stillhere
        pop     eax
%endmacro
----

and then pepper your code with calls to `notdeadyet` until you find
the crash point.

[[nasm-stdmac-output-format]]
==== `__YASM_OBJFMT__` and `__OUTPUT_FORMAT__`: Output Object Format Keyword

indexterm:[%-f%]
((`__YASM_OBJFMT__`)), and its NASM-compatible alias
((`__OUTPUT_FORMAT__`)), expand to the object format ?keyword?
specified on the command line with %-f ?keyword?% (see
<<yasm-option-oformat>>).  For example, if **yasm** is invoked with
%-f elf%, `__YASM_OBJFMT__` expands to `elf`.

These expansions match the option given on the command line exactly,
even when the object formats are equivalent.  For example, %-f elf%
and %-f elf32% are equivalent specifiers for the 32-bit ELF format,
and %-f elf -m amd64% and %-f elf64% are equivalent specifiers for the
64-bit ELF format, but `__YASM_OBJFMT__` would expand to `elf` and
`elf32` for the first two cases, and `elf` and `elf64` for the second
two cases.

[[nasm-stdmac-struc]]
==== `STRUC` and `ENDSTRUC`: Declaring Structure Data Types

indexterm:[Declaring Structure]
The NASM preprocessor is sufficiently powerful that data structures
can be implemented as a set of macros. The macros ((`STRUC`)) and
((`ENDSTRUC`)) are used to define a structure data type.

`STRUC` takes one parameter, which is the name of the data type. This
name is defined as a symbol with the value zero, and also has the
suffix `_size` appended to it and is then defined as an `EQU` giving
the size of the structure. Once `STRUC` has been issued, you are
defining the structure, and should define fields using the `RESB`
family of pseudo-instructions, and then invoke `ENDSTRUC` to finish
the definition.

For example, to define a structure called `mytype` containing a
longword, a word, a byte and a string of bytes, you might code

[source]
----
        struc   mytype
mt_long:        resd 1
mt_word:        resw 1
mt_byte:        resb 1
mt_str:         resb 32
        endstruc
----

The above code defines six symbols: `mt_long` as 0 (the offset from
the beginning of a `mytype` structure to the longword field),
`mt_word` as 4, `mt_byte` as 6, `mt_str` as 7, `mytype_size` as 39,
and `mytype` itself as zero.

The reason why the structure type name is defined at zero is a side
effect of allowing structures to work with the local label mechanism:
if your structure members tend to have the same names in more than one
structure, you can define the above structure like this:

[source]
----
        struc   mytype
.long:  resd 1
.word:  resw 1
.byte:  resb 1
.str:   resb 32
        endstruc
----

This defines the offsets to the structure fields as `mytype.long`,
`mytype.word`, `mytype.byte` and `mytype.str`.

Since NASM syntax has no _intrinsic_ structure support, does not
support any form of period notation to refer to the elements of a
structure once you have one (except the above local-label notation),
so code such as `mov ax,[mystruc.mt_word]` is not valid.  `mt_word` is
a constant just like any other constant, so the correct syntax is `mov
ax,[mystruc+mt_word]` or `mov ax,[mystruc+mytype.word]`.

[[nasm-stdmac-istruc]]
==== `ISTRUC`, `AT` and `IEND`: Declaring Instances of Structures

indexterm:[Instances of Structures]
indexterm:[`IEND`]
Having defined a structure type, the next thing you typically want to
do is to declare instances of that structure in your data segment. The
NASM preprocessor provides an easy way to do this in the ((`ISTRUC`))
mechanism. To declare a structure of type `mytype` in a program, you
code something like this:

[source]
----
mystruc:        istruc  mytype
        at mt_long, dd 123456
        at mt_word, dw 1024
        at mt_byte, db 'x'
        at mt_str,  db 'hello, world', 13, 10, 0
                iend
----

The function of the ((`AT`)) macro is to make use of the `TIMES`
prefix to advance the assembly position to the correct point for the
specified structure field, and then to declare the specified data.
Therefore the structure fields must be declared in the same order as
they were specified in the structure definition.

If the data to go in a structure field requires more than one source
line to specify, the remaining source lines can easily come after the
`AT` line. For example:

[source]
----
        at mt_str, db 123,134,145,156,167,178,189
        db 190,100,0
----

Depending on personal taste, you can also omit the code part of the
`AT` line completely, and start the structure field on the next line:

[source]
----
        at mt_str
        db 'hello, world'
        db 13,10,0
----

[[nasm-stdmac-align]]
==== `ALIGN` and `ALIGNB`: Data Alignment

The ((`ALIGN`)) and ((`ALIGNB`)) macros provide a convenient way to
align code or data on a word, longword, paragraph or other boundary.
The syntax of the `ALIGN` and `ALIGNB` macros is

[source]
----
        align 4                 ; align on 4-byte boundary
        align 16                ; align on 16-byte boundary
        align 16,nop            ; equivalent to previous line
        align 8,db 0            ; pad with 0s rather than NOPs
        align 4,resb 1          ; align to 4 in the BSS
        alignb 4                ; equivalent to previous line
----

Both macros require their first argument to be a power of two; they
both compute the number of additional bytes required to bring the
length of the current section up to a multiple of that power of two,
and output either NOP fill or apply the `TIMES` prefix to their second
argument to perform the alignment.

If the second argument is not specified, the default for `ALIGN` is
`NOP`, and the default for `ALIGNB` is `RESB 1`.  `ALIGN` treats a
`NOP` argument specially by generating maximal NOP fill instructions
(not necessarily NOP opcodes) for the current `BITS` setting, whereas
`ALIGNB` takes its second argument literally.  Otherwise, the two
macros are equivalent when a second argument is specified.  Normally,
you can just use `ALIGN` in code and data sections and `ALIGNB` in BSS
sections, and never need the second argument except for special
purposes.

`ALIGN` and `ALIGNB`, being simple macros, perform no error checking:
they cannot warn you if their first argument fails to be a power of
two, or if their second argument generates more than one byte of code.
In each of these cases they will silently do the wrong thing.

`ALIGNB` (or `ALIGN` with a second argument of `RESB 1`) can be used
within structure definitions:

[source]
----
        struc   mytype2
mt_byte:        resb 1
                alignb 2
mt_word:        resw 1
                alignb 4
mt_long:        resd 1
mt_str:         resb 32
        endstruc
----

This will ensure that the structure members are sensibly aligned
relative to the base of the structure.

A final caveat: `ALIGNB` works relative to the beginning of the
_section_, not the beginning of the address space in the final
executable. Aligning to a 16-byte boundary when the section you're in
is only guaranteed to be aligned to a 4-byte boundary, for example, is
a waste of effort. Again, Yasm does not check that the section's
alignment characteristics are sensible for the use of `ALIGNB`.
`ALIGN` is more intelligent and _does_ adjust the section alignment to
be the maximum specified alignment.

// vim: set syntax=asciidoc sw=2 tw=70:
