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