NASM 2.01
[nasm/autotest.git] / nasm.c
blobb5497a4eb7eeec28541df9e9abb4570d0c2be11b
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>
19 #include "nasm.h"
20 #include "nasmlib.h"
21 #include "float.h"
22 #include "stdscan.h"
23 #include "insns.h"
24 #include "preproc.h"
25 #include "parser.h"
26 #include "eval.h"
27 #include "assemble.h"
28 #include "labels.h"
29 #include "outform.h"
30 #include "listing.h"
32 struct forwrefinfo { /* info held on forward refs. */
33 int lineno;
34 int operand;
37 static int get_bits(char *value);
38 static uint32_t get_cpu(char *cpu_str);
39 static void parse_cmdline(int, char **);
40 static void assemble_file(char *);
41 static void register_output_formats(void);
42 static void report_error_gnu(int severity, const char *fmt, ...);
43 static void report_error_vc(int severity, const char *fmt, ...);
44 static void report_error_common(int severity, const char *fmt,
45 va_list args);
46 static int is_suppressed_warning(int severity);
47 static void usage(void);
48 static efunc report_error;
50 static int using_debug_info, opt_verbose_info;
51 bool tasm_compatible_mode = false;
52 int pass0, passn;
53 int maxbits = 0;
54 int globalrel = 0;
56 static char inname[FILENAME_MAX];
57 static char outname[FILENAME_MAX];
58 static char listname[FILENAME_MAX];
59 static char errname[FILENAME_MAX];
60 static int globallineno; /* for forward-reference tracking */
61 /* static int pass = 0; */
62 static struct ofmt *ofmt = NULL;
64 static FILE *error_file; /* Where to write error messages */
66 static FILE *ofile = NULL;
67 int optimizing = -1; /* number of optimization passes to take */
68 static int sb, cmd_sb = 16; /* by default */
69 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
70 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
71 bool global_offset_changed; /* referenced in labels.c */
73 static struct location location;
74 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
75 int32_t abs_seg; /* ABSOLUTE segment basis */
76 int32_t abs_offset; /* ABSOLUTE offset */
78 static struct RAA *offsets;
80 static struct SAA *forwrefs; /* keep track of forward references */
81 static const struct forwrefinfo *forwref;
83 static Preproc *preproc;
84 enum op_type {
85 op_normal, /* Preprocess and assemble */
86 op_preprocess, /* Preprocess only */
87 op_depend, /* Generate dependencies */
88 op_depend_missing_ok, /* Generate dependencies, missing OK */
90 static enum op_type operating_mode;
93 * Which of the suppressible warnings are suppressed. Entry zero
94 * isn't an actual warning, but it used for -w+error/-Werror.
96 static bool suppressed[ERR_WARN_MAX+1] = {
97 true, false, true, false, false, true, false, true, true, false
101 * The option names for the suppressible warnings. As before, entry
102 * zero does nothing.
104 static const char *suppressed_names[ERR_WARN_MAX+1] = {
105 "error", "macro-params", "macro-selfref", "orphan-labels",
106 "number-overflow", "gnu-elf-extensions", "float-overflow",
107 "float-denorm", "float-underflow", "float-toolong"
111 * The explanations for the suppressible warnings. As before, entry
112 * zero does nothing.
114 static const char *suppressed_what[ERR_WARN_MAX+1] = {
115 "treat warnings as errors",
116 "macro calls with wrong parameter count",
117 "cyclic macro references",
118 "labels alone on lines without trailing `:'",
119 "numeric constants does not fit in 64 bits",
120 "using 8- or 16-bit relocation in ELF32, a GNU extension",
121 "floating point overflow",
122 "floating point denormal",
123 "floating point underflow",
124 "too many digits in floating-point number"
128 * This is a null preprocessor which just copies lines from input
129 * to output. It's used when someone explicitly requests that NASM
130 * not preprocess their source file.
133 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *);
134 static char *no_pp_getline(void);
135 static void no_pp_cleanup(int);
136 static Preproc no_pp = {
137 no_pp_reset,
138 no_pp_getline,
139 no_pp_cleanup
143 * get/set current offset...
145 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
146 raa_read(offsets,location.segment))
147 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
148 (void)(offsets=raa_write(offsets,location.segment,(x))))
150 static int want_usage;
151 static int terminate_after_phase;
152 int user_nolist = 0; /* fbk 9/2/00 */
154 static void nasm_fputs(const char *line, FILE * outfile)
156 if (outfile) {
157 fputs(line, outfile);
158 putc('\n', outfile);
159 } else
160 puts(line);
163 int main(int argc, char **argv)
165 pass0 = 1;
166 want_usage = terminate_after_phase = false;
167 report_error = report_error_gnu;
169 error_file = stderr;
171 nasm_set_malloc_error(report_error);
172 offsets = raa_init();
173 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
175 preproc = &nasmpp;
176 operating_mode = op_normal;
178 seg_init();
180 register_output_formats();
182 parse_cmdline(argc, argv);
184 if (terminate_after_phase) {
185 if (want_usage)
186 usage();
187 return 1;
190 /* If debugging info is disabled, suppress any debug calls */
191 if (!using_debug_info)
192 ofmt->current_dfmt = &null_debug_form;
194 if (ofmt->stdmac)
195 pp_extra_stdmac(ofmt->stdmac);
196 parser_global_info(ofmt, &location);
197 eval_global_info(ofmt, lookup_label, &location);
199 /* define some macros dependent of command-line */
201 char temp[64];
202 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
203 ofmt->shortname);
204 pp_pre_define(temp);
207 switch (operating_mode) {
208 case op_depend_missing_ok:
209 pp_include_path(NULL); /* "assume generated" */
210 /* fall through */
211 case op_depend:
213 char *line;
214 preproc->reset(inname, 0, report_error, evaluate, &nasmlist);
215 if (outname[0] == '\0')
216 ofmt->filename(inname, outname, report_error);
217 ofile = NULL;
218 fprintf(stdout, "%s: %s", outname, inname);
219 while ((line = preproc->getline()))
220 nasm_free(line);
221 preproc->cleanup(0);
222 putc('\n', stdout);
224 break;
226 case op_preprocess:
228 char *line;
229 char *file_name = NULL;
230 int32_t prior_linnum = 0;
231 int lineinc = 0;
233 if (*outname) {
234 ofile = fopen(outname, "w");
235 if (!ofile)
236 report_error(ERR_FATAL | ERR_NOFILE,
237 "unable to open output file `%s'",
238 outname);
239 } else
240 ofile = NULL;
242 location.known = false;
244 /* pass = 1; */
245 preproc->reset(inname, 2, report_error, evaluate, &nasmlist);
246 while ((line = preproc->getline())) {
248 * We generate %line directives if needed for later programs
250 int32_t linnum = prior_linnum += lineinc;
251 int altline = src_get(&linnum, &file_name);
252 if (altline) {
253 if (altline == 1 && lineinc == 1)
254 nasm_fputs("", ofile);
255 else {
256 lineinc = (altline != -1 || lineinc != 1);
257 fprintf(ofile ? ofile : stdout,
258 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
259 file_name);
261 prior_linnum = linnum;
263 nasm_fputs(line, ofile);
264 nasm_free(line);
266 nasm_free(file_name);
267 preproc->cleanup(0);
268 if (ofile)
269 fclose(ofile);
270 if (ofile && terminate_after_phase)
271 remove(outname);
273 break;
275 case op_normal:
278 * We must call ofmt->filename _anyway_, even if the user
279 * has specified their own output file, because some
280 * formats (eg OBJ and COFF) use ofmt->filename to find out
281 * the name of the input file and then put that inside the
282 * file.
284 ofmt->filename(inname, outname, report_error);
286 ofile = fopen(outname, "wb");
287 if (!ofile) {
288 report_error(ERR_FATAL | ERR_NOFILE,
289 "unable to open output file `%s'", outname);
293 * We must call init_labels() before ofmt->init() since
294 * some object formats will want to define labels in their
295 * init routines. (eg OS/2 defines the FLAT group)
297 init_labels();
299 ofmt->init(ofile, report_error, define_label, evaluate);
301 assemble_file(inname);
303 if (!terminate_after_phase) {
304 ofmt->cleanup(using_debug_info);
305 cleanup_labels();
306 } else {
308 * We had an fclose on the output file here, but we
309 * actually do that in all the object file drivers as well,
310 * so we're leaving out the one here.
311 * fclose (ofile);
313 remove(outname);
314 if (listname[0])
315 remove(listname);
318 break;
321 if (want_usage)
322 usage();
324 raa_free(offsets);
325 saa_free(forwrefs);
326 eval_cleanup();
327 stdscan_cleanup();
329 if (terminate_after_phase)
330 return 1;
331 else
332 return 0;
336 * Get a parameter for a command line option.
337 * First arg must be in the form of e.g. -f...
339 static char *get_param(char *p, char *q, bool *advance)
341 *advance = false;
342 if (p[2]) { /* the parameter's in the option */
343 p += 2;
344 while (isspace(*p))
345 p++;
346 return p;
348 if (q && q[0]) {
349 *advance = true;
350 return q;
352 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
353 "option `-%c' requires an argument", p[1]);
354 return NULL;
358 * Copy a filename
360 static void copy_filename(char *dst, const char *src)
362 size_t len = strlen(src);
364 if (len >= (size_t)FILENAME_MAX) {
365 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
366 return;
368 strncpy(dst, src, FILENAME_MAX);
371 struct textargs {
372 const char *label;
373 int value;
376 #define OPT_PREFIX 0
377 #define OPT_POSTFIX 1
378 struct textargs textopts[] = {
379 {"prefix", OPT_PREFIX},
380 {"postfix", OPT_POSTFIX},
381 {NULL, 0}
384 static bool stopoptions = false;
385 static bool process_arg(char *p, char *q)
387 char *param;
388 int i;
389 bool advance = false;
390 bool suppress;
392 if (!p || !p[0])
393 return false;
395 if (p[0] == '-' && !stopoptions) {
396 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
397 /* These parameters take values */
398 if (!(param = get_param(p, q, &advance)))
399 return advance;
402 switch (p[1]) {
403 case 's':
404 error_file = stdout;
405 break;
407 case 'o': /* output file */
408 copy_filename(outname, param);
409 break;
411 case 'f': /* output format */
412 ofmt = ofmt_find(param);
413 if (!ofmt) {
414 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
415 "unrecognised output format `%s' - "
416 "use -hf for a list", param);
417 } else {
418 ofmt->current_dfmt = ofmt->debug_formats[0];
420 break;
422 case 'O': /* Optimization level */
424 int opt;
426 if (!*param) {
427 /* Naked -O == -Ox */
428 optimizing = INT_MAX >> 1; /* Almost unlimited */
429 } else {
430 while (*param) {
431 switch (*param) {
432 case '0': case '1': case '2': case '3': case '4':
433 case '5': case '6': case '7': case '8': case '9':
434 opt = strtoul(param, &param, 10);
436 /* -O0 -> optimizing == -1, 0.98 behaviour */
437 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
438 if (opt < 2)
439 optimizing = opt - 1;
440 else
441 optimizing = opt;
442 break;
444 case 'v':
445 case '+':
446 param++;
447 opt_verbose_info = true;
448 break;
450 case 'x':
451 param++;
452 optimizing = INT_MAX >> 1; /* Almost unlimited */
453 break;
455 default:
456 report_error(ERR_FATAL,
457 "unknown optimization option -O%c\n",
458 *param);
459 break;
463 break;
466 case 'p': /* pre-include */
467 case 'P':
468 pp_pre_include(param);
469 break;
471 case 'd': /* pre-define */
472 case 'D':
473 pp_pre_define(param);
474 break;
476 case 'u': /* un-define */
477 case 'U':
478 pp_pre_undefine(param);
479 break;
481 case 'i': /* include search path */
482 case 'I':
483 pp_include_path(param);
484 break;
486 case 'l': /* listing file */
487 copy_filename(listname, param);
488 break;
490 case 'Z': /* error messages file */
491 strcpy(errname, param);
492 break;
494 case 'F': /* specify debug format */
495 ofmt->current_dfmt = dfmt_find(ofmt, param);
496 if (!ofmt->current_dfmt) {
497 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
498 "unrecognized debug format `%s' for"
499 " output format `%s'",
500 param, ofmt->shortname);
502 break;
504 case 'X': /* specify error reporting format */
505 if (nasm_stricmp("vc", param) == 0)
506 report_error = report_error_vc;
507 else if (nasm_stricmp("gnu", param) == 0)
508 report_error = report_error_gnu;
509 else
510 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
511 "unrecognized error reporting format `%s'",
512 param);
513 break;
515 case 'g':
516 using_debug_info = true;
517 break;
519 case 'h':
520 printf
521 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
522 "[-l listfile]\n"
523 " [options...] [--] filename\n"
524 " or nasm -v for version info\n\n"
525 " -t assemble in SciTech TASM compatible mode\n"
526 " -g generate debug information in selected format.\n");
527 printf
528 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
529 " -a don't preprocess (assemble only)\n"
530 " -M generate Makefile dependencies on stdout\n"
531 " -MG d:o, missing files assumed generated\n\n"
532 " -Z<file> redirect error messages to file\n"
533 " -s redirect error messages to stdout\n\n"
534 " -F format select a debugging format\n\n"
535 " -I<path> adds a pathname to the include file path\n");
536 printf
537 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
538 " -P<file> pre-includes a file\n"
539 " -D<macro>[=<value>] pre-defines a macro\n"
540 " -U<macro> undefines a macro\n"
541 " -X<format> specifies error reporting format (gnu or vc)\n"
542 " -w+foo enables warning foo (equiv. -Wfoo)\n"
543 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
544 "Warnings:\n");
545 for (i = 0; i <= ERR_WARN_MAX; i++)
546 printf(" %-23s %s (default %s)\n",
547 suppressed_names[i], suppressed_what[i],
548 suppressed[i] ? "off" : "on");
549 printf
550 ("\nresponse files should contain command line parameters"
551 ", one per line.\n");
552 if (p[2] == 'f') {
553 printf("\nvalid output formats for -f are"
554 " (`*' denotes default):\n");
555 ofmt_list(ofmt, stdout);
556 } else {
557 printf("\nFor a list of valid output formats, use -hf.\n");
558 printf("For a list of debug formats, use -f <form> -y.\n");
560 exit(0); /* never need usage message here */
561 break;
563 case 'y':
564 printf("\nvalid debug formats for '%s' output format are"
565 " ('*' denotes default):\n", ofmt->shortname);
566 dfmt_list(ofmt, stdout);
567 exit(0);
568 break;
570 case 't':
571 tasm_compatible_mode = true;
572 break;
574 case 'v':
576 const char *nasm_version_string =
577 "NASM version " NASM_VER " compiled on " __DATE__
578 #ifdef DEBUG
579 " with -DDEBUG"
580 #endif
582 puts(nasm_version_string);
583 exit(0); /* never need usage message here */
585 break;
587 case 'e': /* preprocess only */
588 case 'E':
589 operating_mode = op_preprocess;
590 break;
592 case 'a': /* assemble only - don't preprocess */
593 preproc = &no_pp;
594 break;
596 case 'W':
597 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
598 suppress = true;
599 param += 3;
600 } else {
601 suppress = false;
603 goto set_warning;
605 case 'w':
606 if (param[0] != '+' && param[0] != '-') {
607 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
608 "invalid option to `-w'");
609 break;
611 suppress = (param[0] == '-');
612 param++;
613 goto set_warning;
614 set_warning:
615 for (i = 0; i <= ERR_WARN_MAX; i++)
616 if (!nasm_stricmp(param, suppressed_names[i]))
617 break;
618 if (i <= ERR_WARN_MAX)
619 suppressed[i] = suppress;
620 else if (!nasm_stricmp(param, "all"))
621 for (i = 1; i <= ERR_WARN_MAX; i++)
622 suppressed[i] = suppress;
623 else if (!nasm_stricmp(param, "none"))
624 for (i = 1; i <= ERR_WARN_MAX; i++)
625 suppressed[i] = !suppress;
626 else
627 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
628 "invalid warning `%s'", param);
629 break;
631 case 'M':
632 operating_mode = p[2] == 'G' ? op_depend_missing_ok : op_depend;
633 break;
635 case '-':
637 int s;
639 if (p[2] == 0) { /* -- => stop processing options */
640 stopoptions = 1;
641 break;
643 for (s = 0; textopts[s].label; s++) {
644 if (!nasm_stricmp(p + 2, textopts[s].label)) {
645 break;
649 switch (s) {
651 case OPT_PREFIX:
652 case OPT_POSTFIX:
654 if (!q) {
655 report_error(ERR_NONFATAL | ERR_NOFILE |
656 ERR_USAGE,
657 "option `--%s' requires an argument",
658 p + 2);
659 break;
660 } else {
661 advance = 1, param = q;
664 if (s == OPT_PREFIX) {
665 strncpy(lprefix, param, PREFIX_MAX - 1);
666 lprefix[PREFIX_MAX - 1] = 0;
667 break;
669 if (s == OPT_POSTFIX) {
670 strncpy(lpostfix, param, POSTFIX_MAX - 1);
671 lpostfix[POSTFIX_MAX - 1] = 0;
672 break;
674 break;
676 default:
678 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
679 "unrecognised option `--%s'", p + 2);
680 break;
683 break;
686 default:
687 if (!ofmt->setinfo(GI_SWITCH, &p))
688 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
689 "unrecognised option `-%c'", p[1]);
690 break;
692 } else {
693 if (*inname) {
694 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
695 "more than one input file specified");
696 } else {
697 copy_filename(inname, p);
701 return advance;
704 #define ARG_BUF_DELTA 128
706 static void process_respfile(FILE * rfile)
708 char *buffer, *p, *q, *prevarg;
709 int bufsize, prevargsize;
711 bufsize = prevargsize = ARG_BUF_DELTA;
712 buffer = nasm_malloc(ARG_BUF_DELTA);
713 prevarg = nasm_malloc(ARG_BUF_DELTA);
714 prevarg[0] = '\0';
716 while (1) { /* Loop to handle all lines in file */
717 p = buffer;
718 while (1) { /* Loop to handle long lines */
719 q = fgets(p, bufsize - (p - buffer), rfile);
720 if (!q)
721 break;
722 p += strlen(p);
723 if (p > buffer && p[-1] == '\n')
724 break;
725 if (p - buffer > bufsize - 10) {
726 int offset;
727 offset = p - buffer;
728 bufsize += ARG_BUF_DELTA;
729 buffer = nasm_realloc(buffer, bufsize);
730 p = buffer + offset;
734 if (!q && p == buffer) {
735 if (prevarg[0])
736 process_arg(prevarg, NULL);
737 nasm_free(buffer);
738 nasm_free(prevarg);
739 return;
743 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
744 * them are present at the end of the line.
746 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
748 while (p > buffer && isspace(p[-1]))
749 *--p = '\0';
751 p = buffer;
752 while (isspace(*p))
753 p++;
755 if (process_arg(prevarg, p))
756 *p = '\0';
758 if ((int) strlen(p) > prevargsize - 10) {
759 prevargsize += ARG_BUF_DELTA;
760 prevarg = nasm_realloc(prevarg, prevargsize);
762 strncpy(prevarg, p, prevargsize);
766 /* Function to process args from a string of args, rather than the
767 * argv array. Used by the environment variable and response file
768 * processing.
770 static void process_args(char *args)
772 char *p, *q, *arg, *prevarg;
773 char separator = ' ';
775 p = args;
776 if (*p && *p != '-')
777 separator = *p++;
778 arg = NULL;
779 while (*p) {
780 q = p;
781 while (*p && *p != separator)
782 p++;
783 while (*p == separator)
784 *p++ = '\0';
785 prevarg = arg;
786 arg = q;
787 if (process_arg(prevarg, arg))
788 arg = NULL;
790 if (arg)
791 process_arg(arg, NULL);
794 static void parse_cmdline(int argc, char **argv)
796 FILE *rfile;
797 char *envreal, *envcopy = NULL, *p, *arg;
799 *inname = *outname = *listname = *errname = '\0';
802 * First, process the NASMENV environment variable.
804 envreal = getenv("NASMENV");
805 arg = NULL;
806 if (envreal) {
807 envcopy = nasm_strdup(envreal);
808 process_args(envcopy);
809 nasm_free(envcopy);
813 * Now process the actual command line.
815 while (--argc) {
816 bool advance;
817 argv++;
818 if (argv[0][0] == '@') {
819 /* We have a response file, so process this as a set of
820 * arguments like the environment variable. This allows us
821 * to have multiple arguments on a single line, which is
822 * different to the -@resp file processing below for regular
823 * NASM.
825 char *str = malloc(2048);
826 FILE *f = fopen(&argv[0][1], "r");
827 if (!str) {
828 printf("out of memory");
829 exit(-1);
831 if (f) {
832 while (fgets(str, 2048, f)) {
833 process_args(str);
835 fclose(f);
837 free(str);
838 argc--;
839 argv++;
841 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
842 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
843 if (p) {
844 rfile = fopen(p, "r");
845 if (rfile) {
846 process_respfile(rfile);
847 fclose(rfile);
848 } else
849 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
850 "unable to open response file `%s'", p);
852 } else
853 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
854 argv += advance, argc -= advance;
857 /* Look for basic command line typos. This definitely doesn't
858 catch all errors, but it might help cases of fumbled fingers. */
859 if (!*inname)
860 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
861 "no input file specified");
862 else if (!strcmp(inname, errname) || !strcmp(inname, outname) ||
863 !strcmp(inname, listname))
864 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
865 "file `%s' is both input and output file",
866 inname);
868 if (*errname) {
869 error_file = fopen(errname, "w");
870 if (!error_file) {
871 error_file = stderr; /* Revert to default! */
872 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
873 "cannot open file `%s' for error messages",
874 errname);
879 /* List of directives */
880 enum directives {
881 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
882 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
884 static const char *directives[] = {
885 "", "absolute", "bits", "common", "cpu", "debug", "default",
886 "extern", "float", "global", "list", "section", "segment", "warning"
888 static enum directives getkw(char **directive, char **value);
890 static void assemble_file(char *fname)
892 char *directive, *value, *p, *q, *special, *line, debugid[80];
893 insn output_ins;
894 int i, validid;
895 bool rn_error;
896 int32_t seg;
897 int64_t offs;
898 struct tokenval tokval;
899 expr *e;
900 int pass_max;
902 if (cmd_sb == 32 && cmd_cpu < IF_386)
903 report_error(ERR_FATAL, "command line: "
904 "32-bit segment size requires a higher cpu");
906 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
907 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
908 for (passn = 1; pass0 <= 2; passn++) {
909 int pass1, pass2;
910 ldfunc def_label;
912 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
913 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
914 /* pass0 0, 0, 0, ..., 1, 2 */
916 def_label = passn > 1 ? redefine_label : define_label;
918 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
919 cpu = cmd_cpu;
920 if (pass0 == 2) {
921 if (*listname)
922 nasmlist.init(listname, report_error);
924 in_abs_seg = false;
925 global_offset_changed = false; /* set by redefine_label */
926 location.segment = ofmt->section(NULL, pass2, &sb);
927 globalbits = sb;
928 if (passn > 1) {
929 saa_rewind(forwrefs);
930 forwref = saa_rstruct(forwrefs);
931 raa_free(offsets);
932 offsets = raa_init();
934 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
935 globallineno = 0;
936 if (passn == 1)
937 location.known = true;
938 location.offset = offs = GET_CURR_OFFS;
940 while ((line = preproc->getline())) {
941 enum directives d;
942 globallineno++;
944 /* here we parse our directives; this is not handled by the 'real'
945 * parser. */
946 directive = line;
947 d = getkw(&directive, &value);
948 if (d) {
949 int err = 0;
951 switch (d) {
952 case D_SEGMENT: /* [SEGMENT n] */
953 case D_SECTION:
954 seg = ofmt->section(value, pass2, &sb);
955 if (seg == NO_SEG) {
956 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
957 "segment name `%s' not recognized",
958 value);
959 } else {
960 in_abs_seg = false;
961 location.segment = seg;
963 break;
964 case D_EXTERN: /* [EXTERN label:special] */
965 if (*value == '$')
966 value++; /* skip initial $ if present */
967 if (pass0 == 2) {
968 q = value;
969 while (*q && *q != ':')
970 q++;
971 if (*q == ':') {
972 *q++ = '\0';
973 ofmt->symdef(value, 0L, 0L, 3, q);
975 } else if (passn == 1) {
976 q = value;
977 validid = true;
978 if (!isidstart(*q))
979 validid = false;
980 while (*q && *q != ':') {
981 if (!isidchar(*q))
982 validid = false;
983 q++;
985 if (!validid) {
986 report_error(ERR_NONFATAL,
987 "identifier expected after EXTERN");
988 break;
990 if (*q == ':') {
991 *q++ = '\0';
992 special = q;
993 } else
994 special = NULL;
995 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
996 int temp = pass0;
997 pass0 = 1; /* fake pass 1 in labels.c */
998 declare_as_global(value, special,
999 report_error);
1000 define_label(value, seg_alloc(), 0L, NULL,
1001 false, true, ofmt, report_error);
1002 pass0 = temp;
1004 } /* else pass0 == 1 */
1005 break;
1006 case D_BITS: /* [BITS bits] */
1007 globalbits = sb = get_bits(value);
1008 break;
1009 case D_GLOBAL: /* [GLOBAL symbol:special] */
1010 if (*value == '$')
1011 value++; /* skip initial $ if present */
1012 if (pass0 == 2) { /* pass 2 */
1013 q = value;
1014 while (*q && *q != ':')
1015 q++;
1016 if (*q == ':') {
1017 *q++ = '\0';
1018 ofmt->symdef(value, 0L, 0L, 3, q);
1020 } else if (pass2 == 1) { /* pass == 1 */
1021 q = value;
1022 validid = true;
1023 if (!isidstart(*q))
1024 validid = false;
1025 while (*q && *q != ':') {
1026 if (!isidchar(*q))
1027 validid = false;
1028 q++;
1030 if (!validid) {
1031 report_error(ERR_NONFATAL,
1032 "identifier expected after GLOBAL");
1033 break;
1035 if (*q == ':') {
1036 *q++ = '\0';
1037 special = q;
1038 } else
1039 special = NULL;
1040 declare_as_global(value, special, report_error);
1041 } /* pass == 1 */
1042 break;
1043 case D_COMMON: /* [COMMON symbol size:special] */
1044 if (*value == '$')
1045 value++; /* skip initial $ if present */
1046 if (pass0 == 1) {
1047 p = value;
1048 validid = true;
1049 if (!isidstart(*p))
1050 validid = false;
1051 while (*p && !isspace(*p)) {
1052 if (!isidchar(*p))
1053 validid = false;
1054 p++;
1056 if (!validid) {
1057 report_error(ERR_NONFATAL,
1058 "identifier expected after COMMON");
1059 break;
1061 if (*p) {
1062 int64_t size;
1064 while (*p && isspace(*p))
1065 *p++ = '\0';
1066 q = p;
1067 while (*q && *q != ':')
1068 q++;
1069 if (*q == ':') {
1070 *q++ = '\0';
1071 special = q;
1072 } else
1073 special = NULL;
1074 size = readnum(p, &rn_error);
1075 if (rn_error)
1076 report_error(ERR_NONFATAL,
1077 "invalid size specified"
1078 " in COMMON declaration");
1079 else
1080 define_common(value, seg_alloc(), size,
1081 special, ofmt, report_error);
1082 } else
1083 report_error(ERR_NONFATAL,
1084 "no size specified in"
1085 " COMMON declaration");
1086 } else if (pass0 == 2) { /* pass == 2 */
1087 q = value;
1088 while (*q && *q != ':') {
1089 if (isspace(*q))
1090 *q = '\0';
1091 q++;
1093 if (*q == ':') {
1094 *q++ = '\0';
1095 ofmt->symdef(value, 0L, 0L, 3, q);
1098 break;
1099 case D_ABSOLUTE: /* [ABSOLUTE address] */
1100 stdscan_reset();
1101 stdscan_bufptr = value;
1102 tokval.t_type = TOKEN_INVALID;
1103 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1104 report_error, NULL);
1105 if (e) {
1106 if (!is_reloc(e))
1107 report_error(pass0 ==
1108 1 ? ERR_NONFATAL : ERR_PANIC,
1109 "cannot use non-relocatable expression as "
1110 "ABSOLUTE address");
1111 else {
1112 abs_seg = reloc_seg(e);
1113 abs_offset = reloc_value(e);
1115 } else if (passn == 1)
1116 abs_offset = 0x100; /* don't go near zero in case of / */
1117 else
1118 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1119 "in pass two");
1120 in_abs_seg = true;
1121 location.segment = NO_SEG;
1122 break;
1123 case D_DEBUG: /* [DEBUG] */
1124 p = value;
1125 q = debugid;
1126 validid = true;
1127 if (!isidstart(*p))
1128 validid = false;
1129 while (*p && !isspace(*p)) {
1130 if (!isidchar(*p))
1131 validid = false;
1132 *q++ = *p++;
1134 *q++ = 0;
1135 if (!validid) {
1136 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1137 "identifier expected after DEBUG");
1138 break;
1140 while (*p && isspace(*p))
1141 p++;
1142 if (pass0 == 2)
1143 ofmt->current_dfmt->debug_directive(debugid, p);
1144 break;
1145 case D_WARNING: /* [WARNING {+|-}warn-name] */
1146 if (pass1 == 1) {
1147 while (*value && isspace(*value))
1148 value++;
1150 if (*value == '+' || *value == '-') {
1151 validid = (*value == '-') ? true : false;
1152 value++;
1153 } else
1154 validid = false;
1156 for (i = 1; i <= ERR_WARN_MAX; i++)
1157 if (!nasm_stricmp(value, suppressed_names[i]))
1158 break;
1159 if (i <= ERR_WARN_MAX)
1160 suppressed[i] = validid;
1161 else
1162 report_error(ERR_NONFATAL,
1163 "invalid warning id in WARNING directive");
1165 break;
1166 case D_CPU: /* [CPU] */
1167 cpu = get_cpu(value);
1168 break;
1169 case D_LIST: /* [LIST {+|-}] */
1170 while (*value && isspace(*value))
1171 value++;
1173 if (*value == '+') {
1174 user_nolist = 0;
1175 } else {
1176 if (*value == '-') {
1177 user_nolist = 1;
1178 } else {
1179 err = 1;
1182 break;
1183 case D_DEFAULT: /* [DEFAULT] */
1184 stdscan_reset();
1185 stdscan_bufptr = value;
1186 tokval.t_type = TOKEN_INVALID;
1187 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1188 switch ((int)tokval.t_integer) {
1189 case S_REL:
1190 globalrel = 1;
1191 break;
1192 case S_ABS:
1193 globalrel = 0;
1194 break;
1195 default:
1196 err = 1;
1197 break;
1199 } else {
1200 err = 1;
1202 break;
1203 case D_FLOAT:
1204 if (float_option(value)) {
1205 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1206 "unknown 'float' directive: %s",
1207 value);
1209 break;
1210 default:
1211 if (!ofmt->directive(directive, value, pass2))
1212 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1213 "unrecognised directive [%s]",
1214 directive);
1216 if (err) {
1217 report_error(ERR_NONFATAL,
1218 "invalid parameter to [%s] directive",
1219 directive);
1221 } else { /* it isn't a directive */
1223 parse_line(pass1, line, &output_ins,
1224 report_error, evaluate, def_label);
1226 if (!(optimizing > 0) && pass0 == 2) {
1227 if (forwref != NULL && globallineno == forwref->lineno) {
1228 output_ins.forw_ref = true;
1229 do {
1230 output_ins.oprs[forwref->operand].opflags |=
1231 OPFLAG_FORWARD;
1232 forwref = saa_rstruct(forwrefs);
1233 } while (forwref != NULL
1234 && forwref->lineno == globallineno);
1235 } else
1236 output_ins.forw_ref = false;
1239 if (!(optimizing > 0) && output_ins.forw_ref) {
1240 if (passn == 1) {
1241 for (i = 0; i < output_ins.operands; i++) {
1242 if (output_ins.oprs[i].
1243 opflags & OPFLAG_FORWARD) {
1244 struct forwrefinfo *fwinf =
1245 (struct forwrefinfo *)
1246 saa_wstruct(forwrefs);
1247 fwinf->lineno = globallineno;
1248 fwinf->operand = i;
1251 } else { /* passn > 1 */
1253 * Hack to prevent phase error in the code
1254 * rol ax,x
1255 * x equ 1
1257 * If the second operand is a forward reference,
1258 * the UNITY property of the number 1 in that
1259 * operand is cancelled. Otherwise the above
1260 * sequence will cause a phase error.
1262 * This hack means that the above code will
1263 * generate 286+ code.
1265 * The forward reference will mean that the
1266 * operand will not have the UNITY property on
1267 * the first pass, so the pass behaviours will
1268 * be consistent.
1271 if (output_ins.operands >= 2 &&
1272 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1273 !(IMMEDIATE & ~output_ins.oprs[1].type))
1275 /* Remove special properties bits */
1276 output_ins.oprs[1].type &= ~REG_SMASK;
1283 /* forw_ref */
1284 if (output_ins.opcode == I_EQU) {
1285 if (pass1 == 1) {
1287 * Special `..' EQUs get processed in pass two,
1288 * except `..@' macro-processor EQUs which are done
1289 * in the normal place.
1291 if (!output_ins.label)
1292 report_error(ERR_NONFATAL,
1293 "EQU not preceded by label");
1295 else if (output_ins.label[0] != '.' ||
1296 output_ins.label[1] != '.' ||
1297 output_ins.label[2] == '@') {
1298 if (output_ins.operands == 1 &&
1299 (output_ins.oprs[0].type & IMMEDIATE) &&
1300 output_ins.oprs[0].wrt == NO_SEG) {
1301 int isext =
1302 output_ins.oprs[0].
1303 opflags & OPFLAG_EXTERN;
1304 def_label(output_ins.label,
1305 output_ins.oprs[0].segment,
1306 output_ins.oprs[0].offset, NULL,
1307 false, isext, ofmt,
1308 report_error);
1309 } else if (output_ins.operands == 2
1310 && (output_ins.oprs[0].
1311 type & IMMEDIATE)
1312 && (output_ins.oprs[0].type & COLON)
1313 && output_ins.oprs[0].segment ==
1314 NO_SEG
1315 && output_ins.oprs[0].wrt == NO_SEG
1316 && (output_ins.oprs[1].
1317 type & IMMEDIATE)
1318 && output_ins.oprs[1].segment ==
1319 NO_SEG
1320 && output_ins.oprs[1].wrt ==
1321 NO_SEG) {
1322 def_label(output_ins.label,
1323 output_ins.oprs[0].
1324 offset | SEG_ABS,
1325 output_ins.oprs[1].offset, NULL,
1326 false, false, ofmt,
1327 report_error);
1328 } else
1329 report_error(ERR_NONFATAL,
1330 "bad syntax for EQU");
1332 } else {
1334 * Special `..' EQUs get processed here, except
1335 * `..@' macro processor EQUs which are done above.
1337 if (output_ins.label[0] == '.' &&
1338 output_ins.label[1] == '.' &&
1339 output_ins.label[2] != '@') {
1340 if (output_ins.operands == 1 &&
1341 (output_ins.oprs[0].type & IMMEDIATE)) {
1342 define_label(output_ins.label,
1343 output_ins.oprs[0].segment,
1344 output_ins.oprs[0].offset,
1345 NULL, false, false, ofmt,
1346 report_error);
1347 } else if (output_ins.operands == 2
1348 && (output_ins.oprs[0].
1349 type & IMMEDIATE)
1350 && (output_ins.oprs[0].type & COLON)
1351 && output_ins.oprs[0].segment ==
1352 NO_SEG
1353 && (output_ins.oprs[1].
1354 type & IMMEDIATE)
1355 && output_ins.oprs[1].segment ==
1356 NO_SEG) {
1357 define_label(output_ins.label,
1358 output_ins.oprs[0].
1359 offset | SEG_ABS,
1360 output_ins.oprs[1].offset,
1361 NULL, false, false, ofmt,
1362 report_error);
1363 } else
1364 report_error(ERR_NONFATAL,
1365 "bad syntax for EQU");
1368 } else { /* instruction isn't an EQU */
1370 if (pass1 == 1) {
1372 int64_t l = insn_size(location.segment, offs, sb, cpu,
1373 &output_ins, report_error);
1375 /* if (using_debug_info) && output_ins.opcode != -1) */
1376 if (using_debug_info)
1377 { /* fbk 03/25/01 */
1378 /* this is done here so we can do debug type info */
1379 int32_t typeinfo =
1380 TYS_ELEMENTS(output_ins.operands);
1381 switch (output_ins.opcode) {
1382 case I_RESB:
1383 typeinfo =
1384 TYS_ELEMENTS(output_ins.oprs[0].
1385 offset) | TY_BYTE;
1386 break;
1387 case I_RESW:
1388 typeinfo =
1389 TYS_ELEMENTS(output_ins.oprs[0].
1390 offset) | TY_WORD;
1391 break;
1392 case I_RESD:
1393 typeinfo =
1394 TYS_ELEMENTS(output_ins.oprs[0].
1395 offset) | TY_DWORD;
1396 break;
1397 case I_RESQ:
1398 typeinfo =
1399 TYS_ELEMENTS(output_ins.oprs[0].
1400 offset) | TY_QWORD;
1401 break;
1402 case I_REST:
1403 typeinfo =
1404 TYS_ELEMENTS(output_ins.oprs[0].
1405 offset) | TY_TBYTE;
1406 break;
1407 case I_DB:
1408 typeinfo |= TY_BYTE;
1409 break;
1410 case I_DW:
1411 typeinfo |= TY_WORD;
1412 break;
1413 case I_DD:
1414 if (output_ins.eops_float)
1415 typeinfo |= TY_FLOAT;
1416 else
1417 typeinfo |= TY_DWORD;
1418 break;
1419 case I_DQ:
1420 typeinfo |= TY_QWORD;
1421 break;
1422 case I_DT:
1423 typeinfo |= TY_TBYTE;
1424 break;
1425 case I_DO:
1426 typeinfo |= TY_OWORD;
1427 break;
1428 default:
1429 typeinfo = TY_LABEL;
1433 ofmt->current_dfmt->debug_typevalue(typeinfo);
1436 if (l != -1) {
1437 offs += l;
1438 SET_CURR_OFFS(offs);
1441 * else l == -1 => invalid instruction, which will be
1442 * flagged as an error on pass 2
1445 } else {
1446 offs += assemble(location.segment, offs, sb, cpu,
1447 &output_ins, ofmt, report_error,
1448 &nasmlist);
1449 SET_CURR_OFFS(offs);
1452 } /* not an EQU */
1453 cleanup_insn(&output_ins);
1455 nasm_free(line);
1456 location.offset = offs = GET_CURR_OFFS;
1457 } /* end while (line = preproc->getline... */
1459 if (pass1 == 2 && global_offset_changed)
1460 report_error(ERR_NONFATAL,
1461 "phase error detected at end of assembly.");
1463 if (pass1 == 1)
1464 preproc->cleanup(1);
1466 if (pass1 == 1 && terminate_after_phase) {
1467 fclose(ofile);
1468 remove(outname);
1469 if (want_usage)
1470 usage();
1471 exit(1);
1473 if (passn >= pass_max - 2 ||
1474 (passn > 1 && !global_offset_changed))
1475 pass0++;
1478 preproc->cleanup(0);
1479 nasmlist.cleanup();
1480 #if 1
1481 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1482 fprintf(stdout,
1483 "info:: assembly required 1+%d+1 passes\n", passn-3);
1484 #endif
1485 } /* exit from assemble_file (...) */
1487 static enum directives getkw(char **directive, char **value)
1489 char *p, *q, *buf;
1491 buf = *directive;
1493 /* allow leading spaces or tabs */
1494 while (*buf == ' ' || *buf == '\t')
1495 buf++;
1497 if (*buf != '[')
1498 return 0;
1500 p = buf;
1502 while (*p && *p != ']')
1503 p++;
1505 if (!*p)
1506 return 0;
1508 q = p++;
1510 while (*p && *p != ';') {
1511 if (!isspace(*p))
1512 return 0;
1513 p++;
1515 q[1] = '\0';
1517 *directive = p = buf + 1;
1518 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1519 buf++;
1520 if (*buf == ']') {
1521 *buf = '\0';
1522 *value = buf;
1523 } else {
1524 *buf++ = '\0';
1525 while (isspace(*buf))
1526 buf++; /* beppu - skip leading whitespace */
1527 *value = buf;
1528 while (*buf != ']')
1529 buf++;
1530 *buf++ = '\0';
1533 return bsii(*directive, directives, elements(directives));
1537 * gnu style error reporting
1538 * This function prints an error message to error_file in the
1539 * style used by GNU. An example would be:
1540 * file.asm:50: error: blah blah blah
1541 * where file.asm is the name of the file, 50 is the line number on
1542 * which the error occurs (or is detected) and "error:" is one of
1543 * the possible optional diagnostics -- it can be "error" or "warning"
1544 * or something else. Finally the line terminates with the actual
1545 * error message.
1547 * @param severity the severity of the warning or error
1548 * @param fmt the printf style format string
1550 static void report_error_gnu(int severity, const char *fmt, ...)
1552 va_list ap;
1554 if (is_suppressed_warning(severity))
1555 return;
1557 if (severity & ERR_NOFILE)
1558 fputs("nasm: ", error_file);
1559 else {
1560 char *currentfile = NULL;
1561 int32_t lineno = 0;
1562 src_get(&lineno, &currentfile);
1563 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1564 nasm_free(currentfile);
1566 va_start(ap, fmt);
1567 report_error_common(severity, fmt, ap);
1568 va_end(ap);
1572 * MS style error reporting
1573 * This function prints an error message to error_file in the
1574 * style used by Visual C and some other Microsoft tools. An example
1575 * would be:
1576 * file.asm(50) : error: blah blah blah
1577 * where file.asm is the name of the file, 50 is the line number on
1578 * which the error occurs (or is detected) and "error:" is one of
1579 * the possible optional diagnostics -- it can be "error" or "warning"
1580 * or something else. Finally the line terminates with the actual
1581 * error message.
1583 * @param severity the severity of the warning or error
1584 * @param fmt the printf style format string
1586 static void report_error_vc(int severity, const char *fmt, ...)
1588 va_list ap;
1590 if (is_suppressed_warning(severity))
1591 return;
1593 if (severity & ERR_NOFILE)
1594 fputs("nasm: ", error_file);
1595 else {
1596 char *currentfile = NULL;
1597 int32_t lineno = 0;
1598 src_get(&lineno, &currentfile);
1599 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1600 nasm_free(currentfile);
1602 va_start(ap, fmt);
1603 report_error_common(severity, fmt, ap);
1604 va_end(ap);
1608 * check for supressed warning
1609 * checks for suppressed warning or pass one only warning and we're
1610 * not in pass 1
1612 * @param severity the severity of the warning or error
1613 * @return true if we should abort error/warning printing
1615 static int is_suppressed_warning(int severity)
1618 * See if it's a suppressed warning.
1620 return ((severity & ERR_MASK) == ERR_WARNING &&
1621 (severity & ERR_WARN_MASK) != 0 &&
1622 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1624 * See if it's a pass-one only warning and we're not in pass
1625 * zero or one.
1627 ((severity & ERR_PASS1) && pass0 != 1);
1631 * common error reporting
1632 * This is the common back end of the error reporting schemes currently
1633 * implemented. It prints the nature of the warning and then the
1634 * specific error message to error_file and may or may not return. It
1635 * doesn't return if the error severity is a "panic" or "debug" type.
1637 * @param severity the severity of the warning or error
1638 * @param fmt the printf style format string
1640 static void report_error_common(int severity, const char *fmt,
1641 va_list args)
1643 switch (severity & ERR_MASK) {
1644 case ERR_WARNING:
1645 fputs("warning: ", error_file);
1646 break;
1647 case ERR_NONFATAL:
1648 fputs("error: ", error_file);
1649 break;
1650 case ERR_FATAL:
1651 fputs("fatal: ", error_file);
1652 break;
1653 case ERR_PANIC:
1654 fputs("panic: ", error_file);
1655 break;
1656 case ERR_DEBUG:
1657 fputs("debug: ", error_file);
1658 break;
1661 vfprintf(error_file, fmt, args);
1662 putc('\n', error_file);
1664 if (severity & ERR_USAGE)
1665 want_usage = true;
1667 switch (severity & ERR_MASK) {
1668 case ERR_DEBUG:
1669 /* no further action, by definition */
1670 break;
1671 case ERR_WARNING:
1672 if (!suppressed[0]) /* Treat warnings as errors */
1673 terminate_after_phase = true;
1674 break;
1675 case ERR_NONFATAL:
1676 terminate_after_phase = true;
1677 break;
1678 case ERR_FATAL:
1679 if (ofile) {
1680 fclose(ofile);
1681 remove(outname);
1683 if (want_usage)
1684 usage();
1685 exit(1); /* instantly die */
1686 break; /* placate silly compilers */
1687 case ERR_PANIC:
1688 fflush(NULL);
1689 /* abort(); *//* halt, catch fire, and dump core */
1690 exit(3);
1691 break;
1695 static void usage(void)
1697 fputs("type `nasm -h' for help\n", error_file);
1700 static void register_output_formats(void)
1702 ofmt = ofmt_register(report_error);
1705 #define BUF_DELTA 512
1707 static FILE *no_pp_fp;
1708 static efunc no_pp_err;
1709 static ListGen *no_pp_list;
1710 static int32_t no_pp_lineinc;
1712 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1713 ListGen * listgen)
1715 src_set_fname(nasm_strdup(file));
1716 src_set_linnum(0);
1717 no_pp_lineinc = 1;
1718 no_pp_err = error;
1719 no_pp_fp = fopen(file, "r");
1720 if (!no_pp_fp)
1721 no_pp_err(ERR_FATAL | ERR_NOFILE,
1722 "unable to open input file `%s'", file);
1723 no_pp_list = listgen;
1724 (void)pass; /* placate compilers */
1725 (void)eval; /* placate compilers */
1728 static char *no_pp_getline(void)
1730 char *buffer, *p, *q;
1731 int bufsize;
1733 bufsize = BUF_DELTA;
1734 buffer = nasm_malloc(BUF_DELTA);
1735 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1737 while (1) { /* Loop to handle %line */
1739 p = buffer;
1740 while (1) { /* Loop to handle long lines */
1741 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
1742 if (!q)
1743 break;
1744 p += strlen(p);
1745 if (p > buffer && p[-1] == '\n')
1746 break;
1747 if (p - buffer > bufsize - 10) {
1748 int offset;
1749 offset = p - buffer;
1750 bufsize += BUF_DELTA;
1751 buffer = nasm_realloc(buffer, bufsize);
1752 p = buffer + offset;
1756 if (!q && p == buffer) {
1757 nasm_free(buffer);
1758 return NULL;
1762 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1763 * them are present at the end of the line.
1765 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1767 if (!nasm_strnicmp(buffer, "%line", 5)) {
1768 int32_t ln;
1769 int li;
1770 char *nm = nasm_malloc(strlen(buffer));
1771 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
1772 nasm_free(src_set_fname(nm));
1773 src_set_linnum(ln);
1774 no_pp_lineinc = li;
1775 continue;
1777 nasm_free(nm);
1779 break;
1782 no_pp_list->line(LIST_READ, buffer);
1784 return buffer;
1787 static void no_pp_cleanup(int pass)
1789 (void)pass; /* placate GCC */
1790 fclose(no_pp_fp);
1793 static uint32_t get_cpu(char *value)
1795 if (!strcmp(value, "8086"))
1796 return IF_8086;
1797 if (!strcmp(value, "186"))
1798 return IF_186;
1799 if (!strcmp(value, "286"))
1800 return IF_286;
1801 if (!strcmp(value, "386"))
1802 return IF_386;
1803 if (!strcmp(value, "486"))
1804 return IF_486;
1805 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
1806 return IF_PENT;
1807 if (!strcmp(value, "686") ||
1808 !nasm_stricmp(value, "ppro") ||
1809 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
1810 return IF_P6;
1811 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
1812 return IF_KATMAI;
1813 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
1814 !nasm_stricmp(value, "willamette"))
1815 return IF_WILLAMETTE;
1816 if (!nasm_stricmp(value, "prescott"))
1817 return IF_PRESCOTT;
1818 if (!nasm_stricmp(value, "x64") ||
1819 !nasm_stricmp(value, "x86-64"))
1820 return IF_X86_64;
1821 if (!nasm_stricmp(value, "ia64") ||
1822 !nasm_stricmp(value, "ia-64") ||
1823 !nasm_stricmp(value, "itanium") ||
1824 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
1825 return IF_IA64;
1827 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1828 "unknown 'cpu' type");
1830 return IF_PLEVEL; /* the maximum level */
1833 static int get_bits(char *value)
1835 int i;
1837 if ((i = atoi(value)) == 16)
1838 return i; /* set for a 16-bit segment */
1839 else if (i == 32) {
1840 if (cpu < IF_386) {
1841 report_error(ERR_NONFATAL,
1842 "cannot specify 32-bit segment on processor below a 386");
1843 i = 16;
1845 } else if (i == 64) {
1846 if (cpu < IF_X86_64) {
1847 report_error(ERR_NONFATAL,
1848 "cannot specify 64-bit segment on processor below an x86-64");
1849 i = 16;
1851 if (i != maxbits) {
1852 report_error(ERR_NONFATAL,
1853 "%s output format does not support 64-bit code",
1854 ofmt->shortname);
1855 i = 16;
1857 } else {
1858 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1859 "`%s' is not a valid segment size; must be 16, 32 or 64",
1860 value);
1861 i = 16;
1863 return i;
1866 /* end of nasm.c */