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