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