Yasm Manual PDF
Yasm Manual PDF
Yasm Manual PDF
Peter Johnson
October 6, 2014
Yasm User Manual
by Peter Johnson
Published 2009
Copyright © 2006, 2007, 2008, 2009 Peter Johnson
ii
Contents
I Using Yasm 3
1 Running Yasm 5
1.1 yasm Synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.1 General Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.1.1 -a arch or --arch=arch: Select target architecture . . . . . . . . . . . . . . 5
1.3.1.2 -f format or --oformat=format: Select object format . . . . . . . . . . . . 5
1.3.1.3 -g debug or --dformat=debug : Select debugging format . . . . . . . . . . 5
1.3.1.4 -h or --help: Print a summary of options . . . . . . . . . . . . . . . . . . . 6
1.3.1.5 -L list or --lformat=list: Select list file format . . . . . . . . . . . . . . 6
1.3.1.6 -l listfile or --list=listfile: Specify list filename . . . . . . . . . . . 6
1.3.1.7 -m machine or --machine=machine: Select target machine architecture . . 6
1.3.1.8 -o filename or --objfile=filename: Specify object filename . . . . . . . 6
1.3.1.9 -p parser or --parser=parser : Select parser . . . . . . . . . . . . . . . . 6
1.3.1.10 -r preproc or --preproc=preproc: Select preprocessor . . . . . . . . . . 6
1.3.1.11 --version: Get the Yasm version . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.2 Warning Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.2.1 -w: Inhibit all warning messages . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.2.2 -Werror: Treat warnings as errors . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.2.3 -Wno-unrecognized-char: Do not warn on unrecognized input characters 7
1.3.2.4 -Worphan-labels: Warn on labels lacking a trailing colon . . . . . . . . . 7
1.3.2.5 -X style: Change error/warning reporting style . . . . . . . . . . . . . . . 7
1.3.3 Preprocessor Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.3.1 -D macro[=value]: Pre-define a macro . . . . . . . . . . . . . . . . . . . . . 7
1.3.3.2 -e or --preproc-only: Only preprocess . . . . . . . . . . . . . . . . . . . . 7
1.3.3.3 -I path: Add include file path . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.3.4 -P filename: Pre-include a file . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.3.5 -U macro: Undefine a macro . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Supported Target Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5 Supported Parsers (Syntaxes) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6 Supported Object Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7 Supported Debugging Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
II NASM Syntax 13
3 The NASM Language 17
3.1 Layout of a NASM Source Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2 Pseudo-Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2.1 DB and Friends: Declaring Initialized Data . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2.2 RESB and Friends: Declaring Uninitialized Data . . . . . . . . . . . . . . . . . . . . . . 18
3.2.3 INCBIN: Including External Binary Files . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2.4 EQU: Defining Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
iii
CONTENTS
iv
4.7.3 Context-Local Single-Line Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.7.4 %repl: Renaming a Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.7.5 Example Use of the Context Stack: Block IFs . . . . . . . . . . . . . . . . . . . . . . . . 43
4.8 Standard Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.8.1 __YASM_MAJOR__, etc: Yasm Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.8.2 __FILE__ and __LINE__: File Name and Line Number . . . . . . . . . . . . . . . . . 45
4.8.3 __YASM_OBJFMT__ and __OUTPUT_FORMAT__: Output Object Format Keyword . . 45
4.8.4 STRUC and ENDSTRUC: Declaring Structure Data Types . . . . . . . . . . . . . . . . . . 45
4.8.5 ISTRUC, AT and IEND: Declaring Instances of Structures . . . . . . . . . . . . . . . . . 46
4.8.6 ALIGN and ALIGNB: Data Alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
IV Object Formats 61
7 bin: Flat-Form Binary Output 65
7.1 ORG: Binary Origin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.2 bin Extensions to the SECTION Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.3 bin Special Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.4 Map Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
v
CONTENTS
VI Architectures 111
21 x86 Architecture 115
21.1 Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
21.1.1 NOP Padding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
21.2 Execution Modes and Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
21.2.1 CPU Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
21.3 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
21.4 Segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Index 121
vi
List of Figures
21 x86 Architecture
21.1 x86 General Purpose Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
vii
List of Tables
21 x86 Architecture
21.1 x86 NOP Padding Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
21.2 x86 NOP CPU Directive Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
21.3 x86 CPU Feature Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
21.4 x86 CPU Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
ix
Preface
Introduction
Yasm is a 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.
License
Yasm is licensed under the 2-clause and 3-clause “revised” BSD licenses, with one exception: the Bit::Vector
module used by the mainline version of Yasm to implement its large integer and machine-independent
floating point support is triple-licensed under the Artistic license, GPL, and LGPL. The “yasm-nextgen”
codebase uses a different BSD-licensed implementation and is thus entirely under BSD-equivalent licenses.
The full text of the licenses are provided in the Yasm source distribution.
This user manual is licensed under the 2-clause BSD license.
1
Part I
Using Yasm
3
Chapter 1
Running Yasm
1.2 Description
The yasm command assembles the file infile and directs output to the file outfile if specified. If outf-
ile 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 (usu-
ally the terminal). If no errors or warnings are encountered, Yasm does not output any messages.
1.3 Options
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.
5
CHAPTER 1. RUNNING YASM
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.
6
1.3. OPTIONS
7
CHAPTER 1. RUNNING YASM
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).
x86 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.
nasm 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 II.
gas 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 III.
bin The “bin” object format produces a flat-format, non-relocatable binary file. It is appropriate for pro-
ducing 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.
coff 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.
dbg 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 par-
ticular binary representation). This object format is not intended for real use, but rather for debugging
Yasm’s internals.
elf The ELF object format really comes in three flavors: “elf32” (for 32-bit targets), “elf64” (for 64-bit tar-
gets), and “elfx32” (for x32 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.
macho The Mach-O object format really comes in two flavors: “macho32” (for 32-bit targets) and “ma-
cho64” (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.
8
1.7. SUPPORTED DEBUGGING FORMATS
rdf 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 mini-
malistic headers for ease of loading and linking. A complete toolchain (linker, librarian, and loader) is
distributed with NASM.
win32 The Win32 object format produces object files compatible with Microsoft compilers (such as Visual
Studio) that target the 32-bit x86 Windows platform. The object format itself is an extended version of
COFF.
win64 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.
xdf The XDF object format is essentially a simplified version of COFF. It’s a multi-section relocatable for-
mat that supports 64-bit physical and virtual addresses.
cv8 The CV8 debug format is used by Microsoft Visual Studio 2005 (version 8.0) and is completely un-
documented, 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.
dwarf2 The DWARF 2 debug format is a complex, well-documented standard for debugging informa-
tion. 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 nor-
mal program sections) in the object file. Yasm supports full pass-through o-
f DWARF2 debugging information (e.g. from a C compiler), and can also generate assembly-
level line number information.
null The “null” debug format is a placeholder; it adds no debugging information to the output file.
stabs 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.
9
Chapter 2
The build system used in Microsoft Visual Studio 2010 is based on MSBUILD, Microsoft’s dedicated build
management tool, a change that requires that external tools are integrated into the development environ-
ment in a new way. VSYASM has been developed to facilitate Yasm integration with Visual Studio 2010 in
a robust and efficient manner. The main difference between VSYASM and other versions is that it is capable
of assembling multiple source code files given on a single command line.
When assembling a single file VSYASM behaves in the same way as the normal yasm tool. The only
change in this case is that VSYASM doesn’t offer the pre-process only mode.
If however the VSYASM command line includes multiple source files, any output, list and map paths
given on the command line are resolved to their directory components alone and each source code file is
then assembled using these directories for the relevant outputs. Before assembly starts, any non-existent
directories needed for VSYASM outputs are recursively created. The assembly process itself stops if any file
being assembled generates errors.
The -E file command line switch can be used to send error reports to a file, in which case this file
will also include the command line used to invoke VSYASM. This provides a way to check that VSYASM is
being called correctly from the controlling Visual Studio build process.
11
CHAPTER 2. VSYASM - YASM FOR MICROSOFT VISUAL STUDIO 2010
VSYASM will then always be available in the Build Customisations dialogue. An alternative way of
doing this is to put these files in a convenient location and then add the path to this location to the “Build
Customisations Search Path” item under “VC++ Project Settings” in the Visual Studio 2010 Options dia-
logue.
12
Part II
NASM Syntax
13
The chapters in this part of the book document the NASM-compatible syntax accepted by the Yasm
“nasm” parser and preprocessor.
15
Chapter 3
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.
The instruction field may contain any machine instruction: Pentium and P6 instructions, FPU instruc-
tions, 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, de-
scribed 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 pre-
fixed by a % sign), or they can be effective addresses (see Section 3.3), constants (Section 3.5) or expressions
(Section 3.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:
17
CHAPTER 3. THE NASM LANGUAGE
Almost any floating-point instruction that references memory must use one of the prefixes DWORD, QW-
ORD, TWORD, DDQWORD, or OWORD to indicate what size of ((memory operand)) it refers to.
3.2 Pseudo-Instructions
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.
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.
18
3.3. EFFECTIVE ADDRESSES
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.6 for an expla-
nation 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 3.8).
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 (Sec-
tion 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.
19
CHAPTER 3. THE NASM LANGUAGE
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:
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. 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.
20
3.4. IMMEDIATE OPERANDS
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 5.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)
21
CHAPTER 3. THE NASM LANGUAGE
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
3.5 Constants
NASM understands four different types of constant: numeric, character, string and floating-point.
22
3.6. EXPRESSIONS
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.
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.
NASM cannot do compile-time arithmetic on floating-point constants. This is because NASM is de-
signed 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.
3.6 Expressions
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.
23
CHAPTER 3. THE NASM LANGUAGE
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.
24
3.7. STRICT: INHIBITING OPTIMIZATION
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.
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
25
CHAPTER 3. THE NASM LANGUAGE
times (label-$+1) db 0
label: db ’NOW where am I?’
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 symb-
ol1. 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 expres-
sion, 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 know-
ing 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].
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
26
3.9. LOCAL LABELS
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.
27
Chapter 4
NASM contains a powerful macro processor, which supports conditional assembly, multi-level file inclu-
sion, 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:
%define THIS_VERY_LONG_MACRO_NAME_IS_DEFINED_TO \
THIS_VALUE
When the expansion of a single-line macro contains tokens which invoke another macro, the expansion
is performed at invocation time, not at definition time. Thus the code
%define a(x) 1+b(x)
%define b(x) 2 *x
mov ax,a(8)
will evaluate in the expected way to mov ax,1+2*8, even though the macro b wasn’t defined at the
time of definition 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
29
CHAPTER 4. THE NASM PREPROCESSOR
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.
You can overload single-line macros: if you write
%define foo(x) 1+x
%define foo(x,y) 1+x*y
the preprocessor will be able to handle both types of macro call, by counting the parameters you pass;
so foo(3) will become 1+3 whereas foo(ebx,2) will become 1+ebx*2. However, if you define
%define foo bar
then no other definition of foo will be accepted: a macro with no parameters prohibits the definition of
the same name as a macro with parameters, and vice versa.
This doesn’t prevent single-line macros being redefined: you can perfectly well define a macro with
%define foo bar
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 Section 4.1.5).
You can pre-define single-line macros using the “-D” option on the Yasm command line: see Section 1.3.3.1.
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.
%xdefine isTrue 1
%xdefine isFalse isTrue
%xdefine isTrue 0
val1: db isFalse
%xdefine isTrue 1
val2: db isFalse
30
4.1. SINGLE-LINE MACROS
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.
Now, if we need to access the elements of tBIOSDA in different places, we can end up with:
mov ax,BDASTART + tBIOSDA.COM1addr
mov bx,BDASTART + tBIOSDA.COM2addr
This will become pretty ugly (and tedious) if used in many places, and can be reduced in size signifi-
cantly by using the following macro:
; Macro to access BIOS variables by their names (from tBDA):
Using this feature, we can simplify references to a lot of macros (and, in turn, reduce typing errors).
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 Section 1.3.3.5.
31
CHAPTER 4. THE NASM PREPROCESSOR
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:
%define sometext ’my string’
%strlen charcnt sometext
As in the first case, this would result in charcnt being assigned the value of 8.
In this example, mychar gets the value of ’y’. As with %strlen (see Section 4.2.1), 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.
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
32
4.3. MULTI-LINE MACROS
myfunc: prologue 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 alterna-
tive directive %imacro.
If you need to pass a comma as part of a parameter to a multi-line macro, you can do that by enclosing
the entire parameter in braces. So you could code things like
%macro silly 2
%2: db %1
%endmacro
push ebp
mov ebp,esp
%endmacro
to define an alternative form of the function prologue which allocates no local stack space.
Sometimes, however, you might want to “overload” a machine instruction; for example, you might want
to define
%macro push 2
push %1
push %2
%endmacro
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 Section 1.3.2).
33
CHAPTER 4. THE NASM PREPROCESSOR
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 ..@234-
5.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 Section 3.9. You should avoid defining
your own labels in this form (the ..@ prefix, then a number, then another period) in case they interfere with
macro-local labels.
NASM allows you to define the last parameter of a macro to be greedy, meaning that if you invoke the
macro with more parameters than it expects, all the spare parameters get lumped into the last defined one
along with the separating commas. So if you code:
%macro writefile 2+
jmp %%endstr
%%str: db %2
%%endstr:
mov dx,%%str
mov cx,%%endstr-%%str
mov bx,%1
mov ah,0x40
int 0x21
%endmacro
then the example call to writefile above will work as expected: the text before the first comma, [fil-
ehandle], is used as the first macro parameter and expanded when %1 is referred to, and all the subsequent
text is lumped into %2 and placed after the db.
The greedy nature of the macro is indicated to NASM by the use of the + sign after the parameter count
on the %macro line.
If you define a greedy macro, you are effectively telling NASM how it should expand the macro given
any number of parameters from the actual number specified up to infinity; in this case, for example, NASM
now knows what to do when it sees a call to writefile with 2, 3, 4 or more parameters. NASM will take
this into account when overloading macros, and will not allow you to define another form 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
34
4.3. MULTI-LINE MACROS
NASM provides both mechanisms for putting ((commas in macro parameters)), and you choose which
one you prefer for each macro definition.
See Section 5.3.3 for a better way to write the above macro.
writefile 2,%1
mov ax,0x4c01
int 0x21
%endmacro
This macro (which makes use of the writefile macro defined in Section 4.3.3) can be called with an
explicit error message, which it will display on the error output stream before exiting, or it can be called
with no parameters, in which case it will use the default error message supplied in the macro definition.
In general, you supply a minimum and maximum number of parameters for a macro of this type; the
minimum number of parameters are then required in the macro call, and then you provide defaults for the
optional ones. So if a macro definition began with the line
%macro foobar 1-3 eax,[ebx+2]
then it could be called with between one and three parameters, and %1 would always be taken from
the macro call. %2, if not specified by the macro call, would default to eax, and %3 if not specified would
default to [ebx+2].
You may omit parameter defaults from the macro definition, in which case the parameter default is taken
to be blank. This can be useful for macros which can take a variable number of parameters, since the %0
token (see Section 4.3.5) allows you to determine how many parameters were really passed to the macro
call.
This defaulting mechanism can be combined with the greedy-parameter mechanism; so the die macro
above could be made more powerful, and more useful, by changing the first line of the definition to
%macro die 0-1+ "Painful program death has occurred.",13,10
The maximum parameter count can be infinite, denoted by *. In this case, of course, it is impossible to
provide a full set of default parameters. Examples of this usage are shown in Section 4.3.6.
35
CHAPTER 4. THE NASM PREPROCESSOR
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 pa-
rameters are rotated to the left by that many places. If the argument to %rotate is negative, the macro
parameters are rotated to the right.
So a pair of macros to save and restore a set of registers might work as follows:
%macro multipush 1-*
%rep %0
push %1
%rotate 1
%endrep
%endmacro
This macro invokes the PUSH instruction on each of its arguments in turn, from left to right. It begins
by pushing its first argument, %1, then invokes %rotate to move all the arguments one place to the left, so
that the original second argument is now available as %1. Repeating this procedure as many times as there
were arguments (achieved by supplying %0 as the argument to %rep) causes each argument in turn to be
pushed.
Note also the use of * as the maximum parameter count, indicating that there is no upper limit on the
number of parameters you may supply to the multipush macro.
It would be convenient, when using this macro, to have a POP equivalent, which didn’t require the argu-
ments 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:
%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 ap-
pears 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.
%endmacro
keytab:
keytab_entry F1,128+1
keytab_entry F2,128+2
36
4.3. MULTI-LINE MACROS
keytab_entry Return,13
You can just as easily concatenate text on to the other end of a macro parameter, by writing %1foo.
If you need to append a digit to a macro parameter, for example defining labels foo1 and foo2 when
passed the parameter foo, you can’t code %11 because that would be taken as the eleventh macro parameter.
Instead, you must code %{1}1, which will separate the first 1 (giving the number of the macro parameter)
from the second (literal text to be concatenated to the parameter).
This concatenation can also be applied to other preprocessor in-line objects, such as macro-local labels
(Section 4.3.2) and context-local labels (Section 4.7.2). In all cases, ambiguities in syntax can be resolved by
enclosing everything after the % sign and before the literal text in braces: so %{%foo}bar concatenates the
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.)
j%-1 %%skip
ret
%%skip:
%endmacro
This macro can now be invoked using calls like retc ne, which will cause the conditional-jump in-
struction 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.
37
CHAPTER 4. THE NASM PREPROCESSOR
Or like this:
%macro bar 1-5+.nolist a,b,c,d,e,f,g,h
The %else clause is optional, as is the %elif clause. You can have more than one %elif clause as well.
Then you could use the command-line option -D DEBUG to create a version of the program which pro-
duced 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.
%else
%endmacro
38
4.4. CONDITIONAL ASSEMBLY
%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.
%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.
39
CHAPTER 4. THE NASM PREPROCESSOR
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 Section 4.3.3 can be extended to take advantage of %if-
str in the following fashion:
%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:
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).
The usual %elifXXX, %ifnXXX and %elifnXXX versions exist for each of %ifid, %ifnum and %ifstr.
%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.
40
4.5. PREPROCESSOR LOOPS
This will generate a sequence of 64 INC instructions, incrementing every word of memory from [tab-
le] to [table+126].
For more complex termination conditions, or to break out of a repeat loop part way along, you can use
the %exitrep directive to terminate the loop, like this:
fibonacci:
%assign i 0
%assign j 1
%rep 100
%if j > 65535
%exitrep
%endif
dw j
%assign k j+i
%assign i j
%assign j k
%endrep
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.
will include the contents of the file macros.mac into the source file containing the %include directive.
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 Section 1.3.3.3), 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
%ifndef MACROS_MAC
%define MACROS_MAC
41
CHAPTER 4. THE NASM PREPROCESSOR
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 Section 1.3.3.4).
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.
The directive %pop, requiring no arguments, removes the top context from the context stack and destroys
it, along with any labels associated with it.
%push repeat
%$begin:
%endmacro
%macro until 1
j%-1 %$begin
%pop
%endmacro
42
4.7. THE CONTEXT STACK
which would scan every fourth byte of a string in search of the byte in AL.
If you need to define, or access, labels local to the context below the top one on the stack, you can use
%$$foo, or %$$$foo for the context below that, and so on.
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.
%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
43
CHAPTER 4. THE NASM PREPROCESSOR
%endmacro
This code is more robust than the REPEAT and UNTIL macros given in Section 4.7.2, because it uses
conditional assembly to check that the macros are issued in the right order (for example, not calling endif
before if) and issues 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:
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.
44
4.8. STANDARD MACROS
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 gen-
erally only useful in discriminating between Yasm nightly snapshots or pre-release (e.g. release candidate)
Yasm versions.
and then pepper your code with calls to notdeadyet until you find the crash point.
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.
45
CHAPTER 4. THE NASM PREPROCESSOR
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:
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 m-
ytype.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].
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:
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:
at mt_str
db ’hello, world’
db 13,10,0
46
4.8. STANDARD MACROS
Both macros require their first argument to be a power of two; they both compute the number of addi-
tional 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 RE-
SB 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:
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.
47
Chapter 5
NASM, though it attempts to avoid the bureaucracy of assemblers like MASM and TASM, is nevertheless
forced to support a few directives. These are described in this chapter.
NASM’s directives come in two types: user-level directives and primitive directives. Typically, each di-
rective has a user-level form and a primitive form. In almost all cases, we recommend that users use the
user-level forms of the directives, which are implemented as macros which call the primitive forms.
Primitive directives are enclosed in square brackets; user-level directives are not.
In addition to the universal directives described in this chapter, each object file format can optionally
supply extra directives in order to control particular features of that file format. These format-specific direc-
tives are documented along with the formats that implement them, in Part IV.
49
CHAPTER 5. NASM ASSEMBLER DIRECTIVES
When the REX prefix is used, the processor does not know how to address the AH, BH, CH or DH (high
8-bit legacy) registers. Instead, it is possible to access the the low 8-bits of the SP, BP SI, and DI registers as
SPL, BPL, SIL, and DIL, respectively; but only when the REX prefix is used.
The BITS directive has an exactly equivalent primitive form, [BITS 16], [BITS 32], and [BITS 6-
4]. The user-level form is a macro which has no function other than to call the primitive form.
50
5.4. ABSOLUTE: DEFINING ABSOLUTE LABELS
Users may find it useful to make use of this in their own macros. For example, the writefile macro
defined in the NASM Manual can be usefully rewritten in the following more sophisticated form:
%macro writefile 2+
[section .data]
%%str: db %2
%%endstr:
__SECT__
mov dx,%%str
mov cx,%%endstr-%%str
mov bx,%1
mov ah,0x40
int 0x21
%endmacro
This form of the macro, once passed a string to output, first switches temporarily to the data section of
the file, using the primitive form of the SECTION directive so as not to modify __SECT__. It then declares
its string in the data section, and then invokes __SECT__ to switch back to whichever section the user was
previously working in. It thus avoids the need, in the previous version of the macro, to include a JMP
instruction to jump over the data, and also does not fail if, in a complicated OBJ format module, the user
could potentially be assembling the code in any of several separate code sections.
This example describes a section of the PC BIOS data area, at segment address 0x40: the above code
defines kbuf_chr to be 0x1A, kbuf_free to be 0x1C, and kbuf to be 0x1E.
The user-level form of ABSOLUTE, like that of SECTION, redefines the __SECT__ macro when it is in-
voked.
STRUC and ENDSTRUC are defined as macros which use ABSOLUTE (and also __SECT__).
ABSOLUTE doesn’t have to take an absolute constant as an argument: it can take an expression (actually,
a critical expression: see Section 3.8) and it can be a value in a segment. For example, a TSR can re-use its
setup code as run-time BSS like this:
org 100h ; it’s a .COM program
jmp setup ; setup code comes last
; the resident part of the TSR goes here
setup: ; now write the code that installs the TSR here
absolute setup
runtimevar1 resw 1
runtimevar2 resd 20
tsr_end:
This defines some variables “on top of” the setup code, so that after the setup has finished running, the
space it took up can be re-used as data storage for the running TSR. The symbol “tsr_end” can be used to
calculate the total size of the part of the TSR that needs to be made resident.
51
CHAPTER 5. NASM ASSEMBLER DIRECTIVES
Some object-file formats provide extra features to the EXTERN directive. In all cases, the extra features
are used by suffixing a colon to the symbol name followed by object-format specific text. For example, the
obj format allows you to declare that the default segment base of an external should be the group dgroup
by means of the directive
extern _variable:wrt dgroup
The primitive form of EXTERN differs from the user-level form only in that it can take only one argument
at a time: the support for multiple arguments is implemented at the preprocessor level.
You can declare the same variable as EXTERN more than once: NASM will quietly ignore the second and
later redeclarations. You can’t declare a variable as EXTERN as well as something else, though.
GLOBAL, like EXTERN, allows object formats to define private extensions by means of a colon. The elf
object format, for example, lets you specify whether global data items are functions or data:
global hashlookup:function, hashtable:data
Like EXTERN, the primitive form of GLOBAL differs from the user-level form only in that it can take only
one argument at a time.
is similar in function to
global intvar
section .bss
intvar resd 1
The difference is that if more than one module defines the same common variable, then at link time those
variables will be merged, and references to intvar in all modules will point at the same piece of memory.
52
5.8. CPU: DEFINING CPU DEPENDENCIES
Like GLOBAL and EXTERN, COMMON supports object-format specific extensions. For example, the o-
bj format allows common variables to be NEAR or FAR, and the elf format allows you to specify the
alignment requirements of a common variable:
common commvar 4:near ; works in OBJ
common intarray 100:4 ; works in ELF: 4 byte aligned
Once again, like EXTERN and GLOBAL, the primitive form of COMMON differs from the user-level form
only in that it can take only one argument at a time.
53
Part III
GAS Syntax
55
The chapters in this part of the book document the GNU AS-compatible syntax accepted by the Yasm
“gas” parser.
57
Chapter 6
TBD
To be written.
59
Part IV
Object Formats
61
The chapters in this part of the book document Yasm’s support for various object file formats.
63
Chapter 7
The bin “object format” does not produce object files: the output file produced contains only the section
data; no headers or relocations are generated. The output can be considered “plain binary”, and is useful
for operating system and boot loader development, generating MS-DOS .COM executables and .SYS device
drivers, and creating images for embedded target environments (e.g. Flash ROM).
The bin object format supports an unlimited number of named sections. See Section 7.2 for details. The
only restriction on these sections is that their storage locations in the output file cannot overlap.
When used with the x86 architecture, the bin object format starts Yasm in 16-bit mode. In order to write
native 32-bit or 64-bit code, an explicit BITS 32 or BITS 64 directive is required respectively.
bin produces an output file with no extension by default; it simply strips the extension from the input
file name. Thus the default output filename for the input file foo.asm is simply foo.
65
CHAPTER 7. BIN: FLAT-FORM BINARY OUTPUT
66
7.3. BIN SPECIAL SYMBOLS
Only one of start or follows may be specified for a section; the same restriction applies to vstart
and vfollows.
Unless otherwise specified via the use of follows or start, Yasm by default assumes the implicit
ordering given by the order of the sections in the input file. A section named .text is always the first
section. Any code which comes before an explicit SECTION directive goes into the .text section. The .t-
ext section attributes may be overridden by giving an explicit SECTION .text directive with attributes.
Also, unless otherwise specified, Yasm defaults to setting VMA=LMA. If just “valign` is specified, Yasm
just takes the LMA and aligns it to the required alignment. This may have the effect of pushing following
sections” VMAs to non-LMA addresses as well, to avoid VMA overlap.
Yasm treats nobits sections in a special way in order to minimize the size of the output file. As nobits
sections can be 0-sized in the LMA realm, but cannot be if located between two other sections (due to the
VMA=LMA default), Yasm moves all nobits sections with unspecified LMA to the end of the output file,
where they can savely have 0 LMA size and thus not take up any space in the output file. If this behavior
is not desired, a nobits section LMA (just like a progbits section) may be specified using either the
follows or start section attribute.
section.sectname.length Set to the length of the section named sectname. The length is considered
the runtime length, so “nobits` sections” length is their runtime length, not 0.
brief Includes the input and output filenames, origin (ORG value), and a brief section summary listing
the VMA and LMA start and stop addresses and the section length of every section.
sections , segments Includes a detailed list of sections, including the VMA and LMA alignment, any
“follows” settings, as well as the VMA and LMA start addresses and the section length.
symbols Includes a detailed list of all EQU values and VMA and LMA symbol locations, grouped by
section.
67
Chapter 8
69
Chapter 9
The Executable and Linkable Object Format is the primary object format for many operating systems in-
cluding FreeBSD or GNU/Linux. It appears in three forms:
Yasm only directly supports relocatable object files. Other tools, such as the GNU Linker ld, help turn
relocatable object files into the other formats. Yasm supports generation of both 32-bit and 64-bit ELF files,
called elf32 and elf64. An additional format, called elfx32, is a 32-bit ELF file that supports 64-bit
execution (instructions and registers) while limiting pointer sizes to 32-bit.
Yasm defaults to BITS 32 mode when outputting to the elf32 object format.
71
CHAPTER 9. ELF32: EXECUTABLE AND LINKABLE FORMAT 32-BIT OBJECT FILES
72
9.4. ELF EXTENSIONS TO THE GLOBAL DIRECTIVE
The directive takes two parameters; the first parameter is the symbol name, and the second is the symbol
type. The symbol type must be either function or object. An unrecognized type will cause a warning
to be generated. Example of use:
func:
ret
type func function
section .data
var dd 4
type var object
exports the global symbol hashlookup as a function and hashtable as a data object.
Optionally, you can control the ELF visibility of the symbol. Just add one of the visibility keywords:
default, internal, hidden, or protected. The default is default, of course. For example, to make
hashlookup hidden:
global hashlookup:function hidden
73
CHAPTER 9. ELF32: EXECUTABLE AND LINKABLE FORMAT 32-BIT OBJECT FILES
You can also specify the size of the data associated with the symbol, as a numeric expression (which may
involve labels, and even forward references) after the type specifier. Like this:
global hashtable:data (hashtable.end - hashtable)
hashtable:
db this,that,theother ; some data here
.end:
This makes Yasm automatically calculate the length of the table and place that information into the ELF
symbol table. The same information can be given more verbosely using the TYPE (see Section 9.3.3) and
SIZE (see Section 9.3.2) directives as follows:
global hashtable
type hashtable object
size hashtable hashtable.end - hashtable
hashtable:
db this,that,theother ; some data here
.end:
Declaring the type and size of global symbols is necessary when writing shared library code.
This declares the total size of the array to be 128 bytes, and requires that it be aligned on a 4-byte bound-
ary.
74
9.6. ELF32 SPECIAL SYMBOLS AND WRT
..plt Referring to a procedure name using wrt ..plt causes the linker to build a procedure linkage
table entry for the symbol, and the reference gives the address of the PLT entry. You can only use this
in contexts which would generate a PC-relative relocation normally (i.e. as the destination for CALL
or JMP), since ELF contains no relocation type to refer to PLT entries absolutely.
..sym Referring to a symbol name using wrt ..sym causes Yasm to write an ordinary relocation, but
instead of making the relocation relative to the start of the section and then adding on the offset to the
symbol, it will write a relocation record aimed directly at the symbol in question. The distinction is a
necessary one due to a peculiarity of the dynamic linker.
75
Chapter 10
The elf64 object format is the 64-bit version of the Executable and Linkable Object Format. As it shares
many similarities with elf32, only differences between elf32 and elf64 will be described in this chapter.
For details on elf32, see Chapter 9.
Yasm defaults to BITS 64 mode when outputting to the elf64 object format.
elf64 supports the same debug formats as elf32, however, the stabs debug format is limited to 32-bit
addresses, so dwarf2 (see Chapter 19) is the recommended debugging format.
elf64 also supports the exact same sections, section attributes, and directives as elf32. See Section 9.2
for more details on section attributes, and Section 9.3 for details on the additional directives ELF provides.
77
CHAPTER 10. ELF64: EXECUTABLE AND LINKABLE FORMAT 64-BIT OBJECT FILES
..sym As in elf32, referring to a symbol name using wrt ..sym causes Yasm to write an ordinary
relocation, but instead of making the relocation relative to the start of the section and then adding on
the offset to the symbol, it will write a relocation record aimed directly at the symbol in question. The
distinction is a necessary one due to a peculiarity of the dynamic linker.
78
Chapter 11
The elfx32 object format is the 32-bit version of the Executable and Linkable Object Format for 64-bit
execution. Similar to elf64, it allows for use of 64-bit registers and instructions, but like elf32, limits
pointers to 32 bits in size. As it shares many similarities with elf32 and elf64, only differences between
these formats and elfx32 will be described in this chapter. For details on elf32, see Chapter 9; for details
on elf64, see Chapter 10. Operating system support for elfx32 is currently less common than for elf64.
Yasm defaults to BITS 64 mode when outputting to the elfx32 object format.
elfx32 supports the same debug formats, sections, section attributes, and directives as elf32 and e-
lf64. See Section 9.2 for more details on section attributes, and Section 9.3 for details on the additional
directives ELF provides.
..gotpcrel While RIP-relative addressing allows you to encode an instruction pointer relative data ref-
erence to foo with [rel foo], it’s sometimes necessary to encode a RIP-relative reference to a linker-
generated symbol pointer for symbol foo; this is done using wrt ..gotpcrel, e.g. [rel foo wrt
..gotpcrel]. As in elf64, this relocation, combined with RIP-relative addressing, makes it pos-
sible to load an address from the ((global offset table)) using a single instruction. Note that since
RIP-relative references are limited to a signed 32-bit displacement, the GOT size accessible through
this method is limited to 2 GB.
..got As in elf64, referring to an external or global symbol using wrt ..got causes the linker to build
an entry in the GOT containing the address of the symbol, and the reference gives the distance from the
beginning of the GOT to the entry; so you can add on the address of the GOT, load from the resulting
address, and end up with the address of the symbol.
..plt As in elf64, referring to a procedure name using wrt ..plt causes the linker to build a proce-
dure linkage table entry for the symbol, and the reference gives the address of the PLT entry. You can
only use this in contexts which would generate a PC-relative relocation normally (i.e. as the destina-
tion for CALL or JMP), since ELF contains no relocation type to refer to PLT entries absolutely.
..sym As in elf64, referring to a symbol name using wrt ..sym causes Yasm to write an ordinary
relocation, but instead of making the relocation relative to the start of the section and then adding on
79
CHAPTER 11. ELFX32: ELF 32-BIT OBJECT FILES FOR 64-BIT PROCESSORS
the offset to the symbol, it will write a relocation record aimed directly at the symbol in question. The
distinction is a necessary one due to a peculiarity of the dynamic linker.
80
Chapter 12
81
Chapter 13
83
Chapter 14
85
Chapter 15
The win32 object format generates Microsoft Win32 object files for use on the 32-bit native Windows XP
(and Vista) platforms. Object files produced using this object format may be linked with 32-bit Microsoft
linkers such as Visual Studio in order to produce 32-bit PE executables.
The win32 object format provides a default output filename extension of .obj.
Note that although Microsoft say that Win32 object files follow the COFF (Common Object File Format)
standard, the object files produced by Microsoft Win32 compilers are not compatible with COFF linkers such
as DJGPP’s, and vice versa. This is due to a difference of opinion over the precise semantics of PC-relative
relocations. To produce COFF files suitable for DJGPP, use the coff output format; conversely, the coff
format does not produce object files that Win32 linkers can generate correct output from.
87
CHAPTER 15. WIN32: MICROSOFT WIN32 OBJECT FILES
The defaults assumed by Yasm if you do not specify the above qualifiers are:
Among other improvements in Windows XP SP2 and Windows Server 2003 Microsoft introduced the con-
cept of "safe structured exception handling." The general idea is to collect handlers’ entry points in a des-
ignated read-only table and have each entry point verified against this table for exceptions prior to control
being passed to the handler. In order for an executable to be created with a safe exception handler table,
each object file on the linker command line must contain a special symbol named @feat.00. If any object
file passed to the linker does not have this symbol, then the exception handler table is omitted from the
executable and thus the run-time checks will not be performed for the application. By default, the table
is omitted from the executable silently if this happens and therefore can be easily overlooked. A user can
instruct the linker to refuse to produce an executable without this table by passing the /safeseh command
line option.
As of version 1.1.0, Yasm adds this special symbol to win32 object files so its output does not fail to link
with /safeseh.
Yasm also has directives to support registering custom exception handlers. The safeseh directive in-
structs the assembler to produce appropriately formatted input data for the safe exception handler table. A
typical use case is given in Example 15.1.
88
15.2. WIN32: SAFE STRUCTURED EXCEPTION HANDLING
If an application has a safe exception handler table, attempting to execute any unregistered exception
handler will result in immediate program termination. Thus it is important to register each exception han-
dler’s entry point with the safeseh directive.
All mentions of linker in this section refer to the Microsoft linker version 7.x and later. The presence of the
@feat.00 symbol and the data for the safe exception handler table cause no backward incompatibilities
and thus "safeseh" object files generated can still be linked by earlier linker versions or by non-Microsoft
linkers.
89
Chapter 16
The win64 or x64 object format generates Microsoft Win64 object files for use on the 64-bit native Windows
XP x64 (and Vista x64) platforms. Object files produced using this object format may be linked with 64-bit
Microsoft linkers such as that in Visual Studio 2005 and 2008 in order to produce 64-bit PE32+ executables.
win64 provides a default output filename extension of .obj.
91
CHAPTER 16. WIN64: PE32+ (MICROSOFT WIN64) OBJECT FILES
Function A
R9 data
R8 data
RDX data 16 byte aligned
RCX data stack pointer
Return Address
non-volatile stack pointer
registers and after call
local variables
frame pointer
dynamic stack
space (alloca)
Function B
The first four integer function parameters are passed (in left to right order) in the registers RCX, RDX,
R8 and R9. Further integer parameters are passed on the stack by pushing them in right to left order (pa-
rameters to the left at lower addresses). Stack space is allocated for the four register parameters (“shadow
space”) but their values are not stored by the calling function so the called function must do this if neces-
sary. The called function effectively owns this space and can use it for any purpose, so the calling function
cannot rely on its contents on return. Register parameters occupy the least significant ends of registers and
shadow space must be allocated for four register parameters even if the called function doesn’t have this
many parameters.
The first four floating point parameters are passed in XMM0 to XMM3. When integer and floating point
parameters are mixed, the correspondence between parameters and registers is not changed. Hence an
integer parameter after two floating point ones will be in R8 with RCX and RDX unused.
When they are passed by value, structures and unions whose sizes are 8, 16, 32 or 64 bits are passed
as if they are integers of the same size. Arrays and larger structures and unions are passed as pointers to
memory allocated and assigned by the calling function.
The registers RAX, RCX, RDX, R8, R9, R10, R11 are volatile and can be freely used by a called function
without preserving their values (note, however, that some may be used to pass parameters). In consequence
functions cannot expect these registers to be preserved across calls to other functions.
The registers RBX, RBP, RSI, RDI, R12, R13, R14, R15, and XMM6 to XMM15 are non-volatile and must
be saved and restored by functions that use them.
Except for floating point values, which are returned in XMM0, function return values that fit in 64 bits are
92
16.2. WIN64 STRUCTURED EXCEPTION HANDLING
returned in RAX. Some 128-bit values are also passed in XMM0 but larger values are returned in memory
assigned by the calling program and pointed to by an additional “hidden” function parameter that becomes
the first parameter and pushes other parameters to the right. This pointer value must also be passed back
to the calling program in RAX when the called program returns.
93
CHAPTER 16. WIN64: PE32+ (MICROSOFT WIN64) OBJECT FILES
When a frame pointer is needed the programmer can choose which register is used (“bias” will be ex-
plained later). Although it does not have to be used for access to the allocated space, it must be assigned in
the prologue and remain unchanged during the execution of the body of the function.
If a large amount of stack space is used it is also necessary to call __chkstk with size in RAX prior to
allocating this stack space in order to add memory pages to the stack if needed (see the Microsoft Visual
Studio 2005 documentation for further details).
The matching form of the epilogue is:
The following can also be used provided that a frame pointer register has been established:
lea rsp,[r13+size-bias]
pop r13
pop r14
ret
These are the only two forms of epilogue allowed. It must start either with an add rsp,const instruc-
tion or with lea rsp,[const+fp_register]; the first form can be used either with or without a frame
pointer register but the second form requires one. These instructions are then followed by zero or more 8
byte register pops and a return instruction (which can be replaced with a limited set of jump instructions
as described in Microsoft documentation). Epilogue forms are highly restricted because this allows the ex-
ception dispatch code to locate them without the need for unwind data in addition to that provided for the
prologue.
The data on the location and length of each function prologue, on any fixed stack allocation and on any
saved non-volatile registers is recorded in special sections in the object code. Yasm provides macros to create
this data that will now be described (with examples of the way they are used).
1 but 16 byte stack alignment must be re-established when any functions are called.
2 but the function parameters in registers and on the stack must be compatible.
94
16.2. WIN64 STRUCTURED EXCEPTION HANDLING
In the second type of frame, shown in Figure 16.2, stack space is dynamically allocated with the result
that the stack pointer value is statically unpredictable and cannot be used as a base for unwind offsets. In
this situation a frame pointer register must be used to provide this base address. Here the base for unwind
offsets is the lower end of the fixed allocation area on the stack, which is typically the value of the stack
pointer when the frame register is assigned. It must be 16 byte aligned and must be assigned before any
unwind macros with offsets are used.
In order to allow the maximum amount of data to be accessed with single byte offsets (-128 to \+127)
from the frame pointer register, it is normal to offset its value towards the centre of the allocated area (the
“bias” introduced earlier). The identity of the frame pointer register and this offset, which must be a multiple
of 16 bytes, is recorded in the unwind data to allow the stack frame base address to be calculated from the
value in the frame register.
95
CHAPTER 16. WIN64: PE32+ (MICROSOFT WIN64) OBJECT FILES
[endprolog] Signals the end of the prologue; must be in the first 255 bytes of the function.
Example 16.1 shows how these primitives are used (this is based on an example provided in Microsoft
Visual Studio 2005 documentation).
proc_frame name Generates a function table entry in .pdata and unwind information in .xdata.
save_reg reg , loc Saves a non-volatile register reg at offset loc on the stack.
rex_push_reg reg Pushes a non-volatile register reg on the stack using a 2 byte push instruction.
save_xmm128 reg , loc Saves a non-volatile XMM register reg at offset loc on the stack.
96
16.2. WIN64 STRUCTURED EXCEPTION HANDLING
set_frame reg , loc Sets the frame register reg to offset loc on the stack.
push_rex_eflags Pushes the eflags register using a 2 byte push instruction (allows hot patching).
push_frame code Pushes a 40 byte frame and an optional 8 byte error code onto the stack.
97
Chapter 17
99
Part V
Debugging Formats
101
The chapters in this part of the book document Yasm’s support for various debugging formats.
103
Chapter 18
105
Chapter 19
107
Chapter 20
109
Part VI
Architectures
111
The chapters in this part of the book document Yasm’s support for various instruction set architectures.
113
Chapter 21
x86 Architecture
The x86 architecture is the generic name for a multi-vendor 16-bit, 32-bit, and most recently 64-bit architec-
ture. It was originally developed by Intel in the 8086 series of CPU, extended to 32-bit by Intel in the 80386
CPU, and extended by AMD to 64 bits in the Opteron and Athlon 64 CPU lines. While as of 2007, Intel and
AMD are the highest volume manufacturers of x86 CPUs, many other vendors have also manufactured x86
CPUs. Generally the manufacturers have cross-licensed (or copied) major improvements to the architecture,
but there are some unique features present in many of the implementations.
21.1 Instructions
The x86 architecture has a variable instruction size that allows for moderate code compression while also
allowing for very complex operand combinations as well as a very large instruction set size with many
extensions. Instructions generally vary from zero to three operands with only a single memory operand
allowed.
115
CHAPTER 21. X86 ARCHITECTURE
are instead indexes into a descriptor table that contains the physical base and size of the segment. 32-bit
protected mode allows paging and virtual memory as well as a 32-bit rather than a 16-bit offset.
The 16-bit and 32-bit operating modes both allow for use of both 16-bit and 32-bit registers via instruction
prefixes that set the operation and address size to either 16-bit or 32-bit, with the active operating mode
setting the default operation size and the “other” size being flagged with a prefix. These operation and
address sizes also affect the size of immediate operands: for example, an instruction with a 32-bit operation
size with an immediate operand will have a 32-bit value in the encoded instruction, excepting optimizations
such as sign-extended 8-bit values.
Unlike the 16-bit and 32-bit modes, 64-bit long mode is more of a break from the “legacy” modes. Long
mode obsoletes several instructions. It is also the only mode in which 64-bit registers are available; 64-bit
registers cannot be accessed from either 16-bit or 32-bit mode. Also, unlike the other modes, most encoded
values in long mode are limited to 32 bits in size. A small subset of the MOV instructions allow 64 bit encoded
values, but values greater than 32 bits in other instructions must come from a register. Partly due to this
limitation, but also due to the wide use of relocatable shared libraries, long mode also adds a new addressing
mode: RIP-relative.
116
21.2. EXECUTION MODES AND EXTENSIONS
117
CHAPTER 21. X86 ARCHITECTURE
118
21.3. REGISTERS
The default CPU setting is for the latest processor and all feature flags to be enabled; e.g. all x86 instruc-
tions for any processor, including all instruction set extensions and 64-bit instructions.
21.3 Registers
The 64-bit x86 register set consists of 16 general purpose registers, only 8 of which are available in 16-bit and
32-bit mode. The core eight 16-bit registers are AX, BX, CX, DX, SI, DI, BP, and SP. The least significant 8 bits
of the first four of these registers are accessible via the AL, BL, CL, and DL in all execution modes. In 64-bit
mode, the least significant 8 bits of the other four of these registers are also accessible; these are named SIL,
DIL, SPL, and BPL. The most significant 8 bits of the first four 16-bit registers are also available, although
there are some restrictions on when they can be used in 64-bit mode; these are named AH, BH, CH, and DH.
The 80386 extended these registers to 32 bits while retaining all of the 16-bit and 8-bit names that were
available in 16-bit mode. The new extended registers are denoted by adding a E prefix; thus the core eight
32-bit registers are named EAX, EBX, ECX, EDX, ESI, EDI, EBP, and ESP. The original 8-bit and 16-bit register
names map into the least significant portion of the 32-bit registers.
64-bit long mode further extended these registers to 64 bits in size by adding a R prefix to the 16-bit
name; thus the base eight 64-bit registers are named RAX, RBX, etc. Long mode also added eight extra
registers named numerically r8 through r15. The least significant 32 bits of these registers are available via
a d suffix (r8d through r15d), the least significant 16 bits via a w suffix (r8w through r15w), and the least
significant 8 bits via a b suffix (r8b through r15b).
Figure 21.1 summarizes the full 64-bit x86 general purpose register set.
21.4 Segmentation
119
Index
_ %%, 34
!=, 39 %% operator, 24
* operator, 24 %assign, 31
+ modifier, 34 %clear, 44
+ operator %define, 29
binary, 24 %elif, 38, 39
unary, 24 %elifctx, 39
- operator %elifdef, 38
binary, 24 %elifid, 40
unary, 24 %elifidn, 39
--mapfile, 67 %elifidni, 39
-P, 42 %elifmacro, 39
-f, 45 %elifnctx, 39
..@, 34 %elifndef, 38
..@ symbol prefix, 27 %elifnid, 40
..got, 74, 77, 79 %elifnidn, 39
..gotoff, 74 %elifnidni, 39
..gotpc, 74 %elifnmacro, 39
..gotpcrel, 77, 79 %elifnnum, 40
..plt, 74, 77, 79 %elifnstr, 40
..sym, 74, 77, 79 %elifnum, 40
.COM, 65 %elifstr, 40
.SYS, 65 %else, 38
.comment, 72 %endrep, 41
.drectve, 87 %error, 40
.nolist, 37 %exitrep, 41
.obj, 87 %iassign, 31
.pdata, 91 %idefine, 29
.xdata, 91 %if, 38, 39
/ operator, 24 %ifctx, 39, 43
// operator, 24 %ifdef, 38
<, 39 %ifid, 40
<< operator, 24 %ifidn, 39
<=, 39 %ifidni, 39
<>, 39 %ifmacro, 38
=, 39 %ifnctx, 39
==, 39 %ifndef, 38
>, 39 %ifnid, 40
>=, 39 %ifnidn, 39
>> operator, 24 %ifnidni, 39
?, 18 %ifnmacro, 39
[MAP], 67 %ifnnum, 40
$ %ifnstr, 40
here, 23 %ifnum, 40
prefix, 17, 22 %ifstr, 40
$$, 24, 74 %imacro, 32
% operator, 24 %include, 41
%+, 31 %macro, 32
%+1, 37 %pop, 42
%-1, 37 %push, 42
%0, 35 %rep, 19, 41
%$, 42 %repl, 43
%$$, 43 %rotate, 36
121
INDEX
122
INDEX
123
INDEX
macho precedence, 24
macho32, 81 preferred, 24
macho64, 83 prefix, 17, 22
macho32, 81 preprocessor, 19
macho64, 83 Preprocessor Loops, 41
macro processor, 29 Preprocessor Variables, 31
Macro-Local Labels, 34 primitive directives, 49
macros, 19 procedure linkage table, 75, 77, 79
Map file, 67 Processor Mode, 49
memory reference, 19 protected, 73
Microsoft Visual Studio 2010, 11 pseudo-instructions, 18
modulo operators, 24 PUBLIC, 52
MSBUILD, 11 pure binary, 65
multi-line macro existence, 38
Multi-Line Macros, 32 Q
multi-line macros, 33 QWORD, 18
multiplication, 24
multipush, 36 R
rdf, 85
N RDOFF, 85
NOP, 115 REL, 21, 50
NOSPLIT, 20 relational operators, 39
numeric constant, 18 Relocatable Dynamic Object File Format, 85
Numeric Constants, 22 relocations
PIC-specific, 74, 77, 79
O removing contexts, 42
orphan-labels, 17 renaming contexts, 43
object, 73 Repeating, 19
octal, 22 repeating code, 41
of common variables, 74 RESB, 18, 26
of symbols, 72, 73 RESD, 18
omitted parameters, 35 RESDQ, 18
one’s complement, 24 RESO, 18
operand-size prefixes, 17 RESQ, 18
operands, 17 REST, 18
operators, 24 RESW, 18
ORG, 65 REX, 49
Origin, 65 RIP, 21
overlapping segments, 25 Rotating Macro Parameters, 35
overloading
multi-line macros, 33 S
single-line macros, 30 searching for include files, 41
OWORD, 18 SECTION, 50, 71, 87
win32 extensions to, 87
P section alignment
padding, 115 in win32, 87
paradox, 25 section.length, 67
passes, 25 section.start, 67
PE, 87 section.vstart, 67
PE32+, 91 SEG, 24
period, 26 segment address, 24
PIC, 74, 77 segment override, 17
PIC-specific, 74, 77, 79 segmentation
PLT, 75, 77, 79 x86, 119
Position-Independent Code, 74, 77, 79 segments, 24
pre-define, 30 shift command, 35
124
INDEX
125