Document UTF-8 conversion better, use "byte" instead of "ASCII"
[nasm/nasm.git] / nasm.c
blob1eb5e4f774d0f27afe86816c3cf532e907762159
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 break;
723 case 'X': /* specify error reporting format */
724 if (nasm_stricmp("vc", param) == 0)
725 report_error = report_error_vc;
726 else if (nasm_stricmp("gnu", param) == 0)
727 report_error = report_error_gnu;
728 else
729 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
730 "unrecognized error reporting format `%s'",
731 param);
732 break;
734 case 'g':
735 using_debug_info = true;
736 break;
738 case 'h':
739 printf
740 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
741 "[-l listfile]\n"
742 " [options...] [--] filename\n"
743 " or nasm -v for version info\n\n"
744 " -t assemble in SciTech TASM compatible mode\n"
745 " -g generate debug information in selected format.\n");
746 printf
747 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
748 " -a don't preprocess (assemble only)\n"
749 " -M generate Makefile dependencies on stdout\n"
750 " -MG d:o, missing files assumed generated\n\n"
751 " -Z<file> redirect error messages to file\n"
752 " -s redirect error messages to stdout\n\n"
753 " -F format select a debugging format\n\n"
754 " -I<path> adds a pathname to the include file path\n");
755 printf
756 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
757 " -P<file> pre-includes a file\n"
758 " -D<macro>[=<value>] pre-defines a macro\n"
759 " -U<macro> undefines a macro\n"
760 " -X<format> specifies error reporting format (gnu or vc)\n"
761 " -w+foo enables warning foo (equiv. -Wfoo)\n"
762 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
763 "Warnings:\n");
764 for (i = 0; i <= ERR_WARN_MAX; i++)
765 printf(" %-23s %s (default %s)\n",
766 suppressed_names[i], suppressed_what[i],
767 suppressed[i] ? "off" : "on");
768 printf
769 ("\nresponse files should contain command line parameters"
770 ", one per line.\n");
771 if (p[2] == 'f') {
772 printf("\nvalid output formats for -f are"
773 " (`*' denotes default):\n");
774 ofmt_list(ofmt, stdout);
775 } else {
776 printf("\nFor a list of valid output formats, use -hf.\n");
777 printf("For a list of debug formats, use -f <form> -y.\n");
779 exit(0); /* never need usage message here */
780 break;
782 case 'y':
783 printf("\nvalid debug formats for '%s' output format are"
784 " ('*' denotes default):\n", ofmt->shortname);
785 dfmt_list(ofmt, stdout);
786 exit(0);
787 break;
789 case 't':
790 tasm_compatible_mode = true;
791 break;
793 case 'v':
795 const char *nasm_version_string =
796 "NASM version " NASM_VER " compiled on " __DATE__
797 #ifdef DEBUG
798 " with -DDEBUG"
799 #endif
801 puts(nasm_version_string);
802 exit(0); /* never need usage message here */
804 break;
806 case 'e': /* preprocess only */
807 case 'E':
808 operating_mode = op_preprocess;
809 break;
811 case 'a': /* assemble only - don't preprocess */
812 preproc = &no_pp;
813 break;
815 case 'W':
816 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
817 suppress = true;
818 param += 3;
819 } else {
820 suppress = false;
822 goto set_warning;
824 case 'w':
825 if (param[0] != '+' && param[0] != '-') {
826 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
827 "invalid option to `-w'");
828 break;
830 suppress = (param[0] == '-');
831 param++;
832 goto set_warning;
833 set_warning:
834 for (i = 0; i <= ERR_WARN_MAX; i++)
835 if (!nasm_stricmp(param, suppressed_names[i]))
836 break;
837 if (i <= ERR_WARN_MAX)
838 suppressed[i] = suppress;
839 else if (!nasm_stricmp(param, "all"))
840 for (i = 1; i <= ERR_WARN_MAX; i++)
841 suppressed[i] = suppress;
842 else if (!nasm_stricmp(param, "none"))
843 for (i = 1; i <= ERR_WARN_MAX; i++)
844 suppressed[i] = !suppress;
845 else
846 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
847 "invalid warning `%s'", param);
848 break;
850 case 'M':
851 switch (p[2]) {
852 case 0:
853 operating_mode = op_depend;
854 break;
855 case 'G':
856 operating_mode = op_depend;
857 depend_missing_ok = true;
858 break;
859 case 'P':
860 depend_emit_phony = true;
861 break;
862 case 'D':
863 depend_file = q;
864 advance = true;
865 break;
866 case 'T':
867 depend_target = q;
868 advance = true;
869 break;
870 case 'Q':
871 depend_target = quote_for_make(q);
872 advance = true;
873 break;
874 default:
875 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
876 "unknown dependency option `-M%c'", p[2]);
877 break;
879 if (advance && (!q || !q[0])) {
880 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
881 "option `-M%c' requires a parameter", p[2]);
882 break;
884 break;
886 case '-':
888 int s;
890 if (p[2] == 0) { /* -- => stop processing options */
891 stopoptions = 1;
892 break;
894 for (s = 0; textopts[s].label; s++) {
895 if (!nasm_stricmp(p + 2, textopts[s].label)) {
896 break;
900 switch (s) {
902 case OPT_PREFIX:
903 case OPT_POSTFIX:
905 if (!q) {
906 report_error(ERR_NONFATAL | ERR_NOFILE |
907 ERR_USAGE,
908 "option `--%s' requires an argument",
909 p + 2);
910 break;
911 } else {
912 advance = 1, param = q;
915 if (s == OPT_PREFIX) {
916 strncpy(lprefix, param, PREFIX_MAX - 1);
917 lprefix[PREFIX_MAX - 1] = 0;
918 break;
920 if (s == OPT_POSTFIX) {
921 strncpy(lpostfix, param, POSTFIX_MAX - 1);
922 lpostfix[POSTFIX_MAX - 1] = 0;
923 break;
925 break;
927 default:
929 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
930 "unrecognised option `--%s'", p + 2);
931 break;
934 break;
937 default:
938 if (!ofmt->setinfo(GI_SWITCH, &p))
939 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
940 "unrecognised option `-%c'", p[1]);
941 break;
943 } else {
944 if (*inname) {
945 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
946 "more than one input file specified");
947 } else {
948 copy_filename(inname, p);
952 return advance;
955 #define ARG_BUF_DELTA 128
957 static void process_respfile(FILE * rfile)
959 char *buffer, *p, *q, *prevarg;
960 int bufsize, prevargsize;
962 bufsize = prevargsize = ARG_BUF_DELTA;
963 buffer = nasm_malloc(ARG_BUF_DELTA);
964 prevarg = nasm_malloc(ARG_BUF_DELTA);
965 prevarg[0] = '\0';
967 while (1) { /* Loop to handle all lines in file */
968 p = buffer;
969 while (1) { /* Loop to handle long lines */
970 q = fgets(p, bufsize - (p - buffer), rfile);
971 if (!q)
972 break;
973 p += strlen(p);
974 if (p > buffer && p[-1] == '\n')
975 break;
976 if (p - buffer > bufsize - 10) {
977 int offset;
978 offset = p - buffer;
979 bufsize += ARG_BUF_DELTA;
980 buffer = nasm_realloc(buffer, bufsize);
981 p = buffer + offset;
985 if (!q && p == buffer) {
986 if (prevarg[0])
987 process_arg(prevarg, NULL);
988 nasm_free(buffer);
989 nasm_free(prevarg);
990 return;
994 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
995 * them are present at the end of the line.
997 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
999 while (p > buffer && isspace(p[-1]))
1000 *--p = '\0';
1002 p = buffer;
1003 while (isspace(*p))
1004 p++;
1006 if (process_arg(prevarg, p))
1007 *p = '\0';
1009 if ((int) strlen(p) > prevargsize - 10) {
1010 prevargsize += ARG_BUF_DELTA;
1011 prevarg = nasm_realloc(prevarg, prevargsize);
1013 strncpy(prevarg, p, prevargsize);
1017 /* Function to process args from a string of args, rather than the
1018 * argv array. Used by the environment variable and response file
1019 * processing.
1021 static void process_args(char *args)
1023 char *p, *q, *arg, *prevarg;
1024 char separator = ' ';
1026 p = args;
1027 if (*p && *p != '-')
1028 separator = *p++;
1029 arg = NULL;
1030 while (*p) {
1031 q = p;
1032 while (*p && *p != separator)
1033 p++;
1034 while (*p == separator)
1035 *p++ = '\0';
1036 prevarg = arg;
1037 arg = q;
1038 if (process_arg(prevarg, arg))
1039 arg = NULL;
1041 if (arg)
1042 process_arg(arg, NULL);
1045 static void process_response_file(const char *file)
1047 char str[2048];
1048 FILE *f = fopen(file, "r");
1049 if (!f) {
1050 perror(file);
1051 exit(-1);
1053 while (fgets(str, sizeof str, f)) {
1054 process_args(str);
1056 fclose(f);
1059 static void parse_cmdline(int argc, char **argv)
1061 FILE *rfile;
1062 char *envreal, *envcopy = NULL, *p, *arg;
1064 *inname = *outname = *listname = *errname = '\0';
1067 * First, process the NASMENV environment variable.
1069 envreal = getenv("NASMENV");
1070 arg = NULL;
1071 if (envreal) {
1072 envcopy = nasm_strdup(envreal);
1073 process_args(envcopy);
1074 nasm_free(envcopy);
1078 * Now process the actual command line.
1080 while (--argc) {
1081 bool advance;
1082 argv++;
1083 if (argv[0][0] == '@') {
1084 /* We have a response file, so process this as a set of
1085 * arguments like the environment variable. This allows us
1086 * to have multiple arguments on a single line, which is
1087 * different to the -@resp file processing below for regular
1088 * NASM.
1090 process_response_file(argv[0]+1);
1091 argc--;
1092 argv++;
1094 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1095 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1096 if (p) {
1097 rfile = fopen(p, "r");
1098 if (rfile) {
1099 process_respfile(rfile);
1100 fclose(rfile);
1101 } else
1102 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1103 "unable to open response file `%s'", p);
1105 } else
1106 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1107 argv += advance, argc -= advance;
1110 /* Look for basic command line typos. This definitely doesn't
1111 catch all errors, but it might help cases of fumbled fingers. */
1112 if (!*inname)
1113 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1114 "no input file specified");
1115 else if (!strcmp(inname, errname) ||
1116 !strcmp(inname, outname) ||
1117 !strcmp(inname, listname) ||
1118 (depend_file && !strcmp(inname, depend_file)))
1119 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1120 "file `%s' is both input and output file",
1121 inname);
1123 if (*errname) {
1124 error_file = fopen(errname, "w");
1125 if (!error_file) {
1126 error_file = stderr; /* Revert to default! */
1127 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1128 "cannot open file `%s' for error messages",
1129 errname);
1134 /* List of directives */
1135 enum directives {
1136 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1137 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1139 static const char *directives[] = {
1140 "", "absolute", "bits", "common", "cpu", "debug", "default",
1141 "extern", "float", "global", "list", "section", "segment", "warning"
1143 static enum directives getkw(char **directive, char **value);
1145 static void assemble_file(char *fname, StrList **depend_ptr)
1147 char *directive, *value, *p, *q, *special, *line, debugid[80];
1148 insn output_ins;
1149 int i, validid;
1150 bool rn_error;
1151 int32_t seg;
1152 int64_t offs;
1153 struct tokenval tokval;
1154 expr *e;
1155 int pass_max;
1157 if (cmd_sb == 32 && cmd_cpu < IF_386)
1158 report_error(ERR_FATAL, "command line: "
1159 "32-bit segment size requires a higher cpu");
1161 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
1162 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
1163 for (passn = 1; pass0 <= 2; passn++) {
1164 int pass1, pass2;
1165 ldfunc def_label;
1167 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1168 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1169 /* pass0 0, 0, 0, ..., 1, 2 */
1171 def_label = passn > 1 ? redefine_label : define_label;
1173 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1174 cpu = cmd_cpu;
1175 if (pass0 == 2) {
1176 if (*listname)
1177 nasmlist.init(listname, report_error);
1179 in_abs_seg = false;
1180 global_offset_changed = false; /* set by redefine_label */
1181 location.segment = ofmt->section(NULL, pass2, &sb);
1182 globalbits = sb;
1183 if (passn > 1) {
1184 saa_rewind(forwrefs);
1185 forwref = saa_rstruct(forwrefs);
1186 raa_free(offsets);
1187 offsets = raa_init();
1189 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1190 pass1 == 2 ? depend_ptr : NULL);
1192 globallineno = 0;
1193 if (passn == 1)
1194 location.known = true;
1195 location.offset = offs = GET_CURR_OFFS;
1197 while ((line = preproc->getline())) {
1198 enum directives d;
1199 globallineno++;
1201 /* here we parse our directives; this is not handled by the 'real'
1202 * parser. */
1203 directive = line;
1204 d = getkw(&directive, &value);
1205 if (d) {
1206 int err = 0;
1208 switch (d) {
1209 case D_SEGMENT: /* [SEGMENT n] */
1210 case D_SECTION:
1211 seg = ofmt->section(value, pass2, &sb);
1212 if (seg == NO_SEG) {
1213 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1214 "segment name `%s' not recognized",
1215 value);
1216 } else {
1217 in_abs_seg = false;
1218 location.segment = seg;
1220 break;
1221 case D_EXTERN: /* [EXTERN label:special] */
1222 if (*value == '$')
1223 value++; /* skip initial $ if present */
1224 if (pass0 == 2) {
1225 q = value;
1226 while (*q && *q != ':')
1227 q++;
1228 if (*q == ':') {
1229 *q++ = '\0';
1230 ofmt->symdef(value, 0L, 0L, 3, q);
1232 } else if (passn == 1) {
1233 q = value;
1234 validid = true;
1235 if (!isidstart(*q))
1236 validid = false;
1237 while (*q && *q != ':') {
1238 if (!isidchar(*q))
1239 validid = false;
1240 q++;
1242 if (!validid) {
1243 report_error(ERR_NONFATAL,
1244 "identifier expected after EXTERN");
1245 break;
1247 if (*q == ':') {
1248 *q++ = '\0';
1249 special = q;
1250 } else
1251 special = NULL;
1252 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1253 int temp = pass0;
1254 pass0 = 1; /* fake pass 1 in labels.c */
1255 declare_as_global(value, special,
1256 report_error);
1257 define_label(value, seg_alloc(), 0L, NULL,
1258 false, true, ofmt, report_error);
1259 pass0 = temp;
1261 } /* else pass0 == 1 */
1262 break;
1263 case D_BITS: /* [BITS bits] */
1264 globalbits = sb = get_bits(value);
1265 break;
1266 case D_GLOBAL: /* [GLOBAL symbol:special] */
1267 if (*value == '$')
1268 value++; /* skip initial $ if present */
1269 if (pass0 == 2) { /* pass 2 */
1270 q = value;
1271 while (*q && *q != ':')
1272 q++;
1273 if (*q == ':') {
1274 *q++ = '\0';
1275 ofmt->symdef(value, 0L, 0L, 3, q);
1277 } else if (pass2 == 1) { /* pass == 1 */
1278 q = value;
1279 validid = true;
1280 if (!isidstart(*q))
1281 validid = false;
1282 while (*q && *q != ':') {
1283 if (!isidchar(*q))
1284 validid = false;
1285 q++;
1287 if (!validid) {
1288 report_error(ERR_NONFATAL,
1289 "identifier expected after GLOBAL");
1290 break;
1292 if (*q == ':') {
1293 *q++ = '\0';
1294 special = q;
1295 } else
1296 special = NULL;
1297 declare_as_global(value, special, report_error);
1298 } /* pass == 1 */
1299 break;
1300 case D_COMMON: /* [COMMON symbol size:special] */
1301 if (*value == '$')
1302 value++; /* skip initial $ if present */
1303 if (pass0 == 1) {
1304 p = value;
1305 validid = true;
1306 if (!isidstart(*p))
1307 validid = false;
1308 while (*p && !isspace(*p)) {
1309 if (!isidchar(*p))
1310 validid = false;
1311 p++;
1313 if (!validid) {
1314 report_error(ERR_NONFATAL,
1315 "identifier expected after COMMON");
1316 break;
1318 if (*p) {
1319 int64_t size;
1321 while (*p && isspace(*p))
1322 *p++ = '\0';
1323 q = p;
1324 while (*q && *q != ':')
1325 q++;
1326 if (*q == ':') {
1327 *q++ = '\0';
1328 special = q;
1329 } else
1330 special = NULL;
1331 size = readnum(p, &rn_error);
1332 if (rn_error)
1333 report_error(ERR_NONFATAL,
1334 "invalid size specified"
1335 " in COMMON declaration");
1336 else
1337 define_common(value, seg_alloc(), size,
1338 special, ofmt, report_error);
1339 } else
1340 report_error(ERR_NONFATAL,
1341 "no size specified in"
1342 " COMMON declaration");
1343 } else if (pass0 == 2) { /* pass == 2 */
1344 q = value;
1345 while (*q && *q != ':') {
1346 if (isspace(*q))
1347 *q = '\0';
1348 q++;
1350 if (*q == ':') {
1351 *q++ = '\0';
1352 ofmt->symdef(value, 0L, 0L, 3, q);
1355 break;
1356 case D_ABSOLUTE: /* [ABSOLUTE address] */
1357 stdscan_reset();
1358 stdscan_bufptr = value;
1359 tokval.t_type = TOKEN_INVALID;
1360 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1361 report_error, NULL);
1362 if (e) {
1363 if (!is_reloc(e))
1364 report_error(pass0 ==
1365 1 ? ERR_NONFATAL : ERR_PANIC,
1366 "cannot use non-relocatable expression as "
1367 "ABSOLUTE address");
1368 else {
1369 abs_seg = reloc_seg(e);
1370 abs_offset = reloc_value(e);
1372 } else if (passn == 1)
1373 abs_offset = 0x100; /* don't go near zero in case of / */
1374 else
1375 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1376 "in pass two");
1377 in_abs_seg = true;
1378 location.segment = NO_SEG;
1379 break;
1380 case D_DEBUG: /* [DEBUG] */
1381 p = value;
1382 q = debugid;
1383 validid = true;
1384 if (!isidstart(*p))
1385 validid = false;
1386 while (*p && !isspace(*p)) {
1387 if (!isidchar(*p))
1388 validid = false;
1389 *q++ = *p++;
1391 *q++ = 0;
1392 if (!validid) {
1393 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1394 "identifier expected after DEBUG");
1395 break;
1397 while (*p && isspace(*p))
1398 p++;
1399 if (pass0 == 2)
1400 ofmt->current_dfmt->debug_directive(debugid, p);
1401 break;
1402 case D_WARNING: /* [WARNING {+|-}warn-name] */
1403 if (pass1 == 1) {
1404 while (*value && isspace(*value))
1405 value++;
1407 if (*value == '+' || *value == '-') {
1408 validid = (*value == '-') ? true : false;
1409 value++;
1410 } else
1411 validid = false;
1413 for (i = 1; i <= ERR_WARN_MAX; i++)
1414 if (!nasm_stricmp(value, suppressed_names[i]))
1415 break;
1416 if (i <= ERR_WARN_MAX)
1417 suppressed[i] = validid;
1418 else
1419 report_error(ERR_NONFATAL,
1420 "invalid warning id in WARNING directive");
1422 break;
1423 case D_CPU: /* [CPU] */
1424 cpu = get_cpu(value);
1425 break;
1426 case D_LIST: /* [LIST {+|-}] */
1427 while (*value && isspace(*value))
1428 value++;
1430 if (*value == '+') {
1431 user_nolist = 0;
1432 } else {
1433 if (*value == '-') {
1434 user_nolist = 1;
1435 } else {
1436 err = 1;
1439 break;
1440 case D_DEFAULT: /* [DEFAULT] */
1441 stdscan_reset();
1442 stdscan_bufptr = value;
1443 tokval.t_type = TOKEN_INVALID;
1444 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1445 switch ((int)tokval.t_integer) {
1446 case S_REL:
1447 globalrel = 1;
1448 break;
1449 case S_ABS:
1450 globalrel = 0;
1451 break;
1452 default:
1453 err = 1;
1454 break;
1456 } else {
1457 err = 1;
1459 break;
1460 case D_FLOAT:
1461 if (float_option(value)) {
1462 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1463 "unknown 'float' directive: %s",
1464 value);
1466 break;
1467 default:
1468 if (!ofmt->directive(directive, value, pass2))
1469 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1470 "unrecognised directive [%s]",
1471 directive);
1473 if (err) {
1474 report_error(ERR_NONFATAL,
1475 "invalid parameter to [%s] directive",
1476 directive);
1478 } else { /* it isn't a directive */
1480 parse_line(pass1, line, &output_ins,
1481 report_error, evaluate, def_label);
1483 if (!(optimizing > 0) && pass0 == 2) {
1484 if (forwref != NULL && globallineno == forwref->lineno) {
1485 output_ins.forw_ref = true;
1486 do {
1487 output_ins.oprs[forwref->operand].opflags |=
1488 OPFLAG_FORWARD;
1489 forwref = saa_rstruct(forwrefs);
1490 } while (forwref != NULL
1491 && forwref->lineno == globallineno);
1492 } else
1493 output_ins.forw_ref = false;
1496 if (!(optimizing > 0) && output_ins.forw_ref) {
1497 if (passn == 1) {
1498 for (i = 0; i < output_ins.operands; i++) {
1499 if (output_ins.oprs[i].
1500 opflags & OPFLAG_FORWARD) {
1501 struct forwrefinfo *fwinf =
1502 (struct forwrefinfo *)
1503 saa_wstruct(forwrefs);
1504 fwinf->lineno = globallineno;
1505 fwinf->operand = i;
1508 } else { /* passn > 1 */
1510 * Hack to prevent phase error in the code
1511 * rol ax,x
1512 * x equ 1
1514 * If the second operand is a forward reference,
1515 * the UNITY property of the number 1 in that
1516 * operand is cancelled. Otherwise the above
1517 * sequence will cause a phase error.
1519 * This hack means that the above code will
1520 * generate 286+ code.
1522 * The forward reference will mean that the
1523 * operand will not have the UNITY property on
1524 * the first pass, so the pass behaviours will
1525 * be consistent.
1528 if (output_ins.operands >= 2 &&
1529 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1530 !(IMMEDIATE & ~output_ins.oprs[1].type))
1532 /* Remove special properties bits */
1533 output_ins.oprs[1].type &= ~REG_SMASK;
1540 /* forw_ref */
1541 if (output_ins.opcode == I_EQU) {
1542 if (pass1 == 1) {
1544 * Special `..' EQUs get processed in pass two,
1545 * except `..@' macro-processor EQUs which are done
1546 * in the normal place.
1548 if (!output_ins.label)
1549 report_error(ERR_NONFATAL,
1550 "EQU not preceded by label");
1552 else if (output_ins.label[0] != '.' ||
1553 output_ins.label[1] != '.' ||
1554 output_ins.label[2] == '@') {
1555 if (output_ins.operands == 1 &&
1556 (output_ins.oprs[0].type & IMMEDIATE) &&
1557 output_ins.oprs[0].wrt == NO_SEG) {
1558 int isext =
1559 output_ins.oprs[0].
1560 opflags & OPFLAG_EXTERN;
1561 def_label(output_ins.label,
1562 output_ins.oprs[0].segment,
1563 output_ins.oprs[0].offset, NULL,
1564 false, isext, ofmt,
1565 report_error);
1566 } else if (output_ins.operands == 2
1567 && (output_ins.oprs[0].
1568 type & IMMEDIATE)
1569 && (output_ins.oprs[0].type & COLON)
1570 && output_ins.oprs[0].segment ==
1571 NO_SEG
1572 && output_ins.oprs[0].wrt == NO_SEG
1573 && (output_ins.oprs[1].
1574 type & IMMEDIATE)
1575 && output_ins.oprs[1].segment ==
1576 NO_SEG
1577 && output_ins.oprs[1].wrt ==
1578 NO_SEG) {
1579 def_label(output_ins.label,
1580 output_ins.oprs[0].
1581 offset | SEG_ABS,
1582 output_ins.oprs[1].offset, NULL,
1583 false, false, ofmt,
1584 report_error);
1585 } else
1586 report_error(ERR_NONFATAL,
1587 "bad syntax for EQU");
1589 } else {
1591 * Special `..' EQUs get processed here, except
1592 * `..@' macro processor EQUs which are done above.
1594 if (output_ins.label[0] == '.' &&
1595 output_ins.label[1] == '.' &&
1596 output_ins.label[2] != '@') {
1597 if (output_ins.operands == 1 &&
1598 (output_ins.oprs[0].type & IMMEDIATE)) {
1599 define_label(output_ins.label,
1600 output_ins.oprs[0].segment,
1601 output_ins.oprs[0].offset,
1602 NULL, false, false, ofmt,
1603 report_error);
1604 } else if (output_ins.operands == 2
1605 && (output_ins.oprs[0].
1606 type & IMMEDIATE)
1607 && (output_ins.oprs[0].type & COLON)
1608 && output_ins.oprs[0].segment ==
1609 NO_SEG
1610 && (output_ins.oprs[1].
1611 type & IMMEDIATE)
1612 && output_ins.oprs[1].segment ==
1613 NO_SEG) {
1614 define_label(output_ins.label,
1615 output_ins.oprs[0].
1616 offset | SEG_ABS,
1617 output_ins.oprs[1].offset,
1618 NULL, false, false, ofmt,
1619 report_error);
1620 } else
1621 report_error(ERR_NONFATAL,
1622 "bad syntax for EQU");
1625 } else { /* instruction isn't an EQU */
1627 if (pass1 == 1) {
1629 int64_t l = insn_size(location.segment, offs, sb, cpu,
1630 &output_ins, report_error);
1632 /* if (using_debug_info) && output_ins.opcode != -1) */
1633 if (using_debug_info)
1634 { /* fbk 03/25/01 */
1635 /* this is done here so we can do debug type info */
1636 int32_t typeinfo =
1637 TYS_ELEMENTS(output_ins.operands);
1638 switch (output_ins.opcode) {
1639 case I_RESB:
1640 typeinfo =
1641 TYS_ELEMENTS(output_ins.oprs[0].
1642 offset) | TY_BYTE;
1643 break;
1644 case I_RESW:
1645 typeinfo =
1646 TYS_ELEMENTS(output_ins.oprs[0].
1647 offset) | TY_WORD;
1648 break;
1649 case I_RESD:
1650 typeinfo =
1651 TYS_ELEMENTS(output_ins.oprs[0].
1652 offset) | TY_DWORD;
1653 break;
1654 case I_RESQ:
1655 typeinfo =
1656 TYS_ELEMENTS(output_ins.oprs[0].
1657 offset) | TY_QWORD;
1658 break;
1659 case I_REST:
1660 typeinfo =
1661 TYS_ELEMENTS(output_ins.oprs[0].
1662 offset) | TY_TBYTE;
1663 break;
1664 case I_RESO:
1665 typeinfo =
1666 TYS_ELEMENTS(output_ins.oprs[0].
1667 offset) | TY_OWORD;
1668 break;
1669 case I_RESY:
1670 typeinfo =
1671 TYS_ELEMENTS(output_ins.oprs[0].
1672 offset) | TY_YWORD;
1673 break;
1674 case I_DB:
1675 typeinfo |= TY_BYTE;
1676 break;
1677 case I_DW:
1678 typeinfo |= TY_WORD;
1679 break;
1680 case I_DD:
1681 if (output_ins.eops_float)
1682 typeinfo |= TY_FLOAT;
1683 else
1684 typeinfo |= TY_DWORD;
1685 break;
1686 case I_DQ:
1687 typeinfo |= TY_QWORD;
1688 break;
1689 case I_DT:
1690 typeinfo |= TY_TBYTE;
1691 break;
1692 case I_DO:
1693 typeinfo |= TY_OWORD;
1694 break;
1695 case I_DY:
1696 typeinfo |= TY_YWORD;
1697 break;
1698 default:
1699 typeinfo = TY_LABEL;
1703 ofmt->current_dfmt->debug_typevalue(typeinfo);
1706 if (l != -1) {
1707 offs += l;
1708 SET_CURR_OFFS(offs);
1711 * else l == -1 => invalid instruction, which will be
1712 * flagged as an error on pass 2
1715 } else {
1716 offs += assemble(location.segment, offs, sb, cpu,
1717 &output_ins, ofmt, report_error,
1718 &nasmlist);
1719 SET_CURR_OFFS(offs);
1722 } /* not an EQU */
1723 cleanup_insn(&output_ins);
1725 nasm_free(line);
1726 location.offset = offs = GET_CURR_OFFS;
1727 } /* end while (line = preproc->getline... */
1729 if (pass1 == 2 && global_offset_changed)
1730 report_error(ERR_NONFATAL,
1731 "phase error detected at end of assembly.");
1733 if (pass1 == 1)
1734 preproc->cleanup(1);
1736 if (pass1 == 1 && terminate_after_phase) {
1737 fclose(ofile);
1738 remove(outname);
1739 if (want_usage)
1740 usage();
1741 exit(1);
1743 if (passn >= pass_max - 2 ||
1744 (passn > 1 && !global_offset_changed))
1745 pass0++;
1748 preproc->cleanup(0);
1749 nasmlist.cleanup();
1750 #if 1
1751 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1752 fprintf(stdout,
1753 "info:: assembly required 1+%d+1 passes\n", passn-3);
1754 #endif
1755 } /* exit from assemble_file (...) */
1757 static enum directives getkw(char **directive, char **value)
1759 char *p, *q, *buf;
1761 buf = *directive;
1763 /* allow leading spaces or tabs */
1764 while (*buf == ' ' || *buf == '\t')
1765 buf++;
1767 if (*buf != '[')
1768 return 0;
1770 p = buf;
1772 while (*p && *p != ']')
1773 p++;
1775 if (!*p)
1776 return 0;
1778 q = p++;
1780 while (*p && *p != ';') {
1781 if (!isspace(*p))
1782 return 0;
1783 p++;
1785 q[1] = '\0';
1787 *directive = p = buf + 1;
1788 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1789 buf++;
1790 if (*buf == ']') {
1791 *buf = '\0';
1792 *value = buf;
1793 } else {
1794 *buf++ = '\0';
1795 while (isspace(*buf))
1796 buf++; /* beppu - skip leading whitespace */
1797 *value = buf;
1798 while (*buf != ']')
1799 buf++;
1800 *buf++ = '\0';
1803 return bsii(*directive, directives, elements(directives));
1807 * gnu style error reporting
1808 * This function prints an error message to error_file in the
1809 * style used by GNU. An example would be:
1810 * file.asm:50: error: blah blah blah
1811 * where file.asm is the name of the file, 50 is the line number on
1812 * which the error occurs (or is detected) and "error:" is one of
1813 * the possible optional diagnostics -- it can be "error" or "warning"
1814 * or something else. Finally the line terminates with the actual
1815 * error message.
1817 * @param severity the severity of the warning or error
1818 * @param fmt the printf style format string
1820 static void report_error_gnu(int severity, const char *fmt, ...)
1822 va_list ap;
1824 if (is_suppressed_warning(severity))
1825 return;
1827 if (severity & ERR_NOFILE)
1828 fputs("nasm: ", error_file);
1829 else {
1830 char *currentfile = NULL;
1831 int32_t lineno = 0;
1832 src_get(&lineno, &currentfile);
1833 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1834 nasm_free(currentfile);
1836 va_start(ap, fmt);
1837 report_error_common(severity, fmt, ap);
1838 va_end(ap);
1842 * MS style error reporting
1843 * This function prints an error message to error_file in the
1844 * style used by Visual C and some other Microsoft tools. An example
1845 * would be:
1846 * file.asm(50) : error: blah blah blah
1847 * where file.asm is the name of the file, 50 is the line number on
1848 * which the error occurs (or is detected) and "error:" is one of
1849 * the possible optional diagnostics -- it can be "error" or "warning"
1850 * or something else. Finally the line terminates with the actual
1851 * error message.
1853 * @param severity the severity of the warning or error
1854 * @param fmt the printf style format string
1856 static void report_error_vc(int severity, const char *fmt, ...)
1858 va_list ap;
1860 if (is_suppressed_warning(severity))
1861 return;
1863 if (severity & ERR_NOFILE)
1864 fputs("nasm: ", error_file);
1865 else {
1866 char *currentfile = NULL;
1867 int32_t lineno = 0;
1868 src_get(&lineno, &currentfile);
1869 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1870 nasm_free(currentfile);
1872 va_start(ap, fmt);
1873 report_error_common(severity, fmt, ap);
1874 va_end(ap);
1878 * check for supressed warning
1879 * checks for suppressed warning or pass one only warning and we're
1880 * not in pass 1
1882 * @param severity the severity of the warning or error
1883 * @return true if we should abort error/warning printing
1885 static bool is_suppressed_warning(int severity)
1888 * See if it's a suppressed warning.
1890 return (severity & ERR_MASK) == ERR_WARNING &&
1891 (((severity & ERR_WARN_MASK) != 0 &&
1892 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1893 /* See if it's a pass-one only warning and we're not in pass one. */
1894 ((severity & ERR_PASS1) && pass0 != 1));
1898 * common error reporting
1899 * This is the common back end of the error reporting schemes currently
1900 * implemented. It prints the nature of the warning and then the
1901 * specific error message to error_file and may or may not return. It
1902 * doesn't return if the error severity is a "panic" or "debug" type.
1904 * @param severity the severity of the warning or error
1905 * @param fmt the printf style format string
1907 static void report_error_common(int severity, const char *fmt,
1908 va_list args)
1910 switch (severity & ERR_MASK) {
1911 case ERR_WARNING:
1912 fputs("warning: ", error_file);
1913 break;
1914 case ERR_NONFATAL:
1915 fputs("error: ", error_file);
1916 break;
1917 case ERR_FATAL:
1918 fputs("fatal: ", error_file);
1919 break;
1920 case ERR_PANIC:
1921 fputs("panic: ", error_file);
1922 break;
1923 case ERR_DEBUG:
1924 fputs("debug: ", error_file);
1925 break;
1928 vfprintf(error_file, fmt, args);
1929 putc('\n', error_file);
1931 if (severity & ERR_USAGE)
1932 want_usage = true;
1934 switch (severity & ERR_MASK) {
1935 case ERR_DEBUG:
1936 /* no further action, by definition */
1937 break;
1938 case ERR_WARNING:
1939 if (!suppressed[0]) /* Treat warnings as errors */
1940 terminate_after_phase = true;
1941 break;
1942 case ERR_NONFATAL:
1943 terminate_after_phase = true;
1944 break;
1945 case ERR_FATAL:
1946 if (ofile) {
1947 fclose(ofile);
1948 remove(outname);
1950 if (want_usage)
1951 usage();
1952 exit(1); /* instantly die */
1953 break; /* placate silly compilers */
1954 case ERR_PANIC:
1955 fflush(NULL);
1956 /* abort(); *//* halt, catch fire, and dump core */
1957 exit(3);
1958 break;
1962 static void usage(void)
1964 fputs("type `nasm -h' for help\n", error_file);
1967 static void register_output_formats(void)
1969 ofmt = ofmt_register(report_error);
1972 #define BUF_DELTA 512
1974 static FILE *no_pp_fp;
1975 static efunc no_pp_err;
1976 static ListGen *no_pp_list;
1977 static int32_t no_pp_lineinc;
1979 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1980 ListGen * listgen, StrList **deplist)
1982 src_set_fname(nasm_strdup(file));
1983 src_set_linnum(0);
1984 no_pp_lineinc = 1;
1985 no_pp_err = error;
1986 no_pp_fp = fopen(file, "r");
1987 if (!no_pp_fp)
1988 no_pp_err(ERR_FATAL | ERR_NOFILE,
1989 "unable to open input file `%s'", file);
1990 no_pp_list = listgen;
1991 (void)pass; /* placate compilers */
1992 (void)eval; /* placate compilers */
1994 if (deplist) {
1995 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1996 sl->next = NULL;
1997 strcpy(sl->str, file);
1998 *deplist = sl;
2002 static char *no_pp_getline(void)
2004 char *buffer, *p, *q;
2005 int bufsize;
2007 bufsize = BUF_DELTA;
2008 buffer = nasm_malloc(BUF_DELTA);
2009 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2011 while (1) { /* Loop to handle %line */
2013 p = buffer;
2014 while (1) { /* Loop to handle long lines */
2015 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2016 if (!q)
2017 break;
2018 p += strlen(p);
2019 if (p > buffer && p[-1] == '\n')
2020 break;
2021 if (p - buffer > bufsize - 10) {
2022 int offset;
2023 offset = p - buffer;
2024 bufsize += BUF_DELTA;
2025 buffer = nasm_realloc(buffer, bufsize);
2026 p = buffer + offset;
2030 if (!q && p == buffer) {
2031 nasm_free(buffer);
2032 return NULL;
2036 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2037 * them are present at the end of the line.
2039 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2041 if (!nasm_strnicmp(buffer, "%line", 5)) {
2042 int32_t ln;
2043 int li;
2044 char *nm = nasm_malloc(strlen(buffer));
2045 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2046 nasm_free(src_set_fname(nm));
2047 src_set_linnum(ln);
2048 no_pp_lineinc = li;
2049 continue;
2051 nasm_free(nm);
2053 break;
2056 no_pp_list->line(LIST_READ, buffer);
2058 return buffer;
2061 static void no_pp_cleanup(int pass)
2063 (void)pass; /* placate GCC */
2064 fclose(no_pp_fp);
2067 static uint32_t get_cpu(char *value)
2069 if (!strcmp(value, "8086"))
2070 return IF_8086;
2071 if (!strcmp(value, "186"))
2072 return IF_186;
2073 if (!strcmp(value, "286"))
2074 return IF_286;
2075 if (!strcmp(value, "386"))
2076 return IF_386;
2077 if (!strcmp(value, "486"))
2078 return IF_486;
2079 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2080 return IF_PENT;
2081 if (!strcmp(value, "686") ||
2082 !nasm_stricmp(value, "ppro") ||
2083 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2084 return IF_P6;
2085 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2086 return IF_KATMAI;
2087 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2088 !nasm_stricmp(value, "willamette"))
2089 return IF_WILLAMETTE;
2090 if (!nasm_stricmp(value, "prescott"))
2091 return IF_PRESCOTT;
2092 if (!nasm_stricmp(value, "x64") ||
2093 !nasm_stricmp(value, "x86-64"))
2094 return IF_X86_64;
2095 if (!nasm_stricmp(value, "ia64") ||
2096 !nasm_stricmp(value, "ia-64") ||
2097 !nasm_stricmp(value, "itanium") ||
2098 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2099 return IF_IA64;
2101 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2102 "unknown 'cpu' type");
2104 return IF_PLEVEL; /* the maximum level */
2107 static int get_bits(char *value)
2109 int i;
2111 if ((i = atoi(value)) == 16)
2112 return i; /* set for a 16-bit segment */
2113 else if (i == 32) {
2114 if (cpu < IF_386) {
2115 report_error(ERR_NONFATAL,
2116 "cannot specify 32-bit segment on processor below a 386");
2117 i = 16;
2119 } else if (i == 64) {
2120 if (cpu < IF_X86_64) {
2121 report_error(ERR_NONFATAL,
2122 "cannot specify 64-bit segment on processor below an x86-64");
2123 i = 16;
2125 if (i != maxbits) {
2126 report_error(ERR_NONFATAL,
2127 "%s output format does not support 64-bit code",
2128 ofmt->shortname);
2129 i = 16;
2131 } else {
2132 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2133 "`%s' is not a valid segment size; must be 16, 32 or 64",
2134 value);
2135 i = 16;
2137 return i;
2140 /* end of nasm.c */