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