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