Don't fclose() the output in the backend
[nasm.git] / nasm.c
blob53e1c72b0a2899e2074eaac4fdca21b83bc43779
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2009 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * The Netwide Assembler main program module
38 #include "compiler.h"
40 #include <stdio.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <inttypes.h>
46 #include <limits.h>
47 #include <time.h>
49 #include "nasm.h"
50 #include "nasmlib.h"
51 #include "saa.h"
52 #include "raa.h"
53 #include "float.h"
54 #include "stdscan.h"
55 #include "insns.h"
56 #include "preproc.h"
57 #include "parser.h"
58 #include "eval.h"
59 #include "assemble.h"
60 #include "labels.h"
61 #include "output/outform.h"
62 #include "listing.h"
63 #include "directives.h"
65 struct forwrefinfo { /* info held on forward refs. */
66 int lineno;
67 int operand;
70 static int get_bits(char *value);
71 static uint32_t get_cpu(char *cpu_str);
72 static void parse_cmdline(int, char **);
73 static void assemble_file(char *, StrList **);
74 static void register_output_formats(void);
75 static void report_error_gnu(int severity, const char *fmt, ...);
76 static void report_error_vc(int severity, const char *fmt, ...);
77 static void report_error_common(int severity, const char *fmt,
78 va_list args);
79 static bool is_suppressed_warning(int severity);
80 static void usage(void);
81 static efunc report_error;
83 static int using_debug_info, opt_verbose_info;
84 bool tasm_compatible_mode = false;
85 int pass0, passn;
86 int maxbits = 0;
87 int globalrel = 0;
89 time_t official_compile_time;
91 static char inname[FILENAME_MAX];
92 static char outname[FILENAME_MAX];
93 static char listname[FILENAME_MAX];
94 static char errname[FILENAME_MAX];
95 static int globallineno; /* for forward-reference tracking */
96 /* static int pass = 0; */
97 static struct ofmt *ofmt = NULL;
99 static FILE *error_file; /* Where to write error messages */
101 static FILE *ofile = NULL;
102 int optimizing = -1; /* number of optimization passes to take */
103 static int sb, cmd_sb = 16; /* by default */
104 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
105 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
106 int64_t global_offset_changed; /* referenced in labels.c */
107 int64_t prev_offset_changed;
108 int32_t stall_count;
110 static struct location location;
111 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
112 int32_t abs_seg; /* ABSOLUTE segment basis */
113 int32_t abs_offset; /* ABSOLUTE offset */
115 static struct RAA *offsets;
117 static struct SAA *forwrefs; /* keep track of forward references */
118 static const struct forwrefinfo *forwref;
120 static Preproc *preproc;
121 enum op_type {
122 op_normal, /* Preprocess and assemble */
123 op_preprocess, /* Preprocess only */
124 op_depend, /* Generate dependencies */
126 static enum op_type operating_mode;
127 /* Dependency flags */
128 static bool depend_emit_phony = false;
129 static bool depend_missing_ok = false;
130 static const char *depend_target = NULL;
131 static const char *depend_file = NULL;
134 * Which of the suppressible warnings are suppressed. Entry zero
135 * isn't an actual warning, but it used for -w+error/-Werror.
138 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
139 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
141 static const struct warning {
142 const char *name;
143 const char *help;
144 bool enabled;
145 } warnings[ERR_WARN_MAX+1] = {
146 {"error", "treat warnings as errors", false},
147 {"macro-params", "macro calls with wrong parameter count", true},
148 {"macro-selfref", "cyclic macro references", false},
149 {"macro-defaults", "macros with more default than optional parameters", true},
150 {"orphan-labels", "labels alone on lines without trailing `:'", true},
151 {"number-overflow", "numeric constant does not fit", true},
152 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
153 {"float-overflow", "floating point overflow", true},
154 {"float-denorm", "floating point denormal", false},
155 {"float-underflow", "floating point underflow", false},
156 {"float-toolong", "too many digits in floating-point number", true},
157 {"user", "%warning directives", true},
161 * This is a null preprocessor which just copies lines from input
162 * to output. It's used when someone explicitly requests that NASM
163 * not preprocess their source file.
166 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
167 static char *no_pp_getline(void);
168 static void no_pp_cleanup(int);
169 static Preproc no_pp = {
170 no_pp_reset,
171 no_pp_getline,
172 no_pp_cleanup
176 * get/set current offset...
178 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
179 raa_read(offsets,location.segment))
180 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
181 (void)(offsets=raa_write(offsets,location.segment,(x))))
183 static bool want_usage;
184 static bool terminate_after_phase;
185 int user_nolist = 0; /* fbk 9/2/00 */
187 static void nasm_fputs(const char *line, FILE * outfile)
189 if (outfile) {
190 fputs(line, outfile);
191 putc('\n', outfile);
192 } else
193 puts(line);
196 /* Convert a struct tm to a POSIX-style time constant */
197 static int64_t posix_mktime(struct tm *tm)
199 int64_t t;
200 int64_t y = tm->tm_year;
202 /* See IEEE 1003.1:2004, section 4.14 */
204 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
205 t += tm->tm_yday;
206 t *= 24;
207 t += tm->tm_hour;
208 t *= 60;
209 t += tm->tm_min;
210 t *= 60;
211 t += tm->tm_sec;
213 return t;
216 static void define_macros_early(void)
218 char temp[128];
219 struct tm lt, *lt_p, gm, *gm_p;
220 int64_t posix_time;
222 lt_p = localtime(&official_compile_time);
223 if (lt_p) {
224 lt = *lt_p;
226 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
227 pp_pre_define(temp);
228 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
229 pp_pre_define(temp);
230 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
231 pp_pre_define(temp);
232 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
233 pp_pre_define(temp);
236 gm_p = gmtime(&official_compile_time);
237 if (gm_p) {
238 gm = *gm_p;
240 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
241 pp_pre_define(temp);
242 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
243 pp_pre_define(temp);
244 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
245 pp_pre_define(temp);
246 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
247 pp_pre_define(temp);
250 if (gm_p)
251 posix_time = posix_mktime(&gm);
252 else if (lt_p)
253 posix_time = posix_mktime(&lt);
254 else
255 posix_time = 0;
257 if (posix_time) {
258 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
259 pp_pre_define(temp);
263 static void define_macros_late(void)
265 char temp[128];
267 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
268 ofmt->shortname);
269 pp_pre_define(temp);
272 static void emit_dependencies(StrList *list)
274 FILE *deps;
275 int linepos, len;
276 StrList *l, *nl;
278 if (depend_file && strcmp(depend_file, "-")) {
279 deps = fopen(depend_file, "w");
280 if (!deps) {
281 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
282 "unable to write dependency file `%s'", depend_file);
283 return;
285 } else {
286 deps = stdout;
289 linepos = fprintf(deps, "%s:", depend_target);
290 for (l = list; l; l = l->next) {
291 len = strlen(l->str);
292 if (linepos + len > 62) {
293 fprintf(deps, " \\\n ");
294 linepos = 1;
296 fprintf(deps, " %s", l->str);
297 linepos += len+1;
299 fprintf(deps, "\n\n");
301 for (l = list; l; l = nl) {
302 if (depend_emit_phony)
303 fprintf(deps, "%s:\n\n", l->str);
305 nl = l->next;
306 nasm_free(l);
309 if (deps != stdout)
310 fclose(deps);
313 int main(int argc, char **argv)
315 StrList *depend_list = NULL, **depend_ptr;
317 time(&official_compile_time);
319 pass0 = 0;
320 want_usage = terminate_after_phase = false;
321 report_error = report_error_gnu;
323 error_file = stderr;
325 tolower_init();
327 nasm_set_malloc_error(report_error);
328 offsets = raa_init();
329 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
331 preproc = &nasmpp;
332 operating_mode = op_normal;
334 seg_init();
336 register_output_formats();
338 /* Define some macros dependent on the runtime, but not
339 on the command line. */
340 define_macros_early();
342 parse_cmdline(argc, argv);
344 if (terminate_after_phase) {
345 if (want_usage)
346 usage();
347 return 1;
350 /* If debugging info is disabled, suppress any debug calls */
351 if (!using_debug_info)
352 ofmt->current_dfmt = &null_debug_form;
354 if (ofmt->stdmac)
355 pp_extra_stdmac(ofmt->stdmac);
356 parser_global_info(ofmt, &location);
357 eval_global_info(ofmt, lookup_label, &location);
359 /* define some macros dependent of command-line */
360 define_macros_late();
362 depend_ptr = (depend_file || (operating_mode == op_depend))
363 ? &depend_list : NULL;
364 if (!depend_target)
365 depend_target = outname;
367 switch (operating_mode) {
368 case op_depend:
370 char *line;
372 if (depend_missing_ok)
373 pp_include_path(NULL); /* "assume generated" */
375 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
376 depend_ptr);
377 if (outname[0] == '\0')
378 ofmt->filename(inname, outname, report_error);
379 ofile = NULL;
380 while ((line = preproc->getline()))
381 nasm_free(line);
382 preproc->cleanup(0);
384 break;
386 case op_preprocess:
388 char *line;
389 char *file_name = NULL;
390 int32_t prior_linnum = 0;
391 int lineinc = 0;
393 if (*outname) {
394 ofile = fopen(outname, "w");
395 if (!ofile)
396 report_error(ERR_FATAL | ERR_NOFILE,
397 "unable to open output file `%s'",
398 outname);
399 } else
400 ofile = NULL;
402 location.known = false;
404 /* pass = 1; */
405 preproc->reset(inname, 3, report_error, evaluate, &nasmlist,
406 depend_ptr);
408 while ((line = preproc->getline())) {
410 * We generate %line directives if needed for later programs
412 int32_t linnum = prior_linnum += lineinc;
413 int altline = src_get(&linnum, &file_name);
414 if (altline) {
415 if (altline == 1 && lineinc == 1)
416 nasm_fputs("", ofile);
417 else {
418 lineinc = (altline != -1 || lineinc != 1);
419 fprintf(ofile ? ofile : stdout,
420 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
421 file_name);
423 prior_linnum = linnum;
425 nasm_fputs(line, ofile);
426 nasm_free(line);
428 nasm_free(file_name);
429 preproc->cleanup(0);
430 if (ofile)
431 fclose(ofile);
432 if (ofile && terminate_after_phase)
433 remove(outname);
434 ofile = NULL;
436 break;
438 case op_normal:
441 * We must call ofmt->filename _anyway_, even if the user
442 * has specified their own output file, because some
443 * formats (eg OBJ and COFF) use ofmt->filename to find out
444 * the name of the input file and then put that inside the
445 * file.
447 ofmt->filename(inname, outname, report_error);
449 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
450 if (!ofile) {
451 report_error(ERR_FATAL | ERR_NOFILE,
452 "unable to open output file `%s'", outname);
456 * We must call init_labels() before ofmt->init() since
457 * some object formats will want to define labels in their
458 * init routines. (eg OS/2 defines the FLAT group)
460 init_labels();
462 ofmt->init(ofile, report_error, define_label, evaluate);
463 ofmt->current_dfmt->init(ofmt, NULL, ofile, report_error);
465 assemble_file(inname, depend_ptr);
467 if (!terminate_after_phase) {
468 ofmt->cleanup(using_debug_info);
469 cleanup_labels();
470 fflush(ofile);
471 if (ferror(ofile)) {
472 report_error(ERR_NONFATAL|ERR_NOFILE,
473 "write error on output file `%s'", outname);
477 fclose(ofile);
478 if (ofile && terminate_after_phase)
479 remove(outname);
480 ofile = NULL;
482 break;
485 if (depend_list && !terminate_after_phase)
486 emit_dependencies(depend_list);
488 if (want_usage)
489 usage();
491 raa_free(offsets);
492 saa_free(forwrefs);
493 eval_cleanup();
494 stdscan_cleanup();
496 return terminate_after_phase;
500 * Get a parameter for a command line option.
501 * First arg must be in the form of e.g. -f...
503 static char *get_param(char *p, char *q, bool *advance)
505 *advance = false;
506 if (p[2]) { /* the parameter's in the option */
507 p += 2;
508 while (nasm_isspace(*p))
509 p++;
510 return p;
512 if (q && q[0]) {
513 *advance = true;
514 return q;
516 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
517 "option `-%c' requires an argument", p[1]);
518 return NULL;
522 * Copy a filename
524 static void copy_filename(char *dst, const char *src)
526 size_t len = strlen(src);
528 if (len >= (size_t)FILENAME_MAX) {
529 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
530 return;
532 strncpy(dst, src, FILENAME_MAX);
536 * Convert a string to Make-safe form
538 static char *quote_for_make(const char *str)
540 const char *p;
541 char *os, *q;
543 size_t n = 1; /* Terminating zero */
544 size_t nbs = 0;
546 if (!str)
547 return NULL;
549 for (p = str; *p; p++) {
550 switch (*p) {
551 case ' ':
552 case '\t':
553 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
554 n += nbs + 2;
555 nbs = 0;
556 break;
557 case '$':
558 case '#':
559 nbs = 0;
560 n += 2;
561 break;
562 case '\\':
563 nbs++;
564 n++;
565 break;
566 default:
567 nbs = 0;
568 n++;
569 break;
573 /* Convert N backslashes at the end of filename to 2N backslashes */
574 if (nbs)
575 n += nbs;
577 os = q = nasm_malloc(n);
579 nbs = 0;
580 for (p = str; *p; p++) {
581 switch (*p) {
582 case ' ':
583 case '\t':
584 while (nbs--)
585 *q++ = '\\';
586 *q++ = '\\';
587 *q++ = *p;
588 break;
589 case '$':
590 *q++ = *p;
591 *q++ = *p;
592 nbs = 0;
593 break;
594 case '#':
595 *q++ = '\\';
596 *q++ = *p;
597 nbs = 0;
598 break;
599 case '\\':
600 *q++ = *p;
601 nbs++;
602 break;
603 default:
604 *q++ = *p;
605 nbs = 0;
606 break;
609 while (nbs--)
610 *q++ = '\\';
612 *q = '\0';
614 return os;
617 struct textargs {
618 const char *label;
619 int value;
622 #define OPT_PREFIX 0
623 #define OPT_POSTFIX 1
624 struct textargs textopts[] = {
625 {"prefix", OPT_PREFIX},
626 {"postfix", OPT_POSTFIX},
627 {NULL, 0}
630 static bool stopoptions = false;
631 static bool process_arg(char *p, char *q)
633 char *param;
634 int i;
635 bool advance = false;
636 bool do_warn;
638 if (!p || !p[0])
639 return false;
641 if (p[0] == '-' && !stopoptions) {
642 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
643 /* These parameters take values */
644 if (!(param = get_param(p, q, &advance)))
645 return advance;
648 switch (p[1]) {
649 case 's':
650 error_file = stdout;
651 break;
653 case 'o': /* output file */
654 copy_filename(outname, param);
655 break;
657 case 'f': /* output format */
658 ofmt = ofmt_find(param);
659 if (!ofmt) {
660 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
661 "unrecognised output format `%s' - "
662 "use -hf for a list", param);
664 break;
666 case 'O': /* Optimization level */
668 int opt;
670 if (!*param) {
671 /* Naked -O == -Ox */
672 optimizing = INT_MAX >> 1; /* Almost unlimited */
673 } else {
674 while (*param) {
675 switch (*param) {
676 case '0': case '1': case '2': case '3': case '4':
677 case '5': case '6': case '7': case '8': case '9':
678 opt = strtoul(param, &param, 10);
680 /* -O0 -> optimizing == -1, 0.98 behaviour */
681 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
682 if (opt < 2)
683 optimizing = opt - 1;
684 else
685 optimizing = opt;
686 break;
688 case 'v':
689 case '+':
690 param++;
691 opt_verbose_info = true;
692 break;
694 case 'x':
695 param++;
696 optimizing = INT_MAX >> 1; /* Almost unlimited */
697 break;
699 default:
700 report_error(ERR_FATAL,
701 "unknown optimization option -O%c\n",
702 *param);
703 break;
707 break;
710 case 'p': /* pre-include */
711 case 'P':
712 pp_pre_include(param);
713 break;
715 case 'd': /* pre-define */
716 case 'D':
717 pp_pre_define(param);
718 break;
720 case 'u': /* un-define */
721 case 'U':
722 pp_pre_undefine(param);
723 break;
725 case 'i': /* include search path */
726 case 'I':
727 pp_include_path(param);
728 break;
730 case 'l': /* listing file */
731 copy_filename(listname, param);
732 break;
734 case 'Z': /* error messages file */
735 strcpy(errname, param);
736 break;
738 case 'F': /* specify debug format */
739 ofmt->current_dfmt = dfmt_find(ofmt, param);
740 if (!ofmt->current_dfmt) {
741 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
742 "unrecognized debug format `%s' for"
743 " output format `%s'",
744 param, ofmt->shortname);
746 using_debug_info = true;
747 break;
749 case 'X': /* specify error reporting format */
750 if (nasm_stricmp("vc", param) == 0)
751 report_error = report_error_vc;
752 else if (nasm_stricmp("gnu", param) == 0)
753 report_error = report_error_gnu;
754 else
755 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
756 "unrecognized error reporting format `%s'",
757 param);
758 break;
760 case 'g':
761 using_debug_info = true;
762 break;
764 case 'h':
765 printf
766 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
767 "[-l listfile]\n"
768 " [options...] [--] filename\n"
769 " or nasm -v for version info\n\n"
770 " -t assemble in SciTech TASM compatible mode\n"
771 " -g generate debug information in selected format.\n");
772 printf
773 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
774 " -a don't preprocess (assemble only)\n"
775 " -M generate Makefile dependencies on stdout\n"
776 " -MG d:o, missing files assumed generated\n\n"
777 " -Z<file> redirect error messages to file\n"
778 " -s redirect error messages to stdout\n\n"
779 " -F format select a debugging format\n\n"
780 " -I<path> adds a pathname to the include file path\n");
781 printf
782 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
783 " -P<file> pre-includes a file\n"
784 " -D<macro>[=<value>] pre-defines a macro\n"
785 " -U<macro> undefines a macro\n"
786 " -X<format> specifies error reporting format (gnu or vc)\n"
787 " -w+foo enables warning foo (equiv. -Wfoo)\n"
788 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
789 "Warnings:\n");
790 for (i = 0; i <= ERR_WARN_MAX; i++)
791 printf(" %-23s %s (default %s)\n",
792 warnings[i].name, warnings[i].help,
793 warnings[i].enabled ? "on" : "off");
794 printf
795 ("\nresponse files should contain command line parameters"
796 ", one per line.\n");
797 if (p[2] == 'f') {
798 printf("\nvalid output formats for -f are"
799 " (`*' denotes default):\n");
800 ofmt_list(ofmt, stdout);
801 } else {
802 printf("\nFor a list of valid output formats, use -hf.\n");
803 printf("For a list of debug formats, use -f <form> -y.\n");
805 exit(0); /* never need usage message here */
806 break;
808 case 'y':
809 printf("\nvalid debug formats for '%s' output format are"
810 " ('*' denotes default):\n", ofmt->shortname);
811 dfmt_list(ofmt, stdout);
812 exit(0);
813 break;
815 case 't':
816 tasm_compatible_mode = true;
817 break;
819 case 'v':
820 printf("NASM version %s compiled on %s%s\n",
821 nasm_version, nasm_date, nasm_compile_options);
822 exit(0); /* never need usage message here */
823 break;
825 case 'e': /* preprocess only */
826 case 'E':
827 operating_mode = op_preprocess;
828 break;
830 case 'a': /* assemble only - don't preprocess */
831 preproc = &no_pp;
832 break;
834 case 'W':
835 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
836 do_warn = false;
837 param += 3;
838 } else {
839 do_warn = true;
841 goto set_warning;
843 case 'w':
844 if (param[0] != '+' && param[0] != '-') {
845 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
846 "invalid option to `-w'");
847 break;
849 do_warn = (param[0] == '+');
850 param++;
851 goto set_warning;
852 set_warning:
853 for (i = 0; i <= ERR_WARN_MAX; i++)
854 if (!nasm_stricmp(param, warnings[i].name))
855 break;
856 if (i <= ERR_WARN_MAX)
857 warning_on_global[i] = do_warn;
858 else if (!nasm_stricmp(param, "all"))
859 for (i = 1; i <= ERR_WARN_MAX; i++)
860 warning_on_global[i] = do_warn;
861 else if (!nasm_stricmp(param, "none"))
862 for (i = 1; i <= ERR_WARN_MAX; i++)
863 warning_on_global[i] = !do_warn;
864 else
865 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
866 "invalid warning `%s'", param);
867 break;
869 case 'M':
870 switch (p[2]) {
871 case 0:
872 operating_mode = op_depend;
873 break;
874 case 'G':
875 operating_mode = op_depend;
876 depend_missing_ok = true;
877 break;
878 case 'P':
879 depend_emit_phony = true;
880 break;
881 case 'D':
882 depend_file = q;
883 advance = true;
884 break;
885 case 'T':
886 depend_target = q;
887 advance = true;
888 break;
889 case 'Q':
890 depend_target = quote_for_make(q);
891 advance = true;
892 break;
893 default:
894 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
895 "unknown dependency option `-M%c'", p[2]);
896 break;
898 if (advance && (!q || !q[0])) {
899 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
900 "option `-M%c' requires a parameter", p[2]);
901 break;
903 break;
905 case '-':
907 int s;
909 if (p[2] == 0) { /* -- => stop processing options */
910 stopoptions = 1;
911 break;
913 for (s = 0; textopts[s].label; s++) {
914 if (!nasm_stricmp(p + 2, textopts[s].label)) {
915 break;
919 switch (s) {
921 case OPT_PREFIX:
922 case OPT_POSTFIX:
924 if (!q) {
925 report_error(ERR_NONFATAL | ERR_NOFILE |
926 ERR_USAGE,
927 "option `--%s' requires an argument",
928 p + 2);
929 break;
930 } else {
931 advance = 1, param = q;
934 if (s == OPT_PREFIX) {
935 strncpy(lprefix, param, PREFIX_MAX - 1);
936 lprefix[PREFIX_MAX - 1] = 0;
937 break;
939 if (s == OPT_POSTFIX) {
940 strncpy(lpostfix, param, POSTFIX_MAX - 1);
941 lpostfix[POSTFIX_MAX - 1] = 0;
942 break;
944 break;
946 default:
948 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
949 "unrecognised option `--%s'", p + 2);
950 break;
953 break;
956 default:
957 if (!ofmt->setinfo(GI_SWITCH, &p))
958 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
959 "unrecognised option `-%c'", p[1]);
960 break;
962 } else {
963 if (*inname) {
964 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
965 "more than one input file specified");
966 } else {
967 copy_filename(inname, p);
971 return advance;
974 #define ARG_BUF_DELTA 128
976 static void process_respfile(FILE * rfile)
978 char *buffer, *p, *q, *prevarg;
979 int bufsize, prevargsize;
981 bufsize = prevargsize = ARG_BUF_DELTA;
982 buffer = nasm_malloc(ARG_BUF_DELTA);
983 prevarg = nasm_malloc(ARG_BUF_DELTA);
984 prevarg[0] = '\0';
986 while (1) { /* Loop to handle all lines in file */
987 p = buffer;
988 while (1) { /* Loop to handle long lines */
989 q = fgets(p, bufsize - (p - buffer), rfile);
990 if (!q)
991 break;
992 p += strlen(p);
993 if (p > buffer && p[-1] == '\n')
994 break;
995 if (p - buffer > bufsize - 10) {
996 int offset;
997 offset = p - buffer;
998 bufsize += ARG_BUF_DELTA;
999 buffer = nasm_realloc(buffer, bufsize);
1000 p = buffer + offset;
1004 if (!q && p == buffer) {
1005 if (prevarg[0])
1006 process_arg(prevarg, NULL);
1007 nasm_free(buffer);
1008 nasm_free(prevarg);
1009 return;
1013 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1014 * them are present at the end of the line.
1016 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1018 while (p > buffer && nasm_isspace(p[-1]))
1019 *--p = '\0';
1021 p = buffer;
1022 while (nasm_isspace(*p))
1023 p++;
1025 if (process_arg(prevarg, p))
1026 *p = '\0';
1028 if ((int) strlen(p) > prevargsize - 10) {
1029 prevargsize += ARG_BUF_DELTA;
1030 prevarg = nasm_realloc(prevarg, prevargsize);
1032 strncpy(prevarg, p, prevargsize);
1036 /* Function to process args from a string of args, rather than the
1037 * argv array. Used by the environment variable and response file
1038 * processing.
1040 static void process_args(char *args)
1042 char *p, *q, *arg, *prevarg;
1043 char separator = ' ';
1045 p = args;
1046 if (*p && *p != '-')
1047 separator = *p++;
1048 arg = NULL;
1049 while (*p) {
1050 q = p;
1051 while (*p && *p != separator)
1052 p++;
1053 while (*p == separator)
1054 *p++ = '\0';
1055 prevarg = arg;
1056 arg = q;
1057 if (process_arg(prevarg, arg))
1058 arg = NULL;
1060 if (arg)
1061 process_arg(arg, NULL);
1064 static void process_response_file(const char *file)
1066 char str[2048];
1067 FILE *f = fopen(file, "r");
1068 if (!f) {
1069 perror(file);
1070 exit(-1);
1072 while (fgets(str, sizeof str, f)) {
1073 process_args(str);
1075 fclose(f);
1078 static void parse_cmdline(int argc, char **argv)
1080 FILE *rfile;
1081 char *envreal, *envcopy = NULL, *p, *arg;
1082 int i;
1084 *inname = *outname = *listname = *errname = '\0';
1085 for (i = 0; i <= ERR_WARN_MAX; i++)
1086 warning_on_global[i] = warnings[i].enabled;
1089 * First, process the NASMENV environment variable.
1091 envreal = getenv("NASMENV");
1092 arg = NULL;
1093 if (envreal) {
1094 envcopy = nasm_strdup(envreal);
1095 process_args(envcopy);
1096 nasm_free(envcopy);
1100 * Now process the actual command line.
1102 while (--argc) {
1103 bool advance;
1104 argv++;
1105 if (argv[0][0] == '@') {
1106 /* We have a response file, so process this as a set of
1107 * arguments like the environment variable. This allows us
1108 * to have multiple arguments on a single line, which is
1109 * different to the -@resp file processing below for regular
1110 * NASM.
1112 process_response_file(argv[0]+1);
1113 argc--;
1114 argv++;
1116 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1117 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1118 if (p) {
1119 rfile = fopen(p, "r");
1120 if (rfile) {
1121 process_respfile(rfile);
1122 fclose(rfile);
1123 } else
1124 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1125 "unable to open response file `%s'", p);
1127 } else
1128 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1129 argv += advance, argc -= advance;
1132 /* Look for basic command line typos. This definitely doesn't
1133 catch all errors, but it might help cases of fumbled fingers. */
1134 if (!*inname)
1135 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1136 "no input file specified");
1137 else if (!strcmp(inname, errname) ||
1138 !strcmp(inname, outname) ||
1139 !strcmp(inname, listname) ||
1140 (depend_file && !strcmp(inname, depend_file)))
1141 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1142 "file `%s' is both input and output file",
1143 inname);
1145 if (*errname) {
1146 error_file = fopen(errname, "w");
1147 if (!error_file) {
1148 error_file = stderr; /* Revert to default! */
1149 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1150 "cannot open file `%s' for error messages",
1151 errname);
1156 static enum directives getkw(char **directive, char **value);
1158 static void assemble_file(char *fname, StrList **depend_ptr)
1160 char *directive, *value, *p, *q, *special, *line, debugid[80];
1161 insn output_ins;
1162 int i, validid;
1163 bool rn_error;
1164 int32_t seg;
1165 int64_t offs;
1166 struct tokenval tokval;
1167 expr *e;
1168 int pass_max;
1170 if (cmd_sb == 32 && cmd_cpu < IF_386)
1171 report_error(ERR_FATAL, "command line: "
1172 "32-bit segment size requires a higher cpu");
1174 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1175 for (passn = 1; pass0 <= 2; passn++) {
1176 int pass1, pass2;
1177 ldfunc def_label;
1179 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1180 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1181 /* pass0 0, 0, 0, ..., 1, 2 */
1183 def_label = passn > 1 ? redefine_label : define_label;
1185 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1186 cpu = cmd_cpu;
1187 if (pass0 == 2) {
1188 if (*listname)
1189 nasmlist.init(listname, report_error);
1191 in_abs_seg = false;
1192 global_offset_changed = 0; /* set by redefine_label */
1193 location.segment = ofmt->section(NULL, pass2, &sb);
1194 globalbits = sb;
1195 if (passn > 1) {
1196 saa_rewind(forwrefs);
1197 forwref = saa_rstruct(forwrefs);
1198 raa_free(offsets);
1199 offsets = raa_init();
1201 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1202 pass1 == 2 ? depend_ptr : NULL);
1203 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1205 globallineno = 0;
1206 if (passn == 1)
1207 location.known = true;
1208 location.offset = offs = GET_CURR_OFFS;
1210 while ((line = preproc->getline())) {
1211 enum directives d;
1212 globallineno++;
1215 * Here we parse our directives; this is not handled by the
1216 * 'real' parser. This really should be a separate function.
1218 directive = line;
1219 d = getkw(&directive, &value);
1220 if (d) {
1221 int err = 0;
1223 switch (d) {
1224 case D_SEGMENT: /* [SEGMENT n] */
1225 case D_SECTION:
1226 seg = ofmt->section(value, pass2, &sb);
1227 if (seg == NO_SEG) {
1228 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1229 "segment name `%s' not recognized",
1230 value);
1231 } else {
1232 in_abs_seg = false;
1233 location.segment = seg;
1235 break;
1236 case D_EXTERN: /* [EXTERN label:special] */
1237 if (*value == '$')
1238 value++; /* skip initial $ if present */
1239 if (pass0 == 2) {
1240 q = value;
1241 while (*q && *q != ':')
1242 q++;
1243 if (*q == ':') {
1244 *q++ = '\0';
1245 ofmt->symdef(value, 0L, 0L, 3, q);
1247 } else if (passn == 1) {
1248 q = value;
1249 validid = true;
1250 if (!isidstart(*q))
1251 validid = false;
1252 while (*q && *q != ':') {
1253 if (!isidchar(*q))
1254 validid = false;
1255 q++;
1257 if (!validid) {
1258 report_error(ERR_NONFATAL,
1259 "identifier expected after EXTERN");
1260 break;
1262 if (*q == ':') {
1263 *q++ = '\0';
1264 special = q;
1265 } else
1266 special = NULL;
1267 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1268 int temp = pass0;
1269 pass0 = 1; /* fake pass 1 in labels.c */
1270 declare_as_global(value, special,
1271 report_error);
1272 define_label(value, seg_alloc(), 0L, NULL,
1273 false, true, ofmt, report_error);
1274 pass0 = temp;
1276 } /* else pass0 == 1 */
1277 break;
1278 case D_BITS: /* [BITS bits] */
1279 globalbits = sb = get_bits(value);
1280 break;
1281 case D_GLOBAL: /* [GLOBAL symbol:special] */
1282 if (*value == '$')
1283 value++; /* skip initial $ if present */
1284 if (pass0 == 2) { /* pass 2 */
1285 q = value;
1286 while (*q && *q != ':')
1287 q++;
1288 if (*q == ':') {
1289 *q++ = '\0';
1290 ofmt->symdef(value, 0L, 0L, 3, q);
1292 } else if (pass2 == 1) { /* pass == 1 */
1293 q = value;
1294 validid = true;
1295 if (!isidstart(*q))
1296 validid = false;
1297 while (*q && *q != ':') {
1298 if (!isidchar(*q))
1299 validid = false;
1300 q++;
1302 if (!validid) {
1303 report_error(ERR_NONFATAL,
1304 "identifier expected after GLOBAL");
1305 break;
1307 if (*q == ':') {
1308 *q++ = '\0';
1309 special = q;
1310 } else
1311 special = NULL;
1312 declare_as_global(value, special, report_error);
1313 } /* pass == 1 */
1314 break;
1315 case D_COMMON: /* [COMMON symbol size:special] */
1317 int64_t size;
1319 if (*value == '$')
1320 value++; /* skip initial $ if present */
1321 p = value;
1322 validid = true;
1323 if (!isidstart(*p))
1324 validid = false;
1325 while (*p && !nasm_isspace(*p)) {
1326 if (!isidchar(*p))
1327 validid = false;
1328 p++;
1330 if (!validid) {
1331 report_error(ERR_NONFATAL,
1332 "identifier expected after COMMON");
1333 break;
1335 if (*p) {
1336 while (*p && nasm_isspace(*p))
1337 *p++ = '\0';
1338 q = p;
1339 while (*q && *q != ':')
1340 q++;
1341 if (*q == ':') {
1342 *q++ = '\0';
1343 special = q;
1344 } else {
1345 special = NULL;
1347 size = readnum(p, &rn_error);
1348 if (rn_error) {
1349 report_error(ERR_NONFATAL,
1350 "invalid size specified"
1351 " in COMMON declaration");
1352 break;
1354 } else {
1355 report_error(ERR_NONFATAL,
1356 "no size specified in"
1357 " COMMON declaration");
1358 break;
1361 if (pass0 < 2) {
1362 define_common(value, seg_alloc(), size,
1363 special, ofmt, report_error);
1364 } else if (pass0 == 2) {
1365 ofmt->symdef(value, 0L, 0L, 3, special);
1367 break;
1369 case D_ABSOLUTE: /* [ABSOLUTE address] */
1370 stdscan_reset();
1371 stdscan_bufptr = value;
1372 tokval.t_type = TOKEN_INVALID;
1373 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1374 report_error, NULL);
1375 if (e) {
1376 if (!is_reloc(e))
1377 report_error(pass0 ==
1378 1 ? ERR_NONFATAL : ERR_PANIC,
1379 "cannot use non-relocatable expression as "
1380 "ABSOLUTE address");
1381 else {
1382 abs_seg = reloc_seg(e);
1383 abs_offset = reloc_value(e);
1385 } else if (passn == 1)
1386 abs_offset = 0x100; /* don't go near zero in case of / */
1387 else
1388 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1389 "in pass two");
1390 in_abs_seg = true;
1391 location.segment = NO_SEG;
1392 break;
1393 case D_DEBUG: /* [DEBUG] */
1394 p = value;
1395 q = debugid;
1396 validid = true;
1397 if (!isidstart(*p))
1398 validid = false;
1399 while (*p && !nasm_isspace(*p)) {
1400 if (!isidchar(*p))
1401 validid = false;
1402 *q++ = *p++;
1404 *q++ = 0;
1405 if (!validid) {
1406 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1407 "identifier expected after DEBUG");
1408 break;
1410 while (*p && nasm_isspace(*p))
1411 p++;
1412 if (pass0 == 2)
1413 ofmt->current_dfmt->debug_directive(debugid, p);
1414 break;
1415 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1416 while (*value && nasm_isspace(*value))
1417 value++;
1419 switch(*value) {
1420 case '-': validid = 0; value++; break;
1421 case '+': validid = 1; value++; break;
1422 case '*': validid = 2; value++; break;
1423 default: validid = 1; break;
1426 for (i = 1; i <= ERR_WARN_MAX; i++)
1427 if (!nasm_stricmp(value, warnings[i].name))
1428 break;
1429 if (i <= ERR_WARN_MAX) {
1430 switch(validid) {
1431 case 0:
1432 warning_on[i] = false;
1433 break;
1434 case 1:
1435 warning_on[i] = true;
1436 break;
1437 case 2:
1438 warning_on[i] = warning_on_global[i];
1439 break;
1442 else
1443 report_error(ERR_NONFATAL,
1444 "invalid warning id in WARNING directive");
1445 break;
1446 case D_CPU: /* [CPU] */
1447 cpu = get_cpu(value);
1448 break;
1449 case D_LIST: /* [LIST {+|-}] */
1450 while (*value && nasm_isspace(*value))
1451 value++;
1453 if (*value == '+') {
1454 user_nolist = 0;
1455 } else {
1456 if (*value == '-') {
1457 user_nolist = 1;
1458 } else {
1459 err = 1;
1462 break;
1463 case D_DEFAULT: /* [DEFAULT] */
1464 stdscan_reset();
1465 stdscan_bufptr = value;
1466 tokval.t_type = TOKEN_INVALID;
1467 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1468 switch ((int)tokval.t_integer) {
1469 case S_REL:
1470 globalrel = 1;
1471 break;
1472 case S_ABS:
1473 globalrel = 0;
1474 break;
1475 default:
1476 err = 1;
1477 break;
1479 } else {
1480 err = 1;
1482 break;
1483 case D_FLOAT:
1484 if (float_option(value)) {
1485 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1486 "unknown 'float' directive: %s",
1487 value);
1489 break;
1490 default:
1491 if (!ofmt->directive(directive, value, pass2))
1492 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1493 "unrecognised directive [%s]",
1494 directive);
1496 if (err) {
1497 report_error(ERR_NONFATAL,
1498 "invalid parameter to [%s] directive",
1499 directive);
1501 } else { /* it isn't a directive */
1503 parse_line(pass1, line, &output_ins,
1504 report_error, evaluate, def_label);
1506 if (optimizing > 0) {
1507 if (forwref != NULL && globallineno == forwref->lineno) {
1508 output_ins.forw_ref = true;
1509 do {
1510 output_ins.oprs[forwref->operand].opflags |=
1511 OPFLAG_FORWARD;
1512 forwref = saa_rstruct(forwrefs);
1513 } while (forwref != NULL
1514 && forwref->lineno == globallineno);
1515 } else
1516 output_ins.forw_ref = false;
1518 if (output_ins.forw_ref) {
1519 if (passn == 1) {
1520 for (i = 0; i < output_ins.operands; i++) {
1521 if (output_ins.oprs[i].
1522 opflags & OPFLAG_FORWARD) {
1523 struct forwrefinfo *fwinf =
1524 (struct forwrefinfo *)
1525 saa_wstruct(forwrefs);
1526 fwinf->lineno = globallineno;
1527 fwinf->operand = i;
1534 /* forw_ref */
1535 if (output_ins.opcode == I_EQU) {
1536 if (pass1 == 1) {
1538 * Special `..' EQUs get processed in pass two,
1539 * except `..@' macro-processor EQUs which are done
1540 * in the normal place.
1542 if (!output_ins.label)
1543 report_error(ERR_NONFATAL,
1544 "EQU not preceded by label");
1546 else if (output_ins.label[0] != '.' ||
1547 output_ins.label[1] != '.' ||
1548 output_ins.label[2] == '@') {
1549 if (output_ins.operands == 1 &&
1550 (output_ins.oprs[0].type & IMMEDIATE) &&
1551 output_ins.oprs[0].wrt == NO_SEG) {
1552 bool isext = !!(output_ins.oprs[0].opflags
1553 & OPFLAG_EXTERN);
1554 def_label(output_ins.label,
1555 output_ins.oprs[0].segment,
1556 output_ins.oprs[0].offset, NULL,
1557 false, isext, ofmt,
1558 report_error);
1559 } else if (output_ins.operands == 2
1560 && (output_ins.oprs[0].type & IMMEDIATE)
1561 && (output_ins.oprs[0].type & COLON)
1562 && output_ins.oprs[0].segment == NO_SEG
1563 && output_ins.oprs[0].wrt == NO_SEG
1564 && (output_ins.oprs[1].type & IMMEDIATE)
1565 && output_ins.oprs[1].segment == NO_SEG
1566 && output_ins.oprs[1].wrt == NO_SEG) {
1567 def_label(output_ins.label,
1568 output_ins.oprs[0].offset | SEG_ABS,
1569 output_ins.oprs[1].offset,
1570 NULL, false, false, ofmt,
1571 report_error);
1572 } else
1573 report_error(ERR_NONFATAL,
1574 "bad syntax for EQU");
1576 } else {
1578 * Special `..' EQUs get processed here, except
1579 * `..@' macro processor EQUs which are done above.
1581 if (output_ins.label[0] == '.' &&
1582 output_ins.label[1] == '.' &&
1583 output_ins.label[2] != '@') {
1584 if (output_ins.operands == 1 &&
1585 (output_ins.oprs[0].type & IMMEDIATE)) {
1586 define_label(output_ins.label,
1587 output_ins.oprs[0].segment,
1588 output_ins.oprs[0].offset,
1589 NULL, false, false, ofmt,
1590 report_error);
1591 } else if (output_ins.operands == 2
1592 && (output_ins.oprs[0].
1593 type & IMMEDIATE)
1594 && (output_ins.oprs[0].type & COLON)
1595 && output_ins.oprs[0].segment ==
1596 NO_SEG
1597 && (output_ins.oprs[1].
1598 type & IMMEDIATE)
1599 && output_ins.oprs[1].segment ==
1600 NO_SEG) {
1601 define_label(output_ins.label,
1602 output_ins.oprs[0].
1603 offset | SEG_ABS,
1604 output_ins.oprs[1].offset,
1605 NULL, false, false, ofmt,
1606 report_error);
1607 } else
1608 report_error(ERR_NONFATAL,
1609 "bad syntax for EQU");
1612 } else { /* instruction isn't an EQU */
1614 if (pass1 == 1) {
1616 int64_t l = insn_size(location.segment, offs, sb, cpu,
1617 &output_ins, report_error);
1619 /* if (using_debug_info) && output_ins.opcode != -1) */
1620 if (using_debug_info)
1621 { /* fbk 03/25/01 */
1622 /* this is done here so we can do debug type info */
1623 int32_t typeinfo =
1624 TYS_ELEMENTS(output_ins.operands);
1625 switch (output_ins.opcode) {
1626 case I_RESB:
1627 typeinfo =
1628 TYS_ELEMENTS(output_ins.oprs[0].
1629 offset) | TY_BYTE;
1630 break;
1631 case I_RESW:
1632 typeinfo =
1633 TYS_ELEMENTS(output_ins.oprs[0].
1634 offset) | TY_WORD;
1635 break;
1636 case I_RESD:
1637 typeinfo =
1638 TYS_ELEMENTS(output_ins.oprs[0].
1639 offset) | TY_DWORD;
1640 break;
1641 case I_RESQ:
1642 typeinfo =
1643 TYS_ELEMENTS(output_ins.oprs[0].
1644 offset) | TY_QWORD;
1645 break;
1646 case I_REST:
1647 typeinfo =
1648 TYS_ELEMENTS(output_ins.oprs[0].
1649 offset) | TY_TBYTE;
1650 break;
1651 case I_RESO:
1652 typeinfo =
1653 TYS_ELEMENTS(output_ins.oprs[0].
1654 offset) | TY_OWORD;
1655 break;
1656 case I_RESY:
1657 typeinfo =
1658 TYS_ELEMENTS(output_ins.oprs[0].
1659 offset) | TY_YWORD;
1660 break;
1661 case I_DB:
1662 typeinfo |= TY_BYTE;
1663 break;
1664 case I_DW:
1665 typeinfo |= TY_WORD;
1666 break;
1667 case I_DD:
1668 if (output_ins.eops_float)
1669 typeinfo |= TY_FLOAT;
1670 else
1671 typeinfo |= TY_DWORD;
1672 break;
1673 case I_DQ:
1674 typeinfo |= TY_QWORD;
1675 break;
1676 case I_DT:
1677 typeinfo |= TY_TBYTE;
1678 break;
1679 case I_DO:
1680 typeinfo |= TY_OWORD;
1681 break;
1682 case I_DY:
1683 typeinfo |= TY_YWORD;
1684 break;
1685 default:
1686 typeinfo = TY_LABEL;
1690 ofmt->current_dfmt->debug_typevalue(typeinfo);
1693 if (l != -1) {
1694 offs += l;
1695 SET_CURR_OFFS(offs);
1698 * else l == -1 => invalid instruction, which will be
1699 * flagged as an error on pass 2
1702 } else {
1703 offs += assemble(location.segment, offs, sb, cpu,
1704 &output_ins, ofmt, report_error,
1705 &nasmlist);
1706 SET_CURR_OFFS(offs);
1709 } /* not an EQU */
1710 cleanup_insn(&output_ins);
1712 nasm_free(line);
1713 location.offset = offs = GET_CURR_OFFS;
1714 } /* end while (line = preproc->getline... */
1716 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1717 report_error(ERR_NONFATAL,
1718 "phase error detected at end of assembly.");
1720 if (pass1 == 1)
1721 preproc->cleanup(1);
1723 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1724 pass0++;
1725 } else if (global_offset_changed &&
1726 global_offset_changed < prev_offset_changed) {
1727 prev_offset_changed = global_offset_changed;
1728 stall_count = 0;
1729 } else {
1730 stall_count++;
1733 if (terminate_after_phase)
1734 break;
1736 if ((stall_count > 997) || (passn >= pass_max)) {
1737 /* We get here if the labels don't converge
1738 * Example: FOO equ FOO + 1
1740 report_error(ERR_NONFATAL,
1741 "Can't find valid values for all labels "
1742 "after %d passes, giving up.", passn);
1743 report_error(ERR_NONFATAL,
1744 "Possible causes: recursive EQUs, macro abuse.");
1745 break;
1749 preproc->cleanup(0);
1750 nasmlist.cleanup();
1751 if (!terminate_after_phase && opt_verbose_info) {
1752 /* -On and -Ov switches */
1753 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
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 (!nasm_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 (nasm_isspace(*buf))
1796 buf++; /* beppu - skip leading whitespace */
1797 *value = buf;
1798 while (*buf != ']')
1799 buf++;
1800 *buf++ = '\0';
1803 return find_directive(*directive);
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;
1823 char *currentfile = NULL;
1824 int32_t lineno = 0;
1826 if (is_suppressed_warning(severity))
1827 return;
1829 if (!(severity & ERR_NOFILE))
1830 src_get(&lineno, &currentfile);
1832 if (currentfile) {
1833 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1834 nasm_free(currentfile);
1835 } else {
1836 fputs("nasm: ", error_file);
1839 va_start(ap, fmt);
1840 report_error_common(severity, fmt, ap);
1841 va_end(ap);
1845 * MS style error reporting
1846 * This function prints an error message to error_file in the
1847 * style used by Visual C and some other Microsoft tools. An example
1848 * would be:
1849 * file.asm(50) : error: blah blah blah
1850 * where file.asm is the name of the file, 50 is the line number on
1851 * which the error occurs (or is detected) and "error:" is one of
1852 * the possible optional diagnostics -- it can be "error" or "warning"
1853 * or something else. Finally the line terminates with the actual
1854 * error message.
1856 * @param severity the severity of the warning or error
1857 * @param fmt the printf style format string
1859 static void report_error_vc(int severity, const char *fmt, ...)
1861 va_list ap;
1862 char *currentfile = NULL;
1863 int32_t lineno = 0;
1865 if (is_suppressed_warning(severity))
1866 return;
1868 if (!(severity & ERR_NOFILE))
1869 src_get(&lineno, &currentfile);
1871 if (currentfile) {
1872 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1873 nasm_free(currentfile);
1874 } else {
1875 fputs("nasm: ", error_file);
1878 va_start(ap, fmt);
1879 report_error_common(severity, fmt, ap);
1880 va_end(ap);
1884 * check for supressed warning
1885 * checks for suppressed warning or pass one only warning and we're
1886 * not in pass 1
1888 * @param severity the severity of the warning or error
1889 * @return true if we should abort error/warning printing
1891 static bool is_suppressed_warning(int severity)
1894 * See if it's a suppressed warning.
1896 return (severity & ERR_MASK) == ERR_WARNING &&
1897 (((severity & ERR_WARN_MASK) != 0 &&
1898 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1899 /* See if it's a pass-one only warning and we're not in pass one. */
1900 ((severity & ERR_PASS1) && pass0 != 1) ||
1901 ((severity & ERR_PASS2) && pass0 != 2));
1905 * common error reporting
1906 * This is the common back end of the error reporting schemes currently
1907 * implemented. It prints the nature of the warning and then the
1908 * specific error message to error_file and may or may not return. It
1909 * doesn't return if the error severity is a "panic" or "debug" type.
1911 * @param severity the severity of the warning or error
1912 * @param fmt the printf style format string
1914 static void report_error_common(int severity, const char *fmt,
1915 va_list args)
1917 char msg[1024];
1918 const char *pfx;
1920 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1921 case ERR_WARNING:
1922 pfx = "warning: ";
1923 break;
1924 case ERR_NONFATAL:
1925 pfx = "error: ";
1926 break;
1927 case ERR_FATAL:
1928 pfx = "fatal: ";
1929 break;
1930 case ERR_PANIC:
1931 pfx = "panic: ";
1932 break;
1933 case ERR_DEBUG:
1934 pfx = "debug: ";
1935 break;
1936 default:
1937 pfx = "";
1938 break;
1941 vsnprintf(msg, sizeof msg, fmt, args);
1943 fprintf(error_file, "%s%s\n", pfx, msg);
1945 if (*listname)
1946 nasmlist.error(severity, pfx, msg);
1948 if (severity & ERR_USAGE)
1949 want_usage = true;
1951 switch (severity & ERR_MASK) {
1952 case ERR_DEBUG:
1953 /* no further action, by definition */
1954 break;
1955 case ERR_WARNING:
1956 if (warning_on[0]) /* Treat warnings as errors */
1957 terminate_after_phase = true;
1958 break;
1959 case ERR_NONFATAL:
1960 terminate_after_phase = true;
1961 break;
1962 case ERR_FATAL:
1963 if (ofile) {
1964 fclose(ofile);
1965 remove(outname);
1966 ofile = NULL;
1968 if (want_usage)
1969 usage();
1970 exit(1); /* instantly die */
1971 break; /* placate silly compilers */
1972 case ERR_PANIC:
1973 fflush(NULL);
1974 /* abort(); *//* halt, catch fire, and dump core */
1975 exit(3);
1976 break;
1980 static void usage(void)
1982 fputs("type `nasm -h' for help\n", error_file);
1985 static void register_output_formats(void)
1987 ofmt = ofmt_register(report_error);
1990 #define BUF_DELTA 512
1992 static FILE *no_pp_fp;
1993 static efunc no_pp_err;
1994 static ListGen *no_pp_list;
1995 static int32_t no_pp_lineinc;
1997 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1998 ListGen * listgen, StrList **deplist)
2000 src_set_fname(nasm_strdup(file));
2001 src_set_linnum(0);
2002 no_pp_lineinc = 1;
2003 no_pp_err = error;
2004 no_pp_fp = fopen(file, "r");
2005 if (!no_pp_fp)
2006 no_pp_err(ERR_FATAL | ERR_NOFILE,
2007 "unable to open input file `%s'", file);
2008 no_pp_list = listgen;
2009 (void)pass; /* placate compilers */
2010 (void)eval; /* placate compilers */
2012 if (deplist) {
2013 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2014 sl->next = NULL;
2015 strcpy(sl->str, file);
2016 *deplist = sl;
2020 static char *no_pp_getline(void)
2022 char *buffer, *p, *q;
2023 int bufsize;
2025 bufsize = BUF_DELTA;
2026 buffer = nasm_malloc(BUF_DELTA);
2027 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2029 while (1) { /* Loop to handle %line */
2031 p = buffer;
2032 while (1) { /* Loop to handle long lines */
2033 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2034 if (!q)
2035 break;
2036 p += strlen(p);
2037 if (p > buffer && p[-1] == '\n')
2038 break;
2039 if (p - buffer > bufsize - 10) {
2040 int offset;
2041 offset = p - buffer;
2042 bufsize += BUF_DELTA;
2043 buffer = nasm_realloc(buffer, bufsize);
2044 p = buffer + offset;
2048 if (!q && p == buffer) {
2049 nasm_free(buffer);
2050 return NULL;
2054 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2055 * them are present at the end of the line.
2057 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2059 if (!nasm_strnicmp(buffer, "%line", 5)) {
2060 int32_t ln;
2061 int li;
2062 char *nm = nasm_malloc(strlen(buffer));
2063 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2064 nasm_free(src_set_fname(nm));
2065 src_set_linnum(ln);
2066 no_pp_lineinc = li;
2067 continue;
2069 nasm_free(nm);
2071 break;
2074 no_pp_list->line(LIST_READ, buffer);
2076 return buffer;
2079 static void no_pp_cleanup(int pass)
2081 (void)pass; /* placate GCC */
2082 fclose(no_pp_fp);
2085 static uint32_t get_cpu(char *value)
2087 if (!strcmp(value, "8086"))
2088 return IF_8086;
2089 if (!strcmp(value, "186"))
2090 return IF_186;
2091 if (!strcmp(value, "286"))
2092 return IF_286;
2093 if (!strcmp(value, "386"))
2094 return IF_386;
2095 if (!strcmp(value, "486"))
2096 return IF_486;
2097 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2098 return IF_PENT;
2099 if (!strcmp(value, "686") ||
2100 !nasm_stricmp(value, "ppro") ||
2101 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2102 return IF_P6;
2103 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2104 return IF_KATMAI;
2105 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2106 !nasm_stricmp(value, "willamette"))
2107 return IF_WILLAMETTE;
2108 if (!nasm_stricmp(value, "prescott"))
2109 return IF_PRESCOTT;
2110 if (!nasm_stricmp(value, "x64") ||
2111 !nasm_stricmp(value, "x86-64"))
2112 return IF_X86_64;
2113 if (!nasm_stricmp(value, "ia64") ||
2114 !nasm_stricmp(value, "ia-64") ||
2115 !nasm_stricmp(value, "itanium") ||
2116 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2117 return IF_IA64;
2119 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2120 "unknown 'cpu' type");
2122 return IF_PLEVEL; /* the maximum level */
2125 static int get_bits(char *value)
2127 int i;
2129 if ((i = atoi(value)) == 16)
2130 return i; /* set for a 16-bit segment */
2131 else if (i == 32) {
2132 if (cpu < IF_386) {
2133 report_error(ERR_NONFATAL,
2134 "cannot specify 32-bit segment on processor below a 386");
2135 i = 16;
2137 } else if (i == 64) {
2138 if (cpu < IF_X86_64) {
2139 report_error(ERR_NONFATAL,
2140 "cannot specify 64-bit segment on processor below an x86-64");
2141 i = 16;
2143 if (i != maxbits) {
2144 report_error(ERR_NONFATAL,
2145 "%s output format does not support 64-bit code",
2146 ofmt->shortname);
2147 i = 16;
2149 } else {
2150 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2151 "`%s' is not a valid segment size; must be 16, 32 or 64",
2152 value);
2153 i = 16;
2155 return i;
2158 /* end of nasm.c */