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
66 * This is the maximum number of optimization passes to do. If we ever
67 * find a case where the optimizer doesn't naturally converge, we might
68 * have to drop this value so the assembler doesn't appear to just hang.
70 #define MAX_OPTIMIZE (INT_MAX >> 1)
72 struct forwrefinfo
{ /* info held on forward refs. */
77 static void parse_cmdline(int, char **, int);
78 static void assemble_file(const char *, struct strlist
*);
79 static bool is_suppressed_warning(int severity
);
80 static bool skip_this_pass(int severity
);
81 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list args
);
82 static void nasm_verror_vc(int severity
, const char *fmt
, va_list args
);
83 static void nasm_verror_common(int severity
, const char *fmt
, va_list args
);
84 static void usage(void);
85 static void help(char xopt
);
87 static bool using_debug_info
, opt_verbose_info
;
88 static const char *debug_format
;
90 #ifndef ABORT_ON_PANIC
91 # define ABORT_ON_PANIC 0
93 static bool abort_on_panic
= ABORT_ON_PANIC
;
96 bool tasm_compatible_mode
= false;
99 static int pass1
, pass2
; /* XXX: Get rid of these, they are redundant */
103 struct compile_time official_compile_time
;
107 static const char *listname
;
108 static const char *errname
;
110 static int64_t globallineno
; /* for forward-reference tracking */
112 /* static int pass = 0; */
113 const struct ofmt
*ofmt
= &OF_DEFAULT
;
114 const struct ofmt_alias
*ofmt_alias
= NULL
;
115 const struct dfmt
*dfmt
;
117 static FILE *error_file
; /* Where to write error messages */
120 struct optimization optimizing
=
121 { MAX_OPTIMIZE
, OPTIM_ALL_ENABLED
}; /* number of optimization passes to take */
122 static int cmd_sb
= 16; /* by default */
125 static iflag_t cmd_cpu
;
127 struct location location
;
128 bool in_absolute
; /* Flag we are in ABSOLUTE seg */
129 struct location absolute
; /* Segment/offset inside ABSOLUTE */
131 static struct RAA
*offsets
;
133 static struct SAA
*forwrefs
; /* keep track of forward references */
134 static const struct forwrefinfo
*forwref
;
136 static const struct preproc_ops
*preproc
;
137 static struct strlist
*include_path
;
139 #define OP_NORMAL (1U << 0)
140 #define OP_PREPROCESS (1U << 1)
141 #define OP_DEPEND (1U << 2)
143 static unsigned int operating_mode
;
145 /* Dependency flags */
146 static bool depend_emit_phony
= false;
147 static bool depend_missing_ok
= false;
148 static const char *depend_target
= NULL
;
149 static const char *depend_file
= NULL
;
150 struct strlist
*depend_list
;
152 static bool want_usage
;
153 static bool terminate_after_phase
;
154 bool user_nolist
= false;
156 static char *quote_for_pmake(const char *str
);
157 static char *quote_for_wmake(const char *str
);
158 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
161 * Execution limits that can be set via a command-line option or %pragma
164 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
166 int64_t nasm_limit
[LIMIT_MAX
+1] =
167 { LIMIT_MAX_VAL
, 1000, 1000000, 1000000, 1000000, 2000000000 };
173 static const struct limit_info limit_info
[LIMIT_MAX
+1] = {
174 { "passes", "total number of passes" },
175 { "stalled-passes", "number of passes without forward progress" },
176 { "macro-levels", "levels of macro expansion"},
177 { "rep", "%rep count" },
178 { "eval", "expression evaluation descent"},
179 { "lines", "total source lines processed"}
182 enum directive_result
183 nasm_set_limit(const char *limit
, const char *valstr
)
190 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
191 if (!nasm_stricmp(limit
, limit_info
[i
].name
))
196 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
198 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_UNKNOWN_PRAGMA
;
199 nasm_error(errlevel
, "unknown limit: `%s'", limit
);
203 if (!nasm_stricmp(valstr
, "unlimited")) {
206 val
= readnum(valstr
, &rn_error
);
207 if (rn_error
|| val
< 0) {
209 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
211 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_BAD_PRAGMA
;
212 nasm_error(errlevel
, "invalid limit value: `%s'", limit
);
215 if (val
> LIMIT_MAX_VAL
)
223 int64_t switch_segment(int32_t segment
)
225 location
.segment
= segment
;
226 if (segment
== NO_SEG
) {
227 location
.offset
= absolute
.offset
;
230 location
.offset
= raa_read(offsets
, segment
);
233 return location
.offset
;
236 static void set_curr_offs(int64_t l_off
)
239 absolute
.offset
= l_off
;
241 offsets
= raa_write(offsets
, location
.segment
, l_off
);
244 static void increment_offset(int64_t delta
)
246 if (unlikely(delta
== 0))
249 location
.offset
+= delta
;
250 set_curr_offs(location
.offset
);
253 static void nasm_fputs(const char *line
, FILE * outfile
)
256 fputs(line
, outfile
);
263 * Define system-defined macros that are not part of
264 * macros/standard.mac.
266 static void define_macros(void)
268 const struct compile_time
* const oct
= &official_compile_time
;
271 if (oct
->have_local
) {
272 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
273 preproc
->pre_define(temp
);
274 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
275 preproc
->pre_define(temp
);
276 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
277 preproc
->pre_define(temp
);
278 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
279 preproc
->pre_define(temp
);
283 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
284 preproc
->pre_define(temp
);
285 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
286 preproc
->pre_define(temp
);
287 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
288 preproc
->pre_define(temp
);
289 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
290 preproc
->pre_define(temp
);
293 if (oct
->have_posix
) {
294 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
295 preproc
->pre_define(temp
);
299 * In case if output format is defined by alias
300 * we have to put shortname of the alias itself here
301 * otherwise ABI backward compatibility gets broken.
303 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s",
304 ofmt_alias
? ofmt_alias
->shortname
: ofmt
->shortname
);
305 preproc
->pre_define(temp
);
308 * Output-format specific macros.
311 preproc
->extra_stdmac(ofmt
->stdmac
);
314 * Debug format, if any
316 if (dfmt
!= &null_debug_form
) {
317 snprintf(temp
, sizeof(temp
), "__DEBUG_FORMAT__=%s", dfmt
->shortname
);
318 preproc
->pre_define(temp
);
323 * Initialize the preprocessor, set up the include path, and define
324 * the system-included macros. This is called between passes 1 and 2
325 * of parsing the command options; ofmt and dfmt are defined at this
328 * Command-line specified preprocessor directives (-p, -d, -u,
329 * --pragma, --before) are processed after this function.
331 static void preproc_init(struct strlist
*ipath
)
335 preproc
->include_path(ipath
);
338 static void emit_dependencies(struct strlist
*list
)
342 bool wmake
= (quote_for_make
== quote_for_wmake
);
343 const char *wrapstr
, *nulltarget
;
344 struct strlist_entry
*l
;
349 wrapstr
= wmake
? " &\n " : " \\\n ";
350 nulltarget
= wmake
? "\t%null\n" : "";
352 if (depend_file
&& strcmp(depend_file
, "-")) {
353 deps
= nasm_open_write(depend_file
, NF_TEXT
);
355 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
356 "unable to write dependency file `%s'", depend_file
);
363 linepos
= fprintf(deps
, "%s :", depend_target
);
364 list_for_each(l
, list
->head
) {
365 char *file
= quote_for_make(l
->str
);
367 if (linepos
+ len
> 62 && linepos
> 1) {
368 fputs(wrapstr
, deps
);
371 fprintf(deps
, " %s", file
);
375 fprintf(deps
, "\n\n");
377 list_for_each(l
, list
->head
) {
378 if (depend_emit_phony
) {
379 char *file
= quote_for_make(l
->str
);
380 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
391 /* Convert a struct tm to a POSIX-style time constant */
392 static int64_t make_posix_time(const struct tm
*tm
)
395 int64_t y
= tm
->tm_year
;
397 /* See IEEE 1003.1:2004, section 4.14 */
399 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
411 static void timestamp(void)
413 struct compile_time
* const oct
= &official_compile_time
;
414 const struct tm
*tp
, *best_gm
;
420 tp
= localtime(&oct
->t
);
423 best_gm
= &oct
->local
;
424 oct
->have_local
= true;
427 tp
= gmtime(&oct
->t
);
432 if (!oct
->have_local
)
433 oct
->local
= oct
->gm
;
435 oct
->gm
= oct
->local
;
439 oct
->posix
= make_posix_time(best_gm
);
440 oct
->have_posix
= true;
444 int main(int argc
, char **argv
)
448 iflag_set_default_cpu(&cpu
);
449 iflag_set_default_cpu(&cmd_cpu
);
451 include_path
= strlist_alloc();
454 want_usage
= terminate_after_phase
= false;
455 nasm_set_verror(nasm_verror_gnu
);
463 * We must call init_labels() before the command line parsing,
464 * because we may be setting prefixes/suffixes from the command
469 offsets
= raa_init();
470 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
473 operating_mode
= OP_NORMAL
;
475 parse_cmdline(argc
, argv
, 1);
476 if (terminate_after_phase
) {
482 /* At this point we have ofmt and the name of the desired debug format */
483 if (!using_debug_info
) {
484 /* No debug info, redirect to the null backend (empty stubs) */
485 dfmt
= &null_debug_form
;
486 } else if (!debug_format
) {
487 /* Default debug format for this backend */
488 dfmt
= ofmt
->default_dfmt
;
490 dfmt
= dfmt_find(ofmt
, debug_format
);
492 nasm_fatalf(ERR_NOFILE
| ERR_USAGE
,
493 "unrecognized debug format `%s' for"
494 " output format `%s'",
495 debug_format
, ofmt
->shortname
);
499 preproc_init(include_path
);
501 parse_cmdline(argc
, argv
, 2);
502 if (terminate_after_phase
) {
508 /* Save away the default state of warnings */
509 memcpy(warning_state_init
, warning_state
, sizeof warning_state
);
511 /* Dependency filename if we are also doing other things */
512 if (!depend_file
&& (operating_mode
& ~OP_DEPEND
)) {
514 depend_file
= nasm_strcat(outname
, ".d");
516 depend_file
= filename_set_extension(inname
, ".d");
520 * If no output file name provided and this
521 * is preprocess mode, we're perfectly
522 * fine to output into stdout.
524 if (!outname
&& !(operating_mode
& OP_PREPROCESS
)) {
525 outname
= filename_set_extension(inname
, ofmt
->extension
);
526 if (!strcmp(outname
, inname
)) {
527 outname
= "nasm.out";
528 nasm_error(ERR_WARNING
,
529 "default output file same as input, using `%s' for output\n",
534 depend_list
= (operating_mode
& OP_DEPEND
) ? strlist_alloc() : NULL
;
537 depend_target
= quote_for_make(outname
);
539 if (!(operating_mode
& (OP_PREPROCESS
|OP_NORMAL
))) {
542 if (depend_missing_ok
)
543 preproc
->include_path(NULL
); /* "assume generated" */
545 preproc
->reset(inname
, 0, depend_list
);
547 while ((line
= preproc
->getline()))
550 } else if (operating_mode
& OP_PREPROCESS
) {
552 const char *file_name
= NULL
;
553 int32_t prior_linnum
= 0;
557 ofile
= nasm_open_write(outname
, NF_TEXT
);
559 nasm_fatalf(ERR_NOFILE
,
560 "unable to open output file `%s'",
565 location
.known
= false;
568 preproc
->reset(inname
, 3, depend_list
);
570 /* Revert all warnings to the default state */
571 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
573 while ((line
= preproc
->getline())) {
575 * We generate %line directives if needed for later programs
577 int32_t linnum
= prior_linnum
+= lineinc
;
578 int altline
= src_get(&linnum
, &file_name
);
580 if (altline
== 1 && lineinc
== 1)
581 nasm_fputs("", ofile
);
583 lineinc
= (altline
!= -1 || lineinc
!= 1);
584 fprintf(ofile
? ofile
: stdout
,
585 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
588 prior_linnum
= linnum
;
590 nasm_fputs(line
, ofile
);
596 if (ofile
&& terminate_after_phase
&& !keep_all
)
601 if (operating_mode
& OP_NORMAL
) {
602 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
604 nasm_fatalf(ERR_NOFILE
,
605 "unable to open output file `%s'", outname
);
610 assemble_file(inname
, depend_list
);
612 if (!terminate_after_phase
) {
617 nasm_error(ERR_NONFATAL
|ERR_NOFILE
,
618 "write error on output file `%s'", outname
);
619 terminate_after_phase
= true;
625 if (terminate_after_phase
&& !keep_all
)
631 if (depend_list
&& !terminate_after_phase
)
632 emit_dependencies(depend_list
);
642 strlist_free(include_path
);
644 return terminate_after_phase
;
648 * Get a parameter for a command line option.
649 * First arg must be in the form of e.g. -f...
651 static char *get_param(char *p
, char *q
, bool *advance
)
654 if (p
[2]) /* the parameter's in the option */
655 return nasm_skip_spaces(p
+ 2);
660 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
661 "option `-%c' requires an argument", p
[1]);
668 static void copy_filename(const char **dst
, const char *src
, const char *what
)
671 nasm_fatal("more than one %s file specified: %s\n", what
, src
);
673 *dst
= nasm_strdup(src
);
677 * Convert a string to a POSIX make-safe form
679 static char *quote_for_pmake(const char *str
)
684 size_t n
= 1; /* Terminating zero */
690 for (p
= str
; *p
; p
++) {
694 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
714 /* Convert N backslashes at the end of filename to 2N backslashes */
718 os
= q
= nasm_malloc(n
);
721 for (p
= str
; *p
; p
++) {
759 * Convert a string to a Watcom make-safe form
761 static char *quote_for_wmake(const char *str
)
767 size_t n
= 1; /* Terminating zero */
772 for (p
= str
; *p
; p
++) {
797 os
= q
= nasm_malloc(n
);
802 for (p
= str
; *p
; p
++) {
841 enum text_options opt
;
845 static const struct textargs textopts
[] = {
846 {"v", OPT_VERSION
, false, 0},
847 {"version", OPT_VERSION
, false, 0},
848 {"help", OPT_HELP
, false, 0},
849 {"abort-on-panic", OPT_ABORT_ON_PANIC
, false, 0},
850 {"prefix", OPT_MANGLE
, true, LM_GPREFIX
},
851 {"postfix", OPT_MANGLE
, true, LM_GSUFFIX
},
852 {"gprefix", OPT_MANGLE
, true, LM_GPREFIX
},
853 {"gpostfix", OPT_MANGLE
, true, LM_GSUFFIX
},
854 {"lprefix", OPT_MANGLE
, true, LM_LPREFIX
},
855 {"lpostfix", OPT_MANGLE
, true, LM_LSUFFIX
},
856 {"include", OPT_INCLUDE
, true, 0},
857 {"pragma", OPT_PRAGMA
, true, 0},
858 {"before", OPT_BEFORE
, true, 0},
859 {"limit-", OPT_LIMIT
, true, 0},
860 {"keep-all", OPT_KEEP_ALL
, false, 0},
861 {NULL
, OPT_BOGUS
, false, 0}
864 static void show_version(void)
866 printf("NASM version %s compiled on %s%s\n",
867 nasm_version
, nasm_date
, nasm_compile_options
);
871 static bool stopoptions
= false;
872 static bool process_arg(char *p
, char *q
, int pass
)
875 bool advance
= false;
880 if (p
[0] == '-' && !stopoptions
) {
881 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
882 /* These parameters take values */
883 if (!(param
= get_param(p
, q
, &advance
)))
893 case 'o': /* output file */
895 copy_filename(&outname
, param
, "output");
898 case 'f': /* output format */
900 ofmt
= ofmt_find(param
, &ofmt_alias
);
902 nasm_fatalf(ERR_NOFILE
| ERR_USAGE
,
903 "unrecognised output format `%s' - "
904 "use -hf for a list", param
);
909 case 'O': /* Optimization level */
914 /* Naked -O == -Ox */
915 optimizing
.level
= MAX_OPTIMIZE
;
919 case '0': case '1': case '2': case '3': case '4':
920 case '5': case '6': case '7': case '8': case '9':
921 opt
= strtoul(param
, ¶m
, 10);
923 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
924 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
926 optimizing
.level
= opt
- 1;
928 optimizing
.level
= opt
;
934 opt_verbose_info
= true;
939 optimizing
.level
= MAX_OPTIMIZE
;
943 nasm_fatal("unknown optimization option -O%c\n",
948 if (optimizing
.level
> MAX_OPTIMIZE
)
949 optimizing
.level
= MAX_OPTIMIZE
;
954 case 'p': /* pre-include */
957 preproc
->pre_include(param
);
960 case 'd': /* pre-define */
963 preproc
->pre_define(param
);
966 case 'u': /* un-define */
969 preproc
->pre_undefine(param
);
972 case 'i': /* include search path */
975 strlist_add(include_path
, param
);
978 case 'l': /* listing file */
980 copy_filename(&listname
, param
, "listing");
983 case 'Z': /* error messages file */
985 copy_filename(&errname
, param
, "error");
988 case 'F': /* specify debug format */
990 using_debug_info
= true;
991 debug_format
= param
;
995 case 'X': /* specify error reporting format */
997 if (nasm_stricmp("vc", param
) == 0)
998 nasm_set_verror(nasm_verror_vc
);
999 else if (nasm_stricmp("gnu", param
) == 0)
1000 nasm_set_verror(nasm_verror_gnu
);
1002 nasm_fatalf(ERR_NOFILE
| ERR_USAGE
,
1003 "unrecognized error reporting format `%s'",
1010 using_debug_info
= true;
1012 debug_format
= nasm_skip_spaces(p
+ 2);
1018 exit(0); /* never need usage message here */
1022 printf("\nvalid debug formats for '%s' output format are"
1023 " ('*' denotes default):\n", ofmt
->shortname
);
1024 dfmt_list(ofmt
, stdout
);
1030 tasm_compatible_mode
= true;
1031 nasm_ctype_tasm_mode();
1039 case 'e': /* preprocess only */
1042 operating_mode
= OP_PREPROCESS
;
1045 case 'a': /* assemble only - don't preprocess */
1047 preproc
= &preproc_nop
;
1053 if (!set_warning_status(param
)) {
1054 nasm_error(ERR_WARNING
|ERR_NOFILE
|ERR_WARN_UNK_WARNING
,
1055 "unknown warning option: %s", param
);
1064 quote_for_make
= quote_for_wmake
;
1078 operating_mode
= OP_DEPEND
;
1081 operating_mode
= OP_DEPEND
;
1082 depend_missing_ok
= true;
1085 depend_emit_phony
= true;
1088 operating_mode
|= OP_DEPEND
;
1089 if (q
&& (q
[0] != '-' || q
[1] == '\0')) {
1103 depend_target
= quote_for_make(q
);
1107 /* handled in pass 1 */
1110 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1111 "unknown dependency option `-M%c'", p
[2]);
1115 if (advance
&& (!q
|| !q
[0])) {
1116 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1117 "option `-M%c' requires a parameter", p
[2]);
1124 const struct textargs
*tx
;
1130 if (!*p
) { /* -- => stop processing options */
1136 for (tx
= textopts
; tx
->label
; tx
++) {
1137 olen
= strlen(tx
->label
);
1142 if (nasm_memicmp(p
, tx
->label
, olen
))
1145 if (tx
->label
[olen
-1] == '-')
1146 break; /* Incomplete option */
1148 if (!p
[olen
] || p
[olen
] == '=')
1149 break; /* Complete option */
1153 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1154 "unrecognized option `--%s'", p
);
1157 eqsave
= param
= strchr(p
+olen
, '=');
1167 /* Note: a null string is a valid parameter */
1169 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1170 "option `--%s' requires an argument",
1176 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1177 "option `--%s' does not take an argument",
1187 case OPT_ABORT_ON_PANIC
:
1188 abort_on_panic
= true;
1192 set_label_mangle(tx
->pvt
, param
);
1196 preproc
->pre_include(q
);
1200 preproc
->pre_command("pragma", param
);
1204 preproc
->pre_command(NULL
, param
);
1208 nasm_set_limit(p
+olen
, param
);
1221 *eqsave
= '='; /* Restore = argument separator */
1227 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1228 "unrecognised option `-%c'", p
[1]);
1231 } else if (pass
== 2) {
1232 /* In theory we could allow multiple input files... */
1233 copy_filename(&inname
, p
, "input");
1239 #define ARG_BUF_DELTA 128
1241 static void process_respfile(FILE * rfile
, int pass
)
1243 char *buffer
, *p
, *q
, *prevarg
;
1244 int bufsize
, prevargsize
;
1246 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1247 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1248 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1251 while (1) { /* Loop to handle all lines in file */
1253 while (1) { /* Loop to handle long lines */
1254 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1258 if (p
> buffer
&& p
[-1] == '\n')
1260 if (p
- buffer
> bufsize
- 10) {
1262 offset
= p
- buffer
;
1263 bufsize
+= ARG_BUF_DELTA
;
1264 buffer
= nasm_realloc(buffer
, bufsize
);
1265 p
= buffer
+ offset
;
1269 if (!q
&& p
== buffer
) {
1271 process_arg(prevarg
, NULL
, pass
);
1278 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1279 * them are present at the end of the line.
1281 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1283 while (p
> buffer
&& nasm_isspace(p
[-1]))
1286 p
= nasm_skip_spaces(buffer
);
1288 if (process_arg(prevarg
, p
, pass
))
1291 if ((int) strlen(p
) > prevargsize
- 10) {
1292 prevargsize
+= ARG_BUF_DELTA
;
1293 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1295 strncpy(prevarg
, p
, prevargsize
);
1299 /* Function to process args from a string of args, rather than the
1300 * argv array. Used by the environment variable and response file
1303 static void process_args(char *args
, int pass
)
1305 char *p
, *q
, *arg
, *prevarg
;
1306 char separator
= ' ';
1309 if (*p
&& *p
!= '-')
1314 while (*p
&& *p
!= separator
)
1316 while (*p
== separator
)
1320 if (process_arg(prevarg
, arg
, pass
))
1324 process_arg(arg
, NULL
, pass
);
1327 static void process_response_file(const char *file
, int pass
)
1330 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1335 while (fgets(str
, sizeof str
, f
)) {
1336 process_args(str
, pass
);
1341 static void parse_cmdline(int argc
, char **argv
, int pass
)
1344 char *envreal
, *envcopy
= NULL
, *p
;
1347 /* Initialize all the warnings to their default state */
1348 for (i
= 0; i
< ERR_WARN_ALL
; i
++) {
1349 warning_state_init
[i
] = warning_state
[i
] =
1350 warnings
[i
].enabled
? WARN_ST_ENABLED
: 0;
1354 * First, process the NASMENV environment variable.
1356 envreal
= getenv("NASMENV");
1358 envcopy
= nasm_strdup(envreal
);
1359 process_args(envcopy
, pass
);
1364 * Now process the actual command line.
1369 if (argv
[0][0] == '@') {
1371 * We have a response file, so process this as a set of
1372 * arguments like the environment variable. This allows us
1373 * to have multiple arguments on a single line, which is
1374 * different to the -@resp file processing below for regular
1377 process_response_file(argv
[0]+1, pass
);
1381 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1382 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1384 rfile
= nasm_open_read(p
, NF_TEXT
);
1386 process_respfile(rfile
, pass
);
1389 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1390 "unable to open response file `%s'", p
);
1393 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1394 argv
+= advance
, argc
-= advance
;
1398 * Look for basic command line typos. This definitely doesn't
1399 * catch all errors, but it might help cases of fumbled fingers.
1405 nasm_fatalf(ERR_NOFILE
| ERR_USAGE
, "no input file specified");
1407 else if ((errname
&& !strcmp(inname
, errname
)) ||
1408 (outname
&& !strcmp(inname
, outname
)) ||
1409 (listname
&& !strcmp(inname
, listname
)) ||
1410 (depend_file
&& !strcmp(inname
, depend_file
)))
1411 nasm_fatalf(ERR_USAGE
, "will not overwrite input file");
1414 error_file
= nasm_open_write(errname
, NF_TEXT
);
1416 error_file
= stderr
; /* Revert to default! */
1417 nasm_fatalf(ERR_NOFILE
| ERR_USAGE
,
1418 "cannot open file `%s' for error messages",
1424 static void assemble_file(const char *fname
, struct strlist
*depend_list
)
1429 uint64_t prev_offset_changed
;
1430 int64_t stall_count
= 0; /* Make sure we make forward progress... */
1436 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_386
))
1437 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1440 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_X86_64
))
1441 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1448 prev_offset_changed
= nasm_limit
[LIMIT_PASSES
];
1449 for (passn
= 1; pass0
<= 2; passn
++) {
1450 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1451 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1452 /* pass0 0, 0, 0, ..., 1, 2 */
1454 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1457 lfmt
->init(listname
);
1458 } else if (passn
== 1 && listname
&& !keep_all
) {
1459 /* Remove the list file in case we die before the output pass */
1462 in_absolute
= false;
1463 global_offset_changed
= 0; /* set by redefine_label */
1465 saa_rewind(forwrefs
);
1466 forwref
= saa_rstruct(forwrefs
);
1468 offsets
= raa_init();
1470 location
.segment
= NO_SEG
;
1471 location
.offset
= 0;
1473 location
.known
= true;
1475 switch_segment(ofmt
->section(NULL
, pass2
, &globalbits
));
1476 preproc
->reset(fname
, pass1
, pass1
== 2 ? depend_list
: NULL
);
1478 /* Revert all warnings to the default state */
1479 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
1483 while ((line
= preproc
->getline())) {
1484 if (++globallineno
> nasm_limit
[LIMIT_LINES
])
1485 nasm_fatal("overall line count exceeds the maximum %"PRId64
"\n",
1486 nasm_limit
[LIMIT_LINES
]);
1489 * Here we parse our directives; this is not handled by the
1492 if (process_directives(line
))
1493 goto end_of_line
; /* Just do final cleanup */
1495 /* Not a directive, or even something that starts with [ */
1496 parse_line(pass1
, line
, &output_ins
);
1498 if (optimizing
.level
> 0) {
1499 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1500 output_ins
.forw_ref
= true;
1502 output_ins
.oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1503 forwref
= saa_rstruct(forwrefs
);
1504 } while (forwref
!= NULL
1505 && forwref
->lineno
== globallineno
);
1507 output_ins
.forw_ref
= false;
1509 if (output_ins
.forw_ref
) {
1511 for (i
= 0; i
< output_ins
.operands
; i
++) {
1512 if (output_ins
.oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1513 struct forwrefinfo
*fwinf
= (struct forwrefinfo
*)saa_wstruct(forwrefs
);
1514 fwinf
->lineno
= globallineno
;
1523 if (output_ins
.opcode
== I_EQU
) {
1524 if (!output_ins
.label
) {
1525 nasm_error(ERR_NONFATAL
, "EQU not preceded by label");
1526 } else if (output_ins
.operands
== 1 &&
1527 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1528 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1529 define_label(output_ins
.label
,
1530 output_ins
.oprs
[0].segment
,
1531 output_ins
.oprs
[0].offset
, false);
1532 } else if (output_ins
.operands
== 2
1533 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1534 && (output_ins
.oprs
[0].type
& COLON
)
1535 && output_ins
.oprs
[0].segment
== NO_SEG
1536 && output_ins
.oprs
[0].wrt
== NO_SEG
1537 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1538 && output_ins
.oprs
[1].segment
== NO_SEG
1539 && output_ins
.oprs
[1].wrt
== NO_SEG
) {
1540 define_label(output_ins
.label
,
1541 output_ins
.oprs
[0].offset
| SEG_ABS
,
1542 output_ins
.oprs
[1].offset
, false);
1544 nasm_error(ERR_NONFATAL
, "bad syntax for EQU");
1546 } else { /* instruction isn't an EQU */
1549 nasm_assert(output_ins
.times
>= 0);
1551 for (n
= 1; n
<= output_ins
.times
; n
++) {
1553 int64_t l
= insn_size(location
.segment
,
1555 globalbits
, &output_ins
);
1557 /* if (using_debug_info) && output_ins.opcode != -1) */
1558 if (using_debug_info
)
1559 { /* fbk 03/25/01 */
1560 /* this is done here so we can do debug type info */
1562 TYS_ELEMENTS(output_ins
.operands
);
1563 switch (output_ins
.opcode
) {
1566 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_BYTE
;
1570 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_WORD
;
1574 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_DWORD
;
1578 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_QWORD
;
1582 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_TBYTE
;
1586 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_OWORD
;
1590 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_YWORD
;
1594 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_ZWORD
;
1597 typeinfo
|= TY_BYTE
;
1600 typeinfo
|= TY_WORD
;
1603 if (output_ins
.eops_float
)
1604 typeinfo
|= TY_FLOAT
;
1606 typeinfo
|= TY_DWORD
;
1609 typeinfo
|= TY_QWORD
;
1612 typeinfo
|= TY_TBYTE
;
1615 typeinfo
|= TY_OWORD
;
1618 typeinfo
|= TY_YWORD
;
1621 typeinfo
|= TY_ZWORD
;
1624 typeinfo
= TY_LABEL
;
1628 dfmt
->debug_typevalue(typeinfo
);
1632 * For INCBIN, let the code in assemble
1633 * handle TIMES, so we don't have to read the
1634 * input file over and over.
1637 increment_offset(l
);
1640 * else l == -1 => invalid instruction, which will be
1641 * flagged as an error on pass 2
1645 lfmt
->uplevel(LIST_TIMES
);
1646 increment_offset(assemble(location
.segment
,
1648 globalbits
, &output_ins
));
1652 if (output_ins
.times
> 1)
1653 lfmt
->downlevel(LIST_TIMES
);
1655 cleanup_insn(&output_ins
);
1659 } /* end while (line = preproc->getline... */
1661 if (global_offset_changed
&& !terminate_after_phase
) {
1664 nasm_error(ERR_WARNING
|ERR_WARN_PHASE
,
1665 "phase error during stabilization pass, hoping for the best");
1669 nasm_error(ERR_NONFATAL
,
1670 "phase error during code generation pass");
1674 /* This is normal, we'll keep going... */
1680 preproc
->cleanup(1);
1683 * Always run at least two optimization passes (pass0 == 0);
1684 * things like subsections will fail miserably without that.
1685 * Once we commit to a stabilization pass (pass0 == 1), we can't
1686 * go back, and if something goes bad, we can only hope
1687 * that we don't end up with a phase error at the end.
1689 if ((passn
> 1 && !global_offset_changed
) || pass0
> 0) {
1691 } else if (global_offset_changed
&&
1692 global_offset_changed
< prev_offset_changed
) {
1693 prev_offset_changed
= global_offset_changed
;
1699 if (terminate_after_phase
)
1702 if ((stall_count
> nasm_limit
[LIMIT_STALLED
]) ||
1703 (passn
>= nasm_limit
[LIMIT_PASSES
])) {
1704 /* We get here if the labels don't converge
1705 * Example: FOO equ FOO + 1
1707 nasm_error(ERR_NONFATAL
,
1708 "Can't find valid values for all labels "
1709 "after %"PRId64
" passes, giving up.", passn
);
1710 nasm_error(ERR_NONFATAL
,
1711 "Possible causes: recursive EQUs, macro abuse.");
1716 preproc
->cleanup(0);
1718 if (!terminate_after_phase
&& opt_verbose_info
) {
1719 /* -On and -Ov switches */
1720 fprintf(stdout
, "info: assembly required 1+%"PRId64
"+1 passes\n",
1726 * gnu style error reporting
1727 * This function prints an error message to error_file in the
1728 * style used by GNU. An example would be:
1729 * file.asm:50: error: blah blah blah
1730 * where file.asm is the name of the file, 50 is the line number on
1731 * which the error occurs (or is detected) and "error:" is one of
1732 * the possible optional diagnostics -- it can be "error" or "warning"
1733 * or something else. Finally the line terminates with the actual
1736 * @param severity the severity of the warning or error
1737 * @param fmt the printf style format string
1739 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list ap
)
1741 const char *currentfile
= NULL
;
1744 if (is_suppressed_warning(severity
))
1747 if (!(severity
& ERR_NOFILE
)) {
1748 src_get(&lineno
, ¤tfile
);
1749 if (!currentfile
|| (severity
& ERR_TOPFILE
)) {
1750 currentfile
= inname
&& inname
[0] ?
1751 inname
: outname
&& outname
[0] ?
1757 if (!skip_this_pass(severity
)) {
1759 fprintf(error_file
, "%s:", currentfile
? currentfile
: "nasm");
1761 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1764 nasm_verror_common(severity
, fmt
, ap
);
1768 * MS style error reporting
1769 * This function prints an error message to error_file in the
1770 * style used by Visual C and some other Microsoft tools. An example
1772 * file.asm(50) : error: blah blah blah
1773 * where file.asm is the name of the file, 50 is the line number on
1774 * which the error occurs (or is detected) and "error:" is one of
1775 * the possible optional diagnostics -- it can be "error" or "warning"
1776 * or something else. Finally the line terminates with the actual
1779 * @param severity the severity of the warning or error
1780 * @param fmt the printf style format string
1782 static void nasm_verror_vc(int severity
, const char *fmt
, va_list ap
)
1784 const char *currentfile
= NULL
;
1787 if (is_suppressed_warning(severity
))
1790 if (!(severity
& ERR_NOFILE
))
1791 src_get(&lineno
, ¤tfile
);
1793 if (!skip_this_pass(severity
)) {
1795 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1797 fputs("nasm: ", error_file
);
1801 nasm_verror_common(severity
, fmt
, ap
);
1805 * check to see if this is a suppressable warning
1807 static inline bool is_valid_warning(int severity
)
1809 /* Not a warning at all */
1810 if ((severity
& ERR_MASK
) != ERR_WARNING
)
1813 return WARN_IDX(severity
) < ERR_WARN_ALL
;
1817 * check for suppressed warning
1818 * checks for suppressed warning or pass one only warning and we're
1821 * @param severity the severity of the warning or error
1822 * @return true if we should abort error/warning printing
1824 static bool is_suppressed_warning(int severity
)
1826 /* Might be a warning but suppresed explicitly */
1827 if (is_valid_warning(severity
) && !(severity
& ERR_USAGE
))
1828 return !(warning_state
[WARN_IDX(severity
)] & WARN_ST_ENABLED
);
1833 static bool warning_is_error(int severity
)
1835 if (is_valid_warning(severity
))
1836 return !!(warning_state
[WARN_IDX(severity
)] & WARN_ST_ERROR
);
1841 static bool skip_this_pass(int severity
)
1844 * See if it's a pass-specific error or warning which should be skipped.
1845 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1846 * they cannot be resumed from.
1848 if ((severity
& ERR_MASK
) > ERR_NONFATAL
)
1852 * passn is 1 on the very first pass only.
1853 * pass0 is 2 on the code-generation (final) pass only.
1854 * These are the passes we care about in this case.
1856 return (((severity
& ERR_PASS1
) && passn
!= 1) ||
1857 ((severity
& ERR_PASS2
) && pass0
!= 2));
1861 * common error reporting
1862 * This is the common back end of the error reporting schemes currently
1863 * implemented. It prints the nature of the warning and then the
1864 * specific error message to error_file and may or may not return. It
1865 * doesn't return if the error severity is a "panic" or "debug" type.
1867 * @param severity the severity of the warning or error
1868 * @param fmt the printf style format string
1870 static void nasm_verror_common(int severity
, const char *fmt
, va_list args
)
1875 switch (severity
& (ERR_MASK
|ERR_NO_SEVERITY
)) {
1896 vsnprintf(msg
, sizeof msg
- 64, fmt
, args
);
1897 if (is_valid_warning(severity
) && WARN_IDX(severity
) != ERR_WARN_OTHER
) {
1898 char *p
= strchr(msg
, '\0');
1899 snprintf(p
, 64, " [-w+%s]", warnings
[WARN_IDX(severity
)].name
);
1902 if (!skip_this_pass(severity
))
1903 fprintf(error_file
, "%s%s\n", pfx
, msg
);
1905 /* Are we recursing from error_list_macros? */
1906 if (severity
& ERR_PP_LISTMACRO
)
1910 * Don't suppress this with skip_this_pass(), or we don't get
1911 * pass1 or preprocessor warnings in the list file
1913 lfmt
->error(severity
, pfx
, msg
);
1915 if (skip_this_pass(severity
))
1918 if (severity
& ERR_USAGE
)
1921 preproc
->error_list_macros(severity
);
1923 switch (severity
& ERR_MASK
) {
1925 /* no further action, by definition */
1928 /* Treat warnings as errors */
1929 if (warning_is_error(severity
))
1930 terminate_after_phase
= true;
1933 terminate_after_phase
= true;
1944 exit(1); /* instantly die */
1945 break; /* placate silly compilers */
1950 abort(); /* halt, catch fire, dump core/stop debugger */
1963 static void usage(void)
1965 fputs("type `nasm -h' for help\n", error_file
);
1968 static void help(const char xopt
)
1973 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1975 " [options...] [--] filename\n"
1976 " or nasm -v (or --v) for version info\n\n"
1978 "Response files should contain command line parameters,\n"
1981 " -t assemble in SciTech TASM compatible mode\n");
1983 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1984 " -a don't preprocess (assemble only)\n"
1985 " -M generate Makefile dependencies on stdout\n"
1986 " -MG d:o, missing files assumed generated\n"
1987 " -MF file set Makefile dependency file\n"
1988 " -MD file assemble and generate dependencies\n"
1989 " -MT file dependency target name\n"
1990 " -MQ file dependency target name (quoted)\n"
1991 " -MP emit phony target\n\n"
1992 " -Zfile redirect error messages to file\n"
1993 " -s redirect error messages to stdout\n\n"
1994 " -g generate debugging information\n\n"
1995 " -F format select a debugging format\n\n"
1996 " -gformat same as -g -F format\n\n"
1997 " -o outfile write output to an outfile\n\n"
1998 " -f format select an output format\n\n"
1999 " -l listfile write listing to a listfile\n\n"
2000 " -Ipath add a pathname to the include file path\n");
2002 (" -Olevel optimize opcodes, immediates and branch offsets\n"
2003 " -O0 no optimization\n"
2004 " -O1 minimal optimization\n"
2005 " -Ox multipass optimization (default)\n"
2006 " -Pfile pre-include a file (also --include)\n"
2007 " -Dmacro[=str] pre-define a macro\n"
2008 " -Umacro undefine a macro\n"
2009 " -Xformat specifiy error reporting format (gnu or vc)\n"
2010 " -w+foo enable warning foo (equiv. -Wfoo)\n"
2011 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
2012 " -w[+-]error[=foo]\n"
2013 " promote [specific] warnings to errors\n"
2014 " -h show invocation summary and exit (also --help)\n\n"
2015 " --pragma str pre-executes a specific %%pragma\n"
2016 " --before str add line (usually a preprocessor statement) before the input\n"
2017 " --prefix str prepend the given string to all the given string\n"
2018 " to all extern, common and global symbols (also --gprefix)\n"
2019 " --postfix str append the given string to all the given string\n"
2020 " to all extern, common and global symbols (also --gpostfix)\n"
2021 " --lprefix str prepend the given string to all other symbols\n"
2022 " --lpostfix str append the given string to all other symbols\n"
2023 " --keep-all output files will not be removed even if an error happens\n"
2024 " --limit-X val set execution limit X\n");
2026 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
2027 printf(" %-15s %s (default ",
2028 limit_info
[i
].name
, limit_info
[i
].help
);
2029 if (nasm_limit
[i
] < LIMIT_MAX_VAL
) {
2030 printf("%"PRId64
")\n", nasm_limit
[i
]);
2032 printf("unlimited)\n");
2036 printf("\nWarnings for the -W/-w options:\n");
2038 for (i
= 0; i
<= ERR_WARN_ALL
; i
++)
2039 printf(" %-23s %s%s\n",
2040 warnings
[i
].name
, warnings
[i
].help
,
2041 i
== ERR_WARN_ALL
? "\n" :
2042 warnings
[i
].enabled
? " (default on)" :
2046 printf("valid output formats for -f are"
2047 " (`*' denotes default):\n");
2048 ofmt_list(ofmt
, stdout
);
2050 printf("For a list of valid output formats, use -hf.\n");
2051 printf("For a list of debug formats, use -f <format> -y.\n");