Correct /is4 encoding for EVEX instructions
[nasm.git] / asm / nasm.c
blob6ed6a881b5ccb6104e7b35bad189b477f31dee7c
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 <limits.h>
46 #include <time.h>
48 #include "nasm.h"
49 #include "nasmlib.h"
50 #include "saa.h"
51 #include "raa.h"
52 #include "float.h"
53 #include "stdscan.h"
54 #include "insns.h"
55 #include "preproc.h"
56 #include "parser.h"
57 #include "eval.h"
58 #include "assemble.h"
59 #include "labels.h"
60 #include "outform.h"
61 #include "listing.h"
62 #include "iflag.h"
63 #include "ver.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 bool is_suppressed_warning(int severity);
82 static bool skip_this_pass(int severity);
83 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
84 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
85 static void nasm_verror_common(int severity, const char *fmt, va_list args);
86 static void usage(void);
88 static bool using_debug_info, opt_verbose_info;
89 static const char *debug_format;
91 bool tasm_compatible_mode = false;
92 int pass0, passn;
93 int globalrel = 0;
94 int globalbnd = 0;
96 static time_t official_compile_time;
98 static char inname[FILENAME_MAX];
99 static char outname[FILENAME_MAX];
100 static char listname[FILENAME_MAX];
101 static char errname[FILENAME_MAX];
102 static int globallineno; /* for forward-reference tracking */
103 /* static int pass = 0; */
104 const struct ofmt *ofmt = &OF_DEFAULT;
105 const struct ofmt_alias *ofmt_alias = NULL;
106 const struct dfmt *dfmt;
108 static FILE *error_file; /* Where to write error messages */
110 FILE *ofile = NULL;
111 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
112 static int sb, cmd_sb = 16; /* by default */
114 static iflag_t cpu;
115 static iflag_t cmd_cpu;
117 int64_t global_offset_changed; /* referenced in labels.c */
118 int64_t prev_offset_changed;
119 int32_t stall_count;
121 struct location location;
122 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
123 int32_t abs_seg; /* ABSOLUTE segment basis */
124 int32_t abs_offset; /* ABSOLUTE offset */
126 static struct RAA *offsets;
128 static struct SAA *forwrefs; /* keep track of forward references */
129 static const struct forwrefinfo *forwref;
131 static const struct preproc_ops *preproc;
133 #define OP_NORMAL (1u << 0)
134 #define OP_PREPROCESS (1u << 1)
135 #define OP_DEPEND (1u << 2)
137 static unsigned int operating_mode;
139 /* Dependency flags */
140 static bool depend_emit_phony = false;
141 static bool depend_missing_ok = false;
142 static const char *depend_target = NULL;
143 static const char *depend_file = NULL;
146 * Which of the suppressible warnings are suppressed. Entry zero
147 * isn't an actual warning, but it used for -w+error/-Werror.
150 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
151 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
153 static const struct warning {
154 const char *name;
155 const char *help;
156 bool enabled;
157 } warnings[ERR_WARN_MAX+1] = {
158 {"error", "treat warnings as errors", false},
159 {"macro-params", "macro calls with wrong parameter count", true},
160 {"macro-selfref", "cyclic macro references", false},
161 {"macro-defaults", "macros with more default than optional parameters", true},
162 {"orphan-labels", "labels alone on lines without trailing `:'", true},
163 {"number-overflow", "numeric constant does not fit", true},
164 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
165 {"float-overflow", "floating point overflow", true},
166 {"float-denorm", "floating point denormal", false},
167 {"float-underflow", "floating point underflow", false},
168 {"float-toolong", "too many digits in floating-point number", true},
169 {"user", "%warning directives", true},
170 {"lock", "lock prefix on unlockable instructions", true},
171 {"hle", "invalid hle prefixes", true},
172 {"bnd", "invalid bnd prefixes", true},
173 {"zext-reloc", "relocation zero-extended to match output format", true},
174 {"ptr", "non-NASM keyword used in other assemblers", true},
177 static bool want_usage;
178 static bool terminate_after_phase;
179 bool user_nolist = false;
181 static char *quote_for_make(const char *str);
183 static int64_t get_curr_offs(void)
185 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
188 static void set_curr_offs(int64_t l_off)
190 if (in_abs_seg)
191 abs_offset = l_off;
192 else
193 offsets = raa_write(offsets, location.segment, l_off);
196 static void nasm_fputs(const char *line, FILE * outfile)
198 if (outfile) {
199 fputs(line, outfile);
200 putc('\n', outfile);
201 } else
202 puts(line);
205 /* Convert a struct tm to a POSIX-style time constant */
206 static int64_t make_posix_time(struct tm *tm)
208 int64_t t;
209 int64_t y = tm->tm_year;
211 /* See IEEE 1003.1:2004, section 4.14 */
213 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
214 t += tm->tm_yday;
215 t *= 24;
216 t += tm->tm_hour;
217 t *= 60;
218 t += tm->tm_min;
219 t *= 60;
220 t += tm->tm_sec;
222 return t;
225 static void define_macros_early(void)
227 char temp[128];
228 struct tm lt, *lt_p, gm, *gm_p;
229 int64_t posix_time;
231 lt_p = localtime(&official_compile_time);
232 if (lt_p) {
233 lt = *lt_p;
235 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
238 preproc->pre_define(temp);
239 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
240 preproc->pre_define(temp);
241 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
242 preproc->pre_define(temp);
245 gm_p = gmtime(&official_compile_time);
246 if (gm_p) {
247 gm = *gm_p;
249 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
250 preproc->pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
252 preproc->pre_define(temp);
253 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
254 preproc->pre_define(temp);
255 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
256 preproc->pre_define(temp);
259 if (gm_p)
260 posix_time = make_posix_time(&gm);
261 else if (lt_p)
262 posix_time = make_posix_time(&lt);
263 else
264 posix_time = 0;
266 if (posix_time) {
267 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
268 preproc->pre_define(temp);
272 static void define_macros_late(void)
274 char temp[128];
277 * In case if output format is defined by alias
278 * we have to put shortname of the alias itself here
279 * otherwise ABI backward compatibility gets broken.
281 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
282 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
283 preproc->pre_define(temp);
286 static void emit_dependencies(StrList *list)
288 FILE *deps;
289 int linepos, len;
290 StrList *l, *nl;
292 if (depend_file && strcmp(depend_file, "-")) {
293 deps = nasm_open_write(depend_file, NF_TEXT);
294 if (!deps) {
295 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
296 "unable to write dependency file `%s'", depend_file);
297 return;
299 } else {
300 deps = stdout;
303 linepos = fprintf(deps, "%s:", depend_target);
304 list_for_each(l, list) {
305 char *file = quote_for_make(l->str);
306 len = strlen(file);
307 if (linepos + len > 62 && linepos > 1) {
308 fprintf(deps, " \\\n ");
309 linepos = 1;
311 fprintf(deps, " %s", file);
312 linepos += len+1;
313 nasm_free(file);
315 fprintf(deps, "\n\n");
317 list_for_each_safe(l, nl, list) {
318 if (depend_emit_phony)
319 fprintf(deps, "%s:\n\n", l->str);
320 nasm_free(l);
323 if (deps != stdout)
324 fclose(deps);
327 int main(int argc, char **argv)
329 StrList *depend_list = NULL, **depend_ptr;
331 time(&official_compile_time);
333 iflag_set(&cpu, IF_PLEVEL);
334 iflag_set(&cmd_cpu, IF_PLEVEL);
336 pass0 = 0;
337 want_usage = terminate_after_phase = false;
338 nasm_set_verror(nasm_verror_gnu);
340 error_file = stderr;
342 tolower_init();
343 src_init();
345 offsets = raa_init();
346 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
348 preproc = &nasmpp;
349 operating_mode = OP_NORMAL;
351 /* Define some macros dependent on the runtime, but not
352 on the command line. */
353 define_macros_early();
355 parse_cmdline(argc, argv);
357 if (terminate_after_phase) {
358 if (want_usage)
359 usage();
360 return 1;
363 if (!using_debug_info) {
364 /* No debug info, redirect to the null backend (empty stubs) */
365 dfmt = &null_debug_form;
366 } else if (!debug_format) {
367 /* Default debug format for this backend */
368 dfmt = ofmt->default_dfmt;
369 } else {
370 dfmt = dfmt_find(ofmt, debug_format);
371 if (!dfmt) {
372 nasm_fatal(ERR_NOFILE | ERR_USAGE,
373 "unrecognized debug format `%s' for"
374 " output format `%s'",
375 debug_format, ofmt->shortname);
379 if (ofmt->stdmac)
380 preproc->extra_stdmac(ofmt->stdmac);
382 /* define some macros dependent of command-line */
383 define_macros_late();
385 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
386 if (!depend_target)
387 depend_target = quote_for_make(outname);
389 if (operating_mode & OP_DEPEND) {
390 char *line;
392 if (depend_missing_ok)
393 preproc->include_path(NULL); /* "assume generated" */
395 preproc->reset(inname, 0, depend_ptr);
396 if (outname[0] == '\0')
397 ofmt->filename(inname, outname);
398 ofile = NULL;
399 while ((line = preproc->getline()))
400 nasm_free(line);
401 preproc->cleanup(0);
402 } else if (operating_mode & OP_PREPROCESS) {
403 char *line;
404 const char *file_name = NULL;
405 int32_t prior_linnum = 0;
406 int lineinc = 0;
408 if (*outname) {
409 ofile = nasm_open_write(outname, NF_TEXT);
410 if (!ofile)
411 nasm_fatal(ERR_NOFILE,
412 "unable to open output file `%s'",
413 outname);
414 } else
415 ofile = NULL;
417 location.known = false;
419 /* pass = 1; */
420 preproc->reset(inname, 3, depend_ptr);
421 memcpy(warning_on, warning_on_global,
422 (ERR_WARN_MAX+1) * sizeof(bool));
424 while ((line = preproc->getline())) {
426 * We generate %line directives if needed for later programs
428 int32_t linnum = prior_linnum += lineinc;
429 int altline = src_get(&linnum, &file_name);
430 if (altline) {
431 if (altline == 1 && lineinc == 1)
432 nasm_fputs("", ofile);
433 else {
434 lineinc = (altline != -1 || lineinc != 1);
435 fprintf(ofile ? ofile : stdout,
436 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
437 file_name);
439 prior_linnum = linnum;
441 nasm_fputs(line, ofile);
442 nasm_free(line);
444 preproc->cleanup(0);
445 if (ofile)
446 fclose(ofile);
447 if (ofile && terminate_after_phase)
448 remove(outname);
449 ofile = NULL;
452 if (operating_mode & OP_NORMAL) {
454 * We must call ofmt->filename _anyway_, even if the user
455 * has specified their own output file, because some
456 * formats (eg OBJ and COFF) use ofmt->filename to find out
457 * the name of the input file and then put that inside the
458 * file.
460 ofmt->filename(inname, outname);
462 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
463 if (!ofile)
464 nasm_fatal(ERR_NOFILE,
465 "unable to open output file `%s'", outname);
468 * We must call init_labels() before ofmt->init() since
469 * some object formats will want to define labels in their
470 * init routines. (eg OS/2 defines the FLAT group)
472 init_labels();
474 ofmt->init();
475 dfmt->init();
477 assemble_file(inname, depend_ptr);
479 if (!terminate_after_phase) {
480 ofmt->cleanup();
481 cleanup_labels();
482 fflush(ofile);
483 if (ferror(ofile)) {
484 nasm_error(ERR_NONFATAL|ERR_NOFILE,
485 "write error on output file `%s'", outname);
486 terminate_after_phase = true;
490 if (ofile) {
491 fclose(ofile);
492 if (terminate_after_phase)
493 remove(outname);
494 ofile = NULL;
498 if (depend_list && !terminate_after_phase)
499 emit_dependencies(depend_list);
501 if (want_usage)
502 usage();
504 raa_free(offsets);
505 saa_free(forwrefs);
506 eval_cleanup();
507 stdscan_cleanup();
508 src_free();
510 return terminate_after_phase;
514 * Get a parameter for a command line option.
515 * First arg must be in the form of e.g. -f...
517 static char *get_param(char *p, char *q, bool *advance)
519 *advance = false;
520 if (p[2]) /* the parameter's in the option */
521 return nasm_skip_spaces(p + 2);
522 if (q && q[0]) {
523 *advance = true;
524 return q;
526 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
527 "option `-%c' requires an argument", p[1]);
528 return NULL;
532 * Copy a filename
534 static void copy_filename(char *dst, const char *src)
536 size_t len = strlen(src);
538 if (len >= (size_t)FILENAME_MAX) {
539 nasm_fatal(ERR_NOFILE, "file name too long");
540 return;
542 strncpy(dst, src, FILENAME_MAX);
546 * Convert a string to Make-safe form
548 static char *quote_for_make(const char *str)
550 const char *p;
551 char *os, *q;
553 size_t n = 1; /* Terminating zero */
554 size_t nbs = 0;
556 if (!str)
557 return NULL;
559 for (p = str; *p; p++) {
560 switch (*p) {
561 case ' ':
562 case '\t':
563 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
564 n += nbs + 2;
565 nbs = 0;
566 break;
567 case '$':
568 case '#':
569 nbs = 0;
570 n += 2;
571 break;
572 case '\\':
573 nbs++;
574 n++;
575 break;
576 default:
577 nbs = 0;
578 n++;
579 break;
583 /* Convert N backslashes at the end of filename to 2N backslashes */
584 if (nbs)
585 n += nbs;
587 os = q = nasm_malloc(n);
589 nbs = 0;
590 for (p = str; *p; p++) {
591 switch (*p) {
592 case ' ':
593 case '\t':
594 while (nbs--)
595 *q++ = '\\';
596 *q++ = '\\';
597 *q++ = *p;
598 break;
599 case '$':
600 *q++ = *p;
601 *q++ = *p;
602 nbs = 0;
603 break;
604 case '#':
605 *q++ = '\\';
606 *q++ = *p;
607 nbs = 0;
608 break;
609 case '\\':
610 *q++ = *p;
611 nbs++;
612 break;
613 default:
614 *q++ = *p;
615 nbs = 0;
616 break;
619 while (nbs--)
620 *q++ = '\\';
622 *q = '\0';
624 return os;
627 struct textargs {
628 const char *label;
629 int value;
632 enum text_options {
633 OPT_PREFIX,
634 OPT_POSTFIX
636 static const struct textargs textopts[] = {
637 {"prefix", OPT_PREFIX},
638 {"postfix", OPT_POSTFIX},
639 {NULL, 0}
642 static void show_version(void)
644 printf("NASM version %s compiled on %s%s\n",
645 nasm_version, nasm_date, nasm_compile_options);
646 exit(0);
649 static bool stopoptions = false;
650 static bool process_arg(char *p, char *q)
652 char *param;
653 int i;
654 bool advance = false;
655 bool do_warn;
657 if (!p || !p[0])
658 return false;
660 if (p[0] == '-' && !stopoptions) {
661 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
662 /* These parameters take values */
663 if (!(param = get_param(p, q, &advance)))
664 return advance;
667 switch (p[1]) {
668 case 's':
669 error_file = stdout;
670 break;
672 case 'o': /* output file */
673 copy_filename(outname, param);
674 break;
676 case 'f': /* output format */
677 ofmt = ofmt_find(param, &ofmt_alias);
678 if (!ofmt) {
679 nasm_fatal(ERR_NOFILE | ERR_USAGE,
680 "unrecognised output format `%s' - "
681 "use -hf for a list", param);
683 break;
685 case 'O': /* Optimization level */
687 int opt;
689 if (!*param) {
690 /* Naked -O == -Ox */
691 optimizing = MAX_OPTIMIZE;
692 } else {
693 while (*param) {
694 switch (*param) {
695 case '0': case '1': case '2': case '3': case '4':
696 case '5': case '6': case '7': case '8': case '9':
697 opt = strtoul(param, &param, 10);
699 /* -O0 -> optimizing == -1, 0.98 behaviour */
700 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
701 if (opt < 2)
702 optimizing = opt - 1;
703 else
704 optimizing = opt;
705 break;
707 case 'v':
708 case '+':
709 param++;
710 opt_verbose_info = true;
711 break;
713 case 'x':
714 param++;
715 optimizing = MAX_OPTIMIZE;
716 break;
718 default:
719 nasm_fatal(0,
720 "unknown optimization option -O%c\n",
721 *param);
722 break;
725 if (optimizing > MAX_OPTIMIZE)
726 optimizing = MAX_OPTIMIZE;
728 break;
731 case 'p': /* pre-include */
732 case 'P':
733 preproc->pre_include(param);
734 break;
736 case 'd': /* pre-define */
737 case 'D':
738 preproc->pre_define(param);
739 break;
741 case 'u': /* un-define */
742 case 'U':
743 preproc->pre_undefine(param);
744 break;
746 case 'i': /* include search path */
747 case 'I':
748 preproc->include_path(param);
749 break;
751 case 'l': /* listing file */
752 copy_filename(listname, param);
753 break;
755 case 'Z': /* error messages file */
756 copy_filename(errname, param);
757 break;
759 case 'F': /* specify debug format */
760 using_debug_info = true;
761 debug_format = param;
762 break;
764 case 'X': /* specify error reporting format */
765 if (nasm_stricmp("vc", param) == 0)
766 nasm_set_verror(nasm_verror_vc);
767 else if (nasm_stricmp("gnu", param) == 0)
768 nasm_set_verror(nasm_verror_gnu);
769 else
770 nasm_fatal(ERR_NOFILE | ERR_USAGE,
771 "unrecognized error reporting format `%s'",
772 param);
773 break;
775 case 'g':
776 using_debug_info = true;
777 if (p[2])
778 debug_format = nasm_skip_spaces(p + 2);
779 break;
781 case 'h':
782 printf
783 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
784 "[-l listfile]\n"
785 " [options...] [--] filename\n"
786 " or nasm -v (or --v) for version info\n\n"
787 " -t assemble in SciTech TASM compatible mode\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 " -g generate debugging information\n\n"
801 " -F format select a debugging format\n\n"
802 " -gformat same as -g -F format\n\n"
803 " -o outfile write output to an outfile\n\n"
804 " -f format select an output format\n\n"
805 " -l listfile write listing to a listfile\n\n"
806 " -I<path> adds a pathname to the include file path\n");
807 printf
808 (" -O<digit> optimize branch offsets\n"
809 " -O0: No optimization\n"
810 " -O1: Minimal optimization\n"
811 " -Ox: Multipass optimization (default)\n\n"
812 " -P<file> pre-includes a file\n"
813 " -D<macro>[=<value>] pre-defines a macro\n"
814 " -U<macro> undefines a macro\n"
815 " -X<format> specifies error reporting format (gnu or vc)\n"
816 " -w+foo enables warning foo (equiv. -Wfoo)\n"
817 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
818 " -h show invocation summary and exit\n\n"
819 "--prefix,--postfix\n"
820 " this options prepend or append the given argument to all\n"
821 " extern and global variables\n"
822 "Warnings:\n");
823 for (i = 0; i <= ERR_WARN_MAX; i++)
824 printf(" %-23s %s (default %s)\n",
825 warnings[i].name, warnings[i].help,
826 warnings[i].enabled ? "on" : "off");
827 printf
828 ("\nresponse files should contain command line parameters"
829 ", one per line.\n");
830 if (p[2] == 'f') {
831 printf("\nvalid output formats for -f are"
832 " (`*' denotes default):\n");
833 ofmt_list(ofmt, stdout);
834 } else {
835 printf("\nFor a list of valid output formats, use -hf.\n");
836 printf("For a list of debug formats, use -f <form> -y.\n");
838 exit(0); /* never need usage message here */
839 break;
841 case 'y':
842 printf("\nvalid debug formats for '%s' output format are"
843 " ('*' denotes default):\n", ofmt->shortname);
844 dfmt_list(ofmt, stdout);
845 exit(0);
846 break;
848 case 't':
849 tasm_compatible_mode = true;
850 break;
852 case 'v':
853 show_version();
854 break;
856 case 'e': /* preprocess only */
857 case 'E':
858 operating_mode = OP_PREPROCESS;
859 break;
861 case 'a': /* assemble only - don't preprocess */
862 preproc = &preproc_nop;
863 break;
865 case 'W':
866 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
867 do_warn = false;
868 param += 3;
869 } else {
870 do_warn = true;
872 goto set_warning;
874 case 'w':
875 if (param[0] != '+' && param[0] != '-') {
876 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
877 "invalid option to `-w'");
878 break;
880 do_warn = (param[0] == '+');
881 param++;
883 set_warning:
884 for (i = 0; i <= ERR_WARN_MAX; i++) {
885 if (!nasm_stricmp(param, warnings[i].name))
886 break;
888 if (i <= ERR_WARN_MAX) {
889 warning_on_global[i] = do_warn;
890 } else if (!nasm_stricmp(param, "all")) {
891 for (i = 1; i <= ERR_WARN_MAX; i++)
892 warning_on_global[i] = do_warn;
893 } else if (!nasm_stricmp(param, "none")) {
894 for (i = 1; i <= ERR_WARN_MAX; i++)
895 warning_on_global[i] = !do_warn;
896 } else {
897 /* Ignore invalid warning names; forward compatibility */
899 break;
901 case 'M':
902 switch (p[2]) {
903 case 0:
904 operating_mode = OP_DEPEND;
905 break;
906 case 'G':
907 operating_mode = OP_DEPEND;
908 depend_missing_ok = true;
909 break;
910 case 'P':
911 depend_emit_phony = true;
912 break;
913 case 'D':
914 operating_mode = OP_NORMAL;
915 depend_file = q;
916 advance = true;
917 break;
918 case 'F':
919 depend_file = q;
920 advance = true;
921 break;
922 case 'T':
923 depend_target = q;
924 advance = true;
925 break;
926 case 'Q':
927 depend_target = quote_for_make(q);
928 advance = true;
929 break;
930 default:
931 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
932 "unknown dependency option `-M%c'", p[2]);
933 break;
935 if (advance && (!q || !q[0])) {
936 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
937 "option `-M%c' requires a parameter", p[2]);
938 break;
940 break;
942 case '-':
944 int s;
946 if (p[2] == 0) { /* -- => stop processing options */
947 stopoptions = 1;
948 break;
951 if (!nasm_stricmp(p, "--v"))
952 show_version();
954 if (!nasm_stricmp(p, "--version"))
955 show_version();
957 for (s = 0; textopts[s].label; s++) {
958 if (!nasm_stricmp(p + 2, textopts[s].label)) {
959 break;
963 switch (s) {
965 case OPT_PREFIX:
966 case OPT_POSTFIX:
968 if (!q) {
969 nasm_error(ERR_NONFATAL | ERR_NOFILE |
970 ERR_USAGE,
971 "option `--%s' requires an argument",
972 p + 2);
973 break;
974 } else {
975 advance = 1, param = q;
978 switch (s) {
979 case OPT_PREFIX:
980 strlcpy(lprefix, param, PREFIX_MAX);
981 break;
982 case OPT_POSTFIX:
983 strlcpy(lpostfix, param, POSTFIX_MAX);
984 break;
985 default:
986 nasm_panic(ERR_NOFILE,
987 "internal error");
988 break;
990 break;
993 default:
995 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
996 "unrecognised option `--%s'", p + 2);
997 break;
1000 break;
1003 default:
1004 if (!ofmt->setinfo(GI_SWITCH, &p))
1005 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1006 "unrecognised option `-%c'", p[1]);
1007 break;
1009 } else {
1010 if (*inname) {
1011 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1012 "more than one input file specified");
1013 } else {
1014 copy_filename(inname, p);
1018 return advance;
1021 #define ARG_BUF_DELTA 128
1023 static void process_respfile(FILE * rfile)
1025 char *buffer, *p, *q, *prevarg;
1026 int bufsize, prevargsize;
1028 bufsize = prevargsize = ARG_BUF_DELTA;
1029 buffer = nasm_malloc(ARG_BUF_DELTA);
1030 prevarg = nasm_malloc(ARG_BUF_DELTA);
1031 prevarg[0] = '\0';
1033 while (1) { /* Loop to handle all lines in file */
1034 p = buffer;
1035 while (1) { /* Loop to handle long lines */
1036 q = fgets(p, bufsize - (p - buffer), rfile);
1037 if (!q)
1038 break;
1039 p += strlen(p);
1040 if (p > buffer && p[-1] == '\n')
1041 break;
1042 if (p - buffer > bufsize - 10) {
1043 int offset;
1044 offset = p - buffer;
1045 bufsize += ARG_BUF_DELTA;
1046 buffer = nasm_realloc(buffer, bufsize);
1047 p = buffer + offset;
1051 if (!q && p == buffer) {
1052 if (prevarg[0])
1053 process_arg(prevarg, NULL);
1054 nasm_free(buffer);
1055 nasm_free(prevarg);
1056 return;
1060 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1061 * them are present at the end of the line.
1063 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1065 while (p > buffer && nasm_isspace(p[-1]))
1066 *--p = '\0';
1068 p = nasm_skip_spaces(buffer);
1070 if (process_arg(prevarg, p))
1071 *p = '\0';
1073 if ((int) strlen(p) > prevargsize - 10) {
1074 prevargsize += ARG_BUF_DELTA;
1075 prevarg = nasm_realloc(prevarg, prevargsize);
1077 strncpy(prevarg, p, prevargsize);
1081 /* Function to process args from a string of args, rather than the
1082 * argv array. Used by the environment variable and response file
1083 * processing.
1085 static void process_args(char *args)
1087 char *p, *q, *arg, *prevarg;
1088 char separator = ' ';
1090 p = args;
1091 if (*p && *p != '-')
1092 separator = *p++;
1093 arg = NULL;
1094 while (*p) {
1095 q = p;
1096 while (*p && *p != separator)
1097 p++;
1098 while (*p == separator)
1099 *p++ = '\0';
1100 prevarg = arg;
1101 arg = q;
1102 if (process_arg(prevarg, arg))
1103 arg = NULL;
1105 if (arg)
1106 process_arg(arg, NULL);
1109 static void process_response_file(const char *file)
1111 char str[2048];
1112 FILE *f = nasm_open_read(file, NF_TEXT);
1113 if (!f) {
1114 perror(file);
1115 exit(-1);
1117 while (fgets(str, sizeof str, f)) {
1118 process_args(str);
1120 fclose(f);
1123 static void parse_cmdline(int argc, char **argv)
1125 FILE *rfile;
1126 char *envreal, *envcopy = NULL, *p;
1127 int i;
1129 *inname = *outname = *listname = *errname = '\0';
1131 for (i = 0; i <= ERR_WARN_MAX; i++)
1132 warning_on_global[i] = warnings[i].enabled;
1135 * First, process the NASMENV environment variable.
1137 envreal = getenv("NASMENV");
1138 if (envreal) {
1139 envcopy = nasm_strdup(envreal);
1140 process_args(envcopy);
1141 nasm_free(envcopy);
1145 * Now process the actual command line.
1147 while (--argc) {
1148 bool advance;
1149 argv++;
1150 if (argv[0][0] == '@') {
1152 * We have a response file, so process this as a set of
1153 * arguments like the environment variable. This allows us
1154 * to have multiple arguments on a single line, which is
1155 * different to the -@resp file processing below for regular
1156 * NASM.
1158 process_response_file(argv[0]+1);
1159 argc--;
1160 argv++;
1162 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1163 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1164 if (p) {
1165 rfile = nasm_open_read(p, NF_TEXT);
1166 if (rfile) {
1167 process_respfile(rfile);
1168 fclose(rfile);
1169 } else
1170 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1171 "unable to open response file `%s'", p);
1173 } else
1174 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1175 argv += advance, argc -= advance;
1179 * Look for basic command line typos. This definitely doesn't
1180 * catch all errors, but it might help cases of fumbled fingers.
1182 if (!*inname)
1183 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1184 "no input file specified");
1185 else if (!strcmp(inname, errname) ||
1186 !strcmp(inname, outname) ||
1187 !strcmp(inname, listname) ||
1188 (depend_file && !strcmp(inname, depend_file)))
1189 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1190 "file `%s' is both input and output file",
1191 inname);
1193 if (*errname) {
1194 error_file = nasm_open_write(errname, NF_TEXT);
1195 if (!error_file) {
1196 error_file = stderr; /* Revert to default! */
1197 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1198 "cannot open file `%s' for error messages",
1199 errname);
1204 static enum directives getkw(char **directive, char **value);
1206 static void assemble_file(char *fname, StrList **depend_ptr)
1208 char *directive, *value, *p, *q, *special, *line;
1209 insn output_ins;
1210 int i, validid;
1211 bool rn_error;
1212 int32_t seg;
1213 int64_t offs;
1214 struct tokenval tokval;
1215 expr *e;
1216 int pass_max;
1218 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1219 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1221 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1222 for (passn = 1; pass0 <= 2; passn++) {
1223 int pass1, pass2;
1224 ldfunc def_label;
1226 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1227 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1228 /* pass0 0, 0, 0, ..., 1, 2 */
1230 def_label = passn > 1 ? redefine_label : define_label;
1232 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1233 cpu = cmd_cpu;
1234 if (pass0 == 2) {
1235 lfmt->init(listname);
1237 in_abs_seg = false;
1238 global_offset_changed = 0; /* set by redefine_label */
1239 location.segment = ofmt->section(NULL, pass2, &sb);
1240 globalbits = sb;
1241 if (passn > 1) {
1242 saa_rewind(forwrefs);
1243 forwref = saa_rstruct(forwrefs);
1244 raa_free(offsets);
1245 offsets = raa_init();
1247 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1248 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1250 globallineno = 0;
1251 if (passn == 1)
1252 location.known = true;
1253 location.offset = offs = get_curr_offs();
1255 while ((line = preproc->getline())) {
1256 enum directives d;
1257 globallineno++;
1260 * Here we parse our directives; this is not handled by the
1261 * 'real' parser. This really should be a separate function.
1263 directive = line;
1264 d = getkw(&directive, &value);
1265 if (d) {
1266 int err = 0;
1268 switch (d) {
1269 case D_SEGMENT: /* [SEGMENT n] */
1270 case D_SECTION:
1271 seg = ofmt->section(value, pass2, &sb);
1272 if (seg == NO_SEG) {
1273 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1274 "segment name `%s' not recognized",
1275 value);
1276 } else {
1277 in_abs_seg = false;
1278 location.segment = seg;
1280 break;
1281 case D_SECTALIGN: /* [SECTALIGN n] */
1282 if (*value) {
1283 stdscan_reset();
1284 stdscan_set(value);
1285 tokval.t_type = TOKEN_INVALID;
1286 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1287 if (e) {
1288 unsigned int align = (unsigned int)e->value;
1289 if ((uint64_t)e->value > 0x7fffffff) {
1291 * FIXME: Please make some sane message here
1292 * ofmt should have some 'check' method which
1293 * would report segment alignment bounds.
1295 nasm_fatal(0,
1296 "incorrect segment alignment `%s'", value);
1297 } else if (!is_power2(align)) {
1298 nasm_error(ERR_NONFATAL,
1299 "segment alignment `%s' is not power of two",
1300 value);
1303 /* callee should be able to handle all details */
1304 if (location.segment != NO_SEG)
1305 ofmt->sectalign(location.segment, align);
1308 break;
1309 case D_EXTERN: /* [EXTERN label:special] */
1310 if (*value == '$')
1311 value++; /* skip initial $ if present */
1312 if (pass0 == 2) {
1313 q = value;
1314 while (*q && *q != ':')
1315 q++;
1316 if (*q == ':') {
1317 *q++ = '\0';
1318 ofmt->symdef(value, 0L, 0L, 3, q);
1320 } else if (passn == 1) {
1321 q = value;
1322 validid = true;
1323 if (!isidstart(*q))
1324 validid = false;
1325 while (*q && *q != ':') {
1326 if (!isidchar(*q))
1327 validid = false;
1328 q++;
1330 if (!validid) {
1331 nasm_error(ERR_NONFATAL,
1332 "identifier expected after EXTERN");
1333 break;
1335 if (*q == ':') {
1336 *q++ = '\0';
1337 special = q;
1338 } else
1339 special = NULL;
1340 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1341 int temp = pass0;
1342 pass0 = 1; /* fake pass 1 in labels.c */
1343 declare_as_global(value, special);
1344 define_label(value, seg_alloc(), 0L, NULL,
1345 false, true);
1346 pass0 = temp;
1348 } /* else pass0 == 1 */
1349 break;
1350 case D_BITS: /* [BITS bits] */
1351 globalbits = sb = get_bits(value);
1352 break;
1353 case D_GLOBAL: /* [GLOBAL symbol:special] */
1354 if (*value == '$')
1355 value++; /* skip initial $ if present */
1356 if (pass0 == 2) { /* pass 2 */
1357 q = value;
1358 while (*q && *q != ':')
1359 q++;
1360 if (*q == ':') {
1361 *q++ = '\0';
1362 ofmt->symdef(value, 0L, 0L, 3, q);
1364 } else if (pass2 == 1) { /* pass == 1 */
1365 q = value;
1366 validid = true;
1367 if (!isidstart(*q))
1368 validid = false;
1369 while (*q && *q != ':') {
1370 if (!isidchar(*q))
1371 validid = false;
1372 q++;
1374 if (!validid) {
1375 nasm_error(ERR_NONFATAL,
1376 "identifier expected after GLOBAL");
1377 break;
1379 if (*q == ':') {
1380 *q++ = '\0';
1381 special = q;
1382 } else
1383 special = NULL;
1384 declare_as_global(value, special);
1385 } /* pass == 1 */
1386 break;
1387 case D_COMMON: /* [COMMON symbol size:special] */
1389 int64_t size;
1391 if (*value == '$')
1392 value++; /* skip initial $ if present */
1393 p = value;
1394 validid = true;
1395 if (!isidstart(*p))
1396 validid = false;
1397 while (*p && !nasm_isspace(*p)) {
1398 if (!isidchar(*p))
1399 validid = false;
1400 p++;
1402 if (!validid) {
1403 nasm_error(ERR_NONFATAL,
1404 "identifier expected after COMMON");
1405 break;
1407 if (*p) {
1408 p = nasm_zap_spaces_fwd(p);
1409 q = p;
1410 while (*q && *q != ':')
1411 q++;
1412 if (*q == ':') {
1413 *q++ = '\0';
1414 special = q;
1415 } else {
1416 special = NULL;
1418 size = readnum(p, &rn_error);
1419 if (rn_error) {
1420 nasm_error(ERR_NONFATAL,
1421 "invalid size specified"
1422 " in COMMON declaration");
1423 break;
1425 } else {
1426 nasm_error(ERR_NONFATAL,
1427 "no size specified in"
1428 " COMMON declaration");
1429 break;
1432 if (pass0 < 2) {
1433 define_common(value, seg_alloc(), size, special);
1434 } else if (pass0 == 2) {
1435 if (special)
1436 ofmt->symdef(value, 0L, 0L, 3, special);
1438 break;
1440 case D_ABSOLUTE: /* [ABSOLUTE address] */
1441 stdscan_reset();
1442 stdscan_set(value);
1443 tokval.t_type = TOKEN_INVALID;
1444 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1445 if (e) {
1446 if (!is_reloc(e))
1447 nasm_error(pass0 ==
1448 1 ? ERR_NONFATAL : ERR_PANIC,
1449 "cannot use non-relocatable expression as "
1450 "ABSOLUTE address");
1451 else {
1452 abs_seg = reloc_seg(e);
1453 abs_offset = reloc_value(e);
1455 } else if (passn == 1)
1456 abs_offset = 0x100; /* don't go near zero in case of / */
1457 else
1458 nasm_panic(0, "invalid ABSOLUTE address "
1459 "in pass two");
1460 in_abs_seg = true;
1461 location.segment = NO_SEG;
1462 break;
1463 case D_DEBUG: /* [DEBUG] */
1465 char debugid[128];
1466 bool badid, overlong;
1468 p = value;
1469 q = debugid;
1470 badid = overlong = false;
1471 if (!isidstart(*p)) {
1472 badid = true;
1473 } else {
1474 while (*p && !nasm_isspace(*p)) {
1475 if (q >= debugid + sizeof debugid - 1) {
1476 overlong = true;
1477 break;
1479 if (!isidchar(*p))
1480 badid = true;
1481 *q++ = *p++;
1483 *q = 0;
1485 if (badid) {
1486 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1487 "identifier expected after DEBUG");
1488 break;
1490 if (overlong) {
1491 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1492 "DEBUG identifier too long");
1493 break;
1495 p = nasm_skip_spaces(p);
1496 if (pass0 == 2)
1497 dfmt->debug_directive(debugid, p);
1498 break;
1500 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1501 value = nasm_skip_spaces(value);
1502 switch(*value) {
1503 case '-': validid = 0; value++; break;
1504 case '+': validid = 1; value++; break;
1505 case '*': validid = 2; value++; break;
1506 default: validid = 1; break;
1509 for (i = 1; i <= ERR_WARN_MAX; i++)
1510 if (!nasm_stricmp(value, warnings[i].name))
1511 break;
1512 if (i <= ERR_WARN_MAX) {
1513 switch(validid) {
1514 case 0:
1515 warning_on[i] = false;
1516 break;
1517 case 1:
1518 warning_on[i] = true;
1519 break;
1520 case 2:
1521 warning_on[i] = warning_on_global[i];
1522 break;
1525 break;
1526 case D_CPU: /* [CPU] */
1527 cpu = get_cpu(value);
1528 break;
1529 case D_LIST: /* [LIST {+|-}] */
1530 value = nasm_skip_spaces(value);
1531 if (*value == '+') {
1532 user_nolist = 0;
1533 } else {
1534 if (*value == '-') {
1535 user_nolist = 1;
1536 } else {
1537 err = 1;
1540 break;
1541 case D_DEFAULT: /* [DEFAULT] */
1542 stdscan_reset();
1543 stdscan_set(value);
1544 tokval.t_type = TOKEN_INVALID;
1545 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1546 switch ((int)tokval.t_integer) {
1547 case S_REL:
1548 globalrel = 1;
1549 break;
1550 case S_ABS:
1551 globalrel = 0;
1552 break;
1553 case P_BND:
1554 globalbnd = 1;
1555 break;
1556 case P_NOBND:
1557 globalbnd = 0;
1558 break;
1559 default:
1560 err = 1;
1561 break;
1563 } else {
1564 err = 1;
1566 break;
1567 case D_FLOAT:
1568 if (float_option(value)) {
1569 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1570 "unknown 'float' directive: %s",
1571 value);
1573 break;
1574 default:
1575 if (ofmt->directive(d, value, pass2))
1576 break;
1577 /* else fall through */
1578 case D_unknown:
1579 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1580 "unrecognised directive [%s]",
1581 directive);
1582 break;
1584 if (err) {
1585 nasm_error(ERR_NONFATAL,
1586 "invalid parameter to [%s] directive",
1587 directive);
1589 } else { /* it isn't a directive */
1590 parse_line(pass1, line, &output_ins, def_label);
1592 if (optimizing > 0) {
1593 if (forwref != NULL && globallineno == forwref->lineno) {
1594 output_ins.forw_ref = true;
1595 do {
1596 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1597 forwref = saa_rstruct(forwrefs);
1598 } while (forwref != NULL
1599 && forwref->lineno == globallineno);
1600 } else
1601 output_ins.forw_ref = false;
1603 if (output_ins.forw_ref) {
1604 if (passn == 1) {
1605 for (i = 0; i < output_ins.operands; i++) {
1606 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1607 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1608 fwinf->lineno = globallineno;
1609 fwinf->operand = i;
1616 /* forw_ref */
1617 if (output_ins.opcode == I_EQU) {
1618 if (pass1 == 1) {
1620 * Special `..' EQUs get processed in pass two,
1621 * except `..@' macro-processor EQUs which are done
1622 * in the normal place.
1624 if (!output_ins.label)
1625 nasm_error(ERR_NONFATAL,
1626 "EQU not preceded by label");
1628 else if (output_ins.label[0] != '.' ||
1629 output_ins.label[1] != '.' ||
1630 output_ins.label[2] == '@') {
1631 if (output_ins.operands == 1 &&
1632 (output_ins.oprs[0].type & IMMEDIATE) &&
1633 output_ins.oprs[0].wrt == NO_SEG) {
1634 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1635 def_label(output_ins.label,
1636 output_ins.oprs[0].segment,
1637 output_ins.oprs[0].offset, NULL,
1638 false, isext);
1639 } else if (output_ins.operands == 2
1640 && (output_ins.oprs[0].type & IMMEDIATE)
1641 && (output_ins.oprs[0].type & COLON)
1642 && output_ins.oprs[0].segment == NO_SEG
1643 && output_ins.oprs[0].wrt == NO_SEG
1644 && (output_ins.oprs[1].type & IMMEDIATE)
1645 && output_ins.oprs[1].segment == NO_SEG
1646 && output_ins.oprs[1].wrt == NO_SEG) {
1647 def_label(output_ins.label,
1648 output_ins.oprs[0].offset | SEG_ABS,
1649 output_ins.oprs[1].offset,
1650 NULL, false, false);
1651 } else
1652 nasm_error(ERR_NONFATAL,
1653 "bad syntax for EQU");
1655 } else {
1657 * Special `..' EQUs get processed here, except
1658 * `..@' macro processor EQUs which are done above.
1660 if (output_ins.label[0] == '.' &&
1661 output_ins.label[1] == '.' &&
1662 output_ins.label[2] != '@') {
1663 if (output_ins.operands == 1 &&
1664 (output_ins.oprs[0].type & IMMEDIATE)) {
1665 define_label(output_ins.label,
1666 output_ins.oprs[0].segment,
1667 output_ins.oprs[0].offset,
1668 NULL, false, false);
1669 } else if (output_ins.operands == 2
1670 && (output_ins.oprs[0].type & IMMEDIATE)
1671 && (output_ins.oprs[0].type & COLON)
1672 && output_ins.oprs[0].segment == NO_SEG
1673 && (output_ins.oprs[1].type & IMMEDIATE)
1674 && output_ins.oprs[1].segment == NO_SEG) {
1675 define_label(output_ins.label,
1676 output_ins.oprs[0].offset | SEG_ABS,
1677 output_ins.oprs[1].offset,
1678 NULL, false, false);
1679 } else
1680 nasm_error(ERR_NONFATAL,
1681 "bad syntax for EQU");
1684 } else { /* instruction isn't an EQU */
1686 if (pass1 == 1) {
1688 int64_t l = insn_size(location.segment, offs, sb, cpu,
1689 &output_ins);
1690 l *= output_ins.times;
1692 /* if (using_debug_info) && output_ins.opcode != -1) */
1693 if (using_debug_info)
1694 { /* fbk 03/25/01 */
1695 /* this is done here so we can do debug type info */
1696 int32_t typeinfo =
1697 TYS_ELEMENTS(output_ins.operands);
1698 switch (output_ins.opcode) {
1699 case I_RESB:
1700 typeinfo =
1701 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1702 break;
1703 case I_RESW:
1704 typeinfo =
1705 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1706 break;
1707 case I_RESD:
1708 typeinfo =
1709 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1710 break;
1711 case I_RESQ:
1712 typeinfo =
1713 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1714 break;
1715 case I_REST:
1716 typeinfo =
1717 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1718 break;
1719 case I_RESO:
1720 typeinfo =
1721 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1722 break;
1723 case I_RESY:
1724 typeinfo =
1725 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1726 break;
1727 case I_DB:
1728 typeinfo |= TY_BYTE;
1729 break;
1730 case I_DW:
1731 typeinfo |= TY_WORD;
1732 break;
1733 case I_DD:
1734 if (output_ins.eops_float)
1735 typeinfo |= TY_FLOAT;
1736 else
1737 typeinfo |= TY_DWORD;
1738 break;
1739 case I_DQ:
1740 typeinfo |= TY_QWORD;
1741 break;
1742 case I_DT:
1743 typeinfo |= TY_TBYTE;
1744 break;
1745 case I_DO:
1746 typeinfo |= TY_OWORD;
1747 break;
1748 case I_DY:
1749 typeinfo |= TY_YWORD;
1750 break;
1751 default:
1752 typeinfo = TY_LABEL;
1756 dfmt->debug_typevalue(typeinfo);
1758 if (l != -1) {
1759 offs += l;
1760 set_curr_offs(offs);
1763 * else l == -1 => invalid instruction, which will be
1764 * flagged as an error on pass 2
1767 } else {
1768 offs += assemble(location.segment, offs, sb, cpu,
1769 &output_ins);
1770 set_curr_offs(offs);
1773 } /* not an EQU */
1774 cleanup_insn(&output_ins);
1776 nasm_free(line);
1777 location.offset = offs = get_curr_offs();
1778 } /* end while (line = preproc->getline... */
1780 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1781 nasm_error(ERR_NONFATAL,
1782 "phase error detected at end of assembly.");
1784 if (pass1 == 1)
1785 preproc->cleanup(1);
1787 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1788 pass0++;
1789 } else if (global_offset_changed &&
1790 global_offset_changed < prev_offset_changed) {
1791 prev_offset_changed = global_offset_changed;
1792 stall_count = 0;
1793 } else {
1794 stall_count++;
1797 if (terminate_after_phase)
1798 break;
1800 if ((stall_count > 997) || (passn >= pass_max)) {
1801 /* We get here if the labels don't converge
1802 * Example: FOO equ FOO + 1
1804 nasm_error(ERR_NONFATAL,
1805 "Can't find valid values for all labels "
1806 "after %d passes, giving up.", passn);
1807 nasm_error(ERR_NONFATAL,
1808 "Possible causes: recursive EQUs, macro abuse.");
1809 break;
1813 preproc->cleanup(0);
1814 lfmt->cleanup();
1815 if (!terminate_after_phase && opt_verbose_info) {
1816 /* -On and -Ov switches */
1817 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1821 static enum directives getkw(char **directive, char **value)
1823 char *p, *q, *buf;
1825 buf = nasm_skip_spaces(*directive);
1827 /* it should be enclosed in [ ] */
1828 if (*buf != '[')
1829 return D_none;
1830 q = strchr(buf, ']');
1831 if (!q)
1832 return D_none;
1834 /* stip off the comments */
1835 p = strchr(buf, ';');
1836 if (p) {
1837 if (p < q) /* ouch! somwhere inside */
1838 return D_none;
1839 *p = '\0';
1842 /* no brace, no trailing spaces */
1843 *q = '\0';
1844 nasm_zap_spaces_rev(--q);
1846 /* directive */
1847 p = nasm_skip_spaces(++buf);
1848 q = nasm_skip_word(p);
1849 if (!q)
1850 return D_none; /* sigh... no value there */
1851 *q = '\0';
1852 *directive = p;
1854 /* and value finally */
1855 p = nasm_skip_spaces(++q);
1856 *value = p;
1858 return find_directive(*directive);
1862 * gnu style error reporting
1863 * This function prints an error message to error_file in the
1864 * style used by GNU. An example would be:
1865 * file.asm:50: error: blah blah blah
1866 * where file.asm is the name of the file, 50 is the line number on
1867 * which the error occurs (or is detected) and "error:" is one of
1868 * the possible optional diagnostics -- it can be "error" or "warning"
1869 * or something else. Finally the line terminates with the actual
1870 * error message.
1872 * @param severity the severity of the warning or error
1873 * @param fmt the printf style format string
1875 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1877 const char *currentfile = NULL;
1878 int32_t lineno = 0;
1880 if (is_suppressed_warning(severity))
1881 return;
1883 if (!(severity & ERR_NOFILE))
1884 src_get(&lineno, &currentfile);
1886 if (!skip_this_pass(severity)) {
1887 if (currentfile) {
1888 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1889 } else {
1890 fputs("nasm: ", error_file);
1894 nasm_verror_common(severity, fmt, ap);
1898 * MS style error reporting
1899 * This function prints an error message to error_file in the
1900 * style used by Visual C and some other Microsoft tools. An example
1901 * would be:
1902 * file.asm(50) : error: blah blah blah
1903 * where file.asm is the name of the file, 50 is the line number on
1904 * which the error occurs (or is detected) and "error:" is one of
1905 * the possible optional diagnostics -- it can be "error" or "warning"
1906 * or something else. Finally the line terminates with the actual
1907 * error message.
1909 * @param severity the severity of the warning or error
1910 * @param fmt the printf style format string
1912 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1914 const char *currentfile = NULL;
1915 int32_t lineno = 0;
1917 if (is_suppressed_warning(severity))
1918 return;
1920 if (!(severity & ERR_NOFILE))
1921 src_get(&lineno, &currentfile);
1923 if (!skip_this_pass(severity)) {
1924 if (currentfile) {
1925 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1926 } else {
1927 fputs("nasm: ", error_file);
1931 nasm_verror_common(severity, fmt, ap);
1935 * check for supressed warning
1936 * checks for suppressed warning or pass one only warning and we're
1937 * not in pass 1
1939 * @param severity the severity of the warning or error
1940 * @return true if we should abort error/warning printing
1942 static bool is_suppressed_warning(int severity)
1944 /* Not a warning at all */
1945 if ((severity & ERR_MASK) != ERR_WARNING)
1946 return false;
1948 /* Might be a warning but suppresed explicitly */
1949 if (severity & ERR_WARN_MASK)
1950 return !warning_on[WARN_IDX(severity)];
1951 else
1952 return false;
1955 static bool skip_this_pass(int severity)
1957 /* See if it's a pass-specific warning which should be skipped. */
1959 if ((severity & ERR_MASK) > ERR_WARNING)
1960 return false;
1963 * passn is 1 on the very first pass only.
1964 * pass0 is 2 on the code-generation (final) pass only.
1965 * These are the passes we care about in this case.
1967 return (((severity & ERR_PASS1) && passn != 1) ||
1968 ((severity & ERR_PASS2) && pass0 != 2));
1972 * common error reporting
1973 * This is the common back end of the error reporting schemes currently
1974 * implemented. It prints the nature of the warning and then the
1975 * specific error message to error_file and may or may not return. It
1976 * doesn't return if the error severity is a "panic" or "debug" type.
1978 * @param severity the severity of the warning or error
1979 * @param fmt the printf style format string
1981 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1983 char msg[1024];
1984 const char *pfx;
1986 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1987 case ERR_WARNING:
1988 pfx = "warning: ";
1989 break;
1990 case ERR_NONFATAL:
1991 pfx = "error: ";
1992 break;
1993 case ERR_FATAL:
1994 pfx = "fatal: ";
1995 break;
1996 case ERR_PANIC:
1997 pfx = "panic: ";
1998 break;
1999 case ERR_DEBUG:
2000 pfx = "debug: ";
2001 break;
2002 default:
2003 pfx = "";
2004 break;
2007 vsnprintf(msg, sizeof msg - 64, fmt, args);
2008 if ((severity & (ERR_WARN_MASK|ERR_PP_LISTMACRO)) == ERR_WARN_MASK) {
2009 char *p = strchr(msg, '\0');
2010 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
2013 if (!skip_this_pass(severity))
2014 fprintf(error_file, "%s%s\n", pfx, msg);
2016 /* Are we recursing from error_list_macros? */
2017 if (severity & ERR_PP_LISTMACRO)
2018 return;
2021 * Don't suppress this with skip_this_pass(), or we don't get
2022 * pass1 or preprocessor warnings in the list file
2024 lfmt->error(severity, pfx, msg);
2026 if (severity & ERR_USAGE)
2027 want_usage = true;
2029 preproc->error_list_macros(severity);
2031 switch (severity & ERR_MASK) {
2032 case ERR_DEBUG:
2033 /* no further action, by definition */
2034 break;
2035 case ERR_WARNING:
2036 /* Treat warnings as errors */
2037 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
2038 terminate_after_phase = true;
2039 break;
2040 case ERR_NONFATAL:
2041 terminate_after_phase = true;
2042 break;
2043 case ERR_FATAL:
2044 if (ofile) {
2045 fclose(ofile);
2046 remove(outname);
2047 ofile = NULL;
2049 if (want_usage)
2050 usage();
2051 exit(1); /* instantly die */
2052 break; /* placate silly compilers */
2053 case ERR_PANIC:
2054 fflush(NULL);
2055 /* abort(); */ /* halt, catch fire, and dump core */
2056 if (ofile) {
2057 fclose(ofile);
2058 remove(outname);
2059 ofile = NULL;
2061 exit(3);
2062 break;
2066 static void usage(void)
2068 fputs("type `nasm -h' for help\n", error_file);
2071 static iflag_t get_cpu(char *value)
2073 iflag_t r;
2075 iflag_clear_all(&r);
2077 if (!strcmp(value, "8086"))
2078 iflag_set(&r, IF_8086);
2079 else if (!strcmp(value, "186"))
2080 iflag_set(&r, IF_186);
2081 else if (!strcmp(value, "286"))
2082 iflag_set(&r, IF_286);
2083 else if (!strcmp(value, "386"))
2084 iflag_set(&r, IF_386);
2085 else if (!strcmp(value, "486"))
2086 iflag_set(&r, IF_486);
2087 else if (!strcmp(value, "586") ||
2088 !nasm_stricmp(value, "pentium"))
2089 iflag_set(&r, IF_PENT);
2090 else if (!strcmp(value, "686") ||
2091 !nasm_stricmp(value, "ppro") ||
2092 !nasm_stricmp(value, "pentiumpro") ||
2093 !nasm_stricmp(value, "p2"))
2094 iflag_set(&r, IF_P6);
2095 else if (!nasm_stricmp(value, "p3") ||
2096 !nasm_stricmp(value, "katmai"))
2097 iflag_set(&r, IF_KATMAI);
2098 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2099 !nasm_stricmp(value, "willamette"))
2100 iflag_set(&r, IF_WILLAMETTE);
2101 else if (!nasm_stricmp(value, "prescott"))
2102 iflag_set(&r, IF_PRESCOTT);
2103 else if (!nasm_stricmp(value, "x64") ||
2104 !nasm_stricmp(value, "x86-64"))
2105 iflag_set(&r, IF_X86_64);
2106 else if (!nasm_stricmp(value, "ia64") ||
2107 !nasm_stricmp(value, "ia-64") ||
2108 !nasm_stricmp(value, "itanium")||
2109 !nasm_stricmp(value, "itanic") ||
2110 !nasm_stricmp(value, "merced"))
2111 iflag_set(&r, IF_IA64);
2112 else {
2113 iflag_set(&r, IF_PLEVEL);
2114 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2115 "unknown 'cpu' type");
2117 return r;
2120 static int get_bits(char *value)
2122 int i;
2124 if ((i = atoi(value)) == 16)
2125 return i; /* set for a 16-bit segment */
2126 else if (i == 32) {
2127 if (iflag_ffs(&cpu) < IF_386) {
2128 nasm_error(ERR_NONFATAL,
2129 "cannot specify 32-bit segment on processor below a 386");
2130 i = 16;
2132 } else if (i == 64) {
2133 if (iflag_ffs(&cpu) < IF_X86_64) {
2134 nasm_error(ERR_NONFATAL,
2135 "cannot specify 64-bit segment on processor below an x86-64");
2136 i = 16;
2138 } else {
2139 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2140 "`%s' is not a valid segment size; must be 16, 32 or 64",
2141 value);
2142 i = 16;
2144 return i;