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