Improve process_ea and introduce -OL
[nasm/sigaren-mirror.git] / nasm.c
blobf6a710a4b776e2b034bee9c009158624e374d572
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2010 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * The Netwide Assembler main program module
38 #include "compiler.h"
40 #include <stdio.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <inttypes.h>
46 #include <limits.h>
47 #include <time.h>
49 #include "nasm.h"
50 #include "nasmlib.h"
51 #include "saa.h"
52 #include "raa.h"
53 #include "float.h"
54 #include "stdscan.h"
55 #include "insns.h"
56 #include "preproc.h"
57 #include "parser.h"
58 #include "eval.h"
59 #include "assemble.h"
60 #include "labels.h"
61 #include "output/outform.h"
62 #include "listing.h"
65 * This is the maximum number of optimization passes to do. If we ever
66 * find a case where the optimizer doesn't naturally converge, we might
67 * have to drop this value so the assembler doesn't appear to just hang.
69 #define MAX_OPTIMIZE (INT_MAX >> 1)
71 struct forwrefinfo { /* info held on forward refs. */
72 int lineno;
73 int operand;
76 static int get_bits(char *value);
77 static uint32_t get_cpu(char *cpu_str);
78 static void parse_cmdline(int, char **);
79 static void assemble_file(char *, StrList **);
80 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
81 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
82 static void nasm_verror_common(int severity, const char *fmt, va_list args);
83 static bool is_suppressed_warning(int severity);
84 static void usage(void);
86 static int using_debug_info, opt_verbose_info;
87 bool tasm_compatible_mode = false;
88 int pass0, passn;
89 int maxbits = 0;
90 int globalrel = 0;
92 static time_t official_compile_time;
94 static char inname[FILENAME_MAX];
95 static char outname[FILENAME_MAX];
96 static char listname[FILENAME_MAX];
97 static char errname[FILENAME_MAX];
98 static int globallineno; /* for forward-reference tracking */
99 /* static int pass = 0; */
100 struct ofmt *ofmt = &OF_DEFAULT;
101 const struct dfmt *dfmt;
103 static FILE *error_file; /* Where to write error messages */
105 FILE *ofile = NULL;
106 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
107 static int sb, cmd_sb = 16; /* by default */
108 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
109 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
110 int64_t global_offset_changed; /* referenced in labels.c */
111 int64_t prev_offset_changed;
112 int32_t stall_count;
114 static struct location location;
115 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
116 int32_t abs_seg; /* ABSOLUTE segment basis */
117 int32_t abs_offset; /* ABSOLUTE offset */
119 static struct RAA *offsets;
121 static struct SAA *forwrefs; /* keep track of forward references */
122 static const struct forwrefinfo *forwref;
124 static Preproc *preproc;
125 enum op_type {
126 op_normal, /* Preprocess and assemble */
127 op_preprocess, /* Preprocess only */
128 op_depend, /* Generate dependencies */
130 static enum op_type operating_mode;
131 /* Dependency flags */
132 static bool depend_emit_phony = false;
133 static bool depend_missing_ok = false;
134 static const char *depend_target = NULL;
135 static const char *depend_file = NULL;
138 * Which of the suppressible warnings are suppressed. Entry zero
139 * isn't an actual warning, but it used for -w+error/-Werror.
142 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
143 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
145 static const struct warning {
146 const char *name;
147 const char *help;
148 bool enabled;
149 } warnings[ERR_WARN_MAX+1] = {
150 {"error", "treat warnings as errors", false},
151 {"macro-params", "macro calls with wrong parameter count", true},
152 {"macro-selfref", "cyclic macro references", false},
153 {"macro-defaults", "macros with more default than optional parameters", true},
154 {"orphan-labels", "labels alone on lines without trailing `:'", true},
155 {"number-overflow", "numeric constant does not fit", true},
156 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
157 {"float-overflow", "floating point overflow", true},
158 {"float-denorm", "floating point denormal", false},
159 {"float-underflow", "floating point underflow", false},
160 {"float-toolong", "too many digits in floating-point number", true},
161 {"user", "%warning directives", true},
165 * This is a null preprocessor which just copies lines from input
166 * to output. It's used when someone explicitly requests that NASM
167 * not preprocess their source file.
170 static void no_pp_reset(char *, int, ListGen *, StrList **);
171 static char *no_pp_getline(void);
172 static void no_pp_cleanup(int);
173 static Preproc no_pp = {
174 no_pp_reset,
175 no_pp_getline,
176 no_pp_cleanup
180 * get/set current offset...
182 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
183 raa_read(offsets,location.segment))
184 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
185 (void)(offsets=raa_write(offsets,location.segment,(x))))
187 static bool want_usage;
188 static bool terminate_after_phase;
189 int user_nolist = 0; /* fbk 9/2/00 */
191 static void nasm_fputs(const char *line, FILE * outfile)
193 if (outfile) {
194 fputs(line, outfile);
195 putc('\n', outfile);
196 } else
197 puts(line);
200 /* Convert a struct tm to a POSIX-style time constant */
201 static int64_t posix_mktime(struct tm *tm)
203 int64_t t;
204 int64_t y = tm->tm_year;
206 /* See IEEE 1003.1:2004, section 4.14 */
208 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
209 t += tm->tm_yday;
210 t *= 24;
211 t += tm->tm_hour;
212 t *= 60;
213 t += tm->tm_min;
214 t *= 60;
215 t += tm->tm_sec;
217 return t;
220 static void define_macros_early(void)
222 char temp[128];
223 struct tm lt, *lt_p, gm, *gm_p;
224 int64_t posix_time;
226 lt_p = localtime(&official_compile_time);
227 if (lt_p) {
228 lt = *lt_p;
230 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
231 pp_pre_define(temp);
232 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
233 pp_pre_define(temp);
234 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
235 pp_pre_define(temp);
236 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
237 pp_pre_define(temp);
240 gm_p = gmtime(&official_compile_time);
241 if (gm_p) {
242 gm = *gm_p;
244 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
245 pp_pre_define(temp);
246 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
247 pp_pre_define(temp);
248 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
249 pp_pre_define(temp);
250 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
251 pp_pre_define(temp);
254 if (gm_p)
255 posix_time = posix_mktime(&gm);
256 else if (lt_p)
257 posix_time = posix_mktime(&lt);
258 else
259 posix_time = 0;
261 if (posix_time) {
262 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
263 pp_pre_define(temp);
267 static void define_macros_late(void)
269 char temp[128];
271 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
272 ofmt->shortname);
273 pp_pre_define(temp);
276 static void emit_dependencies(StrList *list)
278 FILE *deps;
279 int linepos, len;
280 StrList *l, *nl;
282 if (depend_file && strcmp(depend_file, "-")) {
283 deps = fopen(depend_file, "w");
284 if (!deps) {
285 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
286 "unable to write dependency file `%s'", depend_file);
287 return;
289 } else {
290 deps = stdout;
293 linepos = fprintf(deps, "%s:", depend_target);
294 list_for_each(l, list) {
295 len = strlen(l->str);
296 if (linepos + len > 62) {
297 fprintf(deps, " \\\n ");
298 linepos = 1;
300 fprintf(deps, " %s", l->str);
301 linepos += len+1;
303 fprintf(deps, "\n\n");
305 list_for_each_safe(l, nl, list) {
306 if (depend_emit_phony)
307 fprintf(deps, "%s:\n\n", l->str);
308 nasm_free(l);
311 if (deps != stdout)
312 fclose(deps);
315 int main(int argc, char **argv)
317 StrList *depend_list = NULL, **depend_ptr;
319 time(&official_compile_time);
321 pass0 = 0;
322 want_usage = terminate_after_phase = false;
323 nasm_set_verror(nasm_verror_gnu);
325 error_file = stderr;
327 tolower_init();
329 nasm_init_malloc_error();
330 offsets = raa_init();
331 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
333 preproc = &nasmpp;
334 operating_mode = op_normal;
336 seg_init();
338 /* Define some macros dependent on the runtime, but not
339 on the command line. */
340 define_macros_early();
342 parse_cmdline(argc, argv);
344 if (terminate_after_phase) {
345 if (want_usage)
346 usage();
347 return 1;
350 /* If debugging info is disabled, suppress any debug calls */
351 if (!using_debug_info)
352 ofmt->current_dfmt = &null_debug_form;
354 if (ofmt->stdmac)
355 pp_extra_stdmac(ofmt->stdmac);
356 parser_global_info(&location);
357 eval_global_info(ofmt, lookup_label, &location);
359 /* define some macros dependent of command-line */
360 define_macros_late();
362 depend_ptr = (depend_file || (operating_mode == op_depend))
363 ? &depend_list : NULL;
364 if (!depend_target)
365 depend_target = outname;
367 switch (operating_mode) {
368 case op_depend:
370 char *line;
372 if (depend_missing_ok)
373 pp_include_path(NULL); /* "assume generated" */
375 preproc->reset(inname, 0, &nasmlist, depend_ptr);
376 if (outname[0] == '\0')
377 ofmt->filename(inname, outname);
378 ofile = NULL;
379 while ((line = preproc->getline()))
380 nasm_free(line);
381 preproc->cleanup(0);
383 break;
385 case op_preprocess:
387 char *line;
388 char *file_name = NULL;
389 int32_t prior_linnum = 0;
390 int lineinc = 0;
392 if (*outname) {
393 ofile = fopen(outname, "w");
394 if (!ofile)
395 nasm_error(ERR_FATAL | ERR_NOFILE,
396 "unable to open output file `%s'",
397 outname);
398 } else
399 ofile = NULL;
401 location.known = false;
403 /* pass = 1; */
404 preproc->reset(inname, 3, &nasmlist, depend_ptr);
406 while ((line = preproc->getline())) {
408 * We generate %line directives if needed for later programs
410 int32_t linnum = prior_linnum += lineinc;
411 int altline = src_get(&linnum, &file_name);
412 if (altline) {
413 if (altline == 1 && lineinc == 1)
414 nasm_fputs("", ofile);
415 else {
416 lineinc = (altline != -1 || lineinc != 1);
417 fprintf(ofile ? ofile : stdout,
418 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
419 file_name);
421 prior_linnum = linnum;
423 nasm_fputs(line, ofile);
424 nasm_free(line);
426 nasm_free(file_name);
427 preproc->cleanup(0);
428 if (ofile)
429 fclose(ofile);
430 if (ofile && terminate_after_phase)
431 remove(outname);
432 ofile = NULL;
434 break;
436 case op_normal:
439 * We must call ofmt->filename _anyway_, even if the user
440 * has specified their own output file, because some
441 * formats (eg OBJ and COFF) use ofmt->filename to find out
442 * the name of the input file and then put that inside the
443 * file.
445 ofmt->filename(inname, outname);
447 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
448 if (!ofile) {
449 nasm_error(ERR_FATAL | ERR_NOFILE,
450 "unable to open output file `%s'", outname);
454 * We must call init_labels() before ofmt->init() since
455 * some object formats will want to define labels in their
456 * init routines. (eg OS/2 defines the FLAT group)
458 init_labels();
460 ofmt->init();
461 dfmt = ofmt->current_dfmt;
462 dfmt->init();
464 assemble_file(inname, depend_ptr);
466 if (!terminate_after_phase) {
467 ofmt->cleanup(using_debug_info);
468 cleanup_labels();
469 fflush(ofile);
470 if (ferror(ofile)) {
471 nasm_error(ERR_NONFATAL|ERR_NOFILE,
472 "write error on output file `%s'", outname);
476 if (ofile) {
477 fclose(ofile);
478 if (terminate_after_phase)
479 remove(outname);
480 ofile = NULL;
483 break;
486 if (depend_list && !terminate_after_phase)
487 emit_dependencies(depend_list);
489 if (want_usage)
490 usage();
492 raa_free(offsets);
493 saa_free(forwrefs);
494 eval_cleanup();
495 stdscan_cleanup();
497 return terminate_after_phase;
501 * Get a parameter for a command line option.
502 * First arg must be in the form of e.g. -f...
504 static char *get_param(char *p, char *q, bool *advance)
506 *advance = false;
507 if (p[2]) /* the parameter's in the option */
508 return nasm_skip_spaces(p + 2);
509 if (q && q[0]) {
510 *advance = true;
511 return q;
513 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
514 "option `-%c' requires an argument", p[1]);
515 return NULL;
519 * Copy a filename
521 static void copy_filename(char *dst, const char *src)
523 size_t len = strlen(src);
525 if (len >= (size_t)FILENAME_MAX) {
526 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
527 return;
529 strncpy(dst, src, FILENAME_MAX);
533 * Convert a string to Make-safe form
535 static char *quote_for_make(const char *str)
537 const char *p;
538 char *os, *q;
540 size_t n = 1; /* Terminating zero */
541 size_t nbs = 0;
543 if (!str)
544 return NULL;
546 for (p = str; *p; p++) {
547 switch (*p) {
548 case ' ':
549 case '\t':
550 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
551 n += nbs + 2;
552 nbs = 0;
553 break;
554 case '$':
555 case '#':
556 nbs = 0;
557 n += 2;
558 break;
559 case '\\':
560 nbs++;
561 n++;
562 break;
563 default:
564 nbs = 0;
565 n++;
566 break;
570 /* Convert N backslashes at the end of filename to 2N backslashes */
571 if (nbs)
572 n += nbs;
574 os = q = nasm_malloc(n);
576 nbs = 0;
577 for (p = str; *p; p++) {
578 switch (*p) {
579 case ' ':
580 case '\t':
581 while (nbs--)
582 *q++ = '\\';
583 *q++ = '\\';
584 *q++ = *p;
585 break;
586 case '$':
587 *q++ = *p;
588 *q++ = *p;
589 nbs = 0;
590 break;
591 case '#':
592 *q++ = '\\';
593 *q++ = *p;
594 nbs = 0;
595 break;
596 case '\\':
597 *q++ = *p;
598 nbs++;
599 break;
600 default:
601 *q++ = *p;
602 nbs = 0;
603 break;
606 while (nbs--)
607 *q++ = '\\';
609 *q = '\0';
611 return os;
614 struct textargs {
615 const char *label;
616 int value;
619 #define OPT_PREFIX 0
620 #define OPT_POSTFIX 1
621 struct textargs textopts[] = {
622 {"prefix", OPT_PREFIX},
623 {"postfix", OPT_POSTFIX},
624 {NULL, 0}
627 static bool stopoptions = false;
628 static bool process_arg(char *p, char *q)
630 char *param;
631 int i;
632 bool advance = false;
633 bool do_warn;
635 if (!p || !p[0])
636 return false;
638 if (p[0] == '-' && !stopoptions) {
639 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
640 /* These parameters take values */
641 if (!(param = get_param(p, q, &advance)))
642 return advance;
645 switch (p[1]) {
646 case 's':
647 error_file = stdout;
648 break;
650 case 'o': /* output file */
651 copy_filename(outname, param);
652 break;
654 case 'f': /* output format */
655 ofmt = ofmt_find(param);
656 if (!ofmt) {
657 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
658 "unrecognised output format `%s' - "
659 "use -hf for a list", param);
661 break;
663 case 'O': /* Optimization level */
665 int opt;
667 if (!*param) {
668 /* Naked -O == -Ox */
669 optimizing = MAX_OPTIMIZE;
670 } else {
671 while (*param) {
672 switch (*param) {
673 case '0': case '1': case '2': case '3': case '4':
674 case '5': case '6': case '7': case '8': case '9':
675 opt = strtoul(param, &param, 10);
677 if (opt == 0)
678 /* no optimization */
679 optimizing = -2;
680 else if (opt == 1)
681 /* 0.98.09 behaviour */
682 optimizing = 0;
683 else
684 optimizing = opt;
685 break;
687 case 'L':
688 /* 0.98 behaviour */
689 param++;
690 optimizing = -1;
691 break;
693 case 'v':
694 case '+':
695 param++;
696 opt_verbose_info = true;
697 break;
699 case 'x':
700 param++;
701 optimizing = MAX_OPTIMIZE;
702 break;
704 default:
705 nasm_error(ERR_FATAL,
706 "unknown optimization option -O%c\n",
707 *param);
708 break;
711 if (optimizing > MAX_OPTIMIZE)
712 optimizing = MAX_OPTIMIZE;
714 break;
717 case 'p': /* pre-include */
718 case 'P':
719 pp_pre_include(param);
720 break;
722 case 'd': /* pre-define */
723 case 'D':
724 pp_pre_define(param);
725 break;
727 case 'u': /* un-define */
728 case 'U':
729 pp_pre_undefine(param);
730 break;
732 case 'i': /* include search path */
733 case 'I':
734 pp_include_path(param);
735 break;
737 case 'l': /* listing file */
738 copy_filename(listname, param);
739 break;
741 case 'Z': /* error messages file */
742 copy_filename(errname, param);
743 break;
745 case 'F': /* specify debug format */
746 ofmt->current_dfmt = dfmt_find(ofmt, param);
747 if (!ofmt->current_dfmt) {
748 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
749 "unrecognized debug format `%s' for"
750 " output format `%s'",
751 param, ofmt->shortname);
753 using_debug_info = true;
754 break;
756 case 'X': /* specify error reporting format */
757 if (nasm_stricmp("vc", param) == 0)
758 nasm_set_verror(nasm_verror_vc);
759 else if (nasm_stricmp("gnu", param) == 0)
760 nasm_set_verror(nasm_verror_gnu);
761 else
762 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
763 "unrecognized error reporting format `%s'",
764 param);
765 break;
767 case 'g':
768 using_debug_info = true;
769 break;
771 case 'h':
772 printf
773 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
774 "[-l listfile]\n"
775 " [options...] [--] filename\n"
776 " or nasm -v for version info\n\n"
777 " -t assemble in SciTech TASM compatible mode\n"
778 " -g generate debug information in selected format\n");
779 printf
780 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
781 " -a don't preprocess (assemble only)\n"
782 " -M generate Makefile dependencies on stdout\n"
783 " -MG d:o, missing files assumed generated\n"
784 " -MF <file> set Makefile dependency file\n"
785 " -MD <file> assemble and generate dependencies\n"
786 " -MT <file> dependency target name\n"
787 " -MQ <file> dependency target name (quoted)\n"
788 " -MP emit phony target\n\n"
789 " -Z<file> redirect error messages to file\n"
790 " -s redirect error messages to stdout\n\n"
791 " -F format select a debugging format\n\n"
792 " -I<path> adds a pathname to the include file path\n");
793 printf
794 (" -O<digit> optimize code size\n"
795 " -O0: No optimization\n"
796 " -OL: Legacy optimization\n"
797 " -O1: Minimal optimization\n"
798 " -Ox: Full optimization (default)\n\n"
799 " -P<file> pre-includes a file\n"
800 " -D<macro>[=<value>] pre-defines a macro\n"
801 " -U<macro> undefines a macro\n"
802 " -X<format> specifies error reporting format (gnu or vc)\n"
803 " -w+foo enables warning foo (equiv. -Wfoo)\n"
804 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
805 "--prefix,--postfix\n"
806 " this options prepend or append the given argument to all\n"
807 " extern and global variables\n\n"
808 "Warnings:\n");
809 for (i = 0; i <= ERR_WARN_MAX; i++)
810 printf(" %-23s %s (default %s)\n",
811 warnings[i].name, warnings[i].help,
812 warnings[i].enabled ? "on" : "off");
813 printf
814 ("\nresponse files should contain command line parameters"
815 ", one per line.\n");
816 if (p[2] == 'f') {
817 printf("\nvalid output formats for -f are"
818 " (`*' denotes default):\n");
819 ofmt_list(ofmt, stdout);
820 } else {
821 printf("\nFor a list of valid output formats, use -hf.\n");
822 printf("For a list of debug formats, use -f <form> -y.\n");
824 exit(0); /* never need usage message here */
825 break;
827 case 'y':
828 printf("\nvalid debug formats for '%s' output format are"
829 " ('*' denotes default):\n", ofmt->shortname);
830 dfmt_list(ofmt, stdout);
831 exit(0);
832 break;
834 case 't':
835 tasm_compatible_mode = true;
836 break;
838 case 'v':
839 printf("NASM version %s compiled on %s%s\n",
840 nasm_version, nasm_date, nasm_compile_options);
841 exit(0); /* never need usage message here */
842 break;
844 case 'e': /* preprocess only */
845 case 'E':
846 operating_mode = op_preprocess;
847 break;
849 case 'a': /* assemble only - don't preprocess */
850 preproc = &no_pp;
851 break;
853 case 'W':
854 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
855 do_warn = false;
856 param += 3;
857 } else {
858 do_warn = true;
860 goto set_warning;
862 case 'w':
863 if (param[0] != '+' && param[0] != '-') {
864 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
865 "invalid option to `-w'");
866 break;
868 do_warn = (param[0] == '+');
869 param++;
871 set_warning:
872 for (i = 0; i <= ERR_WARN_MAX; i++)
873 if (!nasm_stricmp(param, warnings[i].name))
874 break;
875 if (i <= ERR_WARN_MAX)
876 warning_on_global[i] = do_warn;
877 else if (!nasm_stricmp(param, "all"))
878 for (i = 1; i <= ERR_WARN_MAX; i++)
879 warning_on_global[i] = do_warn;
880 else if (!nasm_stricmp(param, "none"))
881 for (i = 1; i <= ERR_WARN_MAX; i++)
882 warning_on_global[i] = !do_warn;
883 else
884 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
885 "invalid warning `%s'", param);
886 break;
888 case 'M':
889 switch (p[2]) {
890 case 0:
891 operating_mode = op_depend;
892 break;
893 case 'G':
894 operating_mode = op_depend;
895 depend_missing_ok = true;
896 break;
897 case 'P':
898 depend_emit_phony = true;
899 break;
900 case 'D':
901 depend_file = q;
902 advance = true;
903 break;
904 case 'T':
905 depend_target = q;
906 advance = true;
907 break;
908 case 'Q':
909 depend_target = quote_for_make(q);
910 advance = true;
911 break;
912 default:
913 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
914 "unknown dependency option `-M%c'", p[2]);
915 break;
917 if (advance && (!q || !q[0])) {
918 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
919 "option `-M%c' requires a parameter", p[2]);
920 break;
922 break;
924 case '-':
926 int s;
928 if (p[2] == 0) { /* -- => stop processing options */
929 stopoptions = 1;
930 break;
932 for (s = 0; textopts[s].label; s++) {
933 if (!nasm_stricmp(p + 2, textopts[s].label)) {
934 break;
938 switch (s) {
940 case OPT_PREFIX:
941 case OPT_POSTFIX:
943 if (!q) {
944 nasm_error(ERR_NONFATAL | ERR_NOFILE |
945 ERR_USAGE,
946 "option `--%s' requires an argument",
947 p + 2);
948 break;
949 } else {
950 advance = 1, param = q;
953 if (s == OPT_PREFIX) {
954 strncpy(lprefix, param, PREFIX_MAX - 1);
955 lprefix[PREFIX_MAX - 1] = 0;
956 break;
958 if (s == OPT_POSTFIX) {
959 strncpy(lpostfix, param, POSTFIX_MAX - 1);
960 lpostfix[POSTFIX_MAX - 1] = 0;
961 break;
963 break;
965 default:
967 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
968 "unrecognised option `--%s'", p + 2);
969 break;
972 break;
975 default:
976 if (!ofmt->setinfo(GI_SWITCH, &p))
977 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
978 "unrecognised option `-%c'", p[1]);
979 break;
981 } else {
982 if (*inname) {
983 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
984 "more than one input file specified");
985 } else {
986 copy_filename(inname, p);
990 return advance;
993 #define ARG_BUF_DELTA 128
995 static void process_respfile(FILE * rfile)
997 char *buffer, *p, *q, *prevarg;
998 int bufsize, prevargsize;
1000 bufsize = prevargsize = ARG_BUF_DELTA;
1001 buffer = nasm_malloc(ARG_BUF_DELTA);
1002 prevarg = nasm_malloc(ARG_BUF_DELTA);
1003 prevarg[0] = '\0';
1005 while (1) { /* Loop to handle all lines in file */
1006 p = buffer;
1007 while (1) { /* Loop to handle long lines */
1008 q = fgets(p, bufsize - (p - buffer), rfile);
1009 if (!q)
1010 break;
1011 p += strlen(p);
1012 if (p > buffer && p[-1] == '\n')
1013 break;
1014 if (p - buffer > bufsize - 10) {
1015 int offset;
1016 offset = p - buffer;
1017 bufsize += ARG_BUF_DELTA;
1018 buffer = nasm_realloc(buffer, bufsize);
1019 p = buffer + offset;
1023 if (!q && p == buffer) {
1024 if (prevarg[0])
1025 process_arg(prevarg, NULL);
1026 nasm_free(buffer);
1027 nasm_free(prevarg);
1028 return;
1032 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1033 * them are present at the end of the line.
1035 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1037 while (p > buffer && nasm_isspace(p[-1]))
1038 *--p = '\0';
1040 p = nasm_skip_spaces(buffer);
1042 if (process_arg(prevarg, p))
1043 *p = '\0';
1045 if ((int) strlen(p) > prevargsize - 10) {
1046 prevargsize += ARG_BUF_DELTA;
1047 prevarg = nasm_realloc(prevarg, prevargsize);
1049 strncpy(prevarg, p, prevargsize);
1053 /* Function to process args from a string of args, rather than the
1054 * argv array. Used by the environment variable and response file
1055 * processing.
1057 static void process_args(char *args)
1059 char *p, *q, *arg, *prevarg;
1060 char separator = ' ';
1062 p = args;
1063 if (*p && *p != '-')
1064 separator = *p++;
1065 arg = NULL;
1066 while (*p) {
1067 q = p;
1068 while (*p && *p != separator)
1069 p++;
1070 while (*p == separator)
1071 *p++ = '\0';
1072 prevarg = arg;
1073 arg = q;
1074 if (process_arg(prevarg, arg))
1075 arg = NULL;
1077 if (arg)
1078 process_arg(arg, NULL);
1081 static void process_response_file(const char *file)
1083 char str[2048];
1084 FILE *f = fopen(file, "r");
1085 if (!f) {
1086 perror(file);
1087 exit(-1);
1089 while (fgets(str, sizeof str, f)) {
1090 process_args(str);
1092 fclose(f);
1095 static void parse_cmdline(int argc, char **argv)
1097 FILE *rfile;
1098 char *envreal, *envcopy = NULL, *p, *arg;
1099 int i;
1101 *inname = *outname = *listname = *errname = '\0';
1102 for (i = 0; i <= ERR_WARN_MAX; i++)
1103 warning_on_global[i] = warnings[i].enabled;
1106 * First, process the NASMENV environment variable.
1108 envreal = getenv("NASMENV");
1109 arg = NULL;
1110 if (envreal) {
1111 envcopy = nasm_strdup(envreal);
1112 process_args(envcopy);
1113 nasm_free(envcopy);
1117 * Now process the actual command line.
1119 while (--argc) {
1120 bool advance;
1121 argv++;
1122 if (argv[0][0] == '@') {
1123 /* We have a response file, so process this as a set of
1124 * arguments like the environment variable. This allows us
1125 * to have multiple arguments on a single line, which is
1126 * different to the -@resp file processing below for regular
1127 * NASM.
1129 process_response_file(argv[0]+1);
1130 argc--;
1131 argv++;
1133 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1134 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1135 if (p) {
1136 rfile = fopen(p, "r");
1137 if (rfile) {
1138 process_respfile(rfile);
1139 fclose(rfile);
1140 } else
1141 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1142 "unable to open response file `%s'", p);
1144 } else
1145 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1146 argv += advance, argc -= advance;
1149 /* Look for basic command line typos. This definitely doesn't
1150 catch all errors, but it might help cases of fumbled fingers. */
1151 if (!*inname)
1152 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1153 "no input file specified");
1154 else if (!strcmp(inname, errname) ||
1155 !strcmp(inname, outname) ||
1156 !strcmp(inname, listname) ||
1157 (depend_file && !strcmp(inname, depend_file)))
1158 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1159 "file `%s' is both input and output file",
1160 inname);
1162 if (*errname) {
1163 error_file = fopen(errname, "w");
1164 if (!error_file) {
1165 error_file = stderr; /* Revert to default! */
1166 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1167 "cannot open file `%s' for error messages",
1168 errname);
1173 static enum directives getkw(char **directive, char **value);
1175 static void assemble_file(char *fname, StrList **depend_ptr)
1177 char *directive, *value, *p, *q, *special, *line;
1178 insn output_ins;
1179 int i, validid;
1180 bool rn_error;
1181 int32_t seg;
1182 int64_t offs;
1183 struct tokenval tokval;
1184 expr *e;
1185 int pass_max;
1187 if (cmd_sb == 32 && cmd_cpu < IF_386)
1188 nasm_error(ERR_FATAL, "command line: "
1189 "32-bit segment size requires a higher cpu");
1191 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1192 for (passn = 1; pass0 <= 2; passn++) {
1193 int pass1, pass2;
1194 ldfunc def_label;
1196 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1197 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1198 /* pass0 0, 0, 0, ..., 1, 2 */
1200 def_label = passn > 1 ? redefine_label : define_label;
1202 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1203 cpu = cmd_cpu;
1204 if (pass0 == 2) {
1205 if (*listname)
1206 nasmlist.init(listname, nasm_error);
1208 in_abs_seg = false;
1209 global_offset_changed = 0; /* set by redefine_label */
1210 location.segment = ofmt->section(NULL, pass2, &sb);
1211 globalbits = sb;
1212 if (passn > 1) {
1213 saa_rewind(forwrefs);
1214 forwref = saa_rstruct(forwrefs);
1215 raa_free(offsets);
1216 offsets = raa_init();
1218 preproc->reset(fname, pass1, &nasmlist,
1219 pass1 == 2 ? depend_ptr : NULL);
1220 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1222 globallineno = 0;
1223 if (passn == 1)
1224 location.known = true;
1225 location.offset = offs = GET_CURR_OFFS;
1227 while ((line = preproc->getline())) {
1228 enum directives d;
1229 globallineno++;
1232 * Here we parse our directives; this is not handled by the
1233 * 'real' parser. This really should be a separate function.
1235 directive = line;
1236 d = getkw(&directive, &value);
1237 if (d) {
1238 int err = 0;
1240 switch (d) {
1241 case D_SEGMENT: /* [SEGMENT n] */
1242 case D_SECTION:
1243 seg = ofmt->section(value, pass2, &sb);
1244 if (seg == NO_SEG) {
1245 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1246 "segment name `%s' not recognized",
1247 value);
1248 } else {
1249 in_abs_seg = false;
1250 location.segment = seg;
1252 break;
1253 case D_SECTALIGN: /* [SECTALIGN n] */
1255 if (*value) {
1256 unsigned int align = atoi(value);
1257 if (!is_power2(align)) {
1258 nasm_error(ERR_NONFATAL,
1259 "segment alignment `%s' is not power of two",
1260 value);
1262 /* callee should be able to handle all details */
1263 ofmt->sectalign(location.segment, align);
1266 break;
1267 case D_EXTERN: /* [EXTERN label:special] */
1268 if (*value == '$')
1269 value++; /* skip initial $ if present */
1270 if (pass0 == 2) {
1271 q = value;
1272 while (*q && *q != ':')
1273 q++;
1274 if (*q == ':') {
1275 *q++ = '\0';
1276 ofmt->symdef(value, 0L, 0L, 3, q);
1278 } else if (passn == 1) {
1279 q = value;
1280 validid = true;
1281 if (!isidstart(*q))
1282 validid = false;
1283 while (*q && *q != ':') {
1284 if (!isidchar(*q))
1285 validid = false;
1286 q++;
1288 if (!validid) {
1289 nasm_error(ERR_NONFATAL,
1290 "identifier expected after EXTERN");
1291 break;
1293 if (*q == ':') {
1294 *q++ = '\0';
1295 special = q;
1296 } else
1297 special = NULL;
1298 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1299 int temp = pass0;
1300 pass0 = 1; /* fake pass 1 in labels.c */
1301 declare_as_global(value, special);
1302 define_label(value, seg_alloc(), 0L, NULL,
1303 false, true);
1304 pass0 = temp;
1306 } /* else pass0 == 1 */
1307 break;
1308 case D_BITS: /* [BITS bits] */
1309 globalbits = sb = get_bits(value);
1310 break;
1311 case D_GLOBAL: /* [GLOBAL symbol:special] */
1312 if (*value == '$')
1313 value++; /* skip initial $ if present */
1314 if (pass0 == 2) { /* pass 2 */
1315 q = value;
1316 while (*q && *q != ':')
1317 q++;
1318 if (*q == ':') {
1319 *q++ = '\0';
1320 ofmt->symdef(value, 0L, 0L, 3, q);
1322 } else if (pass2 == 1) { /* pass == 1 */
1323 q = value;
1324 validid = true;
1325 if (!isidstart(*q))
1326 validid = false;
1327 while (*q && *q != ':') {
1328 if (!isidchar(*q))
1329 validid = false;
1330 q++;
1332 if (!validid) {
1333 nasm_error(ERR_NONFATAL,
1334 "identifier expected after GLOBAL");
1335 break;
1337 if (*q == ':') {
1338 *q++ = '\0';
1339 special = q;
1340 } else
1341 special = NULL;
1342 declare_as_global(value, special);
1343 } /* pass == 1 */
1344 break;
1345 case D_COMMON: /* [COMMON symbol size:special] */
1347 int64_t size;
1349 if (*value == '$')
1350 value++; /* skip initial $ if present */
1351 p = value;
1352 validid = true;
1353 if (!isidstart(*p))
1354 validid = false;
1355 while (*p && !nasm_isspace(*p)) {
1356 if (!isidchar(*p))
1357 validid = false;
1358 p++;
1360 if (!validid) {
1361 nasm_error(ERR_NONFATAL,
1362 "identifier expected after COMMON");
1363 break;
1365 if (*p) {
1366 p = nasm_zap_spaces_fwd(p);
1367 q = p;
1368 while (*q && *q != ':')
1369 q++;
1370 if (*q == ':') {
1371 *q++ = '\0';
1372 special = q;
1373 } else {
1374 special = NULL;
1376 size = readnum(p, &rn_error);
1377 if (rn_error) {
1378 nasm_error(ERR_NONFATAL,
1379 "invalid size specified"
1380 " in COMMON declaration");
1381 break;
1383 } else {
1384 nasm_error(ERR_NONFATAL,
1385 "no size specified in"
1386 " COMMON declaration");
1387 break;
1390 if (pass0 < 2) {
1391 define_common(value, seg_alloc(), size, special);
1392 } else if (pass0 == 2) {
1393 if (special)
1394 ofmt->symdef(value, 0L, 0L, 3, special);
1396 break;
1398 case D_ABSOLUTE: /* [ABSOLUTE address] */
1399 stdscan_reset();
1400 stdscan_set(value);
1401 tokval.t_type = TOKEN_INVALID;
1402 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1403 nasm_error, NULL);
1404 if (e) {
1405 if (!is_reloc(e))
1406 nasm_error(pass0 ==
1407 1 ? ERR_NONFATAL : ERR_PANIC,
1408 "cannot use non-relocatable expression as "
1409 "ABSOLUTE address");
1410 else {
1411 abs_seg = reloc_seg(e);
1412 abs_offset = reloc_value(e);
1414 } else if (passn == 1)
1415 abs_offset = 0x100; /* don't go near zero in case of / */
1416 else
1417 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1418 "in pass two");
1419 in_abs_seg = true;
1420 location.segment = NO_SEG;
1421 break;
1422 case D_DEBUG: /* [DEBUG] */
1424 char debugid[128];
1425 bool badid, overlong;
1427 p = value;
1428 q = debugid;
1429 badid = overlong = false;
1430 if (!isidstart(*p)) {
1431 badid = true;
1432 } else {
1433 while (*p && !nasm_isspace(*p)) {
1434 if (q >= debugid + sizeof debugid - 1) {
1435 overlong = true;
1436 break;
1438 if (!isidchar(*p))
1439 badid = true;
1440 *q++ = *p++;
1442 *q = 0;
1444 if (badid) {
1445 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1446 "identifier expected after DEBUG");
1447 break;
1449 if (overlong) {
1450 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1451 "DEBUG identifier too long");
1452 break;
1454 p = nasm_skip_spaces(p);
1455 if (pass0 == 2)
1456 dfmt->debug_directive(debugid, p);
1457 break;
1459 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1460 value = nasm_skip_spaces(value);
1461 switch(*value) {
1462 case '-': validid = 0; value++; break;
1463 case '+': validid = 1; value++; break;
1464 case '*': validid = 2; value++; break;
1465 default: validid = 1; break;
1468 for (i = 1; i <= ERR_WARN_MAX; i++)
1469 if (!nasm_stricmp(value, warnings[i].name))
1470 break;
1471 if (i <= ERR_WARN_MAX) {
1472 switch(validid) {
1473 case 0:
1474 warning_on[i] = false;
1475 break;
1476 case 1:
1477 warning_on[i] = true;
1478 break;
1479 case 2:
1480 warning_on[i] = warning_on_global[i];
1481 break;
1484 else
1485 nasm_error(ERR_NONFATAL,
1486 "invalid warning id in WARNING directive");
1487 break;
1488 case D_CPU: /* [CPU] */
1489 cpu = get_cpu(value);
1490 break;
1491 case D_LIST: /* [LIST {+|-}] */
1492 value = nasm_skip_spaces(value);
1493 if (*value == '+') {
1494 user_nolist = 0;
1495 } else {
1496 if (*value == '-') {
1497 user_nolist = 1;
1498 } else {
1499 err = 1;
1502 break;
1503 case D_DEFAULT: /* [DEFAULT] */
1504 stdscan_reset();
1505 stdscan_set(value);
1506 tokval.t_type = TOKEN_INVALID;
1507 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1508 switch ((int)tokval.t_integer) {
1509 case S_REL:
1510 globalrel = 1;
1511 break;
1512 case S_ABS:
1513 globalrel = 0;
1514 break;
1515 default:
1516 err = 1;
1517 break;
1519 } else {
1520 err = 1;
1522 break;
1523 case D_FLOAT:
1524 if (float_option(value)) {
1525 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1526 "unknown 'float' directive: %s",
1527 value);
1529 break;
1530 default:
1531 if (ofmt->directive(d, value, pass2))
1532 break;
1533 /* else fall through */
1534 case D_unknown:
1535 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1536 "unrecognised directive [%s]",
1537 directive);
1538 break;
1540 if (err) {
1541 nasm_error(ERR_NONFATAL,
1542 "invalid parameter to [%s] directive",
1543 directive);
1545 } else { /* it isn't a directive */
1546 parse_line(pass1, line, &output_ins, def_label);
1548 if (optimizing > 0) {
1549 if (forwref != NULL && globallineno == forwref->lineno) {
1550 output_ins.forw_ref = true;
1551 do {
1552 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1553 forwref = saa_rstruct(forwrefs);
1554 } while (forwref != NULL
1555 && forwref->lineno == globallineno);
1556 } else
1557 output_ins.forw_ref = false;
1559 if (output_ins.forw_ref) {
1560 if (passn == 1) {
1561 for (i = 0; i < output_ins.operands; i++) {
1562 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1563 struct forwrefinfo *fwinf =
1564 (struct forwrefinfo *)
1565 saa_wstruct(forwrefs);
1566 fwinf->lineno = globallineno;
1567 fwinf->operand = i;
1574 /* forw_ref */
1575 if (output_ins.opcode == I_EQU) {
1576 if (pass1 == 1) {
1578 * Special `..' EQUs get processed in pass two,
1579 * except `..@' macro-processor EQUs which are done
1580 * in the normal place.
1582 if (!output_ins.label)
1583 nasm_error(ERR_NONFATAL,
1584 "EQU not preceded by label");
1586 else if (output_ins.label[0] != '.' ||
1587 output_ins.label[1] != '.' ||
1588 output_ins.label[2] == '@') {
1589 if (output_ins.operands == 1 &&
1590 (output_ins.oprs[0].type & IMMEDIATE) &&
1591 output_ins.oprs[0].wrt == NO_SEG) {
1592 bool isext = !!(output_ins.oprs[0].opflags
1593 & OPFLAG_EXTERN);
1594 def_label(output_ins.label,
1595 output_ins.oprs[0].segment,
1596 output_ins.oprs[0].offset, NULL,
1597 false, isext);
1598 } else if (output_ins.operands == 2
1599 && (output_ins.oprs[0].type & IMMEDIATE)
1600 && (output_ins.oprs[0].type & COLON)
1601 && output_ins.oprs[0].segment == NO_SEG
1602 && output_ins.oprs[0].wrt == NO_SEG
1603 && (output_ins.oprs[1].type & IMMEDIATE)
1604 && output_ins.oprs[1].segment == NO_SEG
1605 && output_ins.oprs[1].wrt == NO_SEG) {
1606 def_label(output_ins.label,
1607 output_ins.oprs[0].offset | SEG_ABS,
1608 output_ins.oprs[1].offset,
1609 NULL, false, false);
1610 } else
1611 nasm_error(ERR_NONFATAL,
1612 "bad syntax for EQU");
1614 } else {
1616 * Special `..' EQUs get processed here, except
1617 * `..@' macro processor EQUs which are done above.
1619 if (output_ins.label[0] == '.' &&
1620 output_ins.label[1] == '.' &&
1621 output_ins.label[2] != '@') {
1622 if (output_ins.operands == 1 &&
1623 (output_ins.oprs[0].type & IMMEDIATE)) {
1624 define_label(output_ins.label,
1625 output_ins.oprs[0].segment,
1626 output_ins.oprs[0].offset,
1627 NULL, false, false);
1628 } else if (output_ins.operands == 2
1629 && (output_ins.oprs[0].type & IMMEDIATE)
1630 && (output_ins.oprs[0].type & COLON)
1631 && output_ins.oprs[0].segment == NO_SEG
1632 && (output_ins.oprs[1].type & IMMEDIATE)
1633 && output_ins.oprs[1].segment == NO_SEG) {
1634 define_label(output_ins.label,
1635 output_ins.oprs[0].offset | SEG_ABS,
1636 output_ins.oprs[1].offset,
1637 NULL, false, false);
1638 } else
1639 nasm_error(ERR_NONFATAL,
1640 "bad syntax for EQU");
1643 } else { /* instruction isn't an EQU */
1645 if (pass1 == 1) {
1647 int64_t l = insn_size(location.segment, offs, sb, cpu,
1648 &output_ins, nasm_error);
1650 /* if (using_debug_info) && output_ins.opcode != -1) */
1651 if (using_debug_info)
1652 { /* fbk 03/25/01 */
1653 /* this is done here so we can do debug type info */
1654 int32_t typeinfo =
1655 TYS_ELEMENTS(output_ins.operands);
1656 switch (output_ins.opcode) {
1657 case I_RESB:
1658 typeinfo =
1659 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1660 break;
1661 case I_RESW:
1662 typeinfo =
1663 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1664 break;
1665 case I_RESD:
1666 typeinfo =
1667 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1668 break;
1669 case I_RESQ:
1670 typeinfo =
1671 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1672 break;
1673 case I_REST:
1674 typeinfo =
1675 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1676 break;
1677 case I_RESO:
1678 typeinfo =
1679 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1680 break;
1681 case I_RESY:
1682 typeinfo =
1683 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1684 break;
1685 case I_DB:
1686 typeinfo |= TY_BYTE;
1687 break;
1688 case I_DW:
1689 typeinfo |= TY_WORD;
1690 break;
1691 case I_DD:
1692 if (output_ins.eops_float)
1693 typeinfo |= TY_FLOAT;
1694 else
1695 typeinfo |= TY_DWORD;
1696 break;
1697 case I_DQ:
1698 typeinfo |= TY_QWORD;
1699 break;
1700 case I_DT:
1701 typeinfo |= TY_TBYTE;
1702 break;
1703 case I_DO:
1704 typeinfo |= TY_OWORD;
1705 break;
1706 case I_DY:
1707 typeinfo |= TY_YWORD;
1708 break;
1709 default:
1710 typeinfo = TY_LABEL;
1714 dfmt->debug_typevalue(typeinfo);
1716 if (l != -1) {
1717 offs += l;
1718 SET_CURR_OFFS(offs);
1721 * else l == -1 => invalid instruction, which will be
1722 * flagged as an error on pass 2
1725 } else {
1726 offs += assemble(location.segment, offs, sb, cpu,
1727 &output_ins, ofmt, nasm_error,
1728 &nasmlist);
1729 SET_CURR_OFFS(offs);
1732 } /* not an EQU */
1733 cleanup_insn(&output_ins);
1735 nasm_free(line);
1736 location.offset = offs = GET_CURR_OFFS;
1737 } /* end while (line = preproc->getline... */
1739 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1740 nasm_error(ERR_NONFATAL,
1741 "phase error detected at end of assembly.");
1743 if (pass1 == 1)
1744 preproc->cleanup(1);
1746 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1747 pass0++;
1748 } else if (global_offset_changed &&
1749 global_offset_changed < prev_offset_changed) {
1750 prev_offset_changed = global_offset_changed;
1751 stall_count = 0;
1752 } else {
1753 stall_count++;
1756 if (terminate_after_phase)
1757 break;
1759 if ((stall_count > 997) || (passn >= pass_max)) {
1760 /* We get here if the labels don't converge
1761 * Example: FOO equ FOO + 1
1763 nasm_error(ERR_NONFATAL,
1764 "Can't find valid values for all labels "
1765 "after %d passes, giving up.", passn);
1766 nasm_error(ERR_NONFATAL,
1767 "Possible causes: recursive EQUs, macro abuse.");
1768 break;
1772 preproc->cleanup(0);
1773 nasmlist.cleanup();
1774 if (!terminate_after_phase && opt_verbose_info) {
1775 /* -On and -Ov switches */
1776 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1780 static enum directives getkw(char **directive, char **value)
1782 char *p, *q, *buf;
1784 buf = nasm_skip_spaces(*directive);
1786 /* it should be enclosed in [ ] */
1787 if (*buf != '[')
1788 return D_none;
1789 q = strchr(buf, ']');
1790 if (!q)
1791 return D_none;
1793 /* stip off the comments */
1794 p = strchr(buf, ';');
1795 if (p) {
1796 if (p < q) /* ouch! somwhere inside */
1797 return D_none;
1798 *p = '\0';
1801 /* no brace, no trailing spaces */
1802 *q = '\0';
1803 nasm_zap_spaces_rev(--q);
1805 /* directive */
1806 p = nasm_skip_spaces(++buf);
1807 q = nasm_skip_word(p);
1808 if (!q)
1809 return D_none; /* sigh... no value there */
1810 *q = '\0';
1811 *directive = p;
1813 /* and value finally */
1814 p = nasm_skip_spaces(++q);
1815 *value = p;
1817 return find_directive(*directive);
1821 * gnu style error reporting
1822 * This function prints an error message to error_file in the
1823 * style used by GNU. An example would be:
1824 * file.asm:50: error: blah blah blah
1825 * where file.asm is the name of the file, 50 is the line number on
1826 * which the error occurs (or is detected) and "error:" is one of
1827 * the possible optional diagnostics -- it can be "error" or "warning"
1828 * or something else. Finally the line terminates with the actual
1829 * error message.
1831 * @param severity the severity of the warning or error
1832 * @param fmt the printf style format string
1834 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1836 char *currentfile = NULL;
1837 int32_t lineno = 0;
1839 if (is_suppressed_warning(severity))
1840 return;
1842 if (!(severity & ERR_NOFILE))
1843 src_get(&lineno, &currentfile);
1845 if (currentfile) {
1846 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1847 nasm_free(currentfile);
1848 } else {
1849 fputs("nasm: ", error_file);
1852 nasm_verror_common(severity, fmt, ap);
1856 * MS style error reporting
1857 * This function prints an error message to error_file in the
1858 * style used by Visual C and some other Microsoft tools. An example
1859 * 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_vc(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 (currentfile) {
1882 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1883 nasm_free(currentfile);
1884 } else {
1885 fputs("nasm: ", error_file);
1888 nasm_verror_common(severity, fmt, ap);
1892 * check for supressed warning
1893 * checks for suppressed warning or pass one only warning and we're
1894 * not in pass 1
1896 * @param severity the severity of the warning or error
1897 * @return true if we should abort error/warning printing
1899 static bool is_suppressed_warning(int severity)
1902 * See if it's a suppressed warning.
1904 return (severity & ERR_MASK) == ERR_WARNING &&
1905 (((severity & ERR_WARN_MASK) != 0 &&
1906 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1907 /* See if it's a pass-one only warning and we're not in pass one. */
1908 ((severity & ERR_PASS1) && pass0 != 1) ||
1909 ((severity & ERR_PASS2) && pass0 != 2));
1913 * common error reporting
1914 * This is the common back end of the error reporting schemes currently
1915 * implemented. It prints the nature of the warning and then the
1916 * specific error message to error_file and may or may not return. It
1917 * doesn't return if the error severity is a "panic" or "debug" type.
1919 * @param severity the severity of the warning or error
1920 * @param fmt the printf style format string
1922 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1924 char msg[1024];
1925 const char *pfx;
1927 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1928 case ERR_WARNING:
1929 pfx = "warning: ";
1930 break;
1931 case ERR_NONFATAL:
1932 pfx = "error: ";
1933 break;
1934 case ERR_FATAL:
1935 pfx = "fatal: ";
1936 break;
1937 case ERR_PANIC:
1938 pfx = "panic: ";
1939 break;
1940 case ERR_DEBUG:
1941 pfx = "debug: ";
1942 break;
1943 default:
1944 pfx = "";
1945 break;
1948 vsnprintf(msg, sizeof msg, fmt, args);
1950 fprintf(error_file, "%s%s\n", pfx, msg);
1952 if (*listname)
1953 nasmlist.error(severity, pfx, msg);
1955 if (severity & ERR_USAGE)
1956 want_usage = true;
1958 switch (severity & ERR_MASK) {
1959 case ERR_DEBUG:
1960 /* no further action, by definition */
1961 break;
1962 case ERR_WARNING:
1963 if (warning_on[0]) /* Treat warnings as errors */
1964 terminate_after_phase = true;
1965 break;
1966 case ERR_NONFATAL:
1967 terminate_after_phase = true;
1968 break;
1969 case ERR_FATAL:
1970 if (ofile) {
1971 fclose(ofile);
1972 remove(outname);
1973 ofile = NULL;
1975 if (want_usage)
1976 usage();
1977 exit(1); /* instantly die */
1978 break; /* placate silly compilers */
1979 case ERR_PANIC:
1980 fflush(NULL);
1981 /* abort(); *//* halt, catch fire, and dump core */
1982 exit(3);
1983 break;
1987 static void usage(void)
1989 fputs("type `nasm -h' for help\n", error_file);
1992 #define BUF_DELTA 512
1994 static FILE *no_pp_fp;
1995 static ListGen *no_pp_list;
1996 static int32_t no_pp_lineinc;
1998 static void no_pp_reset(char *file, int pass, ListGen * listgen,
1999 StrList **deplist)
2001 src_set_fname(nasm_strdup(file));
2002 src_set_linnum(0);
2003 no_pp_lineinc = 1;
2004 no_pp_fp = fopen(file, "r");
2005 if (!no_pp_fp)
2006 nasm_error(ERR_FATAL | ERR_NOFILE,
2007 "unable to open input file `%s'", file);
2008 no_pp_list = listgen;
2009 (void)pass; /* placate compilers */
2011 if (deplist) {
2012 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2013 sl->next = NULL;
2014 strcpy(sl->str, file);
2015 *deplist = sl;
2019 static char *no_pp_getline(void)
2021 char *buffer, *p, *q;
2022 int bufsize;
2024 bufsize = BUF_DELTA;
2025 buffer = nasm_malloc(BUF_DELTA);
2026 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2028 while (1) { /* Loop to handle %line */
2030 p = buffer;
2031 while (1) { /* Loop to handle long lines */
2032 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2033 if (!q)
2034 break;
2035 p += strlen(p);
2036 if (p > buffer && p[-1] == '\n')
2037 break;
2038 if (p - buffer > bufsize - 10) {
2039 int offset;
2040 offset = p - buffer;
2041 bufsize += BUF_DELTA;
2042 buffer = nasm_realloc(buffer, bufsize);
2043 p = buffer + offset;
2047 if (!q && p == buffer) {
2048 nasm_free(buffer);
2049 return NULL;
2053 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2054 * them are present at the end of the line.
2056 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2058 if (!nasm_strnicmp(buffer, "%line", 5)) {
2059 int32_t ln;
2060 int li;
2061 char *nm = nasm_malloc(strlen(buffer));
2062 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2063 nasm_free(src_set_fname(nm));
2064 src_set_linnum(ln);
2065 no_pp_lineinc = li;
2066 continue;
2068 nasm_free(nm);
2070 break;
2073 no_pp_list->line(LIST_READ, buffer);
2075 return buffer;
2078 static void no_pp_cleanup(int pass)
2080 (void)pass; /* placate GCC */
2081 fclose(no_pp_fp);
2084 static uint32_t get_cpu(char *value)
2086 if (!strcmp(value, "8086"))
2087 return IF_8086;
2088 if (!strcmp(value, "186"))
2089 return IF_186;
2090 if (!strcmp(value, "286"))
2091 return IF_286;
2092 if (!strcmp(value, "386"))
2093 return IF_386;
2094 if (!strcmp(value, "486"))
2095 return IF_486;
2096 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2097 return IF_PENT;
2098 if (!strcmp(value, "686") ||
2099 !nasm_stricmp(value, "ppro") ||
2100 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2101 return IF_P6;
2102 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2103 return IF_KATMAI;
2104 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2105 !nasm_stricmp(value, "willamette"))
2106 return IF_WILLAMETTE;
2107 if (!nasm_stricmp(value, "prescott"))
2108 return IF_PRESCOTT;
2109 if (!nasm_stricmp(value, "x64") ||
2110 !nasm_stricmp(value, "x86-64"))
2111 return IF_X86_64;
2112 if (!nasm_stricmp(value, "ia64") ||
2113 !nasm_stricmp(value, "ia-64") ||
2114 !nasm_stricmp(value, "itanium") ||
2115 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2116 return IF_IA64;
2118 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2119 "unknown 'cpu' type");
2121 return IF_PLEVEL; /* the maximum level */
2124 static int get_bits(char *value)
2126 int i;
2128 if ((i = atoi(value)) == 16)
2129 return i; /* set for a 16-bit segment */
2130 else if (i == 32) {
2131 if (cpu < IF_386) {
2132 nasm_error(ERR_NONFATAL,
2133 "cannot specify 32-bit segment on processor below a 386");
2134 i = 16;
2136 } else if (i == 64) {
2137 if (cpu < IF_X86_64) {
2138 nasm_error(ERR_NONFATAL,
2139 "cannot specify 64-bit segment on processor below an x86-64");
2140 i = 16;
2142 if (i != maxbits) {
2143 nasm_error(ERR_NONFATAL,
2144 "%s output format does not support 64-bit code",
2145 ofmt->shortname);
2146 i = 16;
2148 } else {
2149 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2150 "`%s' is not a valid segment size; must be 16, 32 or 64",
2151 value);
2152 i = 16;
2154 return i;