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
65 * This is the maximum number of optimization passes to do. If we ever
66 * find a case where the optimizer doesn't naturally converge, we might
67 * have to drop this value so the assembler doesn't appear to just hang.
69 #define MAX_OPTIMIZE (INT_MAX >> 1)
71 struct forwrefinfo
{ /* info held on forward refs. */
76 static void parse_cmdline(int, char **, int);
77 static void assemble_file(const char *, struct strlist
*);
78 static bool skip_this_pass(errflags severity
);
79 static void nasm_verror_asm(errflags severity
, const char *fmt
, va_list args
);
80 static void usage(void);
81 static void help(char xopt
);
84 const char *beforeline
; /* Before line number, if present */
85 const char *afterline
; /* After line number, if present */
86 const char *beforemsg
; /* Before actual message */
89 static const struct error_format errfmt_gnu
= { ":", "", ": " };
90 static const struct error_format errfmt_msvc
= { "(", ")", " : " };
91 static const struct error_format
*errfmt
= &errfmt_gnu
;
92 static struct strlist
*warn_list
;
94 static bool using_debug_info
, opt_verbose_info
;
95 static const char *debug_format
;
97 #ifndef ABORT_ON_PANIC
98 # define ABORT_ON_PANIC 0
100 static bool abort_on_panic
= ABORT_ON_PANIC
;
101 static bool keep_all
;
103 bool tasm_compatible_mode
= false;
104 enum pass_type _pass_type
;
105 const char * const _pass_types
[] =
107 "init", "first", "optimize", "stabilize", "final"
113 struct compile_time official_compile_time
;
117 static const char *listname
;
118 static const char *errname
;
120 static int64_t globallineno
; /* for forward-reference tracking */
122 const struct ofmt
*ofmt
= &OF_DEFAULT
;
123 const struct ofmt_alias
*ofmt_alias
= NULL
;
124 const struct dfmt
*dfmt
;
126 FILE *error_file
; /* Where to write error messages */
129 struct optimization optimizing
=
130 { MAX_OPTIMIZE
, OPTIM_ALL_ENABLED
}; /* number of optimization passes to take */
131 static int cmd_sb
= 16; /* by default */
134 static iflag_t cmd_cpu
;
136 struct location location
;
137 bool in_absolute
; /* Flag we are in ABSOLUTE seg */
138 struct location absolute
; /* Segment/offset inside ABSOLUTE */
140 static struct RAA
*offsets
;
142 static struct SAA
*forwrefs
; /* keep track of forward references */
143 static const struct forwrefinfo
*forwref
;
145 static const struct preproc_ops
*preproc
;
146 static struct strlist
*include_path
;
147 bool pp_noline
; /* Ignore %line directives */
149 #define OP_NORMAL (1U << 0)
150 #define OP_PREPROCESS (1U << 1)
151 #define OP_DEPEND (1U << 2)
153 static unsigned int operating_mode
;
155 /* Dependency flags */
156 static bool depend_emit_phony
= false;
157 static bool depend_missing_ok
= false;
158 static const char *depend_target
= NULL
;
159 static const char *depend_file
= NULL
;
160 struct strlist
*depend_list
;
162 static bool want_usage
;
163 static bool terminate_after_phase
;
164 bool user_nolist
= false;
166 static char *quote_for_pmake(const char *str
);
167 static char *quote_for_wmake(const char *str
);
168 static char *(*quote_for_make
)(const char *) = quote_for_pmake
;
171 * Execution limits that can be set via a command-line option or %pragma
174 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
176 int64_t nasm_limit
[LIMIT_MAX
+1] =
177 { LIMIT_MAX_VAL
, 1000, 1000000, 1000000, 1000000, 2000000000 };
183 static const struct limit_info limit_info
[LIMIT_MAX
+1] = {
184 { "passes", "total number of passes" },
185 { "stalled-passes", "number of passes without forward progress" },
186 { "macro-levels", "levels of macro expansion"},
187 { "rep", "%rep count" },
188 { "eval", "expression evaluation descent"},
189 { "lines", "total source lines processed"}
192 enum directive_result
193 nasm_set_limit(const char *limit
, const char *valstr
)
200 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
201 if (!nasm_stricmp(limit
, limit_info
[i
].name
))
206 errlevel
= ERR_WARNING
|WARN_OTHER
|ERR_USAGE
;
208 errlevel
= ERR_WARNING
|WARN_UNKNOWN_PRAGMA
;
209 nasm_error(errlevel
, "unknown limit: `%s'", limit
);
213 if (!nasm_stricmp(valstr
, "unlimited")) {
216 val
= readnum(valstr
, &rn_error
);
217 if (rn_error
|| val
< 0) {
219 errlevel
= ERR_WARNING
|WARN_OTHER
|ERR_USAGE
;
221 errlevel
= ERR_WARNING
|WARN_BAD_PRAGMA
;
222 nasm_error(errlevel
, "invalid limit value: `%s'", limit
);
225 if (val
> LIMIT_MAX_VAL
)
233 int64_t switch_segment(int32_t segment
)
235 location
.segment
= segment
;
236 if (segment
== NO_SEG
) {
237 location
.offset
= absolute
.offset
;
240 location
.offset
= raa_read(offsets
, segment
);
243 return location
.offset
;
246 static void set_curr_offs(int64_t l_off
)
249 absolute
.offset
= l_off
;
251 offsets
= raa_write(offsets
, location
.segment
, l_off
);
254 static void increment_offset(int64_t delta
)
256 if (unlikely(delta
== 0))
259 location
.offset
+= delta
;
260 set_curr_offs(location
.offset
);
263 static void nasm_fputs(const char *line
, FILE * outfile
)
266 fputs(line
, outfile
);
273 * Define system-defined macros that are not part of
274 * macros/standard.mac.
276 static void define_macros(void)
278 const struct compile_time
* const oct
= &official_compile_time
;
281 if (oct
->have_local
) {
282 strftime(temp
, sizeof temp
, "__DATE__=\"%Y-%m-%d\"", &oct
->local
);
283 preproc
->pre_define(temp
);
284 strftime(temp
, sizeof temp
, "__DATE_NUM__=%Y%m%d", &oct
->local
);
285 preproc
->pre_define(temp
);
286 strftime(temp
, sizeof temp
, "__TIME__=\"%H:%M:%S\"", &oct
->local
);
287 preproc
->pre_define(temp
);
288 strftime(temp
, sizeof temp
, "__TIME_NUM__=%H%M%S", &oct
->local
);
289 preproc
->pre_define(temp
);
293 strftime(temp
, sizeof temp
, "__UTC_DATE__=\"%Y-%m-%d\"", &oct
->gm
);
294 preproc
->pre_define(temp
);
295 strftime(temp
, sizeof temp
, "__UTC_DATE_NUM__=%Y%m%d", &oct
->gm
);
296 preproc
->pre_define(temp
);
297 strftime(temp
, sizeof temp
, "__UTC_TIME__=\"%H:%M:%S\"", &oct
->gm
);
298 preproc
->pre_define(temp
);
299 strftime(temp
, sizeof temp
, "__UTC_TIME_NUM__=%H%M%S", &oct
->gm
);
300 preproc
->pre_define(temp
);
303 if (oct
->have_posix
) {
304 snprintf(temp
, sizeof temp
, "__POSIX_TIME__=%"PRId64
, oct
->posix
);
305 preproc
->pre_define(temp
);
309 * In case if output format is defined by alias
310 * we have to put shortname of the alias itself here
311 * otherwise ABI backward compatibility gets broken.
313 snprintf(temp
, sizeof(temp
), "__OUTPUT_FORMAT__=%s",
314 ofmt_alias
? ofmt_alias
->shortname
: ofmt
->shortname
);
315 preproc
->pre_define(temp
);
318 * Output-format specific macros.
321 preproc
->extra_stdmac(ofmt
->stdmac
);
324 * Debug format, if any
326 if (dfmt
!= &null_debug_form
) {
327 snprintf(temp
, sizeof(temp
), "__DEBUG_FORMAT__=%s", dfmt
->shortname
);
328 preproc
->pre_define(temp
);
333 * Initialize the preprocessor, set up the include path, and define
334 * the system-included macros. This is called between passes 1 and 2
335 * of parsing the command options; ofmt and dfmt are defined at this
338 * Command-line specified preprocessor directives (-p, -d, -u,
339 * --pragma, --before) are processed after this function.
341 static void preproc_init(struct strlist
*ipath
)
345 preproc
->include_path(ipath
);
348 static void emit_dependencies(struct strlist
*list
)
352 bool wmake
= (quote_for_make
== quote_for_wmake
);
353 const char *wrapstr
, *nulltarget
;
354 const struct strlist_entry
*l
;
359 wrapstr
= wmake
? " &\n " : " \\\n ";
360 nulltarget
= wmake
? "\t%null\n" : "";
362 if (depend_file
&& strcmp(depend_file
, "-")) {
363 deps
= nasm_open_write(depend_file
, NF_TEXT
);
365 nasm_nonfatal("unable to write dependency file `%s'", depend_file
);
372 linepos
= fprintf(deps
, "%s :", depend_target
);
373 strlist_for_each(l
, list
) {
374 char *file
= quote_for_make(l
->str
);
376 if (linepos
+ len
> 62 && linepos
> 1) {
377 fputs(wrapstr
, deps
);
380 fprintf(deps
, " %s", file
);
384 fprintf(deps
, "\n\n");
386 strlist_for_each(l
, list
) {
387 if (depend_emit_phony
) {
388 char *file
= quote_for_make(l
->str
);
389 fprintf(deps
, "%s :\n%s\n", file
, nulltarget
);
400 /* Convert a struct tm to a POSIX-style time constant */
401 static int64_t make_posix_time(const struct tm
*tm
)
404 int64_t y
= tm
->tm_year
;
406 /* See IEEE 1003.1:2004, section 4.14 */
408 t
= (y
-70)*365 + (y
-69)/4 - (y
-1)/100 + (y
+299)/400;
420 static void timestamp(void)
422 struct compile_time
* const oct
= &official_compile_time
;
423 const struct tm
*tp
, *best_gm
;
429 tp
= localtime(&oct
->t
);
432 best_gm
= &oct
->local
;
433 oct
->have_local
= true;
436 tp
= gmtime(&oct
->t
);
441 if (!oct
->have_local
)
442 oct
->local
= oct
->gm
;
444 oct
->gm
= oct
->local
;
448 oct
->posix
= make_posix_time(best_gm
);
449 oct
->have_posix
= true;
453 int main(int argc
, char **argv
)
459 iflag_set_default_cpu(&cpu
);
460 iflag_set_default_cpu(&cmd_cpu
);
462 include_path
= strlist_alloc(true);
464 _pass_type
= PASS_INIT
;
467 want_usage
= terminate_after_phase
= false;
468 nasm_set_verror(nasm_verror_asm
);
474 * We must call init_labels() before the command line parsing,
475 * because we may be setting prefixes/suffixes from the command
480 offsets
= raa_init();
481 forwrefs
= saa_init((int32_t)sizeof(struct forwrefinfo
));
484 operating_mode
= OP_NORMAL
;
486 parse_cmdline(argc
, argv
, 1);
487 if (terminate_after_phase
) {
493 /* At this point we have ofmt and the name of the desired debug format */
494 if (!using_debug_info
) {
495 /* No debug info, redirect to the null backend (empty stubs) */
496 dfmt
= &null_debug_form
;
497 } else if (!debug_format
) {
498 /* Default debug format for this backend */
499 dfmt
= ofmt
->default_dfmt
;
501 dfmt
= dfmt_find(ofmt
, debug_format
);
503 nasm_fatalf(ERR_USAGE
, "unrecognized debug format `%s' for output format `%s'",
504 debug_format
, ofmt
->shortname
);
508 preproc_init(include_path
);
510 parse_cmdline(argc
, argv
, 2);
511 if (terminate_after_phase
) {
517 /* Save away the default state of warnings */
518 memcpy(warning_state_init
, warning_state
, sizeof warning_state_init
);
520 /* Dependency filename if we are also doing other things */
521 if (!depend_file
&& (operating_mode
& ~OP_DEPEND
)) {
523 depend_file
= nasm_strcat(outname
, ".d");
525 depend_file
= filename_set_extension(inname
, ".d");
529 * If no output file name provided and this
530 * is preprocess mode, we're perfectly
531 * fine to output into stdout.
533 if (!outname
&& !(operating_mode
& OP_PREPROCESS
)) {
534 outname
= filename_set_extension(inname
, ofmt
->extension
);
535 if (!strcmp(outname
, inname
)) {
536 outname
= "nasm.out";
537 nasm_warn(WARN_OTHER
, "default output file same as input, using `%s' for output\n", outname
);
541 depend_list
= (operating_mode
& OP_DEPEND
) ? strlist_alloc(true) : NULL
;
544 depend_target
= quote_for_make(outname
);
546 if (!(operating_mode
& (OP_PREPROCESS
|OP_NORMAL
))) {
549 if (depend_missing_ok
)
550 preproc
->include_path(NULL
); /* "assume generated" */
552 preproc
->reset(inname
, PP_DEPS
, depend_list
);
554 while ((line
= preproc
->getline()))
556 preproc
->cleanup_pass();
557 } else if (operating_mode
& OP_PREPROCESS
) {
559 const char *file_name
= NULL
;
560 int32_t prior_linnum
= 0;
564 ofile
= nasm_open_write(outname
, NF_TEXT
);
566 nasm_fatal("unable to open output file `%s'", outname
);
570 location
.known
= false;
572 _pass_type
= PASS_FIRST
; /* We emulate this assembly pass */
573 preproc
->reset(inname
, PP_PREPROC
, depend_list
);
575 /* Revert all warnings to the default state */
576 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
578 while ((line
= preproc
->getline())) {
580 * We generate %line directives if needed for later programs
582 int32_t linnum
= prior_linnum
+= lineinc
;
583 int altline
= src_get(&linnum
, &file_name
);
585 if (altline
== 1 && lineinc
== 1)
586 nasm_fputs("", ofile
);
588 lineinc
= (altline
!= -1 || lineinc
!= 1);
589 fprintf(ofile
? ofile
: stdout
,
590 "%%line %"PRId32
"+%d %s\n", linnum
, lineinc
,
593 prior_linnum
= linnum
;
595 nasm_fputs(line
, ofile
);
598 preproc
->cleanup_pass();
601 if (ofile
&& terminate_after_phase
&& !keep_all
)
606 if (operating_mode
& OP_NORMAL
) {
607 ofile
= nasm_open_write(outname
, (ofmt
->flags
& OFMT_TEXT
) ? NF_TEXT
: NF_BINARY
);
609 nasm_fatal("unable to open output file `%s'", outname
);
614 assemble_file(inname
, depend_list
);
616 if (!terminate_after_phase
) {
621 nasm_nonfatal("write error on output file `%s'", outname
);
626 if (terminate_after_phase
&& !keep_all
)
632 preproc
->cleanup_session();
634 if (depend_list
&& !terminate_after_phase
)
635 emit_dependencies(depend_list
);
645 strlist_free(&include_path
);
647 return terminate_after_phase
;
651 * Get a parameter for a command line option.
652 * First arg must be in the form of e.g. -f...
654 static char *get_param(char *p
, char *q
, bool *advance
)
657 if (p
[2]) /* the parameter's in the option */
658 return nasm_skip_spaces(p
+ 2);
663 nasm_nonfatalf(ERR_USAGE
, "option `-%c' requires an argument", p
[1]);
670 static void copy_filename(const char **dst
, const char *src
, const char *what
)
673 nasm_fatal("more than one %s file specified: %s\n", what
, src
);
675 *dst
= nasm_strdup(src
);
679 * Convert a string to a POSIX make-safe form
681 static char *quote_for_pmake(const char *str
)
686 size_t n
= 1; /* Terminating zero */
692 for (p
= str
; *p
; p
++) {
696 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
716 /* Convert N backslashes at the end of filename to 2N backslashes */
720 os
= q
= nasm_malloc(n
);
723 for (p
= str
; *p
; p
++) {
761 * Convert a string to a Watcom make-safe form
763 static char *quote_for_wmake(const char *str
)
769 size_t n
= 1; /* Terminating zero */
774 for (p
= str
; *p
; p
++) {
799 os
= q
= nasm_malloc(n
);
804 for (p
= str
; *p
; p
++) {
844 enum text_options opt
;
848 static const struct textargs textopts
[] = {
849 {"v", OPT_VERSION
, false, 0},
850 {"version", OPT_VERSION
, false, 0},
851 {"help", OPT_HELP
, false, 0},
852 {"abort-on-panic", OPT_ABORT_ON_PANIC
, false, 0},
853 {"prefix", OPT_MANGLE
, true, LM_GPREFIX
},
854 {"postfix", OPT_MANGLE
, true, LM_GSUFFIX
},
855 {"gprefix", OPT_MANGLE
, true, LM_GPREFIX
},
856 {"gpostfix", OPT_MANGLE
, true, LM_GSUFFIX
},
857 {"lprefix", OPT_MANGLE
, true, LM_LPREFIX
},
858 {"lpostfix", OPT_MANGLE
, true, LM_LSUFFIX
},
859 {"include", OPT_INCLUDE
, true, 0},
860 {"pragma", OPT_PRAGMA
, true, 0},
861 {"before", OPT_BEFORE
, true, 0},
862 {"limit-", OPT_LIMIT
, true, 0},
863 {"keep-all", OPT_KEEP_ALL
, false, 0},
864 {"no-line", OPT_NO_LINE
, false, 0},
865 {NULL
, OPT_BOGUS
, false, 0}
868 static void show_version(void)
870 printf("NASM version %s compiled on %s%s\n",
871 nasm_version
, nasm_date
, nasm_compile_options
);
875 static bool stopoptions
= false;
876 static bool process_arg(char *p
, char *q
, int pass
)
879 bool advance
= false;
884 if (p
[0] == '-' && !stopoptions
) {
885 if (strchr("oOfpPdDiIlFXuUZwW", p
[1])) {
886 /* These parameters take values */
887 if (!(param
= get_param(p
, q
, &advance
)))
897 case 'o': /* output file */
899 copy_filename(&outname
, param
, "output");
902 case 'f': /* output format */
904 ofmt
= ofmt_find(param
, &ofmt_alias
);
906 nasm_fatalf(ERR_USAGE
, "unrecognised output format `%s' - use -hf for a list", param
);
911 case 'O': /* Optimization level */
916 /* Naked -O == -Ox */
917 optimizing
.level
= MAX_OPTIMIZE
;
921 case '0': case '1': case '2': case '3': case '4':
922 case '5': case '6': case '7': case '8': case '9':
923 opt
= strtoul(param
, ¶m
, 10);
925 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
926 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
928 optimizing
.level
= opt
- 1;
930 optimizing
.level
= opt
;
936 opt_verbose_info
= true;
941 optimizing
.level
= MAX_OPTIMIZE
;
945 nasm_fatal("unknown optimization option -O%c\n",
950 if (optimizing
.level
> MAX_OPTIMIZE
)
951 optimizing
.level
= MAX_OPTIMIZE
;
956 case 'p': /* pre-include */
959 preproc
->pre_include(param
);
962 case 'd': /* pre-define */
965 preproc
->pre_define(param
);
968 case 'u': /* un-define */
971 preproc
->pre_undefine(param
);
974 case 'i': /* include search path */
977 strlist_add(include_path
, param
);
980 case 'l': /* listing file */
982 copy_filename(&listname
, param
, "listing");
985 case 'Z': /* error messages file */
987 copy_filename(&errname
, param
, "error");
990 case 'F': /* specify debug format */
992 using_debug_info
= true;
993 debug_format
= param
;
997 case 'X': /* specify error reporting format */
999 if (!nasm_stricmp("vc", param
) || !nasm_stricmp("msvc", param
) || !nasm_stricmp("ms", param
))
1000 errfmt
= &errfmt_msvc
;
1001 else if (!nasm_stricmp("gnu", param
) || !nasm_stricmp("gcc", param
))
1002 errfmt
= &errfmt_gnu
;
1004 nasm_fatalf(ERR_USAGE
, "unrecognized error reporting format `%s'", param
);
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 set_warning_status(param
);
1060 quote_for_make
= quote_for_wmake
;
1074 operating_mode
= OP_DEPEND
;
1077 operating_mode
= OP_DEPEND
;
1078 depend_missing_ok
= true;
1081 depend_emit_phony
= true;
1084 operating_mode
|= OP_DEPEND
;
1085 if (q
&& (q
[0] != '-' || q
[1] == '\0')) {
1099 depend_target
= quote_for_make(q
);
1103 /* handled in pass 1 */
1106 nasm_nonfatalf(ERR_USAGE
, "unknown dependency option `-M%c'", p
[2]);
1110 if (advance
&& (!q
|| !q
[0])) {
1111 nasm_nonfatalf(ERR_USAGE
, "option `-M%c' requires a parameter", p
[2]);
1118 const struct textargs
*tx
;
1124 if (!*p
) { /* -- => stop processing options */
1129 olen
= 0; /* Placate gcc at lower optimization levels */
1131 for (tx
= textopts
; tx
->label
; tx
++) {
1132 olen
= strlen(tx
->label
);
1137 if (nasm_memicmp(p
, tx
->label
, olen
))
1140 if (tx
->label
[olen
-1] == '-')
1141 break; /* Incomplete option */
1143 if (!p
[olen
] || p
[olen
] == '=')
1144 break; /* Complete option */
1148 nasm_nonfatalf(ERR_USAGE
, "unrecognized option `--%s'", p
);
1151 eqsave
= param
= strchr(p
+olen
, '=');
1161 /* Note: a null string is a valid parameter */
1163 nasm_nonfatalf(ERR_USAGE
, "option `--%s' requires an argument", p
);
1168 nasm_nonfatalf(ERR_USAGE
, "option `--%s' does not take an argument", p
);
1176 case OPT_ABORT_ON_PANIC
:
1177 abort_on_panic
= true;
1181 set_label_mangle(tx
->pvt
, param
);
1185 preproc
->pre_include(q
);
1189 preproc
->pre_command("pragma", param
);
1193 preproc
->pre_command(NULL
, param
);
1197 nasm_set_limit(p
+olen
, param
);
1213 *eqsave
= '='; /* Restore = argument separator */
1219 nasm_nonfatalf(ERR_USAGE
, "unrecognised option `-%c'", p
[1]);
1222 } else if (pass
== 2) {
1223 /* In theory we could allow multiple input files... */
1224 copy_filename(&inname
, p
, "input");
1230 #define ARG_BUF_DELTA 128
1232 static void process_respfile(FILE * rfile
, int pass
)
1234 char *buffer
, *p
, *q
, *prevarg
;
1235 int bufsize
, prevargsize
;
1237 bufsize
= prevargsize
= ARG_BUF_DELTA
;
1238 buffer
= nasm_malloc(ARG_BUF_DELTA
);
1239 prevarg
= nasm_malloc(ARG_BUF_DELTA
);
1242 while (1) { /* Loop to handle all lines in file */
1244 while (1) { /* Loop to handle long lines */
1245 q
= fgets(p
, bufsize
- (p
- buffer
), rfile
);
1249 if (p
> buffer
&& p
[-1] == '\n')
1251 if (p
- buffer
> bufsize
- 10) {
1253 offset
= p
- buffer
;
1254 bufsize
+= ARG_BUF_DELTA
;
1255 buffer
= nasm_realloc(buffer
, bufsize
);
1256 p
= buffer
+ offset
;
1260 if (!q
&& p
== buffer
) {
1262 process_arg(prevarg
, NULL
, pass
);
1269 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1270 * them are present at the end of the line.
1272 *(p
= &buffer
[strcspn(buffer
, "\r\n\032")]) = '\0';
1274 while (p
> buffer
&& nasm_isspace(p
[-1]))
1277 p
= nasm_skip_spaces(buffer
);
1279 if (process_arg(prevarg
, p
, pass
))
1282 if ((int) strlen(p
) > prevargsize
- 10) {
1283 prevargsize
+= ARG_BUF_DELTA
;
1284 prevarg
= nasm_realloc(prevarg
, prevargsize
);
1286 strncpy(prevarg
, p
, prevargsize
);
1290 /* Function to process args from a string of args, rather than the
1291 * argv array. Used by the environment variable and response file
1294 static void process_args(char *args
, int pass
)
1296 char *p
, *q
, *arg
, *prevarg
;
1297 char separator
= ' ';
1300 if (*p
&& *p
!= '-')
1305 while (*p
&& *p
!= separator
)
1307 while (*p
== separator
)
1311 if (process_arg(prevarg
, arg
, pass
))
1315 process_arg(arg
, NULL
, pass
);
1318 static void process_response_file(const char *file
, int pass
)
1321 FILE *f
= nasm_open_read(file
, NF_TEXT
);
1326 while (fgets(str
, sizeof str
, f
)) {
1327 process_args(str
, pass
);
1332 static void parse_cmdline(int argc
, char **argv
, int pass
)
1335 char *envreal
, *envcopy
= NULL
, *p
;
1338 * Initialize all the warnings to their default state, including
1339 * warning index 0 used for "always on".
1341 memcpy(warning_state
, warning_default
, sizeof warning_state
);
1342 memcpy(warning_state_init
, warning_default
, sizeof warning_state_init
);
1345 * First, process the NASMENV environment variable.
1347 envreal
= getenv("NASMENV");
1349 envcopy
= nasm_strdup(envreal
);
1350 process_args(envcopy
, pass
);
1355 * Now process the actual command line.
1360 if (argv
[0][0] == '@') {
1362 * We have a response file, so process this as a set of
1363 * arguments like the environment variable. This allows us
1364 * to have multiple arguments on a single line, which is
1365 * different to the -@resp file processing below for regular
1368 process_response_file(argv
[0]+1, pass
);
1372 if (!stopoptions
&& argv
[0][0] == '-' && argv
[0][1] == '@') {
1373 p
= get_param(argv
[0], argc
> 1 ? argv
[1] : NULL
, &advance
);
1375 rfile
= nasm_open_read(p
, NF_TEXT
);
1377 process_respfile(rfile
, pass
);
1380 nasm_nonfatalf(ERR_USAGE
, "unable to open response file `%s'", p
);
1384 advance
= process_arg(argv
[0], argc
> 1 ? argv
[1] : NULL
, pass
);
1385 argv
+= advance
, argc
-= advance
;
1389 * Look for basic command line typos. This definitely doesn't
1390 * catch all errors, but it might help cases of fumbled fingers.
1396 nasm_fatalf(ERR_USAGE
, "no input file specified");
1397 else if ((errname
&& !strcmp(inname
, errname
)) ||
1398 (outname
&& !strcmp(inname
, outname
)) ||
1399 (listname
&& !strcmp(inname
, listname
)) ||
1400 (depend_file
&& !strcmp(inname
, depend_file
)))
1401 nasm_fatalf(ERR_USAGE
, "will not overwrite input file");
1404 error_file
= nasm_open_write(errname
, NF_TEXT
);
1406 error_file
= stderr
; /* Revert to default! */
1407 nasm_fatalf(ERR_USAGE
, "cannot open file `%s' for error messages", errname
);
1412 static void forward_refs(insn
*instruction
)
1415 struct forwrefinfo
*fwinf
;
1417 instruction
->forw_ref
= false;
1419 if (!optimizing
.level
)
1420 return; /* For -O0 don't bother */
1425 if (forwref
->lineno
!= globallineno
)
1428 instruction
->forw_ref
= true;
1430 instruction
->oprs
[forwref
->operand
].opflags
|= OPFLAG_FORWARD
;
1431 forwref
= saa_rstruct(forwrefs
);
1432 } while (forwref
&& forwref
->lineno
== globallineno
);
1437 for (i
= 0; i
< instruction
->operands
; i
++) {
1438 if (instruction
->oprs
[i
].opflags
& OPFLAG_FORWARD
) {
1439 fwinf
= saa_wstruct(forwrefs
);
1440 fwinf
->lineno
= globallineno
;
1446 static void process_insn(insn
*instruction
)
1451 if (!instruction
->times
)
1452 return; /* Nothing to do... */
1454 nasm_assert(instruction
->times
> 0);
1457 * NOTE: insn_size() can change instruction->times
1458 * (usually to 1) when called.
1460 if (!pass_final()) {
1461 for (n
= 1; n
<= instruction
->times
; n
++) {
1462 l
= insn_size(location
.segment
, location
.offset
,
1463 globalbits
, instruction
);
1464 if (l
!= -1) /* l == -1 -> invalid instruction */
1465 increment_offset(l
);
1468 l
= assemble(location
.segment
, location
.offset
,
1469 globalbits
, instruction
);
1470 /* We can't get an invalid instruction here */
1471 increment_offset(l
);
1473 if (instruction
->times
> 1) {
1474 lfmt
->uplevel(LIST_TIMES
);
1475 for (n
= 2; n
<= instruction
->times
; n
++) {
1476 l
= assemble(location
.segment
, location
.offset
,
1477 globalbits
, instruction
);
1478 increment_offset(l
);
1480 lfmt
->downlevel(LIST_TIMES
);
1485 static void assemble_file(const char *fname
, struct strlist
*depend_list
)
1489 uint64_t prev_offset_changed
;
1490 int64_t stall_count
= 0; /* Make sure we make forward progress... */
1496 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_386
))
1497 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1500 if (!iflag_cpu_level_ok(&cmd_cpu
, IF_X86_64
))
1501 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1508 prev_offset_changed
= INT64_MAX
;
1510 if (listname
&& !keep_all
) {
1511 /* Remove the list file in case we die before the output pass */
1515 while (!terminate_after_phase
&& !pass_final()) {
1517 if (pass_type() != PASS_OPT
|| !global_offset_changed
)
1519 global_offset_changed
= 0;
1522 * Create a warning buffer list unless we are in
1523 * pass 2 (everything will be emitted immediately in pass 2.)
1526 if (warn_list
->nstr
|| pass_final())
1527 strlist_free(&warn_list
);
1530 if (!pass_final() && !warn_list
)
1531 warn_list
= strlist_alloc(false);
1533 globalbits
= cmd_sb
; /* set 'bits' to command line default */
1536 lfmt
->init(listname
);
1538 in_absolute
= false;
1539 if (!pass_first()) {
1540 saa_rewind(forwrefs
);
1541 forwref
= saa_rstruct(forwrefs
);
1543 offsets
= raa_init();
1545 location
.segment
= NO_SEG
;
1546 location
.offset
= 0;
1548 location
.known
= true;
1550 switch_segment(ofmt
->section(NULL
, &globalbits
));
1551 preproc
->reset(fname
, PP_NORMAL
, pass_final() ? depend_list
: NULL
);
1553 /* Revert all warnings to the default state */
1554 memcpy(warning_state
, warning_state_init
, sizeof warning_state
);
1558 while ((line
= preproc
->getline())) {
1559 if (++globallineno
> nasm_limit
[LIMIT_LINES
])
1560 nasm_fatal("overall line count exceeds the maximum %"PRId64
"\n",
1561 nasm_limit
[LIMIT_LINES
]);
1564 * Here we parse our directives; this is not handled by the
1567 if (process_directives(line
))
1568 goto end_of_line
; /* Just do final cleanup */
1570 /* Not a directive, or even something that starts with [ */
1571 parse_line(line
, &output_ins
);
1572 forward_refs(&output_ins
);
1573 process_insn(&output_ins
);
1574 cleanup_insn(&output_ins
);
1578 } /* end while (line = preproc->getline... */
1580 preproc
->cleanup_pass();
1582 /* Don't output further messages if we are dead anyway */
1583 if (terminate_after_phase
)
1586 if (global_offset_changed
) {
1587 switch (pass_type()) {
1590 * This is the only pass type that can be executed more
1591 * than once, and therefore has the ability to stall.
1593 if (global_offset_changed
< prev_offset_changed
) {
1594 prev_offset_changed
= global_offset_changed
;
1600 if (stall_count
> nasm_limit
[LIMIT_STALLED
] ||
1601 pass_count() >= nasm_limit
[LIMIT_PASSES
]) {
1602 /* No convergence, almost certainly dead */
1603 nasm_nonfatal("unable to find valid values for all labels "
1604 "after %"PRId64
" passes; "
1605 "stalled for %"PRId64
", giving up.",
1606 pass_count(), stall_count
);
1607 nasm_note("Possible causes: recursive EQUs, macro abuse.");
1613 *!phase [off] phase error during stabilization
1614 *! warns about symbols having changed values during
1615 *! the second-to-last assembly pass. This is not
1616 *! inherently fatal, but may be a source of bugs.
1618 nasm_warn(WARN_PHASE
, "phase error during stabilization "
1619 "pass, hoping for the best");
1623 nasm_nonfatal("phase error during code generation pass");
1627 /* This is normal, we'll keep going... */
1633 if (opt_verbose_info
&& pass_final()) {
1634 /* -On and -Ov switches */
1635 nasm_note("info: assembly required 1+%"PRId64
"+2 passes\n",
1639 strlist_free(&warn_list
);
1644 * get warning index; 0 if this is non-suppressible.
1646 static size_t warn_index(errflags severity
)
1650 if ((severity
& ERR_MASK
) >= ERR_FATAL
)
1651 return 0; /* Fatal errors are never suppressible */
1653 /* Warnings MUST HAVE a warning category specifier! */
1654 nasm_assert((severity
& (ERR_MASK
|WARN_MASK
)) != ERR_WARNING
);
1656 index
= WARN_IDX(severity
);
1657 nasm_assert(index
< WARN_IDX_ALL
);
1662 static bool skip_this_pass(errflags severity
)
1665 * See if it's a pass-specific error or warning which should be skipped.
1666 * We can never skip fatal errors as by definition they cannot be
1669 if ((severity
& ERR_MASK
) >= ERR_FATAL
)
1672 /* This message not applicable unless pass_final */
1673 return (severity
& ERR_PASS2
) && !pass_final();
1677 * check for suppressed message (usually warnings or notes)
1679 * @param severity the severity of the warning or error
1680 * @return true if we should abort error/warning printing
1682 static bool is_suppressed(errflags severity
)
1684 /* Fatal errors must never be suppressed */
1685 if ((severity
& ERR_MASK
) >= ERR_FATAL
)
1688 /* This error/warning is pointless if we are dead anyway */
1689 if ((severity
& ERR_UNDEAD
) && terminate_after_phase
)
1692 return !(warning_state
[warn_index(severity
)] & WARN_ST_ENABLED
);
1696 * Return the true error type (the ERR_MASK part) of the given
1697 * severity, accounting for warnings that may need to be promoted to
1700 * @param severity the severity of the warning or error
1701 * @return true if we should error out
1703 static errflags
true_error_type(errflags severity
)
1705 const uint8_t warn_is_err
= WARN_ST_ENABLED
|WARN_ST_ERROR
;
1708 type
= severity
& ERR_MASK
;
1710 /* Promote warning to error? */
1711 if (type
== ERR_WARNING
) {
1712 uint8_t state
= warning_state
[warn_index(severity
)];
1713 if ((state
& warn_is_err
) == warn_is_err
)
1714 type
= ERR_NONFATAL
;
1721 * common error reporting
1722 * This is the common back end of the error reporting schemes currently
1723 * implemented. It prints the nature of the warning and then the
1724 * specific error message to error_file and may or may not return. It
1725 * doesn't return if the error severity is a "panic" or "debug" type.
1727 * @param severity the severity of the warning or error
1728 * @param fmt the printf style format string
1730 static void nasm_verror_asm(errflags severity
, const char *fmt
, va_list args
)
1736 errflags spec_type
= severity
& ERR_MASK
; /* type originally specified */
1737 errflags true_type
= true_error_type(severity
);
1738 const char *currentfile
= NULL
;
1740 static const char * const pfx_table
[ERR_MASK
+1] = {
1741 "debug: ", "note: ", "warning: ", "error: ",
1742 "", "", "fatal: ", "panic: "
1745 if (is_suppressed(severity
))
1748 if (!(severity
& ERR_NOFILE
)) {
1749 src_get(&lineno
, ¤tfile
);
1751 currentfile
= currentfile
? currentfile
:
1752 inname
&& inname
[0] ? inname
:
1753 outname
&& outname
[0] ? outname
:
1760 * For a debug/warning/note event, if ERR_HERE is set don't
1761 * output anything if there is no current filename available
1763 if (!currentfile
&& (severity
& ERR_HERE
) && true_type
<= ERR_WARNING
)
1766 if (severity
& ERR_NO_SEVERITY
)
1769 pfx
= pfx_table
[true_type
];
1771 vsnprintf(msg
, sizeof msg
, fmt
, args
);
1773 if (spec_type
== ERR_WARNING
) {
1774 snprintf(warnsuf
, sizeof warnsuf
, " [-w+%s%s]",
1775 (true_type
>= ERR_NONFATAL
) ? "error=" : "",
1776 warning_name
[warn_index(severity
)]);
1781 snprintf(linestr
, sizeof linestr
, "%s%"PRId32
"%s",
1782 errfmt
->beforeline
, lineno
, errfmt
->afterline
);
1785 if (!skip_this_pass(severity
)) {
1786 const char *file
= currentfile
? currentfile
: "nasm";
1787 const char *here
= (severity
& ERR_HERE
) ? " here" : "";
1789 if (warn_list
&& true_type
< ERR_NONFATAL
&&
1790 !(pass_first() && (severity
& ERR_PASS1
)))
1793 * Buffer up warnings until we either get an error
1794 * or we are on the code-generation pass.
1796 strlist_printf(warn_list
, "%s%s%s%s%s%s%s",
1797 file
, linestr
, errfmt
->beforemsg
,
1798 pfx
, msg
, here
, warnsuf
);
1801 * If we have buffered warnings, and this is a non-warning,
1804 if (true_type
>= ERR_NONFATAL
&& warn_list
) {
1805 strlist_write(warn_list
, "\n", error_file
);
1806 strlist_free(&warn_list
);
1809 fprintf(error_file
, "%s%s%s%s%s%s%s\n",
1810 file
, linestr
, errfmt
->beforemsg
,
1811 pfx
, msg
, here
, warnsuf
);
1816 /* Are we recursing from error_list_macros? */
1817 if (severity
& ERR_PP_LISTMACRO
)
1821 * Don't suppress this with skip_this_pass(), or we don't get
1822 * pass1 or preprocessor warnings in the list file
1824 if (severity
& ERR_HERE
) {
1826 lfmt
->error(severity
, "%s%s at %s:%"PRId32
"%s",
1827 pfx
, msg
, currentfile
, lineno
, warnsuf
);
1828 else if (currentfile
)
1829 lfmt
->error(severity
, "%s%s in file %s%s",
1830 pfx
, msg
, currentfile
, warnsuf
);
1832 lfmt
->error(severity
, "%s%s in unknown location%s",
1835 lfmt
->error(severity
, "%s%s%s", pfx
, msg
, warnsuf
);
1838 if (skip_this_pass(severity
))
1841 if (severity
& ERR_USAGE
)
1844 preproc
->error_list_macros(severity
);
1846 switch (true_type
) {
1850 /* no further action, by definition */
1853 terminate_after_phase
= true;
1864 exit(1); /* instantly die */
1865 break; /* placate silly compilers */
1870 abort(); /* halt, catch fire, dump core/stop debugger */
1885 static void usage(void)
1887 fputs("type `nasm -h' for help\n", error_file
);
1890 static void help(const char xopt
)
1895 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1897 " [options...] [--] filename\n"
1898 " or nasm -v (or --v) for version info\n\n"
1900 "Response files should contain command line parameters,\n"
1903 " -t assemble in SciTech TASM compatible mode\n");
1905 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1906 " -a don't preprocess (assemble only)\n"
1907 " -M generate Makefile dependencies on stdout\n"
1908 " -MG d:o, missing files assumed generated\n"
1909 " -MF file set Makefile dependency file\n"
1910 " -MD file assemble and generate dependencies\n"
1911 " -MT file dependency target name\n"
1912 " -MQ file dependency target name (quoted)\n"
1913 " -MP emit phony target\n\n"
1914 " -Zfile redirect error messages to file\n"
1915 " -s redirect error messages to stdout\n\n"
1916 " -g generate debugging information\n\n"
1917 " -F format select a debugging format\n\n"
1918 " -gformat same as -g -F format\n\n"
1919 " -o outfile write output to an outfile\n\n"
1920 " -f format select an output format\n\n"
1921 " -l listfile write listing to a listfile\n\n"
1922 " -Ipath add a pathname to the include file path\n");
1924 (" -Oflags... optimize opcodes, immediates and branch offsets\n"
1925 " -O0 no optimization\n"
1926 " -O1 minimal optimization\n"
1927 " -Ox multipass optimization (default)\n"
1928 " -Ov display the number of passes executed at the end\n"
1929 " -Pfile pre-include a file (also --include)\n"
1930 " -Dmacro[=str] pre-define a macro\n"
1931 " -Umacro undefine a macro\n"
1932 " -Xformat specifiy error reporting format (gnu or vc)\n"
1933 " -w+foo enable warning foo (equiv. -Wfoo)\n"
1934 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
1935 " -w[+-]error[=foo]\n"
1936 " promote [specific] warnings to errors\n"
1937 " -h show invocation summary and exit (also --help)\n\n"
1938 " --pragma str pre-executes a specific %%pragma\n"
1939 " --before str add line (usually a preprocessor statement) before the input\n"
1940 " --prefix str prepend the given string to all the given string\n"
1941 " to all extern, common and global symbols (also --gprefix)\n"
1942 " --postfix str append the given string to all the given string\n"
1943 " to all extern, common and global symbols (also --gpostfix)\n"
1944 " --lprefix str prepend the given string to all other symbols\n"
1945 " --lpostfix str append the given string to all other symbols\n"
1946 " --keep-all output files will not be removed even if an error happens\n"
1947 " --no-line ignore %%line directives in input\n"
1948 " --limit-X val set execution limit X\n");
1950 for (i
= 0; i
<= LIMIT_MAX
; i
++) {
1951 printf(" %-15s %s (default ",
1952 limit_info
[i
].name
, limit_info
[i
].help
);
1953 if (nasm_limit
[i
] < LIMIT_MAX_VAL
) {
1954 printf("%"PRId64
")\n", nasm_limit
[i
]);
1956 printf("unlimited)\n");
1960 printf("\nWarnings for the -W/-w options: (defaults in brackets)\n");
1962 for (i
= 1; i
<= WARN_IDX_ALL
; i
++) {
1963 printf(" %-23s %s%s\n",
1964 warning_name
[i
], warning_help
[i
],
1965 i
== WARN_IDX_ALL
? "\n" :
1966 (warning_default
[i
] & WARN_ST_ERROR
) ? " [error]" :
1967 (warning_default
[i
] & WARN_ST_ENABLED
) ? " [on]" : " [off]");
1971 printf("valid output formats for -f are"
1972 " (`*' denotes default):\n");
1973 ofmt_list(ofmt
, stdout
);
1975 printf("For a list of valid output formats, use -hf.\n");
1976 printf("For a list of debug formats, use -f <format> -y.\n");