Merge remote-tracking branch 'origin/nasm-2.13.xx'
[nasm.git] / asm / nasm.c
blobb07ed452c75a4ffd9d9df2fc1aa97d45f186034e
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2017 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(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 bool tasm_compatible_mode = false;
90 int pass0, passn;
91 static int pass1, pass2; /* XXX: Get rid of these, they are redundant */
92 int globalrel = 0;
93 int globalbnd = 0;
95 struct compile_time official_compile_time;
97 static char inname[FILENAME_MAX];
98 static char outname[FILENAME_MAX];
99 static char listname[FILENAME_MAX];
100 static char errname[FILENAME_MAX];
101 static int globallineno; /* for forward-reference tracking */
102 /* static int pass = 0; */
103 const struct ofmt *ofmt = &OF_DEFAULT;
104 const struct ofmt_alias *ofmt_alias = NULL;
105 const struct dfmt *dfmt;
107 static FILE *error_file; /* Where to write error messages */
109 FILE *ofile = NULL;
110 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
111 static int cmd_sb = 16; /* by default */
113 iflag_t cpu;
114 static iflag_t cmd_cpu;
116 struct location location;
117 bool in_absolute; /* Flag we are in ABSOLUTE seg */
118 struct location absolute; /* Segment/offset inside ABSOLUTE */
120 static struct RAA *offsets;
122 static struct SAA *forwrefs; /* keep track of forward references */
123 static const struct forwrefinfo *forwref;
125 static const struct preproc_ops *preproc;
127 #define OP_NORMAL (1u << 0)
128 #define OP_PREPROCESS (1u << 1)
129 #define OP_DEPEND (1u << 2)
131 static unsigned int operating_mode;
133 /* Dependency flags */
134 static bool depend_emit_phony = false;
135 static bool depend_missing_ok = false;
136 static const char *depend_target = NULL;
137 static const char *depend_file = NULL;
138 StrList *depend_list;
140 static bool want_usage;
141 static bool terminate_after_phase;
142 bool user_nolist = false;
144 static char *quote_for_pmake(const char *str);
145 static char *quote_for_wmake(const char *str);
146 static char *(*quote_for_make)(const char *) = quote_for_pmake;
148 static int64_t get_curr_offs(void)
150 return in_absolute ? absolute.offset : raa_read(offsets, location.segment);
153 static void set_curr_offs(int64_t l_off)
155 if (in_absolute)
156 absolute.offset = l_off;
157 else
158 offsets = raa_write(offsets, location.segment, l_off);
161 static void nasm_fputs(const char *line, FILE * outfile)
163 if (outfile) {
164 fputs(line, outfile);
165 putc('\n', outfile);
166 } else
167 puts(line);
170 static void define_macros_early(void)
172 const struct compile_time * const oct = &official_compile_time;
173 char temp[128];
175 if (oct->have_local) {
176 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &oct->local);
177 preproc->pre_define(temp);
178 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &oct->local);
179 preproc->pre_define(temp);
180 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &oct->local);
181 preproc->pre_define(temp);
182 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &oct->local);
183 preproc->pre_define(temp);
186 if (oct->have_gm) {
187 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &oct->gm);
188 preproc->pre_define(temp);
189 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &oct->gm);
190 preproc->pre_define(temp);
191 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &oct->gm);
192 preproc->pre_define(temp);
193 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &oct->gm);
194 preproc->pre_define(temp);
197 if (oct->have_posix) {
198 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, oct->posix);
199 preproc->pre_define(temp);
203 static void define_macros_late(void)
205 char temp[128];
208 * In case if output format is defined by alias
209 * we have to put shortname of the alias itself here
210 * otherwise ABI backward compatibility gets broken.
212 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
213 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
214 preproc->pre_define(temp);
217 static void emit_dependencies(StrList *list)
219 FILE *deps;
220 int linepos, len;
221 StrList *l, *nl;
222 bool wmake = (quote_for_make == quote_for_wmake);
223 const char *wrapstr, *nulltarget;
225 wrapstr = wmake ? " &\n " : " \\\n ";
226 nulltarget = wmake ? "\t%null\n" : "";
228 if (depend_file && strcmp(depend_file, "-")) {
229 deps = nasm_open_write(depend_file, NF_TEXT);
230 if (!deps) {
231 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
232 "unable to write dependency file `%s'", depend_file);
233 return;
235 } else {
236 deps = stdout;
239 linepos = fprintf(deps, "%s :", depend_target);
240 list_for_each(l, list) {
241 char *file = quote_for_make(l->str);
242 len = strlen(file);
243 if (linepos + len > 62 && linepos > 1) {
244 fputs(wrapstr, deps);
245 linepos = 1;
247 fprintf(deps, " %s", file);
248 linepos += len+1;
249 nasm_free(file);
251 fprintf(deps, "\n\n");
253 list_for_each_safe(l, nl, list) {
254 if (depend_emit_phony) {
255 char *file = quote_for_make(l->str);
256 fprintf(deps, "%s :\n%s\n", file, nulltarget);
257 nasm_free(file);
259 nasm_free(l);
262 if (deps != stdout)
263 fclose(deps);
266 /* Convert a struct tm to a POSIX-style time constant */
267 static int64_t make_posix_time(const struct tm *tm)
269 int64_t t;
270 int64_t y = tm->tm_year;
272 /* See IEEE 1003.1:2004, section 4.14 */
274 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
275 t += tm->tm_yday;
276 t *= 24;
277 t += tm->tm_hour;
278 t *= 60;
279 t += tm->tm_min;
280 t *= 60;
281 t += tm->tm_sec;
283 return t;
286 static void timestamp(void)
288 struct compile_time * const oct = &official_compile_time;
289 const struct tm *tp, *best_gm;
291 time(&oct->t);
293 best_gm = NULL;
295 tp = localtime(&oct->t);
296 if (tp) {
297 oct->local = *tp;
298 best_gm = &oct->local;
299 oct->have_local = true;
302 tp = gmtime(&oct->t);
303 if (tp) {
304 oct->gm = *tp;
305 best_gm = &oct->gm;
306 oct->have_gm = true;
307 if (!oct->have_local)
308 oct->local = oct->gm;
309 } else {
310 oct->gm = oct->local;
313 if (best_gm) {
314 oct->posix = make_posix_time(best_gm);
315 oct->have_posix = true;
319 int main(int argc, char **argv)
321 StrList **depend_ptr;
323 timestamp();
325 iflag_set(&cpu, IF_PLEVEL);
326 iflag_set(&cmd_cpu, IF_PLEVEL);
328 pass0 = 0;
329 want_usage = terminate_after_phase = false;
330 nasm_set_verror(nasm_verror_gnu);
332 error_file = stderr;
334 tolower_init();
335 src_init();
337 offsets = raa_init();
338 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
340 preproc = &nasmpp;
341 operating_mode = OP_NORMAL;
343 parse_cmdline(argc, argv, 1);
344 if (terminate_after_phase) {
345 if (want_usage)
346 usage();
347 return 1;
351 * Define some macros dependent on the runtime, but not
352 * on the command line (as those are scanned in cmdline pass 2.)
354 preproc->init();
355 define_macros_early();
357 parse_cmdline(argc, argv, 2);
358 if (terminate_after_phase) {
359 if (want_usage)
360 usage();
361 return 1;
364 /* Save away the default state of warnings */
365 memcpy(warning_state_init, warning_state, sizeof warning_state);
367 if (!using_debug_info) {
368 /* No debug info, redirect to the null backend (empty stubs) */
369 dfmt = &null_debug_form;
370 } else if (!debug_format) {
371 /* Default debug format for this backend */
372 dfmt = ofmt->default_dfmt;
373 } else {
374 dfmt = dfmt_find(ofmt, debug_format);
375 if (!dfmt) {
376 nasm_fatal(ERR_NOFILE | ERR_USAGE,
377 "unrecognized debug format `%s' for"
378 " output format `%s'",
379 debug_format, ofmt->shortname);
383 if (ofmt->stdmac)
384 preproc->extra_stdmac(ofmt->stdmac);
386 /* define some macros dependent of command-line */
387 define_macros_late();
389 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
391 if (!depend_target)
392 depend_target = quote_for_make(outname);
394 if (operating_mode & OP_DEPEND) {
395 char *line;
397 if (depend_missing_ok)
398 preproc->include_path(NULL); /* "assume generated" */
400 preproc->reset(inname, 0, depend_ptr);
401 if (outname[0] == '\0')
402 ofmt->filename(inname, outname);
403 ofile = NULL;
404 while ((line = preproc->getline()))
405 nasm_free(line);
406 preproc->cleanup(0);
407 } else if (operating_mode & OP_PREPROCESS) {
408 char *line;
409 const char *file_name = NULL;
410 int32_t prior_linnum = 0;
411 int lineinc = 0;
413 if (*outname) {
414 ofile = nasm_open_write(outname, NF_TEXT);
415 if (!ofile)
416 nasm_fatal(ERR_NOFILE,
417 "unable to open output file `%s'",
418 outname);
419 } else
420 ofile = NULL;
422 location.known = false;
424 /* pass = 1; */
425 preproc->reset(inname, 3, depend_ptr);
427 /* Revert all warnings to the default state */
428 memcpy(warning_state, warning_state_init, sizeof warning_state);
430 while ((line = preproc->getline())) {
432 * We generate %line directives if needed for later programs
434 int32_t linnum = prior_linnum += lineinc;
435 int altline = src_get(&linnum, &file_name);
436 if (altline) {
437 if (altline == 1 && lineinc == 1)
438 nasm_fputs("", ofile);
439 else {
440 lineinc = (altline != -1 || lineinc != 1);
441 fprintf(ofile ? ofile : stdout,
442 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
443 file_name);
445 prior_linnum = linnum;
447 nasm_fputs(line, ofile);
448 nasm_free(line);
450 preproc->cleanup(0);
451 if (ofile)
452 fclose(ofile);
453 if (ofile && terminate_after_phase)
454 remove(outname);
455 ofile = NULL;
458 if (operating_mode & OP_NORMAL) {
460 * We must call ofmt->filename _anyway_, even if the user
461 * has specified their own output file, because some
462 * formats (eg OBJ and COFF) use ofmt->filename to find out
463 * the name of the input file and then put that inside the
464 * file.
466 ofmt->filename(inname, outname);
468 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
469 if (!ofile)
470 nasm_fatal(ERR_NOFILE,
471 "unable to open output file `%s'", outname);
474 * We must call init_labels() before ofmt->init() since
475 * some object formats will want to define labels in their
476 * init routines. (eg OS/2 defines the FLAT group)
478 init_labels();
480 ofmt->init();
481 dfmt->init();
483 assemble_file(inname, depend_ptr);
485 if (!terminate_after_phase) {
486 ofmt->cleanup();
487 cleanup_labels();
488 fflush(ofile);
489 if (ferror(ofile)) {
490 nasm_error(ERR_NONFATAL|ERR_NOFILE,
491 "write error on output file `%s'", outname);
492 terminate_after_phase = true;
496 if (ofile) {
497 fclose(ofile);
498 if (terminate_after_phase)
499 remove(outname);
500 ofile = NULL;
504 if (depend_list && !terminate_after_phase)
505 emit_dependencies(depend_list);
507 if (want_usage)
508 usage();
510 raa_free(offsets);
511 saa_free(forwrefs);
512 eval_cleanup();
513 stdscan_cleanup();
514 src_free();
516 return terminate_after_phase;
520 * Get a parameter for a command line option.
521 * First arg must be in the form of e.g. -f...
523 static char *get_param(char *p, char *q, bool *advance)
525 *advance = false;
526 if (p[2]) /* the parameter's in the option */
527 return nasm_skip_spaces(p + 2);
528 if (q && q[0]) {
529 *advance = true;
530 return q;
532 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
533 "option `-%c' requires an argument", p[1]);
534 return NULL;
538 * Copy a filename
540 static void copy_filename(char *dst, const char *src)
542 size_t len = strlen(src);
544 if (len >= (size_t)FILENAME_MAX) {
545 nasm_fatal(ERR_NOFILE, "file name too long");
546 return;
548 strncpy(dst, src, FILENAME_MAX);
552 * Convert a string to a POSIX make-safe form
554 static char *quote_for_pmake(const char *str)
556 const char *p;
557 char *os, *q;
559 size_t n = 1; /* Terminating zero */
560 size_t nbs = 0;
562 if (!str)
563 return NULL;
565 for (p = str; *p; p++) {
566 switch (*p) {
567 case ' ':
568 case '\t':
569 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
570 n += nbs + 2;
571 nbs = 0;
572 break;
573 case '$':
574 case '#':
575 nbs = 0;
576 n += 2;
577 break;
578 case '\\':
579 nbs++;
580 n++;
581 break;
582 default:
583 nbs = 0;
584 n++;
585 break;
589 /* Convert N backslashes at the end of filename to 2N backslashes */
590 if (nbs)
591 n += nbs;
593 os = q = nasm_malloc(n);
595 nbs = 0;
596 for (p = str; *p; p++) {
597 switch (*p) {
598 case ' ':
599 case '\t':
600 while (nbs--)
601 *q++ = '\\';
602 *q++ = '\\';
603 *q++ = *p;
604 break;
605 case '$':
606 *q++ = *p;
607 *q++ = *p;
608 nbs = 0;
609 break;
610 case '#':
611 *q++ = '\\';
612 *q++ = *p;
613 nbs = 0;
614 break;
615 case '\\':
616 *q++ = *p;
617 nbs++;
618 break;
619 default:
620 *q++ = *p;
621 nbs = 0;
622 break;
625 while (nbs--)
626 *q++ = '\\';
628 *q = '\0';
630 return os;
634 * Convert a string to a Watcom make-safe form
636 static char *quote_for_wmake(const char *str)
638 const char *p;
639 char *os, *q;
640 bool quote = false;
642 size_t n = 1; /* Terminating zero */
644 if (!str)
645 return NULL;
647 for (p = str; *p; p++) {
648 switch (*p) {
649 case ' ':
650 case '\t':
651 case '&':
652 quote = true;
653 n++;
654 break;
655 case '\"':
656 quote = true;
657 n += 2;
658 break;
659 case '$':
660 case '#':
661 n += 2;
662 break;
663 default:
664 n++;
665 break;
669 if (quote)
670 n += 2;
672 os = q = nasm_malloc(n);
674 if (quote)
675 *q++ = '\"';
677 for (p = str; *p; p++) {
678 switch (*p) {
679 case '$':
680 case '#':
681 *q++ = '$';
682 *q++ = *p;
683 break;
684 case '\"':
685 *q++ = *p;
686 *q++ = *p;
687 break;
688 default:
689 *q++ = *p;
690 break;
694 if (quote)
695 *q++ = '\"';
697 *q = '\0';
699 return os;
702 struct textargs {
703 const char *label;
704 int value;
707 enum text_options {
708 OPT_PREFIX,
709 OPT_POSTFIX
711 static const struct textargs textopts[] = {
712 {"prefix", OPT_PREFIX},
713 {"postfix", OPT_POSTFIX},
714 {NULL, 0}
717 static void show_version(void)
719 printf("NASM version %s compiled on %s%s\n",
720 nasm_version, nasm_date, nasm_compile_options);
721 exit(0);
724 static bool stopoptions = false;
725 static bool process_arg(char *p, char *q, int pass)
727 char *param;
728 int i;
729 bool advance = false;
731 if (!p || !p[0])
732 return false;
734 if (p[0] == '-' && !stopoptions) {
735 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
736 /* These parameters take values */
737 if (!(param = get_param(p, q, &advance)))
738 return advance;
741 switch (p[1]) {
742 case 's':
743 if (pass == 1)
744 error_file = stdout;
745 break;
747 case 'o': /* output file */
748 if (pass == 2)
749 copy_filename(outname, param);
750 break;
752 case 'f': /* output format */
753 if (pass == 1) {
754 ofmt = ofmt_find(param, &ofmt_alias);
755 if (!ofmt) {
756 nasm_fatal(ERR_NOFILE | ERR_USAGE,
757 "unrecognised output format `%s' - "
758 "use -hf for a list", param);
761 break;
763 case 'O': /* Optimization level */
764 if (pass == 2) {
765 int opt;
767 if (!*param) {
768 /* Naked -O == -Ox */
769 optimizing = MAX_OPTIMIZE;
770 } else {
771 while (*param) {
772 switch (*param) {
773 case '0': case '1': case '2': case '3': case '4':
774 case '5': case '6': case '7': case '8': case '9':
775 opt = strtoul(param, &param, 10);
777 /* -O0 -> optimizing == -1, 0.98 behaviour */
778 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
779 if (opt < 2)
780 optimizing = opt - 1;
781 else
782 optimizing = opt;
783 break;
785 case 'v':
786 case '+':
787 param++;
788 opt_verbose_info = true;
789 break;
791 case 'x':
792 param++;
793 optimizing = MAX_OPTIMIZE;
794 break;
796 default:
797 nasm_fatal(0,
798 "unknown optimization option -O%c\n",
799 *param);
800 break;
803 if (optimizing > MAX_OPTIMIZE)
804 optimizing = MAX_OPTIMIZE;
807 break;
809 case 'p': /* pre-include */
810 case 'P':
811 if (pass == 2)
812 preproc->pre_include(param);
813 break;
815 case 'd': /* pre-define */
816 case 'D':
817 if (pass == 2)
818 preproc->pre_define(param);
819 break;
821 case 'u': /* un-define */
822 case 'U':
823 if (pass == 2)
824 preproc->pre_undefine(param);
825 break;
827 case 'i': /* include search path */
828 case 'I':
829 if (pass == 2)
830 preproc->include_path(param);
831 break;
833 case 'l': /* listing file */
834 if (pass == 2)
835 copy_filename(listname, param);
836 break;
838 case 'Z': /* error messages file */
839 if (pass == 1)
840 copy_filename(errname, param);
841 break;
843 case 'F': /* specify debug format */
844 if (pass == 2) {
845 using_debug_info = true;
846 debug_format = param;
848 break;
850 case 'X': /* specify error reporting format */
851 if (pass == 1) {
852 if (nasm_stricmp("vc", param) == 0)
853 nasm_set_verror(nasm_verror_vc);
854 else if (nasm_stricmp("gnu", param) == 0)
855 nasm_set_verror(nasm_verror_gnu);
856 else
857 nasm_fatal(ERR_NOFILE | ERR_USAGE,
858 "unrecognized error reporting format `%s'",
859 param);
861 break;
863 case 'g':
864 if (pass == 2) {
865 using_debug_info = true;
866 if (p[2])
867 debug_format = nasm_skip_spaces(p + 2);
869 break;
871 case 'h':
872 printf
873 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
874 "[-l listfile]\n"
875 " [options...] [--] filename\n"
876 " or nasm -v (or --v) for version info\n\n"
877 " -t assemble in SciTech TASM compatible mode\n");
878 printf
879 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
880 " -a don't preprocess (assemble only)\n"
881 " -M generate Makefile dependencies on stdout\n"
882 " -MG d:o, missing files assumed generated\n"
883 " -MF <file> set Makefile dependency file\n"
884 " -MD <file> assemble and generate dependencies\n"
885 " -MT <file> dependency target name\n"
886 " -MQ <file> dependency target name (quoted)\n"
887 " -MP emit phony target\n\n"
888 " -Z<file> redirect error messages to file\n"
889 " -s redirect error messages to stdout\n\n"
890 " -g generate debugging information\n\n"
891 " -F format select a debugging format\n\n"
892 " -gformat same as -g -F format\n\n"
893 " -o outfile write output to an outfile\n\n"
894 " -f format select an output format\n\n"
895 " -l listfile write listing to a listfile\n\n"
896 " -I<path> adds a pathname to the include file path\n");
897 printf
898 (" -O<digit> optimize branch offsets\n"
899 " -O0: No optimization\n"
900 " -O1: Minimal optimization\n"
901 " -Ox: Multipass optimization (default)\n\n"
902 " -P<file> pre-includes a file\n"
903 " -D<macro>[=<value>] pre-defines a macro\n"
904 " -U<macro> undefines a macro\n"
905 " -X<format> specifies error reporting format (gnu or vc)\n"
906 " -w+foo enables warning foo (equiv. -Wfoo)\n"
907 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
908 " -w[+-]error[=foo] can be used to promote warnings to errors\n"
909 " -h show invocation summary and exit\n\n"
910 "--prefix,--postfix\n"
911 " these options prepend or append the given string\n"
912 " to all extern and global variables\n"
913 "\n"
914 "Response files should contain command line parameters,\n"
915 "one per line.\n"
916 "\n"
917 "Warnings for the -W/-w options:\n");
918 for (i = 0; i <= ERR_WARN_ALL; i++)
919 printf(" %-23s %s%s\n",
920 warnings[i].name, warnings[i].help,
921 i == ERR_WARN_ALL ? "\n" :
922 warnings[i].enabled ? " (default on)" :
923 " (default off)");
924 if (p[2] == 'f') {
925 printf("valid output formats for -f are"
926 " (`*' denotes default):\n");
927 ofmt_list(ofmt, stdout);
928 } else {
929 printf("For a list of valid output formats, use -hf.\n");
930 printf("For a list of debug formats, use -f <form> -y.\n");
932 exit(0); /* never need usage message here */
933 break;
935 case 'y':
936 printf("\nvalid debug formats for '%s' output format are"
937 " ('*' denotes default):\n", ofmt->shortname);
938 dfmt_list(ofmt, stdout);
939 exit(0);
940 break;
942 case 't':
943 if (pass == 2)
944 tasm_compatible_mode = true;
945 break;
947 case 'v':
948 show_version();
949 break;
951 case 'e': /* preprocess only */
952 case 'E':
953 if (pass == 1)
954 operating_mode = OP_PREPROCESS;
955 break;
957 case 'a': /* assemble only - don't preprocess */
958 if (pass == 1)
959 preproc = &preproc_nop;
960 break;
962 case 'w':
963 case 'W':
964 if (pass == 2) {
965 if (!set_warning_status(param)) {
966 nasm_error(ERR_WARNING|ERR_NOFILE|ERR_WARN_UNK_WARNING,
967 "unknown warning option: %s", param);
970 break;
972 case 'M':
973 if (pass == 1) {
974 switch (p[2]) {
975 case 'W':
976 quote_for_make = quote_for_wmake;
977 break;
978 case 'D':
979 case 'F':
980 case 'T':
981 case 'Q':
982 advance = true;
983 break;
984 default:
985 break;
987 } else {
988 switch (p[2]) {
989 case 0:
990 operating_mode = OP_DEPEND;
991 break;
992 case 'G':
993 operating_mode = OP_DEPEND;
994 depend_missing_ok = true;
995 break;
996 case 'P':
997 depend_emit_phony = true;
998 break;
999 case 'D':
1000 operating_mode = OP_NORMAL;
1001 depend_file = q;
1002 advance = true;
1003 break;
1004 case 'F':
1005 depend_file = q;
1006 advance = true;
1007 break;
1008 case 'T':
1009 depend_target = q;
1010 advance = true;
1011 break;
1012 case 'Q':
1013 depend_target = quote_for_make(q);
1014 advance = true;
1015 break;
1016 case 'W':
1017 /* handled in pass 1 */
1018 break;
1019 default:
1020 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1021 "unknown dependency option `-M%c'", p[2]);
1022 break;
1025 if (advance && (!q || !q[0])) {
1026 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1027 "option `-M%c' requires a parameter", p[2]);
1028 break;
1030 break;
1032 case '-':
1034 int s;
1036 if (p[2] == 0) { /* -- => stop processing options */
1037 stopoptions = 1;
1038 break;
1041 if (!nasm_stricmp(p, "--v"))
1042 show_version();
1044 if (!nasm_stricmp(p, "--version"))
1045 show_version();
1047 for (s = 0; textopts[s].label; s++) {
1048 if (!nasm_stricmp(p + 2, textopts[s].label)) {
1049 break;
1053 switch (s) {
1054 case OPT_PREFIX:
1055 case OPT_POSTFIX:
1057 if (!q) {
1058 nasm_error(ERR_NONFATAL | ERR_NOFILE |
1059 ERR_USAGE,
1060 "option `--%s' requires an argument",
1061 p + 2);
1062 break;
1063 } else {
1064 advance = 1, param = q;
1067 switch (s) {
1068 case OPT_PREFIX:
1069 if (pass == 2)
1070 strlcpy(lprefix, param, PREFIX_MAX);
1071 break;
1072 case OPT_POSTFIX:
1073 if (pass == 2)
1074 strlcpy(lpostfix, param, POSTFIX_MAX);
1075 break;
1076 default:
1077 panic();
1078 break;
1080 break;
1083 default:
1085 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1086 "unrecognised option `--%s'", p + 2);
1087 break;
1090 break;
1093 default:
1094 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1095 "unrecognised option `-%c'", p[1]);
1096 break;
1098 } else if (pass == 2) {
1099 if (*inname) {
1100 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1101 "more than one input file specified");
1102 } else {
1103 copy_filename(inname, p);
1107 return advance;
1110 #define ARG_BUF_DELTA 128
1112 static void process_respfile(FILE * rfile, int pass)
1114 char *buffer, *p, *q, *prevarg;
1115 int bufsize, prevargsize;
1117 bufsize = prevargsize = ARG_BUF_DELTA;
1118 buffer = nasm_malloc(ARG_BUF_DELTA);
1119 prevarg = nasm_malloc(ARG_BUF_DELTA);
1120 prevarg[0] = '\0';
1122 while (1) { /* Loop to handle all lines in file */
1123 p = buffer;
1124 while (1) { /* Loop to handle long lines */
1125 q = fgets(p, bufsize - (p - buffer), rfile);
1126 if (!q)
1127 break;
1128 p += strlen(p);
1129 if (p > buffer && p[-1] == '\n')
1130 break;
1131 if (p - buffer > bufsize - 10) {
1132 int offset;
1133 offset = p - buffer;
1134 bufsize += ARG_BUF_DELTA;
1135 buffer = nasm_realloc(buffer, bufsize);
1136 p = buffer + offset;
1140 if (!q && p == buffer) {
1141 if (prevarg[0])
1142 process_arg(prevarg, NULL, pass);
1143 nasm_free(buffer);
1144 nasm_free(prevarg);
1145 return;
1149 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1150 * them are present at the end of the line.
1152 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1154 while (p > buffer && nasm_isspace(p[-1]))
1155 *--p = '\0';
1157 p = nasm_skip_spaces(buffer);
1159 if (process_arg(prevarg, p, pass))
1160 *p = '\0';
1162 if ((int) strlen(p) > prevargsize - 10) {
1163 prevargsize += ARG_BUF_DELTA;
1164 prevarg = nasm_realloc(prevarg, prevargsize);
1166 strncpy(prevarg, p, prevargsize);
1170 /* Function to process args from a string of args, rather than the
1171 * argv array. Used by the environment variable and response file
1172 * processing.
1174 static void process_args(char *args, int pass)
1176 char *p, *q, *arg, *prevarg;
1177 char separator = ' ';
1179 p = args;
1180 if (*p && *p != '-')
1181 separator = *p++;
1182 arg = NULL;
1183 while (*p) {
1184 q = p;
1185 while (*p && *p != separator)
1186 p++;
1187 while (*p == separator)
1188 *p++ = '\0';
1189 prevarg = arg;
1190 arg = q;
1191 if (process_arg(prevarg, arg, pass))
1192 arg = NULL;
1194 if (arg)
1195 process_arg(arg, NULL, pass);
1198 static void process_response_file(const char *file, int pass)
1200 char str[2048];
1201 FILE *f = nasm_open_read(file, NF_TEXT);
1202 if (!f) {
1203 perror(file);
1204 exit(-1);
1206 while (fgets(str, sizeof str, f)) {
1207 process_args(str, pass);
1209 fclose(f);
1212 static void parse_cmdline(int argc, char **argv, int pass)
1214 FILE *rfile;
1215 char *envreal, *envcopy = NULL, *p;
1216 int i;
1218 *inname = *outname = *listname = *errname = '\0';
1220 /* Initialize all the warnings to their default state */
1221 for (i = 0; i < ERR_WARN_ALL; i++) {
1222 warning_state_init[i] = warning_state[i] =
1223 warnings[i].enabled ? WARN_ST_ENABLED : 0;
1227 * First, process the NASMENV environment variable.
1229 envreal = getenv("NASMENV");
1230 if (envreal) {
1231 envcopy = nasm_strdup(envreal);
1232 process_args(envcopy, pass);
1233 nasm_free(envcopy);
1237 * Now process the actual command line.
1239 while (--argc) {
1240 bool advance;
1241 argv++;
1242 if (argv[0][0] == '@') {
1244 * We have a response file, so process this as a set of
1245 * arguments like the environment variable. This allows us
1246 * to have multiple arguments on a single line, which is
1247 * different to the -@resp file processing below for regular
1248 * NASM.
1250 process_response_file(argv[0]+1, pass);
1251 argc--;
1252 argv++;
1254 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1255 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1256 if (p) {
1257 rfile = nasm_open_read(p, NF_TEXT);
1258 if (rfile) {
1259 process_respfile(rfile, pass);
1260 fclose(rfile);
1261 } else
1262 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1263 "unable to open response file `%s'", p);
1265 } else
1266 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1267 argv += advance, argc -= advance;
1271 * Look for basic command line typos. This definitely doesn't
1272 * catch all errors, but it might help cases of fumbled fingers.
1274 if (pass != 2)
1275 return;
1277 if (!*inname)
1278 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1279 "no input file specified");
1280 else if (!strcmp(inname, errname) ||
1281 !strcmp(inname, outname) ||
1282 !strcmp(inname, listname) ||
1283 (depend_file && !strcmp(inname, depend_file)))
1284 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1285 "file `%s' is both input and output file",
1286 inname);
1288 if (*errname) {
1289 error_file = nasm_open_write(errname, NF_TEXT);
1290 if (!error_file) {
1291 error_file = stderr; /* Revert to default! */
1292 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1293 "cannot open file `%s' for error messages",
1294 errname);
1299 static void assemble_file(char *fname, StrList **depend_ptr)
1301 char *line;
1302 insn output_ins;
1303 int i;
1304 int64_t offs;
1305 int pass_max;
1306 uint64_t prev_offset_changed;
1307 unsigned int stall_count = 0; /* Make sure we make forward progress... */
1309 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1310 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1312 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1313 for (passn = 1; pass0 <= 2; passn++) {
1314 ldfunc def_label;
1316 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1317 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1318 /* pass0 0, 0, 0, ..., 1, 2 */
1320 def_label = passn > 1 ? redefine_label : define_label;
1322 globalbits = cmd_sb; /* set 'bits' to command line default */
1323 cpu = cmd_cpu;
1324 if (pass0 == 2) {
1325 lfmt->init(listname);
1326 } else if (passn == 1 && *listname) {
1327 /* Remove the list file in case we die before the output pass */
1328 remove(listname);
1330 in_absolute = false;
1331 global_offset_changed = 0; /* set by redefine_label */
1332 location.segment = ofmt->section(NULL, pass2, &globalbits);
1333 if (passn > 1) {
1334 saa_rewind(forwrefs);
1335 forwref = saa_rstruct(forwrefs);
1336 raa_free(offsets);
1337 offsets = raa_init();
1339 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1341 /* Revert all warnings to the default state */
1342 memcpy(warning_state, warning_state_init, sizeof warning_state);
1344 globallineno = 0;
1345 if (passn == 1)
1346 location.known = true;
1347 location.offset = offs = get_curr_offs();
1349 while ((line = preproc->getline())) {
1350 globallineno++;
1353 * Here we parse our directives; this is not handled by the
1354 * main parser.
1356 if (process_directives(line))
1357 goto end_of_line; /* Just do final cleanup */
1359 /* Not a directive, or even something that starts with [ */
1361 parse_line(pass1, line, &output_ins, def_label);
1363 if (optimizing > 0) {
1364 if (forwref != NULL && globallineno == forwref->lineno) {
1365 output_ins.forw_ref = true;
1366 do {
1367 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1368 forwref = saa_rstruct(forwrefs);
1369 } while (forwref != NULL
1370 && forwref->lineno == globallineno);
1371 } else
1372 output_ins.forw_ref = false;
1374 if (output_ins.forw_ref) {
1375 if (passn == 1) {
1376 for (i = 0; i < output_ins.operands; i++) {
1377 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1378 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1379 fwinf->lineno = globallineno;
1380 fwinf->operand = i;
1387 /* forw_ref */
1388 if (output_ins.opcode == I_EQU) {
1389 if (pass1 == 1) {
1391 * Special `..' EQUs get processed in pass two,
1392 * except `..@' macro-processor EQUs which are done
1393 * in the normal place.
1395 if (!output_ins.label)
1396 nasm_error(ERR_NONFATAL,
1397 "EQU not preceded by label");
1399 else if (output_ins.label[0] != '.' ||
1400 output_ins.label[1] != '.' ||
1401 output_ins.label[2] == '@') {
1402 if (output_ins.operands == 1 &&
1403 (output_ins.oprs[0].type & IMMEDIATE) &&
1404 output_ins.oprs[0].wrt == NO_SEG) {
1405 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1406 def_label(output_ins.label,
1407 output_ins.oprs[0].segment,
1408 output_ins.oprs[0].offset, NULL,
1409 false, isext);
1410 } else if (output_ins.operands == 2
1411 && (output_ins.oprs[0].type & IMMEDIATE)
1412 && (output_ins.oprs[0].type & COLON)
1413 && output_ins.oprs[0].segment == NO_SEG
1414 && output_ins.oprs[0].wrt == NO_SEG
1415 && (output_ins.oprs[1].type & IMMEDIATE)
1416 && output_ins.oprs[1].segment == NO_SEG
1417 && output_ins.oprs[1].wrt == NO_SEG) {
1418 def_label(output_ins.label,
1419 output_ins.oprs[0].offset | SEG_ABS,
1420 output_ins.oprs[1].offset,
1421 NULL, false, false);
1422 } else
1423 nasm_error(ERR_NONFATAL,
1424 "bad syntax for EQU");
1426 } else {
1428 * Special `..' EQUs get processed here, except
1429 * `..@' macro processor EQUs which are done above.
1431 if (output_ins.label[0] == '.' &&
1432 output_ins.label[1] == '.' &&
1433 output_ins.label[2] != '@') {
1434 if (output_ins.operands == 1 &&
1435 (output_ins.oprs[0].type & IMMEDIATE)) {
1436 define_label(output_ins.label,
1437 output_ins.oprs[0].segment,
1438 output_ins.oprs[0].offset,
1439 NULL, false, false);
1440 } else if (output_ins.operands == 2
1441 && (output_ins.oprs[0].type & IMMEDIATE)
1442 && (output_ins.oprs[0].type & COLON)
1443 && output_ins.oprs[0].segment == NO_SEG
1444 && (output_ins.oprs[1].type & IMMEDIATE)
1445 && output_ins.oprs[1].segment == NO_SEG) {
1446 define_label(output_ins.label,
1447 output_ins.oprs[0].offset | SEG_ABS,
1448 output_ins.oprs[1].offset,
1449 NULL, false, false);
1450 } else
1451 nasm_error(ERR_NONFATAL,
1452 "bad syntax for EQU");
1455 } else { /* instruction isn't an EQU */
1456 int32_t n;
1458 nasm_assert(output_ins.times >= 0);
1460 for (n = 1; n <= output_ins.times; n++) {
1461 if (pass1 == 1) {
1462 int64_t l = insn_size(location.segment, offs,
1463 globalbits, &output_ins);
1465 /* if (using_debug_info) && output_ins.opcode != -1) */
1466 if (using_debug_info)
1467 { /* fbk 03/25/01 */
1468 /* this is done here so we can do debug type info */
1469 int32_t typeinfo =
1470 TYS_ELEMENTS(output_ins.operands);
1471 switch (output_ins.opcode) {
1472 case I_RESB:
1473 typeinfo =
1474 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1475 break;
1476 case I_RESW:
1477 typeinfo =
1478 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1479 break;
1480 case I_RESD:
1481 typeinfo =
1482 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1483 break;
1484 case I_RESQ:
1485 typeinfo =
1486 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1487 break;
1488 case I_REST:
1489 typeinfo =
1490 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1491 break;
1492 case I_RESO:
1493 typeinfo =
1494 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1495 break;
1496 case I_RESY:
1497 typeinfo =
1498 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1499 break;
1500 case I_RESZ:
1501 typeinfo =
1502 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;
1503 break;
1504 case I_DB:
1505 typeinfo |= TY_BYTE;
1506 break;
1507 case I_DW:
1508 typeinfo |= TY_WORD;
1509 break;
1510 case I_DD:
1511 if (output_ins.eops_float)
1512 typeinfo |= TY_FLOAT;
1513 else
1514 typeinfo |= TY_DWORD;
1515 break;
1516 case I_DQ:
1517 typeinfo |= TY_QWORD;
1518 break;
1519 case I_DT:
1520 typeinfo |= TY_TBYTE;
1521 break;
1522 case I_DO:
1523 typeinfo |= TY_OWORD;
1524 break;
1525 case I_DY:
1526 typeinfo |= TY_YWORD;
1527 break;
1528 case I_DZ:
1529 typeinfo |= TY_ZWORD;
1530 break;
1531 default:
1532 typeinfo = TY_LABEL;
1533 break;
1536 dfmt->debug_typevalue(typeinfo);
1540 * For INCBIN, let the code in assemble
1541 * handle TIMES, so we don't have to read the
1542 * input file over and over.
1544 if (l != -1) {
1545 offs += l;
1546 set_curr_offs(offs);
1549 * else l == -1 => invalid instruction, which will be
1550 * flagged as an error on pass 2
1552 } else {
1553 if (n == 2)
1554 lfmt->uplevel(LIST_TIMES);
1555 offs += assemble(location.segment, offs,
1556 globalbits, &output_ins);
1557 set_curr_offs(offs);
1559 } /* not an EQU */
1561 if (output_ins.times > 1)
1562 lfmt->downlevel(LIST_TIMES);
1564 cleanup_insn(&output_ins);
1566 end_of_line:
1567 nasm_free(line);
1568 location.offset = offs = get_curr_offs();
1569 } /* end while (line = preproc->getline... */
1571 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1572 nasm_error(ERR_NONFATAL,
1573 "phase error detected at end of assembly.");
1575 if (pass1 == 1)
1576 preproc->cleanup(1);
1578 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1579 pass0++;
1580 } else if (global_offset_changed &&
1581 global_offset_changed < prev_offset_changed) {
1582 prev_offset_changed = global_offset_changed;
1583 stall_count = 0;
1584 } else {
1585 stall_count++;
1588 if (terminate_after_phase)
1589 break;
1591 if ((stall_count > 997U) || (passn >= pass_max)) {
1592 /* We get here if the labels don't converge
1593 * Example: FOO equ FOO + 1
1595 nasm_error(ERR_NONFATAL,
1596 "Can't find valid values for all labels "
1597 "after %d passes, giving up.", passn);
1598 nasm_error(ERR_NONFATAL,
1599 "Possible causes: recursive EQUs, macro abuse.");
1600 break;
1604 preproc->cleanup(0);
1605 lfmt->cleanup();
1606 if (!terminate_after_phase && opt_verbose_info) {
1607 /* -On and -Ov switches */
1608 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1613 * gnu style error reporting
1614 * This function prints an error message to error_file in the
1615 * style used by GNU. An example would be:
1616 * file.asm:50: error: blah blah blah
1617 * where file.asm is the name of the file, 50 is the line number on
1618 * which the error occurs (or is detected) and "error:" is one of
1619 * the possible optional diagnostics -- it can be "error" or "warning"
1620 * or something else. Finally the line terminates with the actual
1621 * error message.
1623 * @param severity the severity of the warning or error
1624 * @param fmt the printf style format string
1626 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1628 const char *currentfile = NULL;
1629 int32_t lineno = 0;
1631 if (is_suppressed_warning(severity))
1632 return;
1634 if (!(severity & ERR_NOFILE))
1635 src_get(&lineno, &currentfile);
1637 if (!skip_this_pass(severity)) {
1638 if (currentfile) {
1639 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1640 } else {
1641 fputs("nasm: ", error_file);
1645 nasm_verror_common(severity, fmt, ap);
1649 * MS style error reporting
1650 * This function prints an error message to error_file in the
1651 * style used by Visual C and some other Microsoft tools. An example
1652 * would be:
1653 * file.asm(50) : error: blah blah blah
1654 * where file.asm is the name of the file, 50 is the line number on
1655 * which the error occurs (or is detected) and "error:" is one of
1656 * the possible optional diagnostics -- it can be "error" or "warning"
1657 * or something else. Finally the line terminates with the actual
1658 * error message.
1660 * @param severity the severity of the warning or error
1661 * @param fmt the printf style format string
1663 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1665 const char *currentfile = NULL;
1666 int32_t lineno = 0;
1668 if (is_suppressed_warning(severity))
1669 return;
1671 if (!(severity & ERR_NOFILE))
1672 src_get(&lineno, &currentfile);
1674 if (!skip_this_pass(severity)) {
1675 if (currentfile) {
1676 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1677 } else {
1678 fputs("nasm: ", error_file);
1682 nasm_verror_common(severity, fmt, ap);
1686 * check to see if this is a suppressable warning
1688 static inline bool is_valid_warning(int severity)
1690 /* Not a warning at all */
1691 if ((severity & ERR_MASK) != ERR_WARNING)
1692 return false;
1694 return WARN_IDX(severity) < ERR_WARN_ALL;
1698 * check for suppressed warning
1699 * checks for suppressed warning or pass one only warning and we're
1700 * not in pass 1
1702 * @param severity the severity of the warning or error
1703 * @return true if we should abort error/warning printing
1705 static bool is_suppressed_warning(int severity)
1707 /* Might be a warning but suppresed explicitly */
1708 if (is_valid_warning(severity))
1709 return !(warning_state[WARN_IDX(severity)] & WARN_ST_ENABLED);
1710 else
1711 return false;
1714 static bool warning_is_error(int severity)
1716 if (is_valid_warning(severity))
1717 return !!(warning_state[WARN_IDX(severity)] & WARN_ST_ERROR);
1718 else
1719 return false;
1722 static bool skip_this_pass(int severity)
1725 * See if it's a pass-specific error or warning which should be skipped.
1726 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1727 * they cannot be resumed from.
1729 if ((severity & ERR_MASK) > ERR_NONFATAL)
1730 return false;
1733 * passn is 1 on the very first pass only.
1734 * pass0 is 2 on the code-generation (final) pass only.
1735 * These are the passes we care about in this case.
1737 return (((severity & ERR_PASS1) && passn != 1) ||
1738 ((severity & ERR_PASS2) && pass0 != 2));
1742 * common error reporting
1743 * This is the common back end of the error reporting schemes currently
1744 * implemented. It prints the nature of the warning and then the
1745 * specific error message to error_file and may or may not return. It
1746 * doesn't return if the error severity is a "panic" or "debug" type.
1748 * @param severity the severity of the warning or error
1749 * @param fmt the printf style format string
1751 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1753 char msg[1024];
1754 const char *pfx;
1756 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1757 case ERR_WARNING:
1758 pfx = "warning: ";
1759 break;
1760 case ERR_NONFATAL:
1761 pfx = "error: ";
1762 break;
1763 case ERR_FATAL:
1764 pfx = "fatal: ";
1765 break;
1766 case ERR_PANIC:
1767 pfx = "panic: ";
1768 break;
1769 case ERR_DEBUG:
1770 pfx = "debug: ";
1771 break;
1772 default:
1773 pfx = "";
1774 break;
1777 vsnprintf(msg, sizeof msg - 64, fmt, args);
1778 if (is_valid_warning(severity) && WARN_IDX(severity) != ERR_WARN_OTHER) {
1779 char *p = strchr(msg, '\0');
1780 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
1783 if (!skip_this_pass(severity))
1784 fprintf(error_file, "%s%s\n", pfx, msg);
1786 /* Are we recursing from error_list_macros? */
1787 if (severity & ERR_PP_LISTMACRO)
1788 return;
1791 * Don't suppress this with skip_this_pass(), or we don't get
1792 * pass1 or preprocessor warnings in the list file
1794 lfmt->error(severity, pfx, msg);
1796 if (skip_this_pass(severity))
1797 return;
1799 if (severity & ERR_USAGE)
1800 want_usage = true;
1802 preproc->error_list_macros(severity);
1804 switch (severity & ERR_MASK) {
1805 case ERR_DEBUG:
1806 /* no further action, by definition */
1807 break;
1808 case ERR_WARNING:
1809 /* Treat warnings as errors */
1810 if (warning_is_error(severity))
1811 terminate_after_phase = true;
1812 break;
1813 case ERR_NONFATAL:
1814 terminate_after_phase = true;
1815 break;
1816 case ERR_FATAL:
1817 if (ofile) {
1818 fclose(ofile);
1819 remove(outname);
1820 ofile = NULL;
1822 if (want_usage)
1823 usage();
1824 exit(1); /* instantly die */
1825 break; /* placate silly compilers */
1826 case ERR_PANIC:
1827 fflush(NULL);
1828 /* abort(); */ /* halt, catch fire, and dump core */
1829 if (ofile) {
1830 fclose(ofile);
1831 remove(outname);
1832 ofile = NULL;
1834 exit(3);
1835 break;
1839 static void usage(void)
1841 fputs("type `nasm -h' for help\n", error_file);