Add dummy test for version tracking
[nasm/autotest.git] / nasm.c
blob66c69bf8c81ae25bc2c02d57884223c225a9941f
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 bool global_offset_changed; /* referenced in labels.c */
78 static struct location location;
79 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
80 int32_t abs_seg; /* ABSOLUTE segment basis */
81 int32_t abs_offset; /* ABSOLUTE offset */
83 static struct RAA *offsets;
85 static struct SAA *forwrefs; /* keep track of forward references */
86 static const struct forwrefinfo *forwref;
88 static Preproc *preproc;
89 enum op_type {
90 op_normal, /* Preprocess and assemble */
91 op_preprocess, /* Preprocess only */
92 op_depend, /* Generate dependencies */
94 static enum op_type operating_mode;
95 /* Dependency flags */
96 static bool depend_emit_phony = false;
97 static bool depend_missing_ok = false;
98 static const char *depend_target = NULL;
99 static const char *depend_file = NULL;
102 * Which of the suppressible warnings are suppressed. Entry zero
103 * isn't an actual warning, but it used for -w+error/-Werror.
105 static bool suppressed[ERR_WARN_MAX+1] = {
106 true, false, true, false, false, true, false, true, true, false
110 * The option names for the suppressible warnings. As before, entry
111 * zero does nothing.
113 static const char *suppressed_names[ERR_WARN_MAX+1] = {
114 "error", "macro-params", "macro-selfref", "orphan-labels",
115 "number-overflow", "gnu-elf-extensions", "float-overflow",
116 "float-denorm", "float-underflow", "float-toolong"
120 * The explanations for the suppressible warnings. As before, entry
121 * zero does nothing.
123 static const char *suppressed_what[ERR_WARN_MAX+1] = {
124 "treat warnings as errors",
125 "macro calls with wrong parameter count",
126 "cyclic macro references",
127 "labels alone on lines without trailing `:'",
128 "numeric constants does not fit in 64 bits",
129 "using 8- or 16-bit relocation in ELF32, a GNU extension",
130 "floating point overflow",
131 "floating point denormal",
132 "floating point underflow",
133 "too many digits in floating-point number"
137 * This is a null preprocessor which just copies lines from input
138 * to output. It's used when someone explicitly requests that NASM
139 * not preprocess their source file.
142 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
143 static char *no_pp_getline(void);
144 static void no_pp_cleanup(int);
145 static Preproc no_pp = {
146 no_pp_reset,
147 no_pp_getline,
148 no_pp_cleanup
152 * get/set current offset...
154 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
155 raa_read(offsets,location.segment))
156 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
157 (void)(offsets=raa_write(offsets,location.segment,(x))))
159 static int want_usage;
160 static int terminate_after_phase;
161 int user_nolist = 0; /* fbk 9/2/00 */
163 static void nasm_fputs(const char *line, FILE * outfile)
165 if (outfile) {
166 fputs(line, outfile);
167 putc('\n', outfile);
168 } else
169 puts(line);
172 /* Convert a struct tm to a POSIX-style time constant */
173 static int64_t posix_mktime(struct tm *tm)
175 int64_t t;
176 int64_t y = tm->tm_year;
178 /* See IEEE 1003.1:2004, section 4.14 */
180 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
181 t += tm->tm_yday;
182 t *= 24;
183 t += tm->tm_hour;
184 t *= 60;
185 t += tm->tm_min;
186 t *= 60;
187 t += tm->tm_sec;
189 return t;
192 static void define_macros_early(void)
194 char temp[128];
195 struct tm lt, *lt_p, gm, *gm_p;
196 int64_t posix_time;
198 lt_p = localtime(&official_compile_time);
199 if (lt_p) {
200 lt = *lt_p;
202 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
203 pp_pre_define(temp);
204 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
205 pp_pre_define(temp);
206 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
207 pp_pre_define(temp);
208 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
209 pp_pre_define(temp);
212 gm_p = gmtime(&official_compile_time);
213 if (gm_p) {
214 gm = *gm_p;
216 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
217 pp_pre_define(temp);
218 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
219 pp_pre_define(temp);
220 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
221 pp_pre_define(temp);
222 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
223 pp_pre_define(temp);
226 if (gm_p)
227 posix_time = posix_mktime(&gm);
228 else if (lt_p)
229 posix_time = posix_mktime(&lt);
230 else
231 posix_time = 0;
233 if (posix_time) {
234 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
235 pp_pre_define(temp);
239 static void define_macros_late(void)
241 char temp[128];
243 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
244 ofmt->shortname);
245 pp_pre_define(temp);
248 static void emit_dependencies(StrList *list)
250 FILE *deps;
251 int linepos, len;
252 StrList *l, *nl;
254 if (depend_file && strcmp(depend_file, "-")) {
255 deps = fopen(depend_file, "w");
256 if (!deps) {
257 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
258 "unable to write dependency file `%s'", depend_file);
259 return;
261 } else {
262 deps = stdout;
265 linepos = fprintf(deps, "%s:", depend_target);
266 for (l = list; l; l = l->next) {
267 len = strlen(l->str);
268 if (linepos + len > 62) {
269 fprintf(deps, " \\\n ");
270 linepos = 1;
272 fprintf(deps, " %s", l->str);
273 linepos += len+1;
275 fprintf(deps, "\n\n");
277 for (l = list; l; l = nl) {
278 if (depend_emit_phony)
279 fprintf(deps, "%s:\n\n", l->str);
281 nl = l->next;
282 nasm_free(l);
285 if (deps != stdout)
286 fclose(deps);
289 int main(int argc, char **argv)
291 StrList *depend_list = NULL, **depend_ptr;
293 time(&official_compile_time);
295 pass0 = 1;
296 want_usage = terminate_after_phase = false;
297 report_error = report_error_gnu;
299 error_file = stderr;
301 tolower_init();
303 nasm_set_malloc_error(report_error);
304 offsets = raa_init();
305 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
307 preproc = &nasmpp;
308 operating_mode = op_normal;
310 seg_init();
312 register_output_formats();
314 /* Define some macros dependent on the runtime, but not
315 on the command line. */
316 define_macros_early();
318 parse_cmdline(argc, argv);
320 if (terminate_after_phase) {
321 if (want_usage)
322 usage();
323 return 1;
326 /* If debugging info is disabled, suppress any debug calls */
327 if (!using_debug_info)
328 ofmt->current_dfmt = &null_debug_form;
330 if (ofmt->stdmac)
331 pp_extra_stdmac(ofmt->stdmac);
332 parser_global_info(ofmt, &location);
333 eval_global_info(ofmt, lookup_label, &location);
335 /* define some macros dependent of command-line */
336 define_macros_late();
338 depend_ptr = (depend_file || (operating_mode == op_depend))
339 ? &depend_list : NULL;
340 if (!depend_target)
341 depend_target = outname;
343 switch (operating_mode) {
344 case op_depend:
346 char *line;
348 if (depend_missing_ok)
349 pp_include_path(NULL); /* "assume generated" */
351 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
352 depend_ptr);
353 if (outname[0] == '\0')
354 ofmt->filename(inname, outname, report_error);
355 ofile = NULL;
356 while ((line = preproc->getline()))
357 nasm_free(line);
358 preproc->cleanup(0);
360 break;
362 case op_preprocess:
364 char *line;
365 char *file_name = NULL;
366 int32_t prior_linnum = 0;
367 int lineinc = 0;
369 if (*outname) {
370 ofile = fopen(outname, "w");
371 if (!ofile)
372 report_error(ERR_FATAL | ERR_NOFILE,
373 "unable to open output file `%s'",
374 outname);
375 } else
376 ofile = NULL;
378 location.known = false;
380 /* pass = 1; */
381 preproc->reset(inname, 2, report_error, evaluate, &nasmlist,
382 depend_ptr);
384 while ((line = preproc->getline())) {
386 * We generate %line directives if needed for later programs
388 int32_t linnum = prior_linnum += lineinc;
389 int altline = src_get(&linnum, &file_name);
390 if (altline) {
391 if (altline == 1 && lineinc == 1)
392 nasm_fputs("", ofile);
393 else {
394 lineinc = (altline != -1 || lineinc != 1);
395 fprintf(ofile ? ofile : stdout,
396 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
397 file_name);
399 prior_linnum = linnum;
401 nasm_fputs(line, ofile);
402 nasm_free(line);
404 nasm_free(file_name);
405 preproc->cleanup(0);
406 if (ofile)
407 fclose(ofile);
408 if (ofile && terminate_after_phase)
409 remove(outname);
411 break;
413 case op_normal:
416 * We must call ofmt->filename _anyway_, even if the user
417 * has specified their own output file, because some
418 * formats (eg OBJ and COFF) use ofmt->filename to find out
419 * the name of the input file and then put that inside the
420 * file.
422 ofmt->filename(inname, outname, report_error);
424 ofile = fopen(outname, "wb");
425 if (!ofile) {
426 report_error(ERR_FATAL | ERR_NOFILE,
427 "unable to open output file `%s'", outname);
431 * We must call init_labels() before ofmt->init() since
432 * some object formats will want to define labels in their
433 * init routines. (eg OS/2 defines the FLAT group)
435 init_labels();
437 ofmt->init(ofile, report_error, define_label, evaluate);
439 assemble_file(inname, depend_ptr);
441 if (!terminate_after_phase) {
442 ofmt->cleanup(using_debug_info);
443 cleanup_labels();
444 } else {
446 * Despite earlier comments, we need this fclose.
447 * The object output drivers only fclose on cleanup,
448 * and we just skipped that.
450 fclose (ofile);
452 remove(outname);
453 if (listname[0])
454 remove(listname);
457 break;
460 if (depend_list)
461 emit_dependencies(depend_list);
463 if (want_usage)
464 usage();
466 raa_free(offsets);
467 saa_free(forwrefs);
468 eval_cleanup();
469 stdscan_cleanup();
471 if (terminate_after_phase)
472 return 1;
473 else
474 return 0;
478 * Get a parameter for a command line option.
479 * First arg must be in the form of e.g. -f...
481 static char *get_param(char *p, char *q, bool *advance)
483 *advance = false;
484 if (p[2]) { /* the parameter's in the option */
485 p += 2;
486 while (nasm_isspace(*p))
487 p++;
488 return p;
490 if (q && q[0]) {
491 *advance = true;
492 return q;
494 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
495 "option `-%c' requires an argument", p[1]);
496 return NULL;
500 * Copy a filename
502 static void copy_filename(char *dst, const char *src)
504 size_t len = strlen(src);
506 if (len >= (size_t)FILENAME_MAX) {
507 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
508 return;
510 strncpy(dst, src, FILENAME_MAX);
514 * Convert a string to Make-safe form
516 static char *quote_for_make(const char *str)
518 const char *p;
519 char *os, *q;
521 size_t n = 1; /* Terminating zero */
522 size_t nbs = 0;
524 if (!str)
525 return NULL;
527 for (p = str; *p; p++) {
528 switch (*p) {
529 case ' ':
530 case '\t':
531 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
532 n += nbs + 2;
533 nbs = 0;
534 break;
535 case '$':
536 case '#':
537 nbs = 0;
538 n += 2;
539 break;
540 case '\\':
541 nbs++;
542 n++;
543 break;
544 default:
545 nbs = 0;
546 n++;
547 break;
551 /* Convert N backslashes at the end of filename to 2N backslashes */
552 if (nbs)
553 n += nbs;
555 os = q = nasm_malloc(n);
557 nbs = 0;
558 for (p = str; *p; p++) {
559 switch (*p) {
560 case ' ':
561 case '\t':
562 while (nbs--)
563 *q++ = '\\';
564 *q++ = '\\';
565 *q++ = *p;
566 break;
567 case '$':
568 *q++ = *p;
569 *q++ = *p;
570 nbs = 0;
571 break;
572 case '#':
573 *q++ = '\\';
574 *q++ = *p;
575 nbs = 0;
576 break;
577 case '\\':
578 *q++ = *p;
579 nbs++;
580 break;
581 default:
582 *q++ = *p;
583 nbs = 0;
584 break;
587 while (nbs--)
588 *q++ = '\\';
590 *q = '\0';
592 return os;
595 struct textargs {
596 const char *label;
597 int value;
600 #define OPT_PREFIX 0
601 #define OPT_POSTFIX 1
602 struct textargs textopts[] = {
603 {"prefix", OPT_PREFIX},
604 {"postfix", OPT_POSTFIX},
605 {NULL, 0}
608 static bool stopoptions = false;
609 static bool process_arg(char *p, char *q)
611 char *param;
612 int i;
613 bool advance = false;
614 bool suppress;
616 if (!p || !p[0])
617 return false;
619 if (p[0] == '-' && !stopoptions) {
620 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
621 /* These parameters take values */
622 if (!(param = get_param(p, q, &advance)))
623 return advance;
626 switch (p[1]) {
627 case 's':
628 error_file = stdout;
629 break;
631 case 'o': /* output file */
632 copy_filename(outname, param);
633 break;
635 case 'f': /* output format */
636 ofmt = ofmt_find(param);
637 if (!ofmt) {
638 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
639 "unrecognised output format `%s' - "
640 "use -hf for a list", param);
641 } else {
642 ofmt->current_dfmt = ofmt->debug_formats[0];
644 break;
646 case 'O': /* Optimization level */
648 int opt;
650 if (!*param) {
651 /* Naked -O == -Ox */
652 optimizing = INT_MAX >> 1; /* Almost unlimited */
653 } else {
654 while (*param) {
655 switch (*param) {
656 case '0': case '1': case '2': case '3': case '4':
657 case '5': case '6': case '7': case '8': case '9':
658 opt = strtoul(param, &param, 10);
660 /* -O0 -> optimizing == -1, 0.98 behaviour */
661 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
662 if (opt < 2)
663 optimizing = opt - 1;
664 else
665 optimizing = opt;
666 break;
668 case 'v':
669 case '+':
670 param++;
671 opt_verbose_info = true;
672 break;
674 case 'x':
675 param++;
676 optimizing = INT_MAX >> 1; /* Almost unlimited */
677 break;
679 default:
680 report_error(ERR_FATAL,
681 "unknown optimization option -O%c\n",
682 *param);
683 break;
687 break;
690 case 'p': /* pre-include */
691 case 'P':
692 pp_pre_include(param);
693 break;
695 case 'd': /* pre-define */
696 case 'D':
697 pp_pre_define(param);
698 break;
700 case 'u': /* un-define */
701 case 'U':
702 pp_pre_undefine(param);
703 break;
705 case 'i': /* include search path */
706 case 'I':
707 pp_include_path(param);
708 break;
710 case 'l': /* listing file */
711 copy_filename(listname, param);
712 break;
714 case 'Z': /* error messages file */
715 strcpy(errname, param);
716 break;
718 case 'F': /* specify debug format */
719 ofmt->current_dfmt = dfmt_find(ofmt, param);
720 if (!ofmt->current_dfmt) {
721 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
722 "unrecognized debug format `%s' for"
723 " output format `%s'",
724 param, ofmt->shortname);
726 using_debug_info = true;
727 break;
729 case 'X': /* specify error reporting format */
730 if (nasm_stricmp("vc", param) == 0)
731 report_error = report_error_vc;
732 else if (nasm_stricmp("gnu", param) == 0)
733 report_error = report_error_gnu;
734 else
735 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
736 "unrecognized error reporting format `%s'",
737 param);
738 break;
740 case 'g':
741 using_debug_info = true;
742 break;
744 case 'h':
745 printf
746 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
747 "[-l listfile]\n"
748 " [options...] [--] filename\n"
749 " or nasm -v for version info\n\n"
750 " -t assemble in SciTech TASM compatible mode\n"
751 " -g generate debug information in selected format.\n");
752 printf
753 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
754 " -a don't preprocess (assemble only)\n"
755 " -M generate Makefile dependencies on stdout\n"
756 " -MG d:o, missing files assumed generated\n\n"
757 " -Z<file> redirect error messages to file\n"
758 " -s redirect error messages to stdout\n\n"
759 " -F format select a debugging format\n\n"
760 " -I<path> adds a pathname to the include file path\n");
761 printf
762 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
763 " -P<file> pre-includes a file\n"
764 " -D<macro>[=<value>] pre-defines a macro\n"
765 " -U<macro> undefines a macro\n"
766 " -X<format> specifies error reporting format (gnu or vc)\n"
767 " -w+foo enables warning foo (equiv. -Wfoo)\n"
768 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
769 "Warnings:\n");
770 for (i = 0; i <= ERR_WARN_MAX; i++)
771 printf(" %-23s %s (default %s)\n",
772 suppressed_names[i], suppressed_what[i],
773 suppressed[i] ? "off" : "on");
774 printf
775 ("\nresponse files should contain command line parameters"
776 ", one per line.\n");
777 if (p[2] == 'f') {
778 printf("\nvalid output formats for -f are"
779 " (`*' denotes default):\n");
780 ofmt_list(ofmt, stdout);
781 } else {
782 printf("\nFor a list of valid output formats, use -hf.\n");
783 printf("For a list of debug formats, use -f <form> -y.\n");
785 exit(0); /* never need usage message here */
786 break;
788 case 'y':
789 printf("\nvalid debug formats for '%s' output format are"
790 " ('*' denotes default):\n", ofmt->shortname);
791 dfmt_list(ofmt, stdout);
792 exit(0);
793 break;
795 case 't':
796 tasm_compatible_mode = true;
797 break;
799 case 'v':
801 const char *nasm_version_string =
802 "NASM version " NASM_VER " compiled on " __DATE__
803 #ifdef DEBUG
804 " with -DDEBUG"
805 #endif
807 puts(nasm_version_string);
808 exit(0); /* never need usage message here */
810 break;
812 case 'e': /* preprocess only */
813 case 'E':
814 operating_mode = op_preprocess;
815 break;
817 case 'a': /* assemble only - don't preprocess */
818 preproc = &no_pp;
819 break;
821 case 'W':
822 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
823 suppress = true;
824 param += 3;
825 } else {
826 suppress = false;
828 goto set_warning;
830 case 'w':
831 if (param[0] != '+' && param[0] != '-') {
832 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
833 "invalid option to `-w'");
834 break;
836 suppress = (param[0] == '-');
837 param++;
838 goto set_warning;
839 set_warning:
840 for (i = 0; i <= ERR_WARN_MAX; i++)
841 if (!nasm_stricmp(param, suppressed_names[i]))
842 break;
843 if (i <= ERR_WARN_MAX)
844 suppressed[i] = suppress;
845 else if (!nasm_stricmp(param, "all"))
846 for (i = 1; i <= ERR_WARN_MAX; i++)
847 suppressed[i] = suppress;
848 else if (!nasm_stricmp(param, "none"))
849 for (i = 1; i <= ERR_WARN_MAX; i++)
850 suppressed[i] = !suppress;
851 else
852 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
853 "invalid warning `%s'", param);
854 break;
856 case 'M':
857 switch (p[2]) {
858 case 0:
859 operating_mode = op_depend;
860 break;
861 case 'G':
862 operating_mode = op_depend;
863 depend_missing_ok = true;
864 break;
865 case 'P':
866 depend_emit_phony = true;
867 break;
868 case 'D':
869 depend_file = q;
870 advance = true;
871 break;
872 case 'T':
873 depend_target = q;
874 advance = true;
875 break;
876 case 'Q':
877 depend_target = quote_for_make(q);
878 advance = true;
879 break;
880 default:
881 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
882 "unknown dependency option `-M%c'", p[2]);
883 break;
885 if (advance && (!q || !q[0])) {
886 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
887 "option `-M%c' requires a parameter", p[2]);
888 break;
890 break;
892 case '-':
894 int s;
896 if (p[2] == 0) { /* -- => stop processing options */
897 stopoptions = 1;
898 break;
900 for (s = 0; textopts[s].label; s++) {
901 if (!nasm_stricmp(p + 2, textopts[s].label)) {
902 break;
906 switch (s) {
908 case OPT_PREFIX:
909 case OPT_POSTFIX:
911 if (!q) {
912 report_error(ERR_NONFATAL | ERR_NOFILE |
913 ERR_USAGE,
914 "option `--%s' requires an argument",
915 p + 2);
916 break;
917 } else {
918 advance = 1, param = q;
921 if (s == OPT_PREFIX) {
922 strncpy(lprefix, param, PREFIX_MAX - 1);
923 lprefix[PREFIX_MAX - 1] = 0;
924 break;
926 if (s == OPT_POSTFIX) {
927 strncpy(lpostfix, param, POSTFIX_MAX - 1);
928 lpostfix[POSTFIX_MAX - 1] = 0;
929 break;
931 break;
933 default:
935 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
936 "unrecognised option `--%s'", p + 2);
937 break;
940 break;
943 default:
944 if (!ofmt->setinfo(GI_SWITCH, &p))
945 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
946 "unrecognised option `-%c'", p[1]);
947 break;
949 } else {
950 if (*inname) {
951 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
952 "more than one input file specified");
953 } else {
954 copy_filename(inname, p);
958 return advance;
961 #define ARG_BUF_DELTA 128
963 static void process_respfile(FILE * rfile)
965 char *buffer, *p, *q, *prevarg;
966 int bufsize, prevargsize;
968 bufsize = prevargsize = ARG_BUF_DELTA;
969 buffer = nasm_malloc(ARG_BUF_DELTA);
970 prevarg = nasm_malloc(ARG_BUF_DELTA);
971 prevarg[0] = '\0';
973 while (1) { /* Loop to handle all lines in file */
974 p = buffer;
975 while (1) { /* Loop to handle long lines */
976 q = fgets(p, bufsize - (p - buffer), rfile);
977 if (!q)
978 break;
979 p += strlen(p);
980 if (p > buffer && p[-1] == '\n')
981 break;
982 if (p - buffer > bufsize - 10) {
983 int offset;
984 offset = p - buffer;
985 bufsize += ARG_BUF_DELTA;
986 buffer = nasm_realloc(buffer, bufsize);
987 p = buffer + offset;
991 if (!q && p == buffer) {
992 if (prevarg[0])
993 process_arg(prevarg, NULL);
994 nasm_free(buffer);
995 nasm_free(prevarg);
996 return;
1000 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1001 * them are present at the end of the line.
1003 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1005 while (p > buffer && nasm_isspace(p[-1]))
1006 *--p = '\0';
1008 p = buffer;
1009 while (nasm_isspace(*p))
1010 p++;
1012 if (process_arg(prevarg, p))
1013 *p = '\0';
1015 if ((int) strlen(p) > prevargsize - 10) {
1016 prevargsize += ARG_BUF_DELTA;
1017 prevarg = nasm_realloc(prevarg, prevargsize);
1019 strncpy(prevarg, p, prevargsize);
1023 /* Function to process args from a string of args, rather than the
1024 * argv array. Used by the environment variable and response file
1025 * processing.
1027 static void process_args(char *args)
1029 char *p, *q, *arg, *prevarg;
1030 char separator = ' ';
1032 p = args;
1033 if (*p && *p != '-')
1034 separator = *p++;
1035 arg = NULL;
1036 while (*p) {
1037 q = p;
1038 while (*p && *p != separator)
1039 p++;
1040 while (*p == separator)
1041 *p++ = '\0';
1042 prevarg = arg;
1043 arg = q;
1044 if (process_arg(prevarg, arg))
1045 arg = NULL;
1047 if (arg)
1048 process_arg(arg, NULL);
1051 static void process_response_file(const char *file)
1053 char str[2048];
1054 FILE *f = fopen(file, "r");
1055 if (!f) {
1056 perror(file);
1057 exit(-1);
1059 while (fgets(str, sizeof str, f)) {
1060 process_args(str);
1062 fclose(f);
1065 static void parse_cmdline(int argc, char **argv)
1067 FILE *rfile;
1068 char *envreal, *envcopy = NULL, *p, *arg;
1070 *inname = *outname = *listname = *errname = '\0';
1073 * First, process the NASMENV environment variable.
1075 envreal = getenv("NASMENV");
1076 arg = NULL;
1077 if (envreal) {
1078 envcopy = nasm_strdup(envreal);
1079 process_args(envcopy);
1080 nasm_free(envcopy);
1084 * Now process the actual command line.
1086 while (--argc) {
1087 bool advance;
1088 argv++;
1089 if (argv[0][0] == '@') {
1090 /* We have a response file, so process this as a set of
1091 * arguments like the environment variable. This allows us
1092 * to have multiple arguments on a single line, which is
1093 * different to the -@resp file processing below for regular
1094 * NASM.
1096 process_response_file(argv[0]+1);
1097 argc--;
1098 argv++;
1100 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1101 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1102 if (p) {
1103 rfile = fopen(p, "r");
1104 if (rfile) {
1105 process_respfile(rfile);
1106 fclose(rfile);
1107 } else
1108 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1109 "unable to open response file `%s'", p);
1111 } else
1112 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1113 argv += advance, argc -= advance;
1116 /* Look for basic command line typos. This definitely doesn't
1117 catch all errors, but it might help cases of fumbled fingers. */
1118 if (!*inname)
1119 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1120 "no input file specified");
1121 else if (!strcmp(inname, errname) ||
1122 !strcmp(inname, outname) ||
1123 !strcmp(inname, listname) ||
1124 (depend_file && !strcmp(inname, depend_file)))
1125 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1126 "file `%s' is both input and output file",
1127 inname);
1129 if (*errname) {
1130 error_file = fopen(errname, "w");
1131 if (!error_file) {
1132 error_file = stderr; /* Revert to default! */
1133 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1134 "cannot open file `%s' for error messages",
1135 errname);
1140 /* List of directives */
1141 enum directives {
1142 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1143 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1145 static const char *directives[] = {
1146 "", "absolute", "bits", "common", "cpu", "debug", "default",
1147 "extern", "float", "global", "list", "section", "segment", "warning"
1149 static enum directives getkw(char **directive, char **value);
1151 static void assemble_file(char *fname, StrList **depend_ptr)
1153 char *directive, *value, *p, *q, *special, *line, debugid[80];
1154 insn output_ins;
1155 int i, validid;
1156 bool rn_error;
1157 int32_t seg;
1158 int64_t offs;
1159 struct tokenval tokval;
1160 expr *e;
1161 int pass_max;
1163 if (cmd_sb == 32 && cmd_cpu < IF_386)
1164 report_error(ERR_FATAL, "command line: "
1165 "32-bit segment size requires a higher cpu");
1167 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
1168 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
1169 for (passn = 1; pass0 <= 2; passn++) {
1170 int pass1, pass2;
1171 ldfunc def_label;
1173 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1174 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1175 /* pass0 0, 0, 0, ..., 1, 2 */
1177 def_label = passn > 1 ? redefine_label : define_label;
1179 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1180 cpu = cmd_cpu;
1181 if (pass0 == 2) {
1182 if (*listname)
1183 nasmlist.init(listname, report_error);
1185 in_abs_seg = false;
1186 global_offset_changed = false; /* set by redefine_label */
1187 location.segment = ofmt->section(NULL, pass2, &sb);
1188 globalbits = sb;
1189 if (passn > 1) {
1190 saa_rewind(forwrefs);
1191 forwref = saa_rstruct(forwrefs);
1192 raa_free(offsets);
1193 offsets = raa_init();
1195 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1196 pass1 == 2 ? depend_ptr : NULL);
1198 globallineno = 0;
1199 if (passn == 1)
1200 location.known = true;
1201 location.offset = offs = GET_CURR_OFFS;
1203 while ((line = preproc->getline())) {
1204 enum directives d;
1205 globallineno++;
1207 /* here we parse our directives; this is not handled by the 'real'
1208 * parser. */
1209 directive = line;
1210 d = getkw(&directive, &value);
1211 if (d) {
1212 int err = 0;
1214 switch (d) {
1215 case D_SEGMENT: /* [SEGMENT n] */
1216 case D_SECTION:
1217 seg = ofmt->section(value, pass2, &sb);
1218 if (seg == NO_SEG) {
1219 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1220 "segment name `%s' not recognized",
1221 value);
1222 } else {
1223 in_abs_seg = false;
1224 location.segment = seg;
1226 break;
1227 case D_EXTERN: /* [EXTERN label:special] */
1228 if (*value == '$')
1229 value++; /* skip initial $ if present */
1230 if (pass0 == 2) {
1231 q = value;
1232 while (*q && *q != ':')
1233 q++;
1234 if (*q == ':') {
1235 *q++ = '\0';
1236 ofmt->symdef(value, 0L, 0L, 3, q);
1238 } else if (passn == 1) {
1239 q = value;
1240 validid = true;
1241 if (!isidstart(*q))
1242 validid = false;
1243 while (*q && *q != ':') {
1244 if (!isidchar(*q))
1245 validid = false;
1246 q++;
1248 if (!validid) {
1249 report_error(ERR_NONFATAL,
1250 "identifier expected after EXTERN");
1251 break;
1253 if (*q == ':') {
1254 *q++ = '\0';
1255 special = q;
1256 } else
1257 special = NULL;
1258 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1259 int temp = pass0;
1260 pass0 = 1; /* fake pass 1 in labels.c */
1261 declare_as_global(value, special,
1262 report_error);
1263 define_label(value, seg_alloc(), 0L, NULL,
1264 false, true, ofmt, report_error);
1265 pass0 = temp;
1267 } /* else pass0 == 1 */
1268 break;
1269 case D_BITS: /* [BITS bits] */
1270 globalbits = sb = get_bits(value);
1271 break;
1272 case D_GLOBAL: /* [GLOBAL symbol:special] */
1273 if (*value == '$')
1274 value++; /* skip initial $ if present */
1275 if (pass0 == 2) { /* pass 2 */
1276 q = value;
1277 while (*q && *q != ':')
1278 q++;
1279 if (*q == ':') {
1280 *q++ = '\0';
1281 ofmt->symdef(value, 0L, 0L, 3, q);
1283 } else if (pass2 == 1) { /* pass == 1 */
1284 q = value;
1285 validid = true;
1286 if (!isidstart(*q))
1287 validid = false;
1288 while (*q && *q != ':') {
1289 if (!isidchar(*q))
1290 validid = false;
1291 q++;
1293 if (!validid) {
1294 report_error(ERR_NONFATAL,
1295 "identifier expected after GLOBAL");
1296 break;
1298 if (*q == ':') {
1299 *q++ = '\0';
1300 special = q;
1301 } else
1302 special = NULL;
1303 declare_as_global(value, special, report_error);
1304 } /* pass == 1 */
1305 break;
1306 case D_COMMON: /* [COMMON symbol size:special] */
1307 if (*value == '$')
1308 value++; /* skip initial $ if present */
1309 if (pass0 == 1) {
1310 p = value;
1311 validid = true;
1312 if (!isidstart(*p))
1313 validid = false;
1314 while (*p && !nasm_isspace(*p)) {
1315 if (!isidchar(*p))
1316 validid = false;
1317 p++;
1319 if (!validid) {
1320 report_error(ERR_NONFATAL,
1321 "identifier expected after COMMON");
1322 break;
1324 if (*p) {
1325 int64_t size;
1327 while (*p && nasm_isspace(*p))
1328 *p++ = '\0';
1329 q = p;
1330 while (*q && *q != ':')
1331 q++;
1332 if (*q == ':') {
1333 *q++ = '\0';
1334 special = q;
1335 } else
1336 special = NULL;
1337 size = readnum(p, &rn_error);
1338 if (rn_error)
1339 report_error(ERR_NONFATAL,
1340 "invalid size specified"
1341 " in COMMON declaration");
1342 else
1343 define_common(value, seg_alloc(), size,
1344 special, ofmt, report_error);
1345 } else
1346 report_error(ERR_NONFATAL,
1347 "no size specified in"
1348 " COMMON declaration");
1349 } else if (pass0 == 2) { /* pass == 2 */
1350 q = value;
1351 while (*q && *q != ':') {
1352 if (nasm_isspace(*q))
1353 *q = '\0';
1354 q++;
1356 if (*q == ':') {
1357 *q++ = '\0';
1358 ofmt->symdef(value, 0L, 0L, 3, q);
1361 break;
1362 case D_ABSOLUTE: /* [ABSOLUTE address] */
1363 stdscan_reset();
1364 stdscan_bufptr = value;
1365 tokval.t_type = TOKEN_INVALID;
1366 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1367 report_error, NULL);
1368 if (e) {
1369 if (!is_reloc(e))
1370 report_error(pass0 ==
1371 1 ? ERR_NONFATAL : ERR_PANIC,
1372 "cannot use non-relocatable expression as "
1373 "ABSOLUTE address");
1374 else {
1375 abs_seg = reloc_seg(e);
1376 abs_offset = reloc_value(e);
1378 } else if (passn == 1)
1379 abs_offset = 0x100; /* don't go near zero in case of / */
1380 else
1381 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1382 "in pass two");
1383 in_abs_seg = true;
1384 location.segment = NO_SEG;
1385 break;
1386 case D_DEBUG: /* [DEBUG] */
1387 p = value;
1388 q = debugid;
1389 validid = true;
1390 if (!isidstart(*p))
1391 validid = false;
1392 while (*p && !nasm_isspace(*p)) {
1393 if (!isidchar(*p))
1394 validid = false;
1395 *q++ = *p++;
1397 *q++ = 0;
1398 if (!validid) {
1399 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1400 "identifier expected after DEBUG");
1401 break;
1403 while (*p && nasm_isspace(*p))
1404 p++;
1405 if (pass0 == 2)
1406 ofmt->current_dfmt->debug_directive(debugid, p);
1407 break;
1408 case D_WARNING: /* [WARNING {+|-}warn-name] */
1409 if (pass1 == 1) {
1410 while (*value && nasm_isspace(*value))
1411 value++;
1413 if (*value == '+' || *value == '-') {
1414 validid = (*value == '-') ? true : false;
1415 value++;
1416 } else
1417 validid = false;
1419 for (i = 1; i <= ERR_WARN_MAX; i++)
1420 if (!nasm_stricmp(value, suppressed_names[i]))
1421 break;
1422 if (i <= ERR_WARN_MAX)
1423 suppressed[i] = validid;
1424 else
1425 report_error(ERR_NONFATAL,
1426 "invalid warning id in WARNING directive");
1428 break;
1429 case D_CPU: /* [CPU] */
1430 cpu = get_cpu(value);
1431 break;
1432 case D_LIST: /* [LIST {+|-}] */
1433 while (*value && nasm_isspace(*value))
1434 value++;
1436 if (*value == '+') {
1437 user_nolist = 0;
1438 } else {
1439 if (*value == '-') {
1440 user_nolist = 1;
1441 } else {
1442 err = 1;
1445 break;
1446 case D_DEFAULT: /* [DEFAULT] */
1447 stdscan_reset();
1448 stdscan_bufptr = value;
1449 tokval.t_type = TOKEN_INVALID;
1450 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1451 switch ((int)tokval.t_integer) {
1452 case S_REL:
1453 globalrel = 1;
1454 break;
1455 case S_ABS:
1456 globalrel = 0;
1457 break;
1458 default:
1459 err = 1;
1460 break;
1462 } else {
1463 err = 1;
1465 break;
1466 case D_FLOAT:
1467 if (float_option(value)) {
1468 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1469 "unknown 'float' directive: %s",
1470 value);
1472 break;
1473 default:
1474 if (!ofmt->directive(directive, value, pass2))
1475 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1476 "unrecognised directive [%s]",
1477 directive);
1479 if (err) {
1480 report_error(ERR_NONFATAL,
1481 "invalid parameter to [%s] directive",
1482 directive);
1484 } else { /* it isn't a directive */
1486 parse_line(pass1, line, &output_ins,
1487 report_error, evaluate, def_label);
1489 if (!(optimizing > 0) && pass0 == 2) {
1490 if (forwref != NULL && globallineno == forwref->lineno) {
1491 output_ins.forw_ref = true;
1492 do {
1493 output_ins.oprs[forwref->operand].opflags |=
1494 OPFLAG_FORWARD;
1495 forwref = saa_rstruct(forwrefs);
1496 } while (forwref != NULL
1497 && forwref->lineno == globallineno);
1498 } else
1499 output_ins.forw_ref = false;
1502 if (!(optimizing > 0) && output_ins.forw_ref) {
1503 if (passn == 1) {
1504 for (i = 0; i < output_ins.operands; i++) {
1505 if (output_ins.oprs[i].
1506 opflags & OPFLAG_FORWARD) {
1507 struct forwrefinfo *fwinf =
1508 (struct forwrefinfo *)
1509 saa_wstruct(forwrefs);
1510 fwinf->lineno = globallineno;
1511 fwinf->operand = i;
1514 } else { /* passn > 1 */
1516 * Hack to prevent phase error in the code
1517 * rol ax,x
1518 * x equ 1
1520 * If the second operand is a forward reference,
1521 * the UNITY property of the number 1 in that
1522 * operand is cancelled. Otherwise the above
1523 * sequence will cause a phase error.
1525 * This hack means that the above code will
1526 * generate 286+ code.
1528 * The forward reference will mean that the
1529 * operand will not have the UNITY property on
1530 * the first pass, so the pass behaviours will
1531 * be consistent.
1534 if (output_ins.operands >= 2 &&
1535 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1536 !(IMMEDIATE & ~output_ins.oprs[1].type))
1538 /* Remove special properties bits */
1539 output_ins.oprs[1].type &= ~REG_SMASK;
1546 /* forw_ref */
1547 if (output_ins.opcode == I_EQU) {
1548 if (pass1 == 1) {
1550 * Special `..' EQUs get processed in pass two,
1551 * except `..@' macro-processor EQUs which are done
1552 * in the normal place.
1554 if (!output_ins.label)
1555 report_error(ERR_NONFATAL,
1556 "EQU not preceded by label");
1558 else if (output_ins.label[0] != '.' ||
1559 output_ins.label[1] != '.' ||
1560 output_ins.label[2] == '@') {
1561 if (output_ins.operands == 1 &&
1562 (output_ins.oprs[0].type & IMMEDIATE) &&
1563 output_ins.oprs[0].wrt == NO_SEG) {
1564 int isext =
1565 output_ins.oprs[0].
1566 opflags & OPFLAG_EXTERN;
1567 def_label(output_ins.label,
1568 output_ins.oprs[0].segment,
1569 output_ins.oprs[0].offset, NULL,
1570 false, isext, ofmt,
1571 report_error);
1572 } else if (output_ins.operands == 2
1573 && (output_ins.oprs[0].
1574 type & IMMEDIATE)
1575 && (output_ins.oprs[0].type & COLON)
1576 && output_ins.oprs[0].segment ==
1577 NO_SEG
1578 && output_ins.oprs[0].wrt == NO_SEG
1579 && (output_ins.oprs[1].
1580 type & IMMEDIATE)
1581 && output_ins.oprs[1].segment ==
1582 NO_SEG
1583 && output_ins.oprs[1].wrt ==
1584 NO_SEG) {
1585 def_label(output_ins.label,
1586 output_ins.oprs[0].
1587 offset | SEG_ABS,
1588 output_ins.oprs[1].offset, NULL,
1589 false, false, ofmt,
1590 report_error);
1591 } else
1592 report_error(ERR_NONFATAL,
1593 "bad syntax for EQU");
1595 } else {
1597 * Special `..' EQUs get processed here, except
1598 * `..@' macro processor EQUs which are done above.
1600 if (output_ins.label[0] == '.' &&
1601 output_ins.label[1] == '.' &&
1602 output_ins.label[2] != '@') {
1603 if (output_ins.operands == 1 &&
1604 (output_ins.oprs[0].type & IMMEDIATE)) {
1605 define_label(output_ins.label,
1606 output_ins.oprs[0].segment,
1607 output_ins.oprs[0].offset,
1608 NULL, false, false, ofmt,
1609 report_error);
1610 } else if (output_ins.operands == 2
1611 && (output_ins.oprs[0].
1612 type & IMMEDIATE)
1613 && (output_ins.oprs[0].type & COLON)
1614 && output_ins.oprs[0].segment ==
1615 NO_SEG
1616 && (output_ins.oprs[1].
1617 type & IMMEDIATE)
1618 && output_ins.oprs[1].segment ==
1619 NO_SEG) {
1620 define_label(output_ins.label,
1621 output_ins.oprs[0].
1622 offset | SEG_ABS,
1623 output_ins.oprs[1].offset,
1624 NULL, false, false, ofmt,
1625 report_error);
1626 } else
1627 report_error(ERR_NONFATAL,
1628 "bad syntax for EQU");
1631 } else { /* instruction isn't an EQU */
1633 if (pass1 == 1) {
1635 int64_t l = insn_size(location.segment, offs, sb, cpu,
1636 &output_ins, report_error);
1638 /* if (using_debug_info) && output_ins.opcode != -1) */
1639 if (using_debug_info)
1640 { /* fbk 03/25/01 */
1641 /* this is done here so we can do debug type info */
1642 int32_t typeinfo =
1643 TYS_ELEMENTS(output_ins.operands);
1644 switch (output_ins.opcode) {
1645 case I_RESB:
1646 typeinfo =
1647 TYS_ELEMENTS(output_ins.oprs[0].
1648 offset) | TY_BYTE;
1649 break;
1650 case I_RESW:
1651 typeinfo =
1652 TYS_ELEMENTS(output_ins.oprs[0].
1653 offset) | TY_WORD;
1654 break;
1655 case I_RESD:
1656 typeinfo =
1657 TYS_ELEMENTS(output_ins.oprs[0].
1658 offset) | TY_DWORD;
1659 break;
1660 case I_RESQ:
1661 typeinfo =
1662 TYS_ELEMENTS(output_ins.oprs[0].
1663 offset) | TY_QWORD;
1664 break;
1665 case I_REST:
1666 typeinfo =
1667 TYS_ELEMENTS(output_ins.oprs[0].
1668 offset) | TY_TBYTE;
1669 break;
1670 case I_RESO:
1671 typeinfo =
1672 TYS_ELEMENTS(output_ins.oprs[0].
1673 offset) | TY_OWORD;
1674 break;
1675 case I_RESY:
1676 typeinfo =
1677 TYS_ELEMENTS(output_ins.oprs[0].
1678 offset) | TY_YWORD;
1679 break;
1680 case I_DB:
1681 typeinfo |= TY_BYTE;
1682 break;
1683 case I_DW:
1684 typeinfo |= TY_WORD;
1685 break;
1686 case I_DD:
1687 if (output_ins.eops_float)
1688 typeinfo |= TY_FLOAT;
1689 else
1690 typeinfo |= TY_DWORD;
1691 break;
1692 case I_DQ:
1693 typeinfo |= TY_QWORD;
1694 break;
1695 case I_DT:
1696 typeinfo |= TY_TBYTE;
1697 break;
1698 case I_DO:
1699 typeinfo |= TY_OWORD;
1700 break;
1701 case I_DY:
1702 typeinfo |= TY_YWORD;
1703 break;
1704 default:
1705 typeinfo = TY_LABEL;
1709 ofmt->current_dfmt->debug_typevalue(typeinfo);
1712 if (l != -1) {
1713 offs += l;
1714 SET_CURR_OFFS(offs);
1717 * else l == -1 => invalid instruction, which will be
1718 * flagged as an error on pass 2
1721 } else {
1722 offs += assemble(location.segment, offs, sb, cpu,
1723 &output_ins, ofmt, report_error,
1724 &nasmlist);
1725 SET_CURR_OFFS(offs);
1728 } /* not an EQU */
1729 cleanup_insn(&output_ins);
1731 nasm_free(line);
1732 location.offset = offs = GET_CURR_OFFS;
1733 } /* end while (line = preproc->getline... */
1735 if (pass1 == 2 && global_offset_changed)
1736 report_error(ERR_NONFATAL,
1737 "phase error detected at end of assembly.");
1739 if (pass1 == 1)
1740 preproc->cleanup(1);
1742 if (pass1 == 1 && terminate_after_phase) {
1743 fclose(ofile);
1744 remove(outname);
1745 if (want_usage)
1746 usage();
1747 exit(1);
1749 if (passn >= pass_max - 2 ||
1750 (passn > 1 && !global_offset_changed))
1751 pass0++;
1754 preproc->cleanup(0);
1755 nasmlist.cleanup();
1756 #if 1
1757 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1758 fprintf(stdout,
1759 "info:: assembly required 1+%d+1 passes\n", passn-3);
1760 #endif
1761 } /* exit from assemble_file (...) */
1763 static enum directives getkw(char **directive, char **value)
1765 char *p, *q, *buf;
1767 buf = *directive;
1769 /* allow leading spaces or tabs */
1770 while (*buf == ' ' || *buf == '\t')
1771 buf++;
1773 if (*buf != '[')
1774 return 0;
1776 p = buf;
1778 while (*p && *p != ']')
1779 p++;
1781 if (!*p)
1782 return 0;
1784 q = p++;
1786 while (*p && *p != ';') {
1787 if (!nasm_isspace(*p))
1788 return 0;
1789 p++;
1791 q[1] = '\0';
1793 *directive = p = buf + 1;
1794 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1795 buf++;
1796 if (*buf == ']') {
1797 *buf = '\0';
1798 *value = buf;
1799 } else {
1800 *buf++ = '\0';
1801 while (nasm_isspace(*buf))
1802 buf++; /* beppu - skip leading whitespace */
1803 *value = buf;
1804 while (*buf != ']')
1805 buf++;
1806 *buf++ = '\0';
1809 return bsii(*directive, directives, elements(directives));
1813 * gnu style error reporting
1814 * This function prints an error message to error_file in the
1815 * style used by GNU. An example would be:
1816 * file.asm:50: error: blah blah blah
1817 * where file.asm is the name of the file, 50 is the line number on
1818 * which the error occurs (or is detected) and "error:" is one of
1819 * the possible optional diagnostics -- it can be "error" or "warning"
1820 * or something else. Finally the line terminates with the actual
1821 * error message.
1823 * @param severity the severity of the warning or error
1824 * @param fmt the printf style format string
1826 static void report_error_gnu(int severity, const char *fmt, ...)
1828 va_list ap;
1830 if (is_suppressed_warning(severity))
1831 return;
1833 if (severity & ERR_NOFILE)
1834 fputs("nasm: ", error_file);
1835 else {
1836 char *currentfile = NULL;
1837 int32_t lineno = 0;
1838 src_get(&lineno, &currentfile);
1839 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1840 nasm_free(currentfile);
1842 va_start(ap, fmt);
1843 report_error_common(severity, fmt, ap);
1844 va_end(ap);
1848 * MS style error reporting
1849 * This function prints an error message to error_file in the
1850 * style used by Visual C and some other Microsoft tools. An example
1851 * would be:
1852 * file.asm(50) : error: blah blah blah
1853 * where file.asm is the name of the file, 50 is the line number on
1854 * which the error occurs (or is detected) and "error:" is one of
1855 * the possible optional diagnostics -- it can be "error" or "warning"
1856 * or something else. Finally the line terminates with the actual
1857 * error message.
1859 * @param severity the severity of the warning or error
1860 * @param fmt the printf style format string
1862 static void report_error_vc(int severity, const char *fmt, ...)
1864 va_list ap;
1866 if (is_suppressed_warning(severity))
1867 return;
1869 if (severity & ERR_NOFILE)
1870 fputs("nasm: ", error_file);
1871 else {
1872 char *currentfile = NULL;
1873 int32_t lineno = 0;
1874 src_get(&lineno, &currentfile);
1875 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1876 nasm_free(currentfile);
1878 va_start(ap, fmt);
1879 report_error_common(severity, fmt, ap);
1880 va_end(ap);
1884 * check for supressed warning
1885 * checks for suppressed warning or pass one only warning and we're
1886 * not in pass 1
1888 * @param severity the severity of the warning or error
1889 * @return true if we should abort error/warning printing
1891 static bool is_suppressed_warning(int severity)
1894 * See if it's a suppressed warning.
1896 return (severity & ERR_MASK) == ERR_WARNING &&
1897 (((severity & ERR_WARN_MASK) != 0 &&
1898 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1899 /* See if it's a pass-one only warning and we're not in pass one. */
1900 ((severity & ERR_PASS1) && pass0 != 1));
1904 * common error reporting
1905 * This is the common back end of the error reporting schemes currently
1906 * implemented. It prints the nature of the warning and then the
1907 * specific error message to error_file and may or may not return. It
1908 * doesn't return if the error severity is a "panic" or "debug" type.
1910 * @param severity the severity of the warning or error
1911 * @param fmt the printf style format string
1913 static void report_error_common(int severity, const char *fmt,
1914 va_list args)
1916 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1917 case ERR_WARNING:
1918 fputs("warning: ", error_file);
1919 break;
1920 case ERR_NONFATAL:
1921 fputs("error: ", error_file);
1922 break;
1923 case ERR_FATAL:
1924 fputs("fatal: ", error_file);
1925 break;
1926 case ERR_PANIC:
1927 fputs("panic: ", error_file);
1928 break;
1929 case ERR_DEBUG:
1930 fputs("debug: ", error_file);
1931 break;
1932 default:
1933 break;
1936 vfprintf(error_file, fmt, args);
1937 putc('\n', error_file);
1939 if (severity & ERR_USAGE)
1940 want_usage = true;
1942 switch (severity & ERR_MASK) {
1943 case ERR_DEBUG:
1944 /* no further action, by definition */
1945 break;
1946 case ERR_WARNING:
1947 if (!suppressed[0]) /* Treat warnings as errors */
1948 terminate_after_phase = true;
1949 break;
1950 case ERR_NONFATAL:
1951 terminate_after_phase = true;
1952 break;
1953 case ERR_FATAL:
1954 if (ofile) {
1955 fclose(ofile);
1956 remove(outname);
1958 if (want_usage)
1959 usage();
1960 exit(1); /* instantly die */
1961 break; /* placate silly compilers */
1962 case ERR_PANIC:
1963 fflush(NULL);
1964 /* abort(); *//* halt, catch fire, and dump core */
1965 exit(3);
1966 break;
1970 static void usage(void)
1972 fputs("type `nasm -h' for help\n", error_file);
1975 static void register_output_formats(void)
1977 ofmt = ofmt_register(report_error);
1980 #define BUF_DELTA 512
1982 static FILE *no_pp_fp;
1983 static efunc no_pp_err;
1984 static ListGen *no_pp_list;
1985 static int32_t no_pp_lineinc;
1987 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1988 ListGen * listgen, StrList **deplist)
1990 src_set_fname(nasm_strdup(file));
1991 src_set_linnum(0);
1992 no_pp_lineinc = 1;
1993 no_pp_err = error;
1994 no_pp_fp = fopen(file, "r");
1995 if (!no_pp_fp)
1996 no_pp_err(ERR_FATAL | ERR_NOFILE,
1997 "unable to open input file `%s'", file);
1998 no_pp_list = listgen;
1999 (void)pass; /* placate compilers */
2000 (void)eval; /* placate compilers */
2002 if (deplist) {
2003 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2004 sl->next = NULL;
2005 strcpy(sl->str, file);
2006 *deplist = sl;
2010 static char *no_pp_getline(void)
2012 char *buffer, *p, *q;
2013 int bufsize;
2015 bufsize = BUF_DELTA;
2016 buffer = nasm_malloc(BUF_DELTA);
2017 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2019 while (1) { /* Loop to handle %line */
2021 p = buffer;
2022 while (1) { /* Loop to handle long lines */
2023 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2024 if (!q)
2025 break;
2026 p += strlen(p);
2027 if (p > buffer && p[-1] == '\n')
2028 break;
2029 if (p - buffer > bufsize - 10) {
2030 int offset;
2031 offset = p - buffer;
2032 bufsize += BUF_DELTA;
2033 buffer = nasm_realloc(buffer, bufsize);
2034 p = buffer + offset;
2038 if (!q && p == buffer) {
2039 nasm_free(buffer);
2040 return NULL;
2044 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2045 * them are present at the end of the line.
2047 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2049 if (!nasm_strnicmp(buffer, "%line", 5)) {
2050 int32_t ln;
2051 int li;
2052 char *nm = nasm_malloc(strlen(buffer));
2053 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2054 nasm_free(src_set_fname(nm));
2055 src_set_linnum(ln);
2056 no_pp_lineinc = li;
2057 continue;
2059 nasm_free(nm);
2061 break;
2064 no_pp_list->line(LIST_READ, buffer);
2066 return buffer;
2069 static void no_pp_cleanup(int pass)
2071 (void)pass; /* placate GCC */
2072 fclose(no_pp_fp);
2075 static uint32_t get_cpu(char *value)
2077 if (!strcmp(value, "8086"))
2078 return IF_8086;
2079 if (!strcmp(value, "186"))
2080 return IF_186;
2081 if (!strcmp(value, "286"))
2082 return IF_286;
2083 if (!strcmp(value, "386"))
2084 return IF_386;
2085 if (!strcmp(value, "486"))
2086 return IF_486;
2087 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2088 return IF_PENT;
2089 if (!strcmp(value, "686") ||
2090 !nasm_stricmp(value, "ppro") ||
2091 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2092 return IF_P6;
2093 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2094 return IF_KATMAI;
2095 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2096 !nasm_stricmp(value, "willamette"))
2097 return IF_WILLAMETTE;
2098 if (!nasm_stricmp(value, "prescott"))
2099 return IF_PRESCOTT;
2100 if (!nasm_stricmp(value, "x64") ||
2101 !nasm_stricmp(value, "x86-64"))
2102 return IF_X86_64;
2103 if (!nasm_stricmp(value, "ia64") ||
2104 !nasm_stricmp(value, "ia-64") ||
2105 !nasm_stricmp(value, "itanium") ||
2106 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2107 return IF_IA64;
2109 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2110 "unknown 'cpu' type");
2112 return IF_PLEVEL; /* the maximum level */
2115 static int get_bits(char *value)
2117 int i;
2119 if ((i = atoi(value)) == 16)
2120 return i; /* set for a 16-bit segment */
2121 else if (i == 32) {
2122 if (cpu < IF_386) {
2123 report_error(ERR_NONFATAL,
2124 "cannot specify 32-bit segment on processor below a 386");
2125 i = 16;
2127 } else if (i == 64) {
2128 if (cpu < IF_X86_64) {
2129 report_error(ERR_NONFATAL,
2130 "cannot specify 64-bit segment on processor below an x86-64");
2131 i = 16;
2133 if (i != maxbits) {
2134 report_error(ERR_NONFATAL,
2135 "%s output format does not support 64-bit code",
2136 ofmt->shortname);
2137 i = 16;
2139 } else {
2140 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2141 "`%s' is not a valid segment size; must be 16, 32 or 64",
2142 value);
2143 i = 16;
2145 return i;
2148 /* end of nasm.c */