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