elf: fix "object" symbol keyword
[nasm.git] / asm / nasm.c
blob07a360b2db32f24f8c58a2c3712baad83b995c97
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 usage(void);
78 static void help(FILE *);
80 struct error_format {
81 const char *beforeline; /* Before line number, if present */
82 const char *afterline; /* After line number, if present */
83 const char *beforemsg; /* Before actual message */
86 static const struct error_format errfmt_gnu = { ":", "", ": " };
87 static const struct error_format errfmt_msvc = { "(", ")", " : " };
88 static const struct error_format *errfmt = &errfmt_gnu;
89 static struct strlist *warn_list;
91 unsigned int debug_nasm; /* Debugging messages? */
93 static bool using_debug_info, opt_verbose_info;
94 static const char *debug_format;
96 #ifndef ABORT_ON_PANIC
97 # define ABORT_ON_PANIC 0
98 #endif
99 static bool abort_on_panic = ABORT_ON_PANIC;
100 static bool keep_all;
102 bool tasm_compatible_mode = false;
103 enum pass_type _pass_type;
104 const char * const _pass_types[] =
106 "init", "first", "optimize", "stabilize", "final"
108 int64_t _passn;
109 int globalrel = 0;
110 int globalbnd = 0;
112 struct compile_time official_compile_time;
114 const char *inname;
115 const char *outname;
116 static const char *listname;
117 static const char *errname;
119 static int64_t globallineno; /* for forward-reference tracking */
121 const struct ofmt *ofmt = &OF_DEFAULT;
122 const struct ofmt_alias *ofmt_alias = NULL;
123 const struct dfmt *dfmt;
125 FILE *error_file; /* Where to write error messages */
127 FILE *ofile = NULL;
128 struct optimization optimizing =
129 { MAX_OPTIMIZE, OPTIM_ALL_ENABLED }; /* number of optimization passes to take */
130 static int cmd_sb = 16; /* by default */
132 iflag_t cpu;
133 static iflag_t cmd_cpu;
135 struct location location;
136 bool in_absolute; /* Flag we are in ABSOLUTE seg */
137 struct location absolute; /* Segment/offset inside ABSOLUTE */
139 static struct RAA *offsets;
141 static struct SAA *forwrefs; /* keep track of forward references */
142 static const struct forwrefinfo *forwref;
144 static const struct preproc_ops *preproc;
145 static struct strlist *include_path;
146 bool pp_noline; /* Ignore %line directives */
148 #define OP_NORMAL (1U << 0)
149 #define OP_PREPROCESS (1U << 1)
150 #define OP_DEPEND (1U << 2)
152 static unsigned int operating_mode;
154 /* Dependency flags */
155 static bool depend_emit_phony = false;
156 static bool depend_missing_ok = false;
157 static const char *depend_target = NULL;
158 static const char *depend_file = NULL;
159 struct strlist *depend_list;
161 static bool want_usage;
162 static bool terminate_after_phase;
163 bool user_nolist = false;
165 static char *quote_for_pmake(const char *str);
166 static char *quote_for_wmake(const char *str);
167 static char *(*quote_for_make)(const char *) = quote_for_pmake;
170 * Execution limits that can be set via a command-line option or %pragma
174 * This is really unlimited; it would take far longer than the
175 * current age of the universe for this limit to be reached even on
176 * much faster CPUs than currently exist.
178 #define LIMIT_MAX_VAL (INT64_MAX >> 1)
180 int64_t nasm_limit[LIMIT_MAX+1];
182 struct limit_info {
183 const char *name;
184 const char *help;
185 int64_t default_val;
187 /* The order here must match enum nasm_limit in nasm.h */
188 static const struct limit_info limit_info[LIMIT_MAX+1] = {
189 { "passes", "total number of passes", LIMIT_MAX_VAL },
190 { "stalled-passes", "number of passes without forward progress", 1000 },
191 { "macro-levels", "levels of macro expansion", 10000 },
192 { "macro-tokens", "tokens processed during single-lime macro expansion", 10000000 },
193 { "mmacros", "multi-line macros before final return", 100000 },
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 if (!limit)
215 limit = "";
216 if (!valstr)
217 valstr = "";
219 for (i = 0; i <= LIMIT_MAX; i++) {
220 if (!nasm_stricmp(limit, limit_info[i].name))
221 break;
223 if (i > LIMIT_MAX) {
224 if (not_started())
225 errlevel = ERR_WARNING|WARN_OTHER|ERR_USAGE;
226 else
227 errlevel = ERR_WARNING|WARN_PRAGMA_UNKNOWN;
228 nasm_error(errlevel, "unknown limit: `%s'", limit);
229 return DIRR_ERROR;
232 if (!nasm_stricmp(valstr, "unlimited")) {
233 val = LIMIT_MAX_VAL;
234 } else {
235 val = readnum(valstr, &rn_error);
236 if (rn_error || val < 0) {
237 if (not_started())
238 errlevel = ERR_WARNING|WARN_OTHER|ERR_USAGE;
239 else
240 errlevel = ERR_WARNING|WARN_PRAGMA_BAD;
241 nasm_error(errlevel, "invalid limit value: `%s'", valstr);
242 return DIRR_ERROR;
244 if (val > LIMIT_MAX_VAL)
245 val = LIMIT_MAX_VAL;
248 nasm_limit[i] = val;
249 return DIRR_OK;
252 int64_t switch_segment(int32_t segment)
254 location.segment = segment;
255 if (segment == NO_SEG) {
256 location.offset = absolute.offset;
257 in_absolute = true;
258 } else {
259 location.offset = raa_read(offsets, segment);
260 in_absolute = false;
262 return location.offset;
265 static void set_curr_offs(int64_t l_off)
267 if (in_absolute)
268 absolute.offset = l_off;
269 else
270 offsets = raa_write(offsets, location.segment, l_off);
273 static void increment_offset(int64_t delta)
275 if (unlikely(delta == 0))
276 return;
278 location.offset += delta;
279 set_curr_offs(location.offset);
282 static void nasm_fputs(const char *line, FILE * outfile)
284 if (outfile) {
285 fputs(line, outfile);
286 putc('\n', outfile);
287 } else
288 puts(line);
292 * Define system-defined macros that are not part of
293 * macros/standard.mac.
295 static void define_macros(void)
297 const struct compile_time * const oct = &official_compile_time;
298 char temp[128];
300 if (oct->have_local) {
301 strftime(temp, sizeof temp, "__?DATE?__=\"%Y-%m-%d\"", &oct->local);
302 preproc->pre_define(temp);
303 strftime(temp, sizeof temp, "__?DATE_NUM?__=%Y%m%d", &oct->local);
304 preproc->pre_define(temp);
305 strftime(temp, sizeof temp, "__?TIME?__=\"%H:%M:%S\"", &oct->local);
306 preproc->pre_define(temp);
307 strftime(temp, sizeof temp, "__?TIME_NUM?__=%H%M%S", &oct->local);
308 preproc->pre_define(temp);
311 if (oct->have_gm) {
312 strftime(temp, sizeof temp, "__?UTC_DATE?__=\"%Y-%m-%d\"", &oct->gm);
313 preproc->pre_define(temp);
314 strftime(temp, sizeof temp, "__?UTC_DATE_NUM?__=%Y%m%d", &oct->gm);
315 preproc->pre_define(temp);
316 strftime(temp, sizeof temp, "__?UTC_TIME?__=\"%H:%M:%S\"", &oct->gm);
317 preproc->pre_define(temp);
318 strftime(temp, sizeof temp, "__?UTC_TIME_NUM?__=%H%M%S", &oct->gm);
319 preproc->pre_define(temp);
322 if (oct->have_posix) {
323 snprintf(temp, sizeof temp, "__?POSIX_TIME?__=%"PRId64, oct->posix);
324 preproc->pre_define(temp);
328 * In case if output format is defined by alias
329 * we have to put shortname of the alias itself here
330 * otherwise ABI backward compatibility gets broken.
332 snprintf(temp, sizeof(temp), "__?OUTPUT_FORMAT?__=%s",
333 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
334 preproc->pre_define(temp);
337 * Output-format specific macros.
339 if (ofmt->stdmac)
340 preproc->extra_stdmac(ofmt->stdmac);
343 * Debug format, if any
345 if (dfmt != &null_debug_form) {
346 snprintf(temp, sizeof(temp), "__?DEBUG_FORMAT?__=%s", dfmt->shortname);
347 preproc->pre_define(temp);
352 * Initialize the preprocessor, set up the include path, and define
353 * the system-included macros. This is called between passes 1 and 2
354 * of parsing the command options; ofmt and dfmt are defined at this
355 * point.
357 * Command-line specified preprocessor directives (-p, -d, -u,
358 * --pragma, --before) are processed after this function.
360 static void preproc_init(struct strlist *ipath)
362 preproc->init();
363 define_macros();
364 preproc->include_path(ipath);
367 static void emit_dependencies(struct strlist *list)
369 FILE *deps;
370 int linepos, len;
371 bool wmake = (quote_for_make == quote_for_wmake);
372 const char *wrapstr, *nulltarget;
373 const struct strlist_entry *l;
375 if (!list)
376 return;
378 wrapstr = wmake ? " &\n " : " \\\n ";
379 nulltarget = wmake ? "\t%null\n" : "";
381 if (depend_file && strcmp(depend_file, "-")) {
382 deps = nasm_open_write(depend_file, NF_TEXT);
383 if (!deps) {
384 nasm_nonfatal("unable to write dependency file `%s'", depend_file);
385 return;
387 } else {
388 deps = stdout;
391 linepos = fprintf(deps, "%s :", depend_target);
392 strlist_for_each(l, list) {
393 char *file = quote_for_make(l->str);
394 len = strlen(file);
395 if (linepos + len > 62 && linepos > 1) {
396 fputs(wrapstr, deps);
397 linepos = 1;
399 fprintf(deps, " %s", file);
400 linepos += len+1;
401 nasm_free(file);
403 fputs("\n\n", deps);
405 strlist_for_each(l, list) {
406 if (depend_emit_phony) {
407 char *file = quote_for_make(l->str);
408 fprintf(deps, "%s :\n%s\n", file, nulltarget);
409 nasm_free(file);
413 strlist_free(&list);
415 if (deps != stdout)
416 fclose(deps);
419 /* Convert a struct tm to a POSIX-style time constant */
420 static int64_t make_posix_time(const struct tm *tm)
422 int64_t t;
423 int64_t y = tm->tm_year;
425 /* See IEEE 1003.1:2004, section 4.14 */
427 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
428 t += tm->tm_yday;
429 t *= 24;
430 t += tm->tm_hour;
431 t *= 60;
432 t += tm->tm_min;
433 t *= 60;
434 t += tm->tm_sec;
436 return t;
439 static void timestamp(void)
441 struct compile_time * const oct = &official_compile_time;
442 const struct tm *tp, *best_gm;
444 time(&oct->t);
446 best_gm = NULL;
448 tp = localtime(&oct->t);
449 if (tp) {
450 oct->local = *tp;
451 best_gm = &oct->local;
452 oct->have_local = true;
455 tp = gmtime(&oct->t);
456 if (tp) {
457 oct->gm = *tp;
458 best_gm = &oct->gm;
459 oct->have_gm = true;
460 if (!oct->have_local)
461 oct->local = oct->gm;
462 } else {
463 oct->gm = oct->local;
466 if (best_gm) {
467 oct->posix = make_posix_time(best_gm);
468 oct->have_posix = true;
472 int main(int argc, char **argv)
474 /* Do these as early as possible */
475 error_file = stderr;
476 _progname = argv[0];
477 if (!_progname || !_progname[0])
478 _progname = "nasm";
480 timestamp();
482 iflag_set_default_cpu(&cpu);
483 iflag_set_default_cpu(&cmd_cpu);
485 set_default_limits();
487 include_path = strlist_alloc(true);
489 _pass_type = PASS_INIT;
490 _passn = 0;
492 want_usage = terminate_after_phase = false;
494 nasm_ctype_init();
495 src_init();
498 * We must call init_labels() before the command line parsing,
499 * because we may be setting prefixes/suffixes from the command
500 * line.
502 init_labels();
504 offsets = raa_init();
505 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
507 preproc = &nasmpp;
508 operating_mode = OP_NORMAL;
510 parse_cmdline(argc, argv, 1);
511 if (terminate_after_phase) {
512 if (want_usage)
513 usage();
514 return 1;
517 /* At this point we have ofmt and the name of the desired debug format */
518 if (!using_debug_info) {
519 /* No debug info, redirect to the null backend (empty stubs) */
520 dfmt = &null_debug_form;
521 } else if (!debug_format) {
522 /* Default debug format for this backend */
523 dfmt = ofmt->default_dfmt;
524 } else {
525 dfmt = dfmt_find(ofmt, debug_format);
526 if (!dfmt) {
527 nasm_fatalf(ERR_USAGE, "unrecognized debug format `%s' for output format `%s'",
528 debug_format, ofmt->shortname);
532 preproc_init(include_path);
534 parse_cmdline(argc, argv, 2);
535 if (terminate_after_phase) {
536 if (want_usage)
537 usage();
538 return 1;
541 /* Save away the default state of warnings */
542 init_warnings();
544 /* Dependency filename if we are also doing other things */
545 if (!depend_file && (operating_mode & ~OP_DEPEND)) {
546 if (outname)
547 depend_file = nasm_strcat(outname, ".d");
548 else
549 depend_file = filename_set_extension(inname, ".d");
553 * If no output file name provided and this
554 * is preprocess mode, we're perfectly
555 * fine to output into stdout.
557 if (!outname && !(operating_mode & OP_PREPROCESS)) {
558 outname = filename_set_extension(inname, ofmt->extension);
559 if (!strcmp(outname, inname)) {
560 outname = "nasm.out";
561 nasm_warn(WARN_OTHER, "default output file same as input, using `%s' for output\n", outname);
565 depend_list = (operating_mode & OP_DEPEND) ? strlist_alloc(true) : NULL;
567 if (!depend_target)
568 depend_target = quote_for_make(outname);
570 if (!(operating_mode & (OP_PREPROCESS|OP_NORMAL))) {
571 char *line;
573 if (depend_missing_ok)
574 preproc->include_path(NULL); /* "assume generated" */
576 preproc->reset(inname, PP_DEPS, depend_list);
577 ofile = NULL;
578 while ((line = preproc->getline()))
579 nasm_free(line);
580 preproc->cleanup_pass();
581 reset_warnings();
582 } else if (operating_mode & OP_PREPROCESS) {
583 char *line;
584 const char *file_name = NULL;
585 int32_t prior_linnum = 0;
586 int lineinc = 0;
588 if (outname) {
589 ofile = nasm_open_write(outname, NF_TEXT);
590 if (!ofile)
591 nasm_fatal("unable to open output file `%s'", outname);
592 } else
593 ofile = NULL;
595 location.known = false;
597 _pass_type = PASS_FIRST; /* We emulate this assembly pass */
598 preproc->reset(inname, PP_PREPROC, depend_list);
600 while ((line = preproc->getline())) {
602 * We generate %line directives if needed for later programs
604 int32_t linnum = prior_linnum += lineinc;
605 int altline = src_get(&linnum, &file_name);
606 if (altline) {
607 if (altline == 1 && lineinc == 1)
608 nasm_fputs("", ofile);
609 else {
610 lineinc = (altline != -1 || lineinc != 1);
611 fprintf(ofile ? ofile : stdout,
612 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
613 file_name);
615 prior_linnum = linnum;
617 nasm_fputs(line, ofile);
618 nasm_free(line);
620 preproc->cleanup_pass();
621 reset_warnings();
622 if (ofile)
623 fclose(ofile);
624 if (ofile && terminate_after_phase && !keep_all)
625 remove(outname);
626 ofile = NULL;
629 if (operating_mode & OP_NORMAL) {
630 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
631 if (!ofile)
632 nasm_fatal("unable to open output file `%s'", outname);
634 ofmt->init();
635 dfmt->init();
637 assemble_file(inname, depend_list);
639 if (!terminate_after_phase) {
640 ofmt->cleanup();
641 cleanup_labels();
642 fflush(ofile);
643 if (ferror(ofile))
644 nasm_nonfatal("write error on output file `%s'", outname);
647 if (ofile) {
648 fclose(ofile);
649 if (terminate_after_phase && !keep_all)
650 remove(outname);
651 ofile = NULL;
655 preproc->cleanup_session();
657 if (depend_list && !terminate_after_phase)
658 emit_dependencies(depend_list);
660 if (want_usage)
661 usage();
663 raa_free(offsets);
664 saa_free(forwrefs);
665 eval_cleanup();
666 stdscan_cleanup();
667 src_free();
668 strlist_free(&include_path);
670 return terminate_after_phase;
674 * Get a parameter for a command line option.
675 * First arg must be in the form of e.g. -f...
677 static char *get_param(char *p, char *q, bool *advance)
679 *advance = false;
680 if (p[2]) /* the parameter's in the option */
681 return nasm_skip_spaces(p + 2);
682 if (q && q[0]) {
683 *advance = true;
684 return q;
686 nasm_nonfatalf(ERR_USAGE, "option `-%c' requires an argument", p[1]);
687 return NULL;
691 * Copy a filename
693 static void copy_filename(const char **dst, const char *src, const char *what)
695 if (*dst)
696 nasm_fatal("more than one %s file specified: %s\n", what, src);
698 *dst = nasm_strdup(src);
702 * Convert a string to a POSIX make-safe form
704 static char *quote_for_pmake(const char *str)
706 const char *p;
707 char *os, *q;
709 size_t n = 1; /* Terminating zero */
710 size_t nbs = 0;
712 if (!str)
713 return NULL;
715 for (p = str; *p; p++) {
716 switch (*p) {
717 case ' ':
718 case '\t':
719 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
720 n += nbs + 2;
721 nbs = 0;
722 break;
723 case '$':
724 case '#':
725 nbs = 0;
726 n += 2;
727 break;
728 case '\\':
729 nbs++;
730 n++;
731 break;
732 default:
733 nbs = 0;
734 n++;
735 break;
739 /* Convert N backslashes at the end of filename to 2N backslashes */
740 if (nbs)
741 n += nbs;
743 os = q = nasm_malloc(n);
745 nbs = 0;
746 for (p = str; *p; p++) {
747 switch (*p) {
748 case ' ':
749 case '\t':
750 while (nbs--)
751 *q++ = '\\';
752 *q++ = '\\';
753 *q++ = *p;
754 break;
755 case '$':
756 *q++ = *p;
757 *q++ = *p;
758 nbs = 0;
759 break;
760 case '#':
761 *q++ = '\\';
762 *q++ = *p;
763 nbs = 0;
764 break;
765 case '\\':
766 *q++ = *p;
767 nbs++;
768 break;
769 default:
770 *q++ = *p;
771 nbs = 0;
772 break;
775 while (nbs--)
776 *q++ = '\\';
778 *q = '\0';
780 return os;
784 * Convert a string to a Watcom make-safe form
786 static char *quote_for_wmake(const char *str)
788 const char *p;
789 char *os, *q;
790 bool quote = false;
792 size_t n = 1; /* Terminating zero */
794 if (!str)
795 return NULL;
797 for (p = str; *p; p++) {
798 switch (*p) {
799 case ' ':
800 case '\t':
801 case '&':
802 quote = true;
803 n++;
804 break;
805 case '\"':
806 quote = true;
807 n += 2;
808 break;
809 case '$':
810 case '#':
811 n += 2;
812 break;
813 default:
814 n++;
815 break;
819 if (quote)
820 n += 2;
822 os = q = nasm_malloc(n);
824 if (quote)
825 *q++ = '\"';
827 for (p = str; *p; p++) {
828 switch (*p) {
829 case '$':
830 case '#':
831 *q++ = '$';
832 *q++ = *p;
833 break;
834 case '\"':
835 *q++ = *p;
836 *q++ = *p;
837 break;
838 default:
839 *q++ = *p;
840 break;
844 if (quote)
845 *q++ = '\"';
847 *q = '\0';
849 return os;
852 enum text_options {
853 OPT_BOGUS,
854 OPT_VERSION,
855 OPT_HELP,
856 OPT_ABORT_ON_PANIC,
857 OPT_MANGLE,
858 OPT_INCLUDE,
859 OPT_PRAGMA,
860 OPT_BEFORE,
861 OPT_LIMIT,
862 OPT_KEEP_ALL,
863 OPT_NO_LINE,
864 OPT_DEBUG
866 enum need_arg {
867 ARG_NO,
868 ARG_YES,
869 ARG_MAYBE
872 struct textargs {
873 const char *label;
874 enum text_options opt;
875 enum need_arg need_arg;
876 int pvt;
878 static const struct textargs textopts[] = {
879 {"v", OPT_VERSION, ARG_NO, 0},
880 {"version", OPT_VERSION, ARG_NO, 0},
881 {"help", OPT_HELP, ARG_NO, 0},
882 {"abort-on-panic", OPT_ABORT_ON_PANIC, ARG_NO, 0},
883 {"prefix", OPT_MANGLE, ARG_YES, LM_GPREFIX},
884 {"postfix", OPT_MANGLE, ARG_YES, LM_GSUFFIX},
885 {"gprefix", OPT_MANGLE, ARG_YES, LM_GPREFIX},
886 {"gpostfix", OPT_MANGLE, ARG_YES, LM_GSUFFIX},
887 {"lprefix", OPT_MANGLE, ARG_YES, LM_LPREFIX},
888 {"lpostfix", OPT_MANGLE, ARG_YES, LM_LSUFFIX},
889 {"include", OPT_INCLUDE, ARG_YES, 0},
890 {"pragma", OPT_PRAGMA, ARG_YES, 0},
891 {"before", OPT_BEFORE, ARG_YES, 0},
892 {"limit-", OPT_LIMIT, ARG_YES, 0},
893 {"keep-all", OPT_KEEP_ALL, ARG_NO, 0},
894 {"no-line", OPT_NO_LINE, ARG_NO, 0},
895 {"debug", OPT_DEBUG, ARG_MAYBE, 0},
896 {NULL, OPT_BOGUS, ARG_NO, 0}
899 static void show_version(void)
901 printf("NASM version %s compiled on %s%s\n",
902 nasm_version, nasm_date, nasm_compile_options);
903 exit(0);
906 static bool stopoptions = false;
907 static bool process_arg(char *p, char *q, int pass)
909 char *param;
910 bool advance = false;
912 if (!p || !p[0])
913 return false;
915 if (p[0] == '-' && !stopoptions) {
916 if (strchr("oOfpPdDiIlLFXuUZwW", p[1])) {
917 /* These parameters take values */
918 if (!(param = get_param(p, q, &advance)))
919 return advance;
922 switch (p[1]) {
923 case 's':
924 if (pass == 1)
925 error_file = stdout;
926 break;
928 case 'o': /* output file */
929 if (pass == 2)
930 copy_filename(&outname, param, "output");
931 break;
933 case 'f': /* output format */
934 if (pass == 1) {
935 ofmt = ofmt_find(param, &ofmt_alias);
936 if (!ofmt) {
937 nasm_fatalf(ERR_USAGE, "unrecognised output format `%s' - use -hf for a list", param);
940 break;
942 case 'O': /* Optimization level */
943 if (pass == 1) {
944 int opt;
946 if (!*param) {
947 /* Naked -O == -Ox */
948 optimizing.level = MAX_OPTIMIZE;
949 } else {
950 while (*param) {
951 switch (*param) {
952 case '0': case '1': case '2': case '3': case '4':
953 case '5': case '6': case '7': case '8': case '9':
954 opt = strtoul(param, &param, 10);
956 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
957 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
958 if (opt < 2)
959 optimizing.level = opt - 1;
960 else
961 optimizing.level = opt;
962 break;
964 case 'v':
965 case '+':
966 param++;
967 opt_verbose_info = true;
968 break;
970 case 'x':
971 param++;
972 optimizing.level = MAX_OPTIMIZE;
973 break;
975 default:
976 nasm_fatal("unknown optimization option -O%c\n",
977 *param);
978 break;
981 if (optimizing.level > MAX_OPTIMIZE)
982 optimizing.level = MAX_OPTIMIZE;
985 break;
987 case 'p': /* pre-include */
988 case 'P':
989 if (pass == 2)
990 preproc->pre_include(param);
991 break;
993 case 'd': /* pre-define */
994 case 'D':
995 if (pass == 2)
996 preproc->pre_define(param);
997 break;
999 case 'u': /* un-define */
1000 case 'U':
1001 if (pass == 2)
1002 preproc->pre_undefine(param);
1003 break;
1005 case 'i': /* include search path */
1006 case 'I':
1007 if (pass == 1)
1008 strlist_add(include_path, param);
1009 break;
1011 case 'l': /* listing file */
1012 if (pass == 2)
1013 copy_filename(&listname, param, "listing");
1014 break;
1016 case 'L': /* listing options */
1017 if (pass == 2) {
1018 while (*param)
1019 list_options |= list_option_mask(*param++);
1021 break;
1023 case 'Z': /* error messages file */
1024 if (pass == 1)
1025 copy_filename(&errname, param, "error");
1026 break;
1028 case 'F': /* specify debug format */
1029 if (pass == 1) {
1030 using_debug_info = true;
1031 debug_format = param;
1033 break;
1035 case 'X': /* specify error reporting format */
1036 if (pass == 1) {
1037 if (!nasm_stricmp("vc", param) || !nasm_stricmp("msvc", param) || !nasm_stricmp("ms", param))
1038 errfmt = &errfmt_msvc;
1039 else if (!nasm_stricmp("gnu", param) || !nasm_stricmp("gcc", param))
1040 errfmt = &errfmt_gnu;
1041 else
1042 nasm_fatalf(ERR_USAGE, "unrecognized error reporting format `%s'", param);
1044 break;
1046 case 'g':
1047 if (pass == 1) {
1048 using_debug_info = true;
1049 if (p[2])
1050 debug_format = nasm_skip_spaces(p + 2);
1052 break;
1054 case 'h':
1055 help(stdout);
1056 exit(0); /* never need usage message here */
1057 break;
1059 case 'y':
1060 /* legacy option */
1061 dfmt_list(stdout);
1062 exit(0);
1063 break;
1065 case 't':
1066 if (pass == 2) {
1067 tasm_compatible_mode = true;
1068 nasm_ctype_tasm_mode();
1070 break;
1072 case 'v':
1073 show_version();
1074 break;
1076 case 'e': /* preprocess only */
1077 case 'E':
1078 if (pass == 1)
1079 operating_mode = OP_PREPROCESS;
1080 break;
1082 case 'a': /* assemble only - don't preprocess */
1083 if (pass == 1)
1084 preproc = &preproc_nop;
1085 break;
1087 case 'w':
1088 case 'W':
1089 if (pass == 2)
1090 set_warning_status(param);
1091 break;
1093 case 'M':
1094 if (pass == 1) {
1095 switch (p[2]) {
1096 case 'W':
1097 quote_for_make = quote_for_wmake;
1098 break;
1099 case 'D':
1100 case 'F':
1101 case 'T':
1102 case 'Q':
1103 advance = true;
1104 break;
1105 default:
1106 break;
1108 } else {
1109 switch (p[2]) {
1110 case 0:
1111 operating_mode = OP_DEPEND;
1112 break;
1113 case 'G':
1114 operating_mode = OP_DEPEND;
1115 depend_missing_ok = true;
1116 break;
1117 case 'P':
1118 depend_emit_phony = true;
1119 break;
1120 case 'D':
1121 operating_mode |= OP_DEPEND;
1122 if (q && (q[0] != '-' || q[1] == '\0')) {
1123 depend_file = q;
1124 advance = true;
1126 break;
1127 case 'F':
1128 depend_file = q;
1129 advance = true;
1130 break;
1131 case 'T':
1132 depend_target = q;
1133 advance = true;
1134 break;
1135 case 'Q':
1136 depend_target = quote_for_make(q);
1137 advance = true;
1138 break;
1139 case 'W':
1140 /* handled in pass 1 */
1141 break;
1142 default:
1143 nasm_nonfatalf(ERR_USAGE, "unknown dependency option `-M%c'", p[2]);
1144 break;
1147 if (advance && (!q || !q[0])) {
1148 nasm_nonfatalf(ERR_USAGE, "option `-M%c' requires a parameter", p[2]);
1149 break;
1151 break;
1153 case '-':
1155 const struct textargs *tx;
1156 size_t olen, plen;
1157 char *eqsave;
1158 enum text_options opt;
1160 p += 2;
1162 if (!*p) { /* -- => stop processing options */
1163 stopoptions = true;
1164 break;
1167 olen = 0; /* Placate gcc at lower optimization levels */
1168 plen = strlen(p);
1169 for (tx = textopts; tx->label; tx++) {
1170 olen = strlen(tx->label);
1172 if (olen > plen)
1173 continue;
1175 if (nasm_memicmp(p, tx->label, olen))
1176 continue;
1178 if (tx->label[olen-1] == '-')
1179 break; /* Incomplete option */
1181 if (!p[olen] || p[olen] == '=')
1182 break; /* Complete option */
1185 if (!tx->label) {
1186 nasm_nonfatalf(ERR_USAGE, "unrecognized option `--%s'", p);
1189 opt = tx->opt;
1191 eqsave = param = strchr(p+olen, '=');
1192 if (param)
1193 *param++ = '\0';
1195 switch (tx->need_arg) {
1196 case ARG_YES: /* Argument required, and may be standalone */
1197 if (!param) {
1198 param = q;
1199 advance = true;
1202 /* Note: a null string is a valid parameter */
1203 if (!param) {
1204 nasm_nonfatalf(ERR_USAGE, "option `--%s' requires an argument", p);
1205 opt = OPT_BOGUS;
1207 break;
1209 case ARG_NO: /* Argument prohibited */
1210 if (param) {
1211 nasm_nonfatalf(ERR_USAGE, "option `--%s' does not take an argument", p);
1212 opt = OPT_BOGUS;
1214 break;
1216 case ARG_MAYBE: /* Argument permitted, but must be attached with = */
1217 break;
1220 switch (opt) {
1221 case OPT_BOGUS:
1222 break; /* We have already errored out */
1223 case OPT_VERSION:
1224 show_version();
1225 break;
1226 case OPT_ABORT_ON_PANIC:
1227 abort_on_panic = true;
1228 break;
1229 case OPT_MANGLE:
1230 if (pass == 2)
1231 set_label_mangle(tx->pvt, param);
1232 break;
1233 case OPT_INCLUDE:
1234 if (pass == 2)
1235 preproc->pre_include(q);
1236 break;
1237 case OPT_PRAGMA:
1238 if (pass == 2)
1239 preproc->pre_command("pragma", param);
1240 break;
1241 case OPT_BEFORE:
1242 if (pass == 2)
1243 preproc->pre_command(NULL, param);
1244 break;
1245 case OPT_LIMIT:
1246 if (pass == 1)
1247 nasm_set_limit(p+olen, param);
1248 break;
1249 case OPT_KEEP_ALL:
1250 keep_all = true;
1251 break;
1252 case OPT_NO_LINE:
1253 pp_noline = true;
1254 break;
1255 case OPT_DEBUG:
1256 debug_nasm = param ? strtoul(param, NULL, 10) : debug_nasm+1;
1257 break;
1258 case OPT_HELP:
1259 help(stdout);
1260 exit(0);
1261 default:
1262 panic();
1265 if (eqsave)
1266 *eqsave = '='; /* Restore = argument separator */
1268 break;
1271 default:
1272 nasm_nonfatalf(ERR_USAGE, "unrecognised option `-%c'", p[1]);
1273 break;
1275 } else if (pass == 2) {
1276 /* In theory we could allow multiple input files... */
1277 copy_filename(&inname, p, "input");
1280 return advance;
1283 #define ARG_BUF_DELTA 128
1285 static void process_respfile(FILE * rfile, int pass)
1287 char *buffer, *p, *q, *prevarg;
1288 int bufsize, prevargsize;
1290 bufsize = prevargsize = ARG_BUF_DELTA;
1291 buffer = nasm_malloc(ARG_BUF_DELTA);
1292 prevarg = nasm_malloc(ARG_BUF_DELTA);
1293 prevarg[0] = '\0';
1295 while (1) { /* Loop to handle all lines in file */
1296 p = buffer;
1297 while (1) { /* Loop to handle long lines */
1298 q = fgets(p, bufsize - (p - buffer), rfile);
1299 if (!q)
1300 break;
1301 p += strlen(p);
1302 if (p > buffer && p[-1] == '\n')
1303 break;
1304 if (p - buffer > bufsize - 10) {
1305 int offset;
1306 offset = p - buffer;
1307 bufsize += ARG_BUF_DELTA;
1308 buffer = nasm_realloc(buffer, bufsize);
1309 p = buffer + offset;
1313 if (!q && p == buffer) {
1314 if (prevarg[0])
1315 process_arg(prevarg, NULL, pass);
1316 nasm_free(buffer);
1317 nasm_free(prevarg);
1318 return;
1322 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1323 * them are present at the end of the line.
1325 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1327 while (p > buffer && nasm_isspace(p[-1]))
1328 *--p = '\0';
1330 p = nasm_skip_spaces(buffer);
1332 if (process_arg(prevarg, p, pass))
1333 *p = '\0';
1335 if ((int) strlen(p) > prevargsize - 10) {
1336 prevargsize += ARG_BUF_DELTA;
1337 prevarg = nasm_realloc(prevarg, prevargsize);
1339 strncpy(prevarg, p, prevargsize);
1343 /* Function to process args from a string of args, rather than the
1344 * argv array. Used by the environment variable and response file
1345 * processing.
1347 static void process_args(char *args, int pass)
1349 char *p, *q, *arg, *prevarg;
1350 char separator = ' ';
1352 p = args;
1353 if (*p && *p != '-')
1354 separator = *p++;
1355 arg = NULL;
1356 while (*p) {
1357 q = p;
1358 while (*p && *p != separator)
1359 p++;
1360 while (*p == separator)
1361 *p++ = '\0';
1362 prevarg = arg;
1363 arg = q;
1364 if (process_arg(prevarg, arg, pass))
1365 arg = NULL;
1367 if (arg)
1368 process_arg(arg, NULL, pass);
1371 static void process_response_file(const char *file, int pass)
1373 char str[2048];
1374 FILE *f = nasm_open_read(file, NF_TEXT);
1375 if (!f) {
1376 perror(file);
1377 exit(-1);
1379 while (fgets(str, sizeof str, f)) {
1380 process_args(str, pass);
1382 fclose(f);
1385 static void parse_cmdline(int argc, char **argv, int pass)
1387 FILE *rfile;
1388 char *envreal, *envcopy = NULL, *p;
1391 * Initialize all the warnings to their default state, including
1392 * warning index 0 used for "always on".
1394 memcpy(warning_state, warning_default, sizeof warning_state);
1397 * First, process the NASMENV environment variable.
1399 envreal = getenv("NASMENV");
1400 if (envreal) {
1401 envcopy = nasm_strdup(envreal);
1402 process_args(envcopy, pass);
1403 nasm_free(envcopy);
1407 * Now process the actual command line.
1409 while (--argc) {
1410 bool advance;
1411 argv++;
1412 if (argv[0][0] == '@') {
1414 * We have a response file, so process this as a set of
1415 * arguments like the environment variable. This allows us
1416 * to have multiple arguments on a single line, which is
1417 * different to the -@resp file processing below for regular
1418 * NASM.
1420 process_response_file(argv[0]+1, pass);
1421 argc--;
1422 argv++;
1424 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1425 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1426 if (p) {
1427 rfile = nasm_open_read(p, NF_TEXT);
1428 if (rfile) {
1429 process_respfile(rfile, pass);
1430 fclose(rfile);
1431 } else {
1432 nasm_nonfatalf(ERR_USAGE, "unable to open response file `%s'", p);
1435 } else
1436 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1437 argv += advance, argc -= advance;
1441 * Look for basic command line typos. This definitely doesn't
1442 * catch all errors, but it might help cases of fumbled fingers.
1444 if (pass != 2)
1445 return;
1447 if (!inname)
1448 nasm_fatalf(ERR_USAGE, "no input file specified");
1449 else if ((errname && !strcmp(inname, errname)) ||
1450 (outname && !strcmp(inname, outname)) ||
1451 (listname && !strcmp(inname, listname)) ||
1452 (depend_file && !strcmp(inname, depend_file)))
1453 nasm_fatalf(ERR_USAGE, "will not overwrite input file");
1455 if (errname) {
1456 error_file = nasm_open_write(errname, NF_TEXT);
1457 if (!error_file) {
1458 error_file = stderr; /* Revert to default! */
1459 nasm_fatalf(ERR_USAGE, "cannot open file `%s' for error messages", errname);
1464 static void forward_refs(insn *instruction)
1466 int i;
1467 struct forwrefinfo *fwinf;
1469 instruction->forw_ref = false;
1471 if (!optimizing.level)
1472 return; /* For -O0 don't bother */
1474 if (!forwref)
1475 return;
1477 if (forwref->lineno != globallineno)
1478 return;
1480 instruction->forw_ref = true;
1481 do {
1482 instruction->oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1483 forwref = saa_rstruct(forwrefs);
1484 } while (forwref && forwref->lineno == globallineno);
1486 if (!pass_first())
1487 return;
1489 for (i = 0; i < instruction->operands; i++) {
1490 if (instruction->oprs[i].opflags & OPFLAG_FORWARD) {
1491 fwinf = saa_wstruct(forwrefs);
1492 fwinf->lineno = globallineno;
1493 fwinf->operand = i;
1498 static void process_insn(insn *instruction)
1500 int32_t n;
1501 int64_t l;
1503 if (!instruction->times)
1504 return; /* Nothing to do... */
1506 nasm_assert(instruction->times > 0);
1509 * NOTE: insn_size() can change instruction->times
1510 * (usually to 1) when called.
1512 if (!pass_final()) {
1513 int64_t start = location.offset;
1514 for (n = 1; n <= instruction->times; n++) {
1515 l = insn_size(location.segment, location.offset,
1516 globalbits, instruction);
1517 /* l == -1 -> invalid instruction */
1518 if (l != -1)
1519 increment_offset(l);
1521 if (list_option('p')) {
1522 struct out_data dummy;
1523 memset(&dummy, 0, sizeof dummy);
1524 dummy.type = OUT_RAWDATA; /* Handled specially with .data NULL */
1525 dummy.offset = start;
1526 dummy.size = location.offset - start;
1527 lfmt->output(&dummy);
1529 } else {
1530 l = assemble(location.segment, location.offset,
1531 globalbits, instruction);
1532 /* We can't get an invalid instruction here */
1533 increment_offset(l);
1535 if (instruction->times > 1) {
1536 lfmt->uplevel(LIST_TIMES, instruction->times);
1537 for (n = 2; n <= instruction->times; n++) {
1538 l = assemble(location.segment, location.offset,
1539 globalbits, instruction);
1540 increment_offset(l);
1542 lfmt->downlevel(LIST_TIMES);
1547 static void assemble_file(const char *fname, struct strlist *depend_list)
1549 char *line;
1550 insn output_ins;
1551 uint64_t prev_offset_changed;
1552 int64_t stall_count = 0; /* Make sure we make forward progress... */
1554 switch (cmd_sb) {
1555 case 16:
1556 break;
1557 case 32:
1558 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1559 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1560 break;
1561 case 64:
1562 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1563 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1564 break;
1565 default:
1566 panic();
1567 break;
1570 prev_offset_changed = INT64_MAX;
1572 if (listname && !keep_all) {
1573 /* Remove the list file in case we die before the output pass */
1574 remove(listname);
1577 while (!terminate_after_phase && !pass_final()) {
1578 _passn++;
1579 if (pass_type() != PASS_OPT || !global_offset_changed)
1580 _pass_type++;
1581 global_offset_changed = 0;
1584 * Create a warning buffer list unless we are in
1585 * pass 2 (everything will be emitted immediately in pass 2.)
1587 if (warn_list) {
1588 if (warn_list->nstr || pass_final())
1589 strlist_free(&warn_list);
1592 if (!pass_final() && !warn_list)
1593 warn_list = strlist_alloc(false);
1595 globalbits = cmd_sb; /* set 'bits' to command line default */
1596 cpu = cmd_cpu;
1597 if (listname) {
1598 if (pass_final() || list_on_every_pass()) {
1599 active_list_options = list_options;
1600 lfmt->init(listname);
1601 } else if (active_list_options) {
1603 * Looks like we used the list engine on a previous pass,
1604 * but now it is turned off, presumably via %pragma -p
1606 lfmt->cleanup();
1607 if (!keep_all)
1608 remove(listname);
1609 active_list_options = 0;
1613 in_absolute = false;
1614 if (!pass_first()) {
1615 saa_rewind(forwrefs);
1616 forwref = saa_rstruct(forwrefs);
1617 raa_free(offsets);
1618 offsets = raa_init();
1620 location.segment = NO_SEG;
1621 location.offset = 0;
1622 if (pass_first())
1623 location.known = true;
1624 ofmt->reset();
1625 switch_segment(ofmt->section(NULL, &globalbits));
1626 preproc->reset(fname, PP_NORMAL, pass_final() ? depend_list : NULL);
1628 globallineno = 0;
1630 while ((line = preproc->getline())) {
1631 if (++globallineno > nasm_limit[LIMIT_LINES])
1632 nasm_fatal("overall line count exceeds the maximum %"PRId64"\n",
1633 nasm_limit[LIMIT_LINES]);
1636 * Here we parse our directives; this is not handled by the
1637 * main parser.
1639 if (process_directives(line))
1640 goto end_of_line; /* Just do final cleanup */
1642 /* Not a directive, or even something that starts with [ */
1643 parse_line(line, &output_ins);
1644 forward_refs(&output_ins);
1645 process_insn(&output_ins);
1646 cleanup_insn(&output_ins);
1648 end_of_line:
1649 nasm_free(line);
1650 } /* end while (line = preproc->getline... */
1652 preproc->cleanup_pass();
1654 if (global_offset_changed) {
1655 switch (pass_type()) {
1656 case PASS_OPT:
1658 * This is the only pass type that can be executed more
1659 * than once, and therefore has the ability to stall.
1661 if (global_offset_changed < prev_offset_changed) {
1662 prev_offset_changed = global_offset_changed;
1663 stall_count = 0;
1664 } else {
1665 stall_count++;
1668 if (stall_count > nasm_limit[LIMIT_STALLED] ||
1669 pass_count() >= nasm_limit[LIMIT_PASSES]) {
1670 /* No convergence, almost certainly dead */
1671 nasm_nonfatalf(ERR_UNDEAD,
1672 "unable to find valid values for all labels "
1673 "after %"PRId64" passes; "
1674 "stalled for %"PRId64", giving up.",
1675 pass_count(), stall_count);
1676 nasm_nonfatalf(ERR_UNDEAD,
1677 "Possible causes: recursive EQUs, macro abuse.");
1679 break;
1681 case PASS_STAB:
1683 *!phase [off] phase error during stabilization
1684 *! warns about symbols having changed values during
1685 *! the second-to-last assembly pass. This is not
1686 *! inherently fatal, but may be a source of bugs.
1688 nasm_warn(WARN_PHASE|ERR_UNDEAD,
1689 "phase error during stabilization "
1690 "pass, hoping for the best");
1691 break;
1693 case PASS_FINAL:
1694 nasm_nonfatalf(ERR_UNDEAD,
1695 "phase error during code generation pass");
1696 break;
1698 default:
1699 /* This is normal, we'll keep going... */
1700 break;
1704 reset_warnings();
1707 if (opt_verbose_info && pass_final()) {
1708 /* -On and -Ov switches */
1709 nasm_info("assembly required 1+%"PRId64"+2 passes\n", pass_count()-3);
1712 lfmt->cleanup();
1713 strlist_free(&warn_list);
1717 * get warning index; 0 if this is non-suppressible.
1719 static size_t warn_index(errflags severity)
1721 size_t index;
1723 if ((severity & ERR_MASK) >= ERR_FATAL)
1724 return 0; /* Fatal errors are never suppressible */
1726 /* Warnings MUST HAVE a warning category specifier! */
1727 nasm_assert((severity & (ERR_MASK|WARN_MASK)) != ERR_WARNING);
1729 index = WARN_IDX(severity);
1730 nasm_assert(index < WARN_IDX_ALL);
1732 return index;
1735 static bool skip_this_pass(errflags severity)
1737 errflags type = severity & ERR_MASK;
1740 * See if it's a pass-specific error or warning which should be skipped.
1741 * We can never skip fatal errors as by definition they cannot be
1742 * resumed from.
1744 if (type >= ERR_FATAL)
1745 return false;
1748 * ERR_LISTMSG messages are always skipped; the list file
1749 * receives them anyway as this function is not consulted
1750 * for sending to the list file.
1752 if (type == ERR_LISTMSG)
1753 return true;
1755 /* This message not applicable unless pass_final */
1756 return (severity & ERR_PASS2) && !pass_final();
1760 * check for suppressed message (usually warnings or notes)
1762 * @param severity the severity of the warning or error
1763 * @return true if we should abort error/warning printing
1765 static bool is_suppressed(errflags severity)
1767 /* Fatal errors must never be suppressed */
1768 if ((severity & ERR_MASK) >= ERR_FATAL)
1769 return false;
1771 /* This error/warning is pointless if we are dead anyway */
1772 if ((severity & ERR_UNDEAD) && terminate_after_phase)
1773 return true;
1775 if (!(warning_state[warn_index(severity)] & WARN_ST_ENABLED))
1776 return true;
1778 if (preproc && !(severity & ERR_PP_LISTMACRO))
1779 return preproc->suppress_error(severity);
1781 return false;
1785 * Return the true error type (the ERR_MASK part) of the given
1786 * severity, accounting for warnings that may need to be promoted to
1787 * error.
1789 * @param severity the severity of the warning or error
1790 * @return true if we should error out
1792 static errflags true_error_type(errflags severity)
1794 const uint8_t warn_is_err = WARN_ST_ENABLED|WARN_ST_ERROR;
1795 int type;
1797 type = severity & ERR_MASK;
1799 /* Promote warning to error? */
1800 if (type == ERR_WARNING) {
1801 uint8_t state = warning_state[warn_index(severity)];
1802 if ((state & warn_is_err) == warn_is_err)
1803 type = ERR_NONFATAL;
1806 return type;
1810 * The various error type prefixes
1812 static const char * const error_pfx_table[ERR_MASK+1] = {
1813 ";;; ", "debug: ", "info: ", "warning: ",
1814 "error: ", "fatal: ", "critical: ", "panic: "
1816 static const char no_file_name[] = "nasm"; /* What to print if no file name */
1819 * For fatal/critical/panic errors, kill this process.
1821 static fatal_func die_hard(errflags true_type, errflags severity)
1823 fflush(NULL);
1825 if (true_type == ERR_PANIC && abort_on_panic)
1826 abort();
1828 if (ofile) {
1829 fclose(ofile);
1830 if (!keep_all)
1831 remove(outname);
1832 ofile = NULL;
1835 if (severity & ERR_USAGE)
1836 usage();
1838 /* Terminate immediately */
1839 exit(true_type - ERR_FATAL + 1);
1843 * error reporting for critical and panic errors: minimize
1844 * the amount of system dependencies for getting a message out,
1845 * and in particular try to avoid memory allocations.
1847 fatal_func nasm_verror_critical(errflags severity, const char *fmt, va_list args)
1849 const char *currentfile = no_file_name;
1850 int32_t lineno = 0;
1851 errflags true_type = severity & ERR_MASK;
1852 static bool been_here = false;
1854 if (unlikely(been_here))
1855 abort(); /* Recursive error... just die */
1857 been_here = true;
1859 if (!(severity & ERR_NOFILE)) {
1860 src_get(&lineno, &currentfile);
1861 if (!currentfile) {
1862 currentfile =
1863 inname && inname[0] ? inname :
1864 outname && outname[0] ? outname :
1865 no_file_name;
1866 lineno = 0;
1870 fputs(error_pfx_table[severity], error_file);
1871 fputs(currentfile, error_file);
1872 if (lineno) {
1873 fprintf(error_file, "%s%"PRId32"%s",
1874 errfmt->beforeline, lineno, errfmt->afterline);
1876 fputs(errfmt->beforemsg, error_file);
1877 vfprintf(error_file, fmt, args);
1878 fputc('\n', error_file);
1880 die_hard(true_type, severity);
1884 * common error reporting
1885 * This is the common back end of the error reporting schemes currently
1886 * implemented. It prints the nature of the warning and then the
1887 * specific error message to error_file and may or may not return. It
1888 * doesn't return if the error severity is a "panic" or "debug" type.
1890 * @param severity the severity of the warning or error
1891 * @param fmt the printf style format string
1893 void nasm_verror(errflags severity, const char *fmt, va_list args)
1895 char msg[1024];
1896 char warnsuf[64];
1897 char linestr[64];
1898 const char *pfx;
1899 errflags true_type = true_error_type(severity);
1900 const char *currentfile = NULL;
1901 int32_t lineno = 0;
1903 if (true_type >= ERR_CRITICAL)
1904 nasm_verror_critical(severity, fmt, args);
1906 if (is_suppressed(severity))
1907 return;
1909 if (!(severity & ERR_NOFILE)) {
1910 src_get(&lineno, &currentfile);
1911 if (!currentfile) {
1912 currentfile =
1913 inname && inname[0] ? inname :
1914 outname && outname[0] ? outname :
1915 NULL;
1916 lineno = 0;
1920 if (severity & ERR_NO_SEVERITY)
1921 pfx = "";
1922 else
1923 pfx = error_pfx_table[true_type];
1925 vsnprintf(msg, sizeof msg, fmt, args);
1926 *warnsuf = 0;
1927 if ((severity & (ERR_MASK|ERR_HERE|ERR_PP_LISTMACRO)) == ERR_WARNING) {
1929 * It's a warning without ERR_HERE defined, and we are not already
1930 * unwinding the macros that led us here.
1932 snprintf(warnsuf, sizeof warnsuf, " [-w+%s%s]",
1933 (true_type >= ERR_NONFATAL) ? "error=" : "",
1934 warning_name[warn_index(severity)]);
1937 *linestr = 0;
1938 if (lineno) {
1939 snprintf(linestr, sizeof linestr, "%s%"PRId32"%s",
1940 errfmt->beforeline, lineno, errfmt->afterline);
1943 if (!skip_this_pass(severity)) {
1944 const char *file = currentfile ? currentfile : no_file_name;
1945 const char *here = "";
1947 if (severity & ERR_HERE)
1948 here = currentfile ? " here" : " in an unknown location";
1950 if (warn_list && true_type < ERR_NONFATAL &&
1951 !(pass_first() && (severity & ERR_PASS1)))
1954 * Buffer up warnings until we either get an error
1955 * or we are on the code-generation pass.
1957 strlist_printf(warn_list, "%s%s%s%s%s%s%s",
1958 file, linestr, errfmt->beforemsg,
1959 pfx, msg, here, warnsuf);
1960 } else {
1962 * If we have buffered warnings, and this is a non-warning,
1963 * output them now.
1965 if (true_type >= ERR_NONFATAL && warn_list) {
1966 strlist_write(warn_list, "\n", error_file);
1967 strlist_free(&warn_list);
1970 fprintf(error_file, "%s%s%s%s%s%s%s\n",
1971 file, linestr, errfmt->beforemsg,
1972 pfx, msg, here, warnsuf);
1977 /* Are we recursing from error_list_macros? */
1978 if (severity & ERR_PP_LISTMACRO)
1979 return;
1982 * Don't suppress this with skip_this_pass(), or we don't get
1983 * pass1 or preprocessor warnings in the list file
1985 if (severity & ERR_HERE) {
1986 if (lineno)
1987 lfmt->error(severity, "%s%s at %s:%"PRId32"%s",
1988 pfx, msg, currentfile, lineno, warnsuf);
1989 else if (currentfile)
1990 lfmt->error(severity, "%s%s in file %s%s",
1991 pfx, msg, currentfile, warnsuf);
1992 else
1993 lfmt->error(severity, "%s%s in an unknown location%s",
1994 pfx, msg, warnsuf);
1995 } else {
1996 lfmt->error(severity, "%s%s%s", pfx, msg, warnsuf);
1999 if (skip_this_pass(severity))
2000 return;
2002 /* error_list_macros can for obvious reasons not work with ERR_HERE */
2003 if (!(severity & ERR_HERE))
2004 if (preproc)
2005 preproc->error_list_macros(severity);
2007 if (true_type >= ERR_FATAL)
2008 die_hard(true_type, severity);
2009 else if (true_type >= ERR_NONFATAL)
2010 terminate_after_phase = true;
2013 static void usage(void)
2015 fprintf(error_file, "Type %s -h for help.\n", _progname);
2018 static void help(FILE *out)
2020 int i;
2022 fprintf(out,
2023 "Usage: %s [-@ response_file] [options...] [--] filename\n"
2024 " %s -v (or --v)\n",
2025 _progname, _progname);
2026 fputs(
2027 "\n"
2028 "Options (values in brackets indicate defaults):\n"
2029 "\n"
2030 " -h show this text and exit (also --help)\n"
2031 " -v (or --v) print the NASM version number and exit\n"
2032 " -@ file response file; one command line option per line\n"
2033 "\n"
2034 " -o outfile write output to outfile\n"
2035 " --keep-all output files will not be removed even if an error happens\n"
2036 "\n"
2037 " -Xformat specifiy error reporting format (gnu or vc)\n"
2038 " -s redirect error messages to stdout\n"
2039 " -Zfile redirect error messages to file\n"
2040 "\n"
2041 " -M generate Makefile dependencies on stdout\n"
2042 " -MG d:o, missing files assumed generated\n"
2043 " -MF file set Makefile dependency file\n"
2044 " -MD file assemble and generate dependencies\n"
2045 " -MT file dependency target name\n"
2046 " -MQ file dependency target name (quoted)\n"
2047 " -MP emit phony targets\n"
2048 "\n"
2049 " -f format select output file format\n"
2050 , out);
2051 ofmt_list(ofmt, out);
2052 fputs(
2053 "\n"
2054 " -g generate debugging information\n"
2055 " -F format select a debugging format (output format dependent)\n"
2056 " -gformat same as -g -F format\n"
2057 , out);
2058 dfmt_list(out);
2059 fputs(
2060 "\n"
2061 " -l listfile write listing to a list file\n"
2062 " -Lflags... add optional information to the list file\n"
2063 " -Lb show builtin macro packages (standard and %use)\n"
2064 " -Ld show byte and repeat counts in decimal, not hex\n"
2065 " -Le show the preprocessed output\n"
2066 " -Lf ignore .nolist (force output)\n"
2067 " -Lm show multi-line macro calls with expanded parmeters\n"
2068 " -Lp output a list file every pass, in case of errors\n"
2069 " -Ls show all single-line macro definitions\n"
2070 " -L+ enable all listing options (very verbose!)\n"
2071 "\n"
2072 " -Oflags... optimize opcodes, immediates and branch offsets\n"
2073 " -O0 no optimization\n"
2074 " -O1 minimal optimization\n"
2075 " -Ox multipass optimization (default)\n"
2076 " -Ov display the number of passes executed at the end\n"
2077 " -t assemble in limited SciTech TASM compatible mode\n"
2078 "\n"
2079 " -E (or -e) preprocess only (writes output to stdout by default)\n"
2080 " -a don't preprocess (assemble only)\n"
2081 " -Ipath add a pathname to the include file path\n"
2082 " -Pfile pre-include a file (also --include)\n"
2083 " -Dmacro[=str] pre-define a macro\n"
2084 " -Umacro undefine a macro\n"
2085 " --pragma str pre-executes a specific %%pragma\n"
2086 " --before str add line (usually a preprocessor statement) before the input\n"
2087 " --no-line ignore %line directives in input\n"
2088 "\n"
2089 " --prefix str prepend the given string to the names of all extern,\n"
2090 " common and global symbols (also --gprefix)\n"
2091 " --suffix str append the given string to the names of all extern,\n"
2092 " common and global symbols (also --gprefix)\n"
2093 " --lprefix str prepend the given string to local symbols\n"
2094 " --lpostfix str append the given string to local symbols\n"
2095 "\n"
2096 " -w+x enable warning x (also -Wx)\n"
2097 " -w-x disable warning x (also -Wno-x)\n"
2098 " -w[+-]error promote all warnings to errors (also -Werror)\n"
2099 " -w[+-]error=x promote warning x to errors (also -Werror=x)\n"
2100 , out);
2102 fprintf(out, " %-20s %s\n",
2103 warning_name[WARN_IDX_ALL], warning_help[WARN_IDX_ALL]);
2105 for (i = 1; i < WARN_IDX_ALL; i++) {
2106 const char *me = warning_name[i];
2107 const char *prev = warning_name[i-1];
2108 const char *next = warning_name[i+1];
2110 if (prev) {
2111 int prev_len = strlen(prev);
2112 const char *dash = me;
2114 while ((dash = strchr(dash+1, '-'))) {
2115 int prefix_len = dash - me; /* Not including final dash */
2116 if (strncmp(next, me, prefix_len+1)) {
2117 /* Only one or last option with this prefix */
2118 break;
2120 if (prefix_len >= prev_len ||
2121 strncmp(prev, me, prefix_len) ||
2122 (prev[prefix_len] != '-' && prev[prefix_len] != '\0')) {
2123 /* This prefix is different from the previous option */
2124 fprintf(out, " %-20.*s all warnings prefixed with \"%.*s\"\n",
2125 prefix_len, me, prefix_len+1, me);
2130 fprintf(out, " %-20s %s%s\n",
2131 warning_name[i], warning_help[i],
2132 (warning_default[i] & WARN_ST_ERROR) ? " [error]" :
2133 (warning_default[i] & WARN_ST_ENABLED) ? " [on]" : " [off]");
2136 fputs(
2137 "\n"
2138 " --limit-X val set execution limit X\n"
2139 , out);
2142 for (i = 0; i <= LIMIT_MAX; i++) {
2143 fprintf(out, " %-20s %s [",
2144 limit_info[i].name, limit_info[i].help);
2145 if (nasm_limit[i] < LIMIT_MAX_VAL) {
2146 fprintf(out, "%"PRId64"]\n", nasm_limit[i]);
2147 } else {
2148 fputs("unlimited]\n", out);