preproc_init: Just clean include path
[nasm.git] / asm / nasm.c
blob9e36314018dacffecf3e9107cff403ba635f64eb
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2018 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * The Netwide Assembler main program module
38 #include "compiler.h"
40 #include <stdio.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <limits.h>
47 #include "nasm.h"
48 #include "nasmlib.h"
49 #include "error.h"
50 #include "saa.h"
51 #include "raa.h"
52 #include "float.h"
53 #include "stdscan.h"
54 #include "insns.h"
55 #include "preproc.h"
56 #include "parser.h"
57 #include "eval.h"
58 #include "assemble.h"
59 #include "labels.h"
60 #include "outform.h"
61 #include "listing.h"
62 #include "iflag.h"
63 #include "ver.h"
66 * This is the maximum number of optimization passes to do. If we ever
67 * find a case where the optimizer doesn't naturally converge, we might
68 * have to drop this value so the assembler doesn't appear to just hang.
70 #define MAX_OPTIMIZE (INT_MAX >> 1)
72 struct forwrefinfo { /* info held on forward refs. */
73 int lineno;
74 int operand;
77 static void parse_cmdline(int, char **, int);
78 static void assemble_file(const char *, StrList *);
79 static bool is_suppressed_warning(int severity);
80 static bool skip_this_pass(int severity);
81 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
82 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
83 static void nasm_verror_common(int severity, const char *fmt, va_list args);
84 static void usage(void);
85 static void help(char xopt);
87 static bool using_debug_info, opt_verbose_info;
88 static const char *debug_format;
90 #ifndef ABORT_ON_PANIC
91 # define ABORT_ON_PANIC 0
92 #endif
93 static bool abort_on_panic = ABORT_ON_PANIC;
94 static bool keep_all;
96 bool tasm_compatible_mode = false;
97 int pass0;
98 int64_t passn;
99 static int pass1, pass2; /* XXX: Get rid of these, they are redundant */
100 int globalrel = 0;
101 int globalbnd = 0;
103 struct compile_time official_compile_time;
105 const char *inname;
106 const char *outname;
107 static const char *listname;
108 static const char *errname;
110 static int64_t globallineno; /* for forward-reference tracking */
112 /* static int pass = 0; */
113 const struct ofmt *ofmt = &OF_DEFAULT;
114 const struct ofmt_alias *ofmt_alias = NULL;
115 const struct dfmt *dfmt;
117 static FILE *error_file; /* Where to write error messages */
119 FILE *ofile = NULL;
120 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 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 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(StrList **ipath)
333 struct strlist_entry *l;
335 preproc->init();
336 define_macros();
338 list_for_each(l, (*ipath)->head)
339 preproc->include_path(l->str);
341 strlist_free(*ipath);
342 *ipath = strlist_allocate();
345 static void emit_dependencies(StrList *list)
347 FILE *deps;
348 int linepos, len;
349 bool wmake = (quote_for_make == quote_for_wmake);
350 const char *wrapstr, *nulltarget;
351 struct strlist_entry *l;
353 if (!list)
354 return;
356 wrapstr = wmake ? " &\n " : " \\\n ";
357 nulltarget = wmake ? "\t%null\n" : "";
359 if (depend_file && strcmp(depend_file, "-")) {
360 deps = nasm_open_write(depend_file, NF_TEXT);
361 if (!deps) {
362 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
363 "unable to write dependency file `%s'", depend_file);
364 return;
366 } else {
367 deps = stdout;
370 linepos = fprintf(deps, "%s :", depend_target);
371 list_for_each(l, list->head) {
372 char *file = quote_for_make(l->str);
373 len = strlen(file);
374 if (linepos + len > 62 && linepos > 1) {
375 fputs(wrapstr, deps);
376 linepos = 1;
378 fprintf(deps, " %s", file);
379 linepos += len+1;
380 nasm_free(file);
382 fprintf(deps, "\n\n");
384 list_for_each(l, list->head) {
385 if (depend_emit_phony) {
386 char *file = quote_for_make(l->str);
387 fprintf(deps, "%s :\n%s\n", file, nulltarget);
388 nasm_free(file);
392 strlist_free(list);
394 if (deps != stdout)
395 fclose(deps);
398 /* Convert a struct tm to a POSIX-style time constant */
399 static int64_t make_posix_time(const struct tm *tm)
401 int64_t t;
402 int64_t y = tm->tm_year;
404 /* See IEEE 1003.1:2004, section 4.14 */
406 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
407 t += tm->tm_yday;
408 t *= 24;
409 t += tm->tm_hour;
410 t *= 60;
411 t += tm->tm_min;
412 t *= 60;
413 t += tm->tm_sec;
415 return t;
418 static void timestamp(void)
420 struct compile_time * const oct = &official_compile_time;
421 const struct tm *tp, *best_gm;
423 time(&oct->t);
425 best_gm = NULL;
427 tp = localtime(&oct->t);
428 if (tp) {
429 oct->local = *tp;
430 best_gm = &oct->local;
431 oct->have_local = true;
434 tp = gmtime(&oct->t);
435 if (tp) {
436 oct->gm = *tp;
437 best_gm = &oct->gm;
438 oct->have_gm = true;
439 if (!oct->have_local)
440 oct->local = oct->gm;
441 } else {
442 oct->gm = oct->local;
445 if (best_gm) {
446 oct->posix = make_posix_time(best_gm);
447 oct->have_posix = true;
451 int main(int argc, char **argv)
453 timestamp();
455 iflag_set_default_cpu(&cpu);
456 iflag_set_default_cpu(&cmd_cpu);
458 include_path = strlist_allocate();
460 pass0 = 0;
461 want_usage = terminate_after_phase = false;
462 nasm_set_verror(nasm_verror_gnu);
464 error_file = stderr;
466 tolower_init();
467 src_init();
470 * We must call init_labels() before the command line parsing,
471 * because we may be setting prefixes/suffixes from the command
472 * line.
474 init_labels();
476 offsets = raa_init();
477 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
479 preproc = &nasmpp;
480 operating_mode = OP_NORMAL;
482 parse_cmdline(argc, argv, 1);
483 if (terminate_after_phase) {
484 if (want_usage)
485 usage();
486 return 1;
489 /* At this point we have ofmt and the name of the desired debug format */
490 if (!using_debug_info) {
491 /* No debug info, redirect to the null backend (empty stubs) */
492 dfmt = &null_debug_form;
493 } else if (!debug_format) {
494 /* Default debug format for this backend */
495 dfmt = ofmt->default_dfmt;
496 } else {
497 dfmt = dfmt_find(ofmt, debug_format);
498 if (!dfmt) {
499 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
500 "unrecognized debug format `%s' for"
501 " output format `%s'",
502 debug_format, ofmt->shortname);
506 preproc_init(&include_path);
508 parse_cmdline(argc, argv, 2);
509 if (terminate_after_phase) {
510 if (want_usage)
511 usage();
512 return 1;
515 /* Save away the default state of warnings */
516 memcpy(warning_state_init, warning_state, sizeof warning_state);
519 * If no output file name provided and this
520 * is a preprocess mode, we're perfectly
521 * fine to output into stdout.
523 if (!outname) {
524 if (!(operating_mode & OP_PREPROCESS))
525 outname = filename_set_extension(inname, ofmt->extension);
528 if (depend_file || (operating_mode & OP_DEPEND))
529 depend_list = strlist_allocate();
531 if (!depend_target)
532 depend_target = quote_for_make(outname);
534 if (operating_mode & OP_DEPEND) {
535 char *line;
537 if (depend_missing_ok)
538 preproc->include_path(NULL); /* "assume generated" */
540 preproc->reset(inname, 0, depend_list);
541 ofile = NULL;
542 while ((line = preproc->getline()))
543 nasm_free(line);
544 preproc->cleanup(0);
545 } else if (operating_mode & OP_PREPROCESS) {
546 char *line;
547 const char *file_name = NULL;
548 int32_t prior_linnum = 0;
549 int lineinc = 0;
551 if (outname) {
552 ofile = nasm_open_write(outname, NF_TEXT);
553 if (!ofile)
554 nasm_fatal_fl(ERR_NOFILE,
555 "unable to open output file `%s'",
556 outname);
557 } else
558 ofile = NULL;
560 location.known = false;
562 /* pass = 1; */
563 preproc->reset(inname, 3, depend_list);
565 /* Revert all warnings to the default state */
566 memcpy(warning_state, warning_state_init, sizeof warning_state);
568 while ((line = preproc->getline())) {
570 * We generate %line directives if needed for later programs
572 int32_t linnum = prior_linnum += lineinc;
573 int altline = src_get(&linnum, &file_name);
574 if (altline) {
575 if (altline == 1 && lineinc == 1)
576 nasm_fputs("", ofile);
577 else {
578 lineinc = (altline != -1 || lineinc != 1);
579 fprintf(ofile ? ofile : stdout,
580 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
581 file_name);
583 prior_linnum = linnum;
585 nasm_fputs(line, ofile);
586 nasm_free(line);
588 preproc->cleanup(0);
589 if (ofile)
590 fclose(ofile);
591 if (ofile && terminate_after_phase && !keep_all)
592 remove(outname);
593 ofile = NULL;
596 if (operating_mode & OP_NORMAL) {
597 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
598 if (!ofile)
599 nasm_fatal_fl(ERR_NOFILE,
600 "unable to open output file `%s'", outname);
602 ofmt->init();
603 dfmt->init();
605 assemble_file(inname, depend_list);
607 if (!terminate_after_phase) {
608 ofmt->cleanup();
609 cleanup_labels();
610 fflush(ofile);
611 if (ferror(ofile)) {
612 nasm_error(ERR_NONFATAL|ERR_NOFILE,
613 "write error on output file `%s'", outname);
614 terminate_after_phase = true;
618 if (ofile) {
619 fclose(ofile);
620 if (terminate_after_phase && !keep_all)
621 remove(outname);
622 ofile = NULL;
626 if (depend_list && !terminate_after_phase)
627 emit_dependencies(depend_list);
629 if (want_usage)
630 usage();
632 raa_free(offsets);
633 saa_free(forwrefs);
634 eval_cleanup();
635 stdscan_cleanup();
636 src_free();
637 strlist_free(include_path);
639 return terminate_after_phase;
643 * Get a parameter for a command line option.
644 * First arg must be in the form of e.g. -f...
646 static char *get_param(char *p, char *q, bool *advance)
648 *advance = false;
649 if (p[2]) /* the parameter's in the option */
650 return nasm_skip_spaces(p + 2);
651 if (q && q[0]) {
652 *advance = true;
653 return q;
655 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
656 "option `-%c' requires an argument", p[1]);
657 return NULL;
661 * Copy a filename
663 static void copy_filename(const char **dst, const char *src, const char *what)
665 if (*dst)
666 nasm_fatal("more than one %s file specified: %s\n", what, src);
668 *dst = nasm_strdup(src);
672 * Convert a string to a POSIX make-safe form
674 static char *quote_for_pmake(const char *str)
676 const char *p;
677 char *os, *q;
679 size_t n = 1; /* Terminating zero */
680 size_t nbs = 0;
682 if (!str)
683 return NULL;
685 for (p = str; *p; p++) {
686 switch (*p) {
687 case ' ':
688 case '\t':
689 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
690 n += nbs + 2;
691 nbs = 0;
692 break;
693 case '$':
694 case '#':
695 nbs = 0;
696 n += 2;
697 break;
698 case '\\':
699 nbs++;
700 n++;
701 break;
702 default:
703 nbs = 0;
704 n++;
705 break;
709 /* Convert N backslashes at the end of filename to 2N backslashes */
710 if (nbs)
711 n += nbs;
713 os = q = nasm_malloc(n);
715 nbs = 0;
716 for (p = str; *p; p++) {
717 switch (*p) {
718 case ' ':
719 case '\t':
720 while (nbs--)
721 *q++ = '\\';
722 *q++ = '\\';
723 *q++ = *p;
724 break;
725 case '$':
726 *q++ = *p;
727 *q++ = *p;
728 nbs = 0;
729 break;
730 case '#':
731 *q++ = '\\';
732 *q++ = *p;
733 nbs = 0;
734 break;
735 case '\\':
736 *q++ = *p;
737 nbs++;
738 break;
739 default:
740 *q++ = *p;
741 nbs = 0;
742 break;
745 while (nbs--)
746 *q++ = '\\';
748 *q = '\0';
750 return os;
754 * Convert a string to a Watcom make-safe form
756 static char *quote_for_wmake(const char *str)
758 const char *p;
759 char *os, *q;
760 bool quote = false;
762 size_t n = 1; /* Terminating zero */
764 if (!str)
765 return NULL;
767 for (p = str; *p; p++) {
768 switch (*p) {
769 case ' ':
770 case '\t':
771 case '&':
772 quote = true;
773 n++;
774 break;
775 case '\"':
776 quote = true;
777 n += 2;
778 break;
779 case '$':
780 case '#':
781 n += 2;
782 break;
783 default:
784 n++;
785 break;
789 if (quote)
790 n += 2;
792 os = q = nasm_malloc(n);
794 if (quote)
795 *q++ = '\"';
797 for (p = str; *p; p++) {
798 switch (*p) {
799 case '$':
800 case '#':
801 *q++ = '$';
802 *q++ = *p;
803 break;
804 case '\"':
805 *q++ = *p;
806 *q++ = *p;
807 break;
808 default:
809 *q++ = *p;
810 break;
814 if (quote)
815 *q++ = '\"';
817 *q = '\0';
819 return os;
822 enum text_options {
823 OPT_BOGUS,
824 OPT_VERSION,
825 OPT_HELP,
826 OPT_ABORT_ON_PANIC,
827 OPT_MANGLE,
828 OPT_INCLUDE,
829 OPT_PRAGMA,
830 OPT_BEFORE,
831 OPT_LIMIT,
832 OPT_KEEP_ALL
834 struct textargs {
835 const char *label;
836 enum text_options opt;
837 bool need_arg;
838 int pvt;
840 static const struct textargs textopts[] = {
841 {"v", OPT_VERSION, false, 0},
842 {"version", OPT_VERSION, false, 0},
843 {"help", OPT_HELP, false, 0},
844 {"abort-on-panic", OPT_ABORT_ON_PANIC, false, 0},
845 {"prefix", OPT_MANGLE, true, LM_GPREFIX},
846 {"postfix", OPT_MANGLE, true, LM_GSUFFIX},
847 {"gprefix", OPT_MANGLE, true, LM_GPREFIX},
848 {"gpostfix", OPT_MANGLE, true, LM_GSUFFIX},
849 {"lprefix", OPT_MANGLE, true, LM_LPREFIX},
850 {"lpostfix", OPT_MANGLE, true, LM_LSUFFIX},
851 {"include", OPT_INCLUDE, true, 0},
852 {"pragma", OPT_PRAGMA, true, 0},
853 {"before", OPT_BEFORE, true, 0},
854 {"limit-", OPT_LIMIT, true, 0},
855 {"keep-all", OPT_KEEP_ALL, false, 0},
856 {NULL, OPT_BOGUS, false, 0}
859 static void show_version(void)
861 printf("NASM version %s compiled on %s%s\n",
862 nasm_version, nasm_date, nasm_compile_options);
863 exit(0);
866 static bool stopoptions = false;
867 static bool process_arg(char *p, char *q, int pass)
869 char *param;
870 bool advance = false;
872 if (!p || !p[0])
873 return false;
875 if (p[0] == '-' && !stopoptions) {
876 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
877 /* These parameters take values */
878 if (!(param = get_param(p, q, &advance)))
879 return advance;
882 switch (p[1]) {
883 case 's':
884 if (pass == 1)
885 error_file = stdout;
886 break;
888 case 'o': /* output file */
889 if (pass == 2)
890 copy_filename(&outname, param, "output");
891 break;
893 case 'f': /* output format */
894 if (pass == 1) {
895 ofmt = ofmt_find(param, &ofmt_alias);
896 if (!ofmt) {
897 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
898 "unrecognised output format `%s' - "
899 "use -hf for a list", param);
902 break;
904 case 'O': /* Optimization level */
905 if (pass == 1) {
906 int opt;
908 if (!*param) {
909 /* Naked -O == -Ox */
910 optimizing.level = MAX_OPTIMIZE;
911 } else {
912 while (*param) {
913 switch (*param) {
914 case '0': case '1': case '2': case '3': case '4':
915 case '5': case '6': case '7': case '8': case '9':
916 opt = strtoul(param, &param, 10);
918 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
919 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
920 if (opt < 2)
921 optimizing.level = opt - 1;
922 else
923 optimizing.level = opt;
924 break;
926 case 'v':
927 case '+':
928 param++;
929 opt_verbose_info = true;
930 break;
932 case 'x':
933 param++;
934 optimizing.level = MAX_OPTIMIZE;
935 break;
937 default:
938 nasm_fatal("unknown optimization option -O%c\n",
939 *param);
940 break;
943 if (optimizing.level > MAX_OPTIMIZE)
944 optimizing.level = MAX_OPTIMIZE;
947 break;
949 case 'p': /* pre-include */
950 case 'P':
951 if (pass == 2)
952 preproc->pre_include(param);
953 break;
955 case 'd': /* pre-define */
956 case 'D':
957 if (pass == 2)
958 preproc->pre_define(param);
959 break;
961 case 'u': /* un-define */
962 case 'U':
963 if (pass == 2)
964 preproc->pre_undefine(param);
965 break;
967 case 'i': /* include search path */
968 case 'I':
969 if (pass == 1)
970 strlist_add_string(include_path, param);
971 break;
973 case 'l': /* listing file */
974 if (pass == 2)
975 copy_filename(&listname, param, "listing");
976 break;
978 case 'Z': /* error messages file */
979 if (pass == 1)
980 copy_filename(&errname, param, "error");
981 break;
983 case 'F': /* specify debug format */
984 if (pass == 1) {
985 using_debug_info = true;
986 debug_format = param;
988 break;
990 case 'X': /* specify error reporting format */
991 if (pass == 1) {
992 if (nasm_stricmp("vc", param) == 0)
993 nasm_set_verror(nasm_verror_vc);
994 else if (nasm_stricmp("gnu", param) == 0)
995 nasm_set_verror(nasm_verror_gnu);
996 else
997 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
998 "unrecognized error reporting format `%s'",
999 param);
1001 break;
1003 case 'g':
1004 if (pass == 1) {
1005 using_debug_info = true;
1006 if (p[2])
1007 debug_format = nasm_skip_spaces(p + 2);
1009 break;
1011 case 'h':
1012 help(p[2]);
1013 exit(0); /* never need usage message here */
1014 break;
1016 case 'y':
1017 printf("\nvalid debug formats for '%s' output format are"
1018 " ('*' denotes default):\n", ofmt->shortname);
1019 dfmt_list(ofmt, stdout);
1020 exit(0);
1021 break;
1023 case 't':
1024 if (pass == 2)
1025 tasm_compatible_mode = true;
1026 break;
1028 case 'v':
1029 show_version();
1030 break;
1032 case 'e': /* preprocess only */
1033 case 'E':
1034 if (pass == 1)
1035 operating_mode = OP_PREPROCESS;
1036 break;
1038 case 'a': /* assemble only - don't preprocess */
1039 if (pass == 1)
1040 preproc = &preproc_nop;
1041 break;
1043 case 'w':
1044 case 'W':
1045 if (pass == 2) {
1046 if (!set_warning_status(param)) {
1047 nasm_error(ERR_WARNING|ERR_NOFILE|ERR_WARN_UNK_WARNING,
1048 "unknown warning option: %s", param);
1051 break;
1053 case 'M':
1054 if (pass == 1) {
1055 switch (p[2]) {
1056 case 'W':
1057 quote_for_make = quote_for_wmake;
1058 break;
1059 case 'D':
1060 case 'F':
1061 case 'T':
1062 case 'Q':
1063 advance = true;
1064 break;
1065 default:
1066 break;
1068 } else {
1069 switch (p[2]) {
1070 case 0:
1071 operating_mode = OP_DEPEND;
1072 break;
1073 case 'G':
1074 operating_mode = OP_DEPEND;
1075 depend_missing_ok = true;
1076 break;
1077 case 'P':
1078 depend_emit_phony = true;
1079 break;
1080 case 'D':
1081 operating_mode = OP_NORMAL;
1082 depend_file = q;
1083 advance = true;
1084 break;
1085 case 'F':
1086 depend_file = q;
1087 advance = true;
1088 break;
1089 case 'T':
1090 depend_target = q;
1091 advance = true;
1092 break;
1093 case 'Q':
1094 depend_target = quote_for_make(q);
1095 advance = true;
1096 break;
1097 case 'W':
1098 /* handled in pass 1 */
1099 break;
1100 default:
1101 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1102 "unknown dependency option `-M%c'", p[2]);
1103 break;
1106 if (advance && (!q || !q[0])) {
1107 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1108 "option `-M%c' requires a parameter", p[2]);
1109 break;
1111 break;
1113 case '-':
1115 const struct textargs *tx;
1116 size_t olen, plen;
1117 char *eqsave;
1119 p += 2;
1121 if (!*p) { /* -- => stop processing options */
1122 stopoptions = true;
1123 break;
1126 plen = strlen(p);
1127 for (tx = textopts; tx->label; tx++) {
1128 olen = strlen(tx->label);
1130 if (olen > plen)
1131 continue;
1133 if (nasm_memicmp(p, tx->label, olen))
1134 continue;
1136 if (tx->label[olen-1] == '-')
1137 break; /* Incomplete option */
1139 if (!p[olen] || p[olen] == '=')
1140 break; /* Complete option */
1143 if (!tx->label) {
1144 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1145 "unrecognized option `--%s'", p);
1148 eqsave = param = strchr(p+olen, '=');
1149 if (param)
1150 *param++ = '\0';
1152 if (tx->need_arg) {
1153 if (!param) {
1154 param = q;
1155 advance = true;
1158 /* Note: a null string is a valid parameter */
1159 if (!param) {
1160 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1161 "option `--%s' requires an argument",
1163 break;
1165 } else {
1166 if (param) {
1167 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1168 "option `--%s' does not take an argument",
1174 switch (tx->opt) {
1175 case OPT_VERSION:
1176 show_version();
1177 break;
1178 case OPT_ABORT_ON_PANIC:
1179 abort_on_panic = true;
1180 break;
1181 case OPT_MANGLE:
1182 if (pass == 2)
1183 set_label_mangle(tx->pvt, param);
1184 break;
1185 case OPT_INCLUDE:
1186 if (pass == 2)
1187 preproc->pre_include(q);
1188 break;
1189 case OPT_PRAGMA:
1190 if (pass == 2)
1191 preproc->pre_command("pragma", param);
1192 break;
1193 case OPT_BEFORE:
1194 if (pass == 2)
1195 preproc->pre_command(NULL, param);
1196 break;
1197 case OPT_LIMIT:
1198 if (pass == 1)
1199 nasm_set_limit(p+olen, param);
1200 break;
1201 case OPT_KEEP_ALL:
1202 keep_all = true;
1203 break;
1204 case OPT_HELP:
1205 help(0);
1206 exit(0);
1207 default:
1208 panic();
1211 if (eqsave)
1212 *eqsave = '='; /* Restore = argument separator */
1214 break;
1217 default:
1218 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1219 "unrecognised option `-%c'", p[1]);
1220 break;
1222 } else if (pass == 2) {
1223 /* In theory we could allow multiple input files... */
1224 copy_filename(&inname, p, "input");
1227 return advance;
1230 #define ARG_BUF_DELTA 128
1232 static void process_respfile(FILE * rfile, int pass)
1234 char *buffer, *p, *q, *prevarg;
1235 int bufsize, prevargsize;
1237 bufsize = prevargsize = ARG_BUF_DELTA;
1238 buffer = nasm_malloc(ARG_BUF_DELTA);
1239 prevarg = nasm_malloc(ARG_BUF_DELTA);
1240 prevarg[0] = '\0';
1242 while (1) { /* Loop to handle all lines in file */
1243 p = buffer;
1244 while (1) { /* Loop to handle long lines */
1245 q = fgets(p, bufsize - (p - buffer), rfile);
1246 if (!q)
1247 break;
1248 p += strlen(p);
1249 if (p > buffer && p[-1] == '\n')
1250 break;
1251 if (p - buffer > bufsize - 10) {
1252 int offset;
1253 offset = p - buffer;
1254 bufsize += ARG_BUF_DELTA;
1255 buffer = nasm_realloc(buffer, bufsize);
1256 p = buffer + offset;
1260 if (!q && p == buffer) {
1261 if (prevarg[0])
1262 process_arg(prevarg, NULL, pass);
1263 nasm_free(buffer);
1264 nasm_free(prevarg);
1265 return;
1269 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1270 * them are present at the end of the line.
1272 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1274 while (p > buffer && nasm_isspace(p[-1]))
1275 *--p = '\0';
1277 p = nasm_skip_spaces(buffer);
1279 if (process_arg(prevarg, p, pass))
1280 *p = '\0';
1282 if ((int) strlen(p) > prevargsize - 10) {
1283 prevargsize += ARG_BUF_DELTA;
1284 prevarg = nasm_realloc(prevarg, prevargsize);
1286 strncpy(prevarg, p, prevargsize);
1290 /* Function to process args from a string of args, rather than the
1291 * argv array. Used by the environment variable and response file
1292 * processing.
1294 static void process_args(char *args, int pass)
1296 char *p, *q, *arg, *prevarg;
1297 char separator = ' ';
1299 p = args;
1300 if (*p && *p != '-')
1301 separator = *p++;
1302 arg = NULL;
1303 while (*p) {
1304 q = p;
1305 while (*p && *p != separator)
1306 p++;
1307 while (*p == separator)
1308 *p++ = '\0';
1309 prevarg = arg;
1310 arg = q;
1311 if (process_arg(prevarg, arg, pass))
1312 arg = NULL;
1314 if (arg)
1315 process_arg(arg, NULL, pass);
1318 static void process_response_file(const char *file, int pass)
1320 char str[2048];
1321 FILE *f = nasm_open_read(file, NF_TEXT);
1322 if (!f) {
1323 perror(file);
1324 exit(-1);
1326 while (fgets(str, sizeof str, f)) {
1327 process_args(str, pass);
1329 fclose(f);
1332 static void parse_cmdline(int argc, char **argv, int pass)
1334 FILE *rfile;
1335 char *envreal, *envcopy = NULL, *p;
1336 int i;
1338 /* Initialize all the warnings to their default state */
1339 for (i = 0; i < ERR_WARN_ALL; i++) {
1340 warning_state_init[i] = warning_state[i] =
1341 warnings[i].enabled ? WARN_ST_ENABLED : 0;
1345 * First, process the NASMENV environment variable.
1347 envreal = getenv("NASMENV");
1348 if (envreal) {
1349 envcopy = nasm_strdup(envreal);
1350 process_args(envcopy, pass);
1351 nasm_free(envcopy);
1355 * Now process the actual command line.
1357 while (--argc) {
1358 bool advance;
1359 argv++;
1360 if (argv[0][0] == '@') {
1362 * We have a response file, so process this as a set of
1363 * arguments like the environment variable. This allows us
1364 * to have multiple arguments on a single line, which is
1365 * different to the -@resp file processing below for regular
1366 * NASM.
1368 process_response_file(argv[0]+1, pass);
1369 argc--;
1370 argv++;
1372 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1373 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1374 if (p) {
1375 rfile = nasm_open_read(p, NF_TEXT);
1376 if (rfile) {
1377 process_respfile(rfile, pass);
1378 fclose(rfile);
1379 } else
1380 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1381 "unable to open response file `%s'", p);
1383 } else
1384 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1385 argv += advance, argc -= advance;
1389 * Look for basic command line typos. This definitely doesn't
1390 * catch all errors, but it might help cases of fumbled fingers.
1392 if (pass != 2)
1393 return;
1395 if (!inname)
1396 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE, "no input file specified");
1398 else if ((errname && !strcmp(inname, errname)) ||
1399 (outname && !strcmp(inname, outname)) ||
1400 (listname && !strcmp(inname, listname)) ||
1401 (depend_file && !strcmp(inname, depend_file)))
1402 nasm_fatal_fl(ERR_USAGE, "will not overwrite input file");
1404 if (errname) {
1405 error_file = nasm_open_write(errname, NF_TEXT);
1406 if (!error_file) {
1407 error_file = stderr; /* Revert to default! */
1408 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
1409 "cannot open file `%s' for error messages",
1410 errname);
1415 static void assemble_file(const char *fname, StrList *depend_list)
1417 char *line;
1418 insn output_ins;
1419 int i;
1420 uint64_t prev_offset_changed;
1421 int64_t stall_count = 0; /* Make sure we make forward progress... */
1423 switch (cmd_sb) {
1424 case 16:
1425 break;
1426 case 32:
1427 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1428 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1429 break;
1430 case 64:
1431 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1432 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1433 break;
1434 default:
1435 panic();
1436 break;
1439 prev_offset_changed = nasm_limit[LIMIT_PASSES];
1440 for (passn = 1; pass0 <= 2; passn++) {
1441 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1442 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1443 /* pass0 0, 0, 0, ..., 1, 2 */
1445 globalbits = cmd_sb; /* set 'bits' to command line default */
1446 cpu = cmd_cpu;
1447 if (pass0 == 2) {
1448 lfmt->init(listname);
1449 } else if (passn == 1 && listname && !keep_all) {
1450 /* Remove the list file in case we die before the output pass */
1451 remove(listname);
1453 in_absolute = false;
1454 global_offset_changed = 0; /* set by redefine_label */
1455 if (passn > 1) {
1456 saa_rewind(forwrefs);
1457 forwref = saa_rstruct(forwrefs);
1458 raa_free(offsets);
1459 offsets = raa_init();
1461 location.segment = NO_SEG;
1462 location.offset = 0;
1463 if (passn == 1)
1464 location.known = true;
1465 ofmt->reset();
1466 switch_segment(ofmt->section(NULL, pass2, &globalbits));
1467 preproc->reset(fname, pass1, pass1 == 2 ? depend_list : NULL);
1469 /* Revert all warnings to the default state */
1470 memcpy(warning_state, warning_state_init, sizeof warning_state);
1472 globallineno = 0;
1474 while ((line = preproc->getline())) {
1475 if (++globallineno > nasm_limit[LIMIT_LINES])
1476 nasm_fatal("overall line count exceeds the maximum %"PRId64"\n",
1477 nasm_limit[LIMIT_LINES]);
1480 * Here we parse our directives; this is not handled by the
1481 * main parser.
1483 if (process_directives(line))
1484 goto end_of_line; /* Just do final cleanup */
1486 /* Not a directive, or even something that starts with [ */
1487 parse_line(pass1, line, &output_ins);
1489 if (optimizing.level > 0) {
1490 if (forwref != NULL && globallineno == forwref->lineno) {
1491 output_ins.forw_ref = true;
1492 do {
1493 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1494 forwref = saa_rstruct(forwrefs);
1495 } while (forwref != NULL
1496 && forwref->lineno == globallineno);
1497 } else
1498 output_ins.forw_ref = false;
1500 if (output_ins.forw_ref) {
1501 if (passn == 1) {
1502 for (i = 0; i < output_ins.operands; i++) {
1503 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1504 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1505 fwinf->lineno = globallineno;
1506 fwinf->operand = i;
1513 /* forw_ref */
1514 if (output_ins.opcode == I_EQU) {
1515 if (!output_ins.label) {
1516 nasm_error(ERR_NONFATAL, "EQU not preceded by label");
1517 } else if (output_ins.operands == 1 &&
1518 (output_ins.oprs[0].type & IMMEDIATE) &&
1519 output_ins.oprs[0].wrt == NO_SEG) {
1520 define_label(output_ins.label,
1521 output_ins.oprs[0].segment,
1522 output_ins.oprs[0].offset, false);
1523 } else if (output_ins.operands == 2
1524 && (output_ins.oprs[0].type & IMMEDIATE)
1525 && (output_ins.oprs[0].type & COLON)
1526 && output_ins.oprs[0].segment == NO_SEG
1527 && output_ins.oprs[0].wrt == NO_SEG
1528 && (output_ins.oprs[1].type & IMMEDIATE)
1529 && output_ins.oprs[1].segment == NO_SEG
1530 && output_ins.oprs[1].wrt == NO_SEG) {
1531 define_label(output_ins.label,
1532 output_ins.oprs[0].offset | SEG_ABS,
1533 output_ins.oprs[1].offset, false);
1534 } else {
1535 nasm_error(ERR_NONFATAL, "bad syntax for EQU");
1537 } else { /* instruction isn't an EQU */
1538 int32_t n;
1540 nasm_assert(output_ins.times >= 0);
1542 for (n = 1; n <= output_ins.times; n++) {
1543 if (pass1 == 1) {
1544 int64_t l = insn_size(location.segment,
1545 location.offset,
1546 globalbits, &output_ins);
1548 /* if (using_debug_info) && output_ins.opcode != -1) */
1549 if (using_debug_info)
1550 { /* fbk 03/25/01 */
1551 /* this is done here so we can do debug type info */
1552 int32_t typeinfo =
1553 TYS_ELEMENTS(output_ins.operands);
1554 switch (output_ins.opcode) {
1555 case I_RESB:
1556 typeinfo =
1557 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1558 break;
1559 case I_RESW:
1560 typeinfo =
1561 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1562 break;
1563 case I_RESD:
1564 typeinfo =
1565 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1566 break;
1567 case I_RESQ:
1568 typeinfo =
1569 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1570 break;
1571 case I_REST:
1572 typeinfo =
1573 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1574 break;
1575 case I_RESO:
1576 typeinfo =
1577 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1578 break;
1579 case I_RESY:
1580 typeinfo =
1581 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1582 break;
1583 case I_RESZ:
1584 typeinfo =
1585 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;
1586 break;
1587 case I_DB:
1588 typeinfo |= TY_BYTE;
1589 break;
1590 case I_DW:
1591 typeinfo |= TY_WORD;
1592 break;
1593 case I_DD:
1594 if (output_ins.eops_float)
1595 typeinfo |= TY_FLOAT;
1596 else
1597 typeinfo |= TY_DWORD;
1598 break;
1599 case I_DQ:
1600 typeinfo |= TY_QWORD;
1601 break;
1602 case I_DT:
1603 typeinfo |= TY_TBYTE;
1604 break;
1605 case I_DO:
1606 typeinfo |= TY_OWORD;
1607 break;
1608 case I_DY:
1609 typeinfo |= TY_YWORD;
1610 break;
1611 case I_DZ:
1612 typeinfo |= TY_ZWORD;
1613 break;
1614 default:
1615 typeinfo = TY_LABEL;
1616 break;
1619 dfmt->debug_typevalue(typeinfo);
1623 * For INCBIN, let the code in assemble
1624 * handle TIMES, so we don't have to read the
1625 * input file over and over.
1627 if (l != -1) {
1628 increment_offset(l);
1631 * else l == -1 => invalid instruction, which will be
1632 * flagged as an error on pass 2
1634 } else {
1635 if (n == 2)
1636 lfmt->uplevel(LIST_TIMES);
1637 increment_offset(assemble(location.segment,
1638 location.offset,
1639 globalbits, &output_ins));
1641 } /* not an EQU */
1643 if (output_ins.times > 1)
1644 lfmt->downlevel(LIST_TIMES);
1646 cleanup_insn(&output_ins);
1648 end_of_line:
1649 nasm_free(line);
1650 } /* end while (line = preproc->getline... */
1652 if (global_offset_changed && !terminate_after_phase) {
1653 switch (pass0) {
1654 case 1:
1655 nasm_error(ERR_WARNING|ERR_WARN_PHASE,
1656 "phase error during stabilization pass, hoping for the best");
1657 break;
1659 case 2:
1660 nasm_error(ERR_NONFATAL,
1661 "phase error during code generation pass");
1662 break;
1664 default:
1665 /* This is normal, we'll keep going... */
1666 break;
1670 if (pass1 == 1)
1671 preproc->cleanup(1);
1674 * Always run at least two optimization passes (pass0 == 0);
1675 * things like subsections will fail miserably without that.
1676 * Once we commit to a stabilization pass (pass0 == 1), we can't
1677 * go back, and if something goes bad, we can only hope
1678 * that we don't end up with a phase error at the end.
1680 if ((passn > 1 && !global_offset_changed) || pass0 > 0) {
1681 pass0++;
1682 } else if (global_offset_changed &&
1683 global_offset_changed < prev_offset_changed) {
1684 prev_offset_changed = global_offset_changed;
1685 stall_count = 0;
1686 } else {
1687 stall_count++;
1690 if (terminate_after_phase)
1691 break;
1693 if ((stall_count > nasm_limit[LIMIT_STALLED]) ||
1694 (passn >= nasm_limit[LIMIT_PASSES])) {
1695 /* We get here if the labels don't converge
1696 * Example: FOO equ FOO + 1
1698 nasm_error(ERR_NONFATAL,
1699 "Can't find valid values for all labels "
1700 "after %"PRId64" passes, giving up.", passn);
1701 nasm_error(ERR_NONFATAL,
1702 "Possible causes: recursive EQUs, macro abuse.");
1703 break;
1707 preproc->cleanup(0);
1708 lfmt->cleanup();
1709 if (!terminate_after_phase && opt_verbose_info) {
1710 /* -On and -Ov switches */
1711 fprintf(stdout, "info: assembly required 1+%"PRId64"+1 passes\n",
1712 passn-3);
1717 * gnu style error reporting
1718 * This function prints an error message to error_file in the
1719 * style used by GNU. An example would be:
1720 * file.asm:50: error: blah blah blah
1721 * where file.asm is the name of the file, 50 is the line number on
1722 * which the error occurs (or is detected) and "error:" is one of
1723 * the possible optional diagnostics -- it can be "error" or "warning"
1724 * or something else. Finally the line terminates with the actual
1725 * error message.
1727 * @param severity the severity of the warning or error
1728 * @param fmt the printf style format string
1730 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1732 const char *currentfile = NULL;
1733 int32_t lineno = 0;
1735 if (is_suppressed_warning(severity))
1736 return;
1738 if (!(severity & ERR_NOFILE)) {
1739 src_get(&lineno, &currentfile);
1740 if (!currentfile || (severity & ERR_TOPFILE)) {
1741 currentfile = inname[0] ? inname : outname[0] ? outname : NULL;
1742 lineno = 0;
1746 if (!skip_this_pass(severity)) {
1747 if (!lineno)
1748 fprintf(error_file, "%s:", currentfile ? currentfile : "nasm");
1749 else
1750 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1753 nasm_verror_common(severity, fmt, ap);
1757 * MS style error reporting
1758 * This function prints an error message to error_file in the
1759 * style used by Visual C and some other Microsoft tools. An example
1760 * would be:
1761 * file.asm(50) : error: blah blah blah
1762 * where file.asm is the name of the file, 50 is the line number on
1763 * which the error occurs (or is detected) and "error:" is one of
1764 * the possible optional diagnostics -- it can be "error" or "warning"
1765 * or something else. Finally the line terminates with the actual
1766 * error message.
1768 * @param severity the severity of the warning or error
1769 * @param fmt the printf style format string
1771 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1773 const char *currentfile = NULL;
1774 int32_t lineno = 0;
1776 if (is_suppressed_warning(severity))
1777 return;
1779 if (!(severity & ERR_NOFILE))
1780 src_get(&lineno, &currentfile);
1782 if (!skip_this_pass(severity)) {
1783 if (currentfile) {
1784 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1785 } else {
1786 fputs("nasm: ", error_file);
1790 nasm_verror_common(severity, fmt, ap);
1794 * check to see if this is a suppressable warning
1796 static inline bool is_valid_warning(int severity)
1798 /* Not a warning at all */
1799 if ((severity & ERR_MASK) != ERR_WARNING)
1800 return false;
1802 return WARN_IDX(severity) < ERR_WARN_ALL;
1806 * check for suppressed warning
1807 * checks for suppressed warning or pass one only warning and we're
1808 * not in pass 1
1810 * @param severity the severity of the warning or error
1811 * @return true if we should abort error/warning printing
1813 static bool is_suppressed_warning(int severity)
1815 /* Might be a warning but suppresed explicitly */
1816 if (is_valid_warning(severity) && !(severity & ERR_USAGE))
1817 return !(warning_state[WARN_IDX(severity)] & WARN_ST_ENABLED);
1818 else
1819 return false;
1822 static bool warning_is_error(int severity)
1824 if (is_valid_warning(severity))
1825 return !!(warning_state[WARN_IDX(severity)] & WARN_ST_ERROR);
1826 else
1827 return false;
1830 static bool skip_this_pass(int severity)
1833 * See if it's a pass-specific error or warning which should be skipped.
1834 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1835 * they cannot be resumed from.
1837 if ((severity & ERR_MASK) > ERR_NONFATAL)
1838 return false;
1841 * passn is 1 on the very first pass only.
1842 * pass0 is 2 on the code-generation (final) pass only.
1843 * These are the passes we care about in this case.
1845 return (((severity & ERR_PASS1) && passn != 1) ||
1846 ((severity & ERR_PASS2) && pass0 != 2));
1850 * common error reporting
1851 * This is the common back end of the error reporting schemes currently
1852 * implemented. It prints the nature of the warning and then the
1853 * specific error message to error_file and may or may not return. It
1854 * doesn't return if the error severity is a "panic" or "debug" type.
1856 * @param severity the severity of the warning or error
1857 * @param fmt the printf style format string
1859 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1861 char msg[1024];
1862 const char *pfx;
1864 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1865 case ERR_WARNING:
1866 pfx = "warning: ";
1867 break;
1868 case ERR_NONFATAL:
1869 pfx = "error: ";
1870 break;
1871 case ERR_FATAL:
1872 pfx = "fatal: ";
1873 break;
1874 case ERR_PANIC:
1875 pfx = "panic: ";
1876 break;
1877 case ERR_DEBUG:
1878 pfx = "debug: ";
1879 break;
1880 default:
1881 pfx = "";
1882 break;
1885 vsnprintf(msg, sizeof msg - 64, fmt, args);
1886 if (is_valid_warning(severity) && WARN_IDX(severity) != ERR_WARN_OTHER) {
1887 char *p = strchr(msg, '\0');
1888 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
1891 if (!skip_this_pass(severity))
1892 fprintf(error_file, "%s%s\n", pfx, msg);
1894 /* Are we recursing from error_list_macros? */
1895 if (severity & ERR_PP_LISTMACRO)
1896 return;
1899 * Don't suppress this with skip_this_pass(), or we don't get
1900 * pass1 or preprocessor warnings in the list file
1902 lfmt->error(severity, pfx, msg);
1904 if (skip_this_pass(severity))
1905 return;
1907 if (severity & ERR_USAGE)
1908 want_usage = true;
1910 preproc->error_list_macros(severity);
1912 switch (severity & ERR_MASK) {
1913 case ERR_DEBUG:
1914 /* no further action, by definition */
1915 break;
1916 case ERR_WARNING:
1917 /* Treat warnings as errors */
1918 if (warning_is_error(severity))
1919 terminate_after_phase = true;
1920 break;
1921 case ERR_NONFATAL:
1922 terminate_after_phase = true;
1923 break;
1924 case ERR_FATAL:
1925 if (ofile) {
1926 fclose(ofile);
1927 if (!keep_all)
1928 remove(outname);
1929 ofile = NULL;
1931 if (want_usage)
1932 usage();
1933 exit(1); /* instantly die */
1934 break; /* placate silly compilers */
1935 case ERR_PANIC:
1936 fflush(NULL);
1938 if (abort_on_panic)
1939 abort(); /* halt, catch fire, dump core/stop debugger */
1941 if (ofile) {
1942 fclose(ofile);
1943 if (!keep_all)
1944 remove(outname);
1945 ofile = NULL;
1947 exit(3);
1948 break;
1952 static void usage(void)
1954 fputs("type `nasm -h' for help\n", error_file);
1957 static void help(const char xopt)
1959 int i;
1961 printf
1962 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1963 "[-l listfile]\n"
1964 " [options...] [--] filename\n"
1965 " or nasm -v (or --v) for version info\n\n"
1966 "\n"
1967 "Response files should contain command line parameters,\n"
1968 "one per line.\n"
1969 "\n"
1970 " -t assemble in SciTech TASM compatible mode\n");
1971 printf
1972 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1973 " -a don't preprocess (assemble only)\n"
1974 " -M generate Makefile dependencies on stdout\n"
1975 " -MG d:o, missing files assumed generated\n"
1976 " -MF file set Makefile dependency file\n"
1977 " -MD file assemble and generate dependencies\n"
1978 " -MT file dependency target name\n"
1979 " -MQ file dependency target name (quoted)\n"
1980 " -MP emit phony target\n\n"
1981 " -Zfile redirect error messages to file\n"
1982 " -s redirect error messages to stdout\n\n"
1983 " -g generate debugging information\n\n"
1984 " -F format select a debugging format\n\n"
1985 " -gformat same as -g -F format\n\n"
1986 " -o outfile write output to an outfile\n\n"
1987 " -f format select an output format\n\n"
1988 " -l listfile write listing to a listfile\n\n"
1989 " -Ipath add a pathname to the include file path\n");
1990 printf
1991 (" -Olevel optimize opcodes, immediates and branch offsets\n"
1992 " -O0 no optimization\n"
1993 " -O1 minimal optimization\n"
1994 " -Ox multipass optimization (default)\n"
1995 " -Pfile pre-include a file (also --include)\n"
1996 " -Dmacro[=str] pre-define a macro\n"
1997 " -Umacro undefine a macro\n"
1998 " -Xformat specifiy error reporting format (gnu or vc)\n"
1999 " -w+foo enable warning foo (equiv. -Wfoo)\n"
2000 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
2001 " -w[+-]error[=foo]\n"
2002 " promote [specific] warnings to errors\n"
2003 " -h show invocation summary and exit (also --help)\n\n"
2004 " --pragma str pre-executes a specific %%pragma\n"
2005 " --before str add line (usually a preprocessor statement) before the input\n"
2006 " --prefix str prepend the given string to all the given string\n"
2007 " to all extern, common and global symbols (also --gprefix)\n"
2008 " --postfix str append the given string to all the given string\n"
2009 " to all extern, common and global symbols (also --gpostfix)\n"
2010 " --lprefix str prepend the given string to all other symbols\n"
2011 " --lpostfix str append the given string to all other symbols\n"
2012 " --keep-all output files will not be removed even if an error happens\n"
2013 " --limit-X val set execution limit X\n");
2015 for (i = 0; i <= LIMIT_MAX; i++) {
2016 printf(" %-15s %s (default ",
2017 limit_info[i].name, limit_info[i].help);
2018 if (nasm_limit[i] < LIMIT_MAX_VAL) {
2019 printf("%"PRId64")\n", nasm_limit[i]);
2020 } else {
2021 printf("unlimited)\n");
2025 printf("\nWarnings for the -W/-w options:\n");
2027 for (i = 0; i <= ERR_WARN_ALL; i++)
2028 printf(" %-23s %s%s\n",
2029 warnings[i].name, warnings[i].help,
2030 i == ERR_WARN_ALL ? "\n" :
2031 warnings[i].enabled ? " (default on)" :
2032 " (default off)");
2034 if (xopt == 'f') {
2035 printf("valid output formats for -f are"
2036 " (`*' denotes default):\n");
2037 ofmt_list(ofmt, stdout);
2038 } else {
2039 printf("For a list of valid output formats, use -hf.\n");
2040 printf("For a list of debug formats, use -f <format> -y.\n");