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