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