BR 2826669: update licensing information in README
[nasm.git] / nasm.c
blob8c7e271a562ef7e845b9d4efd7e9c725f1010d4f
1 /* ----------------------------------------------------------------------- *
2 *
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 * ----------------------------------------------------------------------- */
34 /*
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"
64 struct forwrefinfo { /* info held on forward refs. */
65 int lineno;
66 int operand;
69 static int get_bits(char *value);
70 static uint32_t get_cpu(char *cpu_str);
71 static void parse_cmdline(int, char **);
72 static void assemble_file(char *, StrList **);
73 static void register_output_formats(void);
74 static void report_error_gnu(int severity, const char *fmt, ...);
75 static void report_error_vc(int severity, const char *fmt, ...);
76 static void report_error_common(int severity, const char *fmt,
77 va_list args);
78 static bool is_suppressed_warning(int severity);
79 static void usage(void);
80 static efunc report_error;
82 static int using_debug_info, opt_verbose_info;
83 bool tasm_compatible_mode = false;
84 int pass0, passn;
85 int maxbits = 0;
86 int globalrel = 0;
88 time_t official_compile_time;
90 static char inname[FILENAME_MAX];
91 static char outname[FILENAME_MAX];
92 static char listname[FILENAME_MAX];
93 static char errname[FILENAME_MAX];
94 static int globallineno; /* for forward-reference tracking */
95 /* static int pass = 0; */
96 static struct ofmt *ofmt = NULL;
98 static FILE *error_file; /* Where to write error messages */
100 static FILE *ofile = NULL;
101 int optimizing = -1; /* number of optimization passes to take */
102 static int sb, cmd_sb = 16; /* by default */
103 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
104 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
105 int64_t global_offset_changed; /* referenced in labels.c */
106 int64_t prev_offset_changed;
107 int32_t stall_count;
109 static struct location location;
110 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
111 int32_t abs_seg; /* ABSOLUTE segment basis */
112 int32_t abs_offset; /* ABSOLUTE offset */
114 static struct RAA *offsets;
116 static struct SAA *forwrefs; /* keep track of forward references */
117 static const struct forwrefinfo *forwref;
119 static Preproc *preproc;
120 enum op_type {
121 op_normal, /* Preprocess and assemble */
122 op_preprocess, /* Preprocess only */
123 op_depend, /* Generate dependencies */
125 static enum op_type operating_mode;
126 /* Dependency flags */
127 static bool depend_emit_phony = false;
128 static bool depend_missing_ok = false;
129 static const char *depend_target = NULL;
130 static const char *depend_file = NULL;
133 * Which of the suppressible warnings are suppressed. Entry zero
134 * isn't an actual warning, but it used for -w+error/-Werror.
137 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
138 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
140 static const struct warning {
141 const char *name;
142 const char *help;
143 bool enabled;
144 } warnings[ERR_WARN_MAX+1] = {
145 {"error", "treat warnings as errors", false},
146 {"macro-params", "macro calls with wrong parameter count", true},
147 {"macro-selfref", "cyclic macro references", false},
148 {"macro-defaults", "macros with more default than optional parameters", true},
149 {"orphan-labels", "labels alone on lines without trailing `:'", true},
150 {"number-overflow", "numeric constant does not fit", true},
151 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
152 {"float-overflow", "floating point overflow", true},
153 {"float-denorm", "floating point denormal", false},
154 {"float-underflow", "floating point underflow", false},
155 {"float-toolong", "too many digits in floating-point number", true},
156 {"user", "%warning directives", true},
160 * This is a null preprocessor which just copies lines from input
161 * to output. It's used when someone explicitly requests that NASM
162 * not preprocess their source file.
165 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
166 static char *no_pp_getline(void);
167 static void no_pp_cleanup(int);
168 static Preproc no_pp = {
169 no_pp_reset,
170 no_pp_getline,
171 no_pp_cleanup
175 * get/set current offset...
177 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
178 raa_read(offsets,location.segment))
179 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
180 (void)(offsets=raa_write(offsets,location.segment,(x))))
182 static bool want_usage;
183 static bool terminate_after_phase;
184 int user_nolist = 0; /* fbk 9/2/00 */
186 static void nasm_fputs(const char *line, FILE * outfile)
188 if (outfile) {
189 fputs(line, outfile);
190 putc('\n', outfile);
191 } else
192 puts(line);
195 /* Convert a struct tm to a POSIX-style time constant */
196 static int64_t posix_mktime(struct tm *tm)
198 int64_t t;
199 int64_t y = tm->tm_year;
201 /* See IEEE 1003.1:2004, section 4.14 */
203 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
204 t += tm->tm_yday;
205 t *= 24;
206 t += tm->tm_hour;
207 t *= 60;
208 t += tm->tm_min;
209 t *= 60;
210 t += tm->tm_sec;
212 return t;
215 static void define_macros_early(void)
217 char temp[128];
218 struct tm lt, *lt_p, gm, *gm_p;
219 int64_t posix_time;
221 lt_p = localtime(&official_compile_time);
222 if (lt_p) {
223 lt = *lt_p;
225 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
226 pp_pre_define(temp);
227 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
228 pp_pre_define(temp);
229 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
230 pp_pre_define(temp);
231 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
232 pp_pre_define(temp);
235 gm_p = gmtime(&official_compile_time);
236 if (gm_p) {
237 gm = *gm_p;
239 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
240 pp_pre_define(temp);
241 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
242 pp_pre_define(temp);
243 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
244 pp_pre_define(temp);
245 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
246 pp_pre_define(temp);
249 if (gm_p)
250 posix_time = posix_mktime(&gm);
251 else if (lt_p)
252 posix_time = posix_mktime(&lt);
253 else
254 posix_time = 0;
256 if (posix_time) {
257 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
258 pp_pre_define(temp);
262 static void define_macros_late(void)
264 char temp[128];
266 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
267 ofmt->shortname);
268 pp_pre_define(temp);
271 static void emit_dependencies(StrList *list)
273 FILE *deps;
274 int linepos, len;
275 StrList *l, *nl;
277 if (depend_file && strcmp(depend_file, "-")) {
278 deps = fopen(depend_file, "w");
279 if (!deps) {
280 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
281 "unable to write dependency file `%s'", depend_file);
282 return;
284 } else {
285 deps = stdout;
288 linepos = fprintf(deps, "%s:", depend_target);
289 for (l = list; l; l = l->next) {
290 len = strlen(l->str);
291 if (linepos + len > 62) {
292 fprintf(deps, " \\\n ");
293 linepos = 1;
295 fprintf(deps, " %s", l->str);
296 linepos += len+1;
298 fprintf(deps, "\n\n");
300 for (l = list; l; l = nl) {
301 if (depend_emit_phony)
302 fprintf(deps, "%s:\n\n", l->str);
304 nl = l->next;
305 nasm_free(l);
308 if (deps != stdout)
309 fclose(deps);
312 int main(int argc, char **argv)
314 StrList *depend_list = NULL, **depend_ptr;
316 time(&official_compile_time);
318 pass0 = 0;
319 want_usage = terminate_after_phase = false;
320 report_error = report_error_gnu;
322 error_file = stderr;
324 tolower_init();
326 nasm_set_malloc_error(report_error);
327 offsets = raa_init();
328 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
330 preproc = &nasmpp;
331 operating_mode = op_normal;
333 seg_init();
335 register_output_formats();
337 /* Define some macros dependent on the runtime, but not
338 on the command line. */
339 define_macros_early();
341 parse_cmdline(argc, argv);
343 if (terminate_after_phase) {
344 if (want_usage)
345 usage();
346 return 1;
349 /* If debugging info is disabled, suppress any debug calls */
350 if (!using_debug_info)
351 ofmt->current_dfmt = &null_debug_form;
353 if (ofmt->stdmac)
354 pp_extra_stdmac(ofmt->stdmac);
355 parser_global_info(ofmt, &location);
356 eval_global_info(ofmt, lookup_label, &location);
358 /* define some macros dependent of command-line */
359 define_macros_late();
361 depend_ptr = (depend_file || (operating_mode == op_depend))
362 ? &depend_list : NULL;
363 if (!depend_target)
364 depend_target = outname;
366 switch (operating_mode) {
367 case op_depend:
369 char *line;
371 if (depend_missing_ok)
372 pp_include_path(NULL); /* "assume generated" */
374 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
375 depend_ptr);
376 if (outname[0] == '\0')
377 ofmt->filename(inname, outname, report_error);
378 ofile = NULL;
379 while ((line = preproc->getline()))
380 nasm_free(line);
381 preproc->cleanup(0);
383 break;
385 case op_preprocess:
387 char *line;
388 char *file_name = NULL;
389 int32_t prior_linnum = 0;
390 int lineinc = 0;
392 if (*outname) {
393 ofile = fopen(outname, "w");
394 if (!ofile)
395 report_error(ERR_FATAL | ERR_NOFILE,
396 "unable to open output file `%s'",
397 outname);
398 } else
399 ofile = NULL;
401 location.known = false;
403 /* pass = 1; */
404 preproc->reset(inname, 3, report_error, evaluate, &nasmlist,
405 depend_ptr);
407 while ((line = preproc->getline())) {
409 * We generate %line directives if needed for later programs
411 int32_t linnum = prior_linnum += lineinc;
412 int altline = src_get(&linnum, &file_name);
413 if (altline) {
414 if (altline == 1 && lineinc == 1)
415 nasm_fputs("", ofile);
416 else {
417 lineinc = (altline != -1 || lineinc != 1);
418 fprintf(ofile ? ofile : stdout,
419 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
420 file_name);
422 prior_linnum = linnum;
424 nasm_fputs(line, ofile);
425 nasm_free(line);
427 nasm_free(file_name);
428 preproc->cleanup(0);
429 if (ofile)
430 fclose(ofile);
431 if (ofile && terminate_after_phase)
432 remove(outname);
434 break;
436 case op_normal:
439 * We must call ofmt->filename _anyway_, even if the user
440 * has specified their own output file, because some
441 * formats (eg OBJ and COFF) use ofmt->filename to find out
442 * the name of the input file and then put that inside the
443 * file.
445 ofmt->filename(inname, outname, report_error);
447 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
448 if (!ofile) {
449 report_error(ERR_FATAL | ERR_NOFILE,
450 "unable to open output file `%s'", outname);
454 * We must call init_labels() before ofmt->init() since
455 * some object formats will want to define labels in their
456 * init routines. (eg OS/2 defines the FLAT group)
458 init_labels();
460 ofmt->init(ofile, report_error, define_label, evaluate);
461 ofmt->current_dfmt->init(ofmt, NULL, ofile, report_error);
463 assemble_file(inname, depend_ptr);
465 if (!terminate_after_phase) {
466 ofmt->cleanup(using_debug_info);
467 cleanup_labels();
468 } else {
470 * Despite earlier comments, we need this fclose.
471 * The object output drivers only fclose on cleanup,
472 * and we just skipped that.
474 fclose (ofile);
476 remove(outname);
479 break;
482 if (depend_list && !terminate_after_phase)
483 emit_dependencies(depend_list);
485 if (want_usage)
486 usage();
488 raa_free(offsets);
489 saa_free(forwrefs);
490 eval_cleanup();
491 stdscan_cleanup();
493 return terminate_after_phase;
497 * Get a parameter for a command line option.
498 * First arg must be in the form of e.g. -f...
500 static char *get_param(char *p, char *q, bool *advance)
502 *advance = false;
503 if (p[2]) { /* the parameter's in the option */
504 p += 2;
505 while (nasm_isspace(*p))
506 p++;
507 return p;
509 if (q && q[0]) {
510 *advance = true;
511 return q;
513 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
514 "option `-%c' requires an argument", p[1]);
515 return NULL;
519 * Copy a filename
521 static void copy_filename(char *dst, const char *src)
523 size_t len = strlen(src);
525 if (len >= (size_t)FILENAME_MAX) {
526 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
527 return;
529 strncpy(dst, src, FILENAME_MAX);
533 * Convert a string to Make-safe form
535 static char *quote_for_make(const char *str)
537 const char *p;
538 char *os, *q;
540 size_t n = 1; /* Terminating zero */
541 size_t nbs = 0;
543 if (!str)
544 return NULL;
546 for (p = str; *p; p++) {
547 switch (*p) {
548 case ' ':
549 case '\t':
550 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
551 n += nbs + 2;
552 nbs = 0;
553 break;
554 case '$':
555 case '#':
556 nbs = 0;
557 n += 2;
558 break;
559 case '\\':
560 nbs++;
561 n++;
562 break;
563 default:
564 nbs = 0;
565 n++;
566 break;
570 /* Convert N backslashes at the end of filename to 2N backslashes */
571 if (nbs)
572 n += nbs;
574 os = q = nasm_malloc(n);
576 nbs = 0;
577 for (p = str; *p; p++) {
578 switch (*p) {
579 case ' ':
580 case '\t':
581 while (nbs--)
582 *q++ = '\\';
583 *q++ = '\\';
584 *q++ = *p;
585 break;
586 case '$':
587 *q++ = *p;
588 *q++ = *p;
589 nbs = 0;
590 break;
591 case '#':
592 *q++ = '\\';
593 *q++ = *p;
594 nbs = 0;
595 break;
596 case '\\':
597 *q++ = *p;
598 nbs++;
599 break;
600 default:
601 *q++ = *p;
602 nbs = 0;
603 break;
606 while (nbs--)
607 *q++ = '\\';
609 *q = '\0';
611 return os;
614 struct textargs {
615 const char *label;
616 int value;
619 #define OPT_PREFIX 0
620 #define OPT_POSTFIX 1
621 struct textargs textopts[] = {
622 {"prefix", OPT_PREFIX},
623 {"postfix", OPT_POSTFIX},
624 {NULL, 0}
627 static bool stopoptions = false;
628 static bool process_arg(char *p, char *q)
630 char *param;
631 int i;
632 bool advance = false;
633 bool do_warn;
635 if (!p || !p[0])
636 return false;
638 if (p[0] == '-' && !stopoptions) {
639 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
640 /* These parameters take values */
641 if (!(param = get_param(p, q, &advance)))
642 return advance;
645 switch (p[1]) {
646 case 's':
647 error_file = stdout;
648 break;
650 case 'o': /* output file */
651 copy_filename(outname, param);
652 break;
654 case 'f': /* output format */
655 ofmt = ofmt_find(param);
656 if (!ofmt) {
657 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
658 "unrecognised output format `%s' - "
659 "use -hf for a list", param);
661 break;
663 case 'O': /* Optimization level */
665 int opt;
667 if (!*param) {
668 /* Naked -O == -Ox */
669 optimizing = INT_MAX >> 1; /* Almost unlimited */
670 } else {
671 while (*param) {
672 switch (*param) {
673 case '0': case '1': case '2': case '3': case '4':
674 case '5': case '6': case '7': case '8': case '9':
675 opt = strtoul(param, &param, 10);
677 /* -O0 -> optimizing == -1, 0.98 behaviour */
678 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
679 if (opt < 2)
680 optimizing = opt - 1;
681 else
682 optimizing = opt;
683 break;
685 case 'v':
686 case '+':
687 param++;
688 opt_verbose_info = true;
689 break;
691 case 'x':
692 param++;
693 optimizing = INT_MAX >> 1; /* Almost unlimited */
694 break;
696 default:
697 report_error(ERR_FATAL,
698 "unknown optimization option -O%c\n",
699 *param);
700 break;
704 break;
707 case 'p': /* pre-include */
708 case 'P':
709 pp_pre_include(param);
710 break;
712 case 'd': /* pre-define */
713 case 'D':
714 pp_pre_define(param);
715 break;
717 case 'u': /* un-define */
718 case 'U':
719 pp_pre_undefine(param);
720 break;
722 case 'i': /* include search path */
723 case 'I':
724 pp_include_path(param);
725 break;
727 case 'l': /* listing file */
728 copy_filename(listname, param);
729 break;
731 case 'Z': /* error messages file */
732 strcpy(errname, param);
733 break;
735 case 'F': /* specify debug format */
736 ofmt->current_dfmt = dfmt_find(ofmt, param);
737 if (!ofmt->current_dfmt) {
738 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
739 "unrecognized debug format `%s' for"
740 " output format `%s'",
741 param, ofmt->shortname);
743 using_debug_info = true;
744 break;
746 case 'X': /* specify error reporting format */
747 if (nasm_stricmp("vc", param) == 0)
748 report_error = report_error_vc;
749 else if (nasm_stricmp("gnu", param) == 0)
750 report_error = report_error_gnu;
751 else
752 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
753 "unrecognized error reporting format `%s'",
754 param);
755 break;
757 case 'g':
758 using_debug_info = true;
759 break;
761 case 'h':
762 printf
763 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
764 "[-l listfile]\n"
765 " [options...] [--] filename\n"
766 " or nasm -v for version info\n\n"
767 " -t assemble in SciTech TASM compatible mode\n"
768 " -g generate debug information in selected format.\n");
769 printf
770 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
771 " -a don't preprocess (assemble only)\n"
772 " -M generate Makefile dependencies on stdout\n"
773 " -MG d:o, missing files assumed generated\n\n"
774 " -Z<file> redirect error messages to file\n"
775 " -s redirect error messages to stdout\n\n"
776 " -F format select a debugging format\n\n"
777 " -I<path> adds a pathname to the include file path\n");
778 printf
779 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
780 " -P<file> pre-includes a file\n"
781 " -D<macro>[=<value>] pre-defines a macro\n"
782 " -U<macro> undefines a macro\n"
783 " -X<format> specifies error reporting format (gnu or vc)\n"
784 " -w+foo enables warning foo (equiv. -Wfoo)\n"
785 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
786 "Warnings:\n");
787 for (i = 0; i <= ERR_WARN_MAX; i++)
788 printf(" %-23s %s (default %s)\n",
789 warnings[i].name, warnings[i].help,
790 warnings[i].enabled ? "on" : "off");
791 printf
792 ("\nresponse files should contain command line parameters"
793 ", one per line.\n");
794 if (p[2] == 'f') {
795 printf("\nvalid output formats for -f are"
796 " (`*' denotes default):\n");
797 ofmt_list(ofmt, stdout);
798 } else {
799 printf("\nFor a list of valid output formats, use -hf.\n");
800 printf("For a list of debug formats, use -f <form> -y.\n");
802 exit(0); /* never need usage message here */
803 break;
805 case 'y':
806 printf("\nvalid debug formats for '%s' output format are"
807 " ('*' denotes default):\n", ofmt->shortname);
808 dfmt_list(ofmt, stdout);
809 exit(0);
810 break;
812 case 't':
813 tasm_compatible_mode = true;
814 break;
816 case 'v':
817 printf("NASM version %s compiled on %s%s\n",
818 nasm_version, nasm_date, nasm_compile_options);
819 exit(0); /* never need usage message here */
820 break;
822 case 'e': /* preprocess only */
823 case 'E':
824 operating_mode = op_preprocess;
825 break;
827 case 'a': /* assemble only - don't preprocess */
828 preproc = &no_pp;
829 break;
831 case 'W':
832 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
833 do_warn = false;
834 param += 3;
835 } else {
836 do_warn = true;
838 goto set_warning;
840 case 'w':
841 if (param[0] != '+' && param[0] != '-') {
842 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
843 "invalid option to `-w'");
844 break;
846 do_warn = (param[0] == '+');
847 param++;
848 goto set_warning;
849 set_warning:
850 for (i = 0; i <= ERR_WARN_MAX; i++)
851 if (!nasm_stricmp(param, warnings[i].name))
852 break;
853 if (i <= ERR_WARN_MAX)
854 warning_on_global[i] = do_warn;
855 else if (!nasm_stricmp(param, "all"))
856 for (i = 1; i <= ERR_WARN_MAX; i++)
857 warning_on_global[i] = do_warn;
858 else if (!nasm_stricmp(param, "none"))
859 for (i = 1; i <= ERR_WARN_MAX; i++)
860 warning_on_global[i] = !do_warn;
861 else
862 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
863 "invalid warning `%s'", param);
864 break;
866 case 'M':
867 switch (p[2]) {
868 case 0:
869 operating_mode = op_depend;
870 break;
871 case 'G':
872 operating_mode = op_depend;
873 depend_missing_ok = true;
874 break;
875 case 'P':
876 depend_emit_phony = true;
877 break;
878 case 'D':
879 depend_file = q;
880 advance = true;
881 break;
882 case 'T':
883 depend_target = q;
884 advance = true;
885 break;
886 case 'Q':
887 depend_target = quote_for_make(q);
888 advance = true;
889 break;
890 default:
891 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
892 "unknown dependency option `-M%c'", p[2]);
893 break;
895 if (advance && (!q || !q[0])) {
896 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
897 "option `-M%c' requires a parameter", p[2]);
898 break;
900 break;
902 case '-':
904 int s;
906 if (p[2] == 0) { /* -- => stop processing options */
907 stopoptions = 1;
908 break;
910 for (s = 0; textopts[s].label; s++) {
911 if (!nasm_stricmp(p + 2, textopts[s].label)) {
912 break;
916 switch (s) {
918 case OPT_PREFIX:
919 case OPT_POSTFIX:
921 if (!q) {
922 report_error(ERR_NONFATAL | ERR_NOFILE |
923 ERR_USAGE,
924 "option `--%s' requires an argument",
925 p + 2);
926 break;
927 } else {
928 advance = 1, param = q;
931 if (s == OPT_PREFIX) {
932 strncpy(lprefix, param, PREFIX_MAX - 1);
933 lprefix[PREFIX_MAX - 1] = 0;
934 break;
936 if (s == OPT_POSTFIX) {
937 strncpy(lpostfix, param, POSTFIX_MAX - 1);
938 lpostfix[POSTFIX_MAX - 1] = 0;
939 break;
941 break;
943 default:
945 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
946 "unrecognised option `--%s'", p + 2);
947 break;
950 break;
953 default:
954 if (!ofmt->setinfo(GI_SWITCH, &p))
955 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
956 "unrecognised option `-%c'", p[1]);
957 break;
959 } else {
960 if (*inname) {
961 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
962 "more than one input file specified");
963 } else {
964 copy_filename(inname, p);
968 return advance;
971 #define ARG_BUF_DELTA 128
973 static void process_respfile(FILE * rfile)
975 char *buffer, *p, *q, *prevarg;
976 int bufsize, prevargsize;
978 bufsize = prevargsize = ARG_BUF_DELTA;
979 buffer = nasm_malloc(ARG_BUF_DELTA);
980 prevarg = nasm_malloc(ARG_BUF_DELTA);
981 prevarg[0] = '\0';
983 while (1) { /* Loop to handle all lines in file */
984 p = buffer;
985 while (1) { /* Loop to handle long lines */
986 q = fgets(p, bufsize - (p - buffer), rfile);
987 if (!q)
988 break;
989 p += strlen(p);
990 if (p > buffer && p[-1] == '\n')
991 break;
992 if (p - buffer > bufsize - 10) {
993 int offset;
994 offset = p - buffer;
995 bufsize += ARG_BUF_DELTA;
996 buffer = nasm_realloc(buffer, bufsize);
997 p = buffer + offset;
1001 if (!q && p == buffer) {
1002 if (prevarg[0])
1003 process_arg(prevarg, NULL);
1004 nasm_free(buffer);
1005 nasm_free(prevarg);
1006 return;
1010 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1011 * them are present at the end of the line.
1013 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1015 while (p > buffer && nasm_isspace(p[-1]))
1016 *--p = '\0';
1018 p = buffer;
1019 while (nasm_isspace(*p))
1020 p++;
1022 if (process_arg(prevarg, p))
1023 *p = '\0';
1025 if ((int) strlen(p) > prevargsize - 10) {
1026 prevargsize += ARG_BUF_DELTA;
1027 prevarg = nasm_realloc(prevarg, prevargsize);
1029 strncpy(prevarg, p, prevargsize);
1033 /* Function to process args from a string of args, rather than the
1034 * argv array. Used by the environment variable and response file
1035 * processing.
1037 static void process_args(char *args)
1039 char *p, *q, *arg, *prevarg;
1040 char separator = ' ';
1042 p = args;
1043 if (*p && *p != '-')
1044 separator = *p++;
1045 arg = NULL;
1046 while (*p) {
1047 q = p;
1048 while (*p && *p != separator)
1049 p++;
1050 while (*p == separator)
1051 *p++ = '\0';
1052 prevarg = arg;
1053 arg = q;
1054 if (process_arg(prevarg, arg))
1055 arg = NULL;
1057 if (arg)
1058 process_arg(arg, NULL);
1061 static void process_response_file(const char *file)
1063 char str[2048];
1064 FILE *f = fopen(file, "r");
1065 if (!f) {
1066 perror(file);
1067 exit(-1);
1069 while (fgets(str, sizeof str, f)) {
1070 process_args(str);
1072 fclose(f);
1075 static void parse_cmdline(int argc, char **argv)
1077 FILE *rfile;
1078 char *envreal, *envcopy = NULL, *p, *arg;
1079 int i;
1081 *inname = *outname = *listname = *errname = '\0';
1082 for (i = 0; i <= ERR_WARN_MAX; i++)
1083 warning_on_global[i] = warnings[i].enabled;
1086 * First, process the NASMENV environment variable.
1088 envreal = getenv("NASMENV");
1089 arg = NULL;
1090 if (envreal) {
1091 envcopy = nasm_strdup(envreal);
1092 process_args(envcopy);
1093 nasm_free(envcopy);
1097 * Now process the actual command line.
1099 while (--argc) {
1100 bool advance;
1101 argv++;
1102 if (argv[0][0] == '@') {
1103 /* We have a response file, so process this as a set of
1104 * arguments like the environment variable. This allows us
1105 * to have multiple arguments on a single line, which is
1106 * different to the -@resp file processing below for regular
1107 * NASM.
1109 process_response_file(argv[0]+1);
1110 argc--;
1111 argv++;
1113 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1114 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1115 if (p) {
1116 rfile = fopen(p, "r");
1117 if (rfile) {
1118 process_respfile(rfile);
1119 fclose(rfile);
1120 } else
1121 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1122 "unable to open response file `%s'", p);
1124 } else
1125 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1126 argv += advance, argc -= advance;
1129 /* Look for basic command line typos. This definitely doesn't
1130 catch all errors, but it might help cases of fumbled fingers. */
1131 if (!*inname)
1132 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1133 "no input file specified");
1134 else if (!strcmp(inname, errname) ||
1135 !strcmp(inname, outname) ||
1136 !strcmp(inname, listname) ||
1137 (depend_file && !strcmp(inname, depend_file)))
1138 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1139 "file `%s' is both input and output file",
1140 inname);
1142 if (*errname) {
1143 error_file = fopen(errname, "w");
1144 if (!error_file) {
1145 error_file = stderr; /* Revert to default! */
1146 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1147 "cannot open file `%s' for error messages",
1148 errname);
1153 /* List of directives */
1154 enum directives {
1155 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1156 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1158 static const char *directives[] = {
1159 "", "absolute", "bits", "common", "cpu", "debug", "default",
1160 "extern", "float", "global", "list", "section", "segment", "warning"
1162 static enum directives getkw(char **directive, char **value);
1164 static void assemble_file(char *fname, StrList **depend_ptr)
1166 char *directive, *value, *p, *q, *special, *line, debugid[80];
1167 insn output_ins;
1168 int i, validid;
1169 bool rn_error;
1170 int32_t seg;
1171 int64_t offs;
1172 struct tokenval tokval;
1173 expr *e;
1174 int pass_max;
1176 if (cmd_sb == 32 && cmd_cpu < IF_386)
1177 report_error(ERR_FATAL, "command line: "
1178 "32-bit segment size requires a higher cpu");
1180 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1181 for (passn = 1; pass0 <= 2; passn++) {
1182 int pass1, pass2;
1183 ldfunc def_label;
1185 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1186 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1187 /* pass0 0, 0, 0, ..., 1, 2 */
1189 def_label = passn > 1 ? redefine_label : define_label;
1191 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1192 cpu = cmd_cpu;
1193 if (pass0 == 2) {
1194 if (*listname)
1195 nasmlist.init(listname, report_error);
1197 in_abs_seg = false;
1198 global_offset_changed = 0; /* set by redefine_label */
1199 location.segment = ofmt->section(NULL, pass2, &sb);
1200 globalbits = sb;
1201 if (passn > 1) {
1202 saa_rewind(forwrefs);
1203 forwref = saa_rstruct(forwrefs);
1204 raa_free(offsets);
1205 offsets = raa_init();
1207 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1208 pass1 == 2 ? depend_ptr : NULL);
1209 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1211 globallineno = 0;
1212 if (passn == 1)
1213 location.known = true;
1214 location.offset = offs = GET_CURR_OFFS;
1216 while ((line = preproc->getline())) {
1217 enum directives d;
1218 globallineno++;
1221 * Here we parse our directives; this is not handled by the
1222 * 'real' parser. This really should be a separate function.
1224 directive = line;
1225 d = getkw(&directive, &value);
1226 if (d) {
1227 int err = 0;
1229 switch (d) {
1230 case D_SEGMENT: /* [SEGMENT n] */
1231 case D_SECTION:
1232 seg = ofmt->section(value, pass2, &sb);
1233 if (seg == NO_SEG) {
1234 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1235 "segment name `%s' not recognized",
1236 value);
1237 } else {
1238 in_abs_seg = false;
1239 location.segment = seg;
1241 break;
1242 case D_EXTERN: /* [EXTERN label:special] */
1243 if (*value == '$')
1244 value++; /* skip initial $ if present */
1245 if (pass0 == 2) {
1246 q = value;
1247 while (*q && *q != ':')
1248 q++;
1249 if (*q == ':') {
1250 *q++ = '\0';
1251 ofmt->symdef(value, 0L, 0L, 3, q);
1253 } else if (passn == 1) {
1254 q = value;
1255 validid = true;
1256 if (!isidstart(*q))
1257 validid = false;
1258 while (*q && *q != ':') {
1259 if (!isidchar(*q))
1260 validid = false;
1261 q++;
1263 if (!validid) {
1264 report_error(ERR_NONFATAL,
1265 "identifier expected after EXTERN");
1266 break;
1268 if (*q == ':') {
1269 *q++ = '\0';
1270 special = q;
1271 } else
1272 special = NULL;
1273 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1274 int temp = pass0;
1275 pass0 = 1; /* fake pass 1 in labels.c */
1276 declare_as_global(value, special,
1277 report_error);
1278 define_label(value, seg_alloc(), 0L, NULL,
1279 false, true, ofmt, report_error);
1280 pass0 = temp;
1282 } /* else pass0 == 1 */
1283 break;
1284 case D_BITS: /* [BITS bits] */
1285 globalbits = sb = get_bits(value);
1286 break;
1287 case D_GLOBAL: /* [GLOBAL symbol:special] */
1288 if (*value == '$')
1289 value++; /* skip initial $ if present */
1290 if (pass0 == 2) { /* pass 2 */
1291 q = value;
1292 while (*q && *q != ':')
1293 q++;
1294 if (*q == ':') {
1295 *q++ = '\0';
1296 ofmt->symdef(value, 0L, 0L, 3, q);
1298 } else if (pass2 == 1) { /* pass == 1 */
1299 q = value;
1300 validid = true;
1301 if (!isidstart(*q))
1302 validid = false;
1303 while (*q && *q != ':') {
1304 if (!isidchar(*q))
1305 validid = false;
1306 q++;
1308 if (!validid) {
1309 report_error(ERR_NONFATAL,
1310 "identifier expected after GLOBAL");
1311 break;
1313 if (*q == ':') {
1314 *q++ = '\0';
1315 special = q;
1316 } else
1317 special = NULL;
1318 declare_as_global(value, special, report_error);
1319 } /* pass == 1 */
1320 break;
1321 case D_COMMON: /* [COMMON symbol size:special] */
1323 int64_t size;
1325 if (*value == '$')
1326 value++; /* skip initial $ if present */
1327 p = value;
1328 validid = true;
1329 if (!isidstart(*p))
1330 validid = false;
1331 while (*p && !nasm_isspace(*p)) {
1332 if (!isidchar(*p))
1333 validid = false;
1334 p++;
1336 if (!validid) {
1337 report_error(ERR_NONFATAL,
1338 "identifier expected after COMMON");
1339 break;
1341 if (*p) {
1342 while (*p && nasm_isspace(*p))
1343 *p++ = '\0';
1344 q = p;
1345 while (*q && *q != ':')
1346 q++;
1347 if (*q == ':') {
1348 *q++ = '\0';
1349 special = q;
1350 } else {
1351 special = NULL;
1353 size = readnum(p, &rn_error);
1354 if (rn_error) {
1355 report_error(ERR_NONFATAL,
1356 "invalid size specified"
1357 " in COMMON declaration");
1358 break;
1360 } else {
1361 report_error(ERR_NONFATAL,
1362 "no size specified in"
1363 " COMMON declaration");
1364 break;
1367 if (pass0 < 2) {
1368 define_common(value, seg_alloc(), size,
1369 special, ofmt, report_error);
1370 } else if (pass0 == 2) {
1371 if (special)
1372 ofmt->symdef(value, 0L, 0L, 3, special);
1374 break;
1376 case D_ABSOLUTE: /* [ABSOLUTE address] */
1377 stdscan_reset();
1378 stdscan_bufptr = value;
1379 tokval.t_type = TOKEN_INVALID;
1380 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1381 report_error, NULL);
1382 if (e) {
1383 if (!is_reloc(e))
1384 report_error(pass0 ==
1385 1 ? ERR_NONFATAL : ERR_PANIC,
1386 "cannot use non-relocatable expression as "
1387 "ABSOLUTE address");
1388 else {
1389 abs_seg = reloc_seg(e);
1390 abs_offset = reloc_value(e);
1392 } else if (passn == 1)
1393 abs_offset = 0x100; /* don't go near zero in case of / */
1394 else
1395 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1396 "in pass two");
1397 in_abs_seg = true;
1398 location.segment = NO_SEG;
1399 break;
1400 case D_DEBUG: /* [DEBUG] */
1401 p = value;
1402 q = debugid;
1403 validid = true;
1404 if (!isidstart(*p))
1405 validid = false;
1406 while (*p && !nasm_isspace(*p)) {
1407 if (!isidchar(*p))
1408 validid = false;
1409 *q++ = *p++;
1411 *q++ = 0;
1412 if (!validid) {
1413 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1414 "identifier expected after DEBUG");
1415 break;
1417 while (*p && nasm_isspace(*p))
1418 p++;
1419 if (pass0 == 2)
1420 ofmt->current_dfmt->debug_directive(debugid, p);
1421 break;
1422 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1423 while (*value && nasm_isspace(*value))
1424 value++;
1426 switch(*value) {
1427 case '-': validid = 0; value++; break;
1428 case '+': validid = 1; value++; break;
1429 case '*': validid = 2; value++; break;
1430 default: validid = 1; break;
1433 for (i = 1; i <= ERR_WARN_MAX; i++)
1434 if (!nasm_stricmp(value, warnings[i].name))
1435 break;
1436 if (i <= ERR_WARN_MAX) {
1437 switch(validid) {
1438 case 0:
1439 warning_on[i] = false;
1440 break;
1441 case 1:
1442 warning_on[i] = true;
1443 break;
1444 case 2:
1445 warning_on[i] = warning_on_global[i];
1446 break;
1449 else
1450 report_error(ERR_NONFATAL,
1451 "invalid warning id in WARNING directive");
1452 break;
1453 case D_CPU: /* [CPU] */
1454 cpu = get_cpu(value);
1455 break;
1456 case D_LIST: /* [LIST {+|-}] */
1457 while (*value && nasm_isspace(*value))
1458 value++;
1460 if (*value == '+') {
1461 user_nolist = 0;
1462 } else {
1463 if (*value == '-') {
1464 user_nolist = 1;
1465 } else {
1466 err = 1;
1469 break;
1470 case D_DEFAULT: /* [DEFAULT] */
1471 stdscan_reset();
1472 stdscan_bufptr = value;
1473 tokval.t_type = TOKEN_INVALID;
1474 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1475 switch ((int)tokval.t_integer) {
1476 case S_REL:
1477 globalrel = 1;
1478 break;
1479 case S_ABS:
1480 globalrel = 0;
1481 break;
1482 default:
1483 err = 1;
1484 break;
1486 } else {
1487 err = 1;
1489 break;
1490 case D_FLOAT:
1491 if (float_option(value)) {
1492 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1493 "unknown 'float' directive: %s",
1494 value);
1496 break;
1497 default:
1498 if (!ofmt->directive(directive, value, pass2))
1499 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1500 "unrecognised directive [%s]",
1501 directive);
1503 if (err) {
1504 report_error(ERR_NONFATAL,
1505 "invalid parameter to [%s] directive",
1506 directive);
1508 } else { /* it isn't a directive */
1510 parse_line(pass1, line, &output_ins,
1511 report_error, evaluate, def_label);
1513 if (optimizing > 0) {
1514 if (forwref != NULL && globallineno == forwref->lineno) {
1515 output_ins.forw_ref = true;
1516 do {
1517 output_ins.oprs[forwref->operand].opflags |=
1518 OPFLAG_FORWARD;
1519 forwref = saa_rstruct(forwrefs);
1520 } while (forwref != NULL
1521 && forwref->lineno == globallineno);
1522 } else
1523 output_ins.forw_ref = false;
1525 if (output_ins.forw_ref) {
1526 if (passn == 1) {
1527 for (i = 0; i < output_ins.operands; i++) {
1528 if (output_ins.oprs[i].
1529 opflags & OPFLAG_FORWARD) {
1530 struct forwrefinfo *fwinf =
1531 (struct forwrefinfo *)
1532 saa_wstruct(forwrefs);
1533 fwinf->lineno = globallineno;
1534 fwinf->operand = i;
1541 /* forw_ref */
1542 if (output_ins.opcode == I_EQU) {
1543 if (pass1 == 1) {
1545 * Special `..' EQUs get processed in pass two,
1546 * except `..@' macro-processor EQUs which are done
1547 * in the normal place.
1549 if (!output_ins.label)
1550 report_error(ERR_NONFATAL,
1551 "EQU not preceded by label");
1553 else if (output_ins.label[0] != '.' ||
1554 output_ins.label[1] != '.' ||
1555 output_ins.label[2] == '@') {
1556 if (output_ins.operands == 1 &&
1557 (output_ins.oprs[0].type & IMMEDIATE) &&
1558 output_ins.oprs[0].wrt == NO_SEG) {
1559 bool isext = !!(output_ins.oprs[0].opflags
1560 & OPFLAG_EXTERN);
1561 def_label(output_ins.label,
1562 output_ins.oprs[0].segment,
1563 output_ins.oprs[0].offset, NULL,
1564 false, isext, ofmt,
1565 report_error);
1566 } else if (output_ins.operands == 2
1567 && (output_ins.oprs[0].type & IMMEDIATE)
1568 && (output_ins.oprs[0].type & COLON)
1569 && output_ins.oprs[0].segment == NO_SEG
1570 && output_ins.oprs[0].wrt == NO_SEG
1571 && (output_ins.oprs[1].type & IMMEDIATE)
1572 && output_ins.oprs[1].segment == NO_SEG
1573 && output_ins.oprs[1].wrt == NO_SEG) {
1574 def_label(output_ins.label,
1575 output_ins.oprs[0].offset | SEG_ABS,
1576 output_ins.oprs[1].offset,
1577 NULL, false, false, ofmt,
1578 report_error);
1579 } else
1580 report_error(ERR_NONFATAL,
1581 "bad syntax for EQU");
1583 } else {
1585 * Special `..' EQUs get processed here, except
1586 * `..@' macro processor EQUs which are done above.
1588 if (output_ins.label[0] == '.' &&
1589 output_ins.label[1] == '.' &&
1590 output_ins.label[2] != '@') {
1591 if (output_ins.operands == 1 &&
1592 (output_ins.oprs[0].type & IMMEDIATE)) {
1593 define_label(output_ins.label,
1594 output_ins.oprs[0].segment,
1595 output_ins.oprs[0].offset,
1596 NULL, false, false, ofmt,
1597 report_error);
1598 } else if (output_ins.operands == 2
1599 && (output_ins.oprs[0].
1600 type & IMMEDIATE)
1601 && (output_ins.oprs[0].type & COLON)
1602 && output_ins.oprs[0].segment ==
1603 NO_SEG
1604 && (output_ins.oprs[1].
1605 type & IMMEDIATE)
1606 && output_ins.oprs[1].segment ==
1607 NO_SEG) {
1608 define_label(output_ins.label,
1609 output_ins.oprs[0].
1610 offset | SEG_ABS,
1611 output_ins.oprs[1].offset,
1612 NULL, false, false, ofmt,
1613 report_error);
1614 } else
1615 report_error(ERR_NONFATAL,
1616 "bad syntax for EQU");
1619 } else { /* instruction isn't an EQU */
1621 if (pass1 == 1) {
1623 int64_t l = insn_size(location.segment, offs, sb, cpu,
1624 &output_ins, report_error);
1626 /* if (using_debug_info) && output_ins.opcode != -1) */
1627 if (using_debug_info)
1628 { /* fbk 03/25/01 */
1629 /* this is done here so we can do debug type info */
1630 int32_t typeinfo =
1631 TYS_ELEMENTS(output_ins.operands);
1632 switch (output_ins.opcode) {
1633 case I_RESB:
1634 typeinfo =
1635 TYS_ELEMENTS(output_ins.oprs[0].
1636 offset) | TY_BYTE;
1637 break;
1638 case I_RESW:
1639 typeinfo =
1640 TYS_ELEMENTS(output_ins.oprs[0].
1641 offset) | TY_WORD;
1642 break;
1643 case I_RESD:
1644 typeinfo =
1645 TYS_ELEMENTS(output_ins.oprs[0].
1646 offset) | TY_DWORD;
1647 break;
1648 case I_RESQ:
1649 typeinfo =
1650 TYS_ELEMENTS(output_ins.oprs[0].
1651 offset) | TY_QWORD;
1652 break;
1653 case I_REST:
1654 typeinfo =
1655 TYS_ELEMENTS(output_ins.oprs[0].
1656 offset) | TY_TBYTE;
1657 break;
1658 case I_RESO:
1659 typeinfo =
1660 TYS_ELEMENTS(output_ins.oprs[0].
1661 offset) | TY_OWORD;
1662 break;
1663 case I_RESY:
1664 typeinfo =
1665 TYS_ELEMENTS(output_ins.oprs[0].
1666 offset) | TY_YWORD;
1667 break;
1668 case I_DB:
1669 typeinfo |= TY_BYTE;
1670 break;
1671 case I_DW:
1672 typeinfo |= TY_WORD;
1673 break;
1674 case I_DD:
1675 if (output_ins.eops_float)
1676 typeinfo |= TY_FLOAT;
1677 else
1678 typeinfo |= TY_DWORD;
1679 break;
1680 case I_DQ:
1681 typeinfo |= TY_QWORD;
1682 break;
1683 case I_DT:
1684 typeinfo |= TY_TBYTE;
1685 break;
1686 case I_DO:
1687 typeinfo |= TY_OWORD;
1688 break;
1689 case I_DY:
1690 typeinfo |= TY_YWORD;
1691 break;
1692 default:
1693 typeinfo = TY_LABEL;
1697 ofmt->current_dfmt->debug_typevalue(typeinfo);
1700 if (l != -1) {
1701 offs += l;
1702 SET_CURR_OFFS(offs);
1705 * else l == -1 => invalid instruction, which will be
1706 * flagged as an error on pass 2
1709 } else {
1710 offs += assemble(location.segment, offs, sb, cpu,
1711 &output_ins, ofmt, report_error,
1712 &nasmlist);
1713 SET_CURR_OFFS(offs);
1716 } /* not an EQU */
1717 cleanup_insn(&output_ins);
1719 nasm_free(line);
1720 location.offset = offs = GET_CURR_OFFS;
1721 } /* end while (line = preproc->getline... */
1723 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1724 report_error(ERR_NONFATAL,
1725 "phase error detected at end of assembly.");
1727 if (pass1 == 1)
1728 preproc->cleanup(1);
1730 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1731 pass0++;
1732 } else if (global_offset_changed &&
1733 global_offset_changed < prev_offset_changed) {
1734 prev_offset_changed = global_offset_changed;
1735 stall_count = 0;
1736 } else {
1737 stall_count++;
1740 if (terminate_after_phase)
1741 break;
1743 if ((stall_count > 997) || (passn >= pass_max)) {
1744 /* We get here if the labels don't converge
1745 * Example: FOO equ FOO + 1
1747 report_error(ERR_NONFATAL,
1748 "Can't find valid values for all labels "
1749 "after %d passes, giving up.", passn);
1750 report_error(ERR_NONFATAL,
1751 "Possible causes: recursive EQUs, macro abuse.");
1752 break;
1756 preproc->cleanup(0);
1757 nasmlist.cleanup();
1758 if (!terminate_after_phase && opt_verbose_info) {
1759 /* -On and -Ov switches */
1760 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1764 static enum directives getkw(char **directive, char **value)
1766 char *p, *q, *buf;
1768 buf = *directive;
1770 /* allow leading spaces or tabs */
1771 while (*buf == ' ' || *buf == '\t')
1772 buf++;
1774 if (*buf != '[')
1775 return 0;
1777 p = buf;
1779 while (*p && *p != ']')
1780 p++;
1782 if (!*p)
1783 return 0;
1785 q = p++;
1787 while (*p && *p != ';') {
1788 if (!nasm_isspace(*p))
1789 return 0;
1790 p++;
1792 q[1] = '\0';
1794 *directive = p = buf + 1;
1795 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1796 buf++;
1797 if (*buf == ']') {
1798 *buf = '\0';
1799 *value = buf;
1800 } else {
1801 *buf++ = '\0';
1802 while (nasm_isspace(*buf))
1803 buf++; /* beppu - skip leading whitespace */
1804 *value = buf;
1805 while (*buf != ']')
1806 buf++;
1807 *buf++ = '\0';
1810 return bsii(*directive, directives, elements(directives));
1814 * gnu style error reporting
1815 * This function prints an error message to error_file in the
1816 * style used by GNU. An example would be:
1817 * file.asm:50: error: blah blah blah
1818 * where file.asm is the name of the file, 50 is the line number on
1819 * which the error occurs (or is detected) and "error:" is one of
1820 * the possible optional diagnostics -- it can be "error" or "warning"
1821 * or something else. Finally the line terminates with the actual
1822 * error message.
1824 * @param severity the severity of the warning or error
1825 * @param fmt the printf style format string
1827 static void report_error_gnu(int severity, const char *fmt, ...)
1829 va_list ap;
1830 char *currentfile = NULL;
1831 int32_t lineno = 0;
1833 if (is_suppressed_warning(severity))
1834 return;
1836 if (!(severity & ERR_NOFILE))
1837 src_get(&lineno, &currentfile);
1839 if (currentfile) {
1840 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1841 nasm_free(currentfile);
1842 } else {
1843 fputs("nasm: ", error_file);
1846 va_start(ap, fmt);
1847 report_error_common(severity, fmt, ap);
1848 va_end(ap);
1852 * MS style error reporting
1853 * This function prints an error message to error_file in the
1854 * style used by Visual C and some other Microsoft tools. An example
1855 * would be:
1856 * file.asm(50) : error: blah blah blah
1857 * where file.asm is the name of the file, 50 is the line number on
1858 * which the error occurs (or is detected) and "error:" is one of
1859 * the possible optional diagnostics -- it can be "error" or "warning"
1860 * or something else. Finally the line terminates with the actual
1861 * error message.
1863 * @param severity the severity of the warning or error
1864 * @param fmt the printf style format string
1866 static void report_error_vc(int severity, const char *fmt, ...)
1868 va_list ap;
1869 char *currentfile = NULL;
1870 int32_t lineno = 0;
1872 if (is_suppressed_warning(severity))
1873 return;
1875 if (!(severity & ERR_NOFILE))
1876 src_get(&lineno, &currentfile);
1878 if (currentfile) {
1879 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1880 nasm_free(currentfile);
1881 } else {
1882 fputs("nasm: ", error_file);
1885 va_start(ap, fmt);
1886 report_error_common(severity, fmt, ap);
1887 va_end(ap);
1891 * check for supressed warning
1892 * checks for suppressed warning or pass one only warning and we're
1893 * not in pass 1
1895 * @param severity the severity of the warning or error
1896 * @return true if we should abort error/warning printing
1898 static bool is_suppressed_warning(int severity)
1901 * See if it's a suppressed warning.
1903 return (severity & ERR_MASK) == ERR_WARNING &&
1904 (((severity & ERR_WARN_MASK) != 0 &&
1905 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1906 /* See if it's a pass-one only warning and we're not in pass one. */
1907 ((severity & ERR_PASS1) && pass0 != 1) ||
1908 ((severity & ERR_PASS2) && pass0 != 2));
1912 * common error reporting
1913 * This is the common back end of the error reporting schemes currently
1914 * implemented. It prints the nature of the warning and then the
1915 * specific error message to error_file and may or may not return. It
1916 * doesn't return if the error severity is a "panic" or "debug" type.
1918 * @param severity the severity of the warning or error
1919 * @param fmt the printf style format string
1921 static void report_error_common(int severity, const char *fmt,
1922 va_list args)
1924 char msg[1024];
1925 const char *pfx;
1927 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1928 case ERR_WARNING:
1929 pfx = "warning: ";
1930 break;
1931 case ERR_NONFATAL:
1932 pfx = "error: ";
1933 break;
1934 case ERR_FATAL:
1935 pfx = "fatal: ";
1936 break;
1937 case ERR_PANIC:
1938 pfx = "panic: ";
1939 break;
1940 case ERR_DEBUG:
1941 pfx = "debug: ";
1942 break;
1943 default:
1944 pfx = "";
1945 break;
1948 vsnprintf(msg, sizeof msg, fmt, args);
1950 fprintf(error_file, "%s%s\n", pfx, msg);
1952 if (*listname)
1953 nasmlist.error(severity, pfx, msg);
1955 if (severity & ERR_USAGE)
1956 want_usage = true;
1958 switch (severity & ERR_MASK) {
1959 case ERR_DEBUG:
1960 /* no further action, by definition */
1961 break;
1962 case ERR_WARNING:
1963 if (warning_on[0]) /* Treat warnings as errors */
1964 terminate_after_phase = true;
1965 break;
1966 case ERR_NONFATAL:
1967 terminate_after_phase = true;
1968 break;
1969 case ERR_FATAL:
1970 if (ofile) {
1971 fclose(ofile);
1972 remove(outname);
1974 if (want_usage)
1975 usage();
1976 exit(1); /* instantly die */
1977 break; /* placate silly compilers */
1978 case ERR_PANIC:
1979 fflush(NULL);
1980 /* abort(); *//* halt, catch fire, and dump core */
1981 exit(3);
1982 break;
1986 static void usage(void)
1988 fputs("type `nasm -h' for help\n", error_file);
1991 static void register_output_formats(void)
1993 ofmt = ofmt_register(report_error);
1996 #define BUF_DELTA 512
1998 static FILE *no_pp_fp;
1999 static efunc no_pp_err;
2000 static ListGen *no_pp_list;
2001 static int32_t no_pp_lineinc;
2003 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
2004 ListGen * listgen, StrList **deplist)
2006 src_set_fname(nasm_strdup(file));
2007 src_set_linnum(0);
2008 no_pp_lineinc = 1;
2009 no_pp_err = error;
2010 no_pp_fp = fopen(file, "r");
2011 if (!no_pp_fp)
2012 no_pp_err(ERR_FATAL | ERR_NOFILE,
2013 "unable to open input file `%s'", file);
2014 no_pp_list = listgen;
2015 (void)pass; /* placate compilers */
2016 (void)eval; /* placate compilers */
2018 if (deplist) {
2019 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2020 sl->next = NULL;
2021 strcpy(sl->str, file);
2022 *deplist = sl;
2026 static char *no_pp_getline(void)
2028 char *buffer, *p, *q;
2029 int bufsize;
2031 bufsize = BUF_DELTA;
2032 buffer = nasm_malloc(BUF_DELTA);
2033 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2035 while (1) { /* Loop to handle %line */
2037 p = buffer;
2038 while (1) { /* Loop to handle long lines */
2039 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2040 if (!q)
2041 break;
2042 p += strlen(p);
2043 if (p > buffer && p[-1] == '\n')
2044 break;
2045 if (p - buffer > bufsize - 10) {
2046 int offset;
2047 offset = p - buffer;
2048 bufsize += BUF_DELTA;
2049 buffer = nasm_realloc(buffer, bufsize);
2050 p = buffer + offset;
2054 if (!q && p == buffer) {
2055 nasm_free(buffer);
2056 return NULL;
2060 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2061 * them are present at the end of the line.
2063 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2065 if (!nasm_strnicmp(buffer, "%line", 5)) {
2066 int32_t ln;
2067 int li;
2068 char *nm = nasm_malloc(strlen(buffer));
2069 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2070 nasm_free(src_set_fname(nm));
2071 src_set_linnum(ln);
2072 no_pp_lineinc = li;
2073 continue;
2075 nasm_free(nm);
2077 break;
2080 no_pp_list->line(LIST_READ, buffer);
2082 return buffer;
2085 static void no_pp_cleanup(int pass)
2087 (void)pass; /* placate GCC */
2088 fclose(no_pp_fp);
2091 static uint32_t get_cpu(char *value)
2093 if (!strcmp(value, "8086"))
2094 return IF_8086;
2095 if (!strcmp(value, "186"))
2096 return IF_186;
2097 if (!strcmp(value, "286"))
2098 return IF_286;
2099 if (!strcmp(value, "386"))
2100 return IF_386;
2101 if (!strcmp(value, "486"))
2102 return IF_486;
2103 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2104 return IF_PENT;
2105 if (!strcmp(value, "686") ||
2106 !nasm_stricmp(value, "ppro") ||
2107 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2108 return IF_P6;
2109 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2110 return IF_KATMAI;
2111 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2112 !nasm_stricmp(value, "willamette"))
2113 return IF_WILLAMETTE;
2114 if (!nasm_stricmp(value, "prescott"))
2115 return IF_PRESCOTT;
2116 if (!nasm_stricmp(value, "x64") ||
2117 !nasm_stricmp(value, "x86-64"))
2118 return IF_X86_64;
2119 if (!nasm_stricmp(value, "ia64") ||
2120 !nasm_stricmp(value, "ia-64") ||
2121 !nasm_stricmp(value, "itanium") ||
2122 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2123 return IF_IA64;
2125 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2126 "unknown 'cpu' type");
2128 return IF_PLEVEL; /* the maximum level */
2131 static int get_bits(char *value)
2133 int i;
2135 if ((i = atoi(value)) == 16)
2136 return i; /* set for a 16-bit segment */
2137 else if (i == 32) {
2138 if (cpu < IF_386) {
2139 report_error(ERR_NONFATAL,
2140 "cannot specify 32-bit segment on processor below a 386");
2141 i = 16;
2143 } else if (i == 64) {
2144 if (cpu < IF_X86_64) {
2145 report_error(ERR_NONFATAL,
2146 "cannot specify 64-bit segment on processor below an x86-64");
2147 i = 16;
2149 if (i != maxbits) {
2150 report_error(ERR_NONFATAL,
2151 "%s output format does not support 64-bit code",
2152 ofmt->shortname);
2153 i = 16;
2155 } else {
2156 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2157 "`%s' is not a valid segment size; must be 16, 32 or 64",
2158 value);
2159 i = 16;
2161 return i;
2164 /* end of nasm.c */