preproc: Add tokenization tracing
[nasm.git] / nasm.c
blob9baec18c73cc3e1e217161ecb877a4eb97da0e2e
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] */
1251 if (*value) {
1252 stdscan_reset();
1253 stdscan_set(value);
1254 tokval.t_type = TOKEN_INVALID;
1255 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1256 if (e) {
1257 unsigned int align = (unsigned int)e->value;
1258 if ((uint64_t)e->value > 0x7fffffff) {
1260 * FIXME: Please make some sane message here
1261 * ofmt should have some 'check' method which
1262 * would report segment alignment bounds.
1264 nasm_error(ERR_FATAL,
1265 "incorrect segment alignment `%s'", value);
1266 } else if (!is_power2(align)) {
1267 nasm_error(ERR_NONFATAL,
1268 "segment alignment `%s' is not power of two",
1269 value);
1271 /* callee should be able to handle all details */
1272 ofmt->sectalign(location.segment, align);
1275 break;
1276 case D_EXTERN: /* [EXTERN label:special] */
1277 if (*value == '$')
1278 value++; /* skip initial $ if present */
1279 if (pass0 == 2) {
1280 q = value;
1281 while (*q && *q != ':')
1282 q++;
1283 if (*q == ':') {
1284 *q++ = '\0';
1285 ofmt->symdef(value, 0L, 0L, 3, q);
1287 } else if (passn == 1) {
1288 q = value;
1289 validid = true;
1290 if (!isidstart(*q))
1291 validid = false;
1292 while (*q && *q != ':') {
1293 if (!isidchar(*q))
1294 validid = false;
1295 q++;
1297 if (!validid) {
1298 nasm_error(ERR_NONFATAL,
1299 "identifier expected after EXTERN");
1300 break;
1302 if (*q == ':') {
1303 *q++ = '\0';
1304 special = q;
1305 } else
1306 special = NULL;
1307 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1308 int temp = pass0;
1309 pass0 = 1; /* fake pass 1 in labels.c */
1310 declare_as_global(value, special);
1311 define_label(value, seg_alloc(), 0L, NULL,
1312 false, true);
1313 pass0 = temp;
1315 } /* else pass0 == 1 */
1316 break;
1317 case D_BITS: /* [BITS bits] */
1318 globalbits = sb = get_bits(value);
1319 break;
1320 case D_GLOBAL: /* [GLOBAL symbol:special] */
1321 if (*value == '$')
1322 value++; /* skip initial $ if present */
1323 if (pass0 == 2) { /* pass 2 */
1324 q = value;
1325 while (*q && *q != ':')
1326 q++;
1327 if (*q == ':') {
1328 *q++ = '\0';
1329 ofmt->symdef(value, 0L, 0L, 3, q);
1331 } else if (pass2 == 1) { /* pass == 1 */
1332 q = value;
1333 validid = true;
1334 if (!isidstart(*q))
1335 validid = false;
1336 while (*q && *q != ':') {
1337 if (!isidchar(*q))
1338 validid = false;
1339 q++;
1341 if (!validid) {
1342 nasm_error(ERR_NONFATAL,
1343 "identifier expected after GLOBAL");
1344 break;
1346 if (*q == ':') {
1347 *q++ = '\0';
1348 special = q;
1349 } else
1350 special = NULL;
1351 declare_as_global(value, special);
1352 } /* pass == 1 */
1353 break;
1354 case D_COMMON: /* [COMMON symbol size:special] */
1356 int64_t size;
1358 if (*value == '$')
1359 value++; /* skip initial $ if present */
1360 p = value;
1361 validid = true;
1362 if (!isidstart(*p))
1363 validid = false;
1364 while (*p && !nasm_isspace(*p)) {
1365 if (!isidchar(*p))
1366 validid = false;
1367 p++;
1369 if (!validid) {
1370 nasm_error(ERR_NONFATAL,
1371 "identifier expected after COMMON");
1372 break;
1374 if (*p) {
1375 p = nasm_zap_spaces_fwd(p);
1376 q = p;
1377 while (*q && *q != ':')
1378 q++;
1379 if (*q == ':') {
1380 *q++ = '\0';
1381 special = q;
1382 } else {
1383 special = NULL;
1385 size = readnum(p, &rn_error);
1386 if (rn_error) {
1387 nasm_error(ERR_NONFATAL,
1388 "invalid size specified"
1389 " in COMMON declaration");
1390 break;
1392 } else {
1393 nasm_error(ERR_NONFATAL,
1394 "no size specified in"
1395 " COMMON declaration");
1396 break;
1399 if (pass0 < 2) {
1400 define_common(value, seg_alloc(), size, special);
1401 } else if (pass0 == 2) {
1402 if (special)
1403 ofmt->symdef(value, 0L, 0L, 3, special);
1405 break;
1407 case D_ABSOLUTE: /* [ABSOLUTE address] */
1408 stdscan_reset();
1409 stdscan_set(value);
1410 tokval.t_type = TOKEN_INVALID;
1411 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1412 nasm_error, NULL);
1413 if (e) {
1414 if (!is_reloc(e))
1415 nasm_error(pass0 ==
1416 1 ? ERR_NONFATAL : ERR_PANIC,
1417 "cannot use non-relocatable expression as "
1418 "ABSOLUTE address");
1419 else {
1420 abs_seg = reloc_seg(e);
1421 abs_offset = reloc_value(e);
1423 } else if (passn == 1)
1424 abs_offset = 0x100; /* don't go near zero in case of / */
1425 else
1426 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1427 "in pass two");
1428 in_abs_seg = true;
1429 location.segment = NO_SEG;
1430 break;
1431 case D_DEBUG: /* [DEBUG] */
1433 char debugid[128];
1434 bool badid, overlong;
1436 p = value;
1437 q = debugid;
1438 badid = overlong = false;
1439 if (!isidstart(*p)) {
1440 badid = true;
1441 } else {
1442 while (*p && !nasm_isspace(*p)) {
1443 if (q >= debugid + sizeof debugid - 1) {
1444 overlong = true;
1445 break;
1447 if (!isidchar(*p))
1448 badid = true;
1449 *q++ = *p++;
1451 *q = 0;
1453 if (badid) {
1454 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1455 "identifier expected after DEBUG");
1456 break;
1458 if (overlong) {
1459 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1460 "DEBUG identifier too long");
1461 break;
1463 p = nasm_skip_spaces(p);
1464 if (pass0 == 2)
1465 dfmt->debug_directive(debugid, p);
1466 break;
1468 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1469 value = nasm_skip_spaces(value);
1470 switch(*value) {
1471 case '-': validid = 0; value++; break;
1472 case '+': validid = 1; value++; break;
1473 case '*': validid = 2; value++; break;
1474 default: validid = 1; break;
1477 for (i = 1; i <= ERR_WARN_MAX; i++)
1478 if (!nasm_stricmp(value, warnings[i].name))
1479 break;
1480 if (i <= ERR_WARN_MAX) {
1481 switch(validid) {
1482 case 0:
1483 warning_on[i] = false;
1484 break;
1485 case 1:
1486 warning_on[i] = true;
1487 break;
1488 case 2:
1489 warning_on[i] = warning_on_global[i];
1490 break;
1493 else
1494 nasm_error(ERR_NONFATAL,
1495 "invalid warning id in WARNING directive");
1496 break;
1497 case D_CPU: /* [CPU] */
1498 cpu = get_cpu(value);
1499 break;
1500 case D_LIST: /* [LIST {+|-}] */
1501 value = nasm_skip_spaces(value);
1502 if (*value == '+') {
1503 user_nolist = 0;
1504 } else {
1505 if (*value == '-') {
1506 user_nolist = 1;
1507 } else {
1508 err = 1;
1511 break;
1512 case D_DEFAULT: /* [DEFAULT] */
1513 stdscan_reset();
1514 stdscan_set(value);
1515 tokval.t_type = TOKEN_INVALID;
1516 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1517 switch ((int)tokval.t_integer) {
1518 case S_REL:
1519 globalrel = 1;
1520 break;
1521 case S_ABS:
1522 globalrel = 0;
1523 break;
1524 default:
1525 err = 1;
1526 break;
1528 } else {
1529 err = 1;
1531 break;
1532 case D_FLOAT:
1533 if (float_option(value)) {
1534 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1535 "unknown 'float' directive: %s",
1536 value);
1538 break;
1539 default:
1540 if (ofmt->directive(d, value, pass2))
1541 break;
1542 /* else fall through */
1543 case D_unknown:
1544 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1545 "unrecognised directive [%s]",
1546 directive);
1547 break;
1549 if (err) {
1550 nasm_error(ERR_NONFATAL,
1551 "invalid parameter to [%s] directive",
1552 directive);
1554 } else { /* it isn't a directive */
1555 parse_line(pass1, line, &output_ins, def_label);
1557 if (optimizing > 0) {
1558 if (forwref != NULL && globallineno == forwref->lineno) {
1559 output_ins.forw_ref = true;
1560 do {
1561 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1562 forwref = saa_rstruct(forwrefs);
1563 } while (forwref != NULL
1564 && forwref->lineno == globallineno);
1565 } else
1566 output_ins.forw_ref = false;
1568 if (output_ins.forw_ref) {
1569 if (passn == 1) {
1570 for (i = 0; i < output_ins.operands; i++) {
1571 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1572 struct forwrefinfo *fwinf =
1573 (struct forwrefinfo *)
1574 saa_wstruct(forwrefs);
1575 fwinf->lineno = globallineno;
1576 fwinf->operand = i;
1583 /* forw_ref */
1584 if (output_ins.opcode == I_EQU) {
1585 if (pass1 == 1) {
1587 * Special `..' EQUs get processed in pass two,
1588 * except `..@' macro-processor EQUs which are done
1589 * in the normal place.
1591 if (!output_ins.label)
1592 nasm_error(ERR_NONFATAL,
1593 "EQU not preceded by label");
1595 else if (output_ins.label[0] != '.' ||
1596 output_ins.label[1] != '.' ||
1597 output_ins.label[2] == '@') {
1598 if (output_ins.operands == 1 &&
1599 (output_ins.oprs[0].type & IMMEDIATE) &&
1600 output_ins.oprs[0].wrt == NO_SEG) {
1601 bool isext = !!(output_ins.oprs[0].opflags
1602 & OPFLAG_EXTERN);
1603 def_label(output_ins.label,
1604 output_ins.oprs[0].segment,
1605 output_ins.oprs[0].offset, NULL,
1606 false, isext);
1607 } else if (output_ins.operands == 2
1608 && (output_ins.oprs[0].type & IMMEDIATE)
1609 && (output_ins.oprs[0].type & COLON)
1610 && output_ins.oprs[0].segment == NO_SEG
1611 && output_ins.oprs[0].wrt == NO_SEG
1612 && (output_ins.oprs[1].type & IMMEDIATE)
1613 && output_ins.oprs[1].segment == NO_SEG
1614 && output_ins.oprs[1].wrt == NO_SEG) {
1615 def_label(output_ins.label,
1616 output_ins.oprs[0].offset | SEG_ABS,
1617 output_ins.oprs[1].offset,
1618 NULL, false, false);
1619 } else
1620 nasm_error(ERR_NONFATAL,
1621 "bad syntax for EQU");
1623 } else {
1625 * Special `..' EQUs get processed here, except
1626 * `..@' macro processor EQUs which are done above.
1628 if (output_ins.label[0] == '.' &&
1629 output_ins.label[1] == '.' &&
1630 output_ins.label[2] != '@') {
1631 if (output_ins.operands == 1 &&
1632 (output_ins.oprs[0].type & IMMEDIATE)) {
1633 define_label(output_ins.label,
1634 output_ins.oprs[0].segment,
1635 output_ins.oprs[0].offset,
1636 NULL, false, false);
1637 } else if (output_ins.operands == 2
1638 && (output_ins.oprs[0].type & IMMEDIATE)
1639 && (output_ins.oprs[0].type & COLON)
1640 && output_ins.oprs[0].segment == NO_SEG
1641 && (output_ins.oprs[1].type & IMMEDIATE)
1642 && output_ins.oprs[1].segment == NO_SEG) {
1643 define_label(output_ins.label,
1644 output_ins.oprs[0].offset | SEG_ABS,
1645 output_ins.oprs[1].offset,
1646 NULL, false, false);
1647 } else
1648 nasm_error(ERR_NONFATAL,
1649 "bad syntax for EQU");
1652 } else { /* instruction isn't an EQU */
1654 if (pass1 == 1) {
1656 int64_t l = insn_size(location.segment, offs, sb, cpu,
1657 &output_ins, nasm_error);
1659 /* if (using_debug_info) && output_ins.opcode != -1) */
1660 if (using_debug_info)
1661 { /* fbk 03/25/01 */
1662 /* this is done here so we can do debug type info */
1663 int32_t typeinfo =
1664 TYS_ELEMENTS(output_ins.operands);
1665 switch (output_ins.opcode) {
1666 case I_RESB:
1667 typeinfo =
1668 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1669 break;
1670 case I_RESW:
1671 typeinfo =
1672 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1673 break;
1674 case I_RESD:
1675 typeinfo =
1676 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1677 break;
1678 case I_RESQ:
1679 typeinfo =
1680 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1681 break;
1682 case I_REST:
1683 typeinfo =
1684 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1685 break;
1686 case I_RESO:
1687 typeinfo =
1688 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1689 break;
1690 case I_RESY:
1691 typeinfo =
1692 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1693 break;
1694 case I_DB:
1695 typeinfo |= TY_BYTE;
1696 break;
1697 case I_DW:
1698 typeinfo |= TY_WORD;
1699 break;
1700 case I_DD:
1701 if (output_ins.eops_float)
1702 typeinfo |= TY_FLOAT;
1703 else
1704 typeinfo |= TY_DWORD;
1705 break;
1706 case I_DQ:
1707 typeinfo |= TY_QWORD;
1708 break;
1709 case I_DT:
1710 typeinfo |= TY_TBYTE;
1711 break;
1712 case I_DO:
1713 typeinfo |= TY_OWORD;
1714 break;
1715 case I_DY:
1716 typeinfo |= TY_YWORD;
1717 break;
1718 default:
1719 typeinfo = TY_LABEL;
1723 dfmt->debug_typevalue(typeinfo);
1725 if (l != -1) {
1726 offs += l;
1727 SET_CURR_OFFS(offs);
1730 * else l == -1 => invalid instruction, which will be
1731 * flagged as an error on pass 2
1734 } else {
1735 offs += assemble(location.segment, offs, sb, cpu,
1736 &output_ins, ofmt, nasm_error,
1737 &nasmlist);
1738 SET_CURR_OFFS(offs);
1741 } /* not an EQU */
1742 cleanup_insn(&output_ins);
1744 nasm_free(line);
1745 location.offset = offs = GET_CURR_OFFS;
1746 } /* end while (line = preproc->getline... */
1748 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1749 nasm_error(ERR_NONFATAL,
1750 "phase error detected at end of assembly.");
1752 if (pass1 == 1)
1753 preproc->cleanup(1);
1755 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1756 pass0++;
1757 } else if (global_offset_changed &&
1758 global_offset_changed < prev_offset_changed) {
1759 prev_offset_changed = global_offset_changed;
1760 stall_count = 0;
1761 } else {
1762 stall_count++;
1765 if (terminate_after_phase)
1766 break;
1768 if ((stall_count > 997) || (passn >= pass_max)) {
1769 /* We get here if the labels don't converge
1770 * Example: FOO equ FOO + 1
1772 nasm_error(ERR_NONFATAL,
1773 "Can't find valid values for all labels "
1774 "after %d passes, giving up.", passn);
1775 nasm_error(ERR_NONFATAL,
1776 "Possible causes: recursive EQUs, macro abuse.");
1777 break;
1781 preproc->cleanup(0);
1782 nasmlist.cleanup();
1783 if (!terminate_after_phase && opt_verbose_info) {
1784 /* -On and -Ov switches */
1785 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1789 static enum directives getkw(char **directive, char **value)
1791 char *p, *q, *buf;
1793 buf = nasm_skip_spaces(*directive);
1795 /* it should be enclosed in [ ] */
1796 if (*buf != '[')
1797 return D_none;
1798 q = strchr(buf, ']');
1799 if (!q)
1800 return D_none;
1802 /* stip off the comments */
1803 p = strchr(buf, ';');
1804 if (p) {
1805 if (p < q) /* ouch! somwhere inside */
1806 return D_none;
1807 *p = '\0';
1810 /* no brace, no trailing spaces */
1811 *q = '\0';
1812 nasm_zap_spaces_rev(--q);
1814 /* directive */
1815 p = nasm_skip_spaces(++buf);
1816 q = nasm_skip_word(p);
1817 if (!q)
1818 return D_none; /* sigh... no value there */
1819 *q = '\0';
1820 *directive = p;
1822 /* and value finally */
1823 p = nasm_skip_spaces(++q);
1824 *value = p;
1826 return find_directive(*directive);
1830 * gnu style error reporting
1831 * This function prints an error message to error_file in the
1832 * style used by GNU. An example would be:
1833 * file.asm:50: error: blah blah blah
1834 * where file.asm is the name of the file, 50 is the line number on
1835 * which the error occurs (or is detected) and "error:" is one of
1836 * the possible optional diagnostics -- it can be "error" or "warning"
1837 * or something else. Finally the line terminates with the actual
1838 * error message.
1840 * @param severity the severity of the warning or error
1841 * @param fmt the printf style format string
1843 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1845 char *currentfile = NULL;
1846 int32_t lineno = 0;
1848 if (is_suppressed_warning(severity))
1849 return;
1851 if (!(severity & ERR_NOFILE))
1852 src_get(&lineno, &currentfile);
1854 if (currentfile) {
1855 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1856 nasm_free(currentfile);
1857 } else {
1858 fputs("nasm: ", error_file);
1861 nasm_verror_common(severity, fmt, ap);
1865 * MS style error reporting
1866 * This function prints an error message to error_file in the
1867 * style used by Visual C and some other Microsoft tools. An example
1868 * would be:
1869 * file.asm(50) : error: blah blah blah
1870 * where file.asm is the name of the file, 50 is the line number on
1871 * which the error occurs (or is detected) and "error:" is one of
1872 * the possible optional diagnostics -- it can be "error" or "warning"
1873 * or something else. Finally the line terminates with the actual
1874 * error message.
1876 * @param severity the severity of the warning or error
1877 * @param fmt the printf style format string
1879 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1881 char *currentfile = NULL;
1882 int32_t lineno = 0;
1884 if (is_suppressed_warning(severity))
1885 return;
1887 if (!(severity & ERR_NOFILE))
1888 src_get(&lineno, &currentfile);
1890 if (currentfile) {
1891 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1892 nasm_free(currentfile);
1893 } else {
1894 fputs("nasm: ", error_file);
1897 nasm_verror_common(severity, fmt, ap);
1901 * check for supressed warning
1902 * checks for suppressed warning or pass one only warning and we're
1903 * not in pass 1
1905 * @param severity the severity of the warning or error
1906 * @return true if we should abort error/warning printing
1908 static bool is_suppressed_warning(int severity)
1911 * See if it's a suppressed warning.
1913 return (severity & ERR_MASK) == ERR_WARNING &&
1914 (((severity & ERR_WARN_MASK) != 0 &&
1915 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1916 /* See if it's a pass-one only warning and we're not in pass one. */
1917 ((severity & ERR_PASS1) && pass0 != 1) ||
1918 ((severity & ERR_PASS2) && pass0 != 2));
1922 * common error reporting
1923 * This is the common back end of the error reporting schemes currently
1924 * implemented. It prints the nature of the warning and then the
1925 * specific error message to error_file and may or may not return. It
1926 * doesn't return if the error severity is a "panic" or "debug" type.
1928 * @param severity the severity of the warning or error
1929 * @param fmt the printf style format string
1931 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1933 char msg[1024];
1934 const char *pfx;
1936 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1937 case ERR_WARNING:
1938 pfx = "warning: ";
1939 break;
1940 case ERR_NONFATAL:
1941 pfx = "error: ";
1942 break;
1943 case ERR_FATAL:
1944 pfx = "fatal: ";
1945 break;
1946 case ERR_PANIC:
1947 pfx = "panic: ";
1948 break;
1949 case ERR_DEBUG:
1950 pfx = "debug: ";
1951 break;
1952 default:
1953 pfx = "";
1954 break;
1957 vsnprintf(msg, sizeof msg, fmt, args);
1959 fprintf(error_file, "%s%s\n", pfx, msg);
1961 if (*listname)
1962 nasmlist.error(severity, pfx, msg);
1964 if (severity & ERR_USAGE)
1965 want_usage = true;
1967 switch (severity & ERR_MASK) {
1968 case ERR_DEBUG:
1969 /* no further action, by definition */
1970 break;
1971 case ERR_WARNING:
1972 if (warning_on[0]) /* Treat warnings as errors */
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 #define BUF_DELTA 512
2003 static FILE *no_pp_fp;
2004 static ListGen *no_pp_list;
2005 static int32_t no_pp_lineinc;
2007 static void no_pp_reset(char *file, int pass, ListGen * listgen,
2008 StrList **deplist)
2010 src_set_fname(nasm_strdup(file));
2011 src_set_linnum(0);
2012 no_pp_lineinc = 1;
2013 no_pp_fp = fopen(file, "r");
2014 if (!no_pp_fp)
2015 nasm_error(ERR_FATAL | ERR_NOFILE,
2016 "unable to open input file `%s'", file);
2017 no_pp_list = listgen;
2018 (void)pass; /* placate compilers */
2020 if (deplist) {
2021 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2022 sl->next = NULL;
2023 strcpy(sl->str, file);
2024 *deplist = sl;
2028 static char *no_pp_getline(void)
2030 char *buffer, *p, *q;
2031 int bufsize;
2033 bufsize = BUF_DELTA;
2034 buffer = nasm_malloc(BUF_DELTA);
2035 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2037 while (1) { /* Loop to handle %line */
2039 p = buffer;
2040 while (1) { /* Loop to handle long lines */
2041 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2042 if (!q)
2043 break;
2044 p += strlen(p);
2045 if (p > buffer && p[-1] == '\n')
2046 break;
2047 if (p - buffer > bufsize - 10) {
2048 int offset;
2049 offset = p - buffer;
2050 bufsize += BUF_DELTA;
2051 buffer = nasm_realloc(buffer, bufsize);
2052 p = buffer + offset;
2056 if (!q && p == buffer) {
2057 nasm_free(buffer);
2058 return NULL;
2062 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2063 * them are present at the end of the line.
2065 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2067 if (!nasm_strnicmp(buffer, "%line", 5)) {
2068 int32_t ln;
2069 int li;
2070 char *nm = nasm_malloc(strlen(buffer));
2071 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2072 nasm_free(src_set_fname(nm));
2073 src_set_linnum(ln);
2074 no_pp_lineinc = li;
2075 continue;
2077 nasm_free(nm);
2079 break;
2082 no_pp_list->line(LIST_READ, buffer);
2084 return buffer;
2087 static void no_pp_cleanup(int pass)
2089 (void)pass; /* placate GCC */
2090 if (no_pp_fp) {
2091 fclose(no_pp_fp);
2092 no_pp_fp = NULL;
2096 static uint32_t get_cpu(char *value)
2098 if (!strcmp(value, "8086"))
2099 return IF_8086;
2100 if (!strcmp(value, "186"))
2101 return IF_186;
2102 if (!strcmp(value, "286"))
2103 return IF_286;
2104 if (!strcmp(value, "386"))
2105 return IF_386;
2106 if (!strcmp(value, "486"))
2107 return IF_486;
2108 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2109 return IF_PENT;
2110 if (!strcmp(value, "686") ||
2111 !nasm_stricmp(value, "ppro") ||
2112 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2113 return IF_P6;
2114 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2115 return IF_KATMAI;
2116 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2117 !nasm_stricmp(value, "willamette"))
2118 return IF_WILLAMETTE;
2119 if (!nasm_stricmp(value, "prescott"))
2120 return IF_PRESCOTT;
2121 if (!nasm_stricmp(value, "x64") ||
2122 !nasm_stricmp(value, "x86-64"))
2123 return IF_X86_64;
2124 if (!nasm_stricmp(value, "ia64") ||
2125 !nasm_stricmp(value, "ia-64") ||
2126 !nasm_stricmp(value, "itanium") ||
2127 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2128 return IF_IA64;
2130 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2131 "unknown 'cpu' type");
2133 return IF_PLEVEL; /* the maximum level */
2136 static int get_bits(char *value)
2138 int i;
2140 if ((i = atoi(value)) == 16)
2141 return i; /* set for a 16-bit segment */
2142 else if (i == 32) {
2143 if (cpu < IF_386) {
2144 nasm_error(ERR_NONFATAL,
2145 "cannot specify 32-bit segment on processor below a 386");
2146 i = 16;
2148 } else if (i == 64) {
2149 if (cpu < IF_X86_64) {
2150 nasm_error(ERR_NONFATAL,
2151 "cannot specify 64-bit segment on processor below an x86-64");
2152 i = 16;
2154 if (i != maxbits) {
2155 nasm_error(ERR_NONFATAL,
2156 "%s output format does not support 64-bit code",
2157 ofmt->shortname);
2158 i = 16;
2160 } else {
2161 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2162 "`%s' is not a valid segment size; must be 16, 32 or 64",
2163 value);
2164 i = 16;
2166 return i;