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