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