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 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
;
138 #define OP_NORMAL (1u << 0)
139 #define OP_PREPROCESS (1u << 1)
140 #define OP_DEPEND (1u << 2)
142 static unsigned int operating_mode
;
144 /* Dependency flags */
145 static bool depend_emit_phony
= false;
146 static bool depend_missing_ok
= false;
147 static const char *depend_target
= NULL
;
148 static const char *depend_file
= NULL
;
149 StrList
*depend_list
;
151 static bool want_usage
;
152 static bool terminate_after_phase
;
153 bool user_nolist
= false;
155 static char *quote_for_pmake(const char *str
);
156 static char *quote_for_wmake(const char *str
);
157 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
160 * Execution limits that can be set via a command-line option or %pragma
163 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
165 int64_t nasm_limit
[LIMIT_MAX
+1] =
166 { LIMIT_MAX_VAL
, 1000, 1000000, 1000000, 1000000, 2000000000 };
172 static const struct limit_info limit_info
[LIMIT_MAX
+1] = {
173 { "passes", "total number of passes" },
174 { "stalled-passes", "number of passes without forward progress" },
175 { "macro-levels", "levels of macro expansion"},
176 { "rep", "%rep count" },
177 { "eval", "expression evaluation descent"},
178 { "lines", "total source lines processed"}
181 enum directive_result
182 nasm_set_limit(const char *limit
, const char *valstr
)
189 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
190 if (!nasm_stricmp(limit
, limit_info
[i
].name
))
195 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
197 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_UNKNOWN_PRAGMA
;
198 nasm_error(errlevel
, "unknown limit: `%s'", limit
);
202 if (!nasm_stricmp(valstr
, "unlimited")) {
205 val
= readnum(valstr
, &rn_error
);
206 if (rn_error
|| val
< 0) {
208 errlevel
= ERR_WARNING
|ERR_NOFILE
|ERR_USAGE
;
210 errlevel
= ERR_WARNING
|ERR_PASS1
|ERR_WARN_BAD_PRAGMA
;
211 nasm_error(errlevel
, "invalid limit value: `%s'", limit
);
214 if (val
> LIMIT_MAX_VAL
)
222 int64_t switch_segment(int32_t segment
)
224 location
.segment
= segment
;
225 if (segment
== NO_SEG
) {
226 location
.offset
= absolute
.offset
;
229 location
.offset
= raa_read(offsets
, segment
);
232 return location
.offset
;
235 static void set_curr_offs(int64_t l_off
)
238 absolute
.offset
= l_off
;
240 offsets
= raa_write(offsets
, location
.segment
, l_off
);
243 static void increment_offset(int64_t delta
)
245 if (unlikely(delta
== 0))
248 location
.offset
+= delta
;
249 set_curr_offs(location
.offset
);
252 static void nasm_fputs(const char *line
, FILE * outfile
)
255 fputs(line
, outfile
);
261 static void define_macros_early(void)
263 const struct compile_time
* const oct
= &official_compile_time
;
266 if (oct
->have_local
) {
267 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
268 preproc
->pre_define(temp
);
269 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
270 preproc
->pre_define(temp
);
271 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
272 preproc
->pre_define(temp
);
273 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
274 preproc
->pre_define(temp
);
278 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
279 preproc
->pre_define(temp
);
280 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
281 preproc
->pre_define(temp
);
282 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
283 preproc
->pre_define(temp
);
284 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
285 preproc
->pre_define(temp
);
288 if (oct
->have_posix
) {
289 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
290 preproc
->pre_define(temp
);
294 static void define_macros_late(void)
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 static void emit_dependencies(StrList
*list
)
312 bool wmake
= (quote_for_make
== quote_for_wmake
);
313 const char *wrapstr
, *nulltarget
;
314 struct strlist_entry
*l
;
319 wrapstr
= wmake
? " &\n " : " \\\n ";
320 nulltarget
= wmake
? "\t%null\n" : "";
322 if (depend_file
&& strcmp(depend_file
, "-")) {
323 deps
= nasm_open_write(depend_file
, NF_TEXT
);
325 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
326 "unable to write dependency file `%s'", depend_file
);
333 linepos
= fprintf(deps
, "%s :", depend_target
);
334 list_for_each(l
, list
->head
) {
335 char *file
= quote_for_make(l
->str
);
337 if (linepos
+ len
> 62 && linepos
> 1) {
338 fputs(wrapstr
, deps
);
341 fprintf(deps
, " %s", file
);
345 fprintf(deps
, "\n\n");
347 list_for_each(l
, list
->head
) {
348 if (depend_emit_phony
) {
349 char *file
= quote_for_make(l
->str
);
350 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
361 /* Convert a struct tm to a POSIX-style time constant */
362 static int64_t make_posix_time(const struct tm
*tm
)
365 int64_t y
= tm
->tm_year
;
367 /* See IEEE 1003.1:2004, section 4.14 */
369 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
381 static void timestamp(void)
383 struct compile_time
* const oct
= &official_compile_time
;
384 const struct tm
*tp
, *best_gm
;
390 tp
= localtime(&oct
->t
);
393 best_gm
= &oct
->local
;
394 oct
->have_local
= true;
397 tp
= gmtime(&oct
->t
);
402 if (!oct
->have_local
)
403 oct
->local
= oct
->gm
;
405 oct
->gm
= oct
->local
;
409 oct
->posix
= make_posix_time(best_gm
);
410 oct
->have_posix
= true;
414 int main(int argc
, char **argv
)
418 iflag_set_default_cpu(&cpu
);
419 iflag_set_default_cpu(&cmd_cpu
);
422 want_usage
= terminate_after_phase
= false;
423 nasm_set_verror(nasm_verror_gnu
);
431 * We must call init_labels() before the command line parsing,
432 * because we may be setting prefixes/suffixes from the command
437 offsets
= raa_init();
438 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
441 operating_mode
= OP_NORMAL
;
443 parse_cmdline(argc
, argv
, 1);
444 if (terminate_after_phase
) {
451 * Define some macros dependent on the runtime, but not
452 * on the command line (as those are scanned in cmdline pass 2.)
455 define_macros_early();
457 parse_cmdline(argc
, argv
, 2);
458 if (terminate_after_phase
) {
464 /* Save away the default state of warnings */
465 memcpy(warning_state_init
, warning_state
, sizeof warning_state
);
467 if (!using_debug_info
) {
468 /* No debug info, redirect to the null backend (empty stubs) */
469 dfmt
= &null_debug_form
;
470 } else if (!debug_format
) {
471 /* Default debug format for this backend */
472 dfmt
= ofmt
->default_dfmt
;
474 dfmt
= dfmt_find(ofmt
, debug_format
);
476 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
477 "unrecognized debug format `%s' for"
478 " output format `%s'",
479 debug_format
, ofmt
->shortname
);
484 preproc
->extra_stdmac(ofmt
->stdmac
);
487 * If no output file name provided and this
488 * is a preprocess mode, we're perfectly
489 * fine to output into stdout.
492 if (!(operating_mode
& OP_PREPROCESS
))
493 outname
= filename_set_extension(inname
, ofmt
->extension
);
496 /* define some macros dependent of command-line */
497 define_macros_late();
499 if (depend_file
|| (operating_mode
& OP_DEPEND
))
500 depend_list
= strlist_allocate();
503 depend_target
= quote_for_make(outname
);
505 if (operating_mode
& OP_DEPEND
) {
508 if (depend_missing_ok
)
509 preproc
->include_path(NULL
); /* "assume generated" */
511 preproc
->reset(inname
, 0, depend_list
);
513 while ((line
= preproc
->getline()))
516 } else if (operating_mode
& OP_PREPROCESS
) {
518 const char *file_name
= NULL
;
519 int32_t prior_linnum
= 0;
523 ofile
= nasm_open_write(outname
, NF_TEXT
);
525 nasm_fatal_fl(ERR_NOFILE
,
526 "unable to open output file `%s'",
531 location
.known
= false;
534 preproc
->reset(inname
, 3, depend_list
);
536 /* Revert all warnings to the default state */
537 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
539 while ((line
= preproc
->getline())) {
541 * We generate %line directives if needed for later programs
543 int32_t linnum
= prior_linnum
+= lineinc
;
544 int altline
= src_get(&linnum
, &file_name
);
546 if (altline
== 1 && lineinc
== 1)
547 nasm_fputs("", ofile
);
549 lineinc
= (altline
!= -1 || lineinc
!= 1);
550 fprintf(ofile
? ofile
: stdout
,
551 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
554 prior_linnum
= linnum
;
556 nasm_fputs(line
, ofile
);
562 if (ofile
&& terminate_after_phase
&& !keep_all
)
567 if (operating_mode
& OP_NORMAL
) {
568 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
570 nasm_fatal_fl(ERR_NOFILE
,
571 "unable to open output file `%s'", outname
);
576 assemble_file(inname
, depend_list
);
578 if (!terminate_after_phase
) {
583 nasm_error(ERR_NONFATAL
|ERR_NOFILE
,
584 "write error on output file `%s'", outname
);
585 terminate_after_phase
= true;
591 if (terminate_after_phase
&& !keep_all
)
597 if (depend_list
&& !terminate_after_phase
)
598 emit_dependencies(depend_list
);
609 return terminate_after_phase
;
613 * Get a parameter for a command line option.
614 * First arg must be in the form of e.g. -f...
616 static char *get_param(char *p
, char *q
, bool *advance
)
619 if (p
[2]) /* the parameter's in the option */
620 return nasm_skip_spaces(p
+ 2);
625 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
626 "option `-%c' requires an argument", p
[1]);
633 static void copy_filename(const char **dst
, const char *src
, const char *what
)
636 nasm_fatal("more than one %s file specified: %s\n", what
, src
);
638 *dst
= nasm_strdup(src
);
642 * Convert a string to a POSIX make-safe form
644 static char *quote_for_pmake(const char *str
)
649 size_t n
= 1; /* Terminating zero */
655 for (p
= str
; *p
; p
++) {
659 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
679 /* Convert N backslashes at the end of filename to 2N backslashes */
683 os
= q
= nasm_malloc(n
);
686 for (p
= str
; *p
; p
++) {
724 * Convert a string to a Watcom make-safe form
726 static char *quote_for_wmake(const char *str
)
732 size_t n
= 1; /* Terminating zero */
737 for (p
= str
; *p
; p
++) {
762 os
= q
= nasm_malloc(n
);
767 for (p
= str
; *p
; p
++) {
806 enum text_options opt
;
810 static const struct textargs textopts
[] = {
811 {"v", OPT_VERSION
, false, 0},
812 {"version", OPT_VERSION
, false, 0},
813 {"help", OPT_HELP
, false, 0},
814 {"abort-on-panic", OPT_ABORT_ON_PANIC
, false, 0},
815 {"prefix", OPT_MANGLE
, true, LM_GPREFIX
},
816 {"postfix", OPT_MANGLE
, true, LM_GSUFFIX
},
817 {"gprefix", OPT_MANGLE
, true, LM_GPREFIX
},
818 {"gpostfix", OPT_MANGLE
, true, LM_GSUFFIX
},
819 {"lprefix", OPT_MANGLE
, true, LM_LPREFIX
},
820 {"lpostfix", OPT_MANGLE
, true, LM_LSUFFIX
},
821 {"include", OPT_INCLUDE
, true, 0},
822 {"pragma", OPT_PRAGMA
, true, 0},
823 {"before", OPT_BEFORE
, true, 0},
824 {"limit-", OPT_LIMIT
, true, 0},
825 {"keep-all", OPT_KEEP_ALL
, false, 0},
826 {NULL
, OPT_BOGUS
, false, 0}
829 static void show_version(void)
831 printf("NASM version %s compiled on %s%s\n",
832 nasm_version
, nasm_date
, nasm_compile_options
);
836 static bool stopoptions
= false;
837 static bool process_arg(char *p
, char *q
, int pass
)
840 bool advance
= false;
845 if (p
[0] == '-' && !stopoptions
) {
846 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
847 /* These parameters take values */
848 if (!(param
= get_param(p
, q
, &advance
)))
858 case 'o': /* output file */
860 copy_filename(&outname
, param
, "output");
863 case 'f': /* output format */
865 ofmt
= ofmt_find(param
, &ofmt_alias
);
867 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
868 "unrecognised output format `%s' - "
869 "use -hf for a list", param
);
874 case 'O': /* Optimization level */
879 /* Naked -O == -Ox */
880 optimizing
.level
= MAX_OPTIMIZE
;
884 case '0': case '1': case '2': case '3': case '4':
885 case '5': case '6': case '7': case '8': case '9':
886 opt
= strtoul(param
, ¶m
, 10);
888 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
889 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
891 optimizing
.level
= opt
- 1;
893 optimizing
.level
= opt
;
899 opt_verbose_info
= true;
904 optimizing
.level
= MAX_OPTIMIZE
;
908 nasm_fatal("unknown optimization option -O%c\n",
913 if (optimizing
.level
> MAX_OPTIMIZE
)
914 optimizing
.level
= MAX_OPTIMIZE
;
919 case 'p': /* pre-include */
922 preproc
->pre_include(param
);
925 case 'd': /* pre-define */
928 preproc
->pre_define(param
);
931 case 'u': /* un-define */
934 preproc
->pre_undefine(param
);
937 case 'i': /* include search path */
940 preproc
->include_path(param
);
943 case 'l': /* listing file */
945 copy_filename(&listname
, param
, "listing");
948 case 'Z': /* error messages file */
950 copy_filename(&errname
, param
, "error");
953 case 'F': /* specify debug format */
955 using_debug_info
= true;
956 debug_format
= param
;
960 case 'X': /* specify error reporting format */
962 if (nasm_stricmp("vc", param
) == 0)
963 nasm_set_verror(nasm_verror_vc
);
964 else if (nasm_stricmp("gnu", param
) == 0)
965 nasm_set_verror(nasm_verror_gnu
);
967 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
968 "unrecognized error reporting format `%s'",
975 using_debug_info
= true;
977 debug_format
= nasm_skip_spaces(p
+ 2);
983 exit(0); /* never need usage message here */
987 printf("\nvalid debug formats for '%s' output format are"
988 " ('*' denotes default):\n", ofmt
->shortname
);
989 dfmt_list(ofmt
, stdout
);
995 tasm_compatible_mode
= true;
1002 case 'e': /* preprocess only */
1005 operating_mode
= OP_PREPROCESS
;
1008 case 'a': /* assemble only - don't preprocess */
1010 preproc
= &preproc_nop
;
1016 if (!set_warning_status(param
)) {
1017 nasm_error(ERR_WARNING
|ERR_NOFILE
|ERR_WARN_UNK_WARNING
,
1018 "unknown warning option: %s", param
);
1027 quote_for_make
= quote_for_wmake
;
1041 operating_mode
= OP_DEPEND
;
1044 operating_mode
= OP_DEPEND
;
1045 depend_missing_ok
= true;
1048 depend_emit_phony
= true;
1051 operating_mode
= OP_NORMAL
;
1064 depend_target
= quote_for_make(q
);
1068 /* handled in pass 1 */
1071 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1072 "unknown dependency option `-M%c'", p
[2]);
1076 if (advance
&& (!q
|| !q
[0])) {
1077 nasm_error(ERR_NONFATAL
|ERR_NOFILE
|ERR_USAGE
,
1078 "option `-M%c' requires a parameter", p
[2]);
1085 const struct textargs
*tx
;
1091 if (!*p
) { /* -- => stop processing options */
1097 for (tx
= textopts
; tx
->label
; tx
++) {
1098 olen
= strlen(tx
->label
);
1103 if (nasm_memicmp(p
, tx
->label
, olen
))
1106 if (tx
->label
[olen
-1] == '-')
1107 break; /* Incomplete option */
1109 if (!p
[olen
] || p
[olen
] == '=')
1110 break; /* Complete option */
1114 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1115 "unrecognized option `--%s'", p
);
1118 eqsave
= param
= strchr(p
+olen
, '=');
1128 /* Note: a null string is a valid parameter */
1130 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1131 "option `--%s' requires an argument",
1137 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1138 "option `--%s' does not take an argument",
1148 case OPT_ABORT_ON_PANIC
:
1149 abort_on_panic
= true;
1153 set_label_mangle(tx
->pvt
, param
);
1157 preproc
->pre_include(q
);
1161 preproc
->pre_command("pragma", param
);
1165 preproc
->pre_command(NULL
, param
);
1169 nasm_set_limit(p
+olen
, param
);
1182 *eqsave
= '='; /* Restore = argument separator */
1188 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1189 "unrecognised option `-%c'", p
[1]);
1192 } else if (pass
== 2) {
1193 /* In theory we could allow multiple input files... */
1194 copy_filename(&inname
, p
, "input");
1200 #define ARG_BUF_DELTA 128
1202 static void process_respfile(FILE * rfile
, int pass
)
1204 char *buffer
, *p
, *q
, *prevarg
;
1205 int bufsize
, prevargsize
;
1207 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1208 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1209 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1212 while (1) { /* Loop to handle all lines in file */
1214 while (1) { /* Loop to handle long lines */
1215 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1219 if (p
> buffer
&& p
[-1] == '\n')
1221 if (p
- buffer
> bufsize
- 10) {
1223 offset
= p
- buffer
;
1224 bufsize
+= ARG_BUF_DELTA
;
1225 buffer
= nasm_realloc(buffer
, bufsize
);
1226 p
= buffer
+ offset
;
1230 if (!q
&& p
== buffer
) {
1232 process_arg(prevarg
, NULL
, pass
);
1239 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1240 * them are present at the end of the line.
1242 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1244 while (p
> buffer
&& nasm_isspace(p
[-1]))
1247 p
= nasm_skip_spaces(buffer
);
1249 if (process_arg(prevarg
, p
, pass
))
1252 if ((int) strlen(p
) > prevargsize
- 10) {
1253 prevargsize
+= ARG_BUF_DELTA
;
1254 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1256 strncpy(prevarg
, p
, prevargsize
);
1260 /* Function to process args from a string of args, rather than the
1261 * argv array. Used by the environment variable and response file
1264 static void process_args(char *args
, int pass
)
1266 char *p
, *q
, *arg
, *prevarg
;
1267 char separator
= ' ';
1270 if (*p
&& *p
!= '-')
1275 while (*p
&& *p
!= separator
)
1277 while (*p
== separator
)
1281 if (process_arg(prevarg
, arg
, pass
))
1285 process_arg(arg
, NULL
, pass
);
1288 static void process_response_file(const char *file
, int pass
)
1291 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1296 while (fgets(str
, sizeof str
, f
)) {
1297 process_args(str
, pass
);
1302 static void parse_cmdline(int argc
, char **argv
, int pass
)
1305 char *envreal
, *envcopy
= NULL
, *p
;
1308 /* Initialize all the warnings to their default state */
1309 for (i
= 0; i
< ERR_WARN_ALL
; i
++) {
1310 warning_state_init
[i
] = warning_state
[i
] =
1311 warnings
[i
].enabled
? WARN_ST_ENABLED
: 0;
1315 * First, process the NASMENV environment variable.
1317 envreal
= getenv("NASMENV");
1319 envcopy
= nasm_strdup(envreal
);
1320 process_args(envcopy
, pass
);
1325 * Now process the actual command line.
1330 if (argv
[0][0] == '@') {
1332 * We have a response file, so process this as a set of
1333 * arguments like the environment variable. This allows us
1334 * to have multiple arguments on a single line, which is
1335 * different to the -@resp file processing below for regular
1338 process_response_file(argv
[0]+1, pass
);
1342 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1343 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1345 rfile
= nasm_open_read(p
, NF_TEXT
);
1347 process_respfile(rfile
, pass
);
1350 nasm_error(ERR_NONFATAL
| ERR_NOFILE
| ERR_USAGE
,
1351 "unable to open response file `%s'", p
);
1354 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1355 argv
+= advance
, argc
-= advance
;
1359 * Look for basic command line typos. This definitely doesn't
1360 * catch all errors, but it might help cases of fumbled fingers.
1366 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
, "no input file specified");
1368 else if ((errname
&& !strcmp(inname
, errname
)) ||
1369 (outname
&& !strcmp(inname
, outname
)) ||
1370 (listname
&& !strcmp(inname
, listname
)) ||
1371 (depend_file
&& !strcmp(inname
, depend_file
)))
1372 nasm_fatal_fl(ERR_USAGE
, "will not overwrite input file");
1375 error_file
= nasm_open_write(errname
, NF_TEXT
);
1377 error_file
= stderr
; /* Revert to default! */
1378 nasm_fatal_fl(ERR_NOFILE
| ERR_USAGE
,
1379 "cannot open file `%s' for error messages",
1385 static void assemble_file(const char *fname
, StrList
*depend_list
)
1390 uint64_t prev_offset_changed
;
1391 int64_t stall_count
= 0; /* Make sure we make forward progress... */
1397 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_386
))
1398 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1401 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_X86_64
))
1402 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1409 prev_offset_changed
= nasm_limit
[LIMIT_PASSES
];
1410 for (passn
= 1; pass0
<= 2; passn
++) {
1411 pass1
= pass0
== 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1412 pass2
= passn
> 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1413 /* pass0 0, 0, 0, ..., 1, 2 */
1415 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1418 lfmt
->init(listname
);
1419 } else if (passn
== 1 && listname
&& !keep_all
) {
1420 /* Remove the list file in case we die before the output pass */
1423 in_absolute
= false;
1424 global_offset_changed
= 0; /* set by redefine_label */
1426 saa_rewind(forwrefs
);
1427 forwref
= saa_rstruct(forwrefs
);
1429 offsets
= raa_init();
1431 location
.segment
= NO_SEG
;
1432 location
.offset
= 0;
1434 location
.known
= true;
1436 switch_segment(ofmt
->section(NULL
, pass2
, &globalbits
));
1437 preproc
->reset(fname
, pass1
, pass1
== 2 ? depend_list
: NULL
);
1439 /* Revert all warnings to the default state */
1440 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
1444 while ((line
= preproc
->getline())) {
1445 if (++globallineno
> nasm_limit
[LIMIT_LINES
])
1446 nasm_fatal("overall line count exceeds the maximum %"PRId64
"\n",
1447 nasm_limit
[LIMIT_LINES
]);
1450 * Here we parse our directives; this is not handled by the
1453 if (process_directives(line
))
1454 goto end_of_line
; /* Just do final cleanup */
1456 /* Not a directive, or even something that starts with [ */
1457 parse_line(pass1
, line
, &output_ins
);
1459 if (optimizing
.level
> 0) {
1460 if (forwref
!= NULL
&& globallineno
== forwref
->lineno
) {
1461 output_ins
.forw_ref
= true;
1463 output_ins
.oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1464 forwref
= saa_rstruct(forwrefs
);
1465 } while (forwref
!= NULL
1466 && forwref
->lineno
== globallineno
);
1468 output_ins
.forw_ref
= false;
1470 if (output_ins
.forw_ref
) {
1472 for (i
= 0; i
< output_ins
.operands
; i
++) {
1473 if (output_ins
.oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1474 struct forwrefinfo
*fwinf
= (struct forwrefinfo
*)saa_wstruct(forwrefs
);
1475 fwinf
->lineno
= globallineno
;
1484 if (output_ins
.opcode
== I_EQU
) {
1485 if (!output_ins
.label
) {
1486 nasm_error(ERR_NONFATAL
, "EQU not preceded by label");
1487 } else if (output_ins
.operands
== 1 &&
1488 (output_ins
.oprs
[0].type
& IMMEDIATE
) &&
1489 output_ins
.oprs
[0].wrt
== NO_SEG
) {
1490 define_label(output_ins
.label
,
1491 output_ins
.oprs
[0].segment
,
1492 output_ins
.oprs
[0].offset
, false);
1493 } else if (output_ins
.operands
== 2
1494 && (output_ins
.oprs
[0].type
& IMMEDIATE
)
1495 && (output_ins
.oprs
[0].type
& COLON
)
1496 && output_ins
.oprs
[0].segment
== NO_SEG
1497 && output_ins
.oprs
[0].wrt
== NO_SEG
1498 && (output_ins
.oprs
[1].type
& IMMEDIATE
)
1499 && output_ins
.oprs
[1].segment
== NO_SEG
1500 && output_ins
.oprs
[1].wrt
== NO_SEG
) {
1501 define_label(output_ins
.label
,
1502 output_ins
.oprs
[0].offset
| SEG_ABS
,
1503 output_ins
.oprs
[1].offset
, false);
1505 nasm_error(ERR_NONFATAL
, "bad syntax for EQU");
1507 } else { /* instruction isn't an EQU */
1510 nasm_assert(output_ins
.times
>= 0);
1512 for (n
= 1; n
<= output_ins
.times
; n
++) {
1514 int64_t l
= insn_size(location
.segment
,
1516 globalbits
, &output_ins
);
1518 /* if (using_debug_info) && output_ins.opcode != -1) */
1519 if (using_debug_info
)
1520 { /* fbk 03/25/01 */
1521 /* this is done here so we can do debug type info */
1523 TYS_ELEMENTS(output_ins
.operands
);
1524 switch (output_ins
.opcode
) {
1527 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_BYTE
;
1531 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_WORD
;
1535 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_DWORD
;
1539 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_QWORD
;
1543 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_TBYTE
;
1547 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_OWORD
;
1551 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_YWORD
;
1555 TYS_ELEMENTS(output_ins
.oprs
[0].offset
) | TY_ZWORD
;
1558 typeinfo
|= TY_BYTE
;
1561 typeinfo
|= TY_WORD
;
1564 if (output_ins
.eops_float
)
1565 typeinfo
|= TY_FLOAT
;
1567 typeinfo
|= TY_DWORD
;
1570 typeinfo
|= TY_QWORD
;
1573 typeinfo
|= TY_TBYTE
;
1576 typeinfo
|= TY_OWORD
;
1579 typeinfo
|= TY_YWORD
;
1582 typeinfo
|= TY_ZWORD
;
1585 typeinfo
= TY_LABEL
;
1589 dfmt
->debug_typevalue(typeinfo
);
1593 * For INCBIN, let the code in assemble
1594 * handle TIMES, so we don't have to read the
1595 * input file over and over.
1598 increment_offset(l
);
1601 * else l == -1 => invalid instruction, which will be
1602 * flagged as an error on pass 2
1606 lfmt
->uplevel(LIST_TIMES
);
1607 increment_offset(assemble(location
.segment
,
1609 globalbits
, &output_ins
));
1613 if (output_ins
.times
> 1)
1614 lfmt
->downlevel(LIST_TIMES
);
1616 cleanup_insn(&output_ins
);
1620 } /* end while (line = preproc->getline... */
1622 if (global_offset_changed
&& !terminate_after_phase
) {
1625 nasm_error(ERR_WARNING
|ERR_WARN_PHASE
,
1626 "phase error during stabilization pass, hoping for the best");
1630 nasm_error(ERR_NONFATAL
,
1631 "phase error during code generation pass");
1635 /* This is normal, we'll keep going... */
1641 preproc
->cleanup(1);
1644 * Always run at least two optimization passes (pass0 == 0);
1645 * things like subsections will fail miserably without that.
1646 * Once we commit to a stabilization pass (pass0 == 1), we can't
1647 * go back, and if something goes bad, we can only hope
1648 * that we don't end up with a phase error at the end.
1650 if ((passn
> 1 && !global_offset_changed
) || pass0
> 0) {
1652 } else if (global_offset_changed
&&
1653 global_offset_changed
< prev_offset_changed
) {
1654 prev_offset_changed
= global_offset_changed
;
1660 if (terminate_after_phase
)
1663 if ((stall_count
> nasm_limit
[LIMIT_STALLED
]) ||
1664 (passn
>= nasm_limit
[LIMIT_PASSES
])) {
1665 /* We get here if the labels don't converge
1666 * Example: FOO equ FOO + 1
1668 nasm_error(ERR_NONFATAL
,
1669 "Can't find valid values for all labels "
1670 "after %"PRId64
" passes, giving up.", passn
);
1671 nasm_error(ERR_NONFATAL
,
1672 "Possible causes: recursive EQUs, macro abuse.");
1677 preproc
->cleanup(0);
1679 if (!terminate_after_phase
&& opt_verbose_info
) {
1680 /* -On and -Ov switches */
1681 fprintf(stdout
, "info: assembly required 1+%"PRId64
"+1 passes\n",
1687 * gnu style error reporting
1688 * This function prints an error message to error_file in the
1689 * style used by GNU. An example would be:
1690 * file.asm:50: error: blah blah blah
1691 * where file.asm is the name of the file, 50 is the line number on
1692 * which the error occurs (or is detected) and "error:" is one of
1693 * the possible optional diagnostics -- it can be "error" or "warning"
1694 * or something else. Finally the line terminates with the actual
1697 * @param severity the severity of the warning or error
1698 * @param fmt the printf style format string
1700 static void nasm_verror_gnu(int severity
, const char *fmt
, va_list ap
)
1702 const char *currentfile
= NULL
;
1705 if (is_suppressed_warning(severity
))
1708 if (!(severity
& ERR_NOFILE
)) {
1709 src_get(&lineno
, ¤tfile
);
1710 if (!currentfile
|| (severity
& ERR_TOPFILE
)) {
1711 currentfile
= inname
[0] ? inname
: outname
[0] ? outname
: NULL
;
1716 if (!skip_this_pass(severity
)) {
1718 fprintf(error_file
, "%s:", currentfile
? currentfile
: "nasm");
1720 fprintf(error_file
, "%s:%"PRId32
": ", currentfile
, lineno
);
1723 nasm_verror_common(severity
, fmt
, ap
);
1727 * MS style error reporting
1728 * This function prints an error message to error_file in the
1729 * style used by Visual C and some other Microsoft tools. An example
1731 * file.asm(50) : error: blah blah blah
1732 * where file.asm is the name of the file, 50 is the line number on
1733 * which the error occurs (or is detected) and "error:" is one of
1734 * the possible optional diagnostics -- it can be "error" or "warning"
1735 * or something else. Finally the line terminates with the actual
1738 * @param severity the severity of the warning or error
1739 * @param fmt the printf style format string
1741 static void nasm_verror_vc(int severity
, const char *fmt
, va_list ap
)
1743 const char *currentfile
= NULL
;
1746 if (is_suppressed_warning(severity
))
1749 if (!(severity
& ERR_NOFILE
))
1750 src_get(&lineno
, ¤tfile
);
1752 if (!skip_this_pass(severity
)) {
1754 fprintf(error_file
, "%s(%"PRId32
") : ", currentfile
, lineno
);
1756 fputs("nasm: ", error_file
);
1760 nasm_verror_common(severity
, fmt
, ap
);
1764 * check to see if this is a suppressable warning
1766 static inline bool is_valid_warning(int severity
)
1768 /* Not a warning at all */
1769 if ((severity
& ERR_MASK
) != ERR_WARNING
)
1772 return WARN_IDX(severity
) < ERR_WARN_ALL
;
1776 * check for suppressed warning
1777 * checks for suppressed warning or pass one only warning and we're
1780 * @param severity the severity of the warning or error
1781 * @return true if we should abort error/warning printing
1783 static bool is_suppressed_warning(int severity
)
1785 /* Might be a warning but suppresed explicitly */
1786 if (is_valid_warning(severity
) && !(severity
& ERR_USAGE
))
1787 return !(warning_state
[WARN_IDX(severity
)] & WARN_ST_ENABLED
);
1792 static bool warning_is_error(int severity
)
1794 if (is_valid_warning(severity
))
1795 return !!(warning_state
[WARN_IDX(severity
)] & WARN_ST_ERROR
);
1800 static bool skip_this_pass(int severity
)
1803 * See if it's a pass-specific error or warning which should be skipped.
1804 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1805 * they cannot be resumed from.
1807 if ((severity
& ERR_MASK
) > ERR_NONFATAL
)
1811 * passn is 1 on the very first pass only.
1812 * pass0 is 2 on the code-generation (final) pass only.
1813 * These are the passes we care about in this case.
1815 return (((severity
& ERR_PASS1
) && passn
!= 1) ||
1816 ((severity
& ERR_PASS2
) && pass0
!= 2));
1820 * common error reporting
1821 * This is the common back end of the error reporting schemes currently
1822 * implemented. It prints the nature of the warning and then the
1823 * specific error message to error_file and may or may not return. It
1824 * doesn't return if the error severity is a "panic" or "debug" type.
1826 * @param severity the severity of the warning or error
1827 * @param fmt the printf style format string
1829 static void nasm_verror_common(int severity
, const char *fmt
, va_list args
)
1834 switch (severity
& (ERR_MASK
|ERR_NO_SEVERITY
)) {
1855 vsnprintf(msg
, sizeof msg
- 64, fmt
, args
);
1856 if (is_valid_warning(severity
) && WARN_IDX(severity
) != ERR_WARN_OTHER
) {
1857 char *p
= strchr(msg
, '\0');
1858 snprintf(p
, 64, " [-w+%s]", warnings
[WARN_IDX(severity
)].name
);
1861 if (!skip_this_pass(severity
))
1862 fprintf(error_file
, "%s%s\n", pfx
, msg
);
1864 /* Are we recursing from error_list_macros? */
1865 if (severity
& ERR_PP_LISTMACRO
)
1869 * Don't suppress this with skip_this_pass(), or we don't get
1870 * pass1 or preprocessor warnings in the list file
1872 lfmt
->error(severity
, pfx
, msg
);
1874 if (skip_this_pass(severity
))
1877 if (severity
& ERR_USAGE
)
1880 preproc
->error_list_macros(severity
);
1882 switch (severity
& ERR_MASK
) {
1884 /* no further action, by definition */
1887 /* Treat warnings as errors */
1888 if (warning_is_error(severity
))
1889 terminate_after_phase
= true;
1892 terminate_after_phase
= true;
1903 exit(1); /* instantly die */
1904 break; /* placate silly compilers */
1909 abort(); /* halt, catch fire, dump core/stop debugger */
1922 static void usage(void)
1924 fputs("type `nasm -h' for help\n", error_file
);
1927 static void help(const char xopt
)
1932 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1934 " [options...] [--] filename\n"
1935 " or nasm -v (or --v) for version info\n\n"
1937 "Response files should contain command line parameters,\n"
1940 " -t assemble in SciTech TASM compatible mode\n");
1942 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1943 " -a don't preprocess (assemble only)\n"
1944 " -M generate Makefile dependencies on stdout\n"
1945 " -MG d:o, missing files assumed generated\n"
1946 " -MF file set Makefile dependency file\n"
1947 " -MD file assemble and generate dependencies\n"
1948 " -MT file dependency target name\n"
1949 " -MQ file dependency target name (quoted)\n"
1950 " -MP emit phony target\n\n"
1951 " -Zfile redirect error messages to file\n"
1952 " -s redirect error messages to stdout\n\n"
1953 " -g generate debugging information\n\n"
1954 " -F format select a debugging format\n\n"
1955 " -gformat same as -g -F format\n\n"
1956 " -o outfile write output to an outfile\n\n"
1957 " -f format select an output format\n\n"
1958 " -l listfile write listing to a listfile\n\n"
1959 " -Ipath add a pathname to the include file path\n");
1961 (" -Olevel optimize opcodes, immediates and branch offsets\n"
1962 " -O0 no optimization\n"
1963 " -O1 minimal optimization\n"
1964 " -Ox multipass optimization (default)\n"
1965 " -Pfile pre-include a file (also --include)\n"
1966 " -Dmacro[=str] pre-define a macro\n"
1967 " -Umacro undefine a macro\n"
1968 " -Xformat specifiy error reporting format (gnu or vc)\n"
1969 " -w+foo enable warning foo (equiv. -Wfoo)\n"
1970 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
1971 " -w[+-]error[=foo]\n"
1972 " promote [specific] warnings to errors\n"
1973 " -h show invocation summary and exit (also --help)\n\n"
1974 " --pragma str pre-executes a specific %%pragma\n"
1975 " --before str add line (usually a preprocessor statement) before the input\n"
1976 " --prefix str prepend the given string to all the given string\n"
1977 " to all extern, common and global symbols (also --gprefix)\n"
1978 " --postfix str append the given string to all the given string\n"
1979 " to all extern, common and global symbols (also --gpostfix)\n"
1980 " --lprefix str prepend the given string to all other symbols\n"
1981 " --lpostfix str append the given string to all other symbols\n"
1982 " --keep-all output files will not be removed even if an error happens\n"
1983 " --limit-X val set execution limit X\n");
1985 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
1986 printf(" %-15s %s (default ",
1987 limit_info
[i
].name
, limit_info
[i
].help
);
1988 if (nasm_limit
[i
] < LIMIT_MAX_VAL
) {
1989 printf("%"PRId64
")\n", nasm_limit
[i
]);
1991 printf("unlimited)\n");
1995 printf("\nWarnings for the -W/-w options:\n");
1997 for (i
= 0; i
<= ERR_WARN_ALL
; i
++)
1998 printf(" %-23s %s%s\n",
1999 warnings
[i
].name
, warnings
[i
].help
,
2000 i
== ERR_WARN_ALL
? "\n" :
2001 warnings
[i
].enabled
? " (default on)" :
2005 printf("valid output formats for -f are"
2006 " (`*' denotes default):\n");
2007 ofmt_list(ofmt
, stdout
);
2009 printf("For a list of valid output formats, use -hf.\n");
2010 printf("For a list of debug formats, use -f <format> -y.\n");