BR 3392207: preproc: Rewrite paste_tokens routine
[nasm.git] / nasm.c
blob63e73e7fd215f4f8dbf4e6faa9e8ce64a9b180bc
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2012 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 struct preproc_ops *preproc;
127 enum op_type {
128 op_normal, /* Preprocess and assemble */
129 op_preprocess, /* Preprocess only */
130 op_depend, /* Generate dependencies */
132 static enum op_type operating_mode;
133 /* Dependency flags */
134 static bool depend_emit_phony = false;
135 static bool depend_missing_ok = false;
136 static const char *depend_target = NULL;
137 static const char *depend_file = NULL;
140 * Which of the suppressible warnings are suppressed. Entry zero
141 * isn't an actual warning, but it used for -w+error/-Werror.
144 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
145 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
147 static const struct warning {
148 const char *name;
149 const char *help;
150 bool enabled;
151 } warnings[ERR_WARN_MAX+1] = {
152 {"error", "treat warnings as errors", false},
153 {"macro-params", "macro calls with wrong parameter count", true},
154 {"macro-selfref", "cyclic macro references", false},
155 {"macro-defaults", "macros with more default than optional parameters", true},
156 {"orphan-labels", "labels alone on lines without trailing `:'", true},
157 {"number-overflow", "numeric constant does not fit", true},
158 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
159 {"float-overflow", "floating point overflow", true},
160 {"float-denorm", "floating point denormal", false},
161 {"float-underflow", "floating point underflow", false},
162 {"float-toolong", "too many digits in floating-point number", true},
163 {"user", "%warning directives", true},
164 {"lock", "lock prefix on unlockable instructions", true},
165 {"hle", "invalid hle prefixes", true},
169 * get/set current offset...
171 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
172 raa_read(offsets,location.segment))
173 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
174 (void)(offsets=raa_write(offsets,location.segment,(x))))
176 static bool want_usage;
177 static bool terminate_after_phase;
178 int user_nolist = 0; /* fbk 9/2/00 */
180 static void nasm_fputs(const char *line, FILE * outfile)
182 if (outfile) {
183 fputs(line, outfile);
184 putc('\n', outfile);
185 } else
186 puts(line);
189 /* Convert a struct tm to a POSIX-style time constant */
190 static int64_t posix_mktime(struct tm *tm)
192 int64_t t;
193 int64_t y = tm->tm_year;
195 /* See IEEE 1003.1:2004, section 4.14 */
197 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
198 t += tm->tm_yday;
199 t *= 24;
200 t += tm->tm_hour;
201 t *= 60;
202 t += tm->tm_min;
203 t *= 60;
204 t += tm->tm_sec;
206 return t;
209 static void define_macros_early(void)
211 char temp[128];
212 struct tm lt, *lt_p, gm, *gm_p;
213 int64_t posix_time;
215 lt_p = localtime(&official_compile_time);
216 if (lt_p) {
217 lt = *lt_p;
219 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
220 preproc->pre_define(temp);
221 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
222 preproc->pre_define(temp);
223 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
224 preproc->pre_define(temp);
225 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
226 preproc->pre_define(temp);
229 gm_p = gmtime(&official_compile_time);
230 if (gm_p) {
231 gm = *gm_p;
233 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
234 preproc->pre_define(temp);
235 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
238 preproc->pre_define(temp);
239 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
240 preproc->pre_define(temp);
243 if (gm_p)
244 posix_time = posix_mktime(&gm);
245 else if (lt_p)
246 posix_time = posix_mktime(&lt);
247 else
248 posix_time = 0;
250 if (posix_time) {
251 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
252 preproc->pre_define(temp);
256 static void define_macros_late(void)
258 char temp[128];
261 * In case if output format is defined by alias
262 * we have to put shortname of the alias itself here
263 * otherwise ABI backward compatibility gets broken.
265 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
266 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
267 preproc->pre_define(temp);
270 static void emit_dependencies(StrList *list)
272 FILE *deps;
273 int linepos, len;
274 StrList *l, *nl;
276 if (depend_file && strcmp(depend_file, "-")) {
277 deps = fopen(depend_file, "w");
278 if (!deps) {
279 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
280 "unable to write dependency file `%s'", depend_file);
281 return;
283 } else {
284 deps = stdout;
287 linepos = fprintf(deps, "%s:", depend_target);
288 list_for_each(l, list) {
289 len = strlen(l->str);
290 if (linepos + len > 62) {
291 fprintf(deps, " \\\n ");
292 linepos = 1;
294 fprintf(deps, " %s", l->str);
295 linepos += len+1;
297 fprintf(deps, "\n\n");
299 list_for_each_safe(l, nl, list) {
300 if (depend_emit_phony)
301 fprintf(deps, "%s:\n\n", l->str);
302 nasm_free(l);
305 if (deps != stdout)
306 fclose(deps);
309 int main(int argc, char **argv)
311 StrList *depend_list = NULL, **depend_ptr;
313 time(&official_compile_time);
315 pass0 = 0;
316 want_usage = terminate_after_phase = false;
317 nasm_set_verror(nasm_verror_gnu);
319 error_file = stderr;
321 tolower_init();
323 nasm_init_malloc_error();
324 offsets = raa_init();
325 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
327 preproc = &nasmpp;
328 operating_mode = op_normal;
330 seg_init();
332 /* Define some macros dependent on the runtime, but not
333 on the command line. */
334 define_macros_early();
336 parse_cmdline(argc, argv);
338 if (terminate_after_phase) {
339 if (want_usage)
340 usage();
341 return 1;
344 /* If debugging info is disabled, suppress any debug calls */
345 if (!using_debug_info)
346 ofmt->current_dfmt = &null_debug_form;
348 if (ofmt->stdmac)
349 preproc->extra_stdmac(ofmt->stdmac);
350 parser_global_info(&location);
351 eval_global_info(ofmt, lookup_label, &location);
353 /* define some macros dependent of command-line */
354 define_macros_late();
356 depend_ptr = (depend_file || (operating_mode == op_depend))
357 ? &depend_list : NULL;
358 if (!depend_target)
359 depend_target = outname;
361 switch (operating_mode) {
362 case op_depend:
364 char *line;
366 if (depend_missing_ok)
367 preproc->include_path(NULL); /* "assume generated" */
369 preproc->reset(inname, 0, &nasmlist, depend_ptr);
370 if (outname[0] == '\0')
371 ofmt->filename(inname, outname);
372 ofile = NULL;
373 while ((line = preproc->getline()))
374 nasm_free(line);
375 preproc->cleanup(0);
377 break;
379 case op_preprocess:
381 char *line;
382 char *file_name = NULL;
383 int32_t prior_linnum = 0;
384 int lineinc = 0;
386 if (*outname) {
387 ofile = fopen(outname, "w");
388 if (!ofile)
389 nasm_error(ERR_FATAL | ERR_NOFILE,
390 "unable to open output file `%s'",
391 outname);
392 } else
393 ofile = NULL;
395 location.known = false;
397 /* pass = 1; */
398 preproc->reset(inname, 3, &nasmlist, depend_ptr);
399 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
401 while ((line = preproc->getline())) {
403 * We generate %line directives if needed for later programs
405 int32_t linnum = prior_linnum += lineinc;
406 int altline = src_get(&linnum, &file_name);
407 if (altline) {
408 if (altline == 1 && lineinc == 1)
409 nasm_fputs("", ofile);
410 else {
411 lineinc = (altline != -1 || lineinc != 1);
412 fprintf(ofile ? ofile : stdout,
413 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
414 file_name);
416 prior_linnum = linnum;
418 nasm_fputs(line, ofile);
419 nasm_free(line);
421 nasm_free(file_name);
422 preproc->cleanup(0);
423 if (ofile)
424 fclose(ofile);
425 if (ofile && terminate_after_phase)
426 remove(outname);
427 ofile = NULL;
429 break;
431 case op_normal:
434 * We must call ofmt->filename _anyway_, even if the user
435 * has specified their own output file, because some
436 * formats (eg OBJ and COFF) use ofmt->filename to find out
437 * the name of the input file and then put that inside the
438 * file.
440 ofmt->filename(inname, outname);
442 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
443 if (!ofile) {
444 nasm_error(ERR_FATAL | ERR_NOFILE,
445 "unable to open output file `%s'", outname);
449 * We must call init_labels() before ofmt->init() since
450 * some object formats will want to define labels in their
451 * init routines. (eg OS/2 defines the FLAT group)
453 init_labels();
455 ofmt->init();
456 dfmt = ofmt->current_dfmt;
457 dfmt->init();
459 assemble_file(inname, depend_ptr);
461 if (!terminate_after_phase) {
462 ofmt->cleanup(using_debug_info);
463 cleanup_labels();
464 fflush(ofile);
465 if (ferror(ofile)) {
466 nasm_error(ERR_NONFATAL|ERR_NOFILE,
467 "write error on output file `%s'", outname);
471 if (ofile) {
472 fclose(ofile);
473 if (terminate_after_phase)
474 remove(outname);
475 ofile = NULL;
478 break;
481 if (depend_list && !terminate_after_phase)
482 emit_dependencies(depend_list);
484 if (want_usage)
485 usage();
487 raa_free(offsets);
488 saa_free(forwrefs);
489 eval_cleanup();
490 stdscan_cleanup();
492 return terminate_after_phase;
496 * Get a parameter for a command line option.
497 * First arg must be in the form of e.g. -f...
499 static char *get_param(char *p, char *q, bool *advance)
501 *advance = false;
502 if (p[2]) /* the parameter's in the option */
503 return nasm_skip_spaces(p + 2);
504 if (q && q[0]) {
505 *advance = true;
506 return q;
508 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
509 "option `-%c' requires an argument", p[1]);
510 return NULL;
514 * Copy a filename
516 static void copy_filename(char *dst, const char *src)
518 size_t len = strlen(src);
520 if (len >= (size_t)FILENAME_MAX) {
521 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
522 return;
524 strncpy(dst, src, FILENAME_MAX);
528 * Convert a string to Make-safe form
530 static char *quote_for_make(const char *str)
532 const char *p;
533 char *os, *q;
535 size_t n = 1; /* Terminating zero */
536 size_t nbs = 0;
538 if (!str)
539 return NULL;
541 for (p = str; *p; p++) {
542 switch (*p) {
543 case ' ':
544 case '\t':
545 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
546 n += nbs + 2;
547 nbs = 0;
548 break;
549 case '$':
550 case '#':
551 nbs = 0;
552 n += 2;
553 break;
554 case '\\':
555 nbs++;
556 n++;
557 break;
558 default:
559 nbs = 0;
560 n++;
561 break;
565 /* Convert N backslashes at the end of filename to 2N backslashes */
566 if (nbs)
567 n += nbs;
569 os = q = nasm_malloc(n);
571 nbs = 0;
572 for (p = str; *p; p++) {
573 switch (*p) {
574 case ' ':
575 case '\t':
576 while (nbs--)
577 *q++ = '\\';
578 *q++ = '\\';
579 *q++ = *p;
580 break;
581 case '$':
582 *q++ = *p;
583 *q++ = *p;
584 nbs = 0;
585 break;
586 case '#':
587 *q++ = '\\';
588 *q++ = *p;
589 nbs = 0;
590 break;
591 case '\\':
592 *q++ = *p;
593 nbs++;
594 break;
595 default:
596 *q++ = *p;
597 nbs = 0;
598 break;
601 while (nbs--)
602 *q++ = '\\';
604 *q = '\0';
606 return os;
609 struct textargs {
610 const char *label;
611 int value;
614 #define OPT_PREFIX 0
615 #define OPT_POSTFIX 1
616 struct textargs textopts[] = {
617 {"prefix", OPT_PREFIX},
618 {"postfix", OPT_POSTFIX},
619 {NULL, 0}
622 static bool stopoptions = false;
623 static bool process_arg(char *p, char *q)
625 char *param;
626 int i;
627 bool advance = false;
628 bool do_warn;
630 if (!p || !p[0])
631 return false;
633 if (p[0] == '-' && !stopoptions) {
634 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
635 /* These parameters take values */
636 if (!(param = get_param(p, q, &advance)))
637 return advance;
640 switch (p[1]) {
641 case 's':
642 error_file = stdout;
643 break;
645 case 'o': /* output file */
646 copy_filename(outname, param);
647 break;
649 case 'f': /* output format */
650 ofmt = ofmt_find(param, &ofmt_alias);
651 if (!ofmt) {
652 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
653 "unrecognised output format `%s' - "
654 "use -hf for a list", param);
656 break;
658 case 'O': /* Optimization level */
660 int opt;
662 if (!*param) {
663 /* Naked -O == -Ox */
664 optimizing = MAX_OPTIMIZE;
665 } else {
666 while (*param) {
667 switch (*param) {
668 case '0': case '1': case '2': case '3': case '4':
669 case '5': case '6': case '7': case '8': case '9':
670 opt = strtoul(param, &param, 10);
672 /* -O0 -> optimizing == -1, 0.98 behaviour */
673 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
674 if (opt < 2)
675 optimizing = opt - 1;
676 else
677 optimizing = opt;
678 break;
680 case 'v':
681 case '+':
682 param++;
683 opt_verbose_info = true;
684 break;
686 case 'x':
687 param++;
688 optimizing = MAX_OPTIMIZE;
689 break;
691 default:
692 nasm_error(ERR_FATAL,
693 "unknown optimization option -O%c\n",
694 *param);
695 break;
698 if (optimizing > MAX_OPTIMIZE)
699 optimizing = MAX_OPTIMIZE;
701 break;
704 case 'p': /* pre-include */
705 case 'P':
706 preproc->pre_include(param);
707 break;
709 case 'd': /* pre-define */
710 case 'D':
711 preproc->pre_define(param);
712 break;
714 case 'u': /* un-define */
715 case 'U':
716 preproc->pre_undefine(param);
717 break;
719 case 'i': /* include search path */
720 case 'I':
721 preproc->include_path(param);
722 break;
724 case 'l': /* listing file */
725 copy_filename(listname, param);
726 break;
728 case 'Z': /* error messages file */
729 copy_filename(errname, param);
730 break;
732 case 'F': /* specify debug format */
733 ofmt->current_dfmt = dfmt_find(ofmt, param);
734 if (!ofmt->current_dfmt) {
735 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
736 "unrecognized debug format `%s' for"
737 " output format `%s'",
738 param, ofmt->shortname);
740 using_debug_info = true;
741 break;
743 case 'X': /* specify error reporting format */
744 if (nasm_stricmp("vc", param) == 0)
745 nasm_set_verror(nasm_verror_vc);
746 else if (nasm_stricmp("gnu", param) == 0)
747 nasm_set_verror(nasm_verror_gnu);
748 else
749 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
750 "unrecognized error reporting format `%s'",
751 param);
752 break;
754 case 'g':
755 using_debug_info = true;
756 break;
758 case 'h':
759 printf
760 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
761 "[-l listfile]\n"
762 " [options...] [--] filename\n"
763 " or nasm -v for version info\n\n"
764 " -t assemble in SciTech TASM compatible mode\n"
765 " -g generate debug information in selected format\n");
766 printf
767 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
768 " -a don't preprocess (assemble only)\n"
769 " -M generate Makefile dependencies on stdout\n"
770 " -MG d:o, missing files assumed generated\n"
771 " -MF <file> set Makefile dependency file\n"
772 " -MD <file> assemble and generate dependencies\n"
773 " -MT <file> dependency target name\n"
774 " -MQ <file> dependency target name (quoted)\n"
775 " -MP emit phony target\n\n"
776 " -Z<file> redirect error messages to file\n"
777 " -s redirect error messages to stdout\n\n"
778 " -F format select a debugging format\n\n"
779 " -I<path> adds a pathname to the include file path\n");
780 printf
781 (" -O<digit> optimize branch offsets\n"
782 " -O0: No optimization\n"
783 " -O1: Minimal optimization\n"
784 " -Ox: Multipass optimization (default)\n\n"
785 " -P<file> pre-includes a file\n"
786 " -D<macro>[=<value>] pre-defines a macro\n"
787 " -U<macro> undefines a macro\n"
788 " -X<format> specifies error reporting format (gnu or vc)\n"
789 " -w+foo enables warning foo (equiv. -Wfoo)\n"
790 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
791 "--prefix,--postfix\n"
792 " this options prepend or append the given argument to all\n"
793 " extern and global variables\n\n"
794 "Warnings:\n");
795 for (i = 0; i <= ERR_WARN_MAX; i++)
796 printf(" %-23s %s (default %s)\n",
797 warnings[i].name, warnings[i].help,
798 warnings[i].enabled ? "on" : "off");
799 printf
800 ("\nresponse files should contain command line parameters"
801 ", one per line.\n");
802 if (p[2] == 'f') {
803 printf("\nvalid output formats for -f are"
804 " (`*' denotes default):\n");
805 ofmt_list(ofmt, stdout);
806 } else {
807 printf("\nFor a list of valid output formats, use -hf.\n");
808 printf("For a list of debug formats, use -f <form> -y.\n");
810 exit(0); /* never need usage message here */
811 break;
813 case 'y':
814 printf("\nvalid debug formats for '%s' output format are"
815 " ('*' denotes default):\n", ofmt->shortname);
816 dfmt_list(ofmt, stdout);
817 exit(0);
818 break;
820 case 't':
821 tasm_compatible_mode = true;
822 break;
824 case 'v':
825 printf("NASM version %s compiled on %s%s\n",
826 nasm_version, nasm_date, nasm_compile_options);
827 exit(0); /* never need usage message here */
828 break;
830 case 'e': /* preprocess only */
831 case 'E':
832 operating_mode = op_preprocess;
833 break;
835 case 'a': /* assemble only - don't preprocess */
836 preproc = &preproc_nop;
837 break;
839 case 'W':
840 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
841 do_warn = false;
842 param += 3;
843 } else {
844 do_warn = true;
846 goto set_warning;
848 case 'w':
849 if (param[0] != '+' && param[0] != '-') {
850 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
851 "invalid option to `-w'");
852 break;
854 do_warn = (param[0] == '+');
855 param++;
857 set_warning:
858 for (i = 0; i <= ERR_WARN_MAX; i++) {
859 if (!nasm_stricmp(param, warnings[i].name))
860 break;
862 if (i <= ERR_WARN_MAX) {
863 warning_on_global[i] = do_warn;
864 } else if (!nasm_stricmp(param, "all")) {
865 for (i = 1; i <= ERR_WARN_MAX; i++)
866 warning_on_global[i] = do_warn;
867 } else if (!nasm_stricmp(param, "none")) {
868 for (i = 1; i <= ERR_WARN_MAX; i++)
869 warning_on_global[i] = !do_warn;
870 } else {
871 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
872 "invalid warning `%s'", param);
874 break;
876 case 'M':
877 switch (p[2]) {
878 case 0:
879 operating_mode = op_depend;
880 break;
881 case 'G':
882 operating_mode = op_depend;
883 depend_missing_ok = true;
884 break;
885 case 'P':
886 depend_emit_phony = true;
887 break;
888 case 'D':
889 depend_file = q;
890 advance = true;
891 break;
892 case 'T':
893 depend_target = q;
894 advance = true;
895 break;
896 case 'Q':
897 depend_target = quote_for_make(q);
898 advance = true;
899 break;
900 default:
901 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
902 "unknown dependency option `-M%c'", p[2]);
903 break;
905 if (advance && (!q || !q[0])) {
906 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
907 "option `-M%c' requires a parameter", p[2]);
908 break;
910 break;
912 case '-':
914 int s;
916 if (p[2] == 0) { /* -- => stop processing options */
917 stopoptions = 1;
918 break;
920 for (s = 0; textopts[s].label; s++) {
921 if (!nasm_stricmp(p + 2, textopts[s].label)) {
922 break;
926 switch (s) {
928 case OPT_PREFIX:
929 case OPT_POSTFIX:
931 if (!q) {
932 nasm_error(ERR_NONFATAL | ERR_NOFILE |
933 ERR_USAGE,
934 "option `--%s' requires an argument",
935 p + 2);
936 break;
937 } else {
938 advance = 1, param = q;
941 if (s == OPT_PREFIX) {
942 strncpy(lprefix, param, PREFIX_MAX - 1);
943 lprefix[PREFIX_MAX - 1] = 0;
944 break;
946 if (s == OPT_POSTFIX) {
947 strncpy(lpostfix, param, POSTFIX_MAX - 1);
948 lpostfix[POSTFIX_MAX - 1] = 0;
949 break;
951 break;
953 default:
955 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
956 "unrecognised option `--%s'", p + 2);
957 break;
960 break;
963 default:
964 if (!ofmt->setinfo(GI_SWITCH, &p))
965 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
966 "unrecognised option `-%c'", p[1]);
967 break;
969 } else {
970 if (*inname) {
971 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
972 "more than one input file specified");
973 } else {
974 copy_filename(inname, p);
978 return advance;
981 #define ARG_BUF_DELTA 128
983 static void process_respfile(FILE * rfile)
985 char *buffer, *p, *q, *prevarg;
986 int bufsize, prevargsize;
988 bufsize = prevargsize = ARG_BUF_DELTA;
989 buffer = nasm_malloc(ARG_BUF_DELTA);
990 prevarg = nasm_malloc(ARG_BUF_DELTA);
991 prevarg[0] = '\0';
993 while (1) { /* Loop to handle all lines in file */
994 p = buffer;
995 while (1) { /* Loop to handle long lines */
996 q = fgets(p, bufsize - (p - buffer), rfile);
997 if (!q)
998 break;
999 p += strlen(p);
1000 if (p > buffer && p[-1] == '\n')
1001 break;
1002 if (p - buffer > bufsize - 10) {
1003 int offset;
1004 offset = p - buffer;
1005 bufsize += ARG_BUF_DELTA;
1006 buffer = nasm_realloc(buffer, bufsize);
1007 p = buffer + offset;
1011 if (!q && p == buffer) {
1012 if (prevarg[0])
1013 process_arg(prevarg, NULL);
1014 nasm_free(buffer);
1015 nasm_free(prevarg);
1016 return;
1020 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1021 * them are present at the end of the line.
1023 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1025 while (p > buffer && nasm_isspace(p[-1]))
1026 *--p = '\0';
1028 p = nasm_skip_spaces(buffer);
1030 if (process_arg(prevarg, p))
1031 *p = '\0';
1033 if ((int) strlen(p) > prevargsize - 10) {
1034 prevargsize += ARG_BUF_DELTA;
1035 prevarg = nasm_realloc(prevarg, prevargsize);
1037 strncpy(prevarg, p, prevargsize);
1041 /* Function to process args from a string of args, rather than the
1042 * argv array. Used by the environment variable and response file
1043 * processing.
1045 static void process_args(char *args)
1047 char *p, *q, *arg, *prevarg;
1048 char separator = ' ';
1050 p = args;
1051 if (*p && *p != '-')
1052 separator = *p++;
1053 arg = NULL;
1054 while (*p) {
1055 q = p;
1056 while (*p && *p != separator)
1057 p++;
1058 while (*p == separator)
1059 *p++ = '\0';
1060 prevarg = arg;
1061 arg = q;
1062 if (process_arg(prevarg, arg))
1063 arg = NULL;
1065 if (arg)
1066 process_arg(arg, NULL);
1069 static void process_response_file(const char *file)
1071 char str[2048];
1072 FILE *f = fopen(file, "r");
1073 if (!f) {
1074 perror(file);
1075 exit(-1);
1077 while (fgets(str, sizeof str, f)) {
1078 process_args(str);
1080 fclose(f);
1083 static void parse_cmdline(int argc, char **argv)
1085 FILE *rfile;
1086 char *envreal, *envcopy = NULL, *p;
1087 int i;
1089 *inname = *outname = *listname = *errname = '\0';
1091 for (i = 0; i <= ERR_WARN_MAX; i++)
1092 warning_on_global[i] = warnings[i].enabled;
1095 * First, process the NASMENV environment variable.
1097 envreal = getenv("NASMENV");
1098 if (envreal) {
1099 envcopy = nasm_strdup(envreal);
1100 process_args(envcopy);
1101 nasm_free(envcopy);
1105 * Now process the actual command line.
1107 while (--argc) {
1108 bool advance;
1109 argv++;
1110 if (argv[0][0] == '@') {
1112 * We have a response file, so process this as a set of
1113 * arguments like the environment variable. This allows us
1114 * to have multiple arguments on a single line, which is
1115 * different to the -@resp file processing below for regular
1116 * NASM.
1118 process_response_file(argv[0]+1);
1119 argc--;
1120 argv++;
1122 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1123 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1124 if (p) {
1125 rfile = fopen(p, "r");
1126 if (rfile) {
1127 process_respfile(rfile);
1128 fclose(rfile);
1129 } else
1130 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1131 "unable to open response file `%s'", p);
1133 } else
1134 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1135 argv += advance, argc -= advance;
1139 * Look for basic command line typos. This definitely doesn't
1140 * catch all errors, but it might help cases of fumbled fingers.
1142 if (!*inname)
1143 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1144 "no input file specified");
1145 else if (!strcmp(inname, errname) ||
1146 !strcmp(inname, outname) ||
1147 !strcmp(inname, listname) ||
1148 (depend_file && !strcmp(inname, depend_file)))
1149 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1150 "file `%s' is both input and output file",
1151 inname);
1153 if (*errname) {
1154 error_file = fopen(errname, "w");
1155 if (!error_file) {
1156 error_file = stderr; /* Revert to default! */
1157 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1158 "cannot open file `%s' for error messages",
1159 errname);
1164 static enum directives getkw(char **directive, char **value);
1166 static void assemble_file(char *fname, StrList **depend_ptr)
1168 char *directive, *value, *p, *q, *special, *line;
1169 insn output_ins;
1170 int i, validid;
1171 bool rn_error;
1172 int32_t seg;
1173 int64_t offs;
1174 struct tokenval tokval;
1175 expr *e;
1176 int pass_max;
1178 if (cmd_sb == 32 && cmd_cpu < IF_386)
1179 nasm_error(ERR_FATAL, "command line: "
1180 "32-bit segment size requires a higher cpu");
1182 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1183 for (passn = 1; pass0 <= 2; passn++) {
1184 int pass1, pass2;
1185 ldfunc def_label;
1187 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1188 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1189 /* pass0 0, 0, 0, ..., 1, 2 */
1191 def_label = passn > 1 ? redefine_label : define_label;
1193 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1194 cpu = cmd_cpu;
1195 if (pass0 == 2) {
1196 if (*listname)
1197 nasmlist.init(listname, nasm_error);
1199 in_abs_seg = false;
1200 global_offset_changed = 0; /* set by redefine_label */
1201 location.segment = ofmt->section(NULL, pass2, &sb);
1202 globalbits = sb;
1203 if (passn > 1) {
1204 saa_rewind(forwrefs);
1205 forwref = saa_rstruct(forwrefs);
1206 raa_free(offsets);
1207 offsets = raa_init();
1209 preproc->reset(fname, pass1, &nasmlist,
1210 pass1 == 2 ? depend_ptr : NULL);
1211 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1213 globallineno = 0;
1214 if (passn == 1)
1215 location.known = true;
1216 location.offset = offs = GET_CURR_OFFS;
1218 while ((line = preproc->getline())) {
1219 enum directives d;
1220 globallineno++;
1223 * Here we parse our directives; this is not handled by the
1224 * 'real' parser. This really should be a separate function.
1226 directive = line;
1227 d = getkw(&directive, &value);
1228 if (d) {
1229 int err = 0;
1231 switch (d) {
1232 case D_SEGMENT: /* [SEGMENT n] */
1233 case D_SECTION:
1234 seg = ofmt->section(value, pass2, &sb);
1235 if (seg == NO_SEG) {
1236 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1237 "segment name `%s' not recognized",
1238 value);
1239 } else {
1240 in_abs_seg = false;
1241 location.segment = seg;
1243 break;
1244 case D_SECTALIGN: /* [SECTALIGN n] */
1245 if (*value) {
1246 stdscan_reset();
1247 stdscan_set(value);
1248 tokval.t_type = TOKEN_INVALID;
1249 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1250 if (e) {
1251 unsigned int align = (unsigned int)e->value;
1252 if ((uint64_t)e->value > 0x7fffffff) {
1254 * FIXME: Please make some sane message here
1255 * ofmt should have some 'check' method which
1256 * would report segment alignment bounds.
1258 nasm_error(ERR_FATAL,
1259 "incorrect segment alignment `%s'", value);
1260 } else if (!is_power2(align)) {
1261 nasm_error(ERR_NONFATAL,
1262 "segment alignment `%s' is not power of two",
1263 value);
1265 /* callee should be able to handle all details */
1266 ofmt->sectalign(location.segment, align);
1269 break;
1270 case D_EXTERN: /* [EXTERN label:special] */
1271 if (*value == '$')
1272 value++; /* skip initial $ if present */
1273 if (pass0 == 2) {
1274 q = value;
1275 while (*q && *q != ':')
1276 q++;
1277 if (*q == ':') {
1278 *q++ = '\0';
1279 ofmt->symdef(value, 0L, 0L, 3, q);
1281 } else if (passn == 1) {
1282 q = value;
1283 validid = true;
1284 if (!isidstart(*q))
1285 validid = false;
1286 while (*q && *q != ':') {
1287 if (!isidchar(*q))
1288 validid = false;
1289 q++;
1291 if (!validid) {
1292 nasm_error(ERR_NONFATAL,
1293 "identifier expected after EXTERN");
1294 break;
1296 if (*q == ':') {
1297 *q++ = '\0';
1298 special = q;
1299 } else
1300 special = NULL;
1301 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1302 int temp = pass0;
1303 pass0 = 1; /* fake pass 1 in labels.c */
1304 declare_as_global(value, special);
1305 define_label(value, seg_alloc(), 0L, NULL,
1306 false, true);
1307 pass0 = temp;
1309 } /* else pass0 == 1 */
1310 break;
1311 case D_BITS: /* [BITS bits] */
1312 globalbits = sb = get_bits(value);
1313 break;
1314 case D_GLOBAL: /* [GLOBAL symbol:special] */
1315 if (*value == '$')
1316 value++; /* skip initial $ if present */
1317 if (pass0 == 2) { /* pass 2 */
1318 q = value;
1319 while (*q && *q != ':')
1320 q++;
1321 if (*q == ':') {
1322 *q++ = '\0';
1323 ofmt->symdef(value, 0L, 0L, 3, q);
1325 } else if (pass2 == 1) { /* pass == 1 */
1326 q = value;
1327 validid = true;
1328 if (!isidstart(*q))
1329 validid = false;
1330 while (*q && *q != ':') {
1331 if (!isidchar(*q))
1332 validid = false;
1333 q++;
1335 if (!validid) {
1336 nasm_error(ERR_NONFATAL,
1337 "identifier expected after GLOBAL");
1338 break;
1340 if (*q == ':') {
1341 *q++ = '\0';
1342 special = q;
1343 } else
1344 special = NULL;
1345 declare_as_global(value, special);
1346 } /* pass == 1 */
1347 break;
1348 case D_COMMON: /* [COMMON symbol size:special] */
1350 int64_t size;
1352 if (*value == '$')
1353 value++; /* skip initial $ if present */
1354 p = value;
1355 validid = true;
1356 if (!isidstart(*p))
1357 validid = false;
1358 while (*p && !nasm_isspace(*p)) {
1359 if (!isidchar(*p))
1360 validid = false;
1361 p++;
1363 if (!validid) {
1364 nasm_error(ERR_NONFATAL,
1365 "identifier expected after COMMON");
1366 break;
1368 if (*p) {
1369 p = nasm_zap_spaces_fwd(p);
1370 q = p;
1371 while (*q && *q != ':')
1372 q++;
1373 if (*q == ':') {
1374 *q++ = '\0';
1375 special = q;
1376 } else {
1377 special = NULL;
1379 size = readnum(p, &rn_error);
1380 if (rn_error) {
1381 nasm_error(ERR_NONFATAL,
1382 "invalid size specified"
1383 " in COMMON declaration");
1384 break;
1386 } else {
1387 nasm_error(ERR_NONFATAL,
1388 "no size specified in"
1389 " COMMON declaration");
1390 break;
1393 if (pass0 < 2) {
1394 define_common(value, seg_alloc(), size, special);
1395 } else if (pass0 == 2) {
1396 if (special)
1397 ofmt->symdef(value, 0L, 0L, 3, special);
1399 break;
1401 case D_ABSOLUTE: /* [ABSOLUTE address] */
1402 stdscan_reset();
1403 stdscan_set(value);
1404 tokval.t_type = TOKEN_INVALID;
1405 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1406 nasm_error, NULL);
1407 if (e) {
1408 if (!is_reloc(e))
1409 nasm_error(pass0 ==
1410 1 ? ERR_NONFATAL : ERR_PANIC,
1411 "cannot use non-relocatable expression as "
1412 "ABSOLUTE address");
1413 else {
1414 abs_seg = reloc_seg(e);
1415 abs_offset = reloc_value(e);
1417 } else if (passn == 1)
1418 abs_offset = 0x100; /* don't go near zero in case of / */
1419 else
1420 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1421 "in pass two");
1422 in_abs_seg = true;
1423 location.segment = NO_SEG;
1424 break;
1425 case D_DEBUG: /* [DEBUG] */
1427 char debugid[128];
1428 bool badid, overlong;
1430 p = value;
1431 q = debugid;
1432 badid = overlong = false;
1433 if (!isidstart(*p)) {
1434 badid = true;
1435 } else {
1436 while (*p && !nasm_isspace(*p)) {
1437 if (q >= debugid + sizeof debugid - 1) {
1438 overlong = true;
1439 break;
1441 if (!isidchar(*p))
1442 badid = true;
1443 *q++ = *p++;
1445 *q = 0;
1447 if (badid) {
1448 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1449 "identifier expected after DEBUG");
1450 break;
1452 if (overlong) {
1453 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1454 "DEBUG identifier too long");
1455 break;
1457 p = nasm_skip_spaces(p);
1458 if (pass0 == 2)
1459 dfmt->debug_directive(debugid, p);
1460 break;
1462 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1463 value = nasm_skip_spaces(value);
1464 switch(*value) {
1465 case '-': validid = 0; value++; break;
1466 case '+': validid = 1; value++; break;
1467 case '*': validid = 2; value++; break;
1468 default: validid = 1; break;
1471 for (i = 1; i <= ERR_WARN_MAX; i++)
1472 if (!nasm_stricmp(value, warnings[i].name))
1473 break;
1474 if (i <= ERR_WARN_MAX) {
1475 switch(validid) {
1476 case 0:
1477 warning_on[i] = false;
1478 break;
1479 case 1:
1480 warning_on[i] = true;
1481 break;
1482 case 2:
1483 warning_on[i] = warning_on_global[i];
1484 break;
1487 else
1488 nasm_error(ERR_NONFATAL,
1489 "invalid warning id in WARNING directive");
1490 break;
1491 case D_CPU: /* [CPU] */
1492 cpu = get_cpu(value);
1493 break;
1494 case D_LIST: /* [LIST {+|-}] */
1495 value = nasm_skip_spaces(value);
1496 if (*value == '+') {
1497 user_nolist = 0;
1498 } else {
1499 if (*value == '-') {
1500 user_nolist = 1;
1501 } else {
1502 err = 1;
1505 break;
1506 case D_DEFAULT: /* [DEFAULT] */
1507 stdscan_reset();
1508 stdscan_set(value);
1509 tokval.t_type = TOKEN_INVALID;
1510 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1511 switch ((int)tokval.t_integer) {
1512 case S_REL:
1513 globalrel = 1;
1514 break;
1515 case S_ABS:
1516 globalrel = 0;
1517 break;
1518 default:
1519 err = 1;
1520 break;
1522 } else {
1523 err = 1;
1525 break;
1526 case D_FLOAT:
1527 if (float_option(value)) {
1528 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1529 "unknown 'float' directive: %s",
1530 value);
1532 break;
1533 default:
1534 if (ofmt->directive(d, value, pass2))
1535 break;
1536 /* else fall through */
1537 case D_unknown:
1538 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1539 "unrecognised directive [%s]",
1540 directive);
1541 break;
1543 if (err) {
1544 nasm_error(ERR_NONFATAL,
1545 "invalid parameter to [%s] directive",
1546 directive);
1548 } else { /* it isn't a directive */
1549 parse_line(pass1, line, &output_ins, def_label);
1551 if (optimizing > 0) {
1552 if (forwref != NULL && globallineno == forwref->lineno) {
1553 output_ins.forw_ref = true;
1554 do {
1555 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1556 forwref = saa_rstruct(forwrefs);
1557 } while (forwref != NULL
1558 && forwref->lineno == globallineno);
1559 } else
1560 output_ins.forw_ref = false;
1562 if (output_ins.forw_ref) {
1563 if (passn == 1) {
1564 for (i = 0; i < output_ins.operands; i++) {
1565 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1566 struct forwrefinfo *fwinf =
1567 (struct forwrefinfo *)
1568 saa_wstruct(forwrefs);
1569 fwinf->lineno = globallineno;
1570 fwinf->operand = i;
1577 /* forw_ref */
1578 if (output_ins.opcode == I_EQU) {
1579 if (pass1 == 1) {
1581 * Special `..' EQUs get processed in pass two,
1582 * except `..@' macro-processor EQUs which are done
1583 * in the normal place.
1585 if (!output_ins.label)
1586 nasm_error(ERR_NONFATAL,
1587 "EQU not preceded by label");
1589 else if (output_ins.label[0] != '.' ||
1590 output_ins.label[1] != '.' ||
1591 output_ins.label[2] == '@') {
1592 if (output_ins.operands == 1 &&
1593 (output_ins.oprs[0].type & IMMEDIATE) &&
1594 output_ins.oprs[0].wrt == NO_SEG) {
1595 bool isext = !!(output_ins.oprs[0].opflags
1596 & OPFLAG_EXTERN);
1597 def_label(output_ins.label,
1598 output_ins.oprs[0].segment,
1599 output_ins.oprs[0].offset, NULL,
1600 false, isext);
1601 } else if (output_ins.operands == 2
1602 && (output_ins.oprs[0].type & IMMEDIATE)
1603 && (output_ins.oprs[0].type & COLON)
1604 && output_ins.oprs[0].segment == NO_SEG
1605 && output_ins.oprs[0].wrt == NO_SEG
1606 && (output_ins.oprs[1].type & IMMEDIATE)
1607 && output_ins.oprs[1].segment == NO_SEG
1608 && output_ins.oprs[1].wrt == NO_SEG) {
1609 def_label(output_ins.label,
1610 output_ins.oprs[0].offset | SEG_ABS,
1611 output_ins.oprs[1].offset,
1612 NULL, false, false);
1613 } else
1614 nasm_error(ERR_NONFATAL,
1615 "bad syntax for EQU");
1617 } else {
1619 * Special `..' EQUs get processed here, except
1620 * `..@' macro processor EQUs which are done above.
1622 if (output_ins.label[0] == '.' &&
1623 output_ins.label[1] == '.' &&
1624 output_ins.label[2] != '@') {
1625 if (output_ins.operands == 1 &&
1626 (output_ins.oprs[0].type & IMMEDIATE)) {
1627 define_label(output_ins.label,
1628 output_ins.oprs[0].segment,
1629 output_ins.oprs[0].offset,
1630 NULL, false, false);
1631 } else if (output_ins.operands == 2
1632 && (output_ins.oprs[0].type & IMMEDIATE)
1633 && (output_ins.oprs[0].type & COLON)
1634 && output_ins.oprs[0].segment == NO_SEG
1635 && (output_ins.oprs[1].type & IMMEDIATE)
1636 && output_ins.oprs[1].segment == NO_SEG) {
1637 define_label(output_ins.label,
1638 output_ins.oprs[0].offset | SEG_ABS,
1639 output_ins.oprs[1].offset,
1640 NULL, false, false);
1641 } else
1642 nasm_error(ERR_NONFATAL,
1643 "bad syntax for EQU");
1646 } else { /* instruction isn't an EQU */
1648 if (pass1 == 1) {
1650 int64_t l = insn_size(location.segment, offs, sb, cpu,
1651 &output_ins, nasm_error);
1653 /* if (using_debug_info) && output_ins.opcode != -1) */
1654 if (using_debug_info)
1655 { /* fbk 03/25/01 */
1656 /* this is done here so we can do debug type info */
1657 int32_t typeinfo =
1658 TYS_ELEMENTS(output_ins.operands);
1659 switch (output_ins.opcode) {
1660 case I_RESB:
1661 typeinfo =
1662 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1663 break;
1664 case I_RESW:
1665 typeinfo =
1666 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1667 break;
1668 case I_RESD:
1669 typeinfo =
1670 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1671 break;
1672 case I_RESQ:
1673 typeinfo =
1674 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1675 break;
1676 case I_REST:
1677 typeinfo =
1678 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1679 break;
1680 case I_RESO:
1681 typeinfo =
1682 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1683 break;
1684 case I_RESY:
1685 typeinfo =
1686 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1687 break;
1688 case I_DB:
1689 typeinfo |= TY_BYTE;
1690 break;
1691 case I_DW:
1692 typeinfo |= TY_WORD;
1693 break;
1694 case I_DD:
1695 if (output_ins.eops_float)
1696 typeinfo |= TY_FLOAT;
1697 else
1698 typeinfo |= TY_DWORD;
1699 break;
1700 case I_DQ:
1701 typeinfo |= TY_QWORD;
1702 break;
1703 case I_DT:
1704 typeinfo |= TY_TBYTE;
1705 break;
1706 case I_DO:
1707 typeinfo |= TY_OWORD;
1708 break;
1709 case I_DY:
1710 typeinfo |= TY_YWORD;
1711 break;
1712 default:
1713 typeinfo = TY_LABEL;
1717 dfmt->debug_typevalue(typeinfo);
1719 if (l != -1) {
1720 offs += l;
1721 SET_CURR_OFFS(offs);
1724 * else l == -1 => invalid instruction, which will be
1725 * flagged as an error on pass 2
1728 } else {
1729 offs += assemble(location.segment, offs, sb, cpu,
1730 &output_ins, ofmt, nasm_error,
1731 &nasmlist);
1732 SET_CURR_OFFS(offs);
1735 } /* not an EQU */
1736 cleanup_insn(&output_ins);
1738 nasm_free(line);
1739 location.offset = offs = GET_CURR_OFFS;
1740 } /* end while (line = preproc->getline... */
1742 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1743 nasm_error(ERR_NONFATAL,
1744 "phase error detected at end of assembly.");
1746 if (pass1 == 1)
1747 preproc->cleanup(1);
1749 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1750 pass0++;
1751 } else if (global_offset_changed &&
1752 global_offset_changed < prev_offset_changed) {
1753 prev_offset_changed = global_offset_changed;
1754 stall_count = 0;
1755 } else {
1756 stall_count++;
1759 if (terminate_after_phase)
1760 break;
1762 if ((stall_count > 997) || (passn >= pass_max)) {
1763 /* We get here if the labels don't converge
1764 * Example: FOO equ FOO + 1
1766 nasm_error(ERR_NONFATAL,
1767 "Can't find valid values for all labels "
1768 "after %d passes, giving up.", passn);
1769 nasm_error(ERR_NONFATAL,
1770 "Possible causes: recursive EQUs, macro abuse.");
1771 break;
1775 preproc->cleanup(0);
1776 nasmlist.cleanup();
1777 if (!terminate_after_phase && opt_verbose_info) {
1778 /* -On and -Ov switches */
1779 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1783 static enum directives getkw(char **directive, char **value)
1785 char *p, *q, *buf;
1787 buf = nasm_skip_spaces(*directive);
1789 /* it should be enclosed in [ ] */
1790 if (*buf != '[')
1791 return D_none;
1792 q = strchr(buf, ']');
1793 if (!q)
1794 return D_none;
1796 /* stip off the comments */
1797 p = strchr(buf, ';');
1798 if (p) {
1799 if (p < q) /* ouch! somwhere inside */
1800 return D_none;
1801 *p = '\0';
1804 /* no brace, no trailing spaces */
1805 *q = '\0';
1806 nasm_zap_spaces_rev(--q);
1808 /* directive */
1809 p = nasm_skip_spaces(++buf);
1810 q = nasm_skip_word(p);
1811 if (!q)
1812 return D_none; /* sigh... no value there */
1813 *q = '\0';
1814 *directive = p;
1816 /* and value finally */
1817 p = nasm_skip_spaces(++q);
1818 *value = p;
1820 return find_directive(*directive);
1824 * gnu style error reporting
1825 * This function prints an error message to error_file in the
1826 * style used by GNU. An example would be:
1827 * file.asm:50: error: blah blah blah
1828 * where file.asm is the name of the file, 50 is the line number on
1829 * which the error occurs (or is detected) and "error:" is one of
1830 * the possible optional diagnostics -- it can be "error" or "warning"
1831 * or something else. Finally the line terminates with the actual
1832 * error message.
1834 * @param severity the severity of the warning or error
1835 * @param fmt the printf style format string
1837 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1839 char *currentfile = NULL;
1840 int32_t lineno = 0;
1842 if (is_suppressed_warning(severity))
1843 return;
1845 if (!(severity & ERR_NOFILE))
1846 src_get(&lineno, &currentfile);
1848 if (currentfile) {
1849 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1850 nasm_free(currentfile);
1851 } else {
1852 fputs("nasm: ", error_file);
1855 nasm_verror_common(severity, fmt, ap);
1859 * MS style error reporting
1860 * This function prints an error message to error_file in the
1861 * style used by Visual C and some other Microsoft tools. An example
1862 * would be:
1863 * file.asm(50) : error: blah blah blah
1864 * where file.asm is the name of the file, 50 is the line number on
1865 * which the error occurs (or is detected) and "error:" is one of
1866 * the possible optional diagnostics -- it can be "error" or "warning"
1867 * or something else. Finally the line terminates with the actual
1868 * error message.
1870 * @param severity the severity of the warning or error
1871 * @param fmt the printf style format string
1873 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1875 char *currentfile = NULL;
1876 int32_t lineno = 0;
1878 if (is_suppressed_warning(severity))
1879 return;
1881 if (!(severity & ERR_NOFILE))
1882 src_get(&lineno, &currentfile);
1884 if (currentfile) {
1885 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1886 nasm_free(currentfile);
1887 } else {
1888 fputs("nasm: ", error_file);
1891 nasm_verror_common(severity, fmt, ap);
1895 * check for supressed warning
1896 * checks for suppressed warning or pass one only warning and we're
1897 * not in pass 1
1899 * @param severity the severity of the warning or error
1900 * @return true if we should abort error/warning printing
1902 static bool is_suppressed_warning(int severity)
1904 /* Not a warning at all */
1905 if ((severity & ERR_MASK) != ERR_WARNING)
1906 return false;
1908 /* See if it's a pass-one only warning and we're not in pass one. */
1909 if (((severity & ERR_PASS1) && pass0 != 1) ||
1910 ((severity & ERR_PASS2) && pass0 != 2))
1911 return true;
1913 /* Might be a warning but suppresed explicitly */
1914 if (severity & ERR_WARN_MASK)
1915 return !warning_on[WARN_IDX(severity)];
1916 else
1917 return false;
1921 * common error reporting
1922 * This is the common back end of the error reporting schemes currently
1923 * implemented. It prints the nature of the warning and then the
1924 * specific error message to error_file and may or may not return. It
1925 * doesn't return if the error severity is a "panic" or "debug" type.
1927 * @param severity the severity of the warning or error
1928 * @param fmt the printf style format string
1930 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1932 char msg[1024];
1933 const char *pfx;
1935 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1936 case ERR_WARNING:
1937 pfx = "warning: ";
1938 break;
1939 case ERR_NONFATAL:
1940 pfx = "error: ";
1941 break;
1942 case ERR_FATAL:
1943 pfx = "fatal: ";
1944 break;
1945 case ERR_PANIC:
1946 pfx = "panic: ";
1947 break;
1948 case ERR_DEBUG:
1949 pfx = "debug: ";
1950 break;
1951 default:
1952 pfx = "";
1953 break;
1956 vsnprintf(msg, sizeof msg, fmt, args);
1958 fprintf(error_file, "%s%s\n", pfx, msg);
1960 if (*listname)
1961 nasmlist.error(severity, pfx, msg);
1963 if (severity & ERR_USAGE)
1964 want_usage = true;
1966 switch (severity & ERR_MASK) {
1967 case ERR_DEBUG:
1968 /* no further action, by definition */
1969 break;
1970 case ERR_WARNING:
1971 /* Treat warnings as errors */
1972 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1973 terminate_after_phase = true;
1974 break;
1975 case ERR_NONFATAL:
1976 terminate_after_phase = true;
1977 break;
1978 case ERR_FATAL:
1979 if (ofile) {
1980 fclose(ofile);
1981 remove(outname);
1982 ofile = NULL;
1984 if (want_usage)
1985 usage();
1986 exit(1); /* instantly die */
1987 break; /* placate silly compilers */
1988 case ERR_PANIC:
1989 fflush(NULL);
1990 /* abort(); *//* halt, catch fire, and dump core */
1991 exit(3);
1992 break;
1996 static void usage(void)
1998 fputs("type `nasm -h' for help\n", error_file);
2001 static uint32_t get_cpu(char *value)
2003 if (!strcmp(value, "8086"))
2004 return IF_8086;
2005 if (!strcmp(value, "186"))
2006 return IF_186;
2007 if (!strcmp(value, "286"))
2008 return IF_286;
2009 if (!strcmp(value, "386"))
2010 return IF_386;
2011 if (!strcmp(value, "486"))
2012 return IF_486;
2013 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2014 return IF_PENT;
2015 if (!strcmp(value, "686") ||
2016 !nasm_stricmp(value, "ppro") ||
2017 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2018 return IF_P6;
2019 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2020 return IF_KATMAI;
2021 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2022 !nasm_stricmp(value, "willamette"))
2023 return IF_WILLAMETTE;
2024 if (!nasm_stricmp(value, "prescott"))
2025 return IF_PRESCOTT;
2026 if (!nasm_stricmp(value, "x64") ||
2027 !nasm_stricmp(value, "x86-64"))
2028 return IF_X86_64;
2029 if (!nasm_stricmp(value, "ia64") ||
2030 !nasm_stricmp(value, "ia-64") ||
2031 !nasm_stricmp(value, "itanium") ||
2032 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2033 return IF_IA64;
2035 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2036 "unknown 'cpu' type");
2038 return IF_PLEVEL; /* the maximum level */
2041 static int get_bits(char *value)
2043 int i;
2045 if ((i = atoi(value)) == 16)
2046 return i; /* set for a 16-bit segment */
2047 else if (i == 32) {
2048 if (cpu < IF_386) {
2049 nasm_error(ERR_NONFATAL,
2050 "cannot specify 32-bit segment on processor below a 386");
2051 i = 16;
2053 } else if (i == 64) {
2054 if (cpu < IF_X86_64) {
2055 nasm_error(ERR_NONFATAL,
2056 "cannot specify 64-bit segment on processor below an x86-64");
2057 i = 16;
2059 if (i != maxbits) {
2060 nasm_error(ERR_NONFATAL,
2061 "%s output format does not support 64-bit code",
2062 ofmt->shortname);
2063 i = 16;
2065 } else {
2066 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2067 "`%s' is not a valid segment size; must be 16, 32 or 64",
2068 value);
2069 i = 16;
2071 return i;