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