nasm.c -- use list helpers
[nasm.git] / nasm.c
blob24b80c141d5375fef057bd34d5c1db0eac5cdafe
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2009 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"
64 struct forwrefinfo { /* info held on forward refs. */
65 int lineno;
66 int operand;
69 static int get_bits(char *value);
70 static uint32_t get_cpu(char *cpu_str);
71 static void parse_cmdline(int, char **);
72 static void assemble_file(char *, StrList **);
73 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
74 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
75 static void nasm_verror_common(int severity, const char *fmt, va_list args);
76 static bool is_suppressed_warning(int severity);
77 static void usage(void);
79 static int using_debug_info, opt_verbose_info;
80 bool tasm_compatible_mode = false;
81 int pass0, passn;
82 int maxbits = 0;
83 int globalrel = 0;
85 static time_t official_compile_time;
87 static char inname[FILENAME_MAX];
88 static char outname[FILENAME_MAX];
89 static char listname[FILENAME_MAX];
90 static char errname[FILENAME_MAX];
91 static int globallineno; /* for forward-reference tracking */
92 /* static int pass = 0; */
93 struct ofmt *ofmt = &OF_DEFAULT;
94 const struct dfmt *dfmt;
96 static FILE *error_file; /* Where to write error messages */
98 FILE *ofile = NULL;
99 int optimizing = -1; /* number of optimization passes to take */
100 static int sb, cmd_sb = 16; /* by default */
101 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
102 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
103 int64_t global_offset_changed; /* referenced in labels.c */
104 int64_t prev_offset_changed;
105 int32_t stall_count;
107 static struct location location;
108 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
109 int32_t abs_seg; /* ABSOLUTE segment basis */
110 int32_t abs_offset; /* ABSOLUTE offset */
112 static struct RAA *offsets;
114 static struct SAA *forwrefs; /* keep track of forward references */
115 static const struct forwrefinfo *forwref;
117 static Preproc *preproc;
118 enum op_type {
119 op_normal, /* Preprocess and assemble */
120 op_preprocess, /* Preprocess only */
121 op_depend, /* Generate dependencies */
123 static enum op_type operating_mode;
124 /* Dependency flags */
125 static bool depend_emit_phony = false;
126 static bool depend_missing_ok = false;
127 static const char *depend_target = NULL;
128 static const char *depend_file = NULL;
131 * Which of the suppressible warnings are suppressed. Entry zero
132 * isn't an actual warning, but it used for -w+error/-Werror.
135 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
136 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
138 static const struct warning {
139 const char *name;
140 const char *help;
141 bool enabled;
142 } warnings[ERR_WARN_MAX+1] = {
143 {"error", "treat warnings as errors", false},
144 {"macro-params", "macro calls with wrong parameter count", true},
145 {"macro-selfref", "cyclic macro references", false},
146 {"macro-defaults", "macros with more default than optional parameters", true},
147 {"orphan-labels", "labels alone on lines without trailing `:'", true},
148 {"number-overflow", "numeric constant does not fit", true},
149 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
150 {"float-overflow", "floating point overflow", true},
151 {"float-denorm", "floating point denormal", false},
152 {"float-underflow", "floating point underflow", false},
153 {"float-toolong", "too many digits in floating-point number", true},
154 {"user", "%warning directives", true},
158 * This is a null preprocessor which just copies lines from input
159 * to output. It's used when someone explicitly requests that NASM
160 * not preprocess their source file.
163 static void no_pp_reset(char *, int, ListGen *, StrList **);
164 static char *no_pp_getline(void);
165 static void no_pp_cleanup(int);
166 static Preproc no_pp = {
167 no_pp_reset,
168 no_pp_getline,
169 no_pp_cleanup
173 * get/set current offset...
175 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
176 raa_read(offsets,location.segment))
177 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
178 (void)(offsets=raa_write(offsets,location.segment,(x))))
180 static bool want_usage;
181 static bool terminate_after_phase;
182 int user_nolist = 0; /* fbk 9/2/00 */
184 static void nasm_fputs(const char *line, FILE * outfile)
186 if (outfile) {
187 fputs(line, outfile);
188 putc('\n', outfile);
189 } else
190 puts(line);
193 /* Convert a struct tm to a POSIX-style time constant */
194 static int64_t posix_mktime(struct tm *tm)
196 int64_t t;
197 int64_t y = tm->tm_year;
199 /* See IEEE 1003.1:2004, section 4.14 */
201 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
202 t += tm->tm_yday;
203 t *= 24;
204 t += tm->tm_hour;
205 t *= 60;
206 t += tm->tm_min;
207 t *= 60;
208 t += tm->tm_sec;
210 return t;
213 static void define_macros_early(void)
215 char temp[128];
216 struct tm lt, *lt_p, gm, *gm_p;
217 int64_t posix_time;
219 lt_p = localtime(&official_compile_time);
220 if (lt_p) {
221 lt = *lt_p;
223 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
224 pp_pre_define(temp);
225 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
226 pp_pre_define(temp);
227 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
228 pp_pre_define(temp);
229 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
230 pp_pre_define(temp);
233 gm_p = gmtime(&official_compile_time);
234 if (gm_p) {
235 gm = *gm_p;
237 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
238 pp_pre_define(temp);
239 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
240 pp_pre_define(temp);
241 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
242 pp_pre_define(temp);
243 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
244 pp_pre_define(temp);
247 if (gm_p)
248 posix_time = posix_mktime(&gm);
249 else if (lt_p)
250 posix_time = posix_mktime(&lt);
251 else
252 posix_time = 0;
254 if (posix_time) {
255 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
256 pp_pre_define(temp);
260 static void define_macros_late(void)
262 char temp[128];
264 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
265 ofmt->shortname);
266 pp_pre_define(temp);
269 static void emit_dependencies(StrList *list)
271 FILE *deps;
272 int linepos, len;
273 StrList *l, *nl;
275 if (depend_file && strcmp(depend_file, "-")) {
276 deps = fopen(depend_file, "w");
277 if (!deps) {
278 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
279 "unable to write dependency file `%s'", depend_file);
280 return;
282 } else {
283 deps = stdout;
286 linepos = fprintf(deps, "%s:", depend_target);
287 list_for_each(l, list) {
288 len = strlen(l->str);
289 if (linepos + len > 62) {
290 fprintf(deps, " \\\n ");
291 linepos = 1;
293 fprintf(deps, " %s", l->str);
294 linepos += len+1;
296 fprintf(deps, "\n\n");
298 list_for_each_safe(l, nl, list) {
299 if (depend_emit_phony)
300 fprintf(deps, "%s:\n\n", l->str);
301 nasm_free(l);
304 if (deps != stdout)
305 fclose(deps);
308 int main(int argc, char **argv)
310 StrList *depend_list = NULL, **depend_ptr;
312 time(&official_compile_time);
314 pass0 = 0;
315 want_usage = terminate_after_phase = false;
316 nasm_set_verror(nasm_verror_gnu);
318 error_file = stderr;
320 tolower_init();
322 nasm_init_malloc_error();
323 offsets = raa_init();
324 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
326 preproc = &nasmpp;
327 operating_mode = op_normal;
329 seg_init();
331 /* Define some macros dependent on the runtime, but not
332 on the command line. */
333 define_macros_early();
335 parse_cmdline(argc, argv);
337 if (terminate_after_phase) {
338 if (want_usage)
339 usage();
340 return 1;
343 /* If debugging info is disabled, suppress any debug calls */
344 if (!using_debug_info)
345 ofmt->current_dfmt = &null_debug_form;
347 if (ofmt->stdmac)
348 pp_extra_stdmac(ofmt->stdmac);
349 parser_global_info(&location);
350 eval_global_info(ofmt, lookup_label, &location);
352 /* define some macros dependent of command-line */
353 define_macros_late();
355 depend_ptr = (depend_file || (operating_mode == op_depend))
356 ? &depend_list : NULL;
357 if (!depend_target)
358 depend_target = outname;
360 switch (operating_mode) {
361 case op_depend:
363 char *line;
365 if (depend_missing_ok)
366 pp_include_path(NULL); /* "assume generated" */
368 preproc->reset(inname, 0, &nasmlist, depend_ptr);
369 if (outname[0] == '\0')
370 ofmt->filename(inname, outname);
371 ofile = NULL;
372 while ((line = preproc->getline()))
373 nasm_free(line);
374 preproc->cleanup(0);
376 break;
378 case op_preprocess:
380 char *line;
381 char *file_name = NULL;
382 int32_t prior_linnum = 0;
383 int lineinc = 0;
385 if (*outname) {
386 ofile = fopen(outname, "w");
387 if (!ofile)
388 nasm_error(ERR_FATAL | ERR_NOFILE,
389 "unable to open output file `%s'",
390 outname);
391 } else
392 ofile = NULL;
394 location.known = false;
396 /* pass = 1; */
397 preproc->reset(inname, 3, &nasmlist, depend_ptr);
399 while ((line = preproc->getline())) {
401 * We generate %line directives if needed for later programs
403 int32_t linnum = prior_linnum += lineinc;
404 int altline = src_get(&linnum, &file_name);
405 if (altline) {
406 if (altline == 1 && lineinc == 1)
407 nasm_fputs("", ofile);
408 else {
409 lineinc = (altline != -1 || lineinc != 1);
410 fprintf(ofile ? ofile : stdout,
411 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
412 file_name);
414 prior_linnum = linnum;
416 nasm_fputs(line, ofile);
417 nasm_free(line);
419 nasm_free(file_name);
420 preproc->cleanup(0);
421 if (ofile)
422 fclose(ofile);
423 if (ofile && terminate_after_phase)
424 remove(outname);
425 ofile = NULL;
427 break;
429 case op_normal:
432 * We must call ofmt->filename _anyway_, even if the user
433 * has specified their own output file, because some
434 * formats (eg OBJ and COFF) use ofmt->filename to find out
435 * the name of the input file and then put that inside the
436 * file.
438 ofmt->filename(inname, outname);
440 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
441 if (!ofile) {
442 nasm_error(ERR_FATAL | ERR_NOFILE,
443 "unable to open output file `%s'", outname);
447 * We must call init_labels() before ofmt->init() since
448 * some object formats will want to define labels in their
449 * init routines. (eg OS/2 defines the FLAT group)
451 init_labels();
453 ofmt->init();
454 dfmt = ofmt->current_dfmt;
455 dfmt->init();
457 assemble_file(inname, depend_ptr);
459 if (!terminate_after_phase) {
460 ofmt->cleanup(using_debug_info);
461 cleanup_labels();
462 fflush(ofile);
463 if (ferror(ofile)) {
464 nasm_error(ERR_NONFATAL|ERR_NOFILE,
465 "write error on output file `%s'", outname);
469 if (ofile) {
470 fclose(ofile);
471 if (terminate_after_phase)
472 remove(outname);
473 ofile = NULL;
476 break;
479 if (depend_list && !terminate_after_phase)
480 emit_dependencies(depend_list);
482 if (want_usage)
483 usage();
485 raa_free(offsets);
486 saa_free(forwrefs);
487 eval_cleanup();
488 stdscan_cleanup();
490 return terminate_after_phase;
494 * Get a parameter for a command line option.
495 * First arg must be in the form of e.g. -f...
497 static char *get_param(char *p, char *q, bool *advance)
499 *advance = false;
500 if (p[2]) { /* the parameter's in the option */
501 p += 2;
502 while (nasm_isspace(*p))
503 p++;
504 return p;
506 if (q && q[0]) {
507 *advance = true;
508 return q;
510 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
511 "option `-%c' requires an argument", p[1]);
512 return NULL;
516 * Copy a filename
518 static void copy_filename(char *dst, const char *src)
520 size_t len = strlen(src);
522 if (len >= (size_t)FILENAME_MAX) {
523 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
524 return;
526 strncpy(dst, src, FILENAME_MAX);
530 * Convert a string to Make-safe form
532 static char *quote_for_make(const char *str)
534 const char *p;
535 char *os, *q;
537 size_t n = 1; /* Terminating zero */
538 size_t nbs = 0;
540 if (!str)
541 return NULL;
543 for (p = str; *p; p++) {
544 switch (*p) {
545 case ' ':
546 case '\t':
547 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
548 n += nbs + 2;
549 nbs = 0;
550 break;
551 case '$':
552 case '#':
553 nbs = 0;
554 n += 2;
555 break;
556 case '\\':
557 nbs++;
558 n++;
559 break;
560 default:
561 nbs = 0;
562 n++;
563 break;
567 /* Convert N backslashes at the end of filename to 2N backslashes */
568 if (nbs)
569 n += nbs;
571 os = q = nasm_malloc(n);
573 nbs = 0;
574 for (p = str; *p; p++) {
575 switch (*p) {
576 case ' ':
577 case '\t':
578 while (nbs--)
579 *q++ = '\\';
580 *q++ = '\\';
581 *q++ = *p;
582 break;
583 case '$':
584 *q++ = *p;
585 *q++ = *p;
586 nbs = 0;
587 break;
588 case '#':
589 *q++ = '\\';
590 *q++ = *p;
591 nbs = 0;
592 break;
593 case '\\':
594 *q++ = *p;
595 nbs++;
596 break;
597 default:
598 *q++ = *p;
599 nbs = 0;
600 break;
603 while (nbs--)
604 *q++ = '\\';
606 *q = '\0';
608 return os;
611 struct textargs {
612 const char *label;
613 int value;
616 #define OPT_PREFIX 0
617 #define OPT_POSTFIX 1
618 struct textargs textopts[] = {
619 {"prefix", OPT_PREFIX},
620 {"postfix", OPT_POSTFIX},
621 {NULL, 0}
624 static bool stopoptions = false;
625 static bool process_arg(char *p, char *q)
627 char *param;
628 int i;
629 bool advance = false;
630 bool do_warn;
632 if (!p || !p[0])
633 return false;
635 if (p[0] == '-' && !stopoptions) {
636 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
637 /* These parameters take values */
638 if (!(param = get_param(p, q, &advance)))
639 return advance;
642 switch (p[1]) {
643 case 's':
644 error_file = stdout;
645 break;
647 case 'o': /* output file */
648 copy_filename(outname, param);
649 break;
651 case 'f': /* output format */
652 ofmt = ofmt_find(param);
653 if (!ofmt) {
654 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
655 "unrecognised output format `%s' - "
656 "use -hf for a list", param);
658 break;
660 case 'O': /* Optimization level */
662 int opt;
664 if (!*param) {
665 /* Naked -O == -Ox */
666 optimizing = INT_MAX >> 1; /* Almost unlimited */
667 } else {
668 while (*param) {
669 switch (*param) {
670 case '0': case '1': case '2': case '3': case '4':
671 case '5': case '6': case '7': case '8': case '9':
672 opt = strtoul(param, &param, 10);
674 /* -O0 -> optimizing == -1, 0.98 behaviour */
675 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
676 if (opt < 2)
677 optimizing = opt - 1;
678 else
679 optimizing = opt;
680 break;
682 case 'v':
683 case '+':
684 param++;
685 opt_verbose_info = true;
686 break;
688 case 'x':
689 param++;
690 optimizing = INT_MAX >> 1; /* Almost unlimited */
691 break;
693 default:
694 nasm_error(ERR_FATAL,
695 "unknown optimization option -O%c\n",
696 *param);
697 break;
701 break;
704 case 'p': /* pre-include */
705 case 'P':
706 pp_pre_include(param);
707 break;
709 case 'd': /* pre-define */
710 case 'D':
711 pp_pre_define(param);
712 break;
714 case 'u': /* un-define */
715 case 'U':
716 pp_pre_undefine(param);
717 break;
719 case 'i': /* include search path */
720 case 'I':
721 pp_include_path(param);
722 break;
724 case 'l': /* listing file */
725 copy_filename(listname, param);
726 break;
728 case 'Z': /* error messages file */
729 strcpy(errname, param);
730 break;
732 case 'F': /* specify debug format */
733 ofmt->current_dfmt = dfmt_find(ofmt, param);
734 if (!ofmt->current_dfmt) {
735 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
736 "unrecognized debug format `%s' for"
737 " output format `%s'",
738 param, ofmt->shortname);
740 using_debug_info = true;
741 break;
743 case 'X': /* specify error reporting format */
744 if (nasm_stricmp("vc", param) == 0)
745 nasm_set_verror(nasm_verror_vc);
746 else if (nasm_stricmp("gnu", param) == 0)
747 nasm_set_verror(nasm_verror_gnu);
748 else
749 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
750 "unrecognized error reporting format `%s'",
751 param);
752 break;
754 case 'g':
755 using_debug_info = true;
756 break;
758 case 'h':
759 printf
760 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
761 "[-l listfile]\n"
762 " [options...] [--] filename\n"
763 " or nasm -v for version info\n\n"
764 " -t assemble in SciTech TASM compatible mode\n"
765 " -g generate debug information in selected format.\n");
766 printf
767 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
768 " -a don't preprocess (assemble only)\n"
769 " -M generate Makefile dependencies on stdout\n"
770 " -MG d:o, missing files assumed generated\n\n"
771 " -Z<file> redirect error messages to file\n"
772 " -s redirect error messages to stdout\n\n"
773 " -F format select a debugging format\n\n"
774 " -I<path> adds a pathname to the include file path\n");
775 printf
776 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
777 " -P<file> pre-includes a file\n"
778 " -D<macro>[=<value>] pre-defines a macro\n"
779 " -U<macro> undefines a macro\n"
780 " -X<format> specifies error reporting format (gnu or vc)\n"
781 " -w+foo enables warning foo (equiv. -Wfoo)\n"
782 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
783 "Warnings:\n");
784 for (i = 0; i <= ERR_WARN_MAX; i++)
785 printf(" %-23s %s (default %s)\n",
786 warnings[i].name, warnings[i].help,
787 warnings[i].enabled ? "on" : "off");
788 printf
789 ("\nresponse files should contain command line parameters"
790 ", one per line.\n");
791 if (p[2] == 'f') {
792 printf("\nvalid output formats for -f are"
793 " (`*' denotes default):\n");
794 ofmt_list(ofmt, stdout);
795 } else {
796 printf("\nFor a list of valid output formats, use -hf.\n");
797 printf("For a list of debug formats, use -f <form> -y.\n");
799 exit(0); /* never need usage message here */
800 break;
802 case 'y':
803 printf("\nvalid debug formats for '%s' output format are"
804 " ('*' denotes default):\n", ofmt->shortname);
805 dfmt_list(ofmt, stdout);
806 exit(0);
807 break;
809 case 't':
810 tasm_compatible_mode = true;
811 break;
813 case 'v':
814 printf("NASM version %s compiled on %s%s\n",
815 nasm_version, nasm_date, nasm_compile_options);
816 exit(0); /* never need usage message here */
817 break;
819 case 'e': /* preprocess only */
820 case 'E':
821 operating_mode = op_preprocess;
822 break;
824 case 'a': /* assemble only - don't preprocess */
825 preproc = &no_pp;
826 break;
828 case 'W':
829 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
830 do_warn = false;
831 param += 3;
832 } else {
833 do_warn = true;
835 goto set_warning;
837 case 'w':
838 if (param[0] != '+' && param[0] != '-') {
839 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
840 "invalid option to `-w'");
841 break;
843 do_warn = (param[0] == '+');
844 param++;
845 goto set_warning;
846 set_warning:
847 for (i = 0; i <= ERR_WARN_MAX; i++)
848 if (!nasm_stricmp(param, warnings[i].name))
849 break;
850 if (i <= ERR_WARN_MAX)
851 warning_on_global[i] = do_warn;
852 else if (!nasm_stricmp(param, "all"))
853 for (i = 1; i <= ERR_WARN_MAX; i++)
854 warning_on_global[i] = do_warn;
855 else if (!nasm_stricmp(param, "none"))
856 for (i = 1; i <= ERR_WARN_MAX; i++)
857 warning_on_global[i] = !do_warn;
858 else
859 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
860 "invalid warning `%s'", param);
861 break;
863 case 'M':
864 switch (p[2]) {
865 case 0:
866 operating_mode = op_depend;
867 break;
868 case 'G':
869 operating_mode = op_depend;
870 depend_missing_ok = true;
871 break;
872 case 'P':
873 depend_emit_phony = true;
874 break;
875 case 'D':
876 depend_file = q;
877 advance = true;
878 break;
879 case 'T':
880 depend_target = q;
881 advance = true;
882 break;
883 case 'Q':
884 depend_target = quote_for_make(q);
885 advance = true;
886 break;
887 default:
888 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
889 "unknown dependency option `-M%c'", p[2]);
890 break;
892 if (advance && (!q || !q[0])) {
893 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
894 "option `-M%c' requires a parameter", p[2]);
895 break;
897 break;
899 case '-':
901 int s;
903 if (p[2] == 0) { /* -- => stop processing options */
904 stopoptions = 1;
905 break;
907 for (s = 0; textopts[s].label; s++) {
908 if (!nasm_stricmp(p + 2, textopts[s].label)) {
909 break;
913 switch (s) {
915 case OPT_PREFIX:
916 case OPT_POSTFIX:
918 if (!q) {
919 nasm_error(ERR_NONFATAL | ERR_NOFILE |
920 ERR_USAGE,
921 "option `--%s' requires an argument",
922 p + 2);
923 break;
924 } else {
925 advance = 1, param = q;
928 if (s == OPT_PREFIX) {
929 strncpy(lprefix, param, PREFIX_MAX - 1);
930 lprefix[PREFIX_MAX - 1] = 0;
931 break;
933 if (s == OPT_POSTFIX) {
934 strncpy(lpostfix, param, POSTFIX_MAX - 1);
935 lpostfix[POSTFIX_MAX - 1] = 0;
936 break;
938 break;
940 default:
942 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
943 "unrecognised option `--%s'", p + 2);
944 break;
947 break;
950 default:
951 if (!ofmt->setinfo(GI_SWITCH, &p))
952 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
953 "unrecognised option `-%c'", p[1]);
954 break;
956 } else {
957 if (*inname) {
958 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
959 "more than one input file specified");
960 } else {
961 copy_filename(inname, p);
965 return advance;
968 #define ARG_BUF_DELTA 128
970 static void process_respfile(FILE * rfile)
972 char *buffer, *p, *q, *prevarg;
973 int bufsize, prevargsize;
975 bufsize = prevargsize = ARG_BUF_DELTA;
976 buffer = nasm_malloc(ARG_BUF_DELTA);
977 prevarg = nasm_malloc(ARG_BUF_DELTA);
978 prevarg[0] = '\0';
980 while (1) { /* Loop to handle all lines in file */
981 p = buffer;
982 while (1) { /* Loop to handle long lines */
983 q = fgets(p, bufsize - (p - buffer), rfile);
984 if (!q)
985 break;
986 p += strlen(p);
987 if (p > buffer && p[-1] == '\n')
988 break;
989 if (p - buffer > bufsize - 10) {
990 int offset;
991 offset = p - buffer;
992 bufsize += ARG_BUF_DELTA;
993 buffer = nasm_realloc(buffer, bufsize);
994 p = buffer + offset;
998 if (!q && p == buffer) {
999 if (prevarg[0])
1000 process_arg(prevarg, NULL);
1001 nasm_free(buffer);
1002 nasm_free(prevarg);
1003 return;
1007 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1008 * them are present at the end of the line.
1010 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1012 while (p > buffer && nasm_isspace(p[-1]))
1013 *--p = '\0';
1015 p = buffer;
1016 while (nasm_isspace(*p))
1017 p++;
1019 if (process_arg(prevarg, p))
1020 *p = '\0';
1022 if ((int) strlen(p) > prevargsize - 10) {
1023 prevargsize += ARG_BUF_DELTA;
1024 prevarg = nasm_realloc(prevarg, prevargsize);
1026 strncpy(prevarg, p, prevargsize);
1030 /* Function to process args from a string of args, rather than the
1031 * argv array. Used by the environment variable and response file
1032 * processing.
1034 static void process_args(char *args)
1036 char *p, *q, *arg, *prevarg;
1037 char separator = ' ';
1039 p = args;
1040 if (*p && *p != '-')
1041 separator = *p++;
1042 arg = NULL;
1043 while (*p) {
1044 q = p;
1045 while (*p && *p != separator)
1046 p++;
1047 while (*p == separator)
1048 *p++ = '\0';
1049 prevarg = arg;
1050 arg = q;
1051 if (process_arg(prevarg, arg))
1052 arg = NULL;
1054 if (arg)
1055 process_arg(arg, NULL);
1058 static void process_response_file(const char *file)
1060 char str[2048];
1061 FILE *f = fopen(file, "r");
1062 if (!f) {
1063 perror(file);
1064 exit(-1);
1066 while (fgets(str, sizeof str, f)) {
1067 process_args(str);
1069 fclose(f);
1072 static void parse_cmdline(int argc, char **argv)
1074 FILE *rfile;
1075 char *envreal, *envcopy = NULL, *p, *arg;
1076 int i;
1078 *inname = *outname = *listname = *errname = '\0';
1079 for (i = 0; i <= ERR_WARN_MAX; i++)
1080 warning_on_global[i] = warnings[i].enabled;
1083 * First, process the NASMENV environment variable.
1085 envreal = getenv("NASMENV");
1086 arg = NULL;
1087 if (envreal) {
1088 envcopy = nasm_strdup(envreal);
1089 process_args(envcopy);
1090 nasm_free(envcopy);
1094 * Now process the actual command line.
1096 while (--argc) {
1097 bool advance;
1098 argv++;
1099 if (argv[0][0] == '@') {
1100 /* We have a response file, so process this as a set of
1101 * arguments like the environment variable. This allows us
1102 * to have multiple arguments on a single line, which is
1103 * different to the -@resp file processing below for regular
1104 * NASM.
1106 process_response_file(argv[0]+1);
1107 argc--;
1108 argv++;
1110 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1111 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1112 if (p) {
1113 rfile = fopen(p, "r");
1114 if (rfile) {
1115 process_respfile(rfile);
1116 fclose(rfile);
1117 } else
1118 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1119 "unable to open response file `%s'", p);
1121 } else
1122 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1123 argv += advance, argc -= advance;
1126 /* Look for basic command line typos. This definitely doesn't
1127 catch all errors, but it might help cases of fumbled fingers. */
1128 if (!*inname)
1129 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1130 "no input file specified");
1131 else if (!strcmp(inname, errname) ||
1132 !strcmp(inname, outname) ||
1133 !strcmp(inname, listname) ||
1134 (depend_file && !strcmp(inname, depend_file)))
1135 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1136 "file `%s' is both input and output file",
1137 inname);
1139 if (*errname) {
1140 error_file = fopen(errname, "w");
1141 if (!error_file) {
1142 error_file = stderr; /* Revert to default! */
1143 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1144 "cannot open file `%s' for error messages",
1145 errname);
1150 static enum directives getkw(char **directive, char **value);
1152 static void assemble_file(char *fname, StrList **depend_ptr)
1154 char *directive, *value, *p, *q, *special, *line, debugid[80];
1155 insn output_ins;
1156 int i, validid;
1157 bool rn_error;
1158 int32_t seg;
1159 int64_t offs;
1160 struct tokenval tokval;
1161 expr *e;
1162 int pass_max;
1164 if (cmd_sb == 32 && cmd_cpu < IF_386)
1165 nasm_error(ERR_FATAL, "command line: "
1166 "32-bit segment size requires a higher cpu");
1168 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1169 for (passn = 1; pass0 <= 2; passn++) {
1170 int pass1, pass2;
1171 ldfunc def_label;
1173 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1174 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1175 /* pass0 0, 0, 0, ..., 1, 2 */
1177 def_label = passn > 1 ? redefine_label : define_label;
1179 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1180 cpu = cmd_cpu;
1181 if (pass0 == 2) {
1182 if (*listname)
1183 nasmlist.init(listname, nasm_error);
1185 in_abs_seg = false;
1186 global_offset_changed = 0; /* set by redefine_label */
1187 location.segment = ofmt->section(NULL, pass2, &sb);
1188 globalbits = sb;
1189 if (passn > 1) {
1190 saa_rewind(forwrefs);
1191 forwref = saa_rstruct(forwrefs);
1192 raa_free(offsets);
1193 offsets = raa_init();
1195 preproc->reset(fname, pass1, &nasmlist,
1196 pass1 == 2 ? depend_ptr : NULL);
1197 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1199 globallineno = 0;
1200 if (passn == 1)
1201 location.known = true;
1202 location.offset = offs = GET_CURR_OFFS;
1204 while ((line = preproc->getline())) {
1205 enum directives d;
1206 globallineno++;
1209 * Here we parse our directives; this is not handled by the
1210 * 'real' parser. This really should be a separate function.
1212 directive = line;
1213 d = getkw(&directive, &value);
1214 if (d) {
1215 int err = 0;
1217 switch (d) {
1218 case D_SEGMENT: /* [SEGMENT n] */
1219 case D_SECTION:
1220 seg = ofmt->section(value, pass2, &sb);
1221 if (seg == NO_SEG) {
1222 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1223 "segment name `%s' not recognized",
1224 value);
1225 } else {
1226 in_abs_seg = false;
1227 location.segment = seg;
1229 break;
1230 case D_EXTERN: /* [EXTERN label:special] */
1231 if (*value == '$')
1232 value++; /* skip initial $ if present */
1233 if (pass0 == 2) {
1234 q = value;
1235 while (*q && *q != ':')
1236 q++;
1237 if (*q == ':') {
1238 *q++ = '\0';
1239 ofmt->symdef(value, 0L, 0L, 3, q);
1241 } else if (passn == 1) {
1242 q = value;
1243 validid = true;
1244 if (!isidstart(*q))
1245 validid = false;
1246 while (*q && *q != ':') {
1247 if (!isidchar(*q))
1248 validid = false;
1249 q++;
1251 if (!validid) {
1252 nasm_error(ERR_NONFATAL,
1253 "identifier expected after EXTERN");
1254 break;
1256 if (*q == ':') {
1257 *q++ = '\0';
1258 special = q;
1259 } else
1260 special = NULL;
1261 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1262 int temp = pass0;
1263 pass0 = 1; /* fake pass 1 in labels.c */
1264 declare_as_global(value, special);
1265 define_label(value, seg_alloc(), 0L, NULL,
1266 false, true);
1267 pass0 = temp;
1269 } /* else pass0 == 1 */
1270 break;
1271 case D_BITS: /* [BITS bits] */
1272 globalbits = sb = get_bits(value);
1273 break;
1274 case D_GLOBAL: /* [GLOBAL symbol:special] */
1275 if (*value == '$')
1276 value++; /* skip initial $ if present */
1277 if (pass0 == 2) { /* pass 2 */
1278 q = value;
1279 while (*q && *q != ':')
1280 q++;
1281 if (*q == ':') {
1282 *q++ = '\0';
1283 ofmt->symdef(value, 0L, 0L, 3, q);
1285 } else if (pass2 == 1) { /* pass == 1 */
1286 q = value;
1287 validid = true;
1288 if (!isidstart(*q))
1289 validid = false;
1290 while (*q && *q != ':') {
1291 if (!isidchar(*q))
1292 validid = false;
1293 q++;
1295 if (!validid) {
1296 nasm_error(ERR_NONFATAL,
1297 "identifier expected after GLOBAL");
1298 break;
1300 if (*q == ':') {
1301 *q++ = '\0';
1302 special = q;
1303 } else
1304 special = NULL;
1305 declare_as_global(value, special);
1306 } /* pass == 1 */
1307 break;
1308 case D_COMMON: /* [COMMON symbol size:special] */
1310 int64_t size;
1312 if (*value == '$')
1313 value++; /* skip initial $ if present */
1314 p = value;
1315 validid = true;
1316 if (!isidstart(*p))
1317 validid = false;
1318 while (*p && !nasm_isspace(*p)) {
1319 if (!isidchar(*p))
1320 validid = false;
1321 p++;
1323 if (!validid) {
1324 nasm_error(ERR_NONFATAL,
1325 "identifier expected after COMMON");
1326 break;
1328 if (*p) {
1329 while (*p && nasm_isspace(*p))
1330 *p++ = '\0';
1331 q = p;
1332 while (*q && *q != ':')
1333 q++;
1334 if (*q == ':') {
1335 *q++ = '\0';
1336 special = q;
1337 } else {
1338 special = NULL;
1340 size = readnum(p, &rn_error);
1341 if (rn_error) {
1342 nasm_error(ERR_NONFATAL,
1343 "invalid size specified"
1344 " in COMMON declaration");
1345 break;
1347 } else {
1348 nasm_error(ERR_NONFATAL,
1349 "no size specified in"
1350 " COMMON declaration");
1351 break;
1354 if (pass0 < 2) {
1355 define_common(value, seg_alloc(), size, special);
1356 } else if (pass0 == 2) {
1357 if (special)
1358 ofmt->symdef(value, 0L, 0L, 3, special);
1360 break;
1362 case D_ABSOLUTE: /* [ABSOLUTE address] */
1363 stdscan_reset();
1364 stdscan_bufptr = value;
1365 tokval.t_type = TOKEN_INVALID;
1366 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1367 nasm_error, NULL);
1368 if (e) {
1369 if (!is_reloc(e))
1370 nasm_error(pass0 ==
1371 1 ? ERR_NONFATAL : ERR_PANIC,
1372 "cannot use non-relocatable expression as "
1373 "ABSOLUTE address");
1374 else {
1375 abs_seg = reloc_seg(e);
1376 abs_offset = reloc_value(e);
1378 } else if (passn == 1)
1379 abs_offset = 0x100; /* don't go near zero in case of / */
1380 else
1381 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1382 "in pass two");
1383 in_abs_seg = true;
1384 location.segment = NO_SEG;
1385 break;
1386 case D_DEBUG: /* [DEBUG] */
1387 p = value;
1388 q = debugid;
1389 validid = true;
1390 if (!isidstart(*p))
1391 validid = false;
1392 while (*p && !nasm_isspace(*p)) {
1393 if (!isidchar(*p))
1394 validid = false;
1395 *q++ = *p++;
1397 *q++ = 0;
1398 if (!validid) {
1399 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1400 "identifier expected after DEBUG");
1401 break;
1403 while (*p && nasm_isspace(*p))
1404 p++;
1405 if (pass0 == 2)
1406 dfmt->debug_directive(debugid, p);
1407 break;
1408 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1409 while (*value && nasm_isspace(*value))
1410 value++;
1412 switch(*value) {
1413 case '-': validid = 0; value++; break;
1414 case '+': validid = 1; value++; break;
1415 case '*': validid = 2; value++; break;
1416 default: validid = 1; break;
1419 for (i = 1; i <= ERR_WARN_MAX; i++)
1420 if (!nasm_stricmp(value, warnings[i].name))
1421 break;
1422 if (i <= ERR_WARN_MAX) {
1423 switch(validid) {
1424 case 0:
1425 warning_on[i] = false;
1426 break;
1427 case 1:
1428 warning_on[i] = true;
1429 break;
1430 case 2:
1431 warning_on[i] = warning_on_global[i];
1432 break;
1435 else
1436 nasm_error(ERR_NONFATAL,
1437 "invalid warning id in WARNING directive");
1438 break;
1439 case D_CPU: /* [CPU] */
1440 cpu = get_cpu(value);
1441 break;
1442 case D_LIST: /* [LIST {+|-}] */
1443 while (*value && nasm_isspace(*value))
1444 value++;
1446 if (*value == '+') {
1447 user_nolist = 0;
1448 } else {
1449 if (*value == '-') {
1450 user_nolist = 1;
1451 } else {
1452 err = 1;
1455 break;
1456 case D_DEFAULT: /* [DEFAULT] */
1457 stdscan_reset();
1458 stdscan_bufptr = value;
1459 tokval.t_type = TOKEN_INVALID;
1460 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1461 switch ((int)tokval.t_integer) {
1462 case S_REL:
1463 globalrel = 1;
1464 break;
1465 case S_ABS:
1466 globalrel = 0;
1467 break;
1468 default:
1469 err = 1;
1470 break;
1472 } else {
1473 err = 1;
1475 break;
1476 case D_FLOAT:
1477 if (float_option(value)) {
1478 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1479 "unknown 'float' directive: %s",
1480 value);
1482 break;
1483 default:
1484 if (!d || !ofmt->directive(d, value, pass2))
1485 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1486 "unrecognised directive [%s]",
1487 directive);
1488 break;
1490 if (err) {
1491 nasm_error(ERR_NONFATAL,
1492 "invalid parameter to [%s] directive",
1493 directive);
1495 } else { /* it isn't a directive */
1496 parse_line(pass1, line, &output_ins, def_label);
1498 if (optimizing > 0) {
1499 if (forwref != NULL && globallineno == forwref->lineno) {
1500 output_ins.forw_ref = true;
1501 do {
1502 output_ins.oprs[forwref->operand].opflags |=
1503 OPFLAG_FORWARD;
1504 forwref = saa_rstruct(forwrefs);
1505 } while (forwref != NULL
1506 && forwref->lineno == globallineno);
1507 } else
1508 output_ins.forw_ref = false;
1510 if (output_ins.forw_ref) {
1511 if (passn == 1) {
1512 for (i = 0; i < output_ins.operands; i++) {
1513 if (output_ins.oprs[i].
1514 opflags & OPFLAG_FORWARD) {
1515 struct forwrefinfo *fwinf =
1516 (struct forwrefinfo *)
1517 saa_wstruct(forwrefs);
1518 fwinf->lineno = globallineno;
1519 fwinf->operand = i;
1526 /* forw_ref */
1527 if (output_ins.opcode == I_EQU) {
1528 if (pass1 == 1) {
1530 * Special `..' EQUs get processed in pass two,
1531 * except `..@' macro-processor EQUs which are done
1532 * in the normal place.
1534 if (!output_ins.label)
1535 nasm_error(ERR_NONFATAL,
1536 "EQU not preceded by label");
1538 else if (output_ins.label[0] != '.' ||
1539 output_ins.label[1] != '.' ||
1540 output_ins.label[2] == '@') {
1541 if (output_ins.operands == 1 &&
1542 (output_ins.oprs[0].type & IMMEDIATE) &&
1543 output_ins.oprs[0].wrt == NO_SEG) {
1544 bool isext = !!(output_ins.oprs[0].opflags
1545 & OPFLAG_EXTERN);
1546 def_label(output_ins.label,
1547 output_ins.oprs[0].segment,
1548 output_ins.oprs[0].offset, NULL,
1549 false, isext);
1550 } else if (output_ins.operands == 2
1551 && (output_ins.oprs[0].type & IMMEDIATE)
1552 && (output_ins.oprs[0].type & COLON)
1553 && output_ins.oprs[0].segment == NO_SEG
1554 && output_ins.oprs[0].wrt == NO_SEG
1555 && (output_ins.oprs[1].type & IMMEDIATE)
1556 && output_ins.oprs[1].segment == NO_SEG
1557 && output_ins.oprs[1].wrt == NO_SEG) {
1558 def_label(output_ins.label,
1559 output_ins.oprs[0].offset | SEG_ABS,
1560 output_ins.oprs[1].offset,
1561 NULL, false, false);
1562 } else
1563 nasm_error(ERR_NONFATAL,
1564 "bad syntax for EQU");
1566 } else {
1568 * Special `..' EQUs get processed here, except
1569 * `..@' macro processor EQUs which are done above.
1571 if (output_ins.label[0] == '.' &&
1572 output_ins.label[1] == '.' &&
1573 output_ins.label[2] != '@') {
1574 if (output_ins.operands == 1 &&
1575 (output_ins.oprs[0].type & IMMEDIATE)) {
1576 define_label(output_ins.label,
1577 output_ins.oprs[0].segment,
1578 output_ins.oprs[0].offset,
1579 NULL, false, false);
1580 } else if (output_ins.operands == 2
1581 && (output_ins.oprs[0].
1582 type & IMMEDIATE)
1583 && (output_ins.oprs[0].type & COLON)
1584 && output_ins.oprs[0].segment ==
1585 NO_SEG
1586 && (output_ins.oprs[1].
1587 type & IMMEDIATE)
1588 && output_ins.oprs[1].segment ==
1589 NO_SEG) {
1590 define_label(output_ins.label,
1591 output_ins.oprs[0].
1592 offset | SEG_ABS,
1593 output_ins.oprs[1].offset,
1594 NULL, false, false);
1595 } else
1596 nasm_error(ERR_NONFATAL,
1597 "bad syntax for EQU");
1600 } else { /* instruction isn't an EQU */
1602 if (pass1 == 1) {
1604 int64_t l = insn_size(location.segment, offs, sb, cpu,
1605 &output_ins, nasm_error);
1607 /* if (using_debug_info) && output_ins.opcode != -1) */
1608 if (using_debug_info)
1609 { /* fbk 03/25/01 */
1610 /* this is done here so we can do debug type info */
1611 int32_t typeinfo =
1612 TYS_ELEMENTS(output_ins.operands);
1613 switch (output_ins.opcode) {
1614 case I_RESB:
1615 typeinfo =
1616 TYS_ELEMENTS(output_ins.oprs[0].
1617 offset) | TY_BYTE;
1618 break;
1619 case I_RESW:
1620 typeinfo =
1621 TYS_ELEMENTS(output_ins.oprs[0].
1622 offset) | TY_WORD;
1623 break;
1624 case I_RESD:
1625 typeinfo =
1626 TYS_ELEMENTS(output_ins.oprs[0].
1627 offset) | TY_DWORD;
1628 break;
1629 case I_RESQ:
1630 typeinfo =
1631 TYS_ELEMENTS(output_ins.oprs[0].
1632 offset) | TY_QWORD;
1633 break;
1634 case I_REST:
1635 typeinfo =
1636 TYS_ELEMENTS(output_ins.oprs[0].
1637 offset) | TY_TBYTE;
1638 break;
1639 case I_RESO:
1640 typeinfo =
1641 TYS_ELEMENTS(output_ins.oprs[0].
1642 offset) | TY_OWORD;
1643 break;
1644 case I_RESY:
1645 typeinfo =
1646 TYS_ELEMENTS(output_ins.oprs[0].
1647 offset) | TY_YWORD;
1648 break;
1649 case I_DB:
1650 typeinfo |= TY_BYTE;
1651 break;
1652 case I_DW:
1653 typeinfo |= TY_WORD;
1654 break;
1655 case I_DD:
1656 if (output_ins.eops_float)
1657 typeinfo |= TY_FLOAT;
1658 else
1659 typeinfo |= TY_DWORD;
1660 break;
1661 case I_DQ:
1662 typeinfo |= TY_QWORD;
1663 break;
1664 case I_DT:
1665 typeinfo |= TY_TBYTE;
1666 break;
1667 case I_DO:
1668 typeinfo |= TY_OWORD;
1669 break;
1670 case I_DY:
1671 typeinfo |= TY_YWORD;
1672 break;
1673 default:
1674 typeinfo = TY_LABEL;
1678 dfmt->debug_typevalue(typeinfo);
1680 if (l != -1) {
1681 offs += l;
1682 SET_CURR_OFFS(offs);
1685 * else l == -1 => invalid instruction, which will be
1686 * flagged as an error on pass 2
1689 } else {
1690 offs += assemble(location.segment, offs, sb, cpu,
1691 &output_ins, ofmt, nasm_error,
1692 &nasmlist);
1693 SET_CURR_OFFS(offs);
1696 } /* not an EQU */
1697 cleanup_insn(&output_ins);
1699 nasm_free(line);
1700 location.offset = offs = GET_CURR_OFFS;
1701 } /* end while (line = preproc->getline... */
1703 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1704 nasm_error(ERR_NONFATAL,
1705 "phase error detected at end of assembly.");
1707 if (pass1 == 1)
1708 preproc->cleanup(1);
1710 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1711 pass0++;
1712 } else if (global_offset_changed &&
1713 global_offset_changed < prev_offset_changed) {
1714 prev_offset_changed = global_offset_changed;
1715 stall_count = 0;
1716 } else {
1717 stall_count++;
1720 if (terminate_after_phase)
1721 break;
1723 if ((stall_count > 997) || (passn >= pass_max)) {
1724 /* We get here if the labels don't converge
1725 * Example: FOO equ FOO + 1
1727 nasm_error(ERR_NONFATAL,
1728 "Can't find valid values for all labels "
1729 "after %d passes, giving up.", passn);
1730 nasm_error(ERR_NONFATAL,
1731 "Possible causes: recursive EQUs, macro abuse.");
1732 break;
1736 preproc->cleanup(0);
1737 nasmlist.cleanup();
1738 if (!terminate_after_phase && opt_verbose_info) {
1739 /* -On and -Ov switches */
1740 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1744 static enum directives getkw(char **directive, char **value)
1746 char *p, *q, *buf;
1748 buf = *directive;
1750 /* allow leading spaces or tabs */
1751 while (*buf == ' ' || *buf == '\t')
1752 buf++;
1754 if (*buf != '[')
1755 return 0;
1757 p = buf;
1759 while (*p && *p != ']')
1760 p++;
1762 if (!*p)
1763 return 0;
1765 q = p++;
1767 while (*p && *p != ';') {
1768 if (!nasm_isspace(*p))
1769 return 0;
1770 p++;
1772 q[1] = '\0';
1774 *directive = p = buf + 1;
1775 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1776 buf++;
1777 if (*buf == ']') {
1778 *buf = '\0';
1779 *value = buf;
1780 } else {
1781 *buf++ = '\0';
1782 while (nasm_isspace(*buf))
1783 buf++; /* beppu - skip leading whitespace */
1784 *value = buf;
1785 while (*buf != ']')
1786 buf++;
1787 *buf++ = '\0';
1790 return find_directive(*directive);
1794 * gnu style error reporting
1795 * This function prints an error message to error_file in the
1796 * style used by GNU. An example would be:
1797 * file.asm:50: error: blah blah blah
1798 * where file.asm is the name of the file, 50 is the line number on
1799 * which the error occurs (or is detected) and "error:" is one of
1800 * the possible optional diagnostics -- it can be "error" or "warning"
1801 * or something else. Finally the line terminates with the actual
1802 * error message.
1804 * @param severity the severity of the warning or error
1805 * @param fmt the printf style format string
1807 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1809 char *currentfile = NULL;
1810 int32_t lineno = 0;
1812 if (is_suppressed_warning(severity))
1813 return;
1815 if (!(severity & ERR_NOFILE))
1816 src_get(&lineno, &currentfile);
1818 if (currentfile) {
1819 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1820 nasm_free(currentfile);
1821 } else {
1822 fputs("nasm: ", error_file);
1825 nasm_verror_common(severity, fmt, ap);
1829 * MS style error reporting
1830 * This function prints an error message to error_file in the
1831 * style used by Visual C and some other Microsoft tools. An example
1832 * would be:
1833 * file.asm(50) : error: blah blah blah
1834 * where file.asm is the name of the file, 50 is the line number on
1835 * which the error occurs (or is detected) and "error:" is one of
1836 * the possible optional diagnostics -- it can be "error" or "warning"
1837 * or something else. Finally the line terminates with the actual
1838 * error message.
1840 * @param severity the severity of the warning or error
1841 * @param fmt the printf style format string
1843 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1845 char *currentfile = NULL;
1846 int32_t lineno = 0;
1848 if (is_suppressed_warning(severity))
1849 return;
1851 if (!(severity & ERR_NOFILE))
1852 src_get(&lineno, &currentfile);
1854 if (currentfile) {
1855 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1856 nasm_free(currentfile);
1857 } else {
1858 fputs("nasm: ", error_file);
1861 nasm_verror_common(severity, fmt, ap);
1865 * check for supressed warning
1866 * checks for suppressed warning or pass one only warning and we're
1867 * not in pass 1
1869 * @param severity the severity of the warning or error
1870 * @return true if we should abort error/warning printing
1872 static bool is_suppressed_warning(int severity)
1875 * See if it's a suppressed warning.
1877 return (severity & ERR_MASK) == ERR_WARNING &&
1878 (((severity & ERR_WARN_MASK) != 0 &&
1879 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1880 /* See if it's a pass-one only warning and we're not in pass one. */
1881 ((severity & ERR_PASS1) && pass0 != 1) ||
1882 ((severity & ERR_PASS2) && pass0 != 2));
1886 * common error reporting
1887 * This is the common back end of the error reporting schemes currently
1888 * implemented. It prints the nature of the warning and then the
1889 * specific error message to error_file and may or may not return. It
1890 * doesn't return if the error severity is a "panic" or "debug" type.
1892 * @param severity the severity of the warning or error
1893 * @param fmt the printf style format string
1895 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1897 char msg[1024];
1898 const char *pfx;
1900 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1901 case ERR_WARNING:
1902 pfx = "warning: ";
1903 break;
1904 case ERR_NONFATAL:
1905 pfx = "error: ";
1906 break;
1907 case ERR_FATAL:
1908 pfx = "fatal: ";
1909 break;
1910 case ERR_PANIC:
1911 pfx = "panic: ";
1912 break;
1913 case ERR_DEBUG:
1914 pfx = "debug: ";
1915 break;
1916 default:
1917 pfx = "";
1918 break;
1921 vsnprintf(msg, sizeof msg, fmt, args);
1923 fprintf(error_file, "%s%s\n", pfx, msg);
1925 if (*listname)
1926 nasmlist.error(severity, pfx, msg);
1928 if (severity & ERR_USAGE)
1929 want_usage = true;
1931 switch (severity & ERR_MASK) {
1932 case ERR_DEBUG:
1933 /* no further action, by definition */
1934 break;
1935 case ERR_WARNING:
1936 if (warning_on[0]) /* Treat warnings as errors */
1937 terminate_after_phase = true;
1938 break;
1939 case ERR_NONFATAL:
1940 terminate_after_phase = true;
1941 break;
1942 case ERR_FATAL:
1943 if (ofile) {
1944 fclose(ofile);
1945 remove(outname);
1946 ofile = NULL;
1948 if (want_usage)
1949 usage();
1950 exit(1); /* instantly die */
1951 break; /* placate silly compilers */
1952 case ERR_PANIC:
1953 fflush(NULL);
1954 /* abort(); *//* halt, catch fire, and dump core */
1955 exit(3);
1956 break;
1960 static void usage(void)
1962 fputs("type `nasm -h' for help\n", error_file);
1965 #define BUF_DELTA 512
1967 static FILE *no_pp_fp;
1968 static ListGen *no_pp_list;
1969 static int32_t no_pp_lineinc;
1971 static void no_pp_reset(char *file, int pass, ListGen * listgen,
1972 StrList **deplist)
1974 src_set_fname(nasm_strdup(file));
1975 src_set_linnum(0);
1976 no_pp_lineinc = 1;
1977 no_pp_fp = fopen(file, "r");
1978 if (!no_pp_fp)
1979 nasm_error(ERR_FATAL | ERR_NOFILE,
1980 "unable to open input file `%s'", file);
1981 no_pp_list = listgen;
1982 (void)pass; /* placate compilers */
1984 if (deplist) {
1985 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1986 sl->next = NULL;
1987 strcpy(sl->str, file);
1988 *deplist = sl;
1992 static char *no_pp_getline(void)
1994 char *buffer, *p, *q;
1995 int bufsize;
1997 bufsize = BUF_DELTA;
1998 buffer = nasm_malloc(BUF_DELTA);
1999 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2001 while (1) { /* Loop to handle %line */
2003 p = buffer;
2004 while (1) { /* Loop to handle long lines */
2005 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2006 if (!q)
2007 break;
2008 p += strlen(p);
2009 if (p > buffer && p[-1] == '\n')
2010 break;
2011 if (p - buffer > bufsize - 10) {
2012 int offset;
2013 offset = p - buffer;
2014 bufsize += BUF_DELTA;
2015 buffer = nasm_realloc(buffer, bufsize);
2016 p = buffer + offset;
2020 if (!q && p == buffer) {
2021 nasm_free(buffer);
2022 return NULL;
2026 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2027 * them are present at the end of the line.
2029 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2031 if (!nasm_strnicmp(buffer, "%line", 5)) {
2032 int32_t ln;
2033 int li;
2034 char *nm = nasm_malloc(strlen(buffer));
2035 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2036 nasm_free(src_set_fname(nm));
2037 src_set_linnum(ln);
2038 no_pp_lineinc = li;
2039 continue;
2041 nasm_free(nm);
2043 break;
2046 no_pp_list->line(LIST_READ, buffer);
2048 return buffer;
2051 static void no_pp_cleanup(int pass)
2053 (void)pass; /* placate GCC */
2054 fclose(no_pp_fp);
2057 static uint32_t get_cpu(char *value)
2059 if (!strcmp(value, "8086"))
2060 return IF_8086;
2061 if (!strcmp(value, "186"))
2062 return IF_186;
2063 if (!strcmp(value, "286"))
2064 return IF_286;
2065 if (!strcmp(value, "386"))
2066 return IF_386;
2067 if (!strcmp(value, "486"))
2068 return IF_486;
2069 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2070 return IF_PENT;
2071 if (!strcmp(value, "686") ||
2072 !nasm_stricmp(value, "ppro") ||
2073 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2074 return IF_P6;
2075 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2076 return IF_KATMAI;
2077 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2078 !nasm_stricmp(value, "willamette"))
2079 return IF_WILLAMETTE;
2080 if (!nasm_stricmp(value, "prescott"))
2081 return IF_PRESCOTT;
2082 if (!nasm_stricmp(value, "x64") ||
2083 !nasm_stricmp(value, "x86-64"))
2084 return IF_X86_64;
2085 if (!nasm_stricmp(value, "ia64") ||
2086 !nasm_stricmp(value, "ia-64") ||
2087 !nasm_stricmp(value, "itanium") ||
2088 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2089 return IF_IA64;
2091 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2092 "unknown 'cpu' type");
2094 return IF_PLEVEL; /* the maximum level */
2097 static int get_bits(char *value)
2099 int i;
2101 if ((i = atoi(value)) == 16)
2102 return i; /* set for a 16-bit segment */
2103 else if (i == 32) {
2104 if (cpu < IF_386) {
2105 nasm_error(ERR_NONFATAL,
2106 "cannot specify 32-bit segment on processor below a 386");
2107 i = 16;
2109 } else if (i == 64) {
2110 if (cpu < IF_X86_64) {
2111 nasm_error(ERR_NONFATAL,
2112 "cannot specify 64-bit segment on processor below an x86-64");
2113 i = 16;
2115 if (i != maxbits) {
2116 nasm_error(ERR_NONFATAL,
2117 "%s output format does not support 64-bit code",
2118 ofmt->shortname);
2119 i = 16;
2121 } else {
2122 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2123 "`%s' is not a valid segment size; must be 16, 32 or 64",
2124 value);
2125 i = 16;
2127 return i;
2130 /* end of nasm.c */