Move all version strings to a single compilation unit (ver.c)
[nasm/perl-rewrite.git] / nasm.c
blobab369b8ed9cc20a3fc07da1954136cfc62a550a1
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 "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 int want_usage;
154 static int 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);
433 assemble_file(inname, depend_ptr);
435 if (!terminate_after_phase) {
436 ofmt->cleanup(using_debug_info);
437 cleanup_labels();
438 } else {
440 * Despite earlier comments, we need this fclose.
441 * The object output drivers only fclose on cleanup,
442 * and we just skipped that.
444 fclose (ofile);
446 remove(outname);
447 if (listname[0])
448 remove(listname);
451 break;
454 if (depend_list)
455 emit_dependencies(depend_list);
457 if (want_usage)
458 usage();
460 raa_free(offsets);
461 saa_free(forwrefs);
462 eval_cleanup();
463 stdscan_cleanup();
465 if (terminate_after_phase)
466 return 1;
467 else
468 return 0;
472 * Get a parameter for a command line option.
473 * First arg must be in the form of e.g. -f...
475 static char *get_param(char *p, char *q, bool *advance)
477 *advance = false;
478 if (p[2]) { /* the parameter's in the option */
479 p += 2;
480 while (nasm_isspace(*p))
481 p++;
482 return p;
484 if (q && q[0]) {
485 *advance = true;
486 return q;
488 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
489 "option `-%c' requires an argument", p[1]);
490 return NULL;
494 * Copy a filename
496 static void copy_filename(char *dst, const char *src)
498 size_t len = strlen(src);
500 if (len >= (size_t)FILENAME_MAX) {
501 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
502 return;
504 strncpy(dst, src, FILENAME_MAX);
508 * Convert a string to Make-safe form
510 static char *quote_for_make(const char *str)
512 const char *p;
513 char *os, *q;
515 size_t n = 1; /* Terminating zero */
516 size_t nbs = 0;
518 if (!str)
519 return NULL;
521 for (p = str; *p; p++) {
522 switch (*p) {
523 case ' ':
524 case '\t':
525 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
526 n += nbs + 2;
527 nbs = 0;
528 break;
529 case '$':
530 case '#':
531 nbs = 0;
532 n += 2;
533 break;
534 case '\\':
535 nbs++;
536 n++;
537 break;
538 default:
539 nbs = 0;
540 n++;
541 break;
545 /* Convert N backslashes at the end of filename to 2N backslashes */
546 if (nbs)
547 n += nbs;
549 os = q = nasm_malloc(n);
551 nbs = 0;
552 for (p = str; *p; p++) {
553 switch (*p) {
554 case ' ':
555 case '\t':
556 while (nbs--)
557 *q++ = '\\';
558 *q++ = '\\';
559 *q++ = *p;
560 break;
561 case '$':
562 *q++ = *p;
563 *q++ = *p;
564 nbs = 0;
565 break;
566 case '#':
567 *q++ = '\\';
568 *q++ = *p;
569 nbs = 0;
570 break;
571 case '\\':
572 *q++ = *p;
573 nbs++;
574 break;
575 default:
576 *q++ = *p;
577 nbs = 0;
578 break;
581 while (nbs--)
582 *q++ = '\\';
584 *q = '\0';
586 return os;
589 struct textargs {
590 const char *label;
591 int value;
594 #define OPT_PREFIX 0
595 #define OPT_POSTFIX 1
596 struct textargs textopts[] = {
597 {"prefix", OPT_PREFIX},
598 {"postfix", OPT_POSTFIX},
599 {NULL, 0}
602 static bool stopoptions = false;
603 static bool process_arg(char *p, char *q)
605 char *param;
606 int i;
607 bool advance = false;
608 bool do_warn;
610 if (!p || !p[0])
611 return false;
613 if (p[0] == '-' && !stopoptions) {
614 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
615 /* These parameters take values */
616 if (!(param = get_param(p, q, &advance)))
617 return advance;
620 switch (p[1]) {
621 case 's':
622 error_file = stdout;
623 break;
625 case 'o': /* output file */
626 copy_filename(outname, param);
627 break;
629 case 'f': /* output format */
630 ofmt = ofmt_find(param);
631 if (!ofmt) {
632 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
633 "unrecognised output format `%s' - "
634 "use -hf for a list", param);
635 } else {
636 ofmt->current_dfmt = ofmt->debug_formats[0];
638 break;
640 case 'O': /* Optimization level */
642 int opt;
644 if (!*param) {
645 /* Naked -O == -Ox */
646 optimizing = INT_MAX >> 1; /* Almost unlimited */
647 } else {
648 while (*param) {
649 switch (*param) {
650 case '0': case '1': case '2': case '3': case '4':
651 case '5': case '6': case '7': case '8': case '9':
652 opt = strtoul(param, &param, 10);
654 /* -O0 -> optimizing == -1, 0.98 behaviour */
655 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
656 if (opt < 2)
657 optimizing = opt - 1;
658 else
659 optimizing = opt;
660 break;
662 case 'v':
663 case '+':
664 param++;
665 opt_verbose_info = true;
666 break;
668 case 'x':
669 param++;
670 optimizing = INT_MAX >> 1; /* Almost unlimited */
671 break;
673 default:
674 report_error(ERR_FATAL,
675 "unknown optimization option -O%c\n",
676 *param);
677 break;
681 break;
684 case 'p': /* pre-include */
685 case 'P':
686 pp_pre_include(param);
687 break;
689 case 'd': /* pre-define */
690 case 'D':
691 pp_pre_define(param);
692 break;
694 case 'u': /* un-define */
695 case 'U':
696 pp_pre_undefine(param);
697 break;
699 case 'i': /* include search path */
700 case 'I':
701 pp_include_path(param);
702 break;
704 case 'l': /* listing file */
705 copy_filename(listname, param);
706 break;
708 case 'Z': /* error messages file */
709 strcpy(errname, param);
710 break;
712 case 'F': /* specify debug format */
713 ofmt->current_dfmt = dfmt_find(ofmt, param);
714 if (!ofmt->current_dfmt) {
715 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
716 "unrecognized debug format `%s' for"
717 " output format `%s'",
718 param, ofmt->shortname);
720 using_debug_info = true;
721 break;
723 case 'X': /* specify error reporting format */
724 if (nasm_stricmp("vc", param) == 0)
725 report_error = report_error_vc;
726 else if (nasm_stricmp("gnu", param) == 0)
727 report_error = report_error_gnu;
728 else
729 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
730 "unrecognized error reporting format `%s'",
731 param);
732 break;
734 case 'g':
735 using_debug_info = true;
736 break;
738 case 'h':
739 printf
740 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
741 "[-l listfile]\n"
742 " [options...] [--] filename\n"
743 " or nasm -v for version info\n\n"
744 " -t assemble in SciTech TASM compatible mode\n"
745 " -g generate debug information in selected format.\n");
746 printf
747 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
748 " -a don't preprocess (assemble only)\n"
749 " -M generate Makefile dependencies on stdout\n"
750 " -MG d:o, missing files assumed generated\n\n"
751 " -Z<file> redirect error messages to file\n"
752 " -s redirect error messages to stdout\n\n"
753 " -F format select a debugging format\n\n"
754 " -I<path> adds a pathname to the include file path\n");
755 printf
756 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
757 " -P<file> pre-includes a file\n"
758 " -D<macro>[=<value>] pre-defines a macro\n"
759 " -U<macro> undefines a macro\n"
760 " -X<format> specifies error reporting format (gnu or vc)\n"
761 " -w+foo enables warning foo (equiv. -Wfoo)\n"
762 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
763 "Warnings:\n");
764 for (i = 0; i <= ERR_WARN_MAX; i++)
765 printf(" %-23s %s (default %s)\n",
766 warnings[i].name, warnings[i].help,
767 warnings[i].enabled ? "on" : "off");
768 printf
769 ("\nresponse files should contain command line parameters"
770 ", one per line.\n");
771 if (p[2] == 'f') {
772 printf("\nvalid output formats for -f are"
773 " (`*' denotes default):\n");
774 ofmt_list(ofmt, stdout);
775 } else {
776 printf("\nFor a list of valid output formats, use -hf.\n");
777 printf("For a list of debug formats, use -f <form> -y.\n");
779 exit(0); /* never need usage message here */
780 break;
782 case 'y':
783 printf("\nvalid debug formats for '%s' output format are"
784 " ('*' denotes default):\n", ofmt->shortname);
785 dfmt_list(ofmt, stdout);
786 exit(0);
787 break;
789 case 't':
790 tasm_compatible_mode = true;
791 break;
793 case 'v':
794 fprintf(stderr, "NASM version %s compiled on %s%s\n",
795 nasm_version, nasm_date, nasm_compile_options);
796 exit(0); /* never need usage message here */
797 break;
799 case 'e': /* preprocess only */
800 case 'E':
801 operating_mode = op_preprocess;
802 break;
804 case 'a': /* assemble only - don't preprocess */
805 preproc = &no_pp;
806 break;
808 case 'W':
809 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
810 do_warn = false;
811 param += 3;
812 } else {
813 do_warn = true;
815 goto set_warning;
817 case 'w':
818 if (param[0] != '+' && param[0] != '-') {
819 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
820 "invalid option to `-w'");
821 break;
823 do_warn = (param[0] == '+');
824 param++;
825 goto set_warning;
826 set_warning:
827 for (i = 0; i <= ERR_WARN_MAX; i++)
828 if (!nasm_stricmp(param, warnings[i].name))
829 break;
830 if (i <= ERR_WARN_MAX)
831 warning_on_global[i] = do_warn;
832 else if (!nasm_stricmp(param, "all"))
833 for (i = 1; i <= ERR_WARN_MAX; i++)
834 warning_on_global[i] = do_warn;
835 else if (!nasm_stricmp(param, "none"))
836 for (i = 1; i <= ERR_WARN_MAX; i++)
837 warning_on_global[i] = !do_warn;
838 else
839 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
840 "invalid warning `%s'", param);
841 break;
843 case 'M':
844 switch (p[2]) {
845 case 0:
846 operating_mode = op_depend;
847 break;
848 case 'G':
849 operating_mode = op_depend;
850 depend_missing_ok = true;
851 break;
852 case 'P':
853 depend_emit_phony = true;
854 break;
855 case 'D':
856 depend_file = q;
857 advance = true;
858 break;
859 case 'T':
860 depend_target = q;
861 advance = true;
862 break;
863 case 'Q':
864 depend_target = quote_for_make(q);
865 advance = true;
866 break;
867 default:
868 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
869 "unknown dependency option `-M%c'", p[2]);
870 break;
872 if (advance && (!q || !q[0])) {
873 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
874 "option `-M%c' requires a parameter", p[2]);
875 break;
877 break;
879 case '-':
881 int s;
883 if (p[2] == 0) { /* -- => stop processing options */
884 stopoptions = 1;
885 break;
887 for (s = 0; textopts[s].label; s++) {
888 if (!nasm_stricmp(p + 2, textopts[s].label)) {
889 break;
893 switch (s) {
895 case OPT_PREFIX:
896 case OPT_POSTFIX:
898 if (!q) {
899 report_error(ERR_NONFATAL | ERR_NOFILE |
900 ERR_USAGE,
901 "option `--%s' requires an argument",
902 p + 2);
903 break;
904 } else {
905 advance = 1, param = q;
908 if (s == OPT_PREFIX) {
909 strncpy(lprefix, param, PREFIX_MAX - 1);
910 lprefix[PREFIX_MAX - 1] = 0;
911 break;
913 if (s == OPT_POSTFIX) {
914 strncpy(lpostfix, param, POSTFIX_MAX - 1);
915 lpostfix[POSTFIX_MAX - 1] = 0;
916 break;
918 break;
920 default:
922 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
923 "unrecognised option `--%s'", p + 2);
924 break;
927 break;
930 default:
931 if (!ofmt->setinfo(GI_SWITCH, &p))
932 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
933 "unrecognised option `-%c'", p[1]);
934 break;
936 } else {
937 if (*inname) {
938 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
939 "more than one input file specified");
940 } else {
941 copy_filename(inname, p);
945 return advance;
948 #define ARG_BUF_DELTA 128
950 static void process_respfile(FILE * rfile)
952 char *buffer, *p, *q, *prevarg;
953 int bufsize, prevargsize;
955 bufsize = prevargsize = ARG_BUF_DELTA;
956 buffer = nasm_malloc(ARG_BUF_DELTA);
957 prevarg = nasm_malloc(ARG_BUF_DELTA);
958 prevarg[0] = '\0';
960 while (1) { /* Loop to handle all lines in file */
961 p = buffer;
962 while (1) { /* Loop to handle long lines */
963 q = fgets(p, bufsize - (p - buffer), rfile);
964 if (!q)
965 break;
966 p += strlen(p);
967 if (p > buffer && p[-1] == '\n')
968 break;
969 if (p - buffer > bufsize - 10) {
970 int offset;
971 offset = p - buffer;
972 bufsize += ARG_BUF_DELTA;
973 buffer = nasm_realloc(buffer, bufsize);
974 p = buffer + offset;
978 if (!q && p == buffer) {
979 if (prevarg[0])
980 process_arg(prevarg, NULL);
981 nasm_free(buffer);
982 nasm_free(prevarg);
983 return;
987 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
988 * them are present at the end of the line.
990 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
992 while (p > buffer && nasm_isspace(p[-1]))
993 *--p = '\0';
995 p = buffer;
996 while (nasm_isspace(*p))
997 p++;
999 if (process_arg(prevarg, p))
1000 *p = '\0';
1002 if ((int) strlen(p) > prevargsize - 10) {
1003 prevargsize += ARG_BUF_DELTA;
1004 prevarg = nasm_realloc(prevarg, prevargsize);
1006 strncpy(prevarg, p, prevargsize);
1010 /* Function to process args from a string of args, rather than the
1011 * argv array. Used by the environment variable and response file
1012 * processing.
1014 static void process_args(char *args)
1016 char *p, *q, *arg, *prevarg;
1017 char separator = ' ';
1019 p = args;
1020 if (*p && *p != '-')
1021 separator = *p++;
1022 arg = NULL;
1023 while (*p) {
1024 q = p;
1025 while (*p && *p != separator)
1026 p++;
1027 while (*p == separator)
1028 *p++ = '\0';
1029 prevarg = arg;
1030 arg = q;
1031 if (process_arg(prevarg, arg))
1032 arg = NULL;
1034 if (arg)
1035 process_arg(arg, NULL);
1038 static void process_response_file(const char *file)
1040 char str[2048];
1041 FILE *f = fopen(file, "r");
1042 if (!f) {
1043 perror(file);
1044 exit(-1);
1046 while (fgets(str, sizeof str, f)) {
1047 process_args(str);
1049 fclose(f);
1052 static void parse_cmdline(int argc, char **argv)
1054 FILE *rfile;
1055 char *envreal, *envcopy = NULL, *p, *arg;
1056 int i;
1058 *inname = *outname = *listname = *errname = '\0';
1059 for (i = 0; i <= ERR_WARN_MAX; i++)
1060 warning_on_global[i] = warnings[i].enabled;
1063 * First, process the NASMENV environment variable.
1065 envreal = getenv("NASMENV");
1066 arg = NULL;
1067 if (envreal) {
1068 envcopy = nasm_strdup(envreal);
1069 process_args(envcopy);
1070 nasm_free(envcopy);
1074 * Now process the actual command line.
1076 while (--argc) {
1077 bool advance;
1078 argv++;
1079 if (argv[0][0] == '@') {
1080 /* We have a response file, so process this as a set of
1081 * arguments like the environment variable. This allows us
1082 * to have multiple arguments on a single line, which is
1083 * different to the -@resp file processing below for regular
1084 * NASM.
1086 process_response_file(argv[0]+1);
1087 argc--;
1088 argv++;
1090 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1091 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1092 if (p) {
1093 rfile = fopen(p, "r");
1094 if (rfile) {
1095 process_respfile(rfile);
1096 fclose(rfile);
1097 } else
1098 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1099 "unable to open response file `%s'", p);
1101 } else
1102 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1103 argv += advance, argc -= advance;
1106 /* Look for basic command line typos. This definitely doesn't
1107 catch all errors, but it might help cases of fumbled fingers. */
1108 if (!*inname)
1109 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1110 "no input file specified");
1111 else if (!strcmp(inname, errname) ||
1112 !strcmp(inname, outname) ||
1113 !strcmp(inname, listname) ||
1114 (depend_file && !strcmp(inname, depend_file)))
1115 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1116 "file `%s' is both input and output file",
1117 inname);
1119 if (*errname) {
1120 error_file = fopen(errname, "w");
1121 if (!error_file) {
1122 error_file = stderr; /* Revert to default! */
1123 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1124 "cannot open file `%s' for error messages",
1125 errname);
1130 /* List of directives */
1131 enum directives {
1132 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1133 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1135 static const char *directives[] = {
1136 "", "absolute", "bits", "common", "cpu", "debug", "default",
1137 "extern", "float", "global", "list", "section", "segment", "warning"
1139 static enum directives getkw(char **directive, char **value);
1141 static void assemble_file(char *fname, StrList **depend_ptr)
1143 char *directive, *value, *p, *q, *special, *line, debugid[80];
1144 insn output_ins;
1145 int i, validid;
1146 bool rn_error;
1147 int32_t seg;
1148 int64_t offs;
1149 struct tokenval tokval;
1150 expr *e;
1151 int pass_max;
1153 if (cmd_sb == 32 && cmd_cpu < IF_386)
1154 report_error(ERR_FATAL, "command line: "
1155 "32-bit segment size requires a higher cpu");
1157 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1158 for (passn = 1; pass0 <= 2; passn++) {
1159 int pass1, pass2;
1160 ldfunc def_label;
1162 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1163 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1164 /* pass0 0, 0, 0, ..., 1, 2 */
1166 def_label = passn > 1 ? redefine_label : define_label;
1168 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1169 cpu = cmd_cpu;
1170 if (pass0 == 2) {
1171 if (*listname)
1172 nasmlist.init(listname, report_error);
1174 in_abs_seg = false;
1175 global_offset_changed = 0; /* set by redefine_label */
1176 location.segment = ofmt->section(NULL, pass2, &sb);
1177 globalbits = sb;
1178 if (passn > 1) {
1179 saa_rewind(forwrefs);
1180 forwref = saa_rstruct(forwrefs);
1181 raa_free(offsets);
1182 offsets = raa_init();
1184 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1185 pass1 == 2 ? depend_ptr : NULL);
1186 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1188 globallineno = 0;
1189 if (passn == 1)
1190 location.known = true;
1191 location.offset = offs = GET_CURR_OFFS;
1193 while ((line = preproc->getline())) {
1194 enum directives d;
1195 globallineno++;
1197 /* here we parse our directives; this is not handled by the 'real'
1198 * parser. */
1199 directive = line;
1200 d = getkw(&directive, &value);
1201 if (d) {
1202 int err = 0;
1204 switch (d) {
1205 case D_SEGMENT: /* [SEGMENT n] */
1206 case D_SECTION:
1207 seg = ofmt->section(value, pass2, &sb);
1208 if (seg == NO_SEG) {
1209 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1210 "segment name `%s' not recognized",
1211 value);
1212 } else {
1213 in_abs_seg = false;
1214 location.segment = seg;
1216 break;
1217 case D_EXTERN: /* [EXTERN label:special] */
1218 if (*value == '$')
1219 value++; /* skip initial $ if present */
1220 if (pass0 == 2) {
1221 q = value;
1222 while (*q && *q != ':')
1223 q++;
1224 if (*q == ':') {
1225 *q++ = '\0';
1226 ofmt->symdef(value, 0L, 0L, 3, q);
1228 } else if (passn == 1) {
1229 q = value;
1230 validid = true;
1231 if (!isidstart(*q))
1232 validid = false;
1233 while (*q && *q != ':') {
1234 if (!isidchar(*q))
1235 validid = false;
1236 q++;
1238 if (!validid) {
1239 report_error(ERR_NONFATAL,
1240 "identifier expected after EXTERN");
1241 break;
1243 if (*q == ':') {
1244 *q++ = '\0';
1245 special = q;
1246 } else
1247 special = NULL;
1248 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1249 int temp = pass0;
1250 pass0 = 1; /* fake pass 1 in labels.c */
1251 declare_as_global(value, special,
1252 report_error);
1253 define_label(value, seg_alloc(), 0L, NULL,
1254 false, true, ofmt, report_error);
1255 pass0 = temp;
1257 } /* else pass0 == 1 */
1258 break;
1259 case D_BITS: /* [BITS bits] */
1260 globalbits = sb = get_bits(value);
1261 break;
1262 case D_GLOBAL: /* [GLOBAL symbol:special] */
1263 if (*value == '$')
1264 value++; /* skip initial $ if present */
1265 if (pass0 == 2) { /* pass 2 */
1266 q = value;
1267 while (*q && *q != ':')
1268 q++;
1269 if (*q == ':') {
1270 *q++ = '\0';
1271 ofmt->symdef(value, 0L, 0L, 3, q);
1273 } else if (pass2 == 1) { /* pass == 1 */
1274 q = value;
1275 validid = true;
1276 if (!isidstart(*q))
1277 validid = false;
1278 while (*q && *q != ':') {
1279 if (!isidchar(*q))
1280 validid = false;
1281 q++;
1283 if (!validid) {
1284 report_error(ERR_NONFATAL,
1285 "identifier expected after GLOBAL");
1286 break;
1288 if (*q == ':') {
1289 *q++ = '\0';
1290 special = q;
1291 } else
1292 special = NULL;
1293 declare_as_global(value, special, report_error);
1294 } /* pass == 1 */
1295 break;
1296 case D_COMMON: /* [COMMON symbol size:special] */
1297 if (*value == '$')
1298 value++; /* skip initial $ if present */
1299 if (pass0 == 1) {
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 int64_t size;
1317 while (*p && nasm_isspace(*p))
1318 *p++ = '\0';
1319 q = p;
1320 while (*q && *q != ':')
1321 q++;
1322 if (*q == ':') {
1323 *q++ = '\0';
1324 special = q;
1325 } else
1326 special = NULL;
1327 size = readnum(p, &rn_error);
1328 if (rn_error)
1329 report_error(ERR_NONFATAL,
1330 "invalid size specified"
1331 " in COMMON declaration");
1332 else
1333 define_common(value, seg_alloc(), size,
1334 special, ofmt, report_error);
1335 } else
1336 report_error(ERR_NONFATAL,
1337 "no size specified in"
1338 " COMMON declaration");
1339 } else if (pass0 == 2) { /* pass == 2 */
1340 q = value;
1341 while (*q && *q != ':') {
1342 if (nasm_isspace(*q))
1343 *q = '\0';
1344 q++;
1346 if (*q == ':') {
1347 *q++ = '\0';
1348 ofmt->symdef(value, 0L, 0L, 3, q);
1351 break;
1352 case D_ABSOLUTE: /* [ABSOLUTE address] */
1353 stdscan_reset();
1354 stdscan_bufptr = value;
1355 tokval.t_type = TOKEN_INVALID;
1356 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1357 report_error, NULL);
1358 if (e) {
1359 if (!is_reloc(e))
1360 report_error(pass0 ==
1361 1 ? ERR_NONFATAL : ERR_PANIC,
1362 "cannot use non-relocatable expression as "
1363 "ABSOLUTE address");
1364 else {
1365 abs_seg = reloc_seg(e);
1366 abs_offset = reloc_value(e);
1368 } else if (passn == 1)
1369 abs_offset = 0x100; /* don't go near zero in case of / */
1370 else
1371 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1372 "in pass two");
1373 in_abs_seg = true;
1374 location.segment = NO_SEG;
1375 break;
1376 case D_DEBUG: /* [DEBUG] */
1377 p = value;
1378 q = debugid;
1379 validid = true;
1380 if (!isidstart(*p))
1381 validid = false;
1382 while (*p && !nasm_isspace(*p)) {
1383 if (!isidchar(*p))
1384 validid = false;
1385 *q++ = *p++;
1387 *q++ = 0;
1388 if (!validid) {
1389 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1390 "identifier expected after DEBUG");
1391 break;
1393 while (*p && nasm_isspace(*p))
1394 p++;
1395 if (pass0 == 2)
1396 ofmt->current_dfmt->debug_directive(debugid, p);
1397 break;
1398 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1399 if (pass1 == 1) {
1400 while (*value && nasm_isspace(*value))
1401 value++;
1403 switch(*value) {
1404 case '-': validid = 1; value++; break;
1405 case '+': validid = 1; value++; break;
1406 case '*': validid = 2; value++; break;
1407 default: validid = 1; break;
1410 for (i = 1; i <= ERR_WARN_MAX; i++)
1411 if (!nasm_stricmp(value, warnings[i].name))
1412 break;
1413 if (i <= ERR_WARN_MAX) {
1414 switch(validid) {
1415 case 0:
1416 warning_on[i] = false;
1417 break;
1418 case 1:
1419 warning_on[i] = true;
1420 break;
1421 case 2:
1422 warning_on[i] = warning_on_global[i];
1423 break;
1426 else
1427 report_error(ERR_NONFATAL,
1428 "invalid warning id in WARNING directive");
1430 break;
1431 case D_CPU: /* [CPU] */
1432 cpu = get_cpu(value);
1433 break;
1434 case D_LIST: /* [LIST {+|-}] */
1435 while (*value && nasm_isspace(*value))
1436 value++;
1438 if (*value == '+') {
1439 user_nolist = 0;
1440 } else {
1441 if (*value == '-') {
1442 user_nolist = 1;
1443 } else {
1444 err = 1;
1447 break;
1448 case D_DEFAULT: /* [DEFAULT] */
1449 stdscan_reset();
1450 stdscan_bufptr = value;
1451 tokval.t_type = TOKEN_INVALID;
1452 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1453 switch ((int)tokval.t_integer) {
1454 case S_REL:
1455 globalrel = 1;
1456 break;
1457 case S_ABS:
1458 globalrel = 0;
1459 break;
1460 default:
1461 err = 1;
1462 break;
1464 } else {
1465 err = 1;
1467 break;
1468 case D_FLOAT:
1469 if (float_option(value)) {
1470 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1471 "unknown 'float' directive: %s",
1472 value);
1474 break;
1475 default:
1476 if (!ofmt->directive(directive, value, pass2))
1477 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1478 "unrecognised directive [%s]",
1479 directive);
1481 if (err) {
1482 report_error(ERR_NONFATAL,
1483 "invalid parameter to [%s] directive",
1484 directive);
1486 } else { /* it isn't a directive */
1488 parse_line(pass1, line, &output_ins,
1489 report_error, evaluate, def_label);
1491 if (optimizing > 0) {
1492 if (forwref != NULL && globallineno == forwref->lineno) {
1493 output_ins.forw_ref = true;
1494 do {
1495 output_ins.oprs[forwref->operand].opflags |=
1496 OPFLAG_FORWARD;
1497 forwref = saa_rstruct(forwrefs);
1498 } while (forwref != NULL
1499 && forwref->lineno == globallineno);
1500 } else
1501 output_ins.forw_ref = false;
1504 if (optimizing > 0) {
1505 if (passn == 1) {
1506 for (i = 0; i < output_ins.operands; i++) {
1507 if (output_ins.oprs[i].
1508 opflags & OPFLAG_FORWARD) {
1509 struct forwrefinfo *fwinf =
1510 (struct forwrefinfo *)
1511 saa_wstruct(forwrefs);
1512 fwinf->lineno = globallineno;
1513 fwinf->operand = i;
1519 /* forw_ref */
1520 if (output_ins.opcode == I_EQU) {
1521 if (pass1 == 1) {
1523 * Special `..' EQUs get processed in pass two,
1524 * except `..@' macro-processor EQUs which are done
1525 * in the normal place.
1527 if (!output_ins.label)
1528 report_error(ERR_NONFATAL,
1529 "EQU not preceded by label");
1531 else if (output_ins.label[0] != '.' ||
1532 output_ins.label[1] != '.' ||
1533 output_ins.label[2] == '@') {
1534 if (output_ins.operands == 1 &&
1535 (output_ins.oprs[0].type & IMMEDIATE) &&
1536 output_ins.oprs[0].wrt == NO_SEG) {
1537 int isext =
1538 output_ins.oprs[0].
1539 opflags & OPFLAG_EXTERN;
1540 def_label(output_ins.label,
1541 output_ins.oprs[0].segment,
1542 output_ins.oprs[0].offset, NULL,
1543 false, isext, ofmt,
1544 report_error);
1545 } else if (output_ins.operands == 2
1546 && (output_ins.oprs[0].
1547 type & IMMEDIATE)
1548 && (output_ins.oprs[0].type & COLON)
1549 && output_ins.oprs[0].segment ==
1550 NO_SEG
1551 && output_ins.oprs[0].wrt == NO_SEG
1552 && (output_ins.oprs[1].
1553 type & IMMEDIATE)
1554 && output_ins.oprs[1].segment ==
1555 NO_SEG
1556 && output_ins.oprs[1].wrt ==
1557 NO_SEG) {
1558 def_label(output_ins.label,
1559 output_ins.oprs[0].
1560 offset | SEG_ABS,
1561 output_ins.oprs[1].offset, NULL,
1562 false, false, ofmt,
1563 report_error);
1564 } else
1565 report_error(ERR_NONFATAL,
1566 "bad syntax for EQU");
1568 } else {
1570 * Special `..' EQUs get processed here, except
1571 * `..@' macro processor EQUs which are done above.
1573 if (output_ins.label[0] == '.' &&
1574 output_ins.label[1] == '.' &&
1575 output_ins.label[2] != '@') {
1576 if (output_ins.operands == 1 &&
1577 (output_ins.oprs[0].type & IMMEDIATE)) {
1578 define_label(output_ins.label,
1579 output_ins.oprs[0].segment,
1580 output_ins.oprs[0].offset,
1581 NULL, false, false, ofmt,
1582 report_error);
1583 } else if (output_ins.operands == 2
1584 && (output_ins.oprs[0].
1585 type & IMMEDIATE)
1586 && (output_ins.oprs[0].type & COLON)
1587 && output_ins.oprs[0].segment ==
1588 NO_SEG
1589 && (output_ins.oprs[1].
1590 type & IMMEDIATE)
1591 && output_ins.oprs[1].segment ==
1592 NO_SEG) {
1593 define_label(output_ins.label,
1594 output_ins.oprs[0].
1595 offset | SEG_ABS,
1596 output_ins.oprs[1].offset,
1597 NULL, false, false, ofmt,
1598 report_error);
1599 } else
1600 report_error(ERR_NONFATAL,
1601 "bad syntax for EQU");
1604 } else { /* instruction isn't an EQU */
1606 if (pass1 == 1) {
1608 int64_t l = insn_size(location.segment, offs, sb, cpu,
1609 &output_ins, report_error);
1611 /* if (using_debug_info) && output_ins.opcode != -1) */
1612 if (using_debug_info)
1613 { /* fbk 03/25/01 */
1614 /* this is done here so we can do debug type info */
1615 int32_t typeinfo =
1616 TYS_ELEMENTS(output_ins.operands);
1617 switch (output_ins.opcode) {
1618 case I_RESB:
1619 typeinfo =
1620 TYS_ELEMENTS(output_ins.oprs[0].
1621 offset) | TY_BYTE;
1622 break;
1623 case I_RESW:
1624 typeinfo =
1625 TYS_ELEMENTS(output_ins.oprs[0].
1626 offset) | TY_WORD;
1627 break;
1628 case I_RESD:
1629 typeinfo =
1630 TYS_ELEMENTS(output_ins.oprs[0].
1631 offset) | TY_DWORD;
1632 break;
1633 case I_RESQ:
1634 typeinfo =
1635 TYS_ELEMENTS(output_ins.oprs[0].
1636 offset) | TY_QWORD;
1637 break;
1638 case I_REST:
1639 typeinfo =
1640 TYS_ELEMENTS(output_ins.oprs[0].
1641 offset) | TY_TBYTE;
1642 break;
1643 case I_RESO:
1644 typeinfo =
1645 TYS_ELEMENTS(output_ins.oprs[0].
1646 offset) | TY_OWORD;
1647 break;
1648 case I_RESY:
1649 typeinfo =
1650 TYS_ELEMENTS(output_ins.oprs[0].
1651 offset) | TY_YWORD;
1652 break;
1653 case I_DB:
1654 typeinfo |= TY_BYTE;
1655 break;
1656 case I_DW:
1657 typeinfo |= TY_WORD;
1658 break;
1659 case I_DD:
1660 if (output_ins.eops_float)
1661 typeinfo |= TY_FLOAT;
1662 else
1663 typeinfo |= TY_DWORD;
1664 break;
1665 case I_DQ:
1666 typeinfo |= TY_QWORD;
1667 break;
1668 case I_DT:
1669 typeinfo |= TY_TBYTE;
1670 break;
1671 case I_DO:
1672 typeinfo |= TY_OWORD;
1673 break;
1674 case I_DY:
1675 typeinfo |= TY_YWORD;
1676 break;
1677 default:
1678 typeinfo = TY_LABEL;
1682 ofmt->current_dfmt->debug_typevalue(typeinfo);
1685 if (l != -1) {
1686 offs += l;
1687 SET_CURR_OFFS(offs);
1690 * else l == -1 => invalid instruction, which will be
1691 * flagged as an error on pass 2
1694 } else {
1695 offs += assemble(location.segment, offs, sb, cpu,
1696 &output_ins, ofmt, report_error,
1697 &nasmlist);
1698 SET_CURR_OFFS(offs);
1701 } /* not an EQU */
1702 cleanup_insn(&output_ins);
1704 nasm_free(line);
1705 location.offset = offs = GET_CURR_OFFS;
1706 } /* end while (line = preproc->getline... */
1707 if (pass1 == 2 && global_offset_changed)
1708 report_error(ERR_NONFATAL,
1709 "phase error detected at end of assembly.");
1711 if (pass1 == 1)
1712 preproc->cleanup(1);
1714 if (pass1 == 1 && terminate_after_phase) {
1715 fclose(ofile);
1716 remove(outname);
1717 if (want_usage)
1718 usage();
1719 exit(1);
1722 if (passn > 1 && !global_offset_changed)
1723 pass0++;
1724 else if (global_offset_changed && global_offset_changed < prev_offset_changed) {
1725 prev_offset_changed = global_offset_changed;
1726 stall_count = 0;
1728 else stall_count++;
1730 if((stall_count > 997) || (passn >= pass_max))
1731 /* We get here if the labels don't converge
1732 * Example: FOO equ FOO + 1
1734 report_error(ERR_NONFATAL,
1735 "Can't find valid values for all labels "
1736 "after %d passes, giving up.\n"
1737 " Possible cause: recursive equ's.", passn);
1740 preproc->cleanup(0);
1741 nasmlist.cleanup();
1742 if (opt_verbose_info) /* -On and -Ov switches */
1743 fprintf(stdout,
1744 "info:: assembly required 1+%d+1 passes\n", passn-3);
1745 } /* exit from assemble_file (...) */
1747 static enum directives getkw(char **directive, char **value)
1749 char *p, *q, *buf;
1751 buf = *directive;
1753 /* allow leading spaces or tabs */
1754 while (*buf == ' ' || *buf == '\t')
1755 buf++;
1757 if (*buf != '[')
1758 return 0;
1760 p = buf;
1762 while (*p && *p != ']')
1763 p++;
1765 if (!*p)
1766 return 0;
1768 q = p++;
1770 while (*p && *p != ';') {
1771 if (!nasm_isspace(*p))
1772 return 0;
1773 p++;
1775 q[1] = '\0';
1777 *directive = p = buf + 1;
1778 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1779 buf++;
1780 if (*buf == ']') {
1781 *buf = '\0';
1782 *value = buf;
1783 } else {
1784 *buf++ = '\0';
1785 while (nasm_isspace(*buf))
1786 buf++; /* beppu - skip leading whitespace */
1787 *value = buf;
1788 while (*buf != ']')
1789 buf++;
1790 *buf++ = '\0';
1793 return bsii(*directive, directives, elements(directives));
1797 * gnu style error reporting
1798 * This function prints an error message to error_file in the
1799 * style used by GNU. An example would be:
1800 * file.asm:50: error: blah blah blah
1801 * where file.asm is the name of the file, 50 is the line number on
1802 * which the error occurs (or is detected) and "error:" is one of
1803 * the possible optional diagnostics -- it can be "error" or "warning"
1804 * or something else. Finally the line terminates with the actual
1805 * error message.
1807 * @param severity the severity of the warning or error
1808 * @param fmt the printf style format string
1810 static void report_error_gnu(int severity, const char *fmt, ...)
1812 va_list ap;
1814 if (is_suppressed_warning(severity))
1815 return;
1817 if (severity & ERR_NOFILE)
1818 fputs("nasm: ", error_file);
1819 else {
1820 char *currentfile = NULL;
1821 int32_t lineno = 0;
1822 src_get(&lineno, &currentfile);
1823 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1824 nasm_free(currentfile);
1826 va_start(ap, fmt);
1827 report_error_common(severity, fmt, ap);
1828 va_end(ap);
1832 * MS style error reporting
1833 * This function prints an error message to error_file in the
1834 * style used by Visual C and some other Microsoft tools. An example
1835 * would be:
1836 * file.asm(50) : error: blah blah blah
1837 * where file.asm is the name of the file, 50 is the line number on
1838 * which the error occurs (or is detected) and "error:" is one of
1839 * the possible optional diagnostics -- it can be "error" or "warning"
1840 * or something else. Finally the line terminates with the actual
1841 * error message.
1843 * @param severity the severity of the warning or error
1844 * @param fmt the printf style format string
1846 static void report_error_vc(int severity, const char *fmt, ...)
1848 va_list ap;
1850 if (is_suppressed_warning(severity))
1851 return;
1853 if (severity & ERR_NOFILE)
1854 fputs("nasm: ", error_file);
1855 else {
1856 char *currentfile = NULL;
1857 int32_t lineno = 0;
1858 src_get(&lineno, &currentfile);
1859 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1860 nasm_free(currentfile);
1862 va_start(ap, fmt);
1863 report_error_common(severity, fmt, ap);
1864 va_end(ap);
1868 * check for supressed warning
1869 * checks for suppressed warning or pass one only warning and we're
1870 * not in pass 1
1872 * @param severity the severity of the warning or error
1873 * @return true if we should abort error/warning printing
1875 static bool is_suppressed_warning(int severity)
1878 * See if it's a suppressed warning.
1880 return (severity & ERR_MASK) == ERR_WARNING &&
1881 (((severity & ERR_WARN_MASK) != 0 &&
1882 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1883 /* See if it's a pass-one only warning and we're not in pass one. */
1884 ((severity & ERR_PASS1) && pass0 != 1) ||
1885 ((severity & ERR_PASS2) && pass0 != 2));
1889 * common error reporting
1890 * This is the common back end of the error reporting schemes currently
1891 * implemented. It prints the nature of the warning and then the
1892 * specific error message to error_file and may or may not return. It
1893 * doesn't return if the error severity is a "panic" or "debug" type.
1895 * @param severity the severity of the warning or error
1896 * @param fmt the printf style format string
1898 static void report_error_common(int severity, const char *fmt,
1899 va_list args)
1901 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1902 case ERR_WARNING:
1903 fputs("warning: ", error_file);
1904 break;
1905 case ERR_NONFATAL:
1906 fputs("error: ", error_file);
1907 break;
1908 case ERR_FATAL:
1909 fputs("fatal: ", error_file);
1910 break;
1911 case ERR_PANIC:
1912 fputs("panic: ", error_file);
1913 break;
1914 case ERR_DEBUG:
1915 fputs("debug: ", error_file);
1916 break;
1917 default:
1918 break;
1921 vfprintf(error_file, fmt, args);
1922 putc('\n', error_file);
1924 if (severity & ERR_USAGE)
1925 want_usage = true;
1927 switch (severity & ERR_MASK) {
1928 case ERR_DEBUG:
1929 /* no further action, by definition */
1930 break;
1931 case ERR_WARNING:
1932 if (warning_on[0]) /* Treat warnings as errors */
1933 terminate_after_phase = true;
1934 break;
1935 case ERR_NONFATAL:
1936 terminate_after_phase = true;
1937 break;
1938 case ERR_FATAL:
1939 if (ofile) {
1940 fclose(ofile);
1941 remove(outname);
1943 if (want_usage)
1944 usage();
1945 exit(1); /* instantly die */
1946 break; /* placate silly compilers */
1947 case ERR_PANIC:
1948 fflush(NULL);
1949 /* abort(); *//* halt, catch fire, and dump core */
1950 exit(3);
1951 break;
1955 static void usage(void)
1957 fputs("type `nasm -h' for help\n", error_file);
1960 static void register_output_formats(void)
1962 ofmt = ofmt_register(report_error);
1965 #define BUF_DELTA 512
1967 static FILE *no_pp_fp;
1968 static efunc no_pp_err;
1969 static ListGen *no_pp_list;
1970 static int32_t no_pp_lineinc;
1972 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1973 ListGen * listgen, StrList **deplist)
1975 src_set_fname(nasm_strdup(file));
1976 src_set_linnum(0);
1977 no_pp_lineinc = 1;
1978 no_pp_err = error;
1979 no_pp_fp = fopen(file, "r");
1980 if (!no_pp_fp)
1981 no_pp_err(ERR_FATAL | ERR_NOFILE,
1982 "unable to open input file `%s'", file);
1983 no_pp_list = listgen;
1984 (void)pass; /* placate compilers */
1985 (void)eval; /* placate compilers */
1987 if (deplist) {
1988 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1989 sl->next = NULL;
1990 strcpy(sl->str, file);
1991 *deplist = sl;
1995 static char *no_pp_getline(void)
1997 char *buffer, *p, *q;
1998 int bufsize;
2000 bufsize = BUF_DELTA;
2001 buffer = nasm_malloc(BUF_DELTA);
2002 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2004 while (1) { /* Loop to handle %line */
2006 p = buffer;
2007 while (1) { /* Loop to handle long lines */
2008 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2009 if (!q)
2010 break;
2011 p += strlen(p);
2012 if (p > buffer && p[-1] == '\n')
2013 break;
2014 if (p - buffer > bufsize - 10) {
2015 int offset;
2016 offset = p - buffer;
2017 bufsize += BUF_DELTA;
2018 buffer = nasm_realloc(buffer, bufsize);
2019 p = buffer + offset;
2023 if (!q && p == buffer) {
2024 nasm_free(buffer);
2025 return NULL;
2029 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2030 * them are present at the end of the line.
2032 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2034 if (!nasm_strnicmp(buffer, "%line", 5)) {
2035 int32_t ln;
2036 int li;
2037 char *nm = nasm_malloc(strlen(buffer));
2038 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2039 nasm_free(src_set_fname(nm));
2040 src_set_linnum(ln);
2041 no_pp_lineinc = li;
2042 continue;
2044 nasm_free(nm);
2046 break;
2049 no_pp_list->line(LIST_READ, buffer);
2051 return buffer;
2054 static void no_pp_cleanup(int pass)
2056 (void)pass; /* placate GCC */
2057 fclose(no_pp_fp);
2060 static uint32_t get_cpu(char *value)
2062 if (!strcmp(value, "8086"))
2063 return IF_8086;
2064 if (!strcmp(value, "186"))
2065 return IF_186;
2066 if (!strcmp(value, "286"))
2067 return IF_286;
2068 if (!strcmp(value, "386"))
2069 return IF_386;
2070 if (!strcmp(value, "486"))
2071 return IF_486;
2072 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2073 return IF_PENT;
2074 if (!strcmp(value, "686") ||
2075 !nasm_stricmp(value, "ppro") ||
2076 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2077 return IF_P6;
2078 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2079 return IF_KATMAI;
2080 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2081 !nasm_stricmp(value, "willamette"))
2082 return IF_WILLAMETTE;
2083 if (!nasm_stricmp(value, "prescott"))
2084 return IF_PRESCOTT;
2085 if (!nasm_stricmp(value, "x64") ||
2086 !nasm_stricmp(value, "x86-64"))
2087 return IF_X86_64;
2088 if (!nasm_stricmp(value, "ia64") ||
2089 !nasm_stricmp(value, "ia-64") ||
2090 !nasm_stricmp(value, "itanium") ||
2091 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2092 return IF_IA64;
2094 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2095 "unknown 'cpu' type");
2097 return IF_PLEVEL; /* the maximum level */
2100 static int get_bits(char *value)
2102 int i;
2104 if ((i = atoi(value)) == 16)
2105 return i; /* set for a 16-bit segment */
2106 else if (i == 32) {
2107 if (cpu < IF_386) {
2108 report_error(ERR_NONFATAL,
2109 "cannot specify 32-bit segment on processor below a 386");
2110 i = 16;
2112 } else if (i == 64) {
2113 if (cpu < IF_X86_64) {
2114 report_error(ERR_NONFATAL,
2115 "cannot specify 64-bit segment on processor below an x86-64");
2116 i = 16;
2118 if (i != maxbits) {
2119 report_error(ERR_NONFATAL,
2120 "%s output format does not support 64-bit code",
2121 ofmt->shortname);
2122 i = 16;
2124 } else {
2125 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2126 "`%s' is not a valid segment size; must be 16, 32 or 64",
2127 value);
2128 i = 16;
2130 return i;
2133 /* end of nasm.c */