Merge branch 'nasm-2.14.xx'
[nasm.git] / asm / nasm.c
blob52df47d24f698ec6ef6ccc37c9f35dad7b9256de
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 *list)
333 struct strlist_entry *l;
335 preproc->init();
336 define_macros();
338 list_for_each(l, list->head)
339 preproc->include_path(l->str);
342 static void emit_dependencies(StrList *list)
344 FILE *deps;
345 int linepos, len;
346 bool wmake = (quote_for_make == quote_for_wmake);
347 const char *wrapstr, *nulltarget;
348 struct strlist_entry *l;
350 if (!list)
351 return;
353 wrapstr = wmake ? " &\n " : " \\\n ";
354 nulltarget = wmake ? "\t%null\n" : "";
356 if (depend_file && strcmp(depend_file, "-")) {
357 deps = nasm_open_write(depend_file, NF_TEXT);
358 if (!deps) {
359 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
360 "unable to write dependency file `%s'", depend_file);
361 return;
363 } else {
364 deps = stdout;
367 linepos = fprintf(deps, "%s :", depend_target);
368 list_for_each(l, list->head) {
369 char *file = quote_for_make(l->str);
370 len = strlen(file);
371 if (linepos + len > 62 && linepos > 1) {
372 fputs(wrapstr, deps);
373 linepos = 1;
375 fprintf(deps, " %s", file);
376 linepos += len+1;
377 nasm_free(file);
379 fprintf(deps, "\n\n");
381 list_for_each(l, list->head) {
382 if (depend_emit_phony) {
383 char *file = quote_for_make(l->str);
384 fprintf(deps, "%s :\n%s\n", file, nulltarget);
385 nasm_free(file);
389 strlist_free(list);
391 if (deps != stdout)
392 fclose(deps);
395 /* Convert a struct tm to a POSIX-style time constant */
396 static int64_t make_posix_time(const struct tm *tm)
398 int64_t t;
399 int64_t y = tm->tm_year;
401 /* See IEEE 1003.1:2004, section 4.14 */
403 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
404 t += tm->tm_yday;
405 t *= 24;
406 t += tm->tm_hour;
407 t *= 60;
408 t += tm->tm_min;
409 t *= 60;
410 t += tm->tm_sec;
412 return t;
415 static void timestamp(void)
417 struct compile_time * const oct = &official_compile_time;
418 const struct tm *tp, *best_gm;
420 time(&oct->t);
422 best_gm = NULL;
424 tp = localtime(&oct->t);
425 if (tp) {
426 oct->local = *tp;
427 best_gm = &oct->local;
428 oct->have_local = true;
431 tp = gmtime(&oct->t);
432 if (tp) {
433 oct->gm = *tp;
434 best_gm = &oct->gm;
435 oct->have_gm = true;
436 if (!oct->have_local)
437 oct->local = oct->gm;
438 } else {
439 oct->gm = oct->local;
442 if (best_gm) {
443 oct->posix = make_posix_time(best_gm);
444 oct->have_posix = true;
448 int main(int argc, char **argv)
450 timestamp();
452 iflag_set_default_cpu(&cpu);
453 iflag_set_default_cpu(&cmd_cpu);
455 include_path = strlist_allocate();
457 pass0 = 0;
458 want_usage = terminate_after_phase = false;
459 nasm_set_verror(nasm_verror_gnu);
461 error_file = stderr;
463 tolower_init();
464 src_init();
467 * We must call init_labels() before the command line parsing,
468 * because we may be setting prefixes/suffixes from the command
469 * line.
471 init_labels();
473 offsets = raa_init();
474 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
476 preproc = &nasmpp;
477 operating_mode = OP_NORMAL;
479 parse_cmdline(argc, argv, 1);
480 if (terminate_after_phase) {
481 if (want_usage)
482 usage();
483 return 1;
486 /* At this point we have ofmt and the name of the desired debug format */
487 if (!using_debug_info) {
488 /* No debug info, redirect to the null backend (empty stubs) */
489 dfmt = &null_debug_form;
490 } else if (!debug_format) {
491 /* Default debug format for this backend */
492 dfmt = ofmt->default_dfmt;
493 } else {
494 dfmt = dfmt_find(ofmt, debug_format);
495 if (!dfmt) {
496 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
497 "unrecognized debug format `%s' for"
498 " output format `%s'",
499 debug_format, ofmt->shortname);
503 preproc_init(include_path);
504 strlist_free(include_path);
505 include_path = NULL;
507 parse_cmdline(argc, argv, 2);
508 if (terminate_after_phase) {
509 if (want_usage)
510 usage();
511 return 1;
514 /* Save away the default state of warnings */
515 memcpy(warning_state_init, warning_state, sizeof warning_state);
518 * If no output file name provided and this
519 * is a preprocess mode, we're perfectly
520 * fine to output into stdout.
522 if (!outname) {
523 if (!(operating_mode & OP_PREPROCESS))
524 outname = filename_set_extension(inname, ofmt->extension);
527 if (depend_file || (operating_mode & OP_DEPEND))
528 depend_list = strlist_allocate();
530 if (!depend_target)
531 depend_target = quote_for_make(outname);
533 if (operating_mode & OP_DEPEND) {
534 char *line;
536 if (depend_missing_ok)
537 preproc->include_path(NULL); /* "assume generated" */
539 preproc->reset(inname, 0, depend_list);
540 ofile = NULL;
541 while ((line = preproc->getline()))
542 nasm_free(line);
543 preproc->cleanup(0);
544 } else if (operating_mode & OP_PREPROCESS) {
545 char *line;
546 const char *file_name = NULL;
547 int32_t prior_linnum = 0;
548 int lineinc = 0;
550 if (outname) {
551 ofile = nasm_open_write(outname, NF_TEXT);
552 if (!ofile)
553 nasm_fatal_fl(ERR_NOFILE,
554 "unable to open output file `%s'",
555 outname);
556 } else
557 ofile = NULL;
559 location.known = false;
561 /* pass = 1; */
562 preproc->reset(inname, 3, depend_list);
564 /* Revert all warnings to the default state */
565 memcpy(warning_state, warning_state_init, sizeof warning_state);
567 while ((line = preproc->getline())) {
569 * We generate %line directives if needed for later programs
571 int32_t linnum = prior_linnum += lineinc;
572 int altline = src_get(&linnum, &file_name);
573 if (altline) {
574 if (altline == 1 && lineinc == 1)
575 nasm_fputs("", ofile);
576 else {
577 lineinc = (altline != -1 || lineinc != 1);
578 fprintf(ofile ? ofile : stdout,
579 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
580 file_name);
582 prior_linnum = linnum;
584 nasm_fputs(line, ofile);
585 nasm_free(line);
587 preproc->cleanup(0);
588 if (ofile)
589 fclose(ofile);
590 if (ofile && terminate_after_phase && !keep_all)
591 remove(outname);
592 ofile = NULL;
595 if (operating_mode & OP_NORMAL) {
596 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
597 if (!ofile)
598 nasm_fatal_fl(ERR_NOFILE,
599 "unable to open output file `%s'", outname);
601 ofmt->init();
602 dfmt->init();
604 assemble_file(inname, depend_list);
606 if (!terminate_after_phase) {
607 ofmt->cleanup();
608 cleanup_labels();
609 fflush(ofile);
610 if (ferror(ofile)) {
611 nasm_error(ERR_NONFATAL|ERR_NOFILE,
612 "write error on output file `%s'", outname);
613 terminate_after_phase = true;
617 if (ofile) {
618 fclose(ofile);
619 if (terminate_after_phase && !keep_all)
620 remove(outname);
621 ofile = NULL;
625 if (depend_list && !terminate_after_phase)
626 emit_dependencies(depend_list);
628 if (want_usage)
629 usage();
631 raa_free(offsets);
632 saa_free(forwrefs);
633 eval_cleanup();
634 stdscan_cleanup();
635 src_free();
637 return terminate_after_phase;
641 * Get a parameter for a command line option.
642 * First arg must be in the form of e.g. -f...
644 static char *get_param(char *p, char *q, bool *advance)
646 *advance = false;
647 if (p[2]) /* the parameter's in the option */
648 return nasm_skip_spaces(p + 2);
649 if (q && q[0]) {
650 *advance = true;
651 return q;
653 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
654 "option `-%c' requires an argument", p[1]);
655 return NULL;
659 * Copy a filename
661 static void copy_filename(const char **dst, const char *src, const char *what)
663 if (*dst)
664 nasm_fatal("more than one %s file specified: %s\n", what, src);
666 *dst = nasm_strdup(src);
670 * Convert a string to a POSIX make-safe form
672 static char *quote_for_pmake(const char *str)
674 const char *p;
675 char *os, *q;
677 size_t n = 1; /* Terminating zero */
678 size_t nbs = 0;
680 if (!str)
681 return NULL;
683 for (p = str; *p; p++) {
684 switch (*p) {
685 case ' ':
686 case '\t':
687 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
688 n += nbs + 2;
689 nbs = 0;
690 break;
691 case '$':
692 case '#':
693 nbs = 0;
694 n += 2;
695 break;
696 case '\\':
697 nbs++;
698 n++;
699 break;
700 default:
701 nbs = 0;
702 n++;
703 break;
707 /* Convert N backslashes at the end of filename to 2N backslashes */
708 if (nbs)
709 n += nbs;
711 os = q = nasm_malloc(n);
713 nbs = 0;
714 for (p = str; *p; p++) {
715 switch (*p) {
716 case ' ':
717 case '\t':
718 while (nbs--)
719 *q++ = '\\';
720 *q++ = '\\';
721 *q++ = *p;
722 break;
723 case '$':
724 *q++ = *p;
725 *q++ = *p;
726 nbs = 0;
727 break;
728 case '#':
729 *q++ = '\\';
730 *q++ = *p;
731 nbs = 0;
732 break;
733 case '\\':
734 *q++ = *p;
735 nbs++;
736 break;
737 default:
738 *q++ = *p;
739 nbs = 0;
740 break;
743 while (nbs--)
744 *q++ = '\\';
746 *q = '\0';
748 return os;
752 * Convert a string to a Watcom make-safe form
754 static char *quote_for_wmake(const char *str)
756 const char *p;
757 char *os, *q;
758 bool quote = false;
760 size_t n = 1; /* Terminating zero */
762 if (!str)
763 return NULL;
765 for (p = str; *p; p++) {
766 switch (*p) {
767 case ' ':
768 case '\t':
769 case '&':
770 quote = true;
771 n++;
772 break;
773 case '\"':
774 quote = true;
775 n += 2;
776 break;
777 case '$':
778 case '#':
779 n += 2;
780 break;
781 default:
782 n++;
783 break;
787 if (quote)
788 n += 2;
790 os = q = nasm_malloc(n);
792 if (quote)
793 *q++ = '\"';
795 for (p = str; *p; p++) {
796 switch (*p) {
797 case '$':
798 case '#':
799 *q++ = '$';
800 *q++ = *p;
801 break;
802 case '\"':
803 *q++ = *p;
804 *q++ = *p;
805 break;
806 default:
807 *q++ = *p;
808 break;
812 if (quote)
813 *q++ = '\"';
815 *q = '\0';
817 return os;
820 enum text_options {
821 OPT_BOGUS,
822 OPT_VERSION,
823 OPT_HELP,
824 OPT_ABORT_ON_PANIC,
825 OPT_MANGLE,
826 OPT_INCLUDE,
827 OPT_PRAGMA,
828 OPT_BEFORE,
829 OPT_LIMIT,
830 OPT_KEEP_ALL
832 struct textargs {
833 const char *label;
834 enum text_options opt;
835 bool need_arg;
836 int pvt;
838 static const struct textargs textopts[] = {
839 {"v", OPT_VERSION, false, 0},
840 {"version", OPT_VERSION, false, 0},
841 {"help", OPT_HELP, false, 0},
842 {"abort-on-panic", OPT_ABORT_ON_PANIC, false, 0},
843 {"prefix", OPT_MANGLE, true, LM_GPREFIX},
844 {"postfix", OPT_MANGLE, true, LM_GSUFFIX},
845 {"gprefix", OPT_MANGLE, true, LM_GPREFIX},
846 {"gpostfix", OPT_MANGLE, true, LM_GSUFFIX},
847 {"lprefix", OPT_MANGLE, true, LM_LPREFIX},
848 {"lpostfix", OPT_MANGLE, true, LM_LSUFFIX},
849 {"include", OPT_INCLUDE, true, 0},
850 {"pragma", OPT_PRAGMA, true, 0},
851 {"before", OPT_BEFORE, true, 0},
852 {"limit-", OPT_LIMIT, true, 0},
853 {"keep-all", OPT_KEEP_ALL, false, 0},
854 {NULL, OPT_BOGUS, false, 0}
857 static void show_version(void)
859 printf("NASM version %s compiled on %s%s\n",
860 nasm_version, nasm_date, nasm_compile_options);
861 exit(0);
864 static bool stopoptions = false;
865 static bool process_arg(char *p, char *q, int pass)
867 char *param;
868 bool advance = false;
870 if (!p || !p[0])
871 return false;
873 if (p[0] == '-' && !stopoptions) {
874 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
875 /* These parameters take values */
876 if (!(param = get_param(p, q, &advance)))
877 return advance;
880 switch (p[1]) {
881 case 's':
882 if (pass == 1)
883 error_file = stdout;
884 break;
886 case 'o': /* output file */
887 if (pass == 2)
888 copy_filename(&outname, param, "output");
889 break;
891 case 'f': /* output format */
892 if (pass == 1) {
893 ofmt = ofmt_find(param, &ofmt_alias);
894 if (!ofmt) {
895 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
896 "unrecognised output format `%s' - "
897 "use -hf for a list", param);
900 break;
902 case 'O': /* Optimization level */
903 if (pass == 1) {
904 int opt;
906 if (!*param) {
907 /* Naked -O == -Ox */
908 optimizing.level = MAX_OPTIMIZE;
909 } else {
910 while (*param) {
911 switch (*param) {
912 case '0': case '1': case '2': case '3': case '4':
913 case '5': case '6': case '7': case '8': case '9':
914 opt = strtoul(param, &param, 10);
916 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
917 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
918 if (opt < 2)
919 optimizing.level = opt - 1;
920 else
921 optimizing.level = opt;
922 break;
924 case 'v':
925 case '+':
926 param++;
927 opt_verbose_info = true;
928 break;
930 case 'x':
931 param++;
932 optimizing.level = MAX_OPTIMIZE;
933 break;
935 default:
936 nasm_fatal("unknown optimization option -O%c\n",
937 *param);
938 break;
941 if (optimizing.level > MAX_OPTIMIZE)
942 optimizing.level = MAX_OPTIMIZE;
945 break;
947 case 'p': /* pre-include */
948 case 'P':
949 if (pass == 2)
950 preproc->pre_include(param);
951 break;
953 case 'd': /* pre-define */
954 case 'D':
955 if (pass == 2)
956 preproc->pre_define(param);
957 break;
959 case 'u': /* un-define */
960 case 'U':
961 if (pass == 2)
962 preproc->pre_undefine(param);
963 break;
965 case 'i': /* include search path */
966 case 'I':
967 if (pass == 1)
968 strlist_add_string(include_path, param);
969 break;
971 case 'l': /* listing file */
972 if (pass == 2)
973 copy_filename(&listname, param, "listing");
974 break;
976 case 'Z': /* error messages file */
977 if (pass == 1)
978 copy_filename(&errname, param, "error");
979 break;
981 case 'F': /* specify debug format */
982 if (pass == 1) {
983 using_debug_info = true;
984 debug_format = param;
986 break;
988 case 'X': /* specify error reporting format */
989 if (pass == 1) {
990 if (nasm_stricmp("vc", param) == 0)
991 nasm_set_verror(nasm_verror_vc);
992 else if (nasm_stricmp("gnu", param) == 0)
993 nasm_set_verror(nasm_verror_gnu);
994 else
995 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
996 "unrecognized error reporting format `%s'",
997 param);
999 break;
1001 case 'g':
1002 if (pass == 1) {
1003 using_debug_info = true;
1004 if (p[2])
1005 debug_format = nasm_skip_spaces(p + 2);
1007 break;
1009 case 'h':
1010 help(p[2]);
1011 exit(0); /* never need usage message here */
1012 break;
1014 case 'y':
1015 printf("\nvalid debug formats for '%s' output format are"
1016 " ('*' denotes default):\n", ofmt->shortname);
1017 dfmt_list(ofmt, stdout);
1018 exit(0);
1019 break;
1021 case 't':
1022 if (pass == 2)
1023 tasm_compatible_mode = true;
1024 break;
1026 case 'v':
1027 show_version();
1028 break;
1030 case 'e': /* preprocess only */
1031 case 'E':
1032 if (pass == 1)
1033 operating_mode = OP_PREPROCESS;
1034 break;
1036 case 'a': /* assemble only - don't preprocess */
1037 if (pass == 1)
1038 preproc = &preproc_nop;
1039 break;
1041 case 'w':
1042 case 'W':
1043 if (pass == 2) {
1044 if (!set_warning_status(param)) {
1045 nasm_error(ERR_WARNING|ERR_NOFILE|ERR_WARN_UNK_WARNING,
1046 "unknown warning option: %s", param);
1049 break;
1051 case 'M':
1052 if (pass == 1) {
1053 switch (p[2]) {
1054 case 'W':
1055 quote_for_make = quote_for_wmake;
1056 break;
1057 case 'D':
1058 case 'F':
1059 case 'T':
1060 case 'Q':
1061 advance = true;
1062 break;
1063 default:
1064 break;
1066 } else {
1067 switch (p[2]) {
1068 case 0:
1069 operating_mode = OP_DEPEND;
1070 break;
1071 case 'G':
1072 operating_mode = OP_DEPEND;
1073 depend_missing_ok = true;
1074 break;
1075 case 'P':
1076 depend_emit_phony = true;
1077 break;
1078 case 'D':
1079 operating_mode = OP_NORMAL;
1080 depend_file = q;
1081 advance = true;
1082 break;
1083 case 'F':
1084 depend_file = q;
1085 advance = true;
1086 break;
1087 case 'T':
1088 depend_target = q;
1089 advance = true;
1090 break;
1091 case 'Q':
1092 depend_target = quote_for_make(q);
1093 advance = true;
1094 break;
1095 case 'W':
1096 /* handled in pass 1 */
1097 break;
1098 default:
1099 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1100 "unknown dependency option `-M%c'", p[2]);
1101 break;
1104 if (advance && (!q || !q[0])) {
1105 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1106 "option `-M%c' requires a parameter", p[2]);
1107 break;
1109 break;
1111 case '-':
1113 const struct textargs *tx;
1114 size_t olen, plen;
1115 char *eqsave;
1117 p += 2;
1119 if (!*p) { /* -- => stop processing options */
1120 stopoptions = true;
1121 break;
1124 plen = strlen(p);
1125 for (tx = textopts; tx->label; tx++) {
1126 olen = strlen(tx->label);
1128 if (olen > plen)
1129 continue;
1131 if (nasm_memicmp(p, tx->label, olen))
1132 continue;
1134 if (tx->label[olen-1] == '-')
1135 break; /* Incomplete option */
1137 if (!p[olen] || p[olen] == '=')
1138 break; /* Complete option */
1141 if (!tx->label) {
1142 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1143 "unrecognized option `--%s'", p);
1146 eqsave = param = strchr(p+olen, '=');
1147 if (param)
1148 *param++ = '\0';
1150 if (tx->need_arg) {
1151 if (!param) {
1152 param = q;
1153 advance = true;
1156 /* Note: a null string is a valid parameter */
1157 if (!param) {
1158 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1159 "option `--%s' requires an argument",
1161 break;
1163 } else {
1164 if (param) {
1165 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1166 "option `--%s' does not take an argument",
1172 switch (tx->opt) {
1173 case OPT_VERSION:
1174 show_version();
1175 break;
1176 case OPT_ABORT_ON_PANIC:
1177 abort_on_panic = true;
1178 break;
1179 case OPT_MANGLE:
1180 if (pass == 2)
1181 set_label_mangle(tx->pvt, param);
1182 break;
1183 case OPT_INCLUDE:
1184 if (pass == 2)
1185 preproc->pre_include(q);
1186 break;
1187 case OPT_PRAGMA:
1188 if (pass == 2)
1189 preproc->pre_command("pragma", param);
1190 break;
1191 case OPT_BEFORE:
1192 if (pass == 2)
1193 preproc->pre_command(NULL, param);
1194 break;
1195 case OPT_LIMIT:
1196 if (pass == 1)
1197 nasm_set_limit(p+olen, param);
1198 break;
1199 case OPT_KEEP_ALL:
1200 keep_all = true;
1201 break;
1202 case OPT_HELP:
1203 help(0);
1204 exit(0);
1205 default:
1206 panic();
1209 if (eqsave)
1210 *eqsave = '='; /* Restore = argument separator */
1212 break;
1215 default:
1216 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1217 "unrecognised option `-%c'", p[1]);
1218 break;
1220 } else if (pass == 2) {
1221 /* In theory we could allow multiple input files... */
1222 copy_filename(&inname, p, "input");
1225 return advance;
1228 #define ARG_BUF_DELTA 128
1230 static void process_respfile(FILE * rfile, int pass)
1232 char *buffer, *p, *q, *prevarg;
1233 int bufsize, prevargsize;
1235 bufsize = prevargsize = ARG_BUF_DELTA;
1236 buffer = nasm_malloc(ARG_BUF_DELTA);
1237 prevarg = nasm_malloc(ARG_BUF_DELTA);
1238 prevarg[0] = '\0';
1240 while (1) { /* Loop to handle all lines in file */
1241 p = buffer;
1242 while (1) { /* Loop to handle long lines */
1243 q = fgets(p, bufsize - (p - buffer), rfile);
1244 if (!q)
1245 break;
1246 p += strlen(p);
1247 if (p > buffer && p[-1] == '\n')
1248 break;
1249 if (p - buffer > bufsize - 10) {
1250 int offset;
1251 offset = p - buffer;
1252 bufsize += ARG_BUF_DELTA;
1253 buffer = nasm_realloc(buffer, bufsize);
1254 p = buffer + offset;
1258 if (!q && p == buffer) {
1259 if (prevarg[0])
1260 process_arg(prevarg, NULL, pass);
1261 nasm_free(buffer);
1262 nasm_free(prevarg);
1263 return;
1267 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1268 * them are present at the end of the line.
1270 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1272 while (p > buffer && nasm_isspace(p[-1]))
1273 *--p = '\0';
1275 p = nasm_skip_spaces(buffer);
1277 if (process_arg(prevarg, p, pass))
1278 *p = '\0';
1280 if ((int) strlen(p) > prevargsize - 10) {
1281 prevargsize += ARG_BUF_DELTA;
1282 prevarg = nasm_realloc(prevarg, prevargsize);
1284 strncpy(prevarg, p, prevargsize);
1288 /* Function to process args from a string of args, rather than the
1289 * argv array. Used by the environment variable and response file
1290 * processing.
1292 static void process_args(char *args, int pass)
1294 char *p, *q, *arg, *prevarg;
1295 char separator = ' ';
1297 p = args;
1298 if (*p && *p != '-')
1299 separator = *p++;
1300 arg = NULL;
1301 while (*p) {
1302 q = p;
1303 while (*p && *p != separator)
1304 p++;
1305 while (*p == separator)
1306 *p++ = '\0';
1307 prevarg = arg;
1308 arg = q;
1309 if (process_arg(prevarg, arg, pass))
1310 arg = NULL;
1312 if (arg)
1313 process_arg(arg, NULL, pass);
1316 static void process_response_file(const char *file, int pass)
1318 char str[2048];
1319 FILE *f = nasm_open_read(file, NF_TEXT);
1320 if (!f) {
1321 perror(file);
1322 exit(-1);
1324 while (fgets(str, sizeof str, f)) {
1325 process_args(str, pass);
1327 fclose(f);
1330 static void parse_cmdline(int argc, char **argv, int pass)
1332 FILE *rfile;
1333 char *envreal, *envcopy = NULL, *p;
1334 int i;
1336 /* Initialize all the warnings to their default state */
1337 for (i = 0; i < ERR_WARN_ALL; i++) {
1338 warning_state_init[i] = warning_state[i] =
1339 warnings[i].enabled ? WARN_ST_ENABLED : 0;
1343 * First, process the NASMENV environment variable.
1345 envreal = getenv("NASMENV");
1346 if (envreal) {
1347 envcopy = nasm_strdup(envreal);
1348 process_args(envcopy, pass);
1349 nasm_free(envcopy);
1353 * Now process the actual command line.
1355 while (--argc) {
1356 bool advance;
1357 argv++;
1358 if (argv[0][0] == '@') {
1360 * We have a response file, so process this as a set of
1361 * arguments like the environment variable. This allows us
1362 * to have multiple arguments on a single line, which is
1363 * different to the -@resp file processing below for regular
1364 * NASM.
1366 process_response_file(argv[0]+1, pass);
1367 argc--;
1368 argv++;
1370 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1371 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1372 if (p) {
1373 rfile = nasm_open_read(p, NF_TEXT);
1374 if (rfile) {
1375 process_respfile(rfile, pass);
1376 fclose(rfile);
1377 } else
1378 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1379 "unable to open response file `%s'", p);
1381 } else
1382 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1383 argv += advance, argc -= advance;
1387 * Look for basic command line typos. This definitely doesn't
1388 * catch all errors, but it might help cases of fumbled fingers.
1390 if (pass != 2)
1391 return;
1393 if (!inname)
1394 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE, "no input file specified");
1396 else if ((errname && !strcmp(inname, errname)) ||
1397 (outname && !strcmp(inname, outname)) ||
1398 (listname && !strcmp(inname, listname)) ||
1399 (depend_file && !strcmp(inname, depend_file)))
1400 nasm_fatal_fl(ERR_USAGE, "will not overwrite input file");
1402 if (errname) {
1403 error_file = nasm_open_write(errname, NF_TEXT);
1404 if (!error_file) {
1405 error_file = stderr; /* Revert to default! */
1406 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
1407 "cannot open file `%s' for error messages",
1408 errname);
1413 static void assemble_file(const char *fname, StrList *depend_list)
1415 char *line;
1416 insn output_ins;
1417 int i;
1418 uint64_t prev_offset_changed;
1419 int64_t stall_count = 0; /* Make sure we make forward progress... */
1421 switch (cmd_sb) {
1422 case 16:
1423 break;
1424 case 32:
1425 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1426 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1427 break;
1428 case 64:
1429 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1430 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1431 break;
1432 default:
1433 panic();
1434 break;
1437 prev_offset_changed = nasm_limit[LIMIT_PASSES];
1438 for (passn = 1; pass0 <= 2; passn++) {
1439 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1440 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1441 /* pass0 0, 0, 0, ..., 1, 2 */
1443 globalbits = cmd_sb; /* set 'bits' to command line default */
1444 cpu = cmd_cpu;
1445 if (pass0 == 2) {
1446 lfmt->init(listname);
1447 } else if (passn == 1 && listname && !keep_all) {
1448 /* Remove the list file in case we die before the output pass */
1449 remove(listname);
1451 in_absolute = false;
1452 global_offset_changed = 0; /* set by redefine_label */
1453 if (passn > 1) {
1454 saa_rewind(forwrefs);
1455 forwref = saa_rstruct(forwrefs);
1456 raa_free(offsets);
1457 offsets = raa_init();
1459 location.segment = NO_SEG;
1460 location.offset = 0;
1461 if (passn == 1)
1462 location.known = true;
1463 ofmt->reset();
1464 switch_segment(ofmt->section(NULL, pass2, &globalbits));
1465 preproc->reset(fname, pass1, pass1 == 2 ? depend_list : NULL);
1467 /* Revert all warnings to the default state */
1468 memcpy(warning_state, warning_state_init, sizeof warning_state);
1470 globallineno = 0;
1472 while ((line = preproc->getline())) {
1473 if (++globallineno > nasm_limit[LIMIT_LINES])
1474 nasm_fatal("overall line count exceeds the maximum %"PRId64"\n",
1475 nasm_limit[LIMIT_LINES]);
1478 * Here we parse our directives; this is not handled by the
1479 * main parser.
1481 if (process_directives(line))
1482 goto end_of_line; /* Just do final cleanup */
1484 /* Not a directive, or even something that starts with [ */
1485 parse_line(pass1, line, &output_ins);
1487 if (optimizing.level > 0) {
1488 if (forwref != NULL && globallineno == forwref->lineno) {
1489 output_ins.forw_ref = true;
1490 do {
1491 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1492 forwref = saa_rstruct(forwrefs);
1493 } while (forwref != NULL
1494 && forwref->lineno == globallineno);
1495 } else
1496 output_ins.forw_ref = false;
1498 if (output_ins.forw_ref) {
1499 if (passn == 1) {
1500 for (i = 0; i < output_ins.operands; i++) {
1501 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1502 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1503 fwinf->lineno = globallineno;
1504 fwinf->operand = i;
1511 /* forw_ref */
1512 if (output_ins.opcode == I_EQU) {
1513 if (!output_ins.label) {
1514 nasm_error(ERR_NONFATAL, "EQU not preceded by label");
1515 } else if (output_ins.operands == 1 &&
1516 (output_ins.oprs[0].type & IMMEDIATE) &&
1517 output_ins.oprs[0].wrt == NO_SEG) {
1518 define_label(output_ins.label,
1519 output_ins.oprs[0].segment,
1520 output_ins.oprs[0].offset, false);
1521 } else if (output_ins.operands == 2
1522 && (output_ins.oprs[0].type & IMMEDIATE)
1523 && (output_ins.oprs[0].type & COLON)
1524 && output_ins.oprs[0].segment == NO_SEG
1525 && output_ins.oprs[0].wrt == NO_SEG
1526 && (output_ins.oprs[1].type & IMMEDIATE)
1527 && output_ins.oprs[1].segment == NO_SEG
1528 && output_ins.oprs[1].wrt == NO_SEG) {
1529 define_label(output_ins.label,
1530 output_ins.oprs[0].offset | SEG_ABS,
1531 output_ins.oprs[1].offset, false);
1532 } else {
1533 nasm_error(ERR_NONFATAL, "bad syntax for EQU");
1535 } else { /* instruction isn't an EQU */
1536 int32_t n;
1538 nasm_assert(output_ins.times >= 0);
1540 for (n = 1; n <= output_ins.times; n++) {
1541 if (pass1 == 1) {
1542 int64_t l = insn_size(location.segment,
1543 location.offset,
1544 globalbits, &output_ins);
1546 /* if (using_debug_info) && output_ins.opcode != -1) */
1547 if (using_debug_info)
1548 { /* fbk 03/25/01 */
1549 /* this is done here so we can do debug type info */
1550 int32_t typeinfo =
1551 TYS_ELEMENTS(output_ins.operands);
1552 switch (output_ins.opcode) {
1553 case I_RESB:
1554 typeinfo =
1555 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1556 break;
1557 case I_RESW:
1558 typeinfo =
1559 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1560 break;
1561 case I_RESD:
1562 typeinfo =
1563 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1564 break;
1565 case I_RESQ:
1566 typeinfo =
1567 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1568 break;
1569 case I_REST:
1570 typeinfo =
1571 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1572 break;
1573 case I_RESO:
1574 typeinfo =
1575 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1576 break;
1577 case I_RESY:
1578 typeinfo =
1579 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1580 break;
1581 case I_RESZ:
1582 typeinfo =
1583 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;
1584 break;
1585 case I_DB:
1586 typeinfo |= TY_BYTE;
1587 break;
1588 case I_DW:
1589 typeinfo |= TY_WORD;
1590 break;
1591 case I_DD:
1592 if (output_ins.eops_float)
1593 typeinfo |= TY_FLOAT;
1594 else
1595 typeinfo |= TY_DWORD;
1596 break;
1597 case I_DQ:
1598 typeinfo |= TY_QWORD;
1599 break;
1600 case I_DT:
1601 typeinfo |= TY_TBYTE;
1602 break;
1603 case I_DO:
1604 typeinfo |= TY_OWORD;
1605 break;
1606 case I_DY:
1607 typeinfo |= TY_YWORD;
1608 break;
1609 case I_DZ:
1610 typeinfo |= TY_ZWORD;
1611 break;
1612 default:
1613 typeinfo = TY_LABEL;
1614 break;
1617 dfmt->debug_typevalue(typeinfo);
1621 * For INCBIN, let the code in assemble
1622 * handle TIMES, so we don't have to read the
1623 * input file over and over.
1625 if (l != -1) {
1626 increment_offset(l);
1629 * else l == -1 => invalid instruction, which will be
1630 * flagged as an error on pass 2
1632 } else {
1633 if (n == 2)
1634 lfmt->uplevel(LIST_TIMES);
1635 increment_offset(assemble(location.segment,
1636 location.offset,
1637 globalbits, &output_ins));
1639 } /* not an EQU */
1641 if (output_ins.times > 1)
1642 lfmt->downlevel(LIST_TIMES);
1644 cleanup_insn(&output_ins);
1646 end_of_line:
1647 nasm_free(line);
1648 } /* end while (line = preproc->getline... */
1650 if (global_offset_changed && !terminate_after_phase) {
1651 switch (pass0) {
1652 case 1:
1653 nasm_error(ERR_WARNING|ERR_WARN_PHASE,
1654 "phase error during stabilization pass, hoping for the best");
1655 break;
1657 case 2:
1658 nasm_error(ERR_NONFATAL,
1659 "phase error during code generation pass");
1660 break;
1662 default:
1663 /* This is normal, we'll keep going... */
1664 break;
1668 if (pass1 == 1)
1669 preproc->cleanup(1);
1672 * Always run at least two optimization passes (pass0 == 0);
1673 * things like subsections will fail miserably without that.
1674 * Once we commit to a stabilization pass (pass0 == 1), we can't
1675 * go back, and if something goes bad, we can only hope
1676 * that we don't end up with a phase error at the end.
1678 if ((passn > 1 && !global_offset_changed) || pass0 > 0) {
1679 pass0++;
1680 } else if (global_offset_changed &&
1681 global_offset_changed < prev_offset_changed) {
1682 prev_offset_changed = global_offset_changed;
1683 stall_count = 0;
1684 } else {
1685 stall_count++;
1688 if (terminate_after_phase)
1689 break;
1691 if ((stall_count > nasm_limit[LIMIT_STALLED]) ||
1692 (passn >= nasm_limit[LIMIT_PASSES])) {
1693 /* We get here if the labels don't converge
1694 * Example: FOO equ FOO + 1
1696 nasm_error(ERR_NONFATAL,
1697 "Can't find valid values for all labels "
1698 "after %"PRId64" passes, giving up.", passn);
1699 nasm_error(ERR_NONFATAL,
1700 "Possible causes: recursive EQUs, macro abuse.");
1701 break;
1705 preproc->cleanup(0);
1706 lfmt->cleanup();
1707 if (!terminate_after_phase && opt_verbose_info) {
1708 /* -On and -Ov switches */
1709 fprintf(stdout, "info: assembly required 1+%"PRId64"+1 passes\n",
1710 passn-3);
1715 * gnu style error reporting
1716 * This function prints an error message to error_file in the
1717 * style used by GNU. An example would be:
1718 * file.asm:50: error: blah blah blah
1719 * where file.asm is the name of the file, 50 is the line number on
1720 * which the error occurs (or is detected) and "error:" is one of
1721 * the possible optional diagnostics -- it can be "error" or "warning"
1722 * or something else. Finally the line terminates with the actual
1723 * error message.
1725 * @param severity the severity of the warning or error
1726 * @param fmt the printf style format string
1728 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1730 const char *currentfile = NULL;
1731 int32_t lineno = 0;
1733 if (is_suppressed_warning(severity))
1734 return;
1736 if (!(severity & ERR_NOFILE)) {
1737 src_get(&lineno, &currentfile);
1738 if (!currentfile || (severity & ERR_TOPFILE)) {
1739 currentfile = inname[0] ? inname : outname[0] ? outname : NULL;
1740 lineno = 0;
1744 if (!skip_this_pass(severity)) {
1745 if (!lineno)
1746 fprintf(error_file, "%s:", currentfile ? currentfile : "nasm");
1747 else
1748 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1751 nasm_verror_common(severity, fmt, ap);
1755 * MS style error reporting
1756 * This function prints an error message to error_file in the
1757 * style used by Visual C and some other Microsoft tools. An example
1758 * would be:
1759 * file.asm(50) : error: blah blah blah
1760 * where file.asm is the name of the file, 50 is the line number on
1761 * which the error occurs (or is detected) and "error:" is one of
1762 * the possible optional diagnostics -- it can be "error" or "warning"
1763 * or something else. Finally the line terminates with the actual
1764 * error message.
1766 * @param severity the severity of the warning or error
1767 * @param fmt the printf style format string
1769 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1771 const char *currentfile = NULL;
1772 int32_t lineno = 0;
1774 if (is_suppressed_warning(severity))
1775 return;
1777 if (!(severity & ERR_NOFILE))
1778 src_get(&lineno, &currentfile);
1780 if (!skip_this_pass(severity)) {
1781 if (currentfile) {
1782 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1783 } else {
1784 fputs("nasm: ", error_file);
1788 nasm_verror_common(severity, fmt, ap);
1792 * check to see if this is a suppressable warning
1794 static inline bool is_valid_warning(int severity)
1796 /* Not a warning at all */
1797 if ((severity & ERR_MASK) != ERR_WARNING)
1798 return false;
1800 return WARN_IDX(severity) < ERR_WARN_ALL;
1804 * check for suppressed warning
1805 * checks for suppressed warning or pass one only warning and we're
1806 * not in pass 1
1808 * @param severity the severity of the warning or error
1809 * @return true if we should abort error/warning printing
1811 static bool is_suppressed_warning(int severity)
1813 /* Might be a warning but suppresed explicitly */
1814 if (is_valid_warning(severity) && !(severity & ERR_USAGE))
1815 return !(warning_state[WARN_IDX(severity)] & WARN_ST_ENABLED);
1816 else
1817 return false;
1820 static bool warning_is_error(int severity)
1822 if (is_valid_warning(severity))
1823 return !!(warning_state[WARN_IDX(severity)] & WARN_ST_ERROR);
1824 else
1825 return false;
1828 static bool skip_this_pass(int severity)
1831 * See if it's a pass-specific error or warning which should be skipped.
1832 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1833 * they cannot be resumed from.
1835 if ((severity & ERR_MASK) > ERR_NONFATAL)
1836 return false;
1839 * passn is 1 on the very first pass only.
1840 * pass0 is 2 on the code-generation (final) pass only.
1841 * These are the passes we care about in this case.
1843 return (((severity & ERR_PASS1) && passn != 1) ||
1844 ((severity & ERR_PASS2) && pass0 != 2));
1848 * common error reporting
1849 * This is the common back end of the error reporting schemes currently
1850 * implemented. It prints the nature of the warning and then the
1851 * specific error message to error_file and may or may not return. It
1852 * doesn't return if the error severity is a "panic" or "debug" type.
1854 * @param severity the severity of the warning or error
1855 * @param fmt the printf style format string
1857 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1859 char msg[1024];
1860 const char *pfx;
1862 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1863 case ERR_WARNING:
1864 pfx = "warning: ";
1865 break;
1866 case ERR_NONFATAL:
1867 pfx = "error: ";
1868 break;
1869 case ERR_FATAL:
1870 pfx = "fatal: ";
1871 break;
1872 case ERR_PANIC:
1873 pfx = "panic: ";
1874 break;
1875 case ERR_DEBUG:
1876 pfx = "debug: ";
1877 break;
1878 default:
1879 pfx = "";
1880 break;
1883 vsnprintf(msg, sizeof msg - 64, fmt, args);
1884 if (is_valid_warning(severity) && WARN_IDX(severity) != ERR_WARN_OTHER) {
1885 char *p = strchr(msg, '\0');
1886 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
1889 if (!skip_this_pass(severity))
1890 fprintf(error_file, "%s%s\n", pfx, msg);
1892 /* Are we recursing from error_list_macros? */
1893 if (severity & ERR_PP_LISTMACRO)
1894 return;
1897 * Don't suppress this with skip_this_pass(), or we don't get
1898 * pass1 or preprocessor warnings in the list file
1900 lfmt->error(severity, pfx, msg);
1902 if (skip_this_pass(severity))
1903 return;
1905 if (severity & ERR_USAGE)
1906 want_usage = true;
1908 preproc->error_list_macros(severity);
1910 switch (severity & ERR_MASK) {
1911 case ERR_DEBUG:
1912 /* no further action, by definition */
1913 break;
1914 case ERR_WARNING:
1915 /* Treat warnings as errors */
1916 if (warning_is_error(severity))
1917 terminate_after_phase = true;
1918 break;
1919 case ERR_NONFATAL:
1920 terminate_after_phase = true;
1921 break;
1922 case ERR_FATAL:
1923 if (ofile) {
1924 fclose(ofile);
1925 if (!keep_all)
1926 remove(outname);
1927 ofile = NULL;
1929 if (want_usage)
1930 usage();
1931 exit(1); /* instantly die */
1932 break; /* placate silly compilers */
1933 case ERR_PANIC:
1934 fflush(NULL);
1936 if (abort_on_panic)
1937 abort(); /* halt, catch fire, dump core/stop debugger */
1939 if (ofile) {
1940 fclose(ofile);
1941 if (!keep_all)
1942 remove(outname);
1943 ofile = NULL;
1945 exit(3);
1946 break;
1950 static void usage(void)
1952 fputs("type `nasm -h' for help\n", error_file);
1955 static void help(const char xopt)
1957 int i;
1959 printf
1960 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1961 "[-l listfile]\n"
1962 " [options...] [--] filename\n"
1963 " or nasm -v (or --v) for version info\n\n"
1964 "\n"
1965 "Response files should contain command line parameters,\n"
1966 "one per line.\n"
1967 "\n"
1968 " -t assemble in SciTech TASM compatible mode\n");
1969 printf
1970 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1971 " -a don't preprocess (assemble only)\n"
1972 " -M generate Makefile dependencies on stdout\n"
1973 " -MG d:o, missing files assumed generated\n"
1974 " -MF file set Makefile dependency file\n"
1975 " -MD file assemble and generate dependencies\n"
1976 " -MT file dependency target name\n"
1977 " -MQ file dependency target name (quoted)\n"
1978 " -MP emit phony target\n\n"
1979 " -Zfile redirect error messages to file\n"
1980 " -s redirect error messages to stdout\n\n"
1981 " -g generate debugging information\n\n"
1982 " -F format select a debugging format\n\n"
1983 " -gformat same as -g -F format\n\n"
1984 " -o outfile write output to an outfile\n\n"
1985 " -f format select an output format\n\n"
1986 " -l listfile write listing to a listfile\n\n"
1987 " -Ipath add a pathname to the include file path\n");
1988 printf
1989 (" -Olevel optimize opcodes, immediates and branch offsets\n"
1990 " -O0 no optimization\n"
1991 " -O1 minimal optimization\n"
1992 " -Ox multipass optimization (default)\n"
1993 " -Pfile pre-include a file (also --include)\n"
1994 " -Dmacro[=str] pre-define a macro\n"
1995 " -Umacro undefine a macro\n"
1996 " -Xformat specifiy error reporting format (gnu or vc)\n"
1997 " -w+foo enable warning foo (equiv. -Wfoo)\n"
1998 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
1999 " -w[+-]error[=foo]\n"
2000 " promote [specific] warnings to errors\n"
2001 " -h show invocation summary and exit (also --help)\n\n"
2002 " --pragma str pre-executes a specific %%pragma\n"
2003 " --before str add line (usually a preprocessor statement) before the input\n"
2004 " --prefix str prepend the given string to all the given string\n"
2005 " to all extern, common and global symbols (also --gprefix)\n"
2006 " --postfix str append the given string to all the given string\n"
2007 " to all extern, common and global symbols (also --gpostfix)\n"
2008 " --lprefix str prepend the given string to all other symbols\n"
2009 " --lpostfix str append the given string to all other symbols\n"
2010 " --keep-all output files will not be removed even if an error happens\n"
2011 " --limit-X val set execution limit X\n");
2013 for (i = 0; i <= LIMIT_MAX; i++) {
2014 printf(" %-15s %s (default ",
2015 limit_info[i].name, limit_info[i].help);
2016 if (nasm_limit[i] < LIMIT_MAX_VAL) {
2017 printf("%"PRId64")\n", nasm_limit[i]);
2018 } else {
2019 printf("unlimited)\n");
2023 printf("\nWarnings for the -W/-w options:\n");
2025 for (i = 0; i <= ERR_WARN_ALL; i++)
2026 printf(" %-23s %s%s\n",
2027 warnings[i].name, warnings[i].help,
2028 i == ERR_WARN_ALL ? "\n" :
2029 warnings[i].enabled ? " (default on)" :
2030 " (default off)");
2032 if (xopt == 'f') {
2033 printf("valid output formats for -f are"
2034 " (`*' denotes default):\n");
2035 ofmt_list(ofmt, stdout);
2036 } else {
2037 printf("For a list of valid output formats, use -hf.\n");
2038 printf("For a list of debug formats, use -f <format> -y.\n");