Remove unnecessary calls to memset
[nasm.git] / nasm.c
blob4896d70ca3548de249637a37fbf7efc00517770d
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},
168 static bool want_usage;
169 static bool terminate_after_phase;
170 int user_nolist = 0; /* fbk 9/2/00 */
172 static char *quote_for_make(const char *str);
174 static int64_t get_curr_offs(void)
176 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
179 static void set_curr_offs(int64_t l_off)
181 if (in_abs_seg)
182 abs_offset = l_off;
183 else
184 offsets = raa_write(offsets, location.segment, l_off);
187 static void nasm_fputs(const char *line, FILE * outfile)
189 if (outfile) {
190 fputs(line, outfile);
191 putc('\n', outfile);
192 } else
193 puts(line);
196 /* Convert a struct tm to a POSIX-style time constant */
197 static int64_t posix_mktime(struct tm *tm)
199 int64_t t;
200 int64_t y = tm->tm_year;
202 /* See IEEE 1003.1:2004, section 4.14 */
204 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
205 t += tm->tm_yday;
206 t *= 24;
207 t += tm->tm_hour;
208 t *= 60;
209 t += tm->tm_min;
210 t *= 60;
211 t += tm->tm_sec;
213 return t;
216 static void define_macros_early(void)
218 char temp[128];
219 struct tm lt, *lt_p, gm, *gm_p;
220 int64_t posix_time;
222 lt_p = localtime(&official_compile_time);
223 if (lt_p) {
224 lt = *lt_p;
226 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
227 preproc->pre_define(temp);
228 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
229 preproc->pre_define(temp);
230 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
231 preproc->pre_define(temp);
232 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
233 preproc->pre_define(temp);
236 gm_p = gmtime(&official_compile_time);
237 if (gm_p) {
238 gm = *gm_p;
240 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
241 preproc->pre_define(temp);
242 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
243 preproc->pre_define(temp);
244 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
245 preproc->pre_define(temp);
246 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
247 preproc->pre_define(temp);
250 if (gm_p)
251 posix_time = posix_mktime(&gm);
252 else if (lt_p)
253 posix_time = posix_mktime(&lt);
254 else
255 posix_time = 0;
257 if (posix_time) {
258 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
259 preproc->pre_define(temp);
263 static void define_macros_late(void)
265 char temp[128];
268 * In case if output format is defined by alias
269 * we have to put shortname of the alias itself here
270 * otherwise ABI backward compatibility gets broken.
272 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
273 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
274 preproc->pre_define(temp);
277 static void emit_dependencies(StrList *list)
279 FILE *deps;
280 int linepos, len;
281 StrList *l, *nl;
283 if (depend_file && strcmp(depend_file, "-")) {
284 deps = fopen(depend_file, "w");
285 if (!deps) {
286 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
287 "unable to write dependency file `%s'", depend_file);
288 return;
290 } else {
291 deps = stdout;
294 linepos = fprintf(deps, "%s:", depend_target);
295 list_for_each(l, list) {
296 char *file = quote_for_make(l->str);
297 len = strlen(file);
298 if (linepos + len > 62 && linepos > 1) {
299 fprintf(deps, " \\\n ");
300 linepos = 1;
302 fprintf(deps, " %s", file);
303 linepos += len+1;
304 nasm_free(file);
306 fprintf(deps, "\n\n");
308 list_for_each_safe(l, nl, list) {
309 if (depend_emit_phony)
310 fprintf(deps, "%s:\n\n", l->str);
311 nasm_free(l);
314 if (deps != stdout)
315 fclose(deps);
318 int main(int argc, char **argv)
320 StrList *depend_list = NULL, **depend_ptr;
322 time(&official_compile_time);
324 pass0 = 0;
325 want_usage = terminate_after_phase = false;
326 nasm_set_verror(nasm_verror_gnu);
328 error_file = stderr;
330 tolower_init();
332 nasm_init_malloc_error();
333 offsets = raa_init();
334 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
336 preproc = &nasmpp;
337 operating_mode = op_normal;
339 seg_init();
341 /* Define some macros dependent on the runtime, but not
342 on the command line. */
343 define_macros_early();
345 parse_cmdline(argc, argv);
347 if (terminate_after_phase) {
348 if (want_usage)
349 usage();
350 return 1;
353 /* If debugging info is disabled, suppress any debug calls */
354 if (!using_debug_info)
355 ofmt->current_dfmt = &null_debug_form;
357 if (ofmt->stdmac)
358 preproc->extra_stdmac(ofmt->stdmac);
359 parser_global_info(&location);
360 eval_global_info(ofmt, lookup_label, &location);
362 /* define some macros dependent of command-line */
363 define_macros_late();
365 depend_ptr = (depend_file || (operating_mode == op_depend)) ? &depend_list : NULL;
366 if (!depend_target)
367 depend_target = quote_for_make(outname);
369 switch (operating_mode) {
370 case op_depend:
372 char *line;
374 if (depend_missing_ok)
375 preproc->include_path(NULL); /* "assume generated" */
377 preproc->reset(inname, 0, &nasmlist, depend_ptr);
378 if (outname[0] == '\0')
379 ofmt->filename(inname, outname);
380 ofile = NULL;
381 while ((line = preproc->getline()))
382 nasm_free(line);
383 preproc->cleanup(0);
385 break;
387 case op_preprocess:
389 char *line;
390 char *file_name = NULL;
391 int32_t prior_linnum = 0;
392 int lineinc = 0;
394 if (*outname) {
395 ofile = fopen(outname, "w");
396 if (!ofile)
397 nasm_error(ERR_FATAL | ERR_NOFILE,
398 "unable to open output file `%s'",
399 outname);
400 } else
401 ofile = NULL;
403 location.known = false;
405 /* pass = 1; */
406 preproc->reset(inname, 3, &nasmlist, depend_ptr);
407 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
409 while ((line = preproc->getline())) {
411 * We generate %line directives if needed for later programs
413 int32_t linnum = prior_linnum += lineinc;
414 int altline = src_get(&linnum, &file_name);
415 if (altline) {
416 if (altline == 1 && lineinc == 1)
417 nasm_fputs("", ofile);
418 else {
419 lineinc = (altline != -1 || lineinc != 1);
420 fprintf(ofile ? ofile : stdout,
421 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
422 file_name);
424 prior_linnum = linnum;
426 nasm_fputs(line, ofile);
427 nasm_free(line);
429 nasm_free(file_name);
430 preproc->cleanup(0);
431 if (ofile)
432 fclose(ofile);
433 if (ofile && terminate_after_phase)
434 remove(outname);
435 ofile = NULL;
437 break;
439 case op_normal:
442 * We must call ofmt->filename _anyway_, even if the user
443 * has specified their own output file, because some
444 * formats (eg OBJ and COFF) use ofmt->filename to find out
445 * the name of the input file and then put that inside the
446 * file.
448 ofmt->filename(inname, outname);
450 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
451 if (!ofile) {
452 nasm_error(ERR_FATAL | ERR_NOFILE,
453 "unable to open output file `%s'", outname);
457 * We must call init_labels() before ofmt->init() since
458 * some object formats will want to define labels in their
459 * init routines. (eg OS/2 defines the FLAT group)
461 init_labels();
463 ofmt->init();
464 dfmt = ofmt->current_dfmt;
465 dfmt->init();
467 assemble_file(inname, depend_ptr);
469 if (!terminate_after_phase) {
470 ofmt->cleanup(using_debug_info);
471 cleanup_labels();
472 fflush(ofile);
473 if (ferror(ofile)) {
474 nasm_error(ERR_NONFATAL|ERR_NOFILE,
475 "write error on output file `%s'", outname);
479 if (ofile) {
480 fclose(ofile);
481 if (terminate_after_phase)
482 remove(outname);
483 ofile = NULL;
486 break;
489 if (depend_list && !terminate_after_phase)
490 emit_dependencies(depend_list);
492 if (want_usage)
493 usage();
495 raa_free(offsets);
496 saa_free(forwrefs);
497 eval_cleanup();
498 stdscan_cleanup();
500 return terminate_after_phase;
504 * Get a parameter for a command line option.
505 * First arg must be in the form of e.g. -f...
507 static char *get_param(char *p, char *q, bool *advance)
509 *advance = false;
510 if (p[2]) /* the parameter's in the option */
511 return nasm_skip_spaces(p + 2);
512 if (q && q[0]) {
513 *advance = true;
514 return q;
516 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
517 "option `-%c' requires an argument", p[1]);
518 return NULL;
522 * Copy a filename
524 static void copy_filename(char *dst, const char *src)
526 size_t len = strlen(src);
528 if (len >= (size_t)FILENAME_MAX) {
529 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
530 return;
532 strncpy(dst, src, FILENAME_MAX);
536 * Convert a string to Make-safe form
538 static char *quote_for_make(const char *str)
540 const char *p;
541 char *os, *q;
543 size_t n = 1; /* Terminating zero */
544 size_t nbs = 0;
546 if (!str)
547 return NULL;
549 for (p = str; *p; p++) {
550 switch (*p) {
551 case ' ':
552 case '\t':
553 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
554 n += nbs + 2;
555 nbs = 0;
556 break;
557 case '$':
558 case '#':
559 nbs = 0;
560 n += 2;
561 break;
562 case '\\':
563 nbs++;
564 n++;
565 break;
566 default:
567 nbs = 0;
568 n++;
569 break;
573 /* Convert N backslashes at the end of filename to 2N backslashes */
574 if (nbs)
575 n += nbs;
577 os = q = nasm_malloc(n);
579 nbs = 0;
580 for (p = str; *p; p++) {
581 switch (*p) {
582 case ' ':
583 case '\t':
584 while (nbs--)
585 *q++ = '\\';
586 *q++ = '\\';
587 *q++ = *p;
588 break;
589 case '$':
590 *q++ = *p;
591 *q++ = *p;
592 nbs = 0;
593 break;
594 case '#':
595 *q++ = '\\';
596 *q++ = *p;
597 nbs = 0;
598 break;
599 case '\\':
600 *q++ = *p;
601 nbs++;
602 break;
603 default:
604 *q++ = *p;
605 nbs = 0;
606 break;
609 while (nbs--)
610 *q++ = '\\';
612 *q = '\0';
614 return os;
617 struct textargs {
618 const char *label;
619 int value;
622 #define OPT_PREFIX 0
623 #define OPT_POSTFIX 1
624 struct textargs textopts[] = {
625 {"prefix", OPT_PREFIX},
626 {"postfix", OPT_POSTFIX},
627 {NULL, 0}
630 static bool stopoptions = false;
631 static bool process_arg(char *p, char *q)
633 char *param;
634 int i;
635 bool advance = false;
636 bool do_warn;
638 if (!p || !p[0])
639 return false;
641 if (p[0] == '-' && !stopoptions) {
642 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
643 /* These parameters take values */
644 if (!(param = get_param(p, q, &advance)))
645 return advance;
648 switch (p[1]) {
649 case 's':
650 error_file = stdout;
651 break;
653 case 'o': /* output file */
654 copy_filename(outname, param);
655 break;
657 case 'f': /* output format */
658 ofmt = ofmt_find(param, &ofmt_alias);
659 if (!ofmt) {
660 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
661 "unrecognised output format `%s' - "
662 "use -hf for a list", param);
664 break;
666 case 'O': /* Optimization level */
668 int opt;
670 if (!*param) {
671 /* Naked -O == -Ox */
672 optimizing = MAX_OPTIMIZE;
673 } else {
674 while (*param) {
675 switch (*param) {
676 case '0': case '1': case '2': case '3': case '4':
677 case '5': case '6': case '7': case '8': case '9':
678 opt = strtoul(param, &param, 10);
680 /* -O0 -> optimizing == -1, 0.98 behaviour */
681 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
682 if (opt < 2)
683 optimizing = opt - 1;
684 else
685 optimizing = opt;
686 break;
688 case 'v':
689 case '+':
690 param++;
691 opt_verbose_info = true;
692 break;
694 case 'x':
695 param++;
696 optimizing = MAX_OPTIMIZE;
697 break;
699 default:
700 nasm_error(ERR_FATAL,
701 "unknown optimization option -O%c\n",
702 *param);
703 break;
706 if (optimizing > MAX_OPTIMIZE)
707 optimizing = MAX_OPTIMIZE;
709 break;
712 case 'p': /* pre-include */
713 case 'P':
714 preproc->pre_include(param);
715 break;
717 case 'd': /* pre-define */
718 case 'D':
719 preproc->pre_define(param);
720 break;
722 case 'u': /* un-define */
723 case 'U':
724 preproc->pre_undefine(param);
725 break;
727 case 'i': /* include search path */
728 case 'I':
729 preproc->include_path(param);
730 break;
732 case 'l': /* listing file */
733 copy_filename(listname, param);
734 break;
736 case 'Z': /* error messages file */
737 copy_filename(errname, param);
738 break;
740 case 'F': /* specify debug format */
741 ofmt->current_dfmt = dfmt_find(ofmt, param);
742 if (!ofmt->current_dfmt) {
743 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
744 "unrecognized debug format `%s' for"
745 " output format `%s'",
746 param, ofmt->shortname);
748 using_debug_info = true;
749 break;
751 case 'X': /* specify error reporting format */
752 if (nasm_stricmp("vc", param) == 0)
753 nasm_set_verror(nasm_verror_vc);
754 else if (nasm_stricmp("gnu", param) == 0)
755 nasm_set_verror(nasm_verror_gnu);
756 else
757 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
758 "unrecognized error reporting format `%s'",
759 param);
760 break;
762 case 'g':
763 using_debug_info = true;
764 break;
766 case 'h':
767 printf
768 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
769 "[-l listfile]\n"
770 " [options...] [--] filename\n"
771 " or nasm -v for version info\n\n"
772 " -t assemble in SciTech TASM compatible mode\n"
773 " -g generate debug information in selected format\n");
774 printf
775 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
776 " -a don't preprocess (assemble only)\n"
777 " -M generate Makefile dependencies on stdout\n"
778 " -MG d:o, missing files assumed generated\n"
779 " -MF <file> set Makefile dependency file\n"
780 " -MD <file> assemble and generate dependencies\n"
781 " -MT <file> dependency target name\n"
782 " -MQ <file> dependency target name (quoted)\n"
783 " -MP emit phony target\n\n"
784 " -Z<file> redirect error messages to file\n"
785 " -s redirect error messages to stdout\n\n"
786 " -F format select a debugging format\n\n"
787 " -I<path> adds a pathname to the include file path\n");
788 printf
789 (" -O<digit> optimize branch offsets\n"
790 " -O0: No optimization\n"
791 " -O1: Minimal optimization\n"
792 " -Ox: Multipass optimization (default)\n\n"
793 " -P<file> pre-includes a file\n"
794 " -D<macro>[=<value>] pre-defines a macro\n"
795 " -U<macro> undefines a macro\n"
796 " -X<format> specifies error reporting format (gnu or vc)\n"
797 " -w+foo enables warning foo (equiv. -Wfoo)\n"
798 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
799 "--prefix,--postfix\n"
800 " this options prepend or append the given argument to all\n"
801 " extern and global variables\n\n"
802 "Warnings:\n");
803 for (i = 0; i <= ERR_WARN_MAX; i++)
804 printf(" %-23s %s (default %s)\n",
805 warnings[i].name, warnings[i].help,
806 warnings[i].enabled ? "on" : "off");
807 printf
808 ("\nresponse files should contain command line parameters"
809 ", one per line.\n");
810 if (p[2] == 'f') {
811 printf("\nvalid output formats for -f are"
812 " (`*' denotes default):\n");
813 ofmt_list(ofmt, stdout);
814 } else {
815 printf("\nFor a list of valid output formats, use -hf.\n");
816 printf("For a list of debug formats, use -f <form> -y.\n");
818 exit(0); /* never need usage message here */
819 break;
821 case 'y':
822 printf("\nvalid debug formats for '%s' output format are"
823 " ('*' denotes default):\n", ofmt->shortname);
824 dfmt_list(ofmt, stdout);
825 exit(0);
826 break;
828 case 't':
829 tasm_compatible_mode = true;
830 break;
832 case 'v':
833 printf("NASM version %s compiled on %s%s\n",
834 nasm_version, nasm_date, nasm_compile_options);
835 exit(0); /* never need usage message here */
836 break;
838 case 'e': /* preprocess only */
839 case 'E':
840 operating_mode = op_preprocess;
841 break;
843 case 'a': /* assemble only - don't preprocess */
844 preproc = &preproc_nop;
845 break;
847 case 'W':
848 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
849 do_warn = false;
850 param += 3;
851 } else {
852 do_warn = true;
854 goto set_warning;
856 case 'w':
857 if (param[0] != '+' && param[0] != '-') {
858 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
859 "invalid option to `-w'");
860 break;
862 do_warn = (param[0] == '+');
863 param++;
865 set_warning:
866 for (i = 0; i <= ERR_WARN_MAX; i++) {
867 if (!nasm_stricmp(param, warnings[i].name))
868 break;
870 if (i <= ERR_WARN_MAX) {
871 warning_on_global[i] = do_warn;
872 } else if (!nasm_stricmp(param, "all")) {
873 for (i = 1; i <= ERR_WARN_MAX; i++)
874 warning_on_global[i] = do_warn;
875 } else if (!nasm_stricmp(param, "none")) {
876 for (i = 1; i <= ERR_WARN_MAX; i++)
877 warning_on_global[i] = !do_warn;
878 } else {
879 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
880 "invalid warning `%s'", param);
882 break;
884 case 'M':
885 switch (p[2]) {
886 case 0:
887 operating_mode = op_depend;
888 break;
889 case 'G':
890 operating_mode = op_depend;
891 depend_missing_ok = true;
892 break;
893 case 'P':
894 depend_emit_phony = true;
895 break;
896 case 'D':
897 depend_file = q;
898 advance = true;
899 break;
900 case 'T':
901 depend_target = q;
902 advance = true;
903 break;
904 case 'Q':
905 depend_target = quote_for_make(q);
906 advance = true;
907 break;
908 default:
909 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
910 "unknown dependency option `-M%c'", p[2]);
911 break;
913 if (advance && (!q || !q[0])) {
914 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
915 "option `-M%c' requires a parameter", p[2]);
916 break;
918 break;
920 case '-':
922 int s;
924 if (p[2] == 0) { /* -- => stop processing options */
925 stopoptions = 1;
926 break;
928 for (s = 0; textopts[s].label; s++) {
929 if (!nasm_stricmp(p + 2, textopts[s].label)) {
930 break;
934 switch (s) {
936 case OPT_PREFIX:
937 case OPT_POSTFIX:
939 if (!q) {
940 nasm_error(ERR_NONFATAL | ERR_NOFILE |
941 ERR_USAGE,
942 "option `--%s' requires an argument",
943 p + 2);
944 break;
945 } else {
946 advance = 1, param = q;
949 if (s == OPT_PREFIX) {
950 strncpy(lprefix, param, PREFIX_MAX - 1);
951 lprefix[PREFIX_MAX - 1] = 0;
952 break;
954 if (s == OPT_POSTFIX) {
955 strncpy(lpostfix, param, POSTFIX_MAX - 1);
956 lpostfix[POSTFIX_MAX - 1] = 0;
957 break;
959 break;
961 default:
963 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
964 "unrecognised option `--%s'", p + 2);
965 break;
968 break;
971 default:
972 if (!ofmt->setinfo(GI_SWITCH, &p))
973 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
974 "unrecognised option `-%c'", p[1]);
975 break;
977 } else {
978 if (*inname) {
979 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
980 "more than one input file specified");
981 } else {
982 copy_filename(inname, p);
986 return advance;
989 #define ARG_BUF_DELTA 128
991 static void process_respfile(FILE * rfile)
993 char *buffer, *p, *q, *prevarg;
994 int bufsize, prevargsize;
996 bufsize = prevargsize = ARG_BUF_DELTA;
997 buffer = nasm_malloc(ARG_BUF_DELTA);
998 prevarg = nasm_malloc(ARG_BUF_DELTA);
999 prevarg[0] = '\0';
1001 while (1) { /* Loop to handle all lines in file */
1002 p = buffer;
1003 while (1) { /* Loop to handle long lines */
1004 q = fgets(p, bufsize - (p - buffer), rfile);
1005 if (!q)
1006 break;
1007 p += strlen(p);
1008 if (p > buffer && p[-1] == '\n')
1009 break;
1010 if (p - buffer > bufsize - 10) {
1011 int offset;
1012 offset = p - buffer;
1013 bufsize += ARG_BUF_DELTA;
1014 buffer = nasm_realloc(buffer, bufsize);
1015 p = buffer + offset;
1019 if (!q && p == buffer) {
1020 if (prevarg[0])
1021 process_arg(prevarg, NULL);
1022 nasm_free(buffer);
1023 nasm_free(prevarg);
1024 return;
1028 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1029 * them are present at the end of the line.
1031 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1033 while (p > buffer && nasm_isspace(p[-1]))
1034 *--p = '\0';
1036 p = nasm_skip_spaces(buffer);
1038 if (process_arg(prevarg, p))
1039 *p = '\0';
1041 if ((int) strlen(p) > prevargsize - 10) {
1042 prevargsize += ARG_BUF_DELTA;
1043 prevarg = nasm_realloc(prevarg, prevargsize);
1045 strncpy(prevarg, p, prevargsize);
1049 /* Function to process args from a string of args, rather than the
1050 * argv array. Used by the environment variable and response file
1051 * processing.
1053 static void process_args(char *args)
1055 char *p, *q, *arg, *prevarg;
1056 char separator = ' ';
1058 p = args;
1059 if (*p && *p != '-')
1060 separator = *p++;
1061 arg = NULL;
1062 while (*p) {
1063 q = p;
1064 while (*p && *p != separator)
1065 p++;
1066 while (*p == separator)
1067 *p++ = '\0';
1068 prevarg = arg;
1069 arg = q;
1070 if (process_arg(prevarg, arg))
1071 arg = NULL;
1073 if (arg)
1074 process_arg(arg, NULL);
1077 static void process_response_file(const char *file)
1079 char str[2048];
1080 FILE *f = fopen(file, "r");
1081 if (!f) {
1082 perror(file);
1083 exit(-1);
1085 while (fgets(str, sizeof str, f)) {
1086 process_args(str);
1088 fclose(f);
1091 static void parse_cmdline(int argc, char **argv)
1093 FILE *rfile;
1094 char *envreal, *envcopy = NULL, *p;
1095 int i;
1097 *inname = *outname = *listname = *errname = '\0';
1099 for (i = 0; i <= ERR_WARN_MAX; i++)
1100 warning_on_global[i] = warnings[i].enabled;
1103 * First, process the NASMENV environment variable.
1105 envreal = getenv("NASMENV");
1106 if (envreal) {
1107 envcopy = nasm_strdup(envreal);
1108 process_args(envcopy);
1109 nasm_free(envcopy);
1113 * Now process the actual command line.
1115 while (--argc) {
1116 bool advance;
1117 argv++;
1118 if (argv[0][0] == '@') {
1120 * We have a response file, so process this as a set of
1121 * arguments like the environment variable. This allows us
1122 * to have multiple arguments on a single line, which is
1123 * different to the -@resp file processing below for regular
1124 * NASM.
1126 process_response_file(argv[0]+1);
1127 argc--;
1128 argv++;
1130 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1131 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1132 if (p) {
1133 rfile = fopen(p, "r");
1134 if (rfile) {
1135 process_respfile(rfile);
1136 fclose(rfile);
1137 } else
1138 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1139 "unable to open response file `%s'", p);
1141 } else
1142 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1143 argv += advance, argc -= advance;
1147 * Look for basic command line typos. This definitely doesn't
1148 * catch all errors, but it might help cases of fumbled fingers.
1150 if (!*inname)
1151 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1152 "no input file specified");
1153 else if (!strcmp(inname, errname) ||
1154 !strcmp(inname, outname) ||
1155 !strcmp(inname, listname) ||
1156 (depend_file && !strcmp(inname, depend_file)))
1157 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1158 "file `%s' is both input and output file",
1159 inname);
1161 if (*errname) {
1162 error_file = fopen(errname, "w");
1163 if (!error_file) {
1164 error_file = stderr; /* Revert to default! */
1165 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1166 "cannot open file `%s' for error messages",
1167 errname);
1172 static enum directives getkw(char **directive, char **value);
1174 static void assemble_file(char *fname, StrList **depend_ptr)
1176 char *directive, *value, *p, *q, *special, *line;
1177 insn output_ins;
1178 int i, validid;
1179 bool rn_error;
1180 int32_t seg;
1181 int64_t offs;
1182 struct tokenval tokval;
1183 expr *e;
1184 int pass_max;
1186 if (cmd_sb == 32 && cmd_cpu < IF_386)
1187 nasm_error(ERR_FATAL, "command line: "
1188 "32-bit segment size requires a higher cpu");
1190 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1191 for (passn = 1; pass0 <= 2; passn++) {
1192 int pass1, pass2;
1193 ldfunc def_label;
1195 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1196 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1197 /* pass0 0, 0, 0, ..., 1, 2 */
1199 def_label = passn > 1 ? redefine_label : define_label;
1201 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1202 cpu = cmd_cpu;
1203 if (pass0 == 2) {
1204 if (*listname)
1205 nasmlist.init(listname, nasm_error);
1207 in_abs_seg = false;
1208 global_offset_changed = 0; /* set by redefine_label */
1209 location.segment = ofmt->section(NULL, pass2, &sb);
1210 globalbits = sb;
1211 if (passn > 1) {
1212 saa_rewind(forwrefs);
1213 forwref = saa_rstruct(forwrefs);
1214 raa_free(offsets);
1215 offsets = raa_init();
1217 preproc->reset(fname, pass1, &nasmlist,
1218 pass1 == 2 ? depend_ptr : NULL);
1219 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1221 globallineno = 0;
1222 if (passn == 1)
1223 location.known = true;
1224 location.offset = offs = get_curr_offs();
1226 while ((line = preproc->getline())) {
1227 enum directives d;
1228 globallineno++;
1231 * Here we parse our directives; this is not handled by the
1232 * 'real' parser. This really should be a separate function.
1234 directive = line;
1235 d = getkw(&directive, &value);
1236 if (d) {
1237 int err = 0;
1239 switch (d) {
1240 case D_SEGMENT: /* [SEGMENT n] */
1241 case D_SECTION:
1242 seg = ofmt->section(value, pass2, &sb);
1243 if (seg == NO_SEG) {
1244 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1245 "segment name `%s' not recognized",
1246 value);
1247 } else {
1248 in_abs_seg = false;
1249 location.segment = seg;
1251 break;
1252 case D_SECTALIGN: /* [SECTALIGN n] */
1253 if (*value) {
1254 stdscan_reset();
1255 stdscan_set(value);
1256 tokval.t_type = TOKEN_INVALID;
1257 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1258 if (e) {
1259 unsigned int align = (unsigned int)e->value;
1260 if ((uint64_t)e->value > 0x7fffffff) {
1262 * FIXME: Please make some sane message here
1263 * ofmt should have some 'check' method which
1264 * would report segment alignment bounds.
1266 nasm_error(ERR_FATAL,
1267 "incorrect segment alignment `%s'", value);
1268 } else if (!is_power2(align)) {
1269 nasm_error(ERR_NONFATAL,
1270 "segment alignment `%s' is not power of two",
1271 value);
1273 /* callee should be able to handle all details */
1274 ofmt->sectalign(location.segment, align);
1277 break;
1278 case D_EXTERN: /* [EXTERN label:special] */
1279 if (*value == '$')
1280 value++; /* skip initial $ if present */
1281 if (pass0 == 2) {
1282 q = value;
1283 while (*q && *q != ':')
1284 q++;
1285 if (*q == ':') {
1286 *q++ = '\0';
1287 ofmt->symdef(value, 0L, 0L, 3, q);
1289 } else if (passn == 1) {
1290 q = value;
1291 validid = true;
1292 if (!isidstart(*q))
1293 validid = false;
1294 while (*q && *q != ':') {
1295 if (!isidchar(*q))
1296 validid = false;
1297 q++;
1299 if (!validid) {
1300 nasm_error(ERR_NONFATAL,
1301 "identifier expected after EXTERN");
1302 break;
1304 if (*q == ':') {
1305 *q++ = '\0';
1306 special = q;
1307 } else
1308 special = NULL;
1309 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1310 int temp = pass0;
1311 pass0 = 1; /* fake pass 1 in labels.c */
1312 declare_as_global(value, special);
1313 define_label(value, seg_alloc(), 0L, NULL,
1314 false, true);
1315 pass0 = temp;
1317 } /* else pass0 == 1 */
1318 break;
1319 case D_BITS: /* [BITS bits] */
1320 globalbits = sb = get_bits(value);
1321 break;
1322 case D_GLOBAL: /* [GLOBAL symbol:special] */
1323 if (*value == '$')
1324 value++; /* skip initial $ if present */
1325 if (pass0 == 2) { /* pass 2 */
1326 q = value;
1327 while (*q && *q != ':')
1328 q++;
1329 if (*q == ':') {
1330 *q++ = '\0';
1331 ofmt->symdef(value, 0L, 0L, 3, q);
1333 } else if (pass2 == 1) { /* pass == 1 */
1334 q = value;
1335 validid = true;
1336 if (!isidstart(*q))
1337 validid = false;
1338 while (*q && *q != ':') {
1339 if (!isidchar(*q))
1340 validid = false;
1341 q++;
1343 if (!validid) {
1344 nasm_error(ERR_NONFATAL,
1345 "identifier expected after GLOBAL");
1346 break;
1348 if (*q == ':') {
1349 *q++ = '\0';
1350 special = q;
1351 } else
1352 special = NULL;
1353 declare_as_global(value, special);
1354 } /* pass == 1 */
1355 break;
1356 case D_COMMON: /* [COMMON symbol size:special] */
1358 int64_t size;
1360 if (*value == '$')
1361 value++; /* skip initial $ if present */
1362 p = value;
1363 validid = true;
1364 if (!isidstart(*p))
1365 validid = false;
1366 while (*p && !nasm_isspace(*p)) {
1367 if (!isidchar(*p))
1368 validid = false;
1369 p++;
1371 if (!validid) {
1372 nasm_error(ERR_NONFATAL,
1373 "identifier expected after COMMON");
1374 break;
1376 if (*p) {
1377 p = nasm_zap_spaces_fwd(p);
1378 q = p;
1379 while (*q && *q != ':')
1380 q++;
1381 if (*q == ':') {
1382 *q++ = '\0';
1383 special = q;
1384 } else {
1385 special = NULL;
1387 size = readnum(p, &rn_error);
1388 if (rn_error) {
1389 nasm_error(ERR_NONFATAL,
1390 "invalid size specified"
1391 " in COMMON declaration");
1392 break;
1394 } else {
1395 nasm_error(ERR_NONFATAL,
1396 "no size specified in"
1397 " COMMON declaration");
1398 break;
1401 if (pass0 < 2) {
1402 define_common(value, seg_alloc(), size, special);
1403 } else if (pass0 == 2) {
1404 if (special)
1405 ofmt->symdef(value, 0L, 0L, 3, special);
1407 break;
1409 case D_ABSOLUTE: /* [ABSOLUTE address] */
1410 stdscan_reset();
1411 stdscan_set(value);
1412 tokval.t_type = TOKEN_INVALID;
1413 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1414 nasm_error, NULL);
1415 if (e) {
1416 if (!is_reloc(e))
1417 nasm_error(pass0 ==
1418 1 ? ERR_NONFATAL : ERR_PANIC,
1419 "cannot use non-relocatable expression as "
1420 "ABSOLUTE address");
1421 else {
1422 abs_seg = reloc_seg(e);
1423 abs_offset = reloc_value(e);
1425 } else if (passn == 1)
1426 abs_offset = 0x100; /* don't go near zero in case of / */
1427 else
1428 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1429 "in pass two");
1430 in_abs_seg = true;
1431 location.segment = NO_SEG;
1432 break;
1433 case D_DEBUG: /* [DEBUG] */
1435 char debugid[128];
1436 bool badid, overlong;
1438 p = value;
1439 q = debugid;
1440 badid = overlong = false;
1441 if (!isidstart(*p)) {
1442 badid = true;
1443 } else {
1444 while (*p && !nasm_isspace(*p)) {
1445 if (q >= debugid + sizeof debugid - 1) {
1446 overlong = true;
1447 break;
1449 if (!isidchar(*p))
1450 badid = true;
1451 *q++ = *p++;
1453 *q = 0;
1455 if (badid) {
1456 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1457 "identifier expected after DEBUG");
1458 break;
1460 if (overlong) {
1461 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1462 "DEBUG identifier too long");
1463 break;
1465 p = nasm_skip_spaces(p);
1466 if (pass0 == 2)
1467 dfmt->debug_directive(debugid, p);
1468 break;
1470 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1471 value = nasm_skip_spaces(value);
1472 switch(*value) {
1473 case '-': validid = 0; value++; break;
1474 case '+': validid = 1; value++; break;
1475 case '*': validid = 2; value++; break;
1476 default: validid = 1; break;
1479 for (i = 1; i <= ERR_WARN_MAX; i++)
1480 if (!nasm_stricmp(value, warnings[i].name))
1481 break;
1482 if (i <= ERR_WARN_MAX) {
1483 switch(validid) {
1484 case 0:
1485 warning_on[i] = false;
1486 break;
1487 case 1:
1488 warning_on[i] = true;
1489 break;
1490 case 2:
1491 warning_on[i] = warning_on_global[i];
1492 break;
1494 } else
1495 nasm_error(ERR_NONFATAL,
1496 "invalid warning id in WARNING directive");
1497 break;
1498 case D_CPU: /* [CPU] */
1499 cpu = get_cpu(value);
1500 break;
1501 case D_LIST: /* [LIST {+|-}] */
1502 value = nasm_skip_spaces(value);
1503 if (*value == '+') {
1504 user_nolist = 0;
1505 } else {
1506 if (*value == '-') {
1507 user_nolist = 1;
1508 } else {
1509 err = 1;
1512 break;
1513 case D_DEFAULT: /* [DEFAULT] */
1514 stdscan_reset();
1515 stdscan_set(value);
1516 tokval.t_type = TOKEN_INVALID;
1517 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1518 switch ((int)tokval.t_integer) {
1519 case S_REL:
1520 globalrel = 1;
1521 break;
1522 case S_ABS:
1523 globalrel = 0;
1524 break;
1525 default:
1526 err = 1;
1527 break;
1529 } else {
1530 err = 1;
1532 break;
1533 case D_FLOAT:
1534 if (float_option(value)) {
1535 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1536 "unknown 'float' directive: %s",
1537 value);
1539 break;
1540 default:
1541 if (ofmt->directive(d, value, pass2))
1542 break;
1543 /* else fall through */
1544 case D_unknown:
1545 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1546 "unrecognised directive [%s]",
1547 directive);
1548 break;
1550 if (err) {
1551 nasm_error(ERR_NONFATAL,
1552 "invalid parameter to [%s] directive",
1553 directive);
1555 } else { /* it isn't a directive */
1556 parse_line(pass1, line, &output_ins, def_label);
1558 if (optimizing > 0) {
1559 if (forwref != NULL && globallineno == forwref->lineno) {
1560 output_ins.forw_ref = true;
1561 do {
1562 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1563 forwref = saa_rstruct(forwrefs);
1564 } while (forwref != NULL
1565 && forwref->lineno == globallineno);
1566 } else
1567 output_ins.forw_ref = false;
1569 if (output_ins.forw_ref) {
1570 if (passn == 1) {
1571 for (i = 0; i < output_ins.operands; i++) {
1572 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1573 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1574 fwinf->lineno = globallineno;
1575 fwinf->operand = i;
1582 /* forw_ref */
1583 if (output_ins.opcode == I_EQU) {
1584 if (pass1 == 1) {
1586 * Special `..' EQUs get processed in pass two,
1587 * except `..@' macro-processor EQUs which are done
1588 * in the normal place.
1590 if (!output_ins.label)
1591 nasm_error(ERR_NONFATAL,
1592 "EQU not preceded by label");
1594 else if (output_ins.label[0] != '.' ||
1595 output_ins.label[1] != '.' ||
1596 output_ins.label[2] == '@') {
1597 if (output_ins.operands == 1 &&
1598 (output_ins.oprs[0].type & IMMEDIATE) &&
1599 output_ins.oprs[0].wrt == NO_SEG) {
1600 bool isext = !!(output_ins.oprs[0].opflags & 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;