preproc: Split get rid of global preproc methods
[nasm/sigaren-mirror.git] / nasm.c
blob21f7139ee2c276e210648258a0c701be9398b767
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);
177 static void no_pp_extra_stdmac(macros_t *macros);
178 static void no_pp_pre_define(char *definition);
179 static void no_pp_pre_undefine(char *definition);
180 static void no_pp_pre_include(char *fname);
181 static void no_pp_include_path(char *path);
183 static struct preproc_ops no_pp = {
184 no_pp_reset,
185 no_pp_getline,
186 no_pp_cleanup,
187 no_pp_extra_stdmac,
188 no_pp_pre_define,
189 no_pp_pre_undefine,
190 no_pp_pre_include,
191 no_pp_include_path
195 * get/set current offset...
197 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
198 raa_read(offsets,location.segment))
199 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
200 (void)(offsets=raa_write(offsets,location.segment,(x))))
202 static bool want_usage;
203 static bool terminate_after_phase;
204 int user_nolist = 0; /* fbk 9/2/00 */
206 static void nasm_fputs(const char *line, FILE * outfile)
208 if (outfile) {
209 fputs(line, outfile);
210 putc('\n', outfile);
211 } else
212 puts(line);
215 /* Convert a struct tm to a POSIX-style time constant */
216 static int64_t posix_mktime(struct tm *tm)
218 int64_t t;
219 int64_t y = tm->tm_year;
221 /* See IEEE 1003.1:2004, section 4.14 */
223 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
224 t += tm->tm_yday;
225 t *= 24;
226 t += tm->tm_hour;
227 t *= 60;
228 t += tm->tm_min;
229 t *= 60;
230 t += tm->tm_sec;
232 return t;
235 static void define_macros_early(void)
237 char temp[128];
238 struct tm lt, *lt_p, gm, *gm_p;
239 int64_t posix_time;
241 lt_p = localtime(&official_compile_time);
242 if (lt_p) {
243 lt = *lt_p;
245 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
246 preproc->pre_define(temp);
247 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
248 preproc->pre_define(temp);
249 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
250 preproc->pre_define(temp);
251 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
252 preproc->pre_define(temp);
255 gm_p = gmtime(&official_compile_time);
256 if (gm_p) {
257 gm = *gm_p;
259 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
260 preproc->pre_define(temp);
261 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
262 preproc->pre_define(temp);
263 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
264 preproc->pre_define(temp);
265 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
266 preproc->pre_define(temp);
269 if (gm_p)
270 posix_time = posix_mktime(&gm);
271 else if (lt_p)
272 posix_time = posix_mktime(&lt);
273 else
274 posix_time = 0;
276 if (posix_time) {
277 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
278 preproc->pre_define(temp);
282 static void define_macros_late(void)
284 char temp[128];
287 * In case if output format is defined by alias
288 * we have to put shortname of the alias itself here
289 * otherwise ABI backward compatibility gets broken.
291 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
292 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
293 preproc->pre_define(temp);
296 static void emit_dependencies(StrList *list)
298 FILE *deps;
299 int linepos, len;
300 StrList *l, *nl;
302 if (depend_file && strcmp(depend_file, "-")) {
303 deps = fopen(depend_file, "w");
304 if (!deps) {
305 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
306 "unable to write dependency file `%s'", depend_file);
307 return;
309 } else {
310 deps = stdout;
313 linepos = fprintf(deps, "%s:", depend_target);
314 list_for_each(l, list) {
315 len = strlen(l->str);
316 if (linepos + len > 62) {
317 fprintf(deps, " \\\n ");
318 linepos = 1;
320 fprintf(deps, " %s", l->str);
321 linepos += len+1;
323 fprintf(deps, "\n\n");
325 list_for_each_safe(l, nl, list) {
326 if (depend_emit_phony)
327 fprintf(deps, "%s:\n\n", l->str);
328 nasm_free(l);
331 if (deps != stdout)
332 fclose(deps);
335 int main(int argc, char **argv)
337 StrList *depend_list = NULL, **depend_ptr;
339 time(&official_compile_time);
341 pass0 = 0;
342 want_usage = terminate_after_phase = false;
343 nasm_set_verror(nasm_verror_gnu);
345 error_file = stderr;
347 tolower_init();
349 nasm_init_malloc_error();
350 offsets = raa_init();
351 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
353 preproc = &nasmpp;
354 operating_mode = op_normal;
356 seg_init();
358 /* Define some macros dependent on the runtime, but not
359 on the command line. */
360 define_macros_early();
362 parse_cmdline(argc, argv);
364 if (terminate_after_phase) {
365 if (want_usage)
366 usage();
367 return 1;
370 /* If debugging info is disabled, suppress any debug calls */
371 if (!using_debug_info)
372 ofmt->current_dfmt = &null_debug_form;
374 if (ofmt->stdmac)
375 preproc->extra_stdmac(ofmt->stdmac);
376 parser_global_info(&location);
377 eval_global_info(ofmt, lookup_label, &location);
379 /* define some macros dependent of command-line */
380 define_macros_late();
382 depend_ptr = (depend_file || (operating_mode == op_depend))
383 ? &depend_list : NULL;
384 if (!depend_target)
385 depend_target = outname;
387 switch (operating_mode) {
388 case op_depend:
390 char *line;
392 if (depend_missing_ok)
393 preproc->include_path(NULL); /* "assume generated" */
395 preproc->reset(inname, 0, &nasmlist, depend_ptr);
396 if (outname[0] == '\0')
397 ofmt->filename(inname, outname);
398 ofile = NULL;
399 while ((line = preproc->getline()))
400 nasm_free(line);
401 preproc->cleanup(0);
403 break;
405 case op_preprocess:
407 char *line;
408 char *file_name = NULL;
409 int32_t prior_linnum = 0;
410 int lineinc = 0;
412 if (*outname) {
413 ofile = fopen(outname, "w");
414 if (!ofile)
415 nasm_error(ERR_FATAL | ERR_NOFILE,
416 "unable to open output file `%s'",
417 outname);
418 } else
419 ofile = NULL;
421 location.known = false;
423 /* pass = 1; */
424 preproc->reset(inname, 3, &nasmlist, depend_ptr);
425 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
427 while ((line = preproc->getline())) {
429 * We generate %line directives if needed for later programs
431 int32_t linnum = prior_linnum += lineinc;
432 int altline = src_get(&linnum, &file_name);
433 if (altline) {
434 if (altline == 1 && lineinc == 1)
435 nasm_fputs("", ofile);
436 else {
437 lineinc = (altline != -1 || lineinc != 1);
438 fprintf(ofile ? ofile : stdout,
439 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
440 file_name);
442 prior_linnum = linnum;
444 nasm_fputs(line, ofile);
445 nasm_free(line);
447 nasm_free(file_name);
448 preproc->cleanup(0);
449 if (ofile)
450 fclose(ofile);
451 if (ofile && terminate_after_phase)
452 remove(outname);
453 ofile = NULL;
455 break;
457 case op_normal:
460 * We must call ofmt->filename _anyway_, even if the user
461 * has specified their own output file, because some
462 * formats (eg OBJ and COFF) use ofmt->filename to find out
463 * the name of the input file and then put that inside the
464 * file.
466 ofmt->filename(inname, outname);
468 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
469 if (!ofile) {
470 nasm_error(ERR_FATAL | ERR_NOFILE,
471 "unable to open output file `%s'", outname);
475 * We must call init_labels() before ofmt->init() since
476 * some object formats will want to define labels in their
477 * init routines. (eg OS/2 defines the FLAT group)
479 init_labels();
481 ofmt->init();
482 dfmt = ofmt->current_dfmt;
483 dfmt->init();
485 assemble_file(inname, depend_ptr);
487 if (!terminate_after_phase) {
488 ofmt->cleanup(using_debug_info);
489 cleanup_labels();
490 fflush(ofile);
491 if (ferror(ofile)) {
492 nasm_error(ERR_NONFATAL|ERR_NOFILE,
493 "write error on output file `%s'", outname);
497 if (ofile) {
498 fclose(ofile);
499 if (terminate_after_phase)
500 remove(outname);
501 ofile = NULL;
504 break;
507 if (depend_list && !terminate_after_phase)
508 emit_dependencies(depend_list);
510 if (want_usage)
511 usage();
513 raa_free(offsets);
514 saa_free(forwrefs);
515 eval_cleanup();
516 stdscan_cleanup();
518 return terminate_after_phase;
522 * Get a parameter for a command line option.
523 * First arg must be in the form of e.g. -f...
525 static char *get_param(char *p, char *q, bool *advance)
527 *advance = false;
528 if (p[2]) /* the parameter's in the option */
529 return nasm_skip_spaces(p + 2);
530 if (q && q[0]) {
531 *advance = true;
532 return q;
534 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
535 "option `-%c' requires an argument", p[1]);
536 return NULL;
540 * Copy a filename
542 static void copy_filename(char *dst, const char *src)
544 size_t len = strlen(src);
546 if (len >= (size_t)FILENAME_MAX) {
547 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
548 return;
550 strncpy(dst, src, FILENAME_MAX);
554 * Convert a string to Make-safe form
556 static char *quote_for_make(const char *str)
558 const char *p;
559 char *os, *q;
561 size_t n = 1; /* Terminating zero */
562 size_t nbs = 0;
564 if (!str)
565 return NULL;
567 for (p = str; *p; p++) {
568 switch (*p) {
569 case ' ':
570 case '\t':
571 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
572 n += nbs + 2;
573 nbs = 0;
574 break;
575 case '$':
576 case '#':
577 nbs = 0;
578 n += 2;
579 break;
580 case '\\':
581 nbs++;
582 n++;
583 break;
584 default:
585 nbs = 0;
586 n++;
587 break;
591 /* Convert N backslashes at the end of filename to 2N backslashes */
592 if (nbs)
593 n += nbs;
595 os = q = nasm_malloc(n);
597 nbs = 0;
598 for (p = str; *p; p++) {
599 switch (*p) {
600 case ' ':
601 case '\t':
602 while (nbs--)
603 *q++ = '\\';
604 *q++ = '\\';
605 *q++ = *p;
606 break;
607 case '$':
608 *q++ = *p;
609 *q++ = *p;
610 nbs = 0;
611 break;
612 case '#':
613 *q++ = '\\';
614 *q++ = *p;
615 nbs = 0;
616 break;
617 case '\\':
618 *q++ = *p;
619 nbs++;
620 break;
621 default:
622 *q++ = *p;
623 nbs = 0;
624 break;
627 while (nbs--)
628 *q++ = '\\';
630 *q = '\0';
632 return os;
635 struct textargs {
636 const char *label;
637 int value;
640 #define OPT_PREFIX 0
641 #define OPT_POSTFIX 1
642 struct textargs textopts[] = {
643 {"prefix", OPT_PREFIX},
644 {"postfix", OPT_POSTFIX},
645 {NULL, 0}
648 static bool stopoptions = false;
649 static bool process_arg(char *p, char *q)
651 char *param;
652 int i;
653 bool advance = false;
654 bool do_warn;
656 if (!p || !p[0])
657 return false;
659 if (p[0] == '-' && !stopoptions) {
660 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
661 /* These parameters take values */
662 if (!(param = get_param(p, q, &advance)))
663 return advance;
666 switch (p[1]) {
667 case 's':
668 error_file = stdout;
669 break;
671 case 'o': /* output file */
672 copy_filename(outname, param);
673 break;
675 case 'f': /* output format */
676 ofmt = ofmt_find(param, &ofmt_alias);
677 if (!ofmt) {
678 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
679 "unrecognised output format `%s' - "
680 "use -hf for a list", param);
682 break;
684 case 'O': /* Optimization level */
686 int opt;
688 if (!*param) {
689 /* Naked -O == -Ox */
690 optimizing = MAX_OPTIMIZE;
691 } else {
692 while (*param) {
693 switch (*param) {
694 case '0': case '1': case '2': case '3': case '4':
695 case '5': case '6': case '7': case '8': case '9':
696 opt = strtoul(param, &param, 10);
698 /* -O0 -> optimizing == -1, 0.98 behaviour */
699 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
700 if (opt < 2)
701 optimizing = opt - 1;
702 else
703 optimizing = opt;
704 break;
706 case 'v':
707 case '+':
708 param++;
709 opt_verbose_info = true;
710 break;
712 case 'x':
713 param++;
714 optimizing = MAX_OPTIMIZE;
715 break;
717 default:
718 nasm_error(ERR_FATAL,
719 "unknown optimization option -O%c\n",
720 *param);
721 break;
724 if (optimizing > MAX_OPTIMIZE)
725 optimizing = MAX_OPTIMIZE;
727 break;
730 case 'p': /* pre-include */
731 case 'P':
732 preproc->pre_include(param);
733 break;
735 case 'd': /* pre-define */
736 case 'D':
737 preproc->pre_define(param);
738 break;
740 case 'u': /* un-define */
741 case 'U':
742 preproc->pre_undefine(param);
743 break;
745 case 'i': /* include search path */
746 case 'I':
747 preproc->include_path(param);
748 break;
750 case 'l': /* listing file */
751 copy_filename(listname, param);
752 break;
754 case 'Z': /* error messages file */
755 copy_filename(errname, param);
756 break;
758 case 'F': /* specify debug format */
759 ofmt->current_dfmt = dfmt_find(ofmt, param);
760 if (!ofmt->current_dfmt) {
761 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
762 "unrecognized debug format `%s' for"
763 " output format `%s'",
764 param, ofmt->shortname);
766 using_debug_info = true;
767 break;
769 case 'X': /* specify error reporting format */
770 if (nasm_stricmp("vc", param) == 0)
771 nasm_set_verror(nasm_verror_vc);
772 else if (nasm_stricmp("gnu", param) == 0)
773 nasm_set_verror(nasm_verror_gnu);
774 else
775 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
776 "unrecognized error reporting format `%s'",
777 param);
778 break;
780 case 'g':
781 using_debug_info = true;
782 break;
784 case 'h':
785 printf
786 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
787 "[-l listfile]\n"
788 " [options...] [--] filename\n"
789 " or nasm -v for version info\n\n"
790 " -t assemble in SciTech TASM compatible mode\n"
791 " -g generate debug information in selected format\n");
792 printf
793 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
794 " -a don't preprocess (assemble only)\n"
795 " -M generate Makefile dependencies on stdout\n"
796 " -MG d:o, missing files assumed generated\n"
797 " -MF <file> set Makefile dependency file\n"
798 " -MD <file> assemble and generate dependencies\n"
799 " -MT <file> dependency target name\n"
800 " -MQ <file> dependency target name (quoted)\n"
801 " -MP emit phony target\n\n"
802 " -Z<file> redirect error messages to file\n"
803 " -s redirect error messages to stdout\n\n"
804 " -F format select a debugging format\n\n"
805 " -I<path> adds a pathname to the include file path\n");
806 printf
807 (" -O<digit> optimize branch offsets\n"
808 " -O0: No optimization\n"
809 " -O1: Minimal optimization\n"
810 " -Ox: Multipass optimization (default)\n\n"
811 " -P<file> pre-includes a file\n"
812 " -D<macro>[=<value>] pre-defines a macro\n"
813 " -U<macro> undefines a macro\n"
814 " -X<format> specifies error reporting format (gnu or vc)\n"
815 " -w+foo enables warning foo (equiv. -Wfoo)\n"
816 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
817 "--prefix,--postfix\n"
818 " this options prepend or append the given argument to all\n"
819 " extern and global variables\n\n"
820 "Warnings:\n");
821 for (i = 0; i <= ERR_WARN_MAX; i++)
822 printf(" %-23s %s (default %s)\n",
823 warnings[i].name, warnings[i].help,
824 warnings[i].enabled ? "on" : "off");
825 printf
826 ("\nresponse files should contain command line parameters"
827 ", one per line.\n");
828 if (p[2] == 'f') {
829 printf("\nvalid output formats for -f are"
830 " (`*' denotes default):\n");
831 ofmt_list(ofmt, stdout);
832 } else {
833 printf("\nFor a list of valid output formats, use -hf.\n");
834 printf("For a list of debug formats, use -f <form> -y.\n");
836 exit(0); /* never need usage message here */
837 break;
839 case 'y':
840 printf("\nvalid debug formats for '%s' output format are"
841 " ('*' denotes default):\n", ofmt->shortname);
842 dfmt_list(ofmt, stdout);
843 exit(0);
844 break;
846 case 't':
847 tasm_compatible_mode = true;
848 break;
850 case 'v':
851 printf("NASM version %s compiled on %s%s\n",
852 nasm_version, nasm_date, nasm_compile_options);
853 exit(0); /* never need usage message here */
854 break;
856 case 'e': /* preprocess only */
857 case 'E':
858 operating_mode = op_preprocess;
859 break;
861 case 'a': /* assemble only - don't preprocess */
862 preproc = &no_pp;
863 break;
865 case 'W':
866 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
867 do_warn = false;
868 param += 3;
869 } else {
870 do_warn = true;
872 goto set_warning;
874 case 'w':
875 if (param[0] != '+' && param[0] != '-') {
876 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
877 "invalid option to `-w'");
878 break;
880 do_warn = (param[0] == '+');
881 param++;
883 set_warning:
884 for (i = 0; i <= ERR_WARN_MAX; i++) {
885 if (!nasm_stricmp(param, warnings[i].name))
886 break;
888 if (i <= ERR_WARN_MAX) {
889 warning_on_global[i] = do_warn;
890 } else if (!nasm_stricmp(param, "all")) {
891 for (i = 1; i <= ERR_WARN_MAX; i++)
892 warning_on_global[i] = do_warn;
893 } else if (!nasm_stricmp(param, "none")) {
894 for (i = 1; i <= ERR_WARN_MAX; i++)
895 warning_on_global[i] = !do_warn;
896 } else {
897 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
898 "invalid warning `%s'", param);
900 break;
902 case 'M':
903 switch (p[2]) {
904 case 0:
905 operating_mode = op_depend;
906 break;
907 case 'G':
908 operating_mode = op_depend;
909 depend_missing_ok = true;
910 break;
911 case 'P':
912 depend_emit_phony = true;
913 break;
914 case 'D':
915 depend_file = q;
916 advance = true;
917 break;
918 case 'T':
919 depend_target = q;
920 advance = true;
921 break;
922 case 'Q':
923 depend_target = quote_for_make(q);
924 advance = true;
925 break;
926 default:
927 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
928 "unknown dependency option `-M%c'", p[2]);
929 break;
931 if (advance && (!q || !q[0])) {
932 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
933 "option `-M%c' requires a parameter", p[2]);
934 break;
936 break;
938 case '-':
940 int s;
942 if (p[2] == 0) { /* -- => stop processing options */
943 stopoptions = 1;
944 break;
946 for (s = 0; textopts[s].label; s++) {
947 if (!nasm_stricmp(p + 2, textopts[s].label)) {
948 break;
952 switch (s) {
954 case OPT_PREFIX:
955 case OPT_POSTFIX:
957 if (!q) {
958 nasm_error(ERR_NONFATAL | ERR_NOFILE |
959 ERR_USAGE,
960 "option `--%s' requires an argument",
961 p + 2);
962 break;
963 } else {
964 advance = 1, param = q;
967 if (s == OPT_PREFIX) {
968 strncpy(lprefix, param, PREFIX_MAX - 1);
969 lprefix[PREFIX_MAX - 1] = 0;
970 break;
972 if (s == OPT_POSTFIX) {
973 strncpy(lpostfix, param, POSTFIX_MAX - 1);
974 lpostfix[POSTFIX_MAX - 1] = 0;
975 break;
977 break;
979 default:
981 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
982 "unrecognised option `--%s'", p + 2);
983 break;
986 break;
989 default:
990 if (!ofmt->setinfo(GI_SWITCH, &p))
991 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
992 "unrecognised option `-%c'", p[1]);
993 break;
995 } else {
996 if (*inname) {
997 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
998 "more than one input file specified");
999 } else {
1000 copy_filename(inname, p);
1004 return advance;
1007 #define ARG_BUF_DELTA 128
1009 static void process_respfile(FILE * rfile)
1011 char *buffer, *p, *q, *prevarg;
1012 int bufsize, prevargsize;
1014 bufsize = prevargsize = ARG_BUF_DELTA;
1015 buffer = nasm_malloc(ARG_BUF_DELTA);
1016 prevarg = nasm_malloc(ARG_BUF_DELTA);
1017 prevarg[0] = '\0';
1019 while (1) { /* Loop to handle all lines in file */
1020 p = buffer;
1021 while (1) { /* Loop to handle long lines */
1022 q = fgets(p, bufsize - (p - buffer), rfile);
1023 if (!q)
1024 break;
1025 p += strlen(p);
1026 if (p > buffer && p[-1] == '\n')
1027 break;
1028 if (p - buffer > bufsize - 10) {
1029 int offset;
1030 offset = p - buffer;
1031 bufsize += ARG_BUF_DELTA;
1032 buffer = nasm_realloc(buffer, bufsize);
1033 p = buffer + offset;
1037 if (!q && p == buffer) {
1038 if (prevarg[0])
1039 process_arg(prevarg, NULL);
1040 nasm_free(buffer);
1041 nasm_free(prevarg);
1042 return;
1046 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1047 * them are present at the end of the line.
1049 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1051 while (p > buffer && nasm_isspace(p[-1]))
1052 *--p = '\0';
1054 p = nasm_skip_spaces(buffer);
1056 if (process_arg(prevarg, p))
1057 *p = '\0';
1059 if ((int) strlen(p) > prevargsize - 10) {
1060 prevargsize += ARG_BUF_DELTA;
1061 prevarg = nasm_realloc(prevarg, prevargsize);
1063 strncpy(prevarg, p, prevargsize);
1067 /* Function to process args from a string of args, rather than the
1068 * argv array. Used by the environment variable and response file
1069 * processing.
1071 static void process_args(char *args)
1073 char *p, *q, *arg, *prevarg;
1074 char separator = ' ';
1076 p = args;
1077 if (*p && *p != '-')
1078 separator = *p++;
1079 arg = NULL;
1080 while (*p) {
1081 q = p;
1082 while (*p && *p != separator)
1083 p++;
1084 while (*p == separator)
1085 *p++ = '\0';
1086 prevarg = arg;
1087 arg = q;
1088 if (process_arg(prevarg, arg))
1089 arg = NULL;
1091 if (arg)
1092 process_arg(arg, NULL);
1095 static void process_response_file(const char *file)
1097 char str[2048];
1098 FILE *f = fopen(file, "r");
1099 if (!f) {
1100 perror(file);
1101 exit(-1);
1103 while (fgets(str, sizeof str, f)) {
1104 process_args(str);
1106 fclose(f);
1109 static void parse_cmdline(int argc, char **argv)
1111 FILE *rfile;
1112 char *envreal, *envcopy = NULL, *p;
1113 int i;
1115 *inname = *outname = *listname = *errname = '\0';
1117 for (i = 0; i <= ERR_WARN_MAX; i++)
1118 warning_on_global[i] = warnings[i].enabled;
1121 * First, process the NASMENV environment variable.
1123 envreal = getenv("NASMENV");
1124 if (envreal) {
1125 envcopy = nasm_strdup(envreal);
1126 process_args(envcopy);
1127 nasm_free(envcopy);
1131 * Now process the actual command line.
1133 while (--argc) {
1134 bool advance;
1135 argv++;
1136 if (argv[0][0] == '@') {
1138 * We have a response file, so process this as a set of
1139 * arguments like the environment variable. This allows us
1140 * to have multiple arguments on a single line, which is
1141 * different to the -@resp file processing below for regular
1142 * NASM.
1144 process_response_file(argv[0]+1);
1145 argc--;
1146 argv++;
1148 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1149 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1150 if (p) {
1151 rfile = fopen(p, "r");
1152 if (rfile) {
1153 process_respfile(rfile);
1154 fclose(rfile);
1155 } else
1156 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1157 "unable to open response file `%s'", p);
1159 } else
1160 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1161 argv += advance, argc -= advance;
1165 * Look for basic command line typos. This definitely doesn't
1166 * catch all errors, but it might help cases of fumbled fingers.
1168 if (!*inname)
1169 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1170 "no input file specified");
1171 else if (!strcmp(inname, errname) ||
1172 !strcmp(inname, outname) ||
1173 !strcmp(inname, listname) ||
1174 (depend_file && !strcmp(inname, depend_file)))
1175 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1176 "file `%s' is both input and output file",
1177 inname);
1179 if (*errname) {
1180 error_file = fopen(errname, "w");
1181 if (!error_file) {
1182 error_file = stderr; /* Revert to default! */
1183 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1184 "cannot open file `%s' for error messages",
1185 errname);
1190 static enum directives getkw(char **directive, char **value);
1192 static void assemble_file(char *fname, StrList **depend_ptr)
1194 char *directive, *value, *p, *q, *special, *line;
1195 insn output_ins;
1196 int i, validid;
1197 bool rn_error;
1198 int32_t seg;
1199 int64_t offs;
1200 struct tokenval tokval;
1201 expr *e;
1202 int pass_max;
1204 if (cmd_sb == 32 && cmd_cpu < IF_386)
1205 nasm_error(ERR_FATAL, "command line: "
1206 "32-bit segment size requires a higher cpu");
1208 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1209 for (passn = 1; pass0 <= 2; passn++) {
1210 int pass1, pass2;
1211 ldfunc def_label;
1213 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1214 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1215 /* pass0 0, 0, 0, ..., 1, 2 */
1217 def_label = passn > 1 ? redefine_label : define_label;
1219 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1220 cpu = cmd_cpu;
1221 if (pass0 == 2) {
1222 if (*listname)
1223 nasmlist.init(listname, nasm_error);
1225 in_abs_seg = false;
1226 global_offset_changed = 0; /* set by redefine_label */
1227 location.segment = ofmt->section(NULL, pass2, &sb);
1228 globalbits = sb;
1229 if (passn > 1) {
1230 saa_rewind(forwrefs);
1231 forwref = saa_rstruct(forwrefs);
1232 raa_free(offsets);
1233 offsets = raa_init();
1235 preproc->reset(fname, pass1, &nasmlist,
1236 pass1 == 2 ? depend_ptr : NULL);
1237 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1239 globallineno = 0;
1240 if (passn == 1)
1241 location.known = true;
1242 location.offset = offs = GET_CURR_OFFS;
1244 while ((line = preproc->getline())) {
1245 enum directives d;
1246 globallineno++;
1249 * Here we parse our directives; this is not handled by the
1250 * 'real' parser. This really should be a separate function.
1252 directive = line;
1253 d = getkw(&directive, &value);
1254 if (d) {
1255 int err = 0;
1257 switch (d) {
1258 case D_SEGMENT: /* [SEGMENT n] */
1259 case D_SECTION:
1260 seg = ofmt->section(value, pass2, &sb);
1261 if (seg == NO_SEG) {
1262 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1263 "segment name `%s' not recognized",
1264 value);
1265 } else {
1266 in_abs_seg = false;
1267 location.segment = seg;
1269 break;
1270 case D_SECTALIGN: /* [SECTALIGN n] */
1271 if (*value) {
1272 stdscan_reset();
1273 stdscan_set(value);
1274 tokval.t_type = TOKEN_INVALID;
1275 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1276 if (e) {
1277 unsigned int align = (unsigned int)e->value;
1278 if ((uint64_t)e->value > 0x7fffffff) {
1280 * FIXME: Please make some sane message here
1281 * ofmt should have some 'check' method which
1282 * would report segment alignment bounds.
1284 nasm_error(ERR_FATAL,
1285 "incorrect segment alignment `%s'", value);
1286 } else if (!is_power2(align)) {
1287 nasm_error(ERR_NONFATAL,
1288 "segment alignment `%s' is not power of two",
1289 value);
1291 /* callee should be able to handle all details */
1292 ofmt->sectalign(location.segment, align);
1295 break;
1296 case D_EXTERN: /* [EXTERN label:special] */
1297 if (*value == '$')
1298 value++; /* skip initial $ if present */
1299 if (pass0 == 2) {
1300 q = value;
1301 while (*q && *q != ':')
1302 q++;
1303 if (*q == ':') {
1304 *q++ = '\0';
1305 ofmt->symdef(value, 0L, 0L, 3, q);
1307 } else if (passn == 1) {
1308 q = value;
1309 validid = true;
1310 if (!isidstart(*q))
1311 validid = false;
1312 while (*q && *q != ':') {
1313 if (!isidchar(*q))
1314 validid = false;
1315 q++;
1317 if (!validid) {
1318 nasm_error(ERR_NONFATAL,
1319 "identifier expected after EXTERN");
1320 break;
1322 if (*q == ':') {
1323 *q++ = '\0';
1324 special = q;
1325 } else
1326 special = NULL;
1327 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1328 int temp = pass0;
1329 pass0 = 1; /* fake pass 1 in labels.c */
1330 declare_as_global(value, special);
1331 define_label(value, seg_alloc(), 0L, NULL,
1332 false, true);
1333 pass0 = temp;
1335 } /* else pass0 == 1 */
1336 break;
1337 case D_BITS: /* [BITS bits] */
1338 globalbits = sb = get_bits(value);
1339 break;
1340 case D_GLOBAL: /* [GLOBAL symbol:special] */
1341 if (*value == '$')
1342 value++; /* skip initial $ if present */
1343 if (pass0 == 2) { /* pass 2 */
1344 q = value;
1345 while (*q && *q != ':')
1346 q++;
1347 if (*q == ':') {
1348 *q++ = '\0';
1349 ofmt->symdef(value, 0L, 0L, 3, q);
1351 } else if (pass2 == 1) { /* pass == 1 */
1352 q = value;
1353 validid = true;
1354 if (!isidstart(*q))
1355 validid = false;
1356 while (*q && *q != ':') {
1357 if (!isidchar(*q))
1358 validid = false;
1359 q++;
1361 if (!validid) {
1362 nasm_error(ERR_NONFATAL,
1363 "identifier expected after GLOBAL");
1364 break;
1366 if (*q == ':') {
1367 *q++ = '\0';
1368 special = q;
1369 } else
1370 special = NULL;
1371 declare_as_global(value, special);
1372 } /* pass == 1 */
1373 break;
1374 case D_COMMON: /* [COMMON symbol size:special] */
1376 int64_t size;
1378 if (*value == '$')
1379 value++; /* skip initial $ if present */
1380 p = value;
1381 validid = true;
1382 if (!isidstart(*p))
1383 validid = false;
1384 while (*p && !nasm_isspace(*p)) {
1385 if (!isidchar(*p))
1386 validid = false;
1387 p++;
1389 if (!validid) {
1390 nasm_error(ERR_NONFATAL,
1391 "identifier expected after COMMON");
1392 break;
1394 if (*p) {
1395 p = nasm_zap_spaces_fwd(p);
1396 q = p;
1397 while (*q && *q != ':')
1398 q++;
1399 if (*q == ':') {
1400 *q++ = '\0';
1401 special = q;
1402 } else {
1403 special = NULL;
1405 size = readnum(p, &rn_error);
1406 if (rn_error) {
1407 nasm_error(ERR_NONFATAL,
1408 "invalid size specified"
1409 " in COMMON declaration");
1410 break;
1412 } else {
1413 nasm_error(ERR_NONFATAL,
1414 "no size specified in"
1415 " COMMON declaration");
1416 break;
1419 if (pass0 < 2) {
1420 define_common(value, seg_alloc(), size, special);
1421 } else if (pass0 == 2) {
1422 if (special)
1423 ofmt->symdef(value, 0L, 0L, 3, special);
1425 break;
1427 case D_ABSOLUTE: /* [ABSOLUTE address] */
1428 stdscan_reset();
1429 stdscan_set(value);
1430 tokval.t_type = TOKEN_INVALID;
1431 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1432 nasm_error, NULL);
1433 if (e) {
1434 if (!is_reloc(e))
1435 nasm_error(pass0 ==
1436 1 ? ERR_NONFATAL : ERR_PANIC,
1437 "cannot use non-relocatable expression as "
1438 "ABSOLUTE address");
1439 else {
1440 abs_seg = reloc_seg(e);
1441 abs_offset = reloc_value(e);
1443 } else if (passn == 1)
1444 abs_offset = 0x100; /* don't go near zero in case of / */
1445 else
1446 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1447 "in pass two");
1448 in_abs_seg = true;
1449 location.segment = NO_SEG;
1450 break;
1451 case D_DEBUG: /* [DEBUG] */
1453 char debugid[128];
1454 bool badid, overlong;
1456 p = value;
1457 q = debugid;
1458 badid = overlong = false;
1459 if (!isidstart(*p)) {
1460 badid = true;
1461 } else {
1462 while (*p && !nasm_isspace(*p)) {
1463 if (q >= debugid + sizeof debugid - 1) {
1464 overlong = true;
1465 break;
1467 if (!isidchar(*p))
1468 badid = true;
1469 *q++ = *p++;
1471 *q = 0;
1473 if (badid) {
1474 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1475 "identifier expected after DEBUG");
1476 break;
1478 if (overlong) {
1479 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1480 "DEBUG identifier too long");
1481 break;
1483 p = nasm_skip_spaces(p);
1484 if (pass0 == 2)
1485 dfmt->debug_directive(debugid, p);
1486 break;
1488 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1489 value = nasm_skip_spaces(value);
1490 switch(*value) {
1491 case '-': validid = 0; value++; break;
1492 case '+': validid = 1; value++; break;
1493 case '*': validid = 2; value++; break;
1494 default: validid = 1; break;
1497 for (i = 1; i <= ERR_WARN_MAX; i++)
1498 if (!nasm_stricmp(value, warnings[i].name))
1499 break;
1500 if (i <= ERR_WARN_MAX) {
1501 switch(validid) {
1502 case 0:
1503 warning_on[i] = false;
1504 break;
1505 case 1:
1506 warning_on[i] = true;
1507 break;
1508 case 2:
1509 warning_on[i] = warning_on_global[i];
1510 break;
1513 else
1514 nasm_error(ERR_NONFATAL,
1515 "invalid warning id in WARNING directive");
1516 break;
1517 case D_CPU: /* [CPU] */
1518 cpu = get_cpu(value);
1519 break;
1520 case D_LIST: /* [LIST {+|-}] */
1521 value = nasm_skip_spaces(value);
1522 if (*value == '+') {
1523 user_nolist = 0;
1524 } else {
1525 if (*value == '-') {
1526 user_nolist = 1;
1527 } else {
1528 err = 1;
1531 break;
1532 case D_DEFAULT: /* [DEFAULT] */
1533 stdscan_reset();
1534 stdscan_set(value);
1535 tokval.t_type = TOKEN_INVALID;
1536 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1537 switch ((int)tokval.t_integer) {
1538 case S_REL:
1539 globalrel = 1;
1540 break;
1541 case S_ABS:
1542 globalrel = 0;
1543 break;
1544 default:
1545 err = 1;
1546 break;
1548 } else {
1549 err = 1;
1551 break;
1552 case D_FLOAT:
1553 if (float_option(value)) {
1554 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1555 "unknown 'float' directive: %s",
1556 value);
1558 break;
1559 default:
1560 if (ofmt->directive(d, value, pass2))
1561 break;
1562 /* else fall through */
1563 case D_unknown:
1564 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1565 "unrecognised directive [%s]",
1566 directive);
1567 break;
1569 if (err) {
1570 nasm_error(ERR_NONFATAL,
1571 "invalid parameter to [%s] directive",
1572 directive);
1574 } else { /* it isn't a directive */
1575 parse_line(pass1, line, &output_ins, def_label);
1577 if (optimizing > 0) {
1578 if (forwref != NULL && globallineno == forwref->lineno) {
1579 output_ins.forw_ref = true;
1580 do {
1581 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1582 forwref = saa_rstruct(forwrefs);
1583 } while (forwref != NULL
1584 && forwref->lineno == globallineno);
1585 } else
1586 output_ins.forw_ref = false;
1588 if (output_ins.forw_ref) {
1589 if (passn == 1) {
1590 for (i = 0; i < output_ins.operands; i++) {
1591 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1592 struct forwrefinfo *fwinf =
1593 (struct forwrefinfo *)
1594 saa_wstruct(forwrefs);
1595 fwinf->lineno = globallineno;
1596 fwinf->operand = i;
1603 /* forw_ref */
1604 if (output_ins.opcode == I_EQU) {
1605 if (pass1 == 1) {
1607 * Special `..' EQUs get processed in pass two,
1608 * except `..@' macro-processor EQUs which are done
1609 * in the normal place.
1611 if (!output_ins.label)
1612 nasm_error(ERR_NONFATAL,
1613 "EQU not preceded by label");
1615 else if (output_ins.label[0] != '.' ||
1616 output_ins.label[1] != '.' ||
1617 output_ins.label[2] == '@') {
1618 if (output_ins.operands == 1 &&
1619 (output_ins.oprs[0].type & IMMEDIATE) &&
1620 output_ins.oprs[0].wrt == NO_SEG) {
1621 bool isext = !!(output_ins.oprs[0].opflags
1622 & OPFLAG_EXTERN);
1623 def_label(output_ins.label,
1624 output_ins.oprs[0].segment,
1625 output_ins.oprs[0].offset, NULL,
1626 false, isext);
1627 } else if (output_ins.operands == 2
1628 && (output_ins.oprs[0].type & IMMEDIATE)
1629 && (output_ins.oprs[0].type & COLON)
1630 && output_ins.oprs[0].segment == NO_SEG
1631 && output_ins.oprs[0].wrt == NO_SEG
1632 && (output_ins.oprs[1].type & IMMEDIATE)
1633 && output_ins.oprs[1].segment == NO_SEG
1634 && output_ins.oprs[1].wrt == NO_SEG) {
1635 def_label(output_ins.label,
1636 output_ins.oprs[0].offset | SEG_ABS,
1637 output_ins.oprs[1].offset,
1638 NULL, false, false);
1639 } else
1640 nasm_error(ERR_NONFATAL,
1641 "bad syntax for EQU");
1643 } else {
1645 * Special `..' EQUs get processed here, except
1646 * `..@' macro processor EQUs which are done above.
1648 if (output_ins.label[0] == '.' &&
1649 output_ins.label[1] == '.' &&
1650 output_ins.label[2] != '@') {
1651 if (output_ins.operands == 1 &&
1652 (output_ins.oprs[0].type & IMMEDIATE)) {
1653 define_label(output_ins.label,
1654 output_ins.oprs[0].segment,
1655 output_ins.oprs[0].offset,
1656 NULL, false, false);
1657 } else if (output_ins.operands == 2
1658 && (output_ins.oprs[0].type & IMMEDIATE)
1659 && (output_ins.oprs[0].type & COLON)
1660 && output_ins.oprs[0].segment == NO_SEG
1661 && (output_ins.oprs[1].type & IMMEDIATE)
1662 && output_ins.oprs[1].segment == NO_SEG) {
1663 define_label(output_ins.label,
1664 output_ins.oprs[0].offset | SEG_ABS,
1665 output_ins.oprs[1].offset,
1666 NULL, false, false);
1667 } else
1668 nasm_error(ERR_NONFATAL,
1669 "bad syntax for EQU");
1672 } else { /* instruction isn't an EQU */
1674 if (pass1 == 1) {
1676 int64_t l = insn_size(location.segment, offs, sb, cpu,
1677 &output_ins, nasm_error);
1679 /* if (using_debug_info) && output_ins.opcode != -1) */
1680 if (using_debug_info)
1681 { /* fbk 03/25/01 */
1682 /* this is done here so we can do debug type info */
1683 int32_t typeinfo =
1684 TYS_ELEMENTS(output_ins.operands);
1685 switch (output_ins.opcode) {
1686 case I_RESB:
1687 typeinfo =
1688 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1689 break;
1690 case I_RESW:
1691 typeinfo =
1692 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1693 break;
1694 case I_RESD:
1695 typeinfo =
1696 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1697 break;
1698 case I_RESQ:
1699 typeinfo =
1700 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1701 break;
1702 case I_REST:
1703 typeinfo =
1704 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1705 break;
1706 case I_RESO:
1707 typeinfo =
1708 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1709 break;
1710 case I_RESY:
1711 typeinfo =
1712 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1713 break;
1714 case I_DB:
1715 typeinfo |= TY_BYTE;
1716 break;
1717 case I_DW:
1718 typeinfo |= TY_WORD;
1719 break;
1720 case I_DD:
1721 if (output_ins.eops_float)
1722 typeinfo |= TY_FLOAT;
1723 else
1724 typeinfo |= TY_DWORD;
1725 break;
1726 case I_DQ:
1727 typeinfo |= TY_QWORD;
1728 break;
1729 case I_DT:
1730 typeinfo |= TY_TBYTE;
1731 break;
1732 case I_DO:
1733 typeinfo |= TY_OWORD;
1734 break;
1735 case I_DY:
1736 typeinfo |= TY_YWORD;
1737 break;
1738 default:
1739 typeinfo = TY_LABEL;
1743 dfmt->debug_typevalue(typeinfo);
1745 if (l != -1) {
1746 offs += l;
1747 SET_CURR_OFFS(offs);
1750 * else l == -1 => invalid instruction, which will be
1751 * flagged as an error on pass 2
1754 } else {
1755 offs += assemble(location.segment, offs, sb, cpu,
1756 &output_ins, ofmt, nasm_error,
1757 &nasmlist);
1758 SET_CURR_OFFS(offs);
1761 } /* not an EQU */
1762 cleanup_insn(&output_ins);
1764 nasm_free(line);
1765 location.offset = offs = GET_CURR_OFFS;
1766 } /* end while (line = preproc->getline... */
1768 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1769 nasm_error(ERR_NONFATAL,
1770 "phase error detected at end of assembly.");
1772 if (pass1 == 1)
1773 preproc->cleanup(1);
1775 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1776 pass0++;
1777 } else if (global_offset_changed &&
1778 global_offset_changed < prev_offset_changed) {
1779 prev_offset_changed = global_offset_changed;
1780 stall_count = 0;
1781 } else {
1782 stall_count++;
1785 if (terminate_after_phase)
1786 break;
1788 if ((stall_count > 997) || (passn >= pass_max)) {
1789 /* We get here if the labels don't converge
1790 * Example: FOO equ FOO + 1
1792 nasm_error(ERR_NONFATAL,
1793 "Can't find valid values for all labels "
1794 "after %d passes, giving up.", passn);
1795 nasm_error(ERR_NONFATAL,
1796 "Possible causes: recursive EQUs, macro abuse.");
1797 break;
1801 preproc->cleanup(0);
1802 nasmlist.cleanup();
1803 if (!terminate_after_phase && opt_verbose_info) {
1804 /* -On and -Ov switches */
1805 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1809 static enum directives getkw(char **directive, char **value)
1811 char *p, *q, *buf;
1813 buf = nasm_skip_spaces(*directive);
1815 /* it should be enclosed in [ ] */
1816 if (*buf != '[')
1817 return D_none;
1818 q = strchr(buf, ']');
1819 if (!q)
1820 return D_none;
1822 /* stip off the comments */
1823 p = strchr(buf, ';');
1824 if (p) {
1825 if (p < q) /* ouch! somwhere inside */
1826 return D_none;
1827 *p = '\0';
1830 /* no brace, no trailing spaces */
1831 *q = '\0';
1832 nasm_zap_spaces_rev(--q);
1834 /* directive */
1835 p = nasm_skip_spaces(++buf);
1836 q = nasm_skip_word(p);
1837 if (!q)
1838 return D_none; /* sigh... no value there */
1839 *q = '\0';
1840 *directive = p;
1842 /* and value finally */
1843 p = nasm_skip_spaces(++q);
1844 *value = p;
1846 return find_directive(*directive);
1850 * gnu style error reporting
1851 * This function prints an error message to error_file in the
1852 * style used by GNU. An example would be:
1853 * file.asm:50: error: blah blah blah
1854 * where file.asm is the name of the file, 50 is the line number on
1855 * which the error occurs (or is detected) and "error:" is one of
1856 * the possible optional diagnostics -- it can be "error" or "warning"
1857 * or something else. Finally the line terminates with the actual
1858 * error message.
1860 * @param severity the severity of the warning or error
1861 * @param fmt the printf style format string
1863 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1865 char *currentfile = NULL;
1866 int32_t lineno = 0;
1868 if (is_suppressed_warning(severity))
1869 return;
1871 if (!(severity & ERR_NOFILE))
1872 src_get(&lineno, &currentfile);
1874 if (currentfile) {
1875 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1876 nasm_free(currentfile);
1877 } else {
1878 fputs("nasm: ", error_file);
1881 nasm_verror_common(severity, fmt, ap);
1885 * MS style error reporting
1886 * This function prints an error message to error_file in the
1887 * style used by Visual C and some other Microsoft tools. An example
1888 * would be:
1889 * file.asm(50) : error: blah blah blah
1890 * where file.asm is the name of the file, 50 is the line number on
1891 * which the error occurs (or is detected) and "error:" is one of
1892 * the possible optional diagnostics -- it can be "error" or "warning"
1893 * or something else. Finally the line terminates with the actual
1894 * error message.
1896 * @param severity the severity of the warning or error
1897 * @param fmt the printf style format string
1899 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1901 char *currentfile = NULL;
1902 int32_t lineno = 0;
1904 if (is_suppressed_warning(severity))
1905 return;
1907 if (!(severity & ERR_NOFILE))
1908 src_get(&lineno, &currentfile);
1910 if (currentfile) {
1911 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1912 nasm_free(currentfile);
1913 } else {
1914 fputs("nasm: ", error_file);
1917 nasm_verror_common(severity, fmt, ap);
1921 * check for supressed warning
1922 * checks for suppressed warning or pass one only warning and we're
1923 * not in pass 1
1925 * @param severity the severity of the warning or error
1926 * @return true if we should abort error/warning printing
1928 static bool is_suppressed_warning(int severity)
1930 /* Not a warning at all */
1931 if ((severity & ERR_MASK) != ERR_WARNING)
1932 return false;
1934 /* See if it's a pass-one only warning and we're not in pass one. */
1935 if (((severity & ERR_PASS1) && pass0 != 1) ||
1936 ((severity & ERR_PASS2) && pass0 != 2))
1937 return true;
1939 /* Might be a warning but suppresed explicitly */
1940 if (severity & ERR_WARN_MASK)
1941 return !warning_on[WARN_IDX(severity)];
1942 else
1943 return false;
1947 * common error reporting
1948 * This is the common back end of the error reporting schemes currently
1949 * implemented. It prints the nature of the warning and then the
1950 * specific error message to error_file and may or may not return. It
1951 * doesn't return if the error severity is a "panic" or "debug" type.
1953 * @param severity the severity of the warning or error
1954 * @param fmt the printf style format string
1956 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1958 char msg[1024];
1959 const char *pfx;
1961 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1962 case ERR_WARNING:
1963 pfx = "warning: ";
1964 break;
1965 case ERR_NONFATAL:
1966 pfx = "error: ";
1967 break;
1968 case ERR_FATAL:
1969 pfx = "fatal: ";
1970 break;
1971 case ERR_PANIC:
1972 pfx = "panic: ";
1973 break;
1974 case ERR_DEBUG:
1975 pfx = "debug: ";
1976 break;
1977 default:
1978 pfx = "";
1979 break;
1982 vsnprintf(msg, sizeof msg, fmt, args);
1984 fprintf(error_file, "%s%s\n", pfx, msg);
1986 if (*listname)
1987 nasmlist.error(severity, pfx, msg);
1989 if (severity & ERR_USAGE)
1990 want_usage = true;
1992 switch (severity & ERR_MASK) {
1993 case ERR_DEBUG:
1994 /* no further action, by definition */
1995 break;
1996 case ERR_WARNING:
1997 /* Treat warnings as errors */
1998 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1999 terminate_after_phase = true;
2000 break;
2001 case ERR_NONFATAL:
2002 terminate_after_phase = true;
2003 break;
2004 case ERR_FATAL:
2005 if (ofile) {
2006 fclose(ofile);
2007 remove(outname);
2008 ofile = NULL;
2010 if (want_usage)
2011 usage();
2012 exit(1); /* instantly die */
2013 break; /* placate silly compilers */
2014 case ERR_PANIC:
2015 fflush(NULL);
2016 /* abort(); *//* halt, catch fire, and dump core */
2017 exit(3);
2018 break;
2022 static void usage(void)
2024 fputs("type `nasm -h' for help\n", error_file);
2027 #define BUF_DELTA 512
2029 static FILE *no_pp_fp;
2030 static ListGen *no_pp_list;
2031 static int32_t no_pp_lineinc;
2033 static void no_pp_reset(char *file, int pass, ListGen * listgen,
2034 StrList **deplist)
2036 src_set_fname(nasm_strdup(file));
2037 src_set_linnum(0);
2038 no_pp_lineinc = 1;
2039 no_pp_fp = fopen(file, "r");
2040 if (!no_pp_fp)
2041 nasm_error(ERR_FATAL | ERR_NOFILE,
2042 "unable to open input file `%s'", file);
2043 no_pp_list = listgen;
2044 (void)pass; /* placate compilers */
2046 if (deplist) {
2047 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2048 sl->next = NULL;
2049 strcpy(sl->str, file);
2050 *deplist = sl;
2054 static char *no_pp_getline(void)
2056 char *buffer, *p, *q;
2057 int bufsize;
2059 bufsize = BUF_DELTA;
2060 buffer = nasm_malloc(BUF_DELTA);
2061 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2063 while (1) { /* Loop to handle %line */
2065 p = buffer;
2066 while (1) { /* Loop to handle long lines */
2067 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2068 if (!q)
2069 break;
2070 p += strlen(p);
2071 if (p > buffer && p[-1] == '\n')
2072 break;
2073 if (p - buffer > bufsize - 10) {
2074 int offset;
2075 offset = p - buffer;
2076 bufsize += BUF_DELTA;
2077 buffer = nasm_realloc(buffer, bufsize);
2078 p = buffer + offset;
2082 if (!q && p == buffer) {
2083 nasm_free(buffer);
2084 return NULL;
2088 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2089 * them are present at the end of the line.
2091 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2093 if (!nasm_strnicmp(buffer, "%line", 5)) {
2094 int32_t ln;
2095 int li;
2096 char *nm = nasm_malloc(strlen(buffer));
2097 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2098 nasm_free(src_set_fname(nm));
2099 src_set_linnum(ln);
2100 no_pp_lineinc = li;
2101 continue;
2103 nasm_free(nm);
2105 break;
2108 no_pp_list->line(LIST_READ, buffer);
2110 return buffer;
2113 static void no_pp_cleanup(int pass)
2115 (void)pass; /* placate GCC */
2116 if (no_pp_fp) {
2117 fclose(no_pp_fp);
2118 no_pp_fp = NULL;
2122 static void no_pp_extra_stdmac(macros_t *macros)
2124 (void)macros;
2127 static void no_pp_pre_define(char *definition)
2129 (void)definition;
2132 static void no_pp_pre_undefine(char *definition)
2134 (void)definition;
2137 static void no_pp_pre_include(char *fname)
2139 (void)fname;
2142 static void no_pp_include_path(char *path)
2144 (void)path;
2147 static uint32_t get_cpu(char *value)
2149 if (!strcmp(value, "8086"))
2150 return IF_8086;
2151 if (!strcmp(value, "186"))
2152 return IF_186;
2153 if (!strcmp(value, "286"))
2154 return IF_286;
2155 if (!strcmp(value, "386"))
2156 return IF_386;
2157 if (!strcmp(value, "486"))
2158 return IF_486;
2159 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2160 return IF_PENT;
2161 if (!strcmp(value, "686") ||
2162 !nasm_stricmp(value, "ppro") ||
2163 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2164 return IF_P6;
2165 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2166 return IF_KATMAI;
2167 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2168 !nasm_stricmp(value, "willamette"))
2169 return IF_WILLAMETTE;
2170 if (!nasm_stricmp(value, "prescott"))
2171 return IF_PRESCOTT;
2172 if (!nasm_stricmp(value, "x64") ||
2173 !nasm_stricmp(value, "x86-64"))
2174 return IF_X86_64;
2175 if (!nasm_stricmp(value, "ia64") ||
2176 !nasm_stricmp(value, "ia-64") ||
2177 !nasm_stricmp(value, "itanium") ||
2178 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2179 return IF_IA64;
2181 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2182 "unknown 'cpu' type");
2184 return IF_PLEVEL; /* the maximum level */
2187 static int get_bits(char *value)
2189 int i;
2191 if ((i = atoi(value)) == 16)
2192 return i; /* set for a 16-bit segment */
2193 else if (i == 32) {
2194 if (cpu < IF_386) {
2195 nasm_error(ERR_NONFATAL,
2196 "cannot specify 32-bit segment on processor below a 386");
2197 i = 16;
2199 } else if (i == 64) {
2200 if (cpu < IF_X86_64) {
2201 nasm_error(ERR_NONFATAL,
2202 "cannot specify 64-bit segment on processor below an x86-64");
2203 i = 16;
2205 if (i != maxbits) {
2206 nasm_error(ERR_NONFATAL,
2207 "%s output format does not support 64-bit code",
2208 ofmt->shortname);
2209 i = 16;
2211 } else {
2212 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2213 "`%s' is not a valid segment size; must be 16, 32 or 64",
2214 value);
2215 i = 16;
2217 return i;