nasmlib.c: fwriteint*() only need WORDS_LITTLEENDIAN
[nasm.git] / nasm.c
blob6ce45d957b2f5cb70115cfba53a37c292a62fe58
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 nasm_set_malloc_error(report_error);
302 offsets = raa_init();
303 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
305 preproc = &nasmpp;
306 operating_mode = op_normal;
308 seg_init();
310 register_output_formats();
312 /* Define some macros dependent on the runtime, but not
313 on the command line. */
314 define_macros_early();
316 parse_cmdline(argc, argv);
318 if (terminate_after_phase) {
319 if (want_usage)
320 usage();
321 return 1;
324 /* If debugging info is disabled, suppress any debug calls */
325 if (!using_debug_info)
326 ofmt->current_dfmt = &null_debug_form;
328 if (ofmt->stdmac)
329 pp_extra_stdmac(ofmt->stdmac);
330 parser_global_info(ofmt, &location);
331 eval_global_info(ofmt, lookup_label, &location);
333 /* define some macros dependent of command-line */
334 define_macros_late();
336 depend_ptr = (depend_file || (operating_mode == op_depend))
337 ? &depend_list : NULL;
338 if (!depend_target)
339 depend_target = outname;
341 switch (operating_mode) {
342 case op_depend:
344 char *line;
346 if (depend_missing_ok)
347 pp_include_path(NULL); /* "assume generated" */
349 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
350 depend_ptr);
351 if (outname[0] == '\0')
352 ofmt->filename(inname, outname, report_error);
353 ofile = NULL;
354 while ((line = preproc->getline()))
355 nasm_free(line);
356 preproc->cleanup(0);
358 break;
360 case op_preprocess:
362 char *line;
363 char *file_name = NULL;
364 int32_t prior_linnum = 0;
365 int lineinc = 0;
367 if (*outname) {
368 ofile = fopen(outname, "w");
369 if (!ofile)
370 report_error(ERR_FATAL | ERR_NOFILE,
371 "unable to open output file `%s'",
372 outname);
373 } else
374 ofile = NULL;
376 location.known = false;
378 /* pass = 1; */
379 preproc->reset(inname, 2, report_error, evaluate, &nasmlist,
380 depend_ptr);
382 while ((line = preproc->getline())) {
384 * We generate %line directives if needed for later programs
386 int32_t linnum = prior_linnum += lineinc;
387 int altline = src_get(&linnum, &file_name);
388 if (altline) {
389 if (altline == 1 && lineinc == 1)
390 nasm_fputs("", ofile);
391 else {
392 lineinc = (altline != -1 || lineinc != 1);
393 fprintf(ofile ? ofile : stdout,
394 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
395 file_name);
397 prior_linnum = linnum;
399 nasm_fputs(line, ofile);
400 nasm_free(line);
402 nasm_free(file_name);
403 preproc->cleanup(0);
404 if (ofile)
405 fclose(ofile);
406 if (ofile && terminate_after_phase)
407 remove(outname);
409 break;
411 case op_normal:
414 * We must call ofmt->filename _anyway_, even if the user
415 * has specified their own output file, because some
416 * formats (eg OBJ and COFF) use ofmt->filename to find out
417 * the name of the input file and then put that inside the
418 * file.
420 ofmt->filename(inname, outname, report_error);
422 ofile = fopen(outname, "wb");
423 if (!ofile) {
424 report_error(ERR_FATAL | ERR_NOFILE,
425 "unable to open output file `%s'", outname);
429 * We must call init_labels() before ofmt->init() since
430 * some object formats will want to define labels in their
431 * init routines. (eg OS/2 defines the FLAT group)
433 init_labels();
435 ofmt->init(ofile, report_error, define_label, evaluate);
437 assemble_file(inname, depend_ptr);
439 if (!terminate_after_phase) {
440 ofmt->cleanup(using_debug_info);
441 cleanup_labels();
442 } else {
444 * We had an fclose on the output file here, but we
445 * actually do that in all the object file drivers as well,
446 * so we're leaving out the one here.
447 * fclose (ofile);
449 remove(outname);
450 if (listname[0])
451 remove(listname);
454 break;
457 if (depend_list)
458 emit_dependencies(depend_list);
460 if (want_usage)
461 usage();
463 raa_free(offsets);
464 saa_free(forwrefs);
465 eval_cleanup();
466 stdscan_cleanup();
468 if (terminate_after_phase)
469 return 1;
470 else
471 return 0;
475 * Get a parameter for a command line option.
476 * First arg must be in the form of e.g. -f...
478 static char *get_param(char *p, char *q, bool *advance)
480 *advance = false;
481 if (p[2]) { /* the parameter's in the option */
482 p += 2;
483 while (isspace(*p))
484 p++;
485 return p;
487 if (q && q[0]) {
488 *advance = true;
489 return q;
491 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
492 "option `-%c' requires an argument", p[1]);
493 return NULL;
497 * Copy a filename
499 static void copy_filename(char *dst, const char *src)
501 size_t len = strlen(src);
503 if (len >= (size_t)FILENAME_MAX) {
504 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
505 return;
507 strncpy(dst, src, FILENAME_MAX);
511 * Convert a string to Make-safe form
513 static char *quote_for_make(const char *str)
515 const char *p;
516 char *os, *q;
518 size_t n = 1; /* Terminating zero */
519 size_t nbs = 0;
521 if (!str)
522 return NULL;
524 for (p = str; *p; p++) {
525 switch (*p) {
526 case ' ':
527 case '\t':
528 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
529 n += nbs + 2;
530 nbs = 0;
531 break;
532 case '$':
533 case '#':
534 nbs = 0;
535 n += 2;
536 break;
537 case '\\':
538 nbs++;
539 n++;
540 break;
541 default:
542 nbs = 0;
543 n++;
544 break;
548 /* Convert N backslashes at the end of filename to 2N backslashes */
549 if (nbs)
550 n += nbs;
552 os = q = nasm_malloc(n);
554 nbs = 0;
555 for (p = str; *p; p++) {
556 switch (*p) {
557 case ' ':
558 case '\t':
559 while (nbs--)
560 *q++ = '\\';
561 *q++ = '\\';
562 *q++ = *p;
563 break;
564 case '$':
565 *q++ = *p;
566 *q++ = *p;
567 nbs = 0;
568 break;
569 case '#':
570 *q++ = '\\';
571 *q++ = *p;
572 nbs = 0;
573 break;
574 case '\\':
575 *q++ = *p;
576 nbs++;
577 break;
578 default:
579 *q++ = *p;
580 nbs = 0;
581 break;
584 while (nbs--)
585 *q++ = '\\';
587 *q = '\0';
589 return os;
592 struct textargs {
593 const char *label;
594 int value;
597 #define OPT_PREFIX 0
598 #define OPT_POSTFIX 1
599 struct textargs textopts[] = {
600 {"prefix", OPT_PREFIX},
601 {"postfix", OPT_POSTFIX},
602 {NULL, 0}
605 static bool stopoptions = false;
606 static bool process_arg(char *p, char *q)
608 char *param;
609 int i;
610 bool advance = false;
611 bool suppress;
613 if (!p || !p[0])
614 return false;
616 if (p[0] == '-' && !stopoptions) {
617 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
618 /* These parameters take values */
619 if (!(param = get_param(p, q, &advance)))
620 return advance;
623 switch (p[1]) {
624 case 's':
625 error_file = stdout;
626 break;
628 case 'o': /* output file */
629 copy_filename(outname, param);
630 break;
632 case 'f': /* output format */
633 ofmt = ofmt_find(param);
634 if (!ofmt) {
635 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
636 "unrecognised output format `%s' - "
637 "use -hf for a list", param);
638 } else {
639 ofmt->current_dfmt = ofmt->debug_formats[0];
641 break;
643 case 'O': /* Optimization level */
645 int opt;
647 if (!*param) {
648 /* Naked -O == -Ox */
649 optimizing = INT_MAX >> 1; /* Almost unlimited */
650 } else {
651 while (*param) {
652 switch (*param) {
653 case '0': case '1': case '2': case '3': case '4':
654 case '5': case '6': case '7': case '8': case '9':
655 opt = strtoul(param, &param, 10);
657 /* -O0 -> optimizing == -1, 0.98 behaviour */
658 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
659 if (opt < 2)
660 optimizing = opt - 1;
661 else
662 optimizing = opt;
663 break;
665 case 'v':
666 case '+':
667 param++;
668 opt_verbose_info = true;
669 break;
671 case 'x':
672 param++;
673 optimizing = INT_MAX >> 1; /* Almost unlimited */
674 break;
676 default:
677 report_error(ERR_FATAL,
678 "unknown optimization option -O%c\n",
679 *param);
680 break;
684 break;
687 case 'p': /* pre-include */
688 case 'P':
689 pp_pre_include(param);
690 break;
692 case 'd': /* pre-define */
693 case 'D':
694 pp_pre_define(param);
695 break;
697 case 'u': /* un-define */
698 case 'U':
699 pp_pre_undefine(param);
700 break;
702 case 'i': /* include search path */
703 case 'I':
704 pp_include_path(param);
705 break;
707 case 'l': /* listing file */
708 copy_filename(listname, param);
709 break;
711 case 'Z': /* error messages file */
712 strcpy(errname, param);
713 break;
715 case 'F': /* specify debug format */
716 ofmt->current_dfmt = dfmt_find(ofmt, param);
717 if (!ofmt->current_dfmt) {
718 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
719 "unrecognized debug format `%s' for"
720 " output format `%s'",
721 param, ofmt->shortname);
723 break;
725 case 'X': /* specify error reporting format */
726 if (nasm_stricmp("vc", param) == 0)
727 report_error = report_error_vc;
728 else if (nasm_stricmp("gnu", param) == 0)
729 report_error = report_error_gnu;
730 else
731 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
732 "unrecognized error reporting format `%s'",
733 param);
734 break;
736 case 'g':
737 using_debug_info = true;
738 break;
740 case 'h':
741 printf
742 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
743 "[-l listfile]\n"
744 " [options...] [--] filename\n"
745 " or nasm -v for version info\n\n"
746 " -t assemble in SciTech TASM compatible mode\n"
747 " -g generate debug information in selected format.\n");
748 printf
749 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
750 " -a don't preprocess (assemble only)\n"
751 " -M generate Makefile dependencies on stdout\n"
752 " -MG d:o, missing files assumed generated\n\n"
753 " -Z<file> redirect error messages to file\n"
754 " -s redirect error messages to stdout\n\n"
755 " -F format select a debugging format\n\n"
756 " -I<path> adds a pathname to the include file path\n");
757 printf
758 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
759 " -P<file> pre-includes a file\n"
760 " -D<macro>[=<value>] pre-defines a macro\n"
761 " -U<macro> undefines a macro\n"
762 " -X<format> specifies error reporting format (gnu or vc)\n"
763 " -w+foo enables warning foo (equiv. -Wfoo)\n"
764 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
765 "Warnings:\n");
766 for (i = 0; i <= ERR_WARN_MAX; i++)
767 printf(" %-23s %s (default %s)\n",
768 suppressed_names[i], suppressed_what[i],
769 suppressed[i] ? "off" : "on");
770 printf
771 ("\nresponse files should contain command line parameters"
772 ", one per line.\n");
773 if (p[2] == 'f') {
774 printf("\nvalid output formats for -f are"
775 " (`*' denotes default):\n");
776 ofmt_list(ofmt, stdout);
777 } else {
778 printf("\nFor a list of valid output formats, use -hf.\n");
779 printf("For a list of debug formats, use -f <form> -y.\n");
781 exit(0); /* never need usage message here */
782 break;
784 case 'y':
785 printf("\nvalid debug formats for '%s' output format are"
786 " ('*' denotes default):\n", ofmt->shortname);
787 dfmt_list(ofmt, stdout);
788 exit(0);
789 break;
791 case 't':
792 tasm_compatible_mode = true;
793 break;
795 case 'v':
797 const char *nasm_version_string =
798 "NASM version " NASM_VER " compiled on " __DATE__
799 #ifdef DEBUG
800 " with -DDEBUG"
801 #endif
803 puts(nasm_version_string);
804 exit(0); /* never need usage message here */
806 break;
808 case 'e': /* preprocess only */
809 case 'E':
810 operating_mode = op_preprocess;
811 break;
813 case 'a': /* assemble only - don't preprocess */
814 preproc = &no_pp;
815 break;
817 case 'W':
818 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
819 suppress = true;
820 param += 3;
821 } else {
822 suppress = false;
824 goto set_warning;
826 case 'w':
827 if (param[0] != '+' && param[0] != '-') {
828 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
829 "invalid option to `-w'");
830 break;
832 suppress = (param[0] == '-');
833 param++;
834 goto set_warning;
835 set_warning:
836 for (i = 0; i <= ERR_WARN_MAX; i++)
837 if (!nasm_stricmp(param, suppressed_names[i]))
838 break;
839 if (i <= ERR_WARN_MAX)
840 suppressed[i] = suppress;
841 else if (!nasm_stricmp(param, "all"))
842 for (i = 1; i <= ERR_WARN_MAX; i++)
843 suppressed[i] = suppress;
844 else if (!nasm_stricmp(param, "none"))
845 for (i = 1; i <= ERR_WARN_MAX; i++)
846 suppressed[i] = !suppress;
847 else
848 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
849 "invalid warning `%s'", param);
850 break;
852 case 'M':
853 switch (p[2]) {
854 case 0:
855 operating_mode = op_depend;
856 break;
857 case 'G':
858 operating_mode = op_depend;
859 depend_missing_ok = true;
860 break;
861 case 'P':
862 depend_emit_phony = true;
863 break;
864 case 'D':
865 depend_file = q;
866 advance = true;
867 break;
868 case 'T':
869 depend_target = q;
870 advance = true;
871 break;
872 case 'Q':
873 depend_target = quote_for_make(q);
874 advance = true;
875 break;
876 default:
877 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
878 "unknown dependency option `-M%c'", p[2]);
879 break;
881 if (advance && (!q || !q[0])) {
882 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
883 "option `-M%c' requires a parameter", p[2]);
884 break;
886 break;
888 case '-':
890 int s;
892 if (p[2] == 0) { /* -- => stop processing options */
893 stopoptions = 1;
894 break;
896 for (s = 0; textopts[s].label; s++) {
897 if (!nasm_stricmp(p + 2, textopts[s].label)) {
898 break;
902 switch (s) {
904 case OPT_PREFIX:
905 case OPT_POSTFIX:
907 if (!q) {
908 report_error(ERR_NONFATAL | ERR_NOFILE |
909 ERR_USAGE,
910 "option `--%s' requires an argument",
911 p + 2);
912 break;
913 } else {
914 advance = 1, param = q;
917 if (s == OPT_PREFIX) {
918 strncpy(lprefix, param, PREFIX_MAX - 1);
919 lprefix[PREFIX_MAX - 1] = 0;
920 break;
922 if (s == OPT_POSTFIX) {
923 strncpy(lpostfix, param, POSTFIX_MAX - 1);
924 lpostfix[POSTFIX_MAX - 1] = 0;
925 break;
927 break;
929 default:
931 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
932 "unrecognised option `--%s'", p + 2);
933 break;
936 break;
939 default:
940 if (!ofmt->setinfo(GI_SWITCH, &p))
941 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
942 "unrecognised option `-%c'", p[1]);
943 break;
945 } else {
946 if (*inname) {
947 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
948 "more than one input file specified");
949 } else {
950 copy_filename(inname, p);
954 return advance;
957 #define ARG_BUF_DELTA 128
959 static void process_respfile(FILE * rfile)
961 char *buffer, *p, *q, *prevarg;
962 int bufsize, prevargsize;
964 bufsize = prevargsize = ARG_BUF_DELTA;
965 buffer = nasm_malloc(ARG_BUF_DELTA);
966 prevarg = nasm_malloc(ARG_BUF_DELTA);
967 prevarg[0] = '\0';
969 while (1) { /* Loop to handle all lines in file */
970 p = buffer;
971 while (1) { /* Loop to handle long lines */
972 q = fgets(p, bufsize - (p - buffer), rfile);
973 if (!q)
974 break;
975 p += strlen(p);
976 if (p > buffer && p[-1] == '\n')
977 break;
978 if (p - buffer > bufsize - 10) {
979 int offset;
980 offset = p - buffer;
981 bufsize += ARG_BUF_DELTA;
982 buffer = nasm_realloc(buffer, bufsize);
983 p = buffer + offset;
987 if (!q && p == buffer) {
988 if (prevarg[0])
989 process_arg(prevarg, NULL);
990 nasm_free(buffer);
991 nasm_free(prevarg);
992 return;
996 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
997 * them are present at the end of the line.
999 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1001 while (p > buffer && isspace(p[-1]))
1002 *--p = '\0';
1004 p = buffer;
1005 while (isspace(*p))
1006 p++;
1008 if (process_arg(prevarg, p))
1009 *p = '\0';
1011 if ((int) strlen(p) > prevargsize - 10) {
1012 prevargsize += ARG_BUF_DELTA;
1013 prevarg = nasm_realloc(prevarg, prevargsize);
1015 strncpy(prevarg, p, prevargsize);
1019 /* Function to process args from a string of args, rather than the
1020 * argv array. Used by the environment variable and response file
1021 * processing.
1023 static void process_args(char *args)
1025 char *p, *q, *arg, *prevarg;
1026 char separator = ' ';
1028 p = args;
1029 if (*p && *p != '-')
1030 separator = *p++;
1031 arg = NULL;
1032 while (*p) {
1033 q = p;
1034 while (*p && *p != separator)
1035 p++;
1036 while (*p == separator)
1037 *p++ = '\0';
1038 prevarg = arg;
1039 arg = q;
1040 if (process_arg(prevarg, arg))
1041 arg = NULL;
1043 if (arg)
1044 process_arg(arg, NULL);
1047 static void process_response_file(const char *file)
1049 char str[2048];
1050 FILE *f = fopen(file, "r");
1051 if (!f) {
1052 perror(file);
1053 exit(-1);
1055 while (fgets(str, sizeof str, f)) {
1056 process_args(str);
1058 fclose(f);
1061 static void parse_cmdline(int argc, char **argv)
1063 FILE *rfile;
1064 char *envreal, *envcopy = NULL, *p, *arg;
1066 *inname = *outname = *listname = *errname = '\0';
1069 * First, process the NASMENV environment variable.
1071 envreal = getenv("NASMENV");
1072 arg = NULL;
1073 if (envreal) {
1074 envcopy = nasm_strdup(envreal);
1075 process_args(envcopy);
1076 nasm_free(envcopy);
1080 * Now process the actual command line.
1082 while (--argc) {
1083 bool advance;
1084 argv++;
1085 if (argv[0][0] == '@') {
1086 /* We have a response file, so process this as a set of
1087 * arguments like the environment variable. This allows us
1088 * to have multiple arguments on a single line, which is
1089 * different to the -@resp file processing below for regular
1090 * NASM.
1092 process_response_file(argv[0]+1);
1093 argc--;
1094 argv++;
1096 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1097 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1098 if (p) {
1099 rfile = fopen(p, "r");
1100 if (rfile) {
1101 process_respfile(rfile);
1102 fclose(rfile);
1103 } else
1104 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1105 "unable to open response file `%s'", p);
1107 } else
1108 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1109 argv += advance, argc -= advance;
1112 /* Look for basic command line typos. This definitely doesn't
1113 catch all errors, but it might help cases of fumbled fingers. */
1114 if (!*inname)
1115 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1116 "no input file specified");
1117 else if (!strcmp(inname, errname) ||
1118 !strcmp(inname, outname) ||
1119 !strcmp(inname, listname) ||
1120 (depend_file && !strcmp(inname, depend_file)))
1121 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1122 "file `%s' is both input and output file",
1123 inname);
1125 if (*errname) {
1126 error_file = fopen(errname, "w");
1127 if (!error_file) {
1128 error_file = stderr; /* Revert to default! */
1129 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1130 "cannot open file `%s' for error messages",
1131 errname);
1136 /* List of directives */
1137 enum directives {
1138 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1139 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1141 static const char *directives[] = {
1142 "", "absolute", "bits", "common", "cpu", "debug", "default",
1143 "extern", "float", "global", "list", "section", "segment", "warning"
1145 static enum directives getkw(char **directive, char **value);
1147 static void assemble_file(char *fname, StrList **depend_ptr)
1149 char *directive, *value, *p, *q, *special, *line, debugid[80];
1150 insn output_ins;
1151 int i, validid;
1152 bool rn_error;
1153 int32_t seg;
1154 int64_t offs;
1155 struct tokenval tokval;
1156 expr *e;
1157 int pass_max;
1159 if (cmd_sb == 32 && cmd_cpu < IF_386)
1160 report_error(ERR_FATAL, "command line: "
1161 "32-bit segment size requires a higher cpu");
1163 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
1164 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
1165 for (passn = 1; pass0 <= 2; passn++) {
1166 int pass1, pass2;
1167 ldfunc def_label;
1169 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1170 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1171 /* pass0 0, 0, 0, ..., 1, 2 */
1173 def_label = passn > 1 ? redefine_label : define_label;
1175 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1176 cpu = cmd_cpu;
1177 if (pass0 == 2) {
1178 if (*listname)
1179 nasmlist.init(listname, report_error);
1181 in_abs_seg = false;
1182 global_offset_changed = false; /* set by redefine_label */
1183 location.segment = ofmt->section(NULL, pass2, &sb);
1184 globalbits = sb;
1185 if (passn > 1) {
1186 saa_rewind(forwrefs);
1187 forwref = saa_rstruct(forwrefs);
1188 raa_free(offsets);
1189 offsets = raa_init();
1191 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1192 pass1 == 2 ? depend_ptr : NULL);
1194 globallineno = 0;
1195 if (passn == 1)
1196 location.known = true;
1197 location.offset = offs = GET_CURR_OFFS;
1199 while ((line = preproc->getline())) {
1200 enum directives d;
1201 globallineno++;
1203 /* here we parse our directives; this is not handled by the 'real'
1204 * parser. */
1205 directive = line;
1206 d = getkw(&directive, &value);
1207 if (d) {
1208 int err = 0;
1210 switch (d) {
1211 case D_SEGMENT: /* [SEGMENT n] */
1212 case D_SECTION:
1213 seg = ofmt->section(value, pass2, &sb);
1214 if (seg == NO_SEG) {
1215 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1216 "segment name `%s' not recognized",
1217 value);
1218 } else {
1219 in_abs_seg = false;
1220 location.segment = seg;
1222 break;
1223 case D_EXTERN: /* [EXTERN label:special] */
1224 if (*value == '$')
1225 value++; /* skip initial $ if present */
1226 if (pass0 == 2) {
1227 q = value;
1228 while (*q && *q != ':')
1229 q++;
1230 if (*q == ':') {
1231 *q++ = '\0';
1232 ofmt->symdef(value, 0L, 0L, 3, q);
1234 } else if (passn == 1) {
1235 q = value;
1236 validid = true;
1237 if (!isidstart(*q))
1238 validid = false;
1239 while (*q && *q != ':') {
1240 if (!isidchar(*q))
1241 validid = false;
1242 q++;
1244 if (!validid) {
1245 report_error(ERR_NONFATAL,
1246 "identifier expected after EXTERN");
1247 break;
1249 if (*q == ':') {
1250 *q++ = '\0';
1251 special = q;
1252 } else
1253 special = NULL;
1254 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1255 int temp = pass0;
1256 pass0 = 1; /* fake pass 1 in labels.c */
1257 declare_as_global(value, special,
1258 report_error);
1259 define_label(value, seg_alloc(), 0L, NULL,
1260 false, true, ofmt, report_error);
1261 pass0 = temp;
1263 } /* else pass0 == 1 */
1264 break;
1265 case D_BITS: /* [BITS bits] */
1266 globalbits = sb = get_bits(value);
1267 break;
1268 case D_GLOBAL: /* [GLOBAL symbol:special] */
1269 if (*value == '$')
1270 value++; /* skip initial $ if present */
1271 if (pass0 == 2) { /* pass 2 */
1272 q = value;
1273 while (*q && *q != ':')
1274 q++;
1275 if (*q == ':') {
1276 *q++ = '\0';
1277 ofmt->symdef(value, 0L, 0L, 3, q);
1279 } else if (pass2 == 1) { /* pass == 1 */
1280 q = value;
1281 validid = true;
1282 if (!isidstart(*q))
1283 validid = false;
1284 while (*q && *q != ':') {
1285 if (!isidchar(*q))
1286 validid = false;
1287 q++;
1289 if (!validid) {
1290 report_error(ERR_NONFATAL,
1291 "identifier expected after GLOBAL");
1292 break;
1294 if (*q == ':') {
1295 *q++ = '\0';
1296 special = q;
1297 } else
1298 special = NULL;
1299 declare_as_global(value, special, report_error);
1300 } /* pass == 1 */
1301 break;
1302 case D_COMMON: /* [COMMON symbol size:special] */
1303 if (*value == '$')
1304 value++; /* skip initial $ if present */
1305 if (pass0 == 1) {
1306 p = value;
1307 validid = true;
1308 if (!isidstart(*p))
1309 validid = false;
1310 while (*p && !isspace(*p)) {
1311 if (!isidchar(*p))
1312 validid = false;
1313 p++;
1315 if (!validid) {
1316 report_error(ERR_NONFATAL,
1317 "identifier expected after COMMON");
1318 break;
1320 if (*p) {
1321 int64_t size;
1323 while (*p && isspace(*p))
1324 *p++ = '\0';
1325 q = p;
1326 while (*q && *q != ':')
1327 q++;
1328 if (*q == ':') {
1329 *q++ = '\0';
1330 special = q;
1331 } else
1332 special = NULL;
1333 size = readnum(p, &rn_error);
1334 if (rn_error)
1335 report_error(ERR_NONFATAL,
1336 "invalid size specified"
1337 " in COMMON declaration");
1338 else
1339 define_common(value, seg_alloc(), size,
1340 special, ofmt, report_error);
1341 } else
1342 report_error(ERR_NONFATAL,
1343 "no size specified in"
1344 " COMMON declaration");
1345 } else if (pass0 == 2) { /* pass == 2 */
1346 q = value;
1347 while (*q && *q != ':') {
1348 if (isspace(*q))
1349 *q = '\0';
1350 q++;
1352 if (*q == ':') {
1353 *q++ = '\0';
1354 ofmt->symdef(value, 0L, 0L, 3, q);
1357 break;
1358 case D_ABSOLUTE: /* [ABSOLUTE address] */
1359 stdscan_reset();
1360 stdscan_bufptr = value;
1361 tokval.t_type = TOKEN_INVALID;
1362 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1363 report_error, NULL);
1364 if (e) {
1365 if (!is_reloc(e))
1366 report_error(pass0 ==
1367 1 ? ERR_NONFATAL : ERR_PANIC,
1368 "cannot use non-relocatable expression as "
1369 "ABSOLUTE address");
1370 else {
1371 abs_seg = reloc_seg(e);
1372 abs_offset = reloc_value(e);
1374 } else if (passn == 1)
1375 abs_offset = 0x100; /* don't go near zero in case of / */
1376 else
1377 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1378 "in pass two");
1379 in_abs_seg = true;
1380 location.segment = NO_SEG;
1381 break;
1382 case D_DEBUG: /* [DEBUG] */
1383 p = value;
1384 q = debugid;
1385 validid = true;
1386 if (!isidstart(*p))
1387 validid = false;
1388 while (*p && !isspace(*p)) {
1389 if (!isidchar(*p))
1390 validid = false;
1391 *q++ = *p++;
1393 *q++ = 0;
1394 if (!validid) {
1395 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1396 "identifier expected after DEBUG");
1397 break;
1399 while (*p && isspace(*p))
1400 p++;
1401 if (pass0 == 2)
1402 ofmt->current_dfmt->debug_directive(debugid, p);
1403 break;
1404 case D_WARNING: /* [WARNING {+|-}warn-name] */
1405 if (pass1 == 1) {
1406 while (*value && isspace(*value))
1407 value++;
1409 if (*value == '+' || *value == '-') {
1410 validid = (*value == '-') ? true : false;
1411 value++;
1412 } else
1413 validid = false;
1415 for (i = 1; i <= ERR_WARN_MAX; i++)
1416 if (!nasm_stricmp(value, suppressed_names[i]))
1417 break;
1418 if (i <= ERR_WARN_MAX)
1419 suppressed[i] = validid;
1420 else
1421 report_error(ERR_NONFATAL,
1422 "invalid warning id in WARNING directive");
1424 break;
1425 case D_CPU: /* [CPU] */
1426 cpu = get_cpu(value);
1427 break;
1428 case D_LIST: /* [LIST {+|-}] */
1429 while (*value && isspace(*value))
1430 value++;
1432 if (*value == '+') {
1433 user_nolist = 0;
1434 } else {
1435 if (*value == '-') {
1436 user_nolist = 1;
1437 } else {
1438 err = 1;
1441 break;
1442 case D_DEFAULT: /* [DEFAULT] */
1443 stdscan_reset();
1444 stdscan_bufptr = value;
1445 tokval.t_type = TOKEN_INVALID;
1446 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1447 switch ((int)tokval.t_integer) {
1448 case S_REL:
1449 globalrel = 1;
1450 break;
1451 case S_ABS:
1452 globalrel = 0;
1453 break;
1454 default:
1455 err = 1;
1456 break;
1458 } else {
1459 err = 1;
1461 break;
1462 case D_FLOAT:
1463 if (float_option(value)) {
1464 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1465 "unknown 'float' directive: %s",
1466 value);
1468 break;
1469 default:
1470 if (!ofmt->directive(directive, value, pass2))
1471 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1472 "unrecognised directive [%s]",
1473 directive);
1475 if (err) {
1476 report_error(ERR_NONFATAL,
1477 "invalid parameter to [%s] directive",
1478 directive);
1480 } else { /* it isn't a directive */
1482 parse_line(pass1, line, &output_ins,
1483 report_error, evaluate, def_label);
1485 if (!(optimizing > 0) && pass0 == 2) {
1486 if (forwref != NULL && globallineno == forwref->lineno) {
1487 output_ins.forw_ref = true;
1488 do {
1489 output_ins.oprs[forwref->operand].opflags |=
1490 OPFLAG_FORWARD;
1491 forwref = saa_rstruct(forwrefs);
1492 } while (forwref != NULL
1493 && forwref->lineno == globallineno);
1494 } else
1495 output_ins.forw_ref = false;
1498 if (!(optimizing > 0) && output_ins.forw_ref) {
1499 if (passn == 1) {
1500 for (i = 0; i < output_ins.operands; i++) {
1501 if (output_ins.oprs[i].
1502 opflags & OPFLAG_FORWARD) {
1503 struct forwrefinfo *fwinf =
1504 (struct forwrefinfo *)
1505 saa_wstruct(forwrefs);
1506 fwinf->lineno = globallineno;
1507 fwinf->operand = i;
1510 } else { /* passn > 1 */
1512 * Hack to prevent phase error in the code
1513 * rol ax,x
1514 * x equ 1
1516 * If the second operand is a forward reference,
1517 * the UNITY property of the number 1 in that
1518 * operand is cancelled. Otherwise the above
1519 * sequence will cause a phase error.
1521 * This hack means that the above code will
1522 * generate 286+ code.
1524 * The forward reference will mean that the
1525 * operand will not have the UNITY property on
1526 * the first pass, so the pass behaviours will
1527 * be consistent.
1530 if (output_ins.operands >= 2 &&
1531 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1532 !(IMMEDIATE & ~output_ins.oprs[1].type))
1534 /* Remove special properties bits */
1535 output_ins.oprs[1].type &= ~REG_SMASK;
1542 /* forw_ref */
1543 if (output_ins.opcode == I_EQU) {
1544 if (pass1 == 1) {
1546 * Special `..' EQUs get processed in pass two,
1547 * except `..@' macro-processor EQUs which are done
1548 * in the normal place.
1550 if (!output_ins.label)
1551 report_error(ERR_NONFATAL,
1552 "EQU not preceded by label");
1554 else if (output_ins.label[0] != '.' ||
1555 output_ins.label[1] != '.' ||
1556 output_ins.label[2] == '@') {
1557 if (output_ins.operands == 1 &&
1558 (output_ins.oprs[0].type & IMMEDIATE) &&
1559 output_ins.oprs[0].wrt == NO_SEG) {
1560 int isext =
1561 output_ins.oprs[0].
1562 opflags & OPFLAG_EXTERN;
1563 def_label(output_ins.label,
1564 output_ins.oprs[0].segment,
1565 output_ins.oprs[0].offset, NULL,
1566 false, isext, ofmt,
1567 report_error);
1568 } else if (output_ins.operands == 2
1569 && (output_ins.oprs[0].
1570 type & IMMEDIATE)
1571 && (output_ins.oprs[0].type & COLON)
1572 && output_ins.oprs[0].segment ==
1573 NO_SEG
1574 && output_ins.oprs[0].wrt == NO_SEG
1575 && (output_ins.oprs[1].
1576 type & IMMEDIATE)
1577 && output_ins.oprs[1].segment ==
1578 NO_SEG
1579 && output_ins.oprs[1].wrt ==
1580 NO_SEG) {
1581 def_label(output_ins.label,
1582 output_ins.oprs[0].
1583 offset | SEG_ABS,
1584 output_ins.oprs[1].offset, NULL,
1585 false, false, ofmt,
1586 report_error);
1587 } else
1588 report_error(ERR_NONFATAL,
1589 "bad syntax for EQU");
1591 } else {
1593 * Special `..' EQUs get processed here, except
1594 * `..@' macro processor EQUs which are done above.
1596 if (output_ins.label[0] == '.' &&
1597 output_ins.label[1] == '.' &&
1598 output_ins.label[2] != '@') {
1599 if (output_ins.operands == 1 &&
1600 (output_ins.oprs[0].type & IMMEDIATE)) {
1601 define_label(output_ins.label,
1602 output_ins.oprs[0].segment,
1603 output_ins.oprs[0].offset,
1604 NULL, false, false, ofmt,
1605 report_error);
1606 } else if (output_ins.operands == 2
1607 && (output_ins.oprs[0].
1608 type & IMMEDIATE)
1609 && (output_ins.oprs[0].type & COLON)
1610 && output_ins.oprs[0].segment ==
1611 NO_SEG
1612 && (output_ins.oprs[1].
1613 type & IMMEDIATE)
1614 && output_ins.oprs[1].segment ==
1615 NO_SEG) {
1616 define_label(output_ins.label,
1617 output_ins.oprs[0].
1618 offset | SEG_ABS,
1619 output_ins.oprs[1].offset,
1620 NULL, false, false, ofmt,
1621 report_error);
1622 } else
1623 report_error(ERR_NONFATAL,
1624 "bad syntax for EQU");
1627 } else { /* instruction isn't an EQU */
1629 if (pass1 == 1) {
1631 int64_t l = insn_size(location.segment, offs, sb, cpu,
1632 &output_ins, report_error);
1634 /* if (using_debug_info) && output_ins.opcode != -1) */
1635 if (using_debug_info)
1636 { /* fbk 03/25/01 */
1637 /* this is done here so we can do debug type info */
1638 int32_t typeinfo =
1639 TYS_ELEMENTS(output_ins.operands);
1640 switch (output_ins.opcode) {
1641 case I_RESB:
1642 typeinfo =
1643 TYS_ELEMENTS(output_ins.oprs[0].
1644 offset) | TY_BYTE;
1645 break;
1646 case I_RESW:
1647 typeinfo =
1648 TYS_ELEMENTS(output_ins.oprs[0].
1649 offset) | TY_WORD;
1650 break;
1651 case I_RESD:
1652 typeinfo =
1653 TYS_ELEMENTS(output_ins.oprs[0].
1654 offset) | TY_DWORD;
1655 break;
1656 case I_RESQ:
1657 typeinfo =
1658 TYS_ELEMENTS(output_ins.oprs[0].
1659 offset) | TY_QWORD;
1660 break;
1661 case I_REST:
1662 typeinfo =
1663 TYS_ELEMENTS(output_ins.oprs[0].
1664 offset) | TY_TBYTE;
1665 break;
1666 case I_RESO:
1667 typeinfo =
1668 TYS_ELEMENTS(output_ins.oprs[0].
1669 offset) | TY_OWORD;
1670 break;
1671 case I_RESY:
1672 typeinfo =
1673 TYS_ELEMENTS(output_ins.oprs[0].
1674 offset) | TY_YWORD;
1675 break;
1676 case I_DB:
1677 typeinfo |= TY_BYTE;
1678 break;
1679 case I_DW:
1680 typeinfo |= TY_WORD;
1681 break;
1682 case I_DD:
1683 if (output_ins.eops_float)
1684 typeinfo |= TY_FLOAT;
1685 else
1686 typeinfo |= TY_DWORD;
1687 break;
1688 case I_DQ:
1689 typeinfo |= TY_QWORD;
1690 break;
1691 case I_DT:
1692 typeinfo |= TY_TBYTE;
1693 break;
1694 case I_DO:
1695 typeinfo |= TY_OWORD;
1696 break;
1697 case I_DY:
1698 typeinfo |= TY_YWORD;
1699 break;
1700 default:
1701 typeinfo = TY_LABEL;
1705 ofmt->current_dfmt->debug_typevalue(typeinfo);
1708 if (l != -1) {
1709 offs += l;
1710 SET_CURR_OFFS(offs);
1713 * else l == -1 => invalid instruction, which will be
1714 * flagged as an error on pass 2
1717 } else {
1718 offs += assemble(location.segment, offs, sb, cpu,
1719 &output_ins, ofmt, report_error,
1720 &nasmlist);
1721 SET_CURR_OFFS(offs);
1724 } /* not an EQU */
1725 cleanup_insn(&output_ins);
1727 nasm_free(line);
1728 location.offset = offs = GET_CURR_OFFS;
1729 } /* end while (line = preproc->getline... */
1731 if (pass1 == 2 && global_offset_changed)
1732 report_error(ERR_NONFATAL,
1733 "phase error detected at end of assembly.");
1735 if (pass1 == 1)
1736 preproc->cleanup(1);
1738 if (pass1 == 1 && terminate_after_phase) {
1739 fclose(ofile);
1740 remove(outname);
1741 if (want_usage)
1742 usage();
1743 exit(1);
1745 if (passn >= pass_max - 2 ||
1746 (passn > 1 && !global_offset_changed))
1747 pass0++;
1750 preproc->cleanup(0);
1751 nasmlist.cleanup();
1752 #if 1
1753 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1754 fprintf(stdout,
1755 "info:: assembly required 1+%d+1 passes\n", passn-3);
1756 #endif
1757 } /* exit from assemble_file (...) */
1759 static enum directives getkw(char **directive, char **value)
1761 char *p, *q, *buf;
1763 buf = *directive;
1765 /* allow leading spaces or tabs */
1766 while (*buf == ' ' || *buf == '\t')
1767 buf++;
1769 if (*buf != '[')
1770 return 0;
1772 p = buf;
1774 while (*p && *p != ']')
1775 p++;
1777 if (!*p)
1778 return 0;
1780 q = p++;
1782 while (*p && *p != ';') {
1783 if (!isspace(*p))
1784 return 0;
1785 p++;
1787 q[1] = '\0';
1789 *directive = p = buf + 1;
1790 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1791 buf++;
1792 if (*buf == ']') {
1793 *buf = '\0';
1794 *value = buf;
1795 } else {
1796 *buf++ = '\0';
1797 while (isspace(*buf))
1798 buf++; /* beppu - skip leading whitespace */
1799 *value = buf;
1800 while (*buf != ']')
1801 buf++;
1802 *buf++ = '\0';
1805 return bsii(*directive, directives, elements(directives));
1809 * gnu style error reporting
1810 * This function prints an error message to error_file in the
1811 * style used by GNU. An example would be:
1812 * file.asm:50: error: blah blah blah
1813 * where file.asm is the name of the file, 50 is the line number on
1814 * which the error occurs (or is detected) and "error:" is one of
1815 * the possible optional diagnostics -- it can be "error" or "warning"
1816 * or something else. Finally the line terminates with the actual
1817 * error message.
1819 * @param severity the severity of the warning or error
1820 * @param fmt the printf style format string
1822 static void report_error_gnu(int severity, const char *fmt, ...)
1824 va_list ap;
1826 if (is_suppressed_warning(severity))
1827 return;
1829 if (severity & ERR_NOFILE)
1830 fputs("nasm: ", error_file);
1831 else {
1832 char *currentfile = NULL;
1833 int32_t lineno = 0;
1834 src_get(&lineno, &currentfile);
1835 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1836 nasm_free(currentfile);
1838 va_start(ap, fmt);
1839 report_error_common(severity, fmt, ap);
1840 va_end(ap);
1844 * MS style error reporting
1845 * This function prints an error message to error_file in the
1846 * style used by Visual C and some other Microsoft tools. An example
1847 * would be:
1848 * file.asm(50) : error: blah blah blah
1849 * where file.asm is the name of the file, 50 is the line number on
1850 * which the error occurs (or is detected) and "error:" is one of
1851 * the possible optional diagnostics -- it can be "error" or "warning"
1852 * or something else. Finally the line terminates with the actual
1853 * error message.
1855 * @param severity the severity of the warning or error
1856 * @param fmt the printf style format string
1858 static void report_error_vc(int severity, const char *fmt, ...)
1860 va_list ap;
1862 if (is_suppressed_warning(severity))
1863 return;
1865 if (severity & ERR_NOFILE)
1866 fputs("nasm: ", error_file);
1867 else {
1868 char *currentfile = NULL;
1869 int32_t lineno = 0;
1870 src_get(&lineno, &currentfile);
1871 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1872 nasm_free(currentfile);
1874 va_start(ap, fmt);
1875 report_error_common(severity, fmt, ap);
1876 va_end(ap);
1880 * check for supressed warning
1881 * checks for suppressed warning or pass one only warning and we're
1882 * not in pass 1
1884 * @param severity the severity of the warning or error
1885 * @return true if we should abort error/warning printing
1887 static bool is_suppressed_warning(int severity)
1890 * See if it's a suppressed warning.
1892 return (severity & ERR_MASK) == ERR_WARNING &&
1893 (((severity & ERR_WARN_MASK) != 0 &&
1894 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1895 /* See if it's a pass-one only warning and we're not in pass one. */
1896 ((severity & ERR_PASS1) && pass0 != 1));
1900 * common error reporting
1901 * This is the common back end of the error reporting schemes currently
1902 * implemented. It prints the nature of the warning and then the
1903 * specific error message to error_file and may or may not return. It
1904 * doesn't return if the error severity is a "panic" or "debug" type.
1906 * @param severity the severity of the warning or error
1907 * @param fmt the printf style format string
1909 static void report_error_common(int severity, const char *fmt,
1910 va_list args)
1912 switch (severity & ERR_MASK) {
1913 case ERR_WARNING:
1914 fputs("warning: ", error_file);
1915 break;
1916 case ERR_NONFATAL:
1917 fputs("error: ", error_file);
1918 break;
1919 case ERR_FATAL:
1920 fputs("fatal: ", error_file);
1921 break;
1922 case ERR_PANIC:
1923 fputs("panic: ", error_file);
1924 break;
1925 case ERR_DEBUG:
1926 fputs("debug: ", error_file);
1927 break;
1930 vfprintf(error_file, fmt, args);
1931 putc('\n', error_file);
1933 if (severity & ERR_USAGE)
1934 want_usage = true;
1936 switch (severity & ERR_MASK) {
1937 case ERR_DEBUG:
1938 /* no further action, by definition */
1939 break;
1940 case ERR_WARNING:
1941 if (!suppressed[0]) /* Treat warnings as errors */
1942 terminate_after_phase = true;
1943 break;
1944 case ERR_NONFATAL:
1945 terminate_after_phase = true;
1946 break;
1947 case ERR_FATAL:
1948 if (ofile) {
1949 fclose(ofile);
1950 remove(outname);
1952 if (want_usage)
1953 usage();
1954 exit(1); /* instantly die */
1955 break; /* placate silly compilers */
1956 case ERR_PANIC:
1957 fflush(NULL);
1958 /* abort(); *//* halt, catch fire, and dump core */
1959 exit(3);
1960 break;
1964 static void usage(void)
1966 fputs("type `nasm -h' for help\n", error_file);
1969 static void register_output_formats(void)
1971 ofmt = ofmt_register(report_error);
1974 #define BUF_DELTA 512
1976 static FILE *no_pp_fp;
1977 static efunc no_pp_err;
1978 static ListGen *no_pp_list;
1979 static int32_t no_pp_lineinc;
1981 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1982 ListGen * listgen, StrList **deplist)
1984 src_set_fname(nasm_strdup(file));
1985 src_set_linnum(0);
1986 no_pp_lineinc = 1;
1987 no_pp_err = error;
1988 no_pp_fp = fopen(file, "r");
1989 if (!no_pp_fp)
1990 no_pp_err(ERR_FATAL | ERR_NOFILE,
1991 "unable to open input file `%s'", file);
1992 no_pp_list = listgen;
1993 (void)pass; /* placate compilers */
1994 (void)eval; /* placate compilers */
1996 if (deplist) {
1997 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1998 sl->next = NULL;
1999 strcpy(sl->str, file);
2000 *deplist = sl;
2004 static char *no_pp_getline(void)
2006 char *buffer, *p, *q;
2007 int bufsize;
2009 bufsize = BUF_DELTA;
2010 buffer = nasm_malloc(BUF_DELTA);
2011 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2013 while (1) { /* Loop to handle %line */
2015 p = buffer;
2016 while (1) { /* Loop to handle long lines */
2017 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2018 if (!q)
2019 break;
2020 p += strlen(p);
2021 if (p > buffer && p[-1] == '\n')
2022 break;
2023 if (p - buffer > bufsize - 10) {
2024 int offset;
2025 offset = p - buffer;
2026 bufsize += BUF_DELTA;
2027 buffer = nasm_realloc(buffer, bufsize);
2028 p = buffer + offset;
2032 if (!q && p == buffer) {
2033 nasm_free(buffer);
2034 return NULL;
2038 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2039 * them are present at the end of the line.
2041 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2043 if (!nasm_strnicmp(buffer, "%line", 5)) {
2044 int32_t ln;
2045 int li;
2046 char *nm = nasm_malloc(strlen(buffer));
2047 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2048 nasm_free(src_set_fname(nm));
2049 src_set_linnum(ln);
2050 no_pp_lineinc = li;
2051 continue;
2053 nasm_free(nm);
2055 break;
2058 no_pp_list->line(LIST_READ, buffer);
2060 return buffer;
2063 static void no_pp_cleanup(int pass)
2065 (void)pass; /* placate GCC */
2066 fclose(no_pp_fp);
2069 static uint32_t get_cpu(char *value)
2071 if (!strcmp(value, "8086"))
2072 return IF_8086;
2073 if (!strcmp(value, "186"))
2074 return IF_186;
2075 if (!strcmp(value, "286"))
2076 return IF_286;
2077 if (!strcmp(value, "386"))
2078 return IF_386;
2079 if (!strcmp(value, "486"))
2080 return IF_486;
2081 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2082 return IF_PENT;
2083 if (!strcmp(value, "686") ||
2084 !nasm_stricmp(value, "ppro") ||
2085 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2086 return IF_P6;
2087 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2088 return IF_KATMAI;
2089 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2090 !nasm_stricmp(value, "willamette"))
2091 return IF_WILLAMETTE;
2092 if (!nasm_stricmp(value, "prescott"))
2093 return IF_PRESCOTT;
2094 if (!nasm_stricmp(value, "x64") ||
2095 !nasm_stricmp(value, "x86-64"))
2096 return IF_X86_64;
2097 if (!nasm_stricmp(value, "ia64") ||
2098 !nasm_stricmp(value, "ia-64") ||
2099 !nasm_stricmp(value, "itanium") ||
2100 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2101 return IF_IA64;
2103 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2104 "unknown 'cpu' type");
2106 return IF_PLEVEL; /* the maximum level */
2109 static int get_bits(char *value)
2111 int i;
2113 if ((i = atoi(value)) == 16)
2114 return i; /* set for a 16-bit segment */
2115 else if (i == 32) {
2116 if (cpu < IF_386) {
2117 report_error(ERR_NONFATAL,
2118 "cannot specify 32-bit segment on processor below a 386");
2119 i = 16;
2121 } else if (i == 64) {
2122 if (cpu < IF_X86_64) {
2123 report_error(ERR_NONFATAL,
2124 "cannot specify 64-bit segment on processor below an x86-64");
2125 i = 16;
2127 if (i != maxbits) {
2128 report_error(ERR_NONFATAL,
2129 "%s output format does not support 64-bit code",
2130 ofmt->shortname);
2131 i = 16;
2133 } else {
2134 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2135 "`%s' is not a valid segment size; must be 16, 32 or 64",
2136 value);
2137 i = 16;
2139 return i;
2142 /* end of nasm.c */