changes.src: changelog for 2.11.01
[nasm.git] / nasm.c
blob2bb30292164b788615d2257b91177e8b101ac75d
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2013 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 maxbits = 0;
91 int globalrel = 0;
92 int globalbnd = 0;
94 static time_t official_compile_time;
96 static char inname[FILENAME_MAX];
97 static char outname[FILENAME_MAX];
98 static char listname[FILENAME_MAX];
99 static char errname[FILENAME_MAX];
100 static int globallineno; /* for forward-reference tracking */
101 /* static int pass = 0; */
102 struct ofmt *ofmt = &OF_DEFAULT;
103 struct ofmt_alias *ofmt_alias = NULL;
104 const struct dfmt *dfmt;
106 static FILE *error_file; /* Where to write error messages */
108 FILE *ofile = NULL;
109 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
110 static int sb, cmd_sb = 16; /* by default */
112 static iflag_t cpu;
113 static iflag_t cmd_cpu;
115 int64_t global_offset_changed; /* referenced in labels.c */
116 int64_t prev_offset_changed;
117 int32_t stall_count;
119 static struct location location;
120 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
121 int32_t abs_seg; /* ABSOLUTE segment basis */
122 int32_t abs_offset; /* ABSOLUTE offset */
124 static struct RAA *offsets;
126 static struct SAA *forwrefs; /* keep track of forward references */
127 static const struct forwrefinfo *forwref;
129 static struct preproc_ops *preproc;
131 enum op_type {
132 op_normal, /* Preprocess and assemble */
133 op_preprocess, /* Preprocess only */
134 op_depend, /* Generate dependencies */
136 static enum op_type operating_mode;
137 /* Dependency flags */
138 static bool depend_emit_phony = false;
139 static bool depend_missing_ok = false;
140 static const char *depend_target = NULL;
141 static const char *depend_file = NULL;
144 * Which of the suppressible warnings are suppressed. Entry zero
145 * isn't an actual warning, but it used for -w+error/-Werror.
148 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
149 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
151 static const struct warning {
152 const char *name;
153 const char *help;
154 bool enabled;
155 } warnings[ERR_WARN_MAX+1] = {
156 {"error", "treat warnings as errors", false},
157 {"macro-params", "macro calls with wrong parameter count", true},
158 {"macro-selfref", "cyclic macro references", false},
159 {"macro-defaults", "macros with more default than optional parameters", true},
160 {"orphan-labels", "labels alone on lines without trailing `:'", true},
161 {"number-overflow", "numeric constant does not fit", true},
162 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
163 {"float-overflow", "floating point overflow", true},
164 {"float-denorm", "floating point denormal", false},
165 {"float-underflow", "floating point underflow", false},
166 {"float-toolong", "too many digits in floating-point number", true},
167 {"user", "%warning directives", true},
168 {"lock", "lock prefix on unlockable instructions", true},
169 {"hle", "invalid hle prefixes", true},
170 {"bnd", "invalid bnd prefixes", 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 posix_mktime(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 = posix_mktime(&gm);
257 else if (lt_p)
258 posix_time = posix_mktime(&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 nasm_init_malloc_error();
341 offsets = raa_init();
342 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
344 preproc = &nasmpp;
345 operating_mode = op_normal;
347 seg_init();
349 /* Define some macros dependent on the runtime, but not
350 on the command line. */
351 define_macros_early();
353 parse_cmdline(argc, argv);
355 if (terminate_after_phase) {
356 if (want_usage)
357 usage();
358 return 1;
361 /* If debugging info is disabled, suppress any debug calls */
362 if (!using_debug_info)
363 ofmt->current_dfmt = &null_debug_form;
365 if (ofmt->stdmac)
366 preproc->extra_stdmac(ofmt->stdmac);
367 parser_global_info(&location);
368 eval_global_info(ofmt, lookup_label, &location);
370 /* define some macros dependent of command-line */
371 define_macros_late();
373 depend_ptr = (depend_file || (operating_mode == op_depend)) ? &depend_list : NULL;
374 if (!depend_target)
375 depend_target = quote_for_make(outname);
377 switch (operating_mode) {
378 case op_depend:
380 char *line;
382 if (depend_missing_ok)
383 preproc->include_path(NULL); /* "assume generated" */
385 preproc->reset(inname, 0, &nasmlist, depend_ptr);
386 if (outname[0] == '\0')
387 ofmt->filename(inname, outname);
388 ofile = NULL;
389 while ((line = preproc->getline()))
390 nasm_free(line);
391 preproc->cleanup(0);
393 break;
395 case op_preprocess:
397 char *line;
398 char *file_name = NULL;
399 int32_t prior_linnum = 0;
400 int lineinc = 0;
402 if (*outname) {
403 ofile = fopen(outname, "w");
404 if (!ofile)
405 nasm_error(ERR_FATAL | ERR_NOFILE,
406 "unable to open output file `%s'",
407 outname);
408 } else
409 ofile = NULL;
411 location.known = false;
413 /* pass = 1; */
414 preproc->reset(inname, 3, &nasmlist, depend_ptr);
415 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
417 while ((line = preproc->getline())) {
419 * We generate %line directives if needed for later programs
421 int32_t linnum = prior_linnum += lineinc;
422 int altline = src_get(&linnum, &file_name);
423 if (altline) {
424 if (altline == 1 && lineinc == 1)
425 nasm_fputs("", ofile);
426 else {
427 lineinc = (altline != -1 || lineinc != 1);
428 fprintf(ofile ? ofile : stdout,
429 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
430 file_name);
432 prior_linnum = linnum;
434 nasm_fputs(line, ofile);
435 nasm_free(line);
437 nasm_free(file_name);
438 preproc->cleanup(0);
439 if (ofile)
440 fclose(ofile);
441 if (ofile && terminate_after_phase)
442 remove(outname);
443 ofile = NULL;
445 break;
447 case op_normal:
450 * We must call ofmt->filename _anyway_, even if the user
451 * has specified their own output file, because some
452 * formats (eg OBJ and COFF) use ofmt->filename to find out
453 * the name of the input file and then put that inside the
454 * file.
456 ofmt->filename(inname, outname);
458 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
459 if (!ofile) {
460 nasm_error(ERR_FATAL | ERR_NOFILE,
461 "unable to open output file `%s'", outname);
465 * We must call init_labels() before ofmt->init() since
466 * some object formats will want to define labels in their
467 * init routines. (eg OS/2 defines the FLAT group)
469 init_labels();
471 ofmt->init();
472 dfmt = ofmt->current_dfmt;
473 dfmt->init();
475 assemble_file(inname, depend_ptr);
477 if (!terminate_after_phase) {
478 ofmt->cleanup(using_debug_info);
479 cleanup_labels();
480 fflush(ofile);
481 if (ferror(ofile)) {
482 nasm_error(ERR_NONFATAL|ERR_NOFILE,
483 "write error on output file `%s'", outname);
487 if (ofile) {
488 fclose(ofile);
489 if (terminate_after_phase)
490 remove(outname);
491 ofile = NULL;
494 break;
497 if (depend_list && !terminate_after_phase)
498 emit_dependencies(depend_list);
500 if (want_usage)
501 usage();
503 raa_free(offsets);
504 saa_free(forwrefs);
505 eval_cleanup();
506 stdscan_cleanup();
508 return terminate_after_phase;
512 * Get a parameter for a command line option.
513 * First arg must be in the form of e.g. -f...
515 static char *get_param(char *p, char *q, bool *advance)
517 *advance = false;
518 if (p[2]) /* the parameter's in the option */
519 return nasm_skip_spaces(p + 2);
520 if (q && q[0]) {
521 *advance = true;
522 return q;
524 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
525 "option `-%c' requires an argument", p[1]);
526 return NULL;
530 * Copy a filename
532 static void copy_filename(char *dst, const char *src)
534 size_t len = strlen(src);
536 if (len >= (size_t)FILENAME_MAX) {
537 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
538 return;
540 strncpy(dst, src, FILENAME_MAX);
544 * Convert a string to Make-safe form
546 static char *quote_for_make(const char *str)
548 const char *p;
549 char *os, *q;
551 size_t n = 1; /* Terminating zero */
552 size_t nbs = 0;
554 if (!str)
555 return NULL;
557 for (p = str; *p; p++) {
558 switch (*p) {
559 case ' ':
560 case '\t':
561 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
562 n += nbs + 2;
563 nbs = 0;
564 break;
565 case '$':
566 case '#':
567 nbs = 0;
568 n += 2;
569 break;
570 case '\\':
571 nbs++;
572 n++;
573 break;
574 default:
575 nbs = 0;
576 n++;
577 break;
581 /* Convert N backslashes at the end of filename to 2N backslashes */
582 if (nbs)
583 n += nbs;
585 os = q = nasm_malloc(n);
587 nbs = 0;
588 for (p = str; *p; p++) {
589 switch (*p) {
590 case ' ':
591 case '\t':
592 while (nbs--)
593 *q++ = '\\';
594 *q++ = '\\';
595 *q++ = *p;
596 break;
597 case '$':
598 *q++ = *p;
599 *q++ = *p;
600 nbs = 0;
601 break;
602 case '#':
603 *q++ = '\\';
604 *q++ = *p;
605 nbs = 0;
606 break;
607 case '\\':
608 *q++ = *p;
609 nbs++;
610 break;
611 default:
612 *q++ = *p;
613 nbs = 0;
614 break;
617 while (nbs--)
618 *q++ = '\\';
620 *q = '\0';
622 return os;
625 struct textargs {
626 const char *label;
627 int value;
630 #define OPT_PREFIX 0
631 #define OPT_POSTFIX 1
632 struct textargs textopts[] = {
633 {"prefix", OPT_PREFIX},
634 {"postfix", OPT_POSTFIX},
635 {NULL, 0}
638 static bool stopoptions = false;
639 static bool process_arg(char *p, char *q)
641 char *param;
642 int i;
643 bool advance = false;
644 bool do_warn;
646 if (!p || !p[0])
647 return false;
649 if (p[0] == '-' && !stopoptions) {
650 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
651 /* These parameters take values */
652 if (!(param = get_param(p, q, &advance)))
653 return advance;
656 switch (p[1]) {
657 case 's':
658 error_file = stdout;
659 break;
661 case 'o': /* output file */
662 copy_filename(outname, param);
663 break;
665 case 'f': /* output format */
666 ofmt = ofmt_find(param, &ofmt_alias);
667 if (!ofmt) {
668 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
669 "unrecognised output format `%s' - "
670 "use -hf for a list", param);
672 break;
674 case 'O': /* Optimization level */
676 int opt;
678 if (!*param) {
679 /* Naked -O == -Ox */
680 optimizing = MAX_OPTIMIZE;
681 } else {
682 while (*param) {
683 switch (*param) {
684 case '0': case '1': case '2': case '3': case '4':
685 case '5': case '6': case '7': case '8': case '9':
686 opt = strtoul(param, &param, 10);
688 /* -O0 -> optimizing == -1, 0.98 behaviour */
689 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
690 if (opt < 2)
691 optimizing = opt - 1;
692 else
693 optimizing = opt;
694 break;
696 case 'v':
697 case '+':
698 param++;
699 opt_verbose_info = true;
700 break;
702 case 'x':
703 param++;
704 optimizing = MAX_OPTIMIZE;
705 break;
707 default:
708 nasm_error(ERR_FATAL,
709 "unknown optimization option -O%c\n",
710 *param);
711 break;
714 if (optimizing > MAX_OPTIMIZE)
715 optimizing = MAX_OPTIMIZE;
717 break;
720 case 'p': /* pre-include */
721 case 'P':
722 preproc->pre_include(param);
723 break;
725 case 'd': /* pre-define */
726 case 'D':
727 preproc->pre_define(param);
728 break;
730 case 'u': /* un-define */
731 case 'U':
732 preproc->pre_undefine(param);
733 break;
735 case 'i': /* include search path */
736 case 'I':
737 preproc->include_path(param);
738 break;
740 case 'l': /* listing file */
741 copy_filename(listname, param);
742 break;
744 case 'Z': /* error messages file */
745 copy_filename(errname, param);
746 break;
748 case 'F': /* specify debug format */
749 ofmt->current_dfmt = dfmt_find(ofmt, param);
750 if (!ofmt->current_dfmt) {
751 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
752 "unrecognized debug format `%s' for"
753 " output format `%s'",
754 param, ofmt->shortname);
756 using_debug_info = true;
757 break;
759 case 'X': /* specify error reporting format */
760 if (nasm_stricmp("vc", param) == 0)
761 nasm_set_verror(nasm_verror_vc);
762 else if (nasm_stricmp("gnu", param) == 0)
763 nasm_set_verror(nasm_verror_gnu);
764 else
765 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
766 "unrecognized error reporting format `%s'",
767 param);
768 break;
770 case 'g':
771 using_debug_info = true;
772 break;
774 case 'h':
775 printf
776 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
777 "[-l listfile]\n"
778 " [options...] [--] filename\n"
779 " or nasm -v for version info\n\n"
780 " -t assemble in SciTech TASM compatible mode\n"
781 " -g generate debug information in selected format\n");
782 printf
783 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
784 " -a don't preprocess (assemble only)\n"
785 " -M generate Makefile dependencies on stdout\n"
786 " -MG d:o, missing files assumed generated\n"
787 " -MF <file> set Makefile dependency file\n"
788 " -MD <file> assemble and generate dependencies\n"
789 " -MT <file> dependency target name\n"
790 " -MQ <file> dependency target name (quoted)\n"
791 " -MP emit phony target\n\n"
792 " -Z<file> redirect error messages to file\n"
793 " -s redirect error messages to stdout\n\n"
794 " -F format select a debugging format\n\n"
795 " -o outfile write output to an outfile\n\n"
796 " -f format select an output format\n\n"
797 " -l listfile write listing to a listfile\n\n"
798 " -I<path> adds a pathname to the include file path\n");
799 printf
800 (" -O<digit> optimize branch offsets\n"
801 " -O0: No optimization\n"
802 " -O1: Minimal optimization\n"
803 " -Ox: Multipass optimization (default)\n\n"
804 " -P<file> pre-includes a file\n"
805 " -D<macro>[=<value>] pre-defines a macro\n"
806 " -U<macro> undefines a macro\n"
807 " -X<format> specifies error reporting format (gnu or vc)\n"
808 " -w+foo enables warning foo (equiv. -Wfoo)\n"
809 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
810 " -h show invocation summary and exit\n\n"
811 "--prefix,--postfix\n"
812 " this options prepend or append the given argument to all\n"
813 " extern and global variables\n\n"
814 "Warnings:\n");
815 for (i = 0; i <= ERR_WARN_MAX; i++)
816 printf(" %-23s %s (default %s)\n",
817 warnings[i].name, warnings[i].help,
818 warnings[i].enabled ? "on" : "off");
819 printf
820 ("\nresponse files should contain command line parameters"
821 ", one per line.\n");
822 if (p[2] == 'f') {
823 printf("\nvalid output formats for -f are"
824 " (`*' denotes default):\n");
825 ofmt_list(ofmt, stdout);
826 } else {
827 printf("\nFor a list of valid output formats, use -hf.\n");
828 printf("For a list of debug formats, use -f <form> -y.\n");
830 exit(0); /* never need usage message here */
831 break;
833 case 'y':
834 printf("\nvalid debug formats for '%s' output format are"
835 " ('*' denotes default):\n", ofmt->shortname);
836 dfmt_list(ofmt, stdout);
837 exit(0);
838 break;
840 case 't':
841 tasm_compatible_mode = true;
842 break;
844 case 'v':
845 printf("NASM version %s compiled on %s%s\n",
846 nasm_version, nasm_date, nasm_compile_options);
847 exit(0); /* never need usage message here */
848 break;
850 case 'e': /* preprocess only */
851 case 'E':
852 operating_mode = op_preprocess;
853 break;
855 case 'a': /* assemble only - don't preprocess */
856 preproc = &preproc_nop;
857 break;
859 case 'W':
860 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
861 do_warn = false;
862 param += 3;
863 } else {
864 do_warn = true;
866 goto set_warning;
868 case 'w':
869 if (param[0] != '+' && param[0] != '-') {
870 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
871 "invalid option to `-w'");
872 break;
874 do_warn = (param[0] == '+');
875 param++;
877 set_warning:
878 for (i = 0; i <= ERR_WARN_MAX; i++) {
879 if (!nasm_stricmp(param, warnings[i].name))
880 break;
882 if (i <= ERR_WARN_MAX) {
883 warning_on_global[i] = do_warn;
884 } else if (!nasm_stricmp(param, "all")) {
885 for (i = 1; i <= ERR_WARN_MAX; i++)
886 warning_on_global[i] = do_warn;
887 } else if (!nasm_stricmp(param, "none")) {
888 for (i = 1; i <= ERR_WARN_MAX; i++)
889 warning_on_global[i] = !do_warn;
890 } else {
891 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
892 "invalid warning `%s'", param);
894 break;
896 case 'M':
897 switch (p[2]) {
898 case 0:
899 operating_mode = op_depend;
900 break;
901 case 'G':
902 operating_mode = op_depend;
903 depend_missing_ok = true;
904 break;
905 case 'P':
906 depend_emit_phony = true;
907 break;
908 case 'D':
909 depend_file = q;
910 advance = true;
911 break;
912 case 'T':
913 depend_target = q;
914 advance = true;
915 break;
916 case 'Q':
917 depend_target = quote_for_make(q);
918 advance = true;
919 break;
920 default:
921 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
922 "unknown dependency option `-M%c'", p[2]);
923 break;
925 if (advance && (!q || !q[0])) {
926 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
927 "option `-M%c' requires a parameter", p[2]);
928 break;
930 break;
932 case '-':
934 int s;
936 if (p[2] == 0) { /* -- => stop processing options */
937 stopoptions = 1;
938 break;
940 for (s = 0; textopts[s].label; s++) {
941 if (!nasm_stricmp(p + 2, textopts[s].label)) {
942 break;
946 switch (s) {
948 case OPT_PREFIX:
949 case OPT_POSTFIX:
951 if (!q) {
952 nasm_error(ERR_NONFATAL | ERR_NOFILE |
953 ERR_USAGE,
954 "option `--%s' requires an argument",
955 p + 2);
956 break;
957 } else {
958 advance = 1, param = q;
961 if (s == OPT_PREFIX) {
962 strncpy(lprefix, param, PREFIX_MAX - 1);
963 lprefix[PREFIX_MAX - 1] = 0;
964 break;
966 if (s == OPT_POSTFIX) {
967 strncpy(lpostfix, param, POSTFIX_MAX - 1);
968 lpostfix[POSTFIX_MAX - 1] = 0;
969 break;
971 break;
973 default:
975 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
976 "unrecognised option `--%s'", p + 2);
977 break;
980 break;
983 default:
984 if (!ofmt->setinfo(GI_SWITCH, &p))
985 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
986 "unrecognised option `-%c'", p[1]);
987 break;
989 } else {
990 if (*inname) {
991 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
992 "more than one input file specified");
993 } else {
994 copy_filename(inname, p);
998 return advance;
1001 #define ARG_BUF_DELTA 128
1003 static void process_respfile(FILE * rfile)
1005 char *buffer, *p, *q, *prevarg;
1006 int bufsize, prevargsize;
1008 bufsize = prevargsize = ARG_BUF_DELTA;
1009 buffer = nasm_malloc(ARG_BUF_DELTA);
1010 prevarg = nasm_malloc(ARG_BUF_DELTA);
1011 prevarg[0] = '\0';
1013 while (1) { /* Loop to handle all lines in file */
1014 p = buffer;
1015 while (1) { /* Loop to handle long lines */
1016 q = fgets(p, bufsize - (p - buffer), rfile);
1017 if (!q)
1018 break;
1019 p += strlen(p);
1020 if (p > buffer && p[-1] == '\n')
1021 break;
1022 if (p - buffer > bufsize - 10) {
1023 int offset;
1024 offset = p - buffer;
1025 bufsize += ARG_BUF_DELTA;
1026 buffer = nasm_realloc(buffer, bufsize);
1027 p = buffer + offset;
1031 if (!q && p == buffer) {
1032 if (prevarg[0])
1033 process_arg(prevarg, NULL);
1034 nasm_free(buffer);
1035 nasm_free(prevarg);
1036 return;
1040 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1041 * them are present at the end of the line.
1043 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1045 while (p > buffer && nasm_isspace(p[-1]))
1046 *--p = '\0';
1048 p = nasm_skip_spaces(buffer);
1050 if (process_arg(prevarg, p))
1051 *p = '\0';
1053 if ((int) strlen(p) > prevargsize - 10) {
1054 prevargsize += ARG_BUF_DELTA;
1055 prevarg = nasm_realloc(prevarg, prevargsize);
1057 strncpy(prevarg, p, prevargsize);
1061 /* Function to process args from a string of args, rather than the
1062 * argv array. Used by the environment variable and response file
1063 * processing.
1065 static void process_args(char *args)
1067 char *p, *q, *arg, *prevarg;
1068 char separator = ' ';
1070 p = args;
1071 if (*p && *p != '-')
1072 separator = *p++;
1073 arg = NULL;
1074 while (*p) {
1075 q = p;
1076 while (*p && *p != separator)
1077 p++;
1078 while (*p == separator)
1079 *p++ = '\0';
1080 prevarg = arg;
1081 arg = q;
1082 if (process_arg(prevarg, arg))
1083 arg = NULL;
1085 if (arg)
1086 process_arg(arg, NULL);
1089 static void process_response_file(const char *file)
1091 char str[2048];
1092 FILE *f = fopen(file, "r");
1093 if (!f) {
1094 perror(file);
1095 exit(-1);
1097 while (fgets(str, sizeof str, f)) {
1098 process_args(str);
1100 fclose(f);
1103 static void parse_cmdline(int argc, char **argv)
1105 FILE *rfile;
1106 char *envreal, *envcopy = NULL, *p;
1107 int i;
1109 *inname = *outname = *listname = *errname = '\0';
1111 for (i = 0; i <= ERR_WARN_MAX; i++)
1112 warning_on_global[i] = warnings[i].enabled;
1115 * First, process the NASMENV environment variable.
1117 envreal = getenv("NASMENV");
1118 if (envreal) {
1119 envcopy = nasm_strdup(envreal);
1120 process_args(envcopy);
1121 nasm_free(envcopy);
1125 * Now process the actual command line.
1127 while (--argc) {
1128 bool advance;
1129 argv++;
1130 if (argv[0][0] == '@') {
1132 * We have a response file, so process this as a set of
1133 * arguments like the environment variable. This allows us
1134 * to have multiple arguments on a single line, which is
1135 * different to the -@resp file processing below for regular
1136 * NASM.
1138 process_response_file(argv[0]+1);
1139 argc--;
1140 argv++;
1142 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1143 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1144 if (p) {
1145 rfile = fopen(p, "r");
1146 if (rfile) {
1147 process_respfile(rfile);
1148 fclose(rfile);
1149 } else
1150 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1151 "unable to open response file `%s'", p);
1153 } else
1154 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1155 argv += advance, argc -= advance;
1159 * Look for basic command line typos. This definitely doesn't
1160 * catch all errors, but it might help cases of fumbled fingers.
1162 if (!*inname)
1163 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1164 "no input file specified");
1165 else if (!strcmp(inname, errname) ||
1166 !strcmp(inname, outname) ||
1167 !strcmp(inname, listname) ||
1168 (depend_file && !strcmp(inname, depend_file)))
1169 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1170 "file `%s' is both input and output file",
1171 inname);
1173 if (*errname) {
1174 error_file = fopen(errname, "w");
1175 if (!error_file) {
1176 error_file = stderr; /* Revert to default! */
1177 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1178 "cannot open file `%s' for error messages",
1179 errname);
1184 static enum directives getkw(char **directive, char **value);
1186 static void assemble_file(char *fname, StrList **depend_ptr)
1188 char *directive, *value, *p, *q, *special, *line;
1189 insn output_ins;
1190 int i, validid;
1191 bool rn_error;
1192 int32_t seg;
1193 int64_t offs;
1194 struct tokenval tokval;
1195 expr *e;
1196 int pass_max;
1198 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1199 nasm_error(ERR_FATAL, "command line: "
1200 "32-bit segment size requires a higher cpu");
1202 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1203 for (passn = 1; pass0 <= 2; passn++) {
1204 int pass1, pass2;
1205 ldfunc def_label;
1207 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1208 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1209 /* pass0 0, 0, 0, ..., 1, 2 */
1211 def_label = passn > 1 ? redefine_label : define_label;
1213 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1214 cpu = cmd_cpu;
1215 if (pass0 == 2) {
1216 if (*listname)
1217 nasmlist.init(listname, nasm_error);
1219 in_abs_seg = false;
1220 global_offset_changed = 0; /* set by redefine_label */
1221 location.segment = ofmt->section(NULL, pass2, &sb);
1222 globalbits = sb;
1223 if (passn > 1) {
1224 saa_rewind(forwrefs);
1225 forwref = saa_rstruct(forwrefs);
1226 raa_free(offsets);
1227 offsets = raa_init();
1229 preproc->reset(fname, pass1, &nasmlist,
1230 pass1 == 2 ? depend_ptr : NULL);
1231 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1233 globallineno = 0;
1234 if (passn == 1)
1235 location.known = true;
1236 location.offset = offs = get_curr_offs();
1238 while ((line = preproc->getline())) {
1239 enum directives d;
1240 globallineno++;
1243 * Here we parse our directives; this is not handled by the
1244 * 'real' parser. This really should be a separate function.
1246 directive = line;
1247 d = getkw(&directive, &value);
1248 if (d) {
1249 int err = 0;
1251 switch (d) {
1252 case D_SEGMENT: /* [SEGMENT n] */
1253 case D_SECTION:
1254 seg = ofmt->section(value, pass2, &sb);
1255 if (seg == NO_SEG) {
1256 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1257 "segment name `%s' not recognized",
1258 value);
1259 } else {
1260 in_abs_seg = false;
1261 location.segment = seg;
1263 break;
1264 case D_SECTALIGN: /* [SECTALIGN n] */
1265 if (*value) {
1266 stdscan_reset();
1267 stdscan_set(value);
1268 tokval.t_type = TOKEN_INVALID;
1269 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1270 if (e) {
1271 unsigned int align = (unsigned int)e->value;
1272 if ((uint64_t)e->value > 0x7fffffff) {
1274 * FIXME: Please make some sane message here
1275 * ofmt should have some 'check' method which
1276 * would report segment alignment bounds.
1278 nasm_error(ERR_FATAL,
1279 "incorrect segment alignment `%s'", value);
1280 } else if (!is_power2(align)) {
1281 nasm_error(ERR_NONFATAL,
1282 "segment alignment `%s' is not power of two",
1283 value);
1285 /* callee should be able to handle all details */
1286 ofmt->sectalign(location.segment, align);
1289 break;
1290 case D_EXTERN: /* [EXTERN label:special] */
1291 if (*value == '$')
1292 value++; /* skip initial $ if present */
1293 if (pass0 == 2) {
1294 q = value;
1295 while (*q && *q != ':')
1296 q++;
1297 if (*q == ':') {
1298 *q++ = '\0';
1299 ofmt->symdef(value, 0L, 0L, 3, q);
1301 } else if (passn == 1) {
1302 q = value;
1303 validid = true;
1304 if (!isidstart(*q))
1305 validid = false;
1306 while (*q && *q != ':') {
1307 if (!isidchar(*q))
1308 validid = false;
1309 q++;
1311 if (!validid) {
1312 nasm_error(ERR_NONFATAL,
1313 "identifier expected after EXTERN");
1314 break;
1316 if (*q == ':') {
1317 *q++ = '\0';
1318 special = q;
1319 } else
1320 special = NULL;
1321 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1322 int temp = pass0;
1323 pass0 = 1; /* fake pass 1 in labels.c */
1324 declare_as_global(value, special);
1325 define_label(value, seg_alloc(), 0L, NULL,
1326 false, true);
1327 pass0 = temp;
1329 } /* else pass0 == 1 */
1330 break;
1331 case D_BITS: /* [BITS bits] */
1332 globalbits = sb = get_bits(value);
1333 break;
1334 case D_GLOBAL: /* [GLOBAL symbol:special] */
1335 if (*value == '$')
1336 value++; /* skip initial $ if present */
1337 if (pass0 == 2) { /* pass 2 */
1338 q = value;
1339 while (*q && *q != ':')
1340 q++;
1341 if (*q == ':') {
1342 *q++ = '\0';
1343 ofmt->symdef(value, 0L, 0L, 3, q);
1345 } else if (pass2 == 1) { /* pass == 1 */
1346 q = value;
1347 validid = true;
1348 if (!isidstart(*q))
1349 validid = false;
1350 while (*q && *q != ':') {
1351 if (!isidchar(*q))
1352 validid = false;
1353 q++;
1355 if (!validid) {
1356 nasm_error(ERR_NONFATAL,
1357 "identifier expected after GLOBAL");
1358 break;
1360 if (*q == ':') {
1361 *q++ = '\0';
1362 special = q;
1363 } else
1364 special = NULL;
1365 declare_as_global(value, special);
1366 } /* pass == 1 */
1367 break;
1368 case D_COMMON: /* [COMMON symbol size:special] */
1370 int64_t size;
1372 if (*value == '$')
1373 value++; /* skip initial $ if present */
1374 p = value;
1375 validid = true;
1376 if (!isidstart(*p))
1377 validid = false;
1378 while (*p && !nasm_isspace(*p)) {
1379 if (!isidchar(*p))
1380 validid = false;
1381 p++;
1383 if (!validid) {
1384 nasm_error(ERR_NONFATAL,
1385 "identifier expected after COMMON");
1386 break;
1388 if (*p) {
1389 p = nasm_zap_spaces_fwd(p);
1390 q = p;
1391 while (*q && *q != ':')
1392 q++;
1393 if (*q == ':') {
1394 *q++ = '\0';
1395 special = q;
1396 } else {
1397 special = NULL;
1399 size = readnum(p, &rn_error);
1400 if (rn_error) {
1401 nasm_error(ERR_NONFATAL,
1402 "invalid size specified"
1403 " in COMMON declaration");
1404 break;
1406 } else {
1407 nasm_error(ERR_NONFATAL,
1408 "no size specified in"
1409 " COMMON declaration");
1410 break;
1413 if (pass0 < 2) {
1414 define_common(value, seg_alloc(), size, special);
1415 } else if (pass0 == 2) {
1416 if (special)
1417 ofmt->symdef(value, 0L, 0L, 3, special);
1419 break;
1421 case D_ABSOLUTE: /* [ABSOLUTE address] */
1422 stdscan_reset();
1423 stdscan_set(value);
1424 tokval.t_type = TOKEN_INVALID;
1425 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1426 nasm_error, NULL);
1427 if (e) {
1428 if (!is_reloc(e))
1429 nasm_error(pass0 ==
1430 1 ? ERR_NONFATAL : ERR_PANIC,
1431 "cannot use non-relocatable expression as "
1432 "ABSOLUTE address");
1433 else {
1434 abs_seg = reloc_seg(e);
1435 abs_offset = reloc_value(e);
1437 } else if (passn == 1)
1438 abs_offset = 0x100; /* don't go near zero in case of / */
1439 else
1440 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1441 "in pass two");
1442 in_abs_seg = true;
1443 location.segment = NO_SEG;
1444 break;
1445 case D_DEBUG: /* [DEBUG] */
1447 char debugid[128];
1448 bool badid, overlong;
1450 p = value;
1451 q = debugid;
1452 badid = overlong = false;
1453 if (!isidstart(*p)) {
1454 badid = true;
1455 } else {
1456 while (*p && !nasm_isspace(*p)) {
1457 if (q >= debugid + sizeof debugid - 1) {
1458 overlong = true;
1459 break;
1461 if (!isidchar(*p))
1462 badid = true;
1463 *q++ = *p++;
1465 *q = 0;
1467 if (badid) {
1468 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1469 "identifier expected after DEBUG");
1470 break;
1472 if (overlong) {
1473 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1474 "DEBUG identifier too long");
1475 break;
1477 p = nasm_skip_spaces(p);
1478 if (pass0 == 2)
1479 dfmt->debug_directive(debugid, p);
1480 break;
1482 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1483 value = nasm_skip_spaces(value);
1484 switch(*value) {
1485 case '-': validid = 0; value++; break;
1486 case '+': validid = 1; value++; break;
1487 case '*': validid = 2; value++; break;
1488 default: validid = 1; break;
1491 for (i = 1; i <= ERR_WARN_MAX; i++)
1492 if (!nasm_stricmp(value, warnings[i].name))
1493 break;
1494 if (i <= ERR_WARN_MAX) {
1495 switch(validid) {
1496 case 0:
1497 warning_on[i] = false;
1498 break;
1499 case 1:
1500 warning_on[i] = true;
1501 break;
1502 case 2:
1503 warning_on[i] = warning_on_global[i];
1504 break;
1506 } else
1507 nasm_error(ERR_NONFATAL,
1508 "invalid warning id in WARNING directive");
1509 break;
1510 case D_CPU: /* [CPU] */
1511 cpu = get_cpu(value);
1512 break;
1513 case D_LIST: /* [LIST {+|-}] */
1514 value = nasm_skip_spaces(value);
1515 if (*value == '+') {
1516 user_nolist = 0;
1517 } else {
1518 if (*value == '-') {
1519 user_nolist = 1;
1520 } else {
1521 err = 1;
1524 break;
1525 case D_DEFAULT: /* [DEFAULT] */
1526 stdscan_reset();
1527 stdscan_set(value);
1528 tokval.t_type = TOKEN_INVALID;
1529 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1530 switch ((int)tokval.t_integer) {
1531 case S_REL:
1532 globalrel = 1;
1533 break;
1534 case S_ABS:
1535 globalrel = 0;
1536 break;
1537 case P_BND:
1538 globalbnd = 1;
1539 break;
1540 case P_NOBND:
1541 globalbnd = 0;
1542 break;
1543 default:
1544 err = 1;
1545 break;
1547 } else {
1548 err = 1;
1550 break;
1551 case D_FLOAT:
1552 if (float_option(value)) {
1553 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1554 "unknown 'float' directive: %s",
1555 value);
1557 break;
1558 default:
1559 if (ofmt->directive(d, value, pass2))
1560 break;
1561 /* else fall through */
1562 case D_unknown:
1563 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1564 "unrecognised directive [%s]",
1565 directive);
1566 break;
1568 if (err) {
1569 nasm_error(ERR_NONFATAL,
1570 "invalid parameter to [%s] directive",
1571 directive);
1573 } else { /* it isn't a directive */
1574 parse_line(pass1, line, &output_ins, def_label);
1576 if (optimizing > 0) {
1577 if (forwref != NULL && globallineno == forwref->lineno) {
1578 output_ins.forw_ref = true;
1579 do {
1580 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1581 forwref = saa_rstruct(forwrefs);
1582 } while (forwref != NULL
1583 && forwref->lineno == globallineno);
1584 } else
1585 output_ins.forw_ref = false;
1587 if (output_ins.forw_ref) {
1588 if (passn == 1) {
1589 for (i = 0; i < output_ins.operands; i++) {
1590 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1591 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1592 fwinf->lineno = globallineno;
1593 fwinf->operand = i;
1600 /* forw_ref */
1601 if (output_ins.opcode == I_EQU) {
1602 if (pass1 == 1) {
1604 * Special `..' EQUs get processed in pass two,
1605 * except `..@' macro-processor EQUs which are done
1606 * in the normal place.
1608 if (!output_ins.label)
1609 nasm_error(ERR_NONFATAL,
1610 "EQU not preceded by label");
1612 else if (output_ins.label[0] != '.' ||
1613 output_ins.label[1] != '.' ||
1614 output_ins.label[2] == '@') {
1615 if (output_ins.operands == 1 &&
1616 (output_ins.oprs[0].type & IMMEDIATE) &&
1617 output_ins.oprs[0].wrt == NO_SEG) {
1618 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1619 def_label(output_ins.label,
1620 output_ins.oprs[0].segment,
1621 output_ins.oprs[0].offset, NULL,
1622 false, isext);
1623 } else if (output_ins.operands == 2
1624 && (output_ins.oprs[0].type & IMMEDIATE)
1625 && (output_ins.oprs[0].type & COLON)
1626 && output_ins.oprs[0].segment == NO_SEG
1627 && output_ins.oprs[0].wrt == NO_SEG
1628 && (output_ins.oprs[1].type & IMMEDIATE)
1629 && output_ins.oprs[1].segment == NO_SEG
1630 && output_ins.oprs[1].wrt == NO_SEG) {
1631 def_label(output_ins.label,
1632 output_ins.oprs[0].offset | SEG_ABS,
1633 output_ins.oprs[1].offset,
1634 NULL, false, false);
1635 } else
1636 nasm_error(ERR_NONFATAL,
1637 "bad syntax for EQU");
1639 } else {
1641 * Special `..' EQUs get processed here, except
1642 * `..@' macro processor EQUs which are done above.
1644 if (output_ins.label[0] == '.' &&
1645 output_ins.label[1] == '.' &&
1646 output_ins.label[2] != '@') {
1647 if (output_ins.operands == 1 &&
1648 (output_ins.oprs[0].type & IMMEDIATE)) {
1649 define_label(output_ins.label,
1650 output_ins.oprs[0].segment,
1651 output_ins.oprs[0].offset,
1652 NULL, false, false);
1653 } else if (output_ins.operands == 2
1654 && (output_ins.oprs[0].type & IMMEDIATE)
1655 && (output_ins.oprs[0].type & COLON)
1656 && output_ins.oprs[0].segment == NO_SEG
1657 && (output_ins.oprs[1].type & IMMEDIATE)
1658 && output_ins.oprs[1].segment == NO_SEG) {
1659 define_label(output_ins.label,
1660 output_ins.oprs[0].offset | SEG_ABS,
1661 output_ins.oprs[1].offset,
1662 NULL, false, false);
1663 } else
1664 nasm_error(ERR_NONFATAL,
1665 "bad syntax for EQU");
1668 } else { /* instruction isn't an EQU */
1670 if (pass1 == 1) {
1672 int64_t l = insn_size(location.segment, offs, sb, cpu,
1673 &output_ins, nasm_error);
1675 /* if (using_debug_info) && output_ins.opcode != -1) */
1676 if (using_debug_info)
1677 { /* fbk 03/25/01 */
1678 /* this is done here so we can do debug type info */
1679 int32_t typeinfo =
1680 TYS_ELEMENTS(output_ins.operands);
1681 switch (output_ins.opcode) {
1682 case I_RESB:
1683 typeinfo =
1684 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1685 break;
1686 case I_RESW:
1687 typeinfo =
1688 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1689 break;
1690 case I_RESD:
1691 typeinfo =
1692 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1693 break;
1694 case I_RESQ:
1695 typeinfo =
1696 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1697 break;
1698 case I_REST:
1699 typeinfo =
1700 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1701 break;
1702 case I_RESO:
1703 typeinfo =
1704 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1705 break;
1706 case I_RESY:
1707 typeinfo =
1708 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1709 break;
1710 case I_DB:
1711 typeinfo |= TY_BYTE;
1712 break;
1713 case I_DW:
1714 typeinfo |= TY_WORD;
1715 break;
1716 case I_DD:
1717 if (output_ins.eops_float)
1718 typeinfo |= TY_FLOAT;
1719 else
1720 typeinfo |= TY_DWORD;
1721 break;
1722 case I_DQ:
1723 typeinfo |= TY_QWORD;
1724 break;
1725 case I_DT:
1726 typeinfo |= TY_TBYTE;
1727 break;
1728 case I_DO:
1729 typeinfo |= TY_OWORD;
1730 break;
1731 case I_DY:
1732 typeinfo |= TY_YWORD;
1733 break;
1734 default:
1735 typeinfo = TY_LABEL;
1739 dfmt->debug_typevalue(typeinfo);
1741 if (l != -1) {
1742 offs += l;
1743 set_curr_offs(offs);
1746 * else l == -1 => invalid instruction, which will be
1747 * flagged as an error on pass 2
1750 } else {
1751 offs += assemble(location.segment, offs, sb, cpu,
1752 &output_ins, ofmt, nasm_error,
1753 &nasmlist);
1754 set_curr_offs(offs);
1757 } /* not an EQU */
1758 cleanup_insn(&output_ins);
1760 nasm_free(line);
1761 location.offset = offs = get_curr_offs();
1762 } /* end while (line = preproc->getline... */
1764 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1765 nasm_error(ERR_NONFATAL,
1766 "phase error detected at end of assembly.");
1768 if (pass1 == 1)
1769 preproc->cleanup(1);
1771 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1772 pass0++;
1773 } else if (global_offset_changed &&
1774 global_offset_changed < prev_offset_changed) {
1775 prev_offset_changed = global_offset_changed;
1776 stall_count = 0;
1777 } else {
1778 stall_count++;
1781 if (terminate_after_phase)
1782 break;
1784 if ((stall_count > 997) || (passn >= pass_max)) {
1785 /* We get here if the labels don't converge
1786 * Example: FOO equ FOO + 1
1788 nasm_error(ERR_NONFATAL,
1789 "Can't find valid values for all labels "
1790 "after %d passes, giving up.", passn);
1791 nasm_error(ERR_NONFATAL,
1792 "Possible causes: recursive EQUs, macro abuse.");
1793 break;
1797 preproc->cleanup(0);
1798 nasmlist.cleanup();
1799 if (!terminate_after_phase && opt_verbose_info) {
1800 /* -On and -Ov switches */
1801 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1805 static enum directives getkw(char **directive, char **value)
1807 char *p, *q, *buf;
1809 buf = nasm_skip_spaces(*directive);
1811 /* it should be enclosed in [ ] */
1812 if (*buf != '[')
1813 return D_none;
1814 q = strchr(buf, ']');
1815 if (!q)
1816 return D_none;
1818 /* stip off the comments */
1819 p = strchr(buf, ';');
1820 if (p) {
1821 if (p < q) /* ouch! somwhere inside */
1822 return D_none;
1823 *p = '\0';
1826 /* no brace, no trailing spaces */
1827 *q = '\0';
1828 nasm_zap_spaces_rev(--q);
1830 /* directive */
1831 p = nasm_skip_spaces(++buf);
1832 q = nasm_skip_word(p);
1833 if (!q)
1834 return D_none; /* sigh... no value there */
1835 *q = '\0';
1836 *directive = p;
1838 /* and value finally */
1839 p = nasm_skip_spaces(++q);
1840 *value = p;
1842 return find_directive(*directive);
1846 * gnu style error reporting
1847 * This function prints an error message to error_file in the
1848 * style used by GNU. An example would be:
1849 * file.asm:50: error: blah blah blah
1850 * where file.asm is the name of the file, 50 is the line number on
1851 * which the error occurs (or is detected) and "error:" is one of
1852 * the possible optional diagnostics -- it can be "error" or "warning"
1853 * or something else. Finally the line terminates with the actual
1854 * error message.
1856 * @param severity the severity of the warning or error
1857 * @param fmt the printf style format string
1859 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1861 char *currentfile = NULL;
1862 int32_t lineno = 0;
1864 if (is_suppressed_warning(severity))
1865 return;
1867 if (!(severity & ERR_NOFILE))
1868 src_get(&lineno, &currentfile);
1870 if (currentfile) {
1871 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1872 nasm_free(currentfile);
1873 } else {
1874 fputs("nasm: ", error_file);
1877 nasm_verror_common(severity, fmt, ap);
1881 * MS style error reporting
1882 * This function prints an error message to error_file in the
1883 * style used by Visual C and some other Microsoft tools. An example
1884 * would be:
1885 * file.asm(50) : error: blah blah blah
1886 * where file.asm is the name of the file, 50 is the line number on
1887 * which the error occurs (or is detected) and "error:" is one of
1888 * the possible optional diagnostics -- it can be "error" or "warning"
1889 * or something else. Finally the line terminates with the actual
1890 * error message.
1892 * @param severity the severity of the warning or error
1893 * @param fmt the printf style format string
1895 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1897 char *currentfile = NULL;
1898 int32_t lineno = 0;
1900 if (is_suppressed_warning(severity))
1901 return;
1903 if (!(severity & ERR_NOFILE))
1904 src_get(&lineno, &currentfile);
1906 if (currentfile) {
1907 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1908 nasm_free(currentfile);
1909 } else {
1910 fputs("nasm: ", error_file);
1913 nasm_verror_common(severity, fmt, ap);
1917 * check for supressed warning
1918 * checks for suppressed warning or pass one only warning and we're
1919 * not in pass 1
1921 * @param severity the severity of the warning or error
1922 * @return true if we should abort error/warning printing
1924 static bool is_suppressed_warning(int severity)
1926 /* Not a warning at all */
1927 if ((severity & ERR_MASK) != ERR_WARNING)
1928 return false;
1930 /* See if it's a pass-one only warning and we're not in pass one. */
1931 if (((severity & ERR_PASS1) && pass0 != 1) ||
1932 ((severity & ERR_PASS2) && pass0 != 2))
1933 return true;
1935 /* Might be a warning but suppresed explicitly */
1936 if (severity & ERR_WARN_MASK)
1937 return !warning_on[WARN_IDX(severity)];
1938 else
1939 return false;
1943 * common error reporting
1944 * This is the common back end of the error reporting schemes currently
1945 * implemented. It prints the nature of the warning and then the
1946 * specific error message to error_file and may or may not return. It
1947 * doesn't return if the error severity is a "panic" or "debug" type.
1949 * @param severity the severity of the warning or error
1950 * @param fmt the printf style format string
1952 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1954 char msg[1024];
1955 const char *pfx;
1957 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1958 case ERR_WARNING:
1959 pfx = "warning: ";
1960 break;
1961 case ERR_NONFATAL:
1962 pfx = "error: ";
1963 break;
1964 case ERR_FATAL:
1965 pfx = "fatal: ";
1966 break;
1967 case ERR_PANIC:
1968 pfx = "panic: ";
1969 break;
1970 case ERR_DEBUG:
1971 pfx = "debug: ";
1972 break;
1973 default:
1974 pfx = "";
1975 break;
1978 vsnprintf(msg, sizeof msg, fmt, args);
1980 fprintf(error_file, "%s%s\n", pfx, msg);
1982 if (*listname)
1983 nasmlist.error(severity, pfx, msg);
1985 if (severity & ERR_USAGE)
1986 want_usage = true;
1988 switch (severity & ERR_MASK) {
1989 case ERR_DEBUG:
1990 /* no further action, by definition */
1991 break;
1992 case ERR_WARNING:
1993 /* Treat warnings as errors */
1994 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1995 terminate_after_phase = true;
1996 break;
1997 case ERR_NONFATAL:
1998 terminate_after_phase = true;
1999 break;
2000 case ERR_FATAL:
2001 if (ofile) {
2002 fclose(ofile);
2003 remove(outname);
2004 ofile = NULL;
2006 if (want_usage)
2007 usage();
2008 exit(1); /* instantly die */
2009 break; /* placate silly compilers */
2010 case ERR_PANIC:
2011 fflush(NULL);
2012 /* abort(); */ /* halt, catch fire, and dump core */
2013 exit(3);
2014 break;
2018 static void usage(void)
2020 fputs("type `nasm -h' for help\n", error_file);
2023 static iflag_t get_cpu(char *value)
2025 iflag_t r;
2027 iflag_clear_all(&r);
2029 if (!strcmp(value, "8086"))
2030 iflag_set(&r, IF_8086);
2031 else if (!strcmp(value, "186"))
2032 iflag_set(&r, IF_186);
2033 else if (!strcmp(value, "286"))
2034 iflag_set(&r, IF_286);
2035 else if (!strcmp(value, "386"))
2036 iflag_set(&r, IF_386);
2037 else if (!strcmp(value, "486"))
2038 iflag_set(&r, IF_486);
2039 else if (!strcmp(value, "586") ||
2040 !nasm_stricmp(value, "pentium"))
2041 iflag_set(&r, IF_PENT);
2042 else if (!strcmp(value, "686") ||
2043 !nasm_stricmp(value, "ppro") ||
2044 !nasm_stricmp(value, "pentiumpro") ||
2045 !nasm_stricmp(value, "p2"))
2046 iflag_set(&r, IF_P6);
2047 else if (!nasm_stricmp(value, "p3") ||
2048 !nasm_stricmp(value, "katmai"))
2049 iflag_set(&r, IF_KATMAI);
2050 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2051 !nasm_stricmp(value, "willamette"))
2052 iflag_set(&r, IF_WILLAMETTE);
2053 else if (!nasm_stricmp(value, "prescott"))
2054 iflag_set(&r, IF_PRESCOTT);
2055 else if (!nasm_stricmp(value, "x64") ||
2056 !nasm_stricmp(value, "x86-64"))
2057 iflag_set(&r, IF_X86_64);
2058 else if (!nasm_stricmp(value, "ia64") ||
2059 !nasm_stricmp(value, "ia-64") ||
2060 !nasm_stricmp(value, "itanium")||
2061 !nasm_stricmp(value, "itanic") ||
2062 !nasm_stricmp(value, "merced"))
2063 iflag_set(&r, IF_IA64);
2064 else {
2065 iflag_set(&r, IF_PLEVEL);
2066 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2067 "unknown 'cpu' type");
2069 return r;
2072 static int get_bits(char *value)
2074 int i;
2076 if ((i = atoi(value)) == 16)
2077 return i; /* set for a 16-bit segment */
2078 else if (i == 32) {
2079 if (iflag_ffs(&cpu) < IF_386) {
2080 nasm_error(ERR_NONFATAL,
2081 "cannot specify 32-bit segment on processor below a 386");
2082 i = 16;
2084 } else if (i == 64) {
2085 if (iflag_ffs(&cpu) < IF_X86_64) {
2086 nasm_error(ERR_NONFATAL,
2087 "cannot specify 64-bit segment on processor below an x86-64");
2088 i = 16;
2090 if (i != maxbits) {
2091 nasm_error(ERR_NONFATAL,
2092 "%s output format does not support 64-bit code",
2093 ofmt->shortname);
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;