Merge commit 'nasm-2.07rc7' into new-preproc
[nasm.git] / nasm.c
blobf413d35c834f09bf03c296f610f5dbbb0673099b
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 register_output_formats(void);
74 static void report_error_gnu(int severity, const char *fmt, ...);
75 static void report_error_vc(int severity, const char *fmt, ...);
76 static void report_error_common(int severity, const char *fmt,
77 va_list args);
78 static bool is_suppressed_warning(int severity);
79 static void usage(void);
80 static efunc report_error;
82 static int using_debug_info, opt_verbose_info;
83 bool tasm_compatible_mode = false;
84 int pass0, passn;
85 int maxbits = 0;
86 int globalrel = 0;
88 time_t official_compile_time;
90 static char inname[FILENAME_MAX];
91 static char outname[FILENAME_MAX];
92 static char listname[FILENAME_MAX];
93 static char errname[FILENAME_MAX];
94 static int globallineno; /* for forward-reference tracking */
95 /* static int pass = 0; */
96 static struct ofmt *ofmt = NULL;
98 static FILE *error_file; /* Where to write error messages */
100 static FILE *ofile = NULL;
101 int optimizing = -1; /* number of optimization passes to take */
102 static int sb, cmd_sb = 16; /* by default */
103 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
104 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
105 int64_t global_offset_changed; /* referenced in labels.c */
106 int64_t prev_offset_changed;
107 int32_t stall_count;
109 static struct location location;
110 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
111 int32_t abs_seg; /* ABSOLUTE segment basis */
112 int32_t abs_offset; /* ABSOLUTE offset */
114 static struct RAA *offsets;
116 static struct SAA *forwrefs; /* keep track of forward references */
117 static const struct forwrefinfo *forwref;
119 static Preproc *preproc;
120 enum op_type {
121 op_normal, /* Preprocess and assemble */
122 op_preprocess, /* Preprocess only */
123 op_depend, /* Generate dependencies */
125 static enum op_type operating_mode;
126 /* Dependency flags */
127 static bool depend_emit_phony = false;
128 static bool depend_missing_ok = false;
129 static const char *depend_target = NULL;
130 static const char *depend_file = NULL;
133 * Which of the suppressible warnings are suppressed. Entry zero
134 * isn't an actual warning, but it used for -w+error/-Werror.
137 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
138 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
140 static const struct warning {
141 const char *name;
142 const char *help;
143 bool enabled;
144 } warnings[ERR_WARN_MAX+1] = {
145 {"error", "treat warnings as errors", false},
146 {"macro-params", "macro calls with wrong parameter count", true},
147 {"macro-selfref", "cyclic macro references", false},
148 {"macro-defaults", "macros with more default than optional parameters", true},
149 {"orphan-labels", "labels alone on lines without trailing `:'", true},
150 {"number-overflow", "numeric constant does not fit", true},
151 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
152 {"float-overflow", "floating point overflow", true},
153 {"float-denorm", "floating point denormal", false},
154 {"float-underflow", "floating point underflow", false},
155 {"float-toolong", "too many digits in floating-point number", true},
156 {"user", "%warning directives", true},
160 * This is a null preprocessor which just copies lines from input
161 * to output. It's used when someone explicitly requests that NASM
162 * not preprocess their source file.
165 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
166 static char *no_pp_getline(void);
167 static void no_pp_cleanup(int);
168 static Preproc no_pp = {
169 no_pp_reset,
170 no_pp_getline,
171 no_pp_cleanup
175 * get/set current offset...
177 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
178 raa_read(offsets,location.segment))
179 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
180 (void)(offsets=raa_write(offsets,location.segment,(x))))
182 static bool want_usage;
183 static bool terminate_after_phase;
184 int user_nolist = 0; /* fbk 9/2/00 */
186 static void nasm_fputs(const char *line, FILE * outfile)
188 if (outfile) {
189 fputs(line, outfile);
190 putc('\n', outfile);
191 } else
192 puts(line);
195 /* Convert a struct tm to a POSIX-style time constant */
196 static int64_t posix_mktime(struct tm *tm)
198 int64_t t;
199 int64_t y = tm->tm_year;
201 /* See IEEE 1003.1:2004, section 4.14 */
203 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
204 t += tm->tm_yday;
205 t *= 24;
206 t += tm->tm_hour;
207 t *= 60;
208 t += tm->tm_min;
209 t *= 60;
210 t += tm->tm_sec;
212 return t;
215 static void define_macros_early(void)
217 char temp[128];
218 struct tm lt, *lt_p, gm, *gm_p;
219 int64_t posix_time;
221 lt_p = localtime(&official_compile_time);
222 if (lt_p) {
223 lt = *lt_p;
225 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
226 pp_pre_define(temp);
227 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
228 pp_pre_define(temp);
229 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
230 pp_pre_define(temp);
231 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
232 pp_pre_define(temp);
235 gm_p = gmtime(&official_compile_time);
236 if (gm_p) {
237 gm = *gm_p;
239 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
240 pp_pre_define(temp);
241 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
242 pp_pre_define(temp);
243 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
244 pp_pre_define(temp);
245 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
246 pp_pre_define(temp);
249 if (gm_p)
250 posix_time = posix_mktime(&gm);
251 else if (lt_p)
252 posix_time = posix_mktime(&lt);
253 else
254 posix_time = 0;
256 if (posix_time) {
257 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
258 pp_pre_define(temp);
262 static void define_macros_late(void)
264 char temp[128];
266 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
267 ofmt->shortname);
268 pp_pre_define(temp);
271 static void emit_dependencies(StrList *list)
273 FILE *deps;
274 int linepos, len;
275 StrList *l, *nl;
277 if (depend_file && strcmp(depend_file, "-")) {
278 deps = fopen(depend_file, "w");
279 if (!deps) {
280 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
281 "unable to write dependency file `%s'", depend_file);
282 return;
284 } else {
285 deps = stdout;
288 linepos = fprintf(deps, "%s:", depend_target);
289 for (l = list; l; l = l->next) {
290 len = strlen(l->str);
291 if (linepos + len > 62) {
292 fprintf(deps, " \\\n ");
293 linepos = 1;
295 fprintf(deps, " %s", l->str);
296 linepos += len+1;
298 fprintf(deps, "\n\n");
300 for (l = list; l; l = nl) {
301 if (depend_emit_phony)
302 fprintf(deps, "%s:\n\n", l->str);
304 nl = l->next;
305 nasm_free(l);
308 if (deps != stdout)
309 fclose(deps);
312 int main(int argc, char **argv)
314 StrList *depend_list = NULL, **depend_ptr;
316 time(&official_compile_time);
318 pass0 = 0;
319 want_usage = terminate_after_phase = false;
320 report_error = report_error_gnu;
322 error_file = stderr;
324 tolower_init();
326 nasm_set_malloc_error(report_error);
327 offsets = raa_init();
328 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
330 preproc = &nasmpp;
331 operating_mode = op_normal;
333 seg_init();
335 register_output_formats();
337 /* Define some macros dependent on the runtime, but not
338 on the command line. */
339 define_macros_early();
341 parse_cmdline(argc, argv);
343 if (terminate_after_phase) {
344 if (want_usage)
345 usage();
346 return 1;
349 /* If debugging info is disabled, suppress any debug calls */
350 if (!using_debug_info)
351 ofmt->current_dfmt = &null_debug_form;
353 if (ofmt->stdmac)
354 pp_extra_stdmac(ofmt->stdmac);
355 parser_global_info(ofmt, &location);
356 eval_global_info(ofmt, lookup_label, &location);
358 /* define some macros dependent of command-line */
359 define_macros_late();
361 depend_ptr = (depend_file || (operating_mode == op_depend))
362 ? &depend_list : NULL;
363 if (!depend_target)
364 depend_target = outname;
366 switch (operating_mode) {
367 case op_depend:
369 char *line;
371 if (depend_missing_ok)
372 pp_include_path(NULL); /* "assume generated" */
374 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
375 depend_ptr);
376 if (outname[0] == '\0')
377 ofmt->filename(inname, outname, report_error);
378 ofile = NULL;
379 while ((line = preproc->getline()))
380 nasm_free(line);
381 preproc->cleanup(0);
383 break;
385 case op_preprocess:
387 char *line;
388 char *file_name = NULL;
389 int32_t prior_linnum = 0;
390 int lineinc = 0;
392 if (*outname) {
393 ofile = fopen(outname, "w");
394 if (!ofile)
395 report_error(ERR_FATAL | ERR_NOFILE,
396 "unable to open output file `%s'",
397 outname);
398 } else
399 ofile = NULL;
401 location.known = false;
403 /* pass = 1; */
404 preproc->reset(inname, 3, report_error, evaluate, &nasmlist,
405 depend_ptr);
407 while ((line = preproc->getline())) {
409 * We generate %line directives if needed for later programs
411 int32_t linnum = prior_linnum += lineinc;
412 int altline = src_get(&linnum, &file_name);
413 if (altline) {
414 if (altline == 1 && lineinc == 1)
415 nasm_fputs("", ofile);
416 else {
417 lineinc = (altline != -1 || lineinc != 1);
418 fprintf(ofile ? ofile : stdout,
419 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
420 file_name);
422 prior_linnum = linnum;
424 nasm_fputs(line, ofile);
425 nasm_free(line);
427 nasm_free(file_name);
428 preproc->cleanup(0);
429 if (ofile)
430 fclose(ofile);
431 if (ofile && terminate_after_phase)
432 remove(outname);
433 ofile = NULL;
435 break;
437 case op_normal:
440 * We must call ofmt->filename _anyway_, even if the user
441 * has specified their own output file, because some
442 * formats (eg OBJ and COFF) use ofmt->filename to find out
443 * the name of the input file and then put that inside the
444 * file.
446 ofmt->filename(inname, outname, report_error);
448 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
449 if (!ofile) {
450 report_error(ERR_FATAL | ERR_NOFILE,
451 "unable to open output file `%s'", outname);
455 * We must call init_labels() before ofmt->init() since
456 * some object formats will want to define labels in their
457 * init routines. (eg OS/2 defines the FLAT group)
459 init_labels();
461 ofmt->init(ofile, report_error, define_label, evaluate);
462 ofmt->current_dfmt->init(ofmt, NULL, ofile, report_error);
464 assemble_file(inname, depend_ptr);
466 if (!terminate_after_phase) {
467 ofmt->cleanup(using_debug_info);
468 cleanup_labels();
469 fflush(ofile);
470 if (ferror(ofile)) {
471 report_error(ERR_NONFATAL|ERR_NOFILE,
472 "write error on output file `%s'", outname);
476 if (ofile) {
477 fclose(ofile);
478 if (terminate_after_phase)
479 remove(outname);
480 ofile = NULL;
483 break;
486 if (depend_list && !terminate_after_phase)
487 emit_dependencies(depend_list);
489 if (want_usage)
490 usage();
492 raa_free(offsets);
493 saa_free(forwrefs);
494 eval_cleanup();
495 stdscan_cleanup();
497 return terminate_after_phase;
501 * Get a parameter for a command line option.
502 * First arg must be in the form of e.g. -f...
504 static char *get_param(char *p, char *q, bool *advance)
506 *advance = false;
507 if (p[2]) { /* the parameter's in the option */
508 p += 2;
509 while (nasm_isspace(*p))
510 p++;
511 return p;
513 if (q && q[0]) {
514 *advance = true;
515 return q;
517 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
518 "option `-%c' requires an argument", p[1]);
519 return NULL;
523 * Copy a filename
525 static void copy_filename(char *dst, const char *src)
527 size_t len = strlen(src);
529 if (len >= (size_t)FILENAME_MAX) {
530 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
531 return;
533 strncpy(dst, src, FILENAME_MAX);
537 * Convert a string to Make-safe form
539 static char *quote_for_make(const char *str)
541 const char *p;
542 char *os, *q;
544 size_t n = 1; /* Terminating zero */
545 size_t nbs = 0;
547 if (!str)
548 return NULL;
550 for (p = str; *p; p++) {
551 switch (*p) {
552 case ' ':
553 case '\t':
554 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
555 n += nbs + 2;
556 nbs = 0;
557 break;
558 case '$':
559 case '#':
560 nbs = 0;
561 n += 2;
562 break;
563 case '\\':
564 nbs++;
565 n++;
566 break;
567 default:
568 nbs = 0;
569 n++;
570 break;
574 /* Convert N backslashes at the end of filename to 2N backslashes */
575 if (nbs)
576 n += nbs;
578 os = q = nasm_malloc(n);
580 nbs = 0;
581 for (p = str; *p; p++) {
582 switch (*p) {
583 case ' ':
584 case '\t':
585 while (nbs--)
586 *q++ = '\\';
587 *q++ = '\\';
588 *q++ = *p;
589 break;
590 case '$':
591 *q++ = *p;
592 *q++ = *p;
593 nbs = 0;
594 break;
595 case '#':
596 *q++ = '\\';
597 *q++ = *p;
598 nbs = 0;
599 break;
600 case '\\':
601 *q++ = *p;
602 nbs++;
603 break;
604 default:
605 *q++ = *p;
606 nbs = 0;
607 break;
610 while (nbs--)
611 *q++ = '\\';
613 *q = '\0';
615 return os;
618 struct textargs {
619 const char *label;
620 int value;
623 #define OPT_PREFIX 0
624 #define OPT_POSTFIX 1
625 struct textargs textopts[] = {
626 {"prefix", OPT_PREFIX},
627 {"postfix", OPT_POSTFIX},
628 {NULL, 0}
631 static bool stopoptions = false;
632 static bool process_arg(char *p, char *q)
634 char *param;
635 int i;
636 bool advance = false;
637 bool do_warn;
639 if (!p || !p[0])
640 return false;
642 if (p[0] == '-' && !stopoptions) {
643 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
644 /* These parameters take values */
645 if (!(param = get_param(p, q, &advance)))
646 return advance;
649 switch (p[1]) {
650 case 's':
651 error_file = stdout;
652 break;
654 case 'o': /* output file */
655 copy_filename(outname, param);
656 break;
658 case 'f': /* output format */
659 ofmt = ofmt_find(param);
660 if (!ofmt) {
661 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
662 "unrecognised output format `%s' - "
663 "use -hf for a list", param);
665 break;
667 case 'O': /* Optimization level */
669 int opt;
671 if (!*param) {
672 /* Naked -O == -Ox */
673 optimizing = INT_MAX >> 1; /* Almost unlimited */
674 } else {
675 while (*param) {
676 switch (*param) {
677 case '0': case '1': case '2': case '3': case '4':
678 case '5': case '6': case '7': case '8': case '9':
679 opt = strtoul(param, &param, 10);
681 /* -O0 -> optimizing == -1, 0.98 behaviour */
682 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
683 if (opt < 2)
684 optimizing = opt - 1;
685 else
686 optimizing = opt;
687 break;
689 case 'v':
690 case '+':
691 param++;
692 opt_verbose_info = true;
693 break;
695 case 'x':
696 param++;
697 optimizing = INT_MAX >> 1; /* Almost unlimited */
698 break;
700 default:
701 report_error(ERR_FATAL,
702 "unknown optimization option -O%c\n",
703 *param);
704 break;
708 break;
711 case 'p': /* pre-include */
712 case 'P':
713 pp_pre_include(param);
714 break;
716 case 'd': /* pre-define */
717 case 'D':
718 pp_pre_define(param);
719 break;
721 case 'u': /* un-define */
722 case 'U':
723 pp_pre_undefine(param);
724 break;
726 case 'i': /* include search path */
727 case 'I':
728 pp_include_path(param);
729 break;
731 case 'l': /* listing file */
732 copy_filename(listname, param);
733 break;
735 case 'Z': /* error messages file */
736 strcpy(errname, param);
737 break;
739 case 'F': /* specify debug format */
740 ofmt->current_dfmt = dfmt_find(ofmt, param);
741 if (!ofmt->current_dfmt) {
742 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
743 "unrecognized debug format `%s' for"
744 " output format `%s'",
745 param, ofmt->shortname);
747 using_debug_info = true;
748 break;
750 case 'X': /* specify error reporting format */
751 if (nasm_stricmp("vc", param) == 0)
752 report_error = report_error_vc;
753 else if (nasm_stricmp("gnu", param) == 0)
754 report_error = report_error_gnu;
755 else
756 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
757 "unrecognized error reporting format `%s'",
758 param);
759 break;
761 case 'g':
762 using_debug_info = true;
763 break;
765 case 'h':
766 printf
767 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
768 "[-l listfile]\n"
769 " [options...] [--] filename\n"
770 " or nasm -v for version info\n\n"
771 " -t assemble in SciTech TASM compatible mode\n"
772 " -g generate debug information in selected format.\n");
773 printf
774 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
775 " -a don't preprocess (assemble only)\n"
776 " -M generate Makefile dependencies on stdout\n"
777 " -MG d:o, missing files assumed generated\n\n"
778 " -Z<file> redirect error messages to file\n"
779 " -s redirect error messages to stdout\n\n"
780 " -F format select a debugging format\n\n"
781 " -I<path> adds a pathname to the include file path\n");
782 printf
783 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
784 " -P<file> pre-includes a file\n"
785 " -D<macro>[=<value>] pre-defines a macro\n"
786 " -U<macro> undefines a macro\n"
787 " -X<format> specifies error reporting format (gnu or vc)\n"
788 " -w+foo enables warning foo (equiv. -Wfoo)\n"
789 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
790 "Warnings:\n");
791 for (i = 0; i <= ERR_WARN_MAX; i++)
792 printf(" %-23s %s (default %s)\n",
793 warnings[i].name, warnings[i].help,
794 warnings[i].enabled ? "on" : "off");
795 printf
796 ("\nresponse files should contain command line parameters"
797 ", one per line.\n");
798 if (p[2] == 'f') {
799 printf("\nvalid output formats for -f are"
800 " (`*' denotes default):\n");
801 ofmt_list(ofmt, stdout);
802 } else {
803 printf("\nFor a list of valid output formats, use -hf.\n");
804 printf("For a list of debug formats, use -f <form> -y.\n");
806 exit(0); /* never need usage message here */
807 break;
809 case 'y':
810 printf("\nvalid debug formats for '%s' output format are"
811 " ('*' denotes default):\n", ofmt->shortname);
812 dfmt_list(ofmt, stdout);
813 exit(0);
814 break;
816 case 't':
817 tasm_compatible_mode = true;
818 break;
820 case 'v':
821 printf("NASM version %s compiled on %s%s\n",
822 nasm_version, nasm_date, nasm_compile_options);
823 exit(0); /* never need usage message here */
824 break;
826 case 'e': /* preprocess only */
827 case 'E':
828 operating_mode = op_preprocess;
829 break;
831 case 'a': /* assemble only - don't preprocess */
832 preproc = &no_pp;
833 break;
835 case 'W':
836 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
837 do_warn = false;
838 param += 3;
839 } else {
840 do_warn = true;
842 goto set_warning;
844 case 'w':
845 if (param[0] != '+' && param[0] != '-') {
846 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
847 "invalid option to `-w'");
848 break;
850 do_warn = (param[0] == '+');
851 param++;
852 goto set_warning;
853 set_warning:
854 for (i = 0; i <= ERR_WARN_MAX; i++)
855 if (!nasm_stricmp(param, warnings[i].name))
856 break;
857 if (i <= ERR_WARN_MAX)
858 warning_on_global[i] = do_warn;
859 else if (!nasm_stricmp(param, "all"))
860 for (i = 1; i <= ERR_WARN_MAX; i++)
861 warning_on_global[i] = do_warn;
862 else if (!nasm_stricmp(param, "none"))
863 for (i = 1; i <= ERR_WARN_MAX; i++)
864 warning_on_global[i] = !do_warn;
865 else
866 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
867 "invalid warning `%s'", param);
868 break;
870 case 'M':
871 switch (p[2]) {
872 case 0:
873 operating_mode = op_depend;
874 break;
875 case 'G':
876 operating_mode = op_depend;
877 depend_missing_ok = true;
878 break;
879 case 'P':
880 depend_emit_phony = true;
881 break;
882 case 'D':
883 depend_file = q;
884 advance = true;
885 break;
886 case 'T':
887 depend_target = q;
888 advance = true;
889 break;
890 case 'Q':
891 depend_target = quote_for_make(q);
892 advance = true;
893 break;
894 default:
895 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
896 "unknown dependency option `-M%c'", p[2]);
897 break;
899 if (advance && (!q || !q[0])) {
900 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
901 "option `-M%c' requires a parameter", p[2]);
902 break;
904 break;
906 case '-':
908 int s;
910 if (p[2] == 0) { /* -- => stop processing options */
911 stopoptions = 1;
912 break;
914 for (s = 0; textopts[s].label; s++) {
915 if (!nasm_stricmp(p + 2, textopts[s].label)) {
916 break;
920 switch (s) {
922 case OPT_PREFIX:
923 case OPT_POSTFIX:
925 if (!q) {
926 report_error(ERR_NONFATAL | ERR_NOFILE |
927 ERR_USAGE,
928 "option `--%s' requires an argument",
929 p + 2);
930 break;
931 } else {
932 advance = 1, param = q;
935 if (s == OPT_PREFIX) {
936 strncpy(lprefix, param, PREFIX_MAX - 1);
937 lprefix[PREFIX_MAX - 1] = 0;
938 break;
940 if (s == OPT_POSTFIX) {
941 strncpy(lpostfix, param, POSTFIX_MAX - 1);
942 lpostfix[POSTFIX_MAX - 1] = 0;
943 break;
945 break;
947 default:
949 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
950 "unrecognised option `--%s'", p + 2);
951 break;
954 break;
957 default:
958 if (!ofmt->setinfo(GI_SWITCH, &p))
959 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
960 "unrecognised option `-%c'", p[1]);
961 break;
963 } else {
964 if (*inname) {
965 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
966 "more than one input file specified");
967 } else {
968 copy_filename(inname, p);
972 return advance;
975 #define ARG_BUF_DELTA 128
977 static void process_respfile(FILE * rfile)
979 char *buffer, *p, *q, *prevarg;
980 int bufsize, prevargsize;
982 bufsize = prevargsize = ARG_BUF_DELTA;
983 buffer = nasm_malloc(ARG_BUF_DELTA);
984 prevarg = nasm_malloc(ARG_BUF_DELTA);
985 prevarg[0] = '\0';
987 while (1) { /* Loop to handle all lines in file */
988 p = buffer;
989 while (1) { /* Loop to handle long lines */
990 q = fgets(p, bufsize - (p - buffer), rfile);
991 if (!q)
992 break;
993 p += strlen(p);
994 if (p > buffer && p[-1] == '\n')
995 break;
996 if (p - buffer > bufsize - 10) {
997 int offset;
998 offset = p - buffer;
999 bufsize += ARG_BUF_DELTA;
1000 buffer = nasm_realloc(buffer, bufsize);
1001 p = buffer + offset;
1005 if (!q && p == buffer) {
1006 if (prevarg[0])
1007 process_arg(prevarg, NULL);
1008 nasm_free(buffer);
1009 nasm_free(prevarg);
1010 return;
1014 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1015 * them are present at the end of the line.
1017 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1019 while (p > buffer && nasm_isspace(p[-1]))
1020 *--p = '\0';
1022 p = buffer;
1023 while (nasm_isspace(*p))
1024 p++;
1026 if (process_arg(prevarg, p))
1027 *p = '\0';
1029 if ((int) strlen(p) > prevargsize - 10) {
1030 prevargsize += ARG_BUF_DELTA;
1031 prevarg = nasm_realloc(prevarg, prevargsize);
1033 strncpy(prevarg, p, prevargsize);
1037 /* Function to process args from a string of args, rather than the
1038 * argv array. Used by the environment variable and response file
1039 * processing.
1041 static void process_args(char *args)
1043 char *p, *q, *arg, *prevarg;
1044 char separator = ' ';
1046 p = args;
1047 if (*p && *p != '-')
1048 separator = *p++;
1049 arg = NULL;
1050 while (*p) {
1051 q = p;
1052 while (*p && *p != separator)
1053 p++;
1054 while (*p == separator)
1055 *p++ = '\0';
1056 prevarg = arg;
1057 arg = q;
1058 if (process_arg(prevarg, arg))
1059 arg = NULL;
1061 if (arg)
1062 process_arg(arg, NULL);
1065 static void process_response_file(const char *file)
1067 char str[2048];
1068 FILE *f = fopen(file, "r");
1069 if (!f) {
1070 perror(file);
1071 exit(-1);
1073 while (fgets(str, sizeof str, f)) {
1074 process_args(str);
1076 fclose(f);
1079 static void parse_cmdline(int argc, char **argv)
1081 FILE *rfile;
1082 char *envreal, *envcopy = NULL, *p, *arg;
1083 int i;
1085 *inname = *outname = *listname = *errname = '\0';
1086 for (i = 0; i <= ERR_WARN_MAX; i++)
1087 warning_on_global[i] = warnings[i].enabled;
1090 * First, process the NASMENV environment variable.
1092 envreal = getenv("NASMENV");
1093 arg = NULL;
1094 if (envreal) {
1095 envcopy = nasm_strdup(envreal);
1096 process_args(envcopy);
1097 nasm_free(envcopy);
1101 * Now process the actual command line.
1103 while (--argc) {
1104 bool advance;
1105 argv++;
1106 if (argv[0][0] == '@') {
1107 /* We have a response file, so process this as a set of
1108 * arguments like the environment variable. This allows us
1109 * to have multiple arguments on a single line, which is
1110 * different to the -@resp file processing below for regular
1111 * NASM.
1113 process_response_file(argv[0]+1);
1114 argc--;
1115 argv++;
1117 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1118 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1119 if (p) {
1120 rfile = fopen(p, "r");
1121 if (rfile) {
1122 process_respfile(rfile);
1123 fclose(rfile);
1124 } else
1125 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1126 "unable to open response file `%s'", p);
1128 } else
1129 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1130 argv += advance, argc -= advance;
1133 /* Look for basic command line typos. This definitely doesn't
1134 catch all errors, but it might help cases of fumbled fingers. */
1135 if (!*inname)
1136 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1137 "no input file specified");
1138 else if (!strcmp(inname, errname) ||
1139 !strcmp(inname, outname) ||
1140 !strcmp(inname, listname) ||
1141 (depend_file && !strcmp(inname, depend_file)))
1142 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1143 "file `%s' is both input and output file",
1144 inname);
1146 if (*errname) {
1147 error_file = fopen(errname, "w");
1148 if (!error_file) {
1149 error_file = stderr; /* Revert to default! */
1150 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1151 "cannot open file `%s' for error messages",
1152 errname);
1157 static enum directives getkw(char **directive, char **value);
1159 static void assemble_file(char *fname, StrList **depend_ptr)
1161 char *directive, *value, *p, *q, *special, *line, debugid[80];
1162 insn output_ins;
1163 int i, validid;
1164 bool rn_error;
1165 int32_t seg;
1166 int64_t offs;
1167 struct tokenval tokval;
1168 expr *e;
1169 int pass_max;
1171 if (cmd_sb == 32 && cmd_cpu < IF_386)
1172 report_error(ERR_FATAL, "command line: "
1173 "32-bit segment size requires a higher cpu");
1175 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1176 for (passn = 1; pass0 <= 2; passn++) {
1177 int pass1, pass2;
1178 ldfunc def_label;
1180 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1181 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1182 /* pass0 0, 0, 0, ..., 1, 2 */
1184 def_label = passn > 1 ? redefine_label : define_label;
1186 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1187 cpu = cmd_cpu;
1188 if (pass0 == 2) {
1189 if (*listname)
1190 nasmlist.init(listname, report_error);
1192 in_abs_seg = false;
1193 global_offset_changed = 0; /* set by redefine_label */
1194 location.segment = ofmt->section(NULL, pass2, &sb);
1195 globalbits = sb;
1196 if (passn > 1) {
1197 saa_rewind(forwrefs);
1198 forwref = saa_rstruct(forwrefs);
1199 raa_free(offsets);
1200 offsets = raa_init();
1202 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1203 pass1 == 2 ? depend_ptr : NULL);
1204 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1206 globallineno = 0;
1207 if (passn == 1)
1208 location.known = true;
1209 location.offset = offs = GET_CURR_OFFS;
1211 while ((line = preproc->getline())) {
1212 enum directives d;
1213 globallineno++;
1216 * Here we parse our directives; this is not handled by the
1217 * 'real' parser. This really should be a separate function.
1219 directive = line;
1220 d = getkw(&directive, &value);
1221 if (d) {
1222 int err = 0;
1224 switch (d) {
1225 case D_SEGMENT: /* [SEGMENT n] */
1226 case D_SECTION:
1227 seg = ofmt->section(value, pass2, &sb);
1228 if (seg == NO_SEG) {
1229 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1230 "segment name `%s' not recognized",
1231 value);
1232 } else {
1233 in_abs_seg = false;
1234 location.segment = seg;
1236 break;
1237 case D_EXTERN: /* [EXTERN label:special] */
1238 if (*value == '$')
1239 value++; /* skip initial $ if present */
1240 if (pass0 == 2) {
1241 q = value;
1242 while (*q && *q != ':')
1243 q++;
1244 if (*q == ':') {
1245 *q++ = '\0';
1246 ofmt->symdef(value, 0L, 0L, 3, q);
1248 } else if (passn == 1) {
1249 q = value;
1250 validid = true;
1251 if (!isidstart(*q))
1252 validid = false;
1253 while (*q && *q != ':') {
1254 if (!isidchar(*q))
1255 validid = false;
1256 q++;
1258 if (!validid) {
1259 report_error(ERR_NONFATAL,
1260 "identifier expected after EXTERN");
1261 break;
1263 if (*q == ':') {
1264 *q++ = '\0';
1265 special = q;
1266 } else
1267 special = NULL;
1268 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1269 int temp = pass0;
1270 pass0 = 1; /* fake pass 1 in labels.c */
1271 declare_as_global(value, special,
1272 report_error);
1273 define_label(value, seg_alloc(), 0L, NULL,
1274 false, true, ofmt, report_error);
1275 pass0 = temp;
1277 } /* else pass0 == 1 */
1278 break;
1279 case D_BITS: /* [BITS bits] */
1280 globalbits = sb = get_bits(value);
1281 break;
1282 case D_GLOBAL: /* [GLOBAL symbol:special] */
1283 if (*value == '$')
1284 value++; /* skip initial $ if present */
1285 if (pass0 == 2) { /* pass 2 */
1286 q = value;
1287 while (*q && *q != ':')
1288 q++;
1289 if (*q == ':') {
1290 *q++ = '\0';
1291 ofmt->symdef(value, 0L, 0L, 3, q);
1293 } else if (pass2 == 1) { /* pass == 1 */
1294 q = value;
1295 validid = true;
1296 if (!isidstart(*q))
1297 validid = false;
1298 while (*q && *q != ':') {
1299 if (!isidchar(*q))
1300 validid = false;
1301 q++;
1303 if (!validid) {
1304 report_error(ERR_NONFATAL,
1305 "identifier expected after GLOBAL");
1306 break;
1308 if (*q == ':') {
1309 *q++ = '\0';
1310 special = q;
1311 } else
1312 special = NULL;
1313 declare_as_global(value, special, report_error);
1314 } /* pass == 1 */
1315 break;
1316 case D_COMMON: /* [COMMON symbol size:special] */
1318 int64_t size;
1320 if (*value == '$')
1321 value++; /* skip initial $ if present */
1322 p = value;
1323 validid = true;
1324 if (!isidstart(*p))
1325 validid = false;
1326 while (*p && !nasm_isspace(*p)) {
1327 if (!isidchar(*p))
1328 validid = false;
1329 p++;
1331 if (!validid) {
1332 report_error(ERR_NONFATAL,
1333 "identifier expected after COMMON");
1334 break;
1336 if (*p) {
1337 while (*p && nasm_isspace(*p))
1338 *p++ = '\0';
1339 q = p;
1340 while (*q && *q != ':')
1341 q++;
1342 if (*q == ':') {
1343 *q++ = '\0';
1344 special = q;
1345 } else {
1346 special = NULL;
1348 size = readnum(p, &rn_error);
1349 if (rn_error) {
1350 report_error(ERR_NONFATAL,
1351 "invalid size specified"
1352 " in COMMON declaration");
1353 break;
1355 } else {
1356 report_error(ERR_NONFATAL,
1357 "no size specified in"
1358 " COMMON declaration");
1359 break;
1362 if (pass0 < 2) {
1363 define_common(value, seg_alloc(), size,
1364 special, ofmt, report_error);
1365 } else if (pass0 == 2) {
1366 if (special)
1367 ofmt->symdef(value, 0L, 0L, 3, special);
1369 break;
1371 case D_ABSOLUTE: /* [ABSOLUTE address] */
1372 stdscan_reset();
1373 stdscan_bufptr = value;
1374 tokval.t_type = TOKEN_INVALID;
1375 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1376 report_error, NULL);
1377 if (e) {
1378 if (!is_reloc(e))
1379 report_error(pass0 ==
1380 1 ? ERR_NONFATAL : ERR_PANIC,
1381 "cannot use non-relocatable expression as "
1382 "ABSOLUTE address");
1383 else {
1384 abs_seg = reloc_seg(e);
1385 abs_offset = reloc_value(e);
1387 } else if (passn == 1)
1388 abs_offset = 0x100; /* don't go near zero in case of / */
1389 else
1390 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1391 "in pass two");
1392 in_abs_seg = true;
1393 location.segment = NO_SEG;
1394 break;
1395 case D_DEBUG: /* [DEBUG] */
1396 p = value;
1397 q = debugid;
1398 validid = true;
1399 if (!isidstart(*p))
1400 validid = false;
1401 while (*p && !nasm_isspace(*p)) {
1402 if (!isidchar(*p))
1403 validid = false;
1404 *q++ = *p++;
1406 *q++ = 0;
1407 if (!validid) {
1408 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1409 "identifier expected after DEBUG");
1410 break;
1412 while (*p && nasm_isspace(*p))
1413 p++;
1414 if (pass0 == 2)
1415 ofmt->current_dfmt->debug_directive(debugid, p);
1416 break;
1417 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1418 while (*value && nasm_isspace(*value))
1419 value++;
1421 switch(*value) {
1422 case '-': validid = 0; value++; break;
1423 case '+': validid = 1; value++; break;
1424 case '*': validid = 2; value++; break;
1425 default: validid = 1; break;
1428 for (i = 1; i <= ERR_WARN_MAX; i++)
1429 if (!nasm_stricmp(value, warnings[i].name))
1430 break;
1431 if (i <= ERR_WARN_MAX) {
1432 switch(validid) {
1433 case 0:
1434 warning_on[i] = false;
1435 break;
1436 case 1:
1437 warning_on[i] = true;
1438 break;
1439 case 2:
1440 warning_on[i] = warning_on_global[i];
1441 break;
1444 else
1445 report_error(ERR_NONFATAL,
1446 "invalid warning id in WARNING directive");
1447 break;
1448 case D_CPU: /* [CPU] */
1449 cpu = get_cpu(value);
1450 break;
1451 case D_LIST: /* [LIST {+|-}] */
1452 while (*value && nasm_isspace(*value))
1453 value++;
1455 if (*value == '+') {
1456 user_nolist = 0;
1457 } else {
1458 if (*value == '-') {
1459 user_nolist = 1;
1460 } else {
1461 err = 1;
1464 break;
1465 case D_DEFAULT: /* [DEFAULT] */
1466 stdscan_reset();
1467 stdscan_bufptr = value;
1468 tokval.t_type = TOKEN_INVALID;
1469 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1470 switch ((int)tokval.t_integer) {
1471 case S_REL:
1472 globalrel = 1;
1473 break;
1474 case S_ABS:
1475 globalrel = 0;
1476 break;
1477 default:
1478 err = 1;
1479 break;
1481 } else {
1482 err = 1;
1484 break;
1485 case D_FLOAT:
1486 if (float_option(value)) {
1487 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1488 "unknown 'float' directive: %s",
1489 value);
1491 break;
1492 default:
1493 if (!d || !ofmt->directive(d, value, pass2))
1494 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1495 "unrecognised directive [%s]",
1496 directive);
1497 break;
1499 if (err) {
1500 report_error(ERR_NONFATAL,
1501 "invalid parameter to [%s] directive",
1502 directive);
1504 } else { /* it isn't a directive */
1506 parse_line(pass1, line, &output_ins,
1507 report_error, evaluate, def_label);
1509 if (optimizing > 0) {
1510 if (forwref != NULL && globallineno == forwref->lineno) {
1511 output_ins.forw_ref = true;
1512 do {
1513 output_ins.oprs[forwref->operand].opflags |=
1514 OPFLAG_FORWARD;
1515 forwref = saa_rstruct(forwrefs);
1516 } while (forwref != NULL
1517 && forwref->lineno == globallineno);
1518 } else
1519 output_ins.forw_ref = false;
1521 if (output_ins.forw_ref) {
1522 if (passn == 1) {
1523 for (i = 0; i < output_ins.operands; i++) {
1524 if (output_ins.oprs[i].
1525 opflags & OPFLAG_FORWARD) {
1526 struct forwrefinfo *fwinf =
1527 (struct forwrefinfo *)
1528 saa_wstruct(forwrefs);
1529 fwinf->lineno = globallineno;
1530 fwinf->operand = i;
1537 /* forw_ref */
1538 if (output_ins.opcode == I_EQU) {
1539 if (pass1 == 1) {
1541 * Special `..' EQUs get processed in pass two,
1542 * except `..@' macro-processor EQUs which are done
1543 * in the normal place.
1545 if (!output_ins.label)
1546 report_error(ERR_NONFATAL,
1547 "EQU not preceded by label");
1549 else if (output_ins.label[0] != '.' ||
1550 output_ins.label[1] != '.' ||
1551 output_ins.label[2] == '@') {
1552 if (output_ins.operands == 1 &&
1553 (output_ins.oprs[0].type & IMMEDIATE) &&
1554 output_ins.oprs[0].wrt == NO_SEG) {
1555 bool isext = !!(output_ins.oprs[0].opflags
1556 & OPFLAG_EXTERN);
1557 def_label(output_ins.label,
1558 output_ins.oprs[0].segment,
1559 output_ins.oprs[0].offset, NULL,
1560 false, isext, ofmt,
1561 report_error);
1562 } else if (output_ins.operands == 2
1563 && (output_ins.oprs[0].type & IMMEDIATE)
1564 && (output_ins.oprs[0].type & COLON)
1565 && output_ins.oprs[0].segment == NO_SEG
1566 && output_ins.oprs[0].wrt == NO_SEG
1567 && (output_ins.oprs[1].type & IMMEDIATE)
1568 && output_ins.oprs[1].segment == NO_SEG
1569 && output_ins.oprs[1].wrt == NO_SEG) {
1570 def_label(output_ins.label,
1571 output_ins.oprs[0].offset | SEG_ABS,
1572 output_ins.oprs[1].offset,
1573 NULL, false, false, ofmt,
1574 report_error);
1575 } else
1576 report_error(ERR_NONFATAL,
1577 "bad syntax for EQU");
1579 } else {
1581 * Special `..' EQUs get processed here, except
1582 * `..@' macro processor EQUs which are done above.
1584 if (output_ins.label[0] == '.' &&
1585 output_ins.label[1] == '.' &&
1586 output_ins.label[2] != '@') {
1587 if (output_ins.operands == 1 &&
1588 (output_ins.oprs[0].type & IMMEDIATE)) {
1589 define_label(output_ins.label,
1590 output_ins.oprs[0].segment,
1591 output_ins.oprs[0].offset,
1592 NULL, false, false, ofmt,
1593 report_error);
1594 } else if (output_ins.operands == 2
1595 && (output_ins.oprs[0].
1596 type & IMMEDIATE)
1597 && (output_ins.oprs[0].type & COLON)
1598 && output_ins.oprs[0].segment ==
1599 NO_SEG
1600 && (output_ins.oprs[1].
1601 type & IMMEDIATE)
1602 && output_ins.oprs[1].segment ==
1603 NO_SEG) {
1604 define_label(output_ins.label,
1605 output_ins.oprs[0].
1606 offset | SEG_ABS,
1607 output_ins.oprs[1].offset,
1608 NULL, false, false, ofmt,
1609 report_error);
1610 } else
1611 report_error(ERR_NONFATAL,
1612 "bad syntax for EQU");
1615 } else { /* instruction isn't an EQU */
1617 if (pass1 == 1) {
1619 int64_t l = insn_size(location.segment, offs, sb, cpu,
1620 &output_ins, report_error);
1622 /* if (using_debug_info) && output_ins.opcode != -1) */
1623 if (using_debug_info)
1624 { /* fbk 03/25/01 */
1625 /* this is done here so we can do debug type info */
1626 int32_t typeinfo =
1627 TYS_ELEMENTS(output_ins.operands);
1628 switch (output_ins.opcode) {
1629 case I_RESB:
1630 typeinfo =
1631 TYS_ELEMENTS(output_ins.oprs[0].
1632 offset) | TY_BYTE;
1633 break;
1634 case I_RESW:
1635 typeinfo =
1636 TYS_ELEMENTS(output_ins.oprs[0].
1637 offset) | TY_WORD;
1638 break;
1639 case I_RESD:
1640 typeinfo =
1641 TYS_ELEMENTS(output_ins.oprs[0].
1642 offset) | TY_DWORD;
1643 break;
1644 case I_RESQ:
1645 typeinfo =
1646 TYS_ELEMENTS(output_ins.oprs[0].
1647 offset) | TY_QWORD;
1648 break;
1649 case I_REST:
1650 typeinfo =
1651 TYS_ELEMENTS(output_ins.oprs[0].
1652 offset) | TY_TBYTE;
1653 break;
1654 case I_RESO:
1655 typeinfo =
1656 TYS_ELEMENTS(output_ins.oprs[0].
1657 offset) | TY_OWORD;
1658 break;
1659 case I_RESY:
1660 typeinfo =
1661 TYS_ELEMENTS(output_ins.oprs[0].
1662 offset) | TY_YWORD;
1663 break;
1664 case I_DB:
1665 typeinfo |= TY_BYTE;
1666 break;
1667 case I_DW:
1668 typeinfo |= TY_WORD;
1669 break;
1670 case I_DD:
1671 if (output_ins.eops_float)
1672 typeinfo |= TY_FLOAT;
1673 else
1674 typeinfo |= TY_DWORD;
1675 break;
1676 case I_DQ:
1677 typeinfo |= TY_QWORD;
1678 break;
1679 case I_DT:
1680 typeinfo |= TY_TBYTE;
1681 break;
1682 case I_DO:
1683 typeinfo |= TY_OWORD;
1684 break;
1685 case I_DY:
1686 typeinfo |= TY_YWORD;
1687 break;
1688 default:
1689 typeinfo = TY_LABEL;
1693 ofmt->current_dfmt->debug_typevalue(typeinfo);
1696 if (l != -1) {
1697 offs += l;
1698 SET_CURR_OFFS(offs);
1701 * else l == -1 => invalid instruction, which will be
1702 * flagged as an error on pass 2
1705 } else {
1706 offs += assemble(location.segment, offs, sb, cpu,
1707 &output_ins, ofmt, report_error,
1708 &nasmlist);
1709 SET_CURR_OFFS(offs);
1712 } /* not an EQU */
1713 cleanup_insn(&output_ins);
1715 nasm_free(line);
1716 location.offset = offs = GET_CURR_OFFS;
1717 } /* end while (line = preproc->getline... */
1719 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1720 report_error(ERR_NONFATAL,
1721 "phase error detected at end of assembly.");
1723 if (pass1 == 1)
1724 preproc->cleanup(1);
1726 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1727 pass0++;
1728 } else if (global_offset_changed &&
1729 global_offset_changed < prev_offset_changed) {
1730 prev_offset_changed = global_offset_changed;
1731 stall_count = 0;
1732 } else {
1733 stall_count++;
1736 if (terminate_after_phase)
1737 break;
1739 if ((stall_count > 997) || (passn >= pass_max)) {
1740 /* We get here if the labels don't converge
1741 * Example: FOO equ FOO + 1
1743 report_error(ERR_NONFATAL,
1744 "Can't find valid values for all labels "
1745 "after %d passes, giving up.", passn);
1746 report_error(ERR_NONFATAL,
1747 "Possible causes: recursive EQUs, macro abuse.");
1748 break;
1752 preproc->cleanup(0);
1753 nasmlist.cleanup();
1754 if (!terminate_after_phase && opt_verbose_info) {
1755 /* -On and -Ov switches */
1756 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1760 static enum directives getkw(char **directive, char **value)
1762 char *p, *q, *buf;
1764 buf = *directive;
1766 /* allow leading spaces or tabs */
1767 while (*buf == ' ' || *buf == '\t')
1768 buf++;
1770 if (*buf != '[')
1771 return 0;
1773 p = buf;
1775 while (*p && *p != ']')
1776 p++;
1778 if (!*p)
1779 return 0;
1781 q = p++;
1783 while (*p && *p != ';') {
1784 if (!nasm_isspace(*p))
1785 return 0;
1786 p++;
1788 q[1] = '\0';
1790 *directive = p = buf + 1;
1791 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1792 buf++;
1793 if (*buf == ']') {
1794 *buf = '\0';
1795 *value = buf;
1796 } else {
1797 *buf++ = '\0';
1798 while (nasm_isspace(*buf))
1799 buf++; /* beppu - skip leading whitespace */
1800 *value = buf;
1801 while (*buf != ']')
1802 buf++;
1803 *buf++ = '\0';
1806 return find_directive(*directive);
1810 * gnu style error reporting
1811 * This function prints an error message to error_file in the
1812 * style used by GNU. An example would be:
1813 * file.asm:50: error: blah blah blah
1814 * where file.asm is the name of the file, 50 is the line number on
1815 * which the error occurs (or is detected) and "error:" is one of
1816 * the possible optional diagnostics -- it can be "error" or "warning"
1817 * or something else. Finally the line terminates with the actual
1818 * error message.
1820 * @param severity the severity of the warning or error
1821 * @param fmt the printf style format string
1823 static void report_error_gnu(int severity, const char *fmt, ...)
1825 va_list ap;
1826 char *currentfile = NULL;
1827 int32_t lineno = 0;
1829 if (is_suppressed_warning(severity))
1830 return;
1832 if (!(severity & ERR_NOFILE))
1833 src_get(&lineno, &currentfile);
1835 if (currentfile) {
1836 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1837 nasm_free(currentfile);
1838 } else {
1839 fputs("nasm: ", error_file);
1842 va_start(ap, fmt);
1843 report_error_common(severity, fmt, ap);
1844 va_end(ap);
1848 * MS style error reporting
1849 * This function prints an error message to error_file in the
1850 * style used by Visual C and some other Microsoft tools. An example
1851 * would be:
1852 * file.asm(50) : error: blah blah blah
1853 * where file.asm is the name of the file, 50 is the line number on
1854 * which the error occurs (or is detected) and "error:" is one of
1855 * the possible optional diagnostics -- it can be "error" or "warning"
1856 * or something else. Finally the line terminates with the actual
1857 * error message.
1859 * @param severity the severity of the warning or error
1860 * @param fmt the printf style format string
1862 static void report_error_vc(int severity, const char *fmt, ...)
1864 va_list ap;
1865 char *currentfile = NULL;
1866 int32_t lineno = 0;
1868 if (is_suppressed_warning(severity))
1869 return;
1871 if (!(severity & ERR_NOFILE))
1872 src_get(&lineno, &currentfile);
1874 if (currentfile) {
1875 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1876 nasm_free(currentfile);
1877 } else {
1878 fputs("nasm: ", error_file);
1881 va_start(ap, fmt);
1882 report_error_common(severity, fmt, ap);
1883 va_end(ap);
1887 * check for supressed warning
1888 * checks for suppressed warning or pass one only warning and we're
1889 * not in pass 1
1891 * @param severity the severity of the warning or error
1892 * @return true if we should abort error/warning printing
1894 static bool is_suppressed_warning(int severity)
1897 * See if it's a suppressed warning.
1899 return (severity & ERR_MASK) == ERR_WARNING &&
1900 (((severity & ERR_WARN_MASK) != 0 &&
1901 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1902 /* See if it's a pass-one only warning and we're not in pass one. */
1903 ((severity & ERR_PASS1) && pass0 != 1) ||
1904 ((severity & ERR_PASS2) && pass0 != 2));
1908 * common error reporting
1909 * This is the common back end of the error reporting schemes currently
1910 * implemented. It prints the nature of the warning and then the
1911 * specific error message to error_file and may or may not return. It
1912 * doesn't return if the error severity is a "panic" or "debug" type.
1914 * @param severity the severity of the warning or error
1915 * @param fmt the printf style format string
1917 static void report_error_common(int severity, const char *fmt,
1918 va_list args)
1920 char msg[1024];
1921 const char *pfx;
1923 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1924 case ERR_WARNING:
1925 pfx = "warning: ";
1926 break;
1927 case ERR_NONFATAL:
1928 pfx = "error: ";
1929 break;
1930 case ERR_FATAL:
1931 pfx = "fatal: ";
1932 break;
1933 case ERR_PANIC:
1934 pfx = "panic: ";
1935 break;
1936 case ERR_DEBUG:
1937 pfx = "debug: ";
1938 break;
1939 default:
1940 pfx = "";
1941 break;
1944 vsnprintf(msg, sizeof msg, fmt, args);
1946 fprintf(error_file, "%s%s\n", pfx, msg);
1948 if (*listname)
1949 nasmlist.error(severity, pfx, msg);
1951 if (severity & ERR_USAGE)
1952 want_usage = true;
1954 switch (severity & ERR_MASK) {
1955 case ERR_DEBUG:
1956 /* no further action, by definition */
1957 break;
1958 case ERR_WARNING:
1959 if (warning_on[0]) /* Treat warnings as errors */
1960 terminate_after_phase = true;
1961 break;
1962 case ERR_NONFATAL:
1963 terminate_after_phase = true;
1964 break;
1965 case ERR_FATAL:
1966 if (ofile) {
1967 fclose(ofile);
1968 remove(outname);
1969 ofile = NULL;
1971 if (want_usage)
1972 usage();
1973 exit(1); /* instantly die */
1974 break; /* placate silly compilers */
1975 case ERR_PANIC:
1976 fflush(NULL);
1977 /* abort(); *//* halt, catch fire, and dump core */
1978 exit(3);
1979 break;
1983 static void usage(void)
1985 fputs("type `nasm -h' for help\n", error_file);
1988 static void register_output_formats(void)
1990 ofmt = ofmt_register(report_error);
1993 #define BUF_DELTA 512
1995 static FILE *no_pp_fp;
1996 static efunc no_pp_err;
1997 static ListGen *no_pp_list;
1998 static int32_t no_pp_lineinc;
2000 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
2001 ListGen * listgen, StrList **deplist)
2003 src_set_fname(nasm_strdup(file));
2004 src_set_linnum(0);
2005 no_pp_lineinc = 1;
2006 no_pp_err = error;
2007 no_pp_fp = fopen(file, "r");
2008 if (!no_pp_fp)
2009 no_pp_err(ERR_FATAL | ERR_NOFILE,
2010 "unable to open input file `%s'", file);
2011 no_pp_list = listgen;
2012 (void)pass; /* placate compilers */
2013 (void)eval; /* placate compilers */
2015 if (deplist) {
2016 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2017 sl->next = NULL;
2018 strcpy(sl->str, file);
2019 *deplist = sl;
2023 static char *no_pp_getline(void)
2025 char *buffer, *p, *q;
2026 int bufsize;
2028 bufsize = BUF_DELTA;
2029 buffer = nasm_malloc(BUF_DELTA);
2030 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2032 while (1) { /* Loop to handle %line */
2034 p = buffer;
2035 while (1) { /* Loop to handle long lines */
2036 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2037 if (!q)
2038 break;
2039 p += strlen(p);
2040 if (p > buffer && p[-1] == '\n')
2041 break;
2042 if (p - buffer > bufsize - 10) {
2043 int offset;
2044 offset = p - buffer;
2045 bufsize += BUF_DELTA;
2046 buffer = nasm_realloc(buffer, bufsize);
2047 p = buffer + offset;
2051 if (!q && p == buffer) {
2052 nasm_free(buffer);
2053 return NULL;
2057 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2058 * them are present at the end of the line.
2060 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2062 if (!nasm_strnicmp(buffer, "%line", 5)) {
2063 int32_t ln;
2064 int li;
2065 char *nm = nasm_malloc(strlen(buffer));
2066 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2067 nasm_free(src_set_fname(nm));
2068 src_set_linnum(ln);
2069 no_pp_lineinc = li;
2070 continue;
2072 nasm_free(nm);
2074 break;
2077 no_pp_list->line(LIST_READ, buffer);
2079 return buffer;
2082 static void no_pp_cleanup(int pass)
2084 (void)pass; /* placate GCC */
2085 fclose(no_pp_fp);
2088 static uint32_t get_cpu(char *value)
2090 if (!strcmp(value, "8086"))
2091 return IF_8086;
2092 if (!strcmp(value, "186"))
2093 return IF_186;
2094 if (!strcmp(value, "286"))
2095 return IF_286;
2096 if (!strcmp(value, "386"))
2097 return IF_386;
2098 if (!strcmp(value, "486"))
2099 return IF_486;
2100 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2101 return IF_PENT;
2102 if (!strcmp(value, "686") ||
2103 !nasm_stricmp(value, "ppro") ||
2104 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2105 return IF_P6;
2106 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2107 return IF_KATMAI;
2108 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2109 !nasm_stricmp(value, "willamette"))
2110 return IF_WILLAMETTE;
2111 if (!nasm_stricmp(value, "prescott"))
2112 return IF_PRESCOTT;
2113 if (!nasm_stricmp(value, "x64") ||
2114 !nasm_stricmp(value, "x86-64"))
2115 return IF_X86_64;
2116 if (!nasm_stricmp(value, "ia64") ||
2117 !nasm_stricmp(value, "ia-64") ||
2118 !nasm_stricmp(value, "itanium") ||
2119 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2120 return IF_IA64;
2122 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2123 "unknown 'cpu' type");
2125 return IF_PLEVEL; /* the maximum level */
2128 static int get_bits(char *value)
2130 int i;
2132 if ((i = atoi(value)) == 16)
2133 return i; /* set for a 16-bit segment */
2134 else if (i == 32) {
2135 if (cpu < IF_386) {
2136 report_error(ERR_NONFATAL,
2137 "cannot specify 32-bit segment on processor below a 386");
2138 i = 16;
2140 } else if (i == 64) {
2141 if (cpu < IF_X86_64) {
2142 report_error(ERR_NONFATAL,
2143 "cannot specify 64-bit segment on processor below an x86-64");
2144 i = 16;
2146 if (i != maxbits) {
2147 report_error(ERR_NONFATAL,
2148 "%s output format does not support 64-bit code",
2149 ofmt->shortname);
2150 i = 16;
2152 } else {
2153 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2154 "`%s' is not a valid segment size; must be 16, 32 or 64",
2155 value);
2156 i = 16;
2158 return i;
2161 /* end of nasm.c */