parser.c: fix stylistic nitpick
[nasm/avx512.git] / nasm.c
blob553521530f47c481740e148bd3af03e794238332
1 /* The Netwide Assembler main program module
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the license given in the file "LICENSE"
6 * distributed in the NASM archive.
7 */
9 #include "compiler.h"
11 #include <stdio.h>
12 #include <stdarg.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <ctype.h>
16 #include <inttypes.h>
17 #include <limits.h>
18 #include <time.h>
20 #include "nasm.h"
21 #include "nasmlib.h"
22 #include "saa.h"
23 #include "raa.h"
24 #include "float.h"
25 #include "stdscan.h"
26 #include "insns.h"
27 #include "preproc.h"
28 #include "parser.h"
29 #include "eval.h"
30 #include "assemble.h"
31 #include "labels.h"
32 #include "outform.h"
33 #include "listing.h"
35 struct forwrefinfo { /* info held on forward refs. */
36 int lineno;
37 int operand;
40 static int get_bits(char *value);
41 static uint32_t get_cpu(char *cpu_str);
42 static void parse_cmdline(int, char **);
43 static void assemble_file(char *, StrList **);
44 static void register_output_formats(void);
45 static void report_error_gnu(int severity, const char *fmt, ...);
46 static void report_error_vc(int severity, const char *fmt, ...);
47 static void report_error_common(int severity, const char *fmt,
48 va_list args);
49 static bool is_suppressed_warning(int severity);
50 static void usage(void);
51 static efunc report_error;
53 static int using_debug_info, opt_verbose_info;
54 bool tasm_compatible_mode = false;
55 int pass0, passn;
56 int maxbits = 0;
57 int globalrel = 0;
59 time_t official_compile_time;
61 static char inname[FILENAME_MAX];
62 static char outname[FILENAME_MAX];
63 static char listname[FILENAME_MAX];
64 static char errname[FILENAME_MAX];
65 static int globallineno; /* for forward-reference tracking */
66 /* static int pass = 0; */
67 static struct ofmt *ofmt = NULL;
69 static FILE *error_file; /* Where to write error messages */
71 static FILE *ofile = NULL;
72 int optimizing = -1; /* number of optimization passes to take */
73 static int sb, cmd_sb = 16; /* by default */
74 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
75 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
76 int64_t global_offset_changed; /* referenced in labels.c */
77 int64_t prev_offset_changed;
78 int32_t stall_count;
80 static struct location location;
81 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
82 int32_t abs_seg; /* ABSOLUTE segment basis */
83 int32_t abs_offset; /* ABSOLUTE offset */
85 static struct RAA *offsets;
87 static struct SAA *forwrefs; /* keep track of forward references */
88 static const struct forwrefinfo *forwref;
90 static Preproc *preproc;
91 enum op_type {
92 op_normal, /* Preprocess and assemble */
93 op_preprocess, /* Preprocess only */
94 op_depend, /* Generate dependencies */
96 static enum op_type operating_mode;
97 /* Dependency flags */
98 static bool depend_emit_phony = false;
99 static bool depend_missing_ok = false;
100 static const char *depend_target = NULL;
101 static const char *depend_file = NULL;
104 * Which of the suppressible warnings are suppressed. Entry zero
105 * isn't an actual warning, but it used for -w+error/-Werror.
108 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
109 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
111 static const struct warning {
112 const char *name;
113 const char *help;
114 bool enabled;
115 } warnings[ERR_WARN_MAX+1] = {
116 {"error", "treat warnings as errors", false},
117 {"macro-params", "macro calls with wrong parameter count", true},
118 {"macro-selfref", "cyclic macro references", false},
119 {"macro-defaults", "macros with more default than optional parameters", true},
120 {"orphan-labels", "labels alone on lines without trailing `:'", true},
121 {"number-overflow", "numeric constant does not fit", true},
122 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
123 {"float-overflow", "floating point overflow", true},
124 {"float-denorm", "floating point denormal", false},
125 {"float-underflow", "floating point underflow", false},
126 {"float-toolong", "too many digits in floating-point number", true},
127 {"user", "%warning directives", true},
131 * This is a null preprocessor which just copies lines from input
132 * to output. It's used when someone explicitly requests that NASM
133 * not preprocess their source file.
136 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
137 static char *no_pp_getline(void);
138 static void no_pp_cleanup(int);
139 static Preproc no_pp = {
140 no_pp_reset,
141 no_pp_getline,
142 no_pp_cleanup
146 * get/set current offset...
148 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
149 raa_read(offsets,location.segment))
150 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
151 (void)(offsets=raa_write(offsets,location.segment,(x))))
153 static bool want_usage;
154 static bool terminate_after_phase;
155 int user_nolist = 0; /* fbk 9/2/00 */
157 static void nasm_fputs(const char *line, FILE * outfile)
159 if (outfile) {
160 fputs(line, outfile);
161 putc('\n', outfile);
162 } else
163 puts(line);
166 /* Convert a struct tm to a POSIX-style time constant */
167 static int64_t posix_mktime(struct tm *tm)
169 int64_t t;
170 int64_t y = tm->tm_year;
172 /* See IEEE 1003.1:2004, section 4.14 */
174 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
175 t += tm->tm_yday;
176 t *= 24;
177 t += tm->tm_hour;
178 t *= 60;
179 t += tm->tm_min;
180 t *= 60;
181 t += tm->tm_sec;
183 return t;
186 static void define_macros_early(void)
188 char temp[128];
189 struct tm lt, *lt_p, gm, *gm_p;
190 int64_t posix_time;
192 lt_p = localtime(&official_compile_time);
193 if (lt_p) {
194 lt = *lt_p;
196 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
197 pp_pre_define(temp);
198 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
199 pp_pre_define(temp);
200 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
201 pp_pre_define(temp);
202 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
203 pp_pre_define(temp);
206 gm_p = gmtime(&official_compile_time);
207 if (gm_p) {
208 gm = *gm_p;
210 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
211 pp_pre_define(temp);
212 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
213 pp_pre_define(temp);
214 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
215 pp_pre_define(temp);
216 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
217 pp_pre_define(temp);
220 if (gm_p)
221 posix_time = posix_mktime(&gm);
222 else if (lt_p)
223 posix_time = posix_mktime(&lt);
224 else
225 posix_time = 0;
227 if (posix_time) {
228 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
229 pp_pre_define(temp);
233 static void define_macros_late(void)
235 char temp[128];
237 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
238 ofmt->shortname);
239 pp_pre_define(temp);
242 static void emit_dependencies(StrList *list)
244 FILE *deps;
245 int linepos, len;
246 StrList *l, *nl;
248 if (depend_file && strcmp(depend_file, "-")) {
249 deps = fopen(depend_file, "w");
250 if (!deps) {
251 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
252 "unable to write dependency file `%s'", depend_file);
253 return;
255 } else {
256 deps = stdout;
259 linepos = fprintf(deps, "%s:", depend_target);
260 for (l = list; l; l = l->next) {
261 len = strlen(l->str);
262 if (linepos + len > 62) {
263 fprintf(deps, " \\\n ");
264 linepos = 1;
266 fprintf(deps, " %s", l->str);
267 linepos += len+1;
269 fprintf(deps, "\n\n");
271 for (l = list; l; l = nl) {
272 if (depend_emit_phony)
273 fprintf(deps, "%s:\n\n", l->str);
275 nl = l->next;
276 nasm_free(l);
279 if (deps != stdout)
280 fclose(deps);
283 int main(int argc, char **argv)
285 StrList *depend_list = NULL, **depend_ptr;
287 time(&official_compile_time);
289 pass0 = 0;
290 want_usage = terminate_after_phase = false;
291 report_error = report_error_gnu;
293 error_file = stderr;
295 tolower_init();
297 nasm_set_malloc_error(report_error);
298 offsets = raa_init();
299 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
301 preproc = &nasmpp;
302 operating_mode = op_normal;
304 seg_init();
306 register_output_formats();
308 /* Define some macros dependent on the runtime, but not
309 on the command line. */
310 define_macros_early();
312 parse_cmdline(argc, argv);
314 if (terminate_after_phase) {
315 if (want_usage)
316 usage();
317 return 1;
320 /* If debugging info is disabled, suppress any debug calls */
321 if (!using_debug_info)
322 ofmt->current_dfmt = &null_debug_form;
324 if (ofmt->stdmac)
325 pp_extra_stdmac(ofmt->stdmac);
326 parser_global_info(ofmt, &location);
327 eval_global_info(ofmt, lookup_label, &location);
329 /* define some macros dependent of command-line */
330 define_macros_late();
332 depend_ptr = (depend_file || (operating_mode == op_depend))
333 ? &depend_list : NULL;
334 if (!depend_target)
335 depend_target = outname;
337 switch (operating_mode) {
338 case op_depend:
340 char *line;
342 if (depend_missing_ok)
343 pp_include_path(NULL); /* "assume generated" */
345 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
346 depend_ptr);
347 if (outname[0] == '\0')
348 ofmt->filename(inname, outname, report_error);
349 ofile = NULL;
350 while ((line = preproc->getline()))
351 nasm_free(line);
352 preproc->cleanup(0);
354 break;
356 case op_preprocess:
358 char *line;
359 char *file_name = NULL;
360 int32_t prior_linnum = 0;
361 int lineinc = 0;
363 if (*outname) {
364 ofile = fopen(outname, "w");
365 if (!ofile)
366 report_error(ERR_FATAL | ERR_NOFILE,
367 "unable to open output file `%s'",
368 outname);
369 } else
370 ofile = NULL;
372 location.known = false;
374 /* pass = 1; */
375 preproc->reset(inname, 3, report_error, evaluate, &nasmlist,
376 depend_ptr);
378 while ((line = preproc->getline())) {
380 * We generate %line directives if needed for later programs
382 int32_t linnum = prior_linnum += lineinc;
383 int altline = src_get(&linnum, &file_name);
384 if (altline) {
385 if (altline == 1 && lineinc == 1)
386 nasm_fputs("", ofile);
387 else {
388 lineinc = (altline != -1 || lineinc != 1);
389 fprintf(ofile ? ofile : stdout,
390 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
391 file_name);
393 prior_linnum = linnum;
395 nasm_fputs(line, ofile);
396 nasm_free(line);
398 nasm_free(file_name);
399 preproc->cleanup(0);
400 if (ofile)
401 fclose(ofile);
402 if (ofile && terminate_after_phase)
403 remove(outname);
405 break;
407 case op_normal:
410 * We must call ofmt->filename _anyway_, even if the user
411 * has specified their own output file, because some
412 * formats (eg OBJ and COFF) use ofmt->filename to find out
413 * the name of the input file and then put that inside the
414 * file.
416 ofmt->filename(inname, outname, report_error);
418 ofile = fopen(outname, "wb");
419 if (!ofile) {
420 report_error(ERR_FATAL | ERR_NOFILE,
421 "unable to open output file `%s'", outname);
425 * We must call init_labels() before ofmt->init() since
426 * some object formats will want to define labels in their
427 * init routines. (eg OS/2 defines the FLAT group)
429 init_labels();
431 ofmt->init(ofile, report_error, define_label, evaluate);
433 assemble_file(inname, depend_ptr);
435 if (!terminate_after_phase) {
436 ofmt->cleanup(using_debug_info);
437 cleanup_labels();
438 } else {
440 * Despite earlier comments, we need this fclose.
441 * The object output drivers only fclose on cleanup,
442 * and we just skipped that.
444 fclose (ofile);
446 remove(outname);
447 if (listname[0])
448 remove(listname);
451 break;
454 if (depend_list && !terminate_after_phase)
455 emit_dependencies(depend_list);
457 if (want_usage)
458 usage();
460 raa_free(offsets);
461 saa_free(forwrefs);
462 eval_cleanup();
463 stdscan_cleanup();
465 return terminate_after_phase;
469 * Get a parameter for a command line option.
470 * First arg must be in the form of e.g. -f...
472 static char *get_param(char *p, char *q, bool *advance)
474 *advance = false;
475 if (p[2]) { /* the parameter's in the option */
476 p += 2;
477 while (nasm_isspace(*p))
478 p++;
479 return p;
481 if (q && q[0]) {
482 *advance = true;
483 return q;
485 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
486 "option `-%c' requires an argument", p[1]);
487 return NULL;
491 * Copy a filename
493 static void copy_filename(char *dst, const char *src)
495 size_t len = strlen(src);
497 if (len >= (size_t)FILENAME_MAX) {
498 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
499 return;
501 strncpy(dst, src, FILENAME_MAX);
505 * Convert a string to Make-safe form
507 static char *quote_for_make(const char *str)
509 const char *p;
510 char *os, *q;
512 size_t n = 1; /* Terminating zero */
513 size_t nbs = 0;
515 if (!str)
516 return NULL;
518 for (p = str; *p; p++) {
519 switch (*p) {
520 case ' ':
521 case '\t':
522 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
523 n += nbs + 2;
524 nbs = 0;
525 break;
526 case '$':
527 case '#':
528 nbs = 0;
529 n += 2;
530 break;
531 case '\\':
532 nbs++;
533 n++;
534 break;
535 default:
536 nbs = 0;
537 n++;
538 break;
542 /* Convert N backslashes at the end of filename to 2N backslashes */
543 if (nbs)
544 n += nbs;
546 os = q = nasm_malloc(n);
548 nbs = 0;
549 for (p = str; *p; p++) {
550 switch (*p) {
551 case ' ':
552 case '\t':
553 while (nbs--)
554 *q++ = '\\';
555 *q++ = '\\';
556 *q++ = *p;
557 break;
558 case '$':
559 *q++ = *p;
560 *q++ = *p;
561 nbs = 0;
562 break;
563 case '#':
564 *q++ = '\\';
565 *q++ = *p;
566 nbs = 0;
567 break;
568 case '\\':
569 *q++ = *p;
570 nbs++;
571 break;
572 default:
573 *q++ = *p;
574 nbs = 0;
575 break;
578 while (nbs--)
579 *q++ = '\\';
581 *q = '\0';
583 return os;
586 struct textargs {
587 const char *label;
588 int value;
591 #define OPT_PREFIX 0
592 #define OPT_POSTFIX 1
593 struct textargs textopts[] = {
594 {"prefix", OPT_PREFIX},
595 {"postfix", OPT_POSTFIX},
596 {NULL, 0}
599 static bool stopoptions = false;
600 static bool process_arg(char *p, char *q)
602 char *param;
603 int i;
604 bool advance = false;
605 bool do_warn;
607 if (!p || !p[0])
608 return false;
610 if (p[0] == '-' && !stopoptions) {
611 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
612 /* These parameters take values */
613 if (!(param = get_param(p, q, &advance)))
614 return advance;
617 switch (p[1]) {
618 case 's':
619 error_file = stdout;
620 break;
622 case 'o': /* output file */
623 copy_filename(outname, param);
624 break;
626 case 'f': /* output format */
627 ofmt = ofmt_find(param);
628 if (!ofmt) {
629 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
630 "unrecognised output format `%s' - "
631 "use -hf for a list", param);
633 break;
635 case 'O': /* Optimization level */
637 int opt;
639 if (!*param) {
640 /* Naked -O == -Ox */
641 optimizing = INT_MAX >> 1; /* Almost unlimited */
642 } else {
643 while (*param) {
644 switch (*param) {
645 case '0': case '1': case '2': case '3': case '4':
646 case '5': case '6': case '7': case '8': case '9':
647 opt = strtoul(param, &param, 10);
649 /* -O0 -> optimizing == -1, 0.98 behaviour */
650 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
651 if (opt < 2)
652 optimizing = opt - 1;
653 else
654 optimizing = opt;
655 break;
657 case 'v':
658 case '+':
659 param++;
660 opt_verbose_info = true;
661 break;
663 case 'x':
664 param++;
665 optimizing = INT_MAX >> 1; /* Almost unlimited */
666 break;
668 default:
669 report_error(ERR_FATAL,
670 "unknown optimization option -O%c\n",
671 *param);
672 break;
676 break;
679 case 'p': /* pre-include */
680 case 'P':
681 pp_pre_include(param);
682 break;
684 case 'd': /* pre-define */
685 case 'D':
686 pp_pre_define(param);
687 break;
689 case 'u': /* un-define */
690 case 'U':
691 pp_pre_undefine(param);
692 break;
694 case 'i': /* include search path */
695 case 'I':
696 pp_include_path(param);
697 break;
699 case 'l': /* listing file */
700 copy_filename(listname, param);
701 break;
703 case 'Z': /* error messages file */
704 strcpy(errname, param);
705 break;
707 case 'F': /* specify debug format */
708 ofmt->current_dfmt = dfmt_find(ofmt, param);
709 if (!ofmt->current_dfmt) {
710 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
711 "unrecognized debug format `%s' for"
712 " output format `%s'",
713 param, ofmt->shortname);
715 using_debug_info = true;
716 break;
718 case 'X': /* specify error reporting format */
719 if (nasm_stricmp("vc", param) == 0)
720 report_error = report_error_vc;
721 else if (nasm_stricmp("gnu", param) == 0)
722 report_error = report_error_gnu;
723 else
724 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
725 "unrecognized error reporting format `%s'",
726 param);
727 break;
729 case 'g':
730 using_debug_info = true;
731 break;
733 case 'h':
734 printf
735 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
736 "[-l listfile]\n"
737 " [options...] [--] filename\n"
738 " or nasm -v for version info\n\n"
739 " -t assemble in SciTech TASM compatible mode\n"
740 " -g generate debug information in selected format.\n");
741 printf
742 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
743 " -a don't preprocess (assemble only)\n"
744 " -M generate Makefile dependencies on stdout\n"
745 " -MG d:o, missing files assumed generated\n\n"
746 " -Z<file> redirect error messages to file\n"
747 " -s redirect error messages to stdout\n\n"
748 " -F format select a debugging format\n\n"
749 " -I<path> adds a pathname to the include file path\n");
750 printf
751 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
752 " -P<file> pre-includes a file\n"
753 " -D<macro>[=<value>] pre-defines a macro\n"
754 " -U<macro> undefines a macro\n"
755 " -X<format> specifies error reporting format (gnu or vc)\n"
756 " -w+foo enables warning foo (equiv. -Wfoo)\n"
757 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
758 "Warnings:\n");
759 for (i = 0; i <= ERR_WARN_MAX; i++)
760 printf(" %-23s %s (default %s)\n",
761 warnings[i].name, warnings[i].help,
762 warnings[i].enabled ? "on" : "off");
763 printf
764 ("\nresponse files should contain command line parameters"
765 ", one per line.\n");
766 if (p[2] == 'f') {
767 printf("\nvalid output formats for -f are"
768 " (`*' denotes default):\n");
769 ofmt_list(ofmt, stdout);
770 } else {
771 printf("\nFor a list of valid output formats, use -hf.\n");
772 printf("For a list of debug formats, use -f <form> -y.\n");
774 exit(0); /* never need usage message here */
775 break;
777 case 'y':
778 printf("\nvalid debug formats for '%s' output format are"
779 " ('*' denotes default):\n", ofmt->shortname);
780 dfmt_list(ofmt, stdout);
781 exit(0);
782 break;
784 case 't':
785 tasm_compatible_mode = true;
786 break;
788 case 'v':
789 printf("NASM version %s compiled on %s%s\n",
790 nasm_version, nasm_date, nasm_compile_options);
791 exit(0); /* never need usage message here */
792 break;
794 case 'e': /* preprocess only */
795 case 'E':
796 operating_mode = op_preprocess;
797 break;
799 case 'a': /* assemble only - don't preprocess */
800 preproc = &no_pp;
801 break;
803 case 'W':
804 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
805 do_warn = false;
806 param += 3;
807 } else {
808 do_warn = true;
810 goto set_warning;
812 case 'w':
813 if (param[0] != '+' && param[0] != '-') {
814 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
815 "invalid option to `-w'");
816 break;
818 do_warn = (param[0] == '+');
819 param++;
820 goto set_warning;
821 set_warning:
822 for (i = 0; i <= ERR_WARN_MAX; i++)
823 if (!nasm_stricmp(param, warnings[i].name))
824 break;
825 if (i <= ERR_WARN_MAX)
826 warning_on_global[i] = do_warn;
827 else if (!nasm_stricmp(param, "all"))
828 for (i = 1; i <= ERR_WARN_MAX; i++)
829 warning_on_global[i] = do_warn;
830 else if (!nasm_stricmp(param, "none"))
831 for (i = 1; i <= ERR_WARN_MAX; i++)
832 warning_on_global[i] = !do_warn;
833 else
834 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
835 "invalid warning `%s'", param);
836 break;
838 case 'M':
839 switch (p[2]) {
840 case 0:
841 operating_mode = op_depend;
842 break;
843 case 'G':
844 operating_mode = op_depend;
845 depend_missing_ok = true;
846 break;
847 case 'P':
848 depend_emit_phony = true;
849 break;
850 case 'D':
851 depend_file = q;
852 advance = true;
853 break;
854 case 'T':
855 depend_target = q;
856 advance = true;
857 break;
858 case 'Q':
859 depend_target = quote_for_make(q);
860 advance = true;
861 break;
862 default:
863 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
864 "unknown dependency option `-M%c'", p[2]);
865 break;
867 if (advance && (!q || !q[0])) {
868 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
869 "option `-M%c' requires a parameter", p[2]);
870 break;
872 break;
874 case '-':
876 int s;
878 if (p[2] == 0) { /* -- => stop processing options */
879 stopoptions = 1;
880 break;
882 for (s = 0; textopts[s].label; s++) {
883 if (!nasm_stricmp(p + 2, textopts[s].label)) {
884 break;
888 switch (s) {
890 case OPT_PREFIX:
891 case OPT_POSTFIX:
893 if (!q) {
894 report_error(ERR_NONFATAL | ERR_NOFILE |
895 ERR_USAGE,
896 "option `--%s' requires an argument",
897 p + 2);
898 break;
899 } else {
900 advance = 1, param = q;
903 if (s == OPT_PREFIX) {
904 strncpy(lprefix, param, PREFIX_MAX - 1);
905 lprefix[PREFIX_MAX - 1] = 0;
906 break;
908 if (s == OPT_POSTFIX) {
909 strncpy(lpostfix, param, POSTFIX_MAX - 1);
910 lpostfix[POSTFIX_MAX - 1] = 0;
911 break;
913 break;
915 default:
917 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
918 "unrecognised option `--%s'", p + 2);
919 break;
922 break;
925 default:
926 if (!ofmt->setinfo(GI_SWITCH, &p))
927 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
928 "unrecognised option `-%c'", p[1]);
929 break;
931 } else {
932 if (*inname) {
933 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
934 "more than one input file specified");
935 } else {
936 copy_filename(inname, p);
940 return advance;
943 #define ARG_BUF_DELTA 128
945 static void process_respfile(FILE * rfile)
947 char *buffer, *p, *q, *prevarg;
948 int bufsize, prevargsize;
950 bufsize = prevargsize = ARG_BUF_DELTA;
951 buffer = nasm_malloc(ARG_BUF_DELTA);
952 prevarg = nasm_malloc(ARG_BUF_DELTA);
953 prevarg[0] = '\0';
955 while (1) { /* Loop to handle all lines in file */
956 p = buffer;
957 while (1) { /* Loop to handle long lines */
958 q = fgets(p, bufsize - (p - buffer), rfile);
959 if (!q)
960 break;
961 p += strlen(p);
962 if (p > buffer && p[-1] == '\n')
963 break;
964 if (p - buffer > bufsize - 10) {
965 int offset;
966 offset = p - buffer;
967 bufsize += ARG_BUF_DELTA;
968 buffer = nasm_realloc(buffer, bufsize);
969 p = buffer + offset;
973 if (!q && p == buffer) {
974 if (prevarg[0])
975 process_arg(prevarg, NULL);
976 nasm_free(buffer);
977 nasm_free(prevarg);
978 return;
982 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
983 * them are present at the end of the line.
985 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
987 while (p > buffer && nasm_isspace(p[-1]))
988 *--p = '\0';
990 p = buffer;
991 while (nasm_isspace(*p))
992 p++;
994 if (process_arg(prevarg, p))
995 *p = '\0';
997 if ((int) strlen(p) > prevargsize - 10) {
998 prevargsize += ARG_BUF_DELTA;
999 prevarg = nasm_realloc(prevarg, prevargsize);
1001 strncpy(prevarg, p, prevargsize);
1005 /* Function to process args from a string of args, rather than the
1006 * argv array. Used by the environment variable and response file
1007 * processing.
1009 static void process_args(char *args)
1011 char *p, *q, *arg, *prevarg;
1012 char separator = ' ';
1014 p = args;
1015 if (*p && *p != '-')
1016 separator = *p++;
1017 arg = NULL;
1018 while (*p) {
1019 q = p;
1020 while (*p && *p != separator)
1021 p++;
1022 while (*p == separator)
1023 *p++ = '\0';
1024 prevarg = arg;
1025 arg = q;
1026 if (process_arg(prevarg, arg))
1027 arg = NULL;
1029 if (arg)
1030 process_arg(arg, NULL);
1033 static void process_response_file(const char *file)
1035 char str[2048];
1036 FILE *f = fopen(file, "r");
1037 if (!f) {
1038 perror(file);
1039 exit(-1);
1041 while (fgets(str, sizeof str, f)) {
1042 process_args(str);
1044 fclose(f);
1047 static void parse_cmdline(int argc, char **argv)
1049 FILE *rfile;
1050 char *envreal, *envcopy = NULL, *p, *arg;
1051 int i;
1053 *inname = *outname = *listname = *errname = '\0';
1054 for (i = 0; i <= ERR_WARN_MAX; i++)
1055 warning_on_global[i] = warnings[i].enabled;
1058 * First, process the NASMENV environment variable.
1060 envreal = getenv("NASMENV");
1061 arg = NULL;
1062 if (envreal) {
1063 envcopy = nasm_strdup(envreal);
1064 process_args(envcopy);
1065 nasm_free(envcopy);
1069 * Now process the actual command line.
1071 while (--argc) {
1072 bool advance;
1073 argv++;
1074 if (argv[0][0] == '@') {
1075 /* We have a response file, so process this as a set of
1076 * arguments like the environment variable. This allows us
1077 * to have multiple arguments on a single line, which is
1078 * different to the -@resp file processing below for regular
1079 * NASM.
1081 process_response_file(argv[0]+1);
1082 argc--;
1083 argv++;
1085 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1086 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1087 if (p) {
1088 rfile = fopen(p, "r");
1089 if (rfile) {
1090 process_respfile(rfile);
1091 fclose(rfile);
1092 } else
1093 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1094 "unable to open response file `%s'", p);
1096 } else
1097 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1098 argv += advance, argc -= advance;
1101 /* Look for basic command line typos. This definitely doesn't
1102 catch all errors, but it might help cases of fumbled fingers. */
1103 if (!*inname)
1104 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1105 "no input file specified");
1106 else if (!strcmp(inname, errname) ||
1107 !strcmp(inname, outname) ||
1108 !strcmp(inname, listname) ||
1109 (depend_file && !strcmp(inname, depend_file)))
1110 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1111 "file `%s' is both input and output file",
1112 inname);
1114 if (*errname) {
1115 error_file = fopen(errname, "w");
1116 if (!error_file) {
1117 error_file = stderr; /* Revert to default! */
1118 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1119 "cannot open file `%s' for error messages",
1120 errname);
1125 /* List of directives */
1126 enum directives {
1127 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1128 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1130 static const char *directives[] = {
1131 "", "absolute", "bits", "common", "cpu", "debug", "default",
1132 "extern", "float", "global", "list", "section", "segment", "warning"
1134 static enum directives getkw(char **directive, char **value);
1136 static void assemble_file(char *fname, StrList **depend_ptr)
1138 char *directive, *value, *p, *q, *special, *line, debugid[80];
1139 insn output_ins;
1140 int i, validid;
1141 bool rn_error;
1142 int32_t seg;
1143 int64_t offs;
1144 struct tokenval tokval;
1145 expr *e;
1146 int pass_max;
1148 if (cmd_sb == 32 && cmd_cpu < IF_386)
1149 report_error(ERR_FATAL, "command line: "
1150 "32-bit segment size requires a higher cpu");
1152 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1153 for (passn = 1; pass0 <= 2; passn++) {
1154 int pass1, pass2;
1155 ldfunc def_label;
1157 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1158 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1159 /* pass0 0, 0, 0, ..., 1, 2 */
1161 def_label = passn > 1 ? redefine_label : define_label;
1163 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1164 cpu = cmd_cpu;
1165 if (pass0 == 2) {
1166 if (*listname)
1167 nasmlist.init(listname, report_error);
1169 in_abs_seg = false;
1170 global_offset_changed = 0; /* set by redefine_label */
1171 location.segment = ofmt->section(NULL, pass2, &sb);
1172 globalbits = sb;
1173 if (passn > 1) {
1174 saa_rewind(forwrefs);
1175 forwref = saa_rstruct(forwrefs);
1176 raa_free(offsets);
1177 offsets = raa_init();
1179 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1180 pass1 == 2 ? depend_ptr : NULL);
1181 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1183 globallineno = 0;
1184 if (passn == 1)
1185 location.known = true;
1186 location.offset = offs = GET_CURR_OFFS;
1188 while ((line = preproc->getline())) {
1189 enum directives d;
1190 globallineno++;
1192 /* here we parse our directives; this is not handled by the 'real'
1193 * parser. */
1194 directive = line;
1195 d = getkw(&directive, &value);
1196 if (d) {
1197 int err = 0;
1199 switch (d) {
1200 case D_SEGMENT: /* [SEGMENT n] */
1201 case D_SECTION:
1202 seg = ofmt->section(value, pass2, &sb);
1203 if (seg == NO_SEG) {
1204 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1205 "segment name `%s' not recognized",
1206 value);
1207 } else {
1208 in_abs_seg = false;
1209 location.segment = seg;
1211 break;
1212 case D_EXTERN: /* [EXTERN label:special] */
1213 if (*value == '$')
1214 value++; /* skip initial $ if present */
1215 if (pass0 == 2) {
1216 q = value;
1217 while (*q && *q != ':')
1218 q++;
1219 if (*q == ':') {
1220 *q++ = '\0';
1221 ofmt->symdef(value, 0L, 0L, 3, q);
1223 } else if (passn == 1) {
1224 q = value;
1225 validid = true;
1226 if (!isidstart(*q))
1227 validid = false;
1228 while (*q && *q != ':') {
1229 if (!isidchar(*q))
1230 validid = false;
1231 q++;
1233 if (!validid) {
1234 report_error(ERR_NONFATAL,
1235 "identifier expected after EXTERN");
1236 break;
1238 if (*q == ':') {
1239 *q++ = '\0';
1240 special = q;
1241 } else
1242 special = NULL;
1243 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1244 int temp = pass0;
1245 pass0 = 1; /* fake pass 1 in labels.c */
1246 declare_as_global(value, special,
1247 report_error);
1248 define_label(value, seg_alloc(), 0L, NULL,
1249 false, true, ofmt, report_error);
1250 pass0 = temp;
1252 } /* else pass0 == 1 */
1253 break;
1254 case D_BITS: /* [BITS bits] */
1255 globalbits = sb = get_bits(value);
1256 break;
1257 case D_GLOBAL: /* [GLOBAL symbol:special] */
1258 if (*value == '$')
1259 value++; /* skip initial $ if present */
1260 if (pass0 == 2) { /* pass 2 */
1261 q = value;
1262 while (*q && *q != ':')
1263 q++;
1264 if (*q == ':') {
1265 *q++ = '\0';
1266 ofmt->symdef(value, 0L, 0L, 3, q);
1268 } else if (pass2 == 1) { /* pass == 1 */
1269 q = value;
1270 validid = true;
1271 if (!isidstart(*q))
1272 validid = false;
1273 while (*q && *q != ':') {
1274 if (!isidchar(*q))
1275 validid = false;
1276 q++;
1278 if (!validid) {
1279 report_error(ERR_NONFATAL,
1280 "identifier expected after GLOBAL");
1281 break;
1283 if (*q == ':') {
1284 *q++ = '\0';
1285 special = q;
1286 } else
1287 special = NULL;
1288 declare_as_global(value, special, report_error);
1289 } /* pass == 1 */
1290 break;
1291 case D_COMMON: /* [COMMON symbol size:special] */
1292 if (*value == '$')
1293 value++; /* skip initial $ if present */
1294 if (pass0 == 1) {
1295 p = value;
1296 validid = true;
1297 if (!isidstart(*p))
1298 validid = false;
1299 while (*p && !nasm_isspace(*p)) {
1300 if (!isidchar(*p))
1301 validid = false;
1302 p++;
1304 if (!validid) {
1305 report_error(ERR_NONFATAL,
1306 "identifier expected after COMMON");
1307 break;
1309 if (*p) {
1310 int64_t size;
1312 while (*p && nasm_isspace(*p))
1313 *p++ = '\0';
1314 q = p;
1315 while (*q && *q != ':')
1316 q++;
1317 if (*q == ':') {
1318 *q++ = '\0';
1319 special = q;
1320 } else
1321 special = NULL;
1322 size = readnum(p, &rn_error);
1323 if (rn_error)
1324 report_error(ERR_NONFATAL,
1325 "invalid size specified"
1326 " in COMMON declaration");
1327 else
1328 define_common(value, seg_alloc(), size,
1329 special, ofmt, report_error);
1330 } else
1331 report_error(ERR_NONFATAL,
1332 "no size specified in"
1333 " COMMON declaration");
1334 } else if (pass0 == 2) { /* pass == 2 */
1335 q = value;
1336 while (*q && *q != ':') {
1337 if (nasm_isspace(*q))
1338 *q = '\0';
1339 q++;
1341 if (*q == ':') {
1342 *q++ = '\0';
1343 ofmt->symdef(value, 0L, 0L, 3, q);
1346 break;
1347 case D_ABSOLUTE: /* [ABSOLUTE address] */
1348 stdscan_reset();
1349 stdscan_bufptr = value;
1350 tokval.t_type = TOKEN_INVALID;
1351 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1352 report_error, NULL);
1353 if (e) {
1354 if (!is_reloc(e))
1355 report_error(pass0 ==
1356 1 ? ERR_NONFATAL : ERR_PANIC,
1357 "cannot use non-relocatable expression as "
1358 "ABSOLUTE address");
1359 else {
1360 abs_seg = reloc_seg(e);
1361 abs_offset = reloc_value(e);
1363 } else if (passn == 1)
1364 abs_offset = 0x100; /* don't go near zero in case of / */
1365 else
1366 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1367 "in pass two");
1368 in_abs_seg = true;
1369 location.segment = NO_SEG;
1370 break;
1371 case D_DEBUG: /* [DEBUG] */
1372 p = value;
1373 q = debugid;
1374 validid = true;
1375 if (!isidstart(*p))
1376 validid = false;
1377 while (*p && !nasm_isspace(*p)) {
1378 if (!isidchar(*p))
1379 validid = false;
1380 *q++ = *p++;
1382 *q++ = 0;
1383 if (!validid) {
1384 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1385 "identifier expected after DEBUG");
1386 break;
1388 while (*p && nasm_isspace(*p))
1389 p++;
1390 if (pass0 == 2)
1391 ofmt->current_dfmt->debug_directive(debugid, p);
1392 break;
1393 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1394 while (*value && nasm_isspace(*value))
1395 value++;
1397 switch(*value) {
1398 case '-': validid = 0; value++; break;
1399 case '+': validid = 1; value++; break;
1400 case '*': validid = 2; value++; break;
1401 default: validid = 1; break;
1404 for (i = 1; i <= ERR_WARN_MAX; i++)
1405 if (!nasm_stricmp(value, warnings[i].name))
1406 break;
1407 if (i <= ERR_WARN_MAX) {
1408 switch(validid) {
1409 case 0:
1410 warning_on[i] = false;
1411 break;
1412 case 1:
1413 warning_on[i] = true;
1414 break;
1415 case 2:
1416 warning_on[i] = warning_on_global[i];
1417 break;
1420 else
1421 report_error(ERR_NONFATAL,
1422 "invalid warning id in WARNING directive");
1423 break;
1424 case D_CPU: /* [CPU] */
1425 cpu = get_cpu(value);
1426 break;
1427 case D_LIST: /* [LIST {+|-}] */
1428 while (*value && nasm_isspace(*value))
1429 value++;
1431 if (*value == '+') {
1432 user_nolist = 0;
1433 } else {
1434 if (*value == '-') {
1435 user_nolist = 1;
1436 } else {
1437 err = 1;
1440 break;
1441 case D_DEFAULT: /* [DEFAULT] */
1442 stdscan_reset();
1443 stdscan_bufptr = value;
1444 tokval.t_type = TOKEN_INVALID;
1445 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1446 switch ((int)tokval.t_integer) {
1447 case S_REL:
1448 globalrel = 1;
1449 break;
1450 case S_ABS:
1451 globalrel = 0;
1452 break;
1453 default:
1454 err = 1;
1455 break;
1457 } else {
1458 err = 1;
1460 break;
1461 case D_FLOAT:
1462 if (float_option(value)) {
1463 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1464 "unknown 'float' directive: %s",
1465 value);
1467 break;
1468 default:
1469 if (!ofmt->directive(directive, value, pass2))
1470 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1471 "unrecognised directive [%s]",
1472 directive);
1474 if (err) {
1475 report_error(ERR_NONFATAL,
1476 "invalid parameter to [%s] directive",
1477 directive);
1479 } else { /* it isn't a directive */
1481 parse_line(pass1, line, &output_ins,
1482 report_error, evaluate, def_label);
1484 if (optimizing > 0) {
1485 if (forwref != NULL && globallineno == forwref->lineno) {
1486 output_ins.forw_ref = true;
1487 do {
1488 output_ins.oprs[forwref->operand].opflags |=
1489 OPFLAG_FORWARD;
1490 forwref = saa_rstruct(forwrefs);
1491 } while (forwref != NULL
1492 && forwref->lineno == globallineno);
1493 } else
1494 output_ins.forw_ref = false;
1496 if (output_ins.forw_ref) {
1497 if (passn == 1) {
1498 for (i = 0; i < output_ins.operands; i++) {
1499 if (output_ins.oprs[i].
1500 opflags & OPFLAG_FORWARD) {
1501 struct forwrefinfo *fwinf =
1502 (struct forwrefinfo *)
1503 saa_wstruct(forwrefs);
1504 fwinf->lineno = globallineno;
1505 fwinf->operand = i;
1512 /* forw_ref */
1513 if (output_ins.opcode == I_EQU) {
1514 if (pass1 == 1) {
1516 * Special `..' EQUs get processed in pass two,
1517 * except `..@' macro-processor EQUs which are done
1518 * in the normal place.
1520 if (!output_ins.label)
1521 report_error(ERR_NONFATAL,
1522 "EQU not preceded by label");
1524 else if (output_ins.label[0] != '.' ||
1525 output_ins.label[1] != '.' ||
1526 output_ins.label[2] == '@') {
1527 if (output_ins.operands == 1 &&
1528 (output_ins.oprs[0].type & IMMEDIATE) &&
1529 output_ins.oprs[0].wrt == NO_SEG) {
1530 bool isext = !!(output_ins.oprs[0].opflags
1531 & OPFLAG_EXTERN);
1532 def_label(output_ins.label,
1533 output_ins.oprs[0].segment,
1534 output_ins.oprs[0].offset, NULL,
1535 false, isext, ofmt,
1536 report_error);
1537 } else if (output_ins.operands == 2
1538 && (output_ins.oprs[0].type & IMMEDIATE)
1539 && (output_ins.oprs[0].type & COLON)
1540 && output_ins.oprs[0].segment == NO_SEG
1541 && output_ins.oprs[0].wrt == NO_SEG
1542 && (output_ins.oprs[1].type & IMMEDIATE)
1543 && output_ins.oprs[1].segment == NO_SEG
1544 && output_ins.oprs[1].wrt == NO_SEG) {
1545 def_label(output_ins.label,
1546 output_ins.oprs[0].offset | SEG_ABS,
1547 output_ins.oprs[1].offset,
1548 NULL, false, false, ofmt,
1549 report_error);
1550 } else
1551 report_error(ERR_NONFATAL,
1552 "bad syntax for EQU");
1554 } else {
1556 * Special `..' EQUs get processed here, except
1557 * `..@' macro processor EQUs which are done above.
1559 if (output_ins.label[0] == '.' &&
1560 output_ins.label[1] == '.' &&
1561 output_ins.label[2] != '@') {
1562 if (output_ins.operands == 1 &&
1563 (output_ins.oprs[0].type & IMMEDIATE)) {
1564 define_label(output_ins.label,
1565 output_ins.oprs[0].segment,
1566 output_ins.oprs[0].offset,
1567 NULL, false, false, ofmt,
1568 report_error);
1569 } else if (output_ins.operands == 2
1570 && (output_ins.oprs[0].
1571 type & IMMEDIATE)
1572 && (output_ins.oprs[0].type & COLON)
1573 && output_ins.oprs[0].segment ==
1574 NO_SEG
1575 && (output_ins.oprs[1].
1576 type & IMMEDIATE)
1577 && output_ins.oprs[1].segment ==
1578 NO_SEG) {
1579 define_label(output_ins.label,
1580 output_ins.oprs[0].
1581 offset | SEG_ABS,
1582 output_ins.oprs[1].offset,
1583 NULL, false, false, ofmt,
1584 report_error);
1585 } else
1586 report_error(ERR_NONFATAL,
1587 "bad syntax for EQU");
1590 } else { /* instruction isn't an EQU */
1592 if (pass1 == 1) {
1594 int64_t l = insn_size(location.segment, offs, sb, cpu,
1595 &output_ins, report_error);
1597 /* if (using_debug_info) && output_ins.opcode != -1) */
1598 if (using_debug_info)
1599 { /* fbk 03/25/01 */
1600 /* this is done here so we can do debug type info */
1601 int32_t typeinfo =
1602 TYS_ELEMENTS(output_ins.operands);
1603 switch (output_ins.opcode) {
1604 case I_RESB:
1605 typeinfo =
1606 TYS_ELEMENTS(output_ins.oprs[0].
1607 offset) | TY_BYTE;
1608 break;
1609 case I_RESW:
1610 typeinfo =
1611 TYS_ELEMENTS(output_ins.oprs[0].
1612 offset) | TY_WORD;
1613 break;
1614 case I_RESD:
1615 typeinfo =
1616 TYS_ELEMENTS(output_ins.oprs[0].
1617 offset) | TY_DWORD;
1618 break;
1619 case I_RESQ:
1620 typeinfo =
1621 TYS_ELEMENTS(output_ins.oprs[0].
1622 offset) | TY_QWORD;
1623 break;
1624 case I_REST:
1625 typeinfo =
1626 TYS_ELEMENTS(output_ins.oprs[0].
1627 offset) | TY_TBYTE;
1628 break;
1629 case I_RESO:
1630 typeinfo =
1631 TYS_ELEMENTS(output_ins.oprs[0].
1632 offset) | TY_OWORD;
1633 break;
1634 case I_RESY:
1635 typeinfo =
1636 TYS_ELEMENTS(output_ins.oprs[0].
1637 offset) | TY_YWORD;
1638 break;
1639 case I_DB:
1640 typeinfo |= TY_BYTE;
1641 break;
1642 case I_DW:
1643 typeinfo |= TY_WORD;
1644 break;
1645 case I_DD:
1646 if (output_ins.eops_float)
1647 typeinfo |= TY_FLOAT;
1648 else
1649 typeinfo |= TY_DWORD;
1650 break;
1651 case I_DQ:
1652 typeinfo |= TY_QWORD;
1653 break;
1654 case I_DT:
1655 typeinfo |= TY_TBYTE;
1656 break;
1657 case I_DO:
1658 typeinfo |= TY_OWORD;
1659 break;
1660 case I_DY:
1661 typeinfo |= TY_YWORD;
1662 break;
1663 default:
1664 typeinfo = TY_LABEL;
1668 ofmt->current_dfmt->debug_typevalue(typeinfo);
1671 if (l != -1) {
1672 offs += l;
1673 SET_CURR_OFFS(offs);
1676 * else l == -1 => invalid instruction, which will be
1677 * flagged as an error on pass 2
1680 } else {
1681 offs += assemble(location.segment, offs, sb, cpu,
1682 &output_ins, ofmt, report_error,
1683 &nasmlist);
1684 SET_CURR_OFFS(offs);
1687 } /* not an EQU */
1688 cleanup_insn(&output_ins);
1690 nasm_free(line);
1691 location.offset = offs = GET_CURR_OFFS;
1692 } /* end while (line = preproc->getline... */
1693 if (pass1 == 2 && global_offset_changed)
1694 report_error(ERR_NONFATAL,
1695 "phase error detected at end of assembly.");
1697 if (pass1 == 1)
1698 preproc->cleanup(1);
1700 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1701 pass0++;
1702 } else if (global_offset_changed &&
1703 global_offset_changed < prev_offset_changed) {
1704 prev_offset_changed = global_offset_changed;
1705 stall_count = 0;
1706 } else {
1707 stall_count++;
1710 if (terminate_after_phase)
1711 break;
1713 if ((stall_count > 997) || (passn >= pass_max)) {
1714 /* We get here if the labels don't converge
1715 * Example: FOO equ FOO + 1
1717 report_error(ERR_NONFATAL,
1718 "Can't find valid values for all labels "
1719 "after %d passes, giving up.", passn);
1720 report_error(ERR_NONFATAL,
1721 "Possible causes: recursive EQUs, macro abuse.");
1722 terminate_after_phase = true;
1723 break;
1727 preproc->cleanup(0);
1728 nasmlist.cleanup();
1729 if (!terminate_after_phase && opt_verbose_info) {
1730 /* -On and -Ov switches */
1731 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1735 static enum directives getkw(char **directive, char **value)
1737 char *p, *q, *buf;
1739 buf = *directive;
1741 /* allow leading spaces or tabs */
1742 while (*buf == ' ' || *buf == '\t')
1743 buf++;
1745 if (*buf != '[')
1746 return 0;
1748 p = buf;
1750 while (*p && *p != ']')
1751 p++;
1753 if (!*p)
1754 return 0;
1756 q = p++;
1758 while (*p && *p != ';') {
1759 if (!nasm_isspace(*p))
1760 return 0;
1761 p++;
1763 q[1] = '\0';
1765 *directive = p = buf + 1;
1766 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1767 buf++;
1768 if (*buf == ']') {
1769 *buf = '\0';
1770 *value = buf;
1771 } else {
1772 *buf++ = '\0';
1773 while (nasm_isspace(*buf))
1774 buf++; /* beppu - skip leading whitespace */
1775 *value = buf;
1776 while (*buf != ']')
1777 buf++;
1778 *buf++ = '\0';
1781 return bsii(*directive, directives, elements(directives));
1785 * gnu style error reporting
1786 * This function prints an error message to error_file in the
1787 * style used by GNU. An example would be:
1788 * file.asm:50: error: blah blah blah
1789 * where file.asm is the name of the file, 50 is the line number on
1790 * which the error occurs (or is detected) and "error:" is one of
1791 * the possible optional diagnostics -- it can be "error" or "warning"
1792 * or something else. Finally the line terminates with the actual
1793 * error message.
1795 * @param severity the severity of the warning or error
1796 * @param fmt the printf style format string
1798 static void report_error_gnu(int severity, const char *fmt, ...)
1800 va_list ap;
1802 if (is_suppressed_warning(severity))
1803 return;
1805 if (severity & ERR_NOFILE)
1806 fputs("nasm: ", error_file);
1807 else {
1808 char *currentfile = NULL;
1809 int32_t lineno = 0;
1810 src_get(&lineno, &currentfile);
1811 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1812 nasm_free(currentfile);
1814 va_start(ap, fmt);
1815 report_error_common(severity, fmt, ap);
1816 va_end(ap);
1820 * MS style error reporting
1821 * This function prints an error message to error_file in the
1822 * style used by Visual C and some other Microsoft tools. An example
1823 * would be:
1824 * file.asm(50) : error: blah blah blah
1825 * where file.asm is the name of the file, 50 is the line number on
1826 * which the error occurs (or is detected) and "error:" is one of
1827 * the possible optional diagnostics -- it can be "error" or "warning"
1828 * or something else. Finally the line terminates with the actual
1829 * error message.
1831 * @param severity the severity of the warning or error
1832 * @param fmt the printf style format string
1834 static void report_error_vc(int severity, const char *fmt, ...)
1836 va_list ap;
1838 if (is_suppressed_warning(severity))
1839 return;
1841 if (severity & ERR_NOFILE)
1842 fputs("nasm: ", error_file);
1843 else {
1844 char *currentfile = NULL;
1845 int32_t lineno = 0;
1846 src_get(&lineno, &currentfile);
1847 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1848 nasm_free(currentfile);
1850 va_start(ap, fmt);
1851 report_error_common(severity, fmt, ap);
1852 va_end(ap);
1856 * check for supressed warning
1857 * checks for suppressed warning or pass one only warning and we're
1858 * not in pass 1
1860 * @param severity the severity of the warning or error
1861 * @return true if we should abort error/warning printing
1863 static bool is_suppressed_warning(int severity)
1866 * See if it's a suppressed warning.
1868 return (severity & ERR_MASK) == ERR_WARNING &&
1869 (((severity & ERR_WARN_MASK) != 0 &&
1870 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1871 /* See if it's a pass-one only warning and we're not in pass one. */
1872 ((severity & ERR_PASS1) && pass0 != 1) ||
1873 ((severity & ERR_PASS2) && pass0 != 2));
1877 * common error reporting
1878 * This is the common back end of the error reporting schemes currently
1879 * implemented. It prints the nature of the warning and then the
1880 * specific error message to error_file and may or may not return. It
1881 * doesn't return if the error severity is a "panic" or "debug" type.
1883 * @param severity the severity of the warning or error
1884 * @param fmt the printf style format string
1886 static void report_error_common(int severity, const char *fmt,
1887 va_list args)
1889 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1890 case ERR_WARNING:
1891 fputs("warning: ", error_file);
1892 break;
1893 case ERR_NONFATAL:
1894 fputs("error: ", error_file);
1895 break;
1896 case ERR_FATAL:
1897 fputs("fatal: ", error_file);
1898 break;
1899 case ERR_PANIC:
1900 fputs("panic: ", error_file);
1901 break;
1902 case ERR_DEBUG:
1903 fputs("debug: ", error_file);
1904 break;
1905 default:
1906 break;
1909 vfprintf(error_file, fmt, args);
1910 putc('\n', error_file);
1912 if (severity & ERR_USAGE)
1913 want_usage = true;
1915 switch (severity & ERR_MASK) {
1916 case ERR_DEBUG:
1917 /* no further action, by definition */
1918 break;
1919 case ERR_WARNING:
1920 if (warning_on[0]) /* Treat warnings as errors */
1921 terminate_after_phase = true;
1922 break;
1923 case ERR_NONFATAL:
1924 terminate_after_phase = true;
1925 break;
1926 case ERR_FATAL:
1927 if (ofile) {
1928 fclose(ofile);
1929 remove(outname);
1931 if (want_usage)
1932 usage();
1933 exit(1); /* instantly die */
1934 break; /* placate silly compilers */
1935 case ERR_PANIC:
1936 fflush(NULL);
1937 /* abort(); *//* halt, catch fire, and dump core */
1938 exit(3);
1939 break;
1943 static void usage(void)
1945 fputs("type `nasm -h' for help\n", error_file);
1948 static void register_output_formats(void)
1950 ofmt = ofmt_register(report_error);
1953 #define BUF_DELTA 512
1955 static FILE *no_pp_fp;
1956 static efunc no_pp_err;
1957 static ListGen *no_pp_list;
1958 static int32_t no_pp_lineinc;
1960 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1961 ListGen * listgen, StrList **deplist)
1963 src_set_fname(nasm_strdup(file));
1964 src_set_linnum(0);
1965 no_pp_lineinc = 1;
1966 no_pp_err = error;
1967 no_pp_fp = fopen(file, "r");
1968 if (!no_pp_fp)
1969 no_pp_err(ERR_FATAL | ERR_NOFILE,
1970 "unable to open input file `%s'", file);
1971 no_pp_list = listgen;
1972 (void)pass; /* placate compilers */
1973 (void)eval; /* placate compilers */
1975 if (deplist) {
1976 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1977 sl->next = NULL;
1978 strcpy(sl->str, file);
1979 *deplist = sl;
1983 static char *no_pp_getline(void)
1985 char *buffer, *p, *q;
1986 int bufsize;
1988 bufsize = BUF_DELTA;
1989 buffer = nasm_malloc(BUF_DELTA);
1990 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1992 while (1) { /* Loop to handle %line */
1994 p = buffer;
1995 while (1) { /* Loop to handle long lines */
1996 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
1997 if (!q)
1998 break;
1999 p += strlen(p);
2000 if (p > buffer && p[-1] == '\n')
2001 break;
2002 if (p - buffer > bufsize - 10) {
2003 int offset;
2004 offset = p - buffer;
2005 bufsize += BUF_DELTA;
2006 buffer = nasm_realloc(buffer, bufsize);
2007 p = buffer + offset;
2011 if (!q && p == buffer) {
2012 nasm_free(buffer);
2013 return NULL;
2017 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2018 * them are present at the end of the line.
2020 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2022 if (!nasm_strnicmp(buffer, "%line", 5)) {
2023 int32_t ln;
2024 int li;
2025 char *nm = nasm_malloc(strlen(buffer));
2026 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2027 nasm_free(src_set_fname(nm));
2028 src_set_linnum(ln);
2029 no_pp_lineinc = li;
2030 continue;
2032 nasm_free(nm);
2034 break;
2037 no_pp_list->line(LIST_READ, buffer);
2039 return buffer;
2042 static void no_pp_cleanup(int pass)
2044 (void)pass; /* placate GCC */
2045 fclose(no_pp_fp);
2048 static uint32_t get_cpu(char *value)
2050 if (!strcmp(value, "8086"))
2051 return IF_8086;
2052 if (!strcmp(value, "186"))
2053 return IF_186;
2054 if (!strcmp(value, "286"))
2055 return IF_286;
2056 if (!strcmp(value, "386"))
2057 return IF_386;
2058 if (!strcmp(value, "486"))
2059 return IF_486;
2060 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2061 return IF_PENT;
2062 if (!strcmp(value, "686") ||
2063 !nasm_stricmp(value, "ppro") ||
2064 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2065 return IF_P6;
2066 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2067 return IF_KATMAI;
2068 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2069 !nasm_stricmp(value, "willamette"))
2070 return IF_WILLAMETTE;
2071 if (!nasm_stricmp(value, "prescott"))
2072 return IF_PRESCOTT;
2073 if (!nasm_stricmp(value, "x64") ||
2074 !nasm_stricmp(value, "x86-64"))
2075 return IF_X86_64;
2076 if (!nasm_stricmp(value, "ia64") ||
2077 !nasm_stricmp(value, "ia-64") ||
2078 !nasm_stricmp(value, "itanium") ||
2079 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2080 return IF_IA64;
2082 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2083 "unknown 'cpu' type");
2085 return IF_PLEVEL; /* the maximum level */
2088 static int get_bits(char *value)
2090 int i;
2092 if ((i = atoi(value)) == 16)
2093 return i; /* set for a 16-bit segment */
2094 else if (i == 32) {
2095 if (cpu < IF_386) {
2096 report_error(ERR_NONFATAL,
2097 "cannot specify 32-bit segment on processor below a 386");
2098 i = 16;
2100 } else if (i == 64) {
2101 if (cpu < IF_X86_64) {
2102 report_error(ERR_NONFATAL,
2103 "cannot specify 64-bit segment on processor below an x86-64");
2104 i = 16;
2106 if (i != maxbits) {
2107 report_error(ERR_NONFATAL,
2108 "%s output format does not support 64-bit code",
2109 ofmt->shortname);
2110 i = 16;
2112 } else {
2113 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2114 "`%s' is not a valid segment size; must be 16, 32 or 64",
2115 value);
2116 i = 16;
2118 return i;
2121 /* end of nasm.c */