BR 2148448: Fix RIP-relative addressing with an immediate
[nasm.git] / nasm.c
blob76d1eee0526bfd5e20feba5eec7812a6b74f5ed3
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 constants does not fit in 64 bits", 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 int want_usage;
154 static int 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)
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 if (terminate_after_phase)
466 return 1;
467 else
468 return 0;
472 * Get a parameter for a command line option.
473 * First arg must be in the form of e.g. -f...
475 static char *get_param(char *p, char *q, bool *advance)
477 *advance = false;
478 if (p[2]) { /* the parameter's in the option */
479 p += 2;
480 while (nasm_isspace(*p))
481 p++;
482 return p;
484 if (q && q[0]) {
485 *advance = true;
486 return q;
488 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
489 "option `-%c' requires an argument", p[1]);
490 return NULL;
494 * Copy a filename
496 static void copy_filename(char *dst, const char *src)
498 size_t len = strlen(src);
500 if (len >= (size_t)FILENAME_MAX) {
501 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
502 return;
504 strncpy(dst, src, FILENAME_MAX);
508 * Convert a string to Make-safe form
510 static char *quote_for_make(const char *str)
512 const char *p;
513 char *os, *q;
515 size_t n = 1; /* Terminating zero */
516 size_t nbs = 0;
518 if (!str)
519 return NULL;
521 for (p = str; *p; p++) {
522 switch (*p) {
523 case ' ':
524 case '\t':
525 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
526 n += nbs + 2;
527 nbs = 0;
528 break;
529 case '$':
530 case '#':
531 nbs = 0;
532 n += 2;
533 break;
534 case '\\':
535 nbs++;
536 n++;
537 break;
538 default:
539 nbs = 0;
540 n++;
541 break;
545 /* Convert N backslashes at the end of filename to 2N backslashes */
546 if (nbs)
547 n += nbs;
549 os = q = nasm_malloc(n);
551 nbs = 0;
552 for (p = str; *p; p++) {
553 switch (*p) {
554 case ' ':
555 case '\t':
556 while (nbs--)
557 *q++ = '\\';
558 *q++ = '\\';
559 *q++ = *p;
560 break;
561 case '$':
562 *q++ = *p;
563 *q++ = *p;
564 nbs = 0;
565 break;
566 case '#':
567 *q++ = '\\';
568 *q++ = *p;
569 nbs = 0;
570 break;
571 case '\\':
572 *q++ = *p;
573 nbs++;
574 break;
575 default:
576 *q++ = *p;
577 nbs = 0;
578 break;
581 while (nbs--)
582 *q++ = '\\';
584 *q = '\0';
586 return os;
589 struct textargs {
590 const char *label;
591 int value;
594 #define OPT_PREFIX 0
595 #define OPT_POSTFIX 1
596 struct textargs textopts[] = {
597 {"prefix", OPT_PREFIX},
598 {"postfix", OPT_POSTFIX},
599 {NULL, 0}
602 static bool stopoptions = false;
603 static bool process_arg(char *p, char *q)
605 char *param;
606 int i;
607 bool advance = false;
608 bool do_warn;
610 if (!p || !p[0])
611 return false;
613 if (p[0] == '-' && !stopoptions) {
614 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
615 /* These parameters take values */
616 if (!(param = get_param(p, q, &advance)))
617 return advance;
620 switch (p[1]) {
621 case 's':
622 error_file = stdout;
623 break;
625 case 'o': /* output file */
626 copy_filename(outname, param);
627 break;
629 case 'f': /* output format */
630 ofmt = ofmt_find(param);
631 if (!ofmt) {
632 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
633 "unrecognised output format `%s' - "
634 "use -hf for a list", param);
635 } else {
636 ofmt->current_dfmt = ofmt->debug_formats[0];
638 break;
640 case 'O': /* Optimization level */
642 int opt;
644 if (!*param) {
645 /* Naked -O == -Ox */
646 optimizing = INT_MAX >> 1; /* Almost unlimited */
647 } else {
648 while (*param) {
649 switch (*param) {
650 case '0': case '1': case '2': case '3': case '4':
651 case '5': case '6': case '7': case '8': case '9':
652 opt = strtoul(param, &param, 10);
654 /* -O0 -> optimizing == -1, 0.98 behaviour */
655 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
656 if (opt < 2)
657 optimizing = opt - 1;
658 else
659 optimizing = opt;
660 break;
662 case 'v':
663 case '+':
664 param++;
665 opt_verbose_info = true;
666 break;
668 case 'x':
669 param++;
670 optimizing = INT_MAX >> 1; /* Almost unlimited */
671 break;
673 default:
674 report_error(ERR_FATAL,
675 "unknown optimization option -O%c\n",
676 *param);
677 break;
681 break;
684 case 'p': /* pre-include */
685 case 'P':
686 pp_pre_include(param);
687 break;
689 case 'd': /* pre-define */
690 case 'D':
691 pp_pre_define(param);
692 break;
694 case 'u': /* un-define */
695 case 'U':
696 pp_pre_undefine(param);
697 break;
699 case 'i': /* include search path */
700 case 'I':
701 pp_include_path(param);
702 break;
704 case 'l': /* listing file */
705 copy_filename(listname, param);
706 break;
708 case 'Z': /* error messages file */
709 strcpy(errname, param);
710 break;
712 case 'F': /* specify debug format */
713 ofmt->current_dfmt = dfmt_find(ofmt, param);
714 if (!ofmt->current_dfmt) {
715 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
716 "unrecognized debug format `%s' for"
717 " output format `%s'",
718 param, ofmt->shortname);
720 using_debug_info = true;
721 break;
723 case 'X': /* specify error reporting format */
724 if (nasm_stricmp("vc", param) == 0)
725 report_error = report_error_vc;
726 else if (nasm_stricmp("gnu", param) == 0)
727 report_error = report_error_gnu;
728 else
729 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
730 "unrecognized error reporting format `%s'",
731 param);
732 break;
734 case 'g':
735 using_debug_info = true;
736 break;
738 case 'h':
739 printf
740 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
741 "[-l listfile]\n"
742 " [options...] [--] filename\n"
743 " or nasm -v for version info\n\n"
744 " -t assemble in SciTech TASM compatible mode\n"
745 " -g generate debug information in selected format.\n");
746 printf
747 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
748 " -a don't preprocess (assemble only)\n"
749 " -M generate Makefile dependencies on stdout\n"
750 " -MG d:o, missing files assumed generated\n\n"
751 " -Z<file> redirect error messages to file\n"
752 " -s redirect error messages to stdout\n\n"
753 " -F format select a debugging format\n\n"
754 " -I<path> adds a pathname to the include file path\n");
755 printf
756 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
757 " -P<file> pre-includes a file\n"
758 " -D<macro>[=<value>] pre-defines a macro\n"
759 " -U<macro> undefines a macro\n"
760 " -X<format> specifies error reporting format (gnu or vc)\n"
761 " -w+foo enables warning foo (equiv. -Wfoo)\n"
762 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
763 "Warnings:\n");
764 for (i = 0; i <= ERR_WARN_MAX; i++)
765 printf(" %-23s %s (default %s)\n",
766 warnings[i].name, warnings[i].help,
767 warnings[i].enabled ? "on" : "off");
768 printf
769 ("\nresponse files should contain command line parameters"
770 ", one per line.\n");
771 if (p[2] == 'f') {
772 printf("\nvalid output formats for -f are"
773 " (`*' denotes default):\n");
774 ofmt_list(ofmt, stdout);
775 } else {
776 printf("\nFor a list of valid output formats, use -hf.\n");
777 printf("For a list of debug formats, use -f <form> -y.\n");
779 exit(0); /* never need usage message here */
780 break;
782 case 'y':
783 printf("\nvalid debug formats for '%s' output format are"
784 " ('*' denotes default):\n", ofmt->shortname);
785 dfmt_list(ofmt, stdout);
786 exit(0);
787 break;
789 case 't':
790 tasm_compatible_mode = true;
791 break;
793 case 'v':
795 const char *nasm_version_string =
796 "NASM version " NASM_VER " compiled on " __DATE__
797 #ifdef DEBUG
798 " with -DDEBUG"
799 #endif
801 puts(nasm_version_string);
802 exit(0); /* never need usage message here */
804 break;
806 case 'e': /* preprocess only */
807 case 'E':
808 operating_mode = op_preprocess;
809 break;
811 case 'a': /* assemble only - don't preprocess */
812 preproc = &no_pp;
813 break;
815 case 'W':
816 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
817 do_warn = false;
818 param += 3;
819 } else {
820 do_warn = true;
822 goto set_warning;
824 case 'w':
825 if (param[0] != '+' && param[0] != '-') {
826 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
827 "invalid option to `-w'");
828 break;
830 do_warn = (param[0] == '+');
831 param++;
832 goto set_warning;
833 set_warning:
834 for (i = 0; i <= ERR_WARN_MAX; i++)
835 if (!nasm_stricmp(param, warnings[i].name))
836 break;
837 if (i <= ERR_WARN_MAX)
838 warning_on[i] = do_warn;
839 else if (!nasm_stricmp(param, "all"))
840 for (i = 1; i <= ERR_WARN_MAX; i++)
841 warning_on[i] = do_warn;
842 else if (!nasm_stricmp(param, "none"))
843 for (i = 1; i <= ERR_WARN_MAX; i++)
844 warning_on[i] = !do_warn;
845 else
846 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
847 "invalid warning `%s'", param);
848 break;
850 case 'M':
851 switch (p[2]) {
852 case 0:
853 operating_mode = op_depend;
854 break;
855 case 'G':
856 operating_mode = op_depend;
857 depend_missing_ok = true;
858 break;
859 case 'P':
860 depend_emit_phony = true;
861 break;
862 case 'D':
863 depend_file = q;
864 advance = true;
865 break;
866 case 'T':
867 depend_target = q;
868 advance = true;
869 break;
870 case 'Q':
871 depend_target = quote_for_make(q);
872 advance = true;
873 break;
874 default:
875 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
876 "unknown dependency option `-M%c'", p[2]);
877 break;
879 if (advance && (!q || !q[0])) {
880 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
881 "option `-M%c' requires a parameter", p[2]);
882 break;
884 break;
886 case '-':
888 int s;
890 if (p[2] == 0) { /* -- => stop processing options */
891 stopoptions = 1;
892 break;
894 for (s = 0; textopts[s].label; s++) {
895 if (!nasm_stricmp(p + 2, textopts[s].label)) {
896 break;
900 switch (s) {
902 case OPT_PREFIX:
903 case OPT_POSTFIX:
905 if (!q) {
906 report_error(ERR_NONFATAL | ERR_NOFILE |
907 ERR_USAGE,
908 "option `--%s' requires an argument",
909 p + 2);
910 break;
911 } else {
912 advance = 1, param = q;
915 if (s == OPT_PREFIX) {
916 strncpy(lprefix, param, PREFIX_MAX - 1);
917 lprefix[PREFIX_MAX - 1] = 0;
918 break;
920 if (s == OPT_POSTFIX) {
921 strncpy(lpostfix, param, POSTFIX_MAX - 1);
922 lpostfix[POSTFIX_MAX - 1] = 0;
923 break;
925 break;
927 default:
929 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
930 "unrecognised option `--%s'", p + 2);
931 break;
934 break;
937 default:
938 if (!ofmt->setinfo(GI_SWITCH, &p))
939 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
940 "unrecognised option `-%c'", p[1]);
941 break;
943 } else {
944 if (*inname) {
945 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
946 "more than one input file specified");
947 } else {
948 copy_filename(inname, p);
952 return advance;
955 #define ARG_BUF_DELTA 128
957 static void process_respfile(FILE * rfile)
959 char *buffer, *p, *q, *prevarg;
960 int bufsize, prevargsize;
962 bufsize = prevargsize = ARG_BUF_DELTA;
963 buffer = nasm_malloc(ARG_BUF_DELTA);
964 prevarg = nasm_malloc(ARG_BUF_DELTA);
965 prevarg[0] = '\0';
967 while (1) { /* Loop to handle all lines in file */
968 p = buffer;
969 while (1) { /* Loop to handle long lines */
970 q = fgets(p, bufsize - (p - buffer), rfile);
971 if (!q)
972 break;
973 p += strlen(p);
974 if (p > buffer && p[-1] == '\n')
975 break;
976 if (p - buffer > bufsize - 10) {
977 int offset;
978 offset = p - buffer;
979 bufsize += ARG_BUF_DELTA;
980 buffer = nasm_realloc(buffer, bufsize);
981 p = buffer + offset;
985 if (!q && p == buffer) {
986 if (prevarg[0])
987 process_arg(prevarg, NULL);
988 nasm_free(buffer);
989 nasm_free(prevarg);
990 return;
994 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
995 * them are present at the end of the line.
997 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
999 while (p > buffer && nasm_isspace(p[-1]))
1000 *--p = '\0';
1002 p = buffer;
1003 while (nasm_isspace(*p))
1004 p++;
1006 if (process_arg(prevarg, p))
1007 *p = '\0';
1009 if ((int) strlen(p) > prevargsize - 10) {
1010 prevargsize += ARG_BUF_DELTA;
1011 prevarg = nasm_realloc(prevarg, prevargsize);
1013 strncpy(prevarg, p, prevargsize);
1017 /* Function to process args from a string of args, rather than the
1018 * argv array. Used by the environment variable and response file
1019 * processing.
1021 static void process_args(char *args)
1023 char *p, *q, *arg, *prevarg;
1024 char separator = ' ';
1026 p = args;
1027 if (*p && *p != '-')
1028 separator = *p++;
1029 arg = NULL;
1030 while (*p) {
1031 q = p;
1032 while (*p && *p != separator)
1033 p++;
1034 while (*p == separator)
1035 *p++ = '\0';
1036 prevarg = arg;
1037 arg = q;
1038 if (process_arg(prevarg, arg))
1039 arg = NULL;
1041 if (arg)
1042 process_arg(arg, NULL);
1045 static void process_response_file(const char *file)
1047 char str[2048];
1048 FILE *f = fopen(file, "r");
1049 if (!f) {
1050 perror(file);
1051 exit(-1);
1053 while (fgets(str, sizeof str, f)) {
1054 process_args(str);
1056 fclose(f);
1059 static void parse_cmdline(int argc, char **argv)
1061 FILE *rfile;
1062 char *envreal, *envcopy = NULL, *p, *arg;
1063 int i;
1065 *inname = *outname = *listname = *errname = '\0';
1066 for (i = 0; i <= ERR_WARN_MAX; i++)
1067 warning_on_global[i] = warnings[i].enabled;
1070 * First, process the NASMENV environment variable.
1072 envreal = getenv("NASMENV");
1073 arg = NULL;
1074 if (envreal) {
1075 envcopy = nasm_strdup(envreal);
1076 process_args(envcopy);
1077 nasm_free(envcopy);
1081 * Now process the actual command line.
1083 while (--argc) {
1084 bool advance;
1085 argv++;
1086 if (argv[0][0] == '@') {
1087 /* We have a response file, so process this as a set of
1088 * arguments like the environment variable. This allows us
1089 * to have multiple arguments on a single line, which is
1090 * different to the -@resp file processing below for regular
1091 * NASM.
1093 process_response_file(argv[0]+1);
1094 argc--;
1095 argv++;
1097 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1098 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1099 if (p) {
1100 rfile = fopen(p, "r");
1101 if (rfile) {
1102 process_respfile(rfile);
1103 fclose(rfile);
1104 } else
1105 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1106 "unable to open response file `%s'", p);
1108 } else
1109 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1110 argv += advance, argc -= advance;
1113 /* Look for basic command line typos. This definitely doesn't
1114 catch all errors, but it might help cases of fumbled fingers. */
1115 if (!*inname)
1116 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1117 "no input file specified");
1118 else if (!strcmp(inname, errname) ||
1119 !strcmp(inname, outname) ||
1120 !strcmp(inname, listname) ||
1121 (depend_file && !strcmp(inname, depend_file)))
1122 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1123 "file `%s' is both input and output file",
1124 inname);
1126 if (*errname) {
1127 error_file = fopen(errname, "w");
1128 if (!error_file) {
1129 error_file = stderr; /* Revert to default! */
1130 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1131 "cannot open file `%s' for error messages",
1132 errname);
1137 /* List of directives */
1138 enum directives {
1139 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1140 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1142 static const char *directives[] = {
1143 "", "absolute", "bits", "common", "cpu", "debug", "default",
1144 "extern", "float", "global", "list", "section", "segment", "warning"
1146 static enum directives getkw(char **directive, char **value);
1148 static void assemble_file(char *fname, StrList **depend_ptr)
1150 char *directive, *value, *p, *q, *special, *line, debugid[80];
1151 insn output_ins;
1152 int i, validid;
1153 bool rn_error;
1154 int32_t seg;
1155 int64_t offs;
1156 struct tokenval tokval;
1157 expr *e;
1158 int pass_max;
1160 if (cmd_sb == 32 && cmd_cpu < IF_386)
1161 report_error(ERR_FATAL, "command line: "
1162 "32-bit segment size requires a higher cpu");
1164 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1165 for (passn = 1; pass0 <= 2; passn++) {
1166 int pass1, pass2;
1167 ldfunc def_label;
1169 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1170 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1171 /* pass0 0, 0, 0, ..., 1, 2 */
1173 def_label = passn > 1 ? redefine_label : define_label;
1175 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1176 cpu = cmd_cpu;
1177 if (pass0 == 2) {
1178 if (*listname)
1179 nasmlist.init(listname, report_error);
1181 in_abs_seg = false;
1182 global_offset_changed = 0; /* set by redefine_label */
1183 location.segment = ofmt->section(NULL, pass2, &sb);
1184 globalbits = sb;
1185 if (passn > 1) {
1186 saa_rewind(forwrefs);
1187 forwref = saa_rstruct(forwrefs);
1188 raa_free(offsets);
1189 offsets = raa_init();
1191 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1192 pass1 == 2 ? depend_ptr : NULL);
1193 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1195 globallineno = 0;
1196 if (passn == 1)
1197 location.known = true;
1198 location.offset = offs = GET_CURR_OFFS;
1200 while ((line = preproc->getline())) {
1201 enum directives d;
1202 globallineno++;
1204 /* here we parse our directives; this is not handled by the 'real'
1205 * parser. */
1206 directive = line;
1207 d = getkw(&directive, &value);
1208 if (d) {
1209 int err = 0;
1211 switch (d) {
1212 case D_SEGMENT: /* [SEGMENT n] */
1213 case D_SECTION:
1214 seg = ofmt->section(value, pass2, &sb);
1215 if (seg == NO_SEG) {
1216 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1217 "segment name `%s' not recognized",
1218 value);
1219 } else {
1220 in_abs_seg = false;
1221 location.segment = seg;
1223 break;
1224 case D_EXTERN: /* [EXTERN label:special] */
1225 if (*value == '$')
1226 value++; /* skip initial $ if present */
1227 if (pass0 == 2) {
1228 q = value;
1229 while (*q && *q != ':')
1230 q++;
1231 if (*q == ':') {
1232 *q++ = '\0';
1233 ofmt->symdef(value, 0L, 0L, 3, q);
1235 } else if (passn == 1) {
1236 q = value;
1237 validid = true;
1238 if (!isidstart(*q))
1239 validid = false;
1240 while (*q && *q != ':') {
1241 if (!isidchar(*q))
1242 validid = false;
1243 q++;
1245 if (!validid) {
1246 report_error(ERR_NONFATAL,
1247 "identifier expected after EXTERN");
1248 break;
1250 if (*q == ':') {
1251 *q++ = '\0';
1252 special = q;
1253 } else
1254 special = NULL;
1255 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1256 int temp = pass0;
1257 pass0 = 1; /* fake pass 1 in labels.c */
1258 declare_as_global(value, special,
1259 report_error);
1260 define_label(value, seg_alloc(), 0L, NULL,
1261 false, true, ofmt, report_error);
1262 pass0 = temp;
1264 } /* else pass0 == 1 */
1265 break;
1266 case D_BITS: /* [BITS bits] */
1267 globalbits = sb = get_bits(value);
1268 break;
1269 case D_GLOBAL: /* [GLOBAL symbol:special] */
1270 if (*value == '$')
1271 value++; /* skip initial $ if present */
1272 if (pass0 == 2) { /* pass 2 */
1273 q = value;
1274 while (*q && *q != ':')
1275 q++;
1276 if (*q == ':') {
1277 *q++ = '\0';
1278 ofmt->symdef(value, 0L, 0L, 3, q);
1280 } else if (pass2 == 1) { /* pass == 1 */
1281 q = value;
1282 validid = true;
1283 if (!isidstart(*q))
1284 validid = false;
1285 while (*q && *q != ':') {
1286 if (!isidchar(*q))
1287 validid = false;
1288 q++;
1290 if (!validid) {
1291 report_error(ERR_NONFATAL,
1292 "identifier expected after GLOBAL");
1293 break;
1295 if (*q == ':') {
1296 *q++ = '\0';
1297 special = q;
1298 } else
1299 special = NULL;
1300 declare_as_global(value, special, report_error);
1301 } /* pass == 1 */
1302 break;
1303 case D_COMMON: /* [COMMON symbol size:special] */
1304 if (*value == '$')
1305 value++; /* skip initial $ if present */
1306 if (pass0 == 1) {
1307 p = value;
1308 validid = true;
1309 if (!isidstart(*p))
1310 validid = false;
1311 while (*p && !nasm_isspace(*p)) {
1312 if (!isidchar(*p))
1313 validid = false;
1314 p++;
1316 if (!validid) {
1317 report_error(ERR_NONFATAL,
1318 "identifier expected after COMMON");
1319 break;
1321 if (*p) {
1322 int64_t size;
1324 while (*p && nasm_isspace(*p))
1325 *p++ = '\0';
1326 q = p;
1327 while (*q && *q != ':')
1328 q++;
1329 if (*q == ':') {
1330 *q++ = '\0';
1331 special = q;
1332 } else
1333 special = NULL;
1334 size = readnum(p, &rn_error);
1335 if (rn_error)
1336 report_error(ERR_NONFATAL,
1337 "invalid size specified"
1338 " in COMMON declaration");
1339 else
1340 define_common(value, seg_alloc(), size,
1341 special, ofmt, report_error);
1342 } else
1343 report_error(ERR_NONFATAL,
1344 "no size specified in"
1345 " COMMON declaration");
1346 } else if (pass0 == 2) { /* pass == 2 */
1347 q = value;
1348 while (*q && *q != ':') {
1349 if (nasm_isspace(*q))
1350 *q = '\0';
1351 q++;
1353 if (*q == ':') {
1354 *q++ = '\0';
1355 ofmt->symdef(value, 0L, 0L, 3, q);
1358 break;
1359 case D_ABSOLUTE: /* [ABSOLUTE address] */
1360 stdscan_reset();
1361 stdscan_bufptr = value;
1362 tokval.t_type = TOKEN_INVALID;
1363 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1364 report_error, NULL);
1365 if (e) {
1366 if (!is_reloc(e))
1367 report_error(pass0 ==
1368 1 ? ERR_NONFATAL : ERR_PANIC,
1369 "cannot use non-relocatable expression as "
1370 "ABSOLUTE address");
1371 else {
1372 abs_seg = reloc_seg(e);
1373 abs_offset = reloc_value(e);
1375 } else if (passn == 1)
1376 abs_offset = 0x100; /* don't go near zero in case of / */
1377 else
1378 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1379 "in pass two");
1380 in_abs_seg = true;
1381 location.segment = NO_SEG;
1382 break;
1383 case D_DEBUG: /* [DEBUG] */
1384 p = value;
1385 q = debugid;
1386 validid = true;
1387 if (!isidstart(*p))
1388 validid = false;
1389 while (*p && !nasm_isspace(*p)) {
1390 if (!isidchar(*p))
1391 validid = false;
1392 *q++ = *p++;
1394 *q++ = 0;
1395 if (!validid) {
1396 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1397 "identifier expected after DEBUG");
1398 break;
1400 while (*p && nasm_isspace(*p))
1401 p++;
1402 if (pass0 == 2)
1403 ofmt->current_dfmt->debug_directive(debugid, p);
1404 break;
1405 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1406 if (pass1 == 1) {
1407 while (*value && nasm_isspace(*value))
1408 value++;
1410 switch(*value) {
1411 case '-': validid = 1; value++; break;
1412 case '+': validid = 1; value++; break;
1413 case '*': validid = 2; value++; break;
1414 default: validid = 1; break;
1417 for (i = 1; i <= ERR_WARN_MAX; i++)
1418 if (!nasm_stricmp(value, warnings[i].name))
1419 break;
1420 if (i <= ERR_WARN_MAX) {
1421 switch(validid) {
1422 case 0:
1423 warning_on[i] = false;
1424 break;
1425 case 1:
1426 warning_on[i] = true;
1427 break;
1428 case 2:
1429 warning_on[i] = warning_on_global[i];
1430 break;
1433 else
1434 report_error(ERR_NONFATAL,
1435 "invalid warning id in WARNING directive");
1437 break;
1438 case D_CPU: /* [CPU] */
1439 cpu = get_cpu(value);
1440 break;
1441 case D_LIST: /* [LIST {+|-}] */
1442 while (*value && nasm_isspace(*value))
1443 value++;
1445 if (*value == '+') {
1446 user_nolist = 0;
1447 } else {
1448 if (*value == '-') {
1449 user_nolist = 1;
1450 } else {
1451 err = 1;
1454 break;
1455 case D_DEFAULT: /* [DEFAULT] */
1456 stdscan_reset();
1457 stdscan_bufptr = value;
1458 tokval.t_type = TOKEN_INVALID;
1459 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1460 switch ((int)tokval.t_integer) {
1461 case S_REL:
1462 globalrel = 1;
1463 break;
1464 case S_ABS:
1465 globalrel = 0;
1466 break;
1467 default:
1468 err = 1;
1469 break;
1471 } else {
1472 err = 1;
1474 break;
1475 case D_FLOAT:
1476 if (float_option(value)) {
1477 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1478 "unknown 'float' directive: %s",
1479 value);
1481 break;
1482 default:
1483 if (!ofmt->directive(directive, value, pass2))
1484 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1485 "unrecognised directive [%s]",
1486 directive);
1488 if (err) {
1489 report_error(ERR_NONFATAL,
1490 "invalid parameter to [%s] directive",
1491 directive);
1493 } else { /* it isn't a directive */
1495 parse_line(pass1, line, &output_ins,
1496 report_error, evaluate, def_label);
1498 if (optimizing > 0) {
1499 if (forwref != NULL && globallineno == forwref->lineno) {
1500 output_ins.forw_ref = true;
1501 do {
1502 output_ins.oprs[forwref->operand].opflags |=
1503 OPFLAG_FORWARD;
1504 forwref = saa_rstruct(forwrefs);
1505 } while (forwref != NULL
1506 && forwref->lineno == globallineno);
1507 } else
1508 output_ins.forw_ref = false;
1511 if (optimizing > 0) {
1512 if (passn == 1) {
1513 for (i = 0; i < output_ins.operands; i++) {
1514 if (output_ins.oprs[i].
1515 opflags & OPFLAG_FORWARD) {
1516 struct forwrefinfo *fwinf =
1517 (struct forwrefinfo *)
1518 saa_wstruct(forwrefs);
1519 fwinf->lineno = globallineno;
1520 fwinf->operand = i;
1526 /* forw_ref */
1527 if (output_ins.opcode == I_EQU) {
1528 if (pass1 == 1) {
1530 * Special `..' EQUs get processed in pass two,
1531 * except `..@' macro-processor EQUs which are done
1532 * in the normal place.
1534 if (!output_ins.label)
1535 report_error(ERR_NONFATAL,
1536 "EQU not preceded by label");
1538 else if (output_ins.label[0] != '.' ||
1539 output_ins.label[1] != '.' ||
1540 output_ins.label[2] == '@') {
1541 if (output_ins.operands == 1 &&
1542 (output_ins.oprs[0].type & IMMEDIATE) &&
1543 output_ins.oprs[0].wrt == NO_SEG) {
1544 int isext =
1545 output_ins.oprs[0].
1546 opflags & OPFLAG_EXTERN;
1547 def_label(output_ins.label,
1548 output_ins.oprs[0].segment,
1549 output_ins.oprs[0].offset, NULL,
1550 false, isext, ofmt,
1551 report_error);
1552 } else if (output_ins.operands == 2
1553 && (output_ins.oprs[0].
1554 type & IMMEDIATE)
1555 && (output_ins.oprs[0].type & COLON)
1556 && output_ins.oprs[0].segment ==
1557 NO_SEG
1558 && output_ins.oprs[0].wrt == NO_SEG
1559 && (output_ins.oprs[1].
1560 type & IMMEDIATE)
1561 && output_ins.oprs[1].segment ==
1562 NO_SEG
1563 && output_ins.oprs[1].wrt ==
1564 NO_SEG) {
1565 def_label(output_ins.label,
1566 output_ins.oprs[0].
1567 offset | SEG_ABS,
1568 output_ins.oprs[1].offset, NULL,
1569 false, false, ofmt,
1570 report_error);
1571 } else
1572 report_error(ERR_NONFATAL,
1573 "bad syntax for EQU");
1575 } else {
1577 * Special `..' EQUs get processed here, except
1578 * `..@' macro processor EQUs which are done above.
1580 if (output_ins.label[0] == '.' &&
1581 output_ins.label[1] == '.' &&
1582 output_ins.label[2] != '@') {
1583 if (output_ins.operands == 1 &&
1584 (output_ins.oprs[0].type & IMMEDIATE)) {
1585 define_label(output_ins.label,
1586 output_ins.oprs[0].segment,
1587 output_ins.oprs[0].offset,
1588 NULL, false, false, ofmt,
1589 report_error);
1590 } else if (output_ins.operands == 2
1591 && (output_ins.oprs[0].
1592 type & IMMEDIATE)
1593 && (output_ins.oprs[0].type & COLON)
1594 && output_ins.oprs[0].segment ==
1595 NO_SEG
1596 && (output_ins.oprs[1].
1597 type & IMMEDIATE)
1598 && output_ins.oprs[1].segment ==
1599 NO_SEG) {
1600 define_label(output_ins.label,
1601 output_ins.oprs[0].
1602 offset | SEG_ABS,
1603 output_ins.oprs[1].offset,
1604 NULL, false, false, ofmt,
1605 report_error);
1606 } else
1607 report_error(ERR_NONFATAL,
1608 "bad syntax for EQU");
1611 } else { /* instruction isn't an EQU */
1613 if (pass1 == 1) {
1615 int64_t l = insn_size(location.segment, offs, sb, cpu,
1616 &output_ins, report_error);
1618 /* if (using_debug_info) && output_ins.opcode != -1) */
1619 if (using_debug_info)
1620 { /* fbk 03/25/01 */
1621 /* this is done here so we can do debug type info */
1622 int32_t typeinfo =
1623 TYS_ELEMENTS(output_ins.operands);
1624 switch (output_ins.opcode) {
1625 case I_RESB:
1626 typeinfo =
1627 TYS_ELEMENTS(output_ins.oprs[0].
1628 offset) | TY_BYTE;
1629 break;
1630 case I_RESW:
1631 typeinfo =
1632 TYS_ELEMENTS(output_ins.oprs[0].
1633 offset) | TY_WORD;
1634 break;
1635 case I_RESD:
1636 typeinfo =
1637 TYS_ELEMENTS(output_ins.oprs[0].
1638 offset) | TY_DWORD;
1639 break;
1640 case I_RESQ:
1641 typeinfo =
1642 TYS_ELEMENTS(output_ins.oprs[0].
1643 offset) | TY_QWORD;
1644 break;
1645 case I_REST:
1646 typeinfo =
1647 TYS_ELEMENTS(output_ins.oprs[0].
1648 offset) | TY_TBYTE;
1649 break;
1650 case I_RESO:
1651 typeinfo =
1652 TYS_ELEMENTS(output_ins.oprs[0].
1653 offset) | TY_OWORD;
1654 break;
1655 case I_RESY:
1656 typeinfo =
1657 TYS_ELEMENTS(output_ins.oprs[0].
1658 offset) | TY_YWORD;
1659 break;
1660 case I_DB:
1661 typeinfo |= TY_BYTE;
1662 break;
1663 case I_DW:
1664 typeinfo |= TY_WORD;
1665 break;
1666 case I_DD:
1667 if (output_ins.eops_float)
1668 typeinfo |= TY_FLOAT;
1669 else
1670 typeinfo |= TY_DWORD;
1671 break;
1672 case I_DQ:
1673 typeinfo |= TY_QWORD;
1674 break;
1675 case I_DT:
1676 typeinfo |= TY_TBYTE;
1677 break;
1678 case I_DO:
1679 typeinfo |= TY_OWORD;
1680 break;
1681 case I_DY:
1682 typeinfo |= TY_YWORD;
1683 break;
1684 default:
1685 typeinfo = TY_LABEL;
1689 ofmt->current_dfmt->debug_typevalue(typeinfo);
1692 if (l != -1) {
1693 offs += l;
1694 SET_CURR_OFFS(offs);
1697 * else l == -1 => invalid instruction, which will be
1698 * flagged as an error on pass 2
1701 } else {
1702 offs += assemble(location.segment, offs, sb, cpu,
1703 &output_ins, ofmt, report_error,
1704 &nasmlist);
1705 SET_CURR_OFFS(offs);
1708 } /* not an EQU */
1709 cleanup_insn(&output_ins);
1711 nasm_free(line);
1712 location.offset = offs = GET_CURR_OFFS;
1713 } /* end while (line = preproc->getline... */
1714 if (pass1 == 2 && global_offset_changed)
1715 report_error(ERR_NONFATAL,
1716 "phase error detected at end of assembly.");
1718 if (pass1 == 1)
1719 preproc->cleanup(1);
1721 if (pass1 == 1 && terminate_after_phase) {
1722 fclose(ofile);
1723 remove(outname);
1724 if (want_usage)
1725 usage();
1726 exit(1);
1729 if (passn > 1 && !global_offset_changed)
1730 pass0++;
1731 else if (global_offset_changed && global_offset_changed < prev_offset_changed) {
1732 prev_offset_changed = global_offset_changed;
1733 stall_count = 0;
1735 else stall_count++;
1737 if((stall_count > 997) || (passn >= pass_max))
1738 /* We get here if the labels don't converge
1739 * Example: FOO equ FOO + 1
1741 report_error(ERR_NONFATAL,
1742 "Can't find valid values for all labels "
1743 "after %d passes, giving up.\n"
1744 " Possible cause: recursive equ's.", passn);
1747 preproc->cleanup(0);
1748 nasmlist.cleanup();
1749 if (opt_verbose_info) /* -On and -Ov switches */
1750 fprintf(stdout,
1751 "info:: assembly required 1+%d+1 passes\n", passn-3);
1752 } /* exit from assemble_file (...) */
1754 static enum directives getkw(char **directive, char **value)
1756 char *p, *q, *buf;
1758 buf = *directive;
1760 /* allow leading spaces or tabs */
1761 while (*buf == ' ' || *buf == '\t')
1762 buf++;
1764 if (*buf != '[')
1765 return 0;
1767 p = buf;
1769 while (*p && *p != ']')
1770 p++;
1772 if (!*p)
1773 return 0;
1775 q = p++;
1777 while (*p && *p != ';') {
1778 if (!nasm_isspace(*p))
1779 return 0;
1780 p++;
1782 q[1] = '\0';
1784 *directive = p = buf + 1;
1785 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1786 buf++;
1787 if (*buf == ']') {
1788 *buf = '\0';
1789 *value = buf;
1790 } else {
1791 *buf++ = '\0';
1792 while (nasm_isspace(*buf))
1793 buf++; /* beppu - skip leading whitespace */
1794 *value = buf;
1795 while (*buf != ']')
1796 buf++;
1797 *buf++ = '\0';
1800 return bsii(*directive, directives, elements(directives));
1804 * gnu style error reporting
1805 * This function prints an error message to error_file in the
1806 * style used by GNU. An example would be:
1807 * file.asm:50: error: blah blah blah
1808 * where file.asm is the name of the file, 50 is the line number on
1809 * which the error occurs (or is detected) and "error:" is one of
1810 * the possible optional diagnostics -- it can be "error" or "warning"
1811 * or something else. Finally the line terminates with the actual
1812 * error message.
1814 * @param severity the severity of the warning or error
1815 * @param fmt the printf style format string
1817 static void report_error_gnu(int severity, const char *fmt, ...)
1819 va_list ap;
1821 if (is_suppressed_warning(severity))
1822 return;
1824 if (severity & ERR_NOFILE)
1825 fputs("nasm: ", error_file);
1826 else {
1827 char *currentfile = NULL;
1828 int32_t lineno = 0;
1829 src_get(&lineno, &currentfile);
1830 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1831 nasm_free(currentfile);
1833 va_start(ap, fmt);
1834 report_error_common(severity, fmt, ap);
1835 va_end(ap);
1839 * MS style error reporting
1840 * This function prints an error message to error_file in the
1841 * style used by Visual C and some other Microsoft tools. An example
1842 * would be:
1843 * file.asm(50) : error: blah blah blah
1844 * where file.asm is the name of the file, 50 is the line number on
1845 * which the error occurs (or is detected) and "error:" is one of
1846 * the possible optional diagnostics -- it can be "error" or "warning"
1847 * or something else. Finally the line terminates with the actual
1848 * error message.
1850 * @param severity the severity of the warning or error
1851 * @param fmt the printf style format string
1853 static void report_error_vc(int severity, const char *fmt, ...)
1855 va_list ap;
1857 if (is_suppressed_warning(severity))
1858 return;
1860 if (severity & ERR_NOFILE)
1861 fputs("nasm: ", error_file);
1862 else {
1863 char *currentfile = NULL;
1864 int32_t lineno = 0;
1865 src_get(&lineno, &currentfile);
1866 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1867 nasm_free(currentfile);
1869 va_start(ap, fmt);
1870 report_error_common(severity, fmt, ap);
1871 va_end(ap);
1875 * check for supressed warning
1876 * checks for suppressed warning or pass one only warning and we're
1877 * not in pass 1
1879 * @param severity the severity of the warning or error
1880 * @return true if we should abort error/warning printing
1882 static bool is_suppressed_warning(int severity)
1885 * See if it's a suppressed warning.
1887 return (severity & ERR_MASK) == ERR_WARNING &&
1888 (((severity & ERR_WARN_MASK) != 0 &&
1889 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1890 /* See if it's a pass-one only warning and we're not in pass one. */
1891 ((severity & ERR_PASS1) && pass0 != 1) ||
1892 ((severity & ERR_PASS2) && pass0 != 2));
1896 * common error reporting
1897 * This is the common back end of the error reporting schemes currently
1898 * implemented. It prints the nature of the warning and then the
1899 * specific error message to error_file and may or may not return. It
1900 * doesn't return if the error severity is a "panic" or "debug" type.
1902 * @param severity the severity of the warning or error
1903 * @param fmt the printf style format string
1905 static void report_error_common(int severity, const char *fmt,
1906 va_list args)
1908 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1909 case ERR_WARNING:
1910 fputs("warning: ", error_file);
1911 break;
1912 case ERR_NONFATAL:
1913 fputs("error: ", error_file);
1914 break;
1915 case ERR_FATAL:
1916 fputs("fatal: ", error_file);
1917 break;
1918 case ERR_PANIC:
1919 fputs("panic: ", error_file);
1920 break;
1921 case ERR_DEBUG:
1922 fputs("debug: ", error_file);
1923 break;
1924 default:
1925 break;
1928 vfprintf(error_file, fmt, args);
1929 putc('\n', error_file);
1931 if (severity & ERR_USAGE)
1932 want_usage = true;
1934 switch (severity & ERR_MASK) {
1935 case ERR_DEBUG:
1936 /* no further action, by definition */
1937 break;
1938 case ERR_WARNING:
1939 if (warning_on[0]) /* Treat warnings as errors */
1940 terminate_after_phase = true;
1941 break;
1942 case ERR_NONFATAL:
1943 terminate_after_phase = true;
1944 break;
1945 case ERR_FATAL:
1946 if (ofile) {
1947 fclose(ofile);
1948 remove(outname);
1950 if (want_usage)
1951 usage();
1952 exit(1); /* instantly die */
1953 break; /* placate silly compilers */
1954 case ERR_PANIC:
1955 fflush(NULL);
1956 /* abort(); *//* halt, catch fire, and dump core */
1957 exit(3);
1958 break;
1962 static void usage(void)
1964 fputs("type `nasm -h' for help\n", error_file);
1967 static void register_output_formats(void)
1969 ofmt = ofmt_register(report_error);
1972 #define BUF_DELTA 512
1974 static FILE *no_pp_fp;
1975 static efunc no_pp_err;
1976 static ListGen *no_pp_list;
1977 static int32_t no_pp_lineinc;
1979 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1980 ListGen * listgen, StrList **deplist)
1982 src_set_fname(nasm_strdup(file));
1983 src_set_linnum(0);
1984 no_pp_lineinc = 1;
1985 no_pp_err = error;
1986 no_pp_fp = fopen(file, "r");
1987 if (!no_pp_fp)
1988 no_pp_err(ERR_FATAL | ERR_NOFILE,
1989 "unable to open input file `%s'", file);
1990 no_pp_list = listgen;
1991 (void)pass; /* placate compilers */
1992 (void)eval; /* placate compilers */
1994 if (deplist) {
1995 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1996 sl->next = NULL;
1997 strcpy(sl->str, file);
1998 *deplist = sl;
2002 static char *no_pp_getline(void)
2004 char *buffer, *p, *q;
2005 int bufsize;
2007 bufsize = BUF_DELTA;
2008 buffer = nasm_malloc(BUF_DELTA);
2009 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2011 while (1) { /* Loop to handle %line */
2013 p = buffer;
2014 while (1) { /* Loop to handle long lines */
2015 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2016 if (!q)
2017 break;
2018 p += strlen(p);
2019 if (p > buffer && p[-1] == '\n')
2020 break;
2021 if (p - buffer > bufsize - 10) {
2022 int offset;
2023 offset = p - buffer;
2024 bufsize += BUF_DELTA;
2025 buffer = nasm_realloc(buffer, bufsize);
2026 p = buffer + offset;
2030 if (!q && p == buffer) {
2031 nasm_free(buffer);
2032 return NULL;
2036 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2037 * them are present at the end of the line.
2039 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2041 if (!nasm_strnicmp(buffer, "%line", 5)) {
2042 int32_t ln;
2043 int li;
2044 char *nm = nasm_malloc(strlen(buffer));
2045 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2046 nasm_free(src_set_fname(nm));
2047 src_set_linnum(ln);
2048 no_pp_lineinc = li;
2049 continue;
2051 nasm_free(nm);
2053 break;
2056 no_pp_list->line(LIST_READ, buffer);
2058 return buffer;
2061 static void no_pp_cleanup(int pass)
2063 (void)pass; /* placate GCC */
2064 fclose(no_pp_fp);
2067 static uint32_t get_cpu(char *value)
2069 if (!strcmp(value, "8086"))
2070 return IF_8086;
2071 if (!strcmp(value, "186"))
2072 return IF_186;
2073 if (!strcmp(value, "286"))
2074 return IF_286;
2075 if (!strcmp(value, "386"))
2076 return IF_386;
2077 if (!strcmp(value, "486"))
2078 return IF_486;
2079 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2080 return IF_PENT;
2081 if (!strcmp(value, "686") ||
2082 !nasm_stricmp(value, "ppro") ||
2083 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2084 return IF_P6;
2085 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2086 return IF_KATMAI;
2087 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2088 !nasm_stricmp(value, "willamette"))
2089 return IF_WILLAMETTE;
2090 if (!nasm_stricmp(value, "prescott"))
2091 return IF_PRESCOTT;
2092 if (!nasm_stricmp(value, "x64") ||
2093 !nasm_stricmp(value, "x86-64"))
2094 return IF_X86_64;
2095 if (!nasm_stricmp(value, "ia64") ||
2096 !nasm_stricmp(value, "ia-64") ||
2097 !nasm_stricmp(value, "itanium") ||
2098 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2099 return IF_IA64;
2101 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2102 "unknown 'cpu' type");
2104 return IF_PLEVEL; /* the maximum level */
2107 static int get_bits(char *value)
2109 int i;
2111 if ((i = atoi(value)) == 16)
2112 return i; /* set for a 16-bit segment */
2113 else if (i == 32) {
2114 if (cpu < IF_386) {
2115 report_error(ERR_NONFATAL,
2116 "cannot specify 32-bit segment on processor below a 386");
2117 i = 16;
2119 } else if (i == 64) {
2120 if (cpu < IF_X86_64) {
2121 report_error(ERR_NONFATAL,
2122 "cannot specify 64-bit segment on processor below an x86-64");
2123 i = 16;
2125 if (i != maxbits) {
2126 report_error(ERR_NONFATAL,
2127 "%s output format does not support 64-bit code",
2128 ofmt->shortname);
2129 i = 16;
2131 } else {
2132 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2133 "`%s' is not a valid segment size; must be 16, 32 or 64",
2134 value);
2135 i = 16;
2137 return i;
2140 /* end of nasm.c */