Merge branch 'nasm-2.13.xx'
[nasm.git] / asm / nasm.c
blob666c33753bf0b13060c98a87f714d3dce06ee48f
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);
86 static bool using_debug_info, opt_verbose_info;
87 static const char *debug_format;
89 #ifndef ABORT_ON_PANIC
90 # define ABORT_ON_PANIC 0
91 #endif
92 static bool abort_on_panic = ABORT_ON_PANIC;
94 bool tasm_compatible_mode = false;
95 int pass0, passn;
96 static int pass1, pass2; /* XXX: Get rid of these, they are redundant */
97 int globalrel = 0;
98 int globalbnd = 0;
100 struct compile_time official_compile_time;
102 const char *inname;
103 const char *outname;
104 static const char *listname;
105 static const char *errname;
107 static int globallineno; /* for forward-reference tracking */
108 /* static int pass = 0; */
109 const struct ofmt *ofmt = &OF_DEFAULT;
110 const struct ofmt_alias *ofmt_alias = NULL;
111 const struct dfmt *dfmt;
113 static FILE *error_file; /* Where to write error messages */
115 FILE *ofile = NULL;
116 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
117 static int cmd_sb = 16; /* by default */
119 iflag_t cpu;
120 static iflag_t cmd_cpu;
122 struct location location;
123 bool in_absolute; /* Flag we are in ABSOLUTE seg */
124 struct location absolute; /* Segment/offset inside ABSOLUTE */
126 static struct RAA *offsets;
128 static struct SAA *forwrefs; /* keep track of forward references */
129 static const struct forwrefinfo *forwref;
131 static const struct preproc_ops *preproc;
133 #define OP_NORMAL (1u << 0)
134 #define OP_PREPROCESS (1u << 1)
135 #define OP_DEPEND (1u << 2)
137 static unsigned int operating_mode;
139 /* Dependency flags */
140 static bool depend_emit_phony = false;
141 static bool depend_missing_ok = false;
142 static const char *depend_target = NULL;
143 static const char *depend_file = NULL;
144 StrList *depend_list;
146 static bool want_usage;
147 static bool terminate_after_phase;
148 bool user_nolist = false;
150 static char *quote_for_pmake(const char *str);
151 static char *quote_for_wmake(const char *str);
152 static char *(*quote_for_make)(const char *) = quote_for_pmake;
154 static int64_t get_curr_offs(void)
156 return in_absolute ? absolute.offset : raa_read(offsets, location.segment);
159 static void set_curr_offs(int64_t l_off)
161 if (in_absolute)
162 absolute.offset = l_off;
163 else
164 offsets = raa_write(offsets, location.segment, l_off);
167 static void nasm_fputs(const char *line, FILE * outfile)
169 if (outfile) {
170 fputs(line, outfile);
171 putc('\n', outfile);
172 } else
173 puts(line);
176 static void define_macros_early(void)
178 const struct compile_time * const oct = &official_compile_time;
179 char temp[128];
181 if (oct->have_local) {
182 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &oct->local);
183 preproc->pre_define(temp);
184 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &oct->local);
185 preproc->pre_define(temp);
186 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &oct->local);
187 preproc->pre_define(temp);
188 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &oct->local);
189 preproc->pre_define(temp);
192 if (oct->have_gm) {
193 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &oct->gm);
194 preproc->pre_define(temp);
195 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &oct->gm);
196 preproc->pre_define(temp);
197 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &oct->gm);
198 preproc->pre_define(temp);
199 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &oct->gm);
200 preproc->pre_define(temp);
203 if (oct->have_posix) {
204 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, oct->posix);
205 preproc->pre_define(temp);
209 static void define_macros_late(void)
211 char temp[128];
214 * In case if output format is defined by alias
215 * we have to put shortname of the alias itself here
216 * otherwise ABI backward compatibility gets broken.
218 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
219 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
220 preproc->pre_define(temp);
223 static void emit_dependencies(StrList *list)
225 FILE *deps;
226 int linepos, len;
227 StrList *l, *nl;
228 bool wmake = (quote_for_make == quote_for_wmake);
229 const char *wrapstr, *nulltarget;
231 wrapstr = wmake ? " &\n " : " \\\n ";
232 nulltarget = wmake ? "\t%null\n" : "";
234 if (depend_file && strcmp(depend_file, "-")) {
235 deps = nasm_open_write(depend_file, NF_TEXT);
236 if (!deps) {
237 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
238 "unable to write dependency file `%s'", depend_file);
239 return;
241 } else {
242 deps = stdout;
245 linepos = fprintf(deps, "%s :", depend_target);
246 list_for_each(l, list) {
247 char *file = quote_for_make(l->str);
248 len = strlen(file);
249 if (linepos + len > 62 && linepos > 1) {
250 fputs(wrapstr, deps);
251 linepos = 1;
253 fprintf(deps, " %s", file);
254 linepos += len+1;
255 nasm_free(file);
257 fprintf(deps, "\n\n");
259 list_for_each_safe(l, nl, list) {
260 if (depend_emit_phony) {
261 char *file = quote_for_make(l->str);
262 fprintf(deps, "%s :\n%s\n", file, nulltarget);
263 nasm_free(file);
265 nasm_free(l);
268 if (deps != stdout)
269 fclose(deps);
272 /* Convert a struct tm to a POSIX-style time constant */
273 static int64_t make_posix_time(const struct tm *tm)
275 int64_t t;
276 int64_t y = tm->tm_year;
278 /* See IEEE 1003.1:2004, section 4.14 */
280 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
281 t += tm->tm_yday;
282 t *= 24;
283 t += tm->tm_hour;
284 t *= 60;
285 t += tm->tm_min;
286 t *= 60;
287 t += tm->tm_sec;
289 return t;
292 static void timestamp(void)
294 struct compile_time * const oct = &official_compile_time;
295 const struct tm *tp, *best_gm;
297 time(&oct->t);
299 best_gm = NULL;
301 tp = localtime(&oct->t);
302 if (tp) {
303 oct->local = *tp;
304 best_gm = &oct->local;
305 oct->have_local = true;
308 tp = gmtime(&oct->t);
309 if (tp) {
310 oct->gm = *tp;
311 best_gm = &oct->gm;
312 oct->have_gm = true;
313 if (!oct->have_local)
314 oct->local = oct->gm;
315 } else {
316 oct->gm = oct->local;
319 if (best_gm) {
320 oct->posix = make_posix_time(best_gm);
321 oct->have_posix = true;
325 int main(int argc, char **argv)
327 StrList **depend_ptr;
329 timestamp();
331 iflag_set_default_cpu(&cpu);
332 iflag_set_default_cpu(&cmd_cpu);
334 pass0 = 0;
335 want_usage = terminate_after_phase = false;
336 nasm_set_verror(nasm_verror_gnu);
338 error_file = stderr;
340 tolower_init();
341 src_init();
343 offsets = raa_init();
344 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
346 preproc = &nasmpp;
347 operating_mode = OP_NORMAL;
349 parse_cmdline(argc, argv, 1);
350 if (terminate_after_phase) {
351 if (want_usage)
352 usage();
353 return 1;
357 * Define some macros dependent on the runtime, but not
358 * on the command line (as those are scanned in cmdline pass 2.)
360 preproc->init();
361 define_macros_early();
363 parse_cmdline(argc, argv, 2);
364 if (terminate_after_phase) {
365 if (want_usage)
366 usage();
367 return 1;
370 /* Save away the default state of warnings */
371 memcpy(warning_state_init, warning_state, sizeof warning_state);
373 if (!using_debug_info) {
374 /* No debug info, redirect to the null backend (empty stubs) */
375 dfmt = &null_debug_form;
376 } else if (!debug_format) {
377 /* Default debug format for this backend */
378 dfmt = ofmt->default_dfmt;
379 } else {
380 dfmt = dfmt_find(ofmt, debug_format);
381 if (!dfmt) {
382 nasm_fatal(ERR_NOFILE | ERR_USAGE,
383 "unrecognized debug format `%s' for"
384 " output format `%s'",
385 debug_format, ofmt->shortname);
389 if (ofmt->stdmac)
390 preproc->extra_stdmac(ofmt->stdmac);
392 /* no output file name? */
393 if (!outname)
394 outname = filename_set_extension(inname, ofmt->extension);
396 /* define some macros dependent of command-line */
397 define_macros_late();
399 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
401 if (!depend_target)
402 depend_target = quote_for_make(outname);
404 if (operating_mode & OP_DEPEND) {
405 char *line;
407 if (depend_missing_ok)
408 preproc->include_path(NULL); /* "assume generated" */
410 preproc->reset(inname, 0, depend_ptr);
411 ofile = NULL;
412 while ((line = preproc->getline()))
413 nasm_free(line);
414 preproc->cleanup(0);
415 } else if (operating_mode & OP_PREPROCESS) {
416 char *line;
417 const char *file_name = NULL;
418 int32_t prior_linnum = 0;
419 int lineinc = 0;
421 if (outname) {
422 ofile = nasm_open_write(outname, NF_TEXT);
423 if (!ofile)
424 nasm_fatal(ERR_NOFILE,
425 "unable to open output file `%s'",
426 outname);
427 } else
428 ofile = NULL;
430 location.known = false;
432 /* pass = 1; */
433 preproc->reset(inname, 3, depend_ptr);
435 /* Revert all warnings to the default state */
436 memcpy(warning_state, warning_state_init, sizeof warning_state);
438 while ((line = preproc->getline())) {
440 * We generate %line directives if needed for later programs
442 int32_t linnum = prior_linnum += lineinc;
443 int altline = src_get(&linnum, &file_name);
444 if (altline) {
445 if (altline == 1 && lineinc == 1)
446 nasm_fputs("", ofile);
447 else {
448 lineinc = (altline != -1 || lineinc != 1);
449 fprintf(ofile ? ofile : stdout,
450 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
451 file_name);
453 prior_linnum = linnum;
455 nasm_fputs(line, ofile);
456 nasm_free(line);
458 preproc->cleanup(0);
459 if (ofile)
460 fclose(ofile);
461 if (ofile && terminate_after_phase)
462 remove(outname);
463 ofile = NULL;
466 if (operating_mode & OP_NORMAL) {
467 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
468 if (!ofile)
469 nasm_fatal(ERR_NOFILE,
470 "unable to open output file `%s'", outname);
473 * We must call init_labels() before ofmt->init() since
474 * some object formats will want to define labels in their
475 * init routines. (eg OS/2 defines the FLAT group)
477 init_labels();
479 ofmt->init();
480 dfmt->init();
482 assemble_file(inname, depend_ptr);
484 if (!terminate_after_phase) {
485 ofmt->cleanup();
486 cleanup_labels();
487 fflush(ofile);
488 if (ferror(ofile)) {
489 nasm_error(ERR_NONFATAL|ERR_NOFILE,
490 "write error on output file `%s'", outname);
491 terminate_after_phase = true;
495 if (ofile) {
496 fclose(ofile);
497 if (terminate_after_phase)
498 remove(outname);
499 ofile = NULL;
503 if (depend_list && !terminate_after_phase)
504 emit_dependencies(depend_list);
506 if (want_usage)
507 usage();
509 raa_free(offsets);
510 saa_free(forwrefs);
511 eval_cleanup();
512 stdscan_cleanup();
513 src_free();
515 return terminate_after_phase;
519 * Get a parameter for a command line option.
520 * First arg must be in the form of e.g. -f...
522 static char *get_param(char *p, char *q, bool *advance)
524 *advance = false;
525 if (p[2]) /* the parameter's in the option */
526 return nasm_skip_spaces(p + 2);
527 if (q && q[0]) {
528 *advance = true;
529 return q;
531 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
532 "option `-%c' requires an argument", p[1]);
533 return NULL;
537 * Copy a filename
539 static void copy_filename(const char **dst, const char *src, const char *what)
541 if (*dst)
542 nasm_fatal(0, "more than one %s file specified: %s\n", what, src);
544 *dst = nasm_strdup(src);
548 * Convert a string to a POSIX make-safe form
550 static char *quote_for_pmake(const char *str)
552 const char *p;
553 char *os, *q;
555 size_t n = 1; /* Terminating zero */
556 size_t nbs = 0;
558 if (!str)
559 return NULL;
561 for (p = str; *p; p++) {
562 switch (*p) {
563 case ' ':
564 case '\t':
565 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
566 n += nbs + 2;
567 nbs = 0;
568 break;
569 case '$':
570 case '#':
571 nbs = 0;
572 n += 2;
573 break;
574 case '\\':
575 nbs++;
576 n++;
577 break;
578 default:
579 nbs = 0;
580 n++;
581 break;
585 /* Convert N backslashes at the end of filename to 2N backslashes */
586 if (nbs)
587 n += nbs;
589 os = q = nasm_malloc(n);
591 nbs = 0;
592 for (p = str; *p; p++) {
593 switch (*p) {
594 case ' ':
595 case '\t':
596 while (nbs--)
597 *q++ = '\\';
598 *q++ = '\\';
599 *q++ = *p;
600 break;
601 case '$':
602 *q++ = *p;
603 *q++ = *p;
604 nbs = 0;
605 break;
606 case '#':
607 *q++ = '\\';
608 *q++ = *p;
609 nbs = 0;
610 break;
611 case '\\':
612 *q++ = *p;
613 nbs++;
614 break;
615 default:
616 *q++ = *p;
617 nbs = 0;
618 break;
621 while (nbs--)
622 *q++ = '\\';
624 *q = '\0';
626 return os;
630 * Convert a string to a Watcom make-safe form
632 static char *quote_for_wmake(const char *str)
634 const char *p;
635 char *os, *q;
636 bool quote = false;
638 size_t n = 1; /* Terminating zero */
640 if (!str)
641 return NULL;
643 for (p = str; *p; p++) {
644 switch (*p) {
645 case ' ':
646 case '\t':
647 case '&':
648 quote = true;
649 n++;
650 break;
651 case '\"':
652 quote = true;
653 n += 2;
654 break;
655 case '$':
656 case '#':
657 n += 2;
658 break;
659 default:
660 n++;
661 break;
665 if (quote)
666 n += 2;
668 os = q = nasm_malloc(n);
670 if (quote)
671 *q++ = '\"';
673 for (p = str; *p; p++) {
674 switch (*p) {
675 case '$':
676 case '#':
677 *q++ = '$';
678 *q++ = *p;
679 break;
680 case '\"':
681 *q++ = *p;
682 *q++ = *p;
683 break;
684 default:
685 *q++ = *p;
686 break;
690 if (quote)
691 *q++ = '\"';
693 *q = '\0';
695 return os;
698 enum text_options {
699 OPT_BOGUS,
700 OPT_VERSION,
701 OPT_ABORT_ON_PANIC,
702 OPT_PREFIX,
703 OPT_POSTFIX
705 struct textargs {
706 const char *label;
707 enum text_options opt;
708 bool need_arg;
710 static const struct textargs textopts[] = {
711 {"v", OPT_VERSION, false},
712 {"version", OPT_VERSION, false},
713 {"abort-on-panic", OPT_ABORT_ON_PANIC, false},
714 {"prefix", OPT_PREFIX, true},
715 {"postfix", OPT_POSTFIX, true},
716 {NULL, OPT_BOGUS, false}
719 static void show_version(void)
721 printf("NASM version %s compiled on %s%s\n",
722 nasm_version, nasm_date, nasm_compile_options);
723 exit(0);
726 static bool stopoptions = false;
727 static bool process_arg(char *p, char *q, int pass)
729 char *param;
730 int i;
731 bool advance = false;
733 if (!p || !p[0])
734 return false;
736 if (p[0] == '-' && !stopoptions) {
737 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
738 /* These parameters take values */
739 if (!(param = get_param(p, q, &advance)))
740 return advance;
743 switch (p[1]) {
744 case 's':
745 if (pass == 1)
746 error_file = stdout;
747 break;
749 case 'o': /* output file */
750 if (pass == 2)
751 copy_filename(&outname, param, "output");
752 break;
754 case 'f': /* output format */
755 if (pass == 1) {
756 ofmt = ofmt_find(param, &ofmt_alias);
757 if (!ofmt) {
758 nasm_fatal(ERR_NOFILE | ERR_USAGE,
759 "unrecognised output format `%s' - "
760 "use -hf for a list", param);
763 break;
765 case 'O': /* Optimization level */
766 if (pass == 2) {
767 int opt;
769 if (!*param) {
770 /* Naked -O == -Ox */
771 optimizing = MAX_OPTIMIZE;
772 } else {
773 while (*param) {
774 switch (*param) {
775 case '0': case '1': case '2': case '3': case '4':
776 case '5': case '6': case '7': case '8': case '9':
777 opt = strtoul(param, &param, 10);
779 /* -O0 -> optimizing == -1, 0.98 behaviour */
780 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
781 if (opt < 2)
782 optimizing = opt - 1;
783 else
784 optimizing = opt;
785 break;
787 case 'v':
788 case '+':
789 param++;
790 opt_verbose_info = true;
791 break;
793 case 'x':
794 param++;
795 optimizing = MAX_OPTIMIZE;
796 break;
798 default:
799 nasm_fatal(0,
800 "unknown optimization option -O%c\n",
801 *param);
802 break;
805 if (optimizing > MAX_OPTIMIZE)
806 optimizing = MAX_OPTIMIZE;
809 break;
811 case 'p': /* pre-include */
812 case 'P':
813 if (pass == 2)
814 preproc->pre_include(param);
815 break;
817 case 'd': /* pre-define */
818 case 'D':
819 if (pass == 2)
820 preproc->pre_define(param);
821 break;
823 case 'u': /* un-define */
824 case 'U':
825 if (pass == 2)
826 preproc->pre_undefine(param);
827 break;
829 case 'i': /* include search path */
830 case 'I':
831 if (pass == 2)
832 preproc->include_path(param);
833 break;
835 case 'l': /* listing file */
836 if (pass == 2)
837 copy_filename(&listname, param, "listing");
838 break;
840 case 'Z': /* error messages file */
841 if (pass == 1)
842 copy_filename(&errname, param, "error");
843 break;
845 case 'F': /* specify debug format */
846 if (pass == 2) {
847 using_debug_info = true;
848 debug_format = param;
850 break;
852 case 'X': /* specify error reporting format */
853 if (pass == 1) {
854 if (nasm_stricmp("vc", param) == 0)
855 nasm_set_verror(nasm_verror_vc);
856 else if (nasm_stricmp("gnu", param) == 0)
857 nasm_set_verror(nasm_verror_gnu);
858 else
859 nasm_fatal(ERR_NOFILE | ERR_USAGE,
860 "unrecognized error reporting format `%s'",
861 param);
863 break;
865 case 'g':
866 if (pass == 2) {
867 using_debug_info = true;
868 if (p[2])
869 debug_format = nasm_skip_spaces(p + 2);
871 break;
873 case 'h':
874 printf
875 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
876 "[-l listfile]\n"
877 " [options...] [--] filename\n"
878 " or nasm -v (or --v) for version info\n\n"
879 " -t assemble in SciTech TASM compatible mode\n");
880 printf
881 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
882 " -a don't preprocess (assemble only)\n"
883 " -M generate Makefile dependencies on stdout\n"
884 " -MG d:o, missing files assumed generated\n"
885 " -MF <file> set Makefile dependency file\n"
886 " -MD <file> assemble and generate dependencies\n"
887 " -MT <file> dependency target name\n"
888 " -MQ <file> dependency target name (quoted)\n"
889 " -MP emit phony target\n\n"
890 " -Z<file> redirect error messages to file\n"
891 " -s redirect error messages to stdout\n\n"
892 " -g generate debugging information\n\n"
893 " -F format select a debugging format\n\n"
894 " -gformat same as -g -F format\n\n"
895 " -o outfile write output to an outfile\n\n"
896 " -f format select an output format\n\n"
897 " -l listfile write listing to a listfile\n\n"
898 " -I<path> adds a pathname to the include file path\n");
899 printf
900 (" -O<digit> optimize branch offsets\n"
901 " -O0: No optimization\n"
902 " -O1: Minimal optimization\n"
903 " -Ox: Multipass optimization (default)\n\n"
904 " -P<file> pre-includes a file\n"
905 " -D<macro>[=<value>] pre-defines a macro\n"
906 " -U<macro> undefines a macro\n"
907 " -X<format> specifies error reporting format (gnu or vc)\n"
908 " -w+foo enables warning foo (equiv. -Wfoo)\n"
909 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
910 " -w[+-]error[=foo] can be used to promote warnings to errors\n"
911 " -h show invocation summary and exit\n\n"
912 "--prefix,--postfix\n"
913 " these options prepend or append the given string\n"
914 " to all extern and global variables\n"
915 "\n"
916 "Response files should contain command line parameters,\n"
917 "one per line.\n"
918 "\n"
919 "Warnings for the -W/-w options:\n");
920 for (i = 0; i <= ERR_WARN_ALL; i++)
921 printf(" %-23s %s%s\n",
922 warnings[i].name, warnings[i].help,
923 i == ERR_WARN_ALL ? "\n" :
924 warnings[i].enabled ? " (default on)" :
925 " (default off)");
926 if (p[2] == 'f') {
927 printf("valid output formats for -f are"
928 " (`*' denotes default):\n");
929 ofmt_list(ofmt, stdout);
930 } else {
931 printf("For a list of valid output formats, use -hf.\n");
932 printf("For a list of debug formats, use -f <form> -y.\n");
934 exit(0); /* never need usage message here */
935 break;
937 case 'y':
938 printf("\nvalid debug formats for '%s' output format are"
939 " ('*' denotes default):\n", ofmt->shortname);
940 dfmt_list(ofmt, stdout);
941 exit(0);
942 break;
944 case 't':
945 if (pass == 2)
946 tasm_compatible_mode = true;
947 break;
949 case 'v':
950 show_version();
951 break;
953 case 'e': /* preprocess only */
954 case 'E':
955 if (pass == 1)
956 operating_mode = OP_PREPROCESS;
957 break;
959 case 'a': /* assemble only - don't preprocess */
960 if (pass == 1)
961 preproc = &preproc_nop;
962 break;
964 case 'w':
965 case 'W':
966 if (pass == 2) {
967 if (!set_warning_status(param)) {
968 nasm_error(ERR_WARNING|ERR_NOFILE|ERR_WARN_UNK_WARNING,
969 "unknown warning option: %s", param);
972 break;
974 case 'M':
975 if (pass == 1) {
976 switch (p[2]) {
977 case 'W':
978 quote_for_make = quote_for_wmake;
979 break;
980 case 'D':
981 case 'F':
982 case 'T':
983 case 'Q':
984 advance = true;
985 break;
986 default:
987 break;
989 } else {
990 switch (p[2]) {
991 case 0:
992 operating_mode = OP_DEPEND;
993 break;
994 case 'G':
995 operating_mode = OP_DEPEND;
996 depend_missing_ok = true;
997 break;
998 case 'P':
999 depend_emit_phony = true;
1000 break;
1001 case 'D':
1002 operating_mode = OP_NORMAL;
1003 depend_file = q;
1004 advance = true;
1005 break;
1006 case 'F':
1007 depend_file = q;
1008 advance = true;
1009 break;
1010 case 'T':
1011 depend_target = q;
1012 advance = true;
1013 break;
1014 case 'Q':
1015 depend_target = quote_for_make(q);
1016 advance = true;
1017 break;
1018 case 'W':
1019 /* handled in pass 1 */
1020 break;
1021 default:
1022 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1023 "unknown dependency option `-M%c'", p[2]);
1024 break;
1027 if (advance && (!q || !q[0])) {
1028 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1029 "option `-M%c' requires a parameter", p[2]);
1030 break;
1032 break;
1034 case '-':
1036 const struct textargs *tx;
1038 if (p[2] == 0) { /* -- => stop processing options */
1039 stopoptions = true;
1040 break;
1043 for (tx = textopts; tx->label; tx++) {
1044 if (!nasm_stricmp(p + 2, tx->label))
1045 break;
1048 if (tx->need_arg) {
1049 if (!q) {
1050 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1051 "option `--%s' requires an argument",
1052 p + 2);
1053 break;
1055 advance = true;
1058 switch (tx->opt) {
1059 case OPT_VERSION:
1060 show_version();
1061 break;
1062 case OPT_ABORT_ON_PANIC:
1063 abort_on_panic = true;
1064 break;
1065 case OPT_PREFIX:
1066 if (pass == 2)
1067 strlcpy(lprefix, q, PREFIX_MAX);
1068 break;
1069 case OPT_POSTFIX:
1070 if (pass == 2)
1071 strlcpy(lpostfix, q, POSTFIX_MAX);
1072 break;
1073 case OPT_BOGUS:
1074 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1075 "unrecognized option `--%s'", p + 2);
1076 break;
1077 default:
1078 panic();
1080 break;
1083 default:
1084 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1085 "unrecognised option `-%c'", p[1]);
1086 break;
1088 } else if (pass == 2) {
1089 /* In theory we could allow multiple input files... */
1090 copy_filename(&inname, p, "input");
1093 return advance;
1096 #define ARG_BUF_DELTA 128
1098 static void process_respfile(FILE * rfile, int pass)
1100 char *buffer, *p, *q, *prevarg;
1101 int bufsize, prevargsize;
1103 bufsize = prevargsize = ARG_BUF_DELTA;
1104 buffer = nasm_malloc(ARG_BUF_DELTA);
1105 prevarg = nasm_malloc(ARG_BUF_DELTA);
1106 prevarg[0] = '\0';
1108 while (1) { /* Loop to handle all lines in file */
1109 p = buffer;
1110 while (1) { /* Loop to handle long lines */
1111 q = fgets(p, bufsize - (p - buffer), rfile);
1112 if (!q)
1113 break;
1114 p += strlen(p);
1115 if (p > buffer && p[-1] == '\n')
1116 break;
1117 if (p - buffer > bufsize - 10) {
1118 int offset;
1119 offset = p - buffer;
1120 bufsize += ARG_BUF_DELTA;
1121 buffer = nasm_realloc(buffer, bufsize);
1122 p = buffer + offset;
1126 if (!q && p == buffer) {
1127 if (prevarg[0])
1128 process_arg(prevarg, NULL, pass);
1129 nasm_free(buffer);
1130 nasm_free(prevarg);
1131 return;
1135 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1136 * them are present at the end of the line.
1138 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1140 while (p > buffer && nasm_isspace(p[-1]))
1141 *--p = '\0';
1143 p = nasm_skip_spaces(buffer);
1145 if (process_arg(prevarg, p, pass))
1146 *p = '\0';
1148 if ((int) strlen(p) > prevargsize - 10) {
1149 prevargsize += ARG_BUF_DELTA;
1150 prevarg = nasm_realloc(prevarg, prevargsize);
1152 strncpy(prevarg, p, prevargsize);
1156 /* Function to process args from a string of args, rather than the
1157 * argv array. Used by the environment variable and response file
1158 * processing.
1160 static void process_args(char *args, int pass)
1162 char *p, *q, *arg, *prevarg;
1163 char separator = ' ';
1165 p = args;
1166 if (*p && *p != '-')
1167 separator = *p++;
1168 arg = NULL;
1169 while (*p) {
1170 q = p;
1171 while (*p && *p != separator)
1172 p++;
1173 while (*p == separator)
1174 *p++ = '\0';
1175 prevarg = arg;
1176 arg = q;
1177 if (process_arg(prevarg, arg, pass))
1178 arg = NULL;
1180 if (arg)
1181 process_arg(arg, NULL, pass);
1184 static void process_response_file(const char *file, int pass)
1186 char str[2048];
1187 FILE *f = nasm_open_read(file, NF_TEXT);
1188 if (!f) {
1189 perror(file);
1190 exit(-1);
1192 while (fgets(str, sizeof str, f)) {
1193 process_args(str, pass);
1195 fclose(f);
1198 static void parse_cmdline(int argc, char **argv, int pass)
1200 FILE *rfile;
1201 char *envreal, *envcopy = NULL, *p;
1202 int i;
1204 /* Initialize all the warnings to their default state */
1205 for (i = 0; i < ERR_WARN_ALL; i++) {
1206 warning_state_init[i] = warning_state[i] =
1207 warnings[i].enabled ? WARN_ST_ENABLED : 0;
1211 * First, process the NASMENV environment variable.
1213 envreal = getenv("NASMENV");
1214 if (envreal) {
1215 envcopy = nasm_strdup(envreal);
1216 process_args(envcopy, pass);
1217 nasm_free(envcopy);
1221 * Now process the actual command line.
1223 while (--argc) {
1224 bool advance;
1225 argv++;
1226 if (argv[0][0] == '@') {
1228 * We have a response file, so process this as a set of
1229 * arguments like the environment variable. This allows us
1230 * to have multiple arguments on a single line, which is
1231 * different to the -@resp file processing below for regular
1232 * NASM.
1234 process_response_file(argv[0]+1, pass);
1235 argc--;
1236 argv++;
1238 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1239 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1240 if (p) {
1241 rfile = nasm_open_read(p, NF_TEXT);
1242 if (rfile) {
1243 process_respfile(rfile, pass);
1244 fclose(rfile);
1245 } else
1246 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1247 "unable to open response file `%s'", p);
1249 } else
1250 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1251 argv += advance, argc -= advance;
1255 * Look for basic command line typos. This definitely doesn't
1256 * catch all errors, but it might help cases of fumbled fingers.
1258 if (pass != 2)
1259 return;
1261 if (!inname)
1262 nasm_fatal(ERR_NOFILE | ERR_USAGE, "no input file specified");
1264 else if ((errname && !strcmp(inname, errname)) ||
1265 (outname && !strcmp(inname, outname)) ||
1266 (listname && !strcmp(inname, listname)) ||
1267 (depend_file && !strcmp(inname, depend_file)))
1268 nasm_fatal(ERR_USAGE, "will not overwrite input file");
1270 if (errname) {
1271 error_file = nasm_open_write(errname, NF_TEXT);
1272 if (!error_file) {
1273 error_file = stderr; /* Revert to default! */
1274 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1275 "cannot open file `%s' for error messages",
1276 errname);
1281 static void assemble_file(const char *fname, StrList **depend_ptr)
1283 char *line;
1284 insn output_ins;
1285 int i;
1286 int64_t offs;
1287 int pass_max;
1288 uint64_t prev_offset_changed;
1289 unsigned int stall_count = 0; /* Make sure we make forward progress... */
1291 switch (cmd_sb) {
1292 case 16:
1293 break;
1294 case 32:
1295 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1296 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1297 break;
1298 case 64:
1299 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1300 nasm_fatal(0, "command line: 64-bit segment size requires a higher cpu");
1301 break;
1302 default:
1303 panic();
1304 break;
1307 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1308 for (passn = 1; pass0 <= 2; passn++) {
1309 ldfunc def_label;
1311 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1312 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1313 /* pass0 0, 0, 0, ..., 1, 2 */
1315 def_label = passn > 1 ? redefine_label : define_label;
1317 globalbits = cmd_sb; /* set 'bits' to command line default */
1318 cpu = cmd_cpu;
1319 if (pass0 == 2) {
1320 lfmt->init(listname);
1321 } else if (passn == 1 && listname) {
1322 /* Remove the list file in case we die before the output pass */
1323 remove(listname);
1325 in_absolute = false;
1326 global_offset_changed = 0; /* set by redefine_label */
1327 location.segment = ofmt->section(NULL, pass2, &globalbits);
1328 if (passn > 1) {
1329 saa_rewind(forwrefs);
1330 forwref = saa_rstruct(forwrefs);
1331 raa_free(offsets);
1332 offsets = raa_init();
1334 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1336 /* Revert all warnings to the default state */
1337 memcpy(warning_state, warning_state_init, sizeof warning_state);
1339 globallineno = 0;
1340 if (passn == 1)
1341 location.known = true;
1342 location.offset = offs = get_curr_offs();
1344 while ((line = preproc->getline())) {
1345 globallineno++;
1348 * Here we parse our directives; this is not handled by the
1349 * main parser.
1351 if (process_directives(line))
1352 goto end_of_line; /* Just do final cleanup */
1354 /* Not a directive, or even something that starts with [ */
1356 parse_line(pass1, line, &output_ins, def_label);
1358 if (optimizing > 0) {
1359 if (forwref != NULL && globallineno == forwref->lineno) {
1360 output_ins.forw_ref = true;
1361 do {
1362 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1363 forwref = saa_rstruct(forwrefs);
1364 } while (forwref != NULL
1365 && forwref->lineno == globallineno);
1366 } else
1367 output_ins.forw_ref = false;
1369 if (output_ins.forw_ref) {
1370 if (passn == 1) {
1371 for (i = 0; i < output_ins.operands; i++) {
1372 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1373 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1374 fwinf->lineno = globallineno;
1375 fwinf->operand = i;
1382 /* forw_ref */
1383 if (output_ins.opcode == I_EQU) {
1384 if (pass1 == 1) {
1386 * Special `..' EQUs get processed in pass two,
1387 * except `..@' macro-processor EQUs which are done
1388 * in the normal place.
1390 if (!output_ins.label)
1391 nasm_error(ERR_NONFATAL,
1392 "EQU not preceded by label");
1394 else if (output_ins.label[0] != '.' ||
1395 output_ins.label[1] != '.' ||
1396 output_ins.label[2] == '@') {
1397 if (output_ins.operands == 1 &&
1398 (output_ins.oprs[0].type & IMMEDIATE) &&
1399 output_ins.oprs[0].wrt == NO_SEG) {
1400 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1401 def_label(output_ins.label,
1402 output_ins.oprs[0].segment,
1403 output_ins.oprs[0].offset, NULL,
1404 false, isext);
1405 } else if (output_ins.operands == 2
1406 && (output_ins.oprs[0].type & IMMEDIATE)
1407 && (output_ins.oprs[0].type & COLON)
1408 && output_ins.oprs[0].segment == NO_SEG
1409 && output_ins.oprs[0].wrt == NO_SEG
1410 && (output_ins.oprs[1].type & IMMEDIATE)
1411 && output_ins.oprs[1].segment == NO_SEG
1412 && output_ins.oprs[1].wrt == NO_SEG) {
1413 def_label(output_ins.label,
1414 output_ins.oprs[0].offset | SEG_ABS,
1415 output_ins.oprs[1].offset,
1416 NULL, false, false);
1417 } else
1418 nasm_error(ERR_NONFATAL,
1419 "bad syntax for EQU");
1421 } else {
1423 * Special `..' EQUs get processed here, except
1424 * `..@' macro processor EQUs which are done above.
1426 if (output_ins.label[0] == '.' &&
1427 output_ins.label[1] == '.' &&
1428 output_ins.label[2] != '@') {
1429 if (output_ins.operands == 1 &&
1430 (output_ins.oprs[0].type & IMMEDIATE)) {
1431 define_label(output_ins.label,
1432 output_ins.oprs[0].segment,
1433 output_ins.oprs[0].offset,
1434 NULL, false, false);
1435 } else if (output_ins.operands == 2
1436 && (output_ins.oprs[0].type & IMMEDIATE)
1437 && (output_ins.oprs[0].type & COLON)
1438 && output_ins.oprs[0].segment == NO_SEG
1439 && (output_ins.oprs[1].type & IMMEDIATE)
1440 && output_ins.oprs[1].segment == NO_SEG) {
1441 define_label(output_ins.label,
1442 output_ins.oprs[0].offset | SEG_ABS,
1443 output_ins.oprs[1].offset,
1444 NULL, false, false);
1445 } else
1446 nasm_error(ERR_NONFATAL,
1447 "bad syntax for EQU");
1450 } else { /* instruction isn't an EQU */
1451 int32_t n;
1453 nasm_assert(output_ins.times >= 0);
1455 for (n = 1; n <= output_ins.times; n++) {
1456 if (pass1 == 1) {
1457 int64_t l = insn_size(location.segment, offs,
1458 globalbits, &output_ins);
1460 /* if (using_debug_info) && output_ins.opcode != -1) */
1461 if (using_debug_info)
1462 { /* fbk 03/25/01 */
1463 /* this is done here so we can do debug type info */
1464 int32_t typeinfo =
1465 TYS_ELEMENTS(output_ins.operands);
1466 switch (output_ins.opcode) {
1467 case I_RESB:
1468 typeinfo =
1469 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1470 break;
1471 case I_RESW:
1472 typeinfo =
1473 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1474 break;
1475 case I_RESD:
1476 typeinfo =
1477 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1478 break;
1479 case I_RESQ:
1480 typeinfo =
1481 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1482 break;
1483 case I_REST:
1484 typeinfo =
1485 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1486 break;
1487 case I_RESO:
1488 typeinfo =
1489 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1490 break;
1491 case I_RESY:
1492 typeinfo =
1493 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1494 break;
1495 case I_RESZ:
1496 typeinfo =
1497 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;
1498 break;
1499 case I_DB:
1500 typeinfo |= TY_BYTE;
1501 break;
1502 case I_DW:
1503 typeinfo |= TY_WORD;
1504 break;
1505 case I_DD:
1506 if (output_ins.eops_float)
1507 typeinfo |= TY_FLOAT;
1508 else
1509 typeinfo |= TY_DWORD;
1510 break;
1511 case I_DQ:
1512 typeinfo |= TY_QWORD;
1513 break;
1514 case I_DT:
1515 typeinfo |= TY_TBYTE;
1516 break;
1517 case I_DO:
1518 typeinfo |= TY_OWORD;
1519 break;
1520 case I_DY:
1521 typeinfo |= TY_YWORD;
1522 break;
1523 case I_DZ:
1524 typeinfo |= TY_ZWORD;
1525 break;
1526 default:
1527 typeinfo = TY_LABEL;
1528 break;
1531 dfmt->debug_typevalue(typeinfo);
1535 * For INCBIN, let the code in assemble
1536 * handle TIMES, so we don't have to read the
1537 * input file over and over.
1539 if (l != -1) {
1540 offs += l;
1541 set_curr_offs(offs);
1544 * else l == -1 => invalid instruction, which will be
1545 * flagged as an error on pass 2
1547 } else {
1548 if (n == 2)
1549 lfmt->uplevel(LIST_TIMES);
1550 offs += assemble(location.segment, offs,
1551 globalbits, &output_ins);
1552 set_curr_offs(offs);
1554 } /* not an EQU */
1556 if (output_ins.times > 1)
1557 lfmt->downlevel(LIST_TIMES);
1559 cleanup_insn(&output_ins);
1561 end_of_line:
1562 nasm_free(line);
1563 location.offset = offs = get_curr_offs();
1564 } /* end while (line = preproc->getline... */
1566 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1567 nasm_error(ERR_NONFATAL,
1568 "phase error detected at end of assembly.");
1570 if (pass1 == 1)
1571 preproc->cleanup(1);
1573 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1574 pass0++;
1575 } else if (global_offset_changed &&
1576 global_offset_changed < prev_offset_changed) {
1577 prev_offset_changed = global_offset_changed;
1578 stall_count = 0;
1579 } else {
1580 stall_count++;
1583 if (terminate_after_phase)
1584 break;
1586 if ((stall_count > 997U) || (passn >= pass_max)) {
1587 /* We get here if the labels don't converge
1588 * Example: FOO equ FOO + 1
1590 nasm_error(ERR_NONFATAL,
1591 "Can't find valid values for all labels "
1592 "after %d passes, giving up.", passn);
1593 nasm_error(ERR_NONFATAL,
1594 "Possible causes: recursive EQUs, macro abuse.");
1595 break;
1599 preproc->cleanup(0);
1600 lfmt->cleanup();
1601 if (!terminate_after_phase && opt_verbose_info) {
1602 /* -On and -Ov switches */
1603 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1608 * gnu style error reporting
1609 * This function prints an error message to error_file in the
1610 * style used by GNU. An example would be:
1611 * file.asm:50: error: blah blah blah
1612 * where file.asm is the name of the file, 50 is the line number on
1613 * which the error occurs (or is detected) and "error:" is one of
1614 * the possible optional diagnostics -- it can be "error" or "warning"
1615 * or something else. Finally the line terminates with the actual
1616 * error message.
1618 * @param severity the severity of the warning or error
1619 * @param fmt the printf style format string
1621 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1623 const char *currentfile = NULL;
1624 int32_t lineno = 0;
1626 if (is_suppressed_warning(severity))
1627 return;
1629 if (!(severity & ERR_NOFILE)) {
1630 src_get(&lineno, &currentfile);
1631 if (!currentfile || (severity & ERR_TOPFILE)) {
1632 currentfile = inname[0] ? inname : outname[0] ? outname : NULL;
1633 lineno = 0;
1637 if (!skip_this_pass(severity)) {
1638 if (!lineno)
1639 fprintf(error_file, "%s:", currentfile ? currentfile : "nasm");
1640 else
1641 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1644 nasm_verror_common(severity, fmt, ap);
1648 * MS style error reporting
1649 * This function prints an error message to error_file in the
1650 * style used by Visual C and some other Microsoft tools. An example
1651 * would be:
1652 * file.asm(50) : error: blah blah blah
1653 * where file.asm is the name of the file, 50 is the line number on
1654 * which the error occurs (or is detected) and "error:" is one of
1655 * the possible optional diagnostics -- it can be "error" or "warning"
1656 * or something else. Finally the line terminates with the actual
1657 * error message.
1659 * @param severity the severity of the warning or error
1660 * @param fmt the printf style format string
1662 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1664 const char *currentfile = NULL;
1665 int32_t lineno = 0;
1667 if (is_suppressed_warning(severity))
1668 return;
1670 if (!(severity & ERR_NOFILE))
1671 src_get(&lineno, &currentfile);
1673 if (!skip_this_pass(severity)) {
1674 if (currentfile) {
1675 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1676 } else {
1677 fputs("nasm: ", error_file);
1681 nasm_verror_common(severity, fmt, ap);
1685 * check to see if this is a suppressable warning
1687 static inline bool is_valid_warning(int severity)
1689 /* Not a warning at all */
1690 if ((severity & ERR_MASK) != ERR_WARNING)
1691 return false;
1693 return WARN_IDX(severity) < ERR_WARN_ALL;
1697 * check for suppressed warning
1698 * checks for suppressed warning or pass one only warning and we're
1699 * not in pass 1
1701 * @param severity the severity of the warning or error
1702 * @return true if we should abort error/warning printing
1704 static bool is_suppressed_warning(int severity)
1706 /* Might be a warning but suppresed explicitly */
1707 if (is_valid_warning(severity))
1708 return !(warning_state[WARN_IDX(severity)] & WARN_ST_ENABLED);
1709 else
1710 return false;
1713 static bool warning_is_error(int severity)
1715 if (is_valid_warning(severity))
1716 return !!(warning_state[WARN_IDX(severity)] & WARN_ST_ERROR);
1717 else
1718 return false;
1721 static bool skip_this_pass(int severity)
1724 * See if it's a pass-specific error or warning which should be skipped.
1725 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1726 * they cannot be resumed from.
1728 if ((severity & ERR_MASK) > ERR_NONFATAL)
1729 return false;
1732 * passn is 1 on the very first pass only.
1733 * pass0 is 2 on the code-generation (final) pass only.
1734 * These are the passes we care about in this case.
1736 return (((severity & ERR_PASS1) && passn != 1) ||
1737 ((severity & ERR_PASS2) && pass0 != 2));
1741 * common error reporting
1742 * This is the common back end of the error reporting schemes currently
1743 * implemented. It prints the nature of the warning and then the
1744 * specific error message to error_file and may or may not return. It
1745 * doesn't return if the error severity is a "panic" or "debug" type.
1747 * @param severity the severity of the warning or error
1748 * @param fmt the printf style format string
1750 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1752 char msg[1024];
1753 const char *pfx;
1755 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1756 case ERR_WARNING:
1757 pfx = "warning: ";
1758 break;
1759 case ERR_NONFATAL:
1760 pfx = "error: ";
1761 break;
1762 case ERR_FATAL:
1763 pfx = "fatal: ";
1764 break;
1765 case ERR_PANIC:
1766 pfx = "panic: ";
1767 break;
1768 case ERR_DEBUG:
1769 pfx = "debug: ";
1770 break;
1771 default:
1772 pfx = "";
1773 break;
1776 vsnprintf(msg, sizeof msg - 64, fmt, args);
1777 if (is_valid_warning(severity) && WARN_IDX(severity) != ERR_WARN_OTHER) {
1778 char *p = strchr(msg, '\0');
1779 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
1782 if (!skip_this_pass(severity))
1783 fprintf(error_file, "%s%s\n", pfx, msg);
1785 /* Are we recursing from error_list_macros? */
1786 if (severity & ERR_PP_LISTMACRO)
1787 return;
1790 * Don't suppress this with skip_this_pass(), or we don't get
1791 * pass1 or preprocessor warnings in the list file
1793 lfmt->error(severity, pfx, msg);
1795 if (skip_this_pass(severity))
1796 return;
1798 if (severity & ERR_USAGE)
1799 want_usage = true;
1801 preproc->error_list_macros(severity);
1803 switch (severity & ERR_MASK) {
1804 case ERR_DEBUG:
1805 /* no further action, by definition */
1806 break;
1807 case ERR_WARNING:
1808 /* Treat warnings as errors */
1809 if (warning_is_error(severity))
1810 terminate_after_phase = true;
1811 break;
1812 case ERR_NONFATAL:
1813 terminate_after_phase = true;
1814 break;
1815 case ERR_FATAL:
1816 if (ofile) {
1817 fclose(ofile);
1818 remove(outname);
1819 ofile = NULL;
1821 if (want_usage)
1822 usage();
1823 exit(1); /* instantly die */
1824 break; /* placate silly compilers */
1825 case ERR_PANIC:
1826 fflush(NULL);
1828 if (abort_on_panic)
1829 abort(); /* halt, catch fire, dump core/stop debugger */
1831 if (ofile) {
1832 fclose(ofile);
1833 remove(outname);
1834 ofile = NULL;
1836 exit(3);
1837 break;
1841 static void usage(void)
1843 fputs("type `nasm -h' for help\n", error_file);