Add copyright notice to insns.dat
[nasm.git] / nasm.c
blob2819b66b1f6500e3738810621c1f4a57f5e22124
1 /* The Netwide Assembler main program module
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the license given in the file "LICENSE"
6 * distributed in the NASM archive.
7 */
9 #include "compiler.h"
11 #include <stdio.h>
12 #include <stdarg.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <ctype.h>
16 #include <inttypes.h>
17 #include <limits.h>
18 #include <time.h>
20 #include "nasm.h"
21 #include "nasmlib.h"
22 #include "saa.h"
23 #include "raa.h"
24 #include "float.h"
25 #include "stdscan.h"
26 #include "insns.h"
27 #include "preproc.h"
28 #include "parser.h"
29 #include "eval.h"
30 #include "assemble.h"
31 #include "labels.h"
32 #include "output/outform.h"
33 #include "listing.h"
35 struct forwrefinfo { /* info held on forward refs. */
36 int lineno;
37 int operand;
40 static int get_bits(char *value);
41 static uint32_t get_cpu(char *cpu_str);
42 static void parse_cmdline(int, char **);
43 static void assemble_file(char *, StrList **);
44 static void register_output_formats(void);
45 static void report_error_gnu(int severity, const char *fmt, ...);
46 static void report_error_vc(int severity, const char *fmt, ...);
47 static void report_error_common(int severity, const char *fmt,
48 va_list args);
49 static bool is_suppressed_warning(int severity);
50 static void usage(void);
51 static efunc report_error;
53 static int using_debug_info, opt_verbose_info;
54 bool tasm_compatible_mode = false;
55 int pass0, passn;
56 int maxbits = 0;
57 int globalrel = 0;
59 time_t official_compile_time;
61 static char inname[FILENAME_MAX];
62 static char outname[FILENAME_MAX];
63 static char listname[FILENAME_MAX];
64 static char errname[FILENAME_MAX];
65 static int globallineno; /* for forward-reference tracking */
66 /* static int pass = 0; */
67 static struct ofmt *ofmt = NULL;
69 static FILE *error_file; /* Where to write error messages */
71 static FILE *ofile = NULL;
72 int optimizing = -1; /* number of optimization passes to take */
73 static int sb, cmd_sb = 16; /* by default */
74 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
75 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
76 int64_t global_offset_changed; /* referenced in labels.c */
77 int64_t prev_offset_changed;
78 int32_t stall_count;
80 static struct location location;
81 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
82 int32_t abs_seg; /* ABSOLUTE segment basis */
83 int32_t abs_offset; /* ABSOLUTE offset */
85 static struct RAA *offsets;
87 static struct SAA *forwrefs; /* keep track of forward references */
88 static const struct forwrefinfo *forwref;
90 static Preproc *preproc;
91 enum op_type {
92 op_normal, /* Preprocess and assemble */
93 op_preprocess, /* Preprocess only */
94 op_depend, /* Generate dependencies */
96 static enum op_type operating_mode;
97 /* Dependency flags */
98 static bool depend_emit_phony = false;
99 static bool depend_missing_ok = false;
100 static const char *depend_target = NULL;
101 static const char *depend_file = NULL;
104 * Which of the suppressible warnings are suppressed. Entry zero
105 * isn't an actual warning, but it used for -w+error/-Werror.
108 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
109 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
111 static const struct warning {
112 const char *name;
113 const char *help;
114 bool enabled;
115 } warnings[ERR_WARN_MAX+1] = {
116 {"error", "treat warnings as errors", false},
117 {"macro-params", "macro calls with wrong parameter count", true},
118 {"macro-selfref", "cyclic macro references", false},
119 {"macro-defaults", "macros with more default than optional parameters", true},
120 {"orphan-labels", "labels alone on lines without trailing `:'", true},
121 {"number-overflow", "numeric constant does not fit", true},
122 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
123 {"float-overflow", "floating point overflow", true},
124 {"float-denorm", "floating point denormal", false},
125 {"float-underflow", "floating point underflow", false},
126 {"float-toolong", "too many digits in floating-point number", true},
127 {"user", "%warning directives", true},
131 * This is a null preprocessor which just copies lines from input
132 * to output. It's used when someone explicitly requests that NASM
133 * not preprocess their source file.
136 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
137 static char *no_pp_getline(void);
138 static void no_pp_cleanup(int);
139 static Preproc no_pp = {
140 no_pp_reset,
141 no_pp_getline,
142 no_pp_cleanup
146 * get/set current offset...
148 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
149 raa_read(offsets,location.segment))
150 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
151 (void)(offsets=raa_write(offsets,location.segment,(x))))
153 static bool want_usage;
154 static bool terminate_after_phase;
155 int user_nolist = 0; /* fbk 9/2/00 */
157 static void nasm_fputs(const char *line, FILE * outfile)
159 if (outfile) {
160 fputs(line, outfile);
161 putc('\n', outfile);
162 } else
163 puts(line);
166 /* Convert a struct tm to a POSIX-style time constant */
167 static int64_t posix_mktime(struct tm *tm)
169 int64_t t;
170 int64_t y = tm->tm_year;
172 /* See IEEE 1003.1:2004, section 4.14 */
174 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
175 t += tm->tm_yday;
176 t *= 24;
177 t += tm->tm_hour;
178 t *= 60;
179 t += tm->tm_min;
180 t *= 60;
181 t += tm->tm_sec;
183 return t;
186 static void define_macros_early(void)
188 char temp[128];
189 struct tm lt, *lt_p, gm, *gm_p;
190 int64_t posix_time;
192 lt_p = localtime(&official_compile_time);
193 if (lt_p) {
194 lt = *lt_p;
196 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
197 pp_pre_define(temp);
198 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
199 pp_pre_define(temp);
200 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
201 pp_pre_define(temp);
202 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
203 pp_pre_define(temp);
206 gm_p = gmtime(&official_compile_time);
207 if (gm_p) {
208 gm = *gm_p;
210 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
211 pp_pre_define(temp);
212 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
213 pp_pre_define(temp);
214 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
215 pp_pre_define(temp);
216 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
217 pp_pre_define(temp);
220 if (gm_p)
221 posix_time = posix_mktime(&gm);
222 else if (lt_p)
223 posix_time = posix_mktime(&lt);
224 else
225 posix_time = 0;
227 if (posix_time) {
228 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
229 pp_pre_define(temp);
233 static void define_macros_late(void)
235 char temp[128];
237 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
238 ofmt->shortname);
239 pp_pre_define(temp);
242 static void emit_dependencies(StrList *list)
244 FILE *deps;
245 int linepos, len;
246 StrList *l, *nl;
248 if (depend_file && strcmp(depend_file, "-")) {
249 deps = fopen(depend_file, "w");
250 if (!deps) {
251 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
252 "unable to write dependency file `%s'", depend_file);
253 return;
255 } else {
256 deps = stdout;
259 linepos = fprintf(deps, "%s:", depend_target);
260 for (l = list; l; l = l->next) {
261 len = strlen(l->str);
262 if (linepos + len > 62) {
263 fprintf(deps, " \\\n ");
264 linepos = 1;
266 fprintf(deps, " %s", l->str);
267 linepos += len+1;
269 fprintf(deps, "\n\n");
271 for (l = list; l; l = nl) {
272 if (depend_emit_phony)
273 fprintf(deps, "%s:\n\n", l->str);
275 nl = l->next;
276 nasm_free(l);
279 if (deps != stdout)
280 fclose(deps);
283 int main(int argc, char **argv)
285 StrList *depend_list = NULL, **depend_ptr;
287 time(&official_compile_time);
289 pass0 = 0;
290 want_usage = terminate_after_phase = false;
291 report_error = report_error_gnu;
293 error_file = stderr;
295 tolower_init();
297 nasm_set_malloc_error(report_error);
298 offsets = raa_init();
299 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
301 preproc = &nasmpp;
302 operating_mode = op_normal;
304 seg_init();
306 register_output_formats();
308 /* Define some macros dependent on the runtime, but not
309 on the command line. */
310 define_macros_early();
312 parse_cmdline(argc, argv);
314 if (terminate_after_phase) {
315 if (want_usage)
316 usage();
317 return 1;
320 /* If debugging info is disabled, suppress any debug calls */
321 if (!using_debug_info)
322 ofmt->current_dfmt = &null_debug_form;
324 if (ofmt->stdmac)
325 pp_extra_stdmac(ofmt->stdmac);
326 parser_global_info(ofmt, &location);
327 eval_global_info(ofmt, lookup_label, &location);
329 /* define some macros dependent of command-line */
330 define_macros_late();
332 depend_ptr = (depend_file || (operating_mode == op_depend))
333 ? &depend_list : NULL;
334 if (!depend_target)
335 depend_target = outname;
337 switch (operating_mode) {
338 case op_depend:
340 char *line;
342 if (depend_missing_ok)
343 pp_include_path(NULL); /* "assume generated" */
345 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
346 depend_ptr);
347 if (outname[0] == '\0')
348 ofmt->filename(inname, outname, report_error);
349 ofile = NULL;
350 while ((line = preproc->getline()))
351 nasm_free(line);
352 preproc->cleanup(0);
354 break;
356 case op_preprocess:
358 char *line;
359 char *file_name = NULL;
360 int32_t prior_linnum = 0;
361 int lineinc = 0;
363 if (*outname) {
364 ofile = fopen(outname, "w");
365 if (!ofile)
366 report_error(ERR_FATAL | ERR_NOFILE,
367 "unable to open output file `%s'",
368 outname);
369 } else
370 ofile = NULL;
372 location.known = false;
374 /* pass = 1; */
375 preproc->reset(inname, 3, report_error, evaluate, &nasmlist,
376 depend_ptr);
378 while ((line = preproc->getline())) {
380 * We generate %line directives if needed for later programs
382 int32_t linnum = prior_linnum += lineinc;
383 int altline = src_get(&linnum, &file_name);
384 if (altline) {
385 if (altline == 1 && lineinc == 1)
386 nasm_fputs("", ofile);
387 else {
388 lineinc = (altline != -1 || lineinc != 1);
389 fprintf(ofile ? ofile : stdout,
390 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
391 file_name);
393 prior_linnum = linnum;
395 nasm_fputs(line, ofile);
396 nasm_free(line);
398 nasm_free(file_name);
399 preproc->cleanup(0);
400 if (ofile)
401 fclose(ofile);
402 if (ofile && terminate_after_phase)
403 remove(outname);
405 break;
407 case op_normal:
410 * We must call ofmt->filename _anyway_, even if the user
411 * has specified their own output file, because some
412 * formats (eg OBJ and COFF) use ofmt->filename to find out
413 * the name of the input file and then put that inside the
414 * file.
416 ofmt->filename(inname, outname, report_error);
418 ofile = fopen(outname, "wb");
419 if (!ofile) {
420 report_error(ERR_FATAL | ERR_NOFILE,
421 "unable to open output file `%s'", outname);
425 * We must call init_labels() before ofmt->init() since
426 * some object formats will want to define labels in their
427 * init routines. (eg OS/2 defines the FLAT group)
429 init_labels();
431 ofmt->init(ofile, report_error, define_label, evaluate);
432 ofmt->current_dfmt->init(ofmt, NULL, ofile, report_error);
434 assemble_file(inname, depend_ptr);
436 if (!terminate_after_phase) {
437 ofmt->cleanup(using_debug_info);
438 cleanup_labels();
439 } else {
441 * Despite earlier comments, we need this fclose.
442 * The object output drivers only fclose on cleanup,
443 * and we just skipped that.
445 fclose (ofile);
447 remove(outname);
448 if (listname[0])
449 remove(listname);
452 break;
455 if (depend_list && !terminate_after_phase)
456 emit_dependencies(depend_list);
458 if (want_usage)
459 usage();
461 raa_free(offsets);
462 saa_free(forwrefs);
463 eval_cleanup();
464 stdscan_cleanup();
466 return terminate_after_phase;
470 * Get a parameter for a command line option.
471 * First arg must be in the form of e.g. -f...
473 static char *get_param(char *p, char *q, bool *advance)
475 *advance = false;
476 if (p[2]) { /* the parameter's in the option */
477 p += 2;
478 while (nasm_isspace(*p))
479 p++;
480 return p;
482 if (q && q[0]) {
483 *advance = true;
484 return q;
486 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
487 "option `-%c' requires an argument", p[1]);
488 return NULL;
492 * Copy a filename
494 static void copy_filename(char *dst, const char *src)
496 size_t len = strlen(src);
498 if (len >= (size_t)FILENAME_MAX) {
499 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
500 return;
502 strncpy(dst, src, FILENAME_MAX);
506 * Convert a string to Make-safe form
508 static char *quote_for_make(const char *str)
510 const char *p;
511 char *os, *q;
513 size_t n = 1; /* Terminating zero */
514 size_t nbs = 0;
516 if (!str)
517 return NULL;
519 for (p = str; *p; p++) {
520 switch (*p) {
521 case ' ':
522 case '\t':
523 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
524 n += nbs + 2;
525 nbs = 0;
526 break;
527 case '$':
528 case '#':
529 nbs = 0;
530 n += 2;
531 break;
532 case '\\':
533 nbs++;
534 n++;
535 break;
536 default:
537 nbs = 0;
538 n++;
539 break;
543 /* Convert N backslashes at the end of filename to 2N backslashes */
544 if (nbs)
545 n += nbs;
547 os = q = nasm_malloc(n);
549 nbs = 0;
550 for (p = str; *p; p++) {
551 switch (*p) {
552 case ' ':
553 case '\t':
554 while (nbs--)
555 *q++ = '\\';
556 *q++ = '\\';
557 *q++ = *p;
558 break;
559 case '$':
560 *q++ = *p;
561 *q++ = *p;
562 nbs = 0;
563 break;
564 case '#':
565 *q++ = '\\';
566 *q++ = *p;
567 nbs = 0;
568 break;
569 case '\\':
570 *q++ = *p;
571 nbs++;
572 break;
573 default:
574 *q++ = *p;
575 nbs = 0;
576 break;
579 while (nbs--)
580 *q++ = '\\';
582 *q = '\0';
584 return os;
587 struct textargs {
588 const char *label;
589 int value;
592 #define OPT_PREFIX 0
593 #define OPT_POSTFIX 1
594 struct textargs textopts[] = {
595 {"prefix", OPT_PREFIX},
596 {"postfix", OPT_POSTFIX},
597 {NULL, 0}
600 static bool stopoptions = false;
601 static bool process_arg(char *p, char *q)
603 char *param;
604 int i;
605 bool advance = false;
606 bool do_warn;
608 if (!p || !p[0])
609 return false;
611 if (p[0] == '-' && !stopoptions) {
612 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
613 /* These parameters take values */
614 if (!(param = get_param(p, q, &advance)))
615 return advance;
618 switch (p[1]) {
619 case 's':
620 error_file = stdout;
621 break;
623 case 'o': /* output file */
624 copy_filename(outname, param);
625 break;
627 case 'f': /* output format */
628 ofmt = ofmt_find(param);
629 if (!ofmt) {
630 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
631 "unrecognised output format `%s' - "
632 "use -hf for a list", param);
634 break;
636 case 'O': /* Optimization level */
638 int opt;
640 if (!*param) {
641 /* Naked -O == -Ox */
642 optimizing = INT_MAX >> 1; /* Almost unlimited */
643 } else {
644 while (*param) {
645 switch (*param) {
646 case '0': case '1': case '2': case '3': case '4':
647 case '5': case '6': case '7': case '8': case '9':
648 opt = strtoul(param, &param, 10);
650 /* -O0 -> optimizing == -1, 0.98 behaviour */
651 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
652 if (opt < 2)
653 optimizing = opt - 1;
654 else
655 optimizing = opt;
656 break;
658 case 'v':
659 case '+':
660 param++;
661 opt_verbose_info = true;
662 break;
664 case 'x':
665 param++;
666 optimizing = INT_MAX >> 1; /* Almost unlimited */
667 break;
669 default:
670 report_error(ERR_FATAL,
671 "unknown optimization option -O%c\n",
672 *param);
673 break;
677 break;
680 case 'p': /* pre-include */
681 case 'P':
682 pp_pre_include(param);
683 break;
685 case 'd': /* pre-define */
686 case 'D':
687 pp_pre_define(param);
688 break;
690 case 'u': /* un-define */
691 case 'U':
692 pp_pre_undefine(param);
693 break;
695 case 'i': /* include search path */
696 case 'I':
697 pp_include_path(param);
698 break;
700 case 'l': /* listing file */
701 copy_filename(listname, param);
702 break;
704 case 'Z': /* error messages file */
705 strcpy(errname, param);
706 break;
708 case 'F': /* specify debug format */
709 ofmt->current_dfmt = dfmt_find(ofmt, param);
710 if (!ofmt->current_dfmt) {
711 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
712 "unrecognized debug format `%s' for"
713 " output format `%s'",
714 param, ofmt->shortname);
716 using_debug_info = true;
717 break;
719 case 'X': /* specify error reporting format */
720 if (nasm_stricmp("vc", param) == 0)
721 report_error = report_error_vc;
722 else if (nasm_stricmp("gnu", param) == 0)
723 report_error = report_error_gnu;
724 else
725 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
726 "unrecognized error reporting format `%s'",
727 param);
728 break;
730 case 'g':
731 using_debug_info = true;
732 break;
734 case 'h':
735 printf
736 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
737 "[-l listfile]\n"
738 " [options...] [--] filename\n"
739 " or nasm -v for version info\n\n"
740 " -t assemble in SciTech TASM compatible mode\n"
741 " -g generate debug information in selected format.\n");
742 printf
743 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
744 " -a don't preprocess (assemble only)\n"
745 " -M generate Makefile dependencies on stdout\n"
746 " -MG d:o, missing files assumed generated\n\n"
747 " -Z<file> redirect error messages to file\n"
748 " -s redirect error messages to stdout\n\n"
749 " -F format select a debugging format\n\n"
750 " -I<path> adds a pathname to the include file path\n");
751 printf
752 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
753 " -P<file> pre-includes a file\n"
754 " -D<macro>[=<value>] pre-defines a macro\n"
755 " -U<macro> undefines a macro\n"
756 " -X<format> specifies error reporting format (gnu or vc)\n"
757 " -w+foo enables warning foo (equiv. -Wfoo)\n"
758 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
759 "Warnings:\n");
760 for (i = 0; i <= ERR_WARN_MAX; i++)
761 printf(" %-23s %s (default %s)\n",
762 warnings[i].name, warnings[i].help,
763 warnings[i].enabled ? "on" : "off");
764 printf
765 ("\nresponse files should contain command line parameters"
766 ", one per line.\n");
767 if (p[2] == 'f') {
768 printf("\nvalid output formats for -f are"
769 " (`*' denotes default):\n");
770 ofmt_list(ofmt, stdout);
771 } else {
772 printf("\nFor a list of valid output formats, use -hf.\n");
773 printf("For a list of debug formats, use -f <form> -y.\n");
775 exit(0); /* never need usage message here */
776 break;
778 case 'y':
779 printf("\nvalid debug formats for '%s' output format are"
780 " ('*' denotes default):\n", ofmt->shortname);
781 dfmt_list(ofmt, stdout);
782 exit(0);
783 break;
785 case 't':
786 tasm_compatible_mode = true;
787 break;
789 case 'v':
790 printf("NASM version %s compiled on %s%s\n",
791 nasm_version, nasm_date, nasm_compile_options);
792 exit(0); /* never need usage message here */
793 break;
795 case 'e': /* preprocess only */
796 case 'E':
797 operating_mode = op_preprocess;
798 break;
800 case 'a': /* assemble only - don't preprocess */
801 preproc = &no_pp;
802 break;
804 case 'W':
805 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
806 do_warn = false;
807 param += 3;
808 } else {
809 do_warn = true;
811 goto set_warning;
813 case 'w':
814 if (param[0] != '+' && param[0] != '-') {
815 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
816 "invalid option to `-w'");
817 break;
819 do_warn = (param[0] == '+');
820 param++;
821 goto set_warning;
822 set_warning:
823 for (i = 0; i <= ERR_WARN_MAX; i++)
824 if (!nasm_stricmp(param, warnings[i].name))
825 break;
826 if (i <= ERR_WARN_MAX)
827 warning_on_global[i] = do_warn;
828 else if (!nasm_stricmp(param, "all"))
829 for (i = 1; i <= ERR_WARN_MAX; i++)
830 warning_on_global[i] = do_warn;
831 else if (!nasm_stricmp(param, "none"))
832 for (i = 1; i <= ERR_WARN_MAX; i++)
833 warning_on_global[i] = !do_warn;
834 else
835 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
836 "invalid warning `%s'", param);
837 break;
839 case 'M':
840 switch (p[2]) {
841 case 0:
842 operating_mode = op_depend;
843 break;
844 case 'G':
845 operating_mode = op_depend;
846 depend_missing_ok = true;
847 break;
848 case 'P':
849 depend_emit_phony = true;
850 break;
851 case 'D':
852 depend_file = q;
853 advance = true;
854 break;
855 case 'T':
856 depend_target = q;
857 advance = true;
858 break;
859 case 'Q':
860 depend_target = quote_for_make(q);
861 advance = true;
862 break;
863 default:
864 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
865 "unknown dependency option `-M%c'", p[2]);
866 break;
868 if (advance && (!q || !q[0])) {
869 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
870 "option `-M%c' requires a parameter", p[2]);
871 break;
873 break;
875 case '-':
877 int s;
879 if (p[2] == 0) { /* -- => stop processing options */
880 stopoptions = 1;
881 break;
883 for (s = 0; textopts[s].label; s++) {
884 if (!nasm_stricmp(p + 2, textopts[s].label)) {
885 break;
889 switch (s) {
891 case OPT_PREFIX:
892 case OPT_POSTFIX:
894 if (!q) {
895 report_error(ERR_NONFATAL | ERR_NOFILE |
896 ERR_USAGE,
897 "option `--%s' requires an argument",
898 p + 2);
899 break;
900 } else {
901 advance = 1, param = q;
904 if (s == OPT_PREFIX) {
905 strncpy(lprefix, param, PREFIX_MAX - 1);
906 lprefix[PREFIX_MAX - 1] = 0;
907 break;
909 if (s == OPT_POSTFIX) {
910 strncpy(lpostfix, param, POSTFIX_MAX - 1);
911 lpostfix[POSTFIX_MAX - 1] = 0;
912 break;
914 break;
916 default:
918 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
919 "unrecognised option `--%s'", p + 2);
920 break;
923 break;
926 default:
927 if (!ofmt->setinfo(GI_SWITCH, &p))
928 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
929 "unrecognised option `-%c'", p[1]);
930 break;
932 } else {
933 if (*inname) {
934 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
935 "more than one input file specified");
936 } else {
937 copy_filename(inname, p);
941 return advance;
944 #define ARG_BUF_DELTA 128
946 static void process_respfile(FILE * rfile)
948 char *buffer, *p, *q, *prevarg;
949 int bufsize, prevargsize;
951 bufsize = prevargsize = ARG_BUF_DELTA;
952 buffer = nasm_malloc(ARG_BUF_DELTA);
953 prevarg = nasm_malloc(ARG_BUF_DELTA);
954 prevarg[0] = '\0';
956 while (1) { /* Loop to handle all lines in file */
957 p = buffer;
958 while (1) { /* Loop to handle long lines */
959 q = fgets(p, bufsize - (p - buffer), rfile);
960 if (!q)
961 break;
962 p += strlen(p);
963 if (p > buffer && p[-1] == '\n')
964 break;
965 if (p - buffer > bufsize - 10) {
966 int offset;
967 offset = p - buffer;
968 bufsize += ARG_BUF_DELTA;
969 buffer = nasm_realloc(buffer, bufsize);
970 p = buffer + offset;
974 if (!q && p == buffer) {
975 if (prevarg[0])
976 process_arg(prevarg, NULL);
977 nasm_free(buffer);
978 nasm_free(prevarg);
979 return;
983 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
984 * them are present at the end of the line.
986 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
988 while (p > buffer && nasm_isspace(p[-1]))
989 *--p = '\0';
991 p = buffer;
992 while (nasm_isspace(*p))
993 p++;
995 if (process_arg(prevarg, p))
996 *p = '\0';
998 if ((int) strlen(p) > prevargsize - 10) {
999 prevargsize += ARG_BUF_DELTA;
1000 prevarg = nasm_realloc(prevarg, prevargsize);
1002 strncpy(prevarg, p, prevargsize);
1006 /* Function to process args from a string of args, rather than the
1007 * argv array. Used by the environment variable and response file
1008 * processing.
1010 static void process_args(char *args)
1012 char *p, *q, *arg, *prevarg;
1013 char separator = ' ';
1015 p = args;
1016 if (*p && *p != '-')
1017 separator = *p++;
1018 arg = NULL;
1019 while (*p) {
1020 q = p;
1021 while (*p && *p != separator)
1022 p++;
1023 while (*p == separator)
1024 *p++ = '\0';
1025 prevarg = arg;
1026 arg = q;
1027 if (process_arg(prevarg, arg))
1028 arg = NULL;
1030 if (arg)
1031 process_arg(arg, NULL);
1034 static void process_response_file(const char *file)
1036 char str[2048];
1037 FILE *f = fopen(file, "r");
1038 if (!f) {
1039 perror(file);
1040 exit(-1);
1042 while (fgets(str, sizeof str, f)) {
1043 process_args(str);
1045 fclose(f);
1048 static void parse_cmdline(int argc, char **argv)
1050 FILE *rfile;
1051 char *envreal, *envcopy = NULL, *p, *arg;
1052 int i;
1054 *inname = *outname = *listname = *errname = '\0';
1055 for (i = 0; i <= ERR_WARN_MAX; i++)
1056 warning_on_global[i] = warnings[i].enabled;
1059 * First, process the NASMENV environment variable.
1061 envreal = getenv("NASMENV");
1062 arg = NULL;
1063 if (envreal) {
1064 envcopy = nasm_strdup(envreal);
1065 process_args(envcopy);
1066 nasm_free(envcopy);
1070 * Now process the actual command line.
1072 while (--argc) {
1073 bool advance;
1074 argv++;
1075 if (argv[0][0] == '@') {
1076 /* We have a response file, so process this as a set of
1077 * arguments like the environment variable. This allows us
1078 * to have multiple arguments on a single line, which is
1079 * different to the -@resp file processing below for regular
1080 * NASM.
1082 process_response_file(argv[0]+1);
1083 argc--;
1084 argv++;
1086 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1087 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1088 if (p) {
1089 rfile = fopen(p, "r");
1090 if (rfile) {
1091 process_respfile(rfile);
1092 fclose(rfile);
1093 } else
1094 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1095 "unable to open response file `%s'", p);
1097 } else
1098 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1099 argv += advance, argc -= advance;
1102 /* Look for basic command line typos. This definitely doesn't
1103 catch all errors, but it might help cases of fumbled fingers. */
1104 if (!*inname)
1105 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1106 "no input file specified");
1107 else if (!strcmp(inname, errname) ||
1108 !strcmp(inname, outname) ||
1109 !strcmp(inname, listname) ||
1110 (depend_file && !strcmp(inname, depend_file)))
1111 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1112 "file `%s' is both input and output file",
1113 inname);
1115 if (*errname) {
1116 error_file = fopen(errname, "w");
1117 if (!error_file) {
1118 error_file = stderr; /* Revert to default! */
1119 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1120 "cannot open file `%s' for error messages",
1121 errname);
1126 /* List of directives */
1127 enum directives {
1128 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1129 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1131 static const char *directives[] = {
1132 "", "absolute", "bits", "common", "cpu", "debug", "default",
1133 "extern", "float", "global", "list", "section", "segment", "warning"
1135 static enum directives getkw(char **directive, char **value);
1137 static void assemble_file(char *fname, StrList **depend_ptr)
1139 char *directive, *value, *p, *q, *special, *line, debugid[80];
1140 insn output_ins;
1141 int i, validid;
1142 bool rn_error;
1143 int32_t seg;
1144 int64_t offs;
1145 struct tokenval tokval;
1146 expr *e;
1147 int pass_max;
1149 if (cmd_sb == 32 && cmd_cpu < IF_386)
1150 report_error(ERR_FATAL, "command line: "
1151 "32-bit segment size requires a higher cpu");
1153 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1154 for (passn = 1; pass0 <= 2; passn++) {
1155 int pass1, pass2;
1156 ldfunc def_label;
1158 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1159 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1160 /* pass0 0, 0, 0, ..., 1, 2 */
1162 def_label = passn > 1 ? redefine_label : define_label;
1164 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1165 cpu = cmd_cpu;
1166 if (pass0 == 2) {
1167 if (*listname)
1168 nasmlist.init(listname, report_error);
1170 in_abs_seg = false;
1171 global_offset_changed = 0; /* set by redefine_label */
1172 location.segment = ofmt->section(NULL, pass2, &sb);
1173 globalbits = sb;
1174 if (passn > 1) {
1175 saa_rewind(forwrefs);
1176 forwref = saa_rstruct(forwrefs);
1177 raa_free(offsets);
1178 offsets = raa_init();
1180 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1181 pass1 == 2 ? depend_ptr : NULL);
1182 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1184 globallineno = 0;
1185 if (passn == 1)
1186 location.known = true;
1187 location.offset = offs = GET_CURR_OFFS;
1189 while ((line = preproc->getline())) {
1190 enum directives d;
1191 globallineno++;
1194 * Here we parse our directives; this is not handled by the
1195 * 'real' parser. This really should be a separate function.
1197 directive = line;
1198 d = getkw(&directive, &value);
1199 if (d) {
1200 int err = 0;
1202 switch (d) {
1203 case D_SEGMENT: /* [SEGMENT n] */
1204 case D_SECTION:
1205 seg = ofmt->section(value, pass2, &sb);
1206 if (seg == NO_SEG) {
1207 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1208 "segment name `%s' not recognized",
1209 value);
1210 } else {
1211 in_abs_seg = false;
1212 location.segment = seg;
1214 break;
1215 case D_EXTERN: /* [EXTERN label:special] */
1216 if (*value == '$')
1217 value++; /* skip initial $ if present */
1218 if (pass0 == 2) {
1219 q = value;
1220 while (*q && *q != ':')
1221 q++;
1222 if (*q == ':') {
1223 *q++ = '\0';
1224 ofmt->symdef(value, 0L, 0L, 3, q);
1226 } else if (passn == 1) {
1227 q = value;
1228 validid = true;
1229 if (!isidstart(*q))
1230 validid = false;
1231 while (*q && *q != ':') {
1232 if (!isidchar(*q))
1233 validid = false;
1234 q++;
1236 if (!validid) {
1237 report_error(ERR_NONFATAL,
1238 "identifier expected after EXTERN");
1239 break;
1241 if (*q == ':') {
1242 *q++ = '\0';
1243 special = q;
1244 } else
1245 special = NULL;
1246 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1247 int temp = pass0;
1248 pass0 = 1; /* fake pass 1 in labels.c */
1249 declare_as_global(value, special,
1250 report_error);
1251 define_label(value, seg_alloc(), 0L, NULL,
1252 false, true, ofmt, report_error);
1253 pass0 = temp;
1255 } /* else pass0 == 1 */
1256 break;
1257 case D_BITS: /* [BITS bits] */
1258 globalbits = sb = get_bits(value);
1259 break;
1260 case D_GLOBAL: /* [GLOBAL symbol:special] */
1261 if (*value == '$')
1262 value++; /* skip initial $ if present */
1263 if (pass0 == 2) { /* pass 2 */
1264 q = value;
1265 while (*q && *q != ':')
1266 q++;
1267 if (*q == ':') {
1268 *q++ = '\0';
1269 ofmt->symdef(value, 0L, 0L, 3, q);
1271 } else if (pass2 == 1) { /* pass == 1 */
1272 q = value;
1273 validid = true;
1274 if (!isidstart(*q))
1275 validid = false;
1276 while (*q && *q != ':') {
1277 if (!isidchar(*q))
1278 validid = false;
1279 q++;
1281 if (!validid) {
1282 report_error(ERR_NONFATAL,
1283 "identifier expected after GLOBAL");
1284 break;
1286 if (*q == ':') {
1287 *q++ = '\0';
1288 special = q;
1289 } else
1290 special = NULL;
1291 declare_as_global(value, special, report_error);
1292 } /* pass == 1 */
1293 break;
1294 case D_COMMON: /* [COMMON symbol size:special] */
1296 int64_t size;
1298 if (*value == '$')
1299 value++; /* skip initial $ if present */
1300 p = value;
1301 validid = true;
1302 if (!isidstart(*p))
1303 validid = false;
1304 while (*p && !nasm_isspace(*p)) {
1305 if (!isidchar(*p))
1306 validid = false;
1307 p++;
1309 if (!validid) {
1310 report_error(ERR_NONFATAL,
1311 "identifier expected after COMMON");
1312 break;
1314 if (*p) {
1315 while (*p && nasm_isspace(*p))
1316 *p++ = '\0';
1317 q = p;
1318 while (*q && *q != ':')
1319 q++;
1320 if (*q == ':') {
1321 *q++ = '\0';
1322 special = q;
1323 } else {
1324 special = NULL;
1326 size = readnum(p, &rn_error);
1327 if (rn_error) {
1328 report_error(ERR_NONFATAL,
1329 "invalid size specified"
1330 " in COMMON declaration");
1331 break;
1333 } else {
1334 report_error(ERR_NONFATAL,
1335 "no size specified in"
1336 " COMMON declaration");
1337 break;
1340 if (pass0 < 2) {
1341 define_common(value, seg_alloc(), size,
1342 special, ofmt, report_error);
1343 } else if (pass0 == 2) {
1344 ofmt->symdef(value, 0L, 0L, 3, special);
1346 break;
1348 case D_ABSOLUTE: /* [ABSOLUTE address] */
1349 stdscan_reset();
1350 stdscan_bufptr = value;
1351 tokval.t_type = TOKEN_INVALID;
1352 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1353 report_error, NULL);
1354 if (e) {
1355 if (!is_reloc(e))
1356 report_error(pass0 ==
1357 1 ? ERR_NONFATAL : ERR_PANIC,
1358 "cannot use non-relocatable expression as "
1359 "ABSOLUTE address");
1360 else {
1361 abs_seg = reloc_seg(e);
1362 abs_offset = reloc_value(e);
1364 } else if (passn == 1)
1365 abs_offset = 0x100; /* don't go near zero in case of / */
1366 else
1367 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1368 "in pass two");
1369 in_abs_seg = true;
1370 location.segment = NO_SEG;
1371 break;
1372 case D_DEBUG: /* [DEBUG] */
1373 p = value;
1374 q = debugid;
1375 validid = true;
1376 if (!isidstart(*p))
1377 validid = false;
1378 while (*p && !nasm_isspace(*p)) {
1379 if (!isidchar(*p))
1380 validid = false;
1381 *q++ = *p++;
1383 *q++ = 0;
1384 if (!validid) {
1385 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1386 "identifier expected after DEBUG");
1387 break;
1389 while (*p && nasm_isspace(*p))
1390 p++;
1391 if (pass0 == 2)
1392 ofmt->current_dfmt->debug_directive(debugid, p);
1393 break;
1394 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1395 while (*value && nasm_isspace(*value))
1396 value++;
1398 switch(*value) {
1399 case '-': validid = 0; value++; break;
1400 case '+': validid = 1; value++; break;
1401 case '*': validid = 2; value++; break;
1402 default: validid = 1; break;
1405 for (i = 1; i <= ERR_WARN_MAX; i++)
1406 if (!nasm_stricmp(value, warnings[i].name))
1407 break;
1408 if (i <= ERR_WARN_MAX) {
1409 switch(validid) {
1410 case 0:
1411 warning_on[i] = false;
1412 break;
1413 case 1:
1414 warning_on[i] = true;
1415 break;
1416 case 2:
1417 warning_on[i] = warning_on_global[i];
1418 break;
1421 else
1422 report_error(ERR_NONFATAL,
1423 "invalid warning id in WARNING directive");
1424 break;
1425 case D_CPU: /* [CPU] */
1426 cpu = get_cpu(value);
1427 break;
1428 case D_LIST: /* [LIST {+|-}] */
1429 while (*value && nasm_isspace(*value))
1430 value++;
1432 if (*value == '+') {
1433 user_nolist = 0;
1434 } else {
1435 if (*value == '-') {
1436 user_nolist = 1;
1437 } else {
1438 err = 1;
1441 break;
1442 case D_DEFAULT: /* [DEFAULT] */
1443 stdscan_reset();
1444 stdscan_bufptr = value;
1445 tokval.t_type = TOKEN_INVALID;
1446 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1447 switch ((int)tokval.t_integer) {
1448 case S_REL:
1449 globalrel = 1;
1450 break;
1451 case S_ABS:
1452 globalrel = 0;
1453 break;
1454 default:
1455 err = 1;
1456 break;
1458 } else {
1459 err = 1;
1461 break;
1462 case D_FLOAT:
1463 if (float_option(value)) {
1464 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1465 "unknown 'float' directive: %s",
1466 value);
1468 break;
1469 default:
1470 if (!ofmt->directive(directive, value, pass2))
1471 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1472 "unrecognised directive [%s]",
1473 directive);
1475 if (err) {
1476 report_error(ERR_NONFATAL,
1477 "invalid parameter to [%s] directive",
1478 directive);
1480 } else { /* it isn't a directive */
1482 parse_line(pass1, line, &output_ins,
1483 report_error, evaluate, def_label);
1485 if (optimizing > 0) {
1486 if (forwref != NULL && globallineno == forwref->lineno) {
1487 output_ins.forw_ref = true;
1488 do {
1489 output_ins.oprs[forwref->operand].opflags |=
1490 OPFLAG_FORWARD;
1491 forwref = saa_rstruct(forwrefs);
1492 } while (forwref != NULL
1493 && forwref->lineno == globallineno);
1494 } else
1495 output_ins.forw_ref = false;
1497 if (output_ins.forw_ref) {
1498 if (passn == 1) {
1499 for (i = 0; i < output_ins.operands; i++) {
1500 if (output_ins.oprs[i].
1501 opflags & OPFLAG_FORWARD) {
1502 struct forwrefinfo *fwinf =
1503 (struct forwrefinfo *)
1504 saa_wstruct(forwrefs);
1505 fwinf->lineno = globallineno;
1506 fwinf->operand = i;
1513 /* forw_ref */
1514 if (output_ins.opcode == I_EQU) {
1515 if (pass1 == 1) {
1517 * Special `..' EQUs get processed in pass two,
1518 * except `..@' macro-processor EQUs which are done
1519 * in the normal place.
1521 if (!output_ins.label)
1522 report_error(ERR_NONFATAL,
1523 "EQU not preceded by label");
1525 else if (output_ins.label[0] != '.' ||
1526 output_ins.label[1] != '.' ||
1527 output_ins.label[2] == '@') {
1528 if (output_ins.operands == 1 &&
1529 (output_ins.oprs[0].type & IMMEDIATE) &&
1530 output_ins.oprs[0].wrt == NO_SEG) {
1531 bool isext = !!(output_ins.oprs[0].opflags
1532 & OPFLAG_EXTERN);
1533 def_label(output_ins.label,
1534 output_ins.oprs[0].segment,
1535 output_ins.oprs[0].offset, NULL,
1536 false, isext, ofmt,
1537 report_error);
1538 } else if (output_ins.operands == 2
1539 && (output_ins.oprs[0].type & IMMEDIATE)
1540 && (output_ins.oprs[0].type & COLON)
1541 && output_ins.oprs[0].segment == NO_SEG
1542 && output_ins.oprs[0].wrt == NO_SEG
1543 && (output_ins.oprs[1].type & IMMEDIATE)
1544 && output_ins.oprs[1].segment == NO_SEG
1545 && output_ins.oprs[1].wrt == NO_SEG) {
1546 def_label(output_ins.label,
1547 output_ins.oprs[0].offset | SEG_ABS,
1548 output_ins.oprs[1].offset,
1549 NULL, false, false, ofmt,
1550 report_error);
1551 } else
1552 report_error(ERR_NONFATAL,
1553 "bad syntax for EQU");
1555 } else {
1557 * Special `..' EQUs get processed here, except
1558 * `..@' macro processor EQUs which are done above.
1560 if (output_ins.label[0] == '.' &&
1561 output_ins.label[1] == '.' &&
1562 output_ins.label[2] != '@') {
1563 if (output_ins.operands == 1 &&
1564 (output_ins.oprs[0].type & IMMEDIATE)) {
1565 define_label(output_ins.label,
1566 output_ins.oprs[0].segment,
1567 output_ins.oprs[0].offset,
1568 NULL, false, false, ofmt,
1569 report_error);
1570 } else if (output_ins.operands == 2
1571 && (output_ins.oprs[0].
1572 type & IMMEDIATE)
1573 && (output_ins.oprs[0].type & COLON)
1574 && output_ins.oprs[0].segment ==
1575 NO_SEG
1576 && (output_ins.oprs[1].
1577 type & IMMEDIATE)
1578 && output_ins.oprs[1].segment ==
1579 NO_SEG) {
1580 define_label(output_ins.label,
1581 output_ins.oprs[0].
1582 offset | SEG_ABS,
1583 output_ins.oprs[1].offset,
1584 NULL, false, false, ofmt,
1585 report_error);
1586 } else
1587 report_error(ERR_NONFATAL,
1588 "bad syntax for EQU");
1591 } else { /* instruction isn't an EQU */
1593 if (pass1 == 1) {
1595 int64_t l = insn_size(location.segment, offs, sb, cpu,
1596 &output_ins, report_error);
1598 /* if (using_debug_info) && output_ins.opcode != -1) */
1599 if (using_debug_info)
1600 { /* fbk 03/25/01 */
1601 /* this is done here so we can do debug type info */
1602 int32_t typeinfo =
1603 TYS_ELEMENTS(output_ins.operands);
1604 switch (output_ins.opcode) {
1605 case I_RESB:
1606 typeinfo =
1607 TYS_ELEMENTS(output_ins.oprs[0].
1608 offset) | TY_BYTE;
1609 break;
1610 case I_RESW:
1611 typeinfo =
1612 TYS_ELEMENTS(output_ins.oprs[0].
1613 offset) | TY_WORD;
1614 break;
1615 case I_RESD:
1616 typeinfo =
1617 TYS_ELEMENTS(output_ins.oprs[0].
1618 offset) | TY_DWORD;
1619 break;
1620 case I_RESQ:
1621 typeinfo =
1622 TYS_ELEMENTS(output_ins.oprs[0].
1623 offset) | TY_QWORD;
1624 break;
1625 case I_REST:
1626 typeinfo =
1627 TYS_ELEMENTS(output_ins.oprs[0].
1628 offset) | TY_TBYTE;
1629 break;
1630 case I_RESO:
1631 typeinfo =
1632 TYS_ELEMENTS(output_ins.oprs[0].
1633 offset) | TY_OWORD;
1634 break;
1635 case I_RESY:
1636 typeinfo =
1637 TYS_ELEMENTS(output_ins.oprs[0].
1638 offset) | TY_YWORD;
1639 break;
1640 case I_DB:
1641 typeinfo |= TY_BYTE;
1642 break;
1643 case I_DW:
1644 typeinfo |= TY_WORD;
1645 break;
1646 case I_DD:
1647 if (output_ins.eops_float)
1648 typeinfo |= TY_FLOAT;
1649 else
1650 typeinfo |= TY_DWORD;
1651 break;
1652 case I_DQ:
1653 typeinfo |= TY_QWORD;
1654 break;
1655 case I_DT:
1656 typeinfo |= TY_TBYTE;
1657 break;
1658 case I_DO:
1659 typeinfo |= TY_OWORD;
1660 break;
1661 case I_DY:
1662 typeinfo |= TY_YWORD;
1663 break;
1664 default:
1665 typeinfo = TY_LABEL;
1669 ofmt->current_dfmt->debug_typevalue(typeinfo);
1672 if (l != -1) {
1673 offs += l;
1674 SET_CURR_OFFS(offs);
1677 * else l == -1 => invalid instruction, which will be
1678 * flagged as an error on pass 2
1681 } else {
1682 offs += assemble(location.segment, offs, sb, cpu,
1683 &output_ins, ofmt, report_error,
1684 &nasmlist);
1685 SET_CURR_OFFS(offs);
1688 } /* not an EQU */
1689 cleanup_insn(&output_ins);
1691 nasm_free(line);
1692 location.offset = offs = GET_CURR_OFFS;
1693 } /* end while (line = preproc->getline... */
1695 if (pass0 && global_offset_changed)
1696 report_error(ERR_NONFATAL,
1697 "phase error detected at end of assembly.");
1699 if (pass1 == 1)
1700 preproc->cleanup(1);
1702 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1703 pass0++;
1704 } else if (global_offset_changed &&
1705 global_offset_changed < prev_offset_changed) {
1706 prev_offset_changed = global_offset_changed;
1707 stall_count = 0;
1708 } else {
1709 stall_count++;
1712 if (terminate_after_phase)
1713 break;
1715 if ((stall_count > 997) || (passn >= pass_max)) {
1716 /* We get here if the labels don't converge
1717 * Example: FOO equ FOO + 1
1719 report_error(ERR_NONFATAL,
1720 "Can't find valid values for all labels "
1721 "after %d passes, giving up.", passn);
1722 report_error(ERR_NONFATAL,
1723 "Possible causes: recursive EQUs, macro abuse.");
1724 terminate_after_phase = true;
1725 break;
1729 preproc->cleanup(0);
1730 nasmlist.cleanup();
1731 if (!terminate_after_phase && opt_verbose_info) {
1732 /* -On and -Ov switches */
1733 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1737 static enum directives getkw(char **directive, char **value)
1739 char *p, *q, *buf;
1741 buf = *directive;
1743 /* allow leading spaces or tabs */
1744 while (*buf == ' ' || *buf == '\t')
1745 buf++;
1747 if (*buf != '[')
1748 return 0;
1750 p = buf;
1752 while (*p && *p != ']')
1753 p++;
1755 if (!*p)
1756 return 0;
1758 q = p++;
1760 while (*p && *p != ';') {
1761 if (!nasm_isspace(*p))
1762 return 0;
1763 p++;
1765 q[1] = '\0';
1767 *directive = p = buf + 1;
1768 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1769 buf++;
1770 if (*buf == ']') {
1771 *buf = '\0';
1772 *value = buf;
1773 } else {
1774 *buf++ = '\0';
1775 while (nasm_isspace(*buf))
1776 buf++; /* beppu - skip leading whitespace */
1777 *value = buf;
1778 while (*buf != ']')
1779 buf++;
1780 *buf++ = '\0';
1783 return bsii(*directive, directives, elements(directives));
1787 * gnu style error reporting
1788 * This function prints an error message to error_file in the
1789 * style used by GNU. An example would be:
1790 * file.asm:50: error: blah blah blah
1791 * where file.asm is the name of the file, 50 is the line number on
1792 * which the error occurs (or is detected) and "error:" is one of
1793 * the possible optional diagnostics -- it can be "error" or "warning"
1794 * or something else. Finally the line terminates with the actual
1795 * error message.
1797 * @param severity the severity of the warning or error
1798 * @param fmt the printf style format string
1800 static void report_error_gnu(int severity, const char *fmt, ...)
1802 va_list ap;
1804 if (is_suppressed_warning(severity))
1805 return;
1807 if (severity & ERR_NOFILE)
1808 fputs("nasm: ", error_file);
1809 else {
1810 char *currentfile = NULL;
1811 int32_t lineno = 0;
1812 src_get(&lineno, &currentfile);
1813 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1814 nasm_free(currentfile);
1816 va_start(ap, fmt);
1817 report_error_common(severity, fmt, ap);
1818 va_end(ap);
1822 * MS style error reporting
1823 * This function prints an error message to error_file in the
1824 * style used by Visual C and some other Microsoft tools. An example
1825 * would be:
1826 * file.asm(50) : error: blah blah blah
1827 * where file.asm is the name of the file, 50 is the line number on
1828 * which the error occurs (or is detected) and "error:" is one of
1829 * the possible optional diagnostics -- it can be "error" or "warning"
1830 * or something else. Finally the line terminates with the actual
1831 * error message.
1833 * @param severity the severity of the warning or error
1834 * @param fmt the printf style format string
1836 static void report_error_vc(int severity, const char *fmt, ...)
1838 va_list ap;
1840 if (is_suppressed_warning(severity))
1841 return;
1843 if (severity & ERR_NOFILE)
1844 fputs("nasm: ", error_file);
1845 else {
1846 char *currentfile = NULL;
1847 int32_t lineno = 0;
1848 src_get(&lineno, &currentfile);
1849 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1850 nasm_free(currentfile);
1852 va_start(ap, fmt);
1853 report_error_common(severity, fmt, ap);
1854 va_end(ap);
1858 * check for supressed warning
1859 * checks for suppressed warning or pass one only warning and we're
1860 * not in pass 1
1862 * @param severity the severity of the warning or error
1863 * @return true if we should abort error/warning printing
1865 static bool is_suppressed_warning(int severity)
1868 * See if it's a suppressed warning.
1870 return (severity & ERR_MASK) == ERR_WARNING &&
1871 (((severity & ERR_WARN_MASK) != 0 &&
1872 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1873 /* See if it's a pass-one only warning and we're not in pass one. */
1874 ((severity & ERR_PASS1) && pass0 != 1) ||
1875 ((severity & ERR_PASS2) && pass0 != 2));
1879 * common error reporting
1880 * This is the common back end of the error reporting schemes currently
1881 * implemented. It prints the nature of the warning and then the
1882 * specific error message to error_file and may or may not return. It
1883 * doesn't return if the error severity is a "panic" or "debug" type.
1885 * @param severity the severity of the warning or error
1886 * @param fmt the printf style format string
1888 static void report_error_common(int severity, const char *fmt,
1889 va_list args)
1891 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1892 case ERR_WARNING:
1893 fputs("warning: ", error_file);
1894 break;
1895 case ERR_NONFATAL:
1896 fputs("error: ", error_file);
1897 break;
1898 case ERR_FATAL:
1899 fputs("fatal: ", error_file);
1900 break;
1901 case ERR_PANIC:
1902 fputs("panic: ", error_file);
1903 break;
1904 case ERR_DEBUG:
1905 fputs("debug: ", error_file);
1906 break;
1907 default:
1908 break;
1911 vfprintf(error_file, fmt, args);
1912 putc('\n', error_file);
1914 if (severity & ERR_USAGE)
1915 want_usage = true;
1917 switch (severity & ERR_MASK) {
1918 case ERR_DEBUG:
1919 /* no further action, by definition */
1920 break;
1921 case ERR_WARNING:
1922 if (warning_on[0]) /* Treat warnings as errors */
1923 terminate_after_phase = true;
1924 break;
1925 case ERR_NONFATAL:
1926 terminate_after_phase = true;
1927 break;
1928 case ERR_FATAL:
1929 if (ofile) {
1930 fclose(ofile);
1931 remove(outname);
1933 if (want_usage)
1934 usage();
1935 exit(1); /* instantly die */
1936 break; /* placate silly compilers */
1937 case ERR_PANIC:
1938 fflush(NULL);
1939 /* abort(); *//* halt, catch fire, and dump core */
1940 exit(3);
1941 break;
1945 static void usage(void)
1947 fputs("type `nasm -h' for help\n", error_file);
1950 static void register_output_formats(void)
1952 ofmt = ofmt_register(report_error);
1955 #define BUF_DELTA 512
1957 static FILE *no_pp_fp;
1958 static efunc no_pp_err;
1959 static ListGen *no_pp_list;
1960 static int32_t no_pp_lineinc;
1962 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1963 ListGen * listgen, StrList **deplist)
1965 src_set_fname(nasm_strdup(file));
1966 src_set_linnum(0);
1967 no_pp_lineinc = 1;
1968 no_pp_err = error;
1969 no_pp_fp = fopen(file, "r");
1970 if (!no_pp_fp)
1971 no_pp_err(ERR_FATAL | ERR_NOFILE,
1972 "unable to open input file `%s'", file);
1973 no_pp_list = listgen;
1974 (void)pass; /* placate compilers */
1975 (void)eval; /* placate compilers */
1977 if (deplist) {
1978 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1979 sl->next = NULL;
1980 strcpy(sl->str, file);
1981 *deplist = sl;
1985 static char *no_pp_getline(void)
1987 char *buffer, *p, *q;
1988 int bufsize;
1990 bufsize = BUF_DELTA;
1991 buffer = nasm_malloc(BUF_DELTA);
1992 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1994 while (1) { /* Loop to handle %line */
1996 p = buffer;
1997 while (1) { /* Loop to handle long lines */
1998 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
1999 if (!q)
2000 break;
2001 p += strlen(p);
2002 if (p > buffer && p[-1] == '\n')
2003 break;
2004 if (p - buffer > bufsize - 10) {
2005 int offset;
2006 offset = p - buffer;
2007 bufsize += BUF_DELTA;
2008 buffer = nasm_realloc(buffer, bufsize);
2009 p = buffer + offset;
2013 if (!q && p == buffer) {
2014 nasm_free(buffer);
2015 return NULL;
2019 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2020 * them are present at the end of the line.
2022 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2024 if (!nasm_strnicmp(buffer, "%line", 5)) {
2025 int32_t ln;
2026 int li;
2027 char *nm = nasm_malloc(strlen(buffer));
2028 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2029 nasm_free(src_set_fname(nm));
2030 src_set_linnum(ln);
2031 no_pp_lineinc = li;
2032 continue;
2034 nasm_free(nm);
2036 break;
2039 no_pp_list->line(LIST_READ, buffer);
2041 return buffer;
2044 static void no_pp_cleanup(int pass)
2046 (void)pass; /* placate GCC */
2047 fclose(no_pp_fp);
2050 static uint32_t get_cpu(char *value)
2052 if (!strcmp(value, "8086"))
2053 return IF_8086;
2054 if (!strcmp(value, "186"))
2055 return IF_186;
2056 if (!strcmp(value, "286"))
2057 return IF_286;
2058 if (!strcmp(value, "386"))
2059 return IF_386;
2060 if (!strcmp(value, "486"))
2061 return IF_486;
2062 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2063 return IF_PENT;
2064 if (!strcmp(value, "686") ||
2065 !nasm_stricmp(value, "ppro") ||
2066 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2067 return IF_P6;
2068 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2069 return IF_KATMAI;
2070 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2071 !nasm_stricmp(value, "willamette"))
2072 return IF_WILLAMETTE;
2073 if (!nasm_stricmp(value, "prescott"))
2074 return IF_PRESCOTT;
2075 if (!nasm_stricmp(value, "x64") ||
2076 !nasm_stricmp(value, "x86-64"))
2077 return IF_X86_64;
2078 if (!nasm_stricmp(value, "ia64") ||
2079 !nasm_stricmp(value, "ia-64") ||
2080 !nasm_stricmp(value, "itanium") ||
2081 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2082 return IF_IA64;
2084 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2085 "unknown 'cpu' type");
2087 return IF_PLEVEL; /* the maximum level */
2090 static int get_bits(char *value)
2092 int i;
2094 if ((i = atoi(value)) == 16)
2095 return i; /* set for a 16-bit segment */
2096 else if (i == 32) {
2097 if (cpu < IF_386) {
2098 report_error(ERR_NONFATAL,
2099 "cannot specify 32-bit segment on processor below a 386");
2100 i = 16;
2102 } else if (i == 64) {
2103 if (cpu < IF_X86_64) {
2104 report_error(ERR_NONFATAL,
2105 "cannot specify 64-bit segment on processor below an x86-64");
2106 i = 16;
2108 if (i != maxbits) {
2109 report_error(ERR_NONFATAL,
2110 "%s output format does not support 64-bit code",
2111 ofmt->shortname);
2112 i = 16;
2114 } else {
2115 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2116 "`%s' is not a valid segment size; must be 16, 32 or 64",
2117 value);
2118 i = 16;
2120 return i;
2123 /* end of nasm.c */