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 *, 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 int optimizing
= MAX_OPTIMIZE
; /* number of optimization passes to take */
121 static int cmd_sb
= 16; /* by default */
124 static iflag_t cmd_cpu
;
126 struct location location
;
127 bool in_absolute
; /* Flag we are in ABSOLUTE seg */
128 struct location absolute
; /* Segment/offset inside ABSOLUTE */
130 static struct RAA
*offsets
;
132 static struct SAA
*forwrefs
; /* keep track of forward references */
133 static const struct forwrefinfo
*forwref
;
135 static const struct preproc_ops
*preproc
;
137 #define OP_NORMAL (1u << 0)
138 #define OP_PREPROCESS (1u << 1)
139 #define OP_DEPEND (1u << 2)
141 static unsigned int operating_mode
;
143 /* Dependency flags */
144 static bool depend_emit_phony
= false;
145 static bool depend_missing_ok
= false;
146 static const char *depend_target
= NULL
;
147 static const char *depend_file
= NULL
;
148 StrList
*depend_list
;
150 static bool want_usage
;
151 static bool terminate_after_phase
;
152 bool user_nolist
= false;
154 static char *quote_for_pmake(const char *str
);
155 static char *quote_for_wmake(const char *str
);
156 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
159 * Execution limits that can be set via a command-line option or %pragma
162 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
164 int64_t nasm_limit
[LIMIT_MAX
+1] =
165 { LIMIT_MAX_VAL
, 1000, 1000000, 1000000, 1000000, 2000000000 };
171 static const struct limit_info limit_info
[LIMIT_MAX
+1] = {
172 { "passes", "total number of passes" },
173 { "stalled-passes", "number of passes without forward progress" },
174 { "macro-levels", "levels of macro expansion"},
175 { "rep", "%rep count" },
176 { "eval", "expression evaluation descent"},
177 { "lines", "total source lines processed"}
180 enum directive_result
181 nasm_set_limit(const char *limit
, const char *valstr
)
188 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
189 if (!nasm_stricmp(limit
, limit_info
[i
].name
))
194 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
196 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_UNKNOWN_PRAGMA
;
197 nasm_error(errlevel
, "unknown limit: `%s'", limit
);
201 if (!nasm_stricmp(valstr
, "unlimited")) {
204 val
= readnum(valstr
, &rn_error
);
205 if (rn_error
|| val
< 0) {
207 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
209 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_BAD_PRAGMA
;
210 nasm_error(errlevel
, "invalid limit value: `%s'", limit
);
213 if (val
> LIMIT_MAX_VAL
)
221 int64_t switch_segment(int32_t segment
)
223 location
.segment
= segment
;
224 if (segment
== NO_SEG
) {
225 location
.offset
= absolute
.offset
;
228 location
.offset
= raa_read(offsets
, segment
);
231 return location
.offset
;
234 static void set_curr_offs(int64_t l_off
)
237 absolute
.offset
= l_off
;
239 offsets
= raa_write(offsets
, location
.segment
, l_off
);
242 static void increment_offset(int64_t delta
)
244 if (unlikely(delta
== 0))
247 location
.offset
+= delta
;
248 set_curr_offs(location
.offset
);
251 static void nasm_fputs(const char *line
, FILE * outfile
)
254 fputs(line
, outfile
);
260 static void define_macros_early(void)
262 const struct compile_time
* const oct
= &official_compile_time
;
265 if (oct
->have_local
) {
266 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
267 preproc
->pre_define(temp
);
268 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
269 preproc
->pre_define(temp
);
270 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
271 preproc
->pre_define(temp
);
272 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
273 preproc
->pre_define(temp
);
277 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
278 preproc
->pre_define(temp
);
279 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
280 preproc
->pre_define(temp
);
281 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
282 preproc
->pre_define(temp
);
283 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
284 preproc
->pre_define(temp
);
287 if (oct
->have_posix
) {
288 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
289 preproc
->pre_define(temp
);
293 static void define_macros_late(void)
298 * In case if output format is defined by alias
299 * we have to put shortname of the alias itself here
300 * otherwise ABI backward compatibility gets broken.
302 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s",
303 ofmt_alias
? ofmt_alias
->shortname
: ofmt
->shortname
);
304 preproc
->pre_define(temp
);
307 static void emit_dependencies(StrList
*list
)
312 bool wmake
= (quote_for_make
== quote_for_wmake
);
313 const char *wrapstr
, *nulltarget
;
315 wrapstr
= wmake
? " &\n " : " \\\n ";
316 nulltarget
= wmake
? "\t%null\n" : "";
318 if (depend_file
&& strcmp(depend_file
, "-")) {
319 deps
= nasm_open_write(depend_file
, NF_TEXT
);
321 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
322 "unable to write dependency file `%s'", depend_file
);
329 linepos
= fprintf(deps
, "%s :", depend_target
);
330 list_for_each(l
, list
) {
331 char *file
= quote_for_make(l
->str
);
333 if (linepos
+ len
> 62 && linepos
> 1) {
334 fputs(wrapstr
, deps
);
337 fprintf(deps
, " %s", file
);
341 fprintf(deps
, "\n\n");
343 list_for_each_safe(l
, nl
, list
) {
344 if (depend_emit_phony
) {
345 char *file
= quote_for_make(l
->str
);
346 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
356 /* Convert a struct tm to a POSIX-style time constant */
357 static int64_t make_posix_time(const struct tm
*tm
)
360 int64_t y
= tm
->tm_year
;
362 /* See IEEE 1003.1:2004, section 4.14 */
364 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
376 static void timestamp(void)
378 struct compile_time
* const oct
= &official_compile_time
;
379 const struct tm
*tp
, *best_gm
;
385 tp
= localtime(&oct
->t
);
388 best_gm
= &oct
->local
;
389 oct
->have_local
= true;
392 tp
= gmtime(&oct
->t
);
397 if (!oct
->have_local
)
398 oct
->local
= oct
->gm
;
400 oct
->gm
= oct
->local
;
404 oct
->posix
= make_posix_time(best_gm
);
405 oct
->have_posix
= true;
409 int main(int argc
, char **argv
)
411 StrList
**depend_ptr
;
415 iflag_set_default_cpu(&cpu
);
416 iflag_set_default_cpu(&cmd_cpu
);
419 want_usage
= terminate_after_phase
= false;
420 nasm_set_verror(nasm_verror_gnu
);
428 * We must call init_labels() before the command line parsing,
429 * because we may be setting prefixes/suffixes from the command
434 offsets
= raa_init();
435 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
438 operating_mode
= OP_NORMAL
;
440 parse_cmdline(argc
, argv
, 1);
441 if (terminate_after_phase
) {
448 * Define some macros dependent on the runtime, but not
449 * on the command line (as those are scanned in cmdline pass 2.)
452 define_macros_early();
454 parse_cmdline(argc
, argv
, 2);
455 if (terminate_after_phase
) {
461 /* Save away the default state of warnings */
462 memcpy(warning_state_init
, warning_state
, sizeof warning_state
);
464 if (!using_debug_info
) {
465 /* No debug info, redirect to the null backend (empty stubs) */
466 dfmt
= &null_debug_form
;
467 } else if (!debug_format
) {
468 /* Default debug format for this backend */
469 dfmt
= ofmt
->default_dfmt
;
471 dfmt
= dfmt_find(ofmt
, debug_format
);
473 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
474 "unrecognized debug format `%s' for"
475 " output format `%s'",
476 debug_format
, ofmt
->shortname
);
481 preproc
->extra_stdmac(ofmt
->stdmac
);
483 /* no output file name? */
485 outname
= filename_set_extension(inname
, ofmt
->extension
);
487 /* define some macros dependent of command-line */
488 define_macros_late();
490 depend_ptr
= (depend_file
|| (operating_mode
& OP_DEPEND
)) ? &depend_list
: NULL
;
493 depend_target
= quote_for_make(outname
);
495 if (operating_mode
& OP_DEPEND
) {
498 if (depend_missing_ok
)
499 preproc
->include_path(NULL
); /* "assume generated" */
501 preproc
->reset(inname
, 0, depend_ptr
);
503 while ((line
= preproc
->getline()))
506 } else if (operating_mode
& OP_PREPROCESS
) {
508 const char *file_name
= NULL
;
509 int32_t prior_linnum
= 0;
513 ofile
= nasm_open_write(outname
, NF_TEXT
);
515 nasm_fatal(ERR_NOFILE
,
516 "unable to open output file `%s'",
521 location
.known
= false;
524 preproc
->reset(inname
, 3, depend_ptr
);
526 /* Revert all warnings to the default state */
527 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
529 while ((line
= preproc
->getline())) {
531 * We generate %line directives if needed for later programs
533 int32_t linnum
= prior_linnum
+= lineinc
;
534 int altline
= src_get(&linnum
, &file_name
);
536 if (altline
== 1 && lineinc
== 1)
537 nasm_fputs("", ofile
);
539 lineinc
= (altline
!= -1 || lineinc
!= 1);
540 fprintf(ofile
? ofile
: stdout
,
541 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
544 prior_linnum
= linnum
;
546 nasm_fputs(line
, ofile
);
552 if (ofile
&& terminate_after_phase
&& !keep_all
)
557 if (operating_mode
& OP_NORMAL
) {
558 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
560 nasm_fatal(ERR_NOFILE
,
561 "unable to open output file `%s'", outname
);
566 assemble_file(inname
, depend_ptr
);
568 if (!terminate_after_phase
) {
573 nasm_error(ERR_NONFATAL
|ERR_NOFILE
,
574 "write error on output file `%s'", outname
);
575 terminate_after_phase
= true;
581 if (terminate_after_phase
&& !keep_all
)
587 if (depend_list
&& !terminate_after_phase
)
588 emit_dependencies(depend_list
);
599 return terminate_after_phase
;
603 * Get a parameter for a command line option.
604 * First arg must be in the form of e.g. -f...
606 static char *get_param(char *p
, char *q
, bool *advance
)
609 if (p
[2]) /* the parameter's in the option */
610 return nasm_skip_spaces(p
+ 2);
615 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
616 "option `-%c' requires an argument", p
[1]);
623 static void copy_filename(const char **dst
, const char *src
, const char *what
)
626 nasm_fatal(0, "more than one %s file specified: %s\n", what
, src
);
628 *dst
= nasm_strdup(src
);
632 * Convert a string to a POSIX make-safe form
634 static char *quote_for_pmake(const char *str
)
639 size_t n
= 1; /* Terminating zero */
645 for (p
= str
; *p
; p
++) {
649 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
669 /* Convert N backslashes at the end of filename to 2N backslashes */
673 os
= q
= nasm_malloc(n
);
676 for (p
= str
; *p
; p
++) {
714 * Convert a string to a Watcom make-safe form
716 static char *quote_for_wmake(const char *str
)
722 size_t n
= 1; /* Terminating zero */
727 for (p
= str
; *p
; p
++) {
752 os
= q
= nasm_malloc(n
);
757 for (p
= str
; *p
; p
++) {
796 enum text_options opt
;
800 static const struct textargs textopts
[] = {
801 {"v", OPT_VERSION
, false, 0},
802 {"version", OPT_VERSION
, false, 0},
803 {"help", OPT_HELP
, false, 0},
804 {"abort-on-panic", OPT_ABORT_ON_PANIC
, false, 0},
805 {"prefix", OPT_MANGLE
, true, LM_GPREFIX
},
806 {"postfix", OPT_MANGLE
, true, LM_GSUFFIX
},
807 {"gprefix", OPT_MANGLE
, true, LM_GPREFIX
},
808 {"gpostfix", OPT_MANGLE
, true, LM_GSUFFIX
},
809 {"lprefix", OPT_MANGLE
, true, LM_LPREFIX
},
810 {"lpostfix", OPT_MANGLE
, true, LM_LSUFFIX
},
811 {"include", OPT_INCLUDE
, true, 0},
812 {"pragma", OPT_PRAGMA
, true, 0},
813 {"before", OPT_BEFORE
, true, 0},
814 {"limit-", OPT_LIMIT
, true, 0},
815 {"keep-all", OPT_KEEP_ALL
, false, 0},
816 {NULL
, OPT_BOGUS
, false, 0}
819 static void show_version(void)
821 printf("NASM version %s compiled on %s%s\n",
822 nasm_version
, nasm_date
, nasm_compile_options
);
826 static bool stopoptions
= false;
827 static bool process_arg(char *p
, char *q
, int pass
)
830 bool advance
= false;
835 if (p
[0] == '-' && !stopoptions
) {
836 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
837 /* These parameters take values */
838 if (!(param
= get_param(p
, q
, &advance
)))
848 case 'o': /* output file */
850 copy_filename(&outname
, param
, "output");
853 case 'f': /* output format */
855 ofmt
= ofmt_find(param
, &ofmt_alias
);
857 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
858 "unrecognised output format `%s' - "
859 "use -hf for a list", param
);
864 case 'O': /* Optimization level */
869 /* Naked -O == -Ox */
870 optimizing
= MAX_OPTIMIZE
;
874 case '0': case '1': case '2': case '3': case '4':
875 case '5': case '6': case '7': case '8': case '9':
876 opt
= strtoul(param
, ¶m
, 10);
878 /* -O0 -> optimizing == -1, 0.98 behaviour */
879 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
881 optimizing
= opt
- 1;
889 opt_verbose_info
= true;
894 optimizing
= MAX_OPTIMIZE
;
899 "unknown optimization option -O%c\n",
904 if (optimizing
> MAX_OPTIMIZE
)
905 optimizing
= MAX_OPTIMIZE
;
910 case 'p': /* pre-include */
913 preproc
->pre_include(param
);
916 case 'd': /* pre-define */
919 preproc
->pre_define(param
);
922 case 'u': /* un-define */
925 preproc
->pre_undefine(param
);
928 case 'i': /* include search path */
931 preproc
->include_path(param
);
934 case 'l': /* listing file */
936 copy_filename(&listname
, param
, "listing");
939 case 'Z': /* error messages file */
941 copy_filename(&errname
, param
, "error");
944 case 'F': /* specify debug format */
946 using_debug_info
= true;
947 debug_format
= param
;
951 case 'X': /* specify error reporting format */
953 if (nasm_stricmp("vc", param
) == 0)
954 nasm_set_verror(nasm_verror_vc
);
955 else if (nasm_stricmp("gnu", param
) == 0)
956 nasm_set_verror(nasm_verror_gnu
);
958 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
959 "unrecognized error reporting format `%s'",
966 using_debug_info
= true;
968 debug_format
= nasm_skip_spaces(p
+ 2);
974 exit(0); /* never need usage message here */
978 printf("\nvalid debug formats for '%s' output format are"
979 " ('*' denotes default):\n", ofmt
->shortname
);
980 dfmt_list(ofmt
, stdout
);
986 tasm_compatible_mode
= true;
993 case 'e': /* preprocess only */
996 operating_mode
= OP_PREPROCESS
;
999 case 'a': /* assemble only - don't preprocess */
1001 preproc
= &preproc_nop
;
1007 if (!set_warning_status(param
)) {
1008 nasm_error(ERR_WARNING
|ERR_NOFILE
|ERR_WARN_UNK_WARNING
,
1009 "unknown warning option: %s", param
);
1018 quote_for_make
= quote_for_wmake
;
1032 operating_mode
= OP_DEPEND
;
1035 operating_mode
= OP_DEPEND
;
1036 depend_missing_ok
= true;
1039 depend_emit_phony
= true;
1042 operating_mode
= OP_NORMAL
;
1055 depend_target
= quote_for_make(q
);
1059 /* handled in pass 1 */
1062 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1063 "unknown dependency option `-M%c'", p
[2]);
1067 if (advance
&& (!q
|| !q
[0])) {
1068 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1069 "option `-M%c' requires a parameter", p
[2]);
1076 const struct textargs
*tx
;
1082 if (!*p
) { /* -- => stop processing options */
1088 for (tx
= textopts
; tx
->label
; tx
++) {
1089 olen
= strlen(tx
->label
);
1094 if (nasm_memicmp(p
, tx
->label
, olen
))
1097 if (tx
->label
[olen
-1] == '-')
1098 break; /* Incomplete option */
1100 if (!p
[olen
] || p
[olen
] == '=')
1101 break; /* Complete option */
1105 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1106 "unrecognized option `--%s'", p
);
1109 eqsave
= param
= strchr(p
+olen
, '=');
1119 /* Note: a null string is a valid parameter */
1121 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1122 "option `--%s' requires an argument",
1128 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1129 "option `--%s' does not take an argument",
1139 case OPT_ABORT_ON_PANIC
:
1140 abort_on_panic
= true;
1144 set_label_mangle(tx
->pvt
, param
);
1148 preproc
->pre_include(q
);
1152 preproc
->pre_command("pragma", param
);
1156 preproc
->pre_command(NULL
, param
);
1160 nasm_set_limit(p
+olen
, param
);
1173 *eqsave
= '='; /* Restore = argument separator */
1179 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1180 "unrecognised option `-%c'", p
[1]);
1183 } else if (pass
== 2) {
1184 /* In theory we could allow multiple input files... */
1185 copy_filename(&inname
, p
, "input");
1191 #define ARG_BUF_DELTA 128
1193 static void process_respfile(FILE * rfile
, int pass
)
1195 char *buffer
, *p
, *q
, *prevarg
;
1196 int bufsize
, prevargsize
;
1198 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1199 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1200 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1203 while (1) { /* Loop to handle all lines in file */
1205 while (1) { /* Loop to handle long lines */
1206 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1210 if (p
> buffer
&& p
[-1] == '\n')
1212 if (p
- buffer
> bufsize
- 10) {
1214 offset
= p
- buffer
;
1215 bufsize
+= ARG_BUF_DELTA
;
1216 buffer
= nasm_realloc(buffer
, bufsize
);
1217 p
= buffer
+ offset
;
1221 if (!q
&& p
== buffer
) {
1223 process_arg(prevarg
, NULL
, pass
);
1230 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1231 * them are present at the end of the line.
1233 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1235 while (p
> buffer
&& nasm_isspace(p
[-1]))
1238 p
= nasm_skip_spaces(buffer
);
1240 if (process_arg(prevarg
, p
, pass
))
1243 if ((int) strlen(p
) > prevargsize
- 10) {
1244 prevargsize
+= ARG_BUF_DELTA
;
1245 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1247 strncpy(prevarg
, p
, prevargsize
);
1251 /* Function to process args from a string of args, rather than the
1252 * argv array. Used by the environment variable and response file
1255 static void process_args(char *args
, int pass
)
1257 char *p
, *q
, *arg
, *prevarg
;
1258 char separator
= ' ';
1261 if (*p
&& *p
!= '-')
1266 while (*p
&& *p
!= separator
)
1268 while (*p
== separator
)
1272 if (process_arg(prevarg
, arg
, pass
))
1276 process_arg(arg
, NULL
, pass
);
1279 static void process_response_file(const char *file
, int pass
)
1282 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1287 while (fgets(str
, sizeof str
, f
)) {
1288 process_args(str
, pass
);
1293 static void parse_cmdline(int argc
, char **argv
, int pass
)
1296 char *envreal
, *envcopy
= NULL
, *p
;
1299 /* Initialize all the warnings to their default state */
1300 for (i
= 0; i
< ERR_WARN_ALL
; i
++) {
1301 warning_state_init
[i
] = warning_state
[i
] =
1302 warnings
[i
].enabled
? WARN_ST_ENABLED
: 0;
1306 * First, process the NASMENV environment variable.
1308 envreal
= getenv("NASMENV");
1310 envcopy
= nasm_strdup(envreal
);
1311 process_args(envcopy
, pass
);
1316 * Now process the actual command line.
1321 if (argv
[0][0] == '@') {
1323 * We have a response file, so process this as a set of
1324 * arguments like the environment variable. This allows us
1325 * to have multiple arguments on a single line, which is
1326 * different to the -@resp file processing below for regular
1329 process_response_file(argv
[0]+1, pass
);
1333 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1334 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1336 rfile
= nasm_open_read(p
, NF_TEXT
);
1338 process_respfile(rfile
, pass
);
1341 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1342 "unable to open response file `%s'", p
);
1345 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1346 argv
+= advance
, argc
-= advance
;
1350 * Look for basic command line typos. This definitely doesn't
1351 * catch all errors, but it might help cases of fumbled fingers.
1357 nasm_fatal(ERR_NOFILE
| ERR_USAGE
, "no input file specified");
1359 else if ((errname
&& !strcmp(inname
, errname
)) ||
1360 (outname
&& !strcmp(inname
, outname
)) ||
1361 (listname
&& !strcmp(inname
, listname
)) ||
1362 (depend_file
&& !strcmp(inname
, depend_file
)))
1363 nasm_fatal(ERR_USAGE
, "will not overwrite input file");
1366 error_file
= nasm_open_write(errname
, NF_TEXT
);
1368 error_file
= stderr
; /* Revert to default! */
1369 nasm_fatal(ERR_NOFILE
| ERR_USAGE
,
1370 "cannot open file `%s' for error messages",
1376 static void assemble_file(const char *fname
, StrList
**depend_ptr
)
1381 uint64_t prev_offset_changed
;
1382 int64_t stall_count
= 0; /* Make sure we make forward progress... */
1388 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_386
))
1389 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1392 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_X86_64
))
1393 nasm_fatal(0, "command line: 64-bit segment size requires a higher cpu");
1400 prev_offset_changed
= nasm_limit
[LIMIT_PASSES
];
1401 for (passn
= 1; pass0
<= 2; passn
++) {
1402 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1403 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1404 /* pass0 0, 0, 0, ..., 1, 2 */
1406 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1409 lfmt
->init(listname
);
1410 } else if (passn
== 1 && listname
&& !keep_all
) {
1411 /* Remove the list file in case we die before the output pass */
1414 in_absolute
= false;
1415 global_offset_changed
= 0; /* set by redefine_label */
1417 saa_rewind(forwrefs
);
1418 forwref
= saa_rstruct(forwrefs
);
1420 offsets
= raa_init();
1422 location
.segment
= NO_SEG
;
1423 location
.offset
= 0;
1425 location
.known
= true;
1427 switch_segment(ofmt
->section(NULL
, pass2
, &globalbits
));
1428 preproc
->reset(fname
, pass1
, pass1
== 2 ? depend_ptr
: NULL
);
1430 /* Revert all warnings to the default state */
1431 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
1435 while ((line
= preproc
->getline())) {
1436 if (++globallineno
> nasm_limit
[LIMIT_LINES
])
1438 "overall line count exceeds the maximum %"PRId64
"\n",
1439 nasm_limit
[LIMIT_LINES
]);
1442 * Here we parse our directives; this is not handled by the
1445 if (process_directives(line
))
1446 goto end_of_line
; /* Just do final cleanup */
1448 /* Not a directive, or even something that starts with [ */
1449 parse_line(pass1
, line
, &output_ins
);
1451 if (optimizing
> 0) {
1452 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1453 output_ins
.forw_ref
= true;
1455 output_ins
.oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1456 forwref
= saa_rstruct(forwrefs
);
1457 } while (forwref
!= NULL
1458 && forwref
->lineno
== globallineno
);
1460 output_ins
.forw_ref
= false;
1462 if (output_ins
.forw_ref
) {
1464 for (i
= 0; i
< output_ins
.operands
; i
++) {
1465 if (output_ins
.oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1466 struct forwrefinfo
*fwinf
= (struct forwrefinfo
*)saa_wstruct(forwrefs
);
1467 fwinf
->lineno
= globallineno
;
1476 if (output_ins
.opcode
== I_EQU
) {
1477 if (!output_ins
.label
)
1478 nasm_error(ERR_NONFATAL
,
1479 "EQU not preceded by label");
1481 if (output_ins
.operands
== 1 &&
1482 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1483 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1484 define_label(output_ins
.label
,
1485 output_ins
.oprs
[0].segment
,
1486 output_ins
.oprs
[0].offset
, false);
1487 } else if (output_ins
.operands
== 2
1488 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1489 && (output_ins
.oprs
[0].type
& COLON
)
1490 && output_ins
.oprs
[0].segment
== NO_SEG
1491 && output_ins
.oprs
[0].wrt
== NO_SEG
1492 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1493 && output_ins
.oprs
[1].segment
== NO_SEG
1494 && output_ins
.oprs
[1].wrt
== NO_SEG
) {
1495 define_label(output_ins
.label
,
1496 output_ins
.oprs
[0].offset
| SEG_ABS
,
1497 output_ins
.oprs
[1].offset
, false);
1499 nasm_error(ERR_NONFATAL
, "bad syntax for EQU");
1501 } else { /* instruction isn't an EQU */
1504 nasm_assert(output_ins
.times
>= 0);
1506 for (n
= 1; n
<= output_ins
.times
; n
++) {
1508 int64_t l
= insn_size(location
.segment
,
1510 globalbits
, &output_ins
);
1512 /* if (using_debug_info) && output_ins.opcode != -1) */
1513 if (using_debug_info
)
1514 { /* fbk 03/25/01 */
1515 /* this is done here so we can do debug type info */
1517 TYS_ELEMENTS(output_ins
.operands
);
1518 switch (output_ins
.opcode
) {
1521 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_BYTE
;
1525 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_WORD
;
1529 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_DWORD
;
1533 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_QWORD
;
1537 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_TBYTE
;
1541 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_OWORD
;
1545 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_YWORD
;
1549 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_ZWORD
;
1552 typeinfo
|= TY_BYTE
;
1555 typeinfo
|= TY_WORD
;
1558 if (output_ins
.eops_float
)
1559 typeinfo
|= TY_FLOAT
;
1561 typeinfo
|= TY_DWORD
;
1564 typeinfo
|= TY_QWORD
;
1567 typeinfo
|= TY_TBYTE
;
1570 typeinfo
|= TY_OWORD
;
1573 typeinfo
|= TY_YWORD
;
1576 typeinfo
|= TY_ZWORD
;
1579 typeinfo
= TY_LABEL
;
1583 dfmt
->debug_typevalue(typeinfo
);
1587 * For INCBIN, let the code in assemble
1588 * handle TIMES, so we don't have to read the
1589 * input file over and over.
1592 increment_offset(l
);
1595 * else l == -1 => invalid instruction, which will be
1596 * flagged as an error on pass 2
1600 lfmt
->uplevel(LIST_TIMES
);
1601 increment_offset(assemble(location
.segment
,
1603 globalbits
, &output_ins
));
1607 if (output_ins
.times
> 1)
1608 lfmt
->downlevel(LIST_TIMES
);
1610 cleanup_insn(&output_ins
);
1614 } /* end while (line = preproc->getline... */
1616 if (pass0
== 2 && global_offset_changed
&& !terminate_after_phase
)
1617 nasm_error(ERR_NONFATAL
,
1618 "phase error detected at end of assembly.");
1621 preproc
->cleanup(1);
1624 * Always run at least two optimization passes (pass0 == 0);
1625 * things like subsections will fail miserably without that.
1626 * Once we commit to a stabilization pass (pass0 == 1), we can't
1627 * go back, and if something goes bad, we can only hope
1628 * that we don't end up with a phase error at the end.
1630 if ((passn
> 1 && !global_offset_changed
) || pass0
> 0) {
1632 } else if (global_offset_changed
&&
1633 global_offset_changed
< prev_offset_changed
) {
1634 prev_offset_changed
= global_offset_changed
;
1640 if (terminate_after_phase
)
1643 if ((stall_count
> nasm_limit
[LIMIT_STALLED
]) ||
1644 (passn
>= nasm_limit
[LIMIT_PASSES
])) {
1645 /* We get here if the labels don't converge
1646 * Example: FOO equ FOO + 1
1648 nasm_error(ERR_NONFATAL
,
1649 "Can't find valid values for all labels "
1650 "after %"PRId64
" passes, giving up.", passn
);
1651 nasm_error(ERR_NONFATAL
,
1652 "Possible causes: recursive EQUs, macro abuse.");
1657 preproc
->cleanup(0);
1659 if (!terminate_after_phase
&& opt_verbose_info
) {
1660 /* -On and -Ov switches */
1661 fprintf(stdout
, "info: assembly required 1+%"PRId64
"+1 passes\n",
1667 * gnu style error reporting
1668 * This function prints an error message to error_file in the
1669 * style used by GNU. An example would be:
1670 * file.asm:50: error: blah blah blah
1671 * where file.asm is the name of the file, 50 is the line number on
1672 * which the error occurs (or is detected) and "error:" is one of
1673 * the possible optional diagnostics -- it can be "error" or "warning"
1674 * or something else. Finally the line terminates with the actual
1677 * @param severity the severity of the warning or error
1678 * @param fmt the printf style format string
1680 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list ap
)
1682 const char *currentfile
= NULL
;
1685 if (is_suppressed_warning(severity
))
1688 if (!(severity
& ERR_NOFILE
)) {
1689 src_get(&lineno
, ¤tfile
);
1690 if (!currentfile
|| (severity
& ERR_TOPFILE
)) {
1691 currentfile
= inname
[0] ? inname
: outname
[0] ? outname
: NULL
;
1696 if (!skip_this_pass(severity
)) {
1698 fprintf(error_file
, "%s:", currentfile
? currentfile
: "nasm");
1700 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1703 nasm_verror_common(severity
, fmt
, ap
);
1707 * MS style error reporting
1708 * This function prints an error message to error_file in the
1709 * style used by Visual C and some other Microsoft tools. An example
1711 * file.asm(50) : error: blah blah blah
1712 * where file.asm is the name of the file, 50 is the line number on
1713 * which the error occurs (or is detected) and "error:" is one of
1714 * the possible optional diagnostics -- it can be "error" or "warning"
1715 * or something else. Finally the line terminates with the actual
1718 * @param severity the severity of the warning or error
1719 * @param fmt the printf style format string
1721 static void nasm_verror_vc(int severity
, const char *fmt
, va_list ap
)
1723 const char *currentfile
= NULL
;
1726 if (is_suppressed_warning(severity
))
1729 if (!(severity
& ERR_NOFILE
))
1730 src_get(&lineno
, ¤tfile
);
1732 if (!skip_this_pass(severity
)) {
1734 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1736 fputs("nasm: ", error_file
);
1740 nasm_verror_common(severity
, fmt
, ap
);
1744 * check to see if this is a suppressable warning
1746 static inline bool is_valid_warning(int severity
)
1748 /* Not a warning at all */
1749 if ((severity
& ERR_MASK
) != ERR_WARNING
)
1752 return WARN_IDX(severity
) < ERR_WARN_ALL
;
1756 * check for suppressed warning
1757 * checks for suppressed warning or pass one only warning and we're
1760 * @param severity the severity of the warning or error
1761 * @return true if we should abort error/warning printing
1763 static bool is_suppressed_warning(int severity
)
1765 /* Might be a warning but suppresed explicitly */
1766 if (is_valid_warning(severity
) && !(severity
& ERR_USAGE
))
1767 return !(warning_state
[WARN_IDX(severity
)] & WARN_ST_ENABLED
);
1772 static bool warning_is_error(int severity
)
1774 if (is_valid_warning(severity
))
1775 return !!(warning_state
[WARN_IDX(severity
)] & WARN_ST_ERROR
);
1780 static bool skip_this_pass(int severity
)
1783 * See if it's a pass-specific error or warning which should be skipped.
1784 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1785 * they cannot be resumed from.
1787 if ((severity
& ERR_MASK
) > ERR_NONFATAL
)
1791 * passn is 1 on the very first pass only.
1792 * pass0 is 2 on the code-generation (final) pass only.
1793 * These are the passes we care about in this case.
1795 return (((severity
& ERR_PASS1
) && passn
!= 1) ||
1796 ((severity
& ERR_PASS2
) && pass0
!= 2));
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_common(int severity
, const char *fmt
, va_list args
)
1814 switch (severity
& (ERR_MASK
|ERR_NO_SEVERITY
)) {
1835 vsnprintf(msg
, sizeof msg
- 64, fmt
, args
);
1836 if (is_valid_warning(severity
) && WARN_IDX(severity
) != ERR_WARN_OTHER
) {
1837 char *p
= strchr(msg
, '\0');
1838 snprintf(p
, 64, " [-w+%s]", warnings
[WARN_IDX(severity
)].name
);
1841 if (!skip_this_pass(severity
))
1842 fprintf(error_file
, "%s%s\n", pfx
, msg
);
1844 /* Are we recursing from error_list_macros? */
1845 if (severity
& ERR_PP_LISTMACRO
)
1849 * Don't suppress this with skip_this_pass(), or we don't get
1850 * pass1 or preprocessor warnings in the list file
1852 lfmt
->error(severity
, pfx
, msg
);
1854 if (skip_this_pass(severity
))
1857 if (severity
& ERR_USAGE
)
1860 preproc
->error_list_macros(severity
);
1862 switch (severity
& ERR_MASK
) {
1864 /* no further action, by definition */
1867 /* Treat warnings as errors */
1868 if (warning_is_error(severity
))
1869 terminate_after_phase
= true;
1872 terminate_after_phase
= true;
1883 exit(1); /* instantly die */
1884 break; /* placate silly compilers */
1889 abort(); /* halt, catch fire, dump core/stop debugger */
1902 static void usage(void)
1904 fputs("type `nasm -h' for help\n", error_file
);
1907 static void help(const char xopt
)
1912 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1914 " [options...] [--] filename\n"
1915 " or nasm -v (or --v) for version info\n\n"
1917 "Response files should contain command line parameters,\n"
1920 " -t assemble in SciTech TASM compatible mode\n");
1922 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1923 " -a don't preprocess (assemble only)\n"
1924 " -M generate Makefile dependencies on stdout\n"
1925 " -MG d:o, missing files assumed generated\n"
1926 " -MF file set Makefile dependency file\n"
1927 " -MD file assemble and generate dependencies\n"
1928 " -MT file dependency target name\n"
1929 " -MQ file dependency target name (quoted)\n"
1930 " -MP emit phony target\n\n"
1931 " -Zfile redirect error messages to file\n"
1932 " -s redirect error messages to stdout\n\n"
1933 " -g generate debugging information\n\n"
1934 " -F format select a debugging format\n\n"
1935 " -gformat same as -g -F format\n\n"
1936 " -o outfile write output to an outfile\n\n"
1937 " -f format select an output format\n\n"
1938 " -l listfile write listing to a listfile\n\n"
1939 " -Ipath add a pathname to the include file path\n");
1941 (" -Olevel optimize opcodes, immediates and branch offsets\n"
1942 " -O0 no optimization\n"
1943 " -O1 minimal optimization\n"
1944 " -Ox multipass optimization (default)\n"
1945 " -Pfile pre-include a file (also --include)\n"
1946 " -Dmacro[=str] pre-define a macro\n"
1947 " -Umacro undefine a macro\n"
1948 " -Xformat specifiy error reporting format (gnu or vc)\n"
1949 " -w+foo enable warning foo (equiv. -Wfoo)\n"
1950 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
1951 " -w[+-]error[=foo]\n"
1952 " promote [specific] warnings to errors\n"
1953 " -h show invocation summary and exit (also --help)\n\n"
1954 " --pragma str pre-executes a specific %%pragma\n"
1955 " --before str add line (usually a preprocessor statement) before the input\n"
1956 " --prefix str prepend the given string to all the given string\n"
1957 " to all extern, common and global symbols (also --gprefix)\n"
1958 " --postfix str append the given string to all the given string\n"
1959 " to all extern, common and global symbols (also --gpostfix)\n"
1960 " --lprefix str prepend the given string to all other symbols\n"
1961 " --lpostfix str append the given string to all other symbols\n"
1962 " --keep-all output files will not be removed even if an error happens\n"
1963 " --limit-X val set execution limit X\n");
1965 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
1966 printf(" %-15s %s (default ",
1967 limit_info
[i
].name
, limit_info
[i
].help
);
1968 if (nasm_limit
[i
] < LIMIT_MAX_VAL
) {
1969 printf("%"PRId64
")\n", nasm_limit
[i
]);
1971 printf("unlimited)\n");
1975 printf("\nWarnings for the -W/-w options:\n");
1977 for (i
= 0; i
<= ERR_WARN_ALL
; i
++)
1978 printf(" %-23s %s%s\n",
1979 warnings
[i
].name
, warnings
[i
].help
,
1980 i
== ERR_WARN_ALL
? "\n" :
1981 warnings
[i
].enabled
? " (default on)" :
1985 printf("valid output formats for -f are"
1986 " (`*' denotes default):\n");
1987 ofmt_list(ofmt
, stdout
);
1989 printf("For a list of valid output formats, use -hf.\n");
1990 printf("For a list of debug formats, use -f <format> -y.\n");