output: bin -- Use nasm_error helpers
[nasm.git] / asm / nasm.c
blobeb6f476015014b5e0d54423189fb278080e17c50
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 <limits.h>
46 #include "nasm.h"
47 #include "nasmlib.h"
48 #include "nctype.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 *, struct 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 struct optimization optimizing =
121 { MAX_OPTIMIZE, OPTIM_ALL_ENABLED }; /* number of optimization passes to take */
122 static int cmd_sb = 16; /* by default */
124 iflag_t cpu;
125 static iflag_t cmd_cpu;
127 struct location location;
128 bool in_absolute; /* Flag we are in ABSOLUTE seg */
129 struct location absolute; /* Segment/offset inside ABSOLUTE */
131 static struct RAA *offsets;
133 static struct SAA *forwrefs; /* keep track of forward references */
134 static const struct forwrefinfo *forwref;
136 static const struct preproc_ops *preproc;
137 static struct strlist *include_path;
139 #define OP_NORMAL (1U << 0)
140 #define OP_PREPROCESS (1U << 1)
141 #define OP_DEPEND (1U << 2)
143 static unsigned int operating_mode;
145 /* Dependency flags */
146 static bool depend_emit_phony = false;
147 static bool depend_missing_ok = false;
148 static const char *depend_target = NULL;
149 static const char *depend_file = NULL;
150 struct strlist *depend_list;
152 static bool want_usage;
153 static bool terminate_after_phase;
154 bool user_nolist = false;
156 static char *quote_for_pmake(const char *str);
157 static char *quote_for_wmake(const char *str);
158 static char *(*quote_for_make)(const char *) = quote_for_pmake;
161 * Execution limits that can be set via a command-line option or %pragma
164 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
166 int64_t nasm_limit[LIMIT_MAX+1] =
167 { LIMIT_MAX_VAL, 1000, 1000000, 1000000, 1000000, 2000000000 };
169 struct limit_info {
170 const char *name;
171 const char *help;
173 static const struct limit_info limit_info[LIMIT_MAX+1] = {
174 { "passes", "total number of passes" },
175 { "stalled-passes", "number of passes without forward progress" },
176 { "macro-levels", "levels of macro expansion"},
177 { "rep", "%rep count" },
178 { "eval", "expression evaluation descent"},
179 { "lines", "total source lines processed"}
182 enum directive_result
183 nasm_set_limit(const char *limit, const char *valstr)
185 int i;
186 int64_t val;
187 bool rn_error;
188 int errlevel;
190 for (i = 0; i <= LIMIT_MAX; i++) {
191 if (!nasm_stricmp(limit, limit_info[i].name))
192 break;
194 if (i > LIMIT_MAX) {
195 if (passn == 0)
196 errlevel = ERR_WARNING|ERR_NOFILE|ERR_USAGE;
197 else
198 errlevel = ERR_WARNING|ERR_PASS1|ERR_WARN_UNKNOWN_PRAGMA;
199 nasm_error(errlevel, "unknown limit: `%s'", limit);
200 return DIRR_ERROR;
203 if (!nasm_stricmp(valstr, "unlimited")) {
204 val = LIMIT_MAX_VAL;
205 } else {
206 val = readnum(valstr, &rn_error);
207 if (rn_error || val < 0) {
208 if (passn == 0)
209 errlevel = ERR_WARNING|ERR_NOFILE|ERR_USAGE;
210 else
211 errlevel = ERR_WARNING|ERR_PASS1|ERR_WARN_BAD_PRAGMA;
212 nasm_error(errlevel, "invalid limit value: `%s'", limit);
213 return DIRR_ERROR;
215 if (val > LIMIT_MAX_VAL)
216 val = LIMIT_MAX_VAL;
219 nasm_limit[i] = val;
220 return DIRR_OK;
223 int64_t switch_segment(int32_t segment)
225 location.segment = segment;
226 if (segment == NO_SEG) {
227 location.offset = absolute.offset;
228 in_absolute = true;
229 } else {
230 location.offset = raa_read(offsets, segment);
231 in_absolute = false;
233 return location.offset;
236 static void set_curr_offs(int64_t l_off)
238 if (in_absolute)
239 absolute.offset = l_off;
240 else
241 offsets = raa_write(offsets, location.segment, l_off);
244 static void increment_offset(int64_t delta)
246 if (unlikely(delta == 0))
247 return;
249 location.offset += delta;
250 set_curr_offs(location.offset);
253 static void nasm_fputs(const char *line, FILE * outfile)
255 if (outfile) {
256 fputs(line, outfile);
257 putc('\n', outfile);
258 } else
259 puts(line);
263 * Define system-defined macros that are not part of
264 * macros/standard.mac.
266 static void define_macros(void)
268 const struct compile_time * const oct = &official_compile_time;
269 char temp[128];
271 if (oct->have_local) {
272 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &oct->local);
273 preproc->pre_define(temp);
274 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &oct->local);
275 preproc->pre_define(temp);
276 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &oct->local);
277 preproc->pre_define(temp);
278 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &oct->local);
279 preproc->pre_define(temp);
282 if (oct->have_gm) {
283 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &oct->gm);
284 preproc->pre_define(temp);
285 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &oct->gm);
286 preproc->pre_define(temp);
287 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &oct->gm);
288 preproc->pre_define(temp);
289 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &oct->gm);
290 preproc->pre_define(temp);
293 if (oct->have_posix) {
294 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, oct->posix);
295 preproc->pre_define(temp);
299 * In case if output format is defined by alias
300 * we have to put shortname of the alias itself here
301 * otherwise ABI backward compatibility gets broken.
303 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
304 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
305 preproc->pre_define(temp);
308 * Output-format specific macros.
310 if (ofmt->stdmac)
311 preproc->extra_stdmac(ofmt->stdmac);
314 * Debug format, if any
316 if (dfmt != &null_debug_form) {
317 snprintf(temp, sizeof(temp), "__DEBUG_FORMAT__=%s", dfmt->shortname);
318 preproc->pre_define(temp);
323 * Initialize the preprocessor, set up the include path, and define
324 * the system-included macros. This is called between passes 1 and 2
325 * of parsing the command options; ofmt and dfmt are defined at this
326 * point.
328 * Command-line specified preprocessor directives (-p, -d, -u,
329 * --pragma, --before) are processed after this function.
331 static void preproc_init(struct strlist *ipath)
333 preproc->init();
334 define_macros();
335 preproc->include_path(ipath);
338 static void emit_dependencies(struct strlist *list)
340 FILE *deps;
341 int linepos, len;
342 bool wmake = (quote_for_make == quote_for_wmake);
343 const char *wrapstr, *nulltarget;
344 struct strlist_entry *l;
346 if (!list)
347 return;
349 wrapstr = wmake ? " &\n " : " \\\n ";
350 nulltarget = wmake ? "\t%null\n" : "";
352 if (depend_file && strcmp(depend_file, "-")) {
353 deps = nasm_open_write(depend_file, NF_TEXT);
354 if (!deps) {
355 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
356 "unable to write dependency file `%s'", depend_file);
357 return;
359 } else {
360 deps = stdout;
363 linepos = fprintf(deps, "%s :", depend_target);
364 list_for_each(l, list->head) {
365 char *file = quote_for_make(l->str);
366 len = strlen(file);
367 if (linepos + len > 62 && linepos > 1) {
368 fputs(wrapstr, deps);
369 linepos = 1;
371 fprintf(deps, " %s", file);
372 linepos += len+1;
373 nasm_free(file);
375 fprintf(deps, "\n\n");
377 list_for_each(l, list->head) {
378 if (depend_emit_phony) {
379 char *file = quote_for_make(l->str);
380 fprintf(deps, "%s :\n%s\n", file, nulltarget);
381 nasm_free(file);
385 strlist_free(list);
387 if (deps != stdout)
388 fclose(deps);
391 /* Convert a struct tm to a POSIX-style time constant */
392 static int64_t make_posix_time(const struct tm *tm)
394 int64_t t;
395 int64_t y = tm->tm_year;
397 /* See IEEE 1003.1:2004, section 4.14 */
399 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
400 t += tm->tm_yday;
401 t *= 24;
402 t += tm->tm_hour;
403 t *= 60;
404 t += tm->tm_min;
405 t *= 60;
406 t += tm->tm_sec;
408 return t;
411 static void timestamp(void)
413 struct compile_time * const oct = &official_compile_time;
414 const struct tm *tp, *best_gm;
416 time(&oct->t);
418 best_gm = NULL;
420 tp = localtime(&oct->t);
421 if (tp) {
422 oct->local = *tp;
423 best_gm = &oct->local;
424 oct->have_local = true;
427 tp = gmtime(&oct->t);
428 if (tp) {
429 oct->gm = *tp;
430 best_gm = &oct->gm;
431 oct->have_gm = true;
432 if (!oct->have_local)
433 oct->local = oct->gm;
434 } else {
435 oct->gm = oct->local;
438 if (best_gm) {
439 oct->posix = make_posix_time(best_gm);
440 oct->have_posix = true;
444 int main(int argc, char **argv)
446 timestamp();
448 iflag_set_default_cpu(&cpu);
449 iflag_set_default_cpu(&cmd_cpu);
451 include_path = strlist_alloc();
453 pass0 = 0;
454 want_usage = terminate_after_phase = false;
455 nasm_set_verror(nasm_verror_gnu);
457 error_file = stderr;
459 nasm_ctype_init();
460 src_init();
463 * We must call init_labels() before the command line parsing,
464 * because we may be setting prefixes/suffixes from the command
465 * line.
467 init_labels();
469 offsets = raa_init();
470 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
472 preproc = &nasmpp;
473 operating_mode = OP_NORMAL;
475 parse_cmdline(argc, argv, 1);
476 if (terminate_after_phase) {
477 if (want_usage)
478 usage();
479 return 1;
482 /* At this point we have ofmt and the name of the desired debug format */
483 if (!using_debug_info) {
484 /* No debug info, redirect to the null backend (empty stubs) */
485 dfmt = &null_debug_form;
486 } else if (!debug_format) {
487 /* Default debug format for this backend */
488 dfmt = ofmt->default_dfmt;
489 } else {
490 dfmt = dfmt_find(ofmt, debug_format);
491 if (!dfmt) {
492 nasm_fatalf(ERR_NOFILE | ERR_USAGE,
493 "unrecognized debug format `%s' for"
494 " output format `%s'",
495 debug_format, ofmt->shortname);
499 preproc_init(include_path);
501 parse_cmdline(argc, argv, 2);
502 if (terminate_after_phase) {
503 if (want_usage)
504 usage();
505 return 1;
508 /* Save away the default state of warnings */
509 memcpy(warning_state_init, warning_state, sizeof warning_state);
511 /* Dependency filename if we are also doing other things */
512 if (!depend_file && (operating_mode & ~OP_DEPEND)) {
513 if (outname)
514 depend_file = nasm_strcat(outname, ".d");
515 else
516 depend_file = filename_set_extension(inname, ".d");
520 * If no output file name provided and this
521 * is preprocess mode, we're perfectly
522 * fine to output into stdout.
524 if (!outname && !(operating_mode & OP_PREPROCESS)) {
525 outname = filename_set_extension(inname, ofmt->extension);
526 if (!strcmp(outname, inname)) {
527 outname = "nasm.out";
528 nasm_error(ERR_WARNING,
529 "default output file same as input, using `%s' for output\n",
530 outname);
534 depend_list = (operating_mode & OP_DEPEND) ? strlist_alloc() : NULL;
536 if (!depend_target)
537 depend_target = quote_for_make(outname);
539 if (!(operating_mode & (OP_PREPROCESS|OP_NORMAL))) {
540 char *line;
542 if (depend_missing_ok)
543 preproc->include_path(NULL); /* "assume generated" */
545 preproc->reset(inname, 0, depend_list);
546 ofile = NULL;
547 while ((line = preproc->getline()))
548 nasm_free(line);
549 preproc->cleanup(0);
550 } else if (operating_mode & OP_PREPROCESS) {
551 char *line;
552 const char *file_name = NULL;
553 int32_t prior_linnum = 0;
554 int lineinc = 0;
556 if (outname) {
557 ofile = nasm_open_write(outname, NF_TEXT);
558 if (!ofile)
559 nasm_fatalf(ERR_NOFILE,
560 "unable to open output file `%s'",
561 outname);
562 } else
563 ofile = NULL;
565 location.known = false;
567 /* pass = 1; */
568 preproc->reset(inname, 3, depend_list);
570 /* Revert all warnings to the default state */
571 memcpy(warning_state, warning_state_init, sizeof warning_state);
573 while ((line = preproc->getline())) {
575 * We generate %line directives if needed for later programs
577 int32_t linnum = prior_linnum += lineinc;
578 int altline = src_get(&linnum, &file_name);
579 if (altline) {
580 if (altline == 1 && lineinc == 1)
581 nasm_fputs("", ofile);
582 else {
583 lineinc = (altline != -1 || lineinc != 1);
584 fprintf(ofile ? ofile : stdout,
585 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
586 file_name);
588 prior_linnum = linnum;
590 nasm_fputs(line, ofile);
591 nasm_free(line);
593 preproc->cleanup(0);
594 if (ofile)
595 fclose(ofile);
596 if (ofile && terminate_after_phase && !keep_all)
597 remove(outname);
598 ofile = NULL;
601 if (operating_mode & OP_NORMAL) {
602 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
603 if (!ofile)
604 nasm_fatalf(ERR_NOFILE,
605 "unable to open output file `%s'", outname);
607 ofmt->init();
608 dfmt->init();
610 assemble_file(inname, depend_list);
612 if (!terminate_after_phase) {
613 ofmt->cleanup();
614 cleanup_labels();
615 fflush(ofile);
616 if (ferror(ofile)) {
617 nasm_error(ERR_NONFATAL|ERR_NOFILE,
618 "write error on output file `%s'", outname);
619 terminate_after_phase = true;
623 if (ofile) {
624 fclose(ofile);
625 if (terminate_after_phase && !keep_all)
626 remove(outname);
627 ofile = NULL;
631 if (depend_list && !terminate_after_phase)
632 emit_dependencies(depend_list);
634 if (want_usage)
635 usage();
637 raa_free(offsets);
638 saa_free(forwrefs);
639 eval_cleanup();
640 stdscan_cleanup();
641 src_free();
642 strlist_free(include_path);
644 return terminate_after_phase;
648 * Get a parameter for a command line option.
649 * First arg must be in the form of e.g. -f...
651 static char *get_param(char *p, char *q, bool *advance)
653 *advance = false;
654 if (p[2]) /* the parameter's in the option */
655 return nasm_skip_spaces(p + 2);
656 if (q && q[0]) {
657 *advance = true;
658 return q;
660 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
661 "option `-%c' requires an argument", p[1]);
662 return NULL;
666 * Copy a filename
668 static void copy_filename(const char **dst, const char *src, const char *what)
670 if (*dst)
671 nasm_fatal("more than one %s file specified: %s\n", what, src);
673 *dst = nasm_strdup(src);
677 * Convert a string to a POSIX make-safe form
679 static char *quote_for_pmake(const char *str)
681 const char *p;
682 char *os, *q;
684 size_t n = 1; /* Terminating zero */
685 size_t nbs = 0;
687 if (!str)
688 return NULL;
690 for (p = str; *p; p++) {
691 switch (*p) {
692 case ' ':
693 case '\t':
694 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
695 n += nbs + 2;
696 nbs = 0;
697 break;
698 case '$':
699 case '#':
700 nbs = 0;
701 n += 2;
702 break;
703 case '\\':
704 nbs++;
705 n++;
706 break;
707 default:
708 nbs = 0;
709 n++;
710 break;
714 /* Convert N backslashes at the end of filename to 2N backslashes */
715 if (nbs)
716 n += nbs;
718 os = q = nasm_malloc(n);
720 nbs = 0;
721 for (p = str; *p; p++) {
722 switch (*p) {
723 case ' ':
724 case '\t':
725 while (nbs--)
726 *q++ = '\\';
727 *q++ = '\\';
728 *q++ = *p;
729 break;
730 case '$':
731 *q++ = *p;
732 *q++ = *p;
733 nbs = 0;
734 break;
735 case '#':
736 *q++ = '\\';
737 *q++ = *p;
738 nbs = 0;
739 break;
740 case '\\':
741 *q++ = *p;
742 nbs++;
743 break;
744 default:
745 *q++ = *p;
746 nbs = 0;
747 break;
750 while (nbs--)
751 *q++ = '\\';
753 *q = '\0';
755 return os;
759 * Convert a string to a Watcom make-safe form
761 static char *quote_for_wmake(const char *str)
763 const char *p;
764 char *os, *q;
765 bool quote = false;
767 size_t n = 1; /* Terminating zero */
769 if (!str)
770 return NULL;
772 for (p = str; *p; p++) {
773 switch (*p) {
774 case ' ':
775 case '\t':
776 case '&':
777 quote = true;
778 n++;
779 break;
780 case '\"':
781 quote = true;
782 n += 2;
783 break;
784 case '$':
785 case '#':
786 n += 2;
787 break;
788 default:
789 n++;
790 break;
794 if (quote)
795 n += 2;
797 os = q = nasm_malloc(n);
799 if (quote)
800 *q++ = '\"';
802 for (p = str; *p; p++) {
803 switch (*p) {
804 case '$':
805 case '#':
806 *q++ = '$';
807 *q++ = *p;
808 break;
809 case '\"':
810 *q++ = *p;
811 *q++ = *p;
812 break;
813 default:
814 *q++ = *p;
815 break;
819 if (quote)
820 *q++ = '\"';
822 *q = '\0';
824 return os;
827 enum text_options {
828 OPT_BOGUS,
829 OPT_VERSION,
830 OPT_HELP,
831 OPT_ABORT_ON_PANIC,
832 OPT_MANGLE,
833 OPT_INCLUDE,
834 OPT_PRAGMA,
835 OPT_BEFORE,
836 OPT_LIMIT,
837 OPT_KEEP_ALL
839 struct textargs {
840 const char *label;
841 enum text_options opt;
842 bool need_arg;
843 int pvt;
845 static const struct textargs textopts[] = {
846 {"v", OPT_VERSION, false, 0},
847 {"version", OPT_VERSION, false, 0},
848 {"help", OPT_HELP, false, 0},
849 {"abort-on-panic", OPT_ABORT_ON_PANIC, false, 0},
850 {"prefix", OPT_MANGLE, true, LM_GPREFIX},
851 {"postfix", OPT_MANGLE, true, LM_GSUFFIX},
852 {"gprefix", OPT_MANGLE, true, LM_GPREFIX},
853 {"gpostfix", OPT_MANGLE, true, LM_GSUFFIX},
854 {"lprefix", OPT_MANGLE, true, LM_LPREFIX},
855 {"lpostfix", OPT_MANGLE, true, LM_LSUFFIX},
856 {"include", OPT_INCLUDE, true, 0},
857 {"pragma", OPT_PRAGMA, true, 0},
858 {"before", OPT_BEFORE, true, 0},
859 {"limit-", OPT_LIMIT, true, 0},
860 {"keep-all", OPT_KEEP_ALL, false, 0},
861 {NULL, OPT_BOGUS, false, 0}
864 static void show_version(void)
866 printf("NASM version %s compiled on %s%s\n",
867 nasm_version, nasm_date, nasm_compile_options);
868 exit(0);
871 static bool stopoptions = false;
872 static bool process_arg(char *p, char *q, int pass)
874 char *param;
875 bool advance = false;
877 if (!p || !p[0])
878 return false;
880 if (p[0] == '-' && !stopoptions) {
881 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
882 /* These parameters take values */
883 if (!(param = get_param(p, q, &advance)))
884 return advance;
887 switch (p[1]) {
888 case 's':
889 if (pass == 1)
890 error_file = stdout;
891 break;
893 case 'o': /* output file */
894 if (pass == 2)
895 copy_filename(&outname, param, "output");
896 break;
898 case 'f': /* output format */
899 if (pass == 1) {
900 ofmt = ofmt_find(param, &ofmt_alias);
901 if (!ofmt) {
902 nasm_fatalf(ERR_NOFILE | ERR_USAGE,
903 "unrecognised output format `%s' - "
904 "use -hf for a list", param);
907 break;
909 case 'O': /* Optimization level */
910 if (pass == 1) {
911 int opt;
913 if (!*param) {
914 /* Naked -O == -Ox */
915 optimizing.level = MAX_OPTIMIZE;
916 } else {
917 while (*param) {
918 switch (*param) {
919 case '0': case '1': case '2': case '3': case '4':
920 case '5': case '6': case '7': case '8': case '9':
921 opt = strtoul(param, &param, 10);
923 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
924 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
925 if (opt < 2)
926 optimizing.level = opt - 1;
927 else
928 optimizing.level = opt;
929 break;
931 case 'v':
932 case '+':
933 param++;
934 opt_verbose_info = true;
935 break;
937 case 'x':
938 param++;
939 optimizing.level = MAX_OPTIMIZE;
940 break;
942 default:
943 nasm_fatal("unknown optimization option -O%c\n",
944 *param);
945 break;
948 if (optimizing.level > MAX_OPTIMIZE)
949 optimizing.level = MAX_OPTIMIZE;
952 break;
954 case 'p': /* pre-include */
955 case 'P':
956 if (pass == 2)
957 preproc->pre_include(param);
958 break;
960 case 'd': /* pre-define */
961 case 'D':
962 if (pass == 2)
963 preproc->pre_define(param);
964 break;
966 case 'u': /* un-define */
967 case 'U':
968 if (pass == 2)
969 preproc->pre_undefine(param);
970 break;
972 case 'i': /* include search path */
973 case 'I':
974 if (pass == 1)
975 strlist_add(include_path, param);
976 break;
978 case 'l': /* listing file */
979 if (pass == 2)
980 copy_filename(&listname, param, "listing");
981 break;
983 case 'Z': /* error messages file */
984 if (pass == 1)
985 copy_filename(&errname, param, "error");
986 break;
988 case 'F': /* specify debug format */
989 if (pass == 1) {
990 using_debug_info = true;
991 debug_format = param;
993 break;
995 case 'X': /* specify error reporting format */
996 if (pass == 1) {
997 if (nasm_stricmp("vc", param) == 0)
998 nasm_set_verror(nasm_verror_vc);
999 else if (nasm_stricmp("gnu", param) == 0)
1000 nasm_set_verror(nasm_verror_gnu);
1001 else
1002 nasm_fatalf(ERR_NOFILE | ERR_USAGE,
1003 "unrecognized error reporting format `%s'",
1004 param);
1006 break;
1008 case 'g':
1009 if (pass == 1) {
1010 using_debug_info = true;
1011 if (p[2])
1012 debug_format = nasm_skip_spaces(p + 2);
1014 break;
1016 case 'h':
1017 help(p[2]);
1018 exit(0); /* never need usage message here */
1019 break;
1021 case 'y':
1022 printf("\nvalid debug formats for '%s' output format are"
1023 " ('*' denotes default):\n", ofmt->shortname);
1024 dfmt_list(ofmt, stdout);
1025 exit(0);
1026 break;
1028 case 't':
1029 if (pass == 2) {
1030 tasm_compatible_mode = true;
1031 nasm_ctype_tasm_mode();
1033 break;
1035 case 'v':
1036 show_version();
1037 break;
1039 case 'e': /* preprocess only */
1040 case 'E':
1041 if (pass == 1)
1042 operating_mode = OP_PREPROCESS;
1043 break;
1045 case 'a': /* assemble only - don't preprocess */
1046 if (pass == 1)
1047 preproc = &preproc_nop;
1048 break;
1050 case 'w':
1051 case 'W':
1052 if (pass == 2) {
1053 if (!set_warning_status(param)) {
1054 nasm_error(ERR_WARNING|ERR_NOFILE|ERR_WARN_UNK_WARNING,
1055 "unknown warning option: %s", param);
1058 break;
1060 case 'M':
1061 if (pass == 1) {
1062 switch (p[2]) {
1063 case 'W':
1064 quote_for_make = quote_for_wmake;
1065 break;
1066 case 'D':
1067 case 'F':
1068 case 'T':
1069 case 'Q':
1070 advance = true;
1071 break;
1072 default:
1073 break;
1075 } else {
1076 switch (p[2]) {
1077 case 0:
1078 operating_mode = OP_DEPEND;
1079 break;
1080 case 'G':
1081 operating_mode = OP_DEPEND;
1082 depend_missing_ok = true;
1083 break;
1084 case 'P':
1085 depend_emit_phony = true;
1086 break;
1087 case 'D':
1088 operating_mode |= OP_DEPEND;
1089 if (q && (q[0] != '-' || q[1] == '\0')) {
1090 depend_file = q;
1091 advance = true;
1093 break;
1094 case 'F':
1095 depend_file = q;
1096 advance = true;
1097 break;
1098 case 'T':
1099 depend_target = q;
1100 advance = true;
1101 break;
1102 case 'Q':
1103 depend_target = quote_for_make(q);
1104 advance = true;
1105 break;
1106 case 'W':
1107 /* handled in pass 1 */
1108 break;
1109 default:
1110 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1111 "unknown dependency option `-M%c'", p[2]);
1112 break;
1115 if (advance && (!q || !q[0])) {
1116 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1117 "option `-M%c' requires a parameter", p[2]);
1118 break;
1120 break;
1122 case '-':
1124 const struct textargs *tx;
1125 size_t olen, plen;
1126 char *eqsave;
1128 p += 2;
1130 if (!*p) { /* -- => stop processing options */
1131 stopoptions = true;
1132 break;
1135 plen = strlen(p);
1136 for (tx = textopts; tx->label; tx++) {
1137 olen = strlen(tx->label);
1139 if (olen > plen)
1140 continue;
1142 if (nasm_memicmp(p, tx->label, olen))
1143 continue;
1145 if (tx->label[olen-1] == '-')
1146 break; /* Incomplete option */
1148 if (!p[olen] || p[olen] == '=')
1149 break; /* Complete option */
1152 if (!tx->label) {
1153 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1154 "unrecognized option `--%s'", p);
1157 eqsave = param = strchr(p+olen, '=');
1158 if (param)
1159 *param++ = '\0';
1161 if (tx->need_arg) {
1162 if (!param) {
1163 param = q;
1164 advance = true;
1167 /* Note: a null string is a valid parameter */
1168 if (!param) {
1169 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1170 "option `--%s' requires an argument",
1172 break;
1174 } else {
1175 if (param) {
1176 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1177 "option `--%s' does not take an argument",
1183 switch (tx->opt) {
1184 case OPT_VERSION:
1185 show_version();
1186 break;
1187 case OPT_ABORT_ON_PANIC:
1188 abort_on_panic = true;
1189 break;
1190 case OPT_MANGLE:
1191 if (pass == 2)
1192 set_label_mangle(tx->pvt, param);
1193 break;
1194 case OPT_INCLUDE:
1195 if (pass == 2)
1196 preproc->pre_include(q);
1197 break;
1198 case OPT_PRAGMA:
1199 if (pass == 2)
1200 preproc->pre_command("pragma", param);
1201 break;
1202 case OPT_BEFORE:
1203 if (pass == 2)
1204 preproc->pre_command(NULL, param);
1205 break;
1206 case OPT_LIMIT:
1207 if (pass == 1)
1208 nasm_set_limit(p+olen, param);
1209 break;
1210 case OPT_KEEP_ALL:
1211 keep_all = true;
1212 break;
1213 case OPT_HELP:
1214 help(0);
1215 exit(0);
1216 default:
1217 panic();
1220 if (eqsave)
1221 *eqsave = '='; /* Restore = argument separator */
1223 break;
1226 default:
1227 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1228 "unrecognised option `-%c'", p[1]);
1229 break;
1231 } else if (pass == 2) {
1232 /* In theory we could allow multiple input files... */
1233 copy_filename(&inname, p, "input");
1236 return advance;
1239 #define ARG_BUF_DELTA 128
1241 static void process_respfile(FILE * rfile, int pass)
1243 char *buffer, *p, *q, *prevarg;
1244 int bufsize, prevargsize;
1246 bufsize = prevargsize = ARG_BUF_DELTA;
1247 buffer = nasm_malloc(ARG_BUF_DELTA);
1248 prevarg = nasm_malloc(ARG_BUF_DELTA);
1249 prevarg[0] = '\0';
1251 while (1) { /* Loop to handle all lines in file */
1252 p = buffer;
1253 while (1) { /* Loop to handle long lines */
1254 q = fgets(p, bufsize - (p - buffer), rfile);
1255 if (!q)
1256 break;
1257 p += strlen(p);
1258 if (p > buffer && p[-1] == '\n')
1259 break;
1260 if (p - buffer > bufsize - 10) {
1261 int offset;
1262 offset = p - buffer;
1263 bufsize += ARG_BUF_DELTA;
1264 buffer = nasm_realloc(buffer, bufsize);
1265 p = buffer + offset;
1269 if (!q && p == buffer) {
1270 if (prevarg[0])
1271 process_arg(prevarg, NULL, pass);
1272 nasm_free(buffer);
1273 nasm_free(prevarg);
1274 return;
1278 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1279 * them are present at the end of the line.
1281 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1283 while (p > buffer && nasm_isspace(p[-1]))
1284 *--p = '\0';
1286 p = nasm_skip_spaces(buffer);
1288 if (process_arg(prevarg, p, pass))
1289 *p = '\0';
1291 if ((int) strlen(p) > prevargsize - 10) {
1292 prevargsize += ARG_BUF_DELTA;
1293 prevarg = nasm_realloc(prevarg, prevargsize);
1295 strncpy(prevarg, p, prevargsize);
1299 /* Function to process args from a string of args, rather than the
1300 * argv array. Used by the environment variable and response file
1301 * processing.
1303 static void process_args(char *args, int pass)
1305 char *p, *q, *arg, *prevarg;
1306 char separator = ' ';
1308 p = args;
1309 if (*p && *p != '-')
1310 separator = *p++;
1311 arg = NULL;
1312 while (*p) {
1313 q = p;
1314 while (*p && *p != separator)
1315 p++;
1316 while (*p == separator)
1317 *p++ = '\0';
1318 prevarg = arg;
1319 arg = q;
1320 if (process_arg(prevarg, arg, pass))
1321 arg = NULL;
1323 if (arg)
1324 process_arg(arg, NULL, pass);
1327 static void process_response_file(const char *file, int pass)
1329 char str[2048];
1330 FILE *f = nasm_open_read(file, NF_TEXT);
1331 if (!f) {
1332 perror(file);
1333 exit(-1);
1335 while (fgets(str, sizeof str, f)) {
1336 process_args(str, pass);
1338 fclose(f);
1341 static void parse_cmdline(int argc, char **argv, int pass)
1343 FILE *rfile;
1344 char *envreal, *envcopy = NULL, *p;
1345 int i;
1347 /* Initialize all the warnings to their default state */
1348 for (i = 0; i < ERR_WARN_ALL; i++) {
1349 warning_state_init[i] = warning_state[i] =
1350 warnings[i].enabled ? WARN_ST_ENABLED : 0;
1354 * First, process the NASMENV environment variable.
1356 envreal = getenv("NASMENV");
1357 if (envreal) {
1358 envcopy = nasm_strdup(envreal);
1359 process_args(envcopy, pass);
1360 nasm_free(envcopy);
1364 * Now process the actual command line.
1366 while (--argc) {
1367 bool advance;
1368 argv++;
1369 if (argv[0][0] == '@') {
1371 * We have a response file, so process this as a set of
1372 * arguments like the environment variable. This allows us
1373 * to have multiple arguments on a single line, which is
1374 * different to the -@resp file processing below for regular
1375 * NASM.
1377 process_response_file(argv[0]+1, pass);
1378 argc--;
1379 argv++;
1381 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1382 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1383 if (p) {
1384 rfile = nasm_open_read(p, NF_TEXT);
1385 if (rfile) {
1386 process_respfile(rfile, pass);
1387 fclose(rfile);
1388 } else
1389 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1390 "unable to open response file `%s'", p);
1392 } else
1393 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1394 argv += advance, argc -= advance;
1398 * Look for basic command line typos. This definitely doesn't
1399 * catch all errors, but it might help cases of fumbled fingers.
1401 if (pass != 2)
1402 return;
1404 if (!inname)
1405 nasm_fatalf(ERR_NOFILE | ERR_USAGE, "no input file specified");
1407 else if ((errname && !strcmp(inname, errname)) ||
1408 (outname && !strcmp(inname, outname)) ||
1409 (listname && !strcmp(inname, listname)) ||
1410 (depend_file && !strcmp(inname, depend_file)))
1411 nasm_fatalf(ERR_USAGE, "will not overwrite input file");
1413 if (errname) {
1414 error_file = nasm_open_write(errname, NF_TEXT);
1415 if (!error_file) {
1416 error_file = stderr; /* Revert to default! */
1417 nasm_fatalf(ERR_NOFILE | ERR_USAGE,
1418 "cannot open file `%s' for error messages",
1419 errname);
1424 static void assemble_file(const char *fname, struct strlist *depend_list)
1426 char *line;
1427 insn output_ins;
1428 int i;
1429 uint64_t prev_offset_changed;
1430 int64_t stall_count = 0; /* Make sure we make forward progress... */
1432 switch (cmd_sb) {
1433 case 16:
1434 break;
1435 case 32:
1436 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1437 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1438 break;
1439 case 64:
1440 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1441 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1442 break;
1443 default:
1444 panic();
1445 break;
1448 prev_offset_changed = nasm_limit[LIMIT_PASSES];
1449 for (passn = 1; pass0 <= 2; passn++) {
1450 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1451 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1452 /* pass0 0, 0, 0, ..., 1, 2 */
1454 globalbits = cmd_sb; /* set 'bits' to command line default */
1455 cpu = cmd_cpu;
1456 if (pass0 == 2) {
1457 lfmt->init(listname);
1458 } else if (passn == 1 && listname && !keep_all) {
1459 /* Remove the list file in case we die before the output pass */
1460 remove(listname);
1462 in_absolute = false;
1463 global_offset_changed = 0; /* set by redefine_label */
1464 if (passn > 1) {
1465 saa_rewind(forwrefs);
1466 forwref = saa_rstruct(forwrefs);
1467 raa_free(offsets);
1468 offsets = raa_init();
1470 location.segment = NO_SEG;
1471 location.offset = 0;
1472 if (passn == 1)
1473 location.known = true;
1474 ofmt->reset();
1475 switch_segment(ofmt->section(NULL, pass2, &globalbits));
1476 preproc->reset(fname, pass1, pass1 == 2 ? depend_list : NULL);
1478 /* Revert all warnings to the default state */
1479 memcpy(warning_state, warning_state_init, sizeof warning_state);
1481 globallineno = 0;
1483 while ((line = preproc->getline())) {
1484 if (++globallineno > nasm_limit[LIMIT_LINES])
1485 nasm_fatal("overall line count exceeds the maximum %"PRId64"\n",
1486 nasm_limit[LIMIT_LINES]);
1489 * Here we parse our directives; this is not handled by the
1490 * main parser.
1492 if (process_directives(line))
1493 goto end_of_line; /* Just do final cleanup */
1495 /* Not a directive, or even something that starts with [ */
1496 parse_line(pass1, line, &output_ins);
1498 if (optimizing.level > 0) {
1499 if (forwref != NULL && globallineno == forwref->lineno) {
1500 output_ins.forw_ref = true;
1501 do {
1502 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1503 forwref = saa_rstruct(forwrefs);
1504 } while (forwref != NULL
1505 && forwref->lineno == globallineno);
1506 } else
1507 output_ins.forw_ref = false;
1509 if (output_ins.forw_ref) {
1510 if (passn == 1) {
1511 for (i = 0; i < output_ins.operands; i++) {
1512 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1513 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1514 fwinf->lineno = globallineno;
1515 fwinf->operand = i;
1522 /* forw_ref */
1523 if (output_ins.opcode == I_EQU) {
1524 if (!output_ins.label) {
1525 nasm_error(ERR_NONFATAL, "EQU not preceded by label");
1526 } else if (output_ins.operands == 1 &&
1527 (output_ins.oprs[0].type & IMMEDIATE) &&
1528 output_ins.oprs[0].wrt == NO_SEG) {
1529 define_label(output_ins.label,
1530 output_ins.oprs[0].segment,
1531 output_ins.oprs[0].offset, false);
1532 } else if (output_ins.operands == 2
1533 && (output_ins.oprs[0].type & IMMEDIATE)
1534 && (output_ins.oprs[0].type & COLON)
1535 && output_ins.oprs[0].segment == NO_SEG
1536 && output_ins.oprs[0].wrt == NO_SEG
1537 && (output_ins.oprs[1].type & IMMEDIATE)
1538 && output_ins.oprs[1].segment == NO_SEG
1539 && output_ins.oprs[1].wrt == NO_SEG) {
1540 define_label(output_ins.label,
1541 output_ins.oprs[0].offset | SEG_ABS,
1542 output_ins.oprs[1].offset, false);
1543 } else {
1544 nasm_error(ERR_NONFATAL, "bad syntax for EQU");
1546 } else { /* instruction isn't an EQU */
1547 int32_t n;
1549 nasm_assert(output_ins.times >= 0);
1551 for (n = 1; n <= output_ins.times; n++) {
1552 if (pass1 == 1) {
1553 int64_t l = insn_size(location.segment,
1554 location.offset,
1555 globalbits, &output_ins);
1557 /* if (using_debug_info) && output_ins.opcode != -1) */
1558 if (using_debug_info)
1559 { /* fbk 03/25/01 */
1560 /* this is done here so we can do debug type info */
1561 int32_t typeinfo =
1562 TYS_ELEMENTS(output_ins.operands);
1563 switch (output_ins.opcode) {
1564 case I_RESB:
1565 typeinfo =
1566 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1567 break;
1568 case I_RESW:
1569 typeinfo =
1570 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1571 break;
1572 case I_RESD:
1573 typeinfo =
1574 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1575 break;
1576 case I_RESQ:
1577 typeinfo =
1578 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1579 break;
1580 case I_REST:
1581 typeinfo =
1582 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1583 break;
1584 case I_RESO:
1585 typeinfo =
1586 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1587 break;
1588 case I_RESY:
1589 typeinfo =
1590 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1591 break;
1592 case I_RESZ:
1593 typeinfo =
1594 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;
1595 break;
1596 case I_DB:
1597 typeinfo |= TY_BYTE;
1598 break;
1599 case I_DW:
1600 typeinfo |= TY_WORD;
1601 break;
1602 case I_DD:
1603 if (output_ins.eops_float)
1604 typeinfo |= TY_FLOAT;
1605 else
1606 typeinfo |= TY_DWORD;
1607 break;
1608 case I_DQ:
1609 typeinfo |= TY_QWORD;
1610 break;
1611 case I_DT:
1612 typeinfo |= TY_TBYTE;
1613 break;
1614 case I_DO:
1615 typeinfo |= TY_OWORD;
1616 break;
1617 case I_DY:
1618 typeinfo |= TY_YWORD;
1619 break;
1620 case I_DZ:
1621 typeinfo |= TY_ZWORD;
1622 break;
1623 default:
1624 typeinfo = TY_LABEL;
1625 break;
1628 dfmt->debug_typevalue(typeinfo);
1632 * For INCBIN, let the code in assemble
1633 * handle TIMES, so we don't have to read the
1634 * input file over and over.
1636 if (l != -1) {
1637 increment_offset(l);
1640 * else l == -1 => invalid instruction, which will be
1641 * flagged as an error on pass 2
1643 } else {
1644 if (n == 2)
1645 lfmt->uplevel(LIST_TIMES);
1646 increment_offset(assemble(location.segment,
1647 location.offset,
1648 globalbits, &output_ins));
1650 } /* not an EQU */
1652 if (output_ins.times > 1)
1653 lfmt->downlevel(LIST_TIMES);
1655 cleanup_insn(&output_ins);
1657 end_of_line:
1658 nasm_free(line);
1659 } /* end while (line = preproc->getline... */
1661 if (global_offset_changed && !terminate_after_phase) {
1662 switch (pass0) {
1663 case 1:
1664 nasm_error(ERR_WARNING|ERR_WARN_PHASE,
1665 "phase error during stabilization pass, hoping for the best");
1666 break;
1668 case 2:
1669 nasm_error(ERR_NONFATAL,
1670 "phase error during code generation pass");
1671 break;
1673 default:
1674 /* This is normal, we'll keep going... */
1675 break;
1679 if (pass1 == 1)
1680 preproc->cleanup(1);
1683 * Always run at least two optimization passes (pass0 == 0);
1684 * things like subsections will fail miserably without that.
1685 * Once we commit to a stabilization pass (pass0 == 1), we can't
1686 * go back, and if something goes bad, we can only hope
1687 * that we don't end up with a phase error at the end.
1689 if ((passn > 1 && !global_offset_changed) || pass0 > 0) {
1690 pass0++;
1691 } else if (global_offset_changed &&
1692 global_offset_changed < prev_offset_changed) {
1693 prev_offset_changed = global_offset_changed;
1694 stall_count = 0;
1695 } else {
1696 stall_count++;
1699 if (terminate_after_phase)
1700 break;
1702 if ((stall_count > nasm_limit[LIMIT_STALLED]) ||
1703 (passn >= nasm_limit[LIMIT_PASSES])) {
1704 /* We get here if the labels don't converge
1705 * Example: FOO equ FOO + 1
1707 nasm_error(ERR_NONFATAL,
1708 "Can't find valid values for all labels "
1709 "after %"PRId64" passes, giving up.", passn);
1710 nasm_error(ERR_NONFATAL,
1711 "Possible causes: recursive EQUs, macro abuse.");
1712 break;
1716 preproc->cleanup(0);
1717 lfmt->cleanup();
1718 if (!terminate_after_phase && opt_verbose_info) {
1719 /* -On and -Ov switches */
1720 fprintf(stdout, "info: assembly required 1+%"PRId64"+1 passes\n",
1721 passn-3);
1726 * gnu style error reporting
1727 * This function prints an error message to error_file in the
1728 * style used by GNU. An example would be:
1729 * file.asm:50: error: blah blah blah
1730 * where file.asm is the name of the file, 50 is the line number on
1731 * which the error occurs (or is detected) and "error:" is one of
1732 * the possible optional diagnostics -- it can be "error" or "warning"
1733 * or something else. Finally the line terminates with the actual
1734 * error message.
1736 * @param severity the severity of the warning or error
1737 * @param fmt the printf style format string
1739 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1741 const char *currentfile = NULL;
1742 int32_t lineno = 0;
1744 if (is_suppressed_warning(severity))
1745 return;
1747 if (!(severity & ERR_NOFILE)) {
1748 src_get(&lineno, &currentfile);
1749 if (!currentfile || (severity & ERR_TOPFILE)) {
1750 currentfile = inname && inname[0] ?
1751 inname : outname && outname[0] ?
1752 outname : NULL;
1753 lineno = 0;
1757 if (!skip_this_pass(severity)) {
1758 if (!lineno)
1759 fprintf(error_file, "%s:", currentfile ? currentfile : "nasm");
1760 else
1761 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1764 nasm_verror_common(severity, fmt, ap);
1768 * MS style error reporting
1769 * This function prints an error message to error_file in the
1770 * style used by Visual C and some other Microsoft tools. An example
1771 * would be:
1772 * file.asm(50) : error: blah blah blah
1773 * where file.asm is the name of the file, 50 is the line number on
1774 * which the error occurs (or is detected) and "error:" is one of
1775 * the possible optional diagnostics -- it can be "error" or "warning"
1776 * or something else. Finally the line terminates with the actual
1777 * error message.
1779 * @param severity the severity of the warning or error
1780 * @param fmt the printf style format string
1782 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1784 const char *currentfile = NULL;
1785 int32_t lineno = 0;
1787 if (is_suppressed_warning(severity))
1788 return;
1790 if (!(severity & ERR_NOFILE))
1791 src_get(&lineno, &currentfile);
1793 if (!skip_this_pass(severity)) {
1794 if (currentfile) {
1795 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1796 } else {
1797 fputs("nasm: ", error_file);
1801 nasm_verror_common(severity, fmt, ap);
1805 * check to see if this is a suppressable warning
1807 static inline bool is_valid_warning(int severity)
1809 /* Not a warning at all */
1810 if ((severity & ERR_MASK) != ERR_WARNING)
1811 return false;
1813 return WARN_IDX(severity) < ERR_WARN_ALL;
1817 * check for suppressed warning
1818 * checks for suppressed warning or pass one only warning and we're
1819 * not in pass 1
1821 * @param severity the severity of the warning or error
1822 * @return true if we should abort error/warning printing
1824 static bool is_suppressed_warning(int severity)
1826 /* Might be a warning but suppresed explicitly */
1827 if (is_valid_warning(severity) && !(severity & ERR_USAGE))
1828 return !(warning_state[WARN_IDX(severity)] & WARN_ST_ENABLED);
1829 else
1830 return false;
1833 static bool warning_is_error(int severity)
1835 if (is_valid_warning(severity))
1836 return !!(warning_state[WARN_IDX(severity)] & WARN_ST_ERROR);
1837 else
1838 return false;
1841 static bool skip_this_pass(int severity)
1844 * See if it's a pass-specific error or warning which should be skipped.
1845 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1846 * they cannot be resumed from.
1848 if ((severity & ERR_MASK) > ERR_NONFATAL)
1849 return false;
1852 * passn is 1 on the very first pass only.
1853 * pass0 is 2 on the code-generation (final) pass only.
1854 * These are the passes we care about in this case.
1856 return (((severity & ERR_PASS1) && passn != 1) ||
1857 ((severity & ERR_PASS2) && pass0 != 2));
1861 * common error reporting
1862 * This is the common back end of the error reporting schemes currently
1863 * implemented. It prints the nature of the warning and then the
1864 * specific error message to error_file and may or may not return. It
1865 * doesn't return if the error severity is a "panic" or "debug" type.
1867 * @param severity the severity of the warning or error
1868 * @param fmt the printf style format string
1870 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1872 char msg[1024];
1873 const char *pfx;
1875 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1876 case ERR_WARNING:
1877 pfx = "warning: ";
1878 break;
1879 case ERR_NONFATAL:
1880 pfx = "error: ";
1881 break;
1882 case ERR_FATAL:
1883 pfx = "fatal: ";
1884 break;
1885 case ERR_PANIC:
1886 pfx = "panic: ";
1887 break;
1888 case ERR_DEBUG:
1889 pfx = "debug: ";
1890 break;
1891 default:
1892 pfx = "";
1893 break;
1896 vsnprintf(msg, sizeof msg - 64, fmt, args);
1897 if (is_valid_warning(severity) && WARN_IDX(severity) != ERR_WARN_OTHER) {
1898 char *p = strchr(msg, '\0');
1899 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
1902 if (!skip_this_pass(severity))
1903 fprintf(error_file, "%s%s\n", pfx, msg);
1905 /* Are we recursing from error_list_macros? */
1906 if (severity & ERR_PP_LISTMACRO)
1907 return;
1910 * Don't suppress this with skip_this_pass(), or we don't get
1911 * pass1 or preprocessor warnings in the list file
1913 lfmt->error(severity, pfx, msg);
1915 if (skip_this_pass(severity))
1916 return;
1918 if (severity & ERR_USAGE)
1919 want_usage = true;
1921 preproc->error_list_macros(severity);
1923 switch (severity & ERR_MASK) {
1924 case ERR_DEBUG:
1925 /* no further action, by definition */
1926 break;
1927 case ERR_WARNING:
1928 /* Treat warnings as errors */
1929 if (warning_is_error(severity))
1930 terminate_after_phase = true;
1931 break;
1932 case ERR_NONFATAL:
1933 terminate_after_phase = true;
1934 break;
1935 case ERR_FATAL:
1936 if (ofile) {
1937 fclose(ofile);
1938 if (!keep_all)
1939 remove(outname);
1940 ofile = NULL;
1942 if (want_usage)
1943 usage();
1944 exit(1); /* instantly die */
1945 break; /* placate silly compilers */
1946 case ERR_PANIC:
1947 fflush(NULL);
1949 if (abort_on_panic)
1950 abort(); /* halt, catch fire, dump core/stop debugger */
1952 if (ofile) {
1953 fclose(ofile);
1954 if (!keep_all)
1955 remove(outname);
1956 ofile = NULL;
1958 exit(3);
1959 break;
1963 static void usage(void)
1965 fputs("type `nasm -h' for help\n", error_file);
1968 static void help(const char xopt)
1970 int i;
1972 printf
1973 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1974 "[-l listfile]\n"
1975 " [options...] [--] filename\n"
1976 " or nasm -v (or --v) for version info\n\n"
1977 "\n"
1978 "Response files should contain command line parameters,\n"
1979 "one per line.\n"
1980 "\n"
1981 " -t assemble in SciTech TASM compatible mode\n");
1982 printf
1983 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1984 " -a don't preprocess (assemble only)\n"
1985 " -M generate Makefile dependencies on stdout\n"
1986 " -MG d:o, missing files assumed generated\n"
1987 " -MF file set Makefile dependency file\n"
1988 " -MD file assemble and generate dependencies\n"
1989 " -MT file dependency target name\n"
1990 " -MQ file dependency target name (quoted)\n"
1991 " -MP emit phony target\n\n"
1992 " -Zfile redirect error messages to file\n"
1993 " -s redirect error messages to stdout\n\n"
1994 " -g generate debugging information\n\n"
1995 " -F format select a debugging format\n\n"
1996 " -gformat same as -g -F format\n\n"
1997 " -o outfile write output to an outfile\n\n"
1998 " -f format select an output format\n\n"
1999 " -l listfile write listing to a listfile\n\n"
2000 " -Ipath add a pathname to the include file path\n");
2001 printf
2002 (" -Olevel optimize opcodes, immediates and branch offsets\n"
2003 " -O0 no optimization\n"
2004 " -O1 minimal optimization\n"
2005 " -Ox multipass optimization (default)\n"
2006 " -Pfile pre-include a file (also --include)\n"
2007 " -Dmacro[=str] pre-define a macro\n"
2008 " -Umacro undefine a macro\n"
2009 " -Xformat specifiy error reporting format (gnu or vc)\n"
2010 " -w+foo enable warning foo (equiv. -Wfoo)\n"
2011 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
2012 " -w[+-]error[=foo]\n"
2013 " promote [specific] warnings to errors\n"
2014 " -h show invocation summary and exit (also --help)\n\n"
2015 " --pragma str pre-executes a specific %%pragma\n"
2016 " --before str add line (usually a preprocessor statement) before the input\n"
2017 " --prefix str prepend the given string to all the given string\n"
2018 " to all extern, common and global symbols (also --gprefix)\n"
2019 " --postfix str append the given string to all the given string\n"
2020 " to all extern, common and global symbols (also --gpostfix)\n"
2021 " --lprefix str prepend the given string to all other symbols\n"
2022 " --lpostfix str append the given string to all other symbols\n"
2023 " --keep-all output files will not be removed even if an error happens\n"
2024 " --limit-X val set execution limit X\n");
2026 for (i = 0; i <= LIMIT_MAX; i++) {
2027 printf(" %-15s %s (default ",
2028 limit_info[i].name, limit_info[i].help);
2029 if (nasm_limit[i] < LIMIT_MAX_VAL) {
2030 printf("%"PRId64")\n", nasm_limit[i]);
2031 } else {
2032 printf("unlimited)\n");
2036 printf("\nWarnings for the -W/-w options:\n");
2038 for (i = 0; i <= ERR_WARN_ALL; i++)
2039 printf(" %-23s %s%s\n",
2040 warnings[i].name, warnings[i].help,
2041 i == ERR_WARN_ALL ? "\n" :
2042 warnings[i].enabled ? " (default on)" :
2043 " (default off)");
2045 if (xopt == 'f') {
2046 printf("valid output formats for -f are"
2047 " (`*' denotes default):\n");
2048 ofmt_list(ofmt, stdout);
2049 } else {
2050 printf("For a list of valid output formats, use -hf.\n");
2051 printf("For a list of debug formats, use -f <format> -y.\n");