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