Sophie

Sophie

distrib > Mageia > 7 > armv7hl > media > core-updates > by-pkgid > 9c6628ec96677114f22603950625f2bc > files > 16

nasm-doc-2.14.02-1.mga7.armv7hl.rpm

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>NASM - The Netwide Assembler</title>
<link href="nasmdoc.css" rel="stylesheet" type="text/css" />
<link href="local.css" rel="stylesheet" type="text/css" />
</head>
<body>
<ul class="navbar">
<li class="first"><a class="prev" href="nasmdoc6.html">Chapter 6</a></li>
<li><a class="next" href="nasmdoc8.html">Chapter 8</a></li>
<li><a class="toc" href="nasmdoc0.html">Contents</a></li>
<li class="last"><a class="index" href="nasmdoci.html">Index</a></li>
</ul>
<div class="title">
<h1>NASM - The Netwide Assembler</h1>
<span class="subtitle">version 2.14.02</span>
</div>
<div class="contents"
>
<h2 id="chapter-7">Chapter 7: Output Formats</h2>
<p>NASM is a portable assembler, designed to be able to compile on any ANSI
C-supporting platform and produce output to run on a variety of Intel x86
operating systems. For this reason, it has a large number of available
output formats, selected using the <code>-f</code> option on the NASM
command line. Each of these formats, along with its extensions to the base
NASM syntax, is detailed in this chapter.</p>
<p>As stated in <a href="nasmdoc2.html#section-2.1.1">section 2.1.1</a>,
NASM chooses a default name for your output file based on the input file
name and the chosen output format. This will be generated by removing the
extension (<code>.asm</code>, <code>.s</code>, or whatever you like to use)
from the input file name, and substituting an extension defined by the
output format. The extensions are given with each format below.</p>
<h3 id="section-7.1">7.1 <code>bin</code>: Flat-Form Binary Output</h3>
<p>The <code>bin</code> format does not produce object files: it generates
nothing in the output file except the code you wrote. Such `pure binary'
files are used by MS-DOS: <code>.COM</code> executables and
<code>.SYS</code> device drivers are pure binary files. Pure binary output
is also useful for operating system and boot loader development.</p>
<p>The <code>bin</code> format supports multiple section names. For details
of how NASM handles sections in the <code>bin</code> format, see
<a href="#section-7.1.3">section 7.1.3</a>.</p>
<p>Using the <code>bin</code> format puts NASM by default into 16-bit mode
(see <a href="nasmdoc6.html#section-6.1">section 6.1</a>). In order to use
<code>bin</code> to write 32-bit or 64-bit code, such as an OS kernel, you
need to explicitly issue the <code>BITS 32</code> or <code>BITS 64</code>
directive.</p>
<p><code>bin</code> has no default output file name extension: instead, it
leaves your file name as it is once the original extension has been
removed. Thus, the default is for NASM to assemble <code>binprog.asm</code>
into a binary file called <code>binprog</code>.</p>
<h4 id="section-7.1.1">7.1.1 <code>ORG</code>: Binary File Program Origin</h4>
<p>The <code>bin</code> format provides an additional directive to the list
given in <a href="nasmdoc6.html">chapter 6</a>: <code>ORG</code>. The
function of the <code>ORG</code> directive is to specify the origin address
which NASM will assume the program begins at when it is loaded into memory.</p>
<p>For example, the following code will generate the longword
<code>0x00000104</code>:</p>
<pre>
        org     0x100 
        dd      label 
label:
</pre>
<p>Unlike the <code>ORG</code> directive provided by MASM-compatible
assemblers, which allows you to jump around in the object file and
overwrite code you have already generated, NASM's <code>ORG</code> does
exactly what the directive says: <em>origin</em>. Its sole function is to
specify one offset which is added to all internal address references within
the section; it does not permit any of the trickery that MASM's version
does. See <a href="nasmdo12.html#section-12.1.3">section 12.1.3</a> for
further comments.</p>
<h4 id="section-7.1.2">7.1.2 <code>bin</code> Extensions to the <code>SECTION</code> Directive</h4>
<p>The <code>bin</code> output format extends the <code>SECTION</code> (or
<code>SEGMENT</code>) directive to allow you to specify the alignment
requirements of segments. This is done by appending the <code>ALIGN</code>
qualifier to the end of the section-definition line. For example,</p>
<pre>
section .data   align=16
</pre>
<p>switches to the section <code>.data</code> and also specifies that it
must be aligned on a 16-byte boundary.</p>
<p>The parameter to <code>ALIGN</code> specifies how many low bits of the
section start address must be forced to zero. The alignment value given may
be any power of two.</p>
<h4 id="section-7.1.3">7.1.3 Multisection Support for the <code>bin</code> Format</h4>
<p>The <code>bin</code> format allows the use of multiple sections, of
arbitrary names, besides the "known" <code>.text</code>,
<code>.data</code>, and <code>.bss</code> names.</p>
<ul>
<li>
<p>Sections may be designated <code>progbits</code> or <code>nobits</code>.
Default is <code>progbits</code> (except <code>.bss</code>, which defaults
to <code>nobits</code>, of course).</p>
</li>
<li>
<p>Sections can be aligned at a specified boundary following the previous
section with <code>align=</code>, or at an arbitrary byte-granular position
with <code>start=</code>.</p>
</li>
<li>
<p>Sections can be given a virtual start address, which will be used for
the calculation of all memory references within that section with
<code>vstart=</code>.</p>
</li>
<li>
<p>Sections can be ordered using
<code>follows=</code><code>&lt;section&gt;</code> or
<code>vfollows=</code><code>&lt;section&gt;</code> as an alternative to
specifying an explicit start address.</p>
</li>
<li>
<p>Arguments to <code>org</code>, <code>start</code>, <code>vstart</code>,
and <code>align=</code> are critical expressions. See
<a href="nasmdoc3.html#section-3.8">section 3.8</a>. E.g.
<code>align=(1 &lt;&lt; ALIGN_SHIFT)</code> &ndash;
<code>ALIGN_SHIFT</code> must be defined before it is used here.</p>
</li>
<li>
<p>Any code which comes before an explicit <code>SECTION</code> directive
is directed by default into the <code>.text</code> section.</p>
</li>
<li>
<p>If an <code>ORG</code> statement is not given, <code>ORG 0</code> is
used by default.</p>
</li>
<li>
<p>The <code>.bss</code> section will be placed after the last
<code>progbits</code> section, unless <code>start=</code>,
<code>vstart=</code>, <code>follows=</code>, or <code>vfollows=</code> has
been specified.</p>
</li>
<li>
<p>All sections are aligned on dword boundaries, unless a different
alignment has been specified.</p>
</li>
<li>
<p>Sections may not overlap.</p>
</li>
<li>
<p>NASM creates the <code>section.&lt;secname&gt;.start</code> for each
section, which may be used in your code.</p>
</li>
</ul>
<h4 id="section-7.1.4">7.1.4 Map Files</h4>
<p>Map files can be generated in <code>-f bin</code> format by means of the
<code>[map]</code> option. Map types of <code>all</code> (default),
<code>brief</code>, <code>sections</code>, <code>segments</code>, or
<code>symbols</code> may be specified. Output may be directed to
<code>stdout</code> (default), <code>stderr</code>, or a specified file.
E.g. <code>[map symbols myfile.map]</code>. No "user form" exists, the
square brackets must be used.</p>
<h3 id="section-7.2">7.2 <code>ith</code>: Intel Hex Output</h3>
<p>The <code>ith</code> file format produces Intel hex-format files. Just
as the <code>bin</code> format, this is a flat memory image format with no
support for relocation or linking. It is usually used with ROM programmers
and similar utilities.</p>
<p>All extensions supported by the <code>bin</code> file format is also
supported by the <code>ith</code> file format.</p>
<p><code>ith</code> provides a default output file-name extension of
<code>.ith</code>.</p>
<h3 id="section-7.3">7.3 <code>srec</code>: Motorola S-Records Output</h3>
<p>The <code>srec</code> file format produces Motorola S-records files.
Just as the <code>bin</code> format, this is a flat memory image format
with no support for relocation or linking. It is usually used with ROM
programmers and similar utilities.</p>
<p>All extensions supported by the <code>bin</code> file format is also
supported by the <code>srec</code> file format.</p>
<p><code>srec</code> provides a default output file-name extension of
<code>.srec</code>.</p>
<h3 id="section-7.4">7.4 <code>obj</code>: Microsoft OMF Object Files</h3>
<p>The <code>obj</code> file format (NASM calls it <code>obj</code> rather
than <code>omf</code> for historical reasons) is the one produced by MASM
and TASM, which is typically fed to 16-bit DOS linkers to produce
<code>.EXE</code> files. It is also the format used by OS/2.</p>
<p><code>obj</code> provides a default output file-name extension of
<code>.obj</code>.</p>
<p><code>obj</code> is not exclusively a 16-bit format, though: NASM has
full support for the 32-bit extensions to the format. In particular, 32-bit
<code>obj</code> format files are used by Borland's Win32 compilers,
instead of using Microsoft's newer <code>win32</code> object file format.</p>
<p>The <code>obj</code> format does not define any special segment names:
you can call your segments anything you like. Typical names for segments in
<code>obj</code> format files are <code>CODE</code>, <code>DATA</code> and
<code>BSS</code>.</p>
<p>If your source file contains code before specifying an explicit
<code>SEGMENT</code> directive, then NASM will invent its own segment
called <code>__NASMDEFSEG</code> for you.</p>
<p>When you define a segment in an <code>obj</code> file, NASM defines the
segment name as a symbol as well, so that you can access the segment
address of the segment. So, for example:</p>
<pre>
segment data 

dvar:   dw      1234 

segment code 

function: 
        mov     ax,data         ; get segment address of data 
        mov     ds,ax           ; and move it into DS 
        inc     word [dvar]     ; now this reference will work 
        ret
</pre>
<p>The <code>obj</code> format also enables the use of the <code>SEG</code>
and <code>WRT</code> operators, so that you can write code which does
things like</p>
<pre>
extern  foo 

      mov   ax,seg foo            ; get preferred segment of foo 
      mov   ds,ax 
      mov   ax,data               ; a different segment 
      mov   es,ax 
      mov   ax,[ds:foo]           ; this accesses `foo' 
      mov   [es:foo wrt data],bx  ; so does this
</pre>
<h4 id="section-7.4.1">7.4.1 <code>obj</code> Extensions to the <code>SEGMENT</code> Directive</h4>
<p>The <code>obj</code> output format extends the <code>SEGMENT</code> (or
<code>SECTION</code>) directive to allow you to specify various properties
of the segment you are defining. This is done by appending extra qualifiers
to the end of the segment-definition line. For example,</p>
<pre>
segment code private align=16
</pre>
<p>defines the segment <code>code</code>, but also declares it to be a
private segment, and requires that the portion of it described in this code
module must be aligned on a 16-byte boundary.</p>
<p>The available qualifiers are:</p>
<ul>
<li>
<p><code>PRIVATE</code>, <code>PUBLIC</code>, <code>COMMON</code> and
<code>STACK</code> specify the combination characteristics of the segment.
<code>PRIVATE</code> segments do not get combined with any others by the
linker; <code>PUBLIC</code> and <code>STACK</code> segments get
concatenated together at link time; and <code>COMMON</code> segments all
get overlaid on top of each other rather than stuck end-to-end.</p>
</li>
<li>
<p><code>ALIGN</code> is used, as shown above, to specify how many low bits
of the segment start address must be forced to zero. The alignment value
given may be any power of two from 1 to 4096; in reality, the only values
supported are 1, 2, 4, 16, 256 and 4096, so if 8 is specified it will be
rounded up to 16, and 32, 64 and 128 will all be rounded up to 256, and so
on. Note that alignment to 4096-byte boundaries is a PharLap extension to
the format and may not be supported by all linkers.</p>
</li>
<li>
<p><code>CLASS</code> can be used to specify the segment class; this
feature indicates to the linker that segments of the same class should be
placed near each other in the output file. The class name can be any word,
e.g. <code>CLASS=CODE</code>.</p>
</li>
<li>
<p><code>OVERLAY</code>, like <code>CLASS</code>, is specified with an
arbitrary word as an argument, and provides overlay information to an
overlay-capable linker.</p>
</li>
<li>
<p>Segments can be declared as <code>USE16</code> or <code>USE32</code>,
which has the effect of recording the choice in the object file and also
ensuring that NASM's default assembly mode when assembling in that segment
is 16-bit or 32-bit respectively.</p>
</li>
<li>
<p>When writing OS/2 object files, you should declare 32-bit segments as
<code>FLAT</code>, which causes the default segment base for anything in
the segment to be the special group <code>FLAT</code>, and also defines the
group if it is not already defined.</p>
</li>
<li>
<p>The <code>obj</code> file format also allows segments to be declared as
having a pre-defined absolute segment address, although no linkers are
currently known to make sensible use of this feature; nevertheless, NASM
allows you to declare a segment such as
<code>SEGMENT SCREEN ABSOLUTE=0xB800</code> if you need to. The
<code>ABSOLUTE</code> and <code>ALIGN</code> keywords are mutually
exclusive.</p>
</li>
</ul>
<p>NASM's default segment attributes are <code>PUBLIC</code>,
<code>ALIGN=1</code>, no class, no overlay, and <code>USE16</code>.</p>
<h4 id="section-7.4.2">7.4.2 <code>GROUP</code>: Defining Groups of Segments</h4>
<p>The <code>obj</code> format also allows segments to be grouped, so that
a single segment register can be used to refer to all the segments in a
group. NASM therefore supplies the <code>GROUP</code> directive, whereby
you can code</p>
<pre>
segment data 

        ; some data 

segment bss 

        ; some uninitialized data 

group dgroup data bss
</pre>
<p>which will define a group called <code>dgroup</code> to contain the
segments <code>data</code> and <code>bss</code>. Like <code>SEGMENT</code>,
<code>GROUP</code> causes the group name to be defined as a symbol, so that
you can refer to a variable <code>var</code> in the <code>data</code>
segment as <code>var wrt data</code> or as <code>var wrt dgroup</code>,
depending on which segment value is currently in your segment register.</p>
<p>If you just refer to <code>var</code>, however, and <code>var</code> is
declared in a segment which is part of a group, then NASM will default to
giving you the offset of <code>var</code> from the beginning of the
<em>group</em>, not the <em>segment</em>. Therefore <code>SEG var</code>,
also, will return the group base rather than the segment base.</p>
<p>NASM will allow a segment to be part of more than one group, but will
generate a warning if you do this. Variables declared in a segment which is
part of more than one group will default to being relative to the first
group that was defined to contain the segment.</p>
<p>A group does not have to contain any segments; you can still make
<code>WRT</code> references to a group which does not contain the variable
you are referring to. OS/2, for example, defines the special group
<code>FLAT</code> with no segments in it.</p>
<h4 id="section-7.4.3">7.4.3 <code>UPPERCASE</code>: Disabling Case Sensitivity in Output</h4>
<p>Although NASM itself is case sensitive, some OMF linkers are not;
therefore it can be useful for NASM to output single-case object files. The
<code>UPPERCASE</code> format-specific directive causes all segment, group
and symbol names that are written to the object file to be forced to upper
case just before being written. Within a source file, NASM is still
case-sensitive; but the object file can be written entirely in upper case
if desired.</p>
<p><code>UPPERCASE</code> is used alone on a line; it requires no
parameters.</p>
<h4 id="section-7.4.4">7.4.4 <code>IMPORT</code>: Importing DLL Symbols</h4>
<p>The <code>IMPORT</code> format-specific directive defines a symbol to be
imported from a DLL, for use if you are writing a DLL's import library in
NASM. You still need to declare the symbol as <code>EXTERN</code> as well
as using the <code>IMPORT</code> directive.</p>
<p>The <code>IMPORT</code> directive takes two required parameters,
separated by white space, which are (respectively) the name of the symbol
you wish to import and the name of the library you wish to import it from.
For example:</p>
<pre>
    import  WSAStartup wsock32.dll
</pre>
<p>A third optional parameter gives the name by which the symbol is known
in the library you are importing it from, in case this is not the same as
the name you wish the symbol to be known by to your code once you have
imported it. For example:</p>
<pre>
    import  asyncsel wsock32.dll WSAAsyncSelect
</pre>
<h4 id="section-7.4.5">7.4.5 <code>EXPORT</code>: Exporting DLL Symbols</h4>
<p>The <code>EXPORT</code> format-specific directive defines a global
symbol to be exported as a DLL symbol, for use if you are writing a DLL in
NASM. You still need to declare the symbol as <code>GLOBAL</code> as well
as using the <code>EXPORT</code> directive.</p>
<p><code>EXPORT</code> takes one required parameter, which is the name of
the symbol you wish to export, as it was defined in your source file. An
optional second parameter (separated by white space from the first) gives
the <em>external</em> name of the symbol: the name by which you wish the
symbol to be known to programs using the DLL. If this name is the same as
the internal name, you may leave the second parameter off.</p>
<p>Further parameters can be given to define attributes of the exported
symbol. These parameters, like the second, are separated by white space. If
further parameters are given, the external name must also be specified,
even if it is the same as the internal name. The available attributes are:</p>
<ul>
<li>
<p><code>resident</code> indicates that the exported name is to be kept
resident by the system loader. This is an optimisation for frequently used
symbols imported by name.</p>
</li>
<li>
<p><code>nodata</code> indicates that the exported symbol is a function
which does not make use of any initialized data.</p>
</li>
<li>
<p><code>parm=NNN</code>, where <code>NNN</code> is an integer, sets the
number of parameter words for the case in which the symbol is a call gate
between 32-bit and 16-bit segments.</p>
</li>
<li>
<p>An attribute which is just a number indicates that the symbol should be
exported with an identifying number (ordinal), and gives the desired
number.</p>
</li>
</ul>
<p>For example:</p>
<pre>
    export  myfunc 
    export  myfunc TheRealMoreFormalLookingFunctionName 
    export  myfunc myfunc 1234  ; export by ordinal 
    export  myfunc myfunc resident parm=23 nodata
</pre>
<h4 id="section-7.4.6">7.4.6 <code>..start</code>: Defining the Program Entry Point</h4>
<p><code>OMF</code> linkers require exactly one of the object files being
linked to define the program entry point, where execution will begin when
the program is run. If the object file that defines the entry point is
assembled using NASM, you specify the entry point by declaring the special
symbol <code>..start</code> at the point where you wish execution to begin.</p>
<h4 id="section-7.4.7">7.4.7 <code>obj</code> Extensions to the <code>EXTERN</code> Directive</h4>
<p>If you declare an external symbol with the directive</p>
<pre>
    extern  foo
</pre>
<p>then references such as <code>mov ax,foo</code> will give you the offset
of <code>foo</code> from its preferred segment base (as specified in
whichever module <code>foo</code> is actually defined in). So to access the
contents of <code>foo</code> you will usually need to do something like</p>
<pre>
        mov     ax,seg foo      ; get preferred segment base 
        mov     es,ax           ; move it into ES 
        mov     ax,[es:foo]     ; and use offset `foo' from it
</pre>
<p>This is a little unwieldy, particularly if you know that an external is
going to be accessible from a given segment or group, say
<code>dgroup</code>. So if <code>DS</code> already contained
<code>dgroup</code>, you could simply code</p>
<pre>
        mov     ax,[foo wrt dgroup]
</pre>
<p>However, having to type this every time you want to access
<code>foo</code> can be a pain; so NASM allows you to declare
<code>foo</code> in the alternative form</p>
<pre>
    extern  foo:wrt dgroup
</pre>
<p>This form causes NASM to pretend that the preferred segment base of
<code>foo</code> is in fact <code>dgroup</code>; so the expression
<code>seg foo</code> will now return <code>dgroup</code>, and the
expression <code>foo</code> is equivalent to <code>foo wrt dgroup</code>.</p>
<p>This default-<code>WRT</code> mechanism can be used to make externals
appear to be relative to any group or segment in your program. It can also
be applied to common variables: see <a href="#section-7.4.8">section
7.4.8</a>.</p>
<h4 id="section-7.4.8">7.4.8 <code>obj</code> Extensions to the <code>COMMON</code> Directive</h4>
<p>The <code>obj</code> format allows common variables to be either near or
far; NASM allows you to specify which your variables should be by the use
of the syntax</p>
<pre>
common  nearvar 2:near   ; `nearvar' is a near common 
common  farvar  10:far   ; and `farvar' is far
</pre>
<p>Far common variables may be greater in size than 64Kb, and so the OMF
specification says that they are declared as a number of <em>elements</em>
of a given size. So a 10-byte far common variable could be declared as ten
one-byte elements, five two-byte elements, two five-byte elements or one
ten-byte element.</p>
<p>Some <code>OMF</code> linkers require the element size, as well as the
variable size, to match when resolving common variables declared in more
than one module. Therefore NASM must allow you to specify the element size
on your far common variables. This is done by the following syntax:</p>
<pre>
common  c_5by2  10:far 5        ; two five-byte elements 
common  c_2by5  10:far 2        ; five two-byte elements
</pre>
<p>If no element size is specified, the default is 1. Also, the
<code>FAR</code> keyword is not required when an element size is specified,
since only far commons may have element sizes at all. So the above
declarations could equivalently be</p>
<pre>
common  c_5by2  10:5            ; two five-byte elements 
common  c_2by5  10:2            ; five two-byte elements
</pre>
<p>In addition to these extensions, the <code>COMMON</code> directive in
<code>obj</code> also supports default-<code>WRT</code> specification like
<code>EXTERN</code> does (explained in <a href="#section-7.4.7">section
7.4.7</a>). So you can also declare things like</p>
<pre>
common  foo     10:wrt dgroup 
common  bar     16:far 2:wrt data 
common  baz     24:wrt data:6
</pre>
<h4 id="section-7.4.9">7.4.9 Embedded File Dependency Information</h4>
<p>Since NASM 2.13.02, <code>obj</code> files contain embedded dependency
file information. To suppress the generation of dependencies, use</p>
<pre>
%pragma obj nodepend
</pre>
<h3 id="section-7.5">7.5 <code>win32</code>: Microsoft Win32 Object Files</h3>
<p>The <code>win32</code> output format generates Microsoft Win32 object
files, suitable for passing to Microsoft linkers such as Visual C++. Note
that Borland Win32 compilers do not use this format, but use
<code>obj</code> instead (see <a href="#section-7.4">section 7.4</a>).</p>
<p><code>win32</code> provides a default output file-name extension of
<code>.obj</code>.</p>
<p>Note that although Microsoft say that Win32 object files follow the
<code>COFF</code> (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 NASM's <code>coff</code> output format;
conversely, the <code>coff</code> format does not produce object files that
Win32 linkers can generate correct output from.</p>
<h4 id="section-7.5.1">7.5.1 <code>win32</code> Extensions to the <code>SECTION</code> Directive</h4>
<p>Like the <code>obj</code> format, <code>win32</code> allows you to
specify additional information on the <code>SECTION</code> directive line,
to control the type and properties of sections you declare. Section types
and properties are generated automatically by NASM for the standard section
names <code>.text</code>, <code>.data</code> and <code>.bss</code>, but may
still be overridden by these qualifiers.</p>
<p>The available qualifiers are:</p>
<ul>
<li>
<p><code>code</code>, or equivalently <code>text</code>, defines the
section to be a code section. This marks the section as readable and
executable, but not writable, and also indicates to the linker that the
type of the section is code.</p>
</li>
<li>
<p><code>data</code> and <code>bss</code> define the section to be a data
section, analogously to <code>code</code>. Data sections are marked as
readable and writable, but not executable. <code>data</code> declares an
initialized data section, whereas <code>bss</code> declares an
uninitialized data section.</p>
</li>
<li>
<p><code>rdata</code> declares an initialized data section that is readable
but not writable. Microsoft compilers use this section to place constants
in it.</p>
</li>
<li>
<p><code>info</code> defines the section to be an informational section,
which is not included in the executable file by the linker, but may (for
example) pass information <em>to</em> the linker. For example, declaring an
<code>info</code>&ndash;type section called <code>.drectve</code> causes
the linker to interpret the contents of the section as command-line
options.</p>
</li>
<li>
<p><code>align=</code>, used with a trailing number as in <code>obj</code>,
gives the alignment requirements of the section. The maximum you may
specify is 64: the Win32 object file format contains no means to request a
greater section alignment than this. If alignment is not explicitly
specified, the defaults are 16-byte alignment for code sections, 8-byte
alignment for rdata sections and 4-byte alignment for data (and BSS)
sections. Informational sections get a default alignment of 1 byte (no
alignment), though the value does not matter.</p>
</li>
</ul>
<p>The defaults assumed by NASM if you do not specify the above qualifiers
are:</p>
<pre>
section .text    code  align=16 
section .data    data  align=4 
section .rdata   rdata align=8 
section .bss     bss   align=4
</pre>
<p>Any other section name is treated by default like <code>.text</code>.</p>
<h4 id="section-7.5.2">7.5.2 <code>win32</code>: Safe Structured Exception Handling</h4>
<p>Among other improvements in Windows XP SP2 and Windows Server 2003
Microsoft has introduced concept of "safe structured exception handling."
General idea is to collect handlers' entry points in designated read-only
table and have alleged entry point verified against this table prior
exception control is passed to the handler. In order for an executable
module to be equipped with such "safe exception handler table," all object
modules on linker command line has to comply with certain criteria. If one
single module among them does not, then the table in question is omitted
and above mentioned run-time checks will not be performed for application
in question. Table omission is by default silent and therefore can be
easily overlooked. One can instruct linker to refuse to produce binary
without such table by passing <code>/safeseh</code> command line option.</p>
<p>Without regard to this run-time check merits it's natural to expect NASM
to be capable of generating modules suitable for <code>/safeseh</code>
linking. From developer's viewpoint the problem is two-fold:</p>
<ul>
<li>
<p>how to adapt modules not deploying exception handlers of their own;</p>
</li>
<li>
<p>how to adapt/develop modules utilizing custom exception handling;</p>
</li>
</ul>
<p>Former can be easily achieved with any NASM version by adding following
line to source code:</p>
<pre>
$@feat.00 equ 1
</pre>
<p>As of version 2.03 NASM adds this absolute symbol automatically. If it's
not already present to be precise. I.e. if for whatever reason developer
would choose to assign another value in source file, it would still be
perfectly possible.</p>
<p>Registering custom exception handler on the other hand requires certain
"magic." As of version 2.03 additional directive is implemented,
<code>safeseh</code>, which instructs the assembler to produce
appropriately formatted input data for above mentioned "safe exception
handler table." Its typical use would be:</p>
<pre>
section .text 
extern  _MessageBoxA@16 
%if     __NASM_VERSION_ID__ &gt;= 0x02030000 
safeseh handler         ; register handler as "safe handler" 
%endif 
handler: 
        push    DWORD 1 ; MB_OKCANCEL 
        push    DWORD caption 
        push    DWORD text 
        push    DWORD 0 
        call    _MessageBoxA@16 
        sub     eax,1   ; incidentally suits as return value 
                        ; for exception handler 
        ret 
global  _main 
_main: 
        push    DWORD handler 
        push    DWORD [fs:0] 
        mov     DWORD [fs:0],esp ; engage exception handler 
        xor     eax,eax 
        mov     eax,DWORD[eax]   ; cause exception 
        pop     DWORD [fs:0]     ; disengage exception handler 
        add     esp,4 
        ret 
text:   db      'OK to rethrow, CANCEL to generate core dump',0 
caption:db      'SEGV',0 

section .drectve info 
        db      '/defaultlib:user32.lib /defaultlib:msvcrt.lib '
</pre>
<p>As you might imagine, it's perfectly possible to produce .exe binary
with "safe exception handler table" and yet engage unregistered exception
handler. Indeed, handler is engaged by simply manipulating
<code>[fs:0]</code> location at run-time, something linker has no power
over, run-time that is. It should be explicitly mentioned that such failure
to register handler's entry point with <code>safeseh</code> directive has
undesired side effect at run-time. If exception is raised and unregistered
handler is to be executed, the application is abruptly terminated without
any notification whatsoever. One can argue that system could at least have
logged some kind "non-safe exception handler in x.exe at address n" message
in event log, but no, literally no notification is provided and user is
left with no clue on what caused application failure.</p>
<p>Finally, all mentions of linker in this paragraph refer to Microsoft
linker version 7.x and later. Presence of <code>@feat.00</code> symbol and
input data for "safe exception handler table" causes no backward
incompatibilities and "safeseh" modules generated by NASM 2.03 and later
can still be linked by earlier versions or non-Microsoft linkers.</p>
<h4 id="section-7.5.3">7.5.3 Debugging formats for Windows </h4>
<p>The <code>win32</code> and <code>win64</code> formats support the
Microsoft CodeView debugging format. Currently CodeView version 8 format is
supported (<code>cv8</code>), but newer versions of the CodeView debugger
should be able to handle this format as well.</p>
<h3 id="section-7.6">7.6 <code>win64</code>: Microsoft Win64 Object Files</h3>
<p>The <code>win64</code> output format generates Microsoft Win64 object
files, which is nearly 100% identical to the <code>win32</code> object
format (<a href="#section-7.5">section 7.5</a>) with the exception that it
is meant to target 64-bit code and the x86-64 platform altogether. This
object file is used exactly the same as the <code>win32</code> object
format (<a href="#section-7.5">section 7.5</a>), in NASM, with regard to
this exception.</p>
<h4 id="section-7.6.1">7.6.1 <code>win64</code>: Writing Position-Independent Code</h4>
<p>While <code>REL</code> takes good care of RIP-relative addressing, there
is one aspect that is easy to overlook for a Win64 programmer: indirect
references. Consider a switch dispatch table:</p>
<pre>
        jmp     qword [dsptch+rax*8] 
        ... 
dsptch: dq      case0 
        dq      case1 
        ...
</pre>
<p>Even a novice Win64 assembler programmer will soon realize that the code
is not 64-bit savvy. Most notably linker will refuse to link it with</p>
<pre>
'ADDR32' relocation to '.text' invalid without /LARGEADDRESSAWARE:NO
</pre>
<p>So [s]he will have to split jmp instruction as following:</p>
<pre>
        lea     rbx,[rel dsptch] 
        jmp     qword [rbx+rax*8]
</pre>
<p>What happens behind the scene is that effective address in
<code>lea</code> is encoded relative to instruction pointer, or in
perfectly position-independent manner. But this is only part of the
problem! Trouble is that in .dll context <code>caseN</code> relocations
will make their way to the final module and might have to be adjusted at
.dll load time. To be specific when it can't be loaded at preferred
address. And when this occurs, pages with such relocations will be rendered
private to current process, which kind of undermines the idea of sharing
.dll. But no worry, it's trivial to fix:</p>
<pre>
        lea     rbx,[rel dsptch] 
        add     rbx,[rbx+rax*8] 
        jmp     rbx 
        ... 
dsptch: dq      case0-dsptch 
        dq      case1-dsptch 
        ...
</pre>
<p>NASM version 2.03 and later provides another alternative,
<code>wrt ..imagebase</code> operator, which returns offset from base
address of the current image, be it .exe or .dll module, therefore the
name. For those acquainted with PE-COFF format base address denotes start
of <code>IMAGE_DOS_HEADER</code> structure. Here is how to implement switch
with these image-relative references:</p>
<pre>
        lea     rbx,[rel dsptch] 
        mov     eax,[rbx+rax*4] 
        sub     rbx,dsptch wrt ..imagebase 
        add     rbx,rax 
        jmp     rbx 
        ... 
dsptch: dd      case0 wrt ..imagebase 
        dd      case1 wrt ..imagebase
</pre>
<p>One can argue that the operator is redundant. Indeed, snippet before
last works just fine with any NASM version and is not even Windows
specific... The real reason for implementing <code>wrt ..imagebase</code>
will become apparent in next paragraph.</p>
<p>It should be noted that <code>wrt ..imagebase</code> is defined as
32-bit operand only:</p>
<pre>
        dd      label wrt ..imagebase           ; ok 
        dq      label wrt ..imagebase           ; bad 
        mov     eax,label wrt ..imagebase       ; ok 
        mov     rax,label wrt ..imagebase       ; bad
</pre>
<h4 id="section-7.6.2">7.6.2 <code>win64</code>: Structured Exception Handling</h4>
<p>Structured exception handing in Win64 is completely different matter
from Win32. Upon exception program counter value is noted, and
linker-generated table comprising start and end addresses of all the
functions [in given executable module] is traversed and compared to the
saved program counter. Thus so called <code>UNWIND_INFO</code> structure is
identified. If it's not found, then offending subroutine is assumed to be
"leaf" and just mentioned lookup procedure is attempted for its caller. In
Win64 leaf function is such function that does not call any other function
<em>nor</em> modifies any Win64 non-volatile registers, including stack
pointer. The latter ensures that it's possible to identify leaf function's
caller by simply pulling the value from the top of the stack.</p>
<p>While majority of subroutines written in assembler are not calling any
other function, requirement for non-volatile registers' immutability leaves
developer with not more than 7 registers and no stack frame, which is not
necessarily what [s]he counted with. Customarily one would meet the
requirement by saving non-volatile registers on stack and restoring them
upon return, so what can go wrong? If [and only if] an exception is raised
at run-time and no <code>UNWIND_INFO</code> structure is associated with
such "leaf" function, the stack unwind procedure will expect to find
caller's return address on the top of stack immediately followed by its
frame. Given that developer pushed caller's non-volatile registers on
stack, would the value on top point at some code segment or even
addressable space? Well, developer can attempt copying caller's return
address to the top of stack and this would actually work in some very
specific circumstances. But unless developer can guarantee that these
circumstances are always met, it's more appropriate to assume worst case
scenario, i.e. stack unwind procedure going berserk. Relevant question is
what happens then? Application is abruptly terminated without any
notification whatsoever. Just like in Win32 case, one can argue that system
could at least have logged "unwind procedure went berserk in x.exe at
address n" in event log, but no, no trace of failure is left.</p>
<p>Now, when we understand significance of the <code>UNWIND_INFO</code>
structure, let's discuss what's in it and/or how it's processed. First of
all it is checked for presence of reference to custom language-specific
exception handler. If there is one, then it's invoked. Depending on the
return value, execution flow is resumed (exception is said to be
"handled"), <em>or</em> rest of <code>UNWIND_INFO</code> structure is
processed as following. Beside optional reference to custom handler, it
carries information about current callee's stack frame and where
non-volatile registers are saved. Information is detailed enough to be able
to reconstruct contents of caller's non-volatile registers upon call to
current callee. And so caller's context is reconstructed, and then unwind
procedure is repeated, i.e. another <code>UNWIND_INFO</code> structure is
associated, this time, with caller's instruction pointer, which is then
checked for presence of reference to language-specific handler, etc. The
procedure is recursively repeated till exception is handled. As last resort
system "handles" it by generating memory core dump and terminating the
application.</p>
<p>As for the moment of this writing NASM unfortunately does not facilitate
generation of above mentioned detailed information about stack frame
layout. But as of version 2.03 it implements building blocks for generating
structures involved in stack unwinding. As simplest example, here is how to
deploy custom exception handler for leaf function:</p>
<pre>
default rel 
section .text 
extern  MessageBoxA 
handler: 
        sub     rsp,40 
        mov     rcx,0 
        lea     rdx,[text] 
        lea     r8,[caption] 
        mov     r9,1    ; MB_OKCANCEL 
        call    MessageBoxA 
        sub     eax,1   ; incidentally suits as return value 
                        ; for exception handler 
        add     rsp,40 
        ret 
global  main 
main: 
        xor     rax,rax 
        mov     rax,QWORD[rax]  ; cause exception 
        ret 
main_end: 
text:   db      'OK to rethrow, CANCEL to generate core dump',0 
caption:db      'SEGV',0 

section .pdata  rdata align=4 
        dd      main wrt ..imagebase 
        dd      main_end wrt ..imagebase 
        dd      xmain wrt ..imagebase 
section .xdata  rdata align=8 
xmain:  db      9,0,0,0 
        dd      handler wrt ..imagebase 
section .drectve info 
        db      '/defaultlib:user32.lib /defaultlib:msvcrt.lib '
</pre>
<p>What you see in <code>.pdata</code> section is element of the "table
comprising start and end addresses of function" along with reference to
associated <code>UNWIND_INFO</code> structure. And what you see in
<code>.xdata</code> section is <code>UNWIND_INFO</code> structure
describing function with no frame, but with designated exception handler.
References are <em>required</em> to be image-relative (which is the real
reason for implementing <code>wrt ..imagebase</code> operator). It should
be noted that <code>rdata align=n</code>, as well as
<code>wrt ..imagebase</code>, are optional in these two segments' contexts,
i.e. can be omitted. Latter means that <em>all</em> 32-bit references, not
only above listed required ones, placed into these two segments turn out
image-relative. Why is it important to understand? Developer is allowed to
append handler-specific data to <code>UNWIND_INFO</code> structure, and if
[s]he adds a 32-bit reference, then [s]he will have to remember to adjust
its value to obtain the real pointer.</p>
<p>As already mentioned, in Win64 terms leaf function is one that does not
call any other function <em>nor</em> modifies any non-volatile register,
including stack pointer. But it's not uncommon that assembler programmer
plans to utilize every single register and sometimes even have variable
stack frame. Is there anything one can do with bare building blocks? I.e.
besides manually composing fully-fledged <code>UNWIND_INFO</code>
structure, which would surely be considered error-prone? Yes, there is.
Recall that exception handler is called first, before stack layout is
analyzed. As it turned out, it's perfectly possible to manipulate current
callee's context in custom handler in manner that permits further stack
unwinding. General idea is that handler would not actually "handle" the
exception, but instead restore callee's context, as it was at its entry
point and thus mimic leaf function. In other words, handler would simply
undertake part of unwinding procedure. Consider following example:</p>
<pre>
function: 
        mov     rax,rsp         ; copy rsp to volatile register 
        push    r15             ; save non-volatile registers 
        push    rbx 
        push    rbp 
        mov     r11,rsp         ; prepare variable stack frame 
        sub     r11,rcx 
        and     r11,-64 
        mov     QWORD[r11],rax  ; check for exceptions 
        mov     rsp,r11         ; allocate stack frame 
        mov     QWORD[rsp],rax  ; save original rsp value 
magic_point: 
        ... 
        mov     r11,QWORD[rsp]  ; pull original rsp value 
        mov     rbp,QWORD[r11-24] 
        mov     rbx,QWORD[r11-16] 
        mov     r15,QWORD[r11-8] 
        mov     rsp,r11         ; destroy frame 
        ret
</pre>
<p>The keyword is that up to <code>magic_point</code> original
<code>rsp</code> value remains in chosen volatile register and no
non-volatile register, except for <code>rsp</code>, is modified. While past
<code>magic_point</code> <code>rsp</code> remains constant till the very
end of the <code>function</code>. In this case custom language-specific
exception handler would look like this:</p>
<pre>
EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, 
        CONTEXT *context,DISPATCHER_CONTEXT *disp) 
{   ULONG64 *rsp; 
    if (context-&gt;Rip&lt;(ULONG64)magic_point) 
        rsp = (ULONG64 *)context-&gt;Rax; 
    else 
    {   rsp = ((ULONG64 **)context-&gt;Rsp)[0]; 
        context-&gt;Rbp = rsp[-3]; 
        context-&gt;Rbx = rsp[-2]; 
        context-&gt;R15 = rsp[-1]; 
    } 
    context-&gt;Rsp = (ULONG64)rsp; 

    memcpy (disp-&gt;ContextRecord,context,sizeof(CONTEXT)); 
    RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp-&gt;ImageBase, 
        dips-&gt;ControlPc,disp-&gt;FunctionEntry,disp-&gt;ContextRecord, 
        &amp;disp-&gt;HandlerData,&amp;disp-&gt;EstablisherFrame,NULL); 
    return ExceptionContinueSearch; 
}
</pre>
<p>As custom handler mimics leaf function, corresponding
<code>UNWIND_INFO</code> structure does not have to contain any information
about stack frame and its layout.</p>
<h3 id="section-7.7">7.7 <code>coff</code>: Common Object File Format</h3>
<p>The <code>coff</code> output type produces <code>COFF</code> object
files suitable for linking with the DJGPP linker.</p>
<p><code>coff</code> provides a default output file-name extension of
<code>.o</code>.</p>
<p>The <code>coff</code> format supports the same extensions to the
<code>SECTION</code> directive as <code>win32</code> does, except that the
<code>align</code> qualifier and the <code>info</code> section type are not
supported.</p>
<h3 id="section-7.8">7.8 <code>macho32</code> and <code>macho64</code>: Mach Object File Format</h3>
<p>The <code>macho32</code> and <code>macho64</code> output formts produces
Mach-O object files suitable for linking with the MacOS X linker.
<code>macho</code> is a synonym for <code>macho32</code>.</p>
<p><code>macho</code> provides a default output file-name extension of
<code>.o</code>.</p>
<h4 id="section-7.8.1">7.8.1 <code>macho</code> extensions to the <code>SECTION</code> Directive </h4>
<p>The <code>macho</code> output format specifies section names in the
format "<em>segment</em><code>,</code><em>section</em>". No spaces are
allowed around the comma. The following flags can also be specified:</p>
<ul>
<li>
<p><code>data</code> &ndash; this section contains initialized data items</p>
</li>
<li>
<p><code>code</code> &ndash; this section contains code exclusively</p>
</li>
<li>
<p><code>mixed</code> &ndash; this section contains both code and data</p>
</li>
<li>
<p><code>bss</code> &ndash; this section is uninitialized and filled with
zero</p>
</li>
<li>
<p><code>zerofill</code> &ndash; same as <code>bss</code></p>
</li>
<li>
<p><code>no_dead_strip</code> &ndash; inhibit dead code stripping for this
section</p>
</li>
<li>
<p><code>live_support</code> &ndash; set the live support flag for this
section</p>
</li>
<li>
<p><code>strip_static_syms</code> &ndash; strip static symbols for this
section</p>
</li>
<li>
<p><code>debug</code> &ndash; this section contains debugging information</p>
</li>
<li>
<p><code>align=</code><em>alignment</em> &ndash; specify section alignment</p>
</li>
</ul>
<p>The default is <code>data</code>, unless the section name is
<code>__text</code> or <code>__bss</code> in which case the default is
<code>text</code> or <code>bss</code>, respectively.</p>
<p>For compatibility with other Unix platforms, the following standard
names are also supported:</p>
<pre>
.text    = __TEXT,__text  text 
.rodata  = __DATA,__const data 
.data    = __DATA,__data  data 
.bss     = __DATA,__bss   bss
</pre>
<p>If the <code>.rodata</code> section contains no relocations, it is
instead put into the <code>__TEXT,__const</code> section unless this
section has already been specified explicitly. However, it is probably
better to specify <code>__TEXT,__const</code> and
<code>__DATA,__const</code> explicitly as appropriate.</p>
<h4 id="section-7.8.2">7.8.2 Thread Local Storage in Mach-O: <code>macho</code> special symbols and <code>WRT</code></h4>
<p>Mach-O defines the following special symbols that can be used on the
right-hand side of the <code>WRT</code> operator:</p>
<ul>
<li>
<p><code>..tlvp</code> is used to specify access to thread-local storage.</p>
</li>
<li>
<p><code>..gotpcrel</code> is used to specify references to the Global
Offset Table. The GOT is supported in the <code>macho64</code> format only.</p>
</li>
</ul>
<h4 id="section-7.8.3">7.8.3 <code>macho</code> specfic directive <code>subsections_via_symbols</code></h4>
<p>The directive <code>subsections_via_symbols</code> sets the
<code>MH_SUBSECTIONS_VIA_SYMBOLS</code> flag in the Mach-O header, that
effectively separates a block (or a subsection) based on a symbol. It is
often used for eliminating dead codes by a linker.</p>
<p>This directive takes no arguments.</p>
<p>This is a macro implemented as a <code>%pragma</code>. It can also be
specified in its <code>%pragma</code> form, in which case it will not
affect non-Mach-O builds of the same source code:</p>
<pre>
     %pragma macho subsections_via_symbols
</pre>
<h4 id="section-7.8.4">7.8.4 <code>macho</code> specfic directive <code>no_dead_strip</code></h4>
<p>The directive <code>no_dead_strip</code> sets the Mach-O
<code>SH_NO_DEAD_STRIP</code> section flag on the section containing a a
specific symbol. This directive takes a list of symbols as its arguments.</p>
<p>This is a macro implemented as a <code>%pragma</code>. It can also be
specified in its <code>%pragma</code> form, in which case it will not
affect non-Mach-O builds of the same source code:</p>
<pre>
     %pragma macho no_dead_strip symbol...
</pre>
<h4 id="section-7.8.5">7.8.5 <code>macho</code> specific extensions to the <code>GLOBAL</code> Directive: <code>private_extern</code></h4>
<p>The directive extension to <code>GLOBAL</code> marks the symbol with
limited global scope. For example, you can specify the global symbol with
this extension:</p>
<pre>
global foo:private_extern 
foo: 
         ; codes
</pre>
<p>Using with static linker will clear the private extern attribute. But
linker option like <code>-keep_private_externs</code> can avoid it.</p>
<h3 id="section-7.9">7.9 <code>elf32</code>, <code>elf64</code>, <code>elfx32</code>: Executable and Linkable Format Object Files</h3>
<p>The <code>elf32</code>, <code>elf64</code> and <code>elfx32</code>
output formats generate <code>ELF32 and ELF64</code> (Executable and
Linkable Format) object files, as used by Linux as well as Unix System V,
including Solaris x86, UnixWare and SCO Unix. <code>elf</code> provides a
default output file-name extension of <code>.o</code>. <code>elf</code> is
a synonym for <code>elf32</code>.</p>
<p>The <code>elfx32</code> format is used for the x32 ABI, which is a
32-bit ABI with the CPU in 64-bit mode.</p>
<h4 id="section-7.9.1">7.9.1 ELF specific directive <code>osabi</code></h4>
<p>The ELF header specifies the application binary interface for the target
operating system (OSABI). This field can be set by using the
<code>osabi</code> directive with the numeric value (0-255) of the target
system. If this directive is not used, the default value will be "UNIX
System V ABI" (0) which will work on most systems which support ELF.</p>
<h4 id="section-7.9.2">7.9.2 <code>elf</code> extensions to the <code>SECTION</code> Directive </h4>
<p>Like the <code>obj</code> format, <code>elf</code> allows you to specify
additional information on the <code>SECTION</code> directive line, to
control the type and properties of sections you declare. Section types and
properties are generated automatically by NASM for the standard section
names, but may still be overridden by these qualifiers.</p>
<p>The available qualifiers are:</p>
<ul>
<li>
<p><code>alloc</code> defines the section to be one which is loaded into
memory when the program is run. <code>noalloc</code> defines it to be one
which is not, such as an informational or comment section.</p>
</li>
<li>
<p><code>exec</code> defines the section to be one which should have
execute permission when the program is run. <code>noexec</code> defines it
as one which should not.</p>
</li>
<li>
<p><code>write</code> defines the section to be one which should be
writable when the program is run. <code>nowrite</code> defines it as one
which should not.</p>
</li>
<li>
<p><code>progbits</code> defines the section to be one with explicit
contents stored in the object file: an ordinary code or data section, for
example, <code>nobits</code> defines the section to be one with no explicit
contents given, such as a BSS section.</p>
</li>
<li>
<p><code>align=</code>, used with a trailing number as in <code>obj</code>,
gives the alignment requirements of the section.</p>
</li>
<li>
<p><code>tls</code> defines the section to be one which contains thread
local variables.</p>
</li>
</ul>
<p>The defaults assumed by NASM if you do not specify the above qualifiers
are:</p>
<p></p>
<pre>
section .text    progbits  alloc   exec    nowrite  align=16 
section .rodata  progbits  alloc   noexec  nowrite  align=4 
section .lrodata progbits  alloc   noexec  nowrite  align=4 
section .data    progbits  alloc   noexec  write    align=4 
section .ldata   progbits  alloc   noexec  write    align=4 
section .bss     nobits    alloc   noexec  write    align=4 
section .lbss    nobits    alloc   noexec  write    align=4 
section .tdata   progbits  alloc   noexec  write    align=4    tls 
section .tbss    nobits    alloc   noexec  write    align=4    tls 
section .comment progbits  noalloc noexec  nowrite  align=1 
section other    progbits  alloc   noexec  nowrite  align=1
</pre>
<p>(Any section name other than those in the above table is treated by
default like <code>other</code> in the above table. Please note that
section names are case sensitive.)</p>
<h4 id="section-7.9.3">7.9.3 Position-Independent Code: <code>macho</code> Special Symbols and <code>WRT</code></h4>
<p>Since <code>ELF</code> does not support segment-base references, the
<code>WRT</code> operator is not used for its normal purpose; therefore
NASM's <code>elf</code> output format makes use of <code>WRT</code> for a
different purpose, namely the PIC-specific relocation types.</p>
<p><code>elf</code> defines five special symbols which you can use as the
right-hand side of the <code>WRT</code> operator to obtain PIC relocation
types. They are <code>..gotpc</code>, <code>..gotoff</code>,
<code>..got</code>, <code>..plt</code> and <code>..sym</code>. Their
functions are summarized here:</p>
<ul>
<li>
<p>Referring to the symbol marking the global offset table base using
<code>wrt ..gotpc</code> will end up giving the distance from the beginning
of the current section to the global offset table.
(<code>_GLOBAL_OFFSET_TABLE_</code> is the standard symbol name used to
refer to the GOT.) So you would then need to add <code>$$</code> to the
result to get the real address of the GOT.</p>
</li>
<li>
<p>Referring to a location in one of your own sections using
<code>wrt ..gotoff</code> will give the distance from the beginning of the
GOT to the specified location, so that adding on the address of the GOT
would give the real address of the location you wanted.</p>
</li>
<li>
<p>Referring to an external or global symbol using <code>wrt ..got</code>
causes the linker to build an entry <em>in</em> 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.</p>
</li>
<li>
<p>Referring to a procedure name using <code>wrt ..plt</code> 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 <code>CALL</code> or <code>JMP</code>), since ELF
contains no relocation type to refer to PLT entries absolutely.</p>
</li>
<li>
<p>Referring to a symbol name using <code>wrt ..sym</code> causes NASM 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.</p>
</li>
</ul>
<p>A fuller explanation of how to use these relocation types to write
shared libraries entirely in NASM is given in
<a href="nasmdoc9.html#section-9.2">section 9.2</a>.</p>
<h4 id="section-7.9.4">7.9.4 Thread Local Storage in ELF: <code>elf</code> Special Symbols and <code>WRT</code></h4>
<ul>
<li>
<p>In ELF32 mode, referring to an external or global symbol using
<code>wrt ..tlsie</code>  causes the linker to build an entry <em>in</em>
the GOT containing the offset of the symbol within the TLS block, so you
can access the value of the symbol with code such as:</p>
<pre>
       mov  eax,[tid wrt ..tlsie] 
       mov  [gs:eax],ebx
</pre>
</li>
<li>
<p>In ELF64 or ELFx32 mode, referring to an external or global symbol using
<code>wrt ..gottpoff</code>  causes the linker to build an entry
<em>in</em> the GOT containing the offset of the symbol within the TLS
block, so you can access the value of the symbol with code such as:</p>
<pre>
       mov   rax,[rel tid wrt ..gottpoff] 
       mov   rcx,[fs:rax]
</pre>
</li>
</ul>
<h4 id="section-7.9.5">7.9.5 <code>elf</code> Extensions to the <code>GLOBAL</code> Directive</h4>
<p><code>ELF</code> object files can contain more information about a
global symbol than just its address: they can contain the size of the
symbol and its type as well. These are not merely debugger conveniences,
but are actually necessary when the program being written is a shared
library. NASM therefore supports some extensions to the <code>GLOBAL</code>
directive, allowing you to specify these features.</p>
<p>You can specify whether a global variable is a function or a data object
by suffixing the name with a colon and the word <code>function</code> or
<code>data</code>. (<code>object</code> is a synonym for
<code>data</code>.) For example:</p>
<pre>
global   hashlookup:function, hashtable:data
</pre>
<p>exports the global symbol <code>hashlookup</code> as a function and
<code>hashtable</code> as a data object.</p>
<p>Optionally, you can control the ELF visibility of the symbol. Just add
one of the visibility keywords: <code>default</code>,
<code>internal</code>, <code>hidden</code>, or <code>protected</code>. The
default is <code>default</code> of course. For example, to make
<code>hashlookup</code> hidden:</p>
<pre>
global   hashlookup:function hidden
</pre>
<p>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:</p>
<pre>
global  hashtable:data (hashtable.end - hashtable) 

hashtable: 
        db this,that,theother  ; some data here 
.end:
</pre>
<p>This makes NASM automatically calculate the length of the table and
place that information into the <code>ELF</code> symbol table.</p>
<p>Declaring the type and size of global symbols is necessary when writing
shared library code. For more information, see
<a href="nasmdoc9.html#section-9.2.4">section 9.2.4</a>.</p>
<h4 id="section-7.9.6">7.9.6 <code>elf</code> Extensions to the <code>COMMON</code> Directive </h4>
<p><code>ELF</code> also allows you to specify alignment requirements on
common variables. This is done by putting a number (which must be a power
of two) after the name and size of the common variable, separated (as
usual) by a colon. For example, an array of doublewords would benefit from
4-byte alignment:</p>
<pre>
common  dwordarray 128:4
</pre>
<p>This declares the total size of the array to be 128 bytes, and requires
that it be aligned on a 4-byte boundary.</p>
<h4 id="section-7.9.7">7.9.7 16-bit code and ELF </h4>
<p>The <code>ELF32</code> specification doesn't provide relocations for 8-
and 16-bit values, but the GNU <code>ld</code> linker adds these as an
extension. NASM can generate GNU-compatible relocations, to allow 16-bit
code to be linked as ELF using GNU <code>ld</code>. If NASM is used with
the <code>-w+gnu-elf-extensions</code> option, a warning is issued when one
of these relocations is generated.</p>
<h4 id="section-7.9.8">7.9.8 Debug formats and ELF </h4>
<p>ELF provides debug information in <code>STABS</code> and
<code>DWARF</code> formats. Line number information is generated for all
executable sections, but please note that only the ".text" section is
executable by default.</p>
<h3 id="section-7.10">7.10 <code>aout</code>: Linux <code>a.out</code> Object Files</h3>
<p>The <code>aout</code> format generates <code>a.out</code> object files,
in the form used by early Linux systems (current Linux systems use ELF, see
<a href="#section-7.9">section 7.9</a>.) These differ from other
<code>a.out</code> object files in that the magic number in the first four
bytes of the file is different; also, some implementations of
<code>a.out</code>, for example NetBSD's, support position-independent
code, which Linux's implementation does not.</p>
<p><code>a.out</code> provides a default output file-name extension of
<code>.o</code>.</p>
<p><code>a.out</code> is a very simple object format. It supports no
special directives, no special symbols, no use of <code>SEG</code> or
<code>WRT</code>, and no extensions to any standard directives. It supports
only the three standard section names <code>.text</code>,
<code>.data</code> and <code>.bss</code>.</p>
<h3 id="section-7.11">7.11 <code>aoutb</code>: NetBSD/FreeBSD/OpenBSD <code>a.out</code> Object Files</h3>
<p>The <code>aoutb</code> format generates <code>a.out</code> object files,
in the form used by the various free <code>BSD Unix</code> clones,
<code>NetBSD</code>, <code>FreeBSD</code> and <code>OpenBSD</code>. For
simple object files, this object format is exactly the same as
<code>aout</code> except for the magic number in the first four bytes of
the file. However, the <code>aoutb</code> format supports
position-independent code in the same way as the <code>elf</code> format,
so you can use it to write <code>BSD</code> shared libraries.</p>
<p><code>aoutb</code> provides a default output file-name extension of
<code>.o</code>.</p>
<p><code>aoutb</code> supports no special directives, no special symbols,
and only the three standard section names <code>.text</code>,
<code>.data</code> and <code>.bss</code>. However, it also supports the
same use of <code>WRT</code> as <code>elf</code> does, to provide
position-independent code relocation types. See
<a href="#section-7.9.3">section 7.9.3</a> for full documentation of this
feature.</p>
<p><code>aoutb</code> also supports the same extensions to the
<code>GLOBAL</code> directive as <code>elf</code> does: see
<a href="#section-7.9.5">section 7.9.5</a> for documentation of this.</p>
<h3 id="section-7.12">7.12 <code>as86</code>: Minix/Linux <code>as86</code> Object Files</h3>
<p>The Minix/Linux 16-bit assembler <code>as86</code> has its own
non-standard object file format. Although its companion linker
<code>ld86</code> produces something close to ordinary <code>a.out</code>
binaries as output, the object file format used to communicate between
<code>as86</code> and <code>ld86</code> is not itself <code>a.out</code>.</p>
<p>NASM supports this format, just in case it is useful, as
<code>as86</code>. <code>as86</code> provides a default output file-name
extension of <code>.o</code>.</p>
<p><code>as86</code> is a very simple object format (from the NASM user's
point of view). It supports no special directives, no use of
<code>SEG</code> or <code>WRT</code>, and no extensions to any standard
directives. It supports only the three standard section names
<code>.text</code>, <code>.data</code> and <code>.bss</code>. The only
special symbol supported is <code>..start</code>.</p>
<h3 id="section-7.13">7.13 <code>rdf</code>: Relocatable Dynamic Object File Format</h3>
<p>The <code>rdf</code> output format produces <code>RDOFF</code> object
files. <code>RDOFF</code> (Relocatable Dynamic Object File Format) is a
home-grown object-file format, designed alongside NASM itself and
reflecting in its file format the internal structure of the assembler.</p>
<p><code>RDOFF</code> is not used by any well-known operating systems.
Those writing their own systems, however, may well wish to use
<code>RDOFF</code> as their object format, on the grounds that it is
designed primarily for simplicity and contains very little file-header
bureaucracy.</p>
<p>The Unix NASM archive, and the DOS archive which includes sources, both
contain an <code>rdoff</code> subdirectory holding a set of RDOFF
utilities: an RDF linker, an <code>RDF</code> static-library manager, an
RDF file dump utility, and a program which will load and execute an RDF
executable under Linux.</p>
<p><code>rdf</code> supports only the standard section names
<code>.text</code>, <code>.data</code> and <code>.bss</code>.</p>
<h4 id="section-7.13.1">7.13.1 Requiring a Library: The <code>LIBRARY</code> Directive</h4>
<p><code>RDOFF</code> contains a mechanism for an object file to demand a
given library to be linked to the module, either at load time or run time.
This is done by the <code>LIBRARY</code> directive, which takes one
argument which is the name of the module:</p>
<pre>
    library  mylib.rdl
</pre>
<h4 id="section-7.13.2">7.13.2 Specifying a Module Name: The <code>MODULE</code> Directive</h4>
<p>Special <code>RDOFF</code> header record is used to store the name of
the module. It can be used, for example, by run-time loader to perform
dynamic linking. <code>MODULE</code> directive takes one argument which is
the name of current module:</p>
<pre>
    module  mymodname
</pre>
<p>Note that when you statically link modules and tell linker to strip the
symbols from output file, all module names will be stripped too. To avoid
it, you should start module names with <code>$</code>, like:</p>
<pre>
    module  $kernel.core
</pre>
<h4 id="section-7.13.3">7.13.3 <code>rdf</code> Extensions to the <code>GLOBAL</code> Directive</h4>
<p><code>RDOFF</code> global symbols can contain additional information
needed by the static linker. You can mark a global symbol as exported, thus
telling the linker do not strip it from target executable or library file.
Like in <code>ELF</code>, you can also specify whether an exported symbol
is a procedure (function) or data object.</p>
<p>Suffixing the name with a colon and the word <code>export</code> you
make the symbol exported:</p>
<pre>
    global  sys_open:export
</pre>
<p>To specify that exported symbol is a procedure (function), you add the
word <code>proc</code> or <code>function</code> after declaration:</p>
<pre>
    global  sys_open:export proc
</pre>
<p>Similarly, to specify exported data object, add the word
<code>data</code> or <code>object</code> to the directive:</p>
<pre>
    global  kernel_ticks:export data
</pre>
<h4 id="section-7.13.4">7.13.4 <code>rdf</code> Extensions to the <code>EXTERN</code> Directive</h4>
<p>By default the <code>EXTERN</code> directive in <code>RDOFF</code>
declares a "pure external" symbol (i.e. the static linker will complain if
such a symbol is not resolved). To declare an "imported" symbol, which must
be resolved later during a dynamic linking phase, <code>RDOFF</code> offers
an additional <code>import</code> modifier. As in <code>GLOBAL</code>, you
can also specify whether an imported symbol is a procedure (function) or
data object. For example:</p>
<pre>
    library $libc 
    extern  _open:import 
    extern  _printf:import proc 
    extern  _errno:import data
</pre>
<p>Here the directive <code>LIBRARY</code> is also included, which gives
the dynamic linker a hint as to where to find requested symbols.</p>
<h3 id="section-7.14">7.14 <code>dbg</code>: Debugging Format</h3>
<p>The <code>dbg</code> format does not output an object file as such;
instead, it outputs a text file which contains a complete list of all the
transactions between the main body of NASM and the output-format back end
module. It is primarily intended to aid people who want to write their own
output drivers, so that they can get a clearer idea of the various requests
the main program makes of the output driver, and in what order they happen.</p>
<p>For simple files, one can easily use the <code>dbg</code> format like
this:</p>
<pre>
nasm -f dbg filename.asm
</pre>
<p>which will generate a diagnostic file called <code>filename.dbg</code>.
However, this will not work well on files which were designed for a
different object format, because each object format defines its own macros
(usually user-level forms of directives), and those macros will not be
defined in the <code>dbg</code> format. Therefore it can be useful to run
NASM twice, in order to do the preprocessing with the native object format
selected:</p>
<pre>
nasm -e -f rdf -o rdfprog.i rdfprog.asm 
nasm -a -f dbg rdfprog.i
</pre>
<p>This preprocesses <code>rdfprog.asm</code> into <code>rdfprog.i</code>,
keeping the <code>rdf</code> object format selected in order to make sure
RDF special directives are converted into primitive form correctly. Then
the preprocessed source is fed through the <code>dbg</code> format to
generate the final diagnostic output.</p>
<p>This workaround will still typically not work for programs intended for
<code>obj</code> format, because the <code>obj</code> <code>SEGMENT</code>
and <code>GROUP</code> directives have side effects of defining the segment
and group names as symbols; <code>dbg</code> will not do this, so the
program will not assemble. You will have to work around that by defining
the symbols yourself (using <code>EXTERN</code>, for example) if you really
need to get a <code>dbg</code> trace of an <code>obj</code>&ndash;specific
source file.</p>
<p><code>dbg</code> accepts any section name and any directives at all, and
logs them all to its output file.</p>
<p><code>dbg</code> accepts and logs any <code>%pragma</code>, but the
specific <code>%pragma</code>:</p>
<pre>
     %pragma dbg maxdump &lt;size&gt;
</pre>
<p>where <code>&lt;size&gt;</code> is either a number or
<code>unlimited</code>, can be used to control the maximum size for dumping
the full contents of a <code>rawdata</code> output object.</p>
</div>
</body>
</html>