Revert "nasmlib/file.c: Windows _chsize_s() *returns* errno"
[nasm.git] / nasm.c
blobccb4f7cd751ed70e908c5426a233f6ee537e3457
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 "output/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},
176 static bool want_usage;
177 static bool terminate_after_phase;
178 bool user_nolist = false;
180 static char *quote_for_make(const char *str);
182 static int64_t get_curr_offs(void)
184 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
187 static void set_curr_offs(int64_t l_off)
189 if (in_abs_seg)
190 abs_offset = l_off;
191 else
192 offsets = raa_write(offsets, location.segment, l_off);
195 static void nasm_fputs(const char *line, FILE * outfile)
197 if (outfile) {
198 fputs(line, outfile);
199 putc('\n', outfile);
200 } else
201 puts(line);
204 /* Convert a struct tm to a POSIX-style time constant */
205 static int64_t make_posix_time(struct tm *tm)
207 int64_t t;
208 int64_t y = tm->tm_year;
210 /* See IEEE 1003.1:2004, section 4.14 */
212 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
213 t += tm->tm_yday;
214 t *= 24;
215 t += tm->tm_hour;
216 t *= 60;
217 t += tm->tm_min;
218 t *= 60;
219 t += tm->tm_sec;
221 return t;
224 static void define_macros_early(void)
226 char temp[128];
227 struct tm lt, *lt_p, gm, *gm_p;
228 int64_t posix_time;
230 lt_p = localtime(&official_compile_time);
231 if (lt_p) {
232 lt = *lt_p;
234 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
235 preproc->pre_define(temp);
236 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
237 preproc->pre_define(temp);
238 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
239 preproc->pre_define(temp);
240 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
241 preproc->pre_define(temp);
244 gm_p = gmtime(&official_compile_time);
245 if (gm_p) {
246 gm = *gm_p;
248 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
249 preproc->pre_define(temp);
250 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
251 preproc->pre_define(temp);
252 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
253 preproc->pre_define(temp);
254 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
255 preproc->pre_define(temp);
258 if (gm_p)
259 posix_time = make_posix_time(&gm);
260 else if (lt_p)
261 posix_time = make_posix_time(&lt);
262 else
263 posix_time = 0;
265 if (posix_time) {
266 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
267 preproc->pre_define(temp);
271 static void define_macros_late(void)
273 char temp[128];
276 * In case if output format is defined by alias
277 * we have to put shortname of the alias itself here
278 * otherwise ABI backward compatibility gets broken.
280 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
281 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
282 preproc->pre_define(temp);
285 static void emit_dependencies(StrList *list)
287 FILE *deps;
288 int linepos, len;
289 StrList *l, *nl;
291 if (depend_file && strcmp(depend_file, "-")) {
292 deps = fopen(depend_file, "w");
293 if (!deps) {
294 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
295 "unable to write dependency file `%s'", depend_file);
296 return;
298 } else {
299 deps = stdout;
302 linepos = fprintf(deps, "%s:", depend_target);
303 list_for_each(l, list) {
304 char *file = quote_for_make(l->str);
305 len = strlen(file);
306 if (linepos + len > 62 && linepos > 1) {
307 fprintf(deps, " \\\n ");
308 linepos = 1;
310 fprintf(deps, " %s", file);
311 linepos += len+1;
312 nasm_free(file);
314 fprintf(deps, "\n\n");
316 list_for_each_safe(l, nl, list) {
317 if (depend_emit_phony)
318 fprintf(deps, "%s:\n\n", l->str);
319 nasm_free(l);
322 if (deps != stdout)
323 fclose(deps);
326 int main(int argc, char **argv)
328 StrList *depend_list = NULL, **depend_ptr;
330 time(&official_compile_time);
332 iflag_set(&cpu, IF_PLEVEL);
333 iflag_set(&cmd_cpu, IF_PLEVEL);
335 pass0 = 0;
336 want_usage = terminate_after_phase = false;
337 nasm_set_verror(nasm_verror_gnu);
339 error_file = stderr;
341 tolower_init();
343 offsets = raa_init();
344 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
346 preproc = &nasmpp;
347 operating_mode = OP_NORMAL;
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 (!using_debug_info) {
362 /* No debug info, redirect to the null backend (empty stubs) */
363 dfmt = &null_debug_form;
364 } else if (!debug_format) {
365 /* Default debug format for this backend */
366 dfmt = ofmt->default_dfmt;
367 } else {
368 dfmt = dfmt_find(ofmt, debug_format);
369 if (!dfmt) {
370 nasm_fatal(ERR_NOFILE | ERR_USAGE,
371 "unrecognized debug format `%s' for"
372 " output format `%s'",
373 debug_format, ofmt->shortname);
377 if (ofmt->stdmac)
378 preproc->extra_stdmac(ofmt->stdmac);
380 /* define some macros dependent of command-line */
381 define_macros_late();
383 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
384 if (!depend_target)
385 depend_target = quote_for_make(outname);
387 if (operating_mode & OP_DEPEND) {
388 char *line;
390 if (depend_missing_ok)
391 preproc->include_path(NULL); /* "assume generated" */
393 preproc->reset(inname, 0, depend_ptr);
394 if (outname[0] == '\0')
395 ofmt->filename(inname, outname);
396 ofile = NULL;
397 while ((line = preproc->getline()))
398 nasm_free(line);
399 preproc->cleanup(0);
400 } else if (operating_mode & OP_PREPROCESS) {
401 char *line;
402 char *file_name = NULL;
403 int32_t prior_linnum = 0;
404 int lineinc = 0;
406 if (*outname) {
407 ofile = fopen(outname, "w");
408 if (!ofile)
409 nasm_fatal(ERR_NOFILE,
410 "unable to open output file `%s'",
411 outname);
412 } else
413 ofile = NULL;
415 location.known = false;
417 /* pass = 1; */
418 preproc->reset(inname, 3, depend_ptr);
419 memcpy(warning_on, warning_on_global,
420 (ERR_WARN_MAX+1) * sizeof(bool));
422 while ((line = preproc->getline())) {
424 * We generate %line directives if needed for later programs
426 int32_t linnum = prior_linnum += lineinc;
427 int altline = src_get(&linnum, &file_name);
428 if (altline) {
429 if (altline == 1 && lineinc == 1)
430 nasm_fputs("", ofile);
431 else {
432 lineinc = (altline != -1 || lineinc != 1);
433 fprintf(ofile ? ofile : stdout,
434 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
435 file_name);
437 prior_linnum = linnum;
439 nasm_fputs(line, ofile);
440 nasm_free(line);
442 nasm_free(file_name);
443 preproc->cleanup(0);
444 if (ofile)
445 fclose(ofile);
446 if (ofile && terminate_after_phase)
447 remove(outname);
448 ofile = NULL;
451 if (operating_mode & OP_NORMAL) {
453 * We must call ofmt->filename _anyway_, even if the user
454 * has specified their own output file, because some
455 * formats (eg OBJ and COFF) use ofmt->filename to find out
456 * the name of the input file and then put that inside the
457 * file.
459 ofmt->filename(inname, outname);
461 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
462 if (!ofile)
463 nasm_fatal(ERR_NOFILE,
464 "unable to open output file `%s'", outname);
467 * We must call init_labels() before ofmt->init() since
468 * some object formats will want to define labels in their
469 * init routines. (eg OS/2 defines the FLAT group)
471 init_labels();
473 ofmt->init();
474 dfmt->init();
476 assemble_file(inname, depend_ptr);
478 if (!terminate_after_phase) {
479 ofmt->cleanup();
480 cleanup_labels();
481 fflush(ofile);
482 if (ferror(ofile))
483 nasm_error(ERR_NONFATAL|ERR_NOFILE,
484 "write error on output file `%s'", outname);
487 if (ofile) {
488 fclose(ofile);
489 if (terminate_after_phase)
490 remove(outname);
491 ofile = NULL;
495 if (depend_list && !terminate_after_phase)
496 emit_dependencies(depend_list);
498 if (want_usage)
499 usage();
501 raa_free(offsets);
502 saa_free(forwrefs);
503 eval_cleanup();
504 stdscan_cleanup();
506 return terminate_after_phase;
510 * Get a parameter for a command line option.
511 * First arg must be in the form of e.g. -f...
513 static char *get_param(char *p, char *q, bool *advance)
515 *advance = false;
516 if (p[2]) /* the parameter's in the option */
517 return nasm_skip_spaces(p + 2);
518 if (q && q[0]) {
519 *advance = true;
520 return q;
522 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
523 "option `-%c' requires an argument", p[1]);
524 return NULL;
528 * Copy a filename
530 static void copy_filename(char *dst, const char *src)
532 size_t len = strlen(src);
534 if (len >= (size_t)FILENAME_MAX) {
535 nasm_fatal(ERR_NOFILE, "file name too long");
536 return;
538 strncpy(dst, src, FILENAME_MAX);
542 * Convert a string to Make-safe form
544 static char *quote_for_make(const char *str)
546 const char *p;
547 char *os, *q;
549 size_t n = 1; /* Terminating zero */
550 size_t nbs = 0;
552 if (!str)
553 return NULL;
555 for (p = str; *p; p++) {
556 switch (*p) {
557 case ' ':
558 case '\t':
559 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
560 n += nbs + 2;
561 nbs = 0;
562 break;
563 case '$':
564 case '#':
565 nbs = 0;
566 n += 2;
567 break;
568 case '\\':
569 nbs++;
570 n++;
571 break;
572 default:
573 nbs = 0;
574 n++;
575 break;
579 /* Convert N backslashes at the end of filename to 2N backslashes */
580 if (nbs)
581 n += nbs;
583 os = q = nasm_malloc(n);
585 nbs = 0;
586 for (p = str; *p; p++) {
587 switch (*p) {
588 case ' ':
589 case '\t':
590 while (nbs--)
591 *q++ = '\\';
592 *q++ = '\\';
593 *q++ = *p;
594 break;
595 case '$':
596 *q++ = *p;
597 *q++ = *p;
598 nbs = 0;
599 break;
600 case '#':
601 *q++ = '\\';
602 *q++ = *p;
603 nbs = 0;
604 break;
605 case '\\':
606 *q++ = *p;
607 nbs++;
608 break;
609 default:
610 *q++ = *p;
611 nbs = 0;
612 break;
615 while (nbs--)
616 *q++ = '\\';
618 *q = '\0';
620 return os;
623 struct textargs {
624 const char *label;
625 int value;
628 enum text_options {
629 OPT_PREFIX,
630 OPT_POSTFIX
632 static const struct textargs textopts[] = {
633 {"prefix", OPT_PREFIX},
634 {"postfix", OPT_POSTFIX},
635 {NULL, 0}
638 static void show_version(void)
640 printf("NASM version %s compiled on %s%s\n",
641 nasm_version, nasm_date, nasm_compile_options);
642 exit(0);
645 static bool stopoptions = false;
646 static bool process_arg(char *p, char *q)
648 char *param;
649 int i;
650 bool advance = false;
651 bool do_warn;
653 if (!p || !p[0])
654 return false;
656 if (p[0] == '-' && !stopoptions) {
657 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
658 /* These parameters take values */
659 if (!(param = get_param(p, q, &advance)))
660 return advance;
663 switch (p[1]) {
664 case 's':
665 error_file = stdout;
666 break;
668 case 'o': /* output file */
669 copy_filename(outname, param);
670 break;
672 case 'f': /* output format */
673 ofmt = ofmt_find(param, &ofmt_alias);
674 if (!ofmt) {
675 nasm_fatal(ERR_NOFILE | ERR_USAGE,
676 "unrecognised output format `%s' - "
677 "use -hf for a list", param);
679 break;
681 case 'O': /* Optimization level */
683 int opt;
685 if (!*param) {
686 /* Naked -O == -Ox */
687 optimizing = MAX_OPTIMIZE;
688 } else {
689 while (*param) {
690 switch (*param) {
691 case '0': case '1': case '2': case '3': case '4':
692 case '5': case '6': case '7': case '8': case '9':
693 opt = strtoul(param, &param, 10);
695 /* -O0 -> optimizing == -1, 0.98 behaviour */
696 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
697 if (opt < 2)
698 optimizing = opt - 1;
699 else
700 optimizing = opt;
701 break;
703 case 'v':
704 case '+':
705 param++;
706 opt_verbose_info = true;
707 break;
709 case 'x':
710 param++;
711 optimizing = MAX_OPTIMIZE;
712 break;
714 default:
715 nasm_fatal(0,
716 "unknown optimization option -O%c\n",
717 *param);
718 break;
721 if (optimizing > MAX_OPTIMIZE)
722 optimizing = MAX_OPTIMIZE;
724 break;
727 case 'p': /* pre-include */
728 case 'P':
729 preproc->pre_include(param);
730 break;
732 case 'd': /* pre-define */
733 case 'D':
734 preproc->pre_define(param);
735 break;
737 case 'u': /* un-define */
738 case 'U':
739 preproc->pre_undefine(param);
740 break;
742 case 'i': /* include search path */
743 case 'I':
744 preproc->include_path(param);
745 break;
747 case 'l': /* listing file */
748 copy_filename(listname, param);
749 break;
751 case 'Z': /* error messages file */
752 copy_filename(errname, param);
753 break;
755 case 'F': /* specify debug format */
756 using_debug_info = true;
757 debug_format = param;
758 break;
760 case 'X': /* specify error reporting format */
761 if (nasm_stricmp("vc", param) == 0)
762 nasm_set_verror(nasm_verror_vc);
763 else if (nasm_stricmp("gnu", param) == 0)
764 nasm_set_verror(nasm_verror_gnu);
765 else
766 nasm_fatal(ERR_NOFILE | ERR_USAGE,
767 "unrecognized error reporting format `%s'",
768 param);
769 break;
771 case 'g':
772 using_debug_info = true;
773 if (p[2])
774 debug_format = nasm_skip_spaces(p + 2);
775 break;
777 case 'h':
778 printf
779 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
780 "[-l listfile]\n"
781 " [options...] [--] filename\n"
782 " or nasm -v (or --v) for version info\n\n"
783 " -t assemble in SciTech TASM compatible mode\n");
784 printf
785 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
786 " -a don't preprocess (assemble only)\n"
787 " -M generate Makefile dependencies on stdout\n"
788 " -MG d:o, missing files assumed generated\n"
789 " -MF <file> set Makefile dependency file\n"
790 " -MD <file> assemble and generate dependencies\n"
791 " -MT <file> dependency target name\n"
792 " -MQ <file> dependency target name (quoted)\n"
793 " -MP emit phony target\n\n"
794 " -Z<file> redirect error messages to file\n"
795 " -s redirect error messages to stdout\n\n"
796 " -g generate debugging information\n\n"
797 " -F format select a debugging format\n\n"
798 " -gformat same as -g -F format\n\n"
799 " -o outfile write output to an outfile\n\n"
800 " -f format select an output format\n\n"
801 " -l listfile write listing to a listfile\n\n"
802 " -I<path> adds a pathname to the include file path\n");
803 printf
804 (" -O<digit> optimize branch offsets\n"
805 " -O0: No optimization\n"
806 " -O1: Minimal optimization\n"
807 " -Ox: Multipass optimization (default)\n\n"
808 " -P<file> pre-includes a file\n"
809 " -D<macro>[=<value>] pre-defines a macro\n"
810 " -U<macro> undefines a macro\n"
811 " -X<format> specifies error reporting format (gnu or vc)\n"
812 " -w+foo enables warning foo (equiv. -Wfoo)\n"
813 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
814 " -h show invocation summary and exit\n\n"
815 "--prefix,--postfix\n"
816 " this options prepend or append the given argument to all\n"
817 " extern and global variables\n"
818 "Warnings:\n");
819 for (i = 0; i <= ERR_WARN_MAX; i++)
820 printf(" %-23s %s (default %s)\n",
821 warnings[i].name, warnings[i].help,
822 warnings[i].enabled ? "on" : "off");
823 printf
824 ("\nresponse files should contain command line parameters"
825 ", one per line.\n");
826 if (p[2] == 'f') {
827 printf("\nvalid output formats for -f are"
828 " (`*' denotes default):\n");
829 ofmt_list(ofmt, stdout);
830 } else {
831 printf("\nFor a list of valid output formats, use -hf.\n");
832 printf("For a list of debug formats, use -f <form> -y.\n");
834 exit(0); /* never need usage message here */
835 break;
837 case 'y':
838 printf("\nvalid debug formats for '%s' output format are"
839 " ('*' denotes default):\n", ofmt->shortname);
840 dfmt_list(ofmt, stdout);
841 exit(0);
842 break;
844 case 't':
845 tasm_compatible_mode = true;
846 break;
848 case 'v':
849 show_version();
850 break;
852 case 'e': /* preprocess only */
853 case 'E':
854 operating_mode = OP_PREPROCESS;
855 break;
857 case 'a': /* assemble only - don't preprocess */
858 preproc = &preproc_nop;
859 break;
861 case 'W':
862 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
863 do_warn = false;
864 param += 3;
865 } else {
866 do_warn = true;
868 goto set_warning;
870 case 'w':
871 if (param[0] != '+' && param[0] != '-') {
872 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
873 "invalid option to `-w'");
874 break;
876 do_warn = (param[0] == '+');
877 param++;
879 set_warning:
880 for (i = 0; i <= ERR_WARN_MAX; i++) {
881 if (!nasm_stricmp(param, warnings[i].name))
882 break;
884 if (i <= ERR_WARN_MAX) {
885 warning_on_global[i] = do_warn;
886 } else if (!nasm_stricmp(param, "all")) {
887 for (i = 1; i <= ERR_WARN_MAX; i++)
888 warning_on_global[i] = do_warn;
889 } else if (!nasm_stricmp(param, "none")) {
890 for (i = 1; i <= ERR_WARN_MAX; i++)
891 warning_on_global[i] = !do_warn;
892 } else {
893 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
894 "invalid warning `%s'", param);
896 break;
898 case 'M':
899 switch (p[2]) {
900 case 0:
901 operating_mode = OP_DEPEND;
902 break;
903 case 'G':
904 operating_mode = OP_DEPEND;
905 depend_missing_ok = true;
906 break;
907 case 'P':
908 depend_emit_phony = true;
909 break;
910 case 'D':
911 operating_mode = OP_NORMAL;
912 depend_file = q;
913 advance = true;
914 break;
915 case 'F':
916 depend_file = q;
917 advance = true;
918 break;
919 case 'T':
920 depend_target = q;
921 advance = true;
922 break;
923 case 'Q':
924 depend_target = quote_for_make(q);
925 advance = true;
926 break;
927 default:
928 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
929 "unknown dependency option `-M%c'", p[2]);
930 break;
932 if (advance && (!q || !q[0])) {
933 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
934 "option `-M%c' requires a parameter", p[2]);
935 break;
937 break;
939 case '-':
941 int s;
943 if (p[2] == 0) { /* -- => stop processing options */
944 stopoptions = 1;
945 break;
948 if (!nasm_stricmp(p, "--v"))
949 show_version();
951 for (s = 0; textopts[s].label; s++) {
952 if (!nasm_stricmp(p + 2, textopts[s].label)) {
953 break;
957 switch (s) {
959 case OPT_PREFIX:
960 case OPT_POSTFIX:
962 if (!q) {
963 nasm_error(ERR_NONFATAL | ERR_NOFILE |
964 ERR_USAGE,
965 "option `--%s' requires an argument",
966 p + 2);
967 break;
968 } else {
969 advance = 1, param = q;
972 switch (s) {
973 case OPT_PREFIX:
974 strlcpy(lprefix, param, PREFIX_MAX);
975 break;
976 case OPT_POSTFIX:
977 strlcpy(lpostfix, param, POSTFIX_MAX);
978 break;
979 default:
980 nasm_panic(ERR_NOFILE,
981 "internal error");
982 break;
984 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_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_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_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1215 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1216 for (passn = 1; pass0 <= 2; passn++) {
1217 int pass1, pass2;
1218 ldfunc def_label;
1220 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1221 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1222 /* pass0 0, 0, 0, ..., 1, 2 */
1224 def_label = passn > 1 ? redefine_label : define_label;
1226 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1227 cpu = cmd_cpu;
1228 if (pass0 == 2) {
1229 lfmt->init(listname);
1231 in_abs_seg = false;
1232 global_offset_changed = 0; /* set by redefine_label */
1233 location.segment = ofmt->section(NULL, pass2, &sb);
1234 globalbits = sb;
1235 if (passn > 1) {
1236 saa_rewind(forwrefs);
1237 forwref = saa_rstruct(forwrefs);
1238 raa_free(offsets);
1239 offsets = raa_init();
1241 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1242 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1244 globallineno = 0;
1245 if (passn == 1)
1246 location.known = true;
1247 location.offset = offs = get_curr_offs();
1249 while ((line = preproc->getline())) {
1250 enum directives d;
1251 globallineno++;
1254 * Here we parse our directives; this is not handled by the
1255 * 'real' parser. This really should be a separate function.
1257 directive = line;
1258 d = getkw(&directive, &value);
1259 if (d) {
1260 int err = 0;
1262 switch (d) {
1263 case D_SEGMENT: /* [SEGMENT n] */
1264 case D_SECTION:
1265 seg = ofmt->section(value, pass2, &sb);
1266 if (seg == NO_SEG) {
1267 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1268 "segment name `%s' not recognized",
1269 value);
1270 } else {
1271 in_abs_seg = false;
1272 location.segment = seg;
1274 break;
1275 case D_SECTALIGN: /* [SECTALIGN n] */
1276 if (*value) {
1277 stdscan_reset();
1278 stdscan_set(value);
1279 tokval.t_type = TOKEN_INVALID;
1280 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1281 if (e) {
1282 unsigned int align = (unsigned int)e->value;
1283 if ((uint64_t)e->value > 0x7fffffff) {
1285 * FIXME: Please make some sane message here
1286 * ofmt should have some 'check' method which
1287 * would report segment alignment bounds.
1289 nasm_fatal(0,
1290 "incorrect segment alignment `%s'", value);
1291 } else if (!is_power2(align)) {
1292 nasm_error(ERR_NONFATAL,
1293 "segment alignment `%s' is not power of two",
1294 value);
1297 /* callee should be able to handle all details */
1298 if (location.segment != NO_SEG)
1299 ofmt->sectalign(location.segment, align);
1302 break;
1303 case D_EXTERN: /* [EXTERN label:special] */
1304 if (*value == '$')
1305 value++; /* skip initial $ if present */
1306 if (pass0 == 2) {
1307 q = value;
1308 while (*q && *q != ':')
1309 q++;
1310 if (*q == ':') {
1311 *q++ = '\0';
1312 ofmt->symdef(value, 0L, 0L, 3, q);
1314 } else if (passn == 1) {
1315 q = value;
1316 validid = true;
1317 if (!isidstart(*q))
1318 validid = false;
1319 while (*q && *q != ':') {
1320 if (!isidchar(*q))
1321 validid = false;
1322 q++;
1324 if (!validid) {
1325 nasm_error(ERR_NONFATAL,
1326 "identifier expected after EXTERN");
1327 break;
1329 if (*q == ':') {
1330 *q++ = '\0';
1331 special = q;
1332 } else
1333 special = NULL;
1334 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1335 int temp = pass0;
1336 pass0 = 1; /* fake pass 1 in labels.c */
1337 declare_as_global(value, special);
1338 define_label(value, seg_alloc(), 0L, NULL,
1339 false, true);
1340 pass0 = temp;
1342 } /* else pass0 == 1 */
1343 break;
1344 case D_BITS: /* [BITS bits] */
1345 globalbits = sb = get_bits(value);
1346 break;
1347 case D_GLOBAL: /* [GLOBAL symbol:special] */
1348 if (*value == '$')
1349 value++; /* skip initial $ if present */
1350 if (pass0 == 2) { /* pass 2 */
1351 q = value;
1352 while (*q && *q != ':')
1353 q++;
1354 if (*q == ':') {
1355 *q++ = '\0';
1356 ofmt->symdef(value, 0L, 0L, 3, q);
1358 } else if (pass2 == 1) { /* pass == 1 */
1359 q = value;
1360 validid = true;
1361 if (!isidstart(*q))
1362 validid = false;
1363 while (*q && *q != ':') {
1364 if (!isidchar(*q))
1365 validid = false;
1366 q++;
1368 if (!validid) {
1369 nasm_error(ERR_NONFATAL,
1370 "identifier expected after GLOBAL");
1371 break;
1373 if (*q == ':') {
1374 *q++ = '\0';
1375 special = q;
1376 } else
1377 special = NULL;
1378 declare_as_global(value, special);
1379 } /* pass == 1 */
1380 break;
1381 case D_COMMON: /* [COMMON symbol size:special] */
1383 int64_t size;
1385 if (*value == '$')
1386 value++; /* skip initial $ if present */
1387 p = value;
1388 validid = true;
1389 if (!isidstart(*p))
1390 validid = false;
1391 while (*p && !nasm_isspace(*p)) {
1392 if (!isidchar(*p))
1393 validid = false;
1394 p++;
1396 if (!validid) {
1397 nasm_error(ERR_NONFATAL,
1398 "identifier expected after COMMON");
1399 break;
1401 if (*p) {
1402 p = nasm_zap_spaces_fwd(p);
1403 q = p;
1404 while (*q && *q != ':')
1405 q++;
1406 if (*q == ':') {
1407 *q++ = '\0';
1408 special = q;
1409 } else {
1410 special = NULL;
1412 size = readnum(p, &rn_error);
1413 if (rn_error) {
1414 nasm_error(ERR_NONFATAL,
1415 "invalid size specified"
1416 " in COMMON declaration");
1417 break;
1419 } else {
1420 nasm_error(ERR_NONFATAL,
1421 "no size specified in"
1422 " COMMON declaration");
1423 break;
1426 if (pass0 < 2) {
1427 define_common(value, seg_alloc(), size, special);
1428 } else if (pass0 == 2) {
1429 if (special)
1430 ofmt->symdef(value, 0L, 0L, 3, special);
1432 break;
1434 case D_ABSOLUTE: /* [ABSOLUTE address] */
1435 stdscan_reset();
1436 stdscan_set(value);
1437 tokval.t_type = TOKEN_INVALID;
1438 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1439 if (e) {
1440 if (!is_reloc(e))
1441 nasm_error(pass0 ==
1442 1 ? ERR_NONFATAL : ERR_PANIC,
1443 "cannot use non-relocatable expression as "
1444 "ABSOLUTE address");
1445 else {
1446 abs_seg = reloc_seg(e);
1447 abs_offset = reloc_value(e);
1449 } else if (passn == 1)
1450 abs_offset = 0x100; /* don't go near zero in case of / */
1451 else
1452 nasm_panic(0, "invalid ABSOLUTE address "
1453 "in pass two");
1454 in_abs_seg = true;
1455 location.segment = NO_SEG;
1456 break;
1457 case D_DEBUG: /* [DEBUG] */
1459 char debugid[128];
1460 bool badid, overlong;
1462 p = value;
1463 q = debugid;
1464 badid = overlong = false;
1465 if (!isidstart(*p)) {
1466 badid = true;
1467 } else {
1468 while (*p && !nasm_isspace(*p)) {
1469 if (q >= debugid + sizeof debugid - 1) {
1470 overlong = true;
1471 break;
1473 if (!isidchar(*p))
1474 badid = true;
1475 *q++ = *p++;
1477 *q = 0;
1479 if (badid) {
1480 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1481 "identifier expected after DEBUG");
1482 break;
1484 if (overlong) {
1485 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1486 "DEBUG identifier too long");
1487 break;
1489 p = nasm_skip_spaces(p);
1490 if (pass0 == 2)
1491 dfmt->debug_directive(debugid, p);
1492 break;
1494 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1495 value = nasm_skip_spaces(value);
1496 switch(*value) {
1497 case '-': validid = 0; value++; break;
1498 case '+': validid = 1; value++; break;
1499 case '*': validid = 2; value++; break;
1500 default: validid = 1; break;
1503 for (i = 1; i <= ERR_WARN_MAX; i++)
1504 if (!nasm_stricmp(value, warnings[i].name))
1505 break;
1506 if (i <= ERR_WARN_MAX) {
1507 switch(validid) {
1508 case 0:
1509 warning_on[i] = false;
1510 break;
1511 case 1:
1512 warning_on[i] = true;
1513 break;
1514 case 2:
1515 warning_on[i] = warning_on_global[i];
1516 break;
1518 } else
1519 nasm_error(ERR_NONFATAL,
1520 "invalid warning id in WARNING directive");
1521 break;
1522 case D_CPU: /* [CPU] */
1523 cpu = get_cpu(value);
1524 break;
1525 case D_LIST: /* [LIST {+|-}] */
1526 value = nasm_skip_spaces(value);
1527 if (*value == '+') {
1528 user_nolist = 0;
1529 } else {
1530 if (*value == '-') {
1531 user_nolist = 1;
1532 } else {
1533 err = 1;
1536 break;
1537 case D_DEFAULT: /* [DEFAULT] */
1538 stdscan_reset();
1539 stdscan_set(value);
1540 tokval.t_type = TOKEN_INVALID;
1541 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1542 switch ((int)tokval.t_integer) {
1543 case S_REL:
1544 globalrel = 1;
1545 break;
1546 case S_ABS:
1547 globalrel = 0;
1548 break;
1549 case P_BND:
1550 globalbnd = 1;
1551 break;
1552 case P_NOBND:
1553 globalbnd = 0;
1554 break;
1555 default:
1556 err = 1;
1557 break;
1559 } else {
1560 err = 1;
1562 break;
1563 case D_FLOAT:
1564 if (float_option(value)) {
1565 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1566 "unknown 'float' directive: %s",
1567 value);
1569 break;
1570 default:
1571 if (ofmt->directive(d, value, pass2))
1572 break;
1573 /* else fall through */
1574 case D_unknown:
1575 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1576 "unrecognised directive [%s]",
1577 directive);
1578 break;
1580 if (err) {
1581 nasm_error(ERR_NONFATAL,
1582 "invalid parameter to [%s] directive",
1583 directive);
1585 } else { /* it isn't a directive */
1586 parse_line(pass1, line, &output_ins, def_label);
1588 if (optimizing > 0) {
1589 if (forwref != NULL && globallineno == forwref->lineno) {
1590 output_ins.forw_ref = true;
1591 do {
1592 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1593 forwref = saa_rstruct(forwrefs);
1594 } while (forwref != NULL
1595 && forwref->lineno == globallineno);
1596 } else
1597 output_ins.forw_ref = false;
1599 if (output_ins.forw_ref) {
1600 if (passn == 1) {
1601 for (i = 0; i < output_ins.operands; i++) {
1602 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1603 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1604 fwinf->lineno = globallineno;
1605 fwinf->operand = i;
1612 /* forw_ref */
1613 if (output_ins.opcode == I_EQU) {
1614 if (pass1 == 1) {
1616 * Special `..' EQUs get processed in pass two,
1617 * except `..@' macro-processor EQUs which are done
1618 * in the normal place.
1620 if (!output_ins.label)
1621 nasm_error(ERR_NONFATAL,
1622 "EQU not preceded by label");
1624 else if (output_ins.label[0] != '.' ||
1625 output_ins.label[1] != '.' ||
1626 output_ins.label[2] == '@') {
1627 if (output_ins.operands == 1 &&
1628 (output_ins.oprs[0].type & IMMEDIATE) &&
1629 output_ins.oprs[0].wrt == NO_SEG) {
1630 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1631 def_label(output_ins.label,
1632 output_ins.oprs[0].segment,
1633 output_ins.oprs[0].offset, NULL,
1634 false, isext);
1635 } else if (output_ins.operands == 2
1636 && (output_ins.oprs[0].type & IMMEDIATE)
1637 && (output_ins.oprs[0].type & COLON)
1638 && output_ins.oprs[0].segment == NO_SEG
1639 && output_ins.oprs[0].wrt == NO_SEG
1640 && (output_ins.oprs[1].type & IMMEDIATE)
1641 && output_ins.oprs[1].segment == NO_SEG
1642 && output_ins.oprs[1].wrt == NO_SEG) {
1643 def_label(output_ins.label,
1644 output_ins.oprs[0].offset | SEG_ABS,
1645 output_ins.oprs[1].offset,
1646 NULL, false, false);
1647 } else
1648 nasm_error(ERR_NONFATAL,
1649 "bad syntax for EQU");
1651 } else {
1653 * Special `..' EQUs get processed here, except
1654 * `..@' macro processor EQUs which are done above.
1656 if (output_ins.label[0] == '.' &&
1657 output_ins.label[1] == '.' &&
1658 output_ins.label[2] != '@') {
1659 if (output_ins.operands == 1 &&
1660 (output_ins.oprs[0].type & IMMEDIATE)) {
1661 define_label(output_ins.label,
1662 output_ins.oprs[0].segment,
1663 output_ins.oprs[0].offset,
1664 NULL, false, false);
1665 } else if (output_ins.operands == 2
1666 && (output_ins.oprs[0].type & IMMEDIATE)
1667 && (output_ins.oprs[0].type & COLON)
1668 && output_ins.oprs[0].segment == NO_SEG
1669 && (output_ins.oprs[1].type & IMMEDIATE)
1670 && output_ins.oprs[1].segment == NO_SEG) {
1671 define_label(output_ins.label,
1672 output_ins.oprs[0].offset | SEG_ABS,
1673 output_ins.oprs[1].offset,
1674 NULL, false, false);
1675 } else
1676 nasm_error(ERR_NONFATAL,
1677 "bad syntax for EQU");
1680 } else { /* instruction isn't an EQU */
1682 if (pass1 == 1) {
1684 int64_t l = insn_size(location.segment, offs, sb, cpu,
1685 &output_ins);
1687 /* if (using_debug_info) && output_ins.opcode != -1) */
1688 if (using_debug_info)
1689 { /* fbk 03/25/01 */
1690 /* this is done here so we can do debug type info */
1691 int32_t typeinfo =
1692 TYS_ELEMENTS(output_ins.operands);
1693 switch (output_ins.opcode) {
1694 case I_RESB:
1695 typeinfo =
1696 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1697 break;
1698 case I_RESW:
1699 typeinfo =
1700 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1701 break;
1702 case I_RESD:
1703 typeinfo =
1704 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1705 break;
1706 case I_RESQ:
1707 typeinfo =
1708 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1709 break;
1710 case I_REST:
1711 typeinfo =
1712 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1713 break;
1714 case I_RESO:
1715 typeinfo =
1716 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1717 break;
1718 case I_RESY:
1719 typeinfo =
1720 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1721 break;
1722 case I_DB:
1723 typeinfo |= TY_BYTE;
1724 break;
1725 case I_DW:
1726 typeinfo |= TY_WORD;
1727 break;
1728 case I_DD:
1729 if (output_ins.eops_float)
1730 typeinfo |= TY_FLOAT;
1731 else
1732 typeinfo |= TY_DWORD;
1733 break;
1734 case I_DQ:
1735 typeinfo |= TY_QWORD;
1736 break;
1737 case I_DT:
1738 typeinfo |= TY_TBYTE;
1739 break;
1740 case I_DO:
1741 typeinfo |= TY_OWORD;
1742 break;
1743 case I_DY:
1744 typeinfo |= TY_YWORD;
1745 break;
1746 default:
1747 typeinfo = TY_LABEL;
1751 dfmt->debug_typevalue(typeinfo);
1753 if (l != -1) {
1754 offs += l;
1755 set_curr_offs(offs);
1758 * else l == -1 => invalid instruction, which will be
1759 * flagged as an error on pass 2
1762 } else {
1763 offs += assemble(location.segment, offs, sb, cpu,
1764 &output_ins);
1765 set_curr_offs(offs);
1768 } /* not an EQU */
1769 cleanup_insn(&output_ins);
1771 nasm_free(line);
1772 location.offset = offs = get_curr_offs();
1773 } /* end while (line = preproc->getline... */
1775 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1776 nasm_error(ERR_NONFATAL,
1777 "phase error detected at end of assembly.");
1779 if (pass1 == 1)
1780 preproc->cleanup(1);
1782 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1783 pass0++;
1784 } else if (global_offset_changed &&
1785 global_offset_changed < prev_offset_changed) {
1786 prev_offset_changed = global_offset_changed;
1787 stall_count = 0;
1788 } else {
1789 stall_count++;
1792 if (terminate_after_phase)
1793 break;
1795 if ((stall_count > 997) || (passn >= pass_max)) {
1796 /* We get here if the labels don't converge
1797 * Example: FOO equ FOO + 1
1799 nasm_error(ERR_NONFATAL,
1800 "Can't find valid values for all labels "
1801 "after %d passes, giving up.", passn);
1802 nasm_error(ERR_NONFATAL,
1803 "Possible causes: recursive EQUs, macro abuse.");
1804 break;
1808 preproc->cleanup(0);
1809 lfmt->cleanup();
1810 if (!terminate_after_phase && opt_verbose_info) {
1811 /* -On and -Ov switches */
1812 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1816 static enum directives getkw(char **directive, char **value)
1818 char *p, *q, *buf;
1820 buf = nasm_skip_spaces(*directive);
1822 /* it should be enclosed in [ ] */
1823 if (*buf != '[')
1824 return D_none;
1825 q = strchr(buf, ']');
1826 if (!q)
1827 return D_none;
1829 /* stip off the comments */
1830 p = strchr(buf, ';');
1831 if (p) {
1832 if (p < q) /* ouch! somwhere inside */
1833 return D_none;
1834 *p = '\0';
1837 /* no brace, no trailing spaces */
1838 *q = '\0';
1839 nasm_zap_spaces_rev(--q);
1841 /* directive */
1842 p = nasm_skip_spaces(++buf);
1843 q = nasm_skip_word(p);
1844 if (!q)
1845 return D_none; /* sigh... no value there */
1846 *q = '\0';
1847 *directive = p;
1849 /* and value finally */
1850 p = nasm_skip_spaces(++q);
1851 *value = p;
1853 return find_directive(*directive);
1857 * gnu style error reporting
1858 * This function prints an error message to error_file in the
1859 * style used by GNU. An example would be:
1860 * file.asm:50: error: blah blah blah
1861 * where file.asm is the name of the file, 50 is the line number on
1862 * which the error occurs (or is detected) and "error:" is one of
1863 * the possible optional diagnostics -- it can be "error" or "warning"
1864 * or something else. Finally the line terminates with the actual
1865 * error message.
1867 * @param severity the severity of the warning or error
1868 * @param fmt the printf style format string
1870 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1872 char *currentfile = NULL;
1873 int32_t lineno = 0;
1875 if (is_suppressed_warning(severity))
1876 return;
1878 if (!(severity & ERR_NOFILE))
1879 src_get(&lineno, &currentfile);
1881 if (!skip_this_pass(severity)) {
1882 if (currentfile) {
1883 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1884 nasm_free(currentfile);
1885 } else {
1886 fputs("nasm: ", error_file);
1890 nasm_verror_common(severity, fmt, ap);
1894 * MS style error reporting
1895 * This function prints an error message to error_file in the
1896 * style used by Visual C and some other Microsoft tools. An example
1897 * would be:
1898 * file.asm(50) : error: blah blah blah
1899 * where file.asm is the name of the file, 50 is the line number on
1900 * which the error occurs (or is detected) and "error:" is one of
1901 * the possible optional diagnostics -- it can be "error" or "warning"
1902 * or something else. Finally the line terminates with the actual
1903 * error message.
1905 * @param severity the severity of the warning or error
1906 * @param fmt the printf style format string
1908 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1910 char *currentfile = NULL;
1911 int32_t lineno = 0;
1913 if (is_suppressed_warning(severity))
1914 return;
1916 if (!(severity & ERR_NOFILE))
1917 src_get(&lineno, &currentfile);
1919 if (!skip_this_pass(severity)) {
1920 if (currentfile) {
1921 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1922 nasm_free(currentfile);
1923 } else {
1924 fputs("nasm: ", error_file);
1928 nasm_verror_common(severity, fmt, ap);
1932 * check for supressed warning
1933 * checks for suppressed warning or pass one only warning and we're
1934 * not in pass 1
1936 * @param severity the severity of the warning or error
1937 * @return true if we should abort error/warning printing
1939 static bool is_suppressed_warning(int severity)
1941 /* Not a warning at all */
1942 if ((severity & ERR_MASK) != ERR_WARNING)
1943 return false;
1945 /* Might be a warning but suppresed explicitly */
1946 if (severity & ERR_WARN_MASK)
1947 return !warning_on[WARN_IDX(severity)];
1948 else
1949 return false;
1952 static bool skip_this_pass(int severity)
1954 /* See if it's a pass-one only warning and we're not in pass one. */
1955 if ((severity & ERR_MASK) > ERR_WARNING)
1956 return false;
1958 if (((severity & ERR_PASS1) && pass0 != 1) ||
1959 ((severity & ERR_PASS2) && pass0 != 2))
1960 return true;
1962 return false;
1966 * common error reporting
1967 * This is the common back end of the error reporting schemes currently
1968 * implemented. It prints the nature of the warning and then the
1969 * specific error message to error_file and may or may not return. It
1970 * doesn't return if the error severity is a "panic" or "debug" type.
1972 * @param severity the severity of the warning or error
1973 * @param fmt the printf style format string
1975 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1977 char msg[1024];
1978 const char *pfx;
1980 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1981 case ERR_WARNING:
1982 pfx = "warning: ";
1983 break;
1984 case ERR_NONFATAL:
1985 pfx = "error: ";
1986 break;
1987 case ERR_FATAL:
1988 pfx = "fatal: ";
1989 break;
1990 case ERR_PANIC:
1991 pfx = "panic: ";
1992 break;
1993 case ERR_DEBUG:
1994 pfx = "debug: ";
1995 break;
1996 default:
1997 pfx = "";
1998 break;
2001 vsnprintf(msg, sizeof msg, fmt, args);
2003 if (!skip_this_pass(severity))
2004 fprintf(error_file, "%s%s\n", pfx, msg);
2007 * Don't suppress this with skip_this_pass(), or we don't get
2008 * preprocessor warnings in the list file
2010 if ((severity & ERR_MASK) >= ERR_WARNING)
2011 lfmt->error(severity, pfx, msg);
2013 if (severity & ERR_USAGE)
2014 want_usage = true;
2016 switch (severity & ERR_MASK) {
2017 case ERR_DEBUG:
2018 /* no further action, by definition */
2019 break;
2020 case ERR_WARNING:
2021 /* Treat warnings as errors */
2022 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
2023 terminate_after_phase = true;
2024 break;
2025 case ERR_NONFATAL:
2026 terminate_after_phase = true;
2027 break;
2028 case ERR_FATAL:
2029 if (ofile) {
2030 fclose(ofile);
2031 remove(outname);
2032 ofile = NULL;
2034 if (want_usage)
2035 usage();
2036 exit(1); /* instantly die */
2037 break; /* placate silly compilers */
2038 case ERR_PANIC:
2039 fflush(NULL);
2040 /* abort(); */ /* halt, catch fire, and dump core */
2041 if (ofile) {
2042 fclose(ofile);
2043 remove(outname);
2044 ofile = NULL;
2046 exit(3);
2047 break;
2051 static void usage(void)
2053 fputs("type `nasm -h' for help\n", error_file);
2056 static iflag_t get_cpu(char *value)
2058 iflag_t r;
2060 iflag_clear_all(&r);
2062 if (!strcmp(value, "8086"))
2063 iflag_set(&r, IF_8086);
2064 else if (!strcmp(value, "186"))
2065 iflag_set(&r, IF_186);
2066 else if (!strcmp(value, "286"))
2067 iflag_set(&r, IF_286);
2068 else if (!strcmp(value, "386"))
2069 iflag_set(&r, IF_386);
2070 else if (!strcmp(value, "486"))
2071 iflag_set(&r, IF_486);
2072 else if (!strcmp(value, "586") ||
2073 !nasm_stricmp(value, "pentium"))
2074 iflag_set(&r, IF_PENT);
2075 else if (!strcmp(value, "686") ||
2076 !nasm_stricmp(value, "ppro") ||
2077 !nasm_stricmp(value, "pentiumpro") ||
2078 !nasm_stricmp(value, "p2"))
2079 iflag_set(&r, IF_P6);
2080 else if (!nasm_stricmp(value, "p3") ||
2081 !nasm_stricmp(value, "katmai"))
2082 iflag_set(&r, IF_KATMAI);
2083 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2084 !nasm_stricmp(value, "willamette"))
2085 iflag_set(&r, IF_WILLAMETTE);
2086 else if (!nasm_stricmp(value, "prescott"))
2087 iflag_set(&r, IF_PRESCOTT);
2088 else if (!nasm_stricmp(value, "x64") ||
2089 !nasm_stricmp(value, "x86-64"))
2090 iflag_set(&r, IF_X86_64);
2091 else if (!nasm_stricmp(value, "ia64") ||
2092 !nasm_stricmp(value, "ia-64") ||
2093 !nasm_stricmp(value, "itanium")||
2094 !nasm_stricmp(value, "itanic") ||
2095 !nasm_stricmp(value, "merced"))
2096 iflag_set(&r, IF_IA64);
2097 else {
2098 iflag_set(&r, IF_PLEVEL);
2099 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2100 "unknown 'cpu' type");
2102 return r;
2105 static int get_bits(char *value)
2107 int i;
2109 if ((i = atoi(value)) == 16)
2110 return i; /* set for a 16-bit segment */
2111 else if (i == 32) {
2112 if (iflag_ffs(&cpu) < IF_386) {
2113 nasm_error(ERR_NONFATAL,
2114 "cannot specify 32-bit segment on processor below a 386");
2115 i = 16;
2117 } else if (i == 64) {
2118 if (iflag_ffs(&cpu) < IF_X86_64) {
2119 nasm_error(ERR_NONFATAL,
2120 "cannot specify 64-bit segment on processor below an x86-64");
2121 i = 16;
2123 } else {
2124 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2125 "`%s' is not a valid segment size; must be 16, 32 or 64",
2126 value);
2127 i = 16;
2129 return i;