test: nasm-t -- Add multisection
[nasm.git] / asm / nasm.c
blobce62b39a631d9c0f143536e5a70066be1004b864
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;
138 #define OP_NORMAL (1u << 0)
139 #define OP_PREPROCESS (1u << 1)
140 #define OP_DEPEND (1u << 2)
142 static unsigned int operating_mode;
144 /* Dependency flags */
145 static bool depend_emit_phony = false;
146 static bool depend_missing_ok = false;
147 static const char *depend_target = NULL;
148 static const char *depend_file = NULL;
149 StrList *depend_list;
151 static bool want_usage;
152 static bool terminate_after_phase;
153 bool user_nolist = false;
155 static char *quote_for_pmake(const char *str);
156 static char *quote_for_wmake(const char *str);
157 static char *(*quote_for_make)(const char *) = quote_for_pmake;
160 * Execution limits that can be set via a command-line option or %pragma
163 #define LIMIT_MAX_VAL (INT64_MAX >> 1) /* Effectively unlimited */
165 int64_t nasm_limit[LIMIT_MAX+1] =
166 { LIMIT_MAX_VAL, 1000, 1000000, 1000000, 1000000, 2000000000 };
168 struct limit_info {
169 const char *name;
170 const char *help;
172 static const struct limit_info limit_info[LIMIT_MAX+1] = {
173 { "passes", "total number of passes" },
174 { "stalled-passes", "number of passes without forward progress" },
175 { "macro-levels", "levels of macro expansion"},
176 { "rep", "%rep count" },
177 { "eval", "expression evaluation descent"},
178 { "lines", "total source lines processed"}
181 enum directive_result
182 nasm_set_limit(const char *limit, const char *valstr)
184 int i;
185 int64_t val;
186 bool rn_error;
187 int errlevel;
189 for (i = 0; i <= LIMIT_MAX; i++) {
190 if (!nasm_stricmp(limit, limit_info[i].name))
191 break;
193 if (i > LIMIT_MAX) {
194 if (passn == 0)
195 errlevel = ERR_WARNING|ERR_NOFILE|ERR_USAGE;
196 else
197 errlevel = ERR_WARNING|ERR_PASS1|ERR_WARN_UNKNOWN_PRAGMA;
198 nasm_error(errlevel, "unknown limit: `%s'", limit);
199 return DIRR_ERROR;
202 if (!nasm_stricmp(valstr, "unlimited")) {
203 val = LIMIT_MAX_VAL;
204 } else {
205 val = readnum(valstr, &rn_error);
206 if (rn_error || val < 0) {
207 if (passn == 0)
208 errlevel = ERR_WARNING|ERR_NOFILE|ERR_USAGE;
209 else
210 errlevel = ERR_WARNING|ERR_PASS1|ERR_WARN_BAD_PRAGMA;
211 nasm_error(errlevel, "invalid limit value: `%s'", limit);
212 return DIRR_ERROR;
214 if (val > LIMIT_MAX_VAL)
215 val = LIMIT_MAX_VAL;
218 nasm_limit[i] = val;
219 return DIRR_OK;
222 int64_t switch_segment(int32_t segment)
224 location.segment = segment;
225 if (segment == NO_SEG) {
226 location.offset = absolute.offset;
227 in_absolute = true;
228 } else {
229 location.offset = raa_read(offsets, segment);
230 in_absolute = false;
232 return location.offset;
235 static void set_curr_offs(int64_t l_off)
237 if (in_absolute)
238 absolute.offset = l_off;
239 else
240 offsets = raa_write(offsets, location.segment, l_off);
243 static void increment_offset(int64_t delta)
245 if (unlikely(delta == 0))
246 return;
248 location.offset += delta;
249 set_curr_offs(location.offset);
252 static void nasm_fputs(const char *line, FILE * outfile)
254 if (outfile) {
255 fputs(line, outfile);
256 putc('\n', outfile);
257 } else
258 puts(line);
261 static void define_macros_early(void)
263 const struct compile_time * const oct = &official_compile_time;
264 char temp[128];
266 if (oct->have_local) {
267 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &oct->local);
268 preproc->pre_define(temp);
269 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &oct->local);
270 preproc->pre_define(temp);
271 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &oct->local);
272 preproc->pre_define(temp);
273 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &oct->local);
274 preproc->pre_define(temp);
277 if (oct->have_gm) {
278 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &oct->gm);
279 preproc->pre_define(temp);
280 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &oct->gm);
281 preproc->pre_define(temp);
282 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &oct->gm);
283 preproc->pre_define(temp);
284 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &oct->gm);
285 preproc->pre_define(temp);
288 if (oct->have_posix) {
289 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, oct->posix);
290 preproc->pre_define(temp);
294 static void define_macros_late(void)
296 char temp[128];
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 static void emit_dependencies(StrList *list)
310 FILE *deps;
311 int linepos, len;
312 bool wmake = (quote_for_make == quote_for_wmake);
313 const char *wrapstr, *nulltarget;
314 struct strlist_entry *l;
316 if (!list)
317 return;
319 wrapstr = wmake ? " &\n " : " \\\n ";
320 nulltarget = wmake ? "\t%null\n" : "";
322 if (depend_file && strcmp(depend_file, "-")) {
323 deps = nasm_open_write(depend_file, NF_TEXT);
324 if (!deps) {
325 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
326 "unable to write dependency file `%s'", depend_file);
327 return;
329 } else {
330 deps = stdout;
333 linepos = fprintf(deps, "%s :", depend_target);
334 list_for_each(l, list->head) {
335 char *file = quote_for_make(l->str);
336 len = strlen(file);
337 if (linepos + len > 62 && linepos > 1) {
338 fputs(wrapstr, deps);
339 linepos = 1;
341 fprintf(deps, " %s", file);
342 linepos += len+1;
343 nasm_free(file);
345 fprintf(deps, "\n\n");
347 list_for_each(l, list->head) {
348 if (depend_emit_phony) {
349 char *file = quote_for_make(l->str);
350 fprintf(deps, "%s :\n%s\n", file, nulltarget);
351 nasm_free(file);
355 strlist_free(list);
357 if (deps != stdout)
358 fclose(deps);
361 /* Convert a struct tm to a POSIX-style time constant */
362 static int64_t make_posix_time(const struct tm *tm)
364 int64_t t;
365 int64_t y = tm->tm_year;
367 /* See IEEE 1003.1:2004, section 4.14 */
369 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
370 t += tm->tm_yday;
371 t *= 24;
372 t += tm->tm_hour;
373 t *= 60;
374 t += tm->tm_min;
375 t *= 60;
376 t += tm->tm_sec;
378 return t;
381 static void timestamp(void)
383 struct compile_time * const oct = &official_compile_time;
384 const struct tm *tp, *best_gm;
386 time(&oct->t);
388 best_gm = NULL;
390 tp = localtime(&oct->t);
391 if (tp) {
392 oct->local = *tp;
393 best_gm = &oct->local;
394 oct->have_local = true;
397 tp = gmtime(&oct->t);
398 if (tp) {
399 oct->gm = *tp;
400 best_gm = &oct->gm;
401 oct->have_gm = true;
402 if (!oct->have_local)
403 oct->local = oct->gm;
404 } else {
405 oct->gm = oct->local;
408 if (best_gm) {
409 oct->posix = make_posix_time(best_gm);
410 oct->have_posix = true;
414 int main(int argc, char **argv)
416 timestamp();
418 iflag_set_default_cpu(&cpu);
419 iflag_set_default_cpu(&cmd_cpu);
421 pass0 = 0;
422 want_usage = terminate_after_phase = false;
423 nasm_set_verror(nasm_verror_gnu);
425 error_file = stderr;
427 tolower_init();
428 src_init();
431 * We must call init_labels() before the command line parsing,
432 * because we may be setting prefixes/suffixes from the command
433 * line.
435 init_labels();
437 offsets = raa_init();
438 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
440 preproc = &nasmpp;
441 operating_mode = OP_NORMAL;
443 parse_cmdline(argc, argv, 1);
444 if (terminate_after_phase) {
445 if (want_usage)
446 usage();
447 return 1;
451 * Define some macros dependent on the runtime, but not
452 * on the command line (as those are scanned in cmdline pass 2.)
454 preproc->init();
455 define_macros_early();
457 parse_cmdline(argc, argv, 2);
458 if (terminate_after_phase) {
459 if (want_usage)
460 usage();
461 return 1;
464 /* Save away the default state of warnings */
465 memcpy(warning_state_init, warning_state, sizeof warning_state);
467 if (!using_debug_info) {
468 /* No debug info, redirect to the null backend (empty stubs) */
469 dfmt = &null_debug_form;
470 } else if (!debug_format) {
471 /* Default debug format for this backend */
472 dfmt = ofmt->default_dfmt;
473 } else {
474 dfmt = dfmt_find(ofmt, debug_format);
475 if (!dfmt) {
476 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
477 "unrecognized debug format `%s' for"
478 " output format `%s'",
479 debug_format, ofmt->shortname);
483 if (ofmt->stdmac)
484 preproc->extra_stdmac(ofmt->stdmac);
487 * If no output file name provided and this
488 * is a preprocess mode, we're perfectly
489 * fine to output into stdout.
491 if (!outname) {
492 if (!(operating_mode & OP_PREPROCESS))
493 outname = filename_set_extension(inname, ofmt->extension);
496 /* define some macros dependent of command-line */
497 define_macros_late();
499 if (depend_file || (operating_mode & OP_DEPEND))
500 depend_list = strlist_allocate();
502 if (!depend_target)
503 depend_target = quote_for_make(outname);
505 if (operating_mode & OP_DEPEND) {
506 char *line;
508 if (depend_missing_ok)
509 preproc->include_path(NULL); /* "assume generated" */
511 preproc->reset(inname, 0, depend_list);
512 ofile = NULL;
513 while ((line = preproc->getline()))
514 nasm_free(line);
515 preproc->cleanup(0);
516 } else if (operating_mode & OP_PREPROCESS) {
517 char *line;
518 const char *file_name = NULL;
519 int32_t prior_linnum = 0;
520 int lineinc = 0;
522 if (outname) {
523 ofile = nasm_open_write(outname, NF_TEXT);
524 if (!ofile)
525 nasm_fatal_fl(ERR_NOFILE,
526 "unable to open output file `%s'",
527 outname);
528 } else
529 ofile = NULL;
531 location.known = false;
533 /* pass = 1; */
534 preproc->reset(inname, 3, depend_list);
536 /* Revert all warnings to the default state */
537 memcpy(warning_state, warning_state_init, sizeof warning_state);
539 while ((line = preproc->getline())) {
541 * We generate %line directives if needed for later programs
543 int32_t linnum = prior_linnum += lineinc;
544 int altline = src_get(&linnum, &file_name);
545 if (altline) {
546 if (altline == 1 && lineinc == 1)
547 nasm_fputs("", ofile);
548 else {
549 lineinc = (altline != -1 || lineinc != 1);
550 fprintf(ofile ? ofile : stdout,
551 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
552 file_name);
554 prior_linnum = linnum;
556 nasm_fputs(line, ofile);
557 nasm_free(line);
559 preproc->cleanup(0);
560 if (ofile)
561 fclose(ofile);
562 if (ofile && terminate_after_phase && !keep_all)
563 remove(outname);
564 ofile = NULL;
567 if (operating_mode & OP_NORMAL) {
568 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
569 if (!ofile)
570 nasm_fatal_fl(ERR_NOFILE,
571 "unable to open output file `%s'", outname);
573 ofmt->init();
574 dfmt->init();
576 assemble_file(inname, depend_list);
578 if (!terminate_after_phase) {
579 ofmt->cleanup();
580 cleanup_labels();
581 fflush(ofile);
582 if (ferror(ofile)) {
583 nasm_error(ERR_NONFATAL|ERR_NOFILE,
584 "write error on output file `%s'", outname);
585 terminate_after_phase = true;
589 if (ofile) {
590 fclose(ofile);
591 if (terminate_after_phase && !keep_all)
592 remove(outname);
593 ofile = NULL;
597 if (depend_list && !terminate_after_phase)
598 emit_dependencies(depend_list);
600 if (want_usage)
601 usage();
603 raa_free(offsets);
604 saa_free(forwrefs);
605 eval_cleanup();
606 stdscan_cleanup();
607 src_free();
609 return terminate_after_phase;
613 * Get a parameter for a command line option.
614 * First arg must be in the form of e.g. -f...
616 static char *get_param(char *p, char *q, bool *advance)
618 *advance = false;
619 if (p[2]) /* the parameter's in the option */
620 return nasm_skip_spaces(p + 2);
621 if (q && q[0]) {
622 *advance = true;
623 return q;
625 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
626 "option `-%c' requires an argument", p[1]);
627 return NULL;
631 * Copy a filename
633 static void copy_filename(const char **dst, const char *src, const char *what)
635 if (*dst)
636 nasm_fatal("more than one %s file specified: %s\n", what, src);
638 *dst = nasm_strdup(src);
642 * Convert a string to a POSIX make-safe form
644 static char *quote_for_pmake(const char *str)
646 const char *p;
647 char *os, *q;
649 size_t n = 1; /* Terminating zero */
650 size_t nbs = 0;
652 if (!str)
653 return NULL;
655 for (p = str; *p; p++) {
656 switch (*p) {
657 case ' ':
658 case '\t':
659 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
660 n += nbs + 2;
661 nbs = 0;
662 break;
663 case '$':
664 case '#':
665 nbs = 0;
666 n += 2;
667 break;
668 case '\\':
669 nbs++;
670 n++;
671 break;
672 default:
673 nbs = 0;
674 n++;
675 break;
679 /* Convert N backslashes at the end of filename to 2N backslashes */
680 if (nbs)
681 n += nbs;
683 os = q = nasm_malloc(n);
685 nbs = 0;
686 for (p = str; *p; p++) {
687 switch (*p) {
688 case ' ':
689 case '\t':
690 while (nbs--)
691 *q++ = '\\';
692 *q++ = '\\';
693 *q++ = *p;
694 break;
695 case '$':
696 *q++ = *p;
697 *q++ = *p;
698 nbs = 0;
699 break;
700 case '#':
701 *q++ = '\\';
702 *q++ = *p;
703 nbs = 0;
704 break;
705 case '\\':
706 *q++ = *p;
707 nbs++;
708 break;
709 default:
710 *q++ = *p;
711 nbs = 0;
712 break;
715 while (nbs--)
716 *q++ = '\\';
718 *q = '\0';
720 return os;
724 * Convert a string to a Watcom make-safe form
726 static char *quote_for_wmake(const char *str)
728 const char *p;
729 char *os, *q;
730 bool quote = false;
732 size_t n = 1; /* Terminating zero */
734 if (!str)
735 return NULL;
737 for (p = str; *p; p++) {
738 switch (*p) {
739 case ' ':
740 case '\t':
741 case '&':
742 quote = true;
743 n++;
744 break;
745 case '\"':
746 quote = true;
747 n += 2;
748 break;
749 case '$':
750 case '#':
751 n += 2;
752 break;
753 default:
754 n++;
755 break;
759 if (quote)
760 n += 2;
762 os = q = nasm_malloc(n);
764 if (quote)
765 *q++ = '\"';
767 for (p = str; *p; p++) {
768 switch (*p) {
769 case '$':
770 case '#':
771 *q++ = '$';
772 *q++ = *p;
773 break;
774 case '\"':
775 *q++ = *p;
776 *q++ = *p;
777 break;
778 default:
779 *q++ = *p;
780 break;
784 if (quote)
785 *q++ = '\"';
787 *q = '\0';
789 return os;
792 enum text_options {
793 OPT_BOGUS,
794 OPT_VERSION,
795 OPT_HELP,
796 OPT_ABORT_ON_PANIC,
797 OPT_MANGLE,
798 OPT_INCLUDE,
799 OPT_PRAGMA,
800 OPT_BEFORE,
801 OPT_LIMIT,
802 OPT_KEEP_ALL
804 struct textargs {
805 const char *label;
806 enum text_options opt;
807 bool need_arg;
808 int pvt;
810 static const struct textargs textopts[] = {
811 {"v", OPT_VERSION, false, 0},
812 {"version", OPT_VERSION, false, 0},
813 {"help", OPT_HELP, false, 0},
814 {"abort-on-panic", OPT_ABORT_ON_PANIC, false, 0},
815 {"prefix", OPT_MANGLE, true, LM_GPREFIX},
816 {"postfix", OPT_MANGLE, true, LM_GSUFFIX},
817 {"gprefix", OPT_MANGLE, true, LM_GPREFIX},
818 {"gpostfix", OPT_MANGLE, true, LM_GSUFFIX},
819 {"lprefix", OPT_MANGLE, true, LM_LPREFIX},
820 {"lpostfix", OPT_MANGLE, true, LM_LSUFFIX},
821 {"include", OPT_INCLUDE, true, 0},
822 {"pragma", OPT_PRAGMA, true, 0},
823 {"before", OPT_BEFORE, true, 0},
824 {"limit-", OPT_LIMIT, true, 0},
825 {"keep-all", OPT_KEEP_ALL, false, 0},
826 {NULL, OPT_BOGUS, false, 0}
829 static void show_version(void)
831 printf("NASM version %s compiled on %s%s\n",
832 nasm_version, nasm_date, nasm_compile_options);
833 exit(0);
836 static bool stopoptions = false;
837 static bool process_arg(char *p, char *q, int pass)
839 char *param;
840 bool advance = false;
842 if (!p || !p[0])
843 return false;
845 if (p[0] == '-' && !stopoptions) {
846 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
847 /* These parameters take values */
848 if (!(param = get_param(p, q, &advance)))
849 return advance;
852 switch (p[1]) {
853 case 's':
854 if (pass == 1)
855 error_file = stdout;
856 break;
858 case 'o': /* output file */
859 if (pass == 2)
860 copy_filename(&outname, param, "output");
861 break;
863 case 'f': /* output format */
864 if (pass == 1) {
865 ofmt = ofmt_find(param, &ofmt_alias);
866 if (!ofmt) {
867 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
868 "unrecognised output format `%s' - "
869 "use -hf for a list", param);
872 break;
874 case 'O': /* Optimization level */
875 if (pass == 2) {
876 int opt;
878 if (!*param) {
879 /* Naked -O == -Ox */
880 optimizing.level = MAX_OPTIMIZE;
881 } else {
882 while (*param) {
883 switch (*param) {
884 case '0': case '1': case '2': case '3': case '4':
885 case '5': case '6': case '7': case '8': case '9':
886 opt = strtoul(param, &param, 10);
888 /* -O0 -> optimizing.level == -1, 0.98 behaviour */
889 /* -O1 -> optimizing.level == 0, 0.98.09 behaviour */
890 if (opt < 2)
891 optimizing.level = opt - 1;
892 else
893 optimizing.level = opt;
894 break;
896 case 'v':
897 case '+':
898 param++;
899 opt_verbose_info = true;
900 break;
902 case 'x':
903 param++;
904 optimizing.level = MAX_OPTIMIZE;
905 break;
907 default:
908 nasm_fatal("unknown optimization option -O%c\n",
909 *param);
910 break;
913 if (optimizing.level > MAX_OPTIMIZE)
914 optimizing.level = MAX_OPTIMIZE;
917 break;
919 case 'p': /* pre-include */
920 case 'P':
921 if (pass == 2)
922 preproc->pre_include(param);
923 break;
925 case 'd': /* pre-define */
926 case 'D':
927 if (pass == 2)
928 preproc->pre_define(param);
929 break;
931 case 'u': /* un-define */
932 case 'U':
933 if (pass == 2)
934 preproc->pre_undefine(param);
935 break;
937 case 'i': /* include search path */
938 case 'I':
939 if (pass == 2)
940 preproc->include_path(param);
941 break;
943 case 'l': /* listing file */
944 if (pass == 2)
945 copy_filename(&listname, param, "listing");
946 break;
948 case 'Z': /* error messages file */
949 if (pass == 1)
950 copy_filename(&errname, param, "error");
951 break;
953 case 'F': /* specify debug format */
954 if (pass == 2) {
955 using_debug_info = true;
956 debug_format = param;
958 break;
960 case 'X': /* specify error reporting format */
961 if (pass == 1) {
962 if (nasm_stricmp("vc", param) == 0)
963 nasm_set_verror(nasm_verror_vc);
964 else if (nasm_stricmp("gnu", param) == 0)
965 nasm_set_verror(nasm_verror_gnu);
966 else
967 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
968 "unrecognized error reporting format `%s'",
969 param);
971 break;
973 case 'g':
974 if (pass == 2) {
975 using_debug_info = true;
976 if (p[2])
977 debug_format = nasm_skip_spaces(p + 2);
979 break;
981 case 'h':
982 help(p[2]);
983 exit(0); /* never need usage message here */
984 break;
986 case 'y':
987 printf("\nvalid debug formats for '%s' output format are"
988 " ('*' denotes default):\n", ofmt->shortname);
989 dfmt_list(ofmt, stdout);
990 exit(0);
991 break;
993 case 't':
994 if (pass == 2)
995 tasm_compatible_mode = true;
996 break;
998 case 'v':
999 show_version();
1000 break;
1002 case 'e': /* preprocess only */
1003 case 'E':
1004 if (pass == 1)
1005 operating_mode = OP_PREPROCESS;
1006 break;
1008 case 'a': /* assemble only - don't preprocess */
1009 if (pass == 1)
1010 preproc = &preproc_nop;
1011 break;
1013 case 'w':
1014 case 'W':
1015 if (pass == 2) {
1016 if (!set_warning_status(param)) {
1017 nasm_error(ERR_WARNING|ERR_NOFILE|ERR_WARN_UNK_WARNING,
1018 "unknown warning option: %s", param);
1021 break;
1023 case 'M':
1024 if (pass == 1) {
1025 switch (p[2]) {
1026 case 'W':
1027 quote_for_make = quote_for_wmake;
1028 break;
1029 case 'D':
1030 case 'F':
1031 case 'T':
1032 case 'Q':
1033 advance = true;
1034 break;
1035 default:
1036 break;
1038 } else {
1039 switch (p[2]) {
1040 case 0:
1041 operating_mode = OP_DEPEND;
1042 break;
1043 case 'G':
1044 operating_mode = OP_DEPEND;
1045 depend_missing_ok = true;
1046 break;
1047 case 'P':
1048 depend_emit_phony = true;
1049 break;
1050 case 'D':
1051 operating_mode = OP_NORMAL;
1052 depend_file = q;
1053 advance = true;
1054 break;
1055 case 'F':
1056 depend_file = q;
1057 advance = true;
1058 break;
1059 case 'T':
1060 depend_target = q;
1061 advance = true;
1062 break;
1063 case 'Q':
1064 depend_target = quote_for_make(q);
1065 advance = true;
1066 break;
1067 case 'W':
1068 /* handled in pass 1 */
1069 break;
1070 default:
1071 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1072 "unknown dependency option `-M%c'", p[2]);
1073 break;
1076 if (advance && (!q || !q[0])) {
1077 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
1078 "option `-M%c' requires a parameter", p[2]);
1079 break;
1081 break;
1083 case '-':
1085 const struct textargs *tx;
1086 size_t olen, plen;
1087 char *eqsave;
1089 p += 2;
1091 if (!*p) { /* -- => stop processing options */
1092 stopoptions = true;
1093 break;
1096 plen = strlen(p);
1097 for (tx = textopts; tx->label; tx++) {
1098 olen = strlen(tx->label);
1100 if (olen > plen)
1101 continue;
1103 if (nasm_memicmp(p, tx->label, olen))
1104 continue;
1106 if (tx->label[olen-1] == '-')
1107 break; /* Incomplete option */
1109 if (!p[olen] || p[olen] == '=')
1110 break; /* Complete option */
1113 if (!tx->label) {
1114 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1115 "unrecognized option `--%s'", p);
1118 eqsave = param = strchr(p+olen, '=');
1119 if (param)
1120 *param++ = '\0';
1122 if (tx->need_arg) {
1123 if (!param) {
1124 param = q;
1125 advance = true;
1128 /* Note: a null string is a valid parameter */
1129 if (!param) {
1130 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1131 "option `--%s' requires an argument",
1133 break;
1135 } else {
1136 if (param) {
1137 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1138 "option `--%s' does not take an argument",
1144 switch (tx->opt) {
1145 case OPT_VERSION:
1146 show_version();
1147 break;
1148 case OPT_ABORT_ON_PANIC:
1149 abort_on_panic = true;
1150 break;
1151 case OPT_MANGLE:
1152 if (pass == 2)
1153 set_label_mangle(tx->pvt, param);
1154 break;
1155 case OPT_INCLUDE:
1156 if (pass == 2)
1157 preproc->pre_include(q);
1158 break;
1159 case OPT_PRAGMA:
1160 if (pass == 2)
1161 preproc->pre_command("pragma", param);
1162 break;
1163 case OPT_BEFORE:
1164 if (pass == 2)
1165 preproc->pre_command(NULL, param);
1166 break;
1167 case OPT_LIMIT:
1168 if (pass == 2)
1169 nasm_set_limit(p+olen, param);
1170 break;
1171 case OPT_KEEP_ALL:
1172 keep_all = true;
1173 break;
1174 case OPT_HELP:
1175 help(0);
1176 exit(0);
1177 default:
1178 panic();
1181 if (eqsave)
1182 *eqsave = '='; /* Restore = argument separator */
1184 break;
1187 default:
1188 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1189 "unrecognised option `-%c'", p[1]);
1190 break;
1192 } else if (pass == 2) {
1193 /* In theory we could allow multiple input files... */
1194 copy_filename(&inname, p, "input");
1197 return advance;
1200 #define ARG_BUF_DELTA 128
1202 static void process_respfile(FILE * rfile, int pass)
1204 char *buffer, *p, *q, *prevarg;
1205 int bufsize, prevargsize;
1207 bufsize = prevargsize = ARG_BUF_DELTA;
1208 buffer = nasm_malloc(ARG_BUF_DELTA);
1209 prevarg = nasm_malloc(ARG_BUF_DELTA);
1210 prevarg[0] = '\0';
1212 while (1) { /* Loop to handle all lines in file */
1213 p = buffer;
1214 while (1) { /* Loop to handle long lines */
1215 q = fgets(p, bufsize - (p - buffer), rfile);
1216 if (!q)
1217 break;
1218 p += strlen(p);
1219 if (p > buffer && p[-1] == '\n')
1220 break;
1221 if (p - buffer > bufsize - 10) {
1222 int offset;
1223 offset = p - buffer;
1224 bufsize += ARG_BUF_DELTA;
1225 buffer = nasm_realloc(buffer, bufsize);
1226 p = buffer + offset;
1230 if (!q && p == buffer) {
1231 if (prevarg[0])
1232 process_arg(prevarg, NULL, pass);
1233 nasm_free(buffer);
1234 nasm_free(prevarg);
1235 return;
1239 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1240 * them are present at the end of the line.
1242 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1244 while (p > buffer && nasm_isspace(p[-1]))
1245 *--p = '\0';
1247 p = nasm_skip_spaces(buffer);
1249 if (process_arg(prevarg, p, pass))
1250 *p = '\0';
1252 if ((int) strlen(p) > prevargsize - 10) {
1253 prevargsize += ARG_BUF_DELTA;
1254 prevarg = nasm_realloc(prevarg, prevargsize);
1256 strncpy(prevarg, p, prevargsize);
1260 /* Function to process args from a string of args, rather than the
1261 * argv array. Used by the environment variable and response file
1262 * processing.
1264 static void process_args(char *args, int pass)
1266 char *p, *q, *arg, *prevarg;
1267 char separator = ' ';
1269 p = args;
1270 if (*p && *p != '-')
1271 separator = *p++;
1272 arg = NULL;
1273 while (*p) {
1274 q = p;
1275 while (*p && *p != separator)
1276 p++;
1277 while (*p == separator)
1278 *p++ = '\0';
1279 prevarg = arg;
1280 arg = q;
1281 if (process_arg(prevarg, arg, pass))
1282 arg = NULL;
1284 if (arg)
1285 process_arg(arg, NULL, pass);
1288 static void process_response_file(const char *file, int pass)
1290 char str[2048];
1291 FILE *f = nasm_open_read(file, NF_TEXT);
1292 if (!f) {
1293 perror(file);
1294 exit(-1);
1296 while (fgets(str, sizeof str, f)) {
1297 process_args(str, pass);
1299 fclose(f);
1302 static void parse_cmdline(int argc, char **argv, int pass)
1304 FILE *rfile;
1305 char *envreal, *envcopy = NULL, *p;
1306 int i;
1308 /* Initialize all the warnings to their default state */
1309 for (i = 0; i < ERR_WARN_ALL; i++) {
1310 warning_state_init[i] = warning_state[i] =
1311 warnings[i].enabled ? WARN_ST_ENABLED : 0;
1315 * First, process the NASMENV environment variable.
1317 envreal = getenv("NASMENV");
1318 if (envreal) {
1319 envcopy = nasm_strdup(envreal);
1320 process_args(envcopy, pass);
1321 nasm_free(envcopy);
1325 * Now process the actual command line.
1327 while (--argc) {
1328 bool advance;
1329 argv++;
1330 if (argv[0][0] == '@') {
1332 * We have a response file, so process this as a set of
1333 * arguments like the environment variable. This allows us
1334 * to have multiple arguments on a single line, which is
1335 * different to the -@resp file processing below for regular
1336 * NASM.
1338 process_response_file(argv[0]+1, pass);
1339 argc--;
1340 argv++;
1342 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1343 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1344 if (p) {
1345 rfile = nasm_open_read(p, NF_TEXT);
1346 if (rfile) {
1347 process_respfile(rfile, pass);
1348 fclose(rfile);
1349 } else
1350 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1351 "unable to open response file `%s'", p);
1353 } else
1354 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1355 argv += advance, argc -= advance;
1359 * Look for basic command line typos. This definitely doesn't
1360 * catch all errors, but it might help cases of fumbled fingers.
1362 if (pass != 2)
1363 return;
1365 if (!inname)
1366 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE, "no input file specified");
1368 else if ((errname && !strcmp(inname, errname)) ||
1369 (outname && !strcmp(inname, outname)) ||
1370 (listname && !strcmp(inname, listname)) ||
1371 (depend_file && !strcmp(inname, depend_file)))
1372 nasm_fatal_fl(ERR_USAGE, "will not overwrite input file");
1374 if (errname) {
1375 error_file = nasm_open_write(errname, NF_TEXT);
1376 if (!error_file) {
1377 error_file = stderr; /* Revert to default! */
1378 nasm_fatal_fl(ERR_NOFILE | ERR_USAGE,
1379 "cannot open file `%s' for error messages",
1380 errname);
1385 static void assemble_file(const char *fname, StrList *depend_list)
1387 char *line;
1388 insn output_ins;
1389 int i;
1390 uint64_t prev_offset_changed;
1391 int64_t stall_count = 0; /* Make sure we make forward progress... */
1393 switch (cmd_sb) {
1394 case 16:
1395 break;
1396 case 32:
1397 if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))
1398 nasm_fatal("command line: 32-bit segment size requires a higher cpu");
1399 break;
1400 case 64:
1401 if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))
1402 nasm_fatal("command line: 64-bit segment size requires a higher cpu");
1403 break;
1404 default:
1405 panic();
1406 break;
1409 prev_offset_changed = nasm_limit[LIMIT_PASSES];
1410 for (passn = 1; pass0 <= 2; passn++) {
1411 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1412 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1413 /* pass0 0, 0, 0, ..., 1, 2 */
1415 globalbits = cmd_sb; /* set 'bits' to command line default */
1416 cpu = cmd_cpu;
1417 if (pass0 == 2) {
1418 lfmt->init(listname);
1419 } else if (passn == 1 && listname && !keep_all) {
1420 /* Remove the list file in case we die before the output pass */
1421 remove(listname);
1423 in_absolute = false;
1424 global_offset_changed = 0; /* set by redefine_label */
1425 if (passn > 1) {
1426 saa_rewind(forwrefs);
1427 forwref = saa_rstruct(forwrefs);
1428 raa_free(offsets);
1429 offsets = raa_init();
1431 location.segment = NO_SEG;
1432 location.offset = 0;
1433 if (passn == 1)
1434 location.known = true;
1435 ofmt->reset();
1436 switch_segment(ofmt->section(NULL, pass2, &globalbits));
1437 preproc->reset(fname, pass1, pass1 == 2 ? depend_list : NULL);
1439 /* Revert all warnings to the default state */
1440 memcpy(warning_state, warning_state_init, sizeof warning_state);
1442 globallineno = 0;
1444 while ((line = preproc->getline())) {
1445 if (++globallineno > nasm_limit[LIMIT_LINES])
1446 nasm_fatal("overall line count exceeds the maximum %"PRId64"\n",
1447 nasm_limit[LIMIT_LINES]);
1450 * Here we parse our directives; this is not handled by the
1451 * main parser.
1453 if (process_directives(line))
1454 goto end_of_line; /* Just do final cleanup */
1456 /* Not a directive, or even something that starts with [ */
1457 parse_line(pass1, line, &output_ins);
1459 if (optimizing.level > 0) {
1460 if (forwref != NULL && globallineno == forwref->lineno) {
1461 output_ins.forw_ref = true;
1462 do {
1463 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1464 forwref = saa_rstruct(forwrefs);
1465 } while (forwref != NULL
1466 && forwref->lineno == globallineno);
1467 } else
1468 output_ins.forw_ref = false;
1470 if (output_ins.forw_ref) {
1471 if (passn == 1) {
1472 for (i = 0; i < output_ins.operands; i++) {
1473 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1474 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1475 fwinf->lineno = globallineno;
1476 fwinf->operand = i;
1483 /* forw_ref */
1484 if (output_ins.opcode == I_EQU) {
1485 if (!output_ins.label) {
1486 nasm_error(ERR_NONFATAL, "EQU not preceded by label");
1487 } else if (output_ins.operands == 1 &&
1488 (output_ins.oprs[0].type & IMMEDIATE) &&
1489 output_ins.oprs[0].wrt == NO_SEG) {
1490 define_label(output_ins.label,
1491 output_ins.oprs[0].segment,
1492 output_ins.oprs[0].offset, false);
1493 } else if (output_ins.operands == 2
1494 && (output_ins.oprs[0].type & IMMEDIATE)
1495 && (output_ins.oprs[0].type & COLON)
1496 && output_ins.oprs[0].segment == NO_SEG
1497 && output_ins.oprs[0].wrt == NO_SEG
1498 && (output_ins.oprs[1].type & IMMEDIATE)
1499 && output_ins.oprs[1].segment == NO_SEG
1500 && output_ins.oprs[1].wrt == NO_SEG) {
1501 define_label(output_ins.label,
1502 output_ins.oprs[0].offset | SEG_ABS,
1503 output_ins.oprs[1].offset, false);
1504 } else {
1505 nasm_error(ERR_NONFATAL, "bad syntax for EQU");
1507 } else { /* instruction isn't an EQU */
1508 int32_t n;
1510 nasm_assert(output_ins.times >= 0);
1512 for (n = 1; n <= output_ins.times; n++) {
1513 if (pass1 == 1) {
1514 int64_t l = insn_size(location.segment,
1515 location.offset,
1516 globalbits, &output_ins);
1518 /* if (using_debug_info) && output_ins.opcode != -1) */
1519 if (using_debug_info)
1520 { /* fbk 03/25/01 */
1521 /* this is done here so we can do debug type info */
1522 int32_t typeinfo =
1523 TYS_ELEMENTS(output_ins.operands);
1524 switch (output_ins.opcode) {
1525 case I_RESB:
1526 typeinfo =
1527 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1528 break;
1529 case I_RESW:
1530 typeinfo =
1531 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1532 break;
1533 case I_RESD:
1534 typeinfo =
1535 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1536 break;
1537 case I_RESQ:
1538 typeinfo =
1539 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1540 break;
1541 case I_REST:
1542 typeinfo =
1543 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1544 break;
1545 case I_RESO:
1546 typeinfo =
1547 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1548 break;
1549 case I_RESY:
1550 typeinfo =
1551 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1552 break;
1553 case I_RESZ:
1554 typeinfo =
1555 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;
1556 break;
1557 case I_DB:
1558 typeinfo |= TY_BYTE;
1559 break;
1560 case I_DW:
1561 typeinfo |= TY_WORD;
1562 break;
1563 case I_DD:
1564 if (output_ins.eops_float)
1565 typeinfo |= TY_FLOAT;
1566 else
1567 typeinfo |= TY_DWORD;
1568 break;
1569 case I_DQ:
1570 typeinfo |= TY_QWORD;
1571 break;
1572 case I_DT:
1573 typeinfo |= TY_TBYTE;
1574 break;
1575 case I_DO:
1576 typeinfo |= TY_OWORD;
1577 break;
1578 case I_DY:
1579 typeinfo |= TY_YWORD;
1580 break;
1581 case I_DZ:
1582 typeinfo |= TY_ZWORD;
1583 break;
1584 default:
1585 typeinfo = TY_LABEL;
1586 break;
1589 dfmt->debug_typevalue(typeinfo);
1593 * For INCBIN, let the code in assemble
1594 * handle TIMES, so we don't have to read the
1595 * input file over and over.
1597 if (l != -1) {
1598 increment_offset(l);
1601 * else l == -1 => invalid instruction, which will be
1602 * flagged as an error on pass 2
1604 } else {
1605 if (n == 2)
1606 lfmt->uplevel(LIST_TIMES);
1607 increment_offset(assemble(location.segment,
1608 location.offset,
1609 globalbits, &output_ins));
1611 } /* not an EQU */
1613 if (output_ins.times > 1)
1614 lfmt->downlevel(LIST_TIMES);
1616 cleanup_insn(&output_ins);
1618 end_of_line:
1619 nasm_free(line);
1620 } /* end while (line = preproc->getline... */
1622 if (global_offset_changed && !terminate_after_phase) {
1623 switch (pass0) {
1624 case 1:
1625 nasm_error(ERR_WARNING|ERR_WARN_PHASE,
1626 "phase error during stabilization pass, hoping for the best");
1627 break;
1629 case 2:
1630 nasm_error(ERR_NONFATAL,
1631 "phase error during code generation pass");
1632 break;
1634 default:
1635 /* This is normal, we'll keep going... */
1636 break;
1640 if (pass1 == 1)
1641 preproc->cleanup(1);
1644 * Always run at least two optimization passes (pass0 == 0);
1645 * things like subsections will fail miserably without that.
1646 * Once we commit to a stabilization pass (pass0 == 1), we can't
1647 * go back, and if something goes bad, we can only hope
1648 * that we don't end up with a phase error at the end.
1650 if ((passn > 1 && !global_offset_changed) || pass0 > 0) {
1651 pass0++;
1652 } else if (global_offset_changed &&
1653 global_offset_changed < prev_offset_changed) {
1654 prev_offset_changed = global_offset_changed;
1655 stall_count = 0;
1656 } else {
1657 stall_count++;
1660 if (terminate_after_phase)
1661 break;
1663 if ((stall_count > nasm_limit[LIMIT_STALLED]) ||
1664 (passn >= nasm_limit[LIMIT_PASSES])) {
1665 /* We get here if the labels don't converge
1666 * Example: FOO equ FOO + 1
1668 nasm_error(ERR_NONFATAL,
1669 "Can't find valid values for all labels "
1670 "after %"PRId64" passes, giving up.", passn);
1671 nasm_error(ERR_NONFATAL,
1672 "Possible causes: recursive EQUs, macro abuse.");
1673 break;
1677 preproc->cleanup(0);
1678 lfmt->cleanup();
1679 if (!terminate_after_phase && opt_verbose_info) {
1680 /* -On and -Ov switches */
1681 fprintf(stdout, "info: assembly required 1+%"PRId64"+1 passes\n",
1682 passn-3);
1687 * gnu style error reporting
1688 * This function prints an error message to error_file in the
1689 * style used by GNU. An example would be:
1690 * file.asm:50: error: blah blah blah
1691 * where file.asm is the name of the file, 50 is the line number on
1692 * which the error occurs (or is detected) and "error:" is one of
1693 * the possible optional diagnostics -- it can be "error" or "warning"
1694 * or something else. Finally the line terminates with the actual
1695 * error message.
1697 * @param severity the severity of the warning or error
1698 * @param fmt the printf style format string
1700 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1702 const char *currentfile = NULL;
1703 int32_t lineno = 0;
1705 if (is_suppressed_warning(severity))
1706 return;
1708 if (!(severity & ERR_NOFILE)) {
1709 src_get(&lineno, &currentfile);
1710 if (!currentfile || (severity & ERR_TOPFILE)) {
1711 currentfile = inname[0] ? inname : outname[0] ? outname : NULL;
1712 lineno = 0;
1716 if (!skip_this_pass(severity)) {
1717 if (!lineno)
1718 fprintf(error_file, "%s:", currentfile ? currentfile : "nasm");
1719 else
1720 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1723 nasm_verror_common(severity, fmt, ap);
1727 * MS style error reporting
1728 * This function prints an error message to error_file in the
1729 * style used by Visual C and some other Microsoft tools. An example
1730 * would be:
1731 * file.asm(50) : error: blah blah blah
1732 * where file.asm is the name of the file, 50 is the line number on
1733 * which the error occurs (or is detected) and "error:" is one of
1734 * the possible optional diagnostics -- it can be "error" or "warning"
1735 * or something else. Finally the line terminates with the actual
1736 * error message.
1738 * @param severity the severity of the warning or error
1739 * @param fmt the printf style format string
1741 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1743 const char *currentfile = NULL;
1744 int32_t lineno = 0;
1746 if (is_suppressed_warning(severity))
1747 return;
1749 if (!(severity & ERR_NOFILE))
1750 src_get(&lineno, &currentfile);
1752 if (!skip_this_pass(severity)) {
1753 if (currentfile) {
1754 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1755 } else {
1756 fputs("nasm: ", error_file);
1760 nasm_verror_common(severity, fmt, ap);
1764 * check to see if this is a suppressable warning
1766 static inline bool is_valid_warning(int severity)
1768 /* Not a warning at all */
1769 if ((severity & ERR_MASK) != ERR_WARNING)
1770 return false;
1772 return WARN_IDX(severity) < ERR_WARN_ALL;
1776 * check for suppressed warning
1777 * checks for suppressed warning or pass one only warning and we're
1778 * not in pass 1
1780 * @param severity the severity of the warning or error
1781 * @return true if we should abort error/warning printing
1783 static bool is_suppressed_warning(int severity)
1785 /* Might be a warning but suppresed explicitly */
1786 if (is_valid_warning(severity) && !(severity & ERR_USAGE))
1787 return !(warning_state[WARN_IDX(severity)] & WARN_ST_ENABLED);
1788 else
1789 return false;
1792 static bool warning_is_error(int severity)
1794 if (is_valid_warning(severity))
1795 return !!(warning_state[WARN_IDX(severity)] & WARN_ST_ERROR);
1796 else
1797 return false;
1800 static bool skip_this_pass(int severity)
1803 * See if it's a pass-specific error or warning which should be skipped.
1804 * We cannot skip errors stronger than ERR_NONFATAL as by definition
1805 * they cannot be resumed from.
1807 if ((severity & ERR_MASK) > ERR_NONFATAL)
1808 return false;
1811 * passn is 1 on the very first pass only.
1812 * pass0 is 2 on the code-generation (final) pass only.
1813 * These are the passes we care about in this case.
1815 return (((severity & ERR_PASS1) && passn != 1) ||
1816 ((severity & ERR_PASS2) && pass0 != 2));
1820 * common error reporting
1821 * This is the common back end of the error reporting schemes currently
1822 * implemented. It prints the nature of the warning and then the
1823 * specific error message to error_file and may or may not return. It
1824 * doesn't return if the error severity is a "panic" or "debug" type.
1826 * @param severity the severity of the warning or error
1827 * @param fmt the printf style format string
1829 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1831 char msg[1024];
1832 const char *pfx;
1834 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1835 case ERR_WARNING:
1836 pfx = "warning: ";
1837 break;
1838 case ERR_NONFATAL:
1839 pfx = "error: ";
1840 break;
1841 case ERR_FATAL:
1842 pfx = "fatal: ";
1843 break;
1844 case ERR_PANIC:
1845 pfx = "panic: ";
1846 break;
1847 case ERR_DEBUG:
1848 pfx = "debug: ";
1849 break;
1850 default:
1851 pfx = "";
1852 break;
1855 vsnprintf(msg, sizeof msg - 64, fmt, args);
1856 if (is_valid_warning(severity) && WARN_IDX(severity) != ERR_WARN_OTHER) {
1857 char *p = strchr(msg, '\0');
1858 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
1861 if (!skip_this_pass(severity))
1862 fprintf(error_file, "%s%s\n", pfx, msg);
1864 /* Are we recursing from error_list_macros? */
1865 if (severity & ERR_PP_LISTMACRO)
1866 return;
1869 * Don't suppress this with skip_this_pass(), or we don't get
1870 * pass1 or preprocessor warnings in the list file
1872 lfmt->error(severity, pfx, msg);
1874 if (skip_this_pass(severity))
1875 return;
1877 if (severity & ERR_USAGE)
1878 want_usage = true;
1880 preproc->error_list_macros(severity);
1882 switch (severity & ERR_MASK) {
1883 case ERR_DEBUG:
1884 /* no further action, by definition */
1885 break;
1886 case ERR_WARNING:
1887 /* Treat warnings as errors */
1888 if (warning_is_error(severity))
1889 terminate_after_phase = true;
1890 break;
1891 case ERR_NONFATAL:
1892 terminate_after_phase = true;
1893 break;
1894 case ERR_FATAL:
1895 if (ofile) {
1896 fclose(ofile);
1897 if (!keep_all)
1898 remove(outname);
1899 ofile = NULL;
1901 if (want_usage)
1902 usage();
1903 exit(1); /* instantly die */
1904 break; /* placate silly compilers */
1905 case ERR_PANIC:
1906 fflush(NULL);
1908 if (abort_on_panic)
1909 abort(); /* halt, catch fire, dump core/stop debugger */
1911 if (ofile) {
1912 fclose(ofile);
1913 if (!keep_all)
1914 remove(outname);
1915 ofile = NULL;
1917 exit(3);
1918 break;
1922 static void usage(void)
1924 fputs("type `nasm -h' for help\n", error_file);
1927 static void help(const char xopt)
1929 int i;
1931 printf
1932 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
1933 "[-l listfile]\n"
1934 " [options...] [--] filename\n"
1935 " or nasm -v (or --v) for version info\n\n"
1936 "\n"
1937 "Response files should contain command line parameters,\n"
1938 "one per line.\n"
1939 "\n"
1940 " -t assemble in SciTech TASM compatible mode\n");
1941 printf
1942 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
1943 " -a don't preprocess (assemble only)\n"
1944 " -M generate Makefile dependencies on stdout\n"
1945 " -MG d:o, missing files assumed generated\n"
1946 " -MF file set Makefile dependency file\n"
1947 " -MD file assemble and generate dependencies\n"
1948 " -MT file dependency target name\n"
1949 " -MQ file dependency target name (quoted)\n"
1950 " -MP emit phony target\n\n"
1951 " -Zfile redirect error messages to file\n"
1952 " -s redirect error messages to stdout\n\n"
1953 " -g generate debugging information\n\n"
1954 " -F format select a debugging format\n\n"
1955 " -gformat same as -g -F format\n\n"
1956 " -o outfile write output to an outfile\n\n"
1957 " -f format select an output format\n\n"
1958 " -l listfile write listing to a listfile\n\n"
1959 " -Ipath add a pathname to the include file path\n");
1960 printf
1961 (" -Olevel optimize opcodes, immediates and branch offsets\n"
1962 " -O0 no optimization\n"
1963 " -O1 minimal optimization\n"
1964 " -Ox multipass optimization (default)\n"
1965 " -Pfile pre-include a file (also --include)\n"
1966 " -Dmacro[=str] pre-define a macro\n"
1967 " -Umacro undefine a macro\n"
1968 " -Xformat specifiy error reporting format (gnu or vc)\n"
1969 " -w+foo enable warning foo (equiv. -Wfoo)\n"
1970 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
1971 " -w[+-]error[=foo]\n"
1972 " promote [specific] warnings to errors\n"
1973 " -h show invocation summary and exit (also --help)\n\n"
1974 " --pragma str pre-executes a specific %%pragma\n"
1975 " --before str add line (usually a preprocessor statement) before the input\n"
1976 " --prefix str prepend the given string to all the given string\n"
1977 " to all extern, common and global symbols (also --gprefix)\n"
1978 " --postfix str append the given string to all the given string\n"
1979 " to all extern, common and global symbols (also --gpostfix)\n"
1980 " --lprefix str prepend the given string to all other symbols\n"
1981 " --lpostfix str append the given string to all other symbols\n"
1982 " --keep-all output files will not be removed even if an error happens\n"
1983 " --limit-X val set execution limit X\n");
1985 for (i = 0; i <= LIMIT_MAX; i++) {
1986 printf(" %-15s %s (default ",
1987 limit_info[i].name, limit_info[i].help);
1988 if (nasm_limit[i] < LIMIT_MAX_VAL) {
1989 printf("%"PRId64")\n", nasm_limit[i]);
1990 } else {
1991 printf("unlimited)\n");
1995 printf("\nWarnings for the -W/-w options:\n");
1997 for (i = 0; i <= ERR_WARN_ALL; i++)
1998 printf(" %-23s %s%s\n",
1999 warnings[i].name, warnings[i].help,
2000 i == ERR_WARN_ALL ? "\n" :
2001 warnings[i].enabled ? " (default on)" :
2002 " (default off)");
2004 if (xopt == 'f') {
2005 printf("valid output formats for -f are"
2006 " (`*' denotes default):\n");
2007 ofmt_list(ofmt, stdout);
2008 } else {
2009 printf("For a list of valid output formats, use -hf.\n");
2010 printf("For a list of debug formats, use -f <format> -y.\n");