Create option -Ox to tell NASM to do unlimited passes
[platform/upstream/nasm.git] / nasm.c
1 /* The Netwide Assembler main program module
2  *
3  * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4  * Julian Hall. All rights reserved. The software is
5  * redistributable under the licence given in the file "Licence"
6  * distributed in the NASM archive.
7  */
8
9 #include "compiler.h"
10
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
19 #include "nasm.h"
20 #include "nasmlib.h"
21 #include "stdscan.h"
22 #include "insns.h"
23 #include "preproc.h"
24 #include "parser.h"
25 #include "eval.h"
26 #include "assemble.h"
27 #include "labels.h"
28 #include "outform.h"
29 #include "listing.h"
30
31 struct forwrefinfo {            /* info held on forward refs. */
32     int lineno;
33     int operand;
34 };
35
36 static int get_bits(char *value);
37 static uint32_t get_cpu(char *cpu_str);
38 static void parse_cmdline(int, char **);
39 static void assemble_file(char *);
40 static int getkw(char **directive, char **value);
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;
49
50 static int using_debug_info, opt_verbose_info;
51 int tasm_compatible_mode = FALSE;
52 int pass0;
53 int maxbits = 0;
54 int globalrel = 0;
55
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;
63
64 static FILE *error_file;        /* Where to write error messages */
65
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 int global_offset_changed;      /* referenced in labels.c */
72
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 */
77
78 static struct RAA *offsets;
79
80 static struct SAA *forwrefs;    /* keep track of forward references */
81 static const struct forwrefinfo *forwref;
82
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 */
89 };
90 static enum op_type operating_mode;
91
92 /*
93  * Which of the suppressible warnings are suppressed. Entry zero
94  * doesn't do anything. Initial defaults are given here.
95  */
96 static char suppressed[1 + ERR_WARN_MAX] = {
97     0, TRUE, TRUE, TRUE, FALSE, TRUE
98 };
99
100 /*
101  * The option names for the suppressible warnings. As before, entry
102  * zero does nothing.
103  */
104 static const char *suppressed_names[1 + ERR_WARN_MAX] = {
105     NULL, "macro-params", "macro-selfref", "orphan-labels",
106         "number-overflow",
107     "gnu-elf-extensions"
108 };
109
110 /*
111  * The explanations for the suppressible warnings. As before, entry
112  * zero does nothing.
113  */
114 static const char *suppressed_what[1 + ERR_WARN_MAX] = {
115     NULL,
116     "macro calls with wrong no. of params",
117     "cyclic macro self-references",
118     "labels alone on lines without trailing `:'",
119     "numeric constants greater than 0xFFFFFFFF",
120     "using 8- or 16-bit relocation in ELF, a GNU extension"
121 };
122
123 /*
124  * This is a null preprocessor which just copies lines from input
125  * to output. It's used when someone explicitly requests that NASM
126  * not preprocess their source file.
127  */
128
129 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *);
130 static char *no_pp_getline(void);
131 static void no_pp_cleanup(int);
132 static Preproc no_pp = {
133     no_pp_reset,
134     no_pp_getline,
135     no_pp_cleanup
136 };
137
138 /*
139  * get/set current offset...
140  */
141 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
142                       raa_read(offsets,location.segment))
143 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
144                          (void)(offsets=raa_write(offsets,location.segment,(x))))
145
146 static int want_usage;
147 static int terminate_after_phase;
148 int user_nolist = 0;            /* fbk 9/2/00 */
149
150 static void nasm_fputs(const char *line, FILE * outfile)
151 {
152     if (outfile) {
153         fputs(line, outfile);
154         fputc('\n', outfile);
155     } else
156         puts(line);
157 }
158
159 int main(int argc, char **argv)
160 {
161     pass0 = 1;
162     want_usage = terminate_after_phase = FALSE;
163     report_error = report_error_gnu;
164
165     error_file = stderr;
166
167     nasm_set_malloc_error(report_error);
168     offsets = raa_init();
169     forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
170
171     preproc = &nasmpp;
172     operating_mode = op_normal;
173
174     seg_init();
175
176     register_output_formats();
177
178     parse_cmdline(argc, argv);
179
180     if (terminate_after_phase) {
181         if (want_usage)
182             usage();
183         return 1;
184     }
185
186     /* If debugging info is disabled, suppress any debug calls */
187     if (!using_debug_info)
188         ofmt->current_dfmt = &null_debug_form;
189
190     if (ofmt->stdmac)
191         pp_extra_stdmac(ofmt->stdmac);
192     parser_global_info(ofmt, &location);
193     eval_global_info(ofmt, lookup_label, &location);
194
195     /* define some macros dependent of command-line */
196     {
197         char temp[64];
198         snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
199                  ofmt->shortname);
200         pp_pre_define(temp);
201     }
202
203     switch (operating_mode) {
204     case op_depend_missing_ok:
205         pp_include_path(NULL);  /* "assume generated" */
206         /* fall through */
207     case op_depend:
208         {
209             char *line;
210             preproc->reset(inname, 0, report_error, evaluate, &nasmlist);
211             if (outname[0] == '\0')
212                 ofmt->filename(inname, outname, report_error);
213             ofile = NULL;
214             fprintf(stdout, "%s: %s", outname, inname);
215             while ((line = preproc->getline()))
216                 nasm_free(line);
217             preproc->cleanup(0);
218             putc('\n', stdout);
219         }
220         break;
221
222     case op_preprocess:
223         {
224             char *line;
225             char *file_name = NULL;
226             int32_t prior_linnum = 0;
227             int lineinc = 0;
228
229             if (*outname) {
230                 ofile = fopen(outname, "w");
231                 if (!ofile)
232                     report_error(ERR_FATAL | ERR_NOFILE,
233                                  "unable to open output file `%s'",
234                                  outname);
235             } else
236                 ofile = NULL;
237
238             location.known = FALSE;
239
240 /*      pass = 1; */
241             preproc->reset(inname, 2, report_error, evaluate, &nasmlist);
242             while ((line = preproc->getline())) {
243                 /*
244                  * We generate %line directives if needed for later programs
245                  */
246                 int32_t linnum = prior_linnum += lineinc;
247                 int altline = src_get(&linnum, &file_name);
248                 if (altline) {
249                     if (altline == 1 && lineinc == 1)
250                         nasm_fputs("", ofile);
251                     else {
252                         lineinc = (altline != -1 || lineinc != 1);
253                         fprintf(ofile ? ofile : stdout,
254                                 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
255                                 file_name);
256                     }
257                     prior_linnum = linnum;
258                 }
259                 nasm_fputs(line, ofile);
260                 nasm_free(line);
261             }
262             nasm_free(file_name);
263             preproc->cleanup(0);
264             if (ofile)
265                 fclose(ofile);
266             if (ofile && terminate_after_phase)
267                 remove(outname);
268         }
269         break;
270
271     case op_normal:
272         {
273             /*
274              * We must call ofmt->filename _anyway_, even if the user
275              * has specified their own output file, because some
276              * formats (eg OBJ and COFF) use ofmt->filename to find out
277              * the name of the input file and then put that inside the
278              * file.
279              */
280             ofmt->filename(inname, outname, report_error);
281
282             ofile = fopen(outname, "wb");
283             if (!ofile) {
284                 report_error(ERR_FATAL | ERR_NOFILE,
285                              "unable to open output file `%s'", outname);
286             }
287
288             /*
289              * We must call init_labels() before ofmt->init() since
290              * some object formats will want to define labels in their
291              * init routines. (eg OS/2 defines the FLAT group)
292              */
293             init_labels();
294
295             ofmt->init(ofile, report_error, define_label, evaluate);
296
297             assemble_file(inname);
298
299             if (!terminate_after_phase) {
300                 ofmt->cleanup(using_debug_info);
301                 cleanup_labels();
302             } else {
303                 /*
304                  * We had an fclose on the output file here, but we
305                  * actually do that in all the object file drivers as well,
306                  * so we're leaving out the one here.
307                  *     fclose (ofile);
308                  */
309                 remove(outname);
310                 if (listname[0])
311                     remove(listname);
312             }
313         }
314         break;
315     }
316
317     if (want_usage)
318         usage();
319
320     raa_free(offsets);
321     saa_free(forwrefs);
322     eval_cleanup();
323     stdscan_cleanup();
324
325     if (terminate_after_phase)
326         return 1;
327     else
328         return 0;
329 }
330
331 /*
332  * Get a parameter for a command line option.
333  * First arg must be in the form of e.g. -f...
334  */
335 static char *get_param(char *p, char *q, int *advance)
336 {
337     *advance = 0;
338     if (p[2]) {                 /* the parameter's in the option */
339         p += 2;
340         while (isspace(*p))
341             p++;
342         return p;
343     }
344     if (q && q[0]) {
345         *advance = 1;
346         return q;
347     }
348     report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
349                  "option `-%c' requires an argument", p[1]);
350     return NULL;
351 }
352
353 struct textargs {
354     const char *label;
355     int value;
356 };
357
358 #define OPT_PREFIX 0
359 #define OPT_POSTFIX 1
360 struct textargs textopts[] = {
361     {"prefix", OPT_PREFIX},
362     {"postfix", OPT_POSTFIX},
363     {NULL, 0}
364 };
365
366 int stopoptions = 0;
367 static int process_arg(char *p, char *q)
368 {
369     char *param;
370     int i, advance = 0;
371
372     if (!p || !p[0])
373         return 0;
374
375     if (p[0] == '-' && !stopoptions) {
376         switch (p[1]) {
377         case 's':
378             error_file = stdout;
379             break;
380         case 'o':              /* these parameters take values */
381         case 'O':
382         case 'f':
383         case 'p':
384         case 'P':
385         case 'd':
386         case 'D':
387         case 'i':
388         case 'I':
389         case 'l':
390         case 'F':
391         case 'X':
392         case 'u':
393         case 'U':
394         case 'Z':
395             if (!(param = get_param(p, q, &advance)))
396                 break;
397             if (p[1] == 'o') {  /* output file */
398                 strcpy(outname, param);
399             } else if (p[1] == 'f') {   /* output format */
400                 ofmt = ofmt_find(param);
401                 if (!ofmt) {
402                     report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
403                                  "unrecognised output format `%s' - "
404                                  "use -hf for a list", param);
405                 } else
406                     ofmt->current_dfmt = ofmt->debug_formats[0];
407             } else if (p[1] == 'O') {   /* Optimization level */
408                 int opt;
409                 
410                 if (!*param) {
411                     /* Naked -O == -Ox */
412                     optimizing = INT_MAX >> 1; /* Almost unlimited */
413                 } else {
414                     while (*param) {
415                         switch (*param) {
416                         case '0': case '1': case '2': case '3': case '4':
417                         case '5': case '6': case '7': case '8': case '9':
418                             opt = strtoul(param, &param, 10);
419
420                             /* -O0 -> optimizing == -1, 0.98 behaviour */
421                             /* -O1 -> optimizing == 0, 0.98.09 behaviour */
422                             if (opt < 2)
423                                 optimizing = opt - 1;
424                             else if (opt <= 5)
425                                 /* The optimizer seems to have problems with
426                                    < 5 passes?  Hidden bug? */
427                                 optimizing = 5; /* 5 passes */
428                             else
429                                 optimizing = opt;   /* More than 5 passes */
430                             break;
431                             
432                         case 'v':
433                         case '+':
434                             param++;
435                             opt_verbose_info = TRUE;
436                             break;
437                             
438                         case 'x':
439                             param++;
440                             optimizing = INT_MAX >> 1; /* Almost unlimited */
441                             break;
442                             
443                         default:
444                             report_error(ERR_FATAL,
445                                          "unknown optimization option -O%c\n",
446                                          *param);
447                             break;
448                         }
449                     }
450                 }
451             } else if (p[1] == 'P' || p[1] == 'p') {    /* pre-include */
452                 pp_pre_include(param);
453             } else if (p[1] == 'D' || p[1] == 'd') {    /* pre-define */
454                 pp_pre_define(param);
455             } else if (p[1] == 'U' || p[1] == 'u') {    /* un-define */
456                 pp_pre_undefine(param);
457             } else if (p[1] == 'I' || p[1] == 'i') {    /* include search path */
458                 pp_include_path(param);
459             } else if (p[1] == 'l') {   /* listing file */
460                 strcpy(listname, param);
461             } else if (p[1] == 'Z') {   /* error messages file */
462                 strcpy(errname, param);
463             } else if (p[1] == 'F') {   /* specify debug format */
464                 ofmt->current_dfmt = dfmt_find(ofmt, param);
465                 if (!ofmt->current_dfmt) {
466                     report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
467                                  "unrecognized debug format `%s' for"
468                                  " output format `%s'",
469                                  param, ofmt->shortname);
470                 }
471             } else if (p[1] == 'X') {   /* specify error reporting format */
472                 if (nasm_stricmp("vc", param) == 0)
473                     report_error = report_error_vc;
474                 else if (nasm_stricmp("gnu", param) == 0)
475                     report_error = report_error_gnu;
476                 else
477                     report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
478                                  "unrecognized error reporting format `%s'",
479                                  param);
480             }
481             break;
482         case 'g':
483             using_debug_info = TRUE;
484             break;
485         case 'h':
486             printf
487                 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
488                  "[-l listfile]\n"
489                  "            [options...] [--] filename\n"
490                  "    or nasm -v   for version info\n\n"
491                  "    -t          assemble in SciTech TASM compatible mode\n"
492                  "    -g          generate debug information in selected format.\n");
493             printf
494                 ("    -E (or -e)  preprocess only (writes output to stdout by default)\n"
495                  "    -a          don't preprocess (assemble only)\n"
496                  "    -M          generate Makefile dependencies on stdout\n"
497                  "    -MG         d:o, missing files assumed generated\n\n"
498                  "    -Z<file>    redirect error messages to file\n"
499                  "    -s          redirect error messages to stdout\n\n"
500                  "    -F format   select a debugging format\n\n"
501                  "    -I<path>    adds a pathname to the include file path\n");
502             printf
503                 ("    -O<digit>   optimize branch offsets (-O0 disables, default)\n"
504                  "    -P<file>    pre-includes a file\n"
505                  "    -D<macro>[=<value>] pre-defines a macro\n"
506                  "    -U<macro>   undefines a macro\n"
507                  "    -X<format>  specifies error reporting format (gnu or vc)\n"
508                  "    -w+foo      enables warnings about foo; -w-foo disables them\n"
509                  "where foo can be:\n");
510             for (i = 1; i <= ERR_WARN_MAX; i++)
511                 printf("    %-23s %s (default %s)\n",
512                        suppressed_names[i], suppressed_what[i],
513                        suppressed[i] ? "off" : "on");
514             printf
515                 ("\nresponse files should contain command line parameters"
516                  ", one per line.\n");
517             if (p[2] == 'f') {
518                 printf("\nvalid output formats for -f are"
519                        " (`*' denotes default):\n");
520                 ofmt_list(ofmt, stdout);
521             } else {
522                 printf("\nFor a list of valid output formats, use -hf.\n");
523                 printf("For a list of debug formats, use -f <form> -y.\n");
524             }
525             exit(0);            /* never need usage message here */
526             break;
527         case 'y':
528             printf("\nvalid debug formats for '%s' output format are"
529                    " ('*' denotes default):\n", ofmt->shortname);
530             dfmt_list(ofmt, stdout);
531             exit(0);
532             break;
533         case 't':
534             tasm_compatible_mode = TRUE;
535             break;
536         case 'v':
537             {
538                 const char *nasm_version_string =
539                     "NASM version " NASM_VER " compiled on " __DATE__
540 #ifdef DEBUG
541                     " with -DDEBUG"
542 #endif
543                     ;
544                 puts(nasm_version_string);
545                 exit(0);        /* never need usage message here */
546             }
547             break;
548         case 'e':              /* preprocess only */
549         case 'E':
550             operating_mode = op_preprocess;
551             break;
552         case 'a':              /* assemble only - don't preprocess */
553             preproc = &no_pp;
554             break;
555         case 'w':
556             if (p[2] != '+' && p[2] != '-') {
557                 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
558                              "invalid option to `-w'");
559             } else {
560                 for (i = 1; i <= ERR_WARN_MAX; i++)
561                     if (!nasm_stricmp(p + 3, suppressed_names[i]))
562                         break;
563                 if (i <= ERR_WARN_MAX)
564                     suppressed[i] = (p[2] == '-');
565                 else
566                     report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
567                                  "invalid option to `-w'");
568             }
569             break;
570         case 'M':
571             operating_mode = p[2] == 'G' ? op_depend_missing_ok : op_depend;
572             break;
573
574         case '-':
575             {
576                 int s;
577
578                 if (p[2] == 0) {        /* -- => stop processing options */
579                     stopoptions = 1;
580                     break;
581                 }
582                 for (s = 0; textopts[s].label; s++) {
583                     if (!nasm_stricmp(p + 2, textopts[s].label)) {
584                         break;
585                     }
586                 }
587
588                 switch (s) {
589
590                 case OPT_PREFIX:
591                 case OPT_POSTFIX:
592                     {
593                         if (!q) {
594                             report_error(ERR_NONFATAL | ERR_NOFILE |
595                                          ERR_USAGE,
596                                          "option `--%s' requires an argument",
597                                          p + 2);
598                             break;
599                         } else {
600                             advance = 1, param = q;
601                         }
602
603                         if (s == OPT_PREFIX) {
604                             strncpy(lprefix, param, PREFIX_MAX - 1);
605                             lprefix[PREFIX_MAX - 1] = 0;
606                             break;
607                         }
608                         if (s == OPT_POSTFIX) {
609                             strncpy(lpostfix, param, POSTFIX_MAX - 1);
610                             lpostfix[POSTFIX_MAX - 1] = 0;
611                             break;
612                         }
613                         break;
614                     }
615                 default:
616                     {
617                         report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
618                                      "unrecognised option `--%s'", p + 2);
619                         break;
620                     }
621                 }
622                 break;
623             }
624
625         default:
626             if (!ofmt->setinfo(GI_SWITCH, &p))
627                 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
628                              "unrecognised option `-%c'", p[1]);
629             break;
630         }
631     } else {
632         if (*inname) {
633             report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
634                          "more than one input file specified");
635         } else
636             strcpy(inname, p);
637     }
638
639     return advance;
640 }
641
642 #define ARG_BUF_DELTA 128
643
644 static void process_respfile(FILE * rfile)
645 {
646     char *buffer, *p, *q, *prevarg;
647     int bufsize, prevargsize;
648
649     bufsize = prevargsize = ARG_BUF_DELTA;
650     buffer = nasm_malloc(ARG_BUF_DELTA);
651     prevarg = nasm_malloc(ARG_BUF_DELTA);
652     prevarg[0] = '\0';
653
654     while (1) {                 /* Loop to handle all lines in file */
655
656         p = buffer;
657         while (1) {             /* Loop to handle long lines */
658             q = fgets(p, bufsize - (p - buffer), rfile);
659             if (!q)
660                 break;
661             p += strlen(p);
662             if (p > buffer && p[-1] == '\n')
663                 break;
664             if (p - buffer > bufsize - 10) {
665                 int offset;
666                 offset = p - buffer;
667                 bufsize += ARG_BUF_DELTA;
668                 buffer = nasm_realloc(buffer, bufsize);
669                 p = buffer + offset;
670             }
671         }
672
673         if (!q && p == buffer) {
674             if (prevarg[0])
675                 process_arg(prevarg, NULL);
676             nasm_free(buffer);
677             nasm_free(prevarg);
678             return;
679         }
680
681         /*
682          * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
683          * them are present at the end of the line.
684          */
685         *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
686
687         while (p > buffer && isspace(p[-1]))
688             *--p = '\0';
689
690         p = buffer;
691         while (isspace(*p))
692             p++;
693
694         if (process_arg(prevarg, p))
695             *p = '\0';
696
697         if (strlen(p) > prevargsize - 10) {
698             prevargsize += ARG_BUF_DELTA;
699             prevarg = nasm_realloc(prevarg, prevargsize);
700         }
701         strcpy(prevarg, p);
702     }
703 }
704
705 /* Function to process args from a string of args, rather than the
706  * argv array. Used by the environment variable and response file
707  * processing.
708  */
709 static void process_args(char *args)
710 {
711     char *p, *q, *arg, *prevarg;
712     char separator = ' ';
713
714     p = args;
715     if (*p && *p != '-')
716         separator = *p++;
717     arg = NULL;
718     while (*p) {
719         q = p;
720         while (*p && *p != separator)
721             p++;
722         while (*p == separator)
723             *p++ = '\0';
724         prevarg = arg;
725         arg = q;
726         if (process_arg(prevarg, arg))
727             arg = NULL;
728     }
729     if (arg)
730         process_arg(arg, NULL);
731 }
732
733 static void parse_cmdline(int argc, char **argv)
734 {
735     FILE *rfile;
736     char *envreal, *envcopy = NULL, *p, *arg;
737
738     *inname = *outname = *listname = *errname = '\0';
739
740     /*
741      * First, process the NASMENV environment variable.
742      */
743     envreal = getenv("NASMENV");
744     arg = NULL;
745     if (envreal) {
746         envcopy = nasm_strdup(envreal);
747         process_args(envcopy);
748         nasm_free(envcopy);
749     }
750
751     /*
752      * Now process the actual command line.
753      */
754     while (--argc) {
755         int i;
756         argv++;
757         if (argv[0][0] == '@') {
758             /* We have a response file, so process this as a set of
759              * arguments like the environment variable. This allows us
760              * to have multiple arguments on a single line, which is
761              * different to the -@resp file processing below for regular
762              * NASM.
763              */
764             char *str = malloc(2048);
765             FILE *f = fopen(&argv[0][1], "r");
766             if (!str) {
767                 printf("out of memory");
768                 exit(-1);
769             }
770             if (f) {
771                 while (fgets(str, 2048, f)) {
772                     process_args(str);
773                 }
774                 fclose(f);
775             }
776             free(str);
777             argc--;
778             argv++;
779         }
780         if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
781             p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &i);
782             if (p) {
783                 rfile = fopen(p, "r");
784                 if (rfile) {
785                     process_respfile(rfile);
786                     fclose(rfile);
787                 } else
788                     report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
789                                  "unable to open response file `%s'", p);
790             }
791         } else
792             i = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
793         argv += i, argc -= i;
794     }
795
796     if (!*inname)
797         report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
798                      "no input file specified");
799
800     /* Look for basic command line typos.  This definitely doesn't
801        catch all errors, but it might help cases of fumbled fingers. */
802     if (!strcmp(inname, errname) || !strcmp(inname, outname) ||
803         !strcmp(inname, listname))
804         report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
805                      "file `%s' is both input and output file",
806                      inname);
807
808     if (*errname) {  
809         error_file = fopen(errname, "w");
810         if (!error_file) {
811             error_file = stderr;        /* Revert to default! */
812             report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
813                          "cannot open file `%s' for error messages",
814                          errname);
815         }
816     }
817 }
818
819 /* List of directives */
820 enum {
821     D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
822     D_EXTERN, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
823 };
824 static const char *directives[] = {
825     "", "absolute", "bits", "common", "cpu", "debug", "default",
826     "extern", "global", "list", "section", "segment", "warning"
827 };
828
829 static void assemble_file(char *fname)
830 {
831     char *directive, *value, *p, *q, *special, *line, debugid[80];
832     insn output_ins;
833     int i, rn_error, validid;
834     int32_t seg, offs;
835     struct tokenval tokval;
836     expr *e;
837     int pass, pass_max;
838     int pass_cnt = 0;           /* count actual passes */
839
840     if (cmd_sb == 32 && cmd_cpu < IF_386)
841         report_error(ERR_FATAL, "command line: "
842                      "32-bit segment size requires a higher cpu");
843
844     pass_max = (optimizing > 0 ? optimizing : 0) + 2;   /* passes 1, optimizing, then 2 */
845     pass0 = !(optimizing > 0);  /* start at 1 if not optimizing */
846     for (pass = 1; pass <= pass_max && pass0 <= 2; pass++) {
847         int pass1, pass2;
848         ldfunc def_label;
849
850         pass1 = pass < pass_max ? 1 : 2;        /* seq is 1, 1, 1,..., 1, 2 */
851         pass2 = pass > 1 ? 2 : 1;       /* seq is 1, 2, 2,..., 2, 2 */
852         /*      pass0                            seq is 0, 0, 0,..., 1, 2 */
853
854         def_label = pass > 1 ? redefine_label : define_label;
855
856         globalbits = sb = cmd_sb;   /* set 'bits' to command line default */
857         cpu = cmd_cpu;
858         if (pass0 == 2) {
859             if (*listname)
860                 nasmlist.init(listname, report_error);
861         }
862         in_abs_seg = FALSE;
863         global_offset_changed = FALSE;  /* set by redefine_label */
864         location.segment = ofmt->section(NULL, pass2, &sb);
865         globalbits = sb;
866         if (pass > 1) {
867             saa_rewind(forwrefs);
868             forwref = saa_rstruct(forwrefs);
869             raa_free(offsets);
870             offsets = raa_init();
871         }
872         preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
873         globallineno = 0;
874         if (pass == 1)
875             location.known = TRUE;
876         location.offset = offs = GET_CURR_OFFS;
877
878         while ((line = preproc->getline())) {
879             globallineno++;
880
881             /* here we parse our directives; this is not handled by the 'real'
882              * parser. */
883             directive = line;
884             i = getkw(&directive, &value);
885             if (i) {
886                 int err = 0;
887
888                 switch (i) {
889                 case D_SEGMENT:         /* [SEGMENT n] */
890                 case D_SECTION:
891                     seg = ofmt->section(value, pass2, &sb);
892                     if (seg == NO_SEG) {
893                         report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
894                                      "segment name `%s' not recognized",
895                                      value);
896                     } else {
897                         in_abs_seg = FALSE;
898                         location.segment = seg;
899                     }
900                     break;
901                 case D_EXTERN:          /* [EXTERN label:special] */
902                     if (*value == '$')
903                         value++;        /* skip initial $ if present */
904                     if (pass0 == 2) {
905                         q = value;
906                         while (*q && *q != ':')
907                             q++;
908                         if (*q == ':') {
909                             *q++ = '\0';
910                             ofmt->symdef(value, 0L, 0L, 3, q);
911                         }
912                     } else if (pass == 1) {     /* pass == 1 */
913                         q = value;
914                         validid = TRUE;
915                         if (!isidstart(*q))
916                             validid = FALSE;
917                         while (*q && *q != ':') {
918                             if (!isidchar(*q))
919                                 validid = FALSE;
920                             q++;
921                         }
922                         if (!validid) {
923                             report_error(ERR_NONFATAL,
924                                          "identifier expected after EXTERN");
925                             break;
926                         }
927                         if (*q == ':') {
928                             *q++ = '\0';
929                             special = q;
930                         } else
931                             special = NULL;
932                         if (!is_extern(value)) {        /* allow re-EXTERN to be ignored */
933                             int temp = pass0;
934                             pass0 = 1;  /* fake pass 1 in labels.c */
935                             declare_as_global(value, special,
936                                               report_error);
937                             define_label(value, seg_alloc(), 0L, NULL,
938                                          FALSE, TRUE, ofmt, report_error);
939                             pass0 = temp;
940                         }
941                     }           /* else  pass0 == 1 */
942                     break;
943                 case D_BITS:            /* [BITS bits] */
944                     globalbits = sb = get_bits(value);
945                     break;
946                 case D_GLOBAL:          /* [GLOBAL symbol:special] */
947                     if (*value == '$')
948                         value++;        /* skip initial $ if present */
949                     if (pass0 == 2) {   /* pass 2 */
950                         q = value;
951                         while (*q && *q != ':')
952                             q++;
953                         if (*q == ':') {
954                             *q++ = '\0';
955                             ofmt->symdef(value, 0L, 0L, 3, q);
956                         }
957                     } else if (pass2 == 1) {    /* pass == 1 */
958                         q = value;
959                         validid = TRUE;
960                         if (!isidstart(*q))
961                             validid = FALSE;
962                         while (*q && *q != ':') {
963                             if (!isidchar(*q))
964                                 validid = FALSE;
965                             q++;
966                         }
967                         if (!validid) {
968                             report_error(ERR_NONFATAL,
969                                          "identifier expected after GLOBAL");
970                             break;
971                         }
972                         if (*q == ':') {
973                             *q++ = '\0';
974                             special = q;
975                         } else
976                             special = NULL;
977                         declare_as_global(value, special, report_error);
978                     }           /* pass == 1 */
979                     break;
980                 case D_COMMON:          /* [COMMON symbol size:special] */
981                     if (*value == '$')
982                         value++;        /* skip initial $ if present */
983                     if (pass0 == 1) {
984                         p = value;
985                         validid = TRUE;
986                         if (!isidstart(*p))
987                             validid = FALSE;
988                         while (*p && !isspace(*p)) {
989                             if (!isidchar(*p))
990                                 validid = FALSE;
991                             p++;
992                         }
993                         if (!validid) {
994                             report_error(ERR_NONFATAL,
995                                          "identifier expected after COMMON");
996                             break;
997                         }
998                         if (*p) {
999                             int64_t size;
1000
1001                             while (*p && isspace(*p))
1002                                 *p++ = '\0';
1003                             q = p;
1004                             while (*q && *q != ':')
1005                                 q++;
1006                             if (*q == ':') {
1007                                 *q++ = '\0';
1008                                 special = q;
1009                             } else
1010                                 special = NULL;
1011                             size = readnum(p, &rn_error);
1012                             if (rn_error)
1013                                 report_error(ERR_NONFATAL,
1014                                              "invalid size specified"
1015                                              " in COMMON declaration");
1016                             else
1017                                 define_common(value, seg_alloc(), size,
1018                                               special, ofmt, report_error);
1019                         } else
1020                             report_error(ERR_NONFATAL,
1021                                          "no size specified in"
1022                                          " COMMON declaration");
1023                     } else if (pass0 == 2) {    /* pass == 2 */
1024                         q = value;
1025                         while (*q && *q != ':') {
1026                             if (isspace(*q))
1027                                 *q = '\0';
1028                             q++;
1029                         }
1030                         if (*q == ':') {
1031                             *q++ = '\0';
1032                             ofmt->symdef(value, 0L, 0L, 3, q);
1033                         }
1034                     }
1035                     break;
1036                 case D_ABSOLUTE:                /* [ABSOLUTE address] */
1037                     stdscan_reset();
1038                     stdscan_bufptr = value;
1039                     tokval.t_type = TOKEN_INVALID;
1040                     e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1041                                  report_error, NULL);
1042                     if (e) {
1043                         if (!is_reloc(e))
1044                             report_error(pass0 ==
1045                                          1 ? ERR_NONFATAL : ERR_PANIC,
1046                                          "cannot use non-relocatable expression as "
1047                                          "ABSOLUTE address");
1048                         else {
1049                             abs_seg = reloc_seg(e);
1050                             abs_offset = reloc_value(e);
1051                         }
1052                     } else if (pass == 1)
1053                         abs_offset = 0x100;     /* don't go near zero in case of / */
1054                     else
1055                         report_error(ERR_PANIC, "invalid ABSOLUTE address "
1056                                      "in pass two");
1057                     in_abs_seg = TRUE;
1058                     location.segment = NO_SEG;
1059                     break;
1060                 case D_DEBUG:           /* [DEBUG] */
1061                     p = value;
1062                     q = debugid;
1063                     validid = TRUE;
1064                     if (!isidstart(*p))
1065                         validid = FALSE;
1066                     while (*p && !isspace(*p)) {
1067                         if (!isidchar(*p))
1068                             validid = FALSE;
1069                         *q++ = *p++;
1070                     }
1071                     *q++ = 0;
1072                     if (!validid) {
1073                         report_error(pass == 1 ? ERR_NONFATAL : ERR_PANIC,
1074                                      "identifier expected after DEBUG");
1075                         break;
1076                     }
1077                     while (*p && isspace(*p))
1078                         p++;
1079                     if (pass == pass_max)
1080                         ofmt->current_dfmt->debug_directive(debugid, p);
1081                     break;
1082                 case D_WARNING:         /* [WARNING {+|-}warn-name] */
1083                     if (pass1 == 1) {
1084                         while (*value && isspace(*value))
1085                             value++;
1086
1087                         if (*value == '+' || *value == '-') {
1088                             validid = (*value == '-') ? TRUE : FALSE;
1089                             value++;
1090                         } else
1091                             validid = FALSE;
1092
1093                         for (i = 1; i <= ERR_WARN_MAX; i++)
1094                             if (!nasm_stricmp(value, suppressed_names[i]))
1095                                 break;
1096                         if (i <= ERR_WARN_MAX)
1097                             suppressed[i] = validid;
1098                         else
1099                             report_error(ERR_NONFATAL,
1100                                          "invalid warning id in WARNING directive");
1101                     }
1102                     break;
1103                 case D_CPU:             /* [CPU] */
1104                     cpu = get_cpu(value);
1105                     break;
1106                 case D_LIST:            /* [LIST {+|-}] */
1107                     while (*value && isspace(*value))
1108                         value++;
1109
1110                     if (*value == '+') {
1111                         user_nolist = 0;
1112                     } else {
1113                         if (*value == '-') {
1114                             user_nolist = 1;
1115                         } else {
1116                             err = 1;
1117                         }
1118                     }
1119                     break;
1120                 case D_DEFAULT:         /* [DEFAULT] */
1121                     stdscan_reset();
1122                     stdscan_bufptr = value;
1123                     tokval.t_type = TOKEN_INVALID;
1124                     if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1125                         switch ((int)tokval.t_integer) {
1126                         case S_REL:
1127                             globalrel = 1;
1128                             break;
1129                         case S_ABS:
1130                             globalrel = 0;
1131                             break;
1132                         default:
1133                             err = 1;
1134                             break;
1135                         }
1136                     } else {
1137                         err = 1;
1138                     }
1139                     break;
1140                 default:
1141                     if (!ofmt->directive(directive, value, pass2))
1142                         report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1143                                      "unrecognised directive [%s]",
1144                                      directive);
1145                 }
1146                 if (err) {
1147                     report_error(ERR_NONFATAL,
1148                                  "invalid parameter to [%s] directive",
1149                                  directive);
1150                 }
1151             } else {            /* it isn't a directive */
1152
1153                 parse_line(pass1, line, &output_ins,
1154                            report_error, evaluate, def_label);
1155
1156                 if (!(optimizing > 0) && pass == 2) {
1157                     if (forwref != NULL && globallineno == forwref->lineno) {
1158                         output_ins.forw_ref = TRUE;
1159                         do {
1160                             output_ins.oprs[forwref->operand].opflags |=
1161                                 OPFLAG_FORWARD;
1162                             forwref = saa_rstruct(forwrefs);
1163                         } while (forwref != NULL
1164                                  && forwref->lineno == globallineno);
1165                     } else
1166                         output_ins.forw_ref = FALSE;
1167                 }
1168
1169                 if (!(optimizing > 0) && output_ins.forw_ref) {
1170                     if (pass == 1) {
1171                         for (i = 0; i < output_ins.operands; i++) {
1172                             if (output_ins.oprs[i].
1173                                 opflags & OPFLAG_FORWARD) {
1174                                 struct forwrefinfo *fwinf =
1175                                     (struct forwrefinfo *)
1176                                     saa_wstruct(forwrefs);
1177                                 fwinf->lineno = globallineno;
1178                                 fwinf->operand = i;
1179                             }
1180                         }
1181                     } else {    /* pass == 2 */
1182                         /*
1183                          * Hack to prevent phase error in the code
1184                          *   rol ax,x
1185                          *   x equ 1
1186                          *
1187                          * If the second operand is a forward reference,
1188                          * the UNITY property of the number 1 in that
1189                          * operand is cancelled. Otherwise the above
1190                          * sequence will cause a phase error.
1191                          *
1192                          * This hack means that the above code will
1193                          * generate 286+ code.
1194                          *
1195                          * The forward reference will mean that the
1196                          * operand will not have the UNITY property on
1197                          * the first pass, so the pass behaviours will
1198                          * be consistent.
1199                          */
1200
1201                         if (output_ins.operands >= 2 &&
1202                             (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1203                             !(IMMEDIATE & ~output_ins.oprs[1].type))
1204                         {
1205                             /* Remove special properties bits */
1206                             output_ins.oprs[1].type &= ~REG_SMASK;
1207                         }
1208
1209                     }           /* pass == 2 */
1210
1211                 }
1212
1213                 /*  forw_ref */
1214                 if (output_ins.opcode == I_EQU) {
1215                     if (pass1 == 1) {
1216                         /*
1217                          * Special `..' EQUs get processed in pass two,
1218                          * except `..@' macro-processor EQUs which are done
1219                          * in the normal place.
1220                          */
1221                         if (!output_ins.label)
1222                             report_error(ERR_NONFATAL,
1223                                          "EQU not preceded by label");
1224
1225                         else if (output_ins.label[0] != '.' ||
1226                                  output_ins.label[1] != '.' ||
1227                                  output_ins.label[2] == '@') {
1228                             if (output_ins.operands == 1 &&
1229                                 (output_ins.oprs[0].type & IMMEDIATE) &&
1230                                 output_ins.oprs[0].wrt == NO_SEG) {
1231                                 int isext =
1232                                     output_ins.oprs[0].
1233                                     opflags & OPFLAG_EXTERN;
1234                                 def_label(output_ins.label,
1235                                           output_ins.oprs[0].segment,
1236                                           output_ins.oprs[0].offset, NULL,
1237                                           FALSE, isext, ofmt,
1238                                           report_error);
1239                             } else if (output_ins.operands == 2
1240                                        && (output_ins.oprs[0].
1241                                            type & IMMEDIATE)
1242                                        && (output_ins.oprs[0].type & COLON)
1243                                        && output_ins.oprs[0].segment ==
1244                                        NO_SEG
1245                                        && output_ins.oprs[0].wrt == NO_SEG
1246                                        && (output_ins.oprs[1].
1247                                            type & IMMEDIATE)
1248                                        && output_ins.oprs[1].segment ==
1249                                        NO_SEG
1250                                        && output_ins.oprs[1].wrt ==
1251                                        NO_SEG) {
1252                                 def_label(output_ins.label,
1253                                           output_ins.oprs[0].
1254                                           offset | SEG_ABS,
1255                                           output_ins.oprs[1].offset, NULL,
1256                                           FALSE, FALSE, ofmt,
1257                                           report_error);
1258                             } else
1259                                 report_error(ERR_NONFATAL,
1260                                              "bad syntax for EQU");
1261                         }
1262                     } else {    /* pass == 2 */
1263                         /*
1264                          * Special `..' EQUs get processed here, except
1265                          * `..@' macro processor EQUs which are done above.
1266                          */
1267                         if (output_ins.label[0] == '.' &&
1268                             output_ins.label[1] == '.' &&
1269                             output_ins.label[2] != '@') {
1270                             if (output_ins.operands == 1 &&
1271                                 (output_ins.oprs[0].type & IMMEDIATE)) {
1272                                 define_label(output_ins.label,
1273                                              output_ins.oprs[0].segment,
1274                                              output_ins.oprs[0].offset,
1275                                              NULL, FALSE, FALSE, ofmt,
1276                                              report_error);
1277                             } else if (output_ins.operands == 2
1278                                        && (output_ins.oprs[0].
1279                                            type & IMMEDIATE)
1280                                        && (output_ins.oprs[0].type & COLON)
1281                                        && output_ins.oprs[0].segment ==
1282                                        NO_SEG
1283                                        && (output_ins.oprs[1].
1284                                            type & IMMEDIATE)
1285                                        && output_ins.oprs[1].segment ==
1286                                        NO_SEG) {
1287                                 define_label(output_ins.label,
1288                                              output_ins.oprs[0].
1289                                              offset | SEG_ABS,
1290                                              output_ins.oprs[1].offset,
1291                                              NULL, FALSE, FALSE, ofmt,
1292                                              report_error);
1293                             } else
1294                                 report_error(ERR_NONFATAL,
1295                                              "bad syntax for EQU");
1296                         }
1297                     }           /* pass == 2 */
1298                 } else {        /* instruction isn't an EQU */
1299
1300                     if (pass1 == 1) {
1301
1302                         int32_t l = insn_size(location.segment, offs, sb, cpu,
1303                                            &output_ins, report_error);
1304
1305                         /* if (using_debug_info)  && output_ins.opcode != -1) */
1306                         if (using_debug_info)
1307                         {       /* fbk 03/25/01 */
1308                             /* this is done here so we can do debug type info */
1309                             int32_t typeinfo =
1310                                 TYS_ELEMENTS(output_ins.operands);
1311                             switch (output_ins.opcode) {
1312                             case I_RESB:
1313                                 typeinfo =
1314                                     TYS_ELEMENTS(output_ins.oprs[0].
1315                                                  offset) | TY_BYTE;
1316                                 break;
1317                             case I_RESW:
1318                                 typeinfo =
1319                                     TYS_ELEMENTS(output_ins.oprs[0].
1320                                                  offset) | TY_WORD;
1321                                 break;
1322                             case I_RESD:
1323                                 typeinfo =
1324                                     TYS_ELEMENTS(output_ins.oprs[0].
1325                                                  offset) | TY_DWORD;
1326                                 break;
1327                             case I_RESQ:
1328                                 typeinfo =
1329                                     TYS_ELEMENTS(output_ins.oprs[0].
1330                                                  offset) | TY_QWORD;
1331                                 break;
1332                             case I_REST:
1333                                 typeinfo =
1334                                     TYS_ELEMENTS(output_ins.oprs[0].
1335                                                  offset) | TY_TBYTE;
1336                                 break;
1337                             case I_DB:
1338                                 typeinfo |= TY_BYTE;
1339                                 break;
1340                             case I_DW:
1341                                 typeinfo |= TY_WORD;
1342                                 break;
1343                             case I_DD:
1344                                 if (output_ins.eops_float)
1345                                     typeinfo |= TY_FLOAT;
1346                                 else
1347                                     typeinfo |= TY_DWORD;
1348                                 break;
1349                             case I_DQ:
1350                                 typeinfo |= TY_QWORD;
1351                                 break;
1352                             case I_DT:
1353                                 typeinfo |= TY_TBYTE;
1354                                 break;
1355                             case I_DO:
1356                                 typeinfo |= TY_OWORD;
1357                                 break;
1358                             default:
1359                                 typeinfo = TY_LABEL;
1360
1361                             }
1362
1363                             ofmt->current_dfmt->debug_typevalue(typeinfo);
1364
1365                         }
1366                         if (l != -1) {
1367                             offs += l;
1368                             SET_CURR_OFFS(offs);
1369                         }
1370                         /*
1371                          * else l == -1 => invalid instruction, which will be
1372                          * flagged as an error on pass 2
1373                          */
1374
1375                     } else {    /* pass == 2 */
1376                         offs += assemble(location.segment, offs, sb, cpu,
1377                                          &output_ins, ofmt, report_error,
1378                                          &nasmlist);
1379                         SET_CURR_OFFS(offs);
1380
1381                     }
1382                 }               /* not an EQU */
1383                 cleanup_insn(&output_ins);
1384             }
1385             nasm_free(line);
1386             location.offset = offs = GET_CURR_OFFS;
1387         }                       /* end while (line = preproc->getline... */
1388
1389         if (pass1 == 2 && global_offset_changed)
1390             report_error(ERR_NONFATAL,
1391                          "phase error detected at end of assembly.");
1392
1393         if (pass1 == 1)
1394             preproc->cleanup(1);
1395
1396         if (pass1 == 1 && terminate_after_phase) {
1397             fclose(ofile);
1398             remove(outname);
1399             if (want_usage)
1400                 usage();
1401             exit(1);
1402         }
1403         pass_cnt++;
1404         if (pass > 1 && !global_offset_changed) {
1405             pass0++;
1406             if (pass0 == 2)
1407                 pass = pass_max - 1;
1408         } else if (!(optimizing > 0))
1409             pass0++;
1410
1411     }                           /* for (pass=1; pass<=2; pass++) */
1412
1413     preproc->cleanup(0);
1414     nasmlist.cleanup();
1415 #if 1
1416     if (optimizing > 0 && opt_verbose_info)     /*  -On and -Ov switches */
1417         fprintf(stdout,
1418                 "info:: assembly required 1+%d+1 passes\n", pass_cnt - 2);
1419 #endif
1420 }                               /* exit from assemble_file (...) */
1421
1422 static int getkw(char **directive, char **value)
1423 {
1424     char *p, *q, *buf;
1425
1426     buf = *directive;
1427
1428     /*  allow leading spaces or tabs */
1429     while (*buf == ' ' || *buf == '\t')
1430         buf++;
1431
1432     if (*buf != '[')
1433         return 0;
1434
1435     p = buf;
1436
1437     while (*p && *p != ']')
1438         p++;
1439
1440     if (!*p)
1441         return 0;
1442
1443     q = p++;
1444
1445     while (*p && *p != ';') {
1446         if (!isspace(*p))
1447             return 0;
1448         p++;
1449     }
1450     q[1] = '\0';
1451
1452     *directive = p = buf + 1;
1453     while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1454         buf++;
1455     if (*buf == ']') {
1456         *buf = '\0';
1457         *value = buf;
1458     } else {
1459         *buf++ = '\0';
1460         while (isspace(*buf))
1461             buf++;              /* beppu - skip leading whitespace */
1462         *value = buf;
1463         while (*buf != ']')
1464             buf++;
1465         *buf++ = '\0';
1466     }
1467
1468     return bsii(*directive, directives, elements(directives));
1469 }
1470
1471 /**
1472  * gnu style error reporting
1473  * This function prints an error message to error_file in the
1474  * style used by GNU. An example would be:
1475  * file.asm:50: error: blah blah blah
1476  * where file.asm is the name of the file, 50 is the line number on 
1477  * which the error occurs (or is detected) and "error:" is one of
1478  * the possible optional diagnostics -- it can be "error" or "warning"
1479  * or something else.  Finally the line terminates with the actual 
1480  * error message.
1481  * 
1482  * @param severity the severity of the warning or error 
1483  * @param fmt the printf style format string
1484  */
1485 static void report_error_gnu(int severity, const char *fmt, ...)
1486 {
1487     va_list ap;
1488
1489     if (is_suppressed_warning(severity))
1490         return;
1491
1492     if (severity & ERR_NOFILE)
1493         fputs("nasm: ", error_file);
1494     else {
1495         char *currentfile = NULL;
1496         int32_t lineno = 0;
1497         src_get(&lineno, &currentfile);
1498         fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1499         nasm_free(currentfile);
1500     }
1501     va_start(ap, fmt);
1502     report_error_common(severity, fmt, ap);
1503     va_end(ap);
1504 }
1505
1506 /**
1507  * MS style error reporting
1508  * This function prints an error message to error_file in the
1509  * style used by Visual C and some other Microsoft tools. An example 
1510  * would be:
1511  * file.asm(50) : error: blah blah blah
1512  * where file.asm is the name of the file, 50 is the line number on 
1513  * which the error occurs (or is detected) and "error:" is one of
1514  * the possible optional diagnostics -- it can be "error" or "warning"
1515  * or something else.  Finally the line terminates with the actual 
1516  * error message.
1517  * 
1518  * @param severity the severity of the warning or error 
1519  * @param fmt the printf style format string
1520  */
1521 static void report_error_vc(int severity, const char *fmt, ...)
1522 {
1523     va_list ap;
1524
1525     if (is_suppressed_warning(severity))
1526         return;
1527
1528     if (severity & ERR_NOFILE)
1529         fputs("nasm: ", error_file);
1530     else {
1531         char *currentfile = NULL;
1532         int32_t lineno = 0;
1533         src_get(&lineno, &currentfile);
1534         fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1535         nasm_free(currentfile);
1536     }
1537     va_start(ap, fmt);
1538     report_error_common(severity, fmt, ap);
1539     va_end(ap);
1540 }
1541
1542 /**
1543  * check for supressed warning
1544  * checks for suppressed warning or pass one only warning and we're 
1545  * not in pass 1
1546  *
1547  * @param severity the severity of the warning or error
1548  * @return true if we should abort error/warning printing
1549  */
1550 static int is_suppressed_warning(int severity)
1551 {
1552     /*
1553      * See if it's a suppressed warning.
1554      */
1555     return ((severity & ERR_MASK) == ERR_WARNING &&
1556             (severity & ERR_WARN_MASK) != 0 &&
1557             suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1558         /*
1559          * See if it's a pass-one only warning and we're not in pass one.
1560          */
1561         ((severity & ERR_PASS1) && pass0 == 2);
1562 }
1563
1564 /**
1565  * common error reporting
1566  * This is the common back end of the error reporting schemes currently
1567  * implemented.  It prints the nature of the warning and then the 
1568  * specific error message to error_file and may or may not return.  It
1569  * doesn't return if the error severity is a "panic" or "debug" type.
1570  * 
1571  * @param severity the severity of the warning or error 
1572  * @param fmt the printf style format string
1573  */
1574 static void report_error_common(int severity, const char *fmt,
1575                                 va_list args)
1576 {
1577     switch (severity & ERR_MASK) {
1578     case ERR_WARNING:
1579         fputs("warning: ", error_file);
1580         break;
1581     case ERR_NONFATAL:
1582         fputs("error: ", error_file);
1583         break;
1584     case ERR_FATAL:
1585         fputs("fatal: ", error_file);
1586         break;
1587     case ERR_PANIC:
1588         fputs("panic: ", error_file);
1589         break;
1590     case ERR_DEBUG:
1591         fputs("debug: ", error_file);
1592         break;
1593     }
1594
1595     vfprintf(error_file, fmt, args);
1596     fputc('\n', error_file);
1597
1598     if (severity & ERR_USAGE)
1599         want_usage = TRUE;
1600
1601     switch (severity & ERR_MASK) {
1602     case ERR_WARNING:
1603     case ERR_DEBUG:
1604         /* no further action, by definition */
1605         break;
1606     case ERR_NONFATAL:
1607         /* hack enables listing(!) on errors */
1608         terminate_after_phase = TRUE;
1609         break;
1610     case ERR_FATAL:
1611         if (ofile) {
1612             fclose(ofile);
1613             remove(outname);
1614         }
1615         if (want_usage)
1616             usage();
1617         exit(1);                /* instantly die */
1618         break;                  /* placate silly compilers */
1619     case ERR_PANIC:
1620         fflush(NULL);
1621         /*      abort();        *//* halt, catch fire, and dump core */
1622         exit(3);
1623         break;
1624     }
1625 }
1626
1627 static void usage(void)
1628 {
1629     fputs("type `nasm -h' for help\n", error_file);
1630 }
1631
1632 static void register_output_formats(void)
1633 {
1634     ofmt = ofmt_register(report_error);
1635 }
1636
1637 #define BUF_DELTA 512
1638
1639 static FILE *no_pp_fp;
1640 static efunc no_pp_err;
1641 static ListGen *no_pp_list;
1642 static int32_t no_pp_lineinc;
1643
1644 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1645                         ListGen * listgen)
1646 {
1647     src_set_fname(nasm_strdup(file));
1648     src_set_linnum(0);
1649     no_pp_lineinc = 1;
1650     no_pp_err = error;
1651     no_pp_fp = fopen(file, "r");
1652     if (!no_pp_fp)
1653         no_pp_err(ERR_FATAL | ERR_NOFILE,
1654                   "unable to open input file `%s'", file);
1655     no_pp_list = listgen;
1656     (void)pass;                 /* placate compilers */
1657     (void)eval;                 /* placate compilers */
1658 }
1659
1660 static char *no_pp_getline(void)
1661 {
1662     char *buffer, *p, *q;
1663     int bufsize;
1664
1665     bufsize = BUF_DELTA;
1666     buffer = nasm_malloc(BUF_DELTA);
1667     src_set_linnum(src_get_linnum() + no_pp_lineinc);
1668
1669     while (1) {                 /* Loop to handle %line */
1670
1671         p = buffer;
1672         while (1) {             /* Loop to handle long lines */
1673             q = fgets(p, bufsize - (p - buffer), no_pp_fp);
1674             if (!q)
1675                 break;
1676             p += strlen(p);
1677             if (p > buffer && p[-1] == '\n')
1678                 break;
1679             if (p - buffer > bufsize - 10) {
1680                 int offset;
1681                 offset = p - buffer;
1682                 bufsize += BUF_DELTA;
1683                 buffer = nasm_realloc(buffer, bufsize);
1684                 p = buffer + offset;
1685             }
1686         }
1687
1688         if (!q && p == buffer) {
1689             nasm_free(buffer);
1690             return NULL;
1691         }
1692
1693         /*
1694          * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1695          * them are present at the end of the line.
1696          */
1697         buffer[strcspn(buffer, "\r\n\032")] = '\0';
1698
1699         if (!nasm_strnicmp(buffer, "%line", 5)) {
1700             int32_t ln;
1701             int li;
1702             char *nm = nasm_malloc(strlen(buffer));
1703             if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
1704                 nasm_free(src_set_fname(nm));
1705                 src_set_linnum(ln);
1706                 no_pp_lineinc = li;
1707                 continue;
1708             }
1709             nasm_free(nm);
1710         }
1711         break;
1712     }
1713
1714     no_pp_list->line(LIST_READ, buffer);
1715
1716     return buffer;
1717 }
1718
1719 static void no_pp_cleanup(int pass)
1720 {
1721     (void)pass;                     /* placate GCC */
1722     fclose(no_pp_fp);
1723 }
1724
1725 static uint32_t get_cpu(char *value)
1726 {
1727
1728     if (!strcmp(value, "8086"))
1729         return IF_8086;
1730     if (!strcmp(value, "186"))
1731         return IF_186;
1732     if (!strcmp(value, "286"))
1733         return IF_286;
1734     if (!strcmp(value, "386"))
1735         return IF_386;
1736     if (!strcmp(value, "486"))
1737         return IF_486;
1738     if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
1739         return IF_PENT;
1740     if (!strcmp(value, "686") ||
1741         !nasm_stricmp(value, "ppro") ||
1742         !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
1743         return IF_P6;
1744     if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
1745         return IF_KATMAI;
1746     if (!nasm_stricmp(value, "p4") ||   /* is this right? -- jrc */
1747         !nasm_stricmp(value, "willamette"))
1748         return IF_WILLAMETTE;
1749     if (!nasm_stricmp(value, "prescott"))
1750         return IF_PRESCOTT;
1751     if (!nasm_stricmp(value, "x64") ||
1752         !nasm_stricmp(value, "x86-64"))
1753         return IF_X86_64;
1754     if (!nasm_stricmp(value, "ia64") ||
1755         !nasm_stricmp(value, "ia-64") ||
1756         !nasm_stricmp(value, "itanium") ||
1757         !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
1758         return IF_IA64;
1759
1760     report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1761                  "unknown 'cpu' type");
1762
1763     return IF_PLEVEL;           /* the maximum level */
1764 }
1765
1766 static int get_bits(char *value)
1767 {
1768     int i;
1769
1770     if ((i = atoi(value)) == 16)
1771         return i;               /* set for a 16-bit segment */
1772     else if (i == 32) {
1773         if (cpu < IF_386) {
1774             report_error(ERR_NONFATAL,
1775                          "cannot specify 32-bit segment on processor below a 386");
1776             i = 16;
1777         }
1778     } else if (i == 64) {
1779         if (cpu < IF_X86_64) {
1780             report_error(ERR_NONFATAL,
1781                          "cannot specify 64-bit segment on processor below an x86-64");
1782             i = 16;
1783         }
1784         if (i != maxbits) {
1785             report_error(ERR_NONFATAL,
1786                          "%s output format does not support 64-bit code",
1787                          ofmt->shortname);
1788             i = 16;
1789         }
1790     } else {
1791         report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1792                      "`%s' is not a valid segment size; must be 16, 32 or 64",
1793                      value);
1794         i = 16;
1795     }
1796     return i;
1797 }
1798
1799 /* end of nasm.c */