Like most assemblers, each NASM source line contains (unless it is a macro, a preprocessor directive or an assembler directive: see chapter 4 and chapter 7) some combination of the four fields
label: instruction operands ; comment
As usual, most of these fields are optional; the presence or absence of any combination of a label, an instruction and a comment is allowed. Of course, the operand field is either required or forbidden by the presence and nature of the instruction field.
NASM uses backslash (\) as the line continuation character; if a line ends with backslash, the next line is considered to be a part of the backslash-ended line.
NASM places no restrictions on white space within a line: labels may
have white space before them, or instructions may have no space before
them, or anything. The colon after a label is also optional. (Note that
this means that if you intend to code lodsb
alone on a line,
and type lodab
by accident, then that's still a valid source
line which does nothing but define a label. Running NASM with the
command-line option -w+orphan-labels
will cause it to warn you
if you define a label alone on a line without a trailing colon.)
Valid characters in labels are letters, numbers, _
,
$
, #
, @
, ~
,
.
, and ?
. The only characters which may be used
as the first character of an identifier are letters,
.
(with special meaning: see section
3.9), _
and ?
. An identifier may also be
prefixed with a $
to indicate that it is intended to be read
as an identifier and not a reserved word; thus, if some other module you
are linking with defines a symbol called eax
, you can refer to
$eax
in NASM code to distinguish the symbol from the register.
Maximum length of an identifier is 4095 characters.
The instruction field may contain any machine instruction: Pentium and
P6 instructions, FPU instructions, MMX instructions and even undocumented
instructions are all supported. The instruction may be prefixed by
LOCK
, REP
, REPE
/REPZ
,
REPNE
/REPNZ
,
XACQUIRE
/XRELEASE
or
BND
/NOBND
, in the usual way. Explicit
address-size and operand-size prefixes A16
, A32
,
A64
, O16
and O32
, O64
are provided – one example of their use is given in
chapter 11. You can also use the name of a
segment register as an instruction prefix: coding
es mov [bx],ax
is equivalent to coding
mov [es:bx],ax
. We recommend the latter syntax, since it is
consistent with other syntactic features of the language, but for
instructions such as LODSB
, which has no operands and yet can
require a segment override, there is no clean syntactic way to proceed
apart from es lodsb
.
An instruction is not required to use a prefix: prefixes such as
CS
, A32
, LOCK
or REPE
can appear on a line by themselves, and NASM will just generate the prefix
bytes.
In addition to actual machine instructions, NASM also supports a number of pseudo-instructions, described in section 3.2.
Instruction operands may take a number of forms: they can be registers,
described simply by the register name (e.g. ax
,
bp
, ebx
, cr0
: NASM does not use the
gas
–style syntax in which register names must be
prefixed by a %
sign), or they can be effective addresses (see
section 3.3), constants
(section 3.4) or expressions
(section 3.5).
For x87 floating-point instructions, NASM accepts a wide range of syntaxes: you can use two-operand forms like MASM supports, or you can use NASM's native single-operand forms in most cases. For example, you can code:
fadd st1 ; this sets st0 := st0 + st1 fadd st0,st1 ; so does this fadd st1,st0 ; this sets st1 := st1 + st0 fadd to st1 ; so does this
Almost any x87 floating-point instruction that references memory must
use one of the prefixes DWORD
, QWORD
or
TWORD
to indicate what size of memory operand it refers to.
Pseudo-instructions are things which, though not real x86 machine
instructions, are used in the instruction field anyway because that's the
most convenient place to put them. The current pseudo-instructions are
DB
, DW
, DD
, DQ
,
DT
, DO
, DY
and DZ
;
their uninitialized counterparts RESB
, RESW
,
RESD
, RESQ
, REST
, RESO
,
RESY
and RESZ
; the INCBIN
command,
the EQU
command, and the TIMES
prefix.
In this documentation, the notation "D
x" and
"RES
x" is used to indicate all the DB
and RESB
type directives, respectively.
D
x: Declaring Initialized DataDB
, DW
, DD
, DQ
,
DT
, DO
, DY
and DZ
(collectively "D
x" in this documentation) are used,
much as in MASM, to declare initialized data in the output file. They can
be invoked in a wide range of ways:
db 0x55 ; just the byte 0x55 db 0x55,0x56,0x57 ; three bytes in succession db 'a',0x55 ; character constants are OK db 'hello',13,10,'$' ; so are string constants dw 0x1234 ; 0x34 0x12 dw 'a' ; 0x61 0x00 (it's just a number) dw 'ab' ; 0x61 0x62 (character constant) dw 'abc' ; 0x61 0x62 0x63 0x00 (string) dd 0x12345678 ; 0x78 0x56 0x34 0x12 dd 1.234567e20 ; floating-point constant dq 0x123456789abcdef0 ; eight byte constant dq 1.234567e20 ; double-precision float dt 1.234567e20 ; extended-precision float
DT
, DO
, DY
and DZ
do
not accept integer numeric constants as operands.
Starting in NASM 2.15, a the following MASM–like features have been implemented:
A ?
argument to declare uninitialized storage:
db ? ; uninitialized
A superset of the DUP
syntax. The NASM version of this has
the following syntax specification; capital letters indicate literal
keywords:
dx := DB | DW | DD | DQ | DT | DO | DY | DZ type := BYTE | WORD | DWORD | QWORD | TWORD | OWORD | YWORD | ZWORD atom := expression | string | float | '?' parlist := '(' value [',' value ...] ')' duplist := expression DUP [type] ['%'] parlist list := duplist | '%' parlist | type ['%'] parlist value := [type] atom | list stmt := dx value [',' value ...]
Note that a list needs to be prefixed with a %
sign unless prefixed by either DUP
or a type in order
to avoid confusing it with a parenthesis starting an expression. The
following expressions are all valid:
db 33 db (44) ; Integer expression ; db (44,55) ; Invalid - error db %(44,55) db %('XX','YY') db ('AA') ; Integer expression - outputs single byte db %('BB') ; List, containing a string db ? db 6 dup (33) db 6 dup (33, 34) db 6 dup (33, 34), 35 db 7 dup (99) db 7 dup dword (?, word ?, ?) dw byte (?,44) dw 3 dup (0xcc, 4 dup byte ('PQR'), ?), 0xabcd dd 16 dup (0xaaaa, ?, 0xbbbbbb) dd 64 dup (?)
The use of $
(current address) in a
D
x statement is undefined in the current version of
NASM, except in the following cases:
For the first expression in the statement, either a DUP
or
a data item.
An expression of the form "value - $
", which is
converted to a self-relative relocation.
Future versions of NASM is likely to produce a different result or issue an error this case.
There is no such restriction on using $$
or
section-relative symbols.
RESB
and Friends: Declaring Uninitialized DataRESB
, RESW
, RESD
,
RESQ
, REST
, RESO
, RESY
and RESZ
are designed to be used in the BSS section of a
module: they declare uninitialized storage space. Each takes a
single operand, which is the number of bytes, words, doublewords or
whatever to reserve. The operand to a RESB
–type
pseudo-instruction would be a critical expression (see
section 3.8), except that for legacy
compatibility reasons forward references are permitted, however the
code will be extremely fragile and this should be considered a severe
programming error. A warning will be issued; code generating this
warning should be remedied as quickly as possible (see the
forward
class in appendix A.)
For example:
buffer: resb 64 ; reserve 64 bytes wordvar: resw 1 ; reserve a word realarray resq 10 ; array of ten reals ymmval: resy 1 ; one YMM register zmmvals: resz 32 ; 32 ZMM registers
Since NASM 2.15, the MASM syntax of using ?
and
DUP
in the D
x directives is also
supported. Thus, the above example could also be written:
buffer: db 64 dup (?) ; reserve 64 bytes wordvar: dw ? ; reserve a word realarray dq 10 dup (?) ; array of ten reals ymmval: dy ? ; one YMM register zmmvals: dz 32 dup (?) ; 32 ZMM registers
INCBIN
: Including External Binary FilesINCBIN
includes binary file data verbatim into the output
file. This can be handy for (for example) including graphics and sound data
directly into a game executable file. It can be called in one of these
three ways:
incbin "file.dat" ; include the whole file incbin "file.dat",1024 ; skip the first 1024 bytes incbin "file.dat",1024,512 ; skip the first 1024, and ; actually include at most 512
INCBIN
is both a directive and a standard macro; the
standard macro version searches for the file in the include file search
path and adds the file to the dependency lists. This macro can be
overridden if desired.
EQU
: Defining ConstantsEQU
defines a symbol to a given constant value: when
EQU
is used, the source line must contain a label. The action
of EQU
is to define the given label name to the value of its
(only) operand. This definition is absolute, and cannot change later. So,
for example,
message db 'hello, world' msglen equ $-message
defines msglen
to be the constant 12. msglen
may not then be redefined later. This is not a preprocessor definition
either: the value of msglen
is evaluated once, using
the value of $
(see section 3.5 for
an explanation of $
) at the point of definition, rather than
being evaluated wherever it is referenced and using the value of
$
at the point of reference.
TIMES
: Repeating Instructions or DataThe TIMES
prefix causes the instruction to be assembled
multiple times. This is partly present as NASM's equivalent of the
DUP
syntax supported by MASM–compatible assemblers, in
that you can code
zerobuf: times 64 db 0
or similar things; but TIMES
is more versatile than that.
The argument to TIMES
is not just a numeric constant, but a
numeric expression, so you can do things like
buffer: db 'hello, world' times 64-$+buffer db ' '
which will store exactly enough spaces to make the total length of
buffer
up to 64. Finally, TIMES
can be applied to
ordinary instructions, so you can code trivial unrolled loops in it:
times 100 movsb
Note that there is no effective difference between
times 100 resb 1
and resb 100
, except that the
latter will be assembled about 100 times faster due to the internal
structure of the assembler.
The operand to TIMES
is a critical expression
(section 3.8).
Note also that TIMES
can't be applied to macros: the reason
for this is that TIMES
is processed after the macro phase,
which allows the argument to TIMES
to contain expressions such
as 64-$+buffer
as above. To repeat more than one line of code,
or a complex macro, use the preprocessor %rep
directive.
An effective address is any operand to an instruction which references memory. Effective addresses, in NASM, have a very simple syntax: they consist of an expression evaluating to the desired address, enclosed in square brackets. For example:
wordvar dw 123 mov ax,[wordvar] mov ax,[wordvar+1] mov ax,[es:wordvar+bx]
Anything not conforming to this simple system is not a valid memory
reference in NASM, for example es:wordvar[bx]
.
More complicated effective addresses, such as those involving more than one register, work in exactly the same way:
mov eax,[ebx*2+ecx+offset] mov ax,[bp+di+8]
NASM is capable of doing algebra on these effective addresses, so that things which don't necessarily look legal are perfectly all right:
mov eax,[ebx*5] ; assembles as [ebx*4+ebx] mov eax,[label1*2-label2] ; ie [label1+(label1-label2)]
Some forms of effective address have more than one assembled form; in
most such cases NASM will generate the smallest form it can. For example,
there are distinct assembled forms for the 32-bit effective addresses
[eax*2+0]
and [eax+eax]
, and NASM will generally
generate the latter on the grounds that the former requires four bytes to
store a zero offset.
NASM has a hinting mechanism which will cause [eax+ebx]
and
[ebx+eax]
to generate different opcodes; this is occasionally
useful because [esi+ebp]
and [ebp+esi]
have
different default segment registers.
However, you can force NASM to generate an effective address in a
particular form by the use of the keywords BYTE
,
WORD
, DWORD
and NOSPLIT
. If you need
[eax+3]
to be assembled using a double-word offset field
instead of the one byte NASM will normally generate, you can code
[dword eax+3]
. Similarly, you can force NASM to use a byte
offset for a small value which it hasn't seen on the first pass (see
section 3.8 for an example of such a code
fragment) by using [byte eax+offset]
. As special cases,
[byte eax]
will code [eax+0]
with a byte offset
of zero, and [dword eax]
will code it with a double-word
offset of zero. The normal form, [eax]
, will be coded with no
offset field.
The form described in the previous paragraph is also useful if you are trying to access data in a 32-bit segment from within 16 bit code. For more information on this see the section on mixed-size addressing (section 11.2). In particular, if you need to access data with a known offset that is larger than will fit in a 16-bit value, if you don't specify that it is a dword offset, nasm will cause the high word of the offset to be lost.
Similarly, NASM will split [eax*2]
into
[eax+eax]
because that allows the offset field to be absent
and space to be saved; in fact, it will also split
[eax*2+offset]
into [eax+eax+offset]
. You can
combat this behaviour by the use of the NOSPLIT
keyword:
[nosplit eax*2]
will force [eax*2+0]
to be
generated literally. [nosplit eax*1]
also has the same effect.
In another way, a split EA form [0, eax*2]
can be used, too.
However, NOSPLIT
in [nosplit eax+eax]
will be
ignored because user's intention here is considered as
[eax+eax]
.
In 64-bit mode, NASM will by default generate absolute addresses. The
REL
keyword makes it produce RIP
–relative
addresses. Since this is frequently the normally desired behaviour, see the
DEFAULT
directive (section
7.2). The keyword ABS
overrides REL
.
A new form of split effective address syntax is also supported. This is mainly intended for mib operands as used by MPX instructions, but can be used for any memory reference. The basic concept of this form is splitting base and index.
mov eax,[ebx+8,ecx*4] ; ebx=base, ecx=index, 4=scale, 8=disp
For mib operands, there are several ways of writing effective address depending on the tools. NASM supports all currently possible ways of mib syntax:
; bndstx ; next 5 lines are parsed same ; base=rax, index=rbx, scale=1, displacement=3 bndstx [rax+0x3,rbx], bnd0 ; NASM - split EA bndstx [rbx*1+rax+0x3], bnd0 ; GAS - '*1' indecates an index reg bndstx [rax+rbx+3], bnd0 ; GAS - without hints bndstx [rax+0x3], bnd0, rbx ; ICC-1 bndstx [rax+0x3], rbx, bnd0 ; ICC-2
When broadcasting decorator is used, the opsize keyword should match the size of each element.
VDIVPS zmm4, zmm5, dword [rbx]{1to16} ; single-precision float VDIVPS zmm4, zmm5, zword [rbx] ; packed 512 bit memory
NASM understands four different types of constant: numeric, character, string and floating-point.
A numeric constant is simply a number. NASM allows you to specify
numbers in a variety of number bases, in a variety of ways: you can suffix
H
or X
, D
or T
,
Q
or O
, and B
or Y
for
hexadecimal, decimal, octal and binary respectively, or you can prefix
0x
, for hexadecimal in the style of C, or you can prefix
$
for hexadecimal in the style of Borland Pascal or Motorola
Assemblers. Note, though, that the $
prefix does double duty
as a prefix on identifiers (see section 3.1), so
a hex number prefixed with a $
sign must have a digit after
the $
rather than a letter. In addition, current versions of
NASM accept the prefix 0h
for hexadecimal, 0d
or
0t
for decimal, 0o
or 0q
for octal,
and 0b
or 0y
for binary. Please note that unlike
C, a 0
prefix by itself does not imply an octal
constant!
Numeric constants can have underscores (_
) interspersed to
break up long strings.
Some examples (all producing exactly the same code):
mov ax,200 ; decimal mov ax,0200 ; still decimal mov ax,0200d ; explicitly decimal mov ax,0d200 ; also decimal mov ax,0c8h ; hex mov ax,$0c8 ; hex again: the 0 is required mov ax,0xc8 ; hex yet again mov ax,0hc8 ; still hex mov ax,310q ; octal mov ax,310o ; octal again mov ax,0o310 ; octal yet again mov ax,0q310 ; octal yet again mov ax,11001000b ; binary mov ax,1100_1000b ; same binary constant mov ax,1100_1000y ; same binary constant once more mov ax,0b1100_1000 ; same binary constant yet again mov ax,0y1100_1000 ; same binary constant yet again
A character string consists of up to eight characters enclosed in either
single quotes ('...'
), double quotes ("..."
) or
backquotes (`...`
). Single or double quotes are equivalent to
NASM (except of course that surrounding the constant with single quotes
allows double quotes to appear within it and vice versa); the contents of
those are represented verbatim. Strings enclosed in backquotes support
C-style \
–escapes for special characters.
The following escape sequences are recognized by backquoted strings:
\' single quote (') \" double quote (") \` backquote (`) \\ backslash (\) \? question mark (?) \a BEL (ASCII 7) \b BS (ASCII 8) \t TAB (ASCII 9) \n LF (ASCII 10) \v VT (ASCII 11) \f FF (ASCII 12) \r CR (ASCII 13) \e ESC (ASCII 27) \377 Up to 3 octal digits - literal byte \xFF Up to 2 hexadecimal digits - literal byte \u1234 4 hexadecimal digits - Unicode character \U12345678 8 hexadecimal digits - Unicode character
All other escape sequences are reserved. Note that \0
,
meaning a NUL
character (ASCII 0), is a special case of the
octal escape sequence.
Unicode characters specified with \u
or \U
are
converted to UTF-8. For example, the following lines are all equivalent:
db `\u263a` ; UTF-8 smiley face db `\xe2\x98\xba` ; UTF-8 smiley face db 0E2h, 098h, 0BAh ; UTF-8 smiley face
A character constant consists of a string up to eight bytes long, used in an expression context. It is treated as if it was an integer.
A character constant with more than one byte will be arranged with little-endian order in mind: if you code
mov eax,'abcd'
then the constant generated is not 0x61626364
, but
0x64636261
, so that if you were then to store the value into
memory, it would read abcd
rather than dcba
. This
is also the sense of character constants understood by the Pentium's
CPUID
instruction.
String constants are character strings used in the context of some
pseudo-instructions, namely the DB
family and
INCBIN
(where it represents a filename.) They are also used in
certain preprocessor directives.
A string constant looks like a character constant, only longer. It is treated as a concatenation of maximum-size character constants for the conditions. So the following are equivalent:
db 'hello' ; string constant db 'h','e','l','l','o' ; equivalent character constants
And the following are also equivalent:
dd 'ninechars' ; doubleword string constant dd 'nine','char','s' ; becomes three doublewords db 'ninechars',0,0,0 ; and really looks like this
Note that when used in a string-supporting context, quoted strings are
treated as a string constants even if they are short enough to be a
character constant, because otherwise db 'ab'
would have the
same effect as db 'a'
, which would be silly. Similarly,
three-character or four-character constants are treated as strings when
they are operands to DW
, and so forth.
The special operators __?utf16?__
,
__?utf16le?__
, __?utf16be?__
,
__?utf32?__
, __?utf32le?__
and
__?utf32be?__
allows definition of Unicode strings. They take
a string in UTF-8 format and converts it to UTF-16 or UTF-32, respectively.
Unless the be
forms are specified, the output is littleendian.
For example:
%define u(x) __?utf16?__(x) %define w(x) __?utf32?__(x) dw u('C:\WINDOWS'), 0 ; Pathname in UTF-16 dd w(`A + B = \u206a`), 0 ; String in UTF-32
The UTF operators can be applied either to strings passed to the
DB
family instructions, or to character constants in an
expression context.
Floating-point constants are acceptable only as arguments to
DB
, DW
, DD
, DQ
,
DT
, and DO
, or as arguments to the special
operators __?float8?__
, __?float16?__
,
__?bfloat16?__
, __?float32?__
,
__?float64?__
, __?float80m?__
,
__?float80e?__
, __?float128l?__
, and
__?float128h?__
. See also
section 6.3.
Floating-point constants are expressed in the traditional form: digits,
then a period, then optionally more digits, then optionally an
E
followed by an exponent. The period is mandatory, so that
NASM can distinguish between dd 1
, which declares an integer
constant, and dd 1.0
which declares a floating-point constant.
NASM also support C99-style hexadecimal floating-point: 0x
,
hexadecimal digits, period, optionally more hexadeximal digits, then
optionally a P
followed by a binary (not hexadecimal)
exponent in decimal notation. As an extension, NASM additionally supports
the 0h
and $
prefixes for hexadecimal, as well
binary and octal floating-point, using the 0b
or
0y
and 0o
or 0q
prefixes,
respectively.
Underscores to break up groups of digits are permitted in floating-point constants as well.
Some examples:
db -0.2 ; "Quarter precision" dw -0.5 ; IEEE 754r/SSE5 half precision dd 1.2 ; an easy one dd 1.222_222_222 ; underscores are permitted dd 0x1p+2 ; 1.0x2^2 = 4.0 dq 0x1p+32 ; 1.0x2^32 = 4 294 967 296.0 dq 1.e10 ; 10 000 000 000.0 dq 1.e+10 ; synonymous with 1.e10 dq 1.e-10 ; 0.000 000 000 1 dt 3.141592653589793238462 ; pi do 1.e+4000 ; IEEE 754r quad precision
The 8-bit "quarter-precision" floating-point format is sign:exponent:mantissa = 1:4:3 with an exponent bias of 7. This appears to be the most frequently used 8-bit floating-point format, although it is not covered by any formal standard. This is sometimes called a "minifloat."
The bfloat16
format is effectively a compressed version of
the 32-bit single precision format, with a reduced mantissa. It is
effectively the same as truncating the 32-bit format to the upper 16 bits,
except for rounding. There is no D
x directive that
corresponds to bfloat16
as it obviously has the same size as
the IEEE standard 16-bit half precision format, see however
section 6.3.
The special operators are used to produce floating-point numbers in
other contexts. They produce the binary representation of a specific
floating-point number as an integer, and can use anywhere integer constants
are used in an expression. __?float80m?__
and
__?float80e?__
produce the 64-bit mantissa and 16-bit exponent
of an 80-bit floating-point number, and __?float128l?__
and
__?float128h?__
produce the lower and upper 64-bit halves of a
128-bit floating-point number, respectively.
For example:
mov rax,__?float64?__(3.141592653589793238462)
... would assign the binary representation of pi as a 64-bit floating
point number into RAX
. This is exactly equivalent to:
mov rax,0x400921fb54442d18
NASM cannot do compile-time arithmetic on floating-point constants. This is because NASM is designed to be portable – although it always generates code to run on x86 processors, the assembler itself can run on any system with an ANSI C compiler. Therefore, the assembler cannot guarantee the presence of a floating-point unit capable of handling the Intel number formats, and so for NASM to be able to do floating arithmetic it would have to include its own complete set of floating-point routines, which would significantly increase the size of the assembler for very little benefit.
The special tokens __?Infinity?__
, __?QNaN?__
(or __?NaN?__
) and __?SNaN?__
can be used to
generate infinities, quiet NaNs, and signalling NaNs, respectively. These
are normally used as macros:
%define Inf __?Infinity?__ %define NaN __?QNaN?__ dq +1.5, -Inf, NaN ; Double-precision constants
The %use fp
standard macro package contains a set of
convenience macros. See section
6.3.
x87-style packed BCD constants can be used in the same contexts as
80-bit floating-point numbers. They are suffixed with p
or
prefixed with 0p
, and can include up to 18 decimal digits.
As with other numeric constants, underscores can be used to separate digits.
For example:
dt 12_345_678_901_245_678p dt -12_345_678_901_245_678p dt +0p33 dt 33p
Expressions in NASM are similar in syntax to those in C. Expressions are evaluated as 64-bit integers which are then adjusted to the appropriate size.
NASM supports two special tokens in expressions, allowing calculations
to involve the current assembly position: the $
and
$$
tokens. $
evaluates to the assembly position
at the beginning of the line containing the expression; so you can code an
infinite loop using JMP $
. $$
evaluates to the
beginning of the current section; so you can tell how far into the section
you are by using ($-$$)
.
The arithmetic operators provided by NASM are listed here, in increasing order of precedence.
A boolean value is true if nonzero and false if zero. The operators which return a boolean value always return 1 for true and 0 for false.
?
... :
: Conditional OperatorThe syntax of this operator, similar to the C conditional operator, is:
boolean ?
trueval :
falseval
This operator evaluates to trueval if boolean is true, otherwise to falseval.
Note that NASM allows ?
characters in symbol names.
Therefore, it is highly advisable to always put spaces around the
?
and :
characters.
||
: Boolean OR OperatorThe ||
operator gives a boolean OR: it evaluates to 1 if
both sides of the expression are nonzero, otherwise 0.
^^
: Boolean XOR OperatorThe ^^
operator gives a boolean XOR: it evaluates to 1 if
any one side of the expression is nonzero, otherwise 0.
&&
: Boolean AND OperatorThe &&
operator gives a boolean AND: it evaluates
to 1 if both sides of the expression is nonzero, otherwise 0.
NASM supports the following comparison operators:
=
or ==
compare for equality.
!=
or <>
compare for inequality.
<
compares signed less than.
<=
compares signed less than or equal.
>
compares signed greater than.
>=
compares signed greater than or equal.
These operators evaluate to 0 for false or 1 for true.
<=> does a signed comparison, and evaluates to –1 for less than, 0 for equal, and 1 for greater than.
At this time, NASM does not provide unsigned comparison operators.
|
: Bitwise OR OperatorThe |
operator gives a bitwise OR, exactly as performed by
the OR
machine instruction.
^
: Bitwise XOR Operator^
provides the bitwise XOR operation.
&
: Bitwise AND Operator&
provides the bitwise AND operation.
<<
gives a bit-shift to the left, just as it does in
C. So 5<<3
evaluates to 5 times 8, or 40.
>>
gives an unsigned (logical) bit-shift to the
right; the bits shifted in from the left are set to zero.
<<<
gives a bit-shift to the left, exactly
equivalent to the <<
operator; it is included for
completeness. >>>
gives an signed
(arithmetic) bit-shift to the right; the bits shifted in from the left are
filled with copies of the most significant (sign) bit.
+
and -
: Addition and Subtraction OperatorsThe +
and -
operators do perfectly ordinary
addition and subtraction.
*
is the multiplication operator.
/
and //
are both division operators:
/
is unsigned division and //
is signed division.
Similarly, %
and %%
provide unsigned and
signed modulo operators respectively.
Since the %
character is used extensively by the macro
preprocessor, you should ensure that both the signed and unsigned modulo
operators are followed by white space wherever they appear.
NASM, like ANSI C, provides no guarantees about the sensible operation of the signed modulo operator. On most systems it will match the signed division operator, such that:
b * (a // b) + (a %% b) = a (b != 0)
The highest-priority operators in NASM's expression grammar are those which only apply to one argument. These are:
-
negates (2's complement) its operand.
+
does nothing; it's provided for symmetry with
-
.
~
computes the bitwise negation (1's complement) of its
operand.
!
is the boolean negation operator. It evaluates to 1 if
the argument is 0, otherwise 0.
SEG
provides the segment address of its operand (explained
in more detail in section 3.6).
A set of additional operators with leading and trailing double
underscores are used to implement the integer functions
of the
ifunc
macro package, see
section 6.4.
SEG
and WRT
When writing large 16-bit programs, which must be split into multiple
segments, it is often necessary to be able to refer to the segment part of
the address of a symbol. NASM supports the SEG
operator to
perform this function.
The SEG
operator evaluates to the preferred
segment base of a symbol, defined as the segment base relative to which the
offset of the symbol makes sense. So the code
mov ax,seg symbol mov es,ax mov bx,symbol
will load ES:BX
with a valid pointer to the symbol
symbol
.
Things can be more complex than this: since 16-bit segments and groups
may overlap, you might occasionally want to refer to some symbol using a
different segment base from the preferred one. NASM lets you do this, by
the use of the WRT
(With Reference To) keyword. So you can do
things like
mov ax,weird_seg ; weird_seg is a segment base mov es,ax mov bx,symbol wrt weird_seg
to load ES:BX
with a different, but functionally
equivalent, pointer to the symbol symbol
.
NASM supports far (inter-segment) calls and jumps by means of the syntax
call segment:offset
, where segment
and
offset
both represent immediate values. So to call a far
procedure, you could code either of
call (seg procedure):procedure call weird_seg:(procedure wrt weird_seg)
(The parentheses are included for clarity, to show the intended parsing of the above instructions. They are not necessary in practice.)
NASM supports the syntax call far procedure
as a synonym
for the first of the above usages. JMP
works identically to
CALL
in these examples.
To declare a far pointer to a data item in a data segment, you must code
dw symbol, seg symbol
NASM supports no convenient synonym for this, though you can always invent one using the macro processor.
STRICT
: Inhibiting OptimizationWhen assembling with the optimizer set to level 2 or higher (see
section 2.1.24), NASM will use
size specifiers (BYTE
, WORD
, DWORD
,
QWORD
, TWORD
, OWORD
,
YWORD
or ZWORD
), but will give them the smallest
possible size. The keyword STRICT
can be used to inhibit
optimization and force a particular operand to be emitted in the specified
size. For example, with the optimizer on, and in BITS 16
mode,
push dword 33
is encoded in three bytes 66 6A 21
, whereas
push strict dword 33
is encoded in six bytes, with a full dword immediate operand
66 68 21 00 00 00
.
With the optimizer off, the same code (six bytes) is generated whether
the STRICT
keyword was used or not.
Although NASM has an optional multi-pass optimizer, there are some expressions which must be resolvable on the first pass. These are called Critical Expressions.
The first pass is used to determine the size of all the assembled code and data, so that the second pass, when generating all the code, knows all the symbol addresses the code refers to. So one thing NASM can't handle is code whose size depends on the value of a symbol declared after the code in question. For example,
times (label-$) db 0 label: db 'Where am I?'
The argument to TIMES
in this case could equally legally
evaluate to anything at all; NASM will reject this example because it
cannot tell the size of the TIMES
line when it first sees it.
It will just as firmly reject the slightly paradoxical code
times (label-$+1) db 0 label: db 'NOW where am I?'
in which any value for the TIMES
argument is by
definition wrong!
NASM rejects these examples by means of a concept called a critical
expression, which is defined to be an expression whose value is
required to be computable in the first pass, and which must therefore
depend only on symbols defined before it. The argument to the
TIMES
prefix is a critical expression.
NASM gives special treatment to symbols beginning with a period. A label beginning with a single period is treated as a local label, which means that it is associated with the previous non-local label. So, for example:
label1 ; some code .loop ; some more code jne .loop ret label2 ; some code .loop ; some more code jne .loop ret
In the above code fragment, each JNE
instruction jumps to
the line immediately before it, because the two definitions of
.loop
are kept separate by virtue of each being associated
with the previous non-local label.
This form of local label handling is borrowed from the old Amiga
assembler DevPac; however, NASM goes one step further, in allowing access
to local labels from other parts of the code. This is achieved by means of
defining a local label in terms of the previous non-local label:
the first definition of .loop
above is really defining a
symbol called label1.loop
, and the second defines a symbol
called label2.loop
. So, if you really needed to, you could
write
label3 ; some more code ; and some more jmp label1.loop
Sometimes it is useful – in a macro, for instance – to be
able to define a label which can be referenced from anywhere but which
doesn't interfere with the normal local-label mechanism. Such a label can't
be non-local because it would interfere with subsequent definitions of, and
references to, local labels; and it can't be local because the macro that
defined it wouldn't know the label's full name. NASM therefore introduces a
third type of label, which is probably only useful in macro definitions: if
a label begins with the special prefix ..@
, then it does
nothing to the local label mechanism. So you could code
label1: ; a non-local label .local: ; this is really label1.local ..@foo: ; this is a special symbol label2: ; another non-local label .local: ; this is really label2.local jmp ..@foo ; this will jump three lines up
NASM has the capacity to define other special symbols beginning with a
double period: for example, ..start
is used to specify the
entry point in the obj
output format (see
section 8.4.6),
..imagebase
is used to find out the offset from a base address
of the current image in the win64
output format (see
section 8.6.1). So just keep in
mind that symbols beginning with a double period are special.