doc: document warning improvements
[nasm.git] / nasm.c
blob3bf98af7cf19cbaa85a807329bb9b9e4a82daee6
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2016 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 <inttypes.h>
46 #include <limits.h>
47 #include <time.h>
49 #include "nasm.h"
50 #include "nasmlib.h"
51 #include "saa.h"
52 #include "raa.h"
53 #include "float.h"
54 #include "stdscan.h"
55 #include "insns.h"
56 #include "preproc.h"
57 #include "parser.h"
58 #include "eval.h"
59 #include "assemble.h"
60 #include "labels.h"
61 #include "output/outform.h"
62 #include "listing.h"
63 #include "iflag.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 int get_bits(char *value);
78 static iflag_t get_cpu(char *cpu_str);
79 static void parse_cmdline(int, char **);
80 static void assemble_file(char *, StrList **);
81 static bool is_suppressed_warning(int severity);
82 static bool skip_this_pass(int severity);
83 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
84 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
85 static void nasm_verror_common(int severity, const char *fmt, va_list args);
86 static void usage(void);
88 static bool using_debug_info, opt_verbose_info;
89 static const char *debug_format;
91 bool tasm_compatible_mode = false;
92 int pass0, passn;
93 int globalrel = 0;
94 int globalbnd = 0;
96 static time_t official_compile_time;
98 static char inname[FILENAME_MAX];
99 static char outname[FILENAME_MAX];
100 static char listname[FILENAME_MAX];
101 static char errname[FILENAME_MAX];
102 static int globallineno; /* for forward-reference tracking */
103 /* static int pass = 0; */
104 struct ofmt *ofmt = &OF_DEFAULT;
105 struct ofmt_alias *ofmt_alias = NULL;
106 const struct dfmt *dfmt;
108 static FILE *error_file; /* Where to write error messages */
110 FILE *ofile = NULL;
111 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
112 static int sb, cmd_sb = 16; /* by default */
114 static iflag_t cpu;
115 static iflag_t cmd_cpu;
117 int64_t global_offset_changed; /* referenced in labels.c */
118 int64_t prev_offset_changed;
119 int32_t stall_count;
121 static struct location location;
122 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
123 int32_t abs_seg; /* ABSOLUTE segment basis */
124 int32_t abs_offset; /* ABSOLUTE offset */
126 static struct RAA *offsets;
128 static struct SAA *forwrefs; /* keep track of forward references */
129 static const struct forwrefinfo *forwref;
131 static const struct preproc_ops *preproc;
133 #define OP_NORMAL (1u << 0)
134 #define OP_PREPROCESS (1u << 1)
135 #define OP_DEPEND (1u << 2)
137 static unsigned int operating_mode;
139 /* Dependency flags */
140 static bool depend_emit_phony = false;
141 static bool depend_missing_ok = false;
142 static const char *depend_target = NULL;
143 static const char *depend_file = NULL;
146 * Which of the suppressible warnings are suppressed. Entry zero
147 * isn't an actual warning, but it used for -w+error/-Werror.
150 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
151 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
153 static const struct warning {
154 const char *name;
155 const char *help;
156 bool enabled;
157 } warnings[ERR_WARN_MAX+1] = {
158 {"error", "treat warnings as errors", false},
159 {"macro-params", "macro calls with wrong parameter count", true},
160 {"macro-selfref", "cyclic macro references", false},
161 {"macro-defaults", "macros with more default than optional parameters", true},
162 {"orphan-labels", "labels alone on lines without trailing `:'", true},
163 {"number-overflow", "numeric constant does not fit", true},
164 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
165 {"float-overflow", "floating point overflow", true},
166 {"float-denorm", "floating point denormal", false},
167 {"float-underflow", "floating point underflow", false},
168 {"float-toolong", "too many digits in floating-point number", true},
169 {"user", "%warning directives", true},
170 {"lock", "lock prefix on unlockable instructions", true},
171 {"hle", "invalid hle prefixes", true},
172 {"bnd", "invalid bnd prefixes", true},
173 {"zext-reloc", "relocation zero-extended to match output format", true},
174 {"ptr", "non-NASM keyword used in other assemblers", true},
177 static bool want_usage;
178 static bool terminate_after_phase;
179 bool user_nolist = false;
181 static char *quote_for_make(const char *str);
183 static int64_t get_curr_offs(void)
185 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
188 static void set_curr_offs(int64_t l_off)
190 if (in_abs_seg)
191 abs_offset = l_off;
192 else
193 offsets = raa_write(offsets, location.segment, l_off);
196 static void nasm_fputs(const char *line, FILE * outfile)
198 if (outfile) {
199 fputs(line, outfile);
200 putc('\n', outfile);
201 } else
202 puts(line);
205 /* Convert a struct tm to a POSIX-style time constant */
206 static int64_t make_posix_time(struct tm *tm)
208 int64_t t;
209 int64_t y = tm->tm_year;
211 /* See IEEE 1003.1:2004, section 4.14 */
213 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
214 t += tm->tm_yday;
215 t *= 24;
216 t += tm->tm_hour;
217 t *= 60;
218 t += tm->tm_min;
219 t *= 60;
220 t += tm->tm_sec;
222 return t;
225 static void define_macros_early(void)
227 char temp[128];
228 struct tm lt, *lt_p, gm, *gm_p;
229 int64_t posix_time;
231 lt_p = localtime(&official_compile_time);
232 if (lt_p) {
233 lt = *lt_p;
235 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
238 preproc->pre_define(temp);
239 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
240 preproc->pre_define(temp);
241 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
242 preproc->pre_define(temp);
245 gm_p = gmtime(&official_compile_time);
246 if (gm_p) {
247 gm = *gm_p;
249 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
250 preproc->pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
252 preproc->pre_define(temp);
253 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
254 preproc->pre_define(temp);
255 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
256 preproc->pre_define(temp);
259 if (gm_p)
260 posix_time = make_posix_time(&gm);
261 else if (lt_p)
262 posix_time = make_posix_time(&lt);
263 else
264 posix_time = 0;
266 if (posix_time) {
267 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
268 preproc->pre_define(temp);
272 static void define_macros_late(void)
274 char temp[128];
277 * In case if output format is defined by alias
278 * we have to put shortname of the alias itself here
279 * otherwise ABI backward compatibility gets broken.
281 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
282 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
283 preproc->pre_define(temp);
286 static void emit_dependencies(StrList *list)
288 FILE *deps;
289 int linepos, len;
290 StrList *l, *nl;
292 if (depend_file && strcmp(depend_file, "-")) {
293 deps = fopen(depend_file, "w");
294 if (!deps) {
295 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
296 "unable to write dependency file `%s'", depend_file);
297 return;
299 } else {
300 deps = stdout;
303 linepos = fprintf(deps, "%s:", depend_target);
304 list_for_each(l, list) {
305 char *file = quote_for_make(l->str);
306 len = strlen(file);
307 if (linepos + len > 62 && linepos > 1) {
308 fprintf(deps, " \\\n ");
309 linepos = 1;
311 fprintf(deps, " %s", file);
312 linepos += len+1;
313 nasm_free(file);
315 fprintf(deps, "\n\n");
317 list_for_each_safe(l, nl, list) {
318 if (depend_emit_phony)
319 fprintf(deps, "%s:\n\n", l->str);
320 nasm_free(l);
323 if (deps != stdout)
324 fclose(deps);
327 int main(int argc, char **argv)
329 StrList *depend_list = NULL, **depend_ptr;
331 time(&official_compile_time);
333 iflag_set(&cpu, IF_PLEVEL);
334 iflag_set(&cmd_cpu, IF_PLEVEL);
336 pass0 = 0;
337 want_usage = terminate_after_phase = false;
338 nasm_set_verror(nasm_verror_gnu);
340 error_file = stderr;
342 tolower_init();
344 offsets = raa_init();
345 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
347 preproc = &nasmpp;
348 operating_mode = OP_NORMAL;
350 /* Define some macros dependent on the runtime, but not
351 on the command line. */
352 define_macros_early();
354 parse_cmdline(argc, argv);
356 if (terminate_after_phase) {
357 if (want_usage)
358 usage();
359 return 1;
362 if (!using_debug_info) {
363 /* No debug info, redirect to the null backend (empty stubs) */
364 dfmt = &null_debug_form;
365 } else if (!debug_format) {
366 /* Default debug format for this backend */
367 dfmt = ofmt->default_dfmt;
368 } else {
369 dfmt = dfmt_find(ofmt, debug_format);
370 if (!dfmt) {
371 nasm_fatal(ERR_NOFILE | ERR_USAGE,
372 "unrecognized debug format `%s' for"
373 " output format `%s'",
374 debug_format, ofmt->shortname);
378 if (ofmt->stdmac)
379 preproc->extra_stdmac(ofmt->stdmac);
380 parser_global_info(&location);
381 eval_global_info(ofmt, lookup_label, &location);
383 /* define some macros dependent of command-line */
384 define_macros_late();
386 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
387 if (!depend_target)
388 depend_target = quote_for_make(outname);
390 if (operating_mode & OP_DEPEND) {
391 char *line;
393 if (depend_missing_ok)
394 preproc->include_path(NULL); /* "assume generated" */
396 preproc->reset(inname, 0, depend_ptr);
397 if (outname[0] == '\0')
398 ofmt->filename(inname, outname);
399 ofile = NULL;
400 while ((line = preproc->getline()))
401 nasm_free(line);
402 preproc->cleanup(0);
403 } else if (operating_mode & OP_PREPROCESS) {
404 char *line;
405 char *file_name = NULL;
406 int32_t prior_linnum = 0;
407 int lineinc = 0;
409 if (*outname) {
410 ofile = fopen(outname, "w");
411 if (!ofile)
412 nasm_fatal(ERR_NOFILE,
413 "unable to open output file `%s'",
414 outname);
415 } else
416 ofile = NULL;
418 location.known = false;
420 /* pass = 1; */
421 preproc->reset(inname, 3, depend_ptr);
422 memcpy(warning_on, warning_on_global,
423 (ERR_WARN_MAX+1) * sizeof(bool));
425 while ((line = preproc->getline())) {
427 * We generate %line directives if needed for later programs
429 int32_t linnum = prior_linnum += lineinc;
430 int altline = src_get(&linnum, &file_name);
431 if (altline) {
432 if (altline == 1 && lineinc == 1)
433 nasm_fputs("", ofile);
434 else {
435 lineinc = (altline != -1 || lineinc != 1);
436 fprintf(ofile ? ofile : stdout,
437 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
438 file_name);
440 prior_linnum = linnum;
442 nasm_fputs(line, ofile);
443 nasm_free(line);
445 nasm_free(file_name);
446 preproc->cleanup(0);
447 if (ofile)
448 fclose(ofile);
449 if (ofile && terminate_after_phase)
450 remove(outname);
451 ofile = NULL;
454 if (operating_mode & OP_NORMAL) {
456 * We must call ofmt->filename _anyway_, even if the user
457 * has specified their own output file, because some
458 * formats (eg OBJ and COFF) use ofmt->filename to find out
459 * the name of the input file and then put that inside the
460 * file.
462 ofmt->filename(inname, outname);
464 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
465 if (!ofile)
466 nasm_fatal(ERR_NOFILE,
467 "unable to open output file `%s'", outname);
470 * We must call init_labels() before ofmt->init() since
471 * some object formats will want to define labels in their
472 * init routines. (eg OS/2 defines the FLAT group)
474 init_labels();
476 ofmt->init();
477 dfmt->init();
479 assemble_file(inname, depend_ptr);
481 if (!terminate_after_phase) {
482 ofmt->cleanup();
483 cleanup_labels();
484 fflush(ofile);
485 if (ferror(ofile))
486 nasm_error(ERR_NONFATAL|ERR_NOFILE,
487 "write error on output file `%s'", outname);
490 if (ofile) {
491 fclose(ofile);
492 if (terminate_after_phase)
493 remove(outname);
494 ofile = NULL;
498 if (depend_list && !terminate_after_phase)
499 emit_dependencies(depend_list);
501 if (want_usage)
502 usage();
504 raa_free(offsets);
505 saa_free(forwrefs);
506 eval_cleanup();
507 stdscan_cleanup();
509 return terminate_after_phase;
513 * Get a parameter for a command line option.
514 * First arg must be in the form of e.g. -f...
516 static char *get_param(char *p, char *q, bool *advance)
518 *advance = false;
519 if (p[2]) /* the parameter's in the option */
520 return nasm_skip_spaces(p + 2);
521 if (q && q[0]) {
522 *advance = true;
523 return q;
525 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
526 "option `-%c' requires an argument", p[1]);
527 return NULL;
531 * Copy a filename
533 static void copy_filename(char *dst, const char *src)
535 size_t len = strlen(src);
537 if (len >= (size_t)FILENAME_MAX) {
538 nasm_fatal(ERR_NOFILE, "file name too long");
539 return;
541 strncpy(dst, src, FILENAME_MAX);
545 * Convert a string to Make-safe form
547 static char *quote_for_make(const char *str)
549 const char *p;
550 char *os, *q;
552 size_t n = 1; /* Terminating zero */
553 size_t nbs = 0;
555 if (!str)
556 return NULL;
558 for (p = str; *p; p++) {
559 switch (*p) {
560 case ' ':
561 case '\t':
562 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
563 n += nbs + 2;
564 nbs = 0;
565 break;
566 case '$':
567 case '#':
568 nbs = 0;
569 n += 2;
570 break;
571 case '\\':
572 nbs++;
573 n++;
574 break;
575 default:
576 nbs = 0;
577 n++;
578 break;
582 /* Convert N backslashes at the end of filename to 2N backslashes */
583 if (nbs)
584 n += nbs;
586 os = q = nasm_malloc(n);
588 nbs = 0;
589 for (p = str; *p; p++) {
590 switch (*p) {
591 case ' ':
592 case '\t':
593 while (nbs--)
594 *q++ = '\\';
595 *q++ = '\\';
596 *q++ = *p;
597 break;
598 case '$':
599 *q++ = *p;
600 *q++ = *p;
601 nbs = 0;
602 break;
603 case '#':
604 *q++ = '\\';
605 *q++ = *p;
606 nbs = 0;
607 break;
608 case '\\':
609 *q++ = *p;
610 nbs++;
611 break;
612 default:
613 *q++ = *p;
614 nbs = 0;
615 break;
618 while (nbs--)
619 *q++ = '\\';
621 *q = '\0';
623 return os;
626 struct textargs {
627 const char *label;
628 int value;
631 enum text_options {
632 OPT_PREFIX,
633 OPT_POSTFIX
635 struct textargs textopts[] = {
636 {"prefix", OPT_PREFIX},
637 {"postfix", OPT_POSTFIX},
638 {NULL, 0}
641 static void show_version(void)
643 printf("NASM version %s compiled on %s%s\n",
644 nasm_version, nasm_date, nasm_compile_options);
645 exit(0);
648 static bool stopoptions = false;
649 static bool process_arg(char *p, char *q)
651 char *param;
652 int i;
653 bool advance = false;
654 bool do_warn;
656 if (!p || !p[0])
657 return false;
659 if (p[0] == '-' && !stopoptions) {
660 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
661 /* These parameters take values */
662 if (!(param = get_param(p, q, &advance)))
663 return advance;
666 switch (p[1]) {
667 case 's':
668 error_file = stdout;
669 break;
671 case 'o': /* output file */
672 copy_filename(outname, param);
673 break;
675 case 'f': /* output format */
676 ofmt = ofmt_find(param, &ofmt_alias);
677 if (!ofmt) {
678 nasm_fatal(ERR_NOFILE | ERR_USAGE,
679 "unrecognised output format `%s' - "
680 "use -hf for a list", param);
682 break;
684 case 'O': /* Optimization level */
686 int opt;
688 if (!*param) {
689 /* Naked -O == -Ox */
690 optimizing = MAX_OPTIMIZE;
691 } else {
692 while (*param) {
693 switch (*param) {
694 case '0': case '1': case '2': case '3': case '4':
695 case '5': case '6': case '7': case '8': case '9':
696 opt = strtoul(param, &param, 10);
698 /* -O0 -> optimizing == -1, 0.98 behaviour */
699 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
700 if (opt < 2)
701 optimizing = opt - 1;
702 else
703 optimizing = opt;
704 break;
706 case 'v':
707 case '+':
708 param++;
709 opt_verbose_info = true;
710 break;
712 case 'x':
713 param++;
714 optimizing = MAX_OPTIMIZE;
715 break;
717 default:
718 nasm_fatal(0,
719 "unknown optimization option -O%c\n",
720 *param);
721 break;
724 if (optimizing > MAX_OPTIMIZE)
725 optimizing = MAX_OPTIMIZE;
727 break;
730 case 'p': /* pre-include */
731 case 'P':
732 preproc->pre_include(param);
733 break;
735 case 'd': /* pre-define */
736 case 'D':
737 preproc->pre_define(param);
738 break;
740 case 'u': /* un-define */
741 case 'U':
742 preproc->pre_undefine(param);
743 break;
745 case 'i': /* include search path */
746 case 'I':
747 preproc->include_path(param);
748 break;
750 case 'l': /* listing file */
751 copy_filename(listname, param);
752 break;
754 case 'Z': /* error messages file */
755 copy_filename(errname, param);
756 break;
758 case 'F': /* specify debug format */
759 using_debug_info = true;
760 debug_format = param;
761 break;
763 case 'X': /* specify error reporting format */
764 if (nasm_stricmp("vc", param) == 0)
765 nasm_set_verror(nasm_verror_vc);
766 else if (nasm_stricmp("gnu", param) == 0)
767 nasm_set_verror(nasm_verror_gnu);
768 else
769 nasm_fatal(ERR_NOFILE | ERR_USAGE,
770 "unrecognized error reporting format `%s'",
771 param);
772 break;
774 case 'g':
775 using_debug_info = true;
776 if (p[2])
777 debug_format = nasm_skip_spaces(p + 2);
778 break;
780 case 'h':
781 printf
782 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
783 "[-l listfile]\n"
784 " [options...] [--] filename\n"
785 " or nasm -v (or --v) for version info\n\n"
786 " -t assemble in SciTech TASM compatible mode\n");
787 printf
788 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
789 " -a don't preprocess (assemble only)\n"
790 " -M generate Makefile dependencies on stdout\n"
791 " -MG d:o, missing files assumed generated\n"
792 " -MF <file> set Makefile dependency file\n"
793 " -MD <file> assemble and generate dependencies\n"
794 " -MT <file> dependency target name\n"
795 " -MQ <file> dependency target name (quoted)\n"
796 " -MP emit phony target\n\n"
797 " -Z<file> redirect error messages to file\n"
798 " -s redirect error messages to stdout\n\n"
799 " -g generate debugging information\n\n"
800 " -F format select a debugging format\n\n"
801 " -gformat same as -g -F format\n\n"
802 " -o outfile write output to an outfile\n\n"
803 " -f format select an output format\n\n"
804 " -l listfile write listing to a listfile\n\n"
805 " -I<path> adds a pathname to the include file path\n");
806 printf
807 (" -O<digit> optimize branch offsets\n"
808 " -O0: No optimization\n"
809 " -O1: Minimal optimization\n"
810 " -Ox: Multipass optimization (default)\n\n"
811 " -P<file> pre-includes a file\n"
812 " -D<macro>[=<value>] pre-defines a macro\n"
813 " -U<macro> undefines a macro\n"
814 " -X<format> specifies error reporting format (gnu or vc)\n"
815 " -w+foo enables warning foo (equiv. -Wfoo)\n"
816 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
817 " -h show invocation summary and exit\n\n"
818 "--prefix,--postfix\n"
819 " this options prepend or append the given argument to all\n"
820 " extern and global variables\n"
821 "Warnings:\n");
822 for (i = 0; i <= ERR_WARN_MAX; i++)
823 printf(" %-23s %s (default %s)\n",
824 warnings[i].name, warnings[i].help,
825 warnings[i].enabled ? "on" : "off");
826 printf
827 ("\nresponse files should contain command line parameters"
828 ", one per line.\n");
829 if (p[2] == 'f') {
830 printf("\nvalid output formats for -f are"
831 " (`*' denotes default):\n");
832 ofmt_list(ofmt, stdout);
833 } else {
834 printf("\nFor a list of valid output formats, use -hf.\n");
835 printf("For a list of debug formats, use -f <form> -y.\n");
837 exit(0); /* never need usage message here */
838 break;
840 case 'y':
841 printf("\nvalid debug formats for '%s' output format are"
842 " ('*' denotes default):\n", ofmt->shortname);
843 dfmt_list(ofmt, stdout);
844 exit(0);
845 break;
847 case 't':
848 tasm_compatible_mode = true;
849 break;
851 case 'v':
852 show_version();
853 break;
855 case 'e': /* preprocess only */
856 case 'E':
857 operating_mode = OP_PREPROCESS;
858 break;
860 case 'a': /* assemble only - don't preprocess */
861 preproc = &preproc_nop;
862 break;
864 case 'W':
865 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
866 do_warn = false;
867 param += 3;
868 } else {
869 do_warn = true;
871 goto set_warning;
873 case 'w':
874 if (param[0] != '+' && param[0] != '-') {
875 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
876 "invalid option to `-w'");
877 break;
879 do_warn = (param[0] == '+');
880 param++;
882 set_warning:
883 for (i = 0; i <= ERR_WARN_MAX; i++) {
884 if (!nasm_stricmp(param, warnings[i].name))
885 break;
887 if (i <= ERR_WARN_MAX) {
888 warning_on_global[i] = do_warn;
889 } else if (!nasm_stricmp(param, "all")) {
890 for (i = 1; i <= ERR_WARN_MAX; i++)
891 warning_on_global[i] = do_warn;
892 } else if (!nasm_stricmp(param, "none")) {
893 for (i = 1; i <= ERR_WARN_MAX; i++)
894 warning_on_global[i] = !do_warn;
895 } else {
896 /* Ignore invalid warning names; forward compatibility */
898 break;
900 case 'M':
901 switch (p[2]) {
902 case 0:
903 operating_mode = OP_DEPEND;
904 break;
905 case 'G':
906 operating_mode = OP_DEPEND;
907 depend_missing_ok = true;
908 break;
909 case 'P':
910 depend_emit_phony = true;
911 break;
912 case 'D':
913 operating_mode = OP_NORMAL;
914 depend_file = q;
915 advance = true;
916 break;
917 case 'F':
918 depend_file = q;
919 advance = true;
920 break;
921 case 'T':
922 depend_target = q;
923 advance = true;
924 break;
925 case 'Q':
926 depend_target = quote_for_make(q);
927 advance = true;
928 break;
929 default:
930 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
931 "unknown dependency option `-M%c'", p[2]);
932 break;
934 if (advance && (!q || !q[0])) {
935 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
936 "option `-M%c' requires a parameter", p[2]);
937 break;
939 break;
941 case '-':
943 int s;
945 if (p[2] == 0) { /* -- => stop processing options */
946 stopoptions = 1;
947 break;
950 if (!nasm_stricmp(p, "--v"))
951 show_version();
953 for (s = 0; textopts[s].label; s++) {
954 if (!nasm_stricmp(p + 2, textopts[s].label)) {
955 break;
959 switch (s) {
961 case OPT_PREFIX:
962 case OPT_POSTFIX:
964 if (!q) {
965 nasm_error(ERR_NONFATAL | ERR_NOFILE |
966 ERR_USAGE,
967 "option `--%s' requires an argument",
968 p + 2);
969 break;
970 } else {
971 advance = 1, param = q;
974 switch (s) {
975 case OPT_PREFIX:
976 strlcpy(lprefix, param, PREFIX_MAX);
977 break;
978 case OPT_POSTFIX:
979 strlcpy(lpostfix, param, POSTFIX_MAX);
980 break;
981 default:
982 nasm_panic(ERR_NOFILE,
983 "internal error");
984 break;
986 break;
989 default:
991 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
992 "unrecognised option `--%s'", p + 2);
993 break;
996 break;
999 default:
1000 if (!ofmt->setinfo(GI_SWITCH, &p))
1001 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1002 "unrecognised option `-%c'", p[1]);
1003 break;
1005 } else {
1006 if (*inname) {
1007 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1008 "more than one input file specified");
1009 } else {
1010 copy_filename(inname, p);
1014 return advance;
1017 #define ARG_BUF_DELTA 128
1019 static void process_respfile(FILE * rfile)
1021 char *buffer, *p, *q, *prevarg;
1022 int bufsize, prevargsize;
1024 bufsize = prevargsize = ARG_BUF_DELTA;
1025 buffer = nasm_malloc(ARG_BUF_DELTA);
1026 prevarg = nasm_malloc(ARG_BUF_DELTA);
1027 prevarg[0] = '\0';
1029 while (1) { /* Loop to handle all lines in file */
1030 p = buffer;
1031 while (1) { /* Loop to handle long lines */
1032 q = fgets(p, bufsize - (p - buffer), rfile);
1033 if (!q)
1034 break;
1035 p += strlen(p);
1036 if (p > buffer && p[-1] == '\n')
1037 break;
1038 if (p - buffer > bufsize - 10) {
1039 int offset;
1040 offset = p - buffer;
1041 bufsize += ARG_BUF_DELTA;
1042 buffer = nasm_realloc(buffer, bufsize);
1043 p = buffer + offset;
1047 if (!q && p == buffer) {
1048 if (prevarg[0])
1049 process_arg(prevarg, NULL);
1050 nasm_free(buffer);
1051 nasm_free(prevarg);
1052 return;
1056 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1057 * them are present at the end of the line.
1059 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1061 while (p > buffer && nasm_isspace(p[-1]))
1062 *--p = '\0';
1064 p = nasm_skip_spaces(buffer);
1066 if (process_arg(prevarg, p))
1067 *p = '\0';
1069 if ((int) strlen(p) > prevargsize - 10) {
1070 prevargsize += ARG_BUF_DELTA;
1071 prevarg = nasm_realloc(prevarg, prevargsize);
1073 strncpy(prevarg, p, prevargsize);
1077 /* Function to process args from a string of args, rather than the
1078 * argv array. Used by the environment variable and response file
1079 * processing.
1081 static void process_args(char *args)
1083 char *p, *q, *arg, *prevarg;
1084 char separator = ' ';
1086 p = args;
1087 if (*p && *p != '-')
1088 separator = *p++;
1089 arg = NULL;
1090 while (*p) {
1091 q = p;
1092 while (*p && *p != separator)
1093 p++;
1094 while (*p == separator)
1095 *p++ = '\0';
1096 prevarg = arg;
1097 arg = q;
1098 if (process_arg(prevarg, arg))
1099 arg = NULL;
1101 if (arg)
1102 process_arg(arg, NULL);
1105 static void process_response_file(const char *file)
1107 char str[2048];
1108 FILE *f = fopen(file, "r");
1109 if (!f) {
1110 perror(file);
1111 exit(-1);
1113 while (fgets(str, sizeof str, f)) {
1114 process_args(str);
1116 fclose(f);
1119 static void parse_cmdline(int argc, char **argv)
1121 FILE *rfile;
1122 char *envreal, *envcopy = NULL, *p;
1123 int i;
1125 *inname = *outname = *listname = *errname = '\0';
1127 for (i = 0; i <= ERR_WARN_MAX; i++)
1128 warning_on_global[i] = warnings[i].enabled;
1131 * First, process the NASMENV environment variable.
1133 envreal = getenv("NASMENV");
1134 if (envreal) {
1135 envcopy = nasm_strdup(envreal);
1136 process_args(envcopy);
1137 nasm_free(envcopy);
1141 * Now process the actual command line.
1143 while (--argc) {
1144 bool advance;
1145 argv++;
1146 if (argv[0][0] == '@') {
1148 * We have a response file, so process this as a set of
1149 * arguments like the environment variable. This allows us
1150 * to have multiple arguments on a single line, which is
1151 * different to the -@resp file processing below for regular
1152 * NASM.
1154 process_response_file(argv[0]+1);
1155 argc--;
1156 argv++;
1158 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1159 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1160 if (p) {
1161 rfile = fopen(p, "r");
1162 if (rfile) {
1163 process_respfile(rfile);
1164 fclose(rfile);
1165 } else
1166 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1167 "unable to open response file `%s'", p);
1169 } else
1170 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1171 argv += advance, argc -= advance;
1175 * Look for basic command line typos. This definitely doesn't
1176 * catch all errors, but it might help cases of fumbled fingers.
1178 if (!*inname)
1179 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1180 "no input file specified");
1181 else if (!strcmp(inname, errname) ||
1182 !strcmp(inname, outname) ||
1183 !strcmp(inname, listname) ||
1184 (depend_file && !strcmp(inname, depend_file)))
1185 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1186 "file `%s' is both input and output file",
1187 inname);
1189 if (*errname) {
1190 error_file = fopen(errname, "w");
1191 if (!error_file) {
1192 error_file = stderr; /* Revert to default! */
1193 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1194 "cannot open file `%s' for error messages",
1195 errname);
1200 static enum directives getkw(char **directive, char **value);
1202 static void assemble_file(char *fname, StrList **depend_ptr)
1204 char *directive, *value, *p, *q, *special, *line;
1205 insn output_ins;
1206 int i, validid;
1207 bool rn_error;
1208 int32_t seg;
1209 int64_t offs;
1210 struct tokenval tokval;
1211 expr *e;
1212 int pass_max;
1214 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1215 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1217 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1218 for (passn = 1; pass0 <= 2; passn++) {
1219 int pass1, pass2;
1220 ldfunc def_label;
1222 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1223 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1224 /* pass0 0, 0, 0, ..., 1, 2 */
1226 def_label = passn > 1 ? redefine_label : define_label;
1228 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1229 cpu = cmd_cpu;
1230 if (pass0 == 2) {
1231 lfmt->init(listname);
1233 in_abs_seg = false;
1234 global_offset_changed = 0; /* set by redefine_label */
1235 location.segment = ofmt->section(NULL, pass2, &sb);
1236 globalbits = sb;
1237 if (passn > 1) {
1238 saa_rewind(forwrefs);
1239 forwref = saa_rstruct(forwrefs);
1240 raa_free(offsets);
1241 offsets = raa_init();
1243 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1244 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1246 globallineno = 0;
1247 if (passn == 1)
1248 location.known = true;
1249 location.offset = offs = get_curr_offs();
1251 while ((line = preproc->getline())) {
1252 enum directives d;
1253 globallineno++;
1256 * Here we parse our directives; this is not handled by the
1257 * 'real' parser. This really should be a separate function.
1259 directive = line;
1260 d = getkw(&directive, &value);
1261 if (d) {
1262 int err = 0;
1264 switch (d) {
1265 case D_SEGMENT: /* [SEGMENT n] */
1266 case D_SECTION:
1267 seg = ofmt->section(value, pass2, &sb);
1268 if (seg == NO_SEG) {
1269 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1270 "segment name `%s' not recognized",
1271 value);
1272 } else {
1273 in_abs_seg = false;
1274 location.segment = seg;
1276 break;
1277 case D_SECTALIGN: /* [SECTALIGN n] */
1278 if (*value) {
1279 stdscan_reset();
1280 stdscan_set(value);
1281 tokval.t_type = TOKEN_INVALID;
1282 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1283 if (e) {
1284 unsigned int align = (unsigned int)e->value;
1285 if ((uint64_t)e->value > 0x7fffffff) {
1287 * FIXME: Please make some sane message here
1288 * ofmt should have some 'check' method which
1289 * would report segment alignment bounds.
1291 nasm_fatal(0,
1292 "incorrect segment alignment `%s'", value);
1293 } else if (!is_power2(align)) {
1294 nasm_error(ERR_NONFATAL,
1295 "segment alignment `%s' is not power of two",
1296 value);
1299 /* callee should be able to handle all details */
1300 if (location.segment != NO_SEG)
1301 ofmt->sectalign(location.segment, align);
1304 break;
1305 case D_EXTERN: /* [EXTERN label:special] */
1306 if (*value == '$')
1307 value++; /* skip initial $ if present */
1308 if (pass0 == 2) {
1309 q = value;
1310 while (*q && *q != ':')
1311 q++;
1312 if (*q == ':') {
1313 *q++ = '\0';
1314 ofmt->symdef(value, 0L, 0L, 3, q);
1316 } else if (passn == 1) {
1317 q = value;
1318 validid = true;
1319 if (!isidstart(*q))
1320 validid = false;
1321 while (*q && *q != ':') {
1322 if (!isidchar(*q))
1323 validid = false;
1324 q++;
1326 if (!validid) {
1327 nasm_error(ERR_NONFATAL,
1328 "identifier expected after EXTERN");
1329 break;
1331 if (*q == ':') {
1332 *q++ = '\0';
1333 special = q;
1334 } else
1335 special = NULL;
1336 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1337 int temp = pass0;
1338 pass0 = 1; /* fake pass 1 in labels.c */
1339 declare_as_global(value, special);
1340 define_label(value, seg_alloc(), 0L, NULL,
1341 false, true);
1342 pass0 = temp;
1344 } /* else pass0 == 1 */
1345 break;
1346 case D_BITS: /* [BITS bits] */
1347 globalbits = sb = get_bits(value);
1348 break;
1349 case D_GLOBAL: /* [GLOBAL symbol:special] */
1350 if (*value == '$')
1351 value++; /* skip initial $ if present */
1352 if (pass0 == 2) { /* pass 2 */
1353 q = value;
1354 while (*q && *q != ':')
1355 q++;
1356 if (*q == ':') {
1357 *q++ = '\0';
1358 ofmt->symdef(value, 0L, 0L, 3, q);
1360 } else if (pass2 == 1) { /* pass == 1 */
1361 q = value;
1362 validid = true;
1363 if (!isidstart(*q))
1364 validid = false;
1365 while (*q && *q != ':') {
1366 if (!isidchar(*q))
1367 validid = false;
1368 q++;
1370 if (!validid) {
1371 nasm_error(ERR_NONFATAL,
1372 "identifier expected after GLOBAL");
1373 break;
1375 if (*q == ':') {
1376 *q++ = '\0';
1377 special = q;
1378 } else
1379 special = NULL;
1380 declare_as_global(value, special);
1381 } /* pass == 1 */
1382 break;
1383 case D_COMMON: /* [COMMON symbol size:special] */
1385 int64_t size;
1387 if (*value == '$')
1388 value++; /* skip initial $ if present */
1389 p = value;
1390 validid = true;
1391 if (!isidstart(*p))
1392 validid = false;
1393 while (*p && !nasm_isspace(*p)) {
1394 if (!isidchar(*p))
1395 validid = false;
1396 p++;
1398 if (!validid) {
1399 nasm_error(ERR_NONFATAL,
1400 "identifier expected after COMMON");
1401 break;
1403 if (*p) {
1404 p = nasm_zap_spaces_fwd(p);
1405 q = p;
1406 while (*q && *q != ':')
1407 q++;
1408 if (*q == ':') {
1409 *q++ = '\0';
1410 special = q;
1411 } else {
1412 special = NULL;
1414 size = readnum(p, &rn_error);
1415 if (rn_error) {
1416 nasm_error(ERR_NONFATAL,
1417 "invalid size specified"
1418 " in COMMON declaration");
1419 break;
1421 } else {
1422 nasm_error(ERR_NONFATAL,
1423 "no size specified in"
1424 " COMMON declaration");
1425 break;
1428 if (pass0 < 2) {
1429 define_common(value, seg_alloc(), size, special);
1430 } else if (pass0 == 2) {
1431 if (special)
1432 ofmt->symdef(value, 0L, 0L, 3, special);
1434 break;
1436 case D_ABSOLUTE: /* [ABSOLUTE address] */
1437 stdscan_reset();
1438 stdscan_set(value);
1439 tokval.t_type = TOKEN_INVALID;
1440 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1441 if (e) {
1442 if (!is_reloc(e))
1443 nasm_error(pass0 ==
1444 1 ? ERR_NONFATAL : ERR_PANIC,
1445 "cannot use non-relocatable expression as "
1446 "ABSOLUTE address");
1447 else {
1448 abs_seg = reloc_seg(e);
1449 abs_offset = reloc_value(e);
1451 } else if (passn == 1)
1452 abs_offset = 0x100; /* don't go near zero in case of / */
1453 else
1454 nasm_panic(0, "invalid ABSOLUTE address "
1455 "in pass two");
1456 in_abs_seg = true;
1457 location.segment = NO_SEG;
1458 break;
1459 case D_DEBUG: /* [DEBUG] */
1461 char debugid[128];
1462 bool badid, overlong;
1464 p = value;
1465 q = debugid;
1466 badid = overlong = false;
1467 if (!isidstart(*p)) {
1468 badid = true;
1469 } else {
1470 while (*p && !nasm_isspace(*p)) {
1471 if (q >= debugid + sizeof debugid - 1) {
1472 overlong = true;
1473 break;
1475 if (!isidchar(*p))
1476 badid = true;
1477 *q++ = *p++;
1479 *q = 0;
1481 if (badid) {
1482 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1483 "identifier expected after DEBUG");
1484 break;
1486 if (overlong) {
1487 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1488 "DEBUG identifier too long");
1489 break;
1491 p = nasm_skip_spaces(p);
1492 if (pass0 == 2)
1493 dfmt->debug_directive(debugid, p);
1494 break;
1496 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1497 value = nasm_skip_spaces(value);
1498 switch(*value) {
1499 case '-': validid = 0; value++; break;
1500 case '+': validid = 1; value++; break;
1501 case '*': validid = 2; value++; break;
1502 default: validid = 1; break;
1505 for (i = 1; i <= ERR_WARN_MAX; i++)
1506 if (!nasm_stricmp(value, warnings[i].name))
1507 break;
1508 if (i <= ERR_WARN_MAX) {
1509 switch(validid) {
1510 case 0:
1511 warning_on[i] = false;
1512 break;
1513 case 1:
1514 warning_on[i] = true;
1515 break;
1516 case 2:
1517 warning_on[i] = warning_on_global[i];
1518 break;
1521 break;
1522 case D_CPU: /* [CPU] */
1523 cpu = get_cpu(value);
1524 break;
1525 case D_LIST: /* [LIST {+|-}] */
1526 value = nasm_skip_spaces(value);
1527 if (*value == '+') {
1528 user_nolist = 0;
1529 } else {
1530 if (*value == '-') {
1531 user_nolist = 1;
1532 } else {
1533 err = 1;
1536 break;
1537 case D_DEFAULT: /* [DEFAULT] */
1538 stdscan_reset();
1539 stdscan_set(value);
1540 tokval.t_type = TOKEN_INVALID;
1541 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1542 switch ((int)tokval.t_integer) {
1543 case S_REL:
1544 globalrel = 1;
1545 break;
1546 case S_ABS:
1547 globalrel = 0;
1548 break;
1549 case P_BND:
1550 globalbnd = 1;
1551 break;
1552 case P_NOBND:
1553 globalbnd = 0;
1554 break;
1555 default:
1556 err = 1;
1557 break;
1559 } else {
1560 err = 1;
1562 break;
1563 case D_FLOAT:
1564 if (float_option(value)) {
1565 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1566 "unknown 'float' directive: %s",
1567 value);
1569 break;
1570 default:
1571 if (ofmt->directive(d, value, pass2))
1572 break;
1573 /* else fall through */
1574 case D_unknown:
1575 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1576 "unrecognised directive [%s]",
1577 directive);
1578 break;
1580 if (err) {
1581 nasm_error(ERR_NONFATAL,
1582 "invalid parameter to [%s] directive",
1583 directive);
1585 } else { /* it isn't a directive */
1586 parse_line(pass1, line, &output_ins, def_label);
1588 if (optimizing > 0) {
1589 if (forwref != NULL && globallineno == forwref->lineno) {
1590 output_ins.forw_ref = true;
1591 do {
1592 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1593 forwref = saa_rstruct(forwrefs);
1594 } while (forwref != NULL
1595 && forwref->lineno == globallineno);
1596 } else
1597 output_ins.forw_ref = false;
1599 if (output_ins.forw_ref) {
1600 if (passn == 1) {
1601 for (i = 0; i < output_ins.operands; i++) {
1602 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1603 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1604 fwinf->lineno = globallineno;
1605 fwinf->operand = i;
1612 /* forw_ref */
1613 if (output_ins.opcode == I_EQU) {
1614 if (pass1 == 1) {
1616 * Special `..' EQUs get processed in pass two,
1617 * except `..@' macro-processor EQUs which are done
1618 * in the normal place.
1620 if (!output_ins.label)
1621 nasm_error(ERR_NONFATAL,
1622 "EQU not preceded by label");
1624 else if (output_ins.label[0] != '.' ||
1625 output_ins.label[1] != '.' ||
1626 output_ins.label[2] == '@') {
1627 if (output_ins.operands == 1 &&
1628 (output_ins.oprs[0].type & IMMEDIATE) &&
1629 output_ins.oprs[0].wrt == NO_SEG) {
1630 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1631 def_label(output_ins.label,
1632 output_ins.oprs[0].segment,
1633 output_ins.oprs[0].offset, NULL,
1634 false, isext);
1635 } else if (output_ins.operands == 2
1636 && (output_ins.oprs[0].type & IMMEDIATE)
1637 && (output_ins.oprs[0].type & COLON)
1638 && output_ins.oprs[0].segment == NO_SEG
1639 && output_ins.oprs[0].wrt == NO_SEG
1640 && (output_ins.oprs[1].type & IMMEDIATE)
1641 && output_ins.oprs[1].segment == NO_SEG
1642 && output_ins.oprs[1].wrt == NO_SEG) {
1643 def_label(output_ins.label,
1644 output_ins.oprs[0].offset | SEG_ABS,
1645 output_ins.oprs[1].offset,
1646 NULL, false, false);
1647 } else
1648 nasm_error(ERR_NONFATAL,
1649 "bad syntax for EQU");
1651 } else {
1653 * Special `..' EQUs get processed here, except
1654 * `..@' macro processor EQUs which are done above.
1656 if (output_ins.label[0] == '.' &&
1657 output_ins.label[1] == '.' &&
1658 output_ins.label[2] != '@') {
1659 if (output_ins.operands == 1 &&
1660 (output_ins.oprs[0].type & IMMEDIATE)) {
1661 define_label(output_ins.label,
1662 output_ins.oprs[0].segment,
1663 output_ins.oprs[0].offset,
1664 NULL, false, false);
1665 } else if (output_ins.operands == 2
1666 && (output_ins.oprs[0].type & IMMEDIATE)
1667 && (output_ins.oprs[0].type & COLON)
1668 && output_ins.oprs[0].segment == NO_SEG
1669 && (output_ins.oprs[1].type & IMMEDIATE)
1670 && output_ins.oprs[1].segment == NO_SEG) {
1671 define_label(output_ins.label,
1672 output_ins.oprs[0].offset | SEG_ABS,
1673 output_ins.oprs[1].offset,
1674 NULL, false, false);
1675 } else
1676 nasm_error(ERR_NONFATAL,
1677 "bad syntax for EQU");
1680 } else { /* instruction isn't an EQU */
1682 if (pass1 == 1) {
1684 int64_t l = insn_size(location.segment, offs, sb, cpu,
1685 &output_ins);
1687 /* if (using_debug_info) && output_ins.opcode != -1) */
1688 if (using_debug_info)
1689 { /* fbk 03/25/01 */
1690 /* this is done here so we can do debug type info */
1691 int32_t typeinfo =
1692 TYS_ELEMENTS(output_ins.operands);
1693 switch (output_ins.opcode) {
1694 case I_RESB:
1695 typeinfo =
1696 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1697 break;
1698 case I_RESW:
1699 typeinfo =
1700 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1701 break;
1702 case I_RESD:
1703 typeinfo =
1704 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1705 break;
1706 case I_RESQ:
1707 typeinfo =
1708 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1709 break;
1710 case I_REST:
1711 typeinfo =
1712 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1713 break;
1714 case I_RESO:
1715 typeinfo =
1716 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1717 break;
1718 case I_RESY:
1719 typeinfo =
1720 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1721 break;
1722 case I_DB:
1723 typeinfo |= TY_BYTE;
1724 break;
1725 case I_DW:
1726 typeinfo |= TY_WORD;
1727 break;
1728 case I_DD:
1729 if (output_ins.eops_float)
1730 typeinfo |= TY_FLOAT;
1731 else
1732 typeinfo |= TY_DWORD;
1733 break;
1734 case I_DQ:
1735 typeinfo |= TY_QWORD;
1736 break;
1737 case I_DT:
1738 typeinfo |= TY_TBYTE;
1739 break;
1740 case I_DO:
1741 typeinfo |= TY_OWORD;
1742 break;
1743 case I_DY:
1744 typeinfo |= TY_YWORD;
1745 break;
1746 default:
1747 typeinfo = TY_LABEL;
1751 dfmt->debug_typevalue(typeinfo);
1753 if (l != -1) {
1754 offs += l;
1755 set_curr_offs(offs);
1758 * else l == -1 => invalid instruction, which will be
1759 * flagged as an error on pass 2
1762 } else {
1763 offs += assemble(location.segment, offs, sb, cpu,
1764 &output_ins);
1765 set_curr_offs(offs);
1768 } /* not an EQU */
1769 cleanup_insn(&output_ins);
1771 nasm_free(line);
1772 location.offset = offs = get_curr_offs();
1773 } /* end while (line = preproc->getline... */
1775 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1776 nasm_error(ERR_NONFATAL,
1777 "phase error detected at end of assembly.");
1779 if (pass1 == 1)
1780 preproc->cleanup(1);
1782 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1783 pass0++;
1784 } else if (global_offset_changed &&
1785 global_offset_changed < prev_offset_changed) {
1786 prev_offset_changed = global_offset_changed;
1787 stall_count = 0;
1788 } else {
1789 stall_count++;
1792 if (terminate_after_phase)
1793 break;
1795 if ((stall_count > 997) || (passn >= pass_max)) {
1796 /* We get here if the labels don't converge
1797 * Example: FOO equ FOO + 1
1799 nasm_error(ERR_NONFATAL,
1800 "Can't find valid values for all labels "
1801 "after %d passes, giving up.", passn);
1802 nasm_error(ERR_NONFATAL,
1803 "Possible causes: recursive EQUs, macro abuse.");
1804 break;
1808 preproc->cleanup(0);
1809 lfmt->cleanup();
1810 if (!terminate_after_phase && opt_verbose_info) {
1811 /* -On and -Ov switches */
1812 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1816 static enum directives getkw(char **directive, char **value)
1818 char *p, *q, *buf;
1820 buf = nasm_skip_spaces(*directive);
1822 /* it should be enclosed in [ ] */
1823 if (*buf != '[')
1824 return D_none;
1825 q = strchr(buf, ']');
1826 if (!q)
1827 return D_none;
1829 /* stip off the comments */
1830 p = strchr(buf, ';');
1831 if (p) {
1832 if (p < q) /* ouch! somwhere inside */
1833 return D_none;
1834 *p = '\0';
1837 /* no brace, no trailing spaces */
1838 *q = '\0';
1839 nasm_zap_spaces_rev(--q);
1841 /* directive */
1842 p = nasm_skip_spaces(++buf);
1843 q = nasm_skip_word(p);
1844 if (!q)
1845 return D_none; /* sigh... no value there */
1846 *q = '\0';
1847 *directive = p;
1849 /* and value finally */
1850 p = nasm_skip_spaces(++q);
1851 *value = p;
1853 return find_directive(*directive);
1857 * gnu style error reporting
1858 * This function prints an error message to error_file in the
1859 * style used by GNU. An example would be:
1860 * file.asm:50: error: blah blah blah
1861 * where file.asm is the name of the file, 50 is the line number on
1862 * which the error occurs (or is detected) and "error:" is one of
1863 * the possible optional diagnostics -- it can be "error" or "warning"
1864 * or something else. Finally the line terminates with the actual
1865 * error message.
1867 * @param severity the severity of the warning or error
1868 * @param fmt the printf style format string
1870 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1872 char *currentfile = NULL;
1873 int32_t lineno = 0;
1875 if (is_suppressed_warning(severity))
1876 return;
1878 if (!(severity & ERR_NOFILE))
1879 src_get(&lineno, &currentfile);
1881 if (!skip_this_pass(severity)) {
1882 if (currentfile) {
1883 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1884 } else {
1885 fputs("nasm: ", error_file);
1889 nasm_verror_common(severity, fmt, ap);
1893 * MS style error reporting
1894 * This function prints an error message to error_file in the
1895 * style used by Visual C and some other Microsoft tools. An example
1896 * would be:
1897 * file.asm(50) : error: blah blah blah
1898 * where file.asm is the name of the file, 50 is the line number on
1899 * which the error occurs (or is detected) and "error:" is one of
1900 * the possible optional diagnostics -- it can be "error" or "warning"
1901 * or something else. Finally the line terminates with the actual
1902 * error message.
1904 * @param severity the severity of the warning or error
1905 * @param fmt the printf style format string
1907 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1909 char *currentfile = NULL;
1910 int32_t lineno = 0;
1912 if (is_suppressed_warning(severity))
1913 return;
1915 if (!(severity & ERR_NOFILE))
1916 src_get(&lineno, &currentfile);
1918 if (!skip_this_pass(severity)) {
1919 if (currentfile) {
1920 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1921 nasm_free(currentfile);
1922 } else {
1923 fputs("nasm: ", error_file);
1927 nasm_verror_common(severity, fmt, ap);
1931 * check for supressed warning
1932 * checks for suppressed warning or pass one only warning and we're
1933 * not in pass 1
1935 * @param severity the severity of the warning or error
1936 * @return true if we should abort error/warning printing
1938 static bool is_suppressed_warning(int severity)
1940 /* Not a warning at all */
1941 if ((severity & ERR_MASK) != ERR_WARNING)
1942 return false;
1944 /* Might be a warning but suppresed explicitly */
1945 if (severity & ERR_WARN_MASK)
1946 return !warning_on[WARN_IDX(severity)];
1947 else
1948 return false;
1951 static bool skip_this_pass(int severity)
1953 /* See if it's a pass-specific warning which should be skipped. */
1955 if ((severity & ERR_MASK) > ERR_WARNING)
1956 return false;
1959 * passn is 1 on the very first pass only.
1960 * pass0 is 2 on the code-generation (final) pass only.
1961 * These are the passes we care about in this case.
1963 return (((severity & ERR_PASS1) && passn != 1) ||
1964 ((severity & ERR_PASS2) && pass0 != 2));
1968 * common error reporting
1969 * This is the common back end of the error reporting schemes currently
1970 * implemented. It prints the nature of the warning and then the
1971 * specific error message to error_file and may or may not return. It
1972 * doesn't return if the error severity is a "panic" or "debug" type.
1974 * @param severity the severity of the warning or error
1975 * @param fmt the printf style format string
1977 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1979 char msg[1024];
1980 const char *pfx;
1982 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1983 case ERR_WARNING:
1984 pfx = "warning: ";
1985 break;
1986 case ERR_NONFATAL:
1987 pfx = "error: ";
1988 break;
1989 case ERR_FATAL:
1990 pfx = "fatal: ";
1991 break;
1992 case ERR_PANIC:
1993 pfx = "panic: ";
1994 break;
1995 case ERR_DEBUG:
1996 pfx = "debug: ";
1997 break;
1998 default:
1999 pfx = "";
2000 break;
2003 vsnprintf(msg, sizeof msg - 64, fmt, args);
2004 if ((severity & (ERR_WARN_MASK|ERR_PP_LISTMACRO)) == ERR_WARN_MASK) {
2005 char *p = strchr(msg, '\0');
2006 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
2009 if (!skip_this_pass(severity))
2010 fprintf(error_file, "%s%s\n", pfx, msg);
2012 /* Are we recursing from error_list_macros? */
2013 if (severity & ERR_PP_LISTMACRO)
2014 return;
2017 * Don't suppress this with skip_this_pass(), or we don't get
2018 * pass1 or preprocessor warnings in the list file
2020 if ((severity & ERR_MASK) >= ERR_WARNING)
2021 lfmt->error(severity, pfx, msg);
2023 if (severity & ERR_USAGE)
2024 want_usage = true;
2026 preproc->error_list_macros(severity);
2028 switch (severity & ERR_MASK) {
2029 case ERR_DEBUG:
2030 /* no further action, by definition */
2031 break;
2032 case ERR_WARNING:
2033 /* Treat warnings as errors */
2034 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
2035 terminate_after_phase = true;
2036 break;
2037 case ERR_NONFATAL:
2038 terminate_after_phase = true;
2039 break;
2040 case ERR_FATAL:
2041 if (ofile) {
2042 fclose(ofile);
2043 remove(outname);
2044 ofile = NULL;
2046 if (want_usage)
2047 usage();
2048 exit(1); /* instantly die */
2049 break; /* placate silly compilers */
2050 case ERR_PANIC:
2051 fflush(NULL);
2052 /* abort(); */ /* halt, catch fire, and dump core */
2053 if (ofile) {
2054 fclose(ofile);
2055 remove(outname);
2056 ofile = NULL;
2058 exit(3);
2059 break;
2063 static void usage(void)
2065 fputs("type `nasm -h' for help\n", error_file);
2068 static iflag_t get_cpu(char *value)
2070 iflag_t r;
2072 iflag_clear_all(&r);
2074 if (!strcmp(value, "8086"))
2075 iflag_set(&r, IF_8086);
2076 else if (!strcmp(value, "186"))
2077 iflag_set(&r, IF_186);
2078 else if (!strcmp(value, "286"))
2079 iflag_set(&r, IF_286);
2080 else if (!strcmp(value, "386"))
2081 iflag_set(&r, IF_386);
2082 else if (!strcmp(value, "486"))
2083 iflag_set(&r, IF_486);
2084 else if (!strcmp(value, "586") ||
2085 !nasm_stricmp(value, "pentium"))
2086 iflag_set(&r, IF_PENT);
2087 else if (!strcmp(value, "686") ||
2088 !nasm_stricmp(value, "ppro") ||
2089 !nasm_stricmp(value, "pentiumpro") ||
2090 !nasm_stricmp(value, "p2"))
2091 iflag_set(&r, IF_P6);
2092 else if (!nasm_stricmp(value, "p3") ||
2093 !nasm_stricmp(value, "katmai"))
2094 iflag_set(&r, IF_KATMAI);
2095 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2096 !nasm_stricmp(value, "willamette"))
2097 iflag_set(&r, IF_WILLAMETTE);
2098 else if (!nasm_stricmp(value, "prescott"))
2099 iflag_set(&r, IF_PRESCOTT);
2100 else if (!nasm_stricmp(value, "x64") ||
2101 !nasm_stricmp(value, "x86-64"))
2102 iflag_set(&r, IF_X86_64);
2103 else if (!nasm_stricmp(value, "ia64") ||
2104 !nasm_stricmp(value, "ia-64") ||
2105 !nasm_stricmp(value, "itanium")||
2106 !nasm_stricmp(value, "itanic") ||
2107 !nasm_stricmp(value, "merced"))
2108 iflag_set(&r, IF_IA64);
2109 else {
2110 iflag_set(&r, IF_PLEVEL);
2111 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2112 "unknown 'cpu' type");
2114 return r;
2117 static int get_bits(char *value)
2119 int i;
2121 if ((i = atoi(value)) == 16)
2122 return i; /* set for a 16-bit segment */
2123 else if (i == 32) {
2124 if (iflag_ffs(&cpu) < IF_386) {
2125 nasm_error(ERR_NONFATAL,
2126 "cannot specify 32-bit segment on processor below a 386");
2127 i = 16;
2129 } else if (i == 64) {
2130 if (iflag_ffs(&cpu) < IF_X86_64) {
2131 nasm_error(ERR_NONFATAL,
2132 "cannot specify 64-bit segment on processor below an x86-64");
2133 i = 16;
2135 } else {
2136 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2137 "`%s' is not a valid segment size; must be 16, 32 or 64",
2138 value);
2139 i = 16;
2141 return i;