Remove function pointers in output, simplify error handling
[nasm/sigaren-mirror.git] / nasm.c
blob7bcdc5af38aeeeed34bf30cc6f96bdfdb83f61f6
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, efunc, evalfunc, 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 for (l = list; l; l = l->next) {
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 for (l = list; l; l = nl) {
299 if (depend_emit_phony)
300 fprintf(deps, "%s:\n\n", l->str);
302 nl = l->next;
303 nasm_free(l);
306 if (deps != stdout)
307 fclose(deps);
310 int main(int argc, char **argv)
312 StrList *depend_list = NULL, **depend_ptr;
314 time(&official_compile_time);
316 pass0 = 0;
317 want_usage = terminate_after_phase = false;
318 nasm_set_verror(nasm_verror_gnu);
320 error_file = stderr;
322 tolower_init();
324 nasm_init_malloc_error();
325 offsets = raa_init();
326 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
328 preproc = &nasmpp;
329 operating_mode = op_normal;
331 seg_init();
333 /* Define some macros dependent on the runtime, but not
334 on the command line. */
335 define_macros_early();
337 parse_cmdline(argc, argv);
339 if (terminate_after_phase) {
340 if (want_usage)
341 usage();
342 return 1;
345 /* If debugging info is disabled, suppress any debug calls */
346 if (!using_debug_info)
347 ofmt->current_dfmt = &null_debug_form;
349 if (ofmt->stdmac)
350 pp_extra_stdmac(ofmt->stdmac);
351 parser_global_info(ofmt, &location);
352 eval_global_info(ofmt, lookup_label, &location);
354 /* define some macros dependent of command-line */
355 define_macros_late();
357 depend_ptr = (depend_file || (operating_mode == op_depend))
358 ? &depend_list : NULL;
359 if (!depend_target)
360 depend_target = outname;
362 switch (operating_mode) {
363 case op_depend:
365 char *line;
367 if (depend_missing_ok)
368 pp_include_path(NULL); /* "assume generated" */
370 preproc->reset(inname, 0, nasm_error, evaluate, &nasmlist,
371 depend_ptr);
372 if (outname[0] == '\0')
373 ofmt->filename(inname, outname);
374 ofile = NULL;
375 while ((line = preproc->getline()))
376 nasm_free(line);
377 preproc->cleanup(0);
379 break;
381 case op_preprocess:
383 char *line;
384 char *file_name = NULL;
385 int32_t prior_linnum = 0;
386 int lineinc = 0;
388 if (*outname) {
389 ofile = fopen(outname, "w");
390 if (!ofile)
391 nasm_error(ERR_FATAL | ERR_NOFILE,
392 "unable to open output file `%s'",
393 outname);
394 } else
395 ofile = NULL;
397 location.known = false;
399 /* pass = 1; */
400 preproc->reset(inname, 3, nasm_error, evaluate, &nasmlist,
401 depend_ptr);
403 while ((line = preproc->getline())) {
405 * We generate %line directives if needed for later programs
407 int32_t linnum = prior_linnum += lineinc;
408 int altline = src_get(&linnum, &file_name);
409 if (altline) {
410 if (altline == 1 && lineinc == 1)
411 nasm_fputs("", ofile);
412 else {
413 lineinc = (altline != -1 || lineinc != 1);
414 fprintf(ofile ? ofile : stdout,
415 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
416 file_name);
418 prior_linnum = linnum;
420 nasm_fputs(line, ofile);
421 nasm_free(line);
423 nasm_free(file_name);
424 preproc->cleanup(0);
425 if (ofile)
426 fclose(ofile);
427 if (ofile && terminate_after_phase)
428 remove(outname);
429 ofile = NULL;
431 break;
433 case op_normal:
436 * We must call ofmt->filename _anyway_, even if the user
437 * has specified their own output file, because some
438 * formats (eg OBJ and COFF) use ofmt->filename to find out
439 * the name of the input file and then put that inside the
440 * file.
442 ofmt->filename(inname, outname);
444 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
445 if (!ofile) {
446 nasm_error(ERR_FATAL | ERR_NOFILE,
447 "unable to open output file `%s'", outname);
451 * We must call init_labels() before ofmt->init() since
452 * some object formats will want to define labels in their
453 * init routines. (eg OS/2 defines the FLAT group)
455 init_labels();
457 ofmt->init();
458 dfmt = ofmt->current_dfmt;
459 dfmt->init();
461 assemble_file(inname, depend_ptr);
463 if (!terminate_after_phase) {
464 ofmt->cleanup(using_debug_info);
465 cleanup_labels();
466 fflush(ofile);
467 if (ferror(ofile)) {
468 nasm_error(ERR_NONFATAL|ERR_NOFILE,
469 "write error on output file `%s'", outname);
473 if (ofile) {
474 fclose(ofile);
475 if (terminate_after_phase)
476 remove(outname);
477 ofile = NULL;
480 break;
483 if (depend_list && !terminate_after_phase)
484 emit_dependencies(depend_list);
486 if (want_usage)
487 usage();
489 raa_free(offsets);
490 saa_free(forwrefs);
491 eval_cleanup();
492 stdscan_cleanup();
494 return terminate_after_phase;
498 * Get a parameter for a command line option.
499 * First arg must be in the form of e.g. -f...
501 static char *get_param(char *p, char *q, bool *advance)
503 *advance = false;
504 if (p[2]) { /* the parameter's in the option */
505 p += 2;
506 while (nasm_isspace(*p))
507 p++;
508 return p;
510 if (q && q[0]) {
511 *advance = true;
512 return q;
514 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
515 "option `-%c' requires an argument", p[1]);
516 return NULL;
520 * Copy a filename
522 static void copy_filename(char *dst, const char *src)
524 size_t len = strlen(src);
526 if (len >= (size_t)FILENAME_MAX) {
527 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
528 return;
530 strncpy(dst, src, FILENAME_MAX);
534 * Convert a string to Make-safe form
536 static char *quote_for_make(const char *str)
538 const char *p;
539 char *os, *q;
541 size_t n = 1; /* Terminating zero */
542 size_t nbs = 0;
544 if (!str)
545 return NULL;
547 for (p = str; *p; p++) {
548 switch (*p) {
549 case ' ':
550 case '\t':
551 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
552 n += nbs + 2;
553 nbs = 0;
554 break;
555 case '$':
556 case '#':
557 nbs = 0;
558 n += 2;
559 break;
560 case '\\':
561 nbs++;
562 n++;
563 break;
564 default:
565 nbs = 0;
566 n++;
567 break;
571 /* Convert N backslashes at the end of filename to 2N backslashes */
572 if (nbs)
573 n += nbs;
575 os = q = nasm_malloc(n);
577 nbs = 0;
578 for (p = str; *p; p++) {
579 switch (*p) {
580 case ' ':
581 case '\t':
582 while (nbs--)
583 *q++ = '\\';
584 *q++ = '\\';
585 *q++ = *p;
586 break;
587 case '$':
588 *q++ = *p;
589 *q++ = *p;
590 nbs = 0;
591 break;
592 case '#':
593 *q++ = '\\';
594 *q++ = *p;
595 nbs = 0;
596 break;
597 case '\\':
598 *q++ = *p;
599 nbs++;
600 break;
601 default:
602 *q++ = *p;
603 nbs = 0;
604 break;
607 while (nbs--)
608 *q++ = '\\';
610 *q = '\0';
612 return os;
615 struct textargs {
616 const char *label;
617 int value;
620 #define OPT_PREFIX 0
621 #define OPT_POSTFIX 1
622 struct textargs textopts[] = {
623 {"prefix", OPT_PREFIX},
624 {"postfix", OPT_POSTFIX},
625 {NULL, 0}
628 static bool stopoptions = false;
629 static bool process_arg(char *p, char *q)
631 char *param;
632 int i;
633 bool advance = false;
634 bool do_warn;
636 if (!p || !p[0])
637 return false;
639 if (p[0] == '-' && !stopoptions) {
640 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
641 /* These parameters take values */
642 if (!(param = get_param(p, q, &advance)))
643 return advance;
646 switch (p[1]) {
647 case 's':
648 error_file = stdout;
649 break;
651 case 'o': /* output file */
652 copy_filename(outname, param);
653 break;
655 case 'f': /* output format */
656 ofmt = ofmt_find(param);
657 if (!ofmt) {
658 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
659 "unrecognised output format `%s' - "
660 "use -hf for a list", param);
662 break;
664 case 'O': /* Optimization level */
666 int opt;
668 if (!*param) {
669 /* Naked -O == -Ox */
670 optimizing = INT_MAX >> 1; /* Almost unlimited */
671 } else {
672 while (*param) {
673 switch (*param) {
674 case '0': case '1': case '2': case '3': case '4':
675 case '5': case '6': case '7': case '8': case '9':
676 opt = strtoul(param, &param, 10);
678 /* -O0 -> optimizing == -1, 0.98 behaviour */
679 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
680 if (opt < 2)
681 optimizing = opt - 1;
682 else
683 optimizing = opt;
684 break;
686 case 'v':
687 case '+':
688 param++;
689 opt_verbose_info = true;
690 break;
692 case 'x':
693 param++;
694 optimizing = INT_MAX >> 1; /* Almost unlimited */
695 break;
697 default:
698 nasm_error(ERR_FATAL,
699 "unknown optimization option -O%c\n",
700 *param);
701 break;
705 break;
708 case 'p': /* pre-include */
709 case 'P':
710 pp_pre_include(param);
711 break;
713 case 'd': /* pre-define */
714 case 'D':
715 pp_pre_define(param);
716 break;
718 case 'u': /* un-define */
719 case 'U':
720 pp_pre_undefine(param);
721 break;
723 case 'i': /* include search path */
724 case 'I':
725 pp_include_path(param);
726 break;
728 case 'l': /* listing file */
729 copy_filename(listname, param);
730 break;
732 case 'Z': /* error messages file */
733 strcpy(errname, param);
734 break;
736 case 'F': /* specify debug format */
737 ofmt->current_dfmt = dfmt_find(ofmt, param);
738 if (!ofmt->current_dfmt) {
739 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
740 "unrecognized debug format `%s' for"
741 " output format `%s'",
742 param, ofmt->shortname);
744 using_debug_info = true;
745 break;
747 case 'X': /* specify error reporting format */
748 if (nasm_stricmp("vc", param) == 0)
749 nasm_set_verror(nasm_verror_vc);
750 else if (nasm_stricmp("gnu", param) == 0)
751 nasm_set_verror(nasm_verror_gnu);
752 else
753 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
754 "unrecognized error reporting format `%s'",
755 param);
756 break;
758 case 'g':
759 using_debug_info = true;
760 break;
762 case 'h':
763 printf
764 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
765 "[-l listfile]\n"
766 " [options...] [--] filename\n"
767 " or nasm -v for version info\n\n"
768 " -t assemble in SciTech TASM compatible mode\n"
769 " -g generate debug information in selected format.\n");
770 printf
771 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
772 " -a don't preprocess (assemble only)\n"
773 " -M generate Makefile dependencies on stdout\n"
774 " -MG d:o, missing files assumed generated\n\n"
775 " -Z<file> redirect error messages to file\n"
776 " -s redirect error messages to stdout\n\n"
777 " -F format select a debugging format\n\n"
778 " -I<path> adds a pathname to the include file path\n");
779 printf
780 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
781 " -P<file> pre-includes a file\n"
782 " -D<macro>[=<value>] pre-defines a macro\n"
783 " -U<macro> undefines a macro\n"
784 " -X<format> specifies error reporting format (gnu or vc)\n"
785 " -w+foo enables warning foo (equiv. -Wfoo)\n"
786 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
787 "Warnings:\n");
788 for (i = 0; i <= ERR_WARN_MAX; i++)
789 printf(" %-23s %s (default %s)\n",
790 warnings[i].name, warnings[i].help,
791 warnings[i].enabled ? "on" : "off");
792 printf
793 ("\nresponse files should contain command line parameters"
794 ", one per line.\n");
795 if (p[2] == 'f') {
796 printf("\nvalid output formats for -f are"
797 " (`*' denotes default):\n");
798 ofmt_list(ofmt, stdout);
799 } else {
800 printf("\nFor a list of valid output formats, use -hf.\n");
801 printf("For a list of debug formats, use -f <form> -y.\n");
803 exit(0); /* never need usage message here */
804 break;
806 case 'y':
807 printf("\nvalid debug formats for '%s' output format are"
808 " ('*' denotes default):\n", ofmt->shortname);
809 dfmt_list(ofmt, stdout);
810 exit(0);
811 break;
813 case 't':
814 tasm_compatible_mode = true;
815 break;
817 case 'v':
818 printf("NASM version %s compiled on %s%s\n",
819 nasm_version, nasm_date, nasm_compile_options);
820 exit(0); /* never need usage message here */
821 break;
823 case 'e': /* preprocess only */
824 case 'E':
825 operating_mode = op_preprocess;
826 break;
828 case 'a': /* assemble only - don't preprocess */
829 preproc = &no_pp;
830 break;
832 case 'W':
833 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
834 do_warn = false;
835 param += 3;
836 } else {
837 do_warn = true;
839 goto set_warning;
841 case 'w':
842 if (param[0] != '+' && param[0] != '-') {
843 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
844 "invalid option to `-w'");
845 break;
847 do_warn = (param[0] == '+');
848 param++;
849 goto set_warning;
850 set_warning:
851 for (i = 0; i <= ERR_WARN_MAX; i++)
852 if (!nasm_stricmp(param, warnings[i].name))
853 break;
854 if (i <= ERR_WARN_MAX)
855 warning_on_global[i] = do_warn;
856 else if (!nasm_stricmp(param, "all"))
857 for (i = 1; i <= ERR_WARN_MAX; i++)
858 warning_on_global[i] = do_warn;
859 else if (!nasm_stricmp(param, "none"))
860 for (i = 1; i <= ERR_WARN_MAX; i++)
861 warning_on_global[i] = !do_warn;
862 else
863 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
864 "invalid warning `%s'", param);
865 break;
867 case 'M':
868 switch (p[2]) {
869 case 0:
870 operating_mode = op_depend;
871 break;
872 case 'G':
873 operating_mode = op_depend;
874 depend_missing_ok = true;
875 break;
876 case 'P':
877 depend_emit_phony = true;
878 break;
879 case 'D':
880 depend_file = q;
881 advance = true;
882 break;
883 case 'T':
884 depend_target = q;
885 advance = true;
886 break;
887 case 'Q':
888 depend_target = quote_for_make(q);
889 advance = true;
890 break;
891 default:
892 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
893 "unknown dependency option `-M%c'", p[2]);
894 break;
896 if (advance && (!q || !q[0])) {
897 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
898 "option `-M%c' requires a parameter", p[2]);
899 break;
901 break;
903 case '-':
905 int s;
907 if (p[2] == 0) { /* -- => stop processing options */
908 stopoptions = 1;
909 break;
911 for (s = 0; textopts[s].label; s++) {
912 if (!nasm_stricmp(p + 2, textopts[s].label)) {
913 break;
917 switch (s) {
919 case OPT_PREFIX:
920 case OPT_POSTFIX:
922 if (!q) {
923 nasm_error(ERR_NONFATAL | ERR_NOFILE |
924 ERR_USAGE,
925 "option `--%s' requires an argument",
926 p + 2);
927 break;
928 } else {
929 advance = 1, param = q;
932 if (s == OPT_PREFIX) {
933 strncpy(lprefix, param, PREFIX_MAX - 1);
934 lprefix[PREFIX_MAX - 1] = 0;
935 break;
937 if (s == OPT_POSTFIX) {
938 strncpy(lpostfix, param, POSTFIX_MAX - 1);
939 lpostfix[POSTFIX_MAX - 1] = 0;
940 break;
942 break;
944 default:
946 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
947 "unrecognised option `--%s'", p + 2);
948 break;
951 break;
954 default:
955 if (!ofmt->setinfo(GI_SWITCH, &p))
956 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
957 "unrecognised option `-%c'", p[1]);
958 break;
960 } else {
961 if (*inname) {
962 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
963 "more than one input file specified");
964 } else {
965 copy_filename(inname, p);
969 return advance;
972 #define ARG_BUF_DELTA 128
974 static void process_respfile(FILE * rfile)
976 char *buffer, *p, *q, *prevarg;
977 int bufsize, prevargsize;
979 bufsize = prevargsize = ARG_BUF_DELTA;
980 buffer = nasm_malloc(ARG_BUF_DELTA);
981 prevarg = nasm_malloc(ARG_BUF_DELTA);
982 prevarg[0] = '\0';
984 while (1) { /* Loop to handle all lines in file */
985 p = buffer;
986 while (1) { /* Loop to handle long lines */
987 q = fgets(p, bufsize - (p - buffer), rfile);
988 if (!q)
989 break;
990 p += strlen(p);
991 if (p > buffer && p[-1] == '\n')
992 break;
993 if (p - buffer > bufsize - 10) {
994 int offset;
995 offset = p - buffer;
996 bufsize += ARG_BUF_DELTA;
997 buffer = nasm_realloc(buffer, bufsize);
998 p = buffer + offset;
1002 if (!q && p == buffer) {
1003 if (prevarg[0])
1004 process_arg(prevarg, NULL);
1005 nasm_free(buffer);
1006 nasm_free(prevarg);
1007 return;
1011 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1012 * them are present at the end of the line.
1014 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1016 while (p > buffer && nasm_isspace(p[-1]))
1017 *--p = '\0';
1019 p = buffer;
1020 while (nasm_isspace(*p))
1021 p++;
1023 if (process_arg(prevarg, p))
1024 *p = '\0';
1026 if ((int) strlen(p) > prevargsize - 10) {
1027 prevargsize += ARG_BUF_DELTA;
1028 prevarg = nasm_realloc(prevarg, prevargsize);
1030 strncpy(prevarg, p, prevargsize);
1034 /* Function to process args from a string of args, rather than the
1035 * argv array. Used by the environment variable and response file
1036 * processing.
1038 static void process_args(char *args)
1040 char *p, *q, *arg, *prevarg;
1041 char separator = ' ';
1043 p = args;
1044 if (*p && *p != '-')
1045 separator = *p++;
1046 arg = NULL;
1047 while (*p) {
1048 q = p;
1049 while (*p && *p != separator)
1050 p++;
1051 while (*p == separator)
1052 *p++ = '\0';
1053 prevarg = arg;
1054 arg = q;
1055 if (process_arg(prevarg, arg))
1056 arg = NULL;
1058 if (arg)
1059 process_arg(arg, NULL);
1062 static void process_response_file(const char *file)
1064 char str[2048];
1065 FILE *f = fopen(file, "r");
1066 if (!f) {
1067 perror(file);
1068 exit(-1);
1070 while (fgets(str, sizeof str, f)) {
1071 process_args(str);
1073 fclose(f);
1076 static void parse_cmdline(int argc, char **argv)
1078 FILE *rfile;
1079 char *envreal, *envcopy = NULL, *p, *arg;
1080 int i;
1082 *inname = *outname = *listname = *errname = '\0';
1083 for (i = 0; i <= ERR_WARN_MAX; i++)
1084 warning_on_global[i] = warnings[i].enabled;
1087 * First, process the NASMENV environment variable.
1089 envreal = getenv("NASMENV");
1090 arg = NULL;
1091 if (envreal) {
1092 envcopy = nasm_strdup(envreal);
1093 process_args(envcopy);
1094 nasm_free(envcopy);
1098 * Now process the actual command line.
1100 while (--argc) {
1101 bool advance;
1102 argv++;
1103 if (argv[0][0] == '@') {
1104 /* We have a response file, so process this as a set of
1105 * arguments like the environment variable. This allows us
1106 * to have multiple arguments on a single line, which is
1107 * different to the -@resp file processing below for regular
1108 * NASM.
1110 process_response_file(argv[0]+1);
1111 argc--;
1112 argv++;
1114 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1115 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1116 if (p) {
1117 rfile = fopen(p, "r");
1118 if (rfile) {
1119 process_respfile(rfile);
1120 fclose(rfile);
1121 } else
1122 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1123 "unable to open response file `%s'", p);
1125 } else
1126 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1127 argv += advance, argc -= advance;
1130 /* Look for basic command line typos. This definitely doesn't
1131 catch all errors, but it might help cases of fumbled fingers. */
1132 if (!*inname)
1133 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1134 "no input file specified");
1135 else if (!strcmp(inname, errname) ||
1136 !strcmp(inname, outname) ||
1137 !strcmp(inname, listname) ||
1138 (depend_file && !strcmp(inname, depend_file)))
1139 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1140 "file `%s' is both input and output file",
1141 inname);
1143 if (*errname) {
1144 error_file = fopen(errname, "w");
1145 if (!error_file) {
1146 error_file = stderr; /* Revert to default! */
1147 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1148 "cannot open file `%s' for error messages",
1149 errname);
1154 static enum directives getkw(char **directive, char **value);
1156 static void assemble_file(char *fname, StrList **depend_ptr)
1158 char *directive, *value, *p, *q, *special, *line, debugid[80];
1159 insn output_ins;
1160 int i, validid;
1161 bool rn_error;
1162 int32_t seg;
1163 int64_t offs;
1164 struct tokenval tokval;
1165 expr *e;
1166 int pass_max;
1168 if (cmd_sb == 32 && cmd_cpu < IF_386)
1169 nasm_error(ERR_FATAL, "command line: "
1170 "32-bit segment size requires a higher cpu");
1172 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1173 for (passn = 1; pass0 <= 2; passn++) {
1174 int pass1, pass2;
1175 ldfunc def_label;
1177 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1178 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1179 /* pass0 0, 0, 0, ..., 1, 2 */
1181 def_label = passn > 1 ? redefine_label : define_label;
1183 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1184 cpu = cmd_cpu;
1185 if (pass0 == 2) {
1186 if (*listname)
1187 nasmlist.init(listname, nasm_error);
1189 in_abs_seg = false;
1190 global_offset_changed = 0; /* set by redefine_label */
1191 location.segment = ofmt->section(NULL, pass2, &sb);
1192 globalbits = sb;
1193 if (passn > 1) {
1194 saa_rewind(forwrefs);
1195 forwref = saa_rstruct(forwrefs);
1196 raa_free(offsets);
1197 offsets = raa_init();
1199 preproc->reset(fname, pass1, nasm_error, evaluate, &nasmlist,
1200 pass1 == 2 ? depend_ptr : NULL);
1201 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1203 globallineno = 0;
1204 if (passn == 1)
1205 location.known = true;
1206 location.offset = offs = GET_CURR_OFFS;
1208 while ((line = preproc->getline())) {
1209 enum directives d;
1210 globallineno++;
1213 * Here we parse our directives; this is not handled by the
1214 * 'real' parser. This really should be a separate function.
1216 directive = line;
1217 d = getkw(&directive, &value);
1218 if (d) {
1219 int err = 0;
1221 switch (d) {
1222 case D_SEGMENT: /* [SEGMENT n] */
1223 case D_SECTION:
1224 seg = ofmt->section(value, pass2, &sb);
1225 if (seg == NO_SEG) {
1226 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1227 "segment name `%s' not recognized",
1228 value);
1229 } else {
1230 in_abs_seg = false;
1231 location.segment = seg;
1233 break;
1234 case D_EXTERN: /* [EXTERN label:special] */
1235 if (*value == '$')
1236 value++; /* skip initial $ if present */
1237 if (pass0 == 2) {
1238 q = value;
1239 while (*q && *q != ':')
1240 q++;
1241 if (*q == ':') {
1242 *q++ = '\0';
1243 ofmt->symdef(value, 0L, 0L, 3, q);
1245 } else if (passn == 1) {
1246 q = value;
1247 validid = true;
1248 if (!isidstart(*q))
1249 validid = false;
1250 while (*q && *q != ':') {
1251 if (!isidchar(*q))
1252 validid = false;
1253 q++;
1255 if (!validid) {
1256 nasm_error(ERR_NONFATAL,
1257 "identifier expected after EXTERN");
1258 break;
1260 if (*q == ':') {
1261 *q++ = '\0';
1262 special = q;
1263 } else
1264 special = NULL;
1265 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1266 int temp = pass0;
1267 pass0 = 1; /* fake pass 1 in labels.c */
1268 declare_as_global(value, special,
1269 nasm_error);
1270 define_label(value, seg_alloc(), 0L, NULL,
1271 false, true, ofmt, nasm_error);
1272 pass0 = temp;
1274 } /* else pass0 == 1 */
1275 break;
1276 case D_BITS: /* [BITS bits] */
1277 globalbits = sb = get_bits(value);
1278 break;
1279 case D_GLOBAL: /* [GLOBAL symbol:special] */
1280 if (*value == '$')
1281 value++; /* skip initial $ if present */
1282 if (pass0 == 2) { /* pass 2 */
1283 q = value;
1284 while (*q && *q != ':')
1285 q++;
1286 if (*q == ':') {
1287 *q++ = '\0';
1288 ofmt->symdef(value, 0L, 0L, 3, q);
1290 } else if (pass2 == 1) { /* pass == 1 */
1291 q = value;
1292 validid = true;
1293 if (!isidstart(*q))
1294 validid = false;
1295 while (*q && *q != ':') {
1296 if (!isidchar(*q))
1297 validid = false;
1298 q++;
1300 if (!validid) {
1301 nasm_error(ERR_NONFATAL,
1302 "identifier expected after GLOBAL");
1303 break;
1305 if (*q == ':') {
1306 *q++ = '\0';
1307 special = q;
1308 } else
1309 special = NULL;
1310 declare_as_global(value, special, nasm_error);
1311 } /* pass == 1 */
1312 break;
1313 case D_COMMON: /* [COMMON symbol size:special] */
1315 int64_t size;
1317 if (*value == '$')
1318 value++; /* skip initial $ if present */
1319 p = value;
1320 validid = true;
1321 if (!isidstart(*p))
1322 validid = false;
1323 while (*p && !nasm_isspace(*p)) {
1324 if (!isidchar(*p))
1325 validid = false;
1326 p++;
1328 if (!validid) {
1329 nasm_error(ERR_NONFATAL,
1330 "identifier expected after COMMON");
1331 break;
1333 if (*p) {
1334 while (*p && nasm_isspace(*p))
1335 *p++ = '\0';
1336 q = p;
1337 while (*q && *q != ':')
1338 q++;
1339 if (*q == ':') {
1340 *q++ = '\0';
1341 special = q;
1342 } else {
1343 special = NULL;
1345 size = readnum(p, &rn_error);
1346 if (rn_error) {
1347 nasm_error(ERR_NONFATAL,
1348 "invalid size specified"
1349 " in COMMON declaration");
1350 break;
1352 } else {
1353 nasm_error(ERR_NONFATAL,
1354 "no size specified in"
1355 " COMMON declaration");
1356 break;
1359 if (pass0 < 2) {
1360 define_common(value, seg_alloc(), size,
1361 special, ofmt, nasm_error);
1362 } else if (pass0 == 2) {
1363 if (special)
1364 ofmt->symdef(value, 0L, 0L, 3, special);
1366 break;
1368 case D_ABSOLUTE: /* [ABSOLUTE address] */
1369 stdscan_reset();
1370 stdscan_bufptr = value;
1371 tokval.t_type = TOKEN_INVALID;
1372 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1373 nasm_error, NULL);
1374 if (e) {
1375 if (!is_reloc(e))
1376 nasm_error(pass0 ==
1377 1 ? ERR_NONFATAL : ERR_PANIC,
1378 "cannot use non-relocatable expression as "
1379 "ABSOLUTE address");
1380 else {
1381 abs_seg = reloc_seg(e);
1382 abs_offset = reloc_value(e);
1384 } else if (passn == 1)
1385 abs_offset = 0x100; /* don't go near zero in case of / */
1386 else
1387 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1388 "in pass two");
1389 in_abs_seg = true;
1390 location.segment = NO_SEG;
1391 break;
1392 case D_DEBUG: /* [DEBUG] */
1393 p = value;
1394 q = debugid;
1395 validid = true;
1396 if (!isidstart(*p))
1397 validid = false;
1398 while (*p && !nasm_isspace(*p)) {
1399 if (!isidchar(*p))
1400 validid = false;
1401 *q++ = *p++;
1403 *q++ = 0;
1404 if (!validid) {
1405 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1406 "identifier expected after DEBUG");
1407 break;
1409 while (*p && nasm_isspace(*p))
1410 p++;
1411 if (pass0 == 2)
1412 dfmt->debug_directive(debugid, p);
1413 break;
1414 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1415 while (*value && nasm_isspace(*value))
1416 value++;
1418 switch(*value) {
1419 case '-': validid = 0; value++; break;
1420 case '+': validid = 1; value++; break;
1421 case '*': validid = 2; value++; break;
1422 default: validid = 1; break;
1425 for (i = 1; i <= ERR_WARN_MAX; i++)
1426 if (!nasm_stricmp(value, warnings[i].name))
1427 break;
1428 if (i <= ERR_WARN_MAX) {
1429 switch(validid) {
1430 case 0:
1431 warning_on[i] = false;
1432 break;
1433 case 1:
1434 warning_on[i] = true;
1435 break;
1436 case 2:
1437 warning_on[i] = warning_on_global[i];
1438 break;
1441 else
1442 nasm_error(ERR_NONFATAL,
1443 "invalid warning id in WARNING directive");
1444 break;
1445 case D_CPU: /* [CPU] */
1446 cpu = get_cpu(value);
1447 break;
1448 case D_LIST: /* [LIST {+|-}] */
1449 while (*value && nasm_isspace(*value))
1450 value++;
1452 if (*value == '+') {
1453 user_nolist = 0;
1454 } else {
1455 if (*value == '-') {
1456 user_nolist = 1;
1457 } else {
1458 err = 1;
1461 break;
1462 case D_DEFAULT: /* [DEFAULT] */
1463 stdscan_reset();
1464 stdscan_bufptr = value;
1465 tokval.t_type = TOKEN_INVALID;
1466 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1467 switch ((int)tokval.t_integer) {
1468 case S_REL:
1469 globalrel = 1;
1470 break;
1471 case S_ABS:
1472 globalrel = 0;
1473 break;
1474 default:
1475 err = 1;
1476 break;
1478 } else {
1479 err = 1;
1481 break;
1482 case D_FLOAT:
1483 if (float_option(value)) {
1484 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1485 "unknown 'float' directive: %s",
1486 value);
1488 break;
1489 default:
1490 if (!d || !ofmt->directive(d, value, pass2))
1491 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1492 "unrecognised directive [%s]",
1493 directive);
1494 break;
1496 if (err) {
1497 nasm_error(ERR_NONFATAL,
1498 "invalid parameter to [%s] directive",
1499 directive);
1501 } else { /* it isn't a directive */
1503 parse_line(pass1, line, &output_ins,
1504 nasm_error, evaluate, def_label);
1506 if (optimizing > 0) {
1507 if (forwref != NULL && globallineno == forwref->lineno) {
1508 output_ins.forw_ref = true;
1509 do {
1510 output_ins.oprs[forwref->operand].opflags |=
1511 OPFLAG_FORWARD;
1512 forwref = saa_rstruct(forwrefs);
1513 } while (forwref != NULL
1514 && forwref->lineno == globallineno);
1515 } else
1516 output_ins.forw_ref = false;
1518 if (output_ins.forw_ref) {
1519 if (passn == 1) {
1520 for (i = 0; i < output_ins.operands; i++) {
1521 if (output_ins.oprs[i].
1522 opflags & OPFLAG_FORWARD) {
1523 struct forwrefinfo *fwinf =
1524 (struct forwrefinfo *)
1525 saa_wstruct(forwrefs);
1526 fwinf->lineno = globallineno;
1527 fwinf->operand = i;
1534 /* forw_ref */
1535 if (output_ins.opcode == I_EQU) {
1536 if (pass1 == 1) {
1538 * Special `..' EQUs get processed in pass two,
1539 * except `..@' macro-processor EQUs which are done
1540 * in the normal place.
1542 if (!output_ins.label)
1543 nasm_error(ERR_NONFATAL,
1544 "EQU not preceded by label");
1546 else if (output_ins.label[0] != '.' ||
1547 output_ins.label[1] != '.' ||
1548 output_ins.label[2] == '@') {
1549 if (output_ins.operands == 1 &&
1550 (output_ins.oprs[0].type & IMMEDIATE) &&
1551 output_ins.oprs[0].wrt == NO_SEG) {
1552 bool isext = !!(output_ins.oprs[0].opflags
1553 & OPFLAG_EXTERN);
1554 def_label(output_ins.label,
1555 output_ins.oprs[0].segment,
1556 output_ins.oprs[0].offset, NULL,
1557 false, isext, ofmt,
1558 nasm_error);
1559 } else if (output_ins.operands == 2
1560 && (output_ins.oprs[0].type & IMMEDIATE)
1561 && (output_ins.oprs[0].type & COLON)
1562 && output_ins.oprs[0].segment == NO_SEG
1563 && output_ins.oprs[0].wrt == NO_SEG
1564 && (output_ins.oprs[1].type & IMMEDIATE)
1565 && output_ins.oprs[1].segment == NO_SEG
1566 && output_ins.oprs[1].wrt == NO_SEG) {
1567 def_label(output_ins.label,
1568 output_ins.oprs[0].offset | SEG_ABS,
1569 output_ins.oprs[1].offset,
1570 NULL, false, false, ofmt,
1571 nasm_error);
1572 } else
1573 nasm_error(ERR_NONFATAL,
1574 "bad syntax for EQU");
1576 } else {
1578 * Special `..' EQUs get processed here, except
1579 * `..@' macro processor EQUs which are done above.
1581 if (output_ins.label[0] == '.' &&
1582 output_ins.label[1] == '.' &&
1583 output_ins.label[2] != '@') {
1584 if (output_ins.operands == 1 &&
1585 (output_ins.oprs[0].type & IMMEDIATE)) {
1586 define_label(output_ins.label,
1587 output_ins.oprs[0].segment,
1588 output_ins.oprs[0].offset,
1589 NULL, false, false, ofmt,
1590 nasm_error);
1591 } else if (output_ins.operands == 2
1592 && (output_ins.oprs[0].
1593 type & IMMEDIATE)
1594 && (output_ins.oprs[0].type & COLON)
1595 && output_ins.oprs[0].segment ==
1596 NO_SEG
1597 && (output_ins.oprs[1].
1598 type & IMMEDIATE)
1599 && output_ins.oprs[1].segment ==
1600 NO_SEG) {
1601 define_label(output_ins.label,
1602 output_ins.oprs[0].
1603 offset | SEG_ABS,
1604 output_ins.oprs[1].offset,
1605 NULL, false, false, ofmt,
1606 nasm_error);
1607 } else
1608 nasm_error(ERR_NONFATAL,
1609 "bad syntax for EQU");
1612 } else { /* instruction isn't an EQU */
1614 if (pass1 == 1) {
1616 int64_t l = insn_size(location.segment, offs, sb, cpu,
1617 &output_ins, nasm_error);
1619 /* if (using_debug_info) && output_ins.opcode != -1) */
1620 if (using_debug_info)
1621 { /* fbk 03/25/01 */
1622 /* this is done here so we can do debug type info */
1623 int32_t typeinfo =
1624 TYS_ELEMENTS(output_ins.operands);
1625 switch (output_ins.opcode) {
1626 case I_RESB:
1627 typeinfo =
1628 TYS_ELEMENTS(output_ins.oprs[0].
1629 offset) | TY_BYTE;
1630 break;
1631 case I_RESW:
1632 typeinfo =
1633 TYS_ELEMENTS(output_ins.oprs[0].
1634 offset) | TY_WORD;
1635 break;
1636 case I_RESD:
1637 typeinfo =
1638 TYS_ELEMENTS(output_ins.oprs[0].
1639 offset) | TY_DWORD;
1640 break;
1641 case I_RESQ:
1642 typeinfo =
1643 TYS_ELEMENTS(output_ins.oprs[0].
1644 offset) | TY_QWORD;
1645 break;
1646 case I_REST:
1647 typeinfo =
1648 TYS_ELEMENTS(output_ins.oprs[0].
1649 offset) | TY_TBYTE;
1650 break;
1651 case I_RESO:
1652 typeinfo =
1653 TYS_ELEMENTS(output_ins.oprs[0].
1654 offset) | TY_OWORD;
1655 break;
1656 case I_RESY:
1657 typeinfo =
1658 TYS_ELEMENTS(output_ins.oprs[0].
1659 offset) | TY_YWORD;
1660 break;
1661 case I_DB:
1662 typeinfo |= TY_BYTE;
1663 break;
1664 case I_DW:
1665 typeinfo |= TY_WORD;
1666 break;
1667 case I_DD:
1668 if (output_ins.eops_float)
1669 typeinfo |= TY_FLOAT;
1670 else
1671 typeinfo |= TY_DWORD;
1672 break;
1673 case I_DQ:
1674 typeinfo |= TY_QWORD;
1675 break;
1676 case I_DT:
1677 typeinfo |= TY_TBYTE;
1678 break;
1679 case I_DO:
1680 typeinfo |= TY_OWORD;
1681 break;
1682 case I_DY:
1683 typeinfo |= TY_YWORD;
1684 break;
1685 default:
1686 typeinfo = TY_LABEL;
1690 dfmt->debug_typevalue(typeinfo);
1692 if (l != -1) {
1693 offs += l;
1694 SET_CURR_OFFS(offs);
1697 * else l == -1 => invalid instruction, which will be
1698 * flagged as an error on pass 2
1701 } else {
1702 offs += assemble(location.segment, offs, sb, cpu,
1703 &output_ins, ofmt, nasm_error,
1704 &nasmlist);
1705 SET_CURR_OFFS(offs);
1708 } /* not an EQU */
1709 cleanup_insn(&output_ins);
1711 nasm_free(line);
1712 location.offset = offs = GET_CURR_OFFS;
1713 } /* end while (line = preproc->getline... */
1715 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1716 nasm_error(ERR_NONFATAL,
1717 "phase error detected at end of assembly.");
1719 if (pass1 == 1)
1720 preproc->cleanup(1);
1722 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1723 pass0++;
1724 } else if (global_offset_changed &&
1725 global_offset_changed < prev_offset_changed) {
1726 prev_offset_changed = global_offset_changed;
1727 stall_count = 0;
1728 } else {
1729 stall_count++;
1732 if (terminate_after_phase)
1733 break;
1735 if ((stall_count > 997) || (passn >= pass_max)) {
1736 /* We get here if the labels don't converge
1737 * Example: FOO equ FOO + 1
1739 nasm_error(ERR_NONFATAL,
1740 "Can't find valid values for all labels "
1741 "after %d passes, giving up.", passn);
1742 nasm_error(ERR_NONFATAL,
1743 "Possible causes: recursive EQUs, macro abuse.");
1744 break;
1748 preproc->cleanup(0);
1749 nasmlist.cleanup();
1750 if (!terminate_after_phase && opt_verbose_info) {
1751 /* -On and -Ov switches */
1752 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1756 static enum directives getkw(char **directive, char **value)
1758 char *p, *q, *buf;
1760 buf = *directive;
1762 /* allow leading spaces or tabs */
1763 while (*buf == ' ' || *buf == '\t')
1764 buf++;
1766 if (*buf != '[')
1767 return 0;
1769 p = buf;
1771 while (*p && *p != ']')
1772 p++;
1774 if (!*p)
1775 return 0;
1777 q = p++;
1779 while (*p && *p != ';') {
1780 if (!nasm_isspace(*p))
1781 return 0;
1782 p++;
1784 q[1] = '\0';
1786 *directive = p = buf + 1;
1787 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1788 buf++;
1789 if (*buf == ']') {
1790 *buf = '\0';
1791 *value = buf;
1792 } else {
1793 *buf++ = '\0';
1794 while (nasm_isspace(*buf))
1795 buf++; /* beppu - skip leading whitespace */
1796 *value = buf;
1797 while (*buf != ']')
1798 buf++;
1799 *buf++ = '\0';
1802 return find_directive(*directive);
1806 * gnu style error reporting
1807 * This function prints an error message to error_file in the
1808 * style used by GNU. An example would be:
1809 * file.asm:50: error: blah blah blah
1810 * where file.asm is the name of the file, 50 is the line number on
1811 * which the error occurs (or is detected) and "error:" is one of
1812 * the possible optional diagnostics -- it can be "error" or "warning"
1813 * or something else. Finally the line terminates with the actual
1814 * error message.
1816 * @param severity the severity of the warning or error
1817 * @param fmt the printf style format string
1819 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1821 char *currentfile = NULL;
1822 int32_t lineno = 0;
1824 if (is_suppressed_warning(severity))
1825 return;
1827 if (!(severity & ERR_NOFILE))
1828 src_get(&lineno, &currentfile);
1830 if (currentfile) {
1831 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1832 nasm_free(currentfile);
1833 } else {
1834 fputs("nasm: ", error_file);
1837 nasm_verror_common(severity, fmt, ap);
1841 * MS style error reporting
1842 * This function prints an error message to error_file in the
1843 * style used by Visual C and some other Microsoft tools. An example
1844 * would be:
1845 * file.asm(50) : error: blah blah blah
1846 * where file.asm is the name of the file, 50 is the line number on
1847 * which the error occurs (or is detected) and "error:" is one of
1848 * the possible optional diagnostics -- it can be "error" or "warning"
1849 * or something else. Finally the line terminates with the actual
1850 * error message.
1852 * @param severity the severity of the warning or error
1853 * @param fmt the printf style format string
1855 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1857 char *currentfile = NULL;
1858 int32_t lineno = 0;
1860 if (is_suppressed_warning(severity))
1861 return;
1863 if (!(severity & ERR_NOFILE))
1864 src_get(&lineno, &currentfile);
1866 if (currentfile) {
1867 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1868 nasm_free(currentfile);
1869 } else {
1870 fputs("nasm: ", error_file);
1873 nasm_verror_common(severity, fmt, ap);
1877 * check for supressed warning
1878 * checks for suppressed warning or pass one only warning and we're
1879 * not in pass 1
1881 * @param severity the severity of the warning or error
1882 * @return true if we should abort error/warning printing
1884 static bool is_suppressed_warning(int severity)
1887 * See if it's a suppressed warning.
1889 return (severity & ERR_MASK) == ERR_WARNING &&
1890 (((severity & ERR_WARN_MASK) != 0 &&
1891 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1892 /* See if it's a pass-one only warning and we're not in pass one. */
1893 ((severity & ERR_PASS1) && pass0 != 1) ||
1894 ((severity & ERR_PASS2) && pass0 != 2));
1898 * common error reporting
1899 * This is the common back end of the error reporting schemes currently
1900 * implemented. It prints the nature of the warning and then the
1901 * specific error message to error_file and may or may not return. It
1902 * doesn't return if the error severity is a "panic" or "debug" type.
1904 * @param severity the severity of the warning or error
1905 * @param fmt the printf style format string
1907 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1909 char msg[1024];
1910 const char *pfx;
1912 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1913 case ERR_WARNING:
1914 pfx = "warning: ";
1915 break;
1916 case ERR_NONFATAL:
1917 pfx = "error: ";
1918 break;
1919 case ERR_FATAL:
1920 pfx = "fatal: ";
1921 break;
1922 case ERR_PANIC:
1923 pfx = "panic: ";
1924 break;
1925 case ERR_DEBUG:
1926 pfx = "debug: ";
1927 break;
1928 default:
1929 pfx = "";
1930 break;
1933 vsnprintf(msg, sizeof msg, fmt, args);
1935 fprintf(error_file, "%s%s\n", pfx, msg);
1937 if (*listname)
1938 nasmlist.error(severity, pfx, msg);
1940 if (severity & ERR_USAGE)
1941 want_usage = true;
1943 switch (severity & ERR_MASK) {
1944 case ERR_DEBUG:
1945 /* no further action, by definition */
1946 break;
1947 case ERR_WARNING:
1948 if (warning_on[0]) /* Treat warnings as errors */
1949 terminate_after_phase = true;
1950 break;
1951 case ERR_NONFATAL:
1952 terminate_after_phase = true;
1953 break;
1954 case ERR_FATAL:
1955 if (ofile) {
1956 fclose(ofile);
1957 remove(outname);
1958 ofile = NULL;
1960 if (want_usage)
1961 usage();
1962 exit(1); /* instantly die */
1963 break; /* placate silly compilers */
1964 case ERR_PANIC:
1965 fflush(NULL);
1966 /* abort(); *//* halt, catch fire, and dump core */
1967 exit(3);
1968 break;
1972 static void usage(void)
1974 fputs("type `nasm -h' for help\n", error_file);
1977 #define BUF_DELTA 512
1979 static FILE *no_pp_fp;
1980 static efunc no_pp_err;
1981 static ListGen *no_pp_list;
1982 static int32_t no_pp_lineinc;
1984 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1985 ListGen * listgen, StrList **deplist)
1987 src_set_fname(nasm_strdup(file));
1988 src_set_linnum(0);
1989 no_pp_lineinc = 1;
1990 no_pp_err = error;
1991 no_pp_fp = fopen(file, "r");
1992 if (!no_pp_fp)
1993 no_pp_err(ERR_FATAL | ERR_NOFILE,
1994 "unable to open input file `%s'", file);
1995 no_pp_list = listgen;
1996 (void)pass; /* placate compilers */
1997 (void)eval; /* placate compilers */
1999 if (deplist) {
2000 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2001 sl->next = NULL;
2002 strcpy(sl->str, file);
2003 *deplist = sl;
2007 static char *no_pp_getline(void)
2009 char *buffer, *p, *q;
2010 int bufsize;
2012 bufsize = BUF_DELTA;
2013 buffer = nasm_malloc(BUF_DELTA);
2014 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2016 while (1) { /* Loop to handle %line */
2018 p = buffer;
2019 while (1) { /* Loop to handle long lines */
2020 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2021 if (!q)
2022 break;
2023 p += strlen(p);
2024 if (p > buffer && p[-1] == '\n')
2025 break;
2026 if (p - buffer > bufsize - 10) {
2027 int offset;
2028 offset = p - buffer;
2029 bufsize += BUF_DELTA;
2030 buffer = nasm_realloc(buffer, bufsize);
2031 p = buffer + offset;
2035 if (!q && p == buffer) {
2036 nasm_free(buffer);
2037 return NULL;
2041 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2042 * them are present at the end of the line.
2044 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2046 if (!nasm_strnicmp(buffer, "%line", 5)) {
2047 int32_t ln;
2048 int li;
2049 char *nm = nasm_malloc(strlen(buffer));
2050 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2051 nasm_free(src_set_fname(nm));
2052 src_set_linnum(ln);
2053 no_pp_lineinc = li;
2054 continue;
2056 nasm_free(nm);
2058 break;
2061 no_pp_list->line(LIST_READ, buffer);
2063 return buffer;
2066 static void no_pp_cleanup(int pass)
2068 (void)pass; /* placate GCC */
2069 fclose(no_pp_fp);
2072 static uint32_t get_cpu(char *value)
2074 if (!strcmp(value, "8086"))
2075 return IF_8086;
2076 if (!strcmp(value, "186"))
2077 return IF_186;
2078 if (!strcmp(value, "286"))
2079 return IF_286;
2080 if (!strcmp(value, "386"))
2081 return IF_386;
2082 if (!strcmp(value, "486"))
2083 return IF_486;
2084 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2085 return IF_PENT;
2086 if (!strcmp(value, "686") ||
2087 !nasm_stricmp(value, "ppro") ||
2088 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2089 return IF_P6;
2090 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2091 return IF_KATMAI;
2092 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2093 !nasm_stricmp(value, "willamette"))
2094 return IF_WILLAMETTE;
2095 if (!nasm_stricmp(value, "prescott"))
2096 return IF_PRESCOTT;
2097 if (!nasm_stricmp(value, "x64") ||
2098 !nasm_stricmp(value, "x86-64"))
2099 return IF_X86_64;
2100 if (!nasm_stricmp(value, "ia64") ||
2101 !nasm_stricmp(value, "ia-64") ||
2102 !nasm_stricmp(value, "itanium") ||
2103 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2104 return IF_IA64;
2106 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2107 "unknown 'cpu' type");
2109 return IF_PLEVEL; /* the maximum level */
2112 static int get_bits(char *value)
2114 int i;
2116 if ((i = atoi(value)) == 16)
2117 return i; /* set for a 16-bit segment */
2118 else if (i == 32) {
2119 if (cpu < IF_386) {
2120 nasm_error(ERR_NONFATAL,
2121 "cannot specify 32-bit segment on processor below a 386");
2122 i = 16;
2124 } else if (i == 64) {
2125 if (cpu < IF_X86_64) {
2126 nasm_error(ERR_NONFATAL,
2127 "cannot specify 64-bit segment on processor below an x86-64");
2128 i = 16;
2130 if (i != maxbits) {
2131 nasm_error(ERR_NONFATAL,
2132 "%s output format does not support 64-bit code",
2133 ofmt->shortname);
2134 i = 16;
2136 } else {
2137 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2138 "`%s' is not a valid segment size; must be 16, 32 or 64",
2139 value);
2140 i = 16;
2142 return i;
2145 /* end of nasm.c */