BR3064459: Missing %endif doesn't always cause error
[nasm/sigaren-mirror.git] / nasm.c
blob7a63afb8e0c98669fd1fea62fea828a241ad9a27
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2010 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 const struct dfmt *dfmt;
103 static FILE *error_file; /* Where to write error messages */
105 FILE *ofile = NULL;
106 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
107 static int sb, cmd_sb = 16; /* by default */
108 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
109 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
110 int64_t global_offset_changed; /* referenced in labels.c */
111 int64_t prev_offset_changed;
112 int32_t stall_count;
114 static struct location location;
115 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
116 int32_t abs_seg; /* ABSOLUTE segment basis */
117 int32_t abs_offset; /* ABSOLUTE offset */
119 static struct RAA *offsets;
121 static struct SAA *forwrefs; /* keep track of forward references */
122 static const struct forwrefinfo *forwref;
124 static Preproc *preproc;
125 enum op_type {
126 op_normal, /* Preprocess and assemble */
127 op_preprocess, /* Preprocess only */
128 op_depend, /* Generate dependencies */
130 static enum op_type operating_mode;
131 /* Dependency flags */
132 static bool depend_emit_phony = false;
133 static bool depend_missing_ok = false;
134 static const char *depend_target = NULL;
135 static const char *depend_file = NULL;
138 * Which of the suppressible warnings are suppressed. Entry zero
139 * isn't an actual warning, but it used for -w+error/-Werror.
142 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
143 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
145 static const struct warning {
146 const char *name;
147 const char *help;
148 bool enabled;
149 } warnings[ERR_WARN_MAX+1] = {
150 {"error", "treat warnings as errors", false},
151 {"macro-params", "macro calls with wrong parameter count", true},
152 {"macro-selfref", "cyclic macro references", false},
153 {"macro-defaults", "macros with more default than optional parameters", true},
154 {"orphan-labels", "labels alone on lines without trailing `:'", true},
155 {"number-overflow", "numeric constant does not fit", true},
156 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
157 {"float-overflow", "floating point overflow", true},
158 {"float-denorm", "floating point denormal", false},
159 {"float-underflow", "floating point underflow", false},
160 {"float-toolong", "too many digits in floating-point number", true},
161 {"user", "%warning directives", true},
165 * This is a null preprocessor which just copies lines from input
166 * to output. It's used when someone explicitly requests that NASM
167 * not preprocess their source file.
170 static void no_pp_reset(char *, int, ListGen *, StrList **);
171 static char *no_pp_getline(void);
172 static void no_pp_cleanup(int);
173 static Preproc no_pp = {
174 no_pp_reset,
175 no_pp_getline,
176 no_pp_cleanup
180 * get/set current offset...
182 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
183 raa_read(offsets,location.segment))
184 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
185 (void)(offsets=raa_write(offsets,location.segment,(x))))
187 static bool want_usage;
188 static bool terminate_after_phase;
189 int user_nolist = 0; /* fbk 9/2/00 */
191 static void nasm_fputs(const char *line, FILE * outfile)
193 if (outfile) {
194 fputs(line, outfile);
195 putc('\n', outfile);
196 } else
197 puts(line);
200 /* Convert a struct tm to a POSIX-style time constant */
201 static int64_t posix_mktime(struct tm *tm)
203 int64_t t;
204 int64_t y = tm->tm_year;
206 /* See IEEE 1003.1:2004, section 4.14 */
208 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
209 t += tm->tm_yday;
210 t *= 24;
211 t += tm->tm_hour;
212 t *= 60;
213 t += tm->tm_min;
214 t *= 60;
215 t += tm->tm_sec;
217 return t;
220 static void define_macros_early(void)
222 char temp[128];
223 struct tm lt, *lt_p, gm, *gm_p;
224 int64_t posix_time;
226 lt_p = localtime(&official_compile_time);
227 if (lt_p) {
228 lt = *lt_p;
230 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
231 pp_pre_define(temp);
232 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
233 pp_pre_define(temp);
234 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
235 pp_pre_define(temp);
236 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
237 pp_pre_define(temp);
240 gm_p = gmtime(&official_compile_time);
241 if (gm_p) {
242 gm = *gm_p;
244 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
245 pp_pre_define(temp);
246 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
247 pp_pre_define(temp);
248 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
249 pp_pre_define(temp);
250 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
251 pp_pre_define(temp);
254 if (gm_p)
255 posix_time = posix_mktime(&gm);
256 else if (lt_p)
257 posix_time = posix_mktime(&lt);
258 else
259 posix_time = 0;
261 if (posix_time) {
262 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
263 pp_pre_define(temp);
267 static void define_macros_late(void)
269 char temp[128];
271 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
272 ofmt->shortname);
273 pp_pre_define(temp);
276 static void emit_dependencies(StrList *list)
278 FILE *deps;
279 int linepos, len;
280 StrList *l, *nl;
282 if (depend_file && strcmp(depend_file, "-")) {
283 deps = fopen(depend_file, "w");
284 if (!deps) {
285 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
286 "unable to write dependency file `%s'", depend_file);
287 return;
289 } else {
290 deps = stdout;
293 linepos = fprintf(deps, "%s:", depend_target);
294 list_for_each(l, list) {
295 len = strlen(l->str);
296 if (linepos + len > 62) {
297 fprintf(deps, " \\\n ");
298 linepos = 1;
300 fprintf(deps, " %s", l->str);
301 linepos += len+1;
303 fprintf(deps, "\n\n");
305 list_for_each_safe(l, nl, list) {
306 if (depend_emit_phony)
307 fprintf(deps, "%s:\n\n", l->str);
308 nasm_free(l);
311 if (deps != stdout)
312 fclose(deps);
315 int main(int argc, char **argv)
317 StrList *depend_list = NULL, **depend_ptr;
319 time(&official_compile_time);
321 pass0 = 0;
322 want_usage = terminate_after_phase = false;
323 nasm_set_verror(nasm_verror_gnu);
325 error_file = stderr;
327 tolower_init();
329 nasm_init_malloc_error();
330 offsets = raa_init();
331 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
333 preproc = &nasmpp;
334 operating_mode = op_normal;
336 seg_init();
338 /* Define some macros dependent on the runtime, but not
339 on the command line. */
340 define_macros_early();
342 parse_cmdline(argc, argv);
344 if (terminate_after_phase) {
345 if (want_usage)
346 usage();
347 return 1;
350 /* If debugging info is disabled, suppress any debug calls */
351 if (!using_debug_info)
352 ofmt->current_dfmt = &null_debug_form;
354 if (ofmt->stdmac)
355 pp_extra_stdmac(ofmt->stdmac);
356 parser_global_info(&location);
357 eval_global_info(ofmt, lookup_label, &location);
359 /* define some macros dependent of command-line */
360 define_macros_late();
362 depend_ptr = (depend_file || (operating_mode == op_depend))
363 ? &depend_list : NULL;
364 if (!depend_target)
365 depend_target = outname;
367 switch (operating_mode) {
368 case op_depend:
370 char *line;
372 if (depend_missing_ok)
373 pp_include_path(NULL); /* "assume generated" */
375 preproc->reset(inname, 0, &nasmlist, depend_ptr);
376 if (outname[0] == '\0')
377 ofmt->filename(inname, outname);
378 ofile = NULL;
379 while ((line = preproc->getline()))
380 nasm_free(line);
381 preproc->cleanup(0);
383 break;
385 case op_preprocess:
387 char *line;
388 char *file_name = NULL;
389 int32_t prior_linnum = 0;
390 int lineinc = 0;
392 if (*outname) {
393 ofile = fopen(outname, "w");
394 if (!ofile)
395 nasm_error(ERR_FATAL | ERR_NOFILE,
396 "unable to open output file `%s'",
397 outname);
398 } else
399 ofile = NULL;
401 location.known = false;
403 /* pass = 1; */
404 preproc->reset(inname, 3, &nasmlist, depend_ptr);
406 while ((line = preproc->getline())) {
408 * We generate %line directives if needed for later programs
410 int32_t linnum = prior_linnum += lineinc;
411 int altline = src_get(&linnum, &file_name);
412 if (altline) {
413 if (altline == 1 && lineinc == 1)
414 nasm_fputs("", ofile);
415 else {
416 lineinc = (altline != -1 || lineinc != 1);
417 fprintf(ofile ? ofile : stdout,
418 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
419 file_name);
421 prior_linnum = linnum;
423 nasm_fputs(line, ofile);
424 nasm_free(line);
426 nasm_free(file_name);
427 preproc->cleanup(0);
428 if (ofile)
429 fclose(ofile);
430 if (ofile && terminate_after_phase)
431 remove(outname);
432 ofile = NULL;
434 break;
436 case op_normal:
439 * We must call ofmt->filename _anyway_, even if the user
440 * has specified their own output file, because some
441 * formats (eg OBJ and COFF) use ofmt->filename to find out
442 * the name of the input file and then put that inside the
443 * file.
445 ofmt->filename(inname, outname);
447 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
448 if (!ofile) {
449 nasm_error(ERR_FATAL | ERR_NOFILE,
450 "unable to open output file `%s'", outname);
454 * We must call init_labels() before ofmt->init() since
455 * some object formats will want to define labels in their
456 * init routines. (eg OS/2 defines the FLAT group)
458 init_labels();
460 ofmt->init();
461 dfmt = ofmt->current_dfmt;
462 dfmt->init();
464 assemble_file(inname, depend_ptr);
466 if (!terminate_after_phase) {
467 ofmt->cleanup(using_debug_info);
468 cleanup_labels();
469 fflush(ofile);
470 if (ferror(ofile)) {
471 nasm_error(ERR_NONFATAL|ERR_NOFILE,
472 "write error on output file `%s'", outname);
476 if (ofile) {
477 fclose(ofile);
478 if (terminate_after_phase)
479 remove(outname);
480 ofile = NULL;
483 break;
486 if (depend_list && !terminate_after_phase)
487 emit_dependencies(depend_list);
489 if (want_usage)
490 usage();
492 raa_free(offsets);
493 saa_free(forwrefs);
494 eval_cleanup();
495 stdscan_cleanup();
497 return terminate_after_phase;
501 * Get a parameter for a command line option.
502 * First arg must be in the form of e.g. -f...
504 static char *get_param(char *p, char *q, bool *advance)
506 *advance = false;
507 if (p[2]) /* the parameter's in the option */
508 return nasm_skip_spaces(p + 2);
509 if (q && q[0]) {
510 *advance = true;
511 return q;
513 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
514 "option `-%c' requires an argument", p[1]);
515 return NULL;
519 * Copy a filename
521 static void copy_filename(char *dst, const char *src)
523 size_t len = strlen(src);
525 if (len >= (size_t)FILENAME_MAX) {
526 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
527 return;
529 strncpy(dst, src, FILENAME_MAX);
533 * Convert a string to Make-safe form
535 static char *quote_for_make(const char *str)
537 const char *p;
538 char *os, *q;
540 size_t n = 1; /* Terminating zero */
541 size_t nbs = 0;
543 if (!str)
544 return NULL;
546 for (p = str; *p; p++) {
547 switch (*p) {
548 case ' ':
549 case '\t':
550 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
551 n += nbs + 2;
552 nbs = 0;
553 break;
554 case '$':
555 case '#':
556 nbs = 0;
557 n += 2;
558 break;
559 case '\\':
560 nbs++;
561 n++;
562 break;
563 default:
564 nbs = 0;
565 n++;
566 break;
570 /* Convert N backslashes at the end of filename to 2N backslashes */
571 if (nbs)
572 n += nbs;
574 os = q = nasm_malloc(n);
576 nbs = 0;
577 for (p = str; *p; p++) {
578 switch (*p) {
579 case ' ':
580 case '\t':
581 while (nbs--)
582 *q++ = '\\';
583 *q++ = '\\';
584 *q++ = *p;
585 break;
586 case '$':
587 *q++ = *p;
588 *q++ = *p;
589 nbs = 0;
590 break;
591 case '#':
592 *q++ = '\\';
593 *q++ = *p;
594 nbs = 0;
595 break;
596 case '\\':
597 *q++ = *p;
598 nbs++;
599 break;
600 default:
601 *q++ = *p;
602 nbs = 0;
603 break;
606 while (nbs--)
607 *q++ = '\\';
609 *q = '\0';
611 return os;
614 struct textargs {
615 const char *label;
616 int value;
619 #define OPT_PREFIX 0
620 #define OPT_POSTFIX 1
621 struct textargs textopts[] = {
622 {"prefix", OPT_PREFIX},
623 {"postfix", OPT_POSTFIX},
624 {NULL, 0}
627 static bool stopoptions = false;
628 static bool process_arg(char *p, char *q)
630 char *param;
631 int i;
632 bool advance = false;
633 bool do_warn;
635 if (!p || !p[0])
636 return false;
638 if (p[0] == '-' && !stopoptions) {
639 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
640 /* These parameters take values */
641 if (!(param = get_param(p, q, &advance)))
642 return advance;
645 switch (p[1]) {
646 case 's':
647 error_file = stdout;
648 break;
650 case 'o': /* output file */
651 copy_filename(outname, param);
652 break;
654 case 'f': /* output format */
655 ofmt = ofmt_find(param);
656 if (!ofmt) {
657 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
658 "unrecognised output format `%s' - "
659 "use -hf for a list", param);
661 break;
663 case 'O': /* Optimization level */
665 int opt;
667 if (!*param) {
668 /* Naked -O == -Ox */
669 optimizing = MAX_OPTIMIZE;
670 } else {
671 while (*param) {
672 switch (*param) {
673 case '0': case '1': case '2': case '3': case '4':
674 case '5': case '6': case '7': case '8': case '9':
675 opt = strtoul(param, &param, 10);
677 /* -O0 -> optimizing == -1, 0.98 behaviour */
678 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
679 if (opt < 2)
680 optimizing = opt - 1;
681 else
682 optimizing = opt;
683 break;
685 case 'v':
686 case '+':
687 param++;
688 opt_verbose_info = true;
689 break;
691 case 'x':
692 param++;
693 optimizing = MAX_OPTIMIZE;
694 break;
696 default:
697 nasm_error(ERR_FATAL,
698 "unknown optimization option -O%c\n",
699 *param);
700 break;
703 if (optimizing > MAX_OPTIMIZE)
704 optimizing = MAX_OPTIMIZE;
706 break;
709 case 'p': /* pre-include */
710 case 'P':
711 pp_pre_include(param);
712 break;
714 case 'd': /* pre-define */
715 case 'D':
716 pp_pre_define(param);
717 break;
719 case 'u': /* un-define */
720 case 'U':
721 pp_pre_undefine(param);
722 break;
724 case 'i': /* include search path */
725 case 'I':
726 pp_include_path(param);
727 break;
729 case 'l': /* listing file */
730 copy_filename(listname, param);
731 break;
733 case 'Z': /* error messages file */
734 copy_filename(errname, param);
735 break;
737 case 'F': /* specify debug format */
738 ofmt->current_dfmt = dfmt_find(ofmt, param);
739 if (!ofmt->current_dfmt) {
740 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
741 "unrecognized debug format `%s' for"
742 " output format `%s'",
743 param, ofmt->shortname);
745 using_debug_info = true;
746 break;
748 case 'X': /* specify error reporting format */
749 if (nasm_stricmp("vc", param) == 0)
750 nasm_set_verror(nasm_verror_vc);
751 else if (nasm_stricmp("gnu", param) == 0)
752 nasm_set_verror(nasm_verror_gnu);
753 else
754 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
755 "unrecognized error reporting format `%s'",
756 param);
757 break;
759 case 'g':
760 using_debug_info = true;
761 break;
763 case 'h':
764 printf
765 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
766 "[-l listfile]\n"
767 " [options...] [--] filename\n"
768 " or nasm -v for version info\n\n"
769 " -t assemble in SciTech TASM compatible mode\n"
770 " -g generate debug information in selected format\n");
771 printf
772 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
773 " -a don't preprocess (assemble only)\n"
774 " -M generate Makefile dependencies on stdout\n"
775 " -MG d:o, missing files assumed generated\n"
776 " -MF <file> set Makefile dependency file\n"
777 " -MD <file> assemble and generate dependencies\n"
778 " -MT <file> dependency target name\n"
779 " -MQ <file> dependency target name (quoted)\n"
780 " -MP emit phony target\n\n"
781 " -Z<file> redirect error messages to file\n"
782 " -s redirect error messages to stdout\n\n"
783 " -F format select a debugging format\n\n"
784 " -I<path> adds a pathname to the include file path\n");
785 printf
786 (" -O<digit> optimize branch offsets\n"
787 " -O0: No optimization (default)\n"
788 " -O1: Minimal optimization\n"
789 " -Ox: Multipass optimization (recommended)\n\n"
790 " -P<file> pre-includes a file\n"
791 " -D<macro>[=<value>] pre-defines a macro\n"
792 " -U<macro> undefines a macro\n"
793 " -X<format> specifies error reporting format (gnu or vc)\n"
794 " -w+foo enables warning foo (equiv. -Wfoo)\n"
795 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
796 "--prefix,--postfix\n"
797 " this options prepend or append the given argument to all\n"
798 " extern and global variables\n\n"
799 "Warnings:\n");
800 for (i = 0; i <= ERR_WARN_MAX; i++)
801 printf(" %-23s %s (default %s)\n",
802 warnings[i].name, warnings[i].help,
803 warnings[i].enabled ? "on" : "off");
804 printf
805 ("\nresponse files should contain command line parameters"
806 ", one per line.\n");
807 if (p[2] == 'f') {
808 printf("\nvalid output formats for -f are"
809 " (`*' denotes default):\n");
810 ofmt_list(ofmt, stdout);
811 } else {
812 printf("\nFor a list of valid output formats, use -hf.\n");
813 printf("For a list of debug formats, use -f <form> -y.\n");
815 exit(0); /* never need usage message here */
816 break;
818 case 'y':
819 printf("\nvalid debug formats for '%s' output format are"
820 " ('*' denotes default):\n", ofmt->shortname);
821 dfmt_list(ofmt, stdout);
822 exit(0);
823 break;
825 case 't':
826 tasm_compatible_mode = true;
827 break;
829 case 'v':
830 printf("NASM version %s compiled on %s%s\n",
831 nasm_version, nasm_date, nasm_compile_options);
832 exit(0); /* never need usage message here */
833 break;
835 case 'e': /* preprocess only */
836 case 'E':
837 operating_mode = op_preprocess;
838 break;
840 case 'a': /* assemble only - don't preprocess */
841 preproc = &no_pp;
842 break;
844 case 'W':
845 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
846 do_warn = false;
847 param += 3;
848 } else {
849 do_warn = true;
851 goto set_warning;
853 case 'w':
854 if (param[0] != '+' && param[0] != '-') {
855 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
856 "invalid option to `-w'");
857 break;
859 do_warn = (param[0] == '+');
860 param++;
862 set_warning:
863 for (i = 0; i <= ERR_WARN_MAX; i++)
864 if (!nasm_stricmp(param, warnings[i].name))
865 break;
866 if (i <= ERR_WARN_MAX)
867 warning_on_global[i] = do_warn;
868 else if (!nasm_stricmp(param, "all"))
869 for (i = 1; i <= ERR_WARN_MAX; i++)
870 warning_on_global[i] = do_warn;
871 else if (!nasm_stricmp(param, "none"))
872 for (i = 1; i <= ERR_WARN_MAX; i++)
873 warning_on_global[i] = !do_warn;
874 else
875 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
876 "invalid warning `%s'", param);
877 break;
879 case 'M':
880 switch (p[2]) {
881 case 0:
882 operating_mode = op_depend;
883 break;
884 case 'G':
885 operating_mode = op_depend;
886 depend_missing_ok = true;
887 break;
888 case 'P':
889 depend_emit_phony = true;
890 break;
891 case 'D':
892 depend_file = q;
893 advance = true;
894 break;
895 case 'T':
896 depend_target = q;
897 advance = true;
898 break;
899 case 'Q':
900 depend_target = quote_for_make(q);
901 advance = true;
902 break;
903 default:
904 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
905 "unknown dependency option `-M%c'", p[2]);
906 break;
908 if (advance && (!q || !q[0])) {
909 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
910 "option `-M%c' requires a parameter", p[2]);
911 break;
913 break;
915 case '-':
917 int s;
919 if (p[2] == 0) { /* -- => stop processing options */
920 stopoptions = 1;
921 break;
923 for (s = 0; textopts[s].label; s++) {
924 if (!nasm_stricmp(p + 2, textopts[s].label)) {
925 break;
929 switch (s) {
931 case OPT_PREFIX:
932 case OPT_POSTFIX:
934 if (!q) {
935 nasm_error(ERR_NONFATAL | ERR_NOFILE |
936 ERR_USAGE,
937 "option `--%s' requires an argument",
938 p + 2);
939 break;
940 } else {
941 advance = 1, param = q;
944 if (s == OPT_PREFIX) {
945 strncpy(lprefix, param, PREFIX_MAX - 1);
946 lprefix[PREFIX_MAX - 1] = 0;
947 break;
949 if (s == OPT_POSTFIX) {
950 strncpy(lpostfix, param, POSTFIX_MAX - 1);
951 lpostfix[POSTFIX_MAX - 1] = 0;
952 break;
954 break;
956 default:
958 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
959 "unrecognised option `--%s'", p + 2);
960 break;
963 break;
966 default:
967 if (!ofmt->setinfo(GI_SWITCH, &p))
968 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
969 "unrecognised option `-%c'", p[1]);
970 break;
972 } else {
973 if (*inname) {
974 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
975 "more than one input file specified");
976 } else {
977 copy_filename(inname, p);
981 return advance;
984 #define ARG_BUF_DELTA 128
986 static void process_respfile(FILE * rfile)
988 char *buffer, *p, *q, *prevarg;
989 int bufsize, prevargsize;
991 bufsize = prevargsize = ARG_BUF_DELTA;
992 buffer = nasm_malloc(ARG_BUF_DELTA);
993 prevarg = nasm_malloc(ARG_BUF_DELTA);
994 prevarg[0] = '\0';
996 while (1) { /* Loop to handle all lines in file */
997 p = buffer;
998 while (1) { /* Loop to handle long lines */
999 q = fgets(p, bufsize - (p - buffer), rfile);
1000 if (!q)
1001 break;
1002 p += strlen(p);
1003 if (p > buffer && p[-1] == '\n')
1004 break;
1005 if (p - buffer > bufsize - 10) {
1006 int offset;
1007 offset = p - buffer;
1008 bufsize += ARG_BUF_DELTA;
1009 buffer = nasm_realloc(buffer, bufsize);
1010 p = buffer + offset;
1014 if (!q && p == buffer) {
1015 if (prevarg[0])
1016 process_arg(prevarg, NULL);
1017 nasm_free(buffer);
1018 nasm_free(prevarg);
1019 return;
1023 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1024 * them are present at the end of the line.
1026 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1028 while (p > buffer && nasm_isspace(p[-1]))
1029 *--p = '\0';
1031 p = nasm_skip_spaces(buffer);
1033 if (process_arg(prevarg, p))
1034 *p = '\0';
1036 if ((int) strlen(p) > prevargsize - 10) {
1037 prevargsize += ARG_BUF_DELTA;
1038 prevarg = nasm_realloc(prevarg, prevargsize);
1040 strncpy(prevarg, p, prevargsize);
1044 /* Function to process args from a string of args, rather than the
1045 * argv array. Used by the environment variable and response file
1046 * processing.
1048 static void process_args(char *args)
1050 char *p, *q, *arg, *prevarg;
1051 char separator = ' ';
1053 p = args;
1054 if (*p && *p != '-')
1055 separator = *p++;
1056 arg = NULL;
1057 while (*p) {
1058 q = p;
1059 while (*p && *p != separator)
1060 p++;
1061 while (*p == separator)
1062 *p++ = '\0';
1063 prevarg = arg;
1064 arg = q;
1065 if (process_arg(prevarg, arg))
1066 arg = NULL;
1068 if (arg)
1069 process_arg(arg, NULL);
1072 static void process_response_file(const char *file)
1074 char str[2048];
1075 FILE *f = fopen(file, "r");
1076 if (!f) {
1077 perror(file);
1078 exit(-1);
1080 while (fgets(str, sizeof str, f)) {
1081 process_args(str);
1083 fclose(f);
1086 static void parse_cmdline(int argc, char **argv)
1088 FILE *rfile;
1089 char *envreal, *envcopy = NULL, *p, *arg;
1090 int i;
1092 *inname = *outname = *listname = *errname = '\0';
1093 for (i = 0; i <= ERR_WARN_MAX; i++)
1094 warning_on_global[i] = warnings[i].enabled;
1097 * First, process the NASMENV environment variable.
1099 envreal = getenv("NASMENV");
1100 arg = NULL;
1101 if (envreal) {
1102 envcopy = nasm_strdup(envreal);
1103 process_args(envcopy);
1104 nasm_free(envcopy);
1108 * Now process the actual command line.
1110 while (--argc) {
1111 bool advance;
1112 argv++;
1113 if (argv[0][0] == '@') {
1114 /* We have a response file, so process this as a set of
1115 * arguments like the environment variable. This allows us
1116 * to have multiple arguments on a single line, which is
1117 * different to the -@resp file processing below for regular
1118 * NASM.
1120 process_response_file(argv[0]+1);
1121 argc--;
1122 argv++;
1124 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1125 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1126 if (p) {
1127 rfile = fopen(p, "r");
1128 if (rfile) {
1129 process_respfile(rfile);
1130 fclose(rfile);
1131 } else
1132 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1133 "unable to open response file `%s'", p);
1135 } else
1136 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1137 argv += advance, argc -= advance;
1140 /* Look for basic command line typos. This definitely doesn't
1141 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] */
1246 if (*value) {
1247 unsigned int align = atoi(value);
1248 if (!is_power2(align)) {
1249 nasm_error(ERR_NONFATAL,
1250 "segment alignment `%s' is not power of two",
1251 value);
1253 /* callee should be able to handle all details */
1254 ofmt->sectalign(location.segment, align);
1257 break;
1258 case D_EXTERN: /* [EXTERN label:special] */
1259 if (*value == '$')
1260 value++; /* skip initial $ if present */
1261 if (pass0 == 2) {
1262 q = value;
1263 while (*q && *q != ':')
1264 q++;
1265 if (*q == ':') {
1266 *q++ = '\0';
1267 ofmt->symdef(value, 0L, 0L, 3, q);
1269 } else if (passn == 1) {
1270 q = value;
1271 validid = true;
1272 if (!isidstart(*q))
1273 validid = false;
1274 while (*q && *q != ':') {
1275 if (!isidchar(*q))
1276 validid = false;
1277 q++;
1279 if (!validid) {
1280 nasm_error(ERR_NONFATAL,
1281 "identifier expected after EXTERN");
1282 break;
1284 if (*q == ':') {
1285 *q++ = '\0';
1286 special = q;
1287 } else
1288 special = NULL;
1289 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1290 int temp = pass0;
1291 pass0 = 1; /* fake pass 1 in labels.c */
1292 declare_as_global(value, special);
1293 define_label(value, seg_alloc(), 0L, NULL,
1294 false, true);
1295 pass0 = temp;
1297 } /* else pass0 == 1 */
1298 break;
1299 case D_BITS: /* [BITS bits] */
1300 globalbits = sb = get_bits(value);
1301 break;
1302 case D_GLOBAL: /* [GLOBAL symbol:special] */
1303 if (*value == '$')
1304 value++; /* skip initial $ if present */
1305 if (pass0 == 2) { /* pass 2 */
1306 q = value;
1307 while (*q && *q != ':')
1308 q++;
1309 if (*q == ':') {
1310 *q++ = '\0';
1311 ofmt->symdef(value, 0L, 0L, 3, q);
1313 } else if (pass2 == 1) { /* pass == 1 */
1314 q = value;
1315 validid = true;
1316 if (!isidstart(*q))
1317 validid = false;
1318 while (*q && *q != ':') {
1319 if (!isidchar(*q))
1320 validid = false;
1321 q++;
1323 if (!validid) {
1324 nasm_error(ERR_NONFATAL,
1325 "identifier expected after GLOBAL");
1326 break;
1328 if (*q == ':') {
1329 *q++ = '\0';
1330 special = q;
1331 } else
1332 special = NULL;
1333 declare_as_global(value, special);
1334 } /* pass == 1 */
1335 break;
1336 case D_COMMON: /* [COMMON symbol size:special] */
1338 int64_t size;
1340 if (*value == '$')
1341 value++; /* skip initial $ if present */
1342 p = value;
1343 validid = true;
1344 if (!isidstart(*p))
1345 validid = false;
1346 while (*p && !nasm_isspace(*p)) {
1347 if (!isidchar(*p))
1348 validid = false;
1349 p++;
1351 if (!validid) {
1352 nasm_error(ERR_NONFATAL,
1353 "identifier expected after COMMON");
1354 break;
1356 if (*p) {
1357 p = nasm_zap_spaces_fwd(p);
1358 q = p;
1359 while (*q && *q != ':')
1360 q++;
1361 if (*q == ':') {
1362 *q++ = '\0';
1363 special = q;
1364 } else {
1365 special = NULL;
1367 size = readnum(p, &rn_error);
1368 if (rn_error) {
1369 nasm_error(ERR_NONFATAL,
1370 "invalid size specified"
1371 " in COMMON declaration");
1372 break;
1374 } else {
1375 nasm_error(ERR_NONFATAL,
1376 "no size specified in"
1377 " COMMON declaration");
1378 break;
1381 if (pass0 < 2) {
1382 define_common(value, seg_alloc(), size, special);
1383 } else if (pass0 == 2) {
1384 if (special)
1385 ofmt->symdef(value, 0L, 0L, 3, special);
1387 break;
1389 case D_ABSOLUTE: /* [ABSOLUTE address] */
1390 stdscan_reset();
1391 stdscan_set(value);
1392 tokval.t_type = TOKEN_INVALID;
1393 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1394 nasm_error, NULL);
1395 if (e) {
1396 if (!is_reloc(e))
1397 nasm_error(pass0 ==
1398 1 ? ERR_NONFATAL : ERR_PANIC,
1399 "cannot use non-relocatable expression as "
1400 "ABSOLUTE address");
1401 else {
1402 abs_seg = reloc_seg(e);
1403 abs_offset = reloc_value(e);
1405 } else if (passn == 1)
1406 abs_offset = 0x100; /* don't go near zero in case of / */
1407 else
1408 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1409 "in pass two");
1410 in_abs_seg = true;
1411 location.segment = NO_SEG;
1412 break;
1413 case D_DEBUG: /* [DEBUG] */
1415 char debugid[128];
1416 bool badid, overlong;
1418 p = value;
1419 q = debugid;
1420 badid = overlong = false;
1421 if (!isidstart(*p)) {
1422 badid = true;
1423 } else {
1424 while (*p && !nasm_isspace(*p)) {
1425 if (q >= debugid + sizeof debugid - 1) {
1426 overlong = true;
1427 break;
1429 if (!isidchar(*p))
1430 badid = true;
1431 *q++ = *p++;
1433 *q = 0;
1435 if (badid) {
1436 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1437 "identifier expected after DEBUG");
1438 break;
1440 if (overlong) {
1441 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1442 "DEBUG identifier too long");
1443 break;
1445 p = nasm_skip_spaces(p);
1446 if (pass0 == 2)
1447 dfmt->debug_directive(debugid, p);
1448 break;
1450 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1451 value = nasm_skip_spaces(value);
1452 switch(*value) {
1453 case '-': validid = 0; value++; break;
1454 case '+': validid = 1; value++; break;
1455 case '*': validid = 2; value++; break;
1456 default: validid = 1; break;
1459 for (i = 1; i <= ERR_WARN_MAX; i++)
1460 if (!nasm_stricmp(value, warnings[i].name))
1461 break;
1462 if (i <= ERR_WARN_MAX) {
1463 switch(validid) {
1464 case 0:
1465 warning_on[i] = false;
1466 break;
1467 case 1:
1468 warning_on[i] = true;
1469 break;
1470 case 2:
1471 warning_on[i] = warning_on_global[i];
1472 break;
1475 else
1476 nasm_error(ERR_NONFATAL,
1477 "invalid warning id in WARNING directive");
1478 break;
1479 case D_CPU: /* [CPU] */
1480 cpu = get_cpu(value);
1481 break;
1482 case D_LIST: /* [LIST {+|-}] */
1483 value = nasm_skip_spaces(value);
1484 if (*value == '+') {
1485 user_nolist = 0;
1486 } else {
1487 if (*value == '-') {
1488 user_nolist = 1;
1489 } else {
1490 err = 1;
1493 break;
1494 case D_DEFAULT: /* [DEFAULT] */
1495 stdscan_reset();
1496 stdscan_set(value);
1497 tokval.t_type = TOKEN_INVALID;
1498 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1499 switch ((int)tokval.t_integer) {
1500 case S_REL:
1501 globalrel = 1;
1502 break;
1503 case S_ABS:
1504 globalrel = 0;
1505 break;
1506 default:
1507 err = 1;
1508 break;
1510 } else {
1511 err = 1;
1513 break;
1514 case D_FLOAT:
1515 if (float_option(value)) {
1516 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1517 "unknown 'float' directive: %s",
1518 value);
1520 break;
1521 default:
1522 if (ofmt->directive(d, value, pass2))
1523 break;
1524 /* else fall through */
1525 case D_unknown:
1526 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1527 "unrecognised directive [%s]",
1528 directive);
1529 break;
1531 if (err) {
1532 nasm_error(ERR_NONFATAL,
1533 "invalid parameter to [%s] directive",
1534 directive);
1536 } else { /* it isn't a directive */
1537 parse_line(pass1, line, &output_ins, def_label);
1539 if (optimizing > 0) {
1540 if (forwref != NULL && globallineno == forwref->lineno) {
1541 output_ins.forw_ref = true;
1542 do {
1543 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1544 forwref = saa_rstruct(forwrefs);
1545 } while (forwref != NULL
1546 && forwref->lineno == globallineno);
1547 } else
1548 output_ins.forw_ref = false;
1550 if (output_ins.forw_ref) {
1551 if (passn == 1) {
1552 for (i = 0; i < output_ins.operands; i++) {
1553 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1554 struct forwrefinfo *fwinf =
1555 (struct forwrefinfo *)
1556 saa_wstruct(forwrefs);
1557 fwinf->lineno = globallineno;
1558 fwinf->operand = i;
1565 /* forw_ref */
1566 if (output_ins.opcode == I_EQU) {
1567 if (pass1 == 1) {
1569 * Special `..' EQUs get processed in pass two,
1570 * except `..@' macro-processor EQUs which are done
1571 * in the normal place.
1573 if (!output_ins.label)
1574 nasm_error(ERR_NONFATAL,
1575 "EQU not preceded by label");
1577 else if (output_ins.label[0] != '.' ||
1578 output_ins.label[1] != '.' ||
1579 output_ins.label[2] == '@') {
1580 if (output_ins.operands == 1 &&
1581 (output_ins.oprs[0].type & IMMEDIATE) &&
1582 output_ins.oprs[0].wrt == NO_SEG) {
1583 bool isext = !!(output_ins.oprs[0].opflags
1584 & OPFLAG_EXTERN);
1585 def_label(output_ins.label,
1586 output_ins.oprs[0].segment,
1587 output_ins.oprs[0].offset, NULL,
1588 false, isext);
1589 } else if (output_ins.operands == 2
1590 && (output_ins.oprs[0].type & IMMEDIATE)
1591 && (output_ins.oprs[0].type & COLON)
1592 && output_ins.oprs[0].segment == NO_SEG
1593 && output_ins.oprs[0].wrt == NO_SEG
1594 && (output_ins.oprs[1].type & IMMEDIATE)
1595 && output_ins.oprs[1].segment == NO_SEG
1596 && output_ins.oprs[1].wrt == NO_SEG) {
1597 def_label(output_ins.label,
1598 output_ins.oprs[0].offset | SEG_ABS,
1599 output_ins.oprs[1].offset,
1600 NULL, false, false);
1601 } else
1602 nasm_error(ERR_NONFATAL,
1603 "bad syntax for EQU");
1605 } else {
1607 * Special `..' EQUs get processed here, except
1608 * `..@' macro processor EQUs which are done above.
1610 if (output_ins.label[0] == '.' &&
1611 output_ins.label[1] == '.' &&
1612 output_ins.label[2] != '@') {
1613 if (output_ins.operands == 1 &&
1614 (output_ins.oprs[0].type & IMMEDIATE)) {
1615 define_label(output_ins.label,
1616 output_ins.oprs[0].segment,
1617 output_ins.oprs[0].offset,
1618 NULL, false, false);
1619 } else if (output_ins.operands == 2
1620 && (output_ins.oprs[0].type & IMMEDIATE)
1621 && (output_ins.oprs[0].type & COLON)
1622 && output_ins.oprs[0].segment == NO_SEG
1623 && (output_ins.oprs[1].type & IMMEDIATE)
1624 && output_ins.oprs[1].segment == NO_SEG) {
1625 define_label(output_ins.label,
1626 output_ins.oprs[0].offset | SEG_ABS,
1627 output_ins.oprs[1].offset,
1628 NULL, false, false);
1629 } else
1630 nasm_error(ERR_NONFATAL,
1631 "bad syntax for EQU");
1634 } else { /* instruction isn't an EQU */
1636 if (pass1 == 1) {
1638 int64_t l = insn_size(location.segment, offs, sb, cpu,
1639 &output_ins, nasm_error);
1641 /* if (using_debug_info) && output_ins.opcode != -1) */
1642 if (using_debug_info)
1643 { /* fbk 03/25/01 */
1644 /* this is done here so we can do debug type info */
1645 int32_t typeinfo =
1646 TYS_ELEMENTS(output_ins.operands);
1647 switch (output_ins.opcode) {
1648 case I_RESB:
1649 typeinfo =
1650 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1651 break;
1652 case I_RESW:
1653 typeinfo =
1654 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1655 break;
1656 case I_RESD:
1657 typeinfo =
1658 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1659 break;
1660 case I_RESQ:
1661 typeinfo =
1662 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1663 break;
1664 case I_REST:
1665 typeinfo =
1666 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1667 break;
1668 case I_RESO:
1669 typeinfo =
1670 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1671 break;
1672 case I_RESY:
1673 typeinfo =
1674 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1675 break;
1676 case I_DB:
1677 typeinfo |= TY_BYTE;
1678 break;
1679 case I_DW:
1680 typeinfo |= TY_WORD;
1681 break;
1682 case I_DD:
1683 if (output_ins.eops_float)
1684 typeinfo |= TY_FLOAT;
1685 else
1686 typeinfo |= TY_DWORD;
1687 break;
1688 case I_DQ:
1689 typeinfo |= TY_QWORD;
1690 break;
1691 case I_DT:
1692 typeinfo |= TY_TBYTE;
1693 break;
1694 case I_DO:
1695 typeinfo |= TY_OWORD;
1696 break;
1697 case I_DY:
1698 typeinfo |= TY_YWORD;
1699 break;
1700 default:
1701 typeinfo = TY_LABEL;
1705 dfmt->debug_typevalue(typeinfo);
1707 if (l != -1) {
1708 offs += l;
1709 SET_CURR_OFFS(offs);
1712 * else l == -1 => invalid instruction, which will be
1713 * flagged as an error on pass 2
1716 } else {
1717 offs += assemble(location.segment, offs, sb, cpu,
1718 &output_ins, ofmt, nasm_error,
1719 &nasmlist);
1720 SET_CURR_OFFS(offs);
1723 } /* not an EQU */
1724 cleanup_insn(&output_ins);
1726 nasm_free(line);
1727 location.offset = offs = GET_CURR_OFFS;
1728 } /* end while (line = preproc->getline... */
1730 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1731 nasm_error(ERR_NONFATAL,
1732 "phase error detected at end of assembly.");
1734 if (pass1 == 1)
1735 preproc->cleanup(1);
1737 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1738 pass0++;
1739 } else if (global_offset_changed &&
1740 global_offset_changed < prev_offset_changed) {
1741 prev_offset_changed = global_offset_changed;
1742 stall_count = 0;
1743 } else {
1744 stall_count++;
1747 if (terminate_after_phase)
1748 break;
1750 if ((stall_count > 997) || (passn >= pass_max)) {
1751 /* We get here if the labels don't converge
1752 * Example: FOO equ FOO + 1
1754 nasm_error(ERR_NONFATAL,
1755 "Can't find valid values for all labels "
1756 "after %d passes, giving up.", passn);
1757 nasm_error(ERR_NONFATAL,
1758 "Possible causes: recursive EQUs, macro abuse.");
1759 break;
1763 preproc->cleanup(0);
1764 nasmlist.cleanup();
1765 if (!terminate_after_phase && opt_verbose_info) {
1766 /* -On and -Ov switches */
1767 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1771 static enum directives getkw(char **directive, char **value)
1773 char *p, *q, *buf;
1775 buf = nasm_skip_spaces(*directive);
1777 /* it should be enclosed in [ ] */
1778 if (*buf != '[')
1779 return D_none;
1780 q = strchr(buf, ']');
1781 if (!q)
1782 return D_none;
1784 /* stip off the comments */
1785 p = strchr(buf, ';');
1786 if (p) {
1787 if (p < q) /* ouch! somwhere inside */
1788 return D_none;
1789 *p = '\0';
1792 /* no brace, no trailing spaces */
1793 *q = '\0';
1794 nasm_zap_spaces_rev(--q);
1796 /* directive */
1797 p = nasm_skip_spaces(++buf);
1798 q = nasm_skip_word(p);
1799 if (!q)
1800 return D_none; /* sigh... no value there */
1801 *q = '\0';
1802 *directive = p;
1804 /* and value finally */
1805 p = nasm_skip_spaces(++q);
1806 *value = p;
1808 return find_directive(*directive);
1812 * gnu style error reporting
1813 * This function prints an error message to error_file in the
1814 * style used by GNU. An example would be:
1815 * file.asm:50: error: blah blah blah
1816 * where file.asm is the name of the file, 50 is the line number on
1817 * which the error occurs (or is detected) and "error:" is one of
1818 * the possible optional diagnostics -- it can be "error" or "warning"
1819 * or something else. Finally the line terminates with the actual
1820 * error message.
1822 * @param severity the severity of the warning or error
1823 * @param fmt the printf style format string
1825 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1827 char *currentfile = NULL;
1828 int32_t lineno = 0;
1830 if (is_suppressed_warning(severity))
1831 return;
1833 if (!(severity & ERR_NOFILE))
1834 src_get(&lineno, &currentfile);
1836 if (currentfile) {
1837 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1838 nasm_free(currentfile);
1839 } else {
1840 fputs("nasm: ", error_file);
1843 nasm_verror_common(severity, fmt, ap);
1847 * MS style error reporting
1848 * This function prints an error message to error_file in the
1849 * style used by Visual C and some other Microsoft tools. An example
1850 * would be:
1851 * file.asm(50) : error: blah blah blah
1852 * where file.asm is the name of the file, 50 is the line number on
1853 * which the error occurs (or is detected) and "error:" is one of
1854 * the possible optional diagnostics -- it can be "error" or "warning"
1855 * or something else. Finally the line terminates with the actual
1856 * error message.
1858 * @param severity the severity of the warning or error
1859 * @param fmt the printf style format string
1861 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1863 char *currentfile = NULL;
1864 int32_t lineno = 0;
1866 if (is_suppressed_warning(severity))
1867 return;
1869 if (!(severity & ERR_NOFILE))
1870 src_get(&lineno, &currentfile);
1872 if (currentfile) {
1873 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1874 nasm_free(currentfile);
1875 } else {
1876 fputs("nasm: ", error_file);
1879 nasm_verror_common(severity, fmt, ap);
1883 * check for supressed warning
1884 * checks for suppressed warning or pass one only warning and we're
1885 * not in pass 1
1887 * @param severity the severity of the warning or error
1888 * @return true if we should abort error/warning printing
1890 static bool is_suppressed_warning(int severity)
1893 * See if it's a suppressed warning.
1895 return (severity & ERR_MASK) == ERR_WARNING &&
1896 (((severity & ERR_WARN_MASK) != 0 &&
1897 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1898 /* See if it's a pass-one only warning and we're not in pass one. */
1899 ((severity & ERR_PASS1) && pass0 != 1) ||
1900 ((severity & ERR_PASS2) && pass0 != 2));
1904 * common error reporting
1905 * This is the common back end of the error reporting schemes currently
1906 * implemented. It prints the nature of the warning and then the
1907 * specific error message to error_file and may or may not return. It
1908 * doesn't return if the error severity is a "panic" or "debug" type.
1910 * @param severity the severity of the warning or error
1911 * @param fmt the printf style format string
1913 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1915 char msg[1024];
1916 const char *pfx;
1918 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1919 case ERR_WARNING:
1920 pfx = "warning: ";
1921 break;
1922 case ERR_NONFATAL:
1923 pfx = "error: ";
1924 break;
1925 case ERR_FATAL:
1926 pfx = "fatal: ";
1927 break;
1928 case ERR_PANIC:
1929 pfx = "panic: ";
1930 break;
1931 case ERR_DEBUG:
1932 pfx = "debug: ";
1933 break;
1934 default:
1935 pfx = "";
1936 break;
1939 vsnprintf(msg, sizeof msg, fmt, args);
1941 fprintf(error_file, "%s%s\n", pfx, msg);
1943 if (*listname)
1944 nasmlist.error(severity, pfx, msg);
1946 if (severity & ERR_USAGE)
1947 want_usage = true;
1949 switch (severity & ERR_MASK) {
1950 case ERR_DEBUG:
1951 /* no further action, by definition */
1952 break;
1953 case ERR_WARNING:
1954 if (warning_on[0]) /* Treat warnings as errors */
1955 terminate_after_phase = true;
1956 break;
1957 case ERR_NONFATAL:
1958 terminate_after_phase = true;
1959 break;
1960 case ERR_FATAL:
1961 if (ofile) {
1962 fclose(ofile);
1963 remove(outname);
1964 ofile = NULL;
1966 if (want_usage)
1967 usage();
1968 exit(1); /* instantly die */
1969 break; /* placate silly compilers */
1970 case ERR_PANIC:
1971 fflush(NULL);
1972 /* abort(); *//* halt, catch fire, and dump core */
1973 exit(3);
1974 break;
1978 static void usage(void)
1980 fputs("type `nasm -h' for help\n", error_file);
1983 #define BUF_DELTA 512
1985 static FILE *no_pp_fp;
1986 static ListGen *no_pp_list;
1987 static int32_t no_pp_lineinc;
1989 static void no_pp_reset(char *file, int pass, ListGen * listgen,
1990 StrList **deplist)
1992 src_set_fname(nasm_strdup(file));
1993 src_set_linnum(0);
1994 no_pp_lineinc = 1;
1995 no_pp_fp = fopen(file, "r");
1996 if (!no_pp_fp)
1997 nasm_error(ERR_FATAL | ERR_NOFILE,
1998 "unable to open input file `%s'", file);
1999 no_pp_list = listgen;
2000 (void)pass; /* placate compilers */
2002 if (deplist) {
2003 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2004 sl->next = NULL;
2005 strcpy(sl->str, file);
2006 *deplist = sl;
2010 static char *no_pp_getline(void)
2012 char *buffer, *p, *q;
2013 int bufsize;
2015 bufsize = BUF_DELTA;
2016 buffer = nasm_malloc(BUF_DELTA);
2017 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2019 while (1) { /* Loop to handle %line */
2021 p = buffer;
2022 while (1) { /* Loop to handle long lines */
2023 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2024 if (!q)
2025 break;
2026 p += strlen(p);
2027 if (p > buffer && p[-1] == '\n')
2028 break;
2029 if (p - buffer > bufsize - 10) {
2030 int offset;
2031 offset = p - buffer;
2032 bufsize += BUF_DELTA;
2033 buffer = nasm_realloc(buffer, bufsize);
2034 p = buffer + offset;
2038 if (!q && p == buffer) {
2039 nasm_free(buffer);
2040 return NULL;
2044 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2045 * them are present at the end of the line.
2047 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2049 if (!nasm_strnicmp(buffer, "%line", 5)) {
2050 int32_t ln;
2051 int li;
2052 char *nm = nasm_malloc(strlen(buffer));
2053 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2054 nasm_free(src_set_fname(nm));
2055 src_set_linnum(ln);
2056 no_pp_lineinc = li;
2057 continue;
2059 nasm_free(nm);
2061 break;
2064 no_pp_list->line(LIST_READ, buffer);
2066 return buffer;
2069 static void no_pp_cleanup(int pass)
2071 (void)pass; /* placate GCC */
2072 fclose(no_pp_fp);
2075 static uint32_t get_cpu(char *value)
2077 if (!strcmp(value, "8086"))
2078 return IF_8086;
2079 if (!strcmp(value, "186"))
2080 return IF_186;
2081 if (!strcmp(value, "286"))
2082 return IF_286;
2083 if (!strcmp(value, "386"))
2084 return IF_386;
2085 if (!strcmp(value, "486"))
2086 return IF_486;
2087 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2088 return IF_PENT;
2089 if (!strcmp(value, "686") ||
2090 !nasm_stricmp(value, "ppro") ||
2091 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2092 return IF_P6;
2093 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2094 return IF_KATMAI;
2095 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2096 !nasm_stricmp(value, "willamette"))
2097 return IF_WILLAMETTE;
2098 if (!nasm_stricmp(value, "prescott"))
2099 return IF_PRESCOTT;
2100 if (!nasm_stricmp(value, "x64") ||
2101 !nasm_stricmp(value, "x86-64"))
2102 return IF_X86_64;
2103 if (!nasm_stricmp(value, "ia64") ||
2104 !nasm_stricmp(value, "ia-64") ||
2105 !nasm_stricmp(value, "itanium") ||
2106 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2107 return IF_IA64;
2109 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2110 "unknown 'cpu' type");
2112 return IF_PLEVEL; /* the maximum level */
2115 static int get_bits(char *value)
2117 int i;
2119 if ((i = atoi(value)) == 16)
2120 return i; /* set for a 16-bit segment */
2121 else if (i == 32) {
2122 if (cpu < IF_386) {
2123 nasm_error(ERR_NONFATAL,
2124 "cannot specify 32-bit segment on processor below a 386");
2125 i = 16;
2127 } else if (i == 64) {
2128 if (cpu < IF_X86_64) {
2129 nasm_error(ERR_NONFATAL,
2130 "cannot specify 64-bit segment on processor below an x86-64");
2131 i = 16;
2133 if (i != maxbits) {
2134 nasm_error(ERR_NONFATAL,
2135 "%s output format does not support 64-bit code",
2136 ofmt->shortname);
2137 i = 16;
2139 } else {
2140 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2141 "`%s' is not a valid segment size; must be 16, 32 or 64",
2142 value);
2143 i = 16;
2145 return i;