nasm.c: Update year in header
[nasm.git] / nasm.c
blob6b8dab1cbe3fc12bca56aa65aac0ee01f4641f44
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2013 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 * get/set current offset...
171 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
172 raa_read(offsets,location.segment))
173 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
174 (void)(offsets=raa_write(offsets,location.segment,(x))))
176 static bool want_usage;
177 static bool terminate_after_phase;
178 int user_nolist = 0; /* fbk 9/2/00 */
180 static char *quote_for_make(const char *str);
182 static void nasm_fputs(const char *line, FILE * outfile)
184 if (outfile) {
185 fputs(line, outfile);
186 putc('\n', outfile);
187 } else
188 puts(line);
191 /* Convert a struct tm to a POSIX-style time constant */
192 static int64_t posix_mktime(struct tm *tm)
194 int64_t t;
195 int64_t y = tm->tm_year;
197 /* See IEEE 1003.1:2004, section 4.14 */
199 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
200 t += tm->tm_yday;
201 t *= 24;
202 t += tm->tm_hour;
203 t *= 60;
204 t += tm->tm_min;
205 t *= 60;
206 t += tm->tm_sec;
208 return t;
211 static void define_macros_early(void)
213 char temp[128];
214 struct tm lt, *lt_p, gm, *gm_p;
215 int64_t posix_time;
217 lt_p = localtime(&official_compile_time);
218 if (lt_p) {
219 lt = *lt_p;
221 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
222 preproc->pre_define(temp);
223 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
224 preproc->pre_define(temp);
225 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
226 preproc->pre_define(temp);
227 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
228 preproc->pre_define(temp);
231 gm_p = gmtime(&official_compile_time);
232 if (gm_p) {
233 gm = *gm_p;
235 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
238 preproc->pre_define(temp);
239 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
240 preproc->pre_define(temp);
241 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
242 preproc->pre_define(temp);
245 if (gm_p)
246 posix_time = posix_mktime(&gm);
247 else if (lt_p)
248 posix_time = posix_mktime(&lt);
249 else
250 posix_time = 0;
252 if (posix_time) {
253 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
254 preproc->pre_define(temp);
258 static void define_macros_late(void)
260 char temp[128];
263 * In case if output format is defined by alias
264 * we have to put shortname of the alias itself here
265 * otherwise ABI backward compatibility gets broken.
267 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
268 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
269 preproc->pre_define(temp);
272 static void emit_dependencies(StrList *list)
274 FILE *deps;
275 int linepos, len;
276 StrList *l, *nl;
278 if (depend_file && strcmp(depend_file, "-")) {
279 deps = fopen(depend_file, "w");
280 if (!deps) {
281 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
282 "unable to write dependency file `%s'", depend_file);
283 return;
285 } else {
286 deps = stdout;
289 linepos = fprintf(deps, "%s:", depend_target);
290 list_for_each(l, list) {
291 char *file = quote_for_make(l->str);
292 len = strlen(file);
293 if (linepos + len > 62 && linepos > 1) {
294 fprintf(deps, " \\\n ");
295 linepos = 1;
297 fprintf(deps, " %s", file);
298 linepos += len+1;
299 nasm_free(file);
301 fprintf(deps, "\n\n");
303 list_for_each_safe(l, nl, list) {
304 if (depend_emit_phony)
305 fprintf(deps, "%s:\n\n", l->str);
306 nasm_free(l);
309 if (deps != stdout)
310 fclose(deps);
313 int main(int argc, char **argv)
315 StrList *depend_list = NULL, **depend_ptr;
317 time(&official_compile_time);
319 pass0 = 0;
320 want_usage = terminate_after_phase = false;
321 nasm_set_verror(nasm_verror_gnu);
323 error_file = stderr;
325 tolower_init();
327 nasm_init_malloc_error();
328 offsets = raa_init();
329 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
331 preproc = &nasmpp;
332 operating_mode = op_normal;
334 seg_init();
336 /* Define some macros dependent on the runtime, but not
337 on the command line. */
338 define_macros_early();
340 parse_cmdline(argc, argv);
342 if (terminate_after_phase) {
343 if (want_usage)
344 usage();
345 return 1;
348 /* If debugging info is disabled, suppress any debug calls */
349 if (!using_debug_info)
350 ofmt->current_dfmt = &null_debug_form;
352 if (ofmt->stdmac)
353 preproc->extra_stdmac(ofmt->stdmac);
354 parser_global_info(&location);
355 eval_global_info(ofmt, lookup_label, &location);
357 /* define some macros dependent of command-line */
358 define_macros_late();
360 depend_ptr = (depend_file || (operating_mode == op_depend)) ? &depend_list : NULL;
361 if (!depend_target)
362 depend_target = quote_for_make(outname);
364 switch (operating_mode) {
365 case op_depend:
367 char *line;
369 if (depend_missing_ok)
370 preproc->include_path(NULL); /* "assume generated" */
372 preproc->reset(inname, 0, &nasmlist, depend_ptr);
373 if (outname[0] == '\0')
374 ofmt->filename(inname, outname);
375 ofile = NULL;
376 while ((line = preproc->getline()))
377 nasm_free(line);
378 preproc->cleanup(0);
380 break;
382 case op_preprocess:
384 char *line;
385 char *file_name = NULL;
386 int32_t prior_linnum = 0;
387 int lineinc = 0;
389 if (*outname) {
390 ofile = fopen(outname, "w");
391 if (!ofile)
392 nasm_error(ERR_FATAL | ERR_NOFILE,
393 "unable to open output file `%s'",
394 outname);
395 } else
396 ofile = NULL;
398 location.known = false;
400 /* pass = 1; */
401 preproc->reset(inname, 3, &nasmlist, depend_ptr);
402 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
404 while ((line = preproc->getline())) {
406 * We generate %line directives if needed for later programs
408 int32_t linnum = prior_linnum += lineinc;
409 int altline = src_get(&linnum, &file_name);
410 if (altline) {
411 if (altline == 1 && lineinc == 1)
412 nasm_fputs("", ofile);
413 else {
414 lineinc = (altline != -1 || lineinc != 1);
415 fprintf(ofile ? ofile : stdout,
416 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
417 file_name);
419 prior_linnum = linnum;
421 nasm_fputs(line, ofile);
422 nasm_free(line);
424 nasm_free(file_name);
425 preproc->cleanup(0);
426 if (ofile)
427 fclose(ofile);
428 if (ofile && terminate_after_phase)
429 remove(outname);
430 ofile = NULL;
432 break;
434 case op_normal:
437 * We must call ofmt->filename _anyway_, even if the user
438 * has specified their own output file, because some
439 * formats (eg OBJ and COFF) use ofmt->filename to find out
440 * the name of the input file and then put that inside the
441 * file.
443 ofmt->filename(inname, outname);
445 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
446 if (!ofile) {
447 nasm_error(ERR_FATAL | ERR_NOFILE,
448 "unable to open output file `%s'", outname);
452 * We must call init_labels() before ofmt->init() since
453 * some object formats will want to define labels in their
454 * init routines. (eg OS/2 defines the FLAT group)
456 init_labels();
458 ofmt->init();
459 dfmt = ofmt->current_dfmt;
460 dfmt->init();
462 assemble_file(inname, depend_ptr);
464 if (!terminate_after_phase) {
465 ofmt->cleanup(using_debug_info);
466 cleanup_labels();
467 fflush(ofile);
468 if (ferror(ofile)) {
469 nasm_error(ERR_NONFATAL|ERR_NOFILE,
470 "write error on output file `%s'", outname);
474 if (ofile) {
475 fclose(ofile);
476 if (terminate_after_phase)
477 remove(outname);
478 ofile = NULL;
481 break;
484 if (depend_list && !terminate_after_phase)
485 emit_dependencies(depend_list);
487 if (want_usage)
488 usage();
490 raa_free(offsets);
491 saa_free(forwrefs);
492 eval_cleanup();
493 stdscan_cleanup();
495 return terminate_after_phase;
499 * Get a parameter for a command line option.
500 * First arg must be in the form of e.g. -f...
502 static char *get_param(char *p, char *q, bool *advance)
504 *advance = false;
505 if (p[2]) /* the parameter's in the option */
506 return nasm_skip_spaces(p + 2);
507 if (q && q[0]) {
508 *advance = true;
509 return q;
511 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
512 "option `-%c' requires an argument", p[1]);
513 return NULL;
517 * Copy a filename
519 static void copy_filename(char *dst, const char *src)
521 size_t len = strlen(src);
523 if (len >= (size_t)FILENAME_MAX) {
524 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
525 return;
527 strncpy(dst, src, FILENAME_MAX);
531 * Convert a string to Make-safe form
533 static char *quote_for_make(const char *str)
535 const char *p;
536 char *os, *q;
538 size_t n = 1; /* Terminating zero */
539 size_t nbs = 0;
541 if (!str)
542 return NULL;
544 for (p = str; *p; p++) {
545 switch (*p) {
546 case ' ':
547 case '\t':
548 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
549 n += nbs + 2;
550 nbs = 0;
551 break;
552 case '$':
553 case '#':
554 nbs = 0;
555 n += 2;
556 break;
557 case '\\':
558 nbs++;
559 n++;
560 break;
561 default:
562 nbs = 0;
563 n++;
564 break;
568 /* Convert N backslashes at the end of filename to 2N backslashes */
569 if (nbs)
570 n += nbs;
572 os = q = nasm_malloc(n);
574 nbs = 0;
575 for (p = str; *p; p++) {
576 switch (*p) {
577 case ' ':
578 case '\t':
579 while (nbs--)
580 *q++ = '\\';
581 *q++ = '\\';
582 *q++ = *p;
583 break;
584 case '$':
585 *q++ = *p;
586 *q++ = *p;
587 nbs = 0;
588 break;
589 case '#':
590 *q++ = '\\';
591 *q++ = *p;
592 nbs = 0;
593 break;
594 case '\\':
595 *q++ = *p;
596 nbs++;
597 break;
598 default:
599 *q++ = *p;
600 nbs = 0;
601 break;
604 while (nbs--)
605 *q++ = '\\';
607 *q = '\0';
609 return os;
612 struct textargs {
613 const char *label;
614 int value;
617 #define OPT_PREFIX 0
618 #define OPT_POSTFIX 1
619 struct textargs textopts[] = {
620 {"prefix", OPT_PREFIX},
621 {"postfix", OPT_POSTFIX},
622 {NULL, 0}
625 static bool stopoptions = false;
626 static bool process_arg(char *p, char *q)
628 char *param;
629 int i;
630 bool advance = false;
631 bool do_warn;
633 if (!p || !p[0])
634 return false;
636 if (p[0] == '-' && !stopoptions) {
637 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
638 /* These parameters take values */
639 if (!(param = get_param(p, q, &advance)))
640 return advance;
643 switch (p[1]) {
644 case 's':
645 error_file = stdout;
646 break;
648 case 'o': /* output file */
649 copy_filename(outname, param);
650 break;
652 case 'f': /* output format */
653 ofmt = ofmt_find(param, &ofmt_alias);
654 if (!ofmt) {
655 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
656 "unrecognised output format `%s' - "
657 "use -hf for a list", param);
659 break;
661 case 'O': /* Optimization level */
663 int opt;
665 if (!*param) {
666 /* Naked -O == -Ox */
667 optimizing = MAX_OPTIMIZE;
668 } else {
669 while (*param) {
670 switch (*param) {
671 case '0': case '1': case '2': case '3': case '4':
672 case '5': case '6': case '7': case '8': case '9':
673 opt = strtoul(param, &param, 10);
675 /* -O0 -> optimizing == -1, 0.98 behaviour */
676 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
677 if (opt < 2)
678 optimizing = opt - 1;
679 else
680 optimizing = opt;
681 break;
683 case 'v':
684 case '+':
685 param++;
686 opt_verbose_info = true;
687 break;
689 case 'x':
690 param++;
691 optimizing = MAX_OPTIMIZE;
692 break;
694 default:
695 nasm_error(ERR_FATAL,
696 "unknown optimization option -O%c\n",
697 *param);
698 break;
701 if (optimizing > MAX_OPTIMIZE)
702 optimizing = MAX_OPTIMIZE;
704 break;
707 case 'p': /* pre-include */
708 case 'P':
709 preproc->pre_include(param);
710 break;
712 case 'd': /* pre-define */
713 case 'D':
714 preproc->pre_define(param);
715 break;
717 case 'u': /* un-define */
718 case 'U':
719 preproc->pre_undefine(param);
720 break;
722 case 'i': /* include search path */
723 case 'I':
724 preproc->include_path(param);
725 break;
727 case 'l': /* listing file */
728 copy_filename(listname, param);
729 break;
731 case 'Z': /* error messages file */
732 copy_filename(errname, param);
733 break;
735 case 'F': /* specify debug format */
736 ofmt->current_dfmt = dfmt_find(ofmt, param);
737 if (!ofmt->current_dfmt) {
738 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
739 "unrecognized debug format `%s' for"
740 " output format `%s'",
741 param, ofmt->shortname);
743 using_debug_info = true;
744 break;
746 case 'X': /* specify error reporting format */
747 if (nasm_stricmp("vc", param) == 0)
748 nasm_set_verror(nasm_verror_vc);
749 else if (nasm_stricmp("gnu", param) == 0)
750 nasm_set_verror(nasm_verror_gnu);
751 else
752 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
753 "unrecognized error reporting format `%s'",
754 param);
755 break;
757 case 'g':
758 using_debug_info = true;
759 break;
761 case 'h':
762 printf
763 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
764 "[-l listfile]\n"
765 " [options...] [--] filename\n"
766 " or nasm -v for version info\n\n"
767 " -t assemble in SciTech TASM compatible mode\n"
768 " -g generate debug information in selected format\n");
769 printf
770 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
771 " -a don't preprocess (assemble only)\n"
772 " -M generate Makefile dependencies on stdout\n"
773 " -MG d:o, missing files assumed generated\n"
774 " -MF <file> set Makefile dependency file\n"
775 " -MD <file> assemble and generate dependencies\n"
776 " -MT <file> dependency target name\n"
777 " -MQ <file> dependency target name (quoted)\n"
778 " -MP emit phony target\n\n"
779 " -Z<file> redirect error messages to file\n"
780 " -s redirect error messages to stdout\n\n"
781 " -F format select a debugging format\n\n"
782 " -I<path> adds a pathname to the include file path\n");
783 printf
784 (" -O<digit> optimize branch offsets\n"
785 " -O0: No optimization\n"
786 " -O1: Minimal optimization\n"
787 " -Ox: Multipass optimization (default)\n\n"
788 " -P<file> pre-includes a file\n"
789 " -D<macro>[=<value>] pre-defines a macro\n"
790 " -U<macro> undefines a macro\n"
791 " -X<format> specifies error reporting format (gnu or vc)\n"
792 " -w+foo enables warning foo (equiv. -Wfoo)\n"
793 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
794 "--prefix,--postfix\n"
795 " this options prepend or append the given argument to all\n"
796 " extern and global variables\n\n"
797 "Warnings:\n");
798 for (i = 0; i <= ERR_WARN_MAX; i++)
799 printf(" %-23s %s (default %s)\n",
800 warnings[i].name, warnings[i].help,
801 warnings[i].enabled ? "on" : "off");
802 printf
803 ("\nresponse files should contain command line parameters"
804 ", one per line.\n");
805 if (p[2] == 'f') {
806 printf("\nvalid output formats for -f are"
807 " (`*' denotes default):\n");
808 ofmt_list(ofmt, stdout);
809 } else {
810 printf("\nFor a list of valid output formats, use -hf.\n");
811 printf("For a list of debug formats, use -f <form> -y.\n");
813 exit(0); /* never need usage message here */
814 break;
816 case 'y':
817 printf("\nvalid debug formats for '%s' output format are"
818 " ('*' denotes default):\n", ofmt->shortname);
819 dfmt_list(ofmt, stdout);
820 exit(0);
821 break;
823 case 't':
824 tasm_compatible_mode = true;
825 break;
827 case 'v':
828 printf("NASM version %s compiled on %s%s\n",
829 nasm_version, nasm_date, nasm_compile_options);
830 exit(0); /* never need usage message here */
831 break;
833 case 'e': /* preprocess only */
834 case 'E':
835 operating_mode = op_preprocess;
836 break;
838 case 'a': /* assemble only - don't preprocess */
839 preproc = &preproc_nop;
840 break;
842 case 'W':
843 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
844 do_warn = false;
845 param += 3;
846 } else {
847 do_warn = true;
849 goto set_warning;
851 case 'w':
852 if (param[0] != '+' && param[0] != '-') {
853 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
854 "invalid option to `-w'");
855 break;
857 do_warn = (param[0] == '+');
858 param++;
860 set_warning:
861 for (i = 0; i <= ERR_WARN_MAX; i++) {
862 if (!nasm_stricmp(param, warnings[i].name))
863 break;
865 if (i <= ERR_WARN_MAX) {
866 warning_on_global[i] = do_warn;
867 } else if (!nasm_stricmp(param, "all")) {
868 for (i = 1; i <= ERR_WARN_MAX; i++)
869 warning_on_global[i] = do_warn;
870 } else if (!nasm_stricmp(param, "none")) {
871 for (i = 1; i <= ERR_WARN_MAX; i++)
872 warning_on_global[i] = !do_warn;
873 } else {
874 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
875 "invalid warning `%s'", param);
877 break;
879 case 'M':
880 switch (p[2]) {
881 case 0:
882 operating_mode = op_depend;
883 break;
884 case 'G':
885 operating_mode = op_depend;
886 depend_missing_ok = true;
887 break;
888 case 'P':
889 depend_emit_phony = true;
890 break;
891 case 'D':
892 depend_file = q;
893 advance = true;
894 break;
895 case 'T':
896 depend_target = q;
897 advance = true;
898 break;
899 case 'Q':
900 depend_target = quote_for_make(q);
901 advance = true;
902 break;
903 default:
904 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
905 "unknown dependency option `-M%c'", p[2]);
906 break;
908 if (advance && (!q || !q[0])) {
909 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
910 "option `-M%c' requires a parameter", p[2]);
911 break;
913 break;
915 case '-':
917 int s;
919 if (p[2] == 0) { /* -- => stop processing options */
920 stopoptions = 1;
921 break;
923 for (s = 0; textopts[s].label; s++) {
924 if (!nasm_stricmp(p + 2, textopts[s].label)) {
925 break;
929 switch (s) {
931 case OPT_PREFIX:
932 case OPT_POSTFIX:
934 if (!q) {
935 nasm_error(ERR_NONFATAL | ERR_NOFILE |
936 ERR_USAGE,
937 "option `--%s' requires an argument",
938 p + 2);
939 break;
940 } else {
941 advance = 1, param = q;
944 if (s == OPT_PREFIX) {
945 strncpy(lprefix, param, PREFIX_MAX - 1);
946 lprefix[PREFIX_MAX - 1] = 0;
947 break;
949 if (s == OPT_POSTFIX) {
950 strncpy(lpostfix, param, POSTFIX_MAX - 1);
951 lpostfix[POSTFIX_MAX - 1] = 0;
952 break;
954 break;
956 default:
958 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
959 "unrecognised option `--%s'", p + 2);
960 break;
963 break;
966 default:
967 if (!ofmt->setinfo(GI_SWITCH, &p))
968 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
969 "unrecognised option `-%c'", p[1]);
970 break;
972 } else {
973 if (*inname) {
974 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
975 "more than one input file specified");
976 } else {
977 copy_filename(inname, p);
981 return advance;
984 #define ARG_BUF_DELTA 128
986 static void process_respfile(FILE * rfile)
988 char *buffer, *p, *q, *prevarg;
989 int bufsize, prevargsize;
991 bufsize = prevargsize = ARG_BUF_DELTA;
992 buffer = nasm_malloc(ARG_BUF_DELTA);
993 prevarg = nasm_malloc(ARG_BUF_DELTA);
994 prevarg[0] = '\0';
996 while (1) { /* Loop to handle all lines in file */
997 p = buffer;
998 while (1) { /* Loop to handle long lines */
999 q = fgets(p, bufsize - (p - buffer), rfile);
1000 if (!q)
1001 break;
1002 p += strlen(p);
1003 if (p > buffer && p[-1] == '\n')
1004 break;
1005 if (p - buffer > bufsize - 10) {
1006 int offset;
1007 offset = p - buffer;
1008 bufsize += ARG_BUF_DELTA;
1009 buffer = nasm_realloc(buffer, bufsize);
1010 p = buffer + offset;
1014 if (!q && p == buffer) {
1015 if (prevarg[0])
1016 process_arg(prevarg, NULL);
1017 nasm_free(buffer);
1018 nasm_free(prevarg);
1019 return;
1023 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1024 * them are present at the end of the line.
1026 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1028 while (p > buffer && nasm_isspace(p[-1]))
1029 *--p = '\0';
1031 p = nasm_skip_spaces(buffer);
1033 if (process_arg(prevarg, p))
1034 *p = '\0';
1036 if ((int) strlen(p) > prevargsize - 10) {
1037 prevargsize += ARG_BUF_DELTA;
1038 prevarg = nasm_realloc(prevarg, prevargsize);
1040 strncpy(prevarg, p, prevargsize);
1044 /* Function to process args from a string of args, rather than the
1045 * argv array. Used by the environment variable and response file
1046 * processing.
1048 static void process_args(char *args)
1050 char *p, *q, *arg, *prevarg;
1051 char separator = ' ';
1053 p = args;
1054 if (*p && *p != '-')
1055 separator = *p++;
1056 arg = NULL;
1057 while (*p) {
1058 q = p;
1059 while (*p && *p != separator)
1060 p++;
1061 while (*p == separator)
1062 *p++ = '\0';
1063 prevarg = arg;
1064 arg = q;
1065 if (process_arg(prevarg, arg))
1066 arg = NULL;
1068 if (arg)
1069 process_arg(arg, NULL);
1072 static void process_response_file(const char *file)
1074 char str[2048];
1075 FILE *f = fopen(file, "r");
1076 if (!f) {
1077 perror(file);
1078 exit(-1);
1080 while (fgets(str, sizeof str, f)) {
1081 process_args(str);
1083 fclose(f);
1086 static void parse_cmdline(int argc, char **argv)
1088 FILE *rfile;
1089 char *envreal, *envcopy = NULL, *p;
1090 int i;
1092 *inname = *outname = *listname = *errname = '\0';
1094 for (i = 0; i <= ERR_WARN_MAX; i++)
1095 warning_on_global[i] = warnings[i].enabled;
1098 * First, process the NASMENV environment variable.
1100 envreal = getenv("NASMENV");
1101 if (envreal) {
1102 envcopy = nasm_strdup(envreal);
1103 process_args(envcopy);
1104 nasm_free(envcopy);
1108 * Now process the actual command line.
1110 while (--argc) {
1111 bool advance;
1112 argv++;
1113 if (argv[0][0] == '@') {
1115 * We have a response file, so process this as a set of
1116 * arguments like the environment variable. This allows us
1117 * to have multiple arguments on a single line, which is
1118 * different to the -@resp file processing below for regular
1119 * NASM.
1121 process_response_file(argv[0]+1);
1122 argc--;
1123 argv++;
1125 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1126 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1127 if (p) {
1128 rfile = fopen(p, "r");
1129 if (rfile) {
1130 process_respfile(rfile);
1131 fclose(rfile);
1132 } else
1133 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1134 "unable to open response file `%s'", p);
1136 } else
1137 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1138 argv += advance, argc -= advance;
1142 * Look for basic command line typos. This definitely doesn't
1143 * catch all errors, but it might help cases of fumbled fingers.
1145 if (!*inname)
1146 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1147 "no input file specified");
1148 else if (!strcmp(inname, errname) ||
1149 !strcmp(inname, outname) ||
1150 !strcmp(inname, listname) ||
1151 (depend_file && !strcmp(inname, depend_file)))
1152 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1153 "file `%s' is both input and output file",
1154 inname);
1156 if (*errname) {
1157 error_file = fopen(errname, "w");
1158 if (!error_file) {
1159 error_file = stderr; /* Revert to default! */
1160 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1161 "cannot open file `%s' for error messages",
1162 errname);
1167 static enum directives getkw(char **directive, char **value);
1169 static void assemble_file(char *fname, StrList **depend_ptr)
1171 char *directive, *value, *p, *q, *special, *line;
1172 insn output_ins;
1173 int i, validid;
1174 bool rn_error;
1175 int32_t seg;
1176 int64_t offs;
1177 struct tokenval tokval;
1178 expr *e;
1179 int pass_max;
1181 if (cmd_sb == 32 && cmd_cpu < IF_386)
1182 nasm_error(ERR_FATAL, "command line: "
1183 "32-bit segment size requires a higher cpu");
1185 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1186 for (passn = 1; pass0 <= 2; passn++) {
1187 int pass1, pass2;
1188 ldfunc def_label;
1190 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1191 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1192 /* pass0 0, 0, 0, ..., 1, 2 */
1194 def_label = passn > 1 ? redefine_label : define_label;
1196 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1197 cpu = cmd_cpu;
1198 if (pass0 == 2) {
1199 if (*listname)
1200 nasmlist.init(listname, nasm_error);
1202 in_abs_seg = false;
1203 global_offset_changed = 0; /* set by redefine_label */
1204 location.segment = ofmt->section(NULL, pass2, &sb);
1205 globalbits = sb;
1206 if (passn > 1) {
1207 saa_rewind(forwrefs);
1208 forwref = saa_rstruct(forwrefs);
1209 raa_free(offsets);
1210 offsets = raa_init();
1212 preproc->reset(fname, pass1, &nasmlist,
1213 pass1 == 2 ? depend_ptr : NULL);
1214 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1216 globallineno = 0;
1217 if (passn == 1)
1218 location.known = true;
1219 location.offset = offs = GET_CURR_OFFS;
1221 while ((line = preproc->getline())) {
1222 enum directives d;
1223 globallineno++;
1226 * Here we parse our directives; this is not handled by the
1227 * 'real' parser. This really should be a separate function.
1229 directive = line;
1230 d = getkw(&directive, &value);
1231 if (d) {
1232 int err = 0;
1234 switch (d) {
1235 case D_SEGMENT: /* [SEGMENT n] */
1236 case D_SECTION:
1237 seg = ofmt->section(value, pass2, &sb);
1238 if (seg == NO_SEG) {
1239 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1240 "segment name `%s' not recognized",
1241 value);
1242 } else {
1243 in_abs_seg = false;
1244 location.segment = seg;
1246 break;
1247 case D_SECTALIGN: /* [SECTALIGN n] */
1248 if (*value) {
1249 stdscan_reset();
1250 stdscan_set(value);
1251 tokval.t_type = TOKEN_INVALID;
1252 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1253 if (e) {
1254 unsigned int align = (unsigned int)e->value;
1255 if ((uint64_t)e->value > 0x7fffffff) {
1257 * FIXME: Please make some sane message here
1258 * ofmt should have some 'check' method which
1259 * would report segment alignment bounds.
1261 nasm_error(ERR_FATAL,
1262 "incorrect segment alignment `%s'", value);
1263 } else if (!is_power2(align)) {
1264 nasm_error(ERR_NONFATAL,
1265 "segment alignment `%s' is not power of two",
1266 value);
1268 /* callee should be able to handle all details */
1269 ofmt->sectalign(location.segment, align);
1272 break;
1273 case D_EXTERN: /* [EXTERN label:special] */
1274 if (*value == '$')
1275 value++; /* skip initial $ if present */
1276 if (pass0 == 2) {
1277 q = value;
1278 while (*q && *q != ':')
1279 q++;
1280 if (*q == ':') {
1281 *q++ = '\0';
1282 ofmt->symdef(value, 0L, 0L, 3, q);
1284 } else if (passn == 1) {
1285 q = value;
1286 validid = true;
1287 if (!isidstart(*q))
1288 validid = false;
1289 while (*q && *q != ':') {
1290 if (!isidchar(*q))
1291 validid = false;
1292 q++;
1294 if (!validid) {
1295 nasm_error(ERR_NONFATAL,
1296 "identifier expected after EXTERN");
1297 break;
1299 if (*q == ':') {
1300 *q++ = '\0';
1301 special = q;
1302 } else
1303 special = NULL;
1304 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1305 int temp = pass0;
1306 pass0 = 1; /* fake pass 1 in labels.c */
1307 declare_as_global(value, special);
1308 define_label(value, seg_alloc(), 0L, NULL,
1309 false, true);
1310 pass0 = temp;
1312 } /* else pass0 == 1 */
1313 break;
1314 case D_BITS: /* [BITS bits] */
1315 globalbits = sb = get_bits(value);
1316 break;
1317 case D_GLOBAL: /* [GLOBAL symbol:special] */
1318 if (*value == '$')
1319 value++; /* skip initial $ if present */
1320 if (pass0 == 2) { /* pass 2 */
1321 q = value;
1322 while (*q && *q != ':')
1323 q++;
1324 if (*q == ':') {
1325 *q++ = '\0';
1326 ofmt->symdef(value, 0L, 0L, 3, q);
1328 } else if (pass2 == 1) { /* pass == 1 */
1329 q = value;
1330 validid = true;
1331 if (!isidstart(*q))
1332 validid = false;
1333 while (*q && *q != ':') {
1334 if (!isidchar(*q))
1335 validid = false;
1336 q++;
1338 if (!validid) {
1339 nasm_error(ERR_NONFATAL,
1340 "identifier expected after GLOBAL");
1341 break;
1343 if (*q == ':') {
1344 *q++ = '\0';
1345 special = q;
1346 } else
1347 special = NULL;
1348 declare_as_global(value, special);
1349 } /* pass == 1 */
1350 break;
1351 case D_COMMON: /* [COMMON symbol size:special] */
1353 int64_t size;
1355 if (*value == '$')
1356 value++; /* skip initial $ if present */
1357 p = value;
1358 validid = true;
1359 if (!isidstart(*p))
1360 validid = false;
1361 while (*p && !nasm_isspace(*p)) {
1362 if (!isidchar(*p))
1363 validid = false;
1364 p++;
1366 if (!validid) {
1367 nasm_error(ERR_NONFATAL,
1368 "identifier expected after COMMON");
1369 break;
1371 if (*p) {
1372 p = nasm_zap_spaces_fwd(p);
1373 q = p;
1374 while (*q && *q != ':')
1375 q++;
1376 if (*q == ':') {
1377 *q++ = '\0';
1378 special = q;
1379 } else {
1380 special = NULL;
1382 size = readnum(p, &rn_error);
1383 if (rn_error) {
1384 nasm_error(ERR_NONFATAL,
1385 "invalid size specified"
1386 " in COMMON declaration");
1387 break;
1389 } else {
1390 nasm_error(ERR_NONFATAL,
1391 "no size specified in"
1392 " COMMON declaration");
1393 break;
1396 if (pass0 < 2) {
1397 define_common(value, seg_alloc(), size, special);
1398 } else if (pass0 == 2) {
1399 if (special)
1400 ofmt->symdef(value, 0L, 0L, 3, special);
1402 break;
1404 case D_ABSOLUTE: /* [ABSOLUTE address] */
1405 stdscan_reset();
1406 stdscan_set(value);
1407 tokval.t_type = TOKEN_INVALID;
1408 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1409 nasm_error, NULL);
1410 if (e) {
1411 if (!is_reloc(e))
1412 nasm_error(pass0 ==
1413 1 ? ERR_NONFATAL : ERR_PANIC,
1414 "cannot use non-relocatable expression as "
1415 "ABSOLUTE address");
1416 else {
1417 abs_seg = reloc_seg(e);
1418 abs_offset = reloc_value(e);
1420 } else if (passn == 1)
1421 abs_offset = 0x100; /* don't go near zero in case of / */
1422 else
1423 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1424 "in pass two");
1425 in_abs_seg = true;
1426 location.segment = NO_SEG;
1427 break;
1428 case D_DEBUG: /* [DEBUG] */
1430 char debugid[128];
1431 bool badid, overlong;
1433 p = value;
1434 q = debugid;
1435 badid = overlong = false;
1436 if (!isidstart(*p)) {
1437 badid = true;
1438 } else {
1439 while (*p && !nasm_isspace(*p)) {
1440 if (q >= debugid + sizeof debugid - 1) {
1441 overlong = true;
1442 break;
1444 if (!isidchar(*p))
1445 badid = true;
1446 *q++ = *p++;
1448 *q = 0;
1450 if (badid) {
1451 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1452 "identifier expected after DEBUG");
1453 break;
1455 if (overlong) {
1456 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1457 "DEBUG identifier too long");
1458 break;
1460 p = nasm_skip_spaces(p);
1461 if (pass0 == 2)
1462 dfmt->debug_directive(debugid, p);
1463 break;
1465 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1466 value = nasm_skip_spaces(value);
1467 switch(*value) {
1468 case '-': validid = 0; value++; break;
1469 case '+': validid = 1; value++; break;
1470 case '*': validid = 2; value++; break;
1471 default: validid = 1; break;
1474 for (i = 1; i <= ERR_WARN_MAX; i++)
1475 if (!nasm_stricmp(value, warnings[i].name))
1476 break;
1477 if (i <= ERR_WARN_MAX) {
1478 switch(validid) {
1479 case 0:
1480 warning_on[i] = false;
1481 break;
1482 case 1:
1483 warning_on[i] = true;
1484 break;
1485 case 2:
1486 warning_on[i] = warning_on_global[i];
1487 break;
1489 } else
1490 nasm_error(ERR_NONFATAL,
1491 "invalid warning id in WARNING directive");
1492 break;
1493 case D_CPU: /* [CPU] */
1494 cpu = get_cpu(value);
1495 break;
1496 case D_LIST: /* [LIST {+|-}] */
1497 value = nasm_skip_spaces(value);
1498 if (*value == '+') {
1499 user_nolist = 0;
1500 } else {
1501 if (*value == '-') {
1502 user_nolist = 1;
1503 } else {
1504 err = 1;
1507 break;
1508 case D_DEFAULT: /* [DEFAULT] */
1509 stdscan_reset();
1510 stdscan_set(value);
1511 tokval.t_type = TOKEN_INVALID;
1512 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1513 switch ((int)tokval.t_integer) {
1514 case S_REL:
1515 globalrel = 1;
1516 break;
1517 case S_ABS:
1518 globalrel = 0;
1519 break;
1520 default:
1521 err = 1;
1522 break;
1524 } else {
1525 err = 1;
1527 break;
1528 case D_FLOAT:
1529 if (float_option(value)) {
1530 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1531 "unknown 'float' directive: %s",
1532 value);
1534 break;
1535 default:
1536 if (ofmt->directive(d, value, pass2))
1537 break;
1538 /* else fall through */
1539 case D_unknown:
1540 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1541 "unrecognised directive [%s]",
1542 directive);
1543 break;
1545 if (err) {
1546 nasm_error(ERR_NONFATAL,
1547 "invalid parameter to [%s] directive",
1548 directive);
1550 } else { /* it isn't a directive */
1551 parse_line(pass1, line, &output_ins, def_label);
1553 if (optimizing > 0) {
1554 if (forwref != NULL && globallineno == forwref->lineno) {
1555 output_ins.forw_ref = true;
1556 do {
1557 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1558 forwref = saa_rstruct(forwrefs);
1559 } while (forwref != NULL
1560 && forwref->lineno == globallineno);
1561 } else
1562 output_ins.forw_ref = false;
1564 if (output_ins.forw_ref) {
1565 if (passn == 1) {
1566 for (i = 0; i < output_ins.operands; i++) {
1567 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1568 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1569 fwinf->lineno = globallineno;
1570 fwinf->operand = i;
1577 /* forw_ref */
1578 if (output_ins.opcode == I_EQU) {
1579 if (pass1 == 1) {
1581 * Special `..' EQUs get processed in pass two,
1582 * except `..@' macro-processor EQUs which are done
1583 * in the normal place.
1585 if (!output_ins.label)
1586 nasm_error(ERR_NONFATAL,
1587 "EQU not preceded by label");
1589 else if (output_ins.label[0] != '.' ||
1590 output_ins.label[1] != '.' ||
1591 output_ins.label[2] == '@') {
1592 if (output_ins.operands == 1 &&
1593 (output_ins.oprs[0].type & IMMEDIATE) &&
1594 output_ins.oprs[0].wrt == NO_SEG) {
1595 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1596 def_label(output_ins.label,
1597 output_ins.oprs[0].segment,
1598 output_ins.oprs[0].offset, NULL,
1599 false, isext);
1600 } else if (output_ins.operands == 2
1601 && (output_ins.oprs[0].type & IMMEDIATE)
1602 && (output_ins.oprs[0].type & COLON)
1603 && output_ins.oprs[0].segment == NO_SEG
1604 && output_ins.oprs[0].wrt == NO_SEG
1605 && (output_ins.oprs[1].type & IMMEDIATE)
1606 && output_ins.oprs[1].segment == NO_SEG
1607 && output_ins.oprs[1].wrt == NO_SEG) {
1608 def_label(output_ins.label,
1609 output_ins.oprs[0].offset | SEG_ABS,
1610 output_ins.oprs[1].offset,
1611 NULL, false, false);
1612 } else
1613 nasm_error(ERR_NONFATAL,
1614 "bad syntax for EQU");
1616 } else {
1618 * Special `..' EQUs get processed here, except
1619 * `..@' macro processor EQUs which are done above.
1621 if (output_ins.label[0] == '.' &&
1622 output_ins.label[1] == '.' &&
1623 output_ins.label[2] != '@') {
1624 if (output_ins.operands == 1 &&
1625 (output_ins.oprs[0].type & IMMEDIATE)) {
1626 define_label(output_ins.label,
1627 output_ins.oprs[0].segment,
1628 output_ins.oprs[0].offset,
1629 NULL, false, false);
1630 } else if (output_ins.operands == 2
1631 && (output_ins.oprs[0].type & IMMEDIATE)
1632 && (output_ins.oprs[0].type & COLON)
1633 && output_ins.oprs[0].segment == NO_SEG
1634 && (output_ins.oprs[1].type & IMMEDIATE)
1635 && output_ins.oprs[1].segment == NO_SEG) {
1636 define_label(output_ins.label,
1637 output_ins.oprs[0].offset | SEG_ABS,
1638 output_ins.oprs[1].offset,
1639 NULL, false, false);
1640 } else
1641 nasm_error(ERR_NONFATAL,
1642 "bad syntax for EQU");
1645 } else { /* instruction isn't an EQU */
1647 if (pass1 == 1) {
1649 int64_t l = insn_size(location.segment, offs, sb, cpu,
1650 &output_ins, nasm_error);
1652 /* if (using_debug_info) && output_ins.opcode != -1) */
1653 if (using_debug_info)
1654 { /* fbk 03/25/01 */
1655 /* this is done here so we can do debug type info */
1656 int32_t typeinfo =
1657 TYS_ELEMENTS(output_ins.operands);
1658 switch (output_ins.opcode) {
1659 case I_RESB:
1660 typeinfo =
1661 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1662 break;
1663 case I_RESW:
1664 typeinfo =
1665 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1666 break;
1667 case I_RESD:
1668 typeinfo =
1669 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1670 break;
1671 case I_RESQ:
1672 typeinfo =
1673 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1674 break;
1675 case I_REST:
1676 typeinfo =
1677 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1678 break;
1679 case I_RESO:
1680 typeinfo =
1681 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1682 break;
1683 case I_RESY:
1684 typeinfo =
1685 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1686 break;
1687 case I_DB:
1688 typeinfo |= TY_BYTE;
1689 break;
1690 case I_DW:
1691 typeinfo |= TY_WORD;
1692 break;
1693 case I_DD:
1694 if (output_ins.eops_float)
1695 typeinfo |= TY_FLOAT;
1696 else
1697 typeinfo |= TY_DWORD;
1698 break;
1699 case I_DQ:
1700 typeinfo |= TY_QWORD;
1701 break;
1702 case I_DT:
1703 typeinfo |= TY_TBYTE;
1704 break;
1705 case I_DO:
1706 typeinfo |= TY_OWORD;
1707 break;
1708 case I_DY:
1709 typeinfo |= TY_YWORD;
1710 break;
1711 default:
1712 typeinfo = TY_LABEL;
1716 dfmt->debug_typevalue(typeinfo);
1718 if (l != -1) {
1719 offs += l;
1720 SET_CURR_OFFS(offs);
1723 * else l == -1 => invalid instruction, which will be
1724 * flagged as an error on pass 2
1727 } else {
1728 offs += assemble(location.segment, offs, sb, cpu,
1729 &output_ins, ofmt, nasm_error,
1730 &nasmlist);
1731 SET_CURR_OFFS(offs);
1734 } /* not an EQU */
1735 cleanup_insn(&output_ins);
1737 nasm_free(line);
1738 location.offset = offs = GET_CURR_OFFS;
1739 } /* end while (line = preproc->getline... */
1741 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1742 nasm_error(ERR_NONFATAL,
1743 "phase error detected at end of assembly.");
1745 if (pass1 == 1)
1746 preproc->cleanup(1);
1748 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1749 pass0++;
1750 } else if (global_offset_changed &&
1751 global_offset_changed < prev_offset_changed) {
1752 prev_offset_changed = global_offset_changed;
1753 stall_count = 0;
1754 } else {
1755 stall_count++;
1758 if (terminate_after_phase)
1759 break;
1761 if ((stall_count > 997) || (passn >= pass_max)) {
1762 /* We get here if the labels don't converge
1763 * Example: FOO equ FOO + 1
1765 nasm_error(ERR_NONFATAL,
1766 "Can't find valid values for all labels "
1767 "after %d passes, giving up.", passn);
1768 nasm_error(ERR_NONFATAL,
1769 "Possible causes: recursive EQUs, macro abuse.");
1770 break;
1774 preproc->cleanup(0);
1775 nasmlist.cleanup();
1776 if (!terminate_after_phase && opt_verbose_info) {
1777 /* -On and -Ov switches */
1778 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1782 static enum directives getkw(char **directive, char **value)
1784 char *p, *q, *buf;
1786 buf = nasm_skip_spaces(*directive);
1788 /* it should be enclosed in [ ] */
1789 if (*buf != '[')
1790 return D_none;
1791 q = strchr(buf, ']');
1792 if (!q)
1793 return D_none;
1795 /* stip off the comments */
1796 p = strchr(buf, ';');
1797 if (p) {
1798 if (p < q) /* ouch! somwhere inside */
1799 return D_none;
1800 *p = '\0';
1803 /* no brace, no trailing spaces */
1804 *q = '\0';
1805 nasm_zap_spaces_rev(--q);
1807 /* directive */
1808 p = nasm_skip_spaces(++buf);
1809 q = nasm_skip_word(p);
1810 if (!q)
1811 return D_none; /* sigh... no value there */
1812 *q = '\0';
1813 *directive = p;
1815 /* and value finally */
1816 p = nasm_skip_spaces(++q);
1817 *value = p;
1819 return find_directive(*directive);
1823 * gnu style error reporting
1824 * This function prints an error message to error_file in the
1825 * style used by GNU. An example would be:
1826 * file.asm:50: error: blah blah blah
1827 * where file.asm is the name of the file, 50 is the line number on
1828 * which the error occurs (or is detected) and "error:" is one of
1829 * the possible optional diagnostics -- it can be "error" or "warning"
1830 * or something else. Finally the line terminates with the actual
1831 * error message.
1833 * @param severity the severity of the warning or error
1834 * @param fmt the printf style format string
1836 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1838 char *currentfile = NULL;
1839 int32_t lineno = 0;
1841 if (is_suppressed_warning(severity))
1842 return;
1844 if (!(severity & ERR_NOFILE))
1845 src_get(&lineno, &currentfile);
1847 if (currentfile) {
1848 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1849 nasm_free(currentfile);
1850 } else {
1851 fputs("nasm: ", error_file);
1854 nasm_verror_common(severity, fmt, ap);
1858 * MS style error reporting
1859 * This function prints an error message to error_file in the
1860 * style used by Visual C and some other Microsoft tools. An example
1861 * would be:
1862 * file.asm(50) : error: blah blah blah
1863 * where file.asm is the name of the file, 50 is the line number on
1864 * which the error occurs (or is detected) and "error:" is one of
1865 * the possible optional diagnostics -- it can be "error" or "warning"
1866 * or something else. Finally the line terminates with the actual
1867 * error message.
1869 * @param severity the severity of the warning or error
1870 * @param fmt the printf style format string
1872 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1874 char *currentfile = NULL;
1875 int32_t lineno = 0;
1877 if (is_suppressed_warning(severity))
1878 return;
1880 if (!(severity & ERR_NOFILE))
1881 src_get(&lineno, &currentfile);
1883 if (currentfile) {
1884 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1885 nasm_free(currentfile);
1886 } else {
1887 fputs("nasm: ", error_file);
1890 nasm_verror_common(severity, fmt, ap);
1894 * check for supressed warning
1895 * checks for suppressed warning or pass one only warning and we're
1896 * not in pass 1
1898 * @param severity the severity of the warning or error
1899 * @return true if we should abort error/warning printing
1901 static bool is_suppressed_warning(int severity)
1903 /* Not a warning at all */
1904 if ((severity & ERR_MASK) != ERR_WARNING)
1905 return false;
1907 /* See if it's a pass-one only warning and we're not in pass one. */
1908 if (((severity & ERR_PASS1) && pass0 != 1) ||
1909 ((severity & ERR_PASS2) && pass0 != 2))
1910 return true;
1912 /* Might be a warning but suppresed explicitly */
1913 if (severity & ERR_WARN_MASK)
1914 return !warning_on[WARN_IDX(severity)];
1915 else
1916 return false;
1920 * common error reporting
1921 * This is the common back end of the error reporting schemes currently
1922 * implemented. It prints the nature of the warning and then the
1923 * specific error message to error_file and may or may not return. It
1924 * doesn't return if the error severity is a "panic" or "debug" type.
1926 * @param severity the severity of the warning or error
1927 * @param fmt the printf style format string
1929 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1931 char msg[1024];
1932 const char *pfx;
1934 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1935 case ERR_WARNING:
1936 pfx = "warning: ";
1937 break;
1938 case ERR_NONFATAL:
1939 pfx = "error: ";
1940 break;
1941 case ERR_FATAL:
1942 pfx = "fatal: ";
1943 break;
1944 case ERR_PANIC:
1945 pfx = "panic: ";
1946 break;
1947 case ERR_DEBUG:
1948 pfx = "debug: ";
1949 break;
1950 default:
1951 pfx = "";
1952 break;
1955 vsnprintf(msg, sizeof msg, fmt, args);
1957 fprintf(error_file, "%s%s\n", pfx, msg);
1959 if (*listname)
1960 nasmlist.error(severity, pfx, msg);
1962 if (severity & ERR_USAGE)
1963 want_usage = true;
1965 switch (severity & ERR_MASK) {
1966 case ERR_DEBUG:
1967 /* no further action, by definition */
1968 break;
1969 case ERR_WARNING:
1970 /* Treat warnings as errors */
1971 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1972 terminate_after_phase = true;
1973 break;
1974 case ERR_NONFATAL:
1975 terminate_after_phase = true;
1976 break;
1977 case ERR_FATAL:
1978 if (ofile) {
1979 fclose(ofile);
1980 remove(outname);
1981 ofile = NULL;
1983 if (want_usage)
1984 usage();
1985 exit(1); /* instantly die */
1986 break; /* placate silly compilers */
1987 case ERR_PANIC:
1988 fflush(NULL);
1989 /* abort(); */ /* halt, catch fire, and dump core */
1990 exit(3);
1991 break;
1995 static void usage(void)
1997 fputs("type `nasm -h' for help\n", error_file);
2000 static uint32_t get_cpu(char *value)
2002 if (!strcmp(value, "8086"))
2003 return IF_8086;
2004 if (!strcmp(value, "186"))
2005 return IF_186;
2006 if (!strcmp(value, "286"))
2007 return IF_286;
2008 if (!strcmp(value, "386"))
2009 return IF_386;
2010 if (!strcmp(value, "486"))
2011 return IF_486;
2012 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2013 return IF_PENT;
2014 if (!strcmp(value, "686") ||
2015 !nasm_stricmp(value, "ppro") ||
2016 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2017 return IF_P6;
2018 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2019 return IF_KATMAI;
2020 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2021 !nasm_stricmp(value, "willamette"))
2022 return IF_WILLAMETTE;
2023 if (!nasm_stricmp(value, "prescott"))
2024 return IF_PRESCOTT;
2025 if (!nasm_stricmp(value, "x64") ||
2026 !nasm_stricmp(value, "x86-64"))
2027 return IF_X86_64;
2028 if (!nasm_stricmp(value, "ia64") ||
2029 !nasm_stricmp(value, "ia-64") ||
2030 !nasm_stricmp(value, "itanium") ||
2031 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2032 return IF_IA64;
2034 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2035 "unknown 'cpu' type");
2037 return IF_PLEVEL; /* the maximum level */
2040 static int get_bits(char *value)
2042 int i;
2044 if ((i = atoi(value)) == 16)
2045 return i; /* set for a 16-bit segment */
2046 else if (i == 32) {
2047 if (cpu < IF_386) {
2048 nasm_error(ERR_NONFATAL,
2049 "cannot specify 32-bit segment on processor below a 386");
2050 i = 16;
2052 } else if (i == 64) {
2053 if (cpu < IF_X86_64) {
2054 nasm_error(ERR_NONFATAL,
2055 "cannot specify 64-bit segment on processor below an x86-64");
2056 i = 16;
2058 if (i != maxbits) {
2059 nasm_error(ERR_NONFATAL,
2060 "%s output format does not support 64-bit code",
2061 ofmt->shortname);
2062 i = 16;
2064 } else {
2065 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2066 "`%s' is not a valid segment size; must be 16, 32 or 64",
2067 value);
2068 i = 16;
2070 return i;