Implement -MD, -MF, -MT, -MQ
[nasm/avx512.git] / nasm.c
blob766248e155b09405234e0f7363442239bb81e9f2
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 *, FILE *);
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_missing_ok = false;
95 static const char *depend_target = NULL;
96 static const char *depend_file = NULL;
99 * Which of the suppressible warnings are suppressed. Entry zero
100 * isn't an actual warning, but it used for -w+error/-Werror.
102 static bool suppressed[ERR_WARN_MAX+1] = {
103 true, false, true, false, false, true, false, true, true, false
107 * The option names for the suppressible warnings. As before, entry
108 * zero does nothing.
110 static const char *suppressed_names[ERR_WARN_MAX+1] = {
111 "error", "macro-params", "macro-selfref", "orphan-labels",
112 "number-overflow", "gnu-elf-extensions", "float-overflow",
113 "float-denorm", "float-underflow", "float-toolong"
117 * The explanations for the suppressible warnings. As before, entry
118 * zero does nothing.
120 static const char *suppressed_what[ERR_WARN_MAX+1] = {
121 "treat warnings as errors",
122 "macro calls with wrong parameter count",
123 "cyclic macro references",
124 "labels alone on lines without trailing `:'",
125 "numeric constants does not fit in 64 bits",
126 "using 8- or 16-bit relocation in ELF32, a GNU extension",
127 "floating point overflow",
128 "floating point denormal",
129 "floating point underflow",
130 "too many digits in floating-point number"
134 * This is a null preprocessor which just copies lines from input
135 * to output. It's used when someone explicitly requests that NASM
136 * not preprocess their source file.
139 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, FILE *);
140 static char *no_pp_getline(void);
141 static void no_pp_cleanup(int);
142 static Preproc no_pp = {
143 no_pp_reset,
144 no_pp_getline,
145 no_pp_cleanup
149 * get/set current offset...
151 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
152 raa_read(offsets,location.segment))
153 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
154 (void)(offsets=raa_write(offsets,location.segment,(x))))
156 static int want_usage;
157 static int terminate_after_phase;
158 int user_nolist = 0; /* fbk 9/2/00 */
160 static void nasm_fputs(const char *line, FILE * outfile)
162 if (outfile) {
163 fputs(line, outfile);
164 putc('\n', outfile);
165 } else
166 puts(line);
169 /* Convert a struct tm to a POSIX-style time constant */
170 static int64_t posix_mktime(struct tm *tm)
172 int64_t t;
173 int64_t y = tm->tm_year;
175 /* See IEEE 1003.1:2004, section 4.14 */
177 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
178 t += tm->tm_yday;
179 t *= 24;
180 t += tm->tm_hour;
181 t *= 60;
182 t += tm->tm_min;
183 t *= 60;
184 t += tm->tm_sec;
186 return t;
189 static void define_macros_early(void)
191 char temp[128];
192 struct tm lt, *lt_p, gm, *gm_p;
193 int64_t posix_time;
195 lt_p = localtime(&official_compile_time);
196 if (lt_p) {
197 lt = *lt_p;
199 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
200 pp_pre_define(temp);
201 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
202 pp_pre_define(temp);
203 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
204 pp_pre_define(temp);
205 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
206 pp_pre_define(temp);
209 gm_p = gmtime(&official_compile_time);
210 if (gm_p) {
211 gm = *gm_p;
213 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
214 pp_pre_define(temp);
215 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
216 pp_pre_define(temp);
217 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
218 pp_pre_define(temp);
219 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
220 pp_pre_define(temp);
223 if (gm_p)
224 posix_time = posix_mktime(&gm);
225 else if (lt_p)
226 posix_time = posix_mktime(&lt);
227 else
228 posix_time = 0;
230 if (posix_time) {
231 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
232 pp_pre_define(temp);
236 static void define_macros_late(void)
238 char temp[128];
240 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
241 ofmt->shortname);
242 pp_pre_define(temp);
245 int main(int argc, char **argv)
247 FILE *depends;
249 time(&official_compile_time);
251 pass0 = 1;
252 want_usage = terminate_after_phase = false;
253 report_error = report_error_gnu;
255 error_file = stderr;
257 nasm_set_malloc_error(report_error);
258 offsets = raa_init();
259 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
261 preproc = &nasmpp;
262 operating_mode = op_normal;
264 seg_init();
266 register_output_formats();
268 /* Define some macros dependent on the runtime, but not
269 on the command line. */
270 define_macros_early();
272 parse_cmdline(argc, argv);
274 if (terminate_after_phase) {
275 if (want_usage)
276 usage();
277 return 1;
280 /* If debugging info is disabled, suppress any debug calls */
281 if (!using_debug_info)
282 ofmt->current_dfmt = &null_debug_form;
284 if (ofmt->stdmac)
285 pp_extra_stdmac(ofmt->stdmac);
286 parser_global_info(ofmt, &location);
287 eval_global_info(ofmt, lookup_label, &location);
289 /* define some macros dependent of command-line */
290 define_macros_late();
292 depends = NULL;
293 if (depend_file) {
294 depends = fopen(depend_file, "w");
295 if (!depends) {
296 report_error(ERR_FATAL | ERR_NOFILE,
297 "unable to open dependencies file `%s'",
298 depend_file);
302 if (!depend_target)
303 depend_target = outname;
305 switch (operating_mode) {
306 case op_depend:
308 char *line;
310 if (!depends)
311 depends = stdout;
313 if (depend_missing_ok)
314 pp_include_path(NULL); /* "assume generated" */
316 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
317 depends);
318 if (outname[0] == '\0')
319 ofmt->filename(inname, outname, report_error);
320 ofile = NULL;
321 fprintf(depends, "%s: %s", depend_target, inname);
322 while ((line = preproc->getline()))
323 nasm_free(line);
324 preproc->cleanup(0);
326 break;
328 case op_preprocess:
330 char *line;
331 char *file_name = NULL;
332 int32_t prior_linnum = 0;
333 int lineinc = 0;
335 if (*outname) {
336 ofile = fopen(outname, "w");
337 if (!ofile)
338 report_error(ERR_FATAL | ERR_NOFILE,
339 "unable to open output file `%s'",
340 outname);
341 } else
342 ofile = NULL;
344 location.known = false;
346 /* pass = 1; */
347 preproc->reset(inname, 2, report_error, evaluate, &nasmlist,
348 depends);
349 if (depends)
350 fprintf(depends, "%s: %s", depend_target, inname);
352 while ((line = preproc->getline())) {
354 * We generate %line directives if needed for later programs
356 int32_t linnum = prior_linnum += lineinc;
357 int altline = src_get(&linnum, &file_name);
358 if (altline) {
359 if (altline == 1 && lineinc == 1)
360 nasm_fputs("", ofile);
361 else {
362 lineinc = (altline != -1 || lineinc != 1);
363 fprintf(ofile ? ofile : stdout,
364 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
365 file_name);
367 prior_linnum = linnum;
369 nasm_fputs(line, ofile);
370 nasm_free(line);
372 nasm_free(file_name);
373 preproc->cleanup(0);
374 if (ofile)
375 fclose(ofile);
376 if (ofile && terminate_after_phase)
377 remove(outname);
379 break;
381 case op_normal:
384 * We must call ofmt->filename _anyway_, even if the user
385 * has specified their own output file, because some
386 * formats (eg OBJ and COFF) use ofmt->filename to find out
387 * the name of the input file and then put that inside the
388 * file.
390 ofmt->filename(inname, outname, report_error);
392 ofile = fopen(outname, "wb");
393 if (!ofile) {
394 report_error(ERR_FATAL | ERR_NOFILE,
395 "unable to open output file `%s'", outname);
399 * We must call init_labels() before ofmt->init() since
400 * some object formats will want to define labels in their
401 * init routines. (eg OS/2 defines the FLAT group)
403 init_labels();
405 ofmt->init(ofile, report_error, define_label, evaluate);
407 assemble_file(inname, depends);
409 if (!terminate_after_phase) {
410 ofmt->cleanup(using_debug_info);
411 cleanup_labels();
412 } else {
414 * We had an fclose on the output file here, but we
415 * actually do that in all the object file drivers as well,
416 * so we're leaving out the one here.
417 * fclose (ofile);
419 remove(outname);
420 if (listname[0])
421 remove(listname);
424 break;
427 if (depends) {
428 putc('\n', depends);
429 if (depends != stdout)
430 fclose(depends);
433 if (want_usage)
434 usage();
436 raa_free(offsets);
437 saa_free(forwrefs);
438 eval_cleanup();
439 stdscan_cleanup();
441 if (terminate_after_phase)
442 return 1;
443 else
444 return 0;
448 * Get a parameter for a command line option.
449 * First arg must be in the form of e.g. -f...
451 static char *get_param(char *p, char *q, bool *advance)
453 *advance = false;
454 if (p[2]) { /* the parameter's in the option */
455 p += 2;
456 while (isspace(*p))
457 p++;
458 return p;
460 if (q && q[0]) {
461 *advance = true;
462 return q;
464 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
465 "option `-%c' requires an argument", p[1]);
466 return NULL;
470 * Copy a filename
472 static void copy_filename(char *dst, const char *src)
474 size_t len = strlen(src);
476 if (len >= (size_t)FILENAME_MAX) {
477 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
478 return;
480 strncpy(dst, src, FILENAME_MAX);
484 * Convert a string to Make-safe form
486 static char *quote_for_make(const char *str)
488 const char *p;
489 char *os, *q;
491 size_t n = 1; /* Terminating zero */
492 size_t nbs = 0;
494 if (!str)
495 return NULL;
497 for (p = str; *p; p++) {
498 switch (*p) {
499 case ' ':
500 case '\t':
501 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
502 n += nbs + 2;
503 nbs = 0;
504 break;
505 case '$':
506 case '#':
507 nbs = 0;
508 n += 2;
509 break;
510 case '\\':
511 nbs++;
512 n++;
513 break;
514 default:
515 nbs = 0;
516 n++;
517 break;
521 /* Convert N backslashes at the end of filename to 2N backslashes */
522 if (nbs)
523 n += nbs;
525 os = q = nasm_malloc(n);
527 nbs = 0;
528 for (p = str; *p; p++) {
529 switch (*p) {
530 case ' ':
531 case '\t':
532 while (nbs--)
533 *q++ = '\\';
534 *q++ = '\\';
535 *q++ = *p;
536 break;
537 case '$':
538 *q++ = *p;
539 *q++ = *p;
540 nbs = 0;
541 break;
542 case '#':
543 *q++ = '\\';
544 *q++ = *p;
545 nbs = 0;
546 break;
547 case '\\':
548 *q++ = *p;
549 nbs++;
550 break;
551 default:
552 *q++ = *p;
553 nbs = 0;
554 break;
557 while (nbs--)
558 *q++ = '\\';
560 *q = '\0';
562 return os;
565 struct textargs {
566 const char *label;
567 int value;
570 #define OPT_PREFIX 0
571 #define OPT_POSTFIX 1
572 struct textargs textopts[] = {
573 {"prefix", OPT_PREFIX},
574 {"postfix", OPT_POSTFIX},
575 {NULL, 0}
578 static bool stopoptions = false;
579 static bool process_arg(char *p, char *q)
581 char *param;
582 int i;
583 bool advance = false;
584 bool suppress;
586 if (!p || !p[0])
587 return false;
589 if (p[0] == '-' && !stopoptions) {
590 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
591 /* These parameters take values */
592 if (!(param = get_param(p, q, &advance)))
593 return advance;
596 switch (p[1]) {
597 case 's':
598 error_file = stdout;
599 break;
601 case 'o': /* output file */
602 copy_filename(outname, param);
603 break;
605 case 'f': /* output format */
606 ofmt = ofmt_find(param);
607 if (!ofmt) {
608 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
609 "unrecognised output format `%s' - "
610 "use -hf for a list", param);
611 } else {
612 ofmt->current_dfmt = ofmt->debug_formats[0];
614 break;
616 case 'O': /* Optimization level */
618 int opt;
620 if (!*param) {
621 /* Naked -O == -Ox */
622 optimizing = INT_MAX >> 1; /* Almost unlimited */
623 } else {
624 while (*param) {
625 switch (*param) {
626 case '0': case '1': case '2': case '3': case '4':
627 case '5': case '6': case '7': case '8': case '9':
628 opt = strtoul(param, &param, 10);
630 /* -O0 -> optimizing == -1, 0.98 behaviour */
631 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
632 if (opt < 2)
633 optimizing = opt - 1;
634 else
635 optimizing = opt;
636 break;
638 case 'v':
639 case '+':
640 param++;
641 opt_verbose_info = true;
642 break;
644 case 'x':
645 param++;
646 optimizing = INT_MAX >> 1; /* Almost unlimited */
647 break;
649 default:
650 report_error(ERR_FATAL,
651 "unknown optimization option -O%c\n",
652 *param);
653 break;
657 break;
660 case 'p': /* pre-include */
661 case 'P':
662 pp_pre_include(param);
663 break;
665 case 'd': /* pre-define */
666 case 'D':
667 pp_pre_define(param);
668 break;
670 case 'u': /* un-define */
671 case 'U':
672 pp_pre_undefine(param);
673 break;
675 case 'i': /* include search path */
676 case 'I':
677 pp_include_path(param);
678 break;
680 case 'l': /* listing file */
681 copy_filename(listname, param);
682 break;
684 case 'Z': /* error messages file */
685 strcpy(errname, param);
686 break;
688 case 'F': /* specify debug format */
689 ofmt->current_dfmt = dfmt_find(ofmt, param);
690 if (!ofmt->current_dfmt) {
691 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
692 "unrecognized debug format `%s' for"
693 " output format `%s'",
694 param, ofmt->shortname);
696 break;
698 case 'X': /* specify error reporting format */
699 if (nasm_stricmp("vc", param) == 0)
700 report_error = report_error_vc;
701 else if (nasm_stricmp("gnu", param) == 0)
702 report_error = report_error_gnu;
703 else
704 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
705 "unrecognized error reporting format `%s'",
706 param);
707 break;
709 case 'g':
710 using_debug_info = true;
711 break;
713 case 'h':
714 printf
715 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
716 "[-l listfile]\n"
717 " [options...] [--] filename\n"
718 " or nasm -v for version info\n\n"
719 " -t assemble in SciTech TASM compatible mode\n"
720 " -g generate debug information in selected format.\n");
721 printf
722 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
723 " -a don't preprocess (assemble only)\n"
724 " -M generate Makefile dependencies on stdout\n"
725 " -MG d:o, missing files assumed generated\n\n"
726 " -Z<file> redirect error messages to file\n"
727 " -s redirect error messages to stdout\n\n"
728 " -F format select a debugging format\n\n"
729 " -I<path> adds a pathname to the include file path\n");
730 printf
731 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
732 " -P<file> pre-includes a file\n"
733 " -D<macro>[=<value>] pre-defines a macro\n"
734 " -U<macro> undefines a macro\n"
735 " -X<format> specifies error reporting format (gnu or vc)\n"
736 " -w+foo enables warning foo (equiv. -Wfoo)\n"
737 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
738 "Warnings:\n");
739 for (i = 0; i <= ERR_WARN_MAX; i++)
740 printf(" %-23s %s (default %s)\n",
741 suppressed_names[i], suppressed_what[i],
742 suppressed[i] ? "off" : "on");
743 printf
744 ("\nresponse files should contain command line parameters"
745 ", one per line.\n");
746 if (p[2] == 'f') {
747 printf("\nvalid output formats for -f are"
748 " (`*' denotes default):\n");
749 ofmt_list(ofmt, stdout);
750 } else {
751 printf("\nFor a list of valid output formats, use -hf.\n");
752 printf("For a list of debug formats, use -f <form> -y.\n");
754 exit(0); /* never need usage message here */
755 break;
757 case 'y':
758 printf("\nvalid debug formats for '%s' output format are"
759 " ('*' denotes default):\n", ofmt->shortname);
760 dfmt_list(ofmt, stdout);
761 exit(0);
762 break;
764 case 't':
765 tasm_compatible_mode = true;
766 break;
768 case 'v':
770 const char *nasm_version_string =
771 "NASM version " NASM_VER " compiled on " __DATE__
772 #ifdef DEBUG
773 " with -DDEBUG"
774 #endif
776 puts(nasm_version_string);
777 exit(0); /* never need usage message here */
779 break;
781 case 'e': /* preprocess only */
782 case 'E':
783 operating_mode = op_preprocess;
784 break;
786 case 'a': /* assemble only - don't preprocess */
787 preproc = &no_pp;
788 break;
790 case 'W':
791 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
792 suppress = true;
793 param += 3;
794 } else {
795 suppress = false;
797 goto set_warning;
799 case 'w':
800 if (param[0] != '+' && param[0] != '-') {
801 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
802 "invalid option to `-w'");
803 break;
805 suppress = (param[0] == '-');
806 param++;
807 goto set_warning;
808 set_warning:
809 for (i = 0; i <= ERR_WARN_MAX; i++)
810 if (!nasm_stricmp(param, suppressed_names[i]))
811 break;
812 if (i <= ERR_WARN_MAX)
813 suppressed[i] = suppress;
814 else if (!nasm_stricmp(param, "all"))
815 for (i = 1; i <= ERR_WARN_MAX; i++)
816 suppressed[i] = suppress;
817 else if (!nasm_stricmp(param, "none"))
818 for (i = 1; i <= ERR_WARN_MAX; i++)
819 suppressed[i] = !suppress;
820 else
821 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
822 "invalid warning `%s'", param);
823 break;
825 case 'M':
826 switch (p[2]) {
827 case 0:
828 case 'M':
829 operating_mode = op_depend;
830 break;
831 case 'G':
832 operating_mode = op_depend;
833 depend_missing_ok = true;
834 break;
835 case 'D':
836 depend_file = q;
837 advance = true;
838 break;
839 case 'T':
840 depend_target = q;
841 advance = true;
842 break;
843 case 'Q':
844 depend_target = quote_for_make(q);
845 advance = true;
846 break;
847 default:
848 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
849 "unknown dependency option `-M%c'", p[2]);
850 break;
852 if (advance && (!q || !q[0])) {
853 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
854 "option `-M%c' requires a parameter", p[2]);
855 break;
857 break;
859 case '-':
861 int s;
863 if (p[2] == 0) { /* -- => stop processing options */
864 stopoptions = 1;
865 break;
867 for (s = 0; textopts[s].label; s++) {
868 if (!nasm_stricmp(p + 2, textopts[s].label)) {
869 break;
873 switch (s) {
875 case OPT_PREFIX:
876 case OPT_POSTFIX:
878 if (!q) {
879 report_error(ERR_NONFATAL | ERR_NOFILE |
880 ERR_USAGE,
881 "option `--%s' requires an argument",
882 p + 2);
883 break;
884 } else {
885 advance = 1, param = q;
888 if (s == OPT_PREFIX) {
889 strncpy(lprefix, param, PREFIX_MAX - 1);
890 lprefix[PREFIX_MAX - 1] = 0;
891 break;
893 if (s == OPT_POSTFIX) {
894 strncpy(lpostfix, param, POSTFIX_MAX - 1);
895 lpostfix[POSTFIX_MAX - 1] = 0;
896 break;
898 break;
900 default:
902 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
903 "unrecognised option `--%s'", p + 2);
904 break;
907 break;
910 default:
911 if (!ofmt->setinfo(GI_SWITCH, &p))
912 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
913 "unrecognised option `-%c'", p[1]);
914 break;
916 } else {
917 if (*inname) {
918 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
919 "more than one input file specified");
920 } else {
921 copy_filename(inname, p);
925 return advance;
928 #define ARG_BUF_DELTA 128
930 static void process_respfile(FILE * rfile)
932 char *buffer, *p, *q, *prevarg;
933 int bufsize, prevargsize;
935 bufsize = prevargsize = ARG_BUF_DELTA;
936 buffer = nasm_malloc(ARG_BUF_DELTA);
937 prevarg = nasm_malloc(ARG_BUF_DELTA);
938 prevarg[0] = '\0';
940 while (1) { /* Loop to handle all lines in file */
941 p = buffer;
942 while (1) { /* Loop to handle long lines */
943 q = fgets(p, bufsize - (p - buffer), rfile);
944 if (!q)
945 break;
946 p += strlen(p);
947 if (p > buffer && p[-1] == '\n')
948 break;
949 if (p - buffer > bufsize - 10) {
950 int offset;
951 offset = p - buffer;
952 bufsize += ARG_BUF_DELTA;
953 buffer = nasm_realloc(buffer, bufsize);
954 p = buffer + offset;
958 if (!q && p == buffer) {
959 if (prevarg[0])
960 process_arg(prevarg, NULL);
961 nasm_free(buffer);
962 nasm_free(prevarg);
963 return;
967 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
968 * them are present at the end of the line.
970 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
972 while (p > buffer && isspace(p[-1]))
973 *--p = '\0';
975 p = buffer;
976 while (isspace(*p))
977 p++;
979 if (process_arg(prevarg, p))
980 *p = '\0';
982 if ((int) strlen(p) > prevargsize - 10) {
983 prevargsize += ARG_BUF_DELTA;
984 prevarg = nasm_realloc(prevarg, prevargsize);
986 strncpy(prevarg, p, prevargsize);
990 /* Function to process args from a string of args, rather than the
991 * argv array. Used by the environment variable and response file
992 * processing.
994 static void process_args(char *args)
996 char *p, *q, *arg, *prevarg;
997 char separator = ' ';
999 p = args;
1000 if (*p && *p != '-')
1001 separator = *p++;
1002 arg = NULL;
1003 while (*p) {
1004 q = p;
1005 while (*p && *p != separator)
1006 p++;
1007 while (*p == separator)
1008 *p++ = '\0';
1009 prevarg = arg;
1010 arg = q;
1011 if (process_arg(prevarg, arg))
1012 arg = NULL;
1014 if (arg)
1015 process_arg(arg, NULL);
1018 static void process_response_file(const char *file)
1020 char str[2048];
1021 FILE *f = fopen(file, "r");
1022 if (!f) {
1023 perror(file);
1024 exit(-1);
1026 while (fgets(str, sizeof str, f)) {
1027 process_args(str);
1029 fclose(f);
1032 static void parse_cmdline(int argc, char **argv)
1034 FILE *rfile;
1035 char *envreal, *envcopy = NULL, *p, *arg;
1037 *inname = *outname = *listname = *errname = '\0';
1040 * First, process the NASMENV environment variable.
1042 envreal = getenv("NASMENV");
1043 arg = NULL;
1044 if (envreal) {
1045 envcopy = nasm_strdup(envreal);
1046 process_args(envcopy);
1047 nasm_free(envcopy);
1051 * Now process the actual command line.
1053 while (--argc) {
1054 bool advance;
1055 argv++;
1056 if (argv[0][0] == '@') {
1057 /* We have a response file, so process this as a set of
1058 * arguments like the environment variable. This allows us
1059 * to have multiple arguments on a single line, which is
1060 * different to the -@resp file processing below for regular
1061 * NASM.
1063 process_response_file(argv[0]+1);
1064 argc--;
1065 argv++;
1067 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1068 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1069 if (p) {
1070 rfile = fopen(p, "r");
1071 if (rfile) {
1072 process_respfile(rfile);
1073 fclose(rfile);
1074 } else
1075 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1076 "unable to open response file `%s'", p);
1078 } else
1079 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1080 argv += advance, argc -= advance;
1083 /* Look for basic command line typos. This definitely doesn't
1084 catch all errors, but it might help cases of fumbled fingers. */
1085 if (!*inname)
1086 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1087 "no input file specified");
1088 else if (!strcmp(inname, errname) || !strcmp(inname, outname) ||
1089 !strcmp(inname, listname))
1090 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1091 "file `%s' is both input and output file",
1092 inname);
1094 if (*errname) {
1095 error_file = fopen(errname, "w");
1096 if (!error_file) {
1097 error_file = stderr; /* Revert to default! */
1098 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1099 "cannot open file `%s' for error messages",
1100 errname);
1105 /* List of directives */
1106 enum directives {
1107 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1108 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1110 static const char *directives[] = {
1111 "", "absolute", "bits", "common", "cpu", "debug", "default",
1112 "extern", "float", "global", "list", "section", "segment", "warning"
1114 static enum directives getkw(char **directive, char **value);
1116 static void assemble_file(char *fname, FILE *depends)
1118 char *directive, *value, *p, *q, *special, *line, debugid[80];
1119 insn output_ins;
1120 int i, validid;
1121 bool rn_error;
1122 int32_t seg;
1123 int64_t offs;
1124 struct tokenval tokval;
1125 expr *e;
1126 int pass_max;
1128 if (cmd_sb == 32 && cmd_cpu < IF_386)
1129 report_error(ERR_FATAL, "command line: "
1130 "32-bit segment size requires a higher cpu");
1132 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
1133 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
1134 for (passn = 1; pass0 <= 2; passn++) {
1135 int pass1, pass2;
1136 ldfunc def_label;
1138 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1139 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1140 /* pass0 0, 0, 0, ..., 1, 2 */
1142 def_label = passn > 1 ? redefine_label : define_label;
1144 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1145 cpu = cmd_cpu;
1146 if (pass0 == 2) {
1147 if (*listname)
1148 nasmlist.init(listname, report_error);
1150 in_abs_seg = false;
1151 global_offset_changed = false; /* set by redefine_label */
1152 location.segment = ofmt->section(NULL, pass2, &sb);
1153 globalbits = sb;
1154 if (passn > 1) {
1155 saa_rewind(forwrefs);
1156 forwref = saa_rstruct(forwrefs);
1157 raa_free(offsets);
1158 offsets = raa_init();
1160 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1161 pass1 == 2 ? depends : NULL);
1162 if (pass1 == 2 && depends)
1163 fprintf(depends, "%s: %s", depend_target, inname);
1165 globallineno = 0;
1166 if (passn == 1)
1167 location.known = true;
1168 location.offset = offs = GET_CURR_OFFS;
1170 while ((line = preproc->getline())) {
1171 enum directives d;
1172 globallineno++;
1174 /* here we parse our directives; this is not handled by the 'real'
1175 * parser. */
1176 directive = line;
1177 d = getkw(&directive, &value);
1178 if (d) {
1179 int err = 0;
1181 switch (d) {
1182 case D_SEGMENT: /* [SEGMENT n] */
1183 case D_SECTION:
1184 seg = ofmt->section(value, pass2, &sb);
1185 if (seg == NO_SEG) {
1186 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1187 "segment name `%s' not recognized",
1188 value);
1189 } else {
1190 in_abs_seg = false;
1191 location.segment = seg;
1193 break;
1194 case D_EXTERN: /* [EXTERN label:special] */
1195 if (*value == '$')
1196 value++; /* skip initial $ if present */
1197 if (pass0 == 2) {
1198 q = value;
1199 while (*q && *q != ':')
1200 q++;
1201 if (*q == ':') {
1202 *q++ = '\0';
1203 ofmt->symdef(value, 0L, 0L, 3, q);
1205 } else if (passn == 1) {
1206 q = value;
1207 validid = true;
1208 if (!isidstart(*q))
1209 validid = false;
1210 while (*q && *q != ':') {
1211 if (!isidchar(*q))
1212 validid = false;
1213 q++;
1215 if (!validid) {
1216 report_error(ERR_NONFATAL,
1217 "identifier expected after EXTERN");
1218 break;
1220 if (*q == ':') {
1221 *q++ = '\0';
1222 special = q;
1223 } else
1224 special = NULL;
1225 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1226 int temp = pass0;
1227 pass0 = 1; /* fake pass 1 in labels.c */
1228 declare_as_global(value, special,
1229 report_error);
1230 define_label(value, seg_alloc(), 0L, NULL,
1231 false, true, ofmt, report_error);
1232 pass0 = temp;
1234 } /* else pass0 == 1 */
1235 break;
1236 case D_BITS: /* [BITS bits] */
1237 globalbits = sb = get_bits(value);
1238 break;
1239 case D_GLOBAL: /* [GLOBAL symbol:special] */
1240 if (*value == '$')
1241 value++; /* skip initial $ if present */
1242 if (pass0 == 2) { /* pass 2 */
1243 q = value;
1244 while (*q && *q != ':')
1245 q++;
1246 if (*q == ':') {
1247 *q++ = '\0';
1248 ofmt->symdef(value, 0L, 0L, 3, q);
1250 } else if (pass2 == 1) { /* pass == 1 */
1251 q = value;
1252 validid = true;
1253 if (!isidstart(*q))
1254 validid = false;
1255 while (*q && *q != ':') {
1256 if (!isidchar(*q))
1257 validid = false;
1258 q++;
1260 if (!validid) {
1261 report_error(ERR_NONFATAL,
1262 "identifier expected after GLOBAL");
1263 break;
1265 if (*q == ':') {
1266 *q++ = '\0';
1267 special = q;
1268 } else
1269 special = NULL;
1270 declare_as_global(value, special, report_error);
1271 } /* pass == 1 */
1272 break;
1273 case D_COMMON: /* [COMMON symbol size:special] */
1274 if (*value == '$')
1275 value++; /* skip initial $ if present */
1276 if (pass0 == 1) {
1277 p = value;
1278 validid = true;
1279 if (!isidstart(*p))
1280 validid = false;
1281 while (*p && !isspace(*p)) {
1282 if (!isidchar(*p))
1283 validid = false;
1284 p++;
1286 if (!validid) {
1287 report_error(ERR_NONFATAL,
1288 "identifier expected after COMMON");
1289 break;
1291 if (*p) {
1292 int64_t size;
1294 while (*p && isspace(*p))
1295 *p++ = '\0';
1296 q = p;
1297 while (*q && *q != ':')
1298 q++;
1299 if (*q == ':') {
1300 *q++ = '\0';
1301 special = q;
1302 } else
1303 special = NULL;
1304 size = readnum(p, &rn_error);
1305 if (rn_error)
1306 report_error(ERR_NONFATAL,
1307 "invalid size specified"
1308 " in COMMON declaration");
1309 else
1310 define_common(value, seg_alloc(), size,
1311 special, ofmt, report_error);
1312 } else
1313 report_error(ERR_NONFATAL,
1314 "no size specified in"
1315 " COMMON declaration");
1316 } else if (pass0 == 2) { /* pass == 2 */
1317 q = value;
1318 while (*q && *q != ':') {
1319 if (isspace(*q))
1320 *q = '\0';
1321 q++;
1323 if (*q == ':') {
1324 *q++ = '\0';
1325 ofmt->symdef(value, 0L, 0L, 3, q);
1328 break;
1329 case D_ABSOLUTE: /* [ABSOLUTE address] */
1330 stdscan_reset();
1331 stdscan_bufptr = value;
1332 tokval.t_type = TOKEN_INVALID;
1333 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1334 report_error, NULL);
1335 if (e) {
1336 if (!is_reloc(e))
1337 report_error(pass0 ==
1338 1 ? ERR_NONFATAL : ERR_PANIC,
1339 "cannot use non-relocatable expression as "
1340 "ABSOLUTE address");
1341 else {
1342 abs_seg = reloc_seg(e);
1343 abs_offset = reloc_value(e);
1345 } else if (passn == 1)
1346 abs_offset = 0x100; /* don't go near zero in case of / */
1347 else
1348 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1349 "in pass two");
1350 in_abs_seg = true;
1351 location.segment = NO_SEG;
1352 break;
1353 case D_DEBUG: /* [DEBUG] */
1354 p = value;
1355 q = debugid;
1356 validid = true;
1357 if (!isidstart(*p))
1358 validid = false;
1359 while (*p && !isspace(*p)) {
1360 if (!isidchar(*p))
1361 validid = false;
1362 *q++ = *p++;
1364 *q++ = 0;
1365 if (!validid) {
1366 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1367 "identifier expected after DEBUG");
1368 break;
1370 while (*p && isspace(*p))
1371 p++;
1372 if (pass0 == 2)
1373 ofmt->current_dfmt->debug_directive(debugid, p);
1374 break;
1375 case D_WARNING: /* [WARNING {+|-}warn-name] */
1376 if (pass1 == 1) {
1377 while (*value && isspace(*value))
1378 value++;
1380 if (*value == '+' || *value == '-') {
1381 validid = (*value == '-') ? true : false;
1382 value++;
1383 } else
1384 validid = false;
1386 for (i = 1; i <= ERR_WARN_MAX; i++)
1387 if (!nasm_stricmp(value, suppressed_names[i]))
1388 break;
1389 if (i <= ERR_WARN_MAX)
1390 suppressed[i] = validid;
1391 else
1392 report_error(ERR_NONFATAL,
1393 "invalid warning id in WARNING directive");
1395 break;
1396 case D_CPU: /* [CPU] */
1397 cpu = get_cpu(value);
1398 break;
1399 case D_LIST: /* [LIST {+|-}] */
1400 while (*value && isspace(*value))
1401 value++;
1403 if (*value == '+') {
1404 user_nolist = 0;
1405 } else {
1406 if (*value == '-') {
1407 user_nolist = 1;
1408 } else {
1409 err = 1;
1412 break;
1413 case D_DEFAULT: /* [DEFAULT] */
1414 stdscan_reset();
1415 stdscan_bufptr = value;
1416 tokval.t_type = TOKEN_INVALID;
1417 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1418 switch ((int)tokval.t_integer) {
1419 case S_REL:
1420 globalrel = 1;
1421 break;
1422 case S_ABS:
1423 globalrel = 0;
1424 break;
1425 default:
1426 err = 1;
1427 break;
1429 } else {
1430 err = 1;
1432 break;
1433 case D_FLOAT:
1434 if (float_option(value)) {
1435 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1436 "unknown 'float' directive: %s",
1437 value);
1439 break;
1440 default:
1441 if (!ofmt->directive(directive, value, pass2))
1442 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1443 "unrecognised directive [%s]",
1444 directive);
1446 if (err) {
1447 report_error(ERR_NONFATAL,
1448 "invalid parameter to [%s] directive",
1449 directive);
1451 } else { /* it isn't a directive */
1453 parse_line(pass1, line, &output_ins,
1454 report_error, evaluate, def_label);
1456 if (!(optimizing > 0) && pass0 == 2) {
1457 if (forwref != NULL && globallineno == forwref->lineno) {
1458 output_ins.forw_ref = true;
1459 do {
1460 output_ins.oprs[forwref->operand].opflags |=
1461 OPFLAG_FORWARD;
1462 forwref = saa_rstruct(forwrefs);
1463 } while (forwref != NULL
1464 && forwref->lineno == globallineno);
1465 } else
1466 output_ins.forw_ref = false;
1469 if (!(optimizing > 0) && output_ins.forw_ref) {
1470 if (passn == 1) {
1471 for (i = 0; i < output_ins.operands; i++) {
1472 if (output_ins.oprs[i].
1473 opflags & OPFLAG_FORWARD) {
1474 struct forwrefinfo *fwinf =
1475 (struct forwrefinfo *)
1476 saa_wstruct(forwrefs);
1477 fwinf->lineno = globallineno;
1478 fwinf->operand = i;
1481 } else { /* passn > 1 */
1483 * Hack to prevent phase error in the code
1484 * rol ax,x
1485 * x equ 1
1487 * If the second operand is a forward reference,
1488 * the UNITY property of the number 1 in that
1489 * operand is cancelled. Otherwise the above
1490 * sequence will cause a phase error.
1492 * This hack means that the above code will
1493 * generate 286+ code.
1495 * The forward reference will mean that the
1496 * operand will not have the UNITY property on
1497 * the first pass, so the pass behaviours will
1498 * be consistent.
1501 if (output_ins.operands >= 2 &&
1502 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1503 !(IMMEDIATE & ~output_ins.oprs[1].type))
1505 /* Remove special properties bits */
1506 output_ins.oprs[1].type &= ~REG_SMASK;
1513 /* forw_ref */
1514 if (output_ins.opcode == I_EQU) {
1515 if (pass1 == 1) {
1517 * Special `..' EQUs get processed in pass two,
1518 * except `..@' macro-processor EQUs which are done
1519 * in the normal place.
1521 if (!output_ins.label)
1522 report_error(ERR_NONFATAL,
1523 "EQU not preceded by label");
1525 else if (output_ins.label[0] != '.' ||
1526 output_ins.label[1] != '.' ||
1527 output_ins.label[2] == '@') {
1528 if (output_ins.operands == 1 &&
1529 (output_ins.oprs[0].type & IMMEDIATE) &&
1530 output_ins.oprs[0].wrt == NO_SEG) {
1531 int isext =
1532 output_ins.oprs[0].
1533 opflags & OPFLAG_EXTERN;
1534 def_label(output_ins.label,
1535 output_ins.oprs[0].segment,
1536 output_ins.oprs[0].offset, NULL,
1537 false, isext, ofmt,
1538 report_error);
1539 } else if (output_ins.operands == 2
1540 && (output_ins.oprs[0].
1541 type & IMMEDIATE)
1542 && (output_ins.oprs[0].type & COLON)
1543 && output_ins.oprs[0].segment ==
1544 NO_SEG
1545 && output_ins.oprs[0].wrt == NO_SEG
1546 && (output_ins.oprs[1].
1547 type & IMMEDIATE)
1548 && output_ins.oprs[1].segment ==
1549 NO_SEG
1550 && output_ins.oprs[1].wrt ==
1551 NO_SEG) {
1552 def_label(output_ins.label,
1553 output_ins.oprs[0].
1554 offset | SEG_ABS,
1555 output_ins.oprs[1].offset, NULL,
1556 false, false, ofmt,
1557 report_error);
1558 } else
1559 report_error(ERR_NONFATAL,
1560 "bad syntax for EQU");
1562 } else {
1564 * Special `..' EQUs get processed here, except
1565 * `..@' macro processor EQUs which are done above.
1567 if (output_ins.label[0] == '.' &&
1568 output_ins.label[1] == '.' &&
1569 output_ins.label[2] != '@') {
1570 if (output_ins.operands == 1 &&
1571 (output_ins.oprs[0].type & IMMEDIATE)) {
1572 define_label(output_ins.label,
1573 output_ins.oprs[0].segment,
1574 output_ins.oprs[0].offset,
1575 NULL, false, false, ofmt,
1576 report_error);
1577 } else if (output_ins.operands == 2
1578 && (output_ins.oprs[0].
1579 type & IMMEDIATE)
1580 && (output_ins.oprs[0].type & COLON)
1581 && output_ins.oprs[0].segment ==
1582 NO_SEG
1583 && (output_ins.oprs[1].
1584 type & IMMEDIATE)
1585 && output_ins.oprs[1].segment ==
1586 NO_SEG) {
1587 define_label(output_ins.label,
1588 output_ins.oprs[0].
1589 offset | SEG_ABS,
1590 output_ins.oprs[1].offset,
1591 NULL, false, false, ofmt,
1592 report_error);
1593 } else
1594 report_error(ERR_NONFATAL,
1595 "bad syntax for EQU");
1598 } else { /* instruction isn't an EQU */
1600 if (pass1 == 1) {
1602 int64_t l = insn_size(location.segment, offs, sb, cpu,
1603 &output_ins, report_error);
1605 /* if (using_debug_info) && output_ins.opcode != -1) */
1606 if (using_debug_info)
1607 { /* fbk 03/25/01 */
1608 /* this is done here so we can do debug type info */
1609 int32_t typeinfo =
1610 TYS_ELEMENTS(output_ins.operands);
1611 switch (output_ins.opcode) {
1612 case I_RESB:
1613 typeinfo =
1614 TYS_ELEMENTS(output_ins.oprs[0].
1615 offset) | TY_BYTE;
1616 break;
1617 case I_RESW:
1618 typeinfo =
1619 TYS_ELEMENTS(output_ins.oprs[0].
1620 offset) | TY_WORD;
1621 break;
1622 case I_RESD:
1623 typeinfo =
1624 TYS_ELEMENTS(output_ins.oprs[0].
1625 offset) | TY_DWORD;
1626 break;
1627 case I_RESQ:
1628 typeinfo =
1629 TYS_ELEMENTS(output_ins.oprs[0].
1630 offset) | TY_QWORD;
1631 break;
1632 case I_REST:
1633 typeinfo =
1634 TYS_ELEMENTS(output_ins.oprs[0].
1635 offset) | TY_TBYTE;
1636 break;
1637 case I_RESO:
1638 typeinfo =
1639 TYS_ELEMENTS(output_ins.oprs[0].
1640 offset) | TY_OWORD;
1641 break;
1642 case I_RESY:
1643 typeinfo =
1644 TYS_ELEMENTS(output_ins.oprs[0].
1645 offset) | TY_YWORD;
1646 break;
1647 case I_DB:
1648 typeinfo |= TY_BYTE;
1649 break;
1650 case I_DW:
1651 typeinfo |= TY_WORD;
1652 break;
1653 case I_DD:
1654 if (output_ins.eops_float)
1655 typeinfo |= TY_FLOAT;
1656 else
1657 typeinfo |= TY_DWORD;
1658 break;
1659 case I_DQ:
1660 typeinfo |= TY_QWORD;
1661 break;
1662 case I_DT:
1663 typeinfo |= TY_TBYTE;
1664 break;
1665 case I_DO:
1666 typeinfo |= TY_OWORD;
1667 break;
1668 case I_DY:
1669 typeinfo |= TY_YWORD;
1670 break;
1671 default:
1672 typeinfo = TY_LABEL;
1676 ofmt->current_dfmt->debug_typevalue(typeinfo);
1679 if (l != -1) {
1680 offs += l;
1681 SET_CURR_OFFS(offs);
1684 * else l == -1 => invalid instruction, which will be
1685 * flagged as an error on pass 2
1688 } else {
1689 offs += assemble(location.segment, offs, sb, cpu,
1690 &output_ins, ofmt, report_error,
1691 &nasmlist);
1692 SET_CURR_OFFS(offs);
1695 } /* not an EQU */
1696 cleanup_insn(&output_ins);
1698 nasm_free(line);
1699 location.offset = offs = GET_CURR_OFFS;
1700 } /* end while (line = preproc->getline... */
1702 if (pass1 == 2 && global_offset_changed)
1703 report_error(ERR_NONFATAL,
1704 "phase error detected at end of assembly.");
1706 if (pass1 == 1)
1707 preproc->cleanup(1);
1709 if (pass1 == 1 && terminate_after_phase) {
1710 fclose(ofile);
1711 remove(outname);
1712 if (want_usage)
1713 usage();
1714 exit(1);
1716 if (passn >= pass_max - 2 ||
1717 (passn > 1 && !global_offset_changed))
1718 pass0++;
1721 preproc->cleanup(0);
1722 nasmlist.cleanup();
1723 #if 1
1724 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1725 fprintf(stdout,
1726 "info:: assembly required 1+%d+1 passes\n", passn-3);
1727 #endif
1728 } /* exit from assemble_file (...) */
1730 static enum directives getkw(char **directive, char **value)
1732 char *p, *q, *buf;
1734 buf = *directive;
1736 /* allow leading spaces or tabs */
1737 while (*buf == ' ' || *buf == '\t')
1738 buf++;
1740 if (*buf != '[')
1741 return 0;
1743 p = buf;
1745 while (*p && *p != ']')
1746 p++;
1748 if (!*p)
1749 return 0;
1751 q = p++;
1753 while (*p && *p != ';') {
1754 if (!isspace(*p))
1755 return 0;
1756 p++;
1758 q[1] = '\0';
1760 *directive = p = buf + 1;
1761 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1762 buf++;
1763 if (*buf == ']') {
1764 *buf = '\0';
1765 *value = buf;
1766 } else {
1767 *buf++ = '\0';
1768 while (isspace(*buf))
1769 buf++; /* beppu - skip leading whitespace */
1770 *value = buf;
1771 while (*buf != ']')
1772 buf++;
1773 *buf++ = '\0';
1776 return bsii(*directive, directives, elements(directives));
1780 * gnu style error reporting
1781 * This function prints an error message to error_file in the
1782 * style used by GNU. An example would be:
1783 * file.asm:50: error: blah blah blah
1784 * where file.asm is the name of the file, 50 is the line number on
1785 * which the error occurs (or is detected) and "error:" is one of
1786 * the possible optional diagnostics -- it can be "error" or "warning"
1787 * or something else. Finally the line terminates with the actual
1788 * error message.
1790 * @param severity the severity of the warning or error
1791 * @param fmt the printf style format string
1793 static void report_error_gnu(int severity, const char *fmt, ...)
1795 va_list ap;
1797 if (is_suppressed_warning(severity))
1798 return;
1800 if (severity & ERR_NOFILE)
1801 fputs("nasm: ", error_file);
1802 else {
1803 char *currentfile = NULL;
1804 int32_t lineno = 0;
1805 src_get(&lineno, &currentfile);
1806 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1807 nasm_free(currentfile);
1809 va_start(ap, fmt);
1810 report_error_common(severity, fmt, ap);
1811 va_end(ap);
1815 * MS style error reporting
1816 * This function prints an error message to error_file in the
1817 * style used by Visual C and some other Microsoft tools. An example
1818 * would be:
1819 * file.asm(50) : error: blah blah blah
1820 * where file.asm is the name of the file, 50 is the line number on
1821 * which the error occurs (or is detected) and "error:" is one of
1822 * the possible optional diagnostics -- it can be "error" or "warning"
1823 * or something else. Finally the line terminates with the actual
1824 * error message.
1826 * @param severity the severity of the warning or error
1827 * @param fmt the printf style format string
1829 static void report_error_vc(int severity, const char *fmt, ...)
1831 va_list ap;
1833 if (is_suppressed_warning(severity))
1834 return;
1836 if (severity & ERR_NOFILE)
1837 fputs("nasm: ", error_file);
1838 else {
1839 char *currentfile = NULL;
1840 int32_t lineno = 0;
1841 src_get(&lineno, &currentfile);
1842 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1843 nasm_free(currentfile);
1845 va_start(ap, fmt);
1846 report_error_common(severity, fmt, ap);
1847 va_end(ap);
1851 * check for supressed warning
1852 * checks for suppressed warning or pass one only warning and we're
1853 * not in pass 1
1855 * @param severity the severity of the warning or error
1856 * @return true if we should abort error/warning printing
1858 static bool is_suppressed_warning(int severity)
1861 * See if it's a suppressed warning.
1863 return (severity & ERR_MASK) == ERR_WARNING &&
1864 (((severity & ERR_WARN_MASK) != 0 &&
1865 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1866 /* See if it's a pass-one only warning and we're not in pass one. */
1867 ((severity & ERR_PASS1) && pass0 != 1));
1871 * common error reporting
1872 * This is the common back end of the error reporting schemes currently
1873 * implemented. It prints the nature of the warning and then the
1874 * specific error message to error_file and may or may not return. It
1875 * doesn't return if the error severity is a "panic" or "debug" type.
1877 * @param severity the severity of the warning or error
1878 * @param fmt the printf style format string
1880 static void report_error_common(int severity, const char *fmt,
1881 va_list args)
1883 switch (severity & ERR_MASK) {
1884 case ERR_WARNING:
1885 fputs("warning: ", error_file);
1886 break;
1887 case ERR_NONFATAL:
1888 fputs("error: ", error_file);
1889 break;
1890 case ERR_FATAL:
1891 fputs("fatal: ", error_file);
1892 break;
1893 case ERR_PANIC:
1894 fputs("panic: ", error_file);
1895 break;
1896 case ERR_DEBUG:
1897 fputs("debug: ", error_file);
1898 break;
1901 vfprintf(error_file, fmt, args);
1902 putc('\n', error_file);
1904 if (severity & ERR_USAGE)
1905 want_usage = true;
1907 switch (severity & ERR_MASK) {
1908 case ERR_DEBUG:
1909 /* no further action, by definition */
1910 break;
1911 case ERR_WARNING:
1912 if (!suppressed[0]) /* Treat warnings as errors */
1913 terminate_after_phase = true;
1914 break;
1915 case ERR_NONFATAL:
1916 terminate_after_phase = true;
1917 break;
1918 case ERR_FATAL:
1919 if (ofile) {
1920 fclose(ofile);
1921 remove(outname);
1923 if (want_usage)
1924 usage();
1925 exit(1); /* instantly die */
1926 break; /* placate silly compilers */
1927 case ERR_PANIC:
1928 fflush(NULL);
1929 /* abort(); *//* halt, catch fire, and dump core */
1930 exit(3);
1931 break;
1935 static void usage(void)
1937 fputs("type `nasm -h' for help\n", error_file);
1940 static void register_output_formats(void)
1942 ofmt = ofmt_register(report_error);
1945 #define BUF_DELTA 512
1947 static FILE *no_pp_fp;
1948 static efunc no_pp_err;
1949 static ListGen *no_pp_list;
1950 static int32_t no_pp_lineinc;
1952 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1953 ListGen * listgen, FILE *depends)
1955 src_set_fname(nasm_strdup(file));
1956 src_set_linnum(0);
1957 no_pp_lineinc = 1;
1958 no_pp_err = error;
1959 no_pp_fp = fopen(file, "r");
1960 if (!no_pp_fp)
1961 no_pp_err(ERR_FATAL | ERR_NOFILE,
1962 "unable to open input file `%s'", file);
1963 no_pp_list = listgen;
1964 (void)pass; /* placate compilers */
1965 (void)eval; /* placate compilers */
1966 (void)depends; /* placate compilers */
1969 static char *no_pp_getline(void)
1971 char *buffer, *p, *q;
1972 int bufsize;
1974 bufsize = BUF_DELTA;
1975 buffer = nasm_malloc(BUF_DELTA);
1976 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1978 while (1) { /* Loop to handle %line */
1980 p = buffer;
1981 while (1) { /* Loop to handle long lines */
1982 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
1983 if (!q)
1984 break;
1985 p += strlen(p);
1986 if (p > buffer && p[-1] == '\n')
1987 break;
1988 if (p - buffer > bufsize - 10) {
1989 int offset;
1990 offset = p - buffer;
1991 bufsize += BUF_DELTA;
1992 buffer = nasm_realloc(buffer, bufsize);
1993 p = buffer + offset;
1997 if (!q && p == buffer) {
1998 nasm_free(buffer);
1999 return NULL;
2003 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2004 * them are present at the end of the line.
2006 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2008 if (!nasm_strnicmp(buffer, "%line", 5)) {
2009 int32_t ln;
2010 int li;
2011 char *nm = nasm_malloc(strlen(buffer));
2012 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2013 nasm_free(src_set_fname(nm));
2014 src_set_linnum(ln);
2015 no_pp_lineinc = li;
2016 continue;
2018 nasm_free(nm);
2020 break;
2023 no_pp_list->line(LIST_READ, buffer);
2025 return buffer;
2028 static void no_pp_cleanup(int pass)
2030 (void)pass; /* placate GCC */
2031 fclose(no_pp_fp);
2034 static uint32_t get_cpu(char *value)
2036 if (!strcmp(value, "8086"))
2037 return IF_8086;
2038 if (!strcmp(value, "186"))
2039 return IF_186;
2040 if (!strcmp(value, "286"))
2041 return IF_286;
2042 if (!strcmp(value, "386"))
2043 return IF_386;
2044 if (!strcmp(value, "486"))
2045 return IF_486;
2046 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2047 return IF_PENT;
2048 if (!strcmp(value, "686") ||
2049 !nasm_stricmp(value, "ppro") ||
2050 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2051 return IF_P6;
2052 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2053 return IF_KATMAI;
2054 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2055 !nasm_stricmp(value, "willamette"))
2056 return IF_WILLAMETTE;
2057 if (!nasm_stricmp(value, "prescott"))
2058 return IF_PRESCOTT;
2059 if (!nasm_stricmp(value, "x64") ||
2060 !nasm_stricmp(value, "x86-64"))
2061 return IF_X86_64;
2062 if (!nasm_stricmp(value, "ia64") ||
2063 !nasm_stricmp(value, "ia-64") ||
2064 !nasm_stricmp(value, "itanium") ||
2065 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2066 return IF_IA64;
2068 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2069 "unknown 'cpu' type");
2071 return IF_PLEVEL; /* the maximum level */
2074 static int get_bits(char *value)
2076 int i;
2078 if ((i = atoi(value)) == 16)
2079 return i; /* set for a 16-bit segment */
2080 else if (i == 32) {
2081 if (cpu < IF_386) {
2082 report_error(ERR_NONFATAL,
2083 "cannot specify 32-bit segment on processor below a 386");
2084 i = 16;
2086 } else if (i == 64) {
2087 if (cpu < IF_X86_64) {
2088 report_error(ERR_NONFATAL,
2089 "cannot specify 64-bit segment on processor below an x86-64");
2090 i = 16;
2092 if (i != maxbits) {
2093 report_error(ERR_NONFATAL,
2094 "%s output format does not support 64-bit code",
2095 ofmt->shortname);
2096 i = 16;
2098 } else {
2099 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2100 "`%s' is not a valid segment size; must be 16, 32 or 64",
2101 value);
2102 i = 16;
2104 return i;
2107 /* end of nasm.c */