listing: encapsulate the list_options encoding, make more comprehensive
[nasm.git] / asm / nasm.c
blobc6ff9ec849c85f55221e5e085bc65145d94b1ae3
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
9 * conditions are met:
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
38 #include "compiler.h"
41 #include "nasm.h"
42 #include "nasmlib.h"
43 #include "nctype.h"
44 #include "error.h"
45 #include "saa.h"
46 #include "raa.h"
47 #include "float.h"
48 #include "stdscan.h"
49 #include "insns.h"
50 #include "preproc.h"
51 #include "parser.h"
52 #include "eval.h"
53 #include "assemble.h"
54 #include "labels.h"
55 #include "outform.h"
56 #include "listing.h"
57 #include "iflag.h"
58 #include "ver.h"
61 * This is the maximum number of optimization passes to do. If we ever
62 * find a case where the optimizer doesn't naturally converge, we might
63 * have to drop this value so the assembler doesn't appear to just hang.
65 #define MAX_OPTIMIZE (INT_MAX >> 1)
67 struct forwrefinfo { /* info held on forward refs. */
68 int lineno;
69 int operand;
72 const char *_progname;
74 static void parse_cmdline(int, char **, int);
75 static void assemble_file(const char *, struct strlist *);
76 static bool skip_this_pass(errflags severity);
77 static void nasm_verror_asm(errflags severity, const char *fmt, va_list args);
78 static void usage(void);
79 static void help(FILE *);
81 struct error_format {
82 const char *beforeline; /* Before line number, if present */
83 const char *afterline; /* After line number, if present */
84 const char *beforemsg; /* Before actual message */
87 static const struct error_format errfmt_gnu = { ":", "", ": " };
88 static const struct error_format errfmt_msvc = { "(", ")", " : " };
89 static const struct error_format *errfmt = &errfmt_gnu;
90 static struct strlist *warn_list;
92 unsigned int debug_nasm; /* Debugging messages? */
94 static bool using_debug_info, opt_verbose_info;
95 static const char *debug_format;
97 #ifndef ABORT_ON_PANIC
98 # define ABORT_ON_PANIC 0
99 #endif
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"
109 int64_t _passn;
110 int globalrel = 0;
111 int globalbnd = 0;
113 struct compile_time official_compile_time;
115 const char *inname;
116 const char *outname;
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 */
128 FILE *ofile = NULL;
129 struct optimization optimizing =
130 { MAX_OPTIMIZE, OPTIM_ALL_ENABLED }; /* number of optimization passes to take */
131 static int cmd_sb = 16; /* by default */
133 iflag_t cpu;
134 static iflag_t cmd_cpu;
136 struct location location;
137 bool in_absolute; /* Flag we are in ABSOLUTE seg */
138 struct location absolute; /* Segment/offset inside ABSOLUTE */
140 static struct RAA *offsets;
142 static struct SAA *forwrefs; /* keep track of forward references */
143 static const struct forwrefinfo *forwref;
145 static const struct preproc_ops *preproc;
146 static struct strlist *include_path;
147 bool pp_noline; /* Ignore %line directives */
149 #define OP_NORMAL (1U << 0)
150 #define OP_PREPROCESS (1U << 1)
151 #define OP_DEPEND (1U << 2)
153 static unsigned int operating_mode;
155 /* Dependency flags */
156 static bool depend_emit_phony = false;
157 static bool depend_missing_ok = false;
158 static const char *depend_target = NULL;
159 static const char *depend_file = NULL;
160 struct strlist *depend_list;
162 static bool want_usage;
163 static bool terminate_after_phase;
164 bool user_nolist = false;
166 static char *quote_for_pmake(const char *str);
167 static char *quote_for_wmake(const char *str);
168 static char *(*quote_for_make)(const char *) = quote_for_pmake;
171 * Execution limits that can be set via a command-line option or %pragma
175 * This is really unlimited; it would take far longer than the
176 * current age of the universe for this limit to be reached even on
177 * much faster CPUs than currently exist.
179 #define LIMIT_MAX_VAL (INT64_MAX >> 1)
181 int64_t nasm_limit[LIMIT_MAX+1];
183 struct limit_info {
184 const char *name;
185 const char *help;
186 int64_t default_val;
188 /* The order here must match enum nasm_limit in nasm.h */
189 static const struct limit_info limit_info[LIMIT_MAX+1] = {
190 { "passes", "total number of passes", LIMIT_MAX_VAL },
191 { "stalled-passes", "number of passes without forward progress", 1000 },
192 { "macro-levels", "levels of macro expansion", 10000 },
193 { "macro-tokens", "tokens processed during macro expansion", 10000000 },
194 { "rep", "%rep count", 1000000 },
195 { "eval", "expression evaluation descent", 1000000},
196 { "lines", "total source lines processed", 2000000000 }
199 static void set_default_limits(void)
201 int i;
202 for (i = 0; i <= LIMIT_MAX; i++)
203 nasm_limit[i] = limit_info[i].default_val;
206 enum directive_result
207 nasm_set_limit(const char *limit, const char *valstr)
209 int i;
210 int64_t val;
211 bool rn_error;
212 int errlevel;
214 for (i = 0; i <= LIMIT_MAX; i++) {
215 if (!nasm_stricmp(limit, limit_info[i].name))
216 break;
218 if (i > LIMIT_MAX) {
219 if (not_started())
220 errlevel = ERR_WARNING|WARN_OTHER|ERR_USAGE;
221 else
222 errlevel = ERR_WARNING|WARN_PRAGMA_UNKNOWN;
223 nasm_error(errlevel, "unknown limit: `%s'", limit);
224 return DIRR_ERROR;
227 if (!nasm_stricmp(valstr, "unlimited")) {
228 val = LIMIT_MAX_VAL;
229 } else {
230 val = readnum(valstr, &rn_error);
231 if (rn_error || val < 0) {
232 if (not_started())
233 errlevel = ERR_WARNING|WARN_OTHER|ERR_USAGE;
234 else
235 errlevel = ERR_WARNING|WARN_PRAGMA_BAD;
236 nasm_error(errlevel, "invalid limit value: `%s'", limit);
237 return DIRR_ERROR;
239 if (val > LIMIT_MAX_VAL)
240 val = LIMIT_MAX_VAL;
243 nasm_limit[i] = val;
244 return DIRR_OK;
247 int64_t switch_segment(int32_t segment)
249 location.segment = segment;
250 if (segment == NO_SEG) {
251 location.offset = absolute.offset;
252 in_absolute = true;
253 } else {
254 location.offset = raa_read(offsets, segment);
255 in_absolute = false;
257 return location.offset;
260 static void set_curr_offs(int64_t l_off)
262 if (in_absolute)
263 absolute.offset = l_off;
264 else
265 offsets = raa_write(offsets, location.segment, l_off);
268 static void increment_offset(int64_t delta)
270 if (unlikely(delta == 0))
271 return;
273 location.offset += delta;
274 set_curr_offs(location.offset);
277 static void nasm_fputs(const char *line, FILE * outfile)
279 if (outfile) {
280 fputs(line, outfile);
281 putc('\n', outfile);
282 } else
283 puts(line);
287 * Define system-defined macros that are not part of
288 * macros/standard.mac.
290 static void define_macros(void)
292 const struct compile_time * const oct = &official_compile_time;
293 char temp[128];
295 if (oct->have_local) {
296 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &oct->local);
297 preproc->pre_define(temp);
298 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &oct->local);
299 preproc->pre_define(temp);
300 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &oct->local);
301 preproc->pre_define(temp);
302 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &oct->local);
303 preproc->pre_define(temp);
306 if (oct->have_gm) {
307 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &oct->gm);
308 preproc->pre_define(temp);
309 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &oct->gm);
310 preproc->pre_define(temp);
311 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &oct->gm);
312 preproc->pre_define(temp);
313 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &oct->gm);
314 preproc->pre_define(temp);
317 if (oct->have_posix) {
318 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, oct->posix);
319 preproc->pre_define(temp);
323 * In case if output format is defined by alias
324 * we have to put shortname of the alias itself here
325 * otherwise ABI backward compatibility gets broken.
327 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
328 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
329 preproc->pre_define(temp);
332 * Output-format specific macros.
334 if (ofmt->stdmac)
335 preproc->extra_stdmac(ofmt->stdmac);
338 * Debug format, if any
340 if (dfmt != &null_debug_form) {
341 snprintf(temp, sizeof(temp), "__DEBUG_FORMAT__=%s", dfmt->shortname);
342 preproc->pre_define(temp);
347 * Initialize the preprocessor, set up the include path, and define
348 * the system-included macros. This is called between passes 1 and 2
349 * of parsing the command options; ofmt and dfmt are defined at this
350 * point.
352 * Command-line specified preprocessor directives (-p, -d, -u,
353 * --pragma, --before) are processed after this function.
355 static void preproc_init(struct strlist *ipath)
357 preproc->init();
358 define_macros();
359 preproc->include_path(ipath);
362 static void emit_dependencies(struct strlist *list)
364 FILE *deps;
365 int linepos, len;
366 bool wmake = (quote_for_make == quote_for_wmake);
367 const char *wrapstr, *nulltarget;
368 const struct strlist_entry *l;
370 if (!list)
371 return;
373 wrapstr = wmake ? " &\n " : " \\\n ";
374 nulltarget = wmake ? "\t%null\n" : "";
376 if (depend_file && strcmp(depend_file, "-")) {
377 deps = nasm_open_write(depend_file, NF_TEXT);
378 if (!deps) {
379 nasm_nonfatal("unable to write dependency file `%s'", depend_file);
380 return;
382 } else {
383 deps = stdout;
386 linepos = fprintf(deps, "%s :", depend_target);
387 strlist_for_each(l, list) {
388 char *file = quote_for_make(l->str);
389 len = strlen(file);
390 if (linepos + len > 62 && linepos > 1) {
391 fputs(wrapstr, deps);
392 linepos = 1;
394 fprintf(deps, " %s", file);
395 linepos += len+1;
396 nasm_free(file);
398 fputs("\n\n", deps);
400 strlist_for_each(l, list) {
401 if (depend_emit_phony) {
402 char *file = quote_for_make(l->str);
403 fprintf(deps, "%s :\n%s\n", file, nulltarget);
404 nasm_free(file);
408 strlist_free(&list);
410 if (deps != stdout)
411 fclose(deps);
414 /* Convert a struct tm to a POSIX-style time constant */
415 static int64_t make_posix_time(const struct tm *tm)
417 int64_t t;
418 int64_t y = tm->tm_year;
420 /* See IEEE 1003.1:2004, section 4.14 */
422 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
423 t += tm->tm_yday;
424 t *= 24;
425 t += tm->tm_hour;
426 t *= 60;
427 t += tm->tm_min;
428 t *= 60;
429 t += tm->tm_sec;
431 return t;
434 static void timestamp(void)
436 struct compile_time * const oct = &official_compile_time;
437 const struct tm *tp, *best_gm;
439 time(&oct->t);
441 best_gm = NULL;
443 tp = localtime(&oct->t);
444 if (tp) {
445 oct->local = *tp;
446 best_gm = &oct->local;
447 oct->have_local = true;
450 tp = gmtime(&oct->t);
451 if (tp) {
452 oct->gm = *tp;
453 best_gm = &oct->gm;
454 oct->have_gm = true;
455 if (!oct->have_local)
456 oct->local = oct->gm;
457 } else {
458 oct->gm = oct->local;
461 if (best_gm) {
462 oct->posix = make_posix_time(best_gm);
463 oct->have_posix = true;
467 int main(int argc, char **argv)
469 _progname = argv[0];
470 if (!_progname || !_progname[0])
471 _progname = "nasm";
473 timestamp();
475 error_file = stderr;
477 iflag_set_default_cpu(&cpu);
478 iflag_set_default_cpu(&cmd_cpu);
480 set_default_limits();
482 include_path = strlist_alloc(true);
484 _pass_type = PASS_INIT;
485 _passn = 0;
487 want_usage = terminate_after_phase = false;
488 nasm_set_verror(nasm_verror_asm);
490 nasm_ctype_init();
491 src_init();
494 * We must call init_labels() before the command line parsing,
495 * because we may be setting prefixes/suffixes from the command
496 * line.
498 init_labels();
500 offsets = raa_init();
501 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
503 preproc = &nasmpp;
504 operating_mode = OP_NORMAL;
506 parse_cmdline(argc, argv, 1);
507 if (terminate_after_phase) {
508 if (want_usage)
509 usage();
510 return 1;
513 /* At this point we have ofmt and the name of the desired debug format */
514 if (!using_debug_info) {
515 /* No debug info, redirect to the null backend (empty stubs) */
516 dfmt = &null_debug_form;
517 } else if (!debug_format) {
518 /* Default debug format for this backend */
519 dfmt = ofmt->default_dfmt;
520 } else {
521 dfmt = dfmt_find(ofmt, debug_format);
522 if (!dfmt) {
523 nasm_fatalf(ERR_USAGE, "unrecognized debug format `%s' for output format `%s'",
524 debug_format, ofmt->shortname);
528 preproc_init(include_path);
530 parse_cmdline(argc, argv, 2);
531 if (terminate_after_phase) {
532 if (want_usage)
533 usage();
534 return 1;
537 /* Save away the default state of warnings */
538 init_warnings();
540 /* Dependency filename if we are also doing other things */
541 if (!depend_file && (operating_mode & ~OP_DEPEND)) {
542 if (outname)
543 depend_file = nasm_strcat(outname, ".d");
544 else
545 depend_file = filename_set_extension(inname, ".d");
549 * If no output file name provided and this
550 * is preprocess mode, we're perfectly
551 * fine to output into stdout.
553 if (!outname && !(operating_mode & OP_PREPROCESS)) {
554 outname = filename_set_extension(inname, ofmt->extension);
555 if (!strcmp(outname, inname)) {
556 outname = "nasm.out";
557 nasm_warn(WARN_OTHER, "default output file same as input, using `%s' for output\n", outname);
561 depend_list = (operating_mode & OP_DEPEND) ? strlist_alloc(true) : NULL;
563 if (!depend_target)
564 depend_target = quote_for_make(outname);
566 if (!(operating_mode & (OP_PREPROCESS|OP_NORMAL))) {
567 char *line;
569 if (depend_missing_ok)
570 preproc->include_path(NULL); /* "assume generated" */
572 preproc->reset(inname, PP_DEPS, depend_list);
573 ofile = NULL;
574 while ((line = preproc->getline()))
575 nasm_free(line);
576 preproc->cleanup_pass();
577 reset_warnings();
578 } else if (operating_mode & OP_PREPROCESS) {
579 char *line;
580 const char *file_name = NULL;
581 int32_t prior_linnum = 0;
582 int lineinc = 0;
584 if (outname) {
585 ofile = nasm_open_write(outname, NF_TEXT);
586 if (!ofile)
587 nasm_fatal("unable to open output file `%s'", outname);
588 } else
589 ofile = NULL;
591 location.known = false;
593 _pass_type = PASS_FIRST; /* We emulate this assembly pass */
594 preproc->reset(inname, PP_PREPROC, depend_list);
596 while ((line = preproc->getline())) {
598 * We generate %line directives if needed for later programs
600 int32_t linnum = prior_linnum += lineinc;
601 int altline = src_get(&linnum, &file_name);
602 if (altline) {
603 if (altline == 1 && lineinc == 1)
604 nasm_fputs("", ofile);
605 else {
606 lineinc = (altline != -1 || lineinc != 1);
607 fprintf(ofile ? ofile : stdout,
608 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
609 file_name);
611 prior_linnum = linnum;
613 nasm_fputs(line, ofile);
614 nasm_free(line);
616 preproc->cleanup_pass();
617 reset_warnings();
618 if (ofile)
619 fclose(ofile);
620 if (ofile && terminate_after_phase && !keep_all)
621 remove(outname);
622 ofile = NULL;
625 if (operating_mode & OP_NORMAL) {
626 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
627 if (!ofile)
628 nasm_fatal("unable to open output file `%s'", outname);
630 ofmt->init();
631 dfmt->init();
633 assemble_file(inname, depend_list);
635 if (!terminate_after_phase) {
636 ofmt->cleanup();
637 cleanup_labels();
638 fflush(ofile);
639 if (ferror(ofile))
640 nasm_nonfatal("write error on output file `%s'", outname);
643 if (ofile) {
644 fclose(ofile);
645 if (terminate_after_phase && !keep_all)
646 remove(outname);
647 ofile = NULL;
651 preproc->cleanup_session();
653 if (depend_list && !terminate_after_phase)
654 emit_dependencies(depend_list);
656 if (want_usage)
657 usage();
659 raa_free(offsets);
660 saa_free(forwrefs);
661 eval_cleanup();
662 stdscan_cleanup();
663 src_free();
664 strlist_free(&include_path);
666 return terminate_after_phase;
670 * Get a parameter for a command line option.
671 * First arg must be in the form of e.g. -f...
673 static char *get_param(char *p, char *q, bool *advance)
675 *advance = false;
676 if (p[2]) /* the parameter's in the option */
677 return nasm_skip_spaces(p + 2);
678 if (q && q[0]) {
679 *advance = true;
680 return q;
682 nasm_nonfatalf(ERR_USAGE, "option `-%c' requires an argument", p[1]);
683 return NULL;
687 * Copy a filename
689 static void copy_filename(const char **dst, const char *src, const char *what)
691 if (*dst)
692 nasm_fatal("more than one %s file specified: %s\n", what, src);
694 *dst = nasm_strdup(src);
698 * Convert a string to a POSIX make-safe form
700 static char *quote_for_pmake(const char *str)
702 const char *p;
703 char *os, *q;
705 size_t n = 1; /* Terminating zero */
706 size_t nbs = 0;
708 if (!str)
709 return NULL;
711 for (p = str; *p; p++) {
712 switch (*p) {
713 case ' ':
714 case '\t':
715 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
716 n += nbs + 2;
717 nbs = 0;
718 break;
719 case '$':
720 case '#':
721 nbs = 0;
722 n += 2;
723 break;
724 case '\\':
725 nbs++;
726 n++;
727 break;
728 default:
729 nbs = 0;
730 n++;
731 break;
735 /* Convert N backslashes at the end of filename to 2N backslashes */
736 if (nbs)
737 n += nbs;
739 os = q = nasm_malloc(n);
741 nbs = 0;
742 for (p = str; *p; p++) {
743 switch (*p) {
744 case ' ':
745 case '\t':
746 while (nbs--)
747 *q++ = '\\';
748 *q++ = '\\';
749 *q++ = *p;
750 break;
751 case '$':
752 *q++ = *p;
753 *q++ = *p;
754 nbs = 0;
755 break;
756 case '#':
757 *q++ = '\\';
758 *q++ = *p;
759 nbs = 0;
760 break;
761 case '\\':
762 *q++ = *p;
763 nbs++;
764 break;
765 default:
766 *q++ = *p;
767 nbs = 0;
768 break;
771 while (nbs--)
772 *q++ = '\\';
774 *q = '\0';
776 return os;
780 * Convert a string to a Watcom make-safe form
782 static char *quote_for_wmake(const char *str)
784 const char *p;
785 char *os, *q;
786 bool quote = false;
788 size_t n = 1; /* Terminating zero */
790 if (!str)
791 return NULL;
793 for (p = str; *p; p++) {
794 switch (*p) {
795 case ' ':
796 case '\t':
797 case '&':
798 quote = true;
799 n++;
800 break;
801 case '\"':
802 quote = true;
803 n += 2;
804 break;
805 case '$':
806 case '#':
807 n += 2;
808 break;
809 default:
810 n++;
811 break;
815 if (quote)
816 n += 2;
818 os = q = nasm_malloc(n);
820 if (quote)
821 *q++ = '\"';
823 for (p = str; *p; p++) {
824 switch (*p) {
825 case '$':
826 case '#':
827 *q++ = '$';
828 *q++ = *p;
829 break;
830 case '\"':
831 *q++ = *p;
832 *q++ = *p;
833 break;
834 default:
835 *q++ = *p;
836 break;
840 if (quote)
841 *q++ = '\"';
843 *q = '\0';
845 return os;
848 enum text_options {
849 OPT_BOGUS,
850 OPT_VERSION,
851 OPT_HELP,
852 OPT_ABORT_ON_PANIC,
853 OPT_MANGLE,
854 OPT_INCLUDE,
855 OPT_PRAGMA,
856 OPT_BEFORE,
857 OPT_LIMIT,
858 OPT_KEEP_ALL,
859 OPT_NO_LINE,
860 OPT_DEBUG
862 enum need_arg {
863 ARG_NO,
864 ARG_YES,
865 ARG_MAYBE
868 struct textargs {
869 const char *label;
870 enum text_options opt;
871 enum need_arg need_arg;
872 int pvt;
874 static const struct textargs textopts[] = {
875 {"v", OPT_VERSION, ARG_NO, 0},
876 {"version", OPT_VERSION, ARG_NO, 0},
877 {"help", OPT_HELP, ARG_NO, 0},
878 {"abort-on-panic", OPT_ABORT_ON_PANIC, ARG_NO, 0},
879 {"prefix", OPT_MANGLE, ARG_YES, LM_GPREFIX},
880 {"postfix", OPT_MANGLE, ARG_YES, LM_GSUFFIX},
881 {"gprefix", OPT_MANGLE, ARG_YES, LM_GPREFIX},
882 {"gpostfix", OPT_MANGLE, ARG_YES, LM_GSUFFIX},
883 {"lprefix", OPT_MANGLE, ARG_YES, LM_LPREFIX},
884 {"lpostfix", OPT_MANGLE, ARG_YES, LM_LSUFFIX},
885 {"include", OPT_INCLUDE, ARG_YES, 0},
886 {"pragma", OPT_PRAGMA, ARG_YES, 0},
887 {"before", OPT_BEFORE, ARG_YES, 0},
888 {"limit-", OPT_LIMIT, ARG_YES, 0},
889 {"keep-all", OPT_KEEP_ALL, ARG_NO, 0},
890 {"no-line", OPT_NO_LINE, ARG_NO, 0},
891 {"debug", OPT_DEBUG, ARG_MAYBE, 0},
892 {NULL, OPT_BOGUS, ARG_NO, 0}
895 static void show_version(void)
897 printf("NASM version %s compiled on %s%s\n",
898 nasm_version, nasm_date, nasm_compile_options);
899 exit(0);
902 static bool stopoptions = false;
903 static bool process_arg(char *p, char *q, int pass)
905 char *param;
906 bool advance = false;
908 if (!p || !p[0])
909 return false;
911 if (p[0] == '-' && !stopoptions) {
912 if (strchr("oOfpPdDiIlLFXuUZwW", p[1])) {
913 /* These parameters take values */
914 if (!(param = get_param(p, q, &advance)))
915 return advance;
918 switch (p[1]) {
919 case 's':
920 if (pass == 1)
921 error_file = stdout;
922 break;
924 case 'o': /* output file */
925 if (pass == 2)
926 copy_filename(&outname, param, "output");
927 break;
929 case 'f': /* output format */
930 if (pass == 1) {
931 ofmt = ofmt_find(param, &ofmt_alias);
932 if (!ofmt) {
933 nasm_fatalf(ERR_USAGE, "unrecognised output format `%s' - use -hf for a list", param);
936 break;
938 case 'O': /* Optimization level */
939 if (pass == 1) {
940 int opt;
942 if (!*param) {
943 /* Naked -O == -Ox */
944 optimizing.level = MAX_OPTIMIZE;
945 } else {
946 while (*param) {
947 switch (*param) {
948 case '0': case '1': case '2': case '3': case '4':
949 case '5': case '6': case '7': case '8': case '9':
950 opt = strtoul(param, &param, 10);
952 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
953 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
954 if (opt < 2)
955 optimizing.level = opt - 1;
956 else
957 optimizing.level = opt;
958 break;
960 case 'v':
961 case '+':
962 param++;
963 opt_verbose_info = true;
964 break;
966 case 'x':
967 param++;
968 optimizing.level = MAX_OPTIMIZE;
969 break;
971 default:
972 nasm_fatal("unknown optimization option -O%c\n",
973 *param);
974 break;
977 if (optimizing.level > MAX_OPTIMIZE)
978 optimizing.level = MAX_OPTIMIZE;
981 break;
983 case 'p': /* pre-include */
984 case 'P':
985 if (pass == 2)
986 preproc->pre_include(param);
987 break;
989 case 'd': /* pre-define */
990 case 'D':
991 if (pass == 2)
992 preproc->pre_define(param);
993 break;
995 case 'u': /* un-define */
996 case 'U':
997 if (pass == 2)
998 preproc->pre_undefine(param);
999 break;
1001 case 'i': /* include search path */
1002 case 'I':
1003 if (pass == 1)
1004 strlist_add(include_path, param);
1005 break;
1007 case 'l': /* listing file */
1008 if (pass == 2)
1009 copy_filename(&listname, param, "listing");
1010 break;
1012 case 'L': /* listing options */
1013 if (pass == 2) {
1014 while (*param)
1015 list_options |= list_option_mask(*param++);
1017 break;
1019 case 'Z': /* error messages file */
1020 if (pass == 1)
1021 copy_filename(&errname, param, "error");
1022 break;
1024 case 'F': /* specify debug format */
1025 if (pass == 1) {
1026 using_debug_info = true;
1027 debug_format = param;
1029 break;
1031 case 'X': /* specify error reporting format */
1032 if (pass == 1) {
1033 if (!nasm_stricmp("vc", param) || !nasm_stricmp("msvc", param) || !nasm_stricmp("ms", param))
1034 errfmt = &errfmt_msvc;
1035 else if (!nasm_stricmp("gnu", param) || !nasm_stricmp("gcc", param))
1036 errfmt = &errfmt_gnu;
1037 else
1038 nasm_fatalf(ERR_USAGE, "unrecognized error reporting format `%s'", param);
1040 break;
1042 case 'g':
1043 if (pass == 1) {
1044 using_debug_info = true;
1045 if (p[2])
1046 debug_format = nasm_skip_spaces(p + 2);
1048 break;
1050 case 'h':
1051 help(stdout);
1052 exit(0); /* never need usage message here */
1053 break;
1055 case 'y':
1056 /* legacy option */
1057 dfmt_list(stdout);
1058 exit(0);
1059 break;
1061 case 't':
1062 if (pass == 2) {
1063 tasm_compatible_mode = true;
1064 nasm_ctype_tasm_mode();
1066 break;
1068 case 'v':
1069 show_version();
1070 break;
1072 case 'e': /* preprocess only */
1073 case 'E':
1074 if (pass == 1)
1075 operating_mode = OP_PREPROCESS;
1076 break;
1078 case 'a': /* assemble only - don't preprocess */
1079 if (pass == 1)
1080 preproc = &preproc_nop;
1081 break;
1083 case 'w':
1084 case 'W':
1085 if (pass == 2)
1086 set_warning_status(param);
1087 break;
1089 case 'M':
1090 if (pass == 1) {
1091 switch (p[2]) {
1092 case 'W':
1093 quote_for_make = quote_for_wmake;
1094 break;
1095 case 'D':
1096 case 'F':
1097 case 'T':
1098 case 'Q':
1099 advance = true;
1100 break;
1101 default:
1102 break;
1104 } else {
1105 switch (p[2]) {
1106 case 0:
1107 operating_mode = OP_DEPEND;
1108 break;
1109 case 'G':
1110 operating_mode = OP_DEPEND;
1111 depend_missing_ok = true;
1112 break;
1113 case 'P':
1114 depend_emit_phony = true;
1115 break;
1116 case 'D':
1117 operating_mode |= OP_DEPEND;
1118 if (q && (q[0] != '-' || q[1] == '\0')) {
1119 depend_file = q;
1120 advance = true;
1122 break;
1123 case 'F':
1124 depend_file = q;
1125 advance = true;
1126 break;
1127 case 'T':
1128 depend_target = q;
1129 advance = true;
1130 break;
1131 case 'Q':
1132 depend_target = quote_for_make(q);
1133 advance = true;
1134 break;
1135 case 'W':
1136 /* handled in pass 1 */
1137 break;
1138 default:
1139 nasm_nonfatalf(ERR_USAGE, "unknown dependency option `-M%c'", p[2]);
1140 break;
1143 if (advance && (!q || !q[0])) {
1144 nasm_nonfatalf(ERR_USAGE, "option `-M%c' requires a parameter", p[2]);
1145 break;
1147 break;
1149 case '-':
1151 const struct textargs *tx;
1152 size_t olen, plen;
1153 char *eqsave;
1154 enum text_options opt;
1156 p += 2;
1158 if (!*p) { /* -- => stop processing options */
1159 stopoptions = true;
1160 break;
1163 olen = 0; /* Placate gcc at lower optimization levels */
1164 plen = strlen(p);
1165 for (tx = textopts; tx->label; tx++) {
1166 olen = strlen(tx->label);
1168 if (olen > plen)
1169 continue;
1171 if (nasm_memicmp(p, tx->label, olen))
1172 continue;
1174 if (tx->label[olen-1] == '-')
1175 break; /* Incomplete option */
1177 if (!p[olen] || p[olen] == '=')
1178 break; /* Complete option */
1181 if (!tx->label) {
1182 nasm_nonfatalf(ERR_USAGE, "unrecognized option `--%s'", p);
1185 opt = tx->opt;
1187 eqsave = param = strchr(p+olen, '=');
1188 if (param)
1189 *param++ = '\0';
1191 switch (tx->need_arg) {
1192 case ARG_YES: /* Argument required, and may be standalone */
1193 if (!param) {
1194 param = q;
1195 advance = true;
1198 /* Note: a null string is a valid parameter */
1199 if (!param) {
1200 nasm_nonfatalf(ERR_USAGE, "option `--%s' requires an argument", p);
1201 opt = OPT_BOGUS;
1203 break;
1205 case ARG_NO: /* Argument prohibited */
1206 if (param) {
1207 nasm_nonfatalf(ERR_USAGE, "option `--%s' does not take an argument", p);
1208 opt = OPT_BOGUS;
1210 break;
1212 case ARG_MAYBE: /* Argument permitted, but must be attached with = */
1213 break;
1216 switch (opt) {
1217 case OPT_BOGUS:
1218 break; /* We have already errored out */
1219 case OPT_VERSION:
1220 show_version();
1221 break;
1222 case OPT_ABORT_ON_PANIC:
1223 abort_on_panic = true;
1224 break;
1225 case OPT_MANGLE:
1226 if (pass == 2)
1227 set_label_mangle(tx->pvt, param);
1228 break;
1229 case OPT_INCLUDE:
1230 if (pass == 2)
1231 preproc->pre_include(q);
1232 break;
1233 case OPT_PRAGMA:
1234 if (pass == 2)
1235 preproc->pre_command("pragma", param);
1236 break;
1237 case OPT_BEFORE:
1238 if (pass == 2)
1239 preproc->pre_command(NULL, param);
1240 break;
1241 case OPT_LIMIT:
1242 if (pass == 1)
1243 nasm_set_limit(p+olen, param);
1244 break;
1245 case OPT_KEEP_ALL:
1246 keep_all = true;
1247 break;
1248 case OPT_NO_LINE:
1249 pp_noline = true;
1250 break;
1251 case OPT_DEBUG:
1252 debug_nasm = param ? strtoul(param, NULL, 10) : debug_nasm+1;
1253 break;
1254 case OPT_HELP:
1255 help(stdout);
1256 exit(0);
1257 default:
1258 panic();
1261 if (eqsave)
1262 *eqsave = '='; /* Restore = argument separator */
1264 break;
1267 default:
1268 nasm_nonfatalf(ERR_USAGE, "unrecognised option `-%c'", p[1]);
1269 break;
1271 } else if (pass == 2) {
1272 /* In theory we could allow multiple input files... */
1273 copy_filename(&inname, p, "input");
1276 return advance;
1279 #define ARG_BUF_DELTA 128
1281 static void process_respfile(FILE * rfile, int pass)
1283 char *buffer, *p, *q, *prevarg;
1284 int bufsize, prevargsize;
1286 bufsize = prevargsize = ARG_BUF_DELTA;
1287 buffer = nasm_malloc(ARG_BUF_DELTA);
1288 prevarg = nasm_malloc(ARG_BUF_DELTA);
1289 prevarg[0] = '\0';
1291 while (1) { /* Loop to handle all lines in file */
1292 p = buffer;
1293 while (1) { /* Loop to handle long lines */
1294 q = fgets(p, bufsize - (p - buffer), rfile);
1295 if (!q)
1296 break;
1297 p += strlen(p);
1298 if (p > buffer && p[-1] == '\n')
1299 break;
1300 if (p - buffer > bufsize - 10) {
1301 int offset;
1302 offset = p - buffer;
1303 bufsize += ARG_BUF_DELTA;
1304 buffer = nasm_realloc(buffer, bufsize);
1305 p = buffer + offset;
1309 if (!q && p == buffer) {
1310 if (prevarg[0])
1311 process_arg(prevarg, NULL, pass);
1312 nasm_free(buffer);
1313 nasm_free(prevarg);
1314 return;
1318 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1319 * them are present at the end of the line.
1321 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1323 while (p > buffer && nasm_isspace(p[-1]))
1324 *--p = '\0';
1326 p = nasm_skip_spaces(buffer);
1328 if (process_arg(prevarg, p, pass))
1329 *p = '\0';
1331 if ((int) strlen(p) > prevargsize - 10) {
1332 prevargsize += ARG_BUF_DELTA;
1333 prevarg = nasm_realloc(prevarg, prevargsize);
1335 strncpy(prevarg, p, prevargsize);
1339 /* Function to process args from a string of args, rather than the
1340 * argv array. Used by the environment variable and response file
1341 * processing.
1343 static void process_args(char *args, int pass)
1345 char *p, *q, *arg, *prevarg;
1346 char separator = ' ';
1348 p = args;
1349 if (*p && *p != '-')
1350 separator = *p++;
1351 arg = NULL;
1352 while (*p) {
1353 q = p;
1354 while (*p && *p != separator)
1355 p++;
1356 while (*p == separator)
1357 *p++ = '\0';
1358 prevarg = arg;
1359 arg = q;
1360 if (process_arg(prevarg, arg, pass))
1361 arg = NULL;
1363 if (arg)
1364 process_arg(arg, NULL, pass);
1367 static void process_response_file(const char *file, int pass)
1369 char str[2048];
1370 FILE *f = nasm_open_read(file, NF_TEXT);
1371 if (!f) {
1372 perror(file);
1373 exit(-1);
1375 while (fgets(str, sizeof str, f)) {
1376 process_args(str, pass);
1378 fclose(f);
1381 static void parse_cmdline(int argc, char **argv, int pass)
1383 FILE *rfile;
1384 char *envreal, *envcopy = NULL, *p;
1387 * Initialize all the warnings to their default state, including
1388 * warning index 0 used for "always on".
1390 memcpy(warning_state, warning_default, sizeof warning_state);
1393 * First, process the NASMENV environment variable.
1395 envreal = getenv("NASMENV");
1396 if (envreal) {
1397 envcopy = nasm_strdup(envreal);
1398 process_args(envcopy, pass);
1399 nasm_free(envcopy);
1403 * Now process the actual command line.
1405 while (--argc) {
1406 bool advance;
1407 argv++;
1408 if (argv[0][0] == '@') {
1410 * We have a response file, so process this as a set of
1411 * arguments like the environment variable. This allows us
1412 * to have multiple arguments on a single line, which is
1413 * different to the -@resp file processing below for regular
1414 * NASM.
1416 process_response_file(argv[0]+1, pass);
1417 argc--;
1418 argv++;
1420 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1421 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1422 if (p) {
1423 rfile = nasm_open_read(p, NF_TEXT);
1424 if (rfile) {
1425 process_respfile(rfile, pass);
1426 fclose(rfile);
1427 } else {
1428 nasm_nonfatalf(ERR_USAGE, "unable to open response file `%s'", p);
1431 } else
1432 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1433 argv += advance, argc -= advance;
1437 * Look for basic command line typos. This definitely doesn't
1438 * catch all errors, but it might help cases of fumbled fingers.
1440 if (pass != 2)
1441 return;
1443 if (!inname)
1444 nasm_fatalf(ERR_USAGE, "no input file specified");
1445 else if ((errname && !strcmp(inname, errname)) ||
1446 (outname && !strcmp(inname, outname)) ||
1447 (listname && !strcmp(inname, listname)) ||
1448 (depend_file && !strcmp(inname, depend_file)))
1449 nasm_fatalf(ERR_USAGE, "will not overwrite input file");
1451 if (errname) {
1452 error_file = nasm_open_write(errname, NF_TEXT);
1453 if (!error_file) {
1454 error_file = stderr; /* Revert to default! */
1455 nasm_fatalf(ERR_USAGE, "cannot open file `%s' for error messages", errname);
1460 static void forward_refs(insn *instruction)
1462 int i;
1463 struct forwrefinfo *fwinf;
1465 instruction->forw_ref = false;
1467 if (!optimizing.level)
1468 return; /* For -O0 don't bother */
1470 if (!forwref)
1471 return;
1473 if (forwref->lineno != globallineno)
1474 return;
1476 instruction->forw_ref = true;
1477 do {
1478 instruction->oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1479 forwref = saa_rstruct(forwrefs);
1480 } while (forwref && forwref->lineno == globallineno);
1482 if (!pass_first())
1483 return;
1485 for (i = 0; i < instruction->operands; i++) {
1486 if (instruction->oprs[i].opflags & OPFLAG_FORWARD) {
1487 fwinf = saa_wstruct(forwrefs);
1488 fwinf->lineno = globallineno;
1489 fwinf->operand = i;
1494 static void process_insn(insn *instruction)
1496 int32_t n;
1497 int64_t l;
1499 if (!instruction->times)
1500 return; /* Nothing to do... */
1502 nasm_assert(instruction->times > 0);
1505 * NOTE: insn_size() can change instruction->times
1506 * (usually to 1) when called.
1508 if (!pass_final()) {
1509 int64_t start = location.offset;
1510 for (n = 1; n <= instruction->times; n++) {
1511 l = insn_size(location.segment, location.offset,
1512 globalbits, instruction);
1513 /* l == -1 -> invalid instruction */
1514 if (l != -1)
1515 increment_offset(l);
1517 if (list_option('p')) {
1518 struct out_data dummy;
1519 memset(&dummy, 0, sizeof dummy);
1520 dummy.type = OUT_RAWDATA; /* Handled specially with .data NULL */
1521 dummy.offset = start;
1522 dummy.size = location.offset - start;
1523 lfmt->output(&dummy);
1525 } else {
1526 l = assemble(location.segment, location.offset,
1527 globalbits, instruction);
1528 /* We can't get an invalid instruction here */
1529 increment_offset(l);
1531 if (instruction->times > 1) {
1532 lfmt->uplevel(LIST_TIMES, instruction->times);
1533 for (n = 2; n <= instruction->times; n++) {
1534 l = assemble(location.segment, location.offset,
1535 globalbits, instruction);
1536 increment_offset(l);
1538 lfmt->downlevel(LIST_TIMES);
1543 static void assemble_file(const char *fname, struct strlist *depend_list)
1545 char *line;
1546 insn output_ins;
1547 uint64_t prev_offset_changed;
1548 int64_t stall_count = 0; /* Make sure we make forward progress... */
1550 switch (cmd_sb) {
1551 case 16:
1552 break;
1553 case 32:
1554 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1555 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1556 break;
1557 case 64:
1558 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1559 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1560 break;
1561 default:
1562 panic();
1563 break;
1566 prev_offset_changed = INT64_MAX;
1568 if (listname && !keep_all) {
1569 /* Remove the list file in case we die before the output pass */
1570 remove(listname);
1573 while (!terminate_after_phase && !pass_final()) {
1574 _passn++;
1575 if (pass_type() != PASS_OPT || !global_offset_changed)
1576 _pass_type++;
1577 global_offset_changed = 0;
1580 * Create a warning buffer list unless we are in
1581 * pass 2 (everything will be emitted immediately in pass 2.)
1583 if (warn_list) {
1584 if (warn_list->nstr || pass_final())
1585 strlist_free(&warn_list);
1588 if (!pass_final() && !warn_list)
1589 warn_list = strlist_alloc(false);
1591 globalbits = cmd_sb; /* set 'bits' to command line default */
1592 cpu = cmd_cpu;
1593 if (listname) {
1594 if (pass_final() || list_on_every_pass()) {
1595 active_list_options = list_options;
1596 lfmt->init(listname);
1597 } else if (active_list_options) {
1599 * Looks like we used the list engine on a previous pass,
1600 * but now it is turned off, presumably via %pragma -p
1602 lfmt->cleanup();
1603 if (!keep_all)
1604 remove(listname);
1605 active_list_options = 0;
1609 in_absolute = false;
1610 if (!pass_first()) {
1611 saa_rewind(forwrefs);
1612 forwref = saa_rstruct(forwrefs);
1613 raa_free(offsets);
1614 offsets = raa_init();
1616 location.segment = NO_SEG;
1617 location.offset = 0;
1618 if (pass_first())
1619 location.known = true;
1620 ofmt->reset();
1621 switch_segment(ofmt->section(NULL, &globalbits));
1622 preproc->reset(fname, PP_NORMAL, pass_final() ? depend_list : NULL);
1624 globallineno = 0;
1626 while ((line = preproc->getline())) {
1627 if (++globallineno > nasm_limit[LIMIT_LINES])
1628 nasm_fatal("overall line count exceeds the maximum %"PRId64"\n",
1629 nasm_limit[LIMIT_LINES]);
1632 * Here we parse our directives; this is not handled by the
1633 * main parser.
1635 if (process_directives(line))
1636 goto end_of_line; /* Just do final cleanup */
1638 /* Not a directive, or even something that starts with [ */
1639 parse_line(line, &output_ins);
1640 forward_refs(&output_ins);
1641 process_insn(&output_ins);
1642 cleanup_insn(&output_ins);
1644 end_of_line:
1645 nasm_free(line);
1646 } /* end while (line = preproc->getline... */
1648 preproc->cleanup_pass();
1650 if (global_offset_changed) {
1651 switch (pass_type()) {
1652 case PASS_OPT:
1654 * This is the only pass type that can be executed more
1655 * than once, and therefore has the ability to stall.
1657 if (global_offset_changed < prev_offset_changed) {
1658 prev_offset_changed = global_offset_changed;
1659 stall_count = 0;
1660 } else {
1661 stall_count++;
1664 if (stall_count > nasm_limit[LIMIT_STALLED] ||
1665 pass_count() >= nasm_limit[LIMIT_PASSES]) {
1666 /* No convergence, almost certainly dead */
1667 nasm_nonfatalf(ERR_UNDEAD,
1668 "unable to find valid values for all labels "
1669 "after %"PRId64" passes; "
1670 "stalled for %"PRId64", giving up.",
1671 pass_count(), stall_count);
1672 nasm_nonfatalf(ERR_UNDEAD,
1673 "Possible causes: recursive EQUs, macro abuse.");
1675 break;
1677 case PASS_STAB:
1679 *!phase [off] phase error during stabilization
1680 *! warns about symbols having changed values during
1681 *! the second-to-last assembly pass. This is not
1682 *! inherently fatal, but may be a source of bugs.
1684 nasm_warn(WARN_PHASE|ERR_UNDEAD,
1685 "phase error during stabilization "
1686 "pass, hoping for the best");
1687 break;
1689 case PASS_FINAL:
1690 nasm_nonfatalf(ERR_UNDEAD,
1691 "phase error during code generation pass");
1692 break;
1694 default:
1695 /* This is normal, we'll keep going... */
1696 break;
1700 reset_warnings();
1703 if (opt_verbose_info && pass_final()) {
1704 /* -On and -Ov switches */
1705 nasm_info("assembly required 1+%"PRId64"+2 passes\n", pass_count()-3);
1708 lfmt->cleanup();
1709 strlist_free(&warn_list);
1713 * get warning index; 0 if this is non-suppressible.
1715 static size_t warn_index(errflags severity)
1717 size_t index;
1719 if ((severity & ERR_MASK) >= ERR_FATAL)
1720 return 0; /* Fatal errors are never suppressible */
1722 /* Warnings MUST HAVE a warning category specifier! */
1723 nasm_assert((severity & (ERR_MASK|WARN_MASK)) != ERR_WARNING);
1725 index = WARN_IDX(severity);
1726 nasm_assert(index < WARN_IDX_ALL);
1728 return index;
1731 static bool skip_this_pass(errflags severity)
1733 errflags type = severity & ERR_MASK;
1736 * See if it's a pass-specific error or warning which should be skipped.
1737 * We can never skip fatal errors as by definition they cannot be
1738 * resumed from.
1740 if (type >= ERR_FATAL)
1741 return false;
1744 * ERR_LISTMSG messages are always skipped; the list file
1745 * receives them anyway as this function is not consulted
1746 * for sending to the list file.
1748 if (type == ERR_LISTMSG)
1749 return true;
1751 /* This message not applicable unless pass_final */
1752 return (severity & ERR_PASS2) && !pass_final();
1756 * check for suppressed message (usually warnings or notes)
1758 * @param severity the severity of the warning or error
1759 * @return true if we should abort error/warning printing
1761 static bool is_suppressed(errflags severity)
1763 /* Fatal errors must never be suppressed */
1764 if ((severity & ERR_MASK) >= ERR_FATAL)
1765 return false;
1767 /* This error/warning is pointless if we are dead anyway */
1768 if ((severity & ERR_UNDEAD) && terminate_after_phase)
1769 return true;
1771 return !(warning_state[warn_index(severity)] & WARN_ST_ENABLED);
1775 * Return the true error type (the ERR_MASK part) of the given
1776 * severity, accounting for warnings that may need to be promoted to
1777 * error.
1779 * @param severity the severity of the warning or error
1780 * @return true if we should error out
1782 static errflags true_error_type(errflags severity)
1784 const uint8_t warn_is_err = WARN_ST_ENABLED|WARN_ST_ERROR;
1785 int type;
1787 type = severity & ERR_MASK;
1789 /* Promote warning to error? */
1790 if (type == ERR_WARNING) {
1791 uint8_t state = warning_state[warn_index(severity)];
1792 if ((state & warn_is_err) == warn_is_err)
1793 type = ERR_NONFATAL;
1796 return type;
1800 * common error reporting
1801 * This is the common back end of the error reporting schemes currently
1802 * implemented. It prints the nature of the warning and then the
1803 * specific error message to error_file and may or may not return. It
1804 * doesn't return if the error severity is a "panic" or "debug" type.
1806 * @param severity the severity of the warning or error
1807 * @param fmt the printf style format string
1809 static void nasm_verror_asm(errflags severity, const char *fmt, va_list args)
1811 char msg[1024];
1812 char warnsuf[64];
1813 char linestr[64];
1814 const char *pfx;
1815 errflags true_type = true_error_type(severity);
1816 const char *currentfile = NULL;
1817 int32_t lineno = 0;
1818 static const char * const pfx_table[ERR_MASK+1] = {
1819 ";;; ", "debug: ", "info: ", "warning: ",
1820 "error: ", "", "fatal: ", "panic: "
1823 if (is_suppressed(severity))
1824 return;
1826 if (!(severity & ERR_NOFILE)) {
1827 src_get(&lineno, &currentfile);
1828 if (!currentfile) {
1829 currentfile = currentfile ? currentfile :
1830 inname && inname[0] ? inname :
1831 outname && outname[0] ? outname :
1832 NULL;
1833 lineno = 0;
1837 if (severity & ERR_NO_SEVERITY)
1838 pfx = "";
1839 else
1840 pfx = pfx_table[true_type];
1842 vsnprintf(msg, sizeof msg, fmt, args);
1843 *warnsuf = 0;
1844 if ((severity & (ERR_MASK|ERR_HERE|ERR_PP_LISTMACRO)) == ERR_WARNING) {
1846 * It's a warning without ERR_HERE defined, and we are not already
1847 * unwinding the macros that led us here.
1849 snprintf(warnsuf, sizeof warnsuf, " [-w+%s%s]",
1850 (true_type >= ERR_NONFATAL) ? "error=" : "",
1851 warning_name[warn_index(severity)]);
1854 *linestr = 0;
1855 if (lineno) {
1856 snprintf(linestr, sizeof linestr, "%s%"PRId32"%s",
1857 errfmt->beforeline, lineno, errfmt->afterline);
1860 if (!skip_this_pass(severity)) {
1861 const char *file = currentfile ? currentfile : "nasm";
1862 const char *here = "";
1864 if (severity & ERR_HERE)
1865 here = currentfile ? " here" : " in an unknown location";
1867 if (warn_list && true_type < ERR_NONFATAL &&
1868 !(pass_first() && (severity & ERR_PASS1)))
1871 * Buffer up warnings until we either get an error
1872 * or we are on the code-generation pass.
1874 strlist_printf(warn_list, "%s%s%s%s%s%s%s",
1875 file, linestr, errfmt->beforemsg,
1876 pfx, msg, here, warnsuf);
1877 } else {
1879 * If we have buffered warnings, and this is a non-warning,
1880 * output them now.
1882 if (true_type >= ERR_NONFATAL && warn_list) {
1883 strlist_write(warn_list, "\n", error_file);
1884 strlist_free(&warn_list);
1887 fprintf(error_file, "%s%s%s%s%s%s%s\n",
1888 file, linestr, errfmt->beforemsg,
1889 pfx, msg, here, warnsuf);
1894 /* Are we recursing from error_list_macros? */
1895 if (severity & ERR_PP_LISTMACRO)
1896 return;
1899 * Don't suppress this with skip_this_pass(), or we don't get
1900 * pass1 or preprocessor warnings in the list file
1902 if (severity & ERR_HERE) {
1903 if (lineno)
1904 lfmt->error(severity, "%s%s at %s:%"PRId32"%s",
1905 pfx, msg, currentfile, lineno, warnsuf);
1906 else if (currentfile)
1907 lfmt->error(severity, "%s%s in file %s%s",
1908 pfx, msg, currentfile, warnsuf);
1909 else
1910 lfmt->error(severity, "%s%s in an unknown location%s",
1911 pfx, msg, warnsuf);
1912 } else {
1913 lfmt->error(severity, "%s%s%s", pfx, msg, warnsuf);
1916 if (skip_this_pass(severity))
1917 return;
1919 if (severity & ERR_USAGE)
1920 want_usage = true;
1922 /* error_list_macros can for obvious reasons not work with ERR_HERE */
1923 if (!(severity & ERR_HERE))
1924 preproc->error_list_macros(severity);
1926 switch (true_type) {
1927 case ERR_LISTMSG:
1928 case ERR_DEBUG:
1929 case ERR_INFO:
1930 case ERR_WARNING:
1931 /* no further action, by definition */
1932 break;
1933 case ERR_NONFATAL:
1934 terminate_after_phase = true;
1935 break;
1936 case ERR_FATAL:
1937 if (ofile) {
1938 fclose(ofile);
1939 if (!keep_all)
1940 remove(outname);
1941 ofile = NULL;
1943 if (want_usage)
1944 usage();
1945 exit(1); /* instantly die */
1946 break; /* placate silly compilers */
1947 case ERR_PANIC:
1948 fflush(NULL);
1950 if (abort_on_panic)
1951 abort(); /* halt, catch fire, dump core/stop debugger */
1953 if (ofile) {
1954 fclose(ofile);
1955 if (!keep_all)
1956 remove(outname);
1957 ofile = NULL;
1959 exit(3);
1960 break;
1961 default:
1962 break; /* ??? */
1966 static void usage(void)
1968 fprintf(error_file, "Type %s -h for help.\n", _progname);
1971 static void help(FILE *out)
1973 int i;
1975 fprintf(out,
1976 "Usage: %s [-@ response_file] [options...] [--] filename\n"
1977 " %s -v (or --v)\n",
1978 _progname, _progname);
1979 fputs(
1980 "\n"
1981 "Options (values in brackets indicate defaults):\n"
1982 "\n"
1983 " -h show this text and exit (also --help)\n"
1984 " -v (or --v) print the NASM version number and exit\n"
1985 " -@ file response file; one command line option per line\n"
1986 "\n"
1987 " -o outfile write output to outfile\n"
1988 " --keep-all output files will not be removed even if an error happens\n"
1989 "\n"
1990 " -Xformat specifiy error reporting format (gnu or vc)\n"
1991 " -s redirect error messages to stdout\n"
1992 " -Zfile redirect error messages to file\n"
1993 "\n"
1994 " -M generate Makefile dependencies on stdout\n"
1995 " -MG d:o, missing files assumed generated\n"
1996 " -MF file set Makefile dependency file\n"
1997 " -MD file assemble and generate dependencies\n"
1998 " -MT file dependency target name\n"
1999 " -MQ file dependency target name (quoted)\n"
2000 " -MP emit phony targets\n"
2001 "\n"
2002 " -f format select output file format\n"
2003 , out);
2004 ofmt_list(ofmt, out);
2005 fputs(
2006 "\n"
2007 " -g generate debugging information\n"
2008 " -F format select a debugging format (output format dependent)\n"
2009 " -gformat same as -g -F format\n"
2010 , out);
2011 dfmt_list(out);
2012 fputs(
2013 "\n"
2014 " -l listfile write listing to a list file\n"
2015 " -Lflags... add optional information to the list file\n"
2016 " -Lb show builtin macro packages (standard and %use)\n"
2017 " -Ld show byte and repeat counts in decimal, not hex\n"
2018 " -Le show the preprocessed output\n"
2019 " -Lf ignore .nolist (force output)\n"
2020 " -Lm show all single-line macro definitions\n"
2021 " -Lp output a list file every pass, in case of errors\n"
2022 "\n"
2023 " -Oflags... optimize opcodes, immediates and branch offsets\n"
2024 " -O0 no optimization\n"
2025 " -O1 minimal optimization\n"
2026 " -Ox multipass optimization (default)\n"
2027 " -Ov display the number of passes executed at the end\n"
2028 " -t assemble in limited SciTech TASM compatible mode\n"
2029 "\n"
2030 " -E (or -e) preprocess only (writes output to stdout by default)\n"
2031 " -a don't preprocess (assemble only)\n"
2032 " -Ipath add a pathname to the include file path\n"
2033 " -Pfile pre-include a file (also --include)\n"
2034 " -Dmacro[=str] pre-define a macro\n"
2035 " -Umacro undefine a macro\n"
2036 " --pragma str pre-executes a specific %%pragma\n"
2037 " --before str add line (usually a preprocessor statement) before the input\n"
2038 " --no-line ignore %line directives in input\n"
2039 "\n"
2040 " --prefix str prepend the given string to the names of all extern,\n"
2041 " common and global symbols (also --gprefix)\n"
2042 " --suffix str append the given string to the names of all extern,\n"
2043 " common and global symbols (also --gprefix)\n"
2044 " --lprefix str prepend the given string to local symbols\n"
2045 " --lpostfix str append the given string to local symbols\n"
2046 "\n"
2047 " -w+x enable warning x (also -Wx)\n"
2048 " -w-x disable warning x (also -Wno-x)\n"
2049 " -w[+-]error promote all warnings to errors (also -Werror)\n"
2050 " -w[+-]error=x promote warning x to errors (also -Werror=x)\n"
2051 , out);
2053 fprintf(out, " %-20s %s\n",
2054 warning_name[WARN_IDX_ALL], warning_help[WARN_IDX_ALL]);
2056 for (i = 1; i < WARN_IDX_ALL; i++) {
2057 const char *me = warning_name[i];
2058 const char *prev = warning_name[i-1];
2059 const char *next = warning_name[i+1];
2061 if (prev) {
2062 int prev_len = strlen(prev);
2063 const char *dash = me;
2065 while ((dash = strchr(dash+1, '-'))) {
2066 int prefix_len = dash - me; /* Not including final dash */
2067 if (strncmp(next, me, prefix_len+1)) {
2068 /* Only one or last option with this prefix */
2069 break;
2071 if (prefix_len >= prev_len ||
2072 strncmp(prev, me, prefix_len) ||
2073 (prev[prefix_len] != '-' && prev[prefix_len] != '\0')) {
2074 /* This prefix is different from the previous option */
2075 fprintf(out, " %-20.*s all warnings prefixed with \"%.*s\"\n",
2076 prefix_len, me, prefix_len+1, me);
2081 fprintf(out, " %-20s %s%s\n",
2082 warning_name[i], warning_help[i],
2083 (warning_default[i] & WARN_ST_ERROR) ? " [error]" :
2084 (warning_default[i] & WARN_ST_ENABLED) ? " [on]" : " [off]");
2087 fputs(
2088 "\n"
2089 " --limit-X val set execution limit X\n"
2090 , out);
2093 for (i = 0; i <= LIMIT_MAX; i++) {
2094 fprintf(out, " %-20s %s [",
2095 limit_info[i].name, limit_info[i].help);
2096 if (nasm_limit[i] < LIMIT_MAX_VAL) {
2097 fprintf(out, "%"PRId64"]\n", nasm_limit[i]);
2098 } else {
2099 fputs("unlimited]\n", out);