nasm.c: min 2 optimization passes, don't re-run pass 1
[nasm.git] / asm / nasm.c
blob5290b07876eae8544061df28757af627eeb60eef
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"
40 #include <stdio.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <limits.h>
47 #include "nasm.h"
48 #include "nasmlib.h"
49 #include "error.h"
50 #include "saa.h"
51 #include "raa.h"
52 #include "float.h"
53 #include "stdscan.h"
54 #include "insns.h"
55 #include "preproc.h"
56 #include "parser.h"
57 #include "eval.h"
58 #include "assemble.h"
59 #include "labels.h"
60 #include "outform.h"
61 #include "listing.h"
62 #include "iflag.h"
63 #include "ver.h"
66 * This is the maximum number of optimization passes to do. If we ever
67 * find a case where the optimizer doesn't naturally converge, we might
68 * have to drop this value so the assembler doesn't appear to just hang.
70 #define MAX_OPTIMIZE (INT_MAX >> 1)
72 struct forwrefinfo { /* info held on forward refs. */
73 int lineno;
74 int operand;
77 static void parse_cmdline(int, char **, int);
78 static void assemble_file(const char *, StrList **);
79 static bool is_suppressed_warning(int severity);
80 static bool skip_this_pass(int severity);
81 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
82 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
83 static void nasm_verror_common(int severity, const char *fmt, va_list args);
84 static void usage(void);
85 static void help(char xopt);
87 static bool using_debug_info, opt_verbose_info;
88 static const char *debug_format;
90 #ifndef ABORT_ON_PANIC
91 # define ABORT_ON_PANIC 0
92 #endif
93 static bool abort_on_panic = ABORT_ON_PANIC;
94 static bool keep_all;
96 bool tasm_compatible_mode = false;
97 int pass0;
98 int64_t passn;
99 static int pass1, pass2; /* XXX: Get rid of these, they are redundant */
100 int globalrel = 0;
101 int globalbnd = 0;
103 struct compile_time official_compile_time;
105 const char *inname;
106 const char *outname;
107 static const char *listname;
108 static const char *errname;
110 static int64_t globallineno; /* for forward-reference tracking */
112 /* static int pass = 0; */
113 const struct ofmt *ofmt = &OF_DEFAULT;
114 const struct ofmt_alias *ofmt_alias = NULL;
115 const struct dfmt *dfmt;
117 static FILE *error_file; /* Where to write error messages */
119 FILE *ofile = NULL;
120 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
121 static int cmd_sb = 16; /* by default */
123 iflag_t cpu;
124 static iflag_t cmd_cpu;
126 struct location location;
127 bool in_absolute; /* Flag we are in ABSOLUTE seg */
128 struct location absolute; /* Segment/offset inside ABSOLUTE */
130 static struct RAA *offsets;
132 static struct SAA *forwrefs; /* keep track of forward references */
133 static const struct forwrefinfo *forwref;
135 static const struct preproc_ops *preproc;
137 #define OP_NORMAL (1u << 0)
138 #define OP_PREPROCESS (1u << 1)
139 #define OP_DEPEND (1u << 2)
141 static unsigned int operating_mode;
143 /* Dependency flags */
144 static bool depend_emit_phony = false;
145 static bool depend_missing_ok = false;
146 static const char *depend_target = NULL;
147 static const char *depend_file = NULL;
148 StrList *depend_list;
150 static bool want_usage;
151 static bool terminate_after_phase;
152 bool user_nolist = false;
154 static char *quote_for_pmake(const char *str);
155 static char *quote_for_wmake(const char *str);
156 static char *(*quote_for_make)(const char *) = quote_for_pmake;
159 * Execution limits that can be set via a command-line option or %pragma
162 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
164 int64_t nasm_limit[LIMIT_MAX+1] =
165 { LIMIT_MAX_VAL, 1000, 1000000, 1000000, 1000000, 2000000000 };
167 struct limit_info {
168 const char *name;
169 const char *help;
171 static const struct limit_info limit_info[LIMIT_MAX+1] = {
172 { "passes", "total number of passes" },
173 { "stalled-passes", "number of passes without forward progress" },
174 { "macro-levels", "levels of macro expansion"},
175 { "rep", "%rep count" },
176 { "eval", "expression evaluation descent"},
177 { "lines", "total source lines processed"}
180 enum directive_result
181 nasm_set_limit(const char *limit, const char *valstr)
183 int i;
184 int64_t val;
185 bool rn_error;
186 int errlevel;
188 for (i = 0; i <= LIMIT_MAX; i++) {
189 if (!nasm_stricmp(limit, limit_info[i].name))
190 break;
192 if (i > LIMIT_MAX) {
193 if (passn == 0)
194 errlevel = ERR_WARNING|ERR_NOFILE|ERR_USAGE;
195 else
196 errlevel = ERR_WARNING|ERR_PASS1|ERR_WARN_UNKNOWN_PRAGMA;
197 nasm_error(errlevel, "unknown limit: `%s'", limit);
198 return DIRR_ERROR;
201 if (!nasm_stricmp(valstr, "unlimited")) {
202 val = LIMIT_MAX_VAL;
203 } else {
204 val = readnum(valstr, &rn_error);
205 if (rn_error || val < 0) {
206 if (passn == 0)
207 errlevel = ERR_WARNING|ERR_NOFILE|ERR_USAGE;
208 else
209 errlevel = ERR_WARNING|ERR_PASS1|ERR_WARN_BAD_PRAGMA;
210 nasm_error(errlevel, "invalid limit value: `%s'", limit);
211 return DIRR_ERROR;
213 if (val > LIMIT_MAX_VAL)
214 val = LIMIT_MAX_VAL;
217 nasm_limit[i] = val;
218 return DIRR_OK;
221 int64_t switch_segment(int32_t segment)
223 location.segment = segment;
224 if (segment == NO_SEG) {
225 location.offset = absolute.offset;
226 in_absolute = true;
227 } else {
228 location.offset = raa_read(offsets, segment);
229 in_absolute = false;
231 return location.offset;
234 static void set_curr_offs(int64_t l_off)
236 if (in_absolute)
237 absolute.offset = l_off;
238 else
239 offsets = raa_write(offsets, location.segment, l_off);
242 static void increment_offset(int64_t delta)
244 if (unlikely(delta == 0))
245 return;
247 location.offset += delta;
248 set_curr_offs(location.offset);
251 static void nasm_fputs(const char *line, FILE * outfile)
253 if (outfile) {
254 fputs(line, outfile);
255 putc('\n', outfile);
256 } else
257 puts(line);
260 static void define_macros_early(void)
262 const struct compile_time * const oct = &official_compile_time;
263 char temp[128];
265 if (oct->have_local) {
266 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &oct->local);
267 preproc->pre_define(temp);
268 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &oct->local);
269 preproc->pre_define(temp);
270 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &oct->local);
271 preproc->pre_define(temp);
272 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &oct->local);
273 preproc->pre_define(temp);
276 if (oct->have_gm) {
277 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &oct->gm);
278 preproc->pre_define(temp);
279 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &oct->gm);
280 preproc->pre_define(temp);
281 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &oct->gm);
282 preproc->pre_define(temp);
283 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &oct->gm);
284 preproc->pre_define(temp);
287 if (oct->have_posix) {
288 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, oct->posix);
289 preproc->pre_define(temp);
293 static void define_macros_late(void)
295 char temp[128];
298 * In case if output format is defined by alias
299 * we have to put shortname of the alias itself here
300 * otherwise ABI backward compatibility gets broken.
302 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
303 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
304 preproc->pre_define(temp);
307 static void emit_dependencies(StrList *list)
309 FILE *deps;
310 int linepos, len;
311 StrList *l, *nl;
312 bool wmake = (quote_for_make == quote_for_wmake);
313 const char *wrapstr, *nulltarget;
315 wrapstr = wmake ? " &\n " : " \\\n ";
316 nulltarget = wmake ? "\t%null\n" : "";
318 if (depend_file && strcmp(depend_file, "-")) {
319 deps = nasm_open_write(depend_file, NF_TEXT);
320 if (!deps) {
321 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
322 "unable to write dependency file `%s'", depend_file);
323 return;
325 } else {
326 deps = stdout;
329 linepos = fprintf(deps, "%s :", depend_target);
330 list_for_each(l, list) {
331 char *file = quote_for_make(l->str);
332 len = strlen(file);
333 if (linepos + len > 62 && linepos > 1) {
334 fputs(wrapstr, deps);
335 linepos = 1;
337 fprintf(deps, " %s", file);
338 linepos += len+1;
339 nasm_free(file);
341 fprintf(deps, "\n\n");
343 list_for_each_safe(l, nl, list) {
344 if (depend_emit_phony) {
345 char *file = quote_for_make(l->str);
346 fprintf(deps, "%s :\n%s\n", file, nulltarget);
347 nasm_free(file);
349 nasm_free(l);
352 if (deps != stdout)
353 fclose(deps);
356 /* Convert a struct tm to a POSIX-style time constant */
357 static int64_t make_posix_time(const struct tm *tm)
359 int64_t t;
360 int64_t y = tm->tm_year;
362 /* See IEEE 1003.1:2004, section 4.14 */
364 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
365 t += tm->tm_yday;
366 t *= 24;
367 t += tm->tm_hour;
368 t *= 60;
369 t += tm->tm_min;
370 t *= 60;
371 t += tm->tm_sec;
373 return t;
376 static void timestamp(void)
378 struct compile_time * const oct = &official_compile_time;
379 const struct tm *tp, *best_gm;
381 time(&oct->t);
383 best_gm = NULL;
385 tp = localtime(&oct->t);
386 if (tp) {
387 oct->local = *tp;
388 best_gm = &oct->local;
389 oct->have_local = true;
392 tp = gmtime(&oct->t);
393 if (tp) {
394 oct->gm = *tp;
395 best_gm = &oct->gm;
396 oct->have_gm = true;
397 if (!oct->have_local)
398 oct->local = oct->gm;
399 } else {
400 oct->gm = oct->local;
403 if (best_gm) {
404 oct->posix = make_posix_time(best_gm);
405 oct->have_posix = true;
409 int main(int argc, char **argv)
411 StrList **depend_ptr;
413 timestamp();
415 iflag_set_default_cpu(&cpu);
416 iflag_set_default_cpu(&cmd_cpu);
418 pass0 = 0;
419 want_usage = terminate_after_phase = false;
420 nasm_set_verror(nasm_verror_gnu);
422 error_file = stderr;
424 tolower_init();
425 src_init();
428 * We must call init_labels() before the command line parsing,
429 * because we may be setting prefixes/suffixes from the command
430 * line.
432 init_labels();
434 offsets = raa_init();
435 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
437 preproc = &nasmpp;
438 operating_mode = OP_NORMAL;
440 parse_cmdline(argc, argv, 1);
441 if (terminate_after_phase) {
442 if (want_usage)
443 usage();
444 return 1;
448 * Define some macros dependent on the runtime, but not
449 * on the command line (as those are scanned in cmdline pass 2.)
451 preproc->init();
452 define_macros_early();
454 parse_cmdline(argc, argv, 2);
455 if (terminate_after_phase) {
456 if (want_usage)
457 usage();
458 return 1;
461 /* Save away the default state of warnings */
462 memcpy(warning_state_init, warning_state, sizeof warning_state);
464 if (!using_debug_info) {
465 /* No debug info, redirect to the null backend (empty stubs) */
466 dfmt = &null_debug_form;
467 } else if (!debug_format) {
468 /* Default debug format for this backend */
469 dfmt = ofmt->default_dfmt;
470 } else {
471 dfmt = dfmt_find(ofmt, debug_format);
472 if (!dfmt) {
473 nasm_fatal(ERR_NOFILE | ERR_USAGE,
474 "unrecognized debug format `%s' for"
475 " output format `%s'",
476 debug_format, ofmt->shortname);
480 if (ofmt->stdmac)
481 preproc->extra_stdmac(ofmt->stdmac);
483 /* no output file name? */
484 if (!outname)
485 outname = filename_set_extension(inname, ofmt->extension);
487 /* define some macros dependent of command-line */
488 define_macros_late();
490 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
492 if (!depend_target)
493 depend_target = quote_for_make(outname);
495 if (operating_mode & OP_DEPEND) {
496 char *line;
498 if (depend_missing_ok)
499 preproc->include_path(NULL); /* "assume generated" */
501 preproc->reset(inname, 0, depend_ptr);
502 ofile = NULL;
503 while ((line = preproc->getline()))
504 nasm_free(line);
505 preproc->cleanup(0);
506 } else if (operating_mode & OP_PREPROCESS) {
507 char *line;
508 const char *file_name = NULL;
509 int32_t prior_linnum = 0;
510 int lineinc = 0;
512 if (outname) {
513 ofile = nasm_open_write(outname, NF_TEXT);
514 if (!ofile)
515 nasm_fatal(ERR_NOFILE,
516 "unable to open output file `%s'",
517 outname);
518 } else
519 ofile = NULL;
521 location.known = false;
523 /* pass = 1; */
524 preproc->reset(inname, 3, depend_ptr);
526 /* Revert all warnings to the default state */
527 memcpy(warning_state, warning_state_init, sizeof warning_state);
529 while ((line = preproc->getline())) {
531 * We generate %line directives if needed for later programs
533 int32_t linnum = prior_linnum += lineinc;
534 int altline = src_get(&linnum, &file_name);
535 if (altline) {
536 if (altline == 1 && lineinc == 1)
537 nasm_fputs("", ofile);
538 else {
539 lineinc = (altline != -1 || lineinc != 1);
540 fprintf(ofile ? ofile : stdout,
541 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
542 file_name);
544 prior_linnum = linnum;
546 nasm_fputs(line, ofile);
547 nasm_free(line);
549 preproc->cleanup(0);
550 if (ofile)
551 fclose(ofile);
552 if (ofile && terminate_after_phase && !keep_all)
553 remove(outname);
554 ofile = NULL;
557 if (operating_mode & OP_NORMAL) {
558 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
559 if (!ofile)
560 nasm_fatal(ERR_NOFILE,
561 "unable to open output file `%s'", outname);
563 ofmt->init();
564 dfmt->init();
566 assemble_file(inname, depend_ptr);
568 if (!terminate_after_phase) {
569 ofmt->cleanup();
570 cleanup_labels();
571 fflush(ofile);
572 if (ferror(ofile)) {
573 nasm_error(ERR_NONFATAL|ERR_NOFILE,
574 "write error on output file `%s'", outname);
575 terminate_after_phase = true;
579 if (ofile) {
580 fclose(ofile);
581 if (terminate_after_phase && !keep_all)
582 remove(outname);
583 ofile = NULL;
587 if (depend_list && !terminate_after_phase)
588 emit_dependencies(depend_list);
590 if (want_usage)
591 usage();
593 raa_free(offsets);
594 saa_free(forwrefs);
595 eval_cleanup();
596 stdscan_cleanup();
597 src_free();
599 return terminate_after_phase;
603 * Get a parameter for a command line option.
604 * First arg must be in the form of e.g. -f...
606 static char *get_param(char *p, char *q, bool *advance)
608 *advance = false;
609 if (p[2]) /* the parameter's in the option */
610 return nasm_skip_spaces(p + 2);
611 if (q && q[0]) {
612 *advance = true;
613 return q;
615 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
616 "option `-%c' requires an argument", p[1]);
617 return NULL;
621 * Copy a filename
623 static void copy_filename(const char **dst, const char *src, const char *what)
625 if (*dst)
626 nasm_fatal(0, "more than one %s file specified: %s\n", what, src);
628 *dst = nasm_strdup(src);
632 * Convert a string to a POSIX make-safe form
634 static char *quote_for_pmake(const char *str)
636 const char *p;
637 char *os, *q;
639 size_t n = 1; /* Terminating zero */
640 size_t nbs = 0;
642 if (!str)
643 return NULL;
645 for (p = str; *p; p++) {
646 switch (*p) {
647 case ' ':
648 case '\t':
649 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
650 n += nbs + 2;
651 nbs = 0;
652 break;
653 case '$':
654 case '#':
655 nbs = 0;
656 n += 2;
657 break;
658 case '\\':
659 nbs++;
660 n++;
661 break;
662 default:
663 nbs = 0;
664 n++;
665 break;
669 /* Convert N backslashes at the end of filename to 2N backslashes */
670 if (nbs)
671 n += nbs;
673 os = q = nasm_malloc(n);
675 nbs = 0;
676 for (p = str; *p; p++) {
677 switch (*p) {
678 case ' ':
679 case '\t':
680 while (nbs--)
681 *q++ = '\\';
682 *q++ = '\\';
683 *q++ = *p;
684 break;
685 case '$':
686 *q++ = *p;
687 *q++ = *p;
688 nbs = 0;
689 break;
690 case '#':
691 *q++ = '\\';
692 *q++ = *p;
693 nbs = 0;
694 break;
695 case '\\':
696 *q++ = *p;
697 nbs++;
698 break;
699 default:
700 *q++ = *p;
701 nbs = 0;
702 break;
705 while (nbs--)
706 *q++ = '\\';
708 *q = '\0';
710 return os;
714 * Convert a string to a Watcom make-safe form
716 static char *quote_for_wmake(const char *str)
718 const char *p;
719 char *os, *q;
720 bool quote = false;
722 size_t n = 1; /* Terminating zero */
724 if (!str)
725 return NULL;
727 for (p = str; *p; p++) {
728 switch (*p) {
729 case ' ':
730 case '\t':
731 case '&':
732 quote = true;
733 n++;
734 break;
735 case '\"':
736 quote = true;
737 n += 2;
738 break;
739 case '$':
740 case '#':
741 n += 2;
742 break;
743 default:
744 n++;
745 break;
749 if (quote)
750 n += 2;
752 os = q = nasm_malloc(n);
754 if (quote)
755 *q++ = '\"';
757 for (p = str; *p; p++) {
758 switch (*p) {
759 case '$':
760 case '#':
761 *q++ = '$';
762 *q++ = *p;
763 break;
764 case '\"':
765 *q++ = *p;
766 *q++ = *p;
767 break;
768 default:
769 *q++ = *p;
770 break;
774 if (quote)
775 *q++ = '\"';
777 *q = '\0';
779 return os;
782 enum text_options {
783 OPT_BOGUS,
784 OPT_VERSION,
785 OPT_HELP,
786 OPT_ABORT_ON_PANIC,
787 OPT_MANGLE,
788 OPT_INCLUDE,
789 OPT_PRAGMA,
790 OPT_BEFORE,
791 OPT_LIMIT,
792 OPT_KEEP_ALL
794 struct textargs {
795 const char *label;
796 enum text_options opt;
797 bool need_arg;
798 int pvt;
800 static const struct textargs textopts[] = {
801 {"v", OPT_VERSION, false, 0},
802 {"version", OPT_VERSION, false, 0},
803 {"help", OPT_HELP, false, 0},
804 {"abort-on-panic", OPT_ABORT_ON_PANIC, false, 0},
805 {"prefix", OPT_MANGLE, true, LM_GPREFIX},
806 {"postfix", OPT_MANGLE, true, LM_GSUFFIX},
807 {"gprefix", OPT_MANGLE, true, LM_GPREFIX},
808 {"gpostfix", OPT_MANGLE, true, LM_GSUFFIX},
809 {"lprefix", OPT_MANGLE, true, LM_LPREFIX},
810 {"lpostfix", OPT_MANGLE, true, LM_LSUFFIX},
811 {"include", OPT_INCLUDE, true, 0},
812 {"pragma", OPT_PRAGMA, true, 0},
813 {"before", OPT_BEFORE, true, 0},
814 {"limit-", OPT_LIMIT, true, 0},
815 {"keep-all", OPT_KEEP_ALL, false, 0},
816 {NULL, OPT_BOGUS, false, 0}
819 static void show_version(void)
821 printf("NASM version %s compiled on %s%s\n",
822 nasm_version, nasm_date, nasm_compile_options);
823 exit(0);
826 static bool stopoptions = false;
827 static bool process_arg(char *p, char *q, int pass)
829 char *param;
830 bool advance = false;
832 if (!p || !p[0])
833 return false;
835 if (p[0] == '-' && !stopoptions) {
836 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
837 /* These parameters take values */
838 if (!(param = get_param(p, q, &advance)))
839 return advance;
842 switch (p[1]) {
843 case 's':
844 if (pass == 1)
845 error_file = stdout;
846 break;
848 case 'o': /* output file */
849 if (pass == 2)
850 copy_filename(&outname, param, "output");
851 break;
853 case 'f': /* output format */
854 if (pass == 1) {
855 ofmt = ofmt_find(param, &ofmt_alias);
856 if (!ofmt) {
857 nasm_fatal(ERR_NOFILE | ERR_USAGE,
858 "unrecognised output format `%s' - "
859 "use -hf for a list", param);
862 break;
864 case 'O': /* Optimization level */
865 if (pass == 2) {
866 int opt;
868 if (!*param) {
869 /* Naked -O == -Ox */
870 optimizing = MAX_OPTIMIZE;
871 } else {
872 while (*param) {
873 switch (*param) {
874 case '0': case '1': case '2': case '3': case '4':
875 case '5': case '6': case '7': case '8': case '9':
876 opt = strtoul(param, &param, 10);
878 /* -O0 -> optimizing == -1, 0.98 behaviour */
879 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
880 if (opt < 2)
881 optimizing = opt - 1;
882 else
883 optimizing = opt;
884 break;
886 case 'v':
887 case '+':
888 param++;
889 opt_verbose_info = true;
890 break;
892 case 'x':
893 param++;
894 optimizing = MAX_OPTIMIZE;
895 break;
897 default:
898 nasm_fatal(0,
899 "unknown optimization option -O%c\n",
900 *param);
901 break;
904 if (optimizing > MAX_OPTIMIZE)
905 optimizing = MAX_OPTIMIZE;
908 break;
910 case 'p': /* pre-include */
911 case 'P':
912 if (pass == 2)
913 preproc->pre_include(param);
914 break;
916 case 'd': /* pre-define */
917 case 'D':
918 if (pass == 2)
919 preproc->pre_define(param);
920 break;
922 case 'u': /* un-define */
923 case 'U':
924 if (pass == 2)
925 preproc->pre_undefine(param);
926 break;
928 case 'i': /* include search path */
929 case 'I':
930 if (pass == 2)
931 preproc->include_path(param);
932 break;
934 case 'l': /* listing file */
935 if (pass == 2)
936 copy_filename(&listname, param, "listing");
937 break;
939 case 'Z': /* error messages file */
940 if (pass == 1)
941 copy_filename(&errname, param, "error");
942 break;
944 case 'F': /* specify debug format */
945 if (pass == 2) {
946 using_debug_info = true;
947 debug_format = param;
949 break;
951 case 'X': /* specify error reporting format */
952 if (pass == 1) {
953 if (nasm_stricmp("vc", param) == 0)
954 nasm_set_verror(nasm_verror_vc);
955 else if (nasm_stricmp("gnu", param) == 0)
956 nasm_set_verror(nasm_verror_gnu);
957 else
958 nasm_fatal(ERR_NOFILE | ERR_USAGE,
959 "unrecognized error reporting format `%s'",
960 param);
962 break;
964 case 'g':
965 if (pass == 2) {
966 using_debug_info = true;
967 if (p[2])
968 debug_format = nasm_skip_spaces(p + 2);
970 break;
972 case 'h':
973 help(p[2]);
974 exit(0); /* never need usage message here */
975 break;
977 case 'y':
978 printf("\nvalid debug formats for '%s' output format are"
979 " ('*' denotes default):\n", ofmt->shortname);
980 dfmt_list(ofmt, stdout);
981 exit(0);
982 break;
984 case 't':
985 if (pass == 2)
986 tasm_compatible_mode = true;
987 break;
989 case 'v':
990 show_version();
991 break;
993 case 'e': /* preprocess only */
994 case 'E':
995 if (pass == 1)
996 operating_mode = OP_PREPROCESS;
997 break;
999 case 'a': /* assemble only - don't preprocess */
1000 if (pass == 1)
1001 preproc = &preproc_nop;
1002 break;
1004 case 'w':
1005 case 'W':
1006 if (pass == 2) {
1007 if (!set_warning_status(param)) {
1008 nasm_error(ERR_WARNING|ERR_NOFILE|ERR_WARN_UNK_WARNING,
1009 "unknown warning option: %s", param);
1012 break;
1014 case 'M':
1015 if (pass == 1) {
1016 switch (p[2]) {
1017 case 'W':
1018 quote_for_make = quote_for_wmake;
1019 break;
1020 case 'D':
1021 case 'F':
1022 case 'T':
1023 case 'Q':
1024 advance = true;
1025 break;
1026 default:
1027 break;
1029 } else {
1030 switch (p[2]) {
1031 case 0:
1032 operating_mode = OP_DEPEND;
1033 break;
1034 case 'G':
1035 operating_mode = OP_DEPEND;
1036 depend_missing_ok = true;
1037 break;
1038 case 'P':
1039 depend_emit_phony = true;
1040 break;
1041 case 'D':
1042 operating_mode = OP_NORMAL;
1043 depend_file = q;
1044 advance = true;
1045 break;
1046 case 'F':
1047 depend_file = q;
1048 advance = true;
1049 break;
1050 case 'T':
1051 depend_target = q;
1052 advance = true;
1053 break;
1054 case 'Q':
1055 depend_target = quote_for_make(q);
1056 advance = true;
1057 break;
1058 case 'W':
1059 /* handled in pass 1 */
1060 break;
1061 default:
1062 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1063 "unknown dependency option `-M%c'", p[2]);
1064 break;
1067 if (advance && (!q || !q[0])) {
1068 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1069 "option `-M%c' requires a parameter", p[2]);
1070 break;
1072 break;
1074 case '-':
1076 const struct textargs *tx;
1077 size_t olen, plen;
1078 char *eqsave;
1080 p += 2;
1082 if (!*p) { /* -- => stop processing options */
1083 stopoptions = true;
1084 break;
1087 plen = strlen(p);
1088 for (tx = textopts; tx->label; tx++) {
1089 olen = strlen(tx->label);
1091 if (olen > plen)
1092 continue;
1094 if (nasm_memicmp(p, tx->label, olen))
1095 continue;
1097 if (tx->label[olen-1] == '-')
1098 break; /* Incomplete option */
1100 if (!p[olen] || p[olen] == '=')
1101 break; /* Complete option */
1104 if (!tx->label) {
1105 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1106 "unrecognized option `--%s'", p);
1109 eqsave = param = strchr(p+olen, '=');
1110 if (param)
1111 *param++ = '\0';
1113 if (tx->need_arg) {
1114 if (!param) {
1115 param = q;
1116 advance = true;
1119 /* Note: a null string is a valid parameter */
1120 if (!param) {
1121 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1122 "option `--%s' requires an argument",
1124 break;
1126 } else {
1127 if (param) {
1128 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1129 "option `--%s' does not take an argument",
1135 switch (tx->opt) {
1136 case OPT_VERSION:
1137 show_version();
1138 break;
1139 case OPT_ABORT_ON_PANIC:
1140 abort_on_panic = true;
1141 break;
1142 case OPT_MANGLE:
1143 if (pass == 2)
1144 set_label_mangle(tx->pvt, param);
1145 break;
1146 case OPT_INCLUDE:
1147 if (pass == 2)
1148 preproc->pre_include(q);
1149 break;
1150 case OPT_PRAGMA:
1151 if (pass == 2)
1152 preproc->pre_command("pragma", param);
1153 break;
1154 case OPT_BEFORE:
1155 if (pass == 2)
1156 preproc->pre_command(NULL, param);
1157 break;
1158 case OPT_LIMIT:
1159 if (pass == 2)
1160 nasm_set_limit(p+olen, param);
1161 break;
1162 case OPT_KEEP_ALL:
1163 keep_all = true;
1164 break;
1165 case OPT_HELP:
1166 help(0);
1167 exit(0);
1168 default:
1169 panic();
1172 if (eqsave)
1173 *eqsave = '='; /* Restore = argument separator */
1175 break;
1178 default:
1179 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1180 "unrecognised option `-%c'", p[1]);
1181 break;
1183 } else if (pass == 2) {
1184 /* In theory we could allow multiple input files... */
1185 copy_filename(&inname, p, "input");
1188 return advance;
1191 #define ARG_BUF_DELTA 128
1193 static void process_respfile(FILE * rfile, int pass)
1195 char *buffer, *p, *q, *prevarg;
1196 int bufsize, prevargsize;
1198 bufsize = prevargsize = ARG_BUF_DELTA;
1199 buffer = nasm_malloc(ARG_BUF_DELTA);
1200 prevarg = nasm_malloc(ARG_BUF_DELTA);
1201 prevarg[0] = '\0';
1203 while (1) { /* Loop to handle all lines in file */
1204 p = buffer;
1205 while (1) { /* Loop to handle long lines */
1206 q = fgets(p, bufsize - (p - buffer), rfile);
1207 if (!q)
1208 break;
1209 p += strlen(p);
1210 if (p > buffer && p[-1] == '\n')
1211 break;
1212 if (p - buffer > bufsize - 10) {
1213 int offset;
1214 offset = p - buffer;
1215 bufsize += ARG_BUF_DELTA;
1216 buffer = nasm_realloc(buffer, bufsize);
1217 p = buffer + offset;
1221 if (!q && p == buffer) {
1222 if (prevarg[0])
1223 process_arg(prevarg, NULL, pass);
1224 nasm_free(buffer);
1225 nasm_free(prevarg);
1226 return;
1230 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1231 * them are present at the end of the line.
1233 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1235 while (p > buffer && nasm_isspace(p[-1]))
1236 *--p = '\0';
1238 p = nasm_skip_spaces(buffer);
1240 if (process_arg(prevarg, p, pass))
1241 *p = '\0';
1243 if ((int) strlen(p) > prevargsize - 10) {
1244 prevargsize += ARG_BUF_DELTA;
1245 prevarg = nasm_realloc(prevarg, prevargsize);
1247 strncpy(prevarg, p, prevargsize);
1251 /* Function to process args from a string of args, rather than the
1252 * argv array. Used by the environment variable and response file
1253 * processing.
1255 static void process_args(char *args, int pass)
1257 char *p, *q, *arg, *prevarg;
1258 char separator = ' ';
1260 p = args;
1261 if (*p && *p != '-')
1262 separator = *p++;
1263 arg = NULL;
1264 while (*p) {
1265 q = p;
1266 while (*p && *p != separator)
1267 p++;
1268 while (*p == separator)
1269 *p++ = '\0';
1270 prevarg = arg;
1271 arg = q;
1272 if (process_arg(prevarg, arg, pass))
1273 arg = NULL;
1275 if (arg)
1276 process_arg(arg, NULL, pass);
1279 static void process_response_file(const char *file, int pass)
1281 char str[2048];
1282 FILE *f = nasm_open_read(file, NF_TEXT);
1283 if (!f) {
1284 perror(file);
1285 exit(-1);
1287 while (fgets(str, sizeof str, f)) {
1288 process_args(str, pass);
1290 fclose(f);
1293 static void parse_cmdline(int argc, char **argv, int pass)
1295 FILE *rfile;
1296 char *envreal, *envcopy = NULL, *p;
1297 int i;
1299 /* Initialize all the warnings to their default state */
1300 for (i = 0; i < ERR_WARN_ALL; i++) {
1301 warning_state_init[i] = warning_state[i] =
1302 warnings[i].enabled ? WARN_ST_ENABLED : 0;
1306 * First, process the NASMENV environment variable.
1308 envreal = getenv("NASMENV");
1309 if (envreal) {
1310 envcopy = nasm_strdup(envreal);
1311 process_args(envcopy, pass);
1312 nasm_free(envcopy);
1316 * Now process the actual command line.
1318 while (--argc) {
1319 bool advance;
1320 argv++;
1321 if (argv[0][0] == '@') {
1323 * We have a response file, so process this as a set of
1324 * arguments like the environment variable. This allows us
1325 * to have multiple arguments on a single line, which is
1326 * different to the -@resp file processing below for regular
1327 * NASM.
1329 process_response_file(argv[0]+1, pass);
1330 argc--;
1331 argv++;
1333 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1334 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1335 if (p) {
1336 rfile = nasm_open_read(p, NF_TEXT);
1337 if (rfile) {
1338 process_respfile(rfile, pass);
1339 fclose(rfile);
1340 } else
1341 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1342 "unable to open response file `%s'", p);
1344 } else
1345 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1346 argv += advance, argc -= advance;
1350 * Look for basic command line typos. This definitely doesn't
1351 * catch all errors, but it might help cases of fumbled fingers.
1353 if (pass != 2)
1354 return;
1356 if (!inname)
1357 nasm_fatal(ERR_NOFILE | ERR_USAGE, "no input file specified");
1359 else if ((errname && !strcmp(inname, errname)) ||
1360 (outname && !strcmp(inname, outname)) ||
1361 (listname && !strcmp(inname, listname)) ||
1362 (depend_file && !strcmp(inname, depend_file)))
1363 nasm_fatal(ERR_USAGE, "will not overwrite input file");
1365 if (errname) {
1366 error_file = nasm_open_write(errname, NF_TEXT);
1367 if (!error_file) {
1368 error_file = stderr; /* Revert to default! */
1369 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1370 "cannot open file `%s' for error messages",
1371 errname);
1376 static void assemble_file(const char *fname, StrList **depend_ptr)
1378 char *line;
1379 insn output_ins;
1380 int i;
1381 uint64_t prev_offset_changed;
1382 int64_t stall_count = 0; /* Make sure we make forward progress... */
1384 switch (cmd_sb) {
1385 case 16:
1386 break;
1387 case 32:
1388 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1389 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1390 break;
1391 case 64:
1392 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1393 nasm_fatal(0, "command line: 64-bit segment size requires a higher cpu");
1394 break;
1395 default:
1396 panic();
1397 break;
1400 prev_offset_changed = nasm_limit[LIMIT_PASSES];
1401 for (passn = 1; pass0 <= 2; passn++) {
1402 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1403 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1404 /* pass0 0, 0, 0, ..., 1, 2 */
1406 globalbits = cmd_sb; /* set 'bits' to command line default */
1407 cpu = cmd_cpu;
1408 if (pass0 == 2) {
1409 lfmt->init(listname);
1410 } else if (passn == 1 && listname && !keep_all) {
1411 /* Remove the list file in case we die before the output pass */
1412 remove(listname);
1414 in_absolute = false;
1415 global_offset_changed = 0; /* set by redefine_label */
1416 if (passn > 1) {
1417 saa_rewind(forwrefs);
1418 forwref = saa_rstruct(forwrefs);
1419 raa_free(offsets);
1420 offsets = raa_init();
1422 location.segment = NO_SEG;
1423 location.offset = 0;
1424 if (passn == 1)
1425 location.known = true;
1426 ofmt->reset();
1427 switch_segment(ofmt->section(NULL, pass2, &globalbits));
1428 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1430 /* Revert all warnings to the default state */
1431 memcpy(warning_state, warning_state_init, sizeof warning_state);
1433 globallineno = 0;
1435 while ((line = preproc->getline())) {
1436 if (++globallineno > nasm_limit[LIMIT_LINES])
1437 nasm_fatal(0,
1438 "overall line count exceeds the maximum %"PRId64"\n",
1439 nasm_limit[LIMIT_LINES]);
1442 * Here we parse our directives; this is not handled by the
1443 * main parser.
1445 if (process_directives(line))
1446 goto end_of_line; /* Just do final cleanup */
1448 /* Not a directive, or even something that starts with [ */
1449 parse_line(pass1, line, &output_ins);
1451 if (optimizing > 0) {
1452 if (forwref != NULL && globallineno == forwref->lineno) {
1453 output_ins.forw_ref = true;
1454 do {
1455 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1456 forwref = saa_rstruct(forwrefs);
1457 } while (forwref != NULL
1458 && forwref->lineno == globallineno);
1459 } else
1460 output_ins.forw_ref = false;
1462 if (output_ins.forw_ref) {
1463 if (passn == 1) {
1464 for (i = 0; i < output_ins.operands; i++) {
1465 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1466 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1467 fwinf->lineno = globallineno;
1468 fwinf->operand = i;
1475 /* forw_ref */
1476 if (output_ins.opcode == I_EQU) {
1477 if (!output_ins.label)
1478 nasm_error(ERR_NONFATAL,
1479 "EQU not preceded by label");
1481 if (output_ins.operands == 1 &&
1482 (output_ins.oprs[0].type & IMMEDIATE) &&
1483 output_ins.oprs[0].wrt == NO_SEG) {
1484 define_label(output_ins.label,
1485 output_ins.oprs[0].segment,
1486 output_ins.oprs[0].offset, false);
1487 } else if (output_ins.operands == 2
1488 && (output_ins.oprs[0].type & IMMEDIATE)
1489 && (output_ins.oprs[0].type & COLON)
1490 && output_ins.oprs[0].segment == NO_SEG
1491 && output_ins.oprs[0].wrt == NO_SEG
1492 && (output_ins.oprs[1].type & IMMEDIATE)
1493 && output_ins.oprs[1].segment == NO_SEG
1494 && output_ins.oprs[1].wrt == NO_SEG) {
1495 define_label(output_ins.label,
1496 output_ins.oprs[0].offset | SEG_ABS,
1497 output_ins.oprs[1].offset, false);
1498 } else {
1499 nasm_error(ERR_NONFATAL, "bad syntax for EQU");
1501 } else { /* instruction isn't an EQU */
1502 int32_t n;
1504 nasm_assert(output_ins.times >= 0);
1506 for (n = 1; n <= output_ins.times; n++) {
1507 if (pass1 == 1) {
1508 int64_t l = insn_size(location.segment,
1509 location.offset,
1510 globalbits, &output_ins);
1512 /* if (using_debug_info) && output_ins.opcode != -1) */
1513 if (using_debug_info)
1514 { /* fbk 03/25/01 */
1515 /* this is done here so we can do debug type info */
1516 int32_t typeinfo =
1517 TYS_ELEMENTS(output_ins.operands);
1518 switch (output_ins.opcode) {
1519 case I_RESB:
1520 typeinfo =
1521 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1522 break;
1523 case I_RESW:
1524 typeinfo =
1525 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1526 break;
1527 case I_RESD:
1528 typeinfo =
1529 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1530 break;
1531 case I_RESQ:
1532 typeinfo =
1533 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1534 break;
1535 case I_REST:
1536 typeinfo =
1537 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1538 break;
1539 case I_RESO:
1540 typeinfo =
1541 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1542 break;
1543 case I_RESY:
1544 typeinfo =
1545 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1546 break;
1547 case I_RESZ:
1548 typeinfo =
1549 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;
1550 break;
1551 case I_DB:
1552 typeinfo |= TY_BYTE;
1553 break;
1554 case I_DW:
1555 typeinfo |= TY_WORD;
1556 break;
1557 case I_DD:
1558 if (output_ins.eops_float)
1559 typeinfo |= TY_FLOAT;
1560 else
1561 typeinfo |= TY_DWORD;
1562 break;
1563 case I_DQ:
1564 typeinfo |= TY_QWORD;
1565 break;
1566 case I_DT:
1567 typeinfo |= TY_TBYTE;
1568 break;
1569 case I_DO:
1570 typeinfo |= TY_OWORD;
1571 break;
1572 case I_DY:
1573 typeinfo |= TY_YWORD;
1574 break;
1575 case I_DZ:
1576 typeinfo |= TY_ZWORD;
1577 break;
1578 default:
1579 typeinfo = TY_LABEL;
1580 break;
1583 dfmt->debug_typevalue(typeinfo);
1587 * For INCBIN, let the code in assemble
1588 * handle TIMES, so we don't have to read the
1589 * input file over and over.
1591 if (l != -1) {
1592 increment_offset(l);
1595 * else l == -1 => invalid instruction, which will be
1596 * flagged as an error on pass 2
1598 } else {
1599 if (n == 2)
1600 lfmt->uplevel(LIST_TIMES);
1601 increment_offset(assemble(location.segment,
1602 location.offset,
1603 globalbits, &output_ins));
1605 } /* not an EQU */
1607 if (output_ins.times > 1)
1608 lfmt->downlevel(LIST_TIMES);
1610 cleanup_insn(&output_ins);
1612 end_of_line:
1613 nasm_free(line);
1614 } /* end while (line = preproc->getline... */
1616 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1617 nasm_error(ERR_NONFATAL,
1618 "phase error detected at end of assembly.");
1620 if (pass1 == 1)
1621 preproc->cleanup(1);
1624 * Always run at least two optimization passes (pass0 == 0);
1625 * things like subsections will fail miserably without that.
1626 * Once we commit to a stabilization pass (pass0 == 1), we can't
1627 * go back, and if something goes bad, we can only hope
1628 * that we don't end up with a phase error at the end.
1630 if ((passn > 1 && !global_offset_changed) || pass0 > 0) {
1631 pass0++;
1632 } else if (global_offset_changed &&
1633 global_offset_changed < prev_offset_changed) {
1634 prev_offset_changed = global_offset_changed;
1635 stall_count = 0;
1636 } else {
1637 stall_count++;
1640 if (terminate_after_phase)
1641 break;
1643 if ((stall_count > nasm_limit[LIMIT_STALLED]) ||
1644 (passn >= nasm_limit[LIMIT_PASSES])) {
1645 /* We get here if the labels don't converge
1646 * Example: FOO equ FOO + 1
1648 nasm_error(ERR_NONFATAL,
1649 "Can't find valid values for all labels "
1650 "after %"PRId64" passes, giving up.", passn);
1651 nasm_error(ERR_NONFATAL,
1652 "Possible causes: recursive EQUs, macro abuse.");
1653 break;
1657 preproc->cleanup(0);
1658 lfmt->cleanup();
1659 if (!terminate_after_phase && opt_verbose_info) {
1660 /* -On and -Ov switches */
1661 fprintf(stdout, "info: assembly required 1+%"PRId64"+1 passes\n",
1662 passn-3);
1667 * gnu style error reporting
1668 * This function prints an error message to error_file in the
1669 * style used by GNU. An example would be:
1670 * file.asm:50: error: blah blah blah
1671 * where file.asm is the name of the file, 50 is the line number on
1672 * which the error occurs (or is detected) and "error:" is one of
1673 * the possible optional diagnostics -- it can be "error" or "warning"
1674 * or something else. Finally the line terminates with the actual
1675 * error message.
1677 * @param severity the severity of the warning or error
1678 * @param fmt the printf style format string
1680 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1682 const char *currentfile = NULL;
1683 int32_t lineno = 0;
1685 if (is_suppressed_warning(severity))
1686 return;
1688 if (!(severity & ERR_NOFILE)) {
1689 src_get(&lineno, &currentfile);
1690 if (!currentfile || (severity & ERR_TOPFILE)) {
1691 currentfile = inname[0] ? inname : outname[0] ? outname : NULL;
1692 lineno = 0;
1696 if (!skip_this_pass(severity)) {
1697 if (!lineno)
1698 fprintf(error_file, "%s:", currentfile ? currentfile : "nasm");
1699 else
1700 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1703 nasm_verror_common(severity, fmt, ap);
1707 * MS style error reporting
1708 * This function prints an error message to error_file in the
1709 * style used by Visual C and some other Microsoft tools. An example
1710 * would be:
1711 * file.asm(50) : error: blah blah blah
1712 * where file.asm is the name of the file, 50 is the line number on
1713 * which the error occurs (or is detected) and "error:" is one of
1714 * the possible optional diagnostics -- it can be "error" or "warning"
1715 * or something else. Finally the line terminates with the actual
1716 * error message.
1718 * @param severity the severity of the warning or error
1719 * @param fmt the printf style format string
1721 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1723 const char *currentfile = NULL;
1724 int32_t lineno = 0;
1726 if (is_suppressed_warning(severity))
1727 return;
1729 if (!(severity & ERR_NOFILE))
1730 src_get(&lineno, &currentfile);
1732 if (!skip_this_pass(severity)) {
1733 if (currentfile) {
1734 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1735 } else {
1736 fputs("nasm: ", error_file);
1740 nasm_verror_common(severity, fmt, ap);
1744 * check to see if this is a suppressable warning
1746 static inline bool is_valid_warning(int severity)
1748 /* Not a warning at all */
1749 if ((severity & ERR_MASK) != ERR_WARNING)
1750 return false;
1752 return WARN_IDX(severity) < ERR_WARN_ALL;
1756 * check for suppressed warning
1757 * checks for suppressed warning or pass one only warning and we're
1758 * not in pass 1
1760 * @param severity the severity of the warning or error
1761 * @return true if we should abort error/warning printing
1763 static bool is_suppressed_warning(int severity)
1765 /* Might be a warning but suppresed explicitly */
1766 if (is_valid_warning(severity) && !(severity & ERR_USAGE))
1767 return !(warning_state[WARN_IDX(severity)] & WARN_ST_ENABLED);
1768 else
1769 return false;
1772 static bool warning_is_error(int severity)
1774 if (is_valid_warning(severity))
1775 return !!(warning_state[WARN_IDX(severity)] & WARN_ST_ERROR);
1776 else
1777 return false;
1780 static bool skip_this_pass(int severity)
1783 * See if it's a pass-specific error or warning which should be skipped.
1784 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1785 * they cannot be resumed from.
1787 if ((severity & ERR_MASK) > ERR_NONFATAL)
1788 return false;
1791 * passn is 1 on the very first pass only.
1792 * pass0 is 2 on the code-generation (final) pass only.
1793 * These are the passes we care about in this case.
1795 return (((severity & ERR_PASS1) && passn != 1) ||
1796 ((severity & ERR_PASS2) && pass0 != 2));
1800 * common error reporting
1801 * This is the common back end of the error reporting schemes currently
1802 * implemented. It prints the nature of the warning and then the
1803 * specific error message to error_file and may or may not return. It
1804 * doesn't return if the error severity is a "panic" or "debug" type.
1806 * @param severity the severity of the warning or error
1807 * @param fmt the printf style format string
1809 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1811 char msg[1024];
1812 const char *pfx;
1814 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1815 case ERR_WARNING:
1816 pfx = "warning: ";
1817 break;
1818 case ERR_NONFATAL:
1819 pfx = "error: ";
1820 break;
1821 case ERR_FATAL:
1822 pfx = "fatal: ";
1823 break;
1824 case ERR_PANIC:
1825 pfx = "panic: ";
1826 break;
1827 case ERR_DEBUG:
1828 pfx = "debug: ";
1829 break;
1830 default:
1831 pfx = "";
1832 break;
1835 vsnprintf(msg, sizeof msg - 64, fmt, args);
1836 if (is_valid_warning(severity) && WARN_IDX(severity) != ERR_WARN_OTHER) {
1837 char *p = strchr(msg, '\0');
1838 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
1841 if (!skip_this_pass(severity))
1842 fprintf(error_file, "%s%s\n", pfx, msg);
1844 /* Are we recursing from error_list_macros? */
1845 if (severity & ERR_PP_LISTMACRO)
1846 return;
1849 * Don't suppress this with skip_this_pass(), or we don't get
1850 * pass1 or preprocessor warnings in the list file
1852 lfmt->error(severity, pfx, msg);
1854 if (skip_this_pass(severity))
1855 return;
1857 if (severity & ERR_USAGE)
1858 want_usage = true;
1860 preproc->error_list_macros(severity);
1862 switch (severity & ERR_MASK) {
1863 case ERR_DEBUG:
1864 /* no further action, by definition */
1865 break;
1866 case ERR_WARNING:
1867 /* Treat warnings as errors */
1868 if (warning_is_error(severity))
1869 terminate_after_phase = true;
1870 break;
1871 case ERR_NONFATAL:
1872 terminate_after_phase = true;
1873 break;
1874 case ERR_FATAL:
1875 if (ofile) {
1876 fclose(ofile);
1877 if (!keep_all)
1878 remove(outname);
1879 ofile = NULL;
1881 if (want_usage)
1882 usage();
1883 exit(1); /* instantly die */
1884 break; /* placate silly compilers */
1885 case ERR_PANIC:
1886 fflush(NULL);
1888 if (abort_on_panic)
1889 abort(); /* halt, catch fire, dump core/stop debugger */
1891 if (ofile) {
1892 fclose(ofile);
1893 if (!keep_all)
1894 remove(outname);
1895 ofile = NULL;
1897 exit(3);
1898 break;
1902 static void usage(void)
1904 fputs("type `nasm -h' for help\n", error_file);
1907 static void help(const char xopt)
1909 int i;
1911 printf
1912 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1913 "[-l listfile]\n"
1914 " [options...] [--] filename\n"
1915 " or nasm -v (or --v) for version info\n\n"
1916 "\n"
1917 "Response files should contain command line parameters,\n"
1918 "one per line.\n"
1919 "\n"
1920 " -t assemble in SciTech TASM compatible mode\n");
1921 printf
1922 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1923 " -a don't preprocess (assemble only)\n"
1924 " -M generate Makefile dependencies on stdout\n"
1925 " -MG d:o, missing files assumed generated\n"
1926 " -MF file set Makefile dependency file\n"
1927 " -MD file assemble and generate dependencies\n"
1928 " -MT file dependency target name\n"
1929 " -MQ file dependency target name (quoted)\n"
1930 " -MP emit phony target\n\n"
1931 " -Zfile redirect error messages to file\n"
1932 " -s redirect error messages to stdout\n\n"
1933 " -g generate debugging information\n\n"
1934 " -F format select a debugging format\n\n"
1935 " -gformat same as -g -F format\n\n"
1936 " -o outfile write output to an outfile\n\n"
1937 " -f format select an output format\n\n"
1938 " -l listfile write listing to a listfile\n\n"
1939 " -Ipath add a pathname to the include file path\n");
1940 printf
1941 (" -Olevel optimize opcodes, immediates and branch offsets\n"
1942 " -O0 no optimization\n"
1943 " -O1 minimal optimization\n"
1944 " -Ox multipass optimization (default)\n"
1945 " -Pfile pre-include a file (also --include)\n"
1946 " -Dmacro[=str] pre-define a macro\n"
1947 " -Umacro undefine a macro\n"
1948 " -Xformat specifiy error reporting format (gnu or vc)\n"
1949 " -w+foo enable warning foo (equiv. -Wfoo)\n"
1950 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
1951 " -w[+-]error[=foo]\n"
1952 " promote [specific] warnings to errors\n"
1953 " -h show invocation summary and exit (also --help)\n\n"
1954 " --pragma str pre-executes a specific %%pragma\n"
1955 " --before str add line (usually a preprocessor statement) before the input\n"
1956 " --prefix str prepend the given string to all the given string\n"
1957 " to all extern, common and global symbols (also --gprefix)\n"
1958 " --postfix str append the given string to all the given string\n"
1959 " to all extern, common and global symbols (also --gpostfix)\n"
1960 " --lprefix str prepend the given string to all other symbols\n"
1961 " --lpostfix str append the given string to all other symbols\n"
1962 " --keep-all output files will not be removed even if an error happens\n"
1963 " --limit-X val set execution limit X\n");
1965 for (i = 0; i <= LIMIT_MAX; i++) {
1966 printf(" %-15s %s (default ",
1967 limit_info[i].name, limit_info[i].help);
1968 if (nasm_limit[i] < LIMIT_MAX_VAL) {
1969 printf("%"PRId64")\n", nasm_limit[i]);
1970 } else {
1971 printf("unlimited)\n");
1975 printf("\nWarnings for the -W/-w options:\n");
1977 for (i = 0; i <= ERR_WARN_ALL; i++)
1978 printf(" %-23s %s%s\n",
1979 warnings[i].name, warnings[i].help,
1980 i == ERR_WARN_ALL ? "\n" :
1981 warnings[i].enabled ? " (default on)" :
1982 " (default off)");
1984 if (xopt == 'f') {
1985 printf("valid output formats for -f are"
1986 " (`*' denotes default):\n");
1987 ofmt_list(ofmt, stdout);
1988 } else {
1989 printf("For a list of valid output formats, use -hf.\n");
1990 printf("For a list of debug formats, use -f <format> -y.\n");