CHANGES: document backport of -F implies -g
[nasm.git] / nasm.c
blob188a204e117d68619140f1fa3d3ce46961532c04
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 "float.h"
23 #include "stdscan.h"
24 #include "insns.h"
25 #include "preproc.h"
26 #include "parser.h"
27 #include "eval.h"
28 #include "assemble.h"
29 #include "labels.h"
30 #include "outform.h"
31 #include "listing.h"
33 struct forwrefinfo { /* info held on forward refs. */
34 int lineno;
35 int operand;
38 static int get_bits(char *value);
39 static uint32_t get_cpu(char *cpu_str);
40 static void parse_cmdline(int, char **);
41 static void assemble_file(char *, StrList **);
42 static void register_output_formats(void);
43 static void report_error_gnu(int severity, const char *fmt, ...);
44 static void report_error_vc(int severity, const char *fmt, ...);
45 static void report_error_common(int severity, const char *fmt,
46 va_list args);
47 static bool is_suppressed_warning(int severity);
48 static void usage(void);
49 static efunc report_error;
51 static int using_debug_info, opt_verbose_info;
52 bool tasm_compatible_mode = false;
53 int pass0, passn;
54 int maxbits = 0;
55 int globalrel = 0;
57 time_t official_compile_time;
59 static char inname[FILENAME_MAX];
60 static char outname[FILENAME_MAX];
61 static char listname[FILENAME_MAX];
62 static char errname[FILENAME_MAX];
63 static int globallineno; /* for forward-reference tracking */
64 /* static int pass = 0; */
65 static struct ofmt *ofmt = NULL;
67 static FILE *error_file; /* Where to write error messages */
69 static FILE *ofile = NULL;
70 int optimizing = -1; /* number of optimization passes to take */
71 static int sb, cmd_sb = 16; /* by default */
72 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
73 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
74 bool global_offset_changed; /* referenced in labels.c */
76 static struct location location;
77 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
78 int32_t abs_seg; /* ABSOLUTE segment basis */
79 int32_t abs_offset; /* ABSOLUTE offset */
81 static struct RAA *offsets;
83 static struct SAA *forwrefs; /* keep track of forward references */
84 static const struct forwrefinfo *forwref;
86 static Preproc *preproc;
87 enum op_type {
88 op_normal, /* Preprocess and assemble */
89 op_preprocess, /* Preprocess only */
90 op_depend, /* Generate dependencies */
92 static enum op_type operating_mode;
93 /* Dependency flags */
94 static bool depend_emit_phony = false;
95 static bool depend_missing_ok = false;
96 static const char *depend_target = NULL;
97 static const char *depend_file = NULL;
100 * Which of the suppressible warnings are suppressed. Entry zero
101 * isn't an actual warning, but it used for -w+error/-Werror.
103 static bool suppressed[ERR_WARN_MAX+1] = {
104 true, false, true, false, false, true, false, true, true, false
108 * The option names for the suppressible warnings. As before, entry
109 * zero does nothing.
111 static const char *suppressed_names[ERR_WARN_MAX+1] = {
112 "error", "macro-params", "macro-selfref", "orphan-labels",
113 "number-overflow", "gnu-elf-extensions", "float-overflow",
114 "float-denorm", "float-underflow", "float-toolong"
118 * The explanations for the suppressible warnings. As before, entry
119 * zero does nothing.
121 static const char *suppressed_what[ERR_WARN_MAX+1] = {
122 "treat warnings as errors",
123 "macro calls with wrong parameter count",
124 "cyclic macro references",
125 "labels alone on lines without trailing `:'",
126 "numeric constants does not fit in 64 bits",
127 "using 8- or 16-bit relocation in ELF32, a GNU extension",
128 "floating point overflow",
129 "floating point denormal",
130 "floating point underflow",
131 "too many digits in floating-point number"
135 * This is a null preprocessor which just copies lines from input
136 * to output. It's used when someone explicitly requests that NASM
137 * not preprocess their source file.
140 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
141 static char *no_pp_getline(void);
142 static void no_pp_cleanup(int);
143 static Preproc no_pp = {
144 no_pp_reset,
145 no_pp_getline,
146 no_pp_cleanup
150 * get/set current offset...
152 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
153 raa_read(offsets,location.segment))
154 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
155 (void)(offsets=raa_write(offsets,location.segment,(x))))
157 static int want_usage;
158 static int terminate_after_phase;
159 int user_nolist = 0; /* fbk 9/2/00 */
161 static void nasm_fputs(const char *line, FILE * outfile)
163 if (outfile) {
164 fputs(line, outfile);
165 putc('\n', outfile);
166 } else
167 puts(line);
170 /* Convert a struct tm to a POSIX-style time constant */
171 static int64_t posix_mktime(struct tm *tm)
173 int64_t t;
174 int64_t y = tm->tm_year;
176 /* See IEEE 1003.1:2004, section 4.14 */
178 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
179 t += tm->tm_yday;
180 t *= 24;
181 t += tm->tm_hour;
182 t *= 60;
183 t += tm->tm_min;
184 t *= 60;
185 t += tm->tm_sec;
187 return t;
190 static void define_macros_early(void)
192 char temp[128];
193 struct tm lt, *lt_p, gm, *gm_p;
194 int64_t posix_time;
196 lt_p = localtime(&official_compile_time);
197 if (lt_p) {
198 lt = *lt_p;
200 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
201 pp_pre_define(temp);
202 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
203 pp_pre_define(temp);
204 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
205 pp_pre_define(temp);
206 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
207 pp_pre_define(temp);
210 gm_p = gmtime(&official_compile_time);
211 if (gm_p) {
212 gm = *gm_p;
214 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
215 pp_pre_define(temp);
216 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
217 pp_pre_define(temp);
218 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
219 pp_pre_define(temp);
220 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
221 pp_pre_define(temp);
224 if (gm_p)
225 posix_time = posix_mktime(&gm);
226 else if (lt_p)
227 posix_time = posix_mktime(&lt);
228 else
229 posix_time = 0;
231 if (posix_time) {
232 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
233 pp_pre_define(temp);
237 static void define_macros_late(void)
239 char temp[128];
241 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
242 ofmt->shortname);
243 pp_pre_define(temp);
246 static void emit_dependencies(StrList *list)
248 FILE *deps;
249 int linepos, len;
250 StrList *l, *nl;
252 if (depend_file && strcmp(depend_file, "-")) {
253 deps = fopen(depend_file, "w");
254 if (!deps) {
255 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
256 "unable to write dependency file `%s'", depend_file);
257 return;
259 } else {
260 deps = stdout;
263 linepos = fprintf(deps, "%s:", depend_target);
264 for (l = list; l; l = l->next) {
265 len = strlen(l->str);
266 if (linepos + len > 62) {
267 fprintf(deps, " \\\n ");
268 linepos = 1;
270 fprintf(deps, " %s", l->str);
271 linepos += len+1;
273 fprintf(deps, "\n\n");
275 for (l = list; l; l = nl) {
276 if (depend_emit_phony)
277 fprintf(deps, "%s:\n\n", l->str);
279 nl = l->next;
280 nasm_free(l);
283 if (deps != stdout)
284 fclose(deps);
287 int main(int argc, char **argv)
289 StrList *depend_list = NULL, **depend_ptr;
291 time(&official_compile_time);
293 pass0 = 1;
294 want_usage = terminate_after_phase = false;
295 report_error = report_error_gnu;
297 error_file = stderr;
299 nasm_set_malloc_error(report_error);
300 offsets = raa_init();
301 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
303 preproc = &nasmpp;
304 operating_mode = op_normal;
306 seg_init();
308 register_output_formats();
310 /* Define some macros dependent on the runtime, but not
311 on the command line. */
312 define_macros_early();
314 parse_cmdline(argc, argv);
316 if (terminate_after_phase) {
317 if (want_usage)
318 usage();
319 return 1;
322 /* If debugging info is disabled, suppress any debug calls */
323 if (!using_debug_info)
324 ofmt->current_dfmt = &null_debug_form;
326 if (ofmt->stdmac)
327 pp_extra_stdmac(ofmt->stdmac);
328 parser_global_info(ofmt, &location);
329 eval_global_info(ofmt, lookup_label, &location);
331 /* define some macros dependent of command-line */
332 define_macros_late();
334 depend_ptr = (depend_file || (operating_mode == op_depend))
335 ? &depend_list : NULL;
336 if (!depend_target)
337 depend_target = outname;
339 switch (operating_mode) {
340 case op_depend:
342 char *line;
344 if (depend_missing_ok)
345 pp_include_path(NULL); /* "assume generated" */
347 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
348 depend_ptr);
349 if (outname[0] == '\0')
350 ofmt->filename(inname, outname, report_error);
351 ofile = NULL;
352 while ((line = preproc->getline()))
353 nasm_free(line);
354 preproc->cleanup(0);
356 break;
358 case op_preprocess:
360 char *line;
361 char *file_name = NULL;
362 int32_t prior_linnum = 0;
363 int lineinc = 0;
365 if (*outname) {
366 ofile = fopen(outname, "w");
367 if (!ofile)
368 report_error(ERR_FATAL | ERR_NOFILE,
369 "unable to open output file `%s'",
370 outname);
371 } else
372 ofile = NULL;
374 location.known = false;
376 /* pass = 1; */
377 preproc->reset(inname, 2, report_error, evaluate, &nasmlist,
378 depend_ptr);
380 while ((line = preproc->getline())) {
382 * We generate %line directives if needed for later programs
384 int32_t linnum = prior_linnum += lineinc;
385 int altline = src_get(&linnum, &file_name);
386 if (altline) {
387 if (altline == 1 && lineinc == 1)
388 nasm_fputs("", ofile);
389 else {
390 lineinc = (altline != -1 || lineinc != 1);
391 fprintf(ofile ? ofile : stdout,
392 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
393 file_name);
395 prior_linnum = linnum;
397 nasm_fputs(line, ofile);
398 nasm_free(line);
400 nasm_free(file_name);
401 preproc->cleanup(0);
402 if (ofile)
403 fclose(ofile);
404 if (ofile && terminate_after_phase)
405 remove(outname);
407 break;
409 case op_normal:
412 * We must call ofmt->filename _anyway_, even if the user
413 * has specified their own output file, because some
414 * formats (eg OBJ and COFF) use ofmt->filename to find out
415 * the name of the input file and then put that inside the
416 * file.
418 ofmt->filename(inname, outname, report_error);
420 ofile = fopen(outname, "wb");
421 if (!ofile) {
422 report_error(ERR_FATAL | ERR_NOFILE,
423 "unable to open output file `%s'", outname);
427 * We must call init_labels() before ofmt->init() since
428 * some object formats will want to define labels in their
429 * init routines. (eg OS/2 defines the FLAT group)
431 init_labels();
433 ofmt->init(ofile, report_error, define_label, evaluate);
435 assemble_file(inname, depend_ptr);
437 if (!terminate_after_phase) {
438 ofmt->cleanup(using_debug_info);
439 cleanup_labels();
440 } else {
442 * We had an fclose on the output file here, but we
443 * actually do that in all the object file drivers as well,
444 * so we're leaving out the one here.
445 * fclose (ofile);
447 remove(outname);
448 if (listname[0])
449 remove(listname);
452 break;
455 if (depend_list)
456 emit_dependencies(depend_list);
458 if (want_usage)
459 usage();
461 raa_free(offsets);
462 saa_free(forwrefs);
463 eval_cleanup();
464 stdscan_cleanup();
466 if (terminate_after_phase)
467 return 1;
468 else
469 return 0;
473 * Get a parameter for a command line option.
474 * First arg must be in the form of e.g. -f...
476 static char *get_param(char *p, char *q, bool *advance)
478 *advance = false;
479 if (p[2]) { /* the parameter's in the option */
480 p += 2;
481 while (isspace(*p))
482 p++;
483 return p;
485 if (q && q[0]) {
486 *advance = true;
487 return q;
489 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
490 "option `-%c' requires an argument", p[1]);
491 return NULL;
495 * Copy a filename
497 static void copy_filename(char *dst, const char *src)
499 size_t len = strlen(src);
501 if (len >= (size_t)FILENAME_MAX) {
502 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
503 return;
505 strncpy(dst, src, FILENAME_MAX);
509 * Convert a string to Make-safe form
511 static char *quote_for_make(const char *str)
513 const char *p;
514 char *os, *q;
516 size_t n = 1; /* Terminating zero */
517 size_t nbs = 0;
519 if (!str)
520 return NULL;
522 for (p = str; *p; p++) {
523 switch (*p) {
524 case ' ':
525 case '\t':
526 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
527 n += nbs + 2;
528 nbs = 0;
529 break;
530 case '$':
531 case '#':
532 nbs = 0;
533 n += 2;
534 break;
535 case '\\':
536 nbs++;
537 n++;
538 break;
539 default:
540 nbs = 0;
541 n++;
542 break;
546 /* Convert N backslashes at the end of filename to 2N backslashes */
547 if (nbs)
548 n += nbs;
550 os = q = nasm_malloc(n);
552 nbs = 0;
553 for (p = str; *p; p++) {
554 switch (*p) {
555 case ' ':
556 case '\t':
557 while (nbs--)
558 *q++ = '\\';
559 *q++ = '\\';
560 *q++ = *p;
561 break;
562 case '$':
563 *q++ = *p;
564 *q++ = *p;
565 nbs = 0;
566 break;
567 case '#':
568 *q++ = '\\';
569 *q++ = *p;
570 nbs = 0;
571 break;
572 case '\\':
573 *q++ = *p;
574 nbs++;
575 break;
576 default:
577 *q++ = *p;
578 nbs = 0;
579 break;
582 while (nbs--)
583 *q++ = '\\';
585 *q = '\0';
587 return os;
590 struct textargs {
591 const char *label;
592 int value;
595 #define OPT_PREFIX 0
596 #define OPT_POSTFIX 1
597 struct textargs textopts[] = {
598 {"prefix", OPT_PREFIX},
599 {"postfix", OPT_POSTFIX},
600 {NULL, 0}
603 static bool stopoptions = false;
604 static bool process_arg(char *p, char *q)
606 char *param;
607 int i;
608 bool advance = false;
609 bool suppress;
611 if (!p || !p[0])
612 return false;
614 if (p[0] == '-' && !stopoptions) {
615 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
616 /* These parameters take values */
617 if (!(param = get_param(p, q, &advance)))
618 return advance;
621 switch (p[1]) {
622 case 's':
623 error_file = stdout;
624 break;
626 case 'o': /* output file */
627 copy_filename(outname, param);
628 break;
630 case 'f': /* output format */
631 ofmt = ofmt_find(param);
632 if (!ofmt) {
633 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
634 "unrecognised output format `%s' - "
635 "use -hf for a list", param);
636 } else {
637 ofmt->current_dfmt = ofmt->debug_formats[0];
639 break;
641 case 'O': /* Optimization level */
643 int opt;
645 if (!*param) {
646 /* Naked -O == -Ox */
647 optimizing = INT_MAX >> 1; /* Almost unlimited */
648 } else {
649 while (*param) {
650 switch (*param) {
651 case '0': case '1': case '2': case '3': case '4':
652 case '5': case '6': case '7': case '8': case '9':
653 opt = strtoul(param, &param, 10);
655 /* -O0 -> optimizing == -1, 0.98 behaviour */
656 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
657 if (opt < 2)
658 optimizing = opt - 1;
659 else
660 optimizing = opt;
661 break;
663 case 'v':
664 case '+':
665 param++;
666 opt_verbose_info = true;
667 break;
669 case 'x':
670 param++;
671 optimizing = INT_MAX >> 1; /* Almost unlimited */
672 break;
674 default:
675 report_error(ERR_FATAL,
676 "unknown optimization option -O%c\n",
677 *param);
678 break;
682 break;
685 case 'p': /* pre-include */
686 case 'P':
687 pp_pre_include(param);
688 break;
690 case 'd': /* pre-define */
691 case 'D':
692 pp_pre_define(param);
693 break;
695 case 'u': /* un-define */
696 case 'U':
697 pp_pre_undefine(param);
698 break;
700 case 'i': /* include search path */
701 case 'I':
702 pp_include_path(param);
703 break;
705 case 'l': /* listing file */
706 copy_filename(listname, param);
707 break;
709 case 'Z': /* error messages file */
710 strcpy(errname, param);
711 break;
713 case 'F': /* specify debug format */
714 ofmt->current_dfmt = dfmt_find(ofmt, param);
715 if (!ofmt->current_dfmt) {
716 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
717 "unrecognized debug format `%s' for"
718 " output format `%s'",
719 param, ofmt->shortname);
721 using_debug_info = true;
722 break;
724 case 'X': /* specify error reporting format */
725 if (nasm_stricmp("vc", param) == 0)
726 report_error = report_error_vc;
727 else if (nasm_stricmp("gnu", param) == 0)
728 report_error = report_error_gnu;
729 else
730 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
731 "unrecognized error reporting format `%s'",
732 param);
733 break;
735 case 'g':
736 using_debug_info = true;
737 break;
739 case 'h':
740 printf
741 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
742 "[-l listfile]\n"
743 " [options...] [--] filename\n"
744 " or nasm -v for version info\n\n"
745 " -t assemble in SciTech TASM compatible mode\n"
746 " -g generate debug information in selected format.\n");
747 printf
748 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
749 " -a don't preprocess (assemble only)\n"
750 " -M generate Makefile dependencies on stdout\n"
751 " -MG d:o, missing files assumed generated\n\n"
752 " -Z<file> redirect error messages to file\n"
753 " -s redirect error messages to stdout\n\n"
754 " -F format select a debugging format\n\n"
755 " -I<path> adds a pathname to the include file path\n");
756 printf
757 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
758 " -P<file> pre-includes a file\n"
759 " -D<macro>[=<value>] pre-defines a macro\n"
760 " -U<macro> undefines a macro\n"
761 " -X<format> specifies error reporting format (gnu or vc)\n"
762 " -w+foo enables warning foo (equiv. -Wfoo)\n"
763 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
764 "Warnings:\n");
765 for (i = 0; i <= ERR_WARN_MAX; i++)
766 printf(" %-23s %s (default %s)\n",
767 suppressed_names[i], suppressed_what[i],
768 suppressed[i] ? "off" : "on");
769 printf
770 ("\nresponse files should contain command line parameters"
771 ", one per line.\n");
772 if (p[2] == 'f') {
773 printf("\nvalid output formats for -f are"
774 " (`*' denotes default):\n");
775 ofmt_list(ofmt, stdout);
776 } else {
777 printf("\nFor a list of valid output formats, use -hf.\n");
778 printf("For a list of debug formats, use -f <form> -y.\n");
780 exit(0); /* never need usage message here */
781 break;
783 case 'y':
784 printf("\nvalid debug formats for '%s' output format are"
785 " ('*' denotes default):\n", ofmt->shortname);
786 dfmt_list(ofmt, stdout);
787 exit(0);
788 break;
790 case 't':
791 tasm_compatible_mode = true;
792 break;
794 case 'v':
796 const char *nasm_version_string =
797 "NASM version " NASM_VER " compiled on " __DATE__
798 #ifdef DEBUG
799 " with -DDEBUG"
800 #endif
802 puts(nasm_version_string);
803 exit(0); /* never need usage message here */
805 break;
807 case 'e': /* preprocess only */
808 case 'E':
809 operating_mode = op_preprocess;
810 break;
812 case 'a': /* assemble only - don't preprocess */
813 preproc = &no_pp;
814 break;
816 case 'W':
817 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
818 suppress = true;
819 param += 3;
820 } else {
821 suppress = false;
823 goto set_warning;
825 case 'w':
826 if (param[0] != '+' && param[0] != '-') {
827 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
828 "invalid option to `-w'");
829 break;
831 suppress = (param[0] == '-');
832 param++;
833 goto set_warning;
834 set_warning:
835 for (i = 0; i <= ERR_WARN_MAX; i++)
836 if (!nasm_stricmp(param, suppressed_names[i]))
837 break;
838 if (i <= ERR_WARN_MAX)
839 suppressed[i] = suppress;
840 else if (!nasm_stricmp(param, "all"))
841 for (i = 1; i <= ERR_WARN_MAX; i++)
842 suppressed[i] = suppress;
843 else if (!nasm_stricmp(param, "none"))
844 for (i = 1; i <= ERR_WARN_MAX; i++)
845 suppressed[i] = !suppress;
846 else
847 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
848 "invalid warning `%s'", param);
849 break;
851 case 'M':
852 switch (p[2]) {
853 case 0:
854 operating_mode = op_depend;
855 break;
856 case 'G':
857 operating_mode = op_depend;
858 depend_missing_ok = true;
859 break;
860 case 'P':
861 depend_emit_phony = true;
862 break;
863 case 'D':
864 depend_file = q;
865 advance = true;
866 break;
867 case 'T':
868 depend_target = q;
869 advance = true;
870 break;
871 case 'Q':
872 depend_target = quote_for_make(q);
873 advance = true;
874 break;
875 default:
876 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
877 "unknown dependency option `-M%c'", p[2]);
878 break;
880 if (advance && (!q || !q[0])) {
881 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
882 "option `-M%c' requires a parameter", p[2]);
883 break;
885 break;
887 case '-':
889 int s;
891 if (p[2] == 0) { /* -- => stop processing options */
892 stopoptions = 1;
893 break;
895 for (s = 0; textopts[s].label; s++) {
896 if (!nasm_stricmp(p + 2, textopts[s].label)) {
897 break;
901 switch (s) {
903 case OPT_PREFIX:
904 case OPT_POSTFIX:
906 if (!q) {
907 report_error(ERR_NONFATAL | ERR_NOFILE |
908 ERR_USAGE,
909 "option `--%s' requires an argument",
910 p + 2);
911 break;
912 } else {
913 advance = 1, param = q;
916 if (s == OPT_PREFIX) {
917 strncpy(lprefix, param, PREFIX_MAX - 1);
918 lprefix[PREFIX_MAX - 1] = 0;
919 break;
921 if (s == OPT_POSTFIX) {
922 strncpy(lpostfix, param, POSTFIX_MAX - 1);
923 lpostfix[POSTFIX_MAX - 1] = 0;
924 break;
926 break;
928 default:
930 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
931 "unrecognised option `--%s'", p + 2);
932 break;
935 break;
938 default:
939 if (!ofmt->setinfo(GI_SWITCH, &p))
940 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
941 "unrecognised option `-%c'", p[1]);
942 break;
944 } else {
945 if (*inname) {
946 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
947 "more than one input file specified");
948 } else {
949 copy_filename(inname, p);
953 return advance;
956 #define ARG_BUF_DELTA 128
958 static void process_respfile(FILE * rfile)
960 char *buffer, *p, *q, *prevarg;
961 int bufsize, prevargsize;
963 bufsize = prevargsize = ARG_BUF_DELTA;
964 buffer = nasm_malloc(ARG_BUF_DELTA);
965 prevarg = nasm_malloc(ARG_BUF_DELTA);
966 prevarg[0] = '\0';
968 while (1) { /* Loop to handle all lines in file */
969 p = buffer;
970 while (1) { /* Loop to handle long lines */
971 q = fgets(p, bufsize - (p - buffer), rfile);
972 if (!q)
973 break;
974 p += strlen(p);
975 if (p > buffer && p[-1] == '\n')
976 break;
977 if (p - buffer > bufsize - 10) {
978 int offset;
979 offset = p - buffer;
980 bufsize += ARG_BUF_DELTA;
981 buffer = nasm_realloc(buffer, bufsize);
982 p = buffer + offset;
986 if (!q && p == buffer) {
987 if (prevarg[0])
988 process_arg(prevarg, NULL);
989 nasm_free(buffer);
990 nasm_free(prevarg);
991 return;
995 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
996 * them are present at the end of the line.
998 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1000 while (p > buffer && isspace(p[-1]))
1001 *--p = '\0';
1003 p = buffer;
1004 while (isspace(*p))
1005 p++;
1007 if (process_arg(prevarg, p))
1008 *p = '\0';
1010 if ((int) strlen(p) > prevargsize - 10) {
1011 prevargsize += ARG_BUF_DELTA;
1012 prevarg = nasm_realloc(prevarg, prevargsize);
1014 strncpy(prevarg, p, prevargsize);
1018 /* Function to process args from a string of args, rather than the
1019 * argv array. Used by the environment variable and response file
1020 * processing.
1022 static void process_args(char *args)
1024 char *p, *q, *arg, *prevarg;
1025 char separator = ' ';
1027 p = args;
1028 if (*p && *p != '-')
1029 separator = *p++;
1030 arg = NULL;
1031 while (*p) {
1032 q = p;
1033 while (*p && *p != separator)
1034 p++;
1035 while (*p == separator)
1036 *p++ = '\0';
1037 prevarg = arg;
1038 arg = q;
1039 if (process_arg(prevarg, arg))
1040 arg = NULL;
1042 if (arg)
1043 process_arg(arg, NULL);
1046 static void process_response_file(const char *file)
1048 char str[2048];
1049 FILE *f = fopen(file, "r");
1050 if (!f) {
1051 perror(file);
1052 exit(-1);
1054 while (fgets(str, sizeof str, f)) {
1055 process_args(str);
1057 fclose(f);
1060 static void parse_cmdline(int argc, char **argv)
1062 FILE *rfile;
1063 char *envreal, *envcopy = NULL, *p, *arg;
1065 *inname = *outname = *listname = *errname = '\0';
1068 * First, process the NASMENV environment variable.
1070 envreal = getenv("NASMENV");
1071 arg = NULL;
1072 if (envreal) {
1073 envcopy = nasm_strdup(envreal);
1074 process_args(envcopy);
1075 nasm_free(envcopy);
1079 * Now process the actual command line.
1081 while (--argc) {
1082 bool advance;
1083 argv++;
1084 if (argv[0][0] == '@') {
1085 /* We have a response file, so process this as a set of
1086 * arguments like the environment variable. This allows us
1087 * to have multiple arguments on a single line, which is
1088 * different to the -@resp file processing below for regular
1089 * NASM.
1091 process_response_file(argv[0]+1);
1092 argc--;
1093 argv++;
1095 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1096 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1097 if (p) {
1098 rfile = fopen(p, "r");
1099 if (rfile) {
1100 process_respfile(rfile);
1101 fclose(rfile);
1102 } else
1103 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1104 "unable to open response file `%s'", p);
1106 } else
1107 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1108 argv += advance, argc -= advance;
1111 /* Look for basic command line typos. This definitely doesn't
1112 catch all errors, but it might help cases of fumbled fingers. */
1113 if (!*inname)
1114 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1115 "no input file specified");
1116 else if (!strcmp(inname, errname) ||
1117 !strcmp(inname, outname) ||
1118 !strcmp(inname, listname) ||
1119 (depend_file && !strcmp(inname, depend_file)))
1120 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1121 "file `%s' is both input and output file",
1122 inname);
1124 if (*errname) {
1125 error_file = fopen(errname, "w");
1126 if (!error_file) {
1127 error_file = stderr; /* Revert to default! */
1128 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1129 "cannot open file `%s' for error messages",
1130 errname);
1135 /* List of directives */
1136 enum directives {
1137 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1138 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1140 static const char *directives[] = {
1141 "", "absolute", "bits", "common", "cpu", "debug", "default",
1142 "extern", "float", "global", "list", "section", "segment", "warning"
1144 static enum directives getkw(char **directive, char **value);
1146 static void assemble_file(char *fname, StrList **depend_ptr)
1148 char *directive, *value, *p, *q, *special, *line, debugid[80];
1149 insn output_ins;
1150 int i, validid;
1151 bool rn_error;
1152 int32_t seg;
1153 int64_t offs;
1154 struct tokenval tokval;
1155 expr *e;
1156 int pass_max;
1158 if (cmd_sb == 32 && cmd_cpu < IF_386)
1159 report_error(ERR_FATAL, "command line: "
1160 "32-bit segment size requires a higher cpu");
1162 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
1163 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
1164 for (passn = 1; pass0 <= 2; passn++) {
1165 int pass1, pass2;
1166 ldfunc def_label;
1168 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1169 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1170 /* pass0 0, 0, 0, ..., 1, 2 */
1172 def_label = passn > 1 ? redefine_label : define_label;
1174 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1175 cpu = cmd_cpu;
1176 if (pass0 == 2) {
1177 if (*listname)
1178 nasmlist.init(listname, report_error);
1180 in_abs_seg = false;
1181 global_offset_changed = false; /* set by redefine_label */
1182 location.segment = ofmt->section(NULL, pass2, &sb);
1183 globalbits = sb;
1184 if (passn > 1) {
1185 saa_rewind(forwrefs);
1186 forwref = saa_rstruct(forwrefs);
1187 raa_free(offsets);
1188 offsets = raa_init();
1190 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1191 pass1 == 2 ? depend_ptr : NULL);
1193 globallineno = 0;
1194 if (passn == 1)
1195 location.known = true;
1196 location.offset = offs = GET_CURR_OFFS;
1198 while ((line = preproc->getline())) {
1199 enum directives d;
1200 globallineno++;
1202 /* here we parse our directives; this is not handled by the 'real'
1203 * parser. */
1204 directive = line;
1205 d = getkw(&directive, &value);
1206 if (d) {
1207 int err = 0;
1209 switch (d) {
1210 case D_SEGMENT: /* [SEGMENT n] */
1211 case D_SECTION:
1212 seg = ofmt->section(value, pass2, &sb);
1213 if (seg == NO_SEG) {
1214 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1215 "segment name `%s' not recognized",
1216 value);
1217 } else {
1218 in_abs_seg = false;
1219 location.segment = seg;
1221 break;
1222 case D_EXTERN: /* [EXTERN label:special] */
1223 if (*value == '$')
1224 value++; /* skip initial $ if present */
1225 if (pass0 == 2) {
1226 q = value;
1227 while (*q && *q != ':')
1228 q++;
1229 if (*q == ':') {
1230 *q++ = '\0';
1231 ofmt->symdef(value, 0L, 0L, 3, q);
1233 } else if (passn == 1) {
1234 q = value;
1235 validid = true;
1236 if (!isidstart(*q))
1237 validid = false;
1238 while (*q && *q != ':') {
1239 if (!isidchar(*q))
1240 validid = false;
1241 q++;
1243 if (!validid) {
1244 report_error(ERR_NONFATAL,
1245 "identifier expected after EXTERN");
1246 break;
1248 if (*q == ':') {
1249 *q++ = '\0';
1250 special = q;
1251 } else
1252 special = NULL;
1253 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1254 int temp = pass0;
1255 pass0 = 1; /* fake pass 1 in labels.c */
1256 declare_as_global(value, special,
1257 report_error);
1258 define_label(value, seg_alloc(), 0L, NULL,
1259 false, true, ofmt, report_error);
1260 pass0 = temp;
1262 } /* else pass0 == 1 */
1263 break;
1264 case D_BITS: /* [BITS bits] */
1265 globalbits = sb = get_bits(value);
1266 break;
1267 case D_GLOBAL: /* [GLOBAL symbol:special] */
1268 if (*value == '$')
1269 value++; /* skip initial $ if present */
1270 if (pass0 == 2) { /* pass 2 */
1271 q = value;
1272 while (*q && *q != ':')
1273 q++;
1274 if (*q == ':') {
1275 *q++ = '\0';
1276 ofmt->symdef(value, 0L, 0L, 3, q);
1278 } else if (pass2 == 1) { /* pass == 1 */
1279 q = value;
1280 validid = true;
1281 if (!isidstart(*q))
1282 validid = false;
1283 while (*q && *q != ':') {
1284 if (!isidchar(*q))
1285 validid = false;
1286 q++;
1288 if (!validid) {
1289 report_error(ERR_NONFATAL,
1290 "identifier expected after GLOBAL");
1291 break;
1293 if (*q == ':') {
1294 *q++ = '\0';
1295 special = q;
1296 } else
1297 special = NULL;
1298 declare_as_global(value, special, report_error);
1299 } /* pass == 1 */
1300 break;
1301 case D_COMMON: /* [COMMON symbol size:special] */
1302 if (*value == '$')
1303 value++; /* skip initial $ if present */
1304 if (pass0 == 1) {
1305 p = value;
1306 validid = true;
1307 if (!isidstart(*p))
1308 validid = false;
1309 while (*p && !isspace(*p)) {
1310 if (!isidchar(*p))
1311 validid = false;
1312 p++;
1314 if (!validid) {
1315 report_error(ERR_NONFATAL,
1316 "identifier expected after COMMON");
1317 break;
1319 if (*p) {
1320 int64_t size;
1322 while (*p && isspace(*p))
1323 *p++ = '\0';
1324 q = p;
1325 while (*q && *q != ':')
1326 q++;
1327 if (*q == ':') {
1328 *q++ = '\0';
1329 special = q;
1330 } else
1331 special = NULL;
1332 size = readnum(p, &rn_error);
1333 if (rn_error)
1334 report_error(ERR_NONFATAL,
1335 "invalid size specified"
1336 " in COMMON declaration");
1337 else
1338 define_common(value, seg_alloc(), size,
1339 special, ofmt, report_error);
1340 } else
1341 report_error(ERR_NONFATAL,
1342 "no size specified in"
1343 " COMMON declaration");
1344 } else if (pass0 == 2) { /* pass == 2 */
1345 q = value;
1346 while (*q && *q != ':') {
1347 if (isspace(*q))
1348 *q = '\0';
1349 q++;
1351 if (*q == ':') {
1352 *q++ = '\0';
1353 ofmt->symdef(value, 0L, 0L, 3, q);
1356 break;
1357 case D_ABSOLUTE: /* [ABSOLUTE address] */
1358 stdscan_reset();
1359 stdscan_bufptr = value;
1360 tokval.t_type = TOKEN_INVALID;
1361 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1362 report_error, NULL);
1363 if (e) {
1364 if (!is_reloc(e))
1365 report_error(pass0 ==
1366 1 ? ERR_NONFATAL : ERR_PANIC,
1367 "cannot use non-relocatable expression as "
1368 "ABSOLUTE address");
1369 else {
1370 abs_seg = reloc_seg(e);
1371 abs_offset = reloc_value(e);
1373 } else if (passn == 1)
1374 abs_offset = 0x100; /* don't go near zero in case of / */
1375 else
1376 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1377 "in pass two");
1378 in_abs_seg = true;
1379 location.segment = NO_SEG;
1380 break;
1381 case D_DEBUG: /* [DEBUG] */
1382 p = value;
1383 q = debugid;
1384 validid = true;
1385 if (!isidstart(*p))
1386 validid = false;
1387 while (*p && !isspace(*p)) {
1388 if (!isidchar(*p))
1389 validid = false;
1390 *q++ = *p++;
1392 *q++ = 0;
1393 if (!validid) {
1394 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1395 "identifier expected after DEBUG");
1396 break;
1398 while (*p && isspace(*p))
1399 p++;
1400 if (pass0 == 2)
1401 ofmt->current_dfmt->debug_directive(debugid, p);
1402 break;
1403 case D_WARNING: /* [WARNING {+|-}warn-name] */
1404 if (pass1 == 1) {
1405 while (*value && isspace(*value))
1406 value++;
1408 if (*value == '+' || *value == '-') {
1409 validid = (*value == '-') ? true : false;
1410 value++;
1411 } else
1412 validid = false;
1414 for (i = 1; i <= ERR_WARN_MAX; i++)
1415 if (!nasm_stricmp(value, suppressed_names[i]))
1416 break;
1417 if (i <= ERR_WARN_MAX)
1418 suppressed[i] = validid;
1419 else
1420 report_error(ERR_NONFATAL,
1421 "invalid warning id in WARNING directive");
1423 break;
1424 case D_CPU: /* [CPU] */
1425 cpu = get_cpu(value);
1426 break;
1427 case D_LIST: /* [LIST {+|-}] */
1428 while (*value && isspace(*value))
1429 value++;
1431 if (*value == '+') {
1432 user_nolist = 0;
1433 } else {
1434 if (*value == '-') {
1435 user_nolist = 1;
1436 } else {
1437 err = 1;
1440 break;
1441 case D_DEFAULT: /* [DEFAULT] */
1442 stdscan_reset();
1443 stdscan_bufptr = value;
1444 tokval.t_type = TOKEN_INVALID;
1445 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1446 switch ((int)tokval.t_integer) {
1447 case S_REL:
1448 globalrel = 1;
1449 break;
1450 case S_ABS:
1451 globalrel = 0;
1452 break;
1453 default:
1454 err = 1;
1455 break;
1457 } else {
1458 err = 1;
1460 break;
1461 case D_FLOAT:
1462 if (float_option(value)) {
1463 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1464 "unknown 'float' directive: %s",
1465 value);
1467 break;
1468 default:
1469 if (!ofmt->directive(directive, value, pass2))
1470 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1471 "unrecognised directive [%s]",
1472 directive);
1474 if (err) {
1475 report_error(ERR_NONFATAL,
1476 "invalid parameter to [%s] directive",
1477 directive);
1479 } else { /* it isn't a directive */
1481 parse_line(pass1, line, &output_ins,
1482 report_error, evaluate, def_label);
1484 if (!(optimizing > 0) && pass0 == 2) {
1485 if (forwref != NULL && globallineno == forwref->lineno) {
1486 output_ins.forw_ref = true;
1487 do {
1488 output_ins.oprs[forwref->operand].opflags |=
1489 OPFLAG_FORWARD;
1490 forwref = saa_rstruct(forwrefs);
1491 } while (forwref != NULL
1492 && forwref->lineno == globallineno);
1493 } else
1494 output_ins.forw_ref = false;
1497 if (!(optimizing > 0) && output_ins.forw_ref) {
1498 if (passn == 1) {
1499 for (i = 0; i < output_ins.operands; i++) {
1500 if (output_ins.oprs[i].
1501 opflags & OPFLAG_FORWARD) {
1502 struct forwrefinfo *fwinf =
1503 (struct forwrefinfo *)
1504 saa_wstruct(forwrefs);
1505 fwinf->lineno = globallineno;
1506 fwinf->operand = i;
1509 } else { /* passn > 1 */
1511 * Hack to prevent phase error in the code
1512 * rol ax,x
1513 * x equ 1
1515 * If the second operand is a forward reference,
1516 * the UNITY property of the number 1 in that
1517 * operand is cancelled. Otherwise the above
1518 * sequence will cause a phase error.
1520 * This hack means that the above code will
1521 * generate 286+ code.
1523 * The forward reference will mean that the
1524 * operand will not have the UNITY property on
1525 * the first pass, so the pass behaviours will
1526 * be consistent.
1529 if (output_ins.operands >= 2 &&
1530 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1531 !(IMMEDIATE & ~output_ins.oprs[1].type))
1533 /* Remove special properties bits */
1534 output_ins.oprs[1].type &= ~REG_SMASK;
1541 /* forw_ref */
1542 if (output_ins.opcode == I_EQU) {
1543 if (pass1 == 1) {
1545 * Special `..' EQUs get processed in pass two,
1546 * except `..@' macro-processor EQUs which are done
1547 * in the normal place.
1549 if (!output_ins.label)
1550 report_error(ERR_NONFATAL,
1551 "EQU not preceded by label");
1553 else if (output_ins.label[0] != '.' ||
1554 output_ins.label[1] != '.' ||
1555 output_ins.label[2] == '@') {
1556 if (output_ins.operands == 1 &&
1557 (output_ins.oprs[0].type & IMMEDIATE) &&
1558 output_ins.oprs[0].wrt == NO_SEG) {
1559 int isext =
1560 output_ins.oprs[0].
1561 opflags & OPFLAG_EXTERN;
1562 def_label(output_ins.label,
1563 output_ins.oprs[0].segment,
1564 output_ins.oprs[0].offset, NULL,
1565 false, isext, ofmt,
1566 report_error);
1567 } else if (output_ins.operands == 2
1568 && (output_ins.oprs[0].
1569 type & IMMEDIATE)
1570 && (output_ins.oprs[0].type & COLON)
1571 && output_ins.oprs[0].segment ==
1572 NO_SEG
1573 && output_ins.oprs[0].wrt == NO_SEG
1574 && (output_ins.oprs[1].
1575 type & IMMEDIATE)
1576 && output_ins.oprs[1].segment ==
1577 NO_SEG
1578 && output_ins.oprs[1].wrt ==
1579 NO_SEG) {
1580 def_label(output_ins.label,
1581 output_ins.oprs[0].
1582 offset | SEG_ABS,
1583 output_ins.oprs[1].offset, NULL,
1584 false, false, ofmt,
1585 report_error);
1586 } else
1587 report_error(ERR_NONFATAL,
1588 "bad syntax for EQU");
1590 } else {
1592 * Special `..' EQUs get processed here, except
1593 * `..@' macro processor EQUs which are done above.
1595 if (output_ins.label[0] == '.' &&
1596 output_ins.label[1] == '.' &&
1597 output_ins.label[2] != '@') {
1598 if (output_ins.operands == 1 &&
1599 (output_ins.oprs[0].type & IMMEDIATE)) {
1600 define_label(output_ins.label,
1601 output_ins.oprs[0].segment,
1602 output_ins.oprs[0].offset,
1603 NULL, false, false, ofmt,
1604 report_error);
1605 } else if (output_ins.operands == 2
1606 && (output_ins.oprs[0].
1607 type & IMMEDIATE)
1608 && (output_ins.oprs[0].type & COLON)
1609 && output_ins.oprs[0].segment ==
1610 NO_SEG
1611 && (output_ins.oprs[1].
1612 type & IMMEDIATE)
1613 && output_ins.oprs[1].segment ==
1614 NO_SEG) {
1615 define_label(output_ins.label,
1616 output_ins.oprs[0].
1617 offset | SEG_ABS,
1618 output_ins.oprs[1].offset,
1619 NULL, false, false, ofmt,
1620 report_error);
1621 } else
1622 report_error(ERR_NONFATAL,
1623 "bad syntax for EQU");
1626 } else { /* instruction isn't an EQU */
1628 if (pass1 == 1) {
1630 int64_t l = insn_size(location.segment, offs, sb, cpu,
1631 &output_ins, report_error);
1633 /* if (using_debug_info) && output_ins.opcode != -1) */
1634 if (using_debug_info)
1635 { /* fbk 03/25/01 */
1636 /* this is done here so we can do debug type info */
1637 int32_t typeinfo =
1638 TYS_ELEMENTS(output_ins.operands);
1639 switch (output_ins.opcode) {
1640 case I_RESB:
1641 typeinfo =
1642 TYS_ELEMENTS(output_ins.oprs[0].
1643 offset) | TY_BYTE;
1644 break;
1645 case I_RESW:
1646 typeinfo =
1647 TYS_ELEMENTS(output_ins.oprs[0].
1648 offset) | TY_WORD;
1649 break;
1650 case I_RESD:
1651 typeinfo =
1652 TYS_ELEMENTS(output_ins.oprs[0].
1653 offset) | TY_DWORD;
1654 break;
1655 case I_RESQ:
1656 typeinfo =
1657 TYS_ELEMENTS(output_ins.oprs[0].
1658 offset) | TY_QWORD;
1659 break;
1660 case I_REST:
1661 typeinfo =
1662 TYS_ELEMENTS(output_ins.oprs[0].
1663 offset) | TY_TBYTE;
1664 break;
1665 case I_RESO:
1666 typeinfo =
1667 TYS_ELEMENTS(output_ins.oprs[0].
1668 offset) | TY_OWORD;
1669 break;
1670 case I_RESY:
1671 typeinfo =
1672 TYS_ELEMENTS(output_ins.oprs[0].
1673 offset) | TY_YWORD;
1674 break;
1675 case I_DB:
1676 typeinfo |= TY_BYTE;
1677 break;
1678 case I_DW:
1679 typeinfo |= TY_WORD;
1680 break;
1681 case I_DD:
1682 if (output_ins.eops_float)
1683 typeinfo |= TY_FLOAT;
1684 else
1685 typeinfo |= TY_DWORD;
1686 break;
1687 case I_DQ:
1688 typeinfo |= TY_QWORD;
1689 break;
1690 case I_DT:
1691 typeinfo |= TY_TBYTE;
1692 break;
1693 case I_DO:
1694 typeinfo |= TY_OWORD;
1695 break;
1696 case I_DY:
1697 typeinfo |= TY_YWORD;
1698 break;
1699 default:
1700 typeinfo = TY_LABEL;
1704 ofmt->current_dfmt->debug_typevalue(typeinfo);
1707 if (l != -1) {
1708 offs += l;
1709 SET_CURR_OFFS(offs);
1712 * else l == -1 => invalid instruction, which will be
1713 * flagged as an error on pass 2
1716 } else {
1717 offs += assemble(location.segment, offs, sb, cpu,
1718 &output_ins, ofmt, report_error,
1719 &nasmlist);
1720 SET_CURR_OFFS(offs);
1723 } /* not an EQU */
1724 cleanup_insn(&output_ins);
1726 nasm_free(line);
1727 location.offset = offs = GET_CURR_OFFS;
1728 } /* end while (line = preproc->getline... */
1730 if (pass1 == 2 && global_offset_changed)
1731 report_error(ERR_NONFATAL,
1732 "phase error detected at end of assembly.");
1734 if (pass1 == 1)
1735 preproc->cleanup(1);
1737 if (pass1 == 1 && terminate_after_phase) {
1738 fclose(ofile);
1739 remove(outname);
1740 if (want_usage)
1741 usage();
1742 exit(1);
1744 if (passn >= pass_max - 2 ||
1745 (passn > 1 && !global_offset_changed))
1746 pass0++;
1749 preproc->cleanup(0);
1750 nasmlist.cleanup();
1751 #if 1
1752 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1753 fprintf(stdout,
1754 "info:: assembly required 1+%d+1 passes\n", passn-3);
1755 #endif
1756 } /* exit from assemble_file (...) */
1758 static enum directives getkw(char **directive, char **value)
1760 char *p, *q, *buf;
1762 buf = *directive;
1764 /* allow leading spaces or tabs */
1765 while (*buf == ' ' || *buf == '\t')
1766 buf++;
1768 if (*buf != '[')
1769 return 0;
1771 p = buf;
1773 while (*p && *p != ']')
1774 p++;
1776 if (!*p)
1777 return 0;
1779 q = p++;
1781 while (*p && *p != ';') {
1782 if (!isspace(*p))
1783 return 0;
1784 p++;
1786 q[1] = '\0';
1788 *directive = p = buf + 1;
1789 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1790 buf++;
1791 if (*buf == ']') {
1792 *buf = '\0';
1793 *value = buf;
1794 } else {
1795 *buf++ = '\0';
1796 while (isspace(*buf))
1797 buf++; /* beppu - skip leading whitespace */
1798 *value = buf;
1799 while (*buf != ']')
1800 buf++;
1801 *buf++ = '\0';
1804 return bsii(*directive, directives, elements(directives));
1808 * gnu style error reporting
1809 * This function prints an error message to error_file in the
1810 * style used by GNU. An example would be:
1811 * file.asm:50: error: blah blah blah
1812 * where file.asm is the name of the file, 50 is the line number on
1813 * which the error occurs (or is detected) and "error:" is one of
1814 * the possible optional diagnostics -- it can be "error" or "warning"
1815 * or something else. Finally the line terminates with the actual
1816 * error message.
1818 * @param severity the severity of the warning or error
1819 * @param fmt the printf style format string
1821 static void report_error_gnu(int severity, const char *fmt, ...)
1823 va_list ap;
1825 if (is_suppressed_warning(severity))
1826 return;
1828 if (severity & ERR_NOFILE)
1829 fputs("nasm: ", error_file);
1830 else {
1831 char *currentfile = NULL;
1832 int32_t lineno = 0;
1833 src_get(&lineno, &currentfile);
1834 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1835 nasm_free(currentfile);
1837 va_start(ap, fmt);
1838 report_error_common(severity, fmt, ap);
1839 va_end(ap);
1843 * MS style error reporting
1844 * This function prints an error message to error_file in the
1845 * style used by Visual C and some other Microsoft tools. An example
1846 * would be:
1847 * file.asm(50) : error: blah blah blah
1848 * where file.asm is the name of the file, 50 is the line number on
1849 * which the error occurs (or is detected) and "error:" is one of
1850 * the possible optional diagnostics -- it can be "error" or "warning"
1851 * or something else. Finally the line terminates with the actual
1852 * error message.
1854 * @param severity the severity of the warning or error
1855 * @param fmt the printf style format string
1857 static void report_error_vc(int severity, const char *fmt, ...)
1859 va_list ap;
1861 if (is_suppressed_warning(severity))
1862 return;
1864 if (severity & ERR_NOFILE)
1865 fputs("nasm: ", error_file);
1866 else {
1867 char *currentfile = NULL;
1868 int32_t lineno = 0;
1869 src_get(&lineno, &currentfile);
1870 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1871 nasm_free(currentfile);
1873 va_start(ap, fmt);
1874 report_error_common(severity, fmt, ap);
1875 va_end(ap);
1879 * check for supressed warning
1880 * checks for suppressed warning or pass one only warning and we're
1881 * not in pass 1
1883 * @param severity the severity of the warning or error
1884 * @return true if we should abort error/warning printing
1886 static bool is_suppressed_warning(int severity)
1889 * See if it's a suppressed warning.
1891 return (severity & ERR_MASK) == ERR_WARNING &&
1892 (((severity & ERR_WARN_MASK) != 0 &&
1893 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1894 /* See if it's a pass-one only warning and we're not in pass one. */
1895 ((severity & ERR_PASS1) && pass0 != 1));
1899 * common error reporting
1900 * This is the common back end of the error reporting schemes currently
1901 * implemented. It prints the nature of the warning and then the
1902 * specific error message to error_file and may or may not return. It
1903 * doesn't return if the error severity is a "panic" or "debug" type.
1905 * @param severity the severity of the warning or error
1906 * @param fmt the printf style format string
1908 static void report_error_common(int severity, const char *fmt,
1909 va_list args)
1911 switch (severity & ERR_MASK) {
1912 case ERR_WARNING:
1913 fputs("warning: ", error_file);
1914 break;
1915 case ERR_NONFATAL:
1916 fputs("error: ", error_file);
1917 break;
1918 case ERR_FATAL:
1919 fputs("fatal: ", error_file);
1920 break;
1921 case ERR_PANIC:
1922 fputs("panic: ", error_file);
1923 break;
1924 case ERR_DEBUG:
1925 fputs("debug: ", error_file);
1926 break;
1929 vfprintf(error_file, fmt, args);
1930 putc('\n', error_file);
1932 if (severity & ERR_USAGE)
1933 want_usage = true;
1935 switch (severity & ERR_MASK) {
1936 case ERR_DEBUG:
1937 /* no further action, by definition */
1938 break;
1939 case ERR_WARNING:
1940 if (!suppressed[0]) /* Treat warnings as errors */
1941 terminate_after_phase = true;
1942 break;
1943 case ERR_NONFATAL:
1944 terminate_after_phase = true;
1945 break;
1946 case ERR_FATAL:
1947 if (ofile) {
1948 fclose(ofile);
1949 remove(outname);
1951 if (want_usage)
1952 usage();
1953 exit(1); /* instantly die */
1954 break; /* placate silly compilers */
1955 case ERR_PANIC:
1956 fflush(NULL);
1957 /* abort(); *//* halt, catch fire, and dump core */
1958 exit(3);
1959 break;
1963 static void usage(void)
1965 fputs("type `nasm -h' for help\n", error_file);
1968 static void register_output_formats(void)
1970 ofmt = ofmt_register(report_error);
1973 #define BUF_DELTA 512
1975 static FILE *no_pp_fp;
1976 static efunc no_pp_err;
1977 static ListGen *no_pp_list;
1978 static int32_t no_pp_lineinc;
1980 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1981 ListGen * listgen, StrList **deplist)
1983 src_set_fname(nasm_strdup(file));
1984 src_set_linnum(0);
1985 no_pp_lineinc = 1;
1986 no_pp_err = error;
1987 no_pp_fp = fopen(file, "r");
1988 if (!no_pp_fp)
1989 no_pp_err(ERR_FATAL | ERR_NOFILE,
1990 "unable to open input file `%s'", file);
1991 no_pp_list = listgen;
1992 (void)pass; /* placate compilers */
1993 (void)eval; /* placate compilers */
1995 if (deplist) {
1996 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1997 sl->next = NULL;
1998 strcpy(sl->str, file);
1999 *deplist = sl;
2003 static char *no_pp_getline(void)
2005 char *buffer, *p, *q;
2006 int bufsize;
2008 bufsize = BUF_DELTA;
2009 buffer = nasm_malloc(BUF_DELTA);
2010 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2012 while (1) { /* Loop to handle %line */
2014 p = buffer;
2015 while (1) { /* Loop to handle long lines */
2016 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2017 if (!q)
2018 break;
2019 p += strlen(p);
2020 if (p > buffer && p[-1] == '\n')
2021 break;
2022 if (p - buffer > bufsize - 10) {
2023 int offset;
2024 offset = p - buffer;
2025 bufsize += BUF_DELTA;
2026 buffer = nasm_realloc(buffer, bufsize);
2027 p = buffer + offset;
2031 if (!q && p == buffer) {
2032 nasm_free(buffer);
2033 return NULL;
2037 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2038 * them are present at the end of the line.
2040 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2042 if (!nasm_strnicmp(buffer, "%line", 5)) {
2043 int32_t ln;
2044 int li;
2045 char *nm = nasm_malloc(strlen(buffer));
2046 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2047 nasm_free(src_set_fname(nm));
2048 src_set_linnum(ln);
2049 no_pp_lineinc = li;
2050 continue;
2052 nasm_free(nm);
2054 break;
2057 no_pp_list->line(LIST_READ, buffer);
2059 return buffer;
2062 static void no_pp_cleanup(int pass)
2064 (void)pass; /* placate GCC */
2065 fclose(no_pp_fp);
2068 static uint32_t get_cpu(char *value)
2070 if (!strcmp(value, "8086"))
2071 return IF_8086;
2072 if (!strcmp(value, "186"))
2073 return IF_186;
2074 if (!strcmp(value, "286"))
2075 return IF_286;
2076 if (!strcmp(value, "386"))
2077 return IF_386;
2078 if (!strcmp(value, "486"))
2079 return IF_486;
2080 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2081 return IF_PENT;
2082 if (!strcmp(value, "686") ||
2083 !nasm_stricmp(value, "ppro") ||
2084 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2085 return IF_P6;
2086 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2087 return IF_KATMAI;
2088 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2089 !nasm_stricmp(value, "willamette"))
2090 return IF_WILLAMETTE;
2091 if (!nasm_stricmp(value, "prescott"))
2092 return IF_PRESCOTT;
2093 if (!nasm_stricmp(value, "x64") ||
2094 !nasm_stricmp(value, "x86-64"))
2095 return IF_X86_64;
2096 if (!nasm_stricmp(value, "ia64") ||
2097 !nasm_stricmp(value, "ia-64") ||
2098 !nasm_stricmp(value, "itanium") ||
2099 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2100 return IF_IA64;
2102 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2103 "unknown 'cpu' type");
2105 return IF_PLEVEL; /* the maximum level */
2108 static int get_bits(char *value)
2110 int i;
2112 if ((i = atoi(value)) == 16)
2113 return i; /* set for a 16-bit segment */
2114 else if (i == 32) {
2115 if (cpu < IF_386) {
2116 report_error(ERR_NONFATAL,
2117 "cannot specify 32-bit segment on processor below a 386");
2118 i = 16;
2120 } else if (i == 64) {
2121 if (cpu < IF_X86_64) {
2122 report_error(ERR_NONFATAL,
2123 "cannot specify 64-bit segment on processor below an x86-64");
2124 i = 16;
2126 if (i != maxbits) {
2127 report_error(ERR_NONFATAL,
2128 "%s output format does not support 64-bit code",
2129 ofmt->shortname);
2130 i = 16;
2132 } else {
2133 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2134 "`%s' is not a valid segment size; must be 16, 32 or 64",
2135 value);
2136 i = 16;
2138 return i;
2141 /* end of nasm.c */