NASM 2.10rc5
[nasm/avx512.git] / nasm.c
blob36be46e46cb0ef49730c8affd45dd5d68ab33490
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2011 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"
65 * This is the maximum number of optimization passes to do. If we ever
66 * find a case where the optimizer doesn't naturally converge, we might
67 * have to drop this value so the assembler doesn't appear to just hang.
69 #define MAX_OPTIMIZE (INT_MAX >> 1)
71 struct forwrefinfo { /* info held on forward refs. */
72 int lineno;
73 int operand;
76 static int get_bits(char *value);
77 static uint32_t get_cpu(char *cpu_str);
78 static void parse_cmdline(int, char **);
79 static void assemble_file(char *, StrList **);
80 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
81 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
82 static void nasm_verror_common(int severity, const char *fmt, va_list args);
83 static bool is_suppressed_warning(int severity);
84 static void usage(void);
86 static int using_debug_info, opt_verbose_info;
87 bool tasm_compatible_mode = false;
88 int pass0, passn;
89 int maxbits = 0;
90 int globalrel = 0;
92 static time_t official_compile_time;
94 static char inname[FILENAME_MAX];
95 static char outname[FILENAME_MAX];
96 static char listname[FILENAME_MAX];
97 static char errname[FILENAME_MAX];
98 static int globallineno; /* for forward-reference tracking */
99 /* static int pass = 0; */
100 struct ofmt *ofmt = &OF_DEFAULT;
101 struct ofmt_alias *ofmt_alias = NULL;
102 const struct dfmt *dfmt;
104 static FILE *error_file; /* Where to write error messages */
106 FILE *ofile = NULL;
107 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
108 static int sb, cmd_sb = 16; /* by default */
109 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
110 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
111 int64_t global_offset_changed; /* referenced in labels.c */
112 int64_t prev_offset_changed;
113 int32_t stall_count;
115 static struct location location;
116 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
117 int32_t abs_seg; /* ABSOLUTE segment basis */
118 int32_t abs_offset; /* ABSOLUTE offset */
120 static struct RAA *offsets;
122 static struct SAA *forwrefs; /* keep track of forward references */
123 static const struct forwrefinfo *forwref;
125 static Preproc *preproc;
126 enum op_type {
127 op_normal, /* Preprocess and assemble */
128 op_preprocess, /* Preprocess only */
129 op_depend, /* Generate dependencies */
131 static enum op_type operating_mode;
132 /* Dependency flags */
133 static bool depend_emit_phony = false;
134 static bool depend_missing_ok = false;
135 static const char *depend_target = NULL;
136 static const char *depend_file = NULL;
139 * Which of the suppressible warnings are suppressed. Entry zero
140 * isn't an actual warning, but it used for -w+error/-Werror.
143 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
144 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
146 static const struct warning {
147 const char *name;
148 const char *help;
149 bool enabled;
150 } warnings[ERR_WARN_MAX+1] = {
151 {"error", "treat warnings as errors", false},
152 {"macro-params", "macro calls with wrong parameter count", true},
153 {"macro-selfref", "cyclic macro references", false},
154 {"macro-defaults", "macros with more default than optional parameters", true},
155 {"orphan-labels", "labels alone on lines without trailing `:'", true},
156 {"number-overflow", "numeric constant does not fit", true},
157 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
158 {"float-overflow", "floating point overflow", true},
159 {"float-denorm", "floating point denormal", false},
160 {"float-underflow", "floating point underflow", false},
161 {"float-toolong", "too many digits in floating-point number", true},
162 {"user", "%warning directives", true},
166 * This is a null preprocessor which just copies lines from input
167 * to output. It's used when someone explicitly requests that NASM
168 * not preprocess their source file.
171 static void no_pp_reset(char *, int, ListGen *, StrList **);
172 static char *no_pp_getline(void);
173 static void no_pp_cleanup(int);
174 static Preproc no_pp = {
175 no_pp_reset,
176 no_pp_getline,
177 no_pp_cleanup
181 * get/set current offset...
183 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
184 raa_read(offsets,location.segment))
185 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
186 (void)(offsets=raa_write(offsets,location.segment,(x))))
188 static bool want_usage;
189 static bool terminate_after_phase;
190 int user_nolist = 0; /* fbk 9/2/00 */
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 pp_pre_define(temp);
233 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
234 pp_pre_define(temp);
235 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
236 pp_pre_define(temp);
237 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
238 pp_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 pp_pre_define(temp);
247 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
248 pp_pre_define(temp);
249 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
250 pp_pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
252 pp_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 pp_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 pp_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 len = strlen(l->str);
302 if (linepos + len > 62) {
303 fprintf(deps, " \\\n ");
304 linepos = 1;
306 fprintf(deps, " %s", l->str);
307 linepos += len+1;
309 fprintf(deps, "\n\n");
311 list_for_each_safe(l, nl, list) {
312 if (depend_emit_phony)
313 fprintf(deps, "%s:\n\n", l->str);
314 nasm_free(l);
317 if (deps != stdout)
318 fclose(deps);
321 int main(int argc, char **argv)
323 StrList *depend_list = NULL, **depend_ptr;
325 time(&official_compile_time);
327 pass0 = 0;
328 want_usage = terminate_after_phase = false;
329 nasm_set_verror(nasm_verror_gnu);
331 error_file = stderr;
333 tolower_init();
335 nasm_init_malloc_error();
336 offsets = raa_init();
337 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
339 preproc = &nasmpp;
340 operating_mode = op_normal;
342 seg_init();
344 /* Define some macros dependent on the runtime, but not
345 on the command line. */
346 define_macros_early();
348 parse_cmdline(argc, argv);
350 if (terminate_after_phase) {
351 if (want_usage)
352 usage();
353 return 1;
356 /* If debugging info is disabled, suppress any debug calls */
357 if (!using_debug_info)
358 ofmt->current_dfmt = &null_debug_form;
360 if (ofmt->stdmac)
361 pp_extra_stdmac(ofmt->stdmac);
362 parser_global_info(&location);
363 eval_global_info(ofmt, lookup_label, &location);
365 /* define some macros dependent of command-line */
366 define_macros_late();
368 depend_ptr = (depend_file || (operating_mode == op_depend))
369 ? &depend_list : NULL;
370 if (!depend_target)
371 depend_target = outname;
373 switch (operating_mode) {
374 case op_depend:
376 char *line;
378 if (depend_missing_ok)
379 pp_include_path(NULL); /* "assume generated" */
381 preproc->reset(inname, 0, &nasmlist, depend_ptr);
382 if (outname[0] == '\0')
383 ofmt->filename(inname, outname);
384 ofile = NULL;
385 while ((line = preproc->getline()))
386 nasm_free(line);
387 preproc->cleanup(0);
389 break;
391 case op_preprocess:
393 char *line;
394 char *file_name = NULL;
395 int32_t prior_linnum = 0;
396 int lineinc = 0;
398 if (*outname) {
399 ofile = fopen(outname, "w");
400 if (!ofile)
401 nasm_error(ERR_FATAL | ERR_NOFILE,
402 "unable to open output file `%s'",
403 outname);
404 } else
405 ofile = NULL;
407 location.known = false;
409 /* pass = 1; */
410 preproc->reset(inname, 3, &nasmlist, depend_ptr);
412 while ((line = preproc->getline())) {
414 * We generate %line directives if needed for later programs
416 int32_t linnum = prior_linnum += lineinc;
417 int altline = src_get(&linnum, &file_name);
418 if (altline) {
419 if (altline == 1 && lineinc == 1)
420 nasm_fputs("", ofile);
421 else {
422 lineinc = (altline != -1 || lineinc != 1);
423 fprintf(ofile ? ofile : stdout,
424 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
425 file_name);
427 prior_linnum = linnum;
429 nasm_fputs(line, ofile);
430 nasm_free(line);
432 nasm_free(file_name);
433 preproc->cleanup(0);
434 if (ofile)
435 fclose(ofile);
436 if (ofile && terminate_after_phase)
437 remove(outname);
438 ofile = NULL;
440 break;
442 case op_normal:
445 * We must call ofmt->filename _anyway_, even if the user
446 * has specified their own output file, because some
447 * formats (eg OBJ and COFF) use ofmt->filename to find out
448 * the name of the input file and then put that inside the
449 * file.
451 ofmt->filename(inname, outname);
453 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
454 if (!ofile) {
455 nasm_error(ERR_FATAL | ERR_NOFILE,
456 "unable to open output file `%s'", outname);
460 * We must call init_labels() before ofmt->init() since
461 * some object formats will want to define labels in their
462 * init routines. (eg OS/2 defines the FLAT group)
464 init_labels();
466 ofmt->init();
467 dfmt = ofmt->current_dfmt;
468 dfmt->init();
470 assemble_file(inname, depend_ptr);
472 if (!terminate_after_phase) {
473 ofmt->cleanup(using_debug_info);
474 cleanup_labels();
475 fflush(ofile);
476 if (ferror(ofile)) {
477 nasm_error(ERR_NONFATAL|ERR_NOFILE,
478 "write error on output file `%s'", outname);
482 if (ofile) {
483 fclose(ofile);
484 if (terminate_after_phase)
485 remove(outname);
486 ofile = NULL;
489 break;
492 if (depend_list && !terminate_after_phase)
493 emit_dependencies(depend_list);
495 if (want_usage)
496 usage();
498 raa_free(offsets);
499 saa_free(forwrefs);
500 eval_cleanup();
501 stdscan_cleanup();
503 return terminate_after_phase;
507 * Get a parameter for a command line option.
508 * First arg must be in the form of e.g. -f...
510 static char *get_param(char *p, char *q, bool *advance)
512 *advance = false;
513 if (p[2]) /* the parameter's in the option */
514 return nasm_skip_spaces(p + 2);
515 if (q && q[0]) {
516 *advance = true;
517 return q;
519 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
520 "option `-%c' requires an argument", p[1]);
521 return NULL;
525 * Copy a filename
527 static void copy_filename(char *dst, const char *src)
529 size_t len = strlen(src);
531 if (len >= (size_t)FILENAME_MAX) {
532 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
533 return;
535 strncpy(dst, src, FILENAME_MAX);
539 * Convert a string to Make-safe form
541 static char *quote_for_make(const char *str)
543 const char *p;
544 char *os, *q;
546 size_t n = 1; /* Terminating zero */
547 size_t nbs = 0;
549 if (!str)
550 return NULL;
552 for (p = str; *p; p++) {
553 switch (*p) {
554 case ' ':
555 case '\t':
556 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
557 n += nbs + 2;
558 nbs = 0;
559 break;
560 case '$':
561 case '#':
562 nbs = 0;
563 n += 2;
564 break;
565 case '\\':
566 nbs++;
567 n++;
568 break;
569 default:
570 nbs = 0;
571 n++;
572 break;
576 /* Convert N backslashes at the end of filename to 2N backslashes */
577 if (nbs)
578 n += nbs;
580 os = q = nasm_malloc(n);
582 nbs = 0;
583 for (p = str; *p; p++) {
584 switch (*p) {
585 case ' ':
586 case '\t':
587 while (nbs--)
588 *q++ = '\\';
589 *q++ = '\\';
590 *q++ = *p;
591 break;
592 case '$':
593 *q++ = *p;
594 *q++ = *p;
595 nbs = 0;
596 break;
597 case '#':
598 *q++ = '\\';
599 *q++ = *p;
600 nbs = 0;
601 break;
602 case '\\':
603 *q++ = *p;
604 nbs++;
605 break;
606 default:
607 *q++ = *p;
608 nbs = 0;
609 break;
612 while (nbs--)
613 *q++ = '\\';
615 *q = '\0';
617 return os;
620 struct textargs {
621 const char *label;
622 int value;
625 #define OPT_PREFIX 0
626 #define OPT_POSTFIX 1
627 struct textargs textopts[] = {
628 {"prefix", OPT_PREFIX},
629 {"postfix", OPT_POSTFIX},
630 {NULL, 0}
633 static bool stopoptions = false;
634 static bool process_arg(char *p, char *q)
636 char *param;
637 int i;
638 bool advance = false;
639 bool do_warn;
641 if (!p || !p[0])
642 return false;
644 if (p[0] == '-' && !stopoptions) {
645 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
646 /* These parameters take values */
647 if (!(param = get_param(p, q, &advance)))
648 return advance;
651 switch (p[1]) {
652 case 's':
653 error_file = stdout;
654 break;
656 case 'o': /* output file */
657 copy_filename(outname, param);
658 break;
660 case 'f': /* output format */
661 ofmt = ofmt_find(param, &ofmt_alias);
662 if (!ofmt) {
663 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
664 "unrecognised output format `%s' - "
665 "use -hf for a list", param);
667 break;
669 case 'O': /* Optimization level */
671 int opt;
673 if (!*param) {
674 /* Naked -O == -Ox */
675 optimizing = MAX_OPTIMIZE;
676 } else {
677 while (*param) {
678 switch (*param) {
679 case '0': case '1': case '2': case '3': case '4':
680 case '5': case '6': case '7': case '8': case '9':
681 opt = strtoul(param, &param, 10);
683 /* -O0 -> optimizing == -1, 0.98 behaviour */
684 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
685 if (opt < 2)
686 optimizing = opt - 1;
687 else
688 optimizing = opt;
689 break;
691 case 'v':
692 case '+':
693 param++;
694 opt_verbose_info = true;
695 break;
697 case 'x':
698 param++;
699 optimizing = MAX_OPTIMIZE;
700 break;
702 default:
703 nasm_error(ERR_FATAL,
704 "unknown optimization option -O%c\n",
705 *param);
706 break;
709 if (optimizing > MAX_OPTIMIZE)
710 optimizing = MAX_OPTIMIZE;
712 break;
715 case 'p': /* pre-include */
716 case 'P':
717 pp_pre_include(param);
718 break;
720 case 'd': /* pre-define */
721 case 'D':
722 pp_pre_define(param);
723 break;
725 case 'u': /* un-define */
726 case 'U':
727 pp_pre_undefine(param);
728 break;
730 case 'i': /* include search path */
731 case 'I':
732 pp_include_path(param);
733 break;
735 case 'l': /* listing file */
736 copy_filename(listname, param);
737 break;
739 case 'Z': /* error messages file */
740 copy_filename(errname, param);
741 break;
743 case 'F': /* specify debug format */
744 ofmt->current_dfmt = dfmt_find(ofmt, param);
745 if (!ofmt->current_dfmt) {
746 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
747 "unrecognized debug format `%s' for"
748 " output format `%s'",
749 param, ofmt->shortname);
751 using_debug_info = true;
752 break;
754 case 'X': /* specify error reporting format */
755 if (nasm_stricmp("vc", param) == 0)
756 nasm_set_verror(nasm_verror_vc);
757 else if (nasm_stricmp("gnu", param) == 0)
758 nasm_set_verror(nasm_verror_gnu);
759 else
760 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
761 "unrecognized error reporting format `%s'",
762 param);
763 break;
765 case 'g':
766 using_debug_info = true;
767 break;
769 case 'h':
770 printf
771 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
772 "[-l listfile]\n"
773 " [options...] [--] filename\n"
774 " or nasm -v for version info\n\n"
775 " -t assemble in SciTech TASM compatible mode\n"
776 " -g generate debug information in selected format\n");
777 printf
778 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
779 " -a don't preprocess (assemble only)\n"
780 " -M generate Makefile dependencies on stdout\n"
781 " -MG d:o, missing files assumed generated\n"
782 " -MF <file> set Makefile dependency file\n"
783 " -MD <file> assemble and generate dependencies\n"
784 " -MT <file> dependency target name\n"
785 " -MQ <file> dependency target name (quoted)\n"
786 " -MP emit phony target\n\n"
787 " -Z<file> redirect error messages to file\n"
788 " -s redirect error messages to stdout\n\n"
789 " -F format select a debugging format\n\n"
790 " -I<path> adds a pathname to the include file path\n");
791 printf
792 (" -O<digit> optimize branch offsets\n"
793 " -O0: No optimization (default)\n"
794 " -O1: Minimal optimization\n"
795 " -Ox: Multipass optimization (recommended)\n\n"
796 " -P<file> pre-includes a file\n"
797 " -D<macro>[=<value>] pre-defines a macro\n"
798 " -U<macro> undefines a macro\n"
799 " -X<format> specifies error reporting format (gnu or vc)\n"
800 " -w+foo enables warning foo (equiv. -Wfoo)\n"
801 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
802 "--prefix,--postfix\n"
803 " this options prepend or append the given argument to all\n"
804 " extern and global variables\n\n"
805 "Warnings:\n");
806 for (i = 0; i <= ERR_WARN_MAX; i++)
807 printf(" %-23s %s (default %s)\n",
808 warnings[i].name, warnings[i].help,
809 warnings[i].enabled ? "on" : "off");
810 printf
811 ("\nresponse files should contain command line parameters"
812 ", one per line.\n");
813 if (p[2] == 'f') {
814 printf("\nvalid output formats for -f are"
815 " (`*' denotes default):\n");
816 ofmt_list(ofmt, stdout);
817 } else {
818 printf("\nFor a list of valid output formats, use -hf.\n");
819 printf("For a list of debug formats, use -f <form> -y.\n");
821 exit(0); /* never need usage message here */
822 break;
824 case 'y':
825 printf("\nvalid debug formats for '%s' output format are"
826 " ('*' denotes default):\n", ofmt->shortname);
827 dfmt_list(ofmt, stdout);
828 exit(0);
829 break;
831 case 't':
832 tasm_compatible_mode = true;
833 break;
835 case 'v':
836 printf("NASM version %s compiled on %s%s\n",
837 nasm_version, nasm_date, nasm_compile_options);
838 exit(0); /* never need usage message here */
839 break;
841 case 'e': /* preprocess only */
842 case 'E':
843 operating_mode = op_preprocess;
844 break;
846 case 'a': /* assemble only - don't preprocess */
847 preproc = &no_pp;
848 break;
850 case 'W':
851 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
852 do_warn = false;
853 param += 3;
854 } else {
855 do_warn = true;
857 goto set_warning;
859 case 'w':
860 if (param[0] != '+' && param[0] != '-') {
861 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
862 "invalid option to `-w'");
863 break;
865 do_warn = (param[0] == '+');
866 param++;
868 set_warning:
869 for (i = 0; i <= ERR_WARN_MAX; i++)
870 if (!nasm_stricmp(param, warnings[i].name))
871 break;
872 if (i <= ERR_WARN_MAX)
873 warning_on_global[i] = do_warn;
874 else if (!nasm_stricmp(param, "all"))
875 for (i = 1; i <= ERR_WARN_MAX; i++)
876 warning_on_global[i] = do_warn;
877 else if (!nasm_stricmp(param, "none"))
878 for (i = 1; i <= ERR_WARN_MAX; i++)
879 warning_on_global[i] = !do_warn;
880 else
881 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
882 "invalid warning `%s'", param);
883 break;
885 case 'M':
886 switch (p[2]) {
887 case 0:
888 operating_mode = op_depend;
889 break;
890 case 'G':
891 operating_mode = op_depend;
892 depend_missing_ok = true;
893 break;
894 case 'P':
895 depend_emit_phony = true;
896 break;
897 case 'D':
898 depend_file = q;
899 advance = true;
900 break;
901 case 'T':
902 depend_target = q;
903 advance = true;
904 break;
905 case 'Q':
906 depend_target = quote_for_make(q);
907 advance = true;
908 break;
909 default:
910 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
911 "unknown dependency option `-M%c'", p[2]);
912 break;
914 if (advance && (!q || !q[0])) {
915 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
916 "option `-M%c' requires a parameter", p[2]);
917 break;
919 break;
921 case '-':
923 int s;
925 if (p[2] == 0) { /* -- => stop processing options */
926 stopoptions = 1;
927 break;
929 for (s = 0; textopts[s].label; s++) {
930 if (!nasm_stricmp(p + 2, textopts[s].label)) {
931 break;
935 switch (s) {
937 case OPT_PREFIX:
938 case OPT_POSTFIX:
940 if (!q) {
941 nasm_error(ERR_NONFATAL | ERR_NOFILE |
942 ERR_USAGE,
943 "option `--%s' requires an argument",
944 p + 2);
945 break;
946 } else {
947 advance = 1, param = q;
950 if (s == OPT_PREFIX) {
951 strncpy(lprefix, param, PREFIX_MAX - 1);
952 lprefix[PREFIX_MAX - 1] = 0;
953 break;
955 if (s == OPT_POSTFIX) {
956 strncpy(lpostfix, param, POSTFIX_MAX - 1);
957 lpostfix[POSTFIX_MAX - 1] = 0;
958 break;
960 break;
962 default:
964 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
965 "unrecognised option `--%s'", p + 2);
966 break;
969 break;
972 default:
973 if (!ofmt->setinfo(GI_SWITCH, &p))
974 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
975 "unrecognised option `-%c'", p[1]);
976 break;
978 } else {
979 if (*inname) {
980 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
981 "more than one input file specified");
982 } else {
983 copy_filename(inname, p);
987 return advance;
990 #define ARG_BUF_DELTA 128
992 static void process_respfile(FILE * rfile)
994 char *buffer, *p, *q, *prevarg;
995 int bufsize, prevargsize;
997 bufsize = prevargsize = ARG_BUF_DELTA;
998 buffer = nasm_malloc(ARG_BUF_DELTA);
999 prevarg = nasm_malloc(ARG_BUF_DELTA);
1000 prevarg[0] = '\0';
1002 while (1) { /* Loop to handle all lines in file */
1003 p = buffer;
1004 while (1) { /* Loop to handle long lines */
1005 q = fgets(p, bufsize - (p - buffer), rfile);
1006 if (!q)
1007 break;
1008 p += strlen(p);
1009 if (p > buffer && p[-1] == '\n')
1010 break;
1011 if (p - buffer > bufsize - 10) {
1012 int offset;
1013 offset = p - buffer;
1014 bufsize += ARG_BUF_DELTA;
1015 buffer = nasm_realloc(buffer, bufsize);
1016 p = buffer + offset;
1020 if (!q && p == buffer) {
1021 if (prevarg[0])
1022 process_arg(prevarg, NULL);
1023 nasm_free(buffer);
1024 nasm_free(prevarg);
1025 return;
1029 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1030 * them are present at the end of the line.
1032 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1034 while (p > buffer && nasm_isspace(p[-1]))
1035 *--p = '\0';
1037 p = nasm_skip_spaces(buffer);
1039 if (process_arg(prevarg, p))
1040 *p = '\0';
1042 if ((int) strlen(p) > prevargsize - 10) {
1043 prevargsize += ARG_BUF_DELTA;
1044 prevarg = nasm_realloc(prevarg, prevargsize);
1046 strncpy(prevarg, p, prevargsize);
1050 /* Function to process args from a string of args, rather than the
1051 * argv array. Used by the environment variable and response file
1052 * processing.
1054 static void process_args(char *args)
1056 char *p, *q, *arg, *prevarg;
1057 char separator = ' ';
1059 p = args;
1060 if (*p && *p != '-')
1061 separator = *p++;
1062 arg = NULL;
1063 while (*p) {
1064 q = p;
1065 while (*p && *p != separator)
1066 p++;
1067 while (*p == separator)
1068 *p++ = '\0';
1069 prevarg = arg;
1070 arg = q;
1071 if (process_arg(prevarg, arg))
1072 arg = NULL;
1074 if (arg)
1075 process_arg(arg, NULL);
1078 static void process_response_file(const char *file)
1080 char str[2048];
1081 FILE *f = fopen(file, "r");
1082 if (!f) {
1083 perror(file);
1084 exit(-1);
1086 while (fgets(str, sizeof str, f)) {
1087 process_args(str);
1089 fclose(f);
1092 static void parse_cmdline(int argc, char **argv)
1094 FILE *rfile;
1095 char *envreal, *envcopy = NULL, *p, *arg;
1096 int i;
1098 *inname = *outname = *listname = *errname = '\0';
1099 for (i = 0; i <= ERR_WARN_MAX; i++)
1100 warning_on_global[i] = warnings[i].enabled;
1103 * First, process the NASMENV environment variable.
1105 envreal = getenv("NASMENV");
1106 arg = NULL;
1107 if (envreal) {
1108 envcopy = nasm_strdup(envreal);
1109 process_args(envcopy);
1110 nasm_free(envcopy);
1114 * Now process the actual command line.
1116 while (--argc) {
1117 bool advance;
1118 argv++;
1119 if (argv[0][0] == '@') {
1120 /* We have a response file, so process this as a set of
1121 * arguments like the environment variable. This allows us
1122 * to have multiple arguments on a single line, which is
1123 * different to the -@resp file processing below for regular
1124 * NASM.
1126 process_response_file(argv[0]+1);
1127 argc--;
1128 argv++;
1130 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1131 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1132 if (p) {
1133 rfile = fopen(p, "r");
1134 if (rfile) {
1135 process_respfile(rfile);
1136 fclose(rfile);
1137 } else
1138 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1139 "unable to open response file `%s'", p);
1141 } else
1142 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1143 argv += advance, argc -= advance;
1146 /* Look for basic command line typos. This definitely doesn't
1147 catch all errors, but it might help cases of fumbled fingers. */
1148 if (!*inname)
1149 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1150 "no input file specified");
1151 else if (!strcmp(inname, errname) ||
1152 !strcmp(inname, outname) ||
1153 !strcmp(inname, listname) ||
1154 (depend_file && !strcmp(inname, depend_file)))
1155 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1156 "file `%s' is both input and output file",
1157 inname);
1159 if (*errname) {
1160 error_file = fopen(errname, "w");
1161 if (!error_file) {
1162 error_file = stderr; /* Revert to default! */
1163 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1164 "cannot open file `%s' for error messages",
1165 errname);
1170 static enum directives getkw(char **directive, char **value);
1172 static void assemble_file(char *fname, StrList **depend_ptr)
1174 char *directive, *value, *p, *q, *special, *line;
1175 insn output_ins;
1176 int i, validid;
1177 bool rn_error;
1178 int32_t seg;
1179 int64_t offs;
1180 struct tokenval tokval;
1181 expr *e;
1182 int pass_max;
1184 if (cmd_sb == 32 && cmd_cpu < IF_386)
1185 nasm_error(ERR_FATAL, "command line: "
1186 "32-bit segment size requires a higher cpu");
1188 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1189 for (passn = 1; pass0 <= 2; passn++) {
1190 int pass1, pass2;
1191 ldfunc def_label;
1193 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1194 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1195 /* pass0 0, 0, 0, ..., 1, 2 */
1197 def_label = passn > 1 ? redefine_label : define_label;
1199 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1200 cpu = cmd_cpu;
1201 if (pass0 == 2) {
1202 if (*listname)
1203 nasmlist.init(listname, nasm_error);
1205 in_abs_seg = false;
1206 global_offset_changed = 0; /* set by redefine_label */
1207 location.segment = ofmt->section(NULL, pass2, &sb);
1208 globalbits = sb;
1209 if (passn > 1) {
1210 saa_rewind(forwrefs);
1211 forwref = saa_rstruct(forwrefs);
1212 raa_free(offsets);
1213 offsets = raa_init();
1215 preproc->reset(fname, pass1, &nasmlist,
1216 pass1 == 2 ? depend_ptr : NULL);
1217 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1219 globallineno = 0;
1220 if (passn == 1)
1221 location.known = true;
1222 location.offset = offs = GET_CURR_OFFS;
1224 while ((line = preproc->getline())) {
1225 enum directives d;
1226 globallineno++;
1229 * Here we parse our directives; this is not handled by the
1230 * 'real' parser. This really should be a separate function.
1232 directive = line;
1233 d = getkw(&directive, &value);
1234 if (d) {
1235 int err = 0;
1237 switch (d) {
1238 case D_SEGMENT: /* [SEGMENT n] */
1239 case D_SECTION:
1240 seg = ofmt->section(value, pass2, &sb);
1241 if (seg == NO_SEG) {
1242 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1243 "segment name `%s' not recognized",
1244 value);
1245 } else {
1246 in_abs_seg = false;
1247 location.segment = seg;
1249 break;
1250 case D_SECTALIGN: /* [SECTALIGN n] */
1252 if (*value) {
1253 unsigned int align = atoi(value);
1254 if (!is_power2(align)) {
1255 nasm_error(ERR_NONFATAL,
1256 "segment alignment `%s' is not power of two",
1257 value);
1259 /* callee should be able to handle all details */
1260 ofmt->sectalign(location.segment, align);
1263 break;
1264 case D_EXTERN: /* [EXTERN label:special] */
1265 if (*value == '$')
1266 value++; /* skip initial $ if present */
1267 if (pass0 == 2) {
1268 q = value;
1269 while (*q && *q != ':')
1270 q++;
1271 if (*q == ':') {
1272 *q++ = '\0';
1273 ofmt->symdef(value, 0L, 0L, 3, q);
1275 } else if (passn == 1) {
1276 q = value;
1277 validid = true;
1278 if (!isidstart(*q))
1279 validid = false;
1280 while (*q && *q != ':') {
1281 if (!isidchar(*q))
1282 validid = false;
1283 q++;
1285 if (!validid) {
1286 nasm_error(ERR_NONFATAL,
1287 "identifier expected after EXTERN");
1288 break;
1290 if (*q == ':') {
1291 *q++ = '\0';
1292 special = q;
1293 } else
1294 special = NULL;
1295 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1296 int temp = pass0;
1297 pass0 = 1; /* fake pass 1 in labels.c */
1298 declare_as_global(value, special);
1299 define_label(value, seg_alloc(), 0L, NULL,
1300 false, true);
1301 pass0 = temp;
1303 } /* else pass0 == 1 */
1304 break;
1305 case D_BITS: /* [BITS bits] */
1306 globalbits = sb = get_bits(value);
1307 break;
1308 case D_GLOBAL: /* [GLOBAL symbol:special] */
1309 if (*value == '$')
1310 value++; /* skip initial $ if present */
1311 if (pass0 == 2) { /* pass 2 */
1312 q = value;
1313 while (*q && *q != ':')
1314 q++;
1315 if (*q == ':') {
1316 *q++ = '\0';
1317 ofmt->symdef(value, 0L, 0L, 3, q);
1319 } else if (pass2 == 1) { /* pass == 1 */
1320 q = value;
1321 validid = true;
1322 if (!isidstart(*q))
1323 validid = false;
1324 while (*q && *q != ':') {
1325 if (!isidchar(*q))
1326 validid = false;
1327 q++;
1329 if (!validid) {
1330 nasm_error(ERR_NONFATAL,
1331 "identifier expected after GLOBAL");
1332 break;
1334 if (*q == ':') {
1335 *q++ = '\0';
1336 special = q;
1337 } else
1338 special = NULL;
1339 declare_as_global(value, special);
1340 } /* pass == 1 */
1341 break;
1342 case D_COMMON: /* [COMMON symbol size:special] */
1344 int64_t size;
1346 if (*value == '$')
1347 value++; /* skip initial $ if present */
1348 p = value;
1349 validid = true;
1350 if (!isidstart(*p))
1351 validid = false;
1352 while (*p && !nasm_isspace(*p)) {
1353 if (!isidchar(*p))
1354 validid = false;
1355 p++;
1357 if (!validid) {
1358 nasm_error(ERR_NONFATAL,
1359 "identifier expected after COMMON");
1360 break;
1362 if (*p) {
1363 p = nasm_zap_spaces_fwd(p);
1364 q = p;
1365 while (*q && *q != ':')
1366 q++;
1367 if (*q == ':') {
1368 *q++ = '\0';
1369 special = q;
1370 } else {
1371 special = NULL;
1373 size = readnum(p, &rn_error);
1374 if (rn_error) {
1375 nasm_error(ERR_NONFATAL,
1376 "invalid size specified"
1377 " in COMMON declaration");
1378 break;
1380 } else {
1381 nasm_error(ERR_NONFATAL,
1382 "no size specified in"
1383 " COMMON declaration");
1384 break;
1387 if (pass0 < 2) {
1388 define_common(value, seg_alloc(), size, special);
1389 } else if (pass0 == 2) {
1390 if (special)
1391 ofmt->symdef(value, 0L, 0L, 3, special);
1393 break;
1395 case D_ABSOLUTE: /* [ABSOLUTE address] */
1396 stdscan_reset();
1397 stdscan_set(value);
1398 tokval.t_type = TOKEN_INVALID;
1399 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1400 nasm_error, NULL);
1401 if (e) {
1402 if (!is_reloc(e))
1403 nasm_error(pass0 ==
1404 1 ? ERR_NONFATAL : ERR_PANIC,
1405 "cannot use non-relocatable expression as "
1406 "ABSOLUTE address");
1407 else {
1408 abs_seg = reloc_seg(e);
1409 abs_offset = reloc_value(e);
1411 } else if (passn == 1)
1412 abs_offset = 0x100; /* don't go near zero in case of / */
1413 else
1414 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1415 "in pass two");
1416 in_abs_seg = true;
1417 location.segment = NO_SEG;
1418 break;
1419 case D_DEBUG: /* [DEBUG] */
1421 char debugid[128];
1422 bool badid, overlong;
1424 p = value;
1425 q = debugid;
1426 badid = overlong = false;
1427 if (!isidstart(*p)) {
1428 badid = true;
1429 } else {
1430 while (*p && !nasm_isspace(*p)) {
1431 if (q >= debugid + sizeof debugid - 1) {
1432 overlong = true;
1433 break;
1435 if (!isidchar(*p))
1436 badid = true;
1437 *q++ = *p++;
1439 *q = 0;
1441 if (badid) {
1442 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1443 "identifier expected after DEBUG");
1444 break;
1446 if (overlong) {
1447 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1448 "DEBUG identifier too long");
1449 break;
1451 p = nasm_skip_spaces(p);
1452 if (pass0 == 2)
1453 dfmt->debug_directive(debugid, p);
1454 break;
1456 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1457 value = nasm_skip_spaces(value);
1458 switch(*value) {
1459 case '-': validid = 0; value++; break;
1460 case '+': validid = 1; value++; break;
1461 case '*': validid = 2; value++; break;
1462 default: validid = 1; break;
1465 for (i = 1; i <= ERR_WARN_MAX; i++)
1466 if (!nasm_stricmp(value, warnings[i].name))
1467 break;
1468 if (i <= ERR_WARN_MAX) {
1469 switch(validid) {
1470 case 0:
1471 warning_on[i] = false;
1472 break;
1473 case 1:
1474 warning_on[i] = true;
1475 break;
1476 case 2:
1477 warning_on[i] = warning_on_global[i];
1478 break;
1481 else
1482 nasm_error(ERR_NONFATAL,
1483 "invalid warning id in WARNING directive");
1484 break;
1485 case D_CPU: /* [CPU] */
1486 cpu = get_cpu(value);
1487 break;
1488 case D_LIST: /* [LIST {+|-}] */
1489 value = nasm_skip_spaces(value);
1490 if (*value == '+') {
1491 user_nolist = 0;
1492 } else {
1493 if (*value == '-') {
1494 user_nolist = 1;
1495 } else {
1496 err = 1;
1499 break;
1500 case D_DEFAULT: /* [DEFAULT] */
1501 stdscan_reset();
1502 stdscan_set(value);
1503 tokval.t_type = TOKEN_INVALID;
1504 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1505 switch ((int)tokval.t_integer) {
1506 case S_REL:
1507 globalrel = 1;
1508 break;
1509 case S_ABS:
1510 globalrel = 0;
1511 break;
1512 default:
1513 err = 1;
1514 break;
1516 } else {
1517 err = 1;
1519 break;
1520 case D_FLOAT:
1521 if (float_option(value)) {
1522 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1523 "unknown 'float' directive: %s",
1524 value);
1526 break;
1527 default:
1528 if (ofmt->directive(d, value, pass2))
1529 break;
1530 /* else fall through */
1531 case D_unknown:
1532 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1533 "unrecognised directive [%s]",
1534 directive);
1535 break;
1537 if (err) {
1538 nasm_error(ERR_NONFATAL,
1539 "invalid parameter to [%s] directive",
1540 directive);
1542 } else { /* it isn't a directive */
1543 parse_line(pass1, line, &output_ins, def_label);
1545 if (optimizing > 0) {
1546 if (forwref != NULL && globallineno == forwref->lineno) {
1547 output_ins.forw_ref = true;
1548 do {
1549 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1550 forwref = saa_rstruct(forwrefs);
1551 } while (forwref != NULL
1552 && forwref->lineno == globallineno);
1553 } else
1554 output_ins.forw_ref = false;
1556 if (output_ins.forw_ref) {
1557 if (passn == 1) {
1558 for (i = 0; i < output_ins.operands; i++) {
1559 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1560 struct forwrefinfo *fwinf =
1561 (struct forwrefinfo *)
1562 saa_wstruct(forwrefs);
1563 fwinf->lineno = globallineno;
1564 fwinf->operand = i;
1571 /* forw_ref */
1572 if (output_ins.opcode == I_EQU) {
1573 if (pass1 == 1) {
1575 * Special `..' EQUs get processed in pass two,
1576 * except `..@' macro-processor EQUs which are done
1577 * in the normal place.
1579 if (!output_ins.label)
1580 nasm_error(ERR_NONFATAL,
1581 "EQU not preceded by label");
1583 else if (output_ins.label[0] != '.' ||
1584 output_ins.label[1] != '.' ||
1585 output_ins.label[2] == '@') {
1586 if (output_ins.operands == 1 &&
1587 (output_ins.oprs[0].type & IMMEDIATE) &&
1588 output_ins.oprs[0].wrt == NO_SEG) {
1589 bool isext = !!(output_ins.oprs[0].opflags
1590 & OPFLAG_EXTERN);
1591 def_label(output_ins.label,
1592 output_ins.oprs[0].segment,
1593 output_ins.oprs[0].offset, NULL,
1594 false, isext);
1595 } else if (output_ins.operands == 2
1596 && (output_ins.oprs[0].type & IMMEDIATE)
1597 && (output_ins.oprs[0].type & COLON)
1598 && output_ins.oprs[0].segment == NO_SEG
1599 && output_ins.oprs[0].wrt == NO_SEG
1600 && (output_ins.oprs[1].type & IMMEDIATE)
1601 && output_ins.oprs[1].segment == NO_SEG
1602 && output_ins.oprs[1].wrt == NO_SEG) {
1603 def_label(output_ins.label,
1604 output_ins.oprs[0].offset | SEG_ABS,
1605 output_ins.oprs[1].offset,
1606 NULL, false, false);
1607 } else
1608 nasm_error(ERR_NONFATAL,
1609 "bad syntax for EQU");
1611 } else {
1613 * Special `..' EQUs get processed here, except
1614 * `..@' macro processor EQUs which are done above.
1616 if (output_ins.label[0] == '.' &&
1617 output_ins.label[1] == '.' &&
1618 output_ins.label[2] != '@') {
1619 if (output_ins.operands == 1 &&
1620 (output_ins.oprs[0].type & IMMEDIATE)) {
1621 define_label(output_ins.label,
1622 output_ins.oprs[0].segment,
1623 output_ins.oprs[0].offset,
1624 NULL, false, false);
1625 } else if (output_ins.operands == 2
1626 && (output_ins.oprs[0].type & IMMEDIATE)
1627 && (output_ins.oprs[0].type & COLON)
1628 && output_ins.oprs[0].segment == NO_SEG
1629 && (output_ins.oprs[1].type & IMMEDIATE)
1630 && output_ins.oprs[1].segment == NO_SEG) {
1631 define_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");
1640 } else { /* instruction isn't an EQU */
1642 if (pass1 == 1) {
1644 int64_t l = insn_size(location.segment, offs, sb, cpu,
1645 &output_ins, nasm_error);
1647 /* if (using_debug_info) && output_ins.opcode != -1) */
1648 if (using_debug_info)
1649 { /* fbk 03/25/01 */
1650 /* this is done here so we can do debug type info */
1651 int32_t typeinfo =
1652 TYS_ELEMENTS(output_ins.operands);
1653 switch (output_ins.opcode) {
1654 case I_RESB:
1655 typeinfo =
1656 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1657 break;
1658 case I_RESW:
1659 typeinfo =
1660 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1661 break;
1662 case I_RESD:
1663 typeinfo =
1664 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1665 break;
1666 case I_RESQ:
1667 typeinfo =
1668 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1669 break;
1670 case I_REST:
1671 typeinfo =
1672 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1673 break;
1674 case I_RESO:
1675 typeinfo =
1676 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1677 break;
1678 case I_RESY:
1679 typeinfo =
1680 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1681 break;
1682 case I_DB:
1683 typeinfo |= TY_BYTE;
1684 break;
1685 case I_DW:
1686 typeinfo |= TY_WORD;
1687 break;
1688 case I_DD:
1689 if (output_ins.eops_float)
1690 typeinfo |= TY_FLOAT;
1691 else
1692 typeinfo |= TY_DWORD;
1693 break;
1694 case I_DQ:
1695 typeinfo |= TY_QWORD;
1696 break;
1697 case I_DT:
1698 typeinfo |= TY_TBYTE;
1699 break;
1700 case I_DO:
1701 typeinfo |= TY_OWORD;
1702 break;
1703 case I_DY:
1704 typeinfo |= TY_YWORD;
1705 break;
1706 default:
1707 typeinfo = TY_LABEL;
1711 dfmt->debug_typevalue(typeinfo);
1713 if (l != -1) {
1714 offs += l;
1715 SET_CURR_OFFS(offs);
1718 * else l == -1 => invalid instruction, which will be
1719 * flagged as an error on pass 2
1722 } else {
1723 offs += assemble(location.segment, offs, sb, cpu,
1724 &output_ins, ofmt, nasm_error,
1725 &nasmlist);
1726 SET_CURR_OFFS(offs);
1729 } /* not an EQU */
1730 cleanup_insn(&output_ins);
1732 nasm_free(line);
1733 location.offset = offs = GET_CURR_OFFS;
1734 } /* end while (line = preproc->getline... */
1736 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1737 nasm_error(ERR_NONFATAL,
1738 "phase error detected at end of assembly.");
1740 if (pass1 == 1)
1741 preproc->cleanup(1);
1743 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1744 pass0++;
1745 } else if (global_offset_changed &&
1746 global_offset_changed < prev_offset_changed) {
1747 prev_offset_changed = global_offset_changed;
1748 stall_count = 0;
1749 } else {
1750 stall_count++;
1753 if (terminate_after_phase)
1754 break;
1756 if ((stall_count > 997) || (passn >= pass_max)) {
1757 /* We get here if the labels don't converge
1758 * Example: FOO equ FOO + 1
1760 nasm_error(ERR_NONFATAL,
1761 "Can't find valid values for all labels "
1762 "after %d passes, giving up.", passn);
1763 nasm_error(ERR_NONFATAL,
1764 "Possible causes: recursive EQUs, macro abuse.");
1765 break;
1769 preproc->cleanup(0);
1770 nasmlist.cleanup();
1771 if (!terminate_after_phase && opt_verbose_info) {
1772 /* -On and -Ov switches */
1773 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1777 static enum directives getkw(char **directive, char **value)
1779 char *p, *q, *buf;
1781 buf = nasm_skip_spaces(*directive);
1783 /* it should be enclosed in [ ] */
1784 if (*buf != '[')
1785 return D_none;
1786 q = strchr(buf, ']');
1787 if (!q)
1788 return D_none;
1790 /* stip off the comments */
1791 p = strchr(buf, ';');
1792 if (p) {
1793 if (p < q) /* ouch! somwhere inside */
1794 return D_none;
1795 *p = '\0';
1798 /* no brace, no trailing spaces */
1799 *q = '\0';
1800 nasm_zap_spaces_rev(--q);
1802 /* directive */
1803 p = nasm_skip_spaces(++buf);
1804 q = nasm_skip_word(p);
1805 if (!q)
1806 return D_none; /* sigh... no value there */
1807 *q = '\0';
1808 *directive = p;
1810 /* and value finally */
1811 p = nasm_skip_spaces(++q);
1812 *value = p;
1814 return find_directive(*directive);
1818 * gnu style error reporting
1819 * This function prints an error message to error_file in the
1820 * style used by GNU. An example would be:
1821 * file.asm:50: error: blah blah blah
1822 * where file.asm is the name of the file, 50 is the line number on
1823 * which the error occurs (or is detected) and "error:" is one of
1824 * the possible optional diagnostics -- it can be "error" or "warning"
1825 * or something else. Finally the line terminates with the actual
1826 * error message.
1828 * @param severity the severity of the warning or error
1829 * @param fmt the printf style format string
1831 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1833 char *currentfile = NULL;
1834 int32_t lineno = 0;
1836 if (is_suppressed_warning(severity))
1837 return;
1839 if (!(severity & ERR_NOFILE))
1840 src_get(&lineno, &currentfile);
1842 if (currentfile) {
1843 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1844 nasm_free(currentfile);
1845 } else {
1846 fputs("nasm: ", error_file);
1849 nasm_verror_common(severity, fmt, ap);
1853 * MS style error reporting
1854 * This function prints an error message to error_file in the
1855 * style used by Visual C and some other Microsoft tools. An example
1856 * would be:
1857 * file.asm(50) : error: blah blah blah
1858 * where file.asm is the name of the file, 50 is the line number on
1859 * which the error occurs (or is detected) and "error:" is one of
1860 * the possible optional diagnostics -- it can be "error" or "warning"
1861 * or something else. Finally the line terminates with the actual
1862 * error message.
1864 * @param severity the severity of the warning or error
1865 * @param fmt the printf style format string
1867 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1869 char *currentfile = NULL;
1870 int32_t lineno = 0;
1872 if (is_suppressed_warning(severity))
1873 return;
1875 if (!(severity & ERR_NOFILE))
1876 src_get(&lineno, &currentfile);
1878 if (currentfile) {
1879 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1880 nasm_free(currentfile);
1881 } else {
1882 fputs("nasm: ", error_file);
1885 nasm_verror_common(severity, fmt, ap);
1889 * check for supressed warning
1890 * checks for suppressed warning or pass one only warning and we're
1891 * not in pass 1
1893 * @param severity the severity of the warning or error
1894 * @return true if we should abort error/warning printing
1896 static bool is_suppressed_warning(int severity)
1899 * See if it's a suppressed warning.
1901 return (severity & ERR_MASK) == ERR_WARNING &&
1902 (((severity & ERR_WARN_MASK) != 0 &&
1903 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1904 /* See if it's a pass-one only warning and we're not in pass one. */
1905 ((severity & ERR_PASS1) && pass0 != 1) ||
1906 ((severity & ERR_PASS2) && pass0 != 2));
1910 * common error reporting
1911 * This is the common back end of the error reporting schemes currently
1912 * implemented. It prints the nature of the warning and then the
1913 * specific error message to error_file and may or may not return. It
1914 * doesn't return if the error severity is a "panic" or "debug" type.
1916 * @param severity the severity of the warning or error
1917 * @param fmt the printf style format string
1919 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1921 char msg[1024];
1922 const char *pfx;
1924 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1925 case ERR_WARNING:
1926 pfx = "warning: ";
1927 break;
1928 case ERR_NONFATAL:
1929 pfx = "error: ";
1930 break;
1931 case ERR_FATAL:
1932 pfx = "fatal: ";
1933 break;
1934 case ERR_PANIC:
1935 pfx = "panic: ";
1936 break;
1937 case ERR_DEBUG:
1938 pfx = "debug: ";
1939 break;
1940 default:
1941 pfx = "";
1942 break;
1945 vsnprintf(msg, sizeof msg, fmt, args);
1947 fprintf(error_file, "%s%s\n", pfx, msg);
1949 if (*listname)
1950 nasmlist.error(severity, pfx, msg);
1952 if (severity & ERR_USAGE)
1953 want_usage = true;
1955 switch (severity & ERR_MASK) {
1956 case ERR_DEBUG:
1957 /* no further action, by definition */
1958 break;
1959 case ERR_WARNING:
1960 if (warning_on[0]) /* Treat warnings as errors */
1961 terminate_after_phase = true;
1962 break;
1963 case ERR_NONFATAL:
1964 terminate_after_phase = true;
1965 break;
1966 case ERR_FATAL:
1967 if (ofile) {
1968 fclose(ofile);
1969 remove(outname);
1970 ofile = NULL;
1972 if (want_usage)
1973 usage();
1974 exit(1); /* instantly die */
1975 break; /* placate silly compilers */
1976 case ERR_PANIC:
1977 fflush(NULL);
1978 /* abort(); *//* halt, catch fire, and dump core */
1979 exit(3);
1980 break;
1984 static void usage(void)
1986 fputs("type `nasm -h' for help\n", error_file);
1989 #define BUF_DELTA 512
1991 static FILE *no_pp_fp;
1992 static ListGen *no_pp_list;
1993 static int32_t no_pp_lineinc;
1995 static void no_pp_reset(char *file, int pass, ListGen * listgen,
1996 StrList **deplist)
1998 src_set_fname(nasm_strdup(file));
1999 src_set_linnum(0);
2000 no_pp_lineinc = 1;
2001 no_pp_fp = fopen(file, "r");
2002 if (!no_pp_fp)
2003 nasm_error(ERR_FATAL | ERR_NOFILE,
2004 "unable to open input file `%s'", file);
2005 no_pp_list = listgen;
2006 (void)pass; /* placate compilers */
2008 if (deplist) {
2009 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2010 sl->next = NULL;
2011 strcpy(sl->str, file);
2012 *deplist = sl;
2016 static char *no_pp_getline(void)
2018 char *buffer, *p, *q;
2019 int bufsize;
2021 bufsize = BUF_DELTA;
2022 buffer = nasm_malloc(BUF_DELTA);
2023 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2025 while (1) { /* Loop to handle %line */
2027 p = buffer;
2028 while (1) { /* Loop to handle long lines */
2029 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2030 if (!q)
2031 break;
2032 p += strlen(p);
2033 if (p > buffer && p[-1] == '\n')
2034 break;
2035 if (p - buffer > bufsize - 10) {
2036 int offset;
2037 offset = p - buffer;
2038 bufsize += BUF_DELTA;
2039 buffer = nasm_realloc(buffer, bufsize);
2040 p = buffer + offset;
2044 if (!q && p == buffer) {
2045 nasm_free(buffer);
2046 return NULL;
2050 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2051 * them are present at the end of the line.
2053 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2055 if (!nasm_strnicmp(buffer, "%line", 5)) {
2056 int32_t ln;
2057 int li;
2058 char *nm = nasm_malloc(strlen(buffer));
2059 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2060 nasm_free(src_set_fname(nm));
2061 src_set_linnum(ln);
2062 no_pp_lineinc = li;
2063 continue;
2065 nasm_free(nm);
2067 break;
2070 no_pp_list->line(LIST_READ, buffer);
2072 return buffer;
2075 static void no_pp_cleanup(int pass)
2077 (void)pass; /* placate GCC */
2078 if (no_pp_fp) {
2079 fclose(no_pp_fp);
2080 no_pp_fp = NULL;
2084 static uint32_t get_cpu(char *value)
2086 if (!strcmp(value, "8086"))
2087 return IF_8086;
2088 if (!strcmp(value, "186"))
2089 return IF_186;
2090 if (!strcmp(value, "286"))
2091 return IF_286;
2092 if (!strcmp(value, "386"))
2093 return IF_386;
2094 if (!strcmp(value, "486"))
2095 return IF_486;
2096 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2097 return IF_PENT;
2098 if (!strcmp(value, "686") ||
2099 !nasm_stricmp(value, "ppro") ||
2100 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2101 return IF_P6;
2102 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2103 return IF_KATMAI;
2104 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2105 !nasm_stricmp(value, "willamette"))
2106 return IF_WILLAMETTE;
2107 if (!nasm_stricmp(value, "prescott"))
2108 return IF_PRESCOTT;
2109 if (!nasm_stricmp(value, "x64") ||
2110 !nasm_stricmp(value, "x86-64"))
2111 return IF_X86_64;
2112 if (!nasm_stricmp(value, "ia64") ||
2113 !nasm_stricmp(value, "ia-64") ||
2114 !nasm_stricmp(value, "itanium") ||
2115 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2116 return IF_IA64;
2118 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2119 "unknown 'cpu' type");
2121 return IF_PLEVEL; /* the maximum level */
2124 static int get_bits(char *value)
2126 int i;
2128 if ((i = atoi(value)) == 16)
2129 return i; /* set for a 16-bit segment */
2130 else if (i == 32) {
2131 if (cpu < IF_386) {
2132 nasm_error(ERR_NONFATAL,
2133 "cannot specify 32-bit segment on processor below a 386");
2134 i = 16;
2136 } else if (i == 64) {
2137 if (cpu < IF_X86_64) {
2138 nasm_error(ERR_NONFATAL,
2139 "cannot specify 64-bit segment on processor below an x86-64");
2140 i = 16;
2142 if (i != maxbits) {
2143 nasm_error(ERR_NONFATAL,
2144 "%s output format does not support 64-bit code",
2145 ofmt->shortname);
2146 i = 16;
2148 } else {
2149 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2150 "`%s' is not a valid segment size; must be 16, 32 or 64",
2151 value);
2152 i = 16;
2154 return i;