NASM 2.10rc14
[nasm.git] / nasm.c
blob5103fea5d03bbe66938760e46bab5a8f1210fbe3
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2012 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},
164 {"lock", "lock prefix on unlockable instructions", true},
165 {"hle", "invalid hle prefixes", true},
169 * This is a null preprocessor which just copies lines from input
170 * to output. It's used when someone explicitly requests that NASM
171 * not preprocess their source file.
174 static void no_pp_reset(char *file, int pass, ListGen *listgen, StrList **deplist);
175 static char *no_pp_getline(void);
176 static void no_pp_cleanup(int pass);
178 static struct preproc_ops no_pp = {
179 no_pp_reset,
180 no_pp_getline,
181 no_pp_cleanup
185 * get/set current offset...
187 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
188 raa_read(offsets,location.segment))
189 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
190 (void)(offsets=raa_write(offsets,location.segment,(x))))
192 static bool want_usage;
193 static bool terminate_after_phase;
194 int user_nolist = 0; /* fbk 9/2/00 */
196 static void nasm_fputs(const char *line, FILE * outfile)
198 if (outfile) {
199 fputs(line, outfile);
200 putc('\n', outfile);
201 } else
202 puts(line);
205 /* Convert a struct tm to a POSIX-style time constant */
206 static int64_t posix_mktime(struct tm *tm)
208 int64_t t;
209 int64_t y = tm->tm_year;
211 /* See IEEE 1003.1:2004, section 4.14 */
213 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
214 t += tm->tm_yday;
215 t *= 24;
216 t += tm->tm_hour;
217 t *= 60;
218 t += tm->tm_min;
219 t *= 60;
220 t += tm->tm_sec;
222 return t;
225 static void define_macros_early(void)
227 char temp[128];
228 struct tm lt, *lt_p, gm, *gm_p;
229 int64_t posix_time;
231 lt_p = localtime(&official_compile_time);
232 if (lt_p) {
233 lt = *lt_p;
235 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
236 pp_pre_define(temp);
237 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
238 pp_pre_define(temp);
239 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
240 pp_pre_define(temp);
241 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
242 pp_pre_define(temp);
245 gm_p = gmtime(&official_compile_time);
246 if (gm_p) {
247 gm = *gm_p;
249 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
250 pp_pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
252 pp_pre_define(temp);
253 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
254 pp_pre_define(temp);
255 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
256 pp_pre_define(temp);
259 if (gm_p)
260 posix_time = posix_mktime(&gm);
261 else if (lt_p)
262 posix_time = posix_mktime(&lt);
263 else
264 posix_time = 0;
266 if (posix_time) {
267 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
268 pp_pre_define(temp);
272 static void define_macros_late(void)
274 char temp[128];
277 * In case if output format is defined by alias
278 * we have to put shortname of the alias itself here
279 * otherwise ABI backward compatibility gets broken.
281 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
282 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
283 pp_pre_define(temp);
286 static void emit_dependencies(StrList *list)
288 FILE *deps;
289 int linepos, len;
290 StrList *l, *nl;
292 if (depend_file && strcmp(depend_file, "-")) {
293 deps = fopen(depend_file, "w");
294 if (!deps) {
295 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
296 "unable to write dependency file `%s'", depend_file);
297 return;
299 } else {
300 deps = stdout;
303 linepos = fprintf(deps, "%s:", depend_target);
304 list_for_each(l, list) {
305 len = strlen(l->str);
306 if (linepos + len > 62) {
307 fprintf(deps, " \\\n ");
308 linepos = 1;
310 fprintf(deps, " %s", l->str);
311 linepos += len+1;
313 fprintf(deps, "\n\n");
315 list_for_each_safe(l, nl, list) {
316 if (depend_emit_phony)
317 fprintf(deps, "%s:\n\n", l->str);
318 nasm_free(l);
321 if (deps != stdout)
322 fclose(deps);
325 int main(int argc, char **argv)
327 StrList *depend_list = NULL, **depend_ptr;
329 time(&official_compile_time);
331 pass0 = 0;
332 want_usage = terminate_after_phase = false;
333 nasm_set_verror(nasm_verror_gnu);
335 error_file = stderr;
337 tolower_init();
339 nasm_init_malloc_error();
340 offsets = raa_init();
341 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
343 preproc = &nasmpp;
344 operating_mode = op_normal;
346 seg_init();
348 /* Define some macros dependent on the runtime, but not
349 on the command line. */
350 define_macros_early();
352 parse_cmdline(argc, argv);
354 if (terminate_after_phase) {
355 if (want_usage)
356 usage();
357 return 1;
360 /* If debugging info is disabled, suppress any debug calls */
361 if (!using_debug_info)
362 ofmt->current_dfmt = &null_debug_form;
364 if (ofmt->stdmac)
365 pp_extra_stdmac(ofmt->stdmac);
366 parser_global_info(&location);
367 eval_global_info(ofmt, lookup_label, &location);
369 /* define some macros dependent of command-line */
370 define_macros_late();
372 depend_ptr = (depend_file || (operating_mode == op_depend))
373 ? &depend_list : NULL;
374 if (!depend_target)
375 depend_target = outname;
377 switch (operating_mode) {
378 case op_depend:
380 char *line;
382 if (depend_missing_ok)
383 pp_include_path(NULL); /* "assume generated" */
385 preproc->reset(inname, 0, &nasmlist, depend_ptr);
386 if (outname[0] == '\0')
387 ofmt->filename(inname, outname);
388 ofile = NULL;
389 while ((line = preproc->getline()))
390 nasm_free(line);
391 preproc->cleanup(0);
393 break;
395 case op_preprocess:
397 char *line;
398 char *file_name = NULL;
399 int32_t prior_linnum = 0;
400 int lineinc = 0;
402 if (*outname) {
403 ofile = fopen(outname, "w");
404 if (!ofile)
405 nasm_error(ERR_FATAL | ERR_NOFILE,
406 "unable to open output file `%s'",
407 outname);
408 } else
409 ofile = NULL;
411 location.known = false;
413 /* pass = 1; */
414 preproc->reset(inname, 3, &nasmlist, depend_ptr);
415 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
417 while ((line = preproc->getline())) {
419 * We generate %line directives if needed for later programs
421 int32_t linnum = prior_linnum += lineinc;
422 int altline = src_get(&linnum, &file_name);
423 if (altline) {
424 if (altline == 1 && lineinc == 1)
425 nasm_fputs("", ofile);
426 else {
427 lineinc = (altline != -1 || lineinc != 1);
428 fprintf(ofile ? ofile : stdout,
429 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
430 file_name);
432 prior_linnum = linnum;
434 nasm_fputs(line, ofile);
435 nasm_free(line);
437 nasm_free(file_name);
438 preproc->cleanup(0);
439 if (ofile)
440 fclose(ofile);
441 if (ofile && terminate_after_phase)
442 remove(outname);
443 ofile = NULL;
445 break;
447 case op_normal:
450 * We must call ofmt->filename _anyway_, even if the user
451 * has specified their own output file, because some
452 * formats (eg OBJ and COFF) use ofmt->filename to find out
453 * the name of the input file and then put that inside the
454 * file.
456 ofmt->filename(inname, outname);
458 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
459 if (!ofile) {
460 nasm_error(ERR_FATAL | ERR_NOFILE,
461 "unable to open output file `%s'", outname);
465 * We must call init_labels() before ofmt->init() since
466 * some object formats will want to define labels in their
467 * init routines. (eg OS/2 defines the FLAT group)
469 init_labels();
471 ofmt->init();
472 dfmt = ofmt->current_dfmt;
473 dfmt->init();
475 assemble_file(inname, depend_ptr);
477 if (!terminate_after_phase) {
478 ofmt->cleanup(using_debug_info);
479 cleanup_labels();
480 fflush(ofile);
481 if (ferror(ofile)) {
482 nasm_error(ERR_NONFATAL|ERR_NOFILE,
483 "write error on output file `%s'", outname);
487 if (ofile) {
488 fclose(ofile);
489 if (terminate_after_phase)
490 remove(outname);
491 ofile = NULL;
494 break;
497 if (depend_list && !terminate_after_phase)
498 emit_dependencies(depend_list);
500 if (want_usage)
501 usage();
503 raa_free(offsets);
504 saa_free(forwrefs);
505 eval_cleanup();
506 stdscan_cleanup();
508 return terminate_after_phase;
512 * Get a parameter for a command line option.
513 * First arg must be in the form of e.g. -f...
515 static char *get_param(char *p, char *q, bool *advance)
517 *advance = false;
518 if (p[2]) /* the parameter's in the option */
519 return nasm_skip_spaces(p + 2);
520 if (q && q[0]) {
521 *advance = true;
522 return q;
524 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
525 "option `-%c' requires an argument", p[1]);
526 return NULL;
530 * Copy a filename
532 static void copy_filename(char *dst, const char *src)
534 size_t len = strlen(src);
536 if (len >= (size_t)FILENAME_MAX) {
537 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
538 return;
540 strncpy(dst, src, FILENAME_MAX);
544 * Convert a string to Make-safe form
546 static char *quote_for_make(const char *str)
548 const char *p;
549 char *os, *q;
551 size_t n = 1; /* Terminating zero */
552 size_t nbs = 0;
554 if (!str)
555 return NULL;
557 for (p = str; *p; p++) {
558 switch (*p) {
559 case ' ':
560 case '\t':
561 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
562 n += nbs + 2;
563 nbs = 0;
564 break;
565 case '$':
566 case '#':
567 nbs = 0;
568 n += 2;
569 break;
570 case '\\':
571 nbs++;
572 n++;
573 break;
574 default:
575 nbs = 0;
576 n++;
577 break;
581 /* Convert N backslashes at the end of filename to 2N backslashes */
582 if (nbs)
583 n += nbs;
585 os = q = nasm_malloc(n);
587 nbs = 0;
588 for (p = str; *p; p++) {
589 switch (*p) {
590 case ' ':
591 case '\t':
592 while (nbs--)
593 *q++ = '\\';
594 *q++ = '\\';
595 *q++ = *p;
596 break;
597 case '$':
598 *q++ = *p;
599 *q++ = *p;
600 nbs = 0;
601 break;
602 case '#':
603 *q++ = '\\';
604 *q++ = *p;
605 nbs = 0;
606 break;
607 case '\\':
608 *q++ = *p;
609 nbs++;
610 break;
611 default:
612 *q++ = *p;
613 nbs = 0;
614 break;
617 while (nbs--)
618 *q++ = '\\';
620 *q = '\0';
622 return os;
625 struct textargs {
626 const char *label;
627 int value;
630 #define OPT_PREFIX 0
631 #define OPT_POSTFIX 1
632 struct textargs textopts[] = {
633 {"prefix", OPT_PREFIX},
634 {"postfix", OPT_POSTFIX},
635 {NULL, 0}
638 static bool stopoptions = false;
639 static bool process_arg(char *p, char *q)
641 char *param;
642 int i;
643 bool advance = false;
644 bool do_warn;
646 if (!p || !p[0])
647 return false;
649 if (p[0] == '-' && !stopoptions) {
650 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
651 /* These parameters take values */
652 if (!(param = get_param(p, q, &advance)))
653 return advance;
656 switch (p[1]) {
657 case 's':
658 error_file = stdout;
659 break;
661 case 'o': /* output file */
662 copy_filename(outname, param);
663 break;
665 case 'f': /* output format */
666 ofmt = ofmt_find(param, &ofmt_alias);
667 if (!ofmt) {
668 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
669 "unrecognised output format `%s' - "
670 "use -hf for a list", param);
672 break;
674 case 'O': /* Optimization level */
676 int opt;
678 if (!*param) {
679 /* Naked -O == -Ox */
680 optimizing = MAX_OPTIMIZE;
681 } else {
682 while (*param) {
683 switch (*param) {
684 case '0': case '1': case '2': case '3': case '4':
685 case '5': case '6': case '7': case '8': case '9':
686 opt = strtoul(param, &param, 10);
688 /* -O0 -> optimizing == -1, 0.98 behaviour */
689 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
690 if (opt < 2)
691 optimizing = opt - 1;
692 else
693 optimizing = opt;
694 break;
696 case 'v':
697 case '+':
698 param++;
699 opt_verbose_info = true;
700 break;
702 case 'x':
703 param++;
704 optimizing = MAX_OPTIMIZE;
705 break;
707 default:
708 nasm_error(ERR_FATAL,
709 "unknown optimization option -O%c\n",
710 *param);
711 break;
714 if (optimizing > MAX_OPTIMIZE)
715 optimizing = MAX_OPTIMIZE;
717 break;
720 case 'p': /* pre-include */
721 case 'P':
722 pp_pre_include(param);
723 break;
725 case 'd': /* pre-define */
726 case 'D':
727 pp_pre_define(param);
728 break;
730 case 'u': /* un-define */
731 case 'U':
732 pp_pre_undefine(param);
733 break;
735 case 'i': /* include search path */
736 case 'I':
737 pp_include_path(param);
738 break;
740 case 'l': /* listing file */
741 copy_filename(listname, param);
742 break;
744 case 'Z': /* error messages file */
745 copy_filename(errname, param);
746 break;
748 case 'F': /* specify debug format */
749 ofmt->current_dfmt = dfmt_find(ofmt, param);
750 if (!ofmt->current_dfmt) {
751 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
752 "unrecognized debug format `%s' for"
753 " output format `%s'",
754 param, ofmt->shortname);
756 using_debug_info = true;
757 break;
759 case 'X': /* specify error reporting format */
760 if (nasm_stricmp("vc", param) == 0)
761 nasm_set_verror(nasm_verror_vc);
762 else if (nasm_stricmp("gnu", param) == 0)
763 nasm_set_verror(nasm_verror_gnu);
764 else
765 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
766 "unrecognized error reporting format `%s'",
767 param);
768 break;
770 case 'g':
771 using_debug_info = true;
772 break;
774 case 'h':
775 printf
776 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
777 "[-l listfile]\n"
778 " [options...] [--] filename\n"
779 " or nasm -v for version info\n\n"
780 " -t assemble in SciTech TASM compatible mode\n"
781 " -g generate debug information in selected format\n");
782 printf
783 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
784 " -a don't preprocess (assemble only)\n"
785 " -M generate Makefile dependencies on stdout\n"
786 " -MG d:o, missing files assumed generated\n"
787 " -MF <file> set Makefile dependency file\n"
788 " -MD <file> assemble and generate dependencies\n"
789 " -MT <file> dependency target name\n"
790 " -MQ <file> dependency target name (quoted)\n"
791 " -MP emit phony target\n\n"
792 " -Z<file> redirect error messages to file\n"
793 " -s redirect error messages to stdout\n\n"
794 " -F format select a debugging format\n\n"
795 " -I<path> adds a pathname to the include file path\n");
796 printf
797 (" -O<digit> optimize branch offsets\n"
798 " -O0: No optimization (default)\n"
799 " -O1: Minimal optimization\n"
800 " -Ox: Multipass optimization (recommended)\n\n"
801 " -P<file> pre-includes a file\n"
802 " -D<macro>[=<value>] pre-defines a macro\n"
803 " -U<macro> undefines a macro\n"
804 " -X<format> specifies error reporting format (gnu or vc)\n"
805 " -w+foo enables warning foo (equiv. -Wfoo)\n"
806 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
807 "--prefix,--postfix\n"
808 " this options prepend or append the given argument to all\n"
809 " extern and global variables\n\n"
810 "Warnings:\n");
811 for (i = 0; i <= ERR_WARN_MAX; i++)
812 printf(" %-23s %s (default %s)\n",
813 warnings[i].name, warnings[i].help,
814 warnings[i].enabled ? "on" : "off");
815 printf
816 ("\nresponse files should contain command line parameters"
817 ", one per line.\n");
818 if (p[2] == 'f') {
819 printf("\nvalid output formats for -f are"
820 " (`*' denotes default):\n");
821 ofmt_list(ofmt, stdout);
822 } else {
823 printf("\nFor a list of valid output formats, use -hf.\n");
824 printf("For a list of debug formats, use -f <form> -y.\n");
826 exit(0); /* never need usage message here */
827 break;
829 case 'y':
830 printf("\nvalid debug formats for '%s' output format are"
831 " ('*' denotes default):\n", ofmt->shortname);
832 dfmt_list(ofmt, stdout);
833 exit(0);
834 break;
836 case 't':
837 tasm_compatible_mode = true;
838 break;
840 case 'v':
841 printf("NASM version %s compiled on %s%s\n",
842 nasm_version, nasm_date, nasm_compile_options);
843 exit(0); /* never need usage message here */
844 break;
846 case 'e': /* preprocess only */
847 case 'E':
848 operating_mode = op_preprocess;
849 break;
851 case 'a': /* assemble only - don't preprocess */
852 preproc = &no_pp;
853 break;
855 case 'W':
856 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
857 do_warn = false;
858 param += 3;
859 } else {
860 do_warn = true;
862 goto set_warning;
864 case 'w':
865 if (param[0] != '+' && param[0] != '-') {
866 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
867 "invalid option to `-w'");
868 break;
870 do_warn = (param[0] == '+');
871 param++;
873 set_warning:
874 for (i = 0; i <= ERR_WARN_MAX; i++) {
875 if (!nasm_stricmp(param, warnings[i].name))
876 break;
878 if (i <= ERR_WARN_MAX) {
879 warning_on_global[i] = do_warn;
880 } else if (!nasm_stricmp(param, "all")) {
881 for (i = 1; i <= ERR_WARN_MAX; i++)
882 warning_on_global[i] = do_warn;
883 } else if (!nasm_stricmp(param, "none")) {
884 for (i = 1; i <= ERR_WARN_MAX; i++)
885 warning_on_global[i] = !do_warn;
886 } else {
887 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
888 "invalid warning `%s'", param);
890 break;
892 case 'M':
893 switch (p[2]) {
894 case 0:
895 operating_mode = op_depend;
896 break;
897 case 'G':
898 operating_mode = op_depend;
899 depend_missing_ok = true;
900 break;
901 case 'P':
902 depend_emit_phony = true;
903 break;
904 case 'D':
905 depend_file = q;
906 advance = true;
907 break;
908 case 'T':
909 depend_target = q;
910 advance = true;
911 break;
912 case 'Q':
913 depend_target = quote_for_make(q);
914 advance = true;
915 break;
916 default:
917 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
918 "unknown dependency option `-M%c'", p[2]);
919 break;
921 if (advance && (!q || !q[0])) {
922 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
923 "option `-M%c' requires a parameter", p[2]);
924 break;
926 break;
928 case '-':
930 int s;
932 if (p[2] == 0) { /* -- => stop processing options */
933 stopoptions = 1;
934 break;
936 for (s = 0; textopts[s].label; s++) {
937 if (!nasm_stricmp(p + 2, textopts[s].label)) {
938 break;
942 switch (s) {
944 case OPT_PREFIX:
945 case OPT_POSTFIX:
947 if (!q) {
948 nasm_error(ERR_NONFATAL | ERR_NOFILE |
949 ERR_USAGE,
950 "option `--%s' requires an argument",
951 p + 2);
952 break;
953 } else {
954 advance = 1, param = q;
957 if (s == OPT_PREFIX) {
958 strncpy(lprefix, param, PREFIX_MAX - 1);
959 lprefix[PREFIX_MAX - 1] = 0;
960 break;
962 if (s == OPT_POSTFIX) {
963 strncpy(lpostfix, param, POSTFIX_MAX - 1);
964 lpostfix[POSTFIX_MAX - 1] = 0;
965 break;
967 break;
969 default:
971 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
972 "unrecognised option `--%s'", p + 2);
973 break;
976 break;
979 default:
980 if (!ofmt->setinfo(GI_SWITCH, &p))
981 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
982 "unrecognised option `-%c'", p[1]);
983 break;
985 } else {
986 if (*inname) {
987 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
988 "more than one input file specified");
989 } else {
990 copy_filename(inname, p);
994 return advance;
997 #define ARG_BUF_DELTA 128
999 static void process_respfile(FILE * rfile)
1001 char *buffer, *p, *q, *prevarg;
1002 int bufsize, prevargsize;
1004 bufsize = prevargsize = ARG_BUF_DELTA;
1005 buffer = nasm_malloc(ARG_BUF_DELTA);
1006 prevarg = nasm_malloc(ARG_BUF_DELTA);
1007 prevarg[0] = '\0';
1009 while (1) { /* Loop to handle all lines in file */
1010 p = buffer;
1011 while (1) { /* Loop to handle long lines */
1012 q = fgets(p, bufsize - (p - buffer), rfile);
1013 if (!q)
1014 break;
1015 p += strlen(p);
1016 if (p > buffer && p[-1] == '\n')
1017 break;
1018 if (p - buffer > bufsize - 10) {
1019 int offset;
1020 offset = p - buffer;
1021 bufsize += ARG_BUF_DELTA;
1022 buffer = nasm_realloc(buffer, bufsize);
1023 p = buffer + offset;
1027 if (!q && p == buffer) {
1028 if (prevarg[0])
1029 process_arg(prevarg, NULL);
1030 nasm_free(buffer);
1031 nasm_free(prevarg);
1032 return;
1036 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1037 * them are present at the end of the line.
1039 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1041 while (p > buffer && nasm_isspace(p[-1]))
1042 *--p = '\0';
1044 p = nasm_skip_spaces(buffer);
1046 if (process_arg(prevarg, p))
1047 *p = '\0';
1049 if ((int) strlen(p) > prevargsize - 10) {
1050 prevargsize += ARG_BUF_DELTA;
1051 prevarg = nasm_realloc(prevarg, prevargsize);
1053 strncpy(prevarg, p, prevargsize);
1057 /* Function to process args from a string of args, rather than the
1058 * argv array. Used by the environment variable and response file
1059 * processing.
1061 static void process_args(char *args)
1063 char *p, *q, *arg, *prevarg;
1064 char separator = ' ';
1066 p = args;
1067 if (*p && *p != '-')
1068 separator = *p++;
1069 arg = NULL;
1070 while (*p) {
1071 q = p;
1072 while (*p && *p != separator)
1073 p++;
1074 while (*p == separator)
1075 *p++ = '\0';
1076 prevarg = arg;
1077 arg = q;
1078 if (process_arg(prevarg, arg))
1079 arg = NULL;
1081 if (arg)
1082 process_arg(arg, NULL);
1085 static void process_response_file(const char *file)
1087 char str[2048];
1088 FILE *f = fopen(file, "r");
1089 if (!f) {
1090 perror(file);
1091 exit(-1);
1093 while (fgets(str, sizeof str, f)) {
1094 process_args(str);
1096 fclose(f);
1099 static void parse_cmdline(int argc, char **argv)
1101 FILE *rfile;
1102 char *envreal, *envcopy = NULL, *p;
1103 int i;
1105 *inname = *outname = *listname = *errname = '\0';
1107 for (i = 0; i <= ERR_WARN_MAX; i++)
1108 warning_on_global[i] = warnings[i].enabled;
1111 * First, process the NASMENV environment variable.
1113 envreal = getenv("NASMENV");
1114 if (envreal) {
1115 envcopy = nasm_strdup(envreal);
1116 process_args(envcopy);
1117 nasm_free(envcopy);
1121 * Now process the actual command line.
1123 while (--argc) {
1124 bool advance;
1125 argv++;
1126 if (argv[0][0] == '@') {
1128 * We have a response file, so process this as a set of
1129 * arguments like the environment variable. This allows us
1130 * to have multiple arguments on a single line, which is
1131 * different to the -@resp file processing below for regular
1132 * NASM.
1134 process_response_file(argv[0]+1);
1135 argc--;
1136 argv++;
1138 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1139 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1140 if (p) {
1141 rfile = fopen(p, "r");
1142 if (rfile) {
1143 process_respfile(rfile);
1144 fclose(rfile);
1145 } else
1146 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1147 "unable to open response file `%s'", p);
1149 } else
1150 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1151 argv += advance, argc -= advance;
1155 * Look for basic command line typos. This definitely doesn't
1156 * catch all errors, but it might help cases of fumbled fingers.
1158 if (!*inname)
1159 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1160 "no input file specified");
1161 else if (!strcmp(inname, errname) ||
1162 !strcmp(inname, outname) ||
1163 !strcmp(inname, listname) ||
1164 (depend_file && !strcmp(inname, depend_file)))
1165 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1166 "file `%s' is both input and output file",
1167 inname);
1169 if (*errname) {
1170 error_file = fopen(errname, "w");
1171 if (!error_file) {
1172 error_file = stderr; /* Revert to default! */
1173 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1174 "cannot open file `%s' for error messages",
1175 errname);
1180 static enum directives getkw(char **directive, char **value);
1182 static void assemble_file(char *fname, StrList **depend_ptr)
1184 char *directive, *value, *p, *q, *special, *line;
1185 insn output_ins;
1186 int i, validid;
1187 bool rn_error;
1188 int32_t seg;
1189 int64_t offs;
1190 struct tokenval tokval;
1191 expr *e;
1192 int pass_max;
1194 if (cmd_sb == 32 && cmd_cpu < IF_386)
1195 nasm_error(ERR_FATAL, "command line: "
1196 "32-bit segment size requires a higher cpu");
1198 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1199 for (passn = 1; pass0 <= 2; passn++) {
1200 int pass1, pass2;
1201 ldfunc def_label;
1203 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1204 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1205 /* pass0 0, 0, 0, ..., 1, 2 */
1207 def_label = passn > 1 ? redefine_label : define_label;
1209 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1210 cpu = cmd_cpu;
1211 if (pass0 == 2) {
1212 if (*listname)
1213 nasmlist.init(listname, nasm_error);
1215 in_abs_seg = false;
1216 global_offset_changed = 0; /* set by redefine_label */
1217 location.segment = ofmt->section(NULL, pass2, &sb);
1218 globalbits = sb;
1219 if (passn > 1) {
1220 saa_rewind(forwrefs);
1221 forwref = saa_rstruct(forwrefs);
1222 raa_free(offsets);
1223 offsets = raa_init();
1225 preproc->reset(fname, pass1, &nasmlist,
1226 pass1 == 2 ? depend_ptr : NULL);
1227 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1229 globallineno = 0;
1230 if (passn == 1)
1231 location.known = true;
1232 location.offset = offs = GET_CURR_OFFS;
1234 while ((line = preproc->getline())) {
1235 enum directives d;
1236 globallineno++;
1239 * Here we parse our directives; this is not handled by the
1240 * 'real' parser. This really should be a separate function.
1242 directive = line;
1243 d = getkw(&directive, &value);
1244 if (d) {
1245 int err = 0;
1247 switch (d) {
1248 case D_SEGMENT: /* [SEGMENT n] */
1249 case D_SECTION:
1250 seg = ofmt->section(value, pass2, &sb);
1251 if (seg == NO_SEG) {
1252 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1253 "segment name `%s' not recognized",
1254 value);
1255 } else {
1256 in_abs_seg = false;
1257 location.segment = seg;
1259 break;
1260 case D_SECTALIGN: /* [SECTALIGN n] */
1261 if (*value) {
1262 stdscan_reset();
1263 stdscan_set(value);
1264 tokval.t_type = TOKEN_INVALID;
1265 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1266 if (e) {
1267 unsigned int align = (unsigned int)e->value;
1268 if ((uint64_t)e->value > 0x7fffffff) {
1270 * FIXME: Please make some sane message here
1271 * ofmt should have some 'check' method which
1272 * would report segment alignment bounds.
1274 nasm_error(ERR_FATAL,
1275 "incorrect segment alignment `%s'", value);
1276 } else if (!is_power2(align)) {
1277 nasm_error(ERR_NONFATAL,
1278 "segment alignment `%s' is not power of two",
1279 value);
1281 /* callee should be able to handle all details */
1282 ofmt->sectalign(location.segment, align);
1285 break;
1286 case D_EXTERN: /* [EXTERN label:special] */
1287 if (*value == '$')
1288 value++; /* skip initial $ if present */
1289 if (pass0 == 2) {
1290 q = value;
1291 while (*q && *q != ':')
1292 q++;
1293 if (*q == ':') {
1294 *q++ = '\0';
1295 ofmt->symdef(value, 0L, 0L, 3, q);
1297 } else if (passn == 1) {
1298 q = value;
1299 validid = true;
1300 if (!isidstart(*q))
1301 validid = false;
1302 while (*q && *q != ':') {
1303 if (!isidchar(*q))
1304 validid = false;
1305 q++;
1307 if (!validid) {
1308 nasm_error(ERR_NONFATAL,
1309 "identifier expected after EXTERN");
1310 break;
1312 if (*q == ':') {
1313 *q++ = '\0';
1314 special = q;
1315 } else
1316 special = NULL;
1317 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1318 int temp = pass0;
1319 pass0 = 1; /* fake pass 1 in labels.c */
1320 declare_as_global(value, special);
1321 define_label(value, seg_alloc(), 0L, NULL,
1322 false, true);
1323 pass0 = temp;
1325 } /* else pass0 == 1 */
1326 break;
1327 case D_BITS: /* [BITS bits] */
1328 globalbits = sb = get_bits(value);
1329 break;
1330 case D_GLOBAL: /* [GLOBAL symbol:special] */
1331 if (*value == '$')
1332 value++; /* skip initial $ if present */
1333 if (pass0 == 2) { /* pass 2 */
1334 q = value;
1335 while (*q && *q != ':')
1336 q++;
1337 if (*q == ':') {
1338 *q++ = '\0';
1339 ofmt->symdef(value, 0L, 0L, 3, q);
1341 } else if (pass2 == 1) { /* pass == 1 */
1342 q = value;
1343 validid = true;
1344 if (!isidstart(*q))
1345 validid = false;
1346 while (*q && *q != ':') {
1347 if (!isidchar(*q))
1348 validid = false;
1349 q++;
1351 if (!validid) {
1352 nasm_error(ERR_NONFATAL,
1353 "identifier expected after GLOBAL");
1354 break;
1356 if (*q == ':') {
1357 *q++ = '\0';
1358 special = q;
1359 } else
1360 special = NULL;
1361 declare_as_global(value, special);
1362 } /* pass == 1 */
1363 break;
1364 case D_COMMON: /* [COMMON symbol size:special] */
1366 int64_t size;
1368 if (*value == '$')
1369 value++; /* skip initial $ if present */
1370 p = value;
1371 validid = true;
1372 if (!isidstart(*p))
1373 validid = false;
1374 while (*p && !nasm_isspace(*p)) {
1375 if (!isidchar(*p))
1376 validid = false;
1377 p++;
1379 if (!validid) {
1380 nasm_error(ERR_NONFATAL,
1381 "identifier expected after COMMON");
1382 break;
1384 if (*p) {
1385 p = nasm_zap_spaces_fwd(p);
1386 q = p;
1387 while (*q && *q != ':')
1388 q++;
1389 if (*q == ':') {
1390 *q++ = '\0';
1391 special = q;
1392 } else {
1393 special = NULL;
1395 size = readnum(p, &rn_error);
1396 if (rn_error) {
1397 nasm_error(ERR_NONFATAL,
1398 "invalid size specified"
1399 " in COMMON declaration");
1400 break;
1402 } else {
1403 nasm_error(ERR_NONFATAL,
1404 "no size specified in"
1405 " COMMON declaration");
1406 break;
1409 if (pass0 < 2) {
1410 define_common(value, seg_alloc(), size, special);
1411 } else if (pass0 == 2) {
1412 if (special)
1413 ofmt->symdef(value, 0L, 0L, 3, special);
1415 break;
1417 case D_ABSOLUTE: /* [ABSOLUTE address] */
1418 stdscan_reset();
1419 stdscan_set(value);
1420 tokval.t_type = TOKEN_INVALID;
1421 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1422 nasm_error, NULL);
1423 if (e) {
1424 if (!is_reloc(e))
1425 nasm_error(pass0 ==
1426 1 ? ERR_NONFATAL : ERR_PANIC,
1427 "cannot use non-relocatable expression as "
1428 "ABSOLUTE address");
1429 else {
1430 abs_seg = reloc_seg(e);
1431 abs_offset = reloc_value(e);
1433 } else if (passn == 1)
1434 abs_offset = 0x100; /* don't go near zero in case of / */
1435 else
1436 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1437 "in pass two");
1438 in_abs_seg = true;
1439 location.segment = NO_SEG;
1440 break;
1441 case D_DEBUG: /* [DEBUG] */
1443 char debugid[128];
1444 bool badid, overlong;
1446 p = value;
1447 q = debugid;
1448 badid = overlong = false;
1449 if (!isidstart(*p)) {
1450 badid = true;
1451 } else {
1452 while (*p && !nasm_isspace(*p)) {
1453 if (q >= debugid + sizeof debugid - 1) {
1454 overlong = true;
1455 break;
1457 if (!isidchar(*p))
1458 badid = true;
1459 *q++ = *p++;
1461 *q = 0;
1463 if (badid) {
1464 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1465 "identifier expected after DEBUG");
1466 break;
1468 if (overlong) {
1469 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1470 "DEBUG identifier too long");
1471 break;
1473 p = nasm_skip_spaces(p);
1474 if (pass0 == 2)
1475 dfmt->debug_directive(debugid, p);
1476 break;
1478 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1479 value = nasm_skip_spaces(value);
1480 switch(*value) {
1481 case '-': validid = 0; value++; break;
1482 case '+': validid = 1; value++; break;
1483 case '*': validid = 2; value++; break;
1484 default: validid = 1; break;
1487 for (i = 1; i <= ERR_WARN_MAX; i++)
1488 if (!nasm_stricmp(value, warnings[i].name))
1489 break;
1490 if (i <= ERR_WARN_MAX) {
1491 switch(validid) {
1492 case 0:
1493 warning_on[i] = false;
1494 break;
1495 case 1:
1496 warning_on[i] = true;
1497 break;
1498 case 2:
1499 warning_on[i] = warning_on_global[i];
1500 break;
1503 else
1504 nasm_error(ERR_NONFATAL,
1505 "invalid warning id in WARNING directive");
1506 break;
1507 case D_CPU: /* [CPU] */
1508 cpu = get_cpu(value);
1509 break;
1510 case D_LIST: /* [LIST {+|-}] */
1511 value = nasm_skip_spaces(value);
1512 if (*value == '+') {
1513 user_nolist = 0;
1514 } else {
1515 if (*value == '-') {
1516 user_nolist = 1;
1517 } else {
1518 err = 1;
1521 break;
1522 case D_DEFAULT: /* [DEFAULT] */
1523 stdscan_reset();
1524 stdscan_set(value);
1525 tokval.t_type = TOKEN_INVALID;
1526 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1527 switch ((int)tokval.t_integer) {
1528 case S_REL:
1529 globalrel = 1;
1530 break;
1531 case S_ABS:
1532 globalrel = 0;
1533 break;
1534 default:
1535 err = 1;
1536 break;
1538 } else {
1539 err = 1;
1541 break;
1542 case D_FLOAT:
1543 if (float_option(value)) {
1544 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1545 "unknown 'float' directive: %s",
1546 value);
1548 break;
1549 default:
1550 if (ofmt->directive(d, value, pass2))
1551 break;
1552 /* else fall through */
1553 case D_unknown:
1554 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1555 "unrecognised directive [%s]",
1556 directive);
1557 break;
1559 if (err) {
1560 nasm_error(ERR_NONFATAL,
1561 "invalid parameter to [%s] directive",
1562 directive);
1564 } else { /* it isn't a directive */
1565 parse_line(pass1, line, &output_ins, def_label);
1567 if (optimizing > 0) {
1568 if (forwref != NULL && globallineno == forwref->lineno) {
1569 output_ins.forw_ref = true;
1570 do {
1571 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1572 forwref = saa_rstruct(forwrefs);
1573 } while (forwref != NULL
1574 && forwref->lineno == globallineno);
1575 } else
1576 output_ins.forw_ref = false;
1578 if (output_ins.forw_ref) {
1579 if (passn == 1) {
1580 for (i = 0; i < output_ins.operands; i++) {
1581 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1582 struct forwrefinfo *fwinf =
1583 (struct forwrefinfo *)
1584 saa_wstruct(forwrefs);
1585 fwinf->lineno = globallineno;
1586 fwinf->operand = i;
1593 /* forw_ref */
1594 if (output_ins.opcode == I_EQU) {
1595 if (pass1 == 1) {
1597 * Special `..' EQUs get processed in pass two,
1598 * except `..@' macro-processor EQUs which are done
1599 * in the normal place.
1601 if (!output_ins.label)
1602 nasm_error(ERR_NONFATAL,
1603 "EQU not preceded by label");
1605 else if (output_ins.label[0] != '.' ||
1606 output_ins.label[1] != '.' ||
1607 output_ins.label[2] == '@') {
1608 if (output_ins.operands == 1 &&
1609 (output_ins.oprs[0].type & IMMEDIATE) &&
1610 output_ins.oprs[0].wrt == NO_SEG) {
1611 bool isext = !!(output_ins.oprs[0].opflags
1612 & OPFLAG_EXTERN);
1613 def_label(output_ins.label,
1614 output_ins.oprs[0].segment,
1615 output_ins.oprs[0].offset, NULL,
1616 false, isext);
1617 } else if (output_ins.operands == 2
1618 && (output_ins.oprs[0].type & IMMEDIATE)
1619 && (output_ins.oprs[0].type & COLON)
1620 && output_ins.oprs[0].segment == NO_SEG
1621 && output_ins.oprs[0].wrt == NO_SEG
1622 && (output_ins.oprs[1].type & IMMEDIATE)
1623 && output_ins.oprs[1].segment == NO_SEG
1624 && output_ins.oprs[1].wrt == NO_SEG) {
1625 def_label(output_ins.label,
1626 output_ins.oprs[0].offset | SEG_ABS,
1627 output_ins.oprs[1].offset,
1628 NULL, false, false);
1629 } else
1630 nasm_error(ERR_NONFATAL,
1631 "bad syntax for EQU");
1633 } else {
1635 * Special `..' EQUs get processed here, except
1636 * `..@' macro processor EQUs which are done above.
1638 if (output_ins.label[0] == '.' &&
1639 output_ins.label[1] == '.' &&
1640 output_ins.label[2] != '@') {
1641 if (output_ins.operands == 1 &&
1642 (output_ins.oprs[0].type & IMMEDIATE)) {
1643 define_label(output_ins.label,
1644 output_ins.oprs[0].segment,
1645 output_ins.oprs[0].offset,
1646 NULL, false, false);
1647 } else if (output_ins.operands == 2
1648 && (output_ins.oprs[0].type & IMMEDIATE)
1649 && (output_ins.oprs[0].type & COLON)
1650 && output_ins.oprs[0].segment == NO_SEG
1651 && (output_ins.oprs[1].type & IMMEDIATE)
1652 && output_ins.oprs[1].segment == NO_SEG) {
1653 define_label(output_ins.label,
1654 output_ins.oprs[0].offset | SEG_ABS,
1655 output_ins.oprs[1].offset,
1656 NULL, false, false);
1657 } else
1658 nasm_error(ERR_NONFATAL,
1659 "bad syntax for EQU");
1662 } else { /* instruction isn't an EQU */
1664 if (pass1 == 1) {
1666 int64_t l = insn_size(location.segment, offs, sb, cpu,
1667 &output_ins, nasm_error);
1669 /* if (using_debug_info) && output_ins.opcode != -1) */
1670 if (using_debug_info)
1671 { /* fbk 03/25/01 */
1672 /* this is done here so we can do debug type info */
1673 int32_t typeinfo =
1674 TYS_ELEMENTS(output_ins.operands);
1675 switch (output_ins.opcode) {
1676 case I_RESB:
1677 typeinfo =
1678 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1679 break;
1680 case I_RESW:
1681 typeinfo =
1682 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1683 break;
1684 case I_RESD:
1685 typeinfo =
1686 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1687 break;
1688 case I_RESQ:
1689 typeinfo =
1690 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1691 break;
1692 case I_REST:
1693 typeinfo =
1694 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1695 break;
1696 case I_RESO:
1697 typeinfo =
1698 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1699 break;
1700 case I_RESY:
1701 typeinfo =
1702 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1703 break;
1704 case I_DB:
1705 typeinfo |= TY_BYTE;
1706 break;
1707 case I_DW:
1708 typeinfo |= TY_WORD;
1709 break;
1710 case I_DD:
1711 if (output_ins.eops_float)
1712 typeinfo |= TY_FLOAT;
1713 else
1714 typeinfo |= TY_DWORD;
1715 break;
1716 case I_DQ:
1717 typeinfo |= TY_QWORD;
1718 break;
1719 case I_DT:
1720 typeinfo |= TY_TBYTE;
1721 break;
1722 case I_DO:
1723 typeinfo |= TY_OWORD;
1724 break;
1725 case I_DY:
1726 typeinfo |= TY_YWORD;
1727 break;
1728 default:
1729 typeinfo = TY_LABEL;
1733 dfmt->debug_typevalue(typeinfo);
1735 if (l != -1) {
1736 offs += l;
1737 SET_CURR_OFFS(offs);
1740 * else l == -1 => invalid instruction, which will be
1741 * flagged as an error on pass 2
1744 } else {
1745 offs += assemble(location.segment, offs, sb, cpu,
1746 &output_ins, ofmt, nasm_error,
1747 &nasmlist);
1748 SET_CURR_OFFS(offs);
1751 } /* not an EQU */
1752 cleanup_insn(&output_ins);
1754 nasm_free(line);
1755 location.offset = offs = GET_CURR_OFFS;
1756 } /* end while (line = preproc->getline... */
1758 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1759 nasm_error(ERR_NONFATAL,
1760 "phase error detected at end of assembly.");
1762 if (pass1 == 1)
1763 preproc->cleanup(1);
1765 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1766 pass0++;
1767 } else if (global_offset_changed &&
1768 global_offset_changed < prev_offset_changed) {
1769 prev_offset_changed = global_offset_changed;
1770 stall_count = 0;
1771 } else {
1772 stall_count++;
1775 if (terminate_after_phase)
1776 break;
1778 if ((stall_count > 997) || (passn >= pass_max)) {
1779 /* We get here if the labels don't converge
1780 * Example: FOO equ FOO + 1
1782 nasm_error(ERR_NONFATAL,
1783 "Can't find valid values for all labels "
1784 "after %d passes, giving up.", passn);
1785 nasm_error(ERR_NONFATAL,
1786 "Possible causes: recursive EQUs, macro abuse.");
1787 break;
1791 preproc->cleanup(0);
1792 nasmlist.cleanup();
1793 if (!terminate_after_phase && opt_verbose_info) {
1794 /* -On and -Ov switches */
1795 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1799 static enum directives getkw(char **directive, char **value)
1801 char *p, *q, *buf;
1803 buf = nasm_skip_spaces(*directive);
1805 /* it should be enclosed in [ ] */
1806 if (*buf != '[')
1807 return D_none;
1808 q = strchr(buf, ']');
1809 if (!q)
1810 return D_none;
1812 /* stip off the comments */
1813 p = strchr(buf, ';');
1814 if (p) {
1815 if (p < q) /* ouch! somwhere inside */
1816 return D_none;
1817 *p = '\0';
1820 /* no brace, no trailing spaces */
1821 *q = '\0';
1822 nasm_zap_spaces_rev(--q);
1824 /* directive */
1825 p = nasm_skip_spaces(++buf);
1826 q = nasm_skip_word(p);
1827 if (!q)
1828 return D_none; /* sigh... no value there */
1829 *q = '\0';
1830 *directive = p;
1832 /* and value finally */
1833 p = nasm_skip_spaces(++q);
1834 *value = p;
1836 return find_directive(*directive);
1840 * gnu style error reporting
1841 * This function prints an error message to error_file in the
1842 * style used by GNU. An example would be:
1843 * file.asm:50: error: blah blah blah
1844 * where file.asm is the name of the file, 50 is the line number on
1845 * which the error occurs (or is detected) and "error:" is one of
1846 * the possible optional diagnostics -- it can be "error" or "warning"
1847 * or something else. Finally the line terminates with the actual
1848 * error message.
1850 * @param severity the severity of the warning or error
1851 * @param fmt the printf style format string
1853 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1855 char *currentfile = NULL;
1856 int32_t lineno = 0;
1858 if (is_suppressed_warning(severity))
1859 return;
1861 if (!(severity & ERR_NOFILE))
1862 src_get(&lineno, &currentfile);
1864 if (currentfile) {
1865 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1866 nasm_free(currentfile);
1867 } else {
1868 fputs("nasm: ", error_file);
1871 nasm_verror_common(severity, fmt, ap);
1875 * MS style error reporting
1876 * This function prints an error message to error_file in the
1877 * style used by Visual C and some other Microsoft tools. An example
1878 * would be:
1879 * file.asm(50) : error: blah blah blah
1880 * where file.asm is the name of the file, 50 is the line number on
1881 * which the error occurs (or is detected) and "error:" is one of
1882 * the possible optional diagnostics -- it can be "error" or "warning"
1883 * or something else. Finally the line terminates with the actual
1884 * error message.
1886 * @param severity the severity of the warning or error
1887 * @param fmt the printf style format string
1889 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1891 char *currentfile = NULL;
1892 int32_t lineno = 0;
1894 if (is_suppressed_warning(severity))
1895 return;
1897 if (!(severity & ERR_NOFILE))
1898 src_get(&lineno, &currentfile);
1900 if (currentfile) {
1901 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1902 nasm_free(currentfile);
1903 } else {
1904 fputs("nasm: ", error_file);
1907 nasm_verror_common(severity, fmt, ap);
1911 * check for supressed warning
1912 * checks for suppressed warning or pass one only warning and we're
1913 * not in pass 1
1915 * @param severity the severity of the warning or error
1916 * @return true if we should abort error/warning printing
1918 static bool is_suppressed_warning(int severity)
1920 /* Not a warning at all */
1921 if ((severity & ERR_MASK) != ERR_WARNING)
1922 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 /* Might be a warning but suppresed explicitly */
1930 if (severity & ERR_WARN_MASK)
1931 return !warning_on[WARN_IDX(severity)];
1932 else
1933 return false;
1937 * common error reporting
1938 * This is the common back end of the error reporting schemes currently
1939 * implemented. It prints the nature of the warning and then the
1940 * specific error message to error_file and may or may not return. It
1941 * doesn't return if the error severity is a "panic" or "debug" type.
1943 * @param severity the severity of the warning or error
1944 * @param fmt the printf style format string
1946 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1948 char msg[1024];
1949 const char *pfx;
1951 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1952 case ERR_WARNING:
1953 pfx = "warning: ";
1954 break;
1955 case ERR_NONFATAL:
1956 pfx = "error: ";
1957 break;
1958 case ERR_FATAL:
1959 pfx = "fatal: ";
1960 break;
1961 case ERR_PANIC:
1962 pfx = "panic: ";
1963 break;
1964 case ERR_DEBUG:
1965 pfx = "debug: ";
1966 break;
1967 default:
1968 pfx = "";
1969 break;
1972 vsnprintf(msg, sizeof msg, fmt, args);
1974 fprintf(error_file, "%s%s\n", pfx, msg);
1976 if (*listname)
1977 nasmlist.error(severity, pfx, msg);
1979 if (severity & ERR_USAGE)
1980 want_usage = true;
1982 switch (severity & ERR_MASK) {
1983 case ERR_DEBUG:
1984 /* no further action, by definition */
1985 break;
1986 case ERR_WARNING:
1987 /* Treat warnings as errors */
1988 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1989 terminate_after_phase = true;
1990 break;
1991 case ERR_NONFATAL:
1992 terminate_after_phase = true;
1993 break;
1994 case ERR_FATAL:
1995 if (ofile) {
1996 fclose(ofile);
1997 remove(outname);
1998 ofile = NULL;
2000 if (want_usage)
2001 usage();
2002 exit(1); /* instantly die */
2003 break; /* placate silly compilers */
2004 case ERR_PANIC:
2005 fflush(NULL);
2006 /* abort(); *//* halt, catch fire, and dump core */
2007 exit(3);
2008 break;
2012 static void usage(void)
2014 fputs("type `nasm -h' for help\n", error_file);
2017 #define BUF_DELTA 512
2019 static FILE *no_pp_fp;
2020 static ListGen *no_pp_list;
2021 static int32_t no_pp_lineinc;
2023 static void no_pp_reset(char *file, int pass, ListGen * listgen,
2024 StrList **deplist)
2026 src_set_fname(nasm_strdup(file));
2027 src_set_linnum(0);
2028 no_pp_lineinc = 1;
2029 no_pp_fp = fopen(file, "r");
2030 if (!no_pp_fp)
2031 nasm_error(ERR_FATAL | ERR_NOFILE,
2032 "unable to open input file `%s'", file);
2033 no_pp_list = listgen;
2034 (void)pass; /* placate compilers */
2036 if (deplist) {
2037 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2038 sl->next = NULL;
2039 strcpy(sl->str, file);
2040 *deplist = sl;
2044 static char *no_pp_getline(void)
2046 char *buffer, *p, *q;
2047 int bufsize;
2049 bufsize = BUF_DELTA;
2050 buffer = nasm_malloc(BUF_DELTA);
2051 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2053 while (1) { /* Loop to handle %line */
2055 p = buffer;
2056 while (1) { /* Loop to handle long lines */
2057 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2058 if (!q)
2059 break;
2060 p += strlen(p);
2061 if (p > buffer && p[-1] == '\n')
2062 break;
2063 if (p - buffer > bufsize - 10) {
2064 int offset;
2065 offset = p - buffer;
2066 bufsize += BUF_DELTA;
2067 buffer = nasm_realloc(buffer, bufsize);
2068 p = buffer + offset;
2072 if (!q && p == buffer) {
2073 nasm_free(buffer);
2074 return NULL;
2078 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2079 * them are present at the end of the line.
2081 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2083 if (!nasm_strnicmp(buffer, "%line", 5)) {
2084 int32_t ln;
2085 int li;
2086 char *nm = nasm_malloc(strlen(buffer));
2087 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2088 nasm_free(src_set_fname(nm));
2089 src_set_linnum(ln);
2090 no_pp_lineinc = li;
2091 continue;
2093 nasm_free(nm);
2095 break;
2098 no_pp_list->line(LIST_READ, buffer);
2100 return buffer;
2103 static void no_pp_cleanup(int pass)
2105 (void)pass; /* placate GCC */
2106 if (no_pp_fp) {
2107 fclose(no_pp_fp);
2108 no_pp_fp = NULL;
2112 static uint32_t get_cpu(char *value)
2114 if (!strcmp(value, "8086"))
2115 return IF_8086;
2116 if (!strcmp(value, "186"))
2117 return IF_186;
2118 if (!strcmp(value, "286"))
2119 return IF_286;
2120 if (!strcmp(value, "386"))
2121 return IF_386;
2122 if (!strcmp(value, "486"))
2123 return IF_486;
2124 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2125 return IF_PENT;
2126 if (!strcmp(value, "686") ||
2127 !nasm_stricmp(value, "ppro") ||
2128 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2129 return IF_P6;
2130 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2131 return IF_KATMAI;
2132 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2133 !nasm_stricmp(value, "willamette"))
2134 return IF_WILLAMETTE;
2135 if (!nasm_stricmp(value, "prescott"))
2136 return IF_PRESCOTT;
2137 if (!nasm_stricmp(value, "x64") ||
2138 !nasm_stricmp(value, "x86-64"))
2139 return IF_X86_64;
2140 if (!nasm_stricmp(value, "ia64") ||
2141 !nasm_stricmp(value, "ia-64") ||
2142 !nasm_stricmp(value, "itanium") ||
2143 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2144 return IF_IA64;
2146 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2147 "unknown 'cpu' type");
2149 return IF_PLEVEL; /* the maximum level */
2152 static int get_bits(char *value)
2154 int i;
2156 if ((i = atoi(value)) == 16)
2157 return i; /* set for a 16-bit segment */
2158 else if (i == 32) {
2159 if (cpu < IF_386) {
2160 nasm_error(ERR_NONFATAL,
2161 "cannot specify 32-bit segment on processor below a 386");
2162 i = 16;
2164 } else if (i == 64) {
2165 if (cpu < IF_X86_64) {
2166 nasm_error(ERR_NONFATAL,
2167 "cannot specify 64-bit segment on processor below an x86-64");
2168 i = 16;
2170 if (i != maxbits) {
2171 nasm_error(ERR_NONFATAL,
2172 "%s output format does not support 64-bit code",
2173 ofmt->shortname);
2174 i = 16;
2176 } else {
2177 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2178 "`%s' is not a valid segment size; must be 16, 32 or 64",
2179 value);
2180 i = 16;
2182 return i;