Chapter 2: Running NASM
- .NASM became 64-bit capable as of version 2.0: invoke nasm -v to check the version you’re running.When assembling, make sure to specify a 64-bit format elf64 for most 64-bit Linux architectures macho64 for 64-bit Mac OS X win64 for 64-bit Windows.
- System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next. Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon.
- The Netwide Assembler on a Mac. The Netwide Assembler or NASM, is an x86 and x64 assembler designed for UNIX operation systems. The assembler comes with documentation which will help you with the basics. It supports a multiple range of object file formats, including Mac, UNIX, and Windows formats.
2.1 NASM Command-Line Syntax
Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I have some problems with linking nasm program for macos: GLOBAL start SEGMENT.text start: mov ax, 5 mov bx, ax mov a, ebx SEGMENT.data a DW 0 t2 DW 0 fry$ nasm -f elf test.
To assemble a file, you issue a command of the form
For example,
will assemble
myfile.asm
into an ELF object filemyfile.o
. Andwill assemble
myfile.asm
into a raw binary filemyfile.com
.To produce a listing file, with the hex codes output from NASM displayedon the left of the original sources, use the
-l
option to givea listing file name, for example:To get further usage instructions from NASM, try typing
The option
--help
is an alias for the -h
option.If you use Linux but aren't sure whether your system is
a.out
or ELF, type(in the directory in which you put the NASM binary when you installedit). If it says something like
then your system is
ELF
, and you should use the option-f elf
when you want NASM to produce Linux object files. If itsaysor something similar, your system is
a.out
, and you shoulduse -f aout
instead (Linux a.out
systems havelong been obsolete, and are rare these days.)Like Unix compilers and assemblers, NASM is silent unless it goes wrong:you won't see any output at all, unless it gives error messages.
2.1.1 The -o
Option: Specifying the Output File Name
NASM will normally choose the name of your output file for you;precisely how it does this is dependent on the object file format. ForMicrosoft object file formats (
obj
, win32
andwin64
), it will remove the .asm
extension (orwhatever extension you like to use – NASM doesn't care) from yoursource file name and substitute .obj
. For Unix object fileformats (aout
, as86
, coff
,elf32
, elf64
, elfx32
,ieee
, macho32
and macho64
) it willsubstitute .o
. For dbg
, rdf
,ith
and srec
, it will use .dbg
,.rdf
, .ith
and .srec
, respectively,and for the bin
format it will simply remove the extension, sothat myfile.asm
produces the output file myfile
.If the output file already exists, NASM will overwrite it, unless it hasthe same name as the input file, in which case it will give a warning anduse
nasm.out
as the output file name instead.For situations in which this behaviour is unacceptable, NASM providesthe
-o
command-line option, which allows you to specify yourdesired output file name. You invoke -o
by following it withthe name you wish for the output file, either with or without anintervening space. For example:Note that this is a small o, and is different from a capital O , whichis used to specify the number of optimization passes required. Seesection 2.1.24.
2.1.2 The -f
Option: Specifying the Output File Format
If you do not supply the
-f
option to NASM, it will choosean output file format for you itself. In the distribution versions of NASM,the default is always bin
; if you've compiled your own copy ofNASM, you can redefine OF_DEFAULT
at compile time and choosewhat you want the default to be.Like
-o
, the intervening space between -f
andthe output file format is optional; so -f elf
and-felf
are both valid.A complete list of the available output file formats can be given byissuing the command
nasm -h
.2.1.3 The -l
Option: Generating a Listing File
If you supply the
-l
option to NASM, followed (with theusual optional space) by a file name, NASM will generate a source-listingfile for you, in which addresses and generated code are listed on the left,and the actual source code, with expansions of multi-line macros (exceptthose which specifically request no expansion in source listings: seesection 4.3.11) on the right.For example:If a list file is selected, you may turn off listing for a section ofyour source with
[list -]
, and turn it back on with[list +]
, (the default, obviously). There is no 'user form'(without the brackets). This can be used to list only sections of interest,avoiding excessively long listings.2.1.4 The -L
Option: Additional or Modified Listing Info
Use this option to specify listing output details.
Supported options are:
-Lb
show builtin macro packages (standard and%use
)-Ld
show byte and repeat counts in decimal, not hex-Le
show the preprocessed input-Lf
ignore.nolist
and force listing output-Lm
show multi-line macro calls with expanded parameters-Lp
output a list file in every pass, in case of errors-Ls
show all single-line macro definitions-Lw
flush the output after every line (very slow, mainlyuseful to debug NASM crashes)-L+
enable all listing options except-Lw
(very verbose)
These options can be enabled or disabled at runtime using the
%pragma list options
directive:For example, to turn on the
d
and m
flags butdisable the s
flag:For forward compatility reasons, an undefined flag will be ignored.Thus, a new flag introduced in a newer version of NASM can be specifiedwithout breaking older versions. Listing flags will always be a singlealphanumeric character and are case sensitive.
2.1.5 The -M
Option: Generate Makefile Dependencies
This option can be used to generate makefile dependencies on stdout.This can be redirected to a file for further processing. For example:
2.1.6 The -MG
Option: Generate Makefile Dependencies
This option can be used to generate makefile dependencies on stdout.This differs from the
-M
option in that if a nonexisting fileis encountered, it is assumed to be a generated file and is added to thedependency list without a prefix.2.1.7 The -MF
Option: Set Makefile Dependency File
This option can be used with the
-M
or -MG
options to send the output to a file, rather than to stdout. For example:2.1.8 The -MD
Option: Assemble and Generate Dependencies
The
-MD
option acts as the combination of the-M
and -MF
options (i.e. a filename has to bespecified.) However, unlike the -M
or -MG
options, -MD
does not inhibit the normal operation ofthe assembler. Use this to automatically generate updated dependencies withevery assembly session. For example:If the argument after
-MD
is an option rather than afilename, then the output filename is the first applicable one of:- the filename set in the
-MF
option; - the output filename from the
-o
option with.d
appended; - the input filename with the extension set to
.d
.
2.1.9 The -MT
Option: Dependency Target Name
The
-MT
option can be used to override the default name ofthe dependency target. This is normally the same as the output filename,specified by the -o
option.2.1.10 The -MQ
Option: Dependency Target Name (Quoted)
The
-MQ
option acts as the -MT
option, exceptit tries to quote characters that have special meaning in Makefile syntax.This is not foolproof, as not all characters with special meaning arequotable in Make. The default output (if no -MT
or-MQ
option is specified) is automatically quoted.2.1.11 The -MP
Option: Emit phony targets
When used with any of the dependency generation options, the
-MP
option causes NASM to emit a phony target withoutdependencies for each header file. This prevents Make from complaining if aheader file has been removed.2.1.12 The -MW
Option: Watcom Make quoting style
This option causes NASM to attempt to quote dependencies according toWatcom Make conventions rather than POSIX Make conventions (also used bymost other Make variants.) This quotes
#
as $#
rather than #
, uses &
rather than
for continuation lines, and encloses filenames containingwhitespace in double quotes.2.1.13 The -F
Option: Selecting a Debug Information Format
This option is used to select the format of the debug informationemitted into the output file, to be used by a debugger (or willbe). Prior to version 2.03.01, the use of this switch did notenable output of the selected debug info format. Use
-g
, seesection 2.1.14, to enable output. Versions2.03.01 and later automatically enable -g
if -F
is specified.A complete list of the available debug file formats for an output formatcan be seen by issuing the command
nasm -h
. Not all outputformats currently support debugging output.This should not be confused with the
-f dbg
output formatoption, see section 8.14.2.1.14 The -g
Option: Enabling Debug Information.
This option can be used to generate debugging information in thespecified format. See section 2.1.13. Using
-g
without -F
results in emitting debug info inthe default format, if any, for the selected output format. If no debuginformation is currently implemented in the selected output format,-g
is silently ignored.2.1.15 The -X
Option: Selecting an Error Reporting Format
This option can be used to select an error reporting format for anyerror messages that might be produced by NASM.
Currently, two error reporting formats may be selected. They are the
-Xvc
option and the -Xgnu
option. The GNU formatis the default and looks like this:where
filename.asm
is the name of the source file in whichthe error was detected, 65
is the source file line number onwhich the error was detected, error
is the severity of theerror (this could be warning
), andspecific error message
is a more detailed text message whichshould help pinpoint the exact problem.The other format, specified by
-Xvc
is the style used byMicrosoft Visual C++ and some other programs. It looks like this:where the only difference is that the line number is in parenthesesinstead of being delimited by colons.
See also the
Visual C++
output format,section 8.5.2.1.16 The -Z
Option: Send Errors to a File
Under
MS-DOS
it can be difficult (though there are ways) toredirect the standard-error output of a program to a file. Since NASMusually produces its warning and error messages on stderr
,this can make it hard to capture the errors if (for example) you want toload them into an editor.NASM therefore provides the
-Z
option, taking a filenameargument which causes errors to be sent to the specified files rather thanstandard error. Therefore you can redirect the errors into a file by typingIn earlier versions of NASM, this option was called
-E
, butit was changed since -E
is an option conventionally used forpreprocessing only, with disastrous results. Seesection 2.1.22.2.1.17 The -s
Option: Send Errors to stdout
The
-s
option redirects error messages tostdout
rather than stderr
, so it can beredirected under MS-DOS
. To assemble the filemyfile.asm
and pipe its output to the more
program, you can type:See also the
-Z
option, section2.1.16.2.1.18 The -i
Option: Include File Search Directories
When NASM sees the
%include
or %pathsearch
directive in a source file (seesection 4.6.1,section 4.6.2 orsection 3.2.3), it will searchfor the given file not only in the current directory, but also in anydirectories specified on the command line by the use of the -i
option. Therefore you can include files from a macro library, for example,by typing(As usual, a space between
-i
and the path name is allowed,and optional).Prior NASM 2.14 a path provided in the option has been considered as averbatim copy and providing a path separator been up to a caller. One couldimplicitly concatenate a search path together with a filename. Still thiswas rather a trick than something useful. Now the trailing path separatoris made to always present, thus
-ifoo
will be considered asthe -ifoo/
directory.If you want to define a standard include search path, similarto
/usr/include
on Unix systems, you should place one or more-i
directives in the NASMENV
environment variable(see section 2.1.35).For Makefile compatibility with many C compilers, this option can alsobe specified as
-I
.2.1.19 The -p
Option: Pre-Include a File
NASM allows you to specify files to be pre-included into yoursource file, by the use of the
-p
option. So runningis equivalent to running
nasm myfile.asm
and placing thedirective %include 'myinc.inc'
at the start of the file.--include
option is also accepted.For consistency with the
-I
, -D
and-U
options, this option can also be specified as-P
.2.1.20 The -d
Option: Pre-Define a Macro
Just as the
-p
option gives an alternative to placing%include
directives at the start of a source file, the-d
option gives an alternative to placing a%define
directive. You could codeas an alternative to placing the directive
at the start of the file. You can miss off the macro value, as well: theoption
-dFOO
is equivalent to coding %define FOO
.This form of the directive may be useful for selecting assembly-timeoptions which are then tested using %ifdef
, for example-dDEBUG
.For Makefile compatibility with many C compilers, this option can alsobe specified as
-D
.2.1.21 The -u
Option: Undefine a Macro
The
-u
option undefines a macro that would otherwise havebeen pre-defined, either automatically or by a -p
or-d
option specified earlier on the command lines.For example, the following command line:
would result in
FOO
not being a predefined macroin the program. This is useful to override options specified at a differentpoint in a Makefile.For Makefile compatibility with many C compilers, this option can alsobe specified as
-U
.2.1.22 The -E
Option: Preprocess Only
NASM allows the preprocessor to be run on its own, up to a point. Usingthe
-E
option (which requires no arguments) will cause NASM topreprocess its input file, expand all the macro references, remove all thecomments and preprocessor directives, and print the resulting file onstandard output (or save it to a file, if the -o
option isalso used).This option cannot be applied to programs which require the preprocessorto evaluate expressions which depend on the values of symbols: so code suchas
will cause an error in preprocess-only mode.
For compatiblity with older version of NASM, this option can also bewritten
-e
. -E
in older versions of NASM was theequivalent of the current -Z
option,section 2.1.16.2.1.23 The -a
Option: Don't Preprocess At All
If NASM is being used as the back end to a compiler, it might bedesirable to suppress preprocessing completely and assume the compiler hasalready done it, to save time and increase compilation speeds. The
-a
option, requiring no argument, instructs NASM to replaceits powerful preprocessor with a stub preprocessor which does nothing.2.1.24 The -O
Option: Specifying Multipass Optimization
Nasm For Mac Os 10.13
Using the
-O
option, you can tell NASM to carry outdifferent levels of optimization. Multiple flags can be specified after the-O
options, some of which can be combined in a single option,e.g. -Oxv
.-O0
: No optimization. All operands take their long forms,if a short form is not specified, except conditional jumps. This isintended to match NASM 0.98 behavior.-O1
: Minimal optimization. As above, but immediate operandswhich will fit in a signed byte are optimized, unless the long form isspecified. Conditional jumps default to the long form unless otherwisespecified.-Ox
(wherex
is the actual letterx
): Multipass optimization. Minimize branch offsets and signedimmediate bytes, overriding size specification unless thestrict
keyword has been used (seesection 3.7). For compatibilitywith earlier releases, the letterx
may also be any numbergreater than one. This number has no effect on the actual number of passes.-Ov
: At the end of assembly, print the number of passesactually executed.
The
-Ox
mode is recommended for most uses, and is thedefault since NASM 2.09.Note that this is a capital
O
, and is different from asmall o
, which is used to specify the output file name. Seesection 2.1.1.2.1.25 The -t
Option: Enable TASM Compatibility Mode
NASM includes a limited form of compatibility with Borland's
TASM
. When NASM's -t
option is used, thefollowing changes are made:- local labels may be prefixed with
@@
instead of.
- size override is supported within brackets. In TASM compatible mode, asize override inside square brackets changes the size of the operand, andnot the address type of the operand as it does in NASM syntax. E.g.
mov eax,[DWORD val]
is valid syntax in TASM compatibilitymode. Note that you lose the ability to override the default address typefor the instruction. - unprefixed forms of some directives supported (
arg
,elif
,else
,endif
,if
,ifdef
,ifdifi
,ifndef
,include
,local
)
2.1.26 The -w
and -W
Options: Enable or Disable Assembly Warnings
NASM can observe many conditions during the course of assembly which areworth mentioning to the user, but not a sufficiently severe error tojustify NASM refusing to generate an output file. These conditions arereported like errors, but come up with the word `warning' before themessage. Warnings do not prevent NASM from generating an output file andreturning a success status to the operating system.
Some conditions are even less severe than that: they are only sometimesworth mentioning to the user. Therefore NASM supports the
-w
command-line option, which enables or disables certain classes of assemblywarning. Such warning classes are described by a name, for examplelabel-orphan
; you can enable warnings of this class by thecommand-line option -w+label-orphan
and disable it by-w-label-orphan
.The current warning classes are:
all
is an group alias for all warning classes.Thus,-w+all
enables all available warnings, and-w-all
disables warnings entirely (since NASM 2.13).bad-pragma
is a backwards compatibility alias forpragma-bad
.bnd
warns about ineffective use of theBND
prefix when theJMP
instruction is converted to theSHORT
form. This should be extremely rare since the shortJMP
only is applicable to jumps inside the same module, but ifit is legitimate, it may be necessary to usebnd jmp dword
.Enabled by default.db-empty
warns about aDB
,DW
,etc declaration with no operands, producing no output. This is permitted,but often indicative of an error. Seesection 3.2.1.Enabled by default.environment
warns if a nonexistent environment variable isaccessed using the%!
preprocessor construct (seesection 4.11.2.) Suchenvironment variables are treated as empty (with this warning issued)starting in NASM 2.15; earlier versions of NASM would treat this as anerror.Enabled by default.float
is a group alias for all warning classes prefixed byfloat-
; currentlyfloat-denorm
,float-overflow
,float-toolong
, andfloat-underflow
.float-denorm
warns about denormal floating point constants.Disabled by default.float-overflow
warns about floating point underflow.Enabled by default.float-toolong
warns about too many digits in floating-pointnumbers.Enabled by default.float-underflow
warns about floating point underflow (anonzero constant rounded to zero.)Disabled by default.hle
warns about invalid use of the HLEXACQUIRE
orXRELEASE
prefixes.Enabled by default.label
is a group alias for all warning classes prefixed bylabel-
; currentlylabel-orphan
,label-redef
, andlabel-redef-late
.label-orphan
warns about source lines which contain noinstruction but define a label without a trailing colon. This is mostlikely indicative of a typo, but is technically correct NASM syntax (seesection 3.1.)Enabled by default.label-redef
warns if a label is defined more than once, butthe value is identical. It is an unconditional error to define the samelabel more than once to different values.Disabled by default.label-redef-late
the value of a label changed during thefinal, code-generation pass. This may be the result of strange use of thepreprocessor. This is very likely to produce incorrect code and may end upbeing an unconditional error in a future version of NASM.Enabled and promoted to error by default.lock
warns aboutLOCK
prefixes on unlockableinstructions.Enabled by default.macro
is a group alias for all warning classes prefixed bymacro-
; currentlymacro-def-case-single
,macro-def-greedy-single
,macro-def-param-single
,macro-defaults
,macro-params-legacy
,macro-params-multi
, andmacro-params-single
.macro-def
is a group alias for all warning classes prefixedbymacro-def-
; currentlymacro-def-case-single
,macro-def-greedy-single
, andmacro-def-param-single
.macro-def-case-single
warns when a single-line macro isdefined both case sensitive and case insensitive. The new macro definitionwill override (shadow) the original one, although the original macro is notdeleted, and will be re-exposed if the new macro is deleted with%undef
, or, if the original macro is the case insensitive one,the macro call is done with a different case.Enabled by default.macro-def-greedy-single
definition shadows greedy macrowarns when a single-line macro is defined which would match a previouslyexisting greedy definition. The new macro definition will override (shadow)the original one, although the original macro is not deleted, and will bere-exposed if the new macro is deleted with%undef
, and willbe invoked if called with a parameter count that does not match the newdefinition.Enabled by default.macro-def-param-single
warns if the same single-line macrois defined with and without parameters. The new macro definition willoverride (shadow) the original one, although the original macro is notdeleted, and will be re-exposed if the new macro is deleted with%undef
.Enabled and promoted to error by default.macro-defaults
warns when a macro has more defaultparameters than optional parameters. Seesection 4.3.5 for why might wantto disable this warning.Enabled by default.macro-params
is a group alias for all warning classesprefixed bymacro-params-
; currentlymacro-params-legacy
,macro-params-multi
, andmacro-params-single
.macro-params-legacy
warns about multi-line macros beinginvoked with the wrong number of parameters, but for bug-compatibility withNASM versions older than 2.15, NASM tried to fix up the parameters to matchthe legacy behavior and call the macro anyway. This can happen in certaincases where there are empty arguments without braces, sometimes as a resultof macro expansion.The legacy behavior is quite strange and highly context-dependent, andcan be disabled with:It is highly recommended to use this option in new code.Enabled by default.macro-params-multi
warns about multi-line macros beinginvoked with the wrong number of parameters. Seesection 4.3.1 for an example ofwhy you might want to disable this warning.Enabled by default.macro-params-single
warns about single-line macros beinginvoked with the wrong number of parameters.Enabled by default.negative-rep
warns about negative counts given to the%rep
preprocessor directive.Enabled by default.not-my-pragma
is a backwards compatibility alias forpragma-na
.number-overflow
covers warnings about numeric constantswhich don't fit in 64 bits.Enabled by default.obsolete
is a group alias for all warning classes prefixedbyobsolete-
; currentlyobsolete-nop
,obsolete-removed
, andobsolete-valid
.obsolete-nop
warns for an instruction which has beenremoved from the architecture, but has been architecturally defined to be anoop for future CPUs.Enabled by default.obsolete-removed
warns for an instruction which has beenremoved from the architecture, and is no longer included in the CPUdefinition given in the[CPU]
directive, for examplePOP CS
, the opcode for which,0Fh
, instead is anopcode prefix on CPUs newer than the first generation 8086.Enabled by default.obsolete-valid
warns for an instruction which has beenremoved from the architecture, but is still valid on the specific CPU givenin theCPU
directive. Code using these instructions is mostlikely not forward compatible.Enabled by default.orphan-labels
is a backwards compatibility alias forlabel-orphan
.other
specifies any warning not included in any specificwarning class.Enabled by default.phase
warns about symbols having changed values during thesecond-to-last assembly pass. This is not inherently fatal, but may be asource of bugs.Disabled by default.pragma
is a group alias for all warning classes prefixed bypragma-
; currentlypragma-bad
,pragma-empty
,pragma-na
, andpragma-unknown
.pragma-bad
warns about a malformed or otherwise unparsable%pragma
directive.Disabled by default.pragma-empty
warns about a%pragma
directivecontaining nothing. This is treated identically to%pragma ignore
except for this optional warning.Disabled by default.pragma-na
warns about a%pragma
directivewhich is not applicable to this particular assembly session. This is notyet implemented.Disabled by default.pragma-unknown
warns about an unknown%pragma
directive. This is not yet implemented for most cases.Disabled by default.ptr
warns about keywords used in other assemblers thatmight indicate a mistake in the source code. Currently only the MASMPTR
keyword is recognized. See alsosection 6.5.Enabled by default.regsize
warns about a register with implicit size (such asEAX
, which is always 32 bits) been given an explicit sizespecification which is inconsistent with the size of the named register,e.g.WORD EAX
.DWORD EAX
orWORD AX
are permitted, and do not trigger this warning. Some registers which donot imply a specific size, such asK0
, may need thisspecification unless the instruction itself implies the instruction size:Enabled by default.unknown-pragma
is a backwards compatibility alias forpragma-unknown
.unknown-warning
warns about a-w
or-W
option or a[WARNING]
directive that containsan unknown warning name or is otherwise not possible to process.Disabled by default.user
controls output of%warning
directives(see section 4.9).Enabled by default.warn-stack-empty
a [WARNING POP] directive was executedwhen the warning stack is empty. This is treated as a [WARNING *all]directive.Enabled by default.zeroing
aRESx
directive was used in a sectionwhich contains initialized data, and the output format does not supportthis. Instead, this will be replaced with explicit zero content, which mayproduce a large output file.Enabled by default.zext-reloc
warns that a relocation has been zero-extendeddue to limitations in the output format.Enabled by default.
Since version 2.15, NASM has group aliases for all prefixed warnings, sothey can be used to enable or disable all warnings in the group. Forexample, –w+float enables all warnings with names starting withfloat-*.
Since version 2.00, NASM has also supported the
gcc
–like syntax -Wwarning-class
and-Wno-warning-class
instead of -w+warning-class
and -w-warning-class
, respectively; both syntaxes workidentically.The option
-w+error
or -Werror
can be used totreat warnings as errors. This can be controlled on a per warning classbasis (-w+error=
warning-class or-Werror=
warning-class); if no warning-classis specified NASM treats it as -w+error=all
; the same appliesto -w-error
or -Wno-error
, of course.In addition, you can control warnings in the source code itself, usingthe
[WARNING]
directive. Seesection 7.13.2.1.27 The -v
Option: Display Version Info
Typing
NASM -v
will display the version of NASM which youare using, and the date on which it was compiled.You will need the version number if you report a bug.
For command-line compatibility with Yasm, the form
--v
isalso accepted for this option starting in NASM version 2.11.05.2.1.28 The --(g|l)prefix
, --(g|l)postfix
Options.
The
--(g)prefix
options prepend the given argument to allextern
, common
, static
, andglobal
symbols, and the --lprefix
option prependsto all other symbols. Similarly, --(g)postfix
and--lpostfix
options append the argument in the exactly same wayas the --xxprefix
options does.Running this:
is equivalent to place the directive with
%pragma macho gprefix _
at the start of the file(section 7.10). It will prependthe underscore to all global and external variables, as C requires it insome, but not all, system calling conventions.2.1.29 The --pragma
Option
NASM accepts an argument as
%pragma
option, which is likeplacing a %pragma
preprocess statement at the beginning of thesource. Running this:is equivalent to the example in section2.1.28. See section 4.10.
2.1.30 The --before
Option
A preprocess statement can be accepted with this option. The exampleshown in section 2.1.29 is the same asrunning this:
2.1.31 The --limit-X
Option
This option allows user to setup various maximum values after which NASMwill terminate with a fatal error rather than consume arbitrary amount ofcompute time. Each limit can be set to a positive number or
unlimited
.--limit-passes
: Number of maximum allowed passes. Defaultisunlimited
.--limit-stalled-passes
: Maximum number of allowedunfinished passes. Default is 1000.--limit-macro-levels
: Define maximum depth of macroexpansion (in preprocess). Default is 10000--limit-macro-tokens
: Maximum number of tokens processedduring single-line macro expansion. Default is 10000000.--limit-mmacros
: Maximum number of multi-line macrosprocessed before returning to the top-level input. Default is 100000.--limit-rep
: Maximum number of allowed preprocessor loop,defined under%rep
. Default is 1000000.--limit-eval
: This number sets the boundary condition ofallowed expression length. Default is 8192 on most systems.--limit-lines
: Total number of source lines allowed to beprocessed. Default is 2000000000.
For example, set the maximum line count to 1000:
Limits can also be set via the directive
%pragma limit
, forexample:2.1.32 The --keep-all
Option
This option prevents NASM from deleting any output files even if anerror happens.
2.1.33 The --no-line
Option
If this option is given, all
%line
directives in the sourcecode are ignored. This can be useful for debugging already preprocessedcode. See section 4.11.1.2.1.34 The --reproducible
Option
If this option is given, NASM will not emit information that isinherently dependent on the NASM version or different from run to run (suchas timestamps) into the output file.
2.1.35 The NASMENV
Environment Variable
If you define an environment variable called
NASMENV
, theprogram will interpret it as a list of extra command-line options, whichare processed before the real command line. You can use this to definestandard search directories for include files, by putting -i
options in the NASMENV
variable.The value of the variable is split up at white space, so that the value
-s -ic:nasmlib
will be treated as two separate options.However, that means that the value -dNAME='my name'
won't dowhat you might want, because it will be split at the space and the NASMcommand-line processing will get confused by the two nonsensical words-dNAME='my
and name'
.To get round this, NASM provides a feature whereby, if you begin the
NASMENV
environment variable with some character that isn't aminus sign, then NASM will treat this character as the separator characterfor options. So setting the NASMENV
variable to the value!-s!-ic:nasmlib
is equivalent to setting it to-s -ic:nasmlib
, but !-dNAME='my name'
willwork.This environment variable was previously called
NASM
. Thiswas changed with version 0.98.31.2.2 Quick Start for MASM Users
If you're used to writing programs with MASM, or with TASM inMASM-compatible (non-Ideal) mode, or with
a86
, this sectionattempts to outline the major differences between MASM's syntax and NASM's.If you're not already used to MASM, it's probably worth skipping thissection.2.2.1 NASM Is Case-Sensitive
One simple difference is that NASM is case-sensitive. It makes adifference whether you call your label
foo
, Foo
or FOO
. If you're assembling to DOS
orOS/2
.OBJ
files, you can invoke theUPPERCASE
directive (documented insection 8.4) to ensure that allsymbols exported to other code modules are forced to be upper case; buteven then, within a single module, NASM will distinguish betweenlabels differing only in case.2.2.2 NASM Requires Square Brackets For Memory References
NASM was designed with simplicity of syntax in mind. One of the designgoals of NASM is that it should be possible, as far as is practical, forthe user to look at a single line of NASM code and tell what opcode isgenerated by it. You can't do this in MASM: if you declare, for example,
then the two lines of code
generate completely different opcodes, despite having identical-lookingsyntaxes.
Nasm Macos Format
NASM avoids this undesirable situation by having a much simpler syntaxfor memory references. The rule is simply that any access to thecontents of a memory location requires square brackets around theaddress, and any access to the address of a variable doesn't. Soan instruction of the form
mov ax,foo
will alwaysrefer to a compile-time constant, whether it's an EQU
or theaddress of a variable; and to access the contents of the variablebar
, you must code mov ax,[bar]
.This also means that NASM has no need for MASM's
OFFSET
keyword, since the MASM code mov ax,offset bar
means exactlythe same thing as NASM's mov ax,bar
. If you're trying to getlarge amounts of MASM code to assemble sensibly under NASM, you can alwayscode %idefine offset
to make the preprocessor treat theOFFSET
keyword as a no-op.This issue is even more confusing in
a86
, where declaring alabel with a trailing colon defines it to be a `label' as opposed to a`variable' and causes a86
to adopt NASM-style semantics; so ina86
, mov ax,var
has different behaviour dependingon whether var
was declared as var: dw 0
(alabel) or var dw 0
(a word-size variable). NASM is very simpleby comparison: everything is a label.NASM, in the interests of simplicity, also does not support the hybridsyntaxes supported by MASM and its clones, such as
mov ax,table[bx]
, where a memory reference is denoted by oneportion outside square brackets and another portion inside. The correctsyntax for the above is mov ax,[table+bx]
. Likewise,mov ax,es:[di]
is wrong and mov ax,[es:di]
isright.2.2.3 NASM Doesn't Store Variable Types
NASM, by design, chooses not to remember the types of variables youdeclare. Whereas MASM will remember, on seeing
var dw 0
, thatyou declared var
as a word-size variable, and will then beable to fill in the ambiguity in the size of the instructionmov var,2
, NASM will deliberately remember nothing about thesymbol var
except where it begins, and so you must explicitlycode mov word [var],2
.Nasm Mac Os X
For this reason, NASM doesn't support the
LODS
,MOVS
, STOS
, SCAS
, CMPS
,INS
, or OUTS
instructions, but only supports theforms such as LODSB
, MOVSW
, andSCASD
, which explicitly specify the size of the components ofthe strings being manipulated.2.2.4 NASM Doesn't ASSUME
As part of NASM's drive for simplicity, it also does not support the
ASSUME
directive. NASM will not keep track of what values youchoose to put in your segment registers, and will neverautomatically generate a segment override prefix.2.2.5 NASM Doesn't Support Memory Models
NASM also does not have any directives to support different 16-bitmemory models. The programmer has to keep track of which functions aresupposed to be called with a far call and which with a near call, and isresponsible for putting the correct form of
RET
instruction(RETN
or RETF
; NASM accepts RET
itself as an alternate form for RETN
); in addition, theprogrammer is responsible for coding CALL FAR instructions where necessarywhen calling external functions, and must also keep track of whichexternal variable definitions are far and which are near.2.2.6 Floating-Point Differences
NASM uses different names to refer to floating-point registers fromMASM: where MASM would call them
ST(0)
, ST(1)
andso on, and a86
would call them simply 0
,1
and so on, NASM chooses to call them st0
,st1
etc.As of version 0.96, NASM now treats the instructions with `nowait' formsin the same way as MASM-compatible assemblers. The idiosyncratic treatmentemployed by 0.95 and earlier was based on a misunderstanding by theauthors.
2.2.7 Other Differences
For historical reasons, NASM uses the keyword
TWORD
whereMASM and compatible assemblers use TBYTE
.Historically, NASM does not declare uninitialized storage in the sameway as MASM: where a MASM programmer might use
stack db 64 dup (?)
, NASM requires stack resb 64
,intended to be read as `reserve 64 bytes'. For a limited amount ofcompatibility, since NASM treats ?
as a valid character insymbol names, you can code ? equ 0
and then writingdw ?
will at least do something vaguely useful.As of NASM 2.15, the MASM syntax is also supported.
Nasm For Mac Os 10.10
In addition to all of this, macros and directives work completelydifferently to MASM. See chapter 4 andchapter 7 for further details.
2.2.8 MASM compatibility package
Nasm Example
See section 6.5.