1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2018 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * The Netwide Assembler main program module
61 * This is the maximum number of optimization passes to do. If we ever
62 * find a case where the optimizer doesn't naturally converge, we might
63 * have to drop this value so the assembler doesn't appear to just hang.
65 #define MAX_OPTIMIZE (INT_MAX >> 1)
67 struct forwrefinfo
{ /* info held on forward refs. */
72 const char *_progname
;
74 static void parse_cmdline(int, char **, int);
75 static void assemble_file(const char *, struct strlist
*);
76 static bool skip_this_pass(errflags severity
);
77 static void nasm_verror_asm(errflags severity
, const char *fmt
, va_list args
);
78 static void usage(void);
79 static void help(FILE *);
82 const char *beforeline
; /* Before line number, if present */
83 const char *afterline
; /* After line number, if present */
84 const char *beforemsg
; /* Before actual message */
87 static const struct error_format errfmt_gnu
= { ":", "", ": " };
88 static const struct error_format errfmt_msvc
= { "(", ")", " : " };
89 static const struct error_format
*errfmt
= &errfmt_gnu
;
90 static struct strlist
*warn_list
;
92 unsigned int debug_nasm
; /* Debugging messages? */
94 static bool using_debug_info
, opt_verbose_info
;
95 static const char *debug_format
;
97 #ifndef ABORT_ON_PANIC
98 # define ABORT_ON_PANIC 0
100 static bool abort_on_panic
= ABORT_ON_PANIC
;
101 static bool keep_all
;
103 bool tasm_compatible_mode
= false;
104 enum pass_type _pass_type
;
105 const char * const _pass_types
[] =
107 "init", "first", "optimize", "stabilize", "final"
113 struct compile_time official_compile_time
;
117 static const char *listname
;
118 static const char *errname
;
120 static int64_t globallineno
; /* for forward-reference tracking */
122 const struct ofmt
*ofmt
= &OF_DEFAULT
;
123 const struct ofmt_alias
*ofmt_alias
= NULL
;
124 const struct dfmt
*dfmt
;
126 FILE *error_file
; /* Where to write error messages */
129 struct optimization optimizing
=
130 { MAX_OPTIMIZE
, OPTIM_ALL_ENABLED
}; /* number of optimization passes to take */
131 static int cmd_sb
= 16; /* by default */
134 static iflag_t cmd_cpu
;
136 struct location location
;
137 bool in_absolute
; /* Flag we are in ABSOLUTE seg */
138 struct location absolute
; /* Segment/offset inside ABSOLUTE */
140 static struct RAA
*offsets
;
142 static struct SAA
*forwrefs
; /* keep track of forward references */
143 static const struct forwrefinfo
*forwref
;
145 static const struct preproc_ops
*preproc
;
146 static struct strlist
*include_path
;
147 bool pp_noline
; /* Ignore %line directives */
149 #define OP_NORMAL (1U << 0)
150 #define OP_PREPROCESS (1U << 1)
151 #define OP_DEPEND (1U << 2)
153 static unsigned int operating_mode
;
155 /* Dependency flags */
156 static bool depend_emit_phony
= false;
157 static bool depend_missing_ok
= false;
158 static const char *depend_target
= NULL
;
159 static const char *depend_file
= NULL
;
160 struct strlist
*depend_list
;
162 static bool want_usage
;
163 static bool terminate_after_phase
;
164 bool user_nolist
= false;
166 static char *quote_for_pmake(const char *str
);
167 static char *quote_for_wmake(const char *str
);
168 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
171 * Execution limits that can be set via a command-line option or %pragma
175 * This is really unlimited; it would take far longer than the
176 * current age of the universe for this limit to be reached even on
177 * much faster CPUs than currently exist.
179 #define LIMIT_MAX_VAL (INT64_MAX >> 1)
181 int64_t nasm_limit
[LIMIT_MAX
+1];
188 /* The order here must match enum nasm_limit in nasm.h */
189 static const struct limit_info limit_info
[LIMIT_MAX
+1] = {
190 { "passes", "total number of passes", LIMIT_MAX_VAL
},
191 { "stalled-passes", "number of passes without forward progress", 1000 },
192 { "macro-levels", "levels of macro expansion", 10000 },
193 { "macro-tokens", "tokens processed during macro expansion", 10000000 },
194 { "rep", "%rep count", 1000000 },
195 { "eval", "expression evaluation descent", 1000000},
196 { "lines", "total source lines processed", 2000000000 }
199 static void set_default_limits(void)
202 for (i
= 0; i
<= LIMIT_MAX
; i
++)
203 nasm_limit
[i
] = limit_info
[i
].default_val
;
206 enum directive_result
207 nasm_set_limit(const char *limit
, const char *valstr
)
214 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
215 if (!nasm_stricmp(limit
, limit_info
[i
].name
))
220 errlevel
= ERR_WARNING
|WARN_OTHER
|ERR_USAGE
;
222 errlevel
= ERR_WARNING
|WARN_PRAGMA_UNKNOWN
;
223 nasm_error(errlevel
, "unknown limit: `%s'", limit
);
227 if (!nasm_stricmp(valstr
, "unlimited")) {
230 val
= readnum(valstr
, &rn_error
);
231 if (rn_error
|| val
< 0) {
233 errlevel
= ERR_WARNING
|WARN_OTHER
|ERR_USAGE
;
235 errlevel
= ERR_WARNING
|WARN_PRAGMA_BAD
;
236 nasm_error(errlevel
, "invalid limit value: `%s'", limit
);
239 if (val
> LIMIT_MAX_VAL
)
247 int64_t switch_segment(int32_t segment
)
249 location
.segment
= segment
;
250 if (segment
== NO_SEG
) {
251 location
.offset
= absolute
.offset
;
254 location
.offset
= raa_read(offsets
, segment
);
257 return location
.offset
;
260 static void set_curr_offs(int64_t l_off
)
263 absolute
.offset
= l_off
;
265 offsets
= raa_write(offsets
, location
.segment
, l_off
);
268 static void increment_offset(int64_t delta
)
270 if (unlikely(delta
== 0))
273 location
.offset
+= delta
;
274 set_curr_offs(location
.offset
);
277 static void nasm_fputs(const char *line
, FILE * outfile
)
280 fputs(line
, outfile
);
287 * Define system-defined macros that are not part of
288 * macros/standard.mac.
290 static void define_macros(void)
292 const struct compile_time
* const oct
= &official_compile_time
;
295 if (oct
->have_local
) {
296 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
297 preproc
->pre_define(temp
);
298 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
299 preproc
->pre_define(temp
);
300 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
301 preproc
->pre_define(temp
);
302 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
303 preproc
->pre_define(temp
);
307 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
308 preproc
->pre_define(temp
);
309 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
310 preproc
->pre_define(temp
);
311 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
312 preproc
->pre_define(temp
);
313 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
314 preproc
->pre_define(temp
);
317 if (oct
->have_posix
) {
318 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
319 preproc
->pre_define(temp
);
323 * In case if output format is defined by alias
324 * we have to put shortname of the alias itself here
325 * otherwise ABI backward compatibility gets broken.
327 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s",
328 ofmt_alias
? ofmt_alias
->shortname
: ofmt
->shortname
);
329 preproc
->pre_define(temp
);
332 * Output-format specific macros.
335 preproc
->extra_stdmac(ofmt
->stdmac
);
338 * Debug format, if any
340 if (dfmt
!= &null_debug_form
) {
341 snprintf(temp
, sizeof(temp
), "__DEBUG_FORMAT__=%s", dfmt
->shortname
);
342 preproc
->pre_define(temp
);
347 * Initialize the preprocessor, set up the include path, and define
348 * the system-included macros. This is called between passes 1 and 2
349 * of parsing the command options; ofmt and dfmt are defined at this
352 * Command-line specified preprocessor directives (-p, -d, -u,
353 * --pragma, --before) are processed after this function.
355 static void preproc_init(struct strlist
*ipath
)
359 preproc
->include_path(ipath
);
362 static void emit_dependencies(struct strlist
*list
)
366 bool wmake
= (quote_for_make
== quote_for_wmake
);
367 const char *wrapstr
, *nulltarget
;
368 const struct strlist_entry
*l
;
373 wrapstr
= wmake
? " &\n " : " \\\n ";
374 nulltarget
= wmake
? "\t%null\n" : "";
376 if (depend_file
&& strcmp(depend_file
, "-")) {
377 deps
= nasm_open_write(depend_file
, NF_TEXT
);
379 nasm_nonfatal("unable to write dependency file `%s'", depend_file
);
386 linepos
= fprintf(deps
, "%s :", depend_target
);
387 strlist_for_each(l
, list
) {
388 char *file
= quote_for_make(l
->str
);
390 if (linepos
+ len
> 62 && linepos
> 1) {
391 fputs(wrapstr
, deps
);
394 fprintf(deps
, " %s", file
);
400 strlist_for_each(l
, list
) {
401 if (depend_emit_phony
) {
402 char *file
= quote_for_make(l
->str
);
403 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
414 /* Convert a struct tm to a POSIX-style time constant */
415 static int64_t make_posix_time(const struct tm
*tm
)
418 int64_t y
= tm
->tm_year
;
420 /* See IEEE 1003.1:2004, section 4.14 */
422 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
434 static void timestamp(void)
436 struct compile_time
* const oct
= &official_compile_time
;
437 const struct tm
*tp
, *best_gm
;
443 tp
= localtime(&oct
->t
);
446 best_gm
= &oct
->local
;
447 oct
->have_local
= true;
450 tp
= gmtime(&oct
->t
);
455 if (!oct
->have_local
)
456 oct
->local
= oct
->gm
;
458 oct
->gm
= oct
->local
;
462 oct
->posix
= make_posix_time(best_gm
);
463 oct
->have_posix
= true;
467 int main(int argc
, char **argv
)
470 if (!_progname
|| !_progname
[0])
477 iflag_set_default_cpu(&cpu
);
478 iflag_set_default_cpu(&cmd_cpu
);
480 set_default_limits();
482 include_path
= strlist_alloc(true);
484 _pass_type
= PASS_INIT
;
487 want_usage
= terminate_after_phase
= false;
488 nasm_set_verror(nasm_verror_asm
);
494 * We must call init_labels() before the command line parsing,
495 * because we may be setting prefixes/suffixes from the command
500 offsets
= raa_init();
501 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
504 operating_mode
= OP_NORMAL
;
506 parse_cmdline(argc
, argv
, 1);
507 if (terminate_after_phase
) {
513 /* At this point we have ofmt and the name of the desired debug format */
514 if (!using_debug_info
) {
515 /* No debug info, redirect to the null backend (empty stubs) */
516 dfmt
= &null_debug_form
;
517 } else if (!debug_format
) {
518 /* Default debug format for this backend */
519 dfmt
= ofmt
->default_dfmt
;
521 dfmt
= dfmt_find(ofmt
, debug_format
);
523 nasm_fatalf(ERR_USAGE
, "unrecognized debug format `%s' for output format `%s'",
524 debug_format
, ofmt
->shortname
);
528 preproc_init(include_path
);
530 parse_cmdline(argc
, argv
, 2);
531 if (terminate_after_phase
) {
537 /* Save away the default state of warnings */
540 /* Dependency filename if we are also doing other things */
541 if (!depend_file
&& (operating_mode
& ~OP_DEPEND
)) {
543 depend_file
= nasm_strcat(outname
, ".d");
545 depend_file
= filename_set_extension(inname
, ".d");
549 * If no output file name provided and this
550 * is preprocess mode, we're perfectly
551 * fine to output into stdout.
553 if (!outname
&& !(operating_mode
& OP_PREPROCESS
)) {
554 outname
= filename_set_extension(inname
, ofmt
->extension
);
555 if (!strcmp(outname
, inname
)) {
556 outname
= "nasm.out";
557 nasm_warn(WARN_OTHER
, "default output file same as input, using `%s' for output\n", outname
);
561 depend_list
= (operating_mode
& OP_DEPEND
) ? strlist_alloc(true) : NULL
;
564 depend_target
= quote_for_make(outname
);
566 if (!(operating_mode
& (OP_PREPROCESS
|OP_NORMAL
))) {
569 if (depend_missing_ok
)
570 preproc
->include_path(NULL
); /* "assume generated" */
572 preproc
->reset(inname
, PP_DEPS
, depend_list
);
574 while ((line
= preproc
->getline()))
576 preproc
->cleanup_pass();
578 } else if (operating_mode
& OP_PREPROCESS
) {
580 const char *file_name
= NULL
;
581 int32_t prior_linnum
= 0;
585 ofile
= nasm_open_write(outname
, NF_TEXT
);
587 nasm_fatal("unable to open output file `%s'", outname
);
591 location
.known
= false;
593 _pass_type
= PASS_FIRST
; /* We emulate this assembly pass */
594 preproc
->reset(inname
, PP_PREPROC
, depend_list
);
596 while ((line
= preproc
->getline())) {
598 * We generate %line directives if needed for later programs
600 int32_t linnum
= prior_linnum
+= lineinc
;
601 int altline
= src_get(&linnum
, &file_name
);
603 if (altline
== 1 && lineinc
== 1)
604 nasm_fputs("", ofile
);
606 lineinc
= (altline
!= -1 || lineinc
!= 1);
607 fprintf(ofile
? ofile
: stdout
,
608 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
611 prior_linnum
= linnum
;
613 nasm_fputs(line
, ofile
);
616 preproc
->cleanup_pass();
620 if (ofile
&& terminate_after_phase
&& !keep_all
)
625 if (operating_mode
& OP_NORMAL
) {
626 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
628 nasm_fatal("unable to open output file `%s'", outname
);
633 assemble_file(inname
, depend_list
);
635 if (!terminate_after_phase
) {
640 nasm_nonfatal("write error on output file `%s'", outname
);
645 if (terminate_after_phase
&& !keep_all
)
651 preproc
->cleanup_session();
653 if (depend_list
&& !terminate_after_phase
)
654 emit_dependencies(depend_list
);
664 strlist_free(&include_path
);
666 return terminate_after_phase
;
670 * Get a parameter for a command line option.
671 * First arg must be in the form of e.g. -f...
673 static char *get_param(char *p
, char *q
, bool *advance
)
676 if (p
[2]) /* the parameter's in the option */
677 return nasm_skip_spaces(p
+ 2);
682 nasm_nonfatalf(ERR_USAGE
, "option `-%c' requires an argument", p
[1]);
689 static void copy_filename(const char **dst
, const char *src
, const char *what
)
692 nasm_fatal("more than one %s file specified: %s\n", what
, src
);
694 *dst
= nasm_strdup(src
);
698 * Convert a string to a POSIX make-safe form
700 static char *quote_for_pmake(const char *str
)
705 size_t n
= 1; /* Terminating zero */
711 for (p
= str
; *p
; p
++) {
715 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
735 /* Convert N backslashes at the end of filename to 2N backslashes */
739 os
= q
= nasm_malloc(n
);
742 for (p
= str
; *p
; p
++) {
780 * Convert a string to a Watcom make-safe form
782 static char *quote_for_wmake(const char *str
)
788 size_t n
= 1; /* Terminating zero */
793 for (p
= str
; *p
; p
++) {
818 os
= q
= nasm_malloc(n
);
823 for (p
= str
; *p
; p
++) {
870 enum text_options opt
;
871 enum need_arg need_arg
;
874 static const struct textargs textopts
[] = {
875 {"v", OPT_VERSION
, ARG_NO
, 0},
876 {"version", OPT_VERSION
, ARG_NO
, 0},
877 {"help", OPT_HELP
, ARG_NO
, 0},
878 {"abort-on-panic", OPT_ABORT_ON_PANIC
, ARG_NO
, 0},
879 {"prefix", OPT_MANGLE
, ARG_YES
, LM_GPREFIX
},
880 {"postfix", OPT_MANGLE
, ARG_YES
, LM_GSUFFIX
},
881 {"gprefix", OPT_MANGLE
, ARG_YES
, LM_GPREFIX
},
882 {"gpostfix", OPT_MANGLE
, ARG_YES
, LM_GSUFFIX
},
883 {"lprefix", OPT_MANGLE
, ARG_YES
, LM_LPREFIX
},
884 {"lpostfix", OPT_MANGLE
, ARG_YES
, LM_LSUFFIX
},
885 {"include", OPT_INCLUDE
, ARG_YES
, 0},
886 {"pragma", OPT_PRAGMA
, ARG_YES
, 0},
887 {"before", OPT_BEFORE
, ARG_YES
, 0},
888 {"limit-", OPT_LIMIT
, ARG_YES
, 0},
889 {"keep-all", OPT_KEEP_ALL
, ARG_NO
, 0},
890 {"no-line", OPT_NO_LINE
, ARG_NO
, 0},
891 {"debug", OPT_DEBUG
, ARG_MAYBE
, 0},
892 {NULL
, OPT_BOGUS
, ARG_NO
, 0}
895 static void show_version(void)
897 printf("NASM version %s compiled on %s%s\n",
898 nasm_version
, nasm_date
, nasm_compile_options
);
902 static bool stopoptions
= false;
903 static bool process_arg(char *p
, char *q
, int pass
)
906 bool advance
= false;
911 if (p
[0] == '-' && !stopoptions
) {
912 if (strchr("oOfpPdDiIlLFXuUZwW", p
[1])) {
913 /* These parameters take values */
914 if (!(param
= get_param(p
, q
, &advance
)))
924 case 'o': /* output file */
926 copy_filename(&outname
, param
, "output");
929 case 'f': /* output format */
931 ofmt
= ofmt_find(param
, &ofmt_alias
);
933 nasm_fatalf(ERR_USAGE
, "unrecognised output format `%s' - use -hf for a list", param
);
938 case 'O': /* Optimization level */
943 /* Naked -O == -Ox */
944 optimizing
.level
= MAX_OPTIMIZE
;
948 case '0': case '1': case '2': case '3': case '4':
949 case '5': case '6': case '7': case '8': case '9':
950 opt
= strtoul(param
, ¶m
, 10);
952 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
953 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
955 optimizing
.level
= opt
- 1;
957 optimizing
.level
= opt
;
963 opt_verbose_info
= true;
968 optimizing
.level
= MAX_OPTIMIZE
;
972 nasm_fatal("unknown optimization option -O%c\n",
977 if (optimizing
.level
> MAX_OPTIMIZE
)
978 optimizing
.level
= MAX_OPTIMIZE
;
983 case 'p': /* pre-include */
986 preproc
->pre_include(param
);
989 case 'd': /* pre-define */
992 preproc
->pre_define(param
);
995 case 'u': /* un-define */
998 preproc
->pre_undefine(param
);
1001 case 'i': /* include search path */
1004 strlist_add(include_path
, param
);
1007 case 'l': /* listing file */
1009 copy_filename(&listname
, param
, "listing");
1012 case 'L': /* listing options */
1015 list_options
|= list_option_mask(*param
++);
1019 case 'Z': /* error messages file */
1021 copy_filename(&errname
, param
, "error");
1024 case 'F': /* specify debug format */
1026 using_debug_info
= true;
1027 debug_format
= param
;
1031 case 'X': /* specify error reporting format */
1033 if (!nasm_stricmp("vc", param
) || !nasm_stricmp("msvc", param
) || !nasm_stricmp("ms", param
))
1034 errfmt
= &errfmt_msvc
;
1035 else if (!nasm_stricmp("gnu", param
) || !nasm_stricmp("gcc", param
))
1036 errfmt
= &errfmt_gnu
;
1038 nasm_fatalf(ERR_USAGE
, "unrecognized error reporting format `%s'", param
);
1044 using_debug_info
= true;
1046 debug_format
= nasm_skip_spaces(p
+ 2);
1052 exit(0); /* never need usage message here */
1063 tasm_compatible_mode
= true;
1064 nasm_ctype_tasm_mode();
1072 case 'e': /* preprocess only */
1075 operating_mode
= OP_PREPROCESS
;
1078 case 'a': /* assemble only - don't preprocess */
1080 preproc
= &preproc_nop
;
1086 set_warning_status(param
);
1093 quote_for_make
= quote_for_wmake
;
1107 operating_mode
= OP_DEPEND
;
1110 operating_mode
= OP_DEPEND
;
1111 depend_missing_ok
= true;
1114 depend_emit_phony
= true;
1117 operating_mode
|= OP_DEPEND
;
1118 if (q
&& (q
[0] != '-' || q
[1] == '\0')) {
1132 depend_target
= quote_for_make(q
);
1136 /* handled in pass 1 */
1139 nasm_nonfatalf(ERR_USAGE
, "unknown dependency option `-M%c'", p
[2]);
1143 if (advance
&& (!q
|| !q
[0])) {
1144 nasm_nonfatalf(ERR_USAGE
, "option `-M%c' requires a parameter", p
[2]);
1151 const struct textargs
*tx
;
1154 enum text_options opt
;
1158 if (!*p
) { /* -- => stop processing options */
1163 olen
= 0; /* Placate gcc at lower optimization levels */
1165 for (tx
= textopts
; tx
->label
; tx
++) {
1166 olen
= strlen(tx
->label
);
1171 if (nasm_memicmp(p
, tx
->label
, olen
))
1174 if (tx
->label
[olen
-1] == '-')
1175 break; /* Incomplete option */
1177 if (!p
[olen
] || p
[olen
] == '=')
1178 break; /* Complete option */
1182 nasm_nonfatalf(ERR_USAGE
, "unrecognized option `--%s'", p
);
1187 eqsave
= param
= strchr(p
+olen
, '=');
1191 switch (tx
->need_arg
) {
1192 case ARG_YES
: /* Argument required, and may be standalone */
1198 /* Note: a null string is a valid parameter */
1200 nasm_nonfatalf(ERR_USAGE
, "option `--%s' requires an argument", p
);
1205 case ARG_NO
: /* Argument prohibited */
1207 nasm_nonfatalf(ERR_USAGE
, "option `--%s' does not take an argument", p
);
1212 case ARG_MAYBE
: /* Argument permitted, but must be attached with = */
1218 break; /* We have already errored out */
1222 case OPT_ABORT_ON_PANIC
:
1223 abort_on_panic
= true;
1227 set_label_mangle(tx
->pvt
, param
);
1231 preproc
->pre_include(q
);
1235 preproc
->pre_command("pragma", param
);
1239 preproc
->pre_command(NULL
, param
);
1243 nasm_set_limit(p
+olen
, param
);
1252 debug_nasm
= param
? strtoul(param
, NULL
, 10) : debug_nasm
+1;
1262 *eqsave
= '='; /* Restore = argument separator */
1268 nasm_nonfatalf(ERR_USAGE
, "unrecognised option `-%c'", p
[1]);
1271 } else if (pass
== 2) {
1272 /* In theory we could allow multiple input files... */
1273 copy_filename(&inname
, p
, "input");
1279 #define ARG_BUF_DELTA 128
1281 static void process_respfile(FILE * rfile
, int pass
)
1283 char *buffer
, *p
, *q
, *prevarg
;
1284 int bufsize
, prevargsize
;
1286 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1287 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1288 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1291 while (1) { /* Loop to handle all lines in file */
1293 while (1) { /* Loop to handle long lines */
1294 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1298 if (p
> buffer
&& p
[-1] == '\n')
1300 if (p
- buffer
> bufsize
- 10) {
1302 offset
= p
- buffer
;
1303 bufsize
+= ARG_BUF_DELTA
;
1304 buffer
= nasm_realloc(buffer
, bufsize
);
1305 p
= buffer
+ offset
;
1309 if (!q
&& p
== buffer
) {
1311 process_arg(prevarg
, NULL
, pass
);
1318 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1319 * them are present at the end of the line.
1321 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1323 while (p
> buffer
&& nasm_isspace(p
[-1]))
1326 p
= nasm_skip_spaces(buffer
);
1328 if (process_arg(prevarg
, p
, pass
))
1331 if ((int) strlen(p
) > prevargsize
- 10) {
1332 prevargsize
+= ARG_BUF_DELTA
;
1333 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1335 strncpy(prevarg
, p
, prevargsize
);
1339 /* Function to process args from a string of args, rather than the
1340 * argv array. Used by the environment variable and response file
1343 static void process_args(char *args
, int pass
)
1345 char *p
, *q
, *arg
, *prevarg
;
1346 char separator
= ' ';
1349 if (*p
&& *p
!= '-')
1354 while (*p
&& *p
!= separator
)
1356 while (*p
== separator
)
1360 if (process_arg(prevarg
, arg
, pass
))
1364 process_arg(arg
, NULL
, pass
);
1367 static void process_response_file(const char *file
, int pass
)
1370 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1375 while (fgets(str
, sizeof str
, f
)) {
1376 process_args(str
, pass
);
1381 static void parse_cmdline(int argc
, char **argv
, int pass
)
1384 char *envreal
, *envcopy
= NULL
, *p
;
1387 * Initialize all the warnings to their default state, including
1388 * warning index 0 used for "always on".
1390 memcpy(warning_state
, warning_default
, sizeof warning_state
);
1393 * First, process the NASMENV environment variable.
1395 envreal
= getenv("NASMENV");
1397 envcopy
= nasm_strdup(envreal
);
1398 process_args(envcopy
, pass
);
1403 * Now process the actual command line.
1408 if (argv
[0][0] == '@') {
1410 * We have a response file, so process this as a set of
1411 * arguments like the environment variable. This allows us
1412 * to have multiple arguments on a single line, which is
1413 * different to the -@resp file processing below for regular
1416 process_response_file(argv
[0]+1, pass
);
1420 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1421 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1423 rfile
= nasm_open_read(p
, NF_TEXT
);
1425 process_respfile(rfile
, pass
);
1428 nasm_nonfatalf(ERR_USAGE
, "unable to open response file `%s'", p
);
1432 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1433 argv
+= advance
, argc
-= advance
;
1437 * Look for basic command line typos. This definitely doesn't
1438 * catch all errors, but it might help cases of fumbled fingers.
1444 nasm_fatalf(ERR_USAGE
, "no input file specified");
1445 else if ((errname
&& !strcmp(inname
, errname
)) ||
1446 (outname
&& !strcmp(inname
, outname
)) ||
1447 (listname
&& !strcmp(inname
, listname
)) ||
1448 (depend_file
&& !strcmp(inname
, depend_file
)))
1449 nasm_fatalf(ERR_USAGE
, "will not overwrite input file");
1452 error_file
= nasm_open_write(errname
, NF_TEXT
);
1454 error_file
= stderr
; /* Revert to default! */
1455 nasm_fatalf(ERR_USAGE
, "cannot open file `%s' for error messages", errname
);
1460 static void forward_refs(insn
*instruction
)
1463 struct forwrefinfo
*fwinf
;
1465 instruction
->forw_ref
= false;
1467 if (!optimizing
.level
)
1468 return; /* For -O0 don't bother */
1473 if (forwref
->lineno
!= globallineno
)
1476 instruction
->forw_ref
= true;
1478 instruction
->oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1479 forwref
= saa_rstruct(forwrefs
);
1480 } while (forwref
&& forwref
->lineno
== globallineno
);
1485 for (i
= 0; i
< instruction
->operands
; i
++) {
1486 if (instruction
->oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1487 fwinf
= saa_wstruct(forwrefs
);
1488 fwinf
->lineno
= globallineno
;
1494 static void process_insn(insn
*instruction
)
1499 if (!instruction
->times
)
1500 return; /* Nothing to do... */
1502 nasm_assert(instruction
->times
> 0);
1505 * NOTE: insn_size() can change instruction->times
1506 * (usually to 1) when called.
1508 if (!pass_final()) {
1509 int64_t start
= location
.offset
;
1510 for (n
= 1; n
<= instruction
->times
; n
++) {
1511 l
= insn_size(location
.segment
, location
.offset
,
1512 globalbits
, instruction
);
1513 /* l == -1 -> invalid instruction */
1515 increment_offset(l
);
1517 if (list_option('p')) {
1518 struct out_data dummy
;
1519 memset(&dummy
, 0, sizeof dummy
);
1520 dummy
.type
= OUT_RAWDATA
; /* Handled specially with .data NULL */
1521 dummy
.offset
= start
;
1522 dummy
.size
= location
.offset
- start
;
1523 lfmt
->output(&dummy
);
1526 l
= assemble(location
.segment
, location
.offset
,
1527 globalbits
, instruction
);
1528 /* We can't get an invalid instruction here */
1529 increment_offset(l
);
1531 if (instruction
->times
> 1) {
1532 lfmt
->uplevel(LIST_TIMES
, instruction
->times
);
1533 for (n
= 2; n
<= instruction
->times
; n
++) {
1534 l
= assemble(location
.segment
, location
.offset
,
1535 globalbits
, instruction
);
1536 increment_offset(l
);
1538 lfmt
->downlevel(LIST_TIMES
);
1543 static void assemble_file(const char *fname
, struct strlist
*depend_list
)
1547 uint64_t prev_offset_changed
;
1548 int64_t stall_count
= 0; /* Make sure we make forward progress... */
1554 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_386
))
1555 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1558 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_X86_64
))
1559 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1566 prev_offset_changed
= INT64_MAX
;
1568 if (listname
&& !keep_all
) {
1569 /* Remove the list file in case we die before the output pass */
1573 while (!terminate_after_phase
&& !pass_final()) {
1575 if (pass_type() != PASS_OPT
|| !global_offset_changed
)
1577 global_offset_changed
= 0;
1580 * Create a warning buffer list unless we are in
1581 * pass 2 (everything will be emitted immediately in pass 2.)
1584 if (warn_list
->nstr
|| pass_final())
1585 strlist_free(&warn_list
);
1588 if (!pass_final() && !warn_list
)
1589 warn_list
= strlist_alloc(false);
1591 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1594 if (pass_final() || list_on_every_pass()) {
1595 active_list_options
= list_options
;
1596 lfmt
->init(listname
);
1597 } else if (active_list_options
) {
1599 * Looks like we used the list engine on a previous pass,
1600 * but now it is turned off, presumably via %pragma -p
1605 active_list_options
= 0;
1609 in_absolute
= false;
1610 if (!pass_first()) {
1611 saa_rewind(forwrefs
);
1612 forwref
= saa_rstruct(forwrefs
);
1614 offsets
= raa_init();
1616 location
.segment
= NO_SEG
;
1617 location
.offset
= 0;
1619 location
.known
= true;
1621 switch_segment(ofmt
->section(NULL
, &globalbits
));
1622 preproc
->reset(fname
, PP_NORMAL
, pass_final() ? depend_list
: NULL
);
1626 while ((line
= preproc
->getline())) {
1627 if (++globallineno
> nasm_limit
[LIMIT_LINES
])
1628 nasm_fatal("overall line count exceeds the maximum %"PRId64
"\n",
1629 nasm_limit
[LIMIT_LINES
]);
1632 * Here we parse our directives; this is not handled by the
1635 if (process_directives(line
))
1636 goto end_of_line
; /* Just do final cleanup */
1638 /* Not a directive, or even something that starts with [ */
1639 parse_line(line
, &output_ins
);
1640 forward_refs(&output_ins
);
1641 process_insn(&output_ins
);
1642 cleanup_insn(&output_ins
);
1646 } /* end while (line = preproc->getline... */
1648 preproc
->cleanup_pass();
1650 if (global_offset_changed
) {
1651 switch (pass_type()) {
1654 * This is the only pass type that can be executed more
1655 * than once, and therefore has the ability to stall.
1657 if (global_offset_changed
< prev_offset_changed
) {
1658 prev_offset_changed
= global_offset_changed
;
1664 if (stall_count
> nasm_limit
[LIMIT_STALLED
] ||
1665 pass_count() >= nasm_limit
[LIMIT_PASSES
]) {
1666 /* No convergence, almost certainly dead */
1667 nasm_nonfatalf(ERR_UNDEAD
,
1668 "unable to find valid values for all labels "
1669 "after %"PRId64
" passes; "
1670 "stalled for %"PRId64
", giving up.",
1671 pass_count(), stall_count
);
1672 nasm_nonfatalf(ERR_UNDEAD
,
1673 "Possible causes: recursive EQUs, macro abuse.");
1679 *!phase [off] phase error during stabilization
1680 *! warns about symbols having changed values during
1681 *! the second-to-last assembly pass. This is not
1682 *! inherently fatal, but may be a source of bugs.
1684 nasm_warn(WARN_PHASE
|ERR_UNDEAD
,
1685 "phase error during stabilization "
1686 "pass, hoping for the best");
1690 nasm_nonfatalf(ERR_UNDEAD
,
1691 "phase error during code generation pass");
1695 /* This is normal, we'll keep going... */
1703 if (opt_verbose_info
&& pass_final()) {
1704 /* -On and -Ov switches */
1705 nasm_info("assembly required 1+%"PRId64
"+2 passes\n", pass_count()-3);
1709 strlist_free(&warn_list
);
1713 * get warning index; 0 if this is non-suppressible.
1715 static size_t warn_index(errflags severity
)
1719 if ((severity
& ERR_MASK
) >= ERR_FATAL
)
1720 return 0; /* Fatal errors are never suppressible */
1722 /* Warnings MUST HAVE a warning category specifier! */
1723 nasm_assert((severity
& (ERR_MASK
|WARN_MASK
)) != ERR_WARNING
);
1725 index
= WARN_IDX(severity
);
1726 nasm_assert(index
< WARN_IDX_ALL
);
1731 static bool skip_this_pass(errflags severity
)
1733 errflags type
= severity
& ERR_MASK
;
1736 * See if it's a pass-specific error or warning which should be skipped.
1737 * We can never skip fatal errors as by definition they cannot be
1740 if (type
>= ERR_FATAL
)
1744 * ERR_LISTMSG messages are always skipped; the list file
1745 * receives them anyway as this function is not consulted
1746 * for sending to the list file.
1748 if (type
== ERR_LISTMSG
)
1751 /* This message not applicable unless pass_final */
1752 return (severity
& ERR_PASS2
) && !pass_final();
1756 * check for suppressed message (usually warnings or notes)
1758 * @param severity the severity of the warning or error
1759 * @return true if we should abort error/warning printing
1761 static bool is_suppressed(errflags severity
)
1763 /* Fatal errors must never be suppressed */
1764 if ((severity
& ERR_MASK
) >= ERR_FATAL
)
1767 /* This error/warning is pointless if we are dead anyway */
1768 if ((severity
& ERR_UNDEAD
) && terminate_after_phase
)
1771 return !(warning_state
[warn_index(severity
)] & WARN_ST_ENABLED
);
1775 * Return the true error type (the ERR_MASK part) of the given
1776 * severity, accounting for warnings that may need to be promoted to
1779 * @param severity the severity of the warning or error
1780 * @return true if we should error out
1782 static errflags
true_error_type(errflags severity
)
1784 const uint8_t warn_is_err
= WARN_ST_ENABLED
|WARN_ST_ERROR
;
1787 type
= severity
& ERR_MASK
;
1789 /* Promote warning to error? */
1790 if (type
== ERR_WARNING
) {
1791 uint8_t state
= warning_state
[warn_index(severity
)];
1792 if ((state
& warn_is_err
) == warn_is_err
)
1793 type
= ERR_NONFATAL
;
1800 * common error reporting
1801 * This is the common back end of the error reporting schemes currently
1802 * implemented. It prints the nature of the warning and then the
1803 * specific error message to error_file and may or may not return. It
1804 * doesn't return if the error severity is a "panic" or "debug" type.
1806 * @param severity the severity of the warning or error
1807 * @param fmt the printf style format string
1809 static void nasm_verror_asm(errflags severity
, const char *fmt
, va_list args
)
1815 errflags true_type
= true_error_type(severity
);
1816 const char *currentfile
= NULL
;
1818 static const char * const pfx_table
[ERR_MASK
+1] = {
1819 ";;; ", "debug: ", "info: ", "warning: ",
1820 "error: ", "", "fatal: ", "panic: "
1823 if (is_suppressed(severity
))
1826 if (!(severity
& ERR_NOFILE
)) {
1827 src_get(&lineno
, ¤tfile
);
1829 currentfile
= currentfile
? currentfile
:
1830 inname
&& inname
[0] ? inname
:
1831 outname
&& outname
[0] ? outname
:
1837 if (severity
& ERR_NO_SEVERITY
)
1840 pfx
= pfx_table
[true_type
];
1842 vsnprintf(msg
, sizeof msg
, fmt
, args
);
1844 if ((severity
& (ERR_MASK
|ERR_HERE
|ERR_PP_LISTMACRO
)) == ERR_WARNING
) {
1846 * It's a warning without ERR_HERE defined, and we are not already
1847 * unwinding the macros that led us here.
1849 snprintf(warnsuf
, sizeof warnsuf
, " [-w+%s%s]",
1850 (true_type
>= ERR_NONFATAL
) ? "error=" : "",
1851 warning_name
[warn_index(severity
)]);
1856 snprintf(linestr
, sizeof linestr
, "%s%"PRId32
"%s",
1857 errfmt
->beforeline
, lineno
, errfmt
->afterline
);
1860 if (!skip_this_pass(severity
)) {
1861 const char *file
= currentfile
? currentfile
: "nasm";
1862 const char *here
= "";
1864 if (severity
& ERR_HERE
)
1865 here
= currentfile
? " here" : " in an unknown location";
1867 if (warn_list
&& true_type
< ERR_NONFATAL
&&
1868 !(pass_first() && (severity
& ERR_PASS1
)))
1871 * Buffer up warnings until we either get an error
1872 * or we are on the code-generation pass.
1874 strlist_printf(warn_list
, "%s%s%s%s%s%s%s",
1875 file
, linestr
, errfmt
->beforemsg
,
1876 pfx
, msg
, here
, warnsuf
);
1879 * If we have buffered warnings, and this is a non-warning,
1882 if (true_type
>= ERR_NONFATAL
&& warn_list
) {
1883 strlist_write(warn_list
, "\n", error_file
);
1884 strlist_free(&warn_list
);
1887 fprintf(error_file
, "%s%s%s%s%s%s%s\n",
1888 file
, linestr
, errfmt
->beforemsg
,
1889 pfx
, msg
, here
, warnsuf
);
1894 /* Are we recursing from error_list_macros? */
1895 if (severity
& ERR_PP_LISTMACRO
)
1899 * Don't suppress this with skip_this_pass(), or we don't get
1900 * pass1 or preprocessor warnings in the list file
1902 if (severity
& ERR_HERE
) {
1904 lfmt
->error(severity
, "%s%s at %s:%"PRId32
"%s",
1905 pfx
, msg
, currentfile
, lineno
, warnsuf
);
1906 else if (currentfile
)
1907 lfmt
->error(severity
, "%s%s in file %s%s",
1908 pfx
, msg
, currentfile
, warnsuf
);
1910 lfmt
->error(severity
, "%s%s in an unknown location%s",
1913 lfmt
->error(severity
, "%s%s%s", pfx
, msg
, warnsuf
);
1916 if (skip_this_pass(severity
))
1919 if (severity
& ERR_USAGE
)
1922 /* error_list_macros can for obvious reasons not work with ERR_HERE */
1923 if (!(severity
& ERR_HERE
))
1924 preproc
->error_list_macros(severity
);
1926 switch (true_type
) {
1931 /* no further action, by definition */
1934 terminate_after_phase
= true;
1945 exit(1); /* instantly die */
1946 break; /* placate silly compilers */
1951 abort(); /* halt, catch fire, dump core/stop debugger */
1966 static void usage(void)
1968 fprintf(error_file
, "Type %s -h for help.\n", _progname
);
1971 static void help(FILE *out
)
1976 "Usage: %s [-@ response_file] [options...] [--] filename\n"
1977 " %s -v (or --v)\n",
1978 _progname
, _progname
);
1981 "Options (values in brackets indicate defaults):\n"
1983 " -h show this text and exit (also --help)\n"
1984 " -v (or --v) print the NASM version number and exit\n"
1985 " -@ file response file; one command line option per line\n"
1987 " -o outfile write output to outfile\n"
1988 " --keep-all output files will not be removed even if an error happens\n"
1990 " -Xformat specifiy error reporting format (gnu or vc)\n"
1991 " -s redirect error messages to stdout\n"
1992 " -Zfile redirect error messages to file\n"
1994 " -M generate Makefile dependencies on stdout\n"
1995 " -MG d:o, missing files assumed generated\n"
1996 " -MF file set Makefile dependency file\n"
1997 " -MD file assemble and generate dependencies\n"
1998 " -MT file dependency target name\n"
1999 " -MQ file dependency target name (quoted)\n"
2000 " -MP emit phony targets\n"
2002 " -f format select output file format\n"
2004 ofmt_list(ofmt
, out
);
2007 " -g generate debugging information\n"
2008 " -F format select a debugging format (output format dependent)\n"
2009 " -gformat same as -g -F format\n"
2014 " -l listfile write listing to a list file\n"
2015 " -Lflags... add optional information to the list file\n"
2016 " -Lb show builtin macro packages (standard and %use)\n"
2017 " -Ld show byte and repeat counts in decimal, not hex\n"
2018 " -Le show the preprocessed output\n"
2019 " -Lf ignore .nolist (force output)\n"
2020 " -Lm show all single-line macro definitions\n"
2021 " -Lp output a list file every pass, in case of errors\n"
2023 " -Oflags... optimize opcodes, immediates and branch offsets\n"
2024 " -O0 no optimization\n"
2025 " -O1 minimal optimization\n"
2026 " -Ox multipass optimization (default)\n"
2027 " -Ov display the number of passes executed at the end\n"
2028 " -t assemble in limited SciTech TASM compatible mode\n"
2030 " -E (or -e) preprocess only (writes output to stdout by default)\n"
2031 " -a don't preprocess (assemble only)\n"
2032 " -Ipath add a pathname to the include file path\n"
2033 " -Pfile pre-include a file (also --include)\n"
2034 " -Dmacro[=str] pre-define a macro\n"
2035 " -Umacro undefine a macro\n"
2036 " --pragma str pre-executes a specific %%pragma\n"
2037 " --before str add line (usually a preprocessor statement) before the input\n"
2038 " --no-line ignore %line directives in input\n"
2040 " --prefix str prepend the given string to the names of all extern,\n"
2041 " common and global symbols (also --gprefix)\n"
2042 " --suffix str append the given string to the names of all extern,\n"
2043 " common and global symbols (also --gprefix)\n"
2044 " --lprefix str prepend the given string to local symbols\n"
2045 " --lpostfix str append the given string to local symbols\n"
2047 " -w+x enable warning x (also -Wx)\n"
2048 " -w-x disable warning x (also -Wno-x)\n"
2049 " -w[+-]error promote all warnings to errors (also -Werror)\n"
2050 " -w[+-]error=x promote warning x to errors (also -Werror=x)\n"
2053 fprintf(out
, " %-20s %s\n",
2054 warning_name
[WARN_IDX_ALL
], warning_help
[WARN_IDX_ALL
]);
2056 for (i
= 1; i
< WARN_IDX_ALL
; i
++) {
2057 const char *me
= warning_name
[i
];
2058 const char *prev
= warning_name
[i
-1];
2059 const char *next
= warning_name
[i
+1];
2062 int prev_len
= strlen(prev
);
2063 const char *dash
= me
;
2065 while ((dash
= strchr(dash
+1, '-'))) {
2066 int prefix_len
= dash
- me
; /* Not including final dash */
2067 if (strncmp(next
, me
, prefix_len
+1)) {
2068 /* Only one or last option with this prefix */
2071 if (prefix_len
>= prev_len
||
2072 strncmp(prev
, me
, prefix_len
) ||
2073 (prev
[prefix_len
] != '-' && prev
[prefix_len
] != '\0')) {
2074 /* This prefix is different from the previous option */
2075 fprintf(out
, " %-20.*s all warnings prefixed with \"%.*s\"\n",
2076 prefix_len
, me
, prefix_len
+1, me
);
2081 fprintf(out
, " %-20s %s%s\n",
2082 warning_name
[i
], warning_help
[i
],
2083 (warning_default
[i
] & WARN_ST_ERROR
) ? " [error]" :
2084 (warning_default
[i
] & WARN_ST_ENABLED
) ? " [on]" : " [off]");
2089 " --limit-X val set execution limit X\n"
2093 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
2094 fprintf(out
, " %-20s %s [",
2095 limit_info
[i
].name
, limit_info
[i
].help
);
2096 if (nasm_limit
[i
] < LIMIT_MAX_VAL
) {
2097 fprintf(out
, "%"PRId64
"]\n", nasm_limit
[i
]);
2099 fputs("unlimited]\n", out
);