Copyright © 2006, 2007 Peter Johnson
2007
Abstract
This document is the user manual for the Yasm assembler. It is intended as both an introduction and a general-purpose reference for all Yasm users.
Table of Contents
%0: Macro Parameter Counter%rotate: Rotating Macro Parameters%ifdef: Testing Single-Line Macro Existence%ifmacro: Testing Multi-Line Macro Existence%ifctx: Testing the Context Stack%if: Testing Arbitrary Numeric Expressions%ifidn and %ifidni: Testing Exact
Text Identity%ifid, %ifnum, %ifstr: Testing Token Types%error: Reporting User-Defined Errors__YASM_MAJOR__, etc: Yasm Version__FILE__ and __LINE__: File Name and
Line Number__YASM_OBJFMT__ and __OUTPUT_FORMAT__: Output Object Format KeywordSTRUC and ENDSTRUC: Declaring
Structure Data TypesISTRUC, AT and IEND: Declaring Instances of StructuresALIGN and ALIGNB: Data
Alignmentbin:
Flat-Form Binary Outputcoff:
Common Object File Formatelf32:
Executable and Linkable Format 32-bit Object Fileself64:
Executable and Linkable Format 64-bit Object Filesmacho32: Mach 32-bit Object File Formatmacho64: Mach 64-bit Object File Formatrdf:
Relocatable Dynamic Object File Formatwin32:
Microsoft Win32 Object Fileswin64:
PE32+ (Microsoft Win64) Object Filesxdf:
Extended Dynamic Object FormatList of Figures
List of Tables
bin Section
AttributesList of Examples
Table of Contents
Yasm is a (mostly) BSD-licensed assembler that is designed from the ground up to allow for multiple assembler syntaxes to be supported (e.g. NASM, GNU AS, etc.) in addition to multiple output object formats and multiple instruction sets. Its modular architecture allows additional object formats, debug formats, and syntaxes to be added relatively easily.
Yasm started life in 2001 as a rewrite of the NASM (Netwide) x86 assembler under the BSD license. Since then, it has matched and exceeded NASM's capabilities, incorporating features such as supporting the 64-bit AMD64 architecture, parsing GNU AS syntax, and generating STABS, DWARF2, and CodeView 8 debugging information.
Yasm is primarily licensed under the 2-clause and 3-clause “revised” BSD licenses, with two exceptions. The NASM preprocessor is imported from the NASM project and is thus LGPL licensed. The Bit::Vector module used by Yasm to implement Yasm's large integer and machine-independent floating point support is triple-licensed under the Artistic license, GPL, and LGPL. The full text of the licenses are provided in the Yasm source distribution.
This user manual is licensed under the 2-clause BSD license, with the exception of Chapter 2, Chapter 3, and Chapter 4, large portions of which are copyrighted by the NASM Development Team and licensed under the LGPL.
This book is intended to be a user's manual for Yasm, serving as both an introduction and a general-purpose reference. While mentions may be made in various sections of Yasm's implementation (usually to explain the reasons behind bugs or unusual aspects to various features), this book will not go into depth explaining how Yasm does its job; for an in-depth discussion of Yasm's internals, see The Design and Implementation of the Yasm Assembler.
Table of Contents
The yasm command assembles the file infile and directs output to the file outfile if specified. If outfile is not specified, yasm will derive a default output file name from the name
of its input file, usually by appending .o or .obj, or by removing all extensions for a raw binary file.
Failing that, the output file name will be yasm.out.
If called with an infile of “-”, yasm assembles
the standard input and directs output to the file outfile, or yasm.out
if no outfile is specified.
If errors or warnings are discovered during execution, Yasm outputs the error message
to stderr (usually the terminal). If no errors or warnings
are encountered, Yasm does not output any messages.
Many options may be given in one of two forms: either a dash followed by a single letter, or two dashes followed by a long option name. Options are listed in alphabetical order.
Selects the target architecture. The default architecture is “x86”, which supports both the IA-32 and derivatives and AMD64
instruction sets. To print a list of available architectures to standard output, use
“help” as arch.
See Section 1.4
for a list of supported architectures.
Selects the output object format. The default object format is “bin”, which is a flat format binary with no relocation. To print a
list of available object formats to standard output, use “help” as format. See Section 1.6 for a list
of supported object formats.
Selects the debugging format for debug information. Debugging information can be used
by a debugger to associate executable code back to the source file or get data structure
and type information. Available debug formats vary between different object formats;
yasm will error when an invalid combination
is selected. The default object format is selected by the object format. To print a list
of available debugging formats to standard output, use “help” as debug. See Section 1.7 for a
list of supported debugging formats.
Prints a summary of invocation options. All other options are ignored, and no output file is generated.
Selects the format/style of the output list file. List files typically intermix the
original source with the machine code generated by the assembler. The default list format
is “nasm”, which mimics the NASM list file format. To
print a list of available list file formats to standard output, use “help” as list.
Specifies the name of the output list file. If this option is not used, no list file is generated.
Selects the target machine architecture. Essentially a subtype of the selected
architecture, the machine type selects between major subsets of an architecture. For
example, for the “x86” architecture, the two available
machines are “x86”, which is used for the IA-32 and
derivative 32-bit instruction set, and “amd64”, which is
used for the 64-bit instruction set. This differentiation is required to generate the
proper object file for relocatable object formats such as COFF and ELF. To print a list
of available machines for a given architecture to standard output, use “help” as machine and the
given architecture using -a . See Part V for more details.arch
Specifies the name of the output file, overriding any default name generated by Yasm.
Selects the parser (the assembler syntax). The default parser is “nasm”, which emulates the syntax of NASM, the Netwide Assembler.
Another available parser is “gas”, which emulates the
syntax of GNU AS. To print a list of available parsers to standard output, use “help” as parser. See Section 1.5 for a
list of supported parsers.
Selects the preprocessor to use on the input file before passing it to the parser.
Preprocessors often provide macro functionality that is not included in the main parser.
The default preprocessor is “nasm”, which is an imported
version of the actual NASM preprocessor. A “raw”
preprocessor is also available, which simply skips the preprocessing step, passing the
input file directly to the parser. To print a list of available preprocessors to standard
output, use “help” as preproc.
-W options have two contrary forms: -W and name-Wno-. Only the
non-default forms are shown here.name
The warning options are handled in the order given on the command line, so if -w is followed by -Worphan-labels, all
warnings are turned off except for
orphan-labels.
This option causes Yasm to inhibit all warning messages. As discussed above, this option may be followed by other options to re-enable specified warnings.
This option causes Yasm to treat all warnings as errors. Normally warnings do not prevent an object file from being generated and do not result in a failure exit status from yasm, whereas errors do. This option makes warnings equivalent to errors in terms of this behavior.
Causes Yasm to not warn on unrecognized characters found in the input. Normally Yasm will generate a warning for any non-ASCII character found in the input file.
When using the NASM-compatible parser, causes Yasm to warn about labels found alone on a line without a trailing colon. While these are legal labels in NASM syntax, they may be unintentional, due to typos or macro definition ordering.
Selects a specific output style for error and warning messages. The default is “gnu” style, which mimics the output of gcc. The “vc” style is also available, which mimics the output of Microsoft's Visual C++ compiler.
This option is available so that Yasm integrates more naturally into IDE environments such as Visual Studio or Emacs, allowing the IDE to correctly recognize the error/warning message as such and link back to the offending line of source code.
While these preprocessor options theoretically will affect any preprocessor, the only preprocessor currently in Yasm is the “nasm” preprocessor.
Pre-defines a single-line macro. The value is optional (if no value is given, the macro is still defined, but to an empty value).
Stops assembly after the preprocessing stage; preprocessed output is sent to the specified output name or, if no output name is specified, the standard output. No object file is produced.
Adds directory path to the search path for
include files. The search path defaults to only including the directory in which the
source file resides.
Pre-includes file filename, making it look
as though filename was prepended to the input.
Can be useful for prepending multi-line macros that the -D
can't support.
Undefines a single-line macro (may be either a built-in macro or one defined earlier
in the command line with -D (see Section 1.3.3.1).
Yasm supports the following instruction set architectures (ISAs). For more details see Part V.
The “lc3b” architecture supports the LC-3b ISA as used in the ECE 411 (formerly ECE 312) course at the University of Illinois, Urbana-Champaign, as well as other university courses. See http://courses.ece.uiuc.edu/ece411/ for more details and example code. The “lc3b” architecture consists of only one machine: “lc3b”.
The “x86” architecture supports the IA-32 instruction set and derivatives (including 16-bit and non-Intel instructions) and the AMD64 instruction set. It consists of two machines: “x86” (for the IA-32 and derivatives) and “amd64” (for the AMD64 and derivatives). The default machine for the “x86” architecture is the “x86” machine.
Yasm parses the following assembler syntaxes:
NASM syntax is the most full-featured syntax supported by Yasm. Yasm is nearly 100% compatible with NASM for 16-bit and 32-bit x86 code. Yasm additionally supports 64-bit AMD64 code with Yasm extensions to the NASM syntax. For more details see Part I.
The GNU Assembler (GAS) is the de-facto cross-platform assembler for modern Unix systems, and is used as the backend for the GCC compiler. Yasm's support for GAS syntax is moderately good, although immature: not all directives are supported, and only 32-bit x86 and AMD64 architectures are supported. There is also no support for the GAS preprocessor. Despite these limitations, Yasm's GAS syntax support is good enough to handle essentially all x86 and AMD64 GCC compiler output. For more details see Part II.
Yasm supports the following object formats. More details can be found in Part III.
The “bin” object format produces a flat-format, non-relocatable binary file. It is appropriate for producing DOS .COM executables or things like boot blocks. It supports only 3 sections and those sections are written in a predefined order to the output file.
The COFF object format is an older relocatable object format used on older Unix and compatible systems, and also (more recently) on the DJGPP development system for DOS.
The “dbg” object format is not a “real” object format; the output file it creates simply describes the sequence of calls made to it by Yasm and the final object and symbol table information in a human-readable text format (that in a normal object format would get processed into that object format's particular binary representation). This object format is not intended for real use, but rather for debugging Yasm's internals.
The ELF object format really comes in two flavors: “elf32” (for 32-bit targets) and “elf64” (for 64-bit targets). ELF is a standard object format in common use on modern Unix and compatible systems (e.g. Linux, FreeBSD). ELF has complex support for relocatable and shared objects.
The Mach-O object format really comes in two flavors: “macho32” (for 32-bit targets) and “macho64” (for 64-bit targets). Mach-O is used as the object format on MacOS X. As Yasm currently only supports x86 and AMD64 instruction sets, it can only generate Mach-O objects for Intel-based Macs.
The RDOFF2 object format is a simple multi-section format originally designed for NASM. It supports segment references but not WRT references. It was designed primarily for simplicity and has minimalistic headers for ease of loading and linking. A complete toolchain (linker, librarian, and loader) is distributed with NASM.
The Win32 object format produces object files compatible with Microsoft compilers (such as Visual C++) that target the 32-bit x86 Windows platform. The object format itself is an extended version of COFF.
The Win64 object format produces object files compatible with Microsoft compilers that target the 64-bit “x64” Windows platform. This format is very similar to the win32 object format, but produces 64-bit objects.
The XDF object format is essentially a simplified version of COFF. It's a multi-section relocatable format that supports 64-bit physical and virtual addresses.
Yasm supports generation of source-level debugging information in the following formats. More details can be found in Part IV.
The CV8 debug format is used by Microsoft Visual Studio 2005 (version 8.0) and is completely undocumented, although it bears strong similarities to earlier CodeView formats. Yasm's support for the CV8 debug format is currently limited to generating assembly-level line number information (to allow some level of source-level debugging). The CV8 debug information is stored in the .debug$S and .debug$T sections of the Win64 object file.
The DWARF 2 debug format is a complex, well-documented standard for debugging information. It was created to overcome shortcomings in STABS, allowing for much more detailed and compact descriptions of data structures, data variable movement, and complex language structures such as in C++. The debugging information is stored in sections (just like normal program sections) in the object file. Yasm supports full pass-through of DWARF2 debugging information (e.g. from a C++ compiler), and can also generate assembly-level line number information.
The “null” debug format is a placeholder; it adds no debugging information to the output file.
The STABS debug format is a poorly documented, semi-standard format for debugging information in COFF and ELF object files. The debugging information is stored as part of the object file's symbol table and thus is limited in complexity and scope. Despite this, STABS is a common debugging format on older Unix and compatible systems, as well as DJGPP.
The chapters in this part of the book document the NASM-compatible syntax accepted by the Yasm “nasm” parser and preprocessor.
Table of Contents
%0: Macro Parameter Counter%rotate: Rotating Macro Parameters%ifdef: Testing Single-Line Macro Existence%ifmacro: Testing Multi-Line Macro Existence%ifctx: Testing the Context Stack%if: Testing Arbitrary Numeric Expressions%ifidn and %ifidni: Testing Exact
Text Identity%ifid, %ifnum, %ifstr: Testing Token Types%error: Reporting User-Defined Errors__YASM_MAJOR__, etc: Yasm Version__FILE__ and __LINE__: File Name and
Line Number__YASM_OBJFMT__ and __OUTPUT_FORMAT__: Output Object Format KeywordSTRUC and ENDSTRUC: Declaring
Structure Data TypesISTRUC, AT and IEND: Declaring Instances of StructuresALIGN and ALIGNB: Data
AlignmentTable of Contents
Like most assemblers, each NASM source line contains (unless it is a macro, a preprocessor directive or an assembler directive: see Chapter 4) 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 2.10), _ 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.
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 or REPNE/REPNZ, in the usual way. Explicit address-size and operand-size
prefixes A16, A32, O16 and O32 are provided. 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 2.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 2.3), constants (Section 2.5) or expressions (Section 2.6).
For 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 floating-point instruction that references memory must use one of the
prefixes DWORD, QWORD, TWORD, DDQWORD, or OWORD 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, DDQ, DO, their uninitialized
counterparts RESB, RESW, RESD, RESQ, REST, RESDDQ, and RESO, the INCBIN command, the EQU command, and the TIMES
prefix.
DB, DW, DD, DQ, DT, DDQ, and DO are used 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' ; 0x41 0x00 (it's just a number)
dw 'ab' ; 0x41 0x42 (character constant)
dw 'abc' ; 0x41 0x42 0x43 0x00 (string)
dd 0x12345678 ; 0x78 0x56 0x34 0x12
dq 0x1122334455667788 ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
ddq 0x112233445566778899aabbccddeeff00
; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
do 0x112233445566778899aabbccddeeff00 ; same as previous
dd 1.234567e20 ; floating-point constant
dq 1.234567e20 ; double-precision float
dt 1.234567e20 ; extended-precision float
DT does not accept numeric constants as operands, and
DDQ does not accept float constants as operands. Any size
larger than DD does not accept strings as operands.
RESB, RESW, RESD, RESQ, REST, RESDQ, and RESO are designed to be used in the BSS section of a module: they
declare uninitialised storage space. Each takes a
single operand, which is the number of bytes, words, doublewords or whatever to reserve.
NASM does not support the MASM/TASM syntax of reserving uninitialised space by writing
DW ? or similar things: this is what it does instead. The
operand to a RESB-type pseudo-instruction is a critical expression: see Section 2.9.
For example:
buffer: resb 64 ; reserve 64 bytes wordvar: resw 1 ; reserve a word realarray resq 10 ; array of ten reals
INCBIN includes a binary file verbatim into the output
file. This can be handy for (for example) including graphics and sound data directly into
a game executable file. However, it is recommended to use this for only small pieces of data. 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
EQU 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 2.6 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. Note that the operand to an EQU
is also a critical expression (Section 2.9).
The 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, like that of EQU and those of RESB and friends, is
a critical expression (Section 2.9).
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 2.9 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. 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.
In BITS 64 mode, displacements, for the most part, remain
32 bits and are sign extended prior to use. The exception is one restricted form of the
mov instruction: between an AL, AX, EAX, or RAX register and a 64-bit absolute address (no registers are
allowed in the effective address, and the address cannot be RIP-relative). In NASM
syntax, use of the 64-bit absolute form requires QWORD.
Examples in NASM syntax:
mov eax, [1] ; 32 bit, with sign extension
mov al, [rax-1] ; 32 bit, with sign extension
mov al, [qword 0x1122334455667788] ; 64-bit absolute
mov al, [0x1122334455667788] ; truncated to 32-bit (warning)
In 64-bit mode, a new form of effective addressing is available to make it easier to
write position-independent code. Any memory reference may be made RIP relative (RIP is the instruction
pointer register, which contains the address of the location immediately following the
current instruction).
In NASM syntax, there are two ways to specify RIP-relative addressing:
mov dword [rip+10], 1
stores the value 1 ten bytes after the end of the instruction. 10 can also be a symbolic constant, and will be
treated the same way. On the other hand,
mov dword [symb wrt rip], 1
stores the value 1 into the address of symbol symb. This is distinctly different than the
behavior of:
mov dword [symb+rip], 1
which takes the address of the end of the instruction, adds the address of symb to it, then stores the value 1 there. If
symb is a variable, this will not store the value 1 into the symb variable!
Yasm also supports the following syntax for RIP-relative addressing. The REL keyword makes it produce RIP-relative addresses, while the ABS
keyword makes it produce non-RIP-relative addresses:
mov [rel sym], rax ; RIP-relative
mov [abs sym], rax ; not RIP-relative
The behavior of mov [sym], rax depends on a mode set by
the DEFAULT directive (see Section 4.2), as follows. The
default mode at Yasm start-up is always ABS, and in REL mode, use of registers, a FS or
GS segment override, or an explicit ABS override will result in a non-RIP-relative effective
address.
default rel
mov [sym], rbx ; RIP-relative
mov [abs sym], rbx ; not RIP-relative (explicit override)
mov [rbx+1], rbx ; not RIP-relative (register use)
mov [fs:sym], rbx ; not RIP-relative (fs or gs use)
mov [ds:sym], rbx ; RIP-relative (segment, but not fs or gs)
mov [rel sym], rbx ; RIP-relative (redundant override)
default abs
mov [sym], rbx ; not RIP-relative
mov [abs sym], rbx ; not RIP-relative
mov [rbx+1], rbx ; not RIP-relative
mov [fs:sym], rbx ; not RIP-relative
mov [ds:sym], rbx ; not RIP-relative
mov [rel sym], rbx ; RIP-relative (explicit override)
Immediate operands in NASM may be 8 bits, 16 bits, 32 bits, and even 64 bits in size.
The immediate size can be directly specified through the use of the BYTE, WORD, or DWORD keywords, respectively.
64 bit immediate operands are limited to direct 64-bit register move instructions in
BITS 64 mode. For all other instructions in 64-bit mode,
immediate values remain 32 bits; their value is sign-extended into the upper 32 bits of
the target register prior to being used. The exception is the mov instruction, which can
take a 64-bit immediate when the destination is a 64-bit register.
All unsized immediate values in BITS 64 in Yasm default
to 32-bit size for consistency. In order to get a 64-bit immediate with a label, specify
the size explicitly with the QWORD keyword. For ease of use,
Yasm will also try to recognize 64-bit values and change the size to 64 bits
automatically for these cases.
Examples in NASM syntax:
add rax, 1 ; optimized down to signed 8-bit
add rax, dword 1 ; force size to 32-bit
add rax, 0xffffffff ; sign-extended 32-bit
add rax, -1 ; same as above
add rax, 0xffffffffffffffff ; truncated to 32-bit (warning)
mov eax, 1 ; 5 byte
mov rax, 1 ; 5 byte (optimized to signed 32-bit)
mov rax, qword 1 ; 10 byte (forced 64-bit)
mov rbx, 0x1234567890abcdef ; 10 byte
mov rcx, 0xffffffff ; 10 byte (does not fit in signed 32-bit)
mov ecx, -1 ; 5 byte, equivalent to above
mov rcx, sym ; 5 byte, 32-bit size default for symbols
mov rcx, qword sym ; 10 byte, override default size
A caution for users using both Yasm and NASM 2.x: the handling of mov reg64, unsized immediate is different between Yasm and NASM 2.x; YASM follows the above behavior, while NASM 2.x does the following:
add rax, 0xffffffff ; sign-extended 32-bit immediate
add rax, -1 ; same as above
add rax, 0xffffffffffffffff ; truncated 32-bit (warning)
add rax, sym ; sign-extended 32-bit immediate
mov eax, 1 ; 5 byte (32-bit immediate)
mov rax, 1 ; 10 byte (64-bit immediate)
mov rbx, 0x1234567890abcdef ; 10 byte instruction
mov rcx, 0xffffffff ; 10 byte instruction
mov ecx, -1 ; 5 byte, equivalent to above
mov ecx, sym ; 5 byte (32-bit immediate)
mov rcx, sym ; 10 byte (64-bit immediate)
mov rcx, qword sym ; 10 byte, same as above
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,
Q or O, and B for hex, octal, and binary, or you can prefix 0x for hex in the style of C, or you can prefix $ for hex in the style of Borland Pascal. Note, though, that the
$ prefix does double duty as a prefix on identifiers (see Section 2.1), so a
hex number prefixed with a $ sign must have a digit after
the $ rather than a letter.
Some examples:
mov ax,100 ; decimal
mov ax,0a2h ; hex
mov ax,$0a2 ; hex again: the 0 is required
mov ax,0xa2 ; hex yet again
mov ax,777q ; octal
mov ax,777o ; octal again
mov ax,10010011b ; binary
A character constant consists of up to four characters enclosed in either single or double quotes. The type of quote makes no difference to NASM, except of course that surrounding the constant with single quotes allows double quotes to appear within it and vice versa.
A character constant with more than one character 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 only acceptable to some pseudo-instructions, namely the DB family and INCBIN.
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 as an operand to db, a constant like
'ab' is treated as a string constant despite being 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.
Floating-point constants are acceptable only as arguments to DW, DD, DQ and DT. They 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.
Some examples:
dw -0.5 ; IEEE half precision
dd 1.2 ; an easy one
dq 1.e10 ; 10,000,000,000
dq 1.e+10 ; synonymous with 1.e10
dq 1.e-10 ; 0.000 000 000 1
dt 3.141592653589793238462 ; pi
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.
Expressions in NASM are similar in syntax to those in C.
NASM does not guarantee the size of the integers used to evaluate expressions at compile time: since NASM can compile and run on 64-bit systems quite happily, don't assume that expressions are evaluated in 32-bit registers and so try to make deliberate use of integer overflow. It might not always work. The only thing NASM will guarantee is what's guaranteed by ANSI C: you always have at least 32 bits to work in.
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.
The | operator gives a bitwise OR, exactly as performed
by the OR machine instruction. Bitwise OR is the
lowest-priority arithmetic operator supported by NASM.
<< gives a bit-shift to the left, just as it does
in C. So 5<<3 evaluates to 5 times 8, or 40. >> gives a bit-shift to the right; in NASM, such a shift is
always unsigned, so that the bits shifted in from
the left-hand end are filled with zero rather than a sign-extension of the previous
highest bit.
* 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.
NASM, like ANSI C, provides no guarantees about the sensible operation of the signed modulo operator.
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.
The highest-priority operators in NASM's expression grammar are those which only apply
to one argument. - negates its operand, + does nothing (it's provided for symmetry with -), ~ computes the one's complement
of its operand, and SEG provides the segment address of its
operand (explained in more detail in Section 2.7).
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 returns 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.
When assembling with the optimizer set to level 2 or higher, NASM will use size
specifiers (BYTE, WORD, DWORD, QWORD, or TWORD), 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.
A limitation of NASM is that it is a two-pass assembler; unlike TASM and others, it will always do exactly two assembly passes. Therefore it is unable to cope with source files that are complex enough to require three or more passes.
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; for the same reason, the
arguments to the RESB family of pseudo-instructions are also
critical expressions.
Critical expressions can crop up in other contexts as well: consider the following code.
mov ax, symbol1
symbol1 equ symbol2
symbol2:
On the first pass, NASM cannot determine the value of symbol1, because symbol1 is defined
to be equal to symbol2 which NASM hasn't seen yet. On the
second pass, therefore, when it encounters the line mov
ax,symbol1, it is unable to generate the code for it because it still doesn't know
the value of symbol1. On the next line, it would see the
EQU again and be able to determine the value of symbol1, but by then it would be too late.
NASM avoids this problem by defining the right-hand side of an EQU statement to be a critical expression, so the definition of
symbol1 would be rejected in the first pass.
There is a related issue involving forward references: consider this code fragment.
mov eax, [ebx+offset]
offset equ 10
NASM, on pass one, must calculate the size of the instruction mov eax,[ebx+offset] without knowing the value of offset. It has no way of knowing that offset is small enough to fit into a one-byte offset field and
that it could therefore get away with generating a shorter form of the effective-address
encoding; for all it knows, in pass one, offset could be a
symbol in the code segment, and it might need the full four-byte form. So it is forced to
compute the size of the instruction to accommodate a four-byte address part. In pass two,
having made this decision, it is now forced to honour it and keep the instruction large,
so the code generated in this case is not as small as it could have been. This problem
can be solved by defining offset before using it, or by
forcing byte size in the effective address by coding [byte
ebx+offset].
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.
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.
Table of Contents
%0: Macro Parameter Counter%rotate: Rotating Macro Parameters