Move all the SAA code out of nasmlib
[nasm.git] / nasm.c
blob31c16fa7c3898d1bb08f70fe948b10c6cb2fab49
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 "float.h"
24 #include "stdscan.h"
25 #include "insns.h"
26 #include "preproc.h"
27 #include "parser.h"
28 #include "eval.h"
29 #include "assemble.h"
30 #include "labels.h"
31 #include "outform.h"
32 #include "listing.h"
34 struct forwrefinfo { /* info held on forward refs. */
35 int lineno;
36 int operand;
39 static int get_bits(char *value);
40 static uint32_t get_cpu(char *cpu_str);
41 static void parse_cmdline(int, char **);
42 static void assemble_file(char *, StrList **);
43 static void register_output_formats(void);
44 static void report_error_gnu(int severity, const char *fmt, ...);
45 static void report_error_vc(int severity, const char *fmt, ...);
46 static void report_error_common(int severity, const char *fmt,
47 va_list args);
48 static bool is_suppressed_warning(int severity);
49 static void usage(void);
50 static efunc report_error;
52 static int using_debug_info, opt_verbose_info;
53 bool tasm_compatible_mode = false;
54 int pass0, passn;
55 int maxbits = 0;
56 int globalrel = 0;
58 time_t official_compile_time;
60 static char inname[FILENAME_MAX];
61 static char outname[FILENAME_MAX];
62 static char listname[FILENAME_MAX];
63 static char errname[FILENAME_MAX];
64 static int globallineno; /* for forward-reference tracking */
65 /* static int pass = 0; */
66 static struct ofmt *ofmt = NULL;
68 static FILE *error_file; /* Where to write error messages */
70 static FILE *ofile = NULL;
71 int optimizing = -1; /* number of optimization passes to take */
72 static int sb, cmd_sb = 16; /* by default */
73 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
74 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
75 bool global_offset_changed; /* referenced in labels.c */
77 static struct location location;
78 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
79 int32_t abs_seg; /* ABSOLUTE segment basis */
80 int32_t abs_offset; /* ABSOLUTE offset */
82 static struct RAA *offsets;
84 static struct SAA *forwrefs; /* keep track of forward references */
85 static const struct forwrefinfo *forwref;
87 static Preproc *preproc;
88 enum op_type {
89 op_normal, /* Preprocess and assemble */
90 op_preprocess, /* Preprocess only */
91 op_depend, /* Generate dependencies */
93 static enum op_type operating_mode;
94 /* Dependency flags */
95 static bool depend_emit_phony = false;
96 static bool depend_missing_ok = false;
97 static const char *depend_target = NULL;
98 static const char *depend_file = NULL;
101 * Which of the suppressible warnings are suppressed. Entry zero
102 * isn't an actual warning, but it used for -w+error/-Werror.
104 static bool suppressed[ERR_WARN_MAX+1] = {
105 true, false, true, false, false, true, false, true, true, false
109 * The option names for the suppressible warnings. As before, entry
110 * zero does nothing.
112 static const char *suppressed_names[ERR_WARN_MAX+1] = {
113 "error", "macro-params", "macro-selfref", "orphan-labels",
114 "number-overflow", "gnu-elf-extensions", "float-overflow",
115 "float-denorm", "float-underflow", "float-toolong"
119 * The explanations for the suppressible warnings. As before, entry
120 * zero does nothing.
122 static const char *suppressed_what[ERR_WARN_MAX+1] = {
123 "treat warnings as errors",
124 "macro calls with wrong parameter count",
125 "cyclic macro references",
126 "labels alone on lines without trailing `:'",
127 "numeric constants does not fit in 64 bits",
128 "using 8- or 16-bit relocation in ELF32, a GNU extension",
129 "floating point overflow",
130 "floating point denormal",
131 "floating point underflow",
132 "too many digits in floating-point number"
136 * This is a null preprocessor which just copies lines from input
137 * to output. It's used when someone explicitly requests that NASM
138 * not preprocess their source file.
141 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
142 static char *no_pp_getline(void);
143 static void no_pp_cleanup(int);
144 static Preproc no_pp = {
145 no_pp_reset,
146 no_pp_getline,
147 no_pp_cleanup
151 * get/set current offset...
153 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
154 raa_read(offsets,location.segment))
155 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
156 (void)(offsets=raa_write(offsets,location.segment,(x))))
158 static int want_usage;
159 static int terminate_after_phase;
160 int user_nolist = 0; /* fbk 9/2/00 */
162 static void nasm_fputs(const char *line, FILE * outfile)
164 if (outfile) {
165 fputs(line, outfile);
166 putc('\n', outfile);
167 } else
168 puts(line);
171 /* Convert a struct tm to a POSIX-style time constant */
172 static int64_t posix_mktime(struct tm *tm)
174 int64_t t;
175 int64_t y = tm->tm_year;
177 /* See IEEE 1003.1:2004, section 4.14 */
179 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
180 t += tm->tm_yday;
181 t *= 24;
182 t += tm->tm_hour;
183 t *= 60;
184 t += tm->tm_min;
185 t *= 60;
186 t += tm->tm_sec;
188 return t;
191 static void define_macros_early(void)
193 char temp[128];
194 struct tm lt, *lt_p, gm, *gm_p;
195 int64_t posix_time;
197 lt_p = localtime(&official_compile_time);
198 if (lt_p) {
199 lt = *lt_p;
201 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
202 pp_pre_define(temp);
203 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
204 pp_pre_define(temp);
205 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
206 pp_pre_define(temp);
207 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
208 pp_pre_define(temp);
211 gm_p = gmtime(&official_compile_time);
212 if (gm_p) {
213 gm = *gm_p;
215 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
216 pp_pre_define(temp);
217 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
218 pp_pre_define(temp);
219 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
220 pp_pre_define(temp);
221 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
222 pp_pre_define(temp);
225 if (gm_p)
226 posix_time = posix_mktime(&gm);
227 else if (lt_p)
228 posix_time = posix_mktime(&lt);
229 else
230 posix_time = 0;
232 if (posix_time) {
233 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
234 pp_pre_define(temp);
238 static void define_macros_late(void)
240 char temp[128];
242 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
243 ofmt->shortname);
244 pp_pre_define(temp);
247 static void emit_dependencies(StrList *list)
249 FILE *deps;
250 int linepos, len;
251 StrList *l, *nl;
253 if (depend_file && strcmp(depend_file, "-")) {
254 deps = fopen(depend_file, "w");
255 if (!deps) {
256 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
257 "unable to write dependency file `%s'", depend_file);
258 return;
260 } else {
261 deps = stdout;
264 linepos = fprintf(deps, "%s:", depend_target);
265 for (l = list; l; l = l->next) {
266 len = strlen(l->str);
267 if (linepos + len > 62) {
268 fprintf(deps, " \\\n ");
269 linepos = 1;
271 fprintf(deps, " %s", l->str);
272 linepos += len+1;
274 fprintf(deps, "\n\n");
276 for (l = list; l; l = nl) {
277 if (depend_emit_phony)
278 fprintf(deps, "%s:\n\n", l->str);
280 nl = l->next;
281 nasm_free(l);
284 if (deps != stdout)
285 fclose(deps);
288 int main(int argc, char **argv)
290 StrList *depend_list = NULL, **depend_ptr;
292 time(&official_compile_time);
294 pass0 = 1;
295 want_usage = terminate_after_phase = false;
296 report_error = report_error_gnu;
298 error_file = stderr;
300 nasm_set_malloc_error(report_error);
301 offsets = raa_init();
302 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
304 preproc = &nasmpp;
305 operating_mode = op_normal;
307 seg_init();
309 register_output_formats();
311 /* Define some macros dependent on the runtime, but not
312 on the command line. */
313 define_macros_early();
315 parse_cmdline(argc, argv);
317 if (terminate_after_phase) {
318 if (want_usage)
319 usage();
320 return 1;
323 /* If debugging info is disabled, suppress any debug calls */
324 if (!using_debug_info)
325 ofmt->current_dfmt = &null_debug_form;
327 if (ofmt->stdmac)
328 pp_extra_stdmac(ofmt->stdmac);
329 parser_global_info(ofmt, &location);
330 eval_global_info(ofmt, lookup_label, &location);
332 /* define some macros dependent of command-line */
333 define_macros_late();
335 depend_ptr = (depend_file || (operating_mode == op_depend))
336 ? &depend_list : NULL;
337 if (!depend_target)
338 depend_target = outname;
340 switch (operating_mode) {
341 case op_depend:
343 char *line;
345 if (depend_missing_ok)
346 pp_include_path(NULL); /* "assume generated" */
348 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
349 depend_ptr);
350 if (outname[0] == '\0')
351 ofmt->filename(inname, outname, report_error);
352 ofile = NULL;
353 while ((line = preproc->getline()))
354 nasm_free(line);
355 preproc->cleanup(0);
357 break;
359 case op_preprocess:
361 char *line;
362 char *file_name = NULL;
363 int32_t prior_linnum = 0;
364 int lineinc = 0;
366 if (*outname) {
367 ofile = fopen(outname, "w");
368 if (!ofile)
369 report_error(ERR_FATAL | ERR_NOFILE,
370 "unable to open output file `%s'",
371 outname);
372 } else
373 ofile = NULL;
375 location.known = false;
377 /* pass = 1; */
378 preproc->reset(inname, 2, report_error, evaluate, &nasmlist,
379 depend_ptr);
381 while ((line = preproc->getline())) {
383 * We generate %line directives if needed for later programs
385 int32_t linnum = prior_linnum += lineinc;
386 int altline = src_get(&linnum, &file_name);
387 if (altline) {
388 if (altline == 1 && lineinc == 1)
389 nasm_fputs("", ofile);
390 else {
391 lineinc = (altline != -1 || lineinc != 1);
392 fprintf(ofile ? ofile : stdout,
393 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
394 file_name);
396 prior_linnum = linnum;
398 nasm_fputs(line, ofile);
399 nasm_free(line);
401 nasm_free(file_name);
402 preproc->cleanup(0);
403 if (ofile)
404 fclose(ofile);
405 if (ofile && terminate_after_phase)
406 remove(outname);
408 break;
410 case op_normal:
413 * We must call ofmt->filename _anyway_, even if the user
414 * has specified their own output file, because some
415 * formats (eg OBJ and COFF) use ofmt->filename to find out
416 * the name of the input file and then put that inside the
417 * file.
419 ofmt->filename(inname, outname, report_error);
421 ofile = fopen(outname, "wb");
422 if (!ofile) {
423 report_error(ERR_FATAL | ERR_NOFILE,
424 "unable to open output file `%s'", outname);
428 * We must call init_labels() before ofmt->init() since
429 * some object formats will want to define labels in their
430 * init routines. (eg OS/2 defines the FLAT group)
432 init_labels();
434 ofmt->init(ofile, report_error, define_label, evaluate);
436 assemble_file(inname, depend_ptr);
438 if (!terminate_after_phase) {
439 ofmt->cleanup(using_debug_info);
440 cleanup_labels();
441 } else {
443 * We had an fclose on the output file here, but we
444 * actually do that in all the object file drivers as well,
445 * so we're leaving out the one here.
446 * fclose (ofile);
448 remove(outname);
449 if (listname[0])
450 remove(listname);
453 break;
456 if (depend_list)
457 emit_dependencies(depend_list);
459 if (want_usage)
460 usage();
462 raa_free(offsets);
463 saa_free(forwrefs);
464 eval_cleanup();
465 stdscan_cleanup();
467 if (terminate_after_phase)
468 return 1;
469 else
470 return 0;
474 * Get a parameter for a command line option.
475 * First arg must be in the form of e.g. -f...
477 static char *get_param(char *p, char *q, bool *advance)
479 *advance = false;
480 if (p[2]) { /* the parameter's in the option */
481 p += 2;
482 while (isspace(*p))
483 p++;
484 return p;
486 if (q && q[0]) {
487 *advance = true;
488 return q;
490 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
491 "option `-%c' requires an argument", p[1]);
492 return NULL;
496 * Copy a filename
498 static void copy_filename(char *dst, const char *src)
500 size_t len = strlen(src);
502 if (len >= (size_t)FILENAME_MAX) {
503 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
504 return;
506 strncpy(dst, src, FILENAME_MAX);
510 * Convert a string to Make-safe form
512 static char *quote_for_make(const char *str)
514 const char *p;
515 char *os, *q;
517 size_t n = 1; /* Terminating zero */
518 size_t nbs = 0;
520 if (!str)
521 return NULL;
523 for (p = str; *p; p++) {
524 switch (*p) {
525 case ' ':
526 case '\t':
527 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
528 n += nbs + 2;
529 nbs = 0;
530 break;
531 case '$':
532 case '#':
533 nbs = 0;
534 n += 2;
535 break;
536 case '\\':
537 nbs++;
538 n++;
539 break;
540 default:
541 nbs = 0;
542 n++;
543 break;
547 /* Convert N backslashes at the end of filename to 2N backslashes */
548 if (nbs)
549 n += nbs;
551 os = q = nasm_malloc(n);
553 nbs = 0;
554 for (p = str; *p; p++) {
555 switch (*p) {
556 case ' ':
557 case '\t':
558 while (nbs--)
559 *q++ = '\\';
560 *q++ = '\\';
561 *q++ = *p;
562 break;
563 case '$':
564 *q++ = *p;
565 *q++ = *p;
566 nbs = 0;
567 break;
568 case '#':
569 *q++ = '\\';
570 *q++ = *p;
571 nbs = 0;
572 break;
573 case '\\':
574 *q++ = *p;
575 nbs++;
576 break;
577 default:
578 *q++ = *p;
579 nbs = 0;
580 break;
583 while (nbs--)
584 *q++ = '\\';
586 *q = '\0';
588 return os;
591 struct textargs {
592 const char *label;
593 int value;
596 #define OPT_PREFIX 0
597 #define OPT_POSTFIX 1
598 struct textargs textopts[] = {
599 {"prefix", OPT_PREFIX},
600 {"postfix", OPT_POSTFIX},
601 {NULL, 0}
604 static bool stopoptions = false;
605 static bool process_arg(char *p, char *q)
607 char *param;
608 int i;
609 bool advance = false;
610 bool suppress;
612 if (!p || !p[0])
613 return false;
615 if (p[0] == '-' && !stopoptions) {
616 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
617 /* These parameters take values */
618 if (!(param = get_param(p, q, &advance)))
619 return advance;
622 switch (p[1]) {
623 case 's':
624 error_file = stdout;
625 break;
627 case 'o': /* output file */
628 copy_filename(outname, param);
629 break;
631 case 'f': /* output format */
632 ofmt = ofmt_find(param);
633 if (!ofmt) {
634 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
635 "unrecognised output format `%s' - "
636 "use -hf for a list", param);
637 } else {
638 ofmt->current_dfmt = ofmt->debug_formats[0];
640 break;
642 case 'O': /* Optimization level */
644 int opt;
646 if (!*param) {
647 /* Naked -O == -Ox */
648 optimizing = INT_MAX >> 1; /* Almost unlimited */
649 } else {
650 while (*param) {
651 switch (*param) {
652 case '0': case '1': case '2': case '3': case '4':
653 case '5': case '6': case '7': case '8': case '9':
654 opt = strtoul(param, &param, 10);
656 /* -O0 -> optimizing == -1, 0.98 behaviour */
657 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
658 if (opt < 2)
659 optimizing = opt - 1;
660 else
661 optimizing = opt;
662 break;
664 case 'v':
665 case '+':
666 param++;
667 opt_verbose_info = true;
668 break;
670 case 'x':
671 param++;
672 optimizing = INT_MAX >> 1; /* Almost unlimited */
673 break;
675 default:
676 report_error(ERR_FATAL,
677 "unknown optimization option -O%c\n",
678 *param);
679 break;
683 break;
686 case 'p': /* pre-include */
687 case 'P':
688 pp_pre_include(param);
689 break;
691 case 'd': /* pre-define */
692 case 'D':
693 pp_pre_define(param);
694 break;
696 case 'u': /* un-define */
697 case 'U':
698 pp_pre_undefine(param);
699 break;
701 case 'i': /* include search path */
702 case 'I':
703 pp_include_path(param);
704 break;
706 case 'l': /* listing file */
707 copy_filename(listname, param);
708 break;
710 case 'Z': /* error messages file */
711 strcpy(errname, param);
712 break;
714 case 'F': /* specify debug format */
715 ofmt->current_dfmt = dfmt_find(ofmt, param);
716 if (!ofmt->current_dfmt) {
717 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
718 "unrecognized debug format `%s' for"
719 " output format `%s'",
720 param, ofmt->shortname);
722 break;
724 case 'X': /* specify error reporting format */
725 if (nasm_stricmp("vc", param) == 0)
726 report_error = report_error_vc;
727 else if (nasm_stricmp("gnu", param) == 0)
728 report_error = report_error_gnu;
729 else
730 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
731 "unrecognized error reporting format `%s'",
732 param);
733 break;
735 case 'g':
736 using_debug_info = true;
737 break;
739 case 'h':
740 printf
741 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
742 "[-l listfile]\n"
743 " [options...] [--] filename\n"
744 " or nasm -v for version info\n\n"
745 " -t assemble in SciTech TASM compatible mode\n"
746 " -g generate debug information in selected format.\n");
747 printf
748 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
749 " -a don't preprocess (assemble only)\n"
750 " -M generate Makefile dependencies on stdout\n"
751 " -MG d:o, missing files assumed generated\n\n"
752 " -Z<file> redirect error messages to file\n"
753 " -s redirect error messages to stdout\n\n"
754 " -F format select a debugging format\n\n"
755 " -I<path> adds a pathname to the include file path\n");
756 printf
757 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
758 " -P<file> pre-includes a file\n"
759 " -D<macro>[=<value>] pre-defines a macro\n"
760 " -U<macro> undefines a macro\n"
761 " -X<format> specifies error reporting format (gnu or vc)\n"
762 " -w+foo enables warning foo (equiv. -Wfoo)\n"
763 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
764 "Warnings:\n");
765 for (i = 0; i <= ERR_WARN_MAX; i++)
766 printf(" %-23s %s (default %s)\n",
767 suppressed_names[i], suppressed_what[i],
768 suppressed[i] ? "off" : "on");
769 printf
770 ("\nresponse files should contain command line parameters"
771 ", one per line.\n");
772 if (p[2] == 'f') {
773 printf("\nvalid output formats for -f are"
774 " (`*' denotes default):\n");
775 ofmt_list(ofmt, stdout);
776 } else {
777 printf("\nFor a list of valid output formats, use -hf.\n");
778 printf("For a list of debug formats, use -f <form> -y.\n");
780 exit(0); /* never need usage message here */
781 break;
783 case 'y':
784 printf("\nvalid debug formats for '%s' output format are"
785 " ('*' denotes default):\n", ofmt->shortname);
786 dfmt_list(ofmt, stdout);
787 exit(0);
788 break;
790 case 't':
791 tasm_compatible_mode = true;
792 break;
794 case 'v':
796 const char *nasm_version_string =
797 "NASM version " NASM_VER " compiled on " __DATE__
798 #ifdef DEBUG
799 " with -DDEBUG"
800 #endif
802 puts(nasm_version_string);
803 exit(0); /* never need usage message here */
805 break;
807 case 'e': /* preprocess only */
808 case 'E':
809 operating_mode = op_preprocess;
810 break;
812 case 'a': /* assemble only - don't preprocess */
813 preproc = &no_pp;
814 break;
816 case 'W':
817 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
818 suppress = true;
819 param += 3;
820 } else {
821 suppress = false;
823 goto set_warning;
825 case 'w':
826 if (param[0] != '+' && param[0] != '-') {
827 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
828 "invalid option to `-w'");
829 break;
831 suppress = (param[0] == '-');
832 param++;
833 goto set_warning;
834 set_warning:
835 for (i = 0; i <= ERR_WARN_MAX; i++)
836 if (!nasm_stricmp(param, suppressed_names[i]))
837 break;
838 if (i <= ERR_WARN_MAX)
839 suppressed[i] = suppress;
840 else if (!nasm_stricmp(param, "all"))
841 for (i = 1; i <= ERR_WARN_MAX; i++)
842 suppressed[i] = suppress;
843 else if (!nasm_stricmp(param, "none"))
844 for (i = 1; i <= ERR_WARN_MAX; i++)
845 suppressed[i] = !suppress;
846 else
847 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
848 "invalid warning `%s'", param);
849 break;
851 case 'M':
852 switch (p[2]) {
853 case 0:
854 operating_mode = op_depend;
855 break;
856 case 'G':
857 operating_mode = op_depend;
858 depend_missing_ok = true;
859 break;
860 case 'P':
861 depend_emit_phony = true;
862 break;
863 case 'D':
864 depend_file = q;
865 advance = true;
866 break;
867 case 'T':
868 depend_target = q;
869 advance = true;
870 break;
871 case 'Q':
872 depend_target = quote_for_make(q);
873 advance = true;
874 break;
875 default:
876 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
877 "unknown dependency option `-M%c'", p[2]);
878 break;
880 if (advance && (!q || !q[0])) {
881 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
882 "option `-M%c' requires a parameter", p[2]);
883 break;
885 break;
887 case '-':
889 int s;
891 if (p[2] == 0) { /* -- => stop processing options */
892 stopoptions = 1;
893 break;
895 for (s = 0; textopts[s].label; s++) {
896 if (!nasm_stricmp(p + 2, textopts[s].label)) {
897 break;
901 switch (s) {
903 case OPT_PREFIX:
904 case OPT_POSTFIX:
906 if (!q) {
907 report_error(ERR_NONFATAL | ERR_NOFILE |
908 ERR_USAGE,
909 "option `--%s' requires an argument",
910 p + 2);
911 break;
912 } else {
913 advance = 1, param = q;
916 if (s == OPT_PREFIX) {
917 strncpy(lprefix, param, PREFIX_MAX - 1);
918 lprefix[PREFIX_MAX - 1] = 0;
919 break;
921 if (s == OPT_POSTFIX) {
922 strncpy(lpostfix, param, POSTFIX_MAX - 1);
923 lpostfix[POSTFIX_MAX - 1] = 0;
924 break;
926 break;
928 default:
930 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
931 "unrecognised option `--%s'", p + 2);
932 break;
935 break;
938 default:
939 if (!ofmt->setinfo(GI_SWITCH, &p))
940 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
941 "unrecognised option `-%c'", p[1]);
942 break;
944 } else {
945 if (*inname) {
946 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
947 "more than one input file specified");
948 } else {
949 copy_filename(inname, p);
953 return advance;
956 #define ARG_BUF_DELTA 128
958 static void process_respfile(FILE * rfile)
960 char *buffer, *p, *q, *prevarg;
961 int bufsize, prevargsize;
963 bufsize = prevargsize = ARG_BUF_DELTA;
964 buffer = nasm_malloc(ARG_BUF_DELTA);
965 prevarg = nasm_malloc(ARG_BUF_DELTA);
966 prevarg[0] = '\0';
968 while (1) { /* Loop to handle all lines in file */
969 p = buffer;
970 while (1) { /* Loop to handle long lines */
971 q = fgets(p, bufsize - (p - buffer), rfile);
972 if (!q)
973 break;
974 p += strlen(p);
975 if (p > buffer && p[-1] == '\n')
976 break;
977 if (p - buffer > bufsize - 10) {
978 int offset;
979 offset = p - buffer;
980 bufsize += ARG_BUF_DELTA;
981 buffer = nasm_realloc(buffer, bufsize);
982 p = buffer + offset;
986 if (!q && p == buffer) {
987 if (prevarg[0])
988 process_arg(prevarg, NULL);
989 nasm_free(buffer);
990 nasm_free(prevarg);
991 return;
995 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
996 * them are present at the end of the line.
998 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1000 while (p > buffer && isspace(p[-1]))
1001 *--p = '\0';
1003 p = buffer;
1004 while (isspace(*p))
1005 p++;
1007 if (process_arg(prevarg, p))
1008 *p = '\0';
1010 if ((int) strlen(p) > prevargsize - 10) {
1011 prevargsize += ARG_BUF_DELTA;
1012 prevarg = nasm_realloc(prevarg, prevargsize);
1014 strncpy(prevarg, p, prevargsize);
1018 /* Function to process args from a string of args, rather than the
1019 * argv array. Used by the environment variable and response file
1020 * processing.
1022 static void process_args(char *args)
1024 char *p, *q, *arg, *prevarg;
1025 char separator = ' ';
1027 p = args;
1028 if (*p && *p != '-')
1029 separator = *p++;
1030 arg = NULL;
1031 while (*p) {
1032 q = p;
1033 while (*p && *p != separator)
1034 p++;
1035 while (*p == separator)
1036 *p++ = '\0';
1037 prevarg = arg;
1038 arg = q;
1039 if (process_arg(prevarg, arg))
1040 arg = NULL;
1042 if (arg)
1043 process_arg(arg, NULL);
1046 static void process_response_file(const char *file)
1048 char str[2048];
1049 FILE *f = fopen(file, "r");
1050 if (!f) {
1051 perror(file);
1052 exit(-1);
1054 while (fgets(str, sizeof str, f)) {
1055 process_args(str);
1057 fclose(f);
1060 static void parse_cmdline(int argc, char **argv)
1062 FILE *rfile;
1063 char *envreal, *envcopy = NULL, *p, *arg;
1065 *inname = *outname = *listname = *errname = '\0';
1068 * First, process the NASMENV environment variable.
1070 envreal = getenv("NASMENV");
1071 arg = NULL;
1072 if (envreal) {
1073 envcopy = nasm_strdup(envreal);
1074 process_args(envcopy);
1075 nasm_free(envcopy);
1079 * Now process the actual command line.
1081 while (--argc) {
1082 bool advance;
1083 argv++;
1084 if (argv[0][0] == '@') {
1085 /* We have a response file, so process this as a set of
1086 * arguments like the environment variable. This allows us
1087 * to have multiple arguments on a single line, which is
1088 * different to the -@resp file processing below for regular
1089 * NASM.
1091 process_response_file(argv[0]+1);
1092 argc--;
1093 argv++;
1095 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1096 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1097 if (p) {
1098 rfile = fopen(p, "r");
1099 if (rfile) {
1100 process_respfile(rfile);
1101 fclose(rfile);
1102 } else
1103 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1104 "unable to open response file `%s'", p);
1106 } else
1107 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1108 argv += advance, argc -= advance;
1111 /* Look for basic command line typos. This definitely doesn't
1112 catch all errors, but it might help cases of fumbled fingers. */
1113 if (!*inname)
1114 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1115 "no input file specified");
1116 else if (!strcmp(inname, errname) ||
1117 !strcmp(inname, outname) ||
1118 !strcmp(inname, listname) ||
1119 (depend_file && !strcmp(inname, depend_file)))
1120 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1121 "file `%s' is both input and output file",
1122 inname);
1124 if (*errname) {
1125 error_file = fopen(errname, "w");
1126 if (!error_file) {
1127 error_file = stderr; /* Revert to default! */
1128 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1129 "cannot open file `%s' for error messages",
1130 errname);
1135 /* List of directives */
1136 enum directives {
1137 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1138 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1140 static const char *directives[] = {
1141 "", "absolute", "bits", "common", "cpu", "debug", "default",
1142 "extern", "float", "global", "list", "section", "segment", "warning"
1144 static enum directives getkw(char **directive, char **value);
1146 static void assemble_file(char *fname, StrList **depend_ptr)
1148 char *directive, *value, *p, *q, *special, *line, debugid[80];
1149 insn output_ins;
1150 int i, validid;
1151 bool rn_error;
1152 int32_t seg;
1153 int64_t offs;
1154 struct tokenval tokval;
1155 expr *e;
1156 int pass_max;
1158 if (cmd_sb == 32 && cmd_cpu < IF_386)
1159 report_error(ERR_FATAL, "command line: "
1160 "32-bit segment size requires a higher cpu");
1162 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
1163 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
1164 for (passn = 1; pass0 <= 2; passn++) {
1165 int pass1, pass2;
1166 ldfunc def_label;
1168 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1169 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1170 /* pass0 0, 0, 0, ..., 1, 2 */
1172 def_label = passn > 1 ? redefine_label : define_label;
1174 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1175 cpu = cmd_cpu;
1176 if (pass0 == 2) {
1177 if (*listname)
1178 nasmlist.init(listname, report_error);
1180 in_abs_seg = false;
1181 global_offset_changed = false; /* set by redefine_label */
1182 location.segment = ofmt->section(NULL, pass2, &sb);
1183 globalbits = sb;
1184 if (passn > 1) {
1185 saa_rewind(forwrefs);
1186 forwref = saa_rstruct(forwrefs);
1187 raa_free(offsets);
1188 offsets = raa_init();
1190 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1191 pass1 == 2 ? depend_ptr : NULL);
1193 globallineno = 0;
1194 if (passn == 1)
1195 location.known = true;
1196 location.offset = offs = GET_CURR_OFFS;
1198 while ((line = preproc->getline())) {
1199 enum directives d;
1200 globallineno++;
1202 /* here we parse our directives; this is not handled by the 'real'
1203 * parser. */
1204 directive = line;
1205 d = getkw(&directive, &value);
1206 if (d) {
1207 int err = 0;
1209 switch (d) {
1210 case D_SEGMENT: /* [SEGMENT n] */
1211 case D_SECTION:
1212 seg = ofmt->section(value, pass2, &sb);
1213 if (seg == NO_SEG) {
1214 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1215 "segment name `%s' not recognized",
1216 value);
1217 } else {
1218 in_abs_seg = false;
1219 location.segment = seg;
1221 break;
1222 case D_EXTERN: /* [EXTERN label:special] */
1223 if (*value == '$')
1224 value++; /* skip initial $ if present */
1225 if (pass0 == 2) {
1226 q = value;
1227 while (*q && *q != ':')
1228 q++;
1229 if (*q == ':') {
1230 *q++ = '\0';
1231 ofmt->symdef(value, 0L, 0L, 3, q);
1233 } else if (passn == 1) {
1234 q = value;
1235 validid = true;
1236 if (!isidstart(*q))
1237 validid = false;
1238 while (*q && *q != ':') {
1239 if (!isidchar(*q))
1240 validid = false;
1241 q++;
1243 if (!validid) {
1244 report_error(ERR_NONFATAL,
1245 "identifier expected after EXTERN");
1246 break;
1248 if (*q == ':') {
1249 *q++ = '\0';
1250 special = q;
1251 } else
1252 special = NULL;
1253 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1254 int temp = pass0;
1255 pass0 = 1; /* fake pass 1 in labels.c */
1256 declare_as_global(value, special,
1257 report_error);
1258 define_label(value, seg_alloc(), 0L, NULL,
1259 false, true, ofmt, report_error);
1260 pass0 = temp;
1262 } /* else pass0 == 1 */
1263 break;
1264 case D_BITS: /* [BITS bits] */
1265 globalbits = sb = get_bits(value);
1266 break;
1267 case D_GLOBAL: /* [GLOBAL symbol:special] */
1268 if (*value == '$')
1269 value++; /* skip initial $ if present */
1270 if (pass0 == 2) { /* pass 2 */
1271 q = value;
1272 while (*q && *q != ':')
1273 q++;
1274 if (*q == ':') {
1275 *q++ = '\0';
1276 ofmt->symdef(value, 0L, 0L, 3, q);
1278 } else if (pass2 == 1) { /* pass == 1 */
1279 q = value;
1280 validid = true;
1281 if (!isidstart(*q))
1282 validid = false;
1283 while (*q && *q != ':') {
1284 if (!isidchar(*q))
1285 validid = false;
1286 q++;
1288 if (!validid) {
1289 report_error(ERR_NONFATAL,
1290 "identifier expected after GLOBAL");
1291 break;
1293 if (*q == ':') {
1294 *q++ = '\0';
1295 special = q;
1296 } else
1297 special = NULL;
1298 declare_as_global(value, special, report_error);
1299 } /* pass == 1 */
1300 break;
1301 case D_COMMON: /* [COMMON symbol size:special] */
1302 if (*value == '$')
1303 value++; /* skip initial $ if present */
1304 if (pass0 == 1) {
1305 p = value;
1306 validid = true;
1307 if (!isidstart(*p))
1308 validid = false;
1309 while (*p && !isspace(*p)) {
1310 if (!isidchar(*p))
1311 validid = false;
1312 p++;
1314 if (!validid) {
1315 report_error(ERR_NONFATAL,
1316 "identifier expected after COMMON");
1317 break;
1319 if (*p) {
1320 int64_t size;
1322 while (*p && isspace(*p))
1323 *p++ = '\0';
1324 q = p;
1325 while (*q && *q != ':')
1326 q++;
1327 if (*q == ':') {
1328 *q++ = '\0';
1329 special = q;
1330 } else
1331 special = NULL;
1332 size = readnum(p, &rn_error);
1333 if (rn_error)
1334 report_error(ERR_NONFATAL,
1335 "invalid size specified"
1336 " in COMMON declaration");
1337 else
1338 define_common(value, seg_alloc(), size,
1339 special, ofmt, report_error);
1340 } else
1341 report_error(ERR_NONFATAL,
1342 "no size specified in"
1343 " COMMON declaration");
1344 } else if (pass0 == 2) { /* pass == 2 */
1345 q = value;
1346 while (*q && *q != ':') {
1347 if (isspace(*q))
1348 *q = '\0';
1349 q++;
1351 if (*q == ':') {
1352 *q++ = '\0';
1353 ofmt->symdef(value, 0L, 0L, 3, q);
1356 break;
1357 case D_ABSOLUTE: /* [ABSOLUTE address] */
1358 stdscan_reset();
1359 stdscan_bufptr = value;
1360 tokval.t_type = TOKEN_INVALID;
1361 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1362 report_error, NULL);
1363 if (e) {
1364 if (!is_reloc(e))
1365 report_error(pass0 ==
1366 1 ? ERR_NONFATAL : ERR_PANIC,
1367 "cannot use non-relocatable expression as "
1368 "ABSOLUTE address");
1369 else {
1370 abs_seg = reloc_seg(e);
1371 abs_offset = reloc_value(e);
1373 } else if (passn == 1)
1374 abs_offset = 0x100; /* don't go near zero in case of / */
1375 else
1376 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1377 "in pass two");
1378 in_abs_seg = true;
1379 location.segment = NO_SEG;
1380 break;
1381 case D_DEBUG: /* [DEBUG] */
1382 p = value;
1383 q = debugid;
1384 validid = true;
1385 if (!isidstart(*p))
1386 validid = false;
1387 while (*p && !isspace(*p)) {
1388 if (!isidchar(*p))
1389 validid = false;
1390 *q++ = *p++;
1392 *q++ = 0;
1393 if (!validid) {
1394 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1395 "identifier expected after DEBUG");
1396 break;
1398 while (*p && isspace(*p))
1399 p++;
1400 if (pass0 == 2)
1401 ofmt->current_dfmt->debug_directive(debugid, p);
1402 break;
1403 case D_WARNING: /* [WARNING {+|-}warn-name] */
1404 if (pass1 == 1) {
1405 while (*value && isspace(*value))
1406 value++;
1408 if (*value == '+' || *value == '-') {
1409 validid = (*value == '-') ? true : false;
1410 value++;
1411 } else
1412 validid = false;
1414 for (i = 1; i <= ERR_WARN_MAX; i++)
1415 if (!nasm_stricmp(value, suppressed_names[i]))
1416 break;
1417 if (i <= ERR_WARN_MAX)
1418 suppressed[i] = validid;
1419 else
1420 report_error(ERR_NONFATAL,
1421 "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 && 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) && pass0 == 2) {
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;
1497 if (!(optimizing > 0) && output_ins.forw_ref) {
1498 if (passn == 1) {
1499 for (i = 0; i < output_ins.operands; i++) {
1500 if (output_ins.oprs[i].
1501 opflags & OPFLAG_FORWARD) {
1502 struct forwrefinfo *fwinf =
1503 (struct forwrefinfo *)
1504 saa_wstruct(forwrefs);
1505 fwinf->lineno = globallineno;
1506 fwinf->operand = i;
1509 } else { /* passn > 1 */
1511 * Hack to prevent phase error in the code
1512 * rol ax,x
1513 * x equ 1
1515 * If the second operand is a forward reference,
1516 * the UNITY property of the number 1 in that
1517 * operand is cancelled. Otherwise the above
1518 * sequence will cause a phase error.
1520 * This hack means that the above code will
1521 * generate 286+ code.
1523 * The forward reference will mean that the
1524 * operand will not have the UNITY property on
1525 * the first pass, so the pass behaviours will
1526 * be consistent.
1529 if (output_ins.operands >= 2 &&
1530 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1531 !(IMMEDIATE & ~output_ins.oprs[1].type))
1533 /* Remove special properties bits */
1534 output_ins.oprs[1].type &= ~REG_SMASK;
1541 /* forw_ref */
1542 if (output_ins.opcode == I_EQU) {
1543 if (pass1 == 1) {
1545 * Special `..' EQUs get processed in pass two,
1546 * except `..@' macro-processor EQUs which are done
1547 * in the normal place.
1549 if (!output_ins.label)
1550 report_error(ERR_NONFATAL,
1551 "EQU not preceded by label");
1553 else if (output_ins.label[0] != '.' ||
1554 output_ins.label[1] != '.' ||
1555 output_ins.label[2] == '@') {
1556 if (output_ins.operands == 1 &&
1557 (output_ins.oprs[0].type & IMMEDIATE) &&
1558 output_ins.oprs[0].wrt == NO_SEG) {
1559 int isext =
1560 output_ins.oprs[0].
1561 opflags & OPFLAG_EXTERN;
1562 def_label(output_ins.label,
1563 output_ins.oprs[0].segment,
1564 output_ins.oprs[0].offset, NULL,
1565 false, isext, ofmt,
1566 report_error);
1567 } else if (output_ins.operands == 2
1568 && (output_ins.oprs[0].
1569 type & IMMEDIATE)
1570 && (output_ins.oprs[0].type & COLON)
1571 && output_ins.oprs[0].segment ==
1572 NO_SEG
1573 && output_ins.oprs[0].wrt == NO_SEG
1574 && (output_ins.oprs[1].
1575 type & IMMEDIATE)
1576 && output_ins.oprs[1].segment ==
1577 NO_SEG
1578 && output_ins.oprs[1].wrt ==
1579 NO_SEG) {
1580 def_label(output_ins.label,
1581 output_ins.oprs[0].
1582 offset | SEG_ABS,
1583 output_ins.oprs[1].offset, NULL,
1584 false, false, ofmt,
1585 report_error);
1586 } else
1587 report_error(ERR_NONFATAL,
1588 "bad syntax for EQU");
1590 } else {
1592 * Special `..' EQUs get processed here, except
1593 * `..@' macro processor EQUs which are done above.
1595 if (output_ins.label[0] == '.' &&
1596 output_ins.label[1] == '.' &&
1597 output_ins.label[2] != '@') {
1598 if (output_ins.operands == 1 &&
1599 (output_ins.oprs[0].type & IMMEDIATE)) {
1600 define_label(output_ins.label,
1601 output_ins.oprs[0].segment,
1602 output_ins.oprs[0].offset,
1603 NULL, false, false, ofmt,
1604 report_error);
1605 } else if (output_ins.operands == 2
1606 && (output_ins.oprs[0].
1607 type & IMMEDIATE)
1608 && (output_ins.oprs[0].type & COLON)
1609 && output_ins.oprs[0].segment ==
1610 NO_SEG
1611 && (output_ins.oprs[1].
1612 type & IMMEDIATE)
1613 && output_ins.oprs[1].segment ==
1614 NO_SEG) {
1615 define_label(output_ins.label,
1616 output_ins.oprs[0].
1617 offset | SEG_ABS,
1618 output_ins.oprs[1].offset,
1619 NULL, false, false, ofmt,
1620 report_error);
1621 } else
1622 report_error(ERR_NONFATAL,
1623 "bad syntax for EQU");
1626 } else { /* instruction isn't an EQU */
1628 if (pass1 == 1) {
1630 int64_t l = insn_size(location.segment, offs, sb, cpu,
1631 &output_ins, report_error);
1633 /* if (using_debug_info) && output_ins.opcode != -1) */
1634 if (using_debug_info)
1635 { /* fbk 03/25/01 */
1636 /* this is done here so we can do debug type info */
1637 int32_t typeinfo =
1638 TYS_ELEMENTS(output_ins.operands);
1639 switch (output_ins.opcode) {
1640 case I_RESB:
1641 typeinfo =
1642 TYS_ELEMENTS(output_ins.oprs[0].
1643 offset) | TY_BYTE;
1644 break;
1645 case I_RESW:
1646 typeinfo =
1647 TYS_ELEMENTS(output_ins.oprs[0].
1648 offset) | TY_WORD;
1649 break;
1650 case I_RESD:
1651 typeinfo =
1652 TYS_ELEMENTS(output_ins.oprs[0].
1653 offset) | TY_DWORD;
1654 break;
1655 case I_RESQ:
1656 typeinfo =
1657 TYS_ELEMENTS(output_ins.oprs[0].
1658 offset) | TY_QWORD;
1659 break;
1660 case I_REST:
1661 typeinfo =
1662 TYS_ELEMENTS(output_ins.oprs[0].
1663 offset) | TY_TBYTE;
1664 break;
1665 case I_RESO:
1666 typeinfo =
1667 TYS_ELEMENTS(output_ins.oprs[0].
1668 offset) | TY_OWORD;
1669 break;
1670 case I_RESY:
1671 typeinfo =
1672 TYS_ELEMENTS(output_ins.oprs[0].
1673 offset) | TY_YWORD;
1674 break;
1675 case I_DB:
1676 typeinfo |= TY_BYTE;
1677 break;
1678 case I_DW:
1679 typeinfo |= TY_WORD;
1680 break;
1681 case I_DD:
1682 if (output_ins.eops_float)
1683 typeinfo |= TY_FLOAT;
1684 else
1685 typeinfo |= TY_DWORD;
1686 break;
1687 case I_DQ:
1688 typeinfo |= TY_QWORD;
1689 break;
1690 case I_DT:
1691 typeinfo |= TY_TBYTE;
1692 break;
1693 case I_DO:
1694 typeinfo |= TY_OWORD;
1695 break;
1696 case I_DY:
1697 typeinfo |= TY_YWORD;
1698 break;
1699 default:
1700 typeinfo = TY_LABEL;
1704 ofmt->current_dfmt->debug_typevalue(typeinfo);
1707 if (l != -1) {
1708 offs += l;
1709 SET_CURR_OFFS(offs);
1712 * else l == -1 => invalid instruction, which will be
1713 * flagged as an error on pass 2
1716 } else {
1717 offs += assemble(location.segment, offs, sb, cpu,
1718 &output_ins, ofmt, report_error,
1719 &nasmlist);
1720 SET_CURR_OFFS(offs);
1723 } /* not an EQU */
1724 cleanup_insn(&output_ins);
1726 nasm_free(line);
1727 location.offset = offs = GET_CURR_OFFS;
1728 } /* end while (line = preproc->getline... */
1730 if (pass1 == 2 && global_offset_changed)
1731 report_error(ERR_NONFATAL,
1732 "phase error detected at end of assembly.");
1734 if (pass1 == 1)
1735 preproc->cleanup(1);
1737 if (pass1 == 1 && terminate_after_phase) {
1738 fclose(ofile);
1739 remove(outname);
1740 if (want_usage)
1741 usage();
1742 exit(1);
1744 if (passn >= pass_max - 2 ||
1745 (passn > 1 && !global_offset_changed))
1746 pass0++;
1749 preproc->cleanup(0);
1750 nasmlist.cleanup();
1751 #if 1
1752 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1753 fprintf(stdout,
1754 "info:: assembly required 1+%d+1 passes\n", passn-3);
1755 #endif
1756 } /* exit from assemble_file (...) */
1758 static enum directives getkw(char **directive, char **value)
1760 char *p, *q, *buf;
1762 buf = *directive;
1764 /* allow leading spaces or tabs */
1765 while (*buf == ' ' || *buf == '\t')
1766 buf++;
1768 if (*buf != '[')
1769 return 0;
1771 p = buf;
1773 while (*p && *p != ']')
1774 p++;
1776 if (!*p)
1777 return 0;
1779 q = p++;
1781 while (*p && *p != ';') {
1782 if (!isspace(*p))
1783 return 0;
1784 p++;
1786 q[1] = '\0';
1788 *directive = p = buf + 1;
1789 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1790 buf++;
1791 if (*buf == ']') {
1792 *buf = '\0';
1793 *value = buf;
1794 } else {
1795 *buf++ = '\0';
1796 while (isspace(*buf))
1797 buf++; /* beppu - skip leading whitespace */
1798 *value = buf;
1799 while (*buf != ']')
1800 buf++;
1801 *buf++ = '\0';
1804 return bsii(*directive, directives, elements(directives));
1808 * gnu style error reporting
1809 * This function prints an error message to error_file in the
1810 * style used by GNU. An example would be:
1811 * file.asm:50: error: blah blah blah
1812 * where file.asm is the name of the file, 50 is the line number on
1813 * which the error occurs (or is detected) and "error:" is one of
1814 * the possible optional diagnostics -- it can be "error" or "warning"
1815 * or something else. Finally the line terminates with the actual
1816 * error message.
1818 * @param severity the severity of the warning or error
1819 * @param fmt the printf style format string
1821 static void report_error_gnu(int severity, const char *fmt, ...)
1823 va_list ap;
1825 if (is_suppressed_warning(severity))
1826 return;
1828 if (severity & ERR_NOFILE)
1829 fputs("nasm: ", error_file);
1830 else {
1831 char *currentfile = NULL;
1832 int32_t lineno = 0;
1833 src_get(&lineno, &currentfile);
1834 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1835 nasm_free(currentfile);
1837 va_start(ap, fmt);
1838 report_error_common(severity, fmt, ap);
1839 va_end(ap);
1843 * MS style error reporting
1844 * This function prints an error message to error_file in the
1845 * style used by Visual C and some other Microsoft tools. An example
1846 * would be:
1847 * file.asm(50) : error: blah blah blah
1848 * where file.asm is the name of the file, 50 is the line number on
1849 * which the error occurs (or is detected) and "error:" is one of
1850 * the possible optional diagnostics -- it can be "error" or "warning"
1851 * or something else. Finally the line terminates with the actual
1852 * error message.
1854 * @param severity the severity of the warning or error
1855 * @param fmt the printf style format string
1857 static void report_error_vc(int severity, const char *fmt, ...)
1859 va_list ap;
1861 if (is_suppressed_warning(severity))
1862 return;
1864 if (severity & ERR_NOFILE)
1865 fputs("nasm: ", error_file);
1866 else {
1867 char *currentfile = NULL;
1868 int32_t lineno = 0;
1869 src_get(&lineno, &currentfile);
1870 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1871 nasm_free(currentfile);
1873 va_start(ap, fmt);
1874 report_error_common(severity, fmt, ap);
1875 va_end(ap);
1879 * check for supressed warning
1880 * checks for suppressed warning or pass one only warning and we're
1881 * not in pass 1
1883 * @param severity the severity of the warning or error
1884 * @return true if we should abort error/warning printing
1886 static bool is_suppressed_warning(int severity)
1889 * See if it's a suppressed warning.
1891 return (severity & ERR_MASK) == ERR_WARNING &&
1892 (((severity & ERR_WARN_MASK) != 0 &&
1893 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1894 /* See if it's a pass-one only warning and we're not in pass one. */
1895 ((severity & ERR_PASS1) && pass0 != 1));
1899 * common error reporting
1900 * This is the common back end of the error reporting schemes currently
1901 * implemented. It prints the nature of the warning and then the
1902 * specific error message to error_file and may or may not return. It
1903 * doesn't return if the error severity is a "panic" or "debug" type.
1905 * @param severity the severity of the warning or error
1906 * @param fmt the printf style format string
1908 static void report_error_common(int severity, const char *fmt,
1909 va_list args)
1911 switch (severity & ERR_MASK) {
1912 case ERR_WARNING:
1913 fputs("warning: ", error_file);
1914 break;
1915 case ERR_NONFATAL:
1916 fputs("error: ", error_file);
1917 break;
1918 case ERR_FATAL:
1919 fputs("fatal: ", error_file);
1920 break;
1921 case ERR_PANIC:
1922 fputs("panic: ", error_file);
1923 break;
1924 case ERR_DEBUG:
1925 fputs("debug: ", error_file);
1926 break;
1929 vfprintf(error_file, fmt, args);
1930 putc('\n', error_file);
1932 if (severity & ERR_USAGE)
1933 want_usage = true;
1935 switch (severity & ERR_MASK) {
1936 case ERR_DEBUG:
1937 /* no further action, by definition */
1938 break;
1939 case ERR_WARNING:
1940 if (!suppressed[0]) /* Treat warnings as errors */
1941 terminate_after_phase = true;
1942 break;
1943 case ERR_NONFATAL:
1944 terminate_after_phase = true;
1945 break;
1946 case ERR_FATAL:
1947 if (ofile) {
1948 fclose(ofile);
1949 remove(outname);
1951 if (want_usage)
1952 usage();
1953 exit(1); /* instantly die */
1954 break; /* placate silly compilers */
1955 case ERR_PANIC:
1956 fflush(NULL);
1957 /* abort(); *//* halt, catch fire, and dump core */
1958 exit(3);
1959 break;
1963 static void usage(void)
1965 fputs("type `nasm -h' for help\n", error_file);
1968 static void register_output_formats(void)
1970 ofmt = ofmt_register(report_error);
1973 #define BUF_DELTA 512
1975 static FILE *no_pp_fp;
1976 static efunc no_pp_err;
1977 static ListGen *no_pp_list;
1978 static int32_t no_pp_lineinc;
1980 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1981 ListGen * listgen, StrList **deplist)
1983 src_set_fname(nasm_strdup(file));
1984 src_set_linnum(0);
1985 no_pp_lineinc = 1;
1986 no_pp_err = error;
1987 no_pp_fp = fopen(file, "r");
1988 if (!no_pp_fp)
1989 no_pp_err(ERR_FATAL | ERR_NOFILE,
1990 "unable to open input file `%s'", file);
1991 no_pp_list = listgen;
1992 (void)pass; /* placate compilers */
1993 (void)eval; /* placate compilers */
1995 if (deplist) {
1996 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1997 sl->next = NULL;
1998 strcpy(sl->str, file);
1999 *deplist = sl;
2003 static char *no_pp_getline(void)
2005 char *buffer, *p, *q;
2006 int bufsize;
2008 bufsize = BUF_DELTA;
2009 buffer = nasm_malloc(BUF_DELTA);
2010 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2012 while (1) { /* Loop to handle %line */
2014 p = buffer;
2015 while (1) { /* Loop to handle long lines */
2016 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2017 if (!q)
2018 break;
2019 p += strlen(p);
2020 if (p > buffer && p[-1] == '\n')
2021 break;
2022 if (p - buffer > bufsize - 10) {
2023 int offset;
2024 offset = p - buffer;
2025 bufsize += BUF_DELTA;
2026 buffer = nasm_realloc(buffer, bufsize);
2027 p = buffer + offset;
2031 if (!q && p == buffer) {
2032 nasm_free(buffer);
2033 return NULL;
2037 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2038 * them are present at the end of the line.
2040 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2042 if (!nasm_strnicmp(buffer, "%line", 5)) {
2043 int32_t ln;
2044 int li;
2045 char *nm = nasm_malloc(strlen(buffer));
2046 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2047 nasm_free(src_set_fname(nm));
2048 src_set_linnum(ln);
2049 no_pp_lineinc = li;
2050 continue;
2052 nasm_free(nm);
2054 break;
2057 no_pp_list->line(LIST_READ, buffer);
2059 return buffer;
2062 static void no_pp_cleanup(int pass)
2064 (void)pass; /* placate GCC */
2065 fclose(no_pp_fp);
2068 static uint32_t get_cpu(char *value)
2070 if (!strcmp(value, "8086"))
2071 return IF_8086;
2072 if (!strcmp(value, "186"))
2073 return IF_186;
2074 if (!strcmp(value, "286"))
2075 return IF_286;
2076 if (!strcmp(value, "386"))
2077 return IF_386;
2078 if (!strcmp(value, "486"))
2079 return IF_486;
2080 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2081 return IF_PENT;
2082 if (!strcmp(value, "686") ||
2083 !nasm_stricmp(value, "ppro") ||
2084 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2085 return IF_P6;
2086 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2087 return IF_KATMAI;
2088 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2089 !nasm_stricmp(value, "willamette"))
2090 return IF_WILLAMETTE;
2091 if (!nasm_stricmp(value, "prescott"))
2092 return IF_PRESCOTT;
2093 if (!nasm_stricmp(value, "x64") ||
2094 !nasm_stricmp(value, "x86-64"))
2095 return IF_X86_64;
2096 if (!nasm_stricmp(value, "ia64") ||
2097 !nasm_stricmp(value, "ia-64") ||
2098 !nasm_stricmp(value, "itanium") ||
2099 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2100 return IF_IA64;
2102 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2103 "unknown 'cpu' type");
2105 return IF_PLEVEL; /* the maximum level */
2108 static int get_bits(char *value)
2110 int i;
2112 if ((i = atoi(value)) == 16)
2113 return i; /* set for a 16-bit segment */
2114 else if (i == 32) {
2115 if (cpu < IF_386) {
2116 report_error(ERR_NONFATAL,
2117 "cannot specify 32-bit segment on processor below a 386");
2118 i = 16;
2120 } else if (i == 64) {
2121 if (cpu < IF_X86_64) {
2122 report_error(ERR_NONFATAL,
2123 "cannot specify 64-bit segment on processor below an x86-64");
2124 i = 16;
2126 if (i != maxbits) {
2127 report_error(ERR_NONFATAL,
2128 "%s output format does not support 64-bit code",
2129 ofmt->shortname);
2130 i = 16;
2132 } else {
2133 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2134 "`%s' is not a valid segment size; must be 16, 32 or 64",
2135 value);
2136 i = 16;
2138 return i;
2141 /* end of nasm.c */