Make --disable-werror work
[nasm.git] / nasm.c
blob5556e061a179af92ec80fdfb8cd0f28866a5786f
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 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 bool is_suppressed_warning(int severity);
85 static void usage(void);
87 static int using_debug_info, opt_verbose_info;
88 bool tasm_compatible_mode = false;
89 int pass0, passn;
90 int globalrel = 0;
91 int globalbnd = 0;
93 static time_t official_compile_time;
95 static char inname[FILENAME_MAX];
96 static char outname[FILENAME_MAX];
97 static char listname[FILENAME_MAX];
98 static char errname[FILENAME_MAX];
99 static int globallineno; /* for forward-reference tracking */
100 /* static int pass = 0; */
101 struct ofmt *ofmt = &OF_DEFAULT;
102 struct ofmt_alias *ofmt_alias = NULL;
103 const struct dfmt *dfmt;
105 static FILE *error_file; /* Where to write error messages */
107 FILE *ofile = NULL;
108 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
109 static int sb, cmd_sb = 16; /* by default */
111 static iflag_t cpu;
112 static iflag_t cmd_cpu;
114 int64_t global_offset_changed; /* referenced in labels.c */
115 int64_t prev_offset_changed;
116 int32_t stall_count;
118 static struct location location;
119 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
120 int32_t abs_seg; /* ABSOLUTE segment basis */
121 int32_t abs_offset; /* ABSOLUTE offset */
123 static struct RAA *offsets;
125 static struct SAA *forwrefs; /* keep track of forward references */
126 static const struct forwrefinfo *forwref;
128 static struct preproc_ops *preproc;
130 #define OP_NORMAL (1u << 0)
131 #define OP_PREPROCESS (1u << 1)
132 #define OP_DEPEND (1u << 2)
134 static unsigned int operating_mode;
136 /* Dependency flags */
137 static bool depend_emit_phony = false;
138 static bool depend_missing_ok = false;
139 static const char *depend_target = NULL;
140 static const char *depend_file = NULL;
143 * Which of the suppressible warnings are suppressed. Entry zero
144 * isn't an actual warning, but it used for -w+error/-Werror.
147 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
148 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
150 static const struct warning {
151 const char *name;
152 const char *help;
153 bool enabled;
154 } warnings[ERR_WARN_MAX+1] = {
155 {"error", "treat warnings as errors", false},
156 {"macro-params", "macro calls with wrong parameter count", true},
157 {"macro-selfref", "cyclic macro references", false},
158 {"macro-defaults", "macros with more default than optional parameters", true},
159 {"orphan-labels", "labels alone on lines without trailing `:'", true},
160 {"number-overflow", "numeric constant does not fit", true},
161 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
162 {"float-overflow", "floating point overflow", true},
163 {"float-denorm", "floating point denormal", false},
164 {"float-underflow", "floating point underflow", false},
165 {"float-toolong", "too many digits in floating-point number", true},
166 {"user", "%warning directives", true},
167 {"lock", "lock prefix on unlockable instructions", true},
168 {"hle", "invalid hle prefixes", true},
169 {"bnd", "invalid bnd prefixes", true},
170 {"zext-reloc", "relocation zero-extended to match output format", true},
173 static bool want_usage;
174 static bool terminate_after_phase;
175 int user_nolist = 0; /* fbk 9/2/00 */
177 static char *quote_for_make(const char *str);
179 static int64_t get_curr_offs(void)
181 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
184 static void set_curr_offs(int64_t l_off)
186 if (in_abs_seg)
187 abs_offset = l_off;
188 else
189 offsets = raa_write(offsets, location.segment, l_off);
192 static void nasm_fputs(const char *line, FILE * outfile)
194 if (outfile) {
195 fputs(line, outfile);
196 putc('\n', outfile);
197 } else
198 puts(line);
201 /* Convert a struct tm to a POSIX-style time constant */
202 static int64_t make_posix_time(struct tm *tm)
204 int64_t t;
205 int64_t y = tm->tm_year;
207 /* See IEEE 1003.1:2004, section 4.14 */
209 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
210 t += tm->tm_yday;
211 t *= 24;
212 t += tm->tm_hour;
213 t *= 60;
214 t += tm->tm_min;
215 t *= 60;
216 t += tm->tm_sec;
218 return t;
221 static void define_macros_early(void)
223 char temp[128];
224 struct tm lt, *lt_p, gm, *gm_p;
225 int64_t posix_time;
227 lt_p = localtime(&official_compile_time);
228 if (lt_p) {
229 lt = *lt_p;
231 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
232 preproc->pre_define(temp);
233 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
234 preproc->pre_define(temp);
235 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
238 preproc->pre_define(temp);
241 gm_p = gmtime(&official_compile_time);
242 if (gm_p) {
243 gm = *gm_p;
245 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
246 preproc->pre_define(temp);
247 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
248 preproc->pre_define(temp);
249 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
250 preproc->pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
252 preproc->pre_define(temp);
255 if (gm_p)
256 posix_time = make_posix_time(&gm);
257 else if (lt_p)
258 posix_time = make_posix_time(&lt);
259 else
260 posix_time = 0;
262 if (posix_time) {
263 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
264 preproc->pre_define(temp);
268 static void define_macros_late(void)
270 char temp[128];
273 * In case if output format is defined by alias
274 * we have to put shortname of the alias itself here
275 * otherwise ABI backward compatibility gets broken.
277 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
278 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
279 preproc->pre_define(temp);
282 static void emit_dependencies(StrList *list)
284 FILE *deps;
285 int linepos, len;
286 StrList *l, *nl;
288 if (depend_file && strcmp(depend_file, "-")) {
289 deps = fopen(depend_file, "w");
290 if (!deps) {
291 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
292 "unable to write dependency file `%s'", depend_file);
293 return;
295 } else {
296 deps = stdout;
299 linepos = fprintf(deps, "%s:", depend_target);
300 list_for_each(l, list) {
301 char *file = quote_for_make(l->str);
302 len = strlen(file);
303 if (linepos + len > 62 && linepos > 1) {
304 fprintf(deps, " \\\n ");
305 linepos = 1;
307 fprintf(deps, " %s", file);
308 linepos += len+1;
309 nasm_free(file);
311 fprintf(deps, "\n\n");
313 list_for_each_safe(l, nl, list) {
314 if (depend_emit_phony)
315 fprintf(deps, "%s:\n\n", l->str);
316 nasm_free(l);
319 if (deps != stdout)
320 fclose(deps);
323 int main(int argc, char **argv)
325 StrList *depend_list = NULL, **depend_ptr;
327 time(&official_compile_time);
329 iflag_set(&cpu, IF_PLEVEL);
330 iflag_set(&cmd_cpu, IF_PLEVEL);
332 pass0 = 0;
333 want_usage = terminate_after_phase = false;
334 nasm_set_verror(nasm_verror_gnu);
336 error_file = stderr;
338 tolower_init();
340 offsets = raa_init();
341 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
343 preproc = &nasmpp;
344 operating_mode = OP_NORMAL;
346 /* Define some macros dependent on the runtime, but not
347 on the command line. */
348 define_macros_early();
350 parse_cmdline(argc, argv);
352 if (terminate_after_phase) {
353 if (want_usage)
354 usage();
355 return 1;
358 /* If debugging info is disabled, suppress any debug calls */
359 if (!using_debug_info)
360 ofmt->current_dfmt = &null_debug_form;
362 if (ofmt->stdmac)
363 preproc->extra_stdmac(ofmt->stdmac);
364 parser_global_info(&location);
365 eval_global_info(ofmt, lookup_label, &location);
367 /* define some macros dependent of command-line */
368 define_macros_late();
370 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
371 if (!depend_target)
372 depend_target = quote_for_make(outname);
374 if (operating_mode & OP_DEPEND) {
375 char *line;
377 if (depend_missing_ok)
378 preproc->include_path(NULL); /* "assume generated" */
380 preproc->reset(inname, 0, &nasmlist, depend_ptr);
381 if (outname[0] == '\0')
382 ofmt->filename(inname, outname);
383 ofile = NULL;
384 while ((line = preproc->getline()))
385 nasm_free(line);
386 preproc->cleanup(0);
387 } else if (operating_mode & OP_PREPROCESS) {
388 char *line;
389 char *file_name = NULL;
390 int32_t prior_linnum = 0;
391 int lineinc = 0;
393 if (*outname) {
394 ofile = fopen(outname, "w");
395 if (!ofile)
396 nasm_error(ERR_FATAL | ERR_NOFILE,
397 "unable to open output file `%s'",
398 outname);
399 } else
400 ofile = NULL;
402 location.known = false;
404 /* pass = 1; */
405 preproc->reset(inname, 3, &nasmlist, depend_ptr);
406 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
408 while ((line = preproc->getline())) {
410 * We generate %line directives if needed for later programs
412 int32_t linnum = prior_linnum += lineinc;
413 int altline = src_get(&linnum, &file_name);
414 if (altline) {
415 if (altline == 1 && lineinc == 1)
416 nasm_fputs("", ofile);
417 else {
418 lineinc = (altline != -1 || lineinc != 1);
419 fprintf(ofile ? ofile : stdout,
420 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
421 file_name);
423 prior_linnum = linnum;
425 nasm_fputs(line, ofile);
426 nasm_free(line);
428 nasm_free(file_name);
429 preproc->cleanup(0);
430 if (ofile)
431 fclose(ofile);
432 if (ofile && terminate_after_phase)
433 remove(outname);
434 ofile = NULL;
437 if (operating_mode & OP_NORMAL) {
439 * We must call ofmt->filename _anyway_, even if the user
440 * has specified their own output file, because some
441 * formats (eg OBJ and COFF) use ofmt->filename to find out
442 * the name of the input file and then put that inside the
443 * file.
445 ofmt->filename(inname, outname);
447 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
448 if (!ofile)
449 nasm_error(ERR_FATAL | ERR_NOFILE,
450 "unable to open output file `%s'", outname);
453 * We must call init_labels() before ofmt->init() since
454 * some object formats will want to define labels in their
455 * init routines. (eg OS/2 defines the FLAT group)
457 init_labels();
459 ofmt->init();
460 dfmt = ofmt->current_dfmt;
461 dfmt->init();
463 assemble_file(inname, depend_ptr);
465 if (!terminate_after_phase) {
466 ofmt->cleanup(using_debug_info);
467 cleanup_labels();
468 fflush(ofile);
469 if (ferror(ofile))
470 nasm_error(ERR_NONFATAL|ERR_NOFILE,
471 "write error on output file `%s'", outname);
474 if (ofile) {
475 fclose(ofile);
476 if (terminate_after_phase)
477 remove(outname);
478 ofile = NULL;
482 if (depend_list && !terminate_after_phase)
483 emit_dependencies(depend_list);
485 if (want_usage)
486 usage();
488 raa_free(offsets);
489 saa_free(forwrefs);
490 eval_cleanup();
491 stdscan_cleanup();
493 return terminate_after_phase;
497 * Get a parameter for a command line option.
498 * First arg must be in the form of e.g. -f...
500 static char *get_param(char *p, char *q, bool *advance)
502 *advance = false;
503 if (p[2]) /* the parameter's in the option */
504 return nasm_skip_spaces(p + 2);
505 if (q && q[0]) {
506 *advance = true;
507 return q;
509 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
510 "option `-%c' requires an argument", p[1]);
511 return NULL;
515 * Copy a filename
517 static void copy_filename(char *dst, const char *src)
519 size_t len = strlen(src);
521 if (len >= (size_t)FILENAME_MAX) {
522 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
523 return;
525 strncpy(dst, src, FILENAME_MAX);
529 * Convert a string to Make-safe form
531 static char *quote_for_make(const char *str)
533 const char *p;
534 char *os, *q;
536 size_t n = 1; /* Terminating zero */
537 size_t nbs = 0;
539 if (!str)
540 return NULL;
542 for (p = str; *p; p++) {
543 switch (*p) {
544 case ' ':
545 case '\t':
546 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
547 n += nbs + 2;
548 nbs = 0;
549 break;
550 case '$':
551 case '#':
552 nbs = 0;
553 n += 2;
554 break;
555 case '\\':
556 nbs++;
557 n++;
558 break;
559 default:
560 nbs = 0;
561 n++;
562 break;
566 /* Convert N backslashes at the end of filename to 2N backslashes */
567 if (nbs)
568 n += nbs;
570 os = q = nasm_malloc(n);
572 nbs = 0;
573 for (p = str; *p; p++) {
574 switch (*p) {
575 case ' ':
576 case '\t':
577 while (nbs--)
578 *q++ = '\\';
579 *q++ = '\\';
580 *q++ = *p;
581 break;
582 case '$':
583 *q++ = *p;
584 *q++ = *p;
585 nbs = 0;
586 break;
587 case '#':
588 *q++ = '\\';
589 *q++ = *p;
590 nbs = 0;
591 break;
592 case '\\':
593 *q++ = *p;
594 nbs++;
595 break;
596 default:
597 *q++ = *p;
598 nbs = 0;
599 break;
602 while (nbs--)
603 *q++ = '\\';
605 *q = '\0';
607 return os;
610 struct textargs {
611 const char *label;
612 int value;
615 enum text_options {
616 OPT_PREFIX,
617 OPT_POSTFIX
619 struct textargs textopts[] = {
620 {"prefix", OPT_PREFIX},
621 {"postfix", OPT_POSTFIX},
622 {NULL, 0}
625 static void show_version(void)
627 printf("NASM version %s compiled on %s%s\n",
628 nasm_version, nasm_date, nasm_compile_options);
629 exit(0);
632 static bool stopoptions = false;
633 static bool process_arg(char *p, char *q)
635 char *param;
636 int i;
637 bool advance = false;
638 bool do_warn;
640 if (!p || !p[0])
641 return false;
643 if (p[0] == '-' && !stopoptions) {
644 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
645 /* These parameters take values */
646 if (!(param = get_param(p, q, &advance)))
647 return advance;
650 switch (p[1]) {
651 case 's':
652 error_file = stdout;
653 break;
655 case 'o': /* output file */
656 copy_filename(outname, param);
657 break;
659 case 'f': /* output format */
660 ofmt = ofmt_find(param, &ofmt_alias);
661 if (!ofmt) {
662 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
663 "unrecognised output format `%s' - "
664 "use -hf for a list", param);
666 break;
668 case 'O': /* Optimization level */
670 int opt;
672 if (!*param) {
673 /* Naked -O == -Ox */
674 optimizing = MAX_OPTIMIZE;
675 } else {
676 while (*param) {
677 switch (*param) {
678 case '0': case '1': case '2': case '3': case '4':
679 case '5': case '6': case '7': case '8': case '9':
680 opt = strtoul(param, &param, 10);
682 /* -O0 -> optimizing == -1, 0.98 behaviour */
683 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
684 if (opt < 2)
685 optimizing = opt - 1;
686 else
687 optimizing = opt;
688 break;
690 case 'v':
691 case '+':
692 param++;
693 opt_verbose_info = true;
694 break;
696 case 'x':
697 param++;
698 optimizing = MAX_OPTIMIZE;
699 break;
701 default:
702 nasm_error(ERR_FATAL,
703 "unknown optimization option -O%c\n",
704 *param);
705 break;
708 if (optimizing > MAX_OPTIMIZE)
709 optimizing = MAX_OPTIMIZE;
711 break;
714 case 'p': /* pre-include */
715 case 'P':
716 preproc->pre_include(param);
717 break;
719 case 'd': /* pre-define */
720 case 'D':
721 preproc->pre_define(param);
722 break;
724 case 'u': /* un-define */
725 case 'U':
726 preproc->pre_undefine(param);
727 break;
729 case 'i': /* include search path */
730 case 'I':
731 preproc->include_path(param);
732 break;
734 case 'l': /* listing file */
735 copy_filename(listname, param);
736 break;
738 case 'Z': /* error messages file */
739 copy_filename(errname, param);
740 break;
742 case 'F': /* specify debug format */
743 ofmt->current_dfmt = dfmt_find(ofmt, param);
744 if (!ofmt->current_dfmt) {
745 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
746 "unrecognized debug format `%s' for"
747 " output format `%s'",
748 param, ofmt->shortname);
750 using_debug_info = true;
751 break;
753 case 'X': /* specify error reporting format */
754 if (nasm_stricmp("vc", param) == 0)
755 nasm_set_verror(nasm_verror_vc);
756 else if (nasm_stricmp("gnu", param) == 0)
757 nasm_set_verror(nasm_verror_gnu);
758 else
759 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
760 "unrecognized error reporting format `%s'",
761 param);
762 break;
764 case 'g':
765 using_debug_info = true;
766 break;
768 case 'h':
769 printf
770 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
771 "[-l listfile]\n"
772 " [options...] [--] filename\n"
773 " or nasm -v (or --v) for version info\n\n"
774 " -t assemble in SciTech TASM compatible mode\n"
775 " -g generate debug information in selected format\n");
776 printf
777 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
778 " -a don't preprocess (assemble only)\n"
779 " -M generate Makefile dependencies on stdout\n"
780 " -MG d:o, missing files assumed generated\n"
781 " -MF <file> set Makefile dependency file\n"
782 " -MD <file> assemble and generate dependencies\n"
783 " -MT <file> dependency target name\n"
784 " -MQ <file> dependency target name (quoted)\n"
785 " -MP emit phony target\n\n"
786 " -Z<file> redirect error messages to file\n"
787 " -s redirect error messages to stdout\n\n"
788 " -F format select a debugging format\n\n"
789 " -o outfile write output to an outfile\n\n"
790 " -f format select an output format\n\n"
791 " -l listfile write listing to a listfile\n\n"
792 " -I<path> adds a pathname to the include file path\n");
793 printf
794 (" -O<digit> optimize branch offsets\n"
795 " -O0: No optimization\n"
796 " -O1: Minimal optimization\n"
797 " -Ox: Multipass optimization (default)\n\n"
798 " -P<file> pre-includes a file\n"
799 " -D<macro>[=<value>] pre-defines a macro\n"
800 " -U<macro> undefines a macro\n"
801 " -X<format> specifies error reporting format (gnu or vc)\n"
802 " -w+foo enables warning foo (equiv. -Wfoo)\n"
803 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
804 " -h show invocation summary and exit\n\n"
805 "--prefix,--postfix\n"
806 " this options prepend or append the given argument to all\n"
807 " extern and global variables\n"
808 "Warnings:\n");
809 for (i = 0; i <= ERR_WARN_MAX; i++)
810 printf(" %-23s %s (default %s)\n",
811 warnings[i].name, warnings[i].help,
812 warnings[i].enabled ? "on" : "off");
813 printf
814 ("\nresponse files should contain command line parameters"
815 ", one per line.\n");
816 if (p[2] == 'f') {
817 printf("\nvalid output formats for -f are"
818 " (`*' denotes default):\n");
819 ofmt_list(ofmt, stdout);
820 } else {
821 printf("\nFor a list of valid output formats, use -hf.\n");
822 printf("For a list of debug formats, use -f <form> -y.\n");
824 exit(0); /* never need usage message here */
825 break;
827 case 'y':
828 printf("\nvalid debug formats for '%s' output format are"
829 " ('*' denotes default):\n", ofmt->shortname);
830 dfmt_list(ofmt, stdout);
831 exit(0);
832 break;
834 case 't':
835 tasm_compatible_mode = true;
836 break;
838 case 'v':
839 show_version();
840 break;
842 case 'e': /* preprocess only */
843 case 'E':
844 operating_mode = OP_PREPROCESS;
845 break;
847 case 'a': /* assemble only - don't preprocess */
848 preproc = &preproc_nop;
849 break;
851 case 'W':
852 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
853 do_warn = false;
854 param += 3;
855 } else {
856 do_warn = true;
858 goto set_warning;
860 case 'w':
861 if (param[0] != '+' && param[0] != '-') {
862 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
863 "invalid option to `-w'");
864 break;
866 do_warn = (param[0] == '+');
867 param++;
869 set_warning:
870 for (i = 0; i <= ERR_WARN_MAX; i++) {
871 if (!nasm_stricmp(param, warnings[i].name))
872 break;
874 if (i <= ERR_WARN_MAX) {
875 warning_on_global[i] = do_warn;
876 } else if (!nasm_stricmp(param, "all")) {
877 for (i = 1; i <= ERR_WARN_MAX; i++)
878 warning_on_global[i] = do_warn;
879 } else if (!nasm_stricmp(param, "none")) {
880 for (i = 1; i <= ERR_WARN_MAX; i++)
881 warning_on_global[i] = !do_warn;
882 } else {
883 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
884 "invalid warning `%s'", param);
886 break;
888 case 'M':
889 switch (p[2]) {
890 case 0:
891 operating_mode = OP_DEPEND;
892 break;
893 case 'G':
894 operating_mode = OP_DEPEND;
895 depend_missing_ok = true;
896 break;
897 case 'P':
898 depend_emit_phony = true;
899 break;
900 case 'D':
901 operating_mode = OP_NORMAL;
902 depend_file = q;
903 advance = true;
904 break;
905 case 'F':
906 depend_file = q;
907 advance = true;
908 break;
909 case 'T':
910 depend_target = q;
911 advance = true;
912 break;
913 case 'Q':
914 depend_target = quote_for_make(q);
915 advance = true;
916 break;
917 default:
918 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
919 "unknown dependency option `-M%c'", p[2]);
920 break;
922 if (advance && (!q || !q[0])) {
923 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
924 "option `-M%c' requires a parameter", p[2]);
925 break;
927 break;
929 case '-':
931 int s;
933 if (p[2] == 0) { /* -- => stop processing options */
934 stopoptions = 1;
935 break;
938 if (!nasm_stricmp(p, "--v"))
939 show_version();
941 for (s = 0; textopts[s].label; s++) {
942 if (!nasm_stricmp(p + 2, textopts[s].label)) {
943 break;
947 switch (s) {
949 case OPT_PREFIX:
950 case OPT_POSTFIX:
952 if (!q) {
953 nasm_error(ERR_NONFATAL | ERR_NOFILE |
954 ERR_USAGE,
955 "option `--%s' requires an argument",
956 p + 2);
957 break;
958 } else {
959 advance = 1, param = q;
962 switch (s) {
963 case OPT_PREFIX:
964 strlcpy(lprefix, param, PREFIX_MAX);
965 break;
966 case OPT_POSTFIX:
967 strlcpy(lpostfix, param, POSTFIX_MAX);
968 break;
969 default:
970 nasm_error(ERR_PANIC | ERR_NOFILE,
971 "internal error");
972 break;
974 break;
977 default:
979 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
980 "unrecognised option `--%s'", p + 2);
981 break;
984 break;
987 default:
988 if (!ofmt->setinfo(GI_SWITCH, &p))
989 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
990 "unrecognised option `-%c'", p[1]);
991 break;
993 } else {
994 if (*inname) {
995 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
996 "more than one input file specified");
997 } else {
998 copy_filename(inname, p);
1002 return advance;
1005 #define ARG_BUF_DELTA 128
1007 static void process_respfile(FILE * rfile)
1009 char *buffer, *p, *q, *prevarg;
1010 int bufsize, prevargsize;
1012 bufsize = prevargsize = ARG_BUF_DELTA;
1013 buffer = nasm_malloc(ARG_BUF_DELTA);
1014 prevarg = nasm_malloc(ARG_BUF_DELTA);
1015 prevarg[0] = '\0';
1017 while (1) { /* Loop to handle all lines in file */
1018 p = buffer;
1019 while (1) { /* Loop to handle long lines */
1020 q = fgets(p, bufsize - (p - buffer), rfile);
1021 if (!q)
1022 break;
1023 p += strlen(p);
1024 if (p > buffer && p[-1] == '\n')
1025 break;
1026 if (p - buffer > bufsize - 10) {
1027 int offset;
1028 offset = p - buffer;
1029 bufsize += ARG_BUF_DELTA;
1030 buffer = nasm_realloc(buffer, bufsize);
1031 p = buffer + offset;
1035 if (!q && p == buffer) {
1036 if (prevarg[0])
1037 process_arg(prevarg, NULL);
1038 nasm_free(buffer);
1039 nasm_free(prevarg);
1040 return;
1044 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1045 * them are present at the end of the line.
1047 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1049 while (p > buffer && nasm_isspace(p[-1]))
1050 *--p = '\0';
1052 p = nasm_skip_spaces(buffer);
1054 if (process_arg(prevarg, p))
1055 *p = '\0';
1057 if ((int) strlen(p) > prevargsize - 10) {
1058 prevargsize += ARG_BUF_DELTA;
1059 prevarg = nasm_realloc(prevarg, prevargsize);
1061 strncpy(prevarg, p, prevargsize);
1065 /* Function to process args from a string of args, rather than the
1066 * argv array. Used by the environment variable and response file
1067 * processing.
1069 static void process_args(char *args)
1071 char *p, *q, *arg, *prevarg;
1072 char separator = ' ';
1074 p = args;
1075 if (*p && *p != '-')
1076 separator = *p++;
1077 arg = NULL;
1078 while (*p) {
1079 q = p;
1080 while (*p && *p != separator)
1081 p++;
1082 while (*p == separator)
1083 *p++ = '\0';
1084 prevarg = arg;
1085 arg = q;
1086 if (process_arg(prevarg, arg))
1087 arg = NULL;
1089 if (arg)
1090 process_arg(arg, NULL);
1093 static void process_response_file(const char *file)
1095 char str[2048];
1096 FILE *f = fopen(file, "r");
1097 if (!f) {
1098 perror(file);
1099 exit(-1);
1101 while (fgets(str, sizeof str, f)) {
1102 process_args(str);
1104 fclose(f);
1107 static void parse_cmdline(int argc, char **argv)
1109 FILE *rfile;
1110 char *envreal, *envcopy = NULL, *p;
1111 int i;
1113 *inname = *outname = *listname = *errname = '\0';
1115 for (i = 0; i <= ERR_WARN_MAX; i++)
1116 warning_on_global[i] = warnings[i].enabled;
1119 * First, process the NASMENV environment variable.
1121 envreal = getenv("NASMENV");
1122 if (envreal) {
1123 envcopy = nasm_strdup(envreal);
1124 process_args(envcopy);
1125 nasm_free(envcopy);
1129 * Now process the actual command line.
1131 while (--argc) {
1132 bool advance;
1133 argv++;
1134 if (argv[0][0] == '@') {
1136 * We have a response file, so process this as a set of
1137 * arguments like the environment variable. This allows us
1138 * to have multiple arguments on a single line, which is
1139 * different to the -@resp file processing below for regular
1140 * NASM.
1142 process_response_file(argv[0]+1);
1143 argc--;
1144 argv++;
1146 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1147 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1148 if (p) {
1149 rfile = fopen(p, "r");
1150 if (rfile) {
1151 process_respfile(rfile);
1152 fclose(rfile);
1153 } else
1154 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1155 "unable to open response file `%s'", p);
1157 } else
1158 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1159 argv += advance, argc -= advance;
1163 * Look for basic command line typos. This definitely doesn't
1164 * catch all errors, but it might help cases of fumbled fingers.
1166 if (!*inname)
1167 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1168 "no input file specified");
1169 else if (!strcmp(inname, errname) ||
1170 !strcmp(inname, outname) ||
1171 !strcmp(inname, listname) ||
1172 (depend_file && !strcmp(inname, depend_file)))
1173 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1174 "file `%s' is both input and output file",
1175 inname);
1177 if (*errname) {
1178 error_file = fopen(errname, "w");
1179 if (!error_file) {
1180 error_file = stderr; /* Revert to default! */
1181 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1182 "cannot open file `%s' for error messages",
1183 errname);
1188 static enum directives getkw(char **directive, char **value);
1190 static void assemble_file(char *fname, StrList **depend_ptr)
1192 char *directive, *value, *p, *q, *special, *line;
1193 insn output_ins;
1194 int i, validid;
1195 bool rn_error;
1196 int32_t seg;
1197 int64_t offs;
1198 struct tokenval tokval;
1199 expr *e;
1200 int pass_max;
1202 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1203 nasm_error(ERR_FATAL, "command line: "
1204 "32-bit segment size requires a higher cpu");
1206 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1207 for (passn = 1; pass0 <= 2; passn++) {
1208 int pass1, pass2;
1209 ldfunc def_label;
1211 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1212 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1213 /* pass0 0, 0, 0, ..., 1, 2 */
1215 def_label = passn > 1 ? redefine_label : define_label;
1217 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1218 cpu = cmd_cpu;
1219 if (pass0 == 2) {
1220 if (*listname)
1221 nasmlist.init(listname, nasm_error);
1223 in_abs_seg = false;
1224 global_offset_changed = 0; /* set by redefine_label */
1225 location.segment = ofmt->section(NULL, pass2, &sb);
1226 globalbits = sb;
1227 if (passn > 1) {
1228 saa_rewind(forwrefs);
1229 forwref = saa_rstruct(forwrefs);
1230 raa_free(offsets);
1231 offsets = raa_init();
1233 preproc->reset(fname, pass1, &nasmlist,
1234 pass1 == 2 ? depend_ptr : NULL);
1235 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1237 globallineno = 0;
1238 if (passn == 1)
1239 location.known = true;
1240 location.offset = offs = get_curr_offs();
1242 while ((line = preproc->getline())) {
1243 enum directives d;
1244 globallineno++;
1247 * Here we parse our directives; this is not handled by the
1248 * 'real' parser. This really should be a separate function.
1250 directive = line;
1251 d = getkw(&directive, &value);
1252 if (d) {
1253 int err = 0;
1255 switch (d) {
1256 case D_SEGMENT: /* [SEGMENT n] */
1257 case D_SECTION:
1258 seg = ofmt->section(value, pass2, &sb);
1259 if (seg == NO_SEG) {
1260 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1261 "segment name `%s' not recognized",
1262 value);
1263 } else {
1264 in_abs_seg = false;
1265 location.segment = seg;
1267 break;
1268 case D_SECTALIGN: /* [SECTALIGN n] */
1269 if (*value) {
1270 stdscan_reset();
1271 stdscan_set(value);
1272 tokval.t_type = TOKEN_INVALID;
1273 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1274 if (e) {
1275 unsigned int align = (unsigned int)e->value;
1276 if ((uint64_t)e->value > 0x7fffffff) {
1278 * FIXME: Please make some sane message here
1279 * ofmt should have some 'check' method which
1280 * would report segment alignment bounds.
1282 nasm_error(ERR_FATAL,
1283 "incorrect segment alignment `%s'", value);
1284 } else if (!is_power2(align)) {
1285 nasm_error(ERR_NONFATAL,
1286 "segment alignment `%s' is not power of two",
1287 value);
1290 /* callee should be able to handle all details */
1291 if (location.segment != NO_SEG)
1292 ofmt->sectalign(location.segment, align);
1295 break;
1296 case D_EXTERN: /* [EXTERN label:special] */
1297 if (*value == '$')
1298 value++; /* skip initial $ if present */
1299 if (pass0 == 2) {
1300 q = value;
1301 while (*q && *q != ':')
1302 q++;
1303 if (*q == ':') {
1304 *q++ = '\0';
1305 ofmt->symdef(value, 0L, 0L, 3, q);
1307 } else if (passn == 1) {
1308 q = value;
1309 validid = true;
1310 if (!isidstart(*q))
1311 validid = false;
1312 while (*q && *q != ':') {
1313 if (!isidchar(*q))
1314 validid = false;
1315 q++;
1317 if (!validid) {
1318 nasm_error(ERR_NONFATAL,
1319 "identifier expected after EXTERN");
1320 break;
1322 if (*q == ':') {
1323 *q++ = '\0';
1324 special = q;
1325 } else
1326 special = NULL;
1327 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1328 int temp = pass0;
1329 pass0 = 1; /* fake pass 1 in labels.c */
1330 declare_as_global(value, special);
1331 define_label(value, seg_alloc(), 0L, NULL,
1332 false, true);
1333 pass0 = temp;
1335 } /* else pass0 == 1 */
1336 break;
1337 case D_BITS: /* [BITS bits] */
1338 globalbits = sb = get_bits(value);
1339 break;
1340 case D_GLOBAL: /* [GLOBAL symbol:special] */
1341 if (*value == '$')
1342 value++; /* skip initial $ if present */
1343 if (pass0 == 2) { /* pass 2 */
1344 q = value;
1345 while (*q && *q != ':')
1346 q++;
1347 if (*q == ':') {
1348 *q++ = '\0';
1349 ofmt->symdef(value, 0L, 0L, 3, q);
1351 } else if (pass2 == 1) { /* pass == 1 */
1352 q = value;
1353 validid = true;
1354 if (!isidstart(*q))
1355 validid = false;
1356 while (*q && *q != ':') {
1357 if (!isidchar(*q))
1358 validid = false;
1359 q++;
1361 if (!validid) {
1362 nasm_error(ERR_NONFATAL,
1363 "identifier expected after GLOBAL");
1364 break;
1366 if (*q == ':') {
1367 *q++ = '\0';
1368 special = q;
1369 } else
1370 special = NULL;
1371 declare_as_global(value, special);
1372 } /* pass == 1 */
1373 break;
1374 case D_COMMON: /* [COMMON symbol size:special] */
1376 int64_t size;
1378 if (*value == '$')
1379 value++; /* skip initial $ if present */
1380 p = value;
1381 validid = true;
1382 if (!isidstart(*p))
1383 validid = false;
1384 while (*p && !nasm_isspace(*p)) {
1385 if (!isidchar(*p))
1386 validid = false;
1387 p++;
1389 if (!validid) {
1390 nasm_error(ERR_NONFATAL,
1391 "identifier expected after COMMON");
1392 break;
1394 if (*p) {
1395 p = nasm_zap_spaces_fwd(p);
1396 q = p;
1397 while (*q && *q != ':')
1398 q++;
1399 if (*q == ':') {
1400 *q++ = '\0';
1401 special = q;
1402 } else {
1403 special = NULL;
1405 size = readnum(p, &rn_error);
1406 if (rn_error) {
1407 nasm_error(ERR_NONFATAL,
1408 "invalid size specified"
1409 " in COMMON declaration");
1410 break;
1412 } else {
1413 nasm_error(ERR_NONFATAL,
1414 "no size specified in"
1415 " COMMON declaration");
1416 break;
1419 if (pass0 < 2) {
1420 define_common(value, seg_alloc(), size, special);
1421 } else if (pass0 == 2) {
1422 if (special)
1423 ofmt->symdef(value, 0L, 0L, 3, special);
1425 break;
1427 case D_ABSOLUTE: /* [ABSOLUTE address] */
1428 stdscan_reset();
1429 stdscan_set(value);
1430 tokval.t_type = TOKEN_INVALID;
1431 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1432 nasm_error, NULL);
1433 if (e) {
1434 if (!is_reloc(e))
1435 nasm_error(pass0 ==
1436 1 ? ERR_NONFATAL : ERR_PANIC,
1437 "cannot use non-relocatable expression as "
1438 "ABSOLUTE address");
1439 else {
1440 abs_seg = reloc_seg(e);
1441 abs_offset = reloc_value(e);
1443 } else if (passn == 1)
1444 abs_offset = 0x100; /* don't go near zero in case of / */
1445 else
1446 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1447 "in pass two");
1448 in_abs_seg = true;
1449 location.segment = NO_SEG;
1450 break;
1451 case D_DEBUG: /* [DEBUG] */
1453 char debugid[128];
1454 bool badid, overlong;
1456 p = value;
1457 q = debugid;
1458 badid = overlong = false;
1459 if (!isidstart(*p)) {
1460 badid = true;
1461 } else {
1462 while (*p && !nasm_isspace(*p)) {
1463 if (q >= debugid + sizeof debugid - 1) {
1464 overlong = true;
1465 break;
1467 if (!isidchar(*p))
1468 badid = true;
1469 *q++ = *p++;
1471 *q = 0;
1473 if (badid) {
1474 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1475 "identifier expected after DEBUG");
1476 break;
1478 if (overlong) {
1479 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1480 "DEBUG identifier too long");
1481 break;
1483 p = nasm_skip_spaces(p);
1484 if (pass0 == 2)
1485 dfmt->debug_directive(debugid, p);
1486 break;
1488 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1489 value = nasm_skip_spaces(value);
1490 switch(*value) {
1491 case '-': validid = 0; value++; break;
1492 case '+': validid = 1; value++; break;
1493 case '*': validid = 2; value++; break;
1494 default: validid = 1; break;
1497 for (i = 1; i <= ERR_WARN_MAX; i++)
1498 if (!nasm_stricmp(value, warnings[i].name))
1499 break;
1500 if (i <= ERR_WARN_MAX) {
1501 switch(validid) {
1502 case 0:
1503 warning_on[i] = false;
1504 break;
1505 case 1:
1506 warning_on[i] = true;
1507 break;
1508 case 2:
1509 warning_on[i] = warning_on_global[i];
1510 break;
1512 } else
1513 nasm_error(ERR_NONFATAL,
1514 "invalid warning id in WARNING directive");
1515 break;
1516 case D_CPU: /* [CPU] */
1517 cpu = get_cpu(value);
1518 break;
1519 case D_LIST: /* [LIST {+|-}] */
1520 value = nasm_skip_spaces(value);
1521 if (*value == '+') {
1522 user_nolist = 0;
1523 } else {
1524 if (*value == '-') {
1525 user_nolist = 1;
1526 } else {
1527 err = 1;
1530 break;
1531 case D_DEFAULT: /* [DEFAULT] */
1532 stdscan_reset();
1533 stdscan_set(value);
1534 tokval.t_type = TOKEN_INVALID;
1535 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1536 switch ((int)tokval.t_integer) {
1537 case S_REL:
1538 globalrel = 1;
1539 break;
1540 case S_ABS:
1541 globalrel = 0;
1542 break;
1543 case P_BND:
1544 globalbnd = 1;
1545 break;
1546 case P_NOBND:
1547 globalbnd = 0;
1548 break;
1549 default:
1550 err = 1;
1551 break;
1553 } else {
1554 err = 1;
1556 break;
1557 case D_FLOAT:
1558 if (float_option(value)) {
1559 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1560 "unknown 'float' directive: %s",
1561 value);
1563 break;
1564 default:
1565 if (ofmt->directive(d, value, pass2))
1566 break;
1567 /* else fall through */
1568 case D_unknown:
1569 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1570 "unrecognised directive [%s]",
1571 directive);
1572 break;
1574 if (err) {
1575 nasm_error(ERR_NONFATAL,
1576 "invalid parameter to [%s] directive",
1577 directive);
1579 } else { /* it isn't a directive */
1580 parse_line(pass1, line, &output_ins, def_label);
1582 if (optimizing > 0) {
1583 if (forwref != NULL && globallineno == forwref->lineno) {
1584 output_ins.forw_ref = true;
1585 do {
1586 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1587 forwref = saa_rstruct(forwrefs);
1588 } while (forwref != NULL
1589 && forwref->lineno == globallineno);
1590 } else
1591 output_ins.forw_ref = false;
1593 if (output_ins.forw_ref) {
1594 if (passn == 1) {
1595 for (i = 0; i < output_ins.operands; i++) {
1596 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1597 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1598 fwinf->lineno = globallineno;
1599 fwinf->operand = i;
1606 /* forw_ref */
1607 if (output_ins.opcode == I_EQU) {
1608 if (pass1 == 1) {
1610 * Special `..' EQUs get processed in pass two,
1611 * except `..@' macro-processor EQUs which are done
1612 * in the normal place.
1614 if (!output_ins.label)
1615 nasm_error(ERR_NONFATAL,
1616 "EQU not preceded by label");
1618 else if (output_ins.label[0] != '.' ||
1619 output_ins.label[1] != '.' ||
1620 output_ins.label[2] == '@') {
1621 if (output_ins.operands == 1 &&
1622 (output_ins.oprs[0].type & IMMEDIATE) &&
1623 output_ins.oprs[0].wrt == NO_SEG) {
1624 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1625 def_label(output_ins.label,
1626 output_ins.oprs[0].segment,
1627 output_ins.oprs[0].offset, NULL,
1628 false, isext);
1629 } else if (output_ins.operands == 2
1630 && (output_ins.oprs[0].type & IMMEDIATE)
1631 && (output_ins.oprs[0].type & COLON)
1632 && output_ins.oprs[0].segment == NO_SEG
1633 && output_ins.oprs[0].wrt == NO_SEG
1634 && (output_ins.oprs[1].type & IMMEDIATE)
1635 && output_ins.oprs[1].segment == NO_SEG
1636 && output_ins.oprs[1].wrt == NO_SEG) {
1637 def_label(output_ins.label,
1638 output_ins.oprs[0].offset | SEG_ABS,
1639 output_ins.oprs[1].offset,
1640 NULL, false, false);
1641 } else
1642 nasm_error(ERR_NONFATAL,
1643 "bad syntax for EQU");
1645 } else {
1647 * Special `..' EQUs get processed here, except
1648 * `..@' macro processor EQUs which are done above.
1650 if (output_ins.label[0] == '.' &&
1651 output_ins.label[1] == '.' &&
1652 output_ins.label[2] != '@') {
1653 if (output_ins.operands == 1 &&
1654 (output_ins.oprs[0].type & IMMEDIATE)) {
1655 define_label(output_ins.label,
1656 output_ins.oprs[0].segment,
1657 output_ins.oprs[0].offset,
1658 NULL, false, false);
1659 } else if (output_ins.operands == 2
1660 && (output_ins.oprs[0].type & IMMEDIATE)
1661 && (output_ins.oprs[0].type & COLON)
1662 && output_ins.oprs[0].segment == NO_SEG
1663 && (output_ins.oprs[1].type & IMMEDIATE)
1664 && output_ins.oprs[1].segment == NO_SEG) {
1665 define_label(output_ins.label,
1666 output_ins.oprs[0].offset | SEG_ABS,
1667 output_ins.oprs[1].offset,
1668 NULL, false, false);
1669 } else
1670 nasm_error(ERR_NONFATAL,
1671 "bad syntax for EQU");
1674 } else { /* instruction isn't an EQU */
1676 if (pass1 == 1) {
1678 int64_t l = insn_size(location.segment, offs, sb, cpu,
1679 &output_ins, nasm_error);
1681 /* if (using_debug_info) && output_ins.opcode != -1) */
1682 if (using_debug_info)
1683 { /* fbk 03/25/01 */
1684 /* this is done here so we can do debug type info */
1685 int32_t typeinfo =
1686 TYS_ELEMENTS(output_ins.operands);
1687 switch (output_ins.opcode) {
1688 case I_RESB:
1689 typeinfo =
1690 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1691 break;
1692 case I_RESW:
1693 typeinfo =
1694 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1695 break;
1696 case I_RESD:
1697 typeinfo =
1698 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1699 break;
1700 case I_RESQ:
1701 typeinfo =
1702 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1703 break;
1704 case I_REST:
1705 typeinfo =
1706 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1707 break;
1708 case I_RESO:
1709 typeinfo =
1710 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1711 break;
1712 case I_RESY:
1713 typeinfo =
1714 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1715 break;
1716 case I_DB:
1717 typeinfo |= TY_BYTE;
1718 break;
1719 case I_DW:
1720 typeinfo |= TY_WORD;
1721 break;
1722 case I_DD:
1723 if (output_ins.eops_float)
1724 typeinfo |= TY_FLOAT;
1725 else
1726 typeinfo |= TY_DWORD;
1727 break;
1728 case I_DQ:
1729 typeinfo |= TY_QWORD;
1730 break;
1731 case I_DT:
1732 typeinfo |= TY_TBYTE;
1733 break;
1734 case I_DO:
1735 typeinfo |= TY_OWORD;
1736 break;
1737 case I_DY:
1738 typeinfo |= TY_YWORD;
1739 break;
1740 default:
1741 typeinfo = TY_LABEL;
1745 dfmt->debug_typevalue(typeinfo);
1747 if (l != -1) {
1748 offs += l;
1749 set_curr_offs(offs);
1752 * else l == -1 => invalid instruction, which will be
1753 * flagged as an error on pass 2
1756 } else {
1757 offs += assemble(location.segment, offs, sb, cpu,
1758 &output_ins, ofmt, nasm_error,
1759 &nasmlist);
1760 set_curr_offs(offs);
1763 } /* not an EQU */
1764 cleanup_insn(&output_ins);
1766 nasm_free(line);
1767 location.offset = offs = get_curr_offs();
1768 } /* end while (line = preproc->getline... */
1770 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1771 nasm_error(ERR_NONFATAL,
1772 "phase error detected at end of assembly.");
1774 if (pass1 == 1)
1775 preproc->cleanup(1);
1777 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1778 pass0++;
1779 } else if (global_offset_changed &&
1780 global_offset_changed < prev_offset_changed) {
1781 prev_offset_changed = global_offset_changed;
1782 stall_count = 0;
1783 } else {
1784 stall_count++;
1787 if (terminate_after_phase)
1788 break;
1790 if ((stall_count > 997) || (passn >= pass_max)) {
1791 /* We get here if the labels don't converge
1792 * Example: FOO equ FOO + 1
1794 nasm_error(ERR_NONFATAL,
1795 "Can't find valid values for all labels "
1796 "after %d passes, giving up.", passn);
1797 nasm_error(ERR_NONFATAL,
1798 "Possible causes: recursive EQUs, macro abuse.");
1799 break;
1803 preproc->cleanup(0);
1804 nasmlist.cleanup();
1805 if (!terminate_after_phase && opt_verbose_info) {
1806 /* -On and -Ov switches */
1807 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1811 static enum directives getkw(char **directive, char **value)
1813 char *p, *q, *buf;
1815 buf = nasm_skip_spaces(*directive);
1817 /* it should be enclosed in [ ] */
1818 if (*buf != '[')
1819 return D_none;
1820 q = strchr(buf, ']');
1821 if (!q)
1822 return D_none;
1824 /* stip off the comments */
1825 p = strchr(buf, ';');
1826 if (p) {
1827 if (p < q) /* ouch! somwhere inside */
1828 return D_none;
1829 *p = '\0';
1832 /* no brace, no trailing spaces */
1833 *q = '\0';
1834 nasm_zap_spaces_rev(--q);
1836 /* directive */
1837 p = nasm_skip_spaces(++buf);
1838 q = nasm_skip_word(p);
1839 if (!q)
1840 return D_none; /* sigh... no value there */
1841 *q = '\0';
1842 *directive = p;
1844 /* and value finally */
1845 p = nasm_skip_spaces(++q);
1846 *value = p;
1848 return find_directive(*directive);
1852 * gnu style error reporting
1853 * This function prints an error message to error_file in the
1854 * style used by GNU. An example would be:
1855 * file.asm:50: error: blah blah blah
1856 * where file.asm is the name of the file, 50 is the line number on
1857 * which the error occurs (or is detected) and "error:" is one of
1858 * the possible optional diagnostics -- it can be "error" or "warning"
1859 * or something else. Finally the line terminates with the actual
1860 * error message.
1862 * @param severity the severity of the warning or error
1863 * @param fmt the printf style format string
1865 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1867 char *currentfile = NULL;
1868 int32_t lineno = 0;
1870 if (is_suppressed_warning(severity))
1871 return;
1873 if (!(severity & ERR_NOFILE))
1874 src_get(&lineno, &currentfile);
1876 if (currentfile) {
1877 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1878 nasm_free(currentfile);
1879 } else {
1880 fputs("nasm: ", error_file);
1883 nasm_verror_common(severity, fmt, ap);
1887 * MS style error reporting
1888 * This function prints an error message to error_file in the
1889 * style used by Visual C and some other Microsoft tools. An example
1890 * would be:
1891 * file.asm(50) : error: blah blah blah
1892 * where file.asm is the name of the file, 50 is the line number on
1893 * which the error occurs (or is detected) and "error:" is one of
1894 * the possible optional diagnostics -- it can be "error" or "warning"
1895 * or something else. Finally the line terminates with the actual
1896 * error message.
1898 * @param severity the severity of the warning or error
1899 * @param fmt the printf style format string
1901 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1903 char *currentfile = NULL;
1904 int32_t lineno = 0;
1906 if (is_suppressed_warning(severity))
1907 return;
1909 if (!(severity & ERR_NOFILE))
1910 src_get(&lineno, &currentfile);
1912 if (currentfile) {
1913 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1914 nasm_free(currentfile);
1915 } else {
1916 fputs("nasm: ", error_file);
1919 nasm_verror_common(severity, fmt, ap);
1923 * check for supressed warning
1924 * checks for suppressed warning or pass one only warning and we're
1925 * not in pass 1
1927 * @param severity the severity of the warning or error
1928 * @return true if we should abort error/warning printing
1930 static bool is_suppressed_warning(int severity)
1932 /* Not a warning at all */
1933 if ((severity & ERR_MASK) != ERR_WARNING)
1934 return false;
1936 /* See if it's a pass-one only warning and we're not in pass one. */
1937 if (((severity & ERR_PASS1) && pass0 != 1) ||
1938 ((severity & ERR_PASS2) && pass0 != 2))
1939 return true;
1941 /* Might be a warning but suppresed explicitly */
1942 if (severity & ERR_WARN_MASK)
1943 return !warning_on[WARN_IDX(severity)];
1944 else
1945 return false;
1949 * common error reporting
1950 * This is the common back end of the error reporting schemes currently
1951 * implemented. It prints the nature of the warning and then the
1952 * specific error message to error_file and may or may not return. It
1953 * doesn't return if the error severity is a "panic" or "debug" type.
1955 * @param severity the severity of the warning or error
1956 * @param fmt the printf style format string
1958 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1960 char msg[1024];
1961 const char *pfx;
1963 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1964 case ERR_WARNING:
1965 pfx = "warning: ";
1966 break;
1967 case ERR_NONFATAL:
1968 pfx = "error: ";
1969 break;
1970 case ERR_FATAL:
1971 pfx = "fatal: ";
1972 break;
1973 case ERR_PANIC:
1974 pfx = "panic: ";
1975 break;
1976 case ERR_DEBUG:
1977 pfx = "debug: ";
1978 break;
1979 default:
1980 pfx = "";
1981 break;
1984 vsnprintf(msg, sizeof msg, fmt, args);
1986 fprintf(error_file, "%s%s\n", pfx, msg);
1988 if (*listname)
1989 nasmlist.error(severity, pfx, msg);
1991 if (severity & ERR_USAGE)
1992 want_usage = true;
1994 switch (severity & ERR_MASK) {
1995 case ERR_DEBUG:
1996 /* no further action, by definition */
1997 break;
1998 case ERR_WARNING:
1999 /* Treat warnings as errors */
2000 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
2001 terminate_after_phase = true;
2002 break;
2003 case ERR_NONFATAL:
2004 terminate_after_phase = true;
2005 break;
2006 case ERR_FATAL:
2007 if (ofile) {
2008 fclose(ofile);
2009 remove(outname);
2010 ofile = NULL;
2012 if (want_usage)
2013 usage();
2014 exit(1); /* instantly die */
2015 break; /* placate silly compilers */
2016 case ERR_PANIC:
2017 fflush(NULL);
2018 /* abort(); */ /* halt, catch fire, and dump core */
2019 exit(3);
2020 break;
2024 static void usage(void)
2026 fputs("type `nasm -h' for help\n", error_file);
2029 static iflag_t get_cpu(char *value)
2031 iflag_t r;
2033 iflag_clear_all(&r);
2035 if (!strcmp(value, "8086"))
2036 iflag_set(&r, IF_8086);
2037 else if (!strcmp(value, "186"))
2038 iflag_set(&r, IF_186);
2039 else if (!strcmp(value, "286"))
2040 iflag_set(&r, IF_286);
2041 else if (!strcmp(value, "386"))
2042 iflag_set(&r, IF_386);
2043 else if (!strcmp(value, "486"))
2044 iflag_set(&r, IF_486);
2045 else if (!strcmp(value, "586") ||
2046 !nasm_stricmp(value, "pentium"))
2047 iflag_set(&r, IF_PENT);
2048 else if (!strcmp(value, "686") ||
2049 !nasm_stricmp(value, "ppro") ||
2050 !nasm_stricmp(value, "pentiumpro") ||
2051 !nasm_stricmp(value, "p2"))
2052 iflag_set(&r, IF_P6);
2053 else if (!nasm_stricmp(value, "p3") ||
2054 !nasm_stricmp(value, "katmai"))
2055 iflag_set(&r, IF_KATMAI);
2056 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2057 !nasm_stricmp(value, "willamette"))
2058 iflag_set(&r, IF_WILLAMETTE);
2059 else if (!nasm_stricmp(value, "prescott"))
2060 iflag_set(&r, IF_PRESCOTT);
2061 else if (!nasm_stricmp(value, "x64") ||
2062 !nasm_stricmp(value, "x86-64"))
2063 iflag_set(&r, IF_X86_64);
2064 else if (!nasm_stricmp(value, "ia64") ||
2065 !nasm_stricmp(value, "ia-64") ||
2066 !nasm_stricmp(value, "itanium")||
2067 !nasm_stricmp(value, "itanic") ||
2068 !nasm_stricmp(value, "merced"))
2069 iflag_set(&r, IF_IA64);
2070 else {
2071 iflag_set(&r, IF_PLEVEL);
2072 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2073 "unknown 'cpu' type");
2075 return r;
2078 static int get_bits(char *value)
2080 int i;
2082 if ((i = atoi(value)) == 16)
2083 return i; /* set for a 16-bit segment */
2084 else if (i == 32) {
2085 if (iflag_ffs(&cpu) < IF_386) {
2086 nasm_error(ERR_NONFATAL,
2087 "cannot specify 32-bit segment on processor below a 386");
2088 i = 16;
2090 } else if (i == 64) {
2091 if (iflag_ffs(&cpu) < IF_X86_64) {
2092 nasm_error(ERR_NONFATAL,
2093 "cannot specify 64-bit segment on processor below an x86-64");
2094 i = 16;
2096 } else {
2097 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2098 "`%s' is not a valid segment size; must be 16, 32 or 64",
2099 value);
2100 i = 16;
2102 return i;