output: Add more Elf unification
[nasm.git] / nasm.c
blob2ee319fe4719d79b7c09f3ed1f9f03fe0c34ce3c
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 * 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))
361 ? &depend_list : NULL;
362 if (!depend_target)
363 depend_target = quote_for_make(outname);
365 switch (operating_mode) {
366 case op_depend:
368 char *line;
370 if (depend_missing_ok)
371 preproc->include_path(NULL); /* "assume generated" */
373 preproc->reset(inname, 0, &nasmlist, depend_ptr);
374 if (outname[0] == '\0')
375 ofmt->filename(inname, outname);
376 ofile = NULL;
377 while ((line = preproc->getline()))
378 nasm_free(line);
379 preproc->cleanup(0);
381 break;
383 case op_preprocess:
385 char *line;
386 char *file_name = NULL;
387 int32_t prior_linnum = 0;
388 int lineinc = 0;
390 if (*outname) {
391 ofile = fopen(outname, "w");
392 if (!ofile)
393 nasm_error(ERR_FATAL | ERR_NOFILE,
394 "unable to open output file `%s'",
395 outname);
396 } else
397 ofile = NULL;
399 location.known = false;
401 /* pass = 1; */
402 preproc->reset(inname, 3, &nasmlist, depend_ptr);
403 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
405 while ((line = preproc->getline())) {
407 * We generate %line directives if needed for later programs
409 int32_t linnum = prior_linnum += lineinc;
410 int altline = src_get(&linnum, &file_name);
411 if (altline) {
412 if (altline == 1 && lineinc == 1)
413 nasm_fputs("", ofile);
414 else {
415 lineinc = (altline != -1 || lineinc != 1);
416 fprintf(ofile ? ofile : stdout,
417 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
418 file_name);
420 prior_linnum = linnum;
422 nasm_fputs(line, ofile);
423 nasm_free(line);
425 nasm_free(file_name);
426 preproc->cleanup(0);
427 if (ofile)
428 fclose(ofile);
429 if (ofile && terminate_after_phase)
430 remove(outname);
431 ofile = NULL;
433 break;
435 case op_normal:
438 * We must call ofmt->filename _anyway_, even if the user
439 * has specified their own output file, because some
440 * formats (eg OBJ and COFF) use ofmt->filename to find out
441 * the name of the input file and then put that inside the
442 * file.
444 ofmt->filename(inname, outname);
446 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
447 if (!ofile) {
448 nasm_error(ERR_FATAL | ERR_NOFILE,
449 "unable to open output file `%s'", outname);
453 * We must call init_labels() before ofmt->init() since
454 * some object formats will want to define labels in their
455 * init routines. (eg OS/2 defines the FLAT group)
457 init_labels();
459 ofmt->init();
460 dfmt = ofmt->current_dfmt;
461 dfmt->init();
463 assemble_file(inname, depend_ptr);
465 if (!terminate_after_phase) {
466 ofmt->cleanup(using_debug_info);
467 cleanup_labels();
468 fflush(ofile);
469 if (ferror(ofile)) {
470 nasm_error(ERR_NONFATAL|ERR_NOFILE,
471 "write error on output file `%s'", outname);
475 if (ofile) {
476 fclose(ofile);
477 if (terminate_after_phase)
478 remove(outname);
479 ofile = NULL;
482 break;
485 if (depend_list && !terminate_after_phase)
486 emit_dependencies(depend_list);
488 if (want_usage)
489 usage();
491 raa_free(offsets);
492 saa_free(forwrefs);
493 eval_cleanup();
494 stdscan_cleanup();
496 return terminate_after_phase;
500 * Get a parameter for a command line option.
501 * First arg must be in the form of e.g. -f...
503 static char *get_param(char *p, char *q, bool *advance)
505 *advance = false;
506 if (p[2]) /* the parameter's in the option */
507 return nasm_skip_spaces(p + 2);
508 if (q && q[0]) {
509 *advance = true;
510 return q;
512 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
513 "option `-%c' requires an argument", p[1]);
514 return NULL;
518 * Copy a filename
520 static void copy_filename(char *dst, const char *src)
522 size_t len = strlen(src);
524 if (len >= (size_t)FILENAME_MAX) {
525 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
526 return;
528 strncpy(dst, src, FILENAME_MAX);
532 * Convert a string to Make-safe form
534 static char *quote_for_make(const char *str)
536 const char *p;
537 char *os, *q;
539 size_t n = 1; /* Terminating zero */
540 size_t nbs = 0;
542 if (!str)
543 return NULL;
545 for (p = str; *p; p++) {
546 switch (*p) {
547 case ' ':
548 case '\t':
549 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
550 n += nbs + 2;
551 nbs = 0;
552 break;
553 case '$':
554 case '#':
555 nbs = 0;
556 n += 2;
557 break;
558 case '\\':
559 nbs++;
560 n++;
561 break;
562 default:
563 nbs = 0;
564 n++;
565 break;
569 /* Convert N backslashes at the end of filename to 2N backslashes */
570 if (nbs)
571 n += nbs;
573 os = q = nasm_malloc(n);
575 nbs = 0;
576 for (p = str; *p; p++) {
577 switch (*p) {
578 case ' ':
579 case '\t':
580 while (nbs--)
581 *q++ = '\\';
582 *q++ = '\\';
583 *q++ = *p;
584 break;
585 case '$':
586 *q++ = *p;
587 *q++ = *p;
588 nbs = 0;
589 break;
590 case '#':
591 *q++ = '\\';
592 *q++ = *p;
593 nbs = 0;
594 break;
595 case '\\':
596 *q++ = *p;
597 nbs++;
598 break;
599 default:
600 *q++ = *p;
601 nbs = 0;
602 break;
605 while (nbs--)
606 *q++ = '\\';
608 *q = '\0';
610 return os;
613 struct textargs {
614 const char *label;
615 int value;
618 #define OPT_PREFIX 0
619 #define OPT_POSTFIX 1
620 struct textargs textopts[] = {
621 {"prefix", OPT_PREFIX},
622 {"postfix", OPT_POSTFIX},
623 {NULL, 0}
626 static bool stopoptions = false;
627 static bool process_arg(char *p, char *q)
629 char *param;
630 int i;
631 bool advance = false;
632 bool do_warn;
634 if (!p || !p[0])
635 return false;
637 if (p[0] == '-' && !stopoptions) {
638 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
639 /* These parameters take values */
640 if (!(param = get_param(p, q, &advance)))
641 return advance;
644 switch (p[1]) {
645 case 's':
646 error_file = stdout;
647 break;
649 case 'o': /* output file */
650 copy_filename(outname, param);
651 break;
653 case 'f': /* output format */
654 ofmt = ofmt_find(param, &ofmt_alias);
655 if (!ofmt) {
656 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
657 "unrecognised output format `%s' - "
658 "use -hf for a list", param);
660 break;
662 case 'O': /* Optimization level */
664 int opt;
666 if (!*param) {
667 /* Naked -O == -Ox */
668 optimizing = MAX_OPTIMIZE;
669 } else {
670 while (*param) {
671 switch (*param) {
672 case '0': case '1': case '2': case '3': case '4':
673 case '5': case '6': case '7': case '8': case '9':
674 opt = strtoul(param, &param, 10);
676 /* -O0 -> optimizing == -1, 0.98 behaviour */
677 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
678 if (opt < 2)
679 optimizing = opt - 1;
680 else
681 optimizing = opt;
682 break;
684 case 'v':
685 case '+':
686 param++;
687 opt_verbose_info = true;
688 break;
690 case 'x':
691 param++;
692 optimizing = MAX_OPTIMIZE;
693 break;
695 default:
696 nasm_error(ERR_FATAL,
697 "unknown optimization option -O%c\n",
698 *param);
699 break;
702 if (optimizing > MAX_OPTIMIZE)
703 optimizing = MAX_OPTIMIZE;
705 break;
708 case 'p': /* pre-include */
709 case 'P':
710 preproc->pre_include(param);
711 break;
713 case 'd': /* pre-define */
714 case 'D':
715 preproc->pre_define(param);
716 break;
718 case 'u': /* un-define */
719 case 'U':
720 preproc->pre_undefine(param);
721 break;
723 case 'i': /* include search path */
724 case 'I':
725 preproc->include_path(param);
726 break;
728 case 'l': /* listing file */
729 copy_filename(listname, param);
730 break;
732 case 'Z': /* error messages file */
733 copy_filename(errname, param);
734 break;
736 case 'F': /* specify debug format */
737 ofmt->current_dfmt = dfmt_find(ofmt, param);
738 if (!ofmt->current_dfmt) {
739 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
740 "unrecognized debug format `%s' for"
741 " output format `%s'",
742 param, ofmt->shortname);
744 using_debug_info = true;
745 break;
747 case 'X': /* specify error reporting format */
748 if (nasm_stricmp("vc", param) == 0)
749 nasm_set_verror(nasm_verror_vc);
750 else if (nasm_stricmp("gnu", param) == 0)
751 nasm_set_verror(nasm_verror_gnu);
752 else
753 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
754 "unrecognized error reporting format `%s'",
755 param);
756 break;
758 case 'g':
759 using_debug_info = true;
760 break;
762 case 'h':
763 printf
764 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
765 "[-l listfile]\n"
766 " [options...] [--] filename\n"
767 " or nasm -v for version info\n\n"
768 " -t assemble in SciTech TASM compatible mode\n"
769 " -g generate debug information in selected format\n");
770 printf
771 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
772 " -a don't preprocess (assemble only)\n"
773 " -M generate Makefile dependencies on stdout\n"
774 " -MG d:o, missing files assumed generated\n"
775 " -MF <file> set Makefile dependency file\n"
776 " -MD <file> assemble and generate dependencies\n"
777 " -MT <file> dependency target name\n"
778 " -MQ <file> dependency target name (quoted)\n"
779 " -MP emit phony target\n\n"
780 " -Z<file> redirect error messages to file\n"
781 " -s redirect error messages to stdout\n\n"
782 " -F format select a debugging format\n\n"
783 " -I<path> adds a pathname to the include file path\n");
784 printf
785 (" -O<digit> optimize branch offsets\n"
786 " -O0: No optimization\n"
787 " -O1: Minimal optimization\n"
788 " -Ox: Multipass optimization (default)\n\n"
789 " -P<file> pre-includes a file\n"
790 " -D<macro>[=<value>] pre-defines a macro\n"
791 " -U<macro> undefines a macro\n"
792 " -X<format> specifies error reporting format (gnu or vc)\n"
793 " -w+foo enables warning foo (equiv. -Wfoo)\n"
794 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
795 "--prefix,--postfix\n"
796 " this options prepend or append the given argument to all\n"
797 " extern and global variables\n\n"
798 "Warnings:\n");
799 for (i = 0; i <= ERR_WARN_MAX; i++)
800 printf(" %-23s %s (default %s)\n",
801 warnings[i].name, warnings[i].help,
802 warnings[i].enabled ? "on" : "off");
803 printf
804 ("\nresponse files should contain command line parameters"
805 ", one per line.\n");
806 if (p[2] == 'f') {
807 printf("\nvalid output formats for -f are"
808 " (`*' denotes default):\n");
809 ofmt_list(ofmt, stdout);
810 } else {
811 printf("\nFor a list of valid output formats, use -hf.\n");
812 printf("For a list of debug formats, use -f <form> -y.\n");
814 exit(0); /* never need usage message here */
815 break;
817 case 'y':
818 printf("\nvalid debug formats for '%s' output format are"
819 " ('*' denotes default):\n", ofmt->shortname);
820 dfmt_list(ofmt, stdout);
821 exit(0);
822 break;
824 case 't':
825 tasm_compatible_mode = true;
826 break;
828 case 'v':
829 printf("NASM version %s compiled on %s%s\n",
830 nasm_version, nasm_date, nasm_compile_options);
831 exit(0); /* never need usage message here */
832 break;
834 case 'e': /* preprocess only */
835 case 'E':
836 operating_mode = op_preprocess;
837 break;
839 case 'a': /* assemble only - don't preprocess */
840 preproc = &preproc_nop;
841 break;
843 case 'W':
844 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
845 do_warn = false;
846 param += 3;
847 } else {
848 do_warn = true;
850 goto set_warning;
852 case 'w':
853 if (param[0] != '+' && param[0] != '-') {
854 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
855 "invalid option to `-w'");
856 break;
858 do_warn = (param[0] == '+');
859 param++;
861 set_warning:
862 for (i = 0; i <= ERR_WARN_MAX; i++) {
863 if (!nasm_stricmp(param, warnings[i].name))
864 break;
866 if (i <= ERR_WARN_MAX) {
867 warning_on_global[i] = do_warn;
868 } else if (!nasm_stricmp(param, "all")) {
869 for (i = 1; i <= ERR_WARN_MAX; i++)
870 warning_on_global[i] = do_warn;
871 } else if (!nasm_stricmp(param, "none")) {
872 for (i = 1; i <= ERR_WARN_MAX; i++)
873 warning_on_global[i] = !do_warn;
874 } else {
875 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
876 "invalid warning `%s'", param);
878 break;
880 case 'M':
881 switch (p[2]) {
882 case 0:
883 operating_mode = op_depend;
884 break;
885 case 'G':
886 operating_mode = op_depend;
887 depend_missing_ok = true;
888 break;
889 case 'P':
890 depend_emit_phony = true;
891 break;
892 case 'D':
893 depend_file = q;
894 advance = true;
895 break;
896 case 'T':
897 depend_target = q;
898 advance = true;
899 break;
900 case 'Q':
901 depend_target = quote_for_make(q);
902 advance = true;
903 break;
904 default:
905 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
906 "unknown dependency option `-M%c'", p[2]);
907 break;
909 if (advance && (!q || !q[0])) {
910 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
911 "option `-M%c' requires a parameter", p[2]);
912 break;
914 break;
916 case '-':
918 int s;
920 if (p[2] == 0) { /* -- => stop processing options */
921 stopoptions = 1;
922 break;
924 for (s = 0; textopts[s].label; s++) {
925 if (!nasm_stricmp(p + 2, textopts[s].label)) {
926 break;
930 switch (s) {
932 case OPT_PREFIX:
933 case OPT_POSTFIX:
935 if (!q) {
936 nasm_error(ERR_NONFATAL | ERR_NOFILE |
937 ERR_USAGE,
938 "option `--%s' requires an argument",
939 p + 2);
940 break;
941 } else {
942 advance = 1, param = q;
945 if (s == OPT_PREFIX) {
946 strncpy(lprefix, param, PREFIX_MAX - 1);
947 lprefix[PREFIX_MAX - 1] = 0;
948 break;
950 if (s == OPT_POSTFIX) {
951 strncpy(lpostfix, param, POSTFIX_MAX - 1);
952 lpostfix[POSTFIX_MAX - 1] = 0;
953 break;
955 break;
957 default:
959 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
960 "unrecognised option `--%s'", p + 2);
961 break;
964 break;
967 default:
968 if (!ofmt->setinfo(GI_SWITCH, &p))
969 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
970 "unrecognised option `-%c'", p[1]);
971 break;
973 } else {
974 if (*inname) {
975 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
976 "more than one input file specified");
977 } else {
978 copy_filename(inname, p);
982 return advance;
985 #define ARG_BUF_DELTA 128
987 static void process_respfile(FILE * rfile)
989 char *buffer, *p, *q, *prevarg;
990 int bufsize, prevargsize;
992 bufsize = prevargsize = ARG_BUF_DELTA;
993 buffer = nasm_malloc(ARG_BUF_DELTA);
994 prevarg = nasm_malloc(ARG_BUF_DELTA);
995 prevarg[0] = '\0';
997 while (1) { /* Loop to handle all lines in file */
998 p = buffer;
999 while (1) { /* Loop to handle long lines */
1000 q = fgets(p, bufsize - (p - buffer), rfile);
1001 if (!q)
1002 break;
1003 p += strlen(p);
1004 if (p > buffer && p[-1] == '\n')
1005 break;
1006 if (p - buffer > bufsize - 10) {
1007 int offset;
1008 offset = p - buffer;
1009 bufsize += ARG_BUF_DELTA;
1010 buffer = nasm_realloc(buffer, bufsize);
1011 p = buffer + offset;
1015 if (!q && p == buffer) {
1016 if (prevarg[0])
1017 process_arg(prevarg, NULL);
1018 nasm_free(buffer);
1019 nasm_free(prevarg);
1020 return;
1024 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1025 * them are present at the end of the line.
1027 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1029 while (p > buffer && nasm_isspace(p[-1]))
1030 *--p = '\0';
1032 p = nasm_skip_spaces(buffer);
1034 if (process_arg(prevarg, p))
1035 *p = '\0';
1037 if ((int) strlen(p) > prevargsize - 10) {
1038 prevargsize += ARG_BUF_DELTA;
1039 prevarg = nasm_realloc(prevarg, prevargsize);
1041 strncpy(prevarg, p, prevargsize);
1045 /* Function to process args from a string of args, rather than the
1046 * argv array. Used by the environment variable and response file
1047 * processing.
1049 static void process_args(char *args)
1051 char *p, *q, *arg, *prevarg;
1052 char separator = ' ';
1054 p = args;
1055 if (*p && *p != '-')
1056 separator = *p++;
1057 arg = NULL;
1058 while (*p) {
1059 q = p;
1060 while (*p && *p != separator)
1061 p++;
1062 while (*p == separator)
1063 *p++ = '\0';
1064 prevarg = arg;
1065 arg = q;
1066 if (process_arg(prevarg, arg))
1067 arg = NULL;
1069 if (arg)
1070 process_arg(arg, NULL);
1073 static void process_response_file(const char *file)
1075 char str[2048];
1076 FILE *f = fopen(file, "r");
1077 if (!f) {
1078 perror(file);
1079 exit(-1);
1081 while (fgets(str, sizeof str, f)) {
1082 process_args(str);
1084 fclose(f);
1087 static void parse_cmdline(int argc, char **argv)
1089 FILE *rfile;
1090 char *envreal, *envcopy = NULL, *p;
1091 int i;
1093 *inname = *outname = *listname = *errname = '\0';
1095 for (i = 0; i <= ERR_WARN_MAX; i++)
1096 warning_on_global[i] = warnings[i].enabled;
1099 * First, process the NASMENV environment variable.
1101 envreal = getenv("NASMENV");
1102 if (envreal) {
1103 envcopy = nasm_strdup(envreal);
1104 process_args(envcopy);
1105 nasm_free(envcopy);
1109 * Now process the actual command line.
1111 while (--argc) {
1112 bool advance;
1113 argv++;
1114 if (argv[0][0] == '@') {
1116 * We have a response file, so process this as a set of
1117 * arguments like the environment variable. This allows us
1118 * to have multiple arguments on a single line, which is
1119 * different to the -@resp file processing below for regular
1120 * NASM.
1122 process_response_file(argv[0]+1);
1123 argc--;
1124 argv++;
1126 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1127 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1128 if (p) {
1129 rfile = fopen(p, "r");
1130 if (rfile) {
1131 process_respfile(rfile);
1132 fclose(rfile);
1133 } else
1134 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1135 "unable to open response file `%s'", p);
1137 } else
1138 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1139 argv += advance, argc -= advance;
1143 * Look for basic command line typos. This definitely doesn't
1144 * catch all errors, but it might help cases of fumbled fingers.
1146 if (!*inname)
1147 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1148 "no input file specified");
1149 else if (!strcmp(inname, errname) ||
1150 !strcmp(inname, outname) ||
1151 !strcmp(inname, listname) ||
1152 (depend_file && !strcmp(inname, depend_file)))
1153 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1154 "file `%s' is both input and output file",
1155 inname);
1157 if (*errname) {
1158 error_file = fopen(errname, "w");
1159 if (!error_file) {
1160 error_file = stderr; /* Revert to default! */
1161 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1162 "cannot open file `%s' for error messages",
1163 errname);
1168 static enum directives getkw(char **directive, char **value);
1170 static void assemble_file(char *fname, StrList **depend_ptr)
1172 char *directive, *value, *p, *q, *special, *line;
1173 insn output_ins;
1174 int i, validid;
1175 bool rn_error;
1176 int32_t seg;
1177 int64_t offs;
1178 struct tokenval tokval;
1179 expr *e;
1180 int pass_max;
1182 if (cmd_sb == 32 && cmd_cpu < IF_386)
1183 nasm_error(ERR_FATAL, "command line: "
1184 "32-bit segment size requires a higher cpu");
1186 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1187 for (passn = 1; pass0 <= 2; passn++) {
1188 int pass1, pass2;
1189 ldfunc def_label;
1191 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1192 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1193 /* pass0 0, 0, 0, ..., 1, 2 */
1195 def_label = passn > 1 ? redefine_label : define_label;
1197 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1198 cpu = cmd_cpu;
1199 if (pass0 == 2) {
1200 if (*listname)
1201 nasmlist.init(listname, nasm_error);
1203 in_abs_seg = false;
1204 global_offset_changed = 0; /* set by redefine_label */
1205 location.segment = ofmt->section(NULL, pass2, &sb);
1206 globalbits = sb;
1207 if (passn > 1) {
1208 saa_rewind(forwrefs);
1209 forwref = saa_rstruct(forwrefs);
1210 raa_free(offsets);
1211 offsets = raa_init();
1213 preproc->reset(fname, pass1, &nasmlist,
1214 pass1 == 2 ? depend_ptr : NULL);
1215 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1217 globallineno = 0;
1218 if (passn == 1)
1219 location.known = true;
1220 location.offset = offs = GET_CURR_OFFS;
1222 while ((line = preproc->getline())) {
1223 enum directives d;
1224 globallineno++;
1227 * Here we parse our directives; this is not handled by the
1228 * 'real' parser. This really should be a separate function.
1230 directive = line;
1231 d = getkw(&directive, &value);
1232 if (d) {
1233 int err = 0;
1235 switch (d) {
1236 case D_SEGMENT: /* [SEGMENT n] */
1237 case D_SECTION:
1238 seg = ofmt->section(value, pass2, &sb);
1239 if (seg == NO_SEG) {
1240 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1241 "segment name `%s' not recognized",
1242 value);
1243 } else {
1244 in_abs_seg = false;
1245 location.segment = seg;
1247 break;
1248 case D_SECTALIGN: /* [SECTALIGN n] */
1249 if (*value) {
1250 stdscan_reset();
1251 stdscan_set(value);
1252 tokval.t_type = TOKEN_INVALID;
1253 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1254 if (e) {
1255 unsigned int align = (unsigned int)e->value;
1256 if ((uint64_t)e->value > 0x7fffffff) {
1258 * FIXME: Please make some sane message here
1259 * ofmt should have some 'check' method which
1260 * would report segment alignment bounds.
1262 nasm_error(ERR_FATAL,
1263 "incorrect segment alignment `%s'", value);
1264 } else if (!is_power2(align)) {
1265 nasm_error(ERR_NONFATAL,
1266 "segment alignment `%s' is not power of two",
1267 value);
1269 /* callee should be able to handle all details */
1270 ofmt->sectalign(location.segment, align);
1273 break;
1274 case D_EXTERN: /* [EXTERN label:special] */
1275 if (*value == '$')
1276 value++; /* skip initial $ if present */
1277 if (pass0 == 2) {
1278 q = value;
1279 while (*q && *q != ':')
1280 q++;
1281 if (*q == ':') {
1282 *q++ = '\0';
1283 ofmt->symdef(value, 0L, 0L, 3, q);
1285 } else if (passn == 1) {
1286 q = value;
1287 validid = true;
1288 if (!isidstart(*q))
1289 validid = false;
1290 while (*q && *q != ':') {
1291 if (!isidchar(*q))
1292 validid = false;
1293 q++;
1295 if (!validid) {
1296 nasm_error(ERR_NONFATAL,
1297 "identifier expected after EXTERN");
1298 break;
1300 if (*q == ':') {
1301 *q++ = '\0';
1302 special = q;
1303 } else
1304 special = NULL;
1305 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1306 int temp = pass0;
1307 pass0 = 1; /* fake pass 1 in labels.c */
1308 declare_as_global(value, special);
1309 define_label(value, seg_alloc(), 0L, NULL,
1310 false, true);
1311 pass0 = temp;
1313 } /* else pass0 == 1 */
1314 break;
1315 case D_BITS: /* [BITS bits] */
1316 globalbits = sb = get_bits(value);
1317 break;
1318 case D_GLOBAL: /* [GLOBAL symbol:special] */
1319 if (*value == '$')
1320 value++; /* skip initial $ if present */
1321 if (pass0 == 2) { /* pass 2 */
1322 q = value;
1323 while (*q && *q != ':')
1324 q++;
1325 if (*q == ':') {
1326 *q++ = '\0';
1327 ofmt->symdef(value, 0L, 0L, 3, q);
1329 } else if (pass2 == 1) { /* pass == 1 */
1330 q = value;
1331 validid = true;
1332 if (!isidstart(*q))
1333 validid = false;
1334 while (*q && *q != ':') {
1335 if (!isidchar(*q))
1336 validid = false;
1337 q++;
1339 if (!validid) {
1340 nasm_error(ERR_NONFATAL,
1341 "identifier expected after GLOBAL");
1342 break;
1344 if (*q == ':') {
1345 *q++ = '\0';
1346 special = q;
1347 } else
1348 special = NULL;
1349 declare_as_global(value, special);
1350 } /* pass == 1 */
1351 break;
1352 case D_COMMON: /* [COMMON symbol size:special] */
1354 int64_t size;
1356 if (*value == '$')
1357 value++; /* skip initial $ if present */
1358 p = value;
1359 validid = true;
1360 if (!isidstart(*p))
1361 validid = false;
1362 while (*p && !nasm_isspace(*p)) {
1363 if (!isidchar(*p))
1364 validid = false;
1365 p++;
1367 if (!validid) {
1368 nasm_error(ERR_NONFATAL,
1369 "identifier expected after COMMON");
1370 break;
1372 if (*p) {
1373 p = nasm_zap_spaces_fwd(p);
1374 q = p;
1375 while (*q && *q != ':')
1376 q++;
1377 if (*q == ':') {
1378 *q++ = '\0';
1379 special = q;
1380 } else {
1381 special = NULL;
1383 size = readnum(p, &rn_error);
1384 if (rn_error) {
1385 nasm_error(ERR_NONFATAL,
1386 "invalid size specified"
1387 " in COMMON declaration");
1388 break;
1390 } else {
1391 nasm_error(ERR_NONFATAL,
1392 "no size specified in"
1393 " COMMON declaration");
1394 break;
1397 if (pass0 < 2) {
1398 define_common(value, seg_alloc(), size, special);
1399 } else if (pass0 == 2) {
1400 if (special)
1401 ofmt->symdef(value, 0L, 0L, 3, special);
1403 break;
1405 case D_ABSOLUTE: /* [ABSOLUTE address] */
1406 stdscan_reset();
1407 stdscan_set(value);
1408 tokval.t_type = TOKEN_INVALID;
1409 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1410 nasm_error, NULL);
1411 if (e) {
1412 if (!is_reloc(e))
1413 nasm_error(pass0 ==
1414 1 ? ERR_NONFATAL : ERR_PANIC,
1415 "cannot use non-relocatable expression as "
1416 "ABSOLUTE address");
1417 else {
1418 abs_seg = reloc_seg(e);
1419 abs_offset = reloc_value(e);
1421 } else if (passn == 1)
1422 abs_offset = 0x100; /* don't go near zero in case of / */
1423 else
1424 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1425 "in pass two");
1426 in_abs_seg = true;
1427 location.segment = NO_SEG;
1428 break;
1429 case D_DEBUG: /* [DEBUG] */
1431 char debugid[128];
1432 bool badid, overlong;
1434 p = value;
1435 q = debugid;
1436 badid = overlong = false;
1437 if (!isidstart(*p)) {
1438 badid = true;
1439 } else {
1440 while (*p && !nasm_isspace(*p)) {
1441 if (q >= debugid + sizeof debugid - 1) {
1442 overlong = true;
1443 break;
1445 if (!isidchar(*p))
1446 badid = true;
1447 *q++ = *p++;
1449 *q = 0;
1451 if (badid) {
1452 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1453 "identifier expected after DEBUG");
1454 break;
1456 if (overlong) {
1457 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1458 "DEBUG identifier too long");
1459 break;
1461 p = nasm_skip_spaces(p);
1462 if (pass0 == 2)
1463 dfmt->debug_directive(debugid, p);
1464 break;
1466 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1467 value = nasm_skip_spaces(value);
1468 switch(*value) {
1469 case '-': validid = 0; value++; break;
1470 case '+': validid = 1; value++; break;
1471 case '*': validid = 2; value++; break;
1472 default: validid = 1; break;
1475 for (i = 1; i <= ERR_WARN_MAX; i++)
1476 if (!nasm_stricmp(value, warnings[i].name))
1477 break;
1478 if (i <= ERR_WARN_MAX) {
1479 switch(validid) {
1480 case 0:
1481 warning_on[i] = false;
1482 break;
1483 case 1:
1484 warning_on[i] = true;
1485 break;
1486 case 2:
1487 warning_on[i] = warning_on_global[i];
1488 break;
1491 else
1492 nasm_error(ERR_NONFATAL,
1493 "invalid warning id in WARNING directive");
1494 break;
1495 case D_CPU: /* [CPU] */
1496 cpu = get_cpu(value);
1497 break;
1498 case D_LIST: /* [LIST {+|-}] */
1499 value = nasm_skip_spaces(value);
1500 if (*value == '+') {
1501 user_nolist = 0;
1502 } else {
1503 if (*value == '-') {
1504 user_nolist = 1;
1505 } else {
1506 err = 1;
1509 break;
1510 case D_DEFAULT: /* [DEFAULT] */
1511 stdscan_reset();
1512 stdscan_set(value);
1513 tokval.t_type = TOKEN_INVALID;
1514 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1515 switch ((int)tokval.t_integer) {
1516 case S_REL:
1517 globalrel = 1;
1518 break;
1519 case S_ABS:
1520 globalrel = 0;
1521 break;
1522 default:
1523 err = 1;
1524 break;
1526 } else {
1527 err = 1;
1529 break;
1530 case D_FLOAT:
1531 if (float_option(value)) {
1532 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1533 "unknown 'float' directive: %s",
1534 value);
1536 break;
1537 default:
1538 if (ofmt->directive(d, value, pass2))
1539 break;
1540 /* else fall through */
1541 case D_unknown:
1542 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1543 "unrecognised directive [%s]",
1544 directive);
1545 break;
1547 if (err) {
1548 nasm_error(ERR_NONFATAL,
1549 "invalid parameter to [%s] directive",
1550 directive);
1552 } else { /* it isn't a directive */
1553 parse_line(pass1, line, &output_ins, def_label);
1555 if (optimizing > 0) {
1556 if (forwref != NULL && globallineno == forwref->lineno) {
1557 output_ins.forw_ref = true;
1558 do {
1559 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1560 forwref = saa_rstruct(forwrefs);
1561 } while (forwref != NULL
1562 && forwref->lineno == globallineno);
1563 } else
1564 output_ins.forw_ref = false;
1566 if (output_ins.forw_ref) {
1567 if (passn == 1) {
1568 for (i = 0; i < output_ins.operands; i++) {
1569 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1570 struct forwrefinfo *fwinf =
1571 (struct forwrefinfo *)
1572 saa_wstruct(forwrefs);
1573 fwinf->lineno = globallineno;
1574 fwinf->operand = i;
1581 /* forw_ref */
1582 if (output_ins.opcode == I_EQU) {
1583 if (pass1 == 1) {
1585 * Special `..' EQUs get processed in pass two,
1586 * except `..@' macro-processor EQUs which are done
1587 * in the normal place.
1589 if (!output_ins.label)
1590 nasm_error(ERR_NONFATAL,
1591 "EQU not preceded by label");
1593 else if (output_ins.label[0] != '.' ||
1594 output_ins.label[1] != '.' ||
1595 output_ins.label[2] == '@') {
1596 if (output_ins.operands == 1 &&
1597 (output_ins.oprs[0].type & IMMEDIATE) &&
1598 output_ins.oprs[0].wrt == NO_SEG) {
1599 bool isext = !!(output_ins.oprs[0].opflags
1600 & OPFLAG_EXTERN);
1601 def_label(output_ins.label,
1602 output_ins.oprs[0].segment,
1603 output_ins.oprs[0].offset, NULL,
1604 false, isext);
1605 } else if (output_ins.operands == 2
1606 && (output_ins.oprs[0].type & IMMEDIATE)
1607 && (output_ins.oprs[0].type & COLON)
1608 && output_ins.oprs[0].segment == NO_SEG
1609 && output_ins.oprs[0].wrt == NO_SEG
1610 && (output_ins.oprs[1].type & IMMEDIATE)
1611 && output_ins.oprs[1].segment == NO_SEG
1612 && output_ins.oprs[1].wrt == NO_SEG) {
1613 def_label(output_ins.label,
1614 output_ins.oprs[0].offset | SEG_ABS,
1615 output_ins.oprs[1].offset,
1616 NULL, false, false);
1617 } else
1618 nasm_error(ERR_NONFATAL,
1619 "bad syntax for EQU");
1621 } else {
1623 * Special `..' EQUs get processed here, except
1624 * `..@' macro processor EQUs which are done above.
1626 if (output_ins.label[0] == '.' &&
1627 output_ins.label[1] == '.' &&
1628 output_ins.label[2] != '@') {
1629 if (output_ins.operands == 1 &&
1630 (output_ins.oprs[0].type & IMMEDIATE)) {
1631 define_label(output_ins.label,
1632 output_ins.oprs[0].segment,
1633 output_ins.oprs[0].offset,
1634 NULL, false, false);
1635 } else if (output_ins.operands == 2
1636 && (output_ins.oprs[0].type & IMMEDIATE)
1637 && (output_ins.oprs[0].type & COLON)
1638 && output_ins.oprs[0].segment == NO_SEG
1639 && (output_ins.oprs[1].type & IMMEDIATE)
1640 && output_ins.oprs[1].segment == NO_SEG) {
1641 define_label(output_ins.label,
1642 output_ins.oprs[0].offset | SEG_ABS,
1643 output_ins.oprs[1].offset,
1644 NULL, false, false);
1645 } else
1646 nasm_error(ERR_NONFATAL,
1647 "bad syntax for EQU");
1650 } else { /* instruction isn't an EQU */
1652 if (pass1 == 1) {
1654 int64_t l = insn_size(location.segment, offs, sb, cpu,
1655 &output_ins, nasm_error);
1657 /* if (using_debug_info) && output_ins.opcode != -1) */
1658 if (using_debug_info)
1659 { /* fbk 03/25/01 */
1660 /* this is done here so we can do debug type info */
1661 int32_t typeinfo =
1662 TYS_ELEMENTS(output_ins.operands);
1663 switch (output_ins.opcode) {
1664 case I_RESB:
1665 typeinfo =
1666 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1667 break;
1668 case I_RESW:
1669 typeinfo =
1670 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1671 break;
1672 case I_RESD:
1673 typeinfo =
1674 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1675 break;
1676 case I_RESQ:
1677 typeinfo =
1678 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1679 break;
1680 case I_REST:
1681 typeinfo =
1682 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1683 break;
1684 case I_RESO:
1685 typeinfo =
1686 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1687 break;
1688 case I_RESY:
1689 typeinfo =
1690 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1691 break;
1692 case I_DB:
1693 typeinfo |= TY_BYTE;
1694 break;
1695 case I_DW:
1696 typeinfo |= TY_WORD;
1697 break;
1698 case I_DD:
1699 if (output_ins.eops_float)
1700 typeinfo |= TY_FLOAT;
1701 else
1702 typeinfo |= TY_DWORD;
1703 break;
1704 case I_DQ:
1705 typeinfo |= TY_QWORD;
1706 break;
1707 case I_DT:
1708 typeinfo |= TY_TBYTE;
1709 break;
1710 case I_DO:
1711 typeinfo |= TY_OWORD;
1712 break;
1713 case I_DY:
1714 typeinfo |= TY_YWORD;
1715 break;
1716 default:
1717 typeinfo = TY_LABEL;
1721 dfmt->debug_typevalue(typeinfo);
1723 if (l != -1) {
1724 offs += l;
1725 SET_CURR_OFFS(offs);
1728 * else l == -1 => invalid instruction, which will be
1729 * flagged as an error on pass 2
1732 } else {
1733 offs += assemble(location.segment, offs, sb, cpu,
1734 &output_ins, ofmt, nasm_error,
1735 &nasmlist);
1736 SET_CURR_OFFS(offs);
1739 } /* not an EQU */
1740 cleanup_insn(&output_ins);
1742 nasm_free(line);
1743 location.offset = offs = GET_CURR_OFFS;
1744 } /* end while (line = preproc->getline... */
1746 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1747 nasm_error(ERR_NONFATAL,
1748 "phase error detected at end of assembly.");
1750 if (pass1 == 1)
1751 preproc->cleanup(1);
1753 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1754 pass0++;
1755 } else if (global_offset_changed &&
1756 global_offset_changed < prev_offset_changed) {
1757 prev_offset_changed = global_offset_changed;
1758 stall_count = 0;
1759 } else {
1760 stall_count++;
1763 if (terminate_after_phase)
1764 break;
1766 if ((stall_count > 997) || (passn >= pass_max)) {
1767 /* We get here if the labels don't converge
1768 * Example: FOO equ FOO + 1
1770 nasm_error(ERR_NONFATAL,
1771 "Can't find valid values for all labels "
1772 "after %d passes, giving up.", passn);
1773 nasm_error(ERR_NONFATAL,
1774 "Possible causes: recursive EQUs, macro abuse.");
1775 break;
1779 preproc->cleanup(0);
1780 nasmlist.cleanup();
1781 if (!terminate_after_phase && opt_verbose_info) {
1782 /* -On and -Ov switches */
1783 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1787 static enum directives getkw(char **directive, char **value)
1789 char *p, *q, *buf;
1791 buf = nasm_skip_spaces(*directive);
1793 /* it should be enclosed in [ ] */
1794 if (*buf != '[')
1795 return D_none;
1796 q = strchr(buf, ']');
1797 if (!q)
1798 return D_none;
1800 /* stip off the comments */
1801 p = strchr(buf, ';');
1802 if (p) {
1803 if (p < q) /* ouch! somwhere inside */
1804 return D_none;
1805 *p = '\0';
1808 /* no brace, no trailing spaces */
1809 *q = '\0';
1810 nasm_zap_spaces_rev(--q);
1812 /* directive */
1813 p = nasm_skip_spaces(++buf);
1814 q = nasm_skip_word(p);
1815 if (!q)
1816 return D_none; /* sigh... no value there */
1817 *q = '\0';
1818 *directive = p;
1820 /* and value finally */
1821 p = nasm_skip_spaces(++q);
1822 *value = p;
1824 return find_directive(*directive);
1828 * gnu style error reporting
1829 * This function prints an error message to error_file in the
1830 * style used by GNU. An example would be:
1831 * file.asm:50: error: blah blah blah
1832 * where file.asm is the name of the file, 50 is the line number on
1833 * which the error occurs (or is detected) and "error:" is one of
1834 * the possible optional diagnostics -- it can be "error" or "warning"
1835 * or something else. Finally the line terminates with the actual
1836 * error message.
1838 * @param severity the severity of the warning or error
1839 * @param fmt the printf style format string
1841 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1843 char *currentfile = NULL;
1844 int32_t lineno = 0;
1846 if (is_suppressed_warning(severity))
1847 return;
1849 if (!(severity & ERR_NOFILE))
1850 src_get(&lineno, &currentfile);
1852 if (currentfile) {
1853 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1854 nasm_free(currentfile);
1855 } else {
1856 fputs("nasm: ", error_file);
1859 nasm_verror_common(severity, fmt, ap);
1863 * MS style error reporting
1864 * This function prints an error message to error_file in the
1865 * style used by Visual C and some other Microsoft tools. An example
1866 * would be:
1867 * file.asm(50) : error: blah blah blah
1868 * where file.asm is the name of the file, 50 is the line number on
1869 * which the error occurs (or is detected) and "error:" is one of
1870 * the possible optional diagnostics -- it can be "error" or "warning"
1871 * or something else. Finally the line terminates with the actual
1872 * error message.
1874 * @param severity the severity of the warning or error
1875 * @param fmt the printf style format string
1877 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1879 char *currentfile = NULL;
1880 int32_t lineno = 0;
1882 if (is_suppressed_warning(severity))
1883 return;
1885 if (!(severity & ERR_NOFILE))
1886 src_get(&lineno, &currentfile);
1888 if (currentfile) {
1889 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1890 nasm_free(currentfile);
1891 } else {
1892 fputs("nasm: ", error_file);
1895 nasm_verror_common(severity, fmt, ap);
1899 * check for supressed warning
1900 * checks for suppressed warning or pass one only warning and we're
1901 * not in pass 1
1903 * @param severity the severity of the warning or error
1904 * @return true if we should abort error/warning printing
1906 static bool is_suppressed_warning(int severity)
1908 /* Not a warning at all */
1909 if ((severity & ERR_MASK) != ERR_WARNING)
1910 return false;
1912 /* See if it's a pass-one only warning and we're not in pass one. */
1913 if (((severity & ERR_PASS1) && pass0 != 1) ||
1914 ((severity & ERR_PASS2) && pass0 != 2))
1915 return true;
1917 /* Might be a warning but suppresed explicitly */
1918 if (severity & ERR_WARN_MASK)
1919 return !warning_on[WARN_IDX(severity)];
1920 else
1921 return false;
1925 * common error reporting
1926 * This is the common back end of the error reporting schemes currently
1927 * implemented. It prints the nature of the warning and then the
1928 * specific error message to error_file and may or may not return. It
1929 * doesn't return if the error severity is a "panic" or "debug" type.
1931 * @param severity the severity of the warning or error
1932 * @param fmt the printf style format string
1934 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1936 char msg[1024];
1937 const char *pfx;
1939 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1940 case ERR_WARNING:
1941 pfx = "warning: ";
1942 break;
1943 case ERR_NONFATAL:
1944 pfx = "error: ";
1945 break;
1946 case ERR_FATAL:
1947 pfx = "fatal: ";
1948 break;
1949 case ERR_PANIC:
1950 pfx = "panic: ";
1951 break;
1952 case ERR_DEBUG:
1953 pfx = "debug: ";
1954 break;
1955 default:
1956 pfx = "";
1957 break;
1960 vsnprintf(msg, sizeof msg, fmt, args);
1962 fprintf(error_file, "%s%s\n", pfx, msg);
1964 if (*listname)
1965 nasmlist.error(severity, pfx, msg);
1967 if (severity & ERR_USAGE)
1968 want_usage = true;
1970 switch (severity & ERR_MASK) {
1971 case ERR_DEBUG:
1972 /* no further action, by definition */
1973 break;
1974 case ERR_WARNING:
1975 /* Treat warnings as errors */
1976 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1977 terminate_after_phase = true;
1978 break;
1979 case ERR_NONFATAL:
1980 terminate_after_phase = true;
1981 break;
1982 case ERR_FATAL:
1983 if (ofile) {
1984 fclose(ofile);
1985 remove(outname);
1986 ofile = NULL;
1988 if (want_usage)
1989 usage();
1990 exit(1); /* instantly die */
1991 break; /* placate silly compilers */
1992 case ERR_PANIC:
1993 fflush(NULL);
1994 /* abort(); *//* halt, catch fire, and dump core */
1995 exit(3);
1996 break;
2000 static void usage(void)
2002 fputs("type `nasm -h' for help\n", error_file);
2005 static uint32_t get_cpu(char *value)
2007 if (!strcmp(value, "8086"))
2008 return IF_8086;
2009 if (!strcmp(value, "186"))
2010 return IF_186;
2011 if (!strcmp(value, "286"))
2012 return IF_286;
2013 if (!strcmp(value, "386"))
2014 return IF_386;
2015 if (!strcmp(value, "486"))
2016 return IF_486;
2017 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2018 return IF_PENT;
2019 if (!strcmp(value, "686") ||
2020 !nasm_stricmp(value, "ppro") ||
2021 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2022 return IF_P6;
2023 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2024 return IF_KATMAI;
2025 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2026 !nasm_stricmp(value, "willamette"))
2027 return IF_WILLAMETTE;
2028 if (!nasm_stricmp(value, "prescott"))
2029 return IF_PRESCOTT;
2030 if (!nasm_stricmp(value, "x64") ||
2031 !nasm_stricmp(value, "x86-64"))
2032 return IF_X86_64;
2033 if (!nasm_stricmp(value, "ia64") ||
2034 !nasm_stricmp(value, "ia-64") ||
2035 !nasm_stricmp(value, "itanium") ||
2036 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2037 return IF_IA64;
2039 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2040 "unknown 'cpu' type");
2042 return IF_PLEVEL; /* the maximum level */
2045 static int get_bits(char *value)
2047 int i;
2049 if ((i = atoi(value)) == 16)
2050 return i; /* set for a 16-bit segment */
2051 else if (i == 32) {
2052 if (cpu < IF_386) {
2053 nasm_error(ERR_NONFATAL,
2054 "cannot specify 32-bit segment on processor below a 386");
2055 i = 16;
2057 } else if (i == 64) {
2058 if (cpu < IF_X86_64) {
2059 nasm_error(ERR_NONFATAL,
2060 "cannot specify 64-bit segment on processor below an x86-64");
2061 i = 16;
2063 if (i != maxbits) {
2064 nasm_error(ERR_NONFATAL,
2065 "%s output format does not support 64-bit code",
2066 ofmt->shortname);
2067 i = 16;
2069 } else {
2070 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2071 "`%s' is not a valid segment size; must be 16, 32 or 64",
2072 value);
2073 i = 16;
2075 return i;