Use proper bracing on setting warnings in comman line parsing
[nasm.git] / nasm.c
blobda6f8bf9cdd9546373c5983628054188ad2d8a19
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2011 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"
65 * This is the maximum number of optimization passes to do. If we ever
66 * find a case where the optimizer doesn't naturally converge, we might
67 * have to drop this value so the assembler doesn't appear to just hang.
69 #define MAX_OPTIMIZE (INT_MAX >> 1)
71 struct forwrefinfo { /* info held on forward refs. */
72 int lineno;
73 int operand;
76 static int get_bits(char *value);
77 static uint32_t get_cpu(char *cpu_str);
78 static void parse_cmdline(int, char **);
79 static void assemble_file(char *, StrList **);
80 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
81 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
82 static void nasm_verror_common(int severity, const char *fmt, va_list args);
83 static bool is_suppressed_warning(int severity);
84 static void usage(void);
86 static int using_debug_info, opt_verbose_info;
87 bool tasm_compatible_mode = false;
88 int pass0, passn;
89 int maxbits = 0;
90 int globalrel = 0;
92 static time_t official_compile_time;
94 static char inname[FILENAME_MAX];
95 static char outname[FILENAME_MAX];
96 static char listname[FILENAME_MAX];
97 static char errname[FILENAME_MAX];
98 static int globallineno; /* for forward-reference tracking */
99 /* static int pass = 0; */
100 struct ofmt *ofmt = &OF_DEFAULT;
101 struct ofmt_alias *ofmt_alias = NULL;
102 const struct dfmt *dfmt;
104 static FILE *error_file; /* Where to write error messages */
106 FILE *ofile = NULL;
107 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
108 static int sb, cmd_sb = 16; /* by default */
109 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
110 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
111 int64_t global_offset_changed; /* referenced in labels.c */
112 int64_t prev_offset_changed;
113 int32_t stall_count;
115 static struct location location;
116 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
117 int32_t abs_seg; /* ABSOLUTE segment basis */
118 int32_t abs_offset; /* ABSOLUTE offset */
120 static struct RAA *offsets;
122 static struct SAA *forwrefs; /* keep track of forward references */
123 static const struct forwrefinfo *forwref;
125 static struct preproc_ops *preproc;
127 enum op_type {
128 op_normal, /* Preprocess and assemble */
129 op_preprocess, /* Preprocess only */
130 op_depend, /* Generate dependencies */
132 static enum op_type operating_mode;
133 /* Dependency flags */
134 static bool depend_emit_phony = false;
135 static bool depend_missing_ok = false;
136 static const char *depend_target = NULL;
137 static const char *depend_file = NULL;
140 * Which of the suppressible warnings are suppressed. Entry zero
141 * isn't an actual warning, but it used for -w+error/-Werror.
144 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
145 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
147 static const struct warning {
148 const char *name;
149 const char *help;
150 bool enabled;
151 } warnings[ERR_WARN_MAX+1] = {
152 {"error", "treat warnings as errors", false},
153 {"macro-params", "macro calls with wrong parameter count", true},
154 {"macro-selfref", "cyclic macro references", false},
155 {"macro-defaults", "macros with more default than optional parameters", true},
156 {"orphan-labels", "labels alone on lines without trailing `:'", true},
157 {"number-overflow", "numeric constant does not fit", true},
158 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
159 {"float-overflow", "floating point overflow", true},
160 {"float-denorm", "floating point denormal", false},
161 {"float-underflow", "floating point underflow", false},
162 {"float-toolong", "too many digits in floating-point number", true},
163 {"user", "%warning directives", true},
167 * This is a null preprocessor which just copies lines from input
168 * to output. It's used when someone explicitly requests that NASM
169 * not preprocess their source file.
172 static void no_pp_reset(char *file, int pass, ListGen *listgen, StrList **deplist);
173 static char *no_pp_getline(void);
174 static void no_pp_cleanup(int pass);
176 static struct preproc_ops no_pp = {
177 no_pp_reset,
178 no_pp_getline,
179 no_pp_cleanup
183 * get/set current offset...
185 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
186 raa_read(offsets,location.segment))
187 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
188 (void)(offsets=raa_write(offsets,location.segment,(x))))
190 static bool want_usage;
191 static bool terminate_after_phase;
192 int user_nolist = 0; /* fbk 9/2/00 */
194 static void nasm_fputs(const char *line, FILE * outfile)
196 if (outfile) {
197 fputs(line, outfile);
198 putc('\n', outfile);
199 } else
200 puts(line);
203 /* Convert a struct tm to a POSIX-style time constant */
204 static int64_t posix_mktime(struct tm *tm)
206 int64_t t;
207 int64_t y = tm->tm_year;
209 /* See IEEE 1003.1:2004, section 4.14 */
211 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
212 t += tm->tm_yday;
213 t *= 24;
214 t += tm->tm_hour;
215 t *= 60;
216 t += tm->tm_min;
217 t *= 60;
218 t += tm->tm_sec;
220 return t;
223 static void define_macros_early(void)
225 char temp[128];
226 struct tm lt, *lt_p, gm, *gm_p;
227 int64_t posix_time;
229 lt_p = localtime(&official_compile_time);
230 if (lt_p) {
231 lt = *lt_p;
233 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
234 pp_pre_define(temp);
235 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
236 pp_pre_define(temp);
237 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
238 pp_pre_define(temp);
239 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
240 pp_pre_define(temp);
243 gm_p = gmtime(&official_compile_time);
244 if (gm_p) {
245 gm = *gm_p;
247 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
248 pp_pre_define(temp);
249 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
250 pp_pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
252 pp_pre_define(temp);
253 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
254 pp_pre_define(temp);
257 if (gm_p)
258 posix_time = posix_mktime(&gm);
259 else if (lt_p)
260 posix_time = posix_mktime(&lt);
261 else
262 posix_time = 0;
264 if (posix_time) {
265 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
266 pp_pre_define(temp);
270 static void define_macros_late(void)
272 char temp[128];
275 * In case if output format is defined by alias
276 * we have to put shortname of the alias itself here
277 * otherwise ABI backward compatibility gets broken.
279 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
280 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
281 pp_pre_define(temp);
284 static void emit_dependencies(StrList *list)
286 FILE *deps;
287 int linepos, len;
288 StrList *l, *nl;
290 if (depend_file && strcmp(depend_file, "-")) {
291 deps = fopen(depend_file, "w");
292 if (!deps) {
293 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
294 "unable to write dependency file `%s'", depend_file);
295 return;
297 } else {
298 deps = stdout;
301 linepos = fprintf(deps, "%s:", depend_target);
302 list_for_each(l, list) {
303 len = strlen(l->str);
304 if (linepos + len > 62) {
305 fprintf(deps, " \\\n ");
306 linepos = 1;
308 fprintf(deps, " %s", l->str);
309 linepos += len+1;
311 fprintf(deps, "\n\n");
313 list_for_each_safe(l, nl, list) {
314 if (depend_emit_phony)
315 fprintf(deps, "%s:\n\n", l->str);
316 nasm_free(l);
319 if (deps != stdout)
320 fclose(deps);
323 int main(int argc, char **argv)
325 StrList *depend_list = NULL, **depend_ptr;
327 time(&official_compile_time);
329 pass0 = 0;
330 want_usage = terminate_after_phase = false;
331 nasm_set_verror(nasm_verror_gnu);
333 error_file = stderr;
335 tolower_init();
337 nasm_init_malloc_error();
338 offsets = raa_init();
339 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
341 preproc = &nasmpp;
342 operating_mode = op_normal;
344 seg_init();
346 /* Define some macros dependent on the runtime, but not
347 on the command line. */
348 define_macros_early();
350 parse_cmdline(argc, argv);
352 if (terminate_after_phase) {
353 if (want_usage)
354 usage();
355 return 1;
358 /* If debugging info is disabled, suppress any debug calls */
359 if (!using_debug_info)
360 ofmt->current_dfmt = &null_debug_form;
362 if (ofmt->stdmac)
363 pp_extra_stdmac(ofmt->stdmac);
364 parser_global_info(&location);
365 eval_global_info(ofmt, lookup_label, &location);
367 /* define some macros dependent of command-line */
368 define_macros_late();
370 depend_ptr = (depend_file || (operating_mode == op_depend))
371 ? &depend_list : NULL;
372 if (!depend_target)
373 depend_target = outname;
375 switch (operating_mode) {
376 case op_depend:
378 char *line;
380 if (depend_missing_ok)
381 pp_include_path(NULL); /* "assume generated" */
383 preproc->reset(inname, 0, &nasmlist, depend_ptr);
384 if (outname[0] == '\0')
385 ofmt->filename(inname, outname);
386 ofile = NULL;
387 while ((line = preproc->getline()))
388 nasm_free(line);
389 preproc->cleanup(0);
391 break;
393 case op_preprocess:
395 char *line;
396 char *file_name = NULL;
397 int32_t prior_linnum = 0;
398 int lineinc = 0;
400 if (*outname) {
401 ofile = fopen(outname, "w");
402 if (!ofile)
403 nasm_error(ERR_FATAL | ERR_NOFILE,
404 "unable to open output file `%s'",
405 outname);
406 } else
407 ofile = NULL;
409 location.known = false;
411 /* pass = 1; */
412 preproc->reset(inname, 3, &nasmlist, depend_ptr);
414 while ((line = preproc->getline())) {
416 * We generate %line directives if needed for later programs
418 int32_t linnum = prior_linnum += lineinc;
419 int altline = src_get(&linnum, &file_name);
420 if (altline) {
421 if (altline == 1 && lineinc == 1)
422 nasm_fputs("", ofile);
423 else {
424 lineinc = (altline != -1 || lineinc != 1);
425 fprintf(ofile ? ofile : stdout,
426 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
427 file_name);
429 prior_linnum = linnum;
431 nasm_fputs(line, ofile);
432 nasm_free(line);
434 nasm_free(file_name);
435 preproc->cleanup(0);
436 if (ofile)
437 fclose(ofile);
438 if (ofile && terminate_after_phase)
439 remove(outname);
440 ofile = NULL;
442 break;
444 case op_normal:
447 * We must call ofmt->filename _anyway_, even if the user
448 * has specified their own output file, because some
449 * formats (eg OBJ and COFF) use ofmt->filename to find out
450 * the name of the input file and then put that inside the
451 * file.
453 ofmt->filename(inname, outname);
455 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
456 if (!ofile) {
457 nasm_error(ERR_FATAL | ERR_NOFILE,
458 "unable to open output file `%s'", outname);
462 * We must call init_labels() before ofmt->init() since
463 * some object formats will want to define labels in their
464 * init routines. (eg OS/2 defines the FLAT group)
466 init_labels();
468 ofmt->init();
469 dfmt = ofmt->current_dfmt;
470 dfmt->init();
472 assemble_file(inname, depend_ptr);
474 if (!terminate_after_phase) {
475 ofmt->cleanup(using_debug_info);
476 cleanup_labels();
477 fflush(ofile);
478 if (ferror(ofile)) {
479 nasm_error(ERR_NONFATAL|ERR_NOFILE,
480 "write error on output file `%s'", outname);
484 if (ofile) {
485 fclose(ofile);
486 if (terminate_after_phase)
487 remove(outname);
488 ofile = NULL;
491 break;
494 if (depend_list && !terminate_after_phase)
495 emit_dependencies(depend_list);
497 if (want_usage)
498 usage();
500 raa_free(offsets);
501 saa_free(forwrefs);
502 eval_cleanup();
503 stdscan_cleanup();
505 return terminate_after_phase;
509 * Get a parameter for a command line option.
510 * First arg must be in the form of e.g. -f...
512 static char *get_param(char *p, char *q, bool *advance)
514 *advance = false;
515 if (p[2]) /* the parameter's in the option */
516 return nasm_skip_spaces(p + 2);
517 if (q && q[0]) {
518 *advance = true;
519 return q;
521 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
522 "option `-%c' requires an argument", p[1]);
523 return NULL;
527 * Copy a filename
529 static void copy_filename(char *dst, const char *src)
531 size_t len = strlen(src);
533 if (len >= (size_t)FILENAME_MAX) {
534 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
535 return;
537 strncpy(dst, src, FILENAME_MAX);
541 * Convert a string to Make-safe form
543 static char *quote_for_make(const char *str)
545 const char *p;
546 char *os, *q;
548 size_t n = 1; /* Terminating zero */
549 size_t nbs = 0;
551 if (!str)
552 return NULL;
554 for (p = str; *p; p++) {
555 switch (*p) {
556 case ' ':
557 case '\t':
558 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
559 n += nbs + 2;
560 nbs = 0;
561 break;
562 case '$':
563 case '#':
564 nbs = 0;
565 n += 2;
566 break;
567 case '\\':
568 nbs++;
569 n++;
570 break;
571 default:
572 nbs = 0;
573 n++;
574 break;
578 /* Convert N backslashes at the end of filename to 2N backslashes */
579 if (nbs)
580 n += nbs;
582 os = q = nasm_malloc(n);
584 nbs = 0;
585 for (p = str; *p; p++) {
586 switch (*p) {
587 case ' ':
588 case '\t':
589 while (nbs--)
590 *q++ = '\\';
591 *q++ = '\\';
592 *q++ = *p;
593 break;
594 case '$':
595 *q++ = *p;
596 *q++ = *p;
597 nbs = 0;
598 break;
599 case '#':
600 *q++ = '\\';
601 *q++ = *p;
602 nbs = 0;
603 break;
604 case '\\':
605 *q++ = *p;
606 nbs++;
607 break;
608 default:
609 *q++ = *p;
610 nbs = 0;
611 break;
614 while (nbs--)
615 *q++ = '\\';
617 *q = '\0';
619 return os;
622 struct textargs {
623 const char *label;
624 int value;
627 #define OPT_PREFIX 0
628 #define OPT_POSTFIX 1
629 struct textargs textopts[] = {
630 {"prefix", OPT_PREFIX},
631 {"postfix", OPT_POSTFIX},
632 {NULL, 0}
635 static bool stopoptions = false;
636 static bool process_arg(char *p, char *q)
638 char *param;
639 int i;
640 bool advance = false;
641 bool do_warn;
643 if (!p || !p[0])
644 return false;
646 if (p[0] == '-' && !stopoptions) {
647 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
648 /* These parameters take values */
649 if (!(param = get_param(p, q, &advance)))
650 return advance;
653 switch (p[1]) {
654 case 's':
655 error_file = stdout;
656 break;
658 case 'o': /* output file */
659 copy_filename(outname, param);
660 break;
662 case 'f': /* output format */
663 ofmt = ofmt_find(param, &ofmt_alias);
664 if (!ofmt) {
665 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
666 "unrecognised output format `%s' - "
667 "use -hf for a list", param);
669 break;
671 case 'O': /* Optimization level */
673 int opt;
675 if (!*param) {
676 /* Naked -O == -Ox */
677 optimizing = MAX_OPTIMIZE;
678 } else {
679 while (*param) {
680 switch (*param) {
681 case '0': case '1': case '2': case '3': case '4':
682 case '5': case '6': case '7': case '8': case '9':
683 opt = strtoul(param, &param, 10);
685 /* -O0 -> optimizing == -1, 0.98 behaviour */
686 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
687 if (opt < 2)
688 optimizing = opt - 1;
689 else
690 optimizing = opt;
691 break;
693 case 'v':
694 case '+':
695 param++;
696 opt_verbose_info = true;
697 break;
699 case 'x':
700 param++;
701 optimizing = MAX_OPTIMIZE;
702 break;
704 default:
705 nasm_error(ERR_FATAL,
706 "unknown optimization option -O%c\n",
707 *param);
708 break;
711 if (optimizing > MAX_OPTIMIZE)
712 optimizing = MAX_OPTIMIZE;
714 break;
717 case 'p': /* pre-include */
718 case 'P':
719 pp_pre_include(param);
720 break;
722 case 'd': /* pre-define */
723 case 'D':
724 pp_pre_define(param);
725 break;
727 case 'u': /* un-define */
728 case 'U':
729 pp_pre_undefine(param);
730 break;
732 case 'i': /* include search path */
733 case 'I':
734 pp_include_path(param);
735 break;
737 case 'l': /* listing file */
738 copy_filename(listname, param);
739 break;
741 case 'Z': /* error messages file */
742 copy_filename(errname, param);
743 break;
745 case 'F': /* specify debug format */
746 ofmt->current_dfmt = dfmt_find(ofmt, param);
747 if (!ofmt->current_dfmt) {
748 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
749 "unrecognized debug format `%s' for"
750 " output format `%s'",
751 param, ofmt->shortname);
753 using_debug_info = true;
754 break;
756 case 'X': /* specify error reporting format */
757 if (nasm_stricmp("vc", param) == 0)
758 nasm_set_verror(nasm_verror_vc);
759 else if (nasm_stricmp("gnu", param) == 0)
760 nasm_set_verror(nasm_verror_gnu);
761 else
762 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
763 "unrecognized error reporting format `%s'",
764 param);
765 break;
767 case 'g':
768 using_debug_info = true;
769 break;
771 case 'h':
772 printf
773 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
774 "[-l listfile]\n"
775 " [options...] [--] filename\n"
776 " or nasm -v for version info\n\n"
777 " -t assemble in SciTech TASM compatible mode\n"
778 " -g generate debug information in selected format\n");
779 printf
780 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
781 " -a don't preprocess (assemble only)\n"
782 " -M generate Makefile dependencies on stdout\n"
783 " -MG d:o, missing files assumed generated\n"
784 " -MF <file> set Makefile dependency file\n"
785 " -MD <file> assemble and generate dependencies\n"
786 " -MT <file> dependency target name\n"
787 " -MQ <file> dependency target name (quoted)\n"
788 " -MP emit phony target\n\n"
789 " -Z<file> redirect error messages to file\n"
790 " -s redirect error messages to stdout\n\n"
791 " -F format select a debugging format\n\n"
792 " -I<path> adds a pathname to the include file path\n");
793 printf
794 (" -O<digit> optimize branch offsets\n"
795 " -O0: No optimization (default)\n"
796 " -O1: Minimal optimization\n"
797 " -Ox: Multipass optimization (recommended)\n\n"
798 " -P<file> pre-includes a file\n"
799 " -D<macro>[=<value>] pre-defines a macro\n"
800 " -U<macro> undefines a macro\n"
801 " -X<format> specifies error reporting format (gnu or vc)\n"
802 " -w+foo enables warning foo (equiv. -Wfoo)\n"
803 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
804 "--prefix,--postfix\n"
805 " this options prepend or append the given argument to all\n"
806 " extern and global variables\n\n"
807 "Warnings:\n");
808 for (i = 0; i <= ERR_WARN_MAX; i++)
809 printf(" %-23s %s (default %s)\n",
810 warnings[i].name, warnings[i].help,
811 warnings[i].enabled ? "on" : "off");
812 printf
813 ("\nresponse files should contain command line parameters"
814 ", one per line.\n");
815 if (p[2] == 'f') {
816 printf("\nvalid output formats for -f are"
817 " (`*' denotes default):\n");
818 ofmt_list(ofmt, stdout);
819 } else {
820 printf("\nFor a list of valid output formats, use -hf.\n");
821 printf("For a list of debug formats, use -f <form> -y.\n");
823 exit(0); /* never need usage message here */
824 break;
826 case 'y':
827 printf("\nvalid debug formats for '%s' output format are"
828 " ('*' denotes default):\n", ofmt->shortname);
829 dfmt_list(ofmt, stdout);
830 exit(0);
831 break;
833 case 't':
834 tasm_compatible_mode = true;
835 break;
837 case 'v':
838 printf("NASM version %s compiled on %s%s\n",
839 nasm_version, nasm_date, nasm_compile_options);
840 exit(0); /* never need usage message here */
841 break;
843 case 'e': /* preprocess only */
844 case 'E':
845 operating_mode = op_preprocess;
846 break;
848 case 'a': /* assemble only - don't preprocess */
849 preproc = &no_pp;
850 break;
852 case 'W':
853 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
854 do_warn = false;
855 param += 3;
856 } else {
857 do_warn = true;
859 goto set_warning;
861 case 'w':
862 if (param[0] != '+' && param[0] != '-') {
863 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
864 "invalid option to `-w'");
865 break;
867 do_warn = (param[0] == '+');
868 param++;
870 set_warning:
871 for (i = 0; i <= ERR_WARN_MAX; i++) {
872 if (!nasm_stricmp(param, warnings[i].name))
873 break;
875 if (i <= ERR_WARN_MAX) {
876 warning_on_global[i] = do_warn;
877 } else if (!nasm_stricmp(param, "all")) {
878 for (i = 1; i <= ERR_WARN_MAX; i++)
879 warning_on_global[i] = do_warn;
880 } else if (!nasm_stricmp(param, "none")) {
881 for (i = 1; i <= ERR_WARN_MAX; i++)
882 warning_on_global[i] = !do_warn;
883 } else {
884 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
885 "invalid warning `%s'", param);
887 break;
889 case 'M':
890 switch (p[2]) {
891 case 0:
892 operating_mode = op_depend;
893 break;
894 case 'G':
895 operating_mode = op_depend;
896 depend_missing_ok = true;
897 break;
898 case 'P':
899 depend_emit_phony = true;
900 break;
901 case 'D':
902 depend_file = q;
903 advance = true;
904 break;
905 case 'T':
906 depend_target = q;
907 advance = true;
908 break;
909 case 'Q':
910 depend_target = quote_for_make(q);
911 advance = true;
912 break;
913 default:
914 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
915 "unknown dependency option `-M%c'", p[2]);
916 break;
918 if (advance && (!q || !q[0])) {
919 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
920 "option `-M%c' requires a parameter", p[2]);
921 break;
923 break;
925 case '-':
927 int s;
929 if (p[2] == 0) { /* -- => stop processing options */
930 stopoptions = 1;
931 break;
933 for (s = 0; textopts[s].label; s++) {
934 if (!nasm_stricmp(p + 2, textopts[s].label)) {
935 break;
939 switch (s) {
941 case OPT_PREFIX:
942 case OPT_POSTFIX:
944 if (!q) {
945 nasm_error(ERR_NONFATAL | ERR_NOFILE |
946 ERR_USAGE,
947 "option `--%s' requires an argument",
948 p + 2);
949 break;
950 } else {
951 advance = 1, param = q;
954 if (s == OPT_PREFIX) {
955 strncpy(lprefix, param, PREFIX_MAX - 1);
956 lprefix[PREFIX_MAX - 1] = 0;
957 break;
959 if (s == OPT_POSTFIX) {
960 strncpy(lpostfix, param, POSTFIX_MAX - 1);
961 lpostfix[POSTFIX_MAX - 1] = 0;
962 break;
964 break;
966 default:
968 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
969 "unrecognised option `--%s'", p + 2);
970 break;
973 break;
976 default:
977 if (!ofmt->setinfo(GI_SWITCH, &p))
978 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
979 "unrecognised option `-%c'", p[1]);
980 break;
982 } else {
983 if (*inname) {
984 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
985 "more than one input file specified");
986 } else {
987 copy_filename(inname, p);
991 return advance;
994 #define ARG_BUF_DELTA 128
996 static void process_respfile(FILE * rfile)
998 char *buffer, *p, *q, *prevarg;
999 int bufsize, prevargsize;
1001 bufsize = prevargsize = ARG_BUF_DELTA;
1002 buffer = nasm_malloc(ARG_BUF_DELTA);
1003 prevarg = nasm_malloc(ARG_BUF_DELTA);
1004 prevarg[0] = '\0';
1006 while (1) { /* Loop to handle all lines in file */
1007 p = buffer;
1008 while (1) { /* Loop to handle long lines */
1009 q = fgets(p, bufsize - (p - buffer), rfile);
1010 if (!q)
1011 break;
1012 p += strlen(p);
1013 if (p > buffer && p[-1] == '\n')
1014 break;
1015 if (p - buffer > bufsize - 10) {
1016 int offset;
1017 offset = p - buffer;
1018 bufsize += ARG_BUF_DELTA;
1019 buffer = nasm_realloc(buffer, bufsize);
1020 p = buffer + offset;
1024 if (!q && p == buffer) {
1025 if (prevarg[0])
1026 process_arg(prevarg, NULL);
1027 nasm_free(buffer);
1028 nasm_free(prevarg);
1029 return;
1033 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1034 * them are present at the end of the line.
1036 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1038 while (p > buffer && nasm_isspace(p[-1]))
1039 *--p = '\0';
1041 p = nasm_skip_spaces(buffer);
1043 if (process_arg(prevarg, p))
1044 *p = '\0';
1046 if ((int) strlen(p) > prevargsize - 10) {
1047 prevargsize += ARG_BUF_DELTA;
1048 prevarg = nasm_realloc(prevarg, prevargsize);
1050 strncpy(prevarg, p, prevargsize);
1054 /* Function to process args from a string of args, rather than the
1055 * argv array. Used by the environment variable and response file
1056 * processing.
1058 static void process_args(char *args)
1060 char *p, *q, *arg, *prevarg;
1061 char separator = ' ';
1063 p = args;
1064 if (*p && *p != '-')
1065 separator = *p++;
1066 arg = NULL;
1067 while (*p) {
1068 q = p;
1069 while (*p && *p != separator)
1070 p++;
1071 while (*p == separator)
1072 *p++ = '\0';
1073 prevarg = arg;
1074 arg = q;
1075 if (process_arg(prevarg, arg))
1076 arg = NULL;
1078 if (arg)
1079 process_arg(arg, NULL);
1082 static void process_response_file(const char *file)
1084 char str[2048];
1085 FILE *f = fopen(file, "r");
1086 if (!f) {
1087 perror(file);
1088 exit(-1);
1090 while (fgets(str, sizeof str, f)) {
1091 process_args(str);
1093 fclose(f);
1096 static void parse_cmdline(int argc, char **argv)
1098 FILE *rfile;
1099 char *envreal, *envcopy = NULL, *p;
1100 int i;
1102 *inname = *outname = *listname = *errname = '\0';
1103 for (i = 0; i <= ERR_WARN_MAX; i++)
1104 warning_on_global[i] = warnings[i].enabled;
1107 * First, process the NASMENV environment variable.
1109 envreal = getenv("NASMENV");
1110 if (envreal) {
1111 envcopy = nasm_strdup(envreal);
1112 process_args(envcopy);
1113 nasm_free(envcopy);
1117 * Now process the actual command line.
1119 while (--argc) {
1120 bool advance;
1121 argv++;
1122 if (argv[0][0] == '@') {
1123 /* We have a response file, so process this as a set of
1124 * arguments like the environment variable. This allows us
1125 * to have multiple arguments on a single line, which is
1126 * different to the -@resp file processing below for regular
1127 * NASM.
1129 process_response_file(argv[0]+1);
1130 argc--;
1131 argv++;
1133 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1134 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1135 if (p) {
1136 rfile = fopen(p, "r");
1137 if (rfile) {
1138 process_respfile(rfile);
1139 fclose(rfile);
1140 } else
1141 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1142 "unable to open response file `%s'", p);
1144 } else
1145 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1146 argv += advance, argc -= advance;
1149 /* Look for basic command line typos. This definitely doesn't
1150 catch all errors, but it might help cases of fumbled fingers. */
1151 if (!*inname)
1152 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1153 "no input file specified");
1154 else if (!strcmp(inname, errname) ||
1155 !strcmp(inname, outname) ||
1156 !strcmp(inname, listname) ||
1157 (depend_file && !strcmp(inname, depend_file)))
1158 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1159 "file `%s' is both input and output file",
1160 inname);
1162 if (*errname) {
1163 error_file = fopen(errname, "w");
1164 if (!error_file) {
1165 error_file = stderr; /* Revert to default! */
1166 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1167 "cannot open file `%s' for error messages",
1168 errname);
1173 static enum directives getkw(char **directive, char **value);
1175 static void assemble_file(char *fname, StrList **depend_ptr)
1177 char *directive, *value, *p, *q, *special, *line;
1178 insn output_ins;
1179 int i, validid;
1180 bool rn_error;
1181 int32_t seg;
1182 int64_t offs;
1183 struct tokenval tokval;
1184 expr *e;
1185 int pass_max;
1187 if (cmd_sb == 32 && cmd_cpu < IF_386)
1188 nasm_error(ERR_FATAL, "command line: "
1189 "32-bit segment size requires a higher cpu");
1191 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1192 for (passn = 1; pass0 <= 2; passn++) {
1193 int pass1, pass2;
1194 ldfunc def_label;
1196 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1197 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1198 /* pass0 0, 0, 0, ..., 1, 2 */
1200 def_label = passn > 1 ? redefine_label : define_label;
1202 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1203 cpu = cmd_cpu;
1204 if (pass0 == 2) {
1205 if (*listname)
1206 nasmlist.init(listname, nasm_error);
1208 in_abs_seg = false;
1209 global_offset_changed = 0; /* set by redefine_label */
1210 location.segment = ofmt->section(NULL, pass2, &sb);
1211 globalbits = sb;
1212 if (passn > 1) {
1213 saa_rewind(forwrefs);
1214 forwref = saa_rstruct(forwrefs);
1215 raa_free(offsets);
1216 offsets = raa_init();
1218 preproc->reset(fname, pass1, &nasmlist,
1219 pass1 == 2 ? depend_ptr : NULL);
1220 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1222 globallineno = 0;
1223 if (passn == 1)
1224 location.known = true;
1225 location.offset = offs = GET_CURR_OFFS;
1227 while ((line = preproc->getline())) {
1228 enum directives d;
1229 globallineno++;
1232 * Here we parse our directives; this is not handled by the
1233 * 'real' parser. This really should be a separate function.
1235 directive = line;
1236 d = getkw(&directive, &value);
1237 if (d) {
1238 int err = 0;
1240 switch (d) {
1241 case D_SEGMENT: /* [SEGMENT n] */
1242 case D_SECTION:
1243 seg = ofmt->section(value, pass2, &sb);
1244 if (seg == NO_SEG) {
1245 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1246 "segment name `%s' not recognized",
1247 value);
1248 } else {
1249 in_abs_seg = false;
1250 location.segment = seg;
1252 break;
1253 case D_SECTALIGN: /* [SECTALIGN n] */
1254 if (*value) {
1255 stdscan_reset();
1256 stdscan_set(value);
1257 tokval.t_type = TOKEN_INVALID;
1258 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1259 if (e) {
1260 unsigned int align = (unsigned int)e->value;
1261 if ((uint64_t)e->value > 0x7fffffff) {
1263 * FIXME: Please make some sane message here
1264 * ofmt should have some 'check' method which
1265 * would report segment alignment bounds.
1267 nasm_error(ERR_FATAL,
1268 "incorrect segment alignment `%s'", value);
1269 } else if (!is_power2(align)) {
1270 nasm_error(ERR_NONFATAL,
1271 "segment alignment `%s' is not power of two",
1272 value);
1274 /* callee should be able to handle all details */
1275 ofmt->sectalign(location.segment, align);
1278 break;
1279 case D_EXTERN: /* [EXTERN label:special] */
1280 if (*value == '$')
1281 value++; /* skip initial $ if present */
1282 if (pass0 == 2) {
1283 q = value;
1284 while (*q && *q != ':')
1285 q++;
1286 if (*q == ':') {
1287 *q++ = '\0';
1288 ofmt->symdef(value, 0L, 0L, 3, q);
1290 } else if (passn == 1) {
1291 q = value;
1292 validid = true;
1293 if (!isidstart(*q))
1294 validid = false;
1295 while (*q && *q != ':') {
1296 if (!isidchar(*q))
1297 validid = false;
1298 q++;
1300 if (!validid) {
1301 nasm_error(ERR_NONFATAL,
1302 "identifier expected after EXTERN");
1303 break;
1305 if (*q == ':') {
1306 *q++ = '\0';
1307 special = q;
1308 } else
1309 special = NULL;
1310 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1311 int temp = pass0;
1312 pass0 = 1; /* fake pass 1 in labels.c */
1313 declare_as_global(value, special);
1314 define_label(value, seg_alloc(), 0L, NULL,
1315 false, true);
1316 pass0 = temp;
1318 } /* else pass0 == 1 */
1319 break;
1320 case D_BITS: /* [BITS bits] */
1321 globalbits = sb = get_bits(value);
1322 break;
1323 case D_GLOBAL: /* [GLOBAL symbol:special] */
1324 if (*value == '$')
1325 value++; /* skip initial $ if present */
1326 if (pass0 == 2) { /* pass 2 */
1327 q = value;
1328 while (*q && *q != ':')
1329 q++;
1330 if (*q == ':') {
1331 *q++ = '\0';
1332 ofmt->symdef(value, 0L, 0L, 3, q);
1334 } else if (pass2 == 1) { /* pass == 1 */
1335 q = value;
1336 validid = true;
1337 if (!isidstart(*q))
1338 validid = false;
1339 while (*q && *q != ':') {
1340 if (!isidchar(*q))
1341 validid = false;
1342 q++;
1344 if (!validid) {
1345 nasm_error(ERR_NONFATAL,
1346 "identifier expected after GLOBAL");
1347 break;
1349 if (*q == ':') {
1350 *q++ = '\0';
1351 special = q;
1352 } else
1353 special = NULL;
1354 declare_as_global(value, special);
1355 } /* pass == 1 */
1356 break;
1357 case D_COMMON: /* [COMMON symbol size:special] */
1359 int64_t size;
1361 if (*value == '$')
1362 value++; /* skip initial $ if present */
1363 p = value;
1364 validid = true;
1365 if (!isidstart(*p))
1366 validid = false;
1367 while (*p && !nasm_isspace(*p)) {
1368 if (!isidchar(*p))
1369 validid = false;
1370 p++;
1372 if (!validid) {
1373 nasm_error(ERR_NONFATAL,
1374 "identifier expected after COMMON");
1375 break;
1377 if (*p) {
1378 p = nasm_zap_spaces_fwd(p);
1379 q = p;
1380 while (*q && *q != ':')
1381 q++;
1382 if (*q == ':') {
1383 *q++ = '\0';
1384 special = q;
1385 } else {
1386 special = NULL;
1388 size = readnum(p, &rn_error);
1389 if (rn_error) {
1390 nasm_error(ERR_NONFATAL,
1391 "invalid size specified"
1392 " in COMMON declaration");
1393 break;
1395 } else {
1396 nasm_error(ERR_NONFATAL,
1397 "no size specified in"
1398 " COMMON declaration");
1399 break;
1402 if (pass0 < 2) {
1403 define_common(value, seg_alloc(), size, special);
1404 } else if (pass0 == 2) {
1405 if (special)
1406 ofmt->symdef(value, 0L, 0L, 3, special);
1408 break;
1410 case D_ABSOLUTE: /* [ABSOLUTE address] */
1411 stdscan_reset();
1412 stdscan_set(value);
1413 tokval.t_type = TOKEN_INVALID;
1414 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1415 nasm_error, NULL);
1416 if (e) {
1417 if (!is_reloc(e))
1418 nasm_error(pass0 ==
1419 1 ? ERR_NONFATAL : ERR_PANIC,
1420 "cannot use non-relocatable expression as "
1421 "ABSOLUTE address");
1422 else {
1423 abs_seg = reloc_seg(e);
1424 abs_offset = reloc_value(e);
1426 } else if (passn == 1)
1427 abs_offset = 0x100; /* don't go near zero in case of / */
1428 else
1429 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1430 "in pass two");
1431 in_abs_seg = true;
1432 location.segment = NO_SEG;
1433 break;
1434 case D_DEBUG: /* [DEBUG] */
1436 char debugid[128];
1437 bool badid, overlong;
1439 p = value;
1440 q = debugid;
1441 badid = overlong = false;
1442 if (!isidstart(*p)) {
1443 badid = true;
1444 } else {
1445 while (*p && !nasm_isspace(*p)) {
1446 if (q >= debugid + sizeof debugid - 1) {
1447 overlong = true;
1448 break;
1450 if (!isidchar(*p))
1451 badid = true;
1452 *q++ = *p++;
1454 *q = 0;
1456 if (badid) {
1457 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1458 "identifier expected after DEBUG");
1459 break;
1461 if (overlong) {
1462 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1463 "DEBUG identifier too long");
1464 break;
1466 p = nasm_skip_spaces(p);
1467 if (pass0 == 2)
1468 dfmt->debug_directive(debugid, p);
1469 break;
1471 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1472 value = nasm_skip_spaces(value);
1473 switch(*value) {
1474 case '-': validid = 0; value++; break;
1475 case '+': validid = 1; value++; break;
1476 case '*': validid = 2; value++; break;
1477 default: validid = 1; break;
1480 for (i = 1; i <= ERR_WARN_MAX; i++)
1481 if (!nasm_stricmp(value, warnings[i].name))
1482 break;
1483 if (i <= ERR_WARN_MAX) {
1484 switch(validid) {
1485 case 0:
1486 warning_on[i] = false;
1487 break;
1488 case 1:
1489 warning_on[i] = true;
1490 break;
1491 case 2:
1492 warning_on[i] = warning_on_global[i];
1493 break;
1496 else
1497 nasm_error(ERR_NONFATAL,
1498 "invalid warning id in WARNING directive");
1499 break;
1500 case D_CPU: /* [CPU] */
1501 cpu = get_cpu(value);
1502 break;
1503 case D_LIST: /* [LIST {+|-}] */
1504 value = nasm_skip_spaces(value);
1505 if (*value == '+') {
1506 user_nolist = 0;
1507 } else {
1508 if (*value == '-') {
1509 user_nolist = 1;
1510 } else {
1511 err = 1;
1514 break;
1515 case D_DEFAULT: /* [DEFAULT] */
1516 stdscan_reset();
1517 stdscan_set(value);
1518 tokval.t_type = TOKEN_INVALID;
1519 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1520 switch ((int)tokval.t_integer) {
1521 case S_REL:
1522 globalrel = 1;
1523 break;
1524 case S_ABS:
1525 globalrel = 0;
1526 break;
1527 default:
1528 err = 1;
1529 break;
1531 } else {
1532 err = 1;
1534 break;
1535 case D_FLOAT:
1536 if (float_option(value)) {
1537 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1538 "unknown 'float' directive: %s",
1539 value);
1541 break;
1542 default:
1543 if (ofmt->directive(d, value, pass2))
1544 break;
1545 /* else fall through */
1546 case D_unknown:
1547 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1548 "unrecognised directive [%s]",
1549 directive);
1550 break;
1552 if (err) {
1553 nasm_error(ERR_NONFATAL,
1554 "invalid parameter to [%s] directive",
1555 directive);
1557 } else { /* it isn't a directive */
1558 parse_line(pass1, line, &output_ins, def_label);
1560 if (optimizing > 0) {
1561 if (forwref != NULL && globallineno == forwref->lineno) {
1562 output_ins.forw_ref = true;
1563 do {
1564 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1565 forwref = saa_rstruct(forwrefs);
1566 } while (forwref != NULL
1567 && forwref->lineno == globallineno);
1568 } else
1569 output_ins.forw_ref = false;
1571 if (output_ins.forw_ref) {
1572 if (passn == 1) {
1573 for (i = 0; i < output_ins.operands; i++) {
1574 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1575 struct forwrefinfo *fwinf =
1576 (struct forwrefinfo *)
1577 saa_wstruct(forwrefs);
1578 fwinf->lineno = globallineno;
1579 fwinf->operand = i;
1586 /* forw_ref */
1587 if (output_ins.opcode == I_EQU) {
1588 if (pass1 == 1) {
1590 * Special `..' EQUs get processed in pass two,
1591 * except `..@' macro-processor EQUs which are done
1592 * in the normal place.
1594 if (!output_ins.label)
1595 nasm_error(ERR_NONFATAL,
1596 "EQU not preceded by label");
1598 else if (output_ins.label[0] != '.' ||
1599 output_ins.label[1] != '.' ||
1600 output_ins.label[2] == '@') {
1601 if (output_ins.operands == 1 &&
1602 (output_ins.oprs[0].type & IMMEDIATE) &&
1603 output_ins.oprs[0].wrt == NO_SEG) {
1604 bool isext = !!(output_ins.oprs[0].opflags
1605 & OPFLAG_EXTERN);
1606 def_label(output_ins.label,
1607 output_ins.oprs[0].segment,
1608 output_ins.oprs[0].offset, NULL,
1609 false, isext);
1610 } else if (output_ins.operands == 2
1611 && (output_ins.oprs[0].type & IMMEDIATE)
1612 && (output_ins.oprs[0].type & COLON)
1613 && output_ins.oprs[0].segment == NO_SEG
1614 && output_ins.oprs[0].wrt == NO_SEG
1615 && (output_ins.oprs[1].type & IMMEDIATE)
1616 && output_ins.oprs[1].segment == NO_SEG
1617 && output_ins.oprs[1].wrt == NO_SEG) {
1618 def_label(output_ins.label,
1619 output_ins.oprs[0].offset | SEG_ABS,
1620 output_ins.oprs[1].offset,
1621 NULL, false, false);
1622 } else
1623 nasm_error(ERR_NONFATAL,
1624 "bad syntax for EQU");
1626 } else {
1628 * Special `..' EQUs get processed here, except
1629 * `..@' macro processor EQUs which are done above.
1631 if (output_ins.label[0] == '.' &&
1632 output_ins.label[1] == '.' &&
1633 output_ins.label[2] != '@') {
1634 if (output_ins.operands == 1 &&
1635 (output_ins.oprs[0].type & IMMEDIATE)) {
1636 define_label(output_ins.label,
1637 output_ins.oprs[0].segment,
1638 output_ins.oprs[0].offset,
1639 NULL, false, false);
1640 } else if (output_ins.operands == 2
1641 && (output_ins.oprs[0].type & IMMEDIATE)
1642 && (output_ins.oprs[0].type & COLON)
1643 && output_ins.oprs[0].segment == NO_SEG
1644 && (output_ins.oprs[1].type & IMMEDIATE)
1645 && output_ins.oprs[1].segment == NO_SEG) {
1646 define_label(output_ins.label,
1647 output_ins.oprs[0].offset | SEG_ABS,
1648 output_ins.oprs[1].offset,
1649 NULL, false, false);
1650 } else
1651 nasm_error(ERR_NONFATAL,
1652 "bad syntax for EQU");
1655 } else { /* instruction isn't an EQU */
1657 if (pass1 == 1) {
1659 int64_t l = insn_size(location.segment, offs, sb, cpu,
1660 &output_ins, nasm_error);
1662 /* if (using_debug_info) && output_ins.opcode != -1) */
1663 if (using_debug_info)
1664 { /* fbk 03/25/01 */
1665 /* this is done here so we can do debug type info */
1666 int32_t typeinfo =
1667 TYS_ELEMENTS(output_ins.operands);
1668 switch (output_ins.opcode) {
1669 case I_RESB:
1670 typeinfo =
1671 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1672 break;
1673 case I_RESW:
1674 typeinfo =
1675 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1676 break;
1677 case I_RESD:
1678 typeinfo =
1679 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1680 break;
1681 case I_RESQ:
1682 typeinfo =
1683 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1684 break;
1685 case I_REST:
1686 typeinfo =
1687 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1688 break;
1689 case I_RESO:
1690 typeinfo =
1691 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1692 break;
1693 case I_RESY:
1694 typeinfo =
1695 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1696 break;
1697 case I_DB:
1698 typeinfo |= TY_BYTE;
1699 break;
1700 case I_DW:
1701 typeinfo |= TY_WORD;
1702 break;
1703 case I_DD:
1704 if (output_ins.eops_float)
1705 typeinfo |= TY_FLOAT;
1706 else
1707 typeinfo |= TY_DWORD;
1708 break;
1709 case I_DQ:
1710 typeinfo |= TY_QWORD;
1711 break;
1712 case I_DT:
1713 typeinfo |= TY_TBYTE;
1714 break;
1715 case I_DO:
1716 typeinfo |= TY_OWORD;
1717 break;
1718 case I_DY:
1719 typeinfo |= TY_YWORD;
1720 break;
1721 default:
1722 typeinfo = TY_LABEL;
1726 dfmt->debug_typevalue(typeinfo);
1728 if (l != -1) {
1729 offs += l;
1730 SET_CURR_OFFS(offs);
1733 * else l == -1 => invalid instruction, which will be
1734 * flagged as an error on pass 2
1737 } else {
1738 offs += assemble(location.segment, offs, sb, cpu,
1739 &output_ins, ofmt, nasm_error,
1740 &nasmlist);
1741 SET_CURR_OFFS(offs);
1744 } /* not an EQU */
1745 cleanup_insn(&output_ins);
1747 nasm_free(line);
1748 location.offset = offs = GET_CURR_OFFS;
1749 } /* end while (line = preproc->getline... */
1751 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1752 nasm_error(ERR_NONFATAL,
1753 "phase error detected at end of assembly.");
1755 if (pass1 == 1)
1756 preproc->cleanup(1);
1758 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1759 pass0++;
1760 } else if (global_offset_changed &&
1761 global_offset_changed < prev_offset_changed) {
1762 prev_offset_changed = global_offset_changed;
1763 stall_count = 0;
1764 } else {
1765 stall_count++;
1768 if (terminate_after_phase)
1769 break;
1771 if ((stall_count > 997) || (passn >= pass_max)) {
1772 /* We get here if the labels don't converge
1773 * Example: FOO equ FOO + 1
1775 nasm_error(ERR_NONFATAL,
1776 "Can't find valid values for all labels "
1777 "after %d passes, giving up.", passn);
1778 nasm_error(ERR_NONFATAL,
1779 "Possible causes: recursive EQUs, macro abuse.");
1780 break;
1784 preproc->cleanup(0);
1785 nasmlist.cleanup();
1786 if (!terminate_after_phase && opt_verbose_info) {
1787 /* -On and -Ov switches */
1788 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1792 static enum directives getkw(char **directive, char **value)
1794 char *p, *q, *buf;
1796 buf = nasm_skip_spaces(*directive);
1798 /* it should be enclosed in [ ] */
1799 if (*buf != '[')
1800 return D_none;
1801 q = strchr(buf, ']');
1802 if (!q)
1803 return D_none;
1805 /* stip off the comments */
1806 p = strchr(buf, ';');
1807 if (p) {
1808 if (p < q) /* ouch! somwhere inside */
1809 return D_none;
1810 *p = '\0';
1813 /* no brace, no trailing spaces */
1814 *q = '\0';
1815 nasm_zap_spaces_rev(--q);
1817 /* directive */
1818 p = nasm_skip_spaces(++buf);
1819 q = nasm_skip_word(p);
1820 if (!q)
1821 return D_none; /* sigh... no value there */
1822 *q = '\0';
1823 *directive = p;
1825 /* and value finally */
1826 p = nasm_skip_spaces(++q);
1827 *value = p;
1829 return find_directive(*directive);
1833 * gnu style error reporting
1834 * This function prints an error message to error_file in the
1835 * style used by GNU. An example would be:
1836 * file.asm:50: error: blah blah blah
1837 * where file.asm is the name of the file, 50 is the line number on
1838 * which the error occurs (or is detected) and "error:" is one of
1839 * the possible optional diagnostics -- it can be "error" or "warning"
1840 * or something else. Finally the line terminates with the actual
1841 * error message.
1843 * @param severity the severity of the warning or error
1844 * @param fmt the printf style format string
1846 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1848 char *currentfile = NULL;
1849 int32_t lineno = 0;
1851 if (is_suppressed_warning(severity))
1852 return;
1854 if (!(severity & ERR_NOFILE))
1855 src_get(&lineno, &currentfile);
1857 if (currentfile) {
1858 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1859 nasm_free(currentfile);
1860 } else {
1861 fputs("nasm: ", error_file);
1864 nasm_verror_common(severity, fmt, ap);
1868 * MS style error reporting
1869 * This function prints an error message to error_file in the
1870 * style used by Visual C and some other Microsoft tools. An example
1871 * would be:
1872 * file.asm(50) : error: blah blah blah
1873 * where file.asm is the name of the file, 50 is the line number on
1874 * which the error occurs (or is detected) and "error:" is one of
1875 * the possible optional diagnostics -- it can be "error" or "warning"
1876 * or something else. Finally the line terminates with the actual
1877 * error message.
1879 * @param severity the severity of the warning or error
1880 * @param fmt the printf style format string
1882 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1884 char *currentfile = NULL;
1885 int32_t lineno = 0;
1887 if (is_suppressed_warning(severity))
1888 return;
1890 if (!(severity & ERR_NOFILE))
1891 src_get(&lineno, &currentfile);
1893 if (currentfile) {
1894 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1895 nasm_free(currentfile);
1896 } else {
1897 fputs("nasm: ", error_file);
1900 nasm_verror_common(severity, fmt, ap);
1904 * check for supressed warning
1905 * checks for suppressed warning or pass one only warning and we're
1906 * not in pass 1
1908 * @param severity the severity of the warning or error
1909 * @return true if we should abort error/warning printing
1911 static bool is_suppressed_warning(int severity)
1914 /* Not a warning at all */
1915 if ((severity & ERR_MASK) != ERR_WARNING)
1916 return false;
1918 /* Might be a warning but suppresed explicitly */
1919 if (severity & ERR_WARN_MASK) {
1920 if (warning_on[WARN_IDX(severity)])
1921 return false;
1924 /* See if it's a pass-one only warning and we're not in pass one. */
1925 if (((severity & ERR_PASS1) && pass0 != 1) ||
1926 ((severity & ERR_PASS2) && pass0 != 2))
1927 return true;
1929 return true;
1933 * common error reporting
1934 * This is the common back end of the error reporting schemes currently
1935 * implemented. It prints the nature of the warning and then the
1936 * specific error message to error_file and may or may not return. It
1937 * doesn't return if the error severity is a "panic" or "debug" type.
1939 * @param severity the severity of the warning or error
1940 * @param fmt the printf style format string
1942 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1944 char msg[1024];
1945 const char *pfx;
1947 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1948 case ERR_WARNING:
1949 pfx = "warning: ";
1950 break;
1951 case ERR_NONFATAL:
1952 pfx = "error: ";
1953 break;
1954 case ERR_FATAL:
1955 pfx = "fatal: ";
1956 break;
1957 case ERR_PANIC:
1958 pfx = "panic: ";
1959 break;
1960 case ERR_DEBUG:
1961 pfx = "debug: ";
1962 break;
1963 default:
1964 pfx = "";
1965 break;
1968 vsnprintf(msg, sizeof msg, fmt, args);
1970 fprintf(error_file, "%s%s\n", pfx, msg);
1972 if (*listname)
1973 nasmlist.error(severity, pfx, msg);
1975 if (severity & ERR_USAGE)
1976 want_usage = true;
1978 switch (severity & ERR_MASK) {
1979 case ERR_DEBUG:
1980 /* no further action, by definition */
1981 break;
1982 case ERR_WARNING:
1983 /* Treat warnings as errors */
1984 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1985 terminate_after_phase = true;
1986 break;
1987 case ERR_NONFATAL:
1988 terminate_after_phase = true;
1989 break;
1990 case ERR_FATAL:
1991 if (ofile) {
1992 fclose(ofile);
1993 remove(outname);
1994 ofile = NULL;
1996 if (want_usage)
1997 usage();
1998 exit(1); /* instantly die */
1999 break; /* placate silly compilers */
2000 case ERR_PANIC:
2001 fflush(NULL);
2002 /* abort(); *//* halt, catch fire, and dump core */
2003 exit(3);
2004 break;
2008 static void usage(void)
2010 fputs("type `nasm -h' for help\n", error_file);
2013 #define BUF_DELTA 512
2015 static FILE *no_pp_fp;
2016 static ListGen *no_pp_list;
2017 static int32_t no_pp_lineinc;
2019 static void no_pp_reset(char *file, int pass, ListGen * listgen,
2020 StrList **deplist)
2022 src_set_fname(nasm_strdup(file));
2023 src_set_linnum(0);
2024 no_pp_lineinc = 1;
2025 no_pp_fp = fopen(file, "r");
2026 if (!no_pp_fp)
2027 nasm_error(ERR_FATAL | ERR_NOFILE,
2028 "unable to open input file `%s'", file);
2029 no_pp_list = listgen;
2030 (void)pass; /* placate compilers */
2032 if (deplist) {
2033 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2034 sl->next = NULL;
2035 strcpy(sl->str, file);
2036 *deplist = sl;
2040 static char *no_pp_getline(void)
2042 char *buffer, *p, *q;
2043 int bufsize;
2045 bufsize = BUF_DELTA;
2046 buffer = nasm_malloc(BUF_DELTA);
2047 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2049 while (1) { /* Loop to handle %line */
2051 p = buffer;
2052 while (1) { /* Loop to handle long lines */
2053 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2054 if (!q)
2055 break;
2056 p += strlen(p);
2057 if (p > buffer && p[-1] == '\n')
2058 break;
2059 if (p - buffer > bufsize - 10) {
2060 int offset;
2061 offset = p - buffer;
2062 bufsize += BUF_DELTA;
2063 buffer = nasm_realloc(buffer, bufsize);
2064 p = buffer + offset;
2068 if (!q && p == buffer) {
2069 nasm_free(buffer);
2070 return NULL;
2074 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2075 * them are present at the end of the line.
2077 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2079 if (!nasm_strnicmp(buffer, "%line", 5)) {
2080 int32_t ln;
2081 int li;
2082 char *nm = nasm_malloc(strlen(buffer));
2083 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2084 nasm_free(src_set_fname(nm));
2085 src_set_linnum(ln);
2086 no_pp_lineinc = li;
2087 continue;
2089 nasm_free(nm);
2091 break;
2094 no_pp_list->line(LIST_READ, buffer);
2096 return buffer;
2099 static void no_pp_cleanup(int pass)
2101 (void)pass; /* placate GCC */
2102 if (no_pp_fp) {
2103 fclose(no_pp_fp);
2104 no_pp_fp = NULL;
2108 static uint32_t get_cpu(char *value)
2110 if (!strcmp(value, "8086"))
2111 return IF_8086;
2112 if (!strcmp(value, "186"))
2113 return IF_186;
2114 if (!strcmp(value, "286"))
2115 return IF_286;
2116 if (!strcmp(value, "386"))
2117 return IF_386;
2118 if (!strcmp(value, "486"))
2119 return IF_486;
2120 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2121 return IF_PENT;
2122 if (!strcmp(value, "686") ||
2123 !nasm_stricmp(value, "ppro") ||
2124 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2125 return IF_P6;
2126 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2127 return IF_KATMAI;
2128 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2129 !nasm_stricmp(value, "willamette"))
2130 return IF_WILLAMETTE;
2131 if (!nasm_stricmp(value, "prescott"))
2132 return IF_PRESCOTT;
2133 if (!nasm_stricmp(value, "x64") ||
2134 !nasm_stricmp(value, "x86-64"))
2135 return IF_X86_64;
2136 if (!nasm_stricmp(value, "ia64") ||
2137 !nasm_stricmp(value, "ia-64") ||
2138 !nasm_stricmp(value, "itanium") ||
2139 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2140 return IF_IA64;
2142 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2143 "unknown 'cpu' type");
2145 return IF_PLEVEL; /* the maximum level */
2148 static int get_bits(char *value)
2150 int i;
2152 if ((i = atoi(value)) == 16)
2153 return i; /* set for a 16-bit segment */
2154 else if (i == 32) {
2155 if (cpu < IF_386) {
2156 nasm_error(ERR_NONFATAL,
2157 "cannot specify 32-bit segment on processor below a 386");
2158 i = 16;
2160 } else if (i == 64) {
2161 if (cpu < IF_X86_64) {
2162 nasm_error(ERR_NONFATAL,
2163 "cannot specify 64-bit segment on processor below an x86-64");
2164 i = 16;
2166 if (i != maxbits) {
2167 nasm_error(ERR_NONFATAL,
2168 "%s output format does not support 64-bit code",
2169 ofmt->shortname);
2170 i = 16;
2172 } else {
2173 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2174 "`%s' is not a valid segment size; must be 16, 32 or 64",
2175 value);
2176 i = 16;
2178 return i;