Change rights 644 to 755
[nasm/github.git] / nasm.c
blob8557b4db4c60b1d820f097079b062a6f1530aa5d
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"
63 #include "iflag.h"
66 * This is the maximum number of optimization passes to do. If we ever
67 * find a case where the optimizer doesn't naturally converge, we might
68 * have to drop this value so the assembler doesn't appear to just hang.
70 #define MAX_OPTIMIZE (INT_MAX >> 1)
72 struct forwrefinfo { /* info held on forward refs. */
73 int lineno;
74 int operand;
77 static int get_bits(char *value);
78 static iflag_t get_cpu(char *cpu_str);
79 static void parse_cmdline(int, char **);
80 static void assemble_file(char *, StrList **);
81 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
82 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
83 static void nasm_verror_common(int severity, const char *fmt, va_list args);
84 static bool is_suppressed_warning(int severity);
85 static void usage(void);
87 static int using_debug_info, opt_verbose_info;
88 bool tasm_compatible_mode = false;
89 int pass0, passn;
90 int maxbits = 0;
91 int globalrel = 0;
92 int globalbnd = 0;
94 static time_t official_compile_time;
96 static char inname[FILENAME_MAX];
97 static char outname[FILENAME_MAX];
98 static char listname[FILENAME_MAX];
99 static char errname[FILENAME_MAX];
100 static int globallineno; /* for forward-reference tracking */
101 /* static int pass = 0; */
102 struct ofmt *ofmt = &OF_DEFAULT;
103 struct ofmt_alias *ofmt_alias = NULL;
104 const struct dfmt *dfmt;
106 static FILE *error_file; /* Where to write error messages */
108 FILE *ofile = NULL;
109 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
110 static int sb, cmd_sb = 16; /* by default */
112 static iflag_t cpu;
113 static iflag_t cmd_cpu;
115 int64_t global_offset_changed; /* referenced in labels.c */
116 int64_t prev_offset_changed;
117 int32_t stall_count;
119 static struct location location;
120 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
121 int32_t abs_seg; /* ABSOLUTE segment basis */
122 int32_t abs_offset; /* ABSOLUTE offset */
124 static struct RAA *offsets;
126 static struct SAA *forwrefs; /* keep track of forward references */
127 static const struct forwrefinfo *forwref;
129 static struct preproc_ops *preproc;
131 #define OP_NORMAL (1u << 0)
132 #define OP_PREPROCESS (1u << 1)
133 #define OP_DEPEND (1u << 2)
135 static unsigned int operating_mode;
137 /* Dependency flags */
138 static bool depend_emit_phony = false;
139 static bool depend_missing_ok = false;
140 static const char *depend_target = NULL;
141 static const char *depend_file = NULL;
144 * Which of the suppressible warnings are suppressed. Entry zero
145 * isn't an actual warning, but it used for -w+error/-Werror.
148 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
149 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
151 static const struct warning {
152 const char *name;
153 const char *help;
154 bool enabled;
155 } warnings[ERR_WARN_MAX+1] = {
156 {"error", "treat warnings as errors", false},
157 {"macro-params", "macro calls with wrong parameter count", true},
158 {"macro-selfref", "cyclic macro references", false},
159 {"macro-defaults", "macros with more default than optional parameters", true},
160 {"orphan-labels", "labels alone on lines without trailing `:'", true},
161 {"number-overflow", "numeric constant does not fit", true},
162 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
163 {"float-overflow", "floating point overflow", true},
164 {"float-denorm", "floating point denormal", false},
165 {"float-underflow", "floating point underflow", false},
166 {"float-toolong", "too many digits in floating-point number", true},
167 {"user", "%warning directives", true},
168 {"lock", "lock prefix on unlockable instructions", true},
169 {"hle", "invalid hle prefixes", true},
170 {"bnd", "invalid bnd prefixes", true},
173 static bool want_usage;
174 static bool terminate_after_phase;
175 int user_nolist = 0; /* fbk 9/2/00 */
177 static char *quote_for_make(const char *str);
179 static int64_t get_curr_offs(void)
181 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
184 static void set_curr_offs(int64_t l_off)
186 if (in_abs_seg)
187 abs_offset = l_off;
188 else
189 offsets = raa_write(offsets, location.segment, l_off);
192 static void nasm_fputs(const char *line, FILE * outfile)
194 if (outfile) {
195 fputs(line, outfile);
196 putc('\n', outfile);
197 } else
198 puts(line);
201 /* Convert a struct tm to a POSIX-style time constant */
202 static int64_t make_posix_time(struct tm *tm)
204 int64_t t;
205 int64_t y = tm->tm_year;
207 /* See IEEE 1003.1:2004, section 4.14 */
209 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
210 t += tm->tm_yday;
211 t *= 24;
212 t += tm->tm_hour;
213 t *= 60;
214 t += tm->tm_min;
215 t *= 60;
216 t += tm->tm_sec;
218 return t;
221 static void define_macros_early(void)
223 char temp[128];
224 struct tm lt, *lt_p, gm, *gm_p;
225 int64_t posix_time;
227 lt_p = localtime(&official_compile_time);
228 if (lt_p) {
229 lt = *lt_p;
231 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
232 preproc->pre_define(temp);
233 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
234 preproc->pre_define(temp);
235 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
238 preproc->pre_define(temp);
241 gm_p = gmtime(&official_compile_time);
242 if (gm_p) {
243 gm = *gm_p;
245 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
246 preproc->pre_define(temp);
247 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
248 preproc->pre_define(temp);
249 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
250 preproc->pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
252 preproc->pre_define(temp);
255 if (gm_p)
256 posix_time = make_posix_time(&gm);
257 else if (lt_p)
258 posix_time = make_posix_time(&lt);
259 else
260 posix_time = 0;
262 if (posix_time) {
263 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
264 preproc->pre_define(temp);
268 static void define_macros_late(void)
270 char temp[128];
273 * In case if output format is defined by alias
274 * we have to put shortname of the alias itself here
275 * otherwise ABI backward compatibility gets broken.
277 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
278 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
279 preproc->pre_define(temp);
282 static void emit_dependencies(StrList *list)
284 FILE *deps;
285 int linepos, len;
286 StrList *l, *nl;
288 if (depend_file && strcmp(depend_file, "-")) {
289 deps = fopen(depend_file, "w");
290 if (!deps) {
291 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
292 "unable to write dependency file `%s'", depend_file);
293 return;
295 } else {
296 deps = stdout;
299 linepos = fprintf(deps, "%s:", depend_target);
300 list_for_each(l, list) {
301 char *file = quote_for_make(l->str);
302 len = strlen(file);
303 if (linepos + len > 62 && linepos > 1) {
304 fprintf(deps, " \\\n ");
305 linepos = 1;
307 fprintf(deps, " %s", file);
308 linepos += len+1;
309 nasm_free(file);
311 fprintf(deps, "\n\n");
313 list_for_each_safe(l, nl, list) {
314 if (depend_emit_phony)
315 fprintf(deps, "%s:\n\n", l->str);
316 nasm_free(l);
319 if (deps != stdout)
320 fclose(deps);
323 int main(int argc, char **argv)
325 StrList *depend_list = NULL, **depend_ptr;
327 time(&official_compile_time);
329 iflag_set(&cpu, IF_PLEVEL);
330 iflag_set(&cmd_cpu, IF_PLEVEL);
332 pass0 = 0;
333 want_usage = terminate_after_phase = false;
334 nasm_set_verror(nasm_verror_gnu);
336 error_file = stderr;
338 tolower_init();
340 offsets = raa_init();
341 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
343 preproc = &nasmpp;
344 operating_mode = OP_NORMAL;
346 seg_init();
348 /* Define some macros dependent on the runtime, but not
349 on the command line. */
350 define_macros_early();
352 parse_cmdline(argc, argv);
354 if (terminate_after_phase) {
355 if (want_usage)
356 usage();
357 return 1;
360 /* If debugging info is disabled, suppress any debug calls */
361 if (!using_debug_info)
362 ofmt->current_dfmt = &null_debug_form;
364 if (ofmt->stdmac)
365 preproc->extra_stdmac(ofmt->stdmac);
366 parser_global_info(&location);
367 eval_global_info(ofmt, lookup_label, &location);
369 /* define some macros dependent of command-line */
370 define_macros_late();
372 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
373 if (!depend_target)
374 depend_target = quote_for_make(outname);
376 if (operating_mode & OP_DEPEND) {
377 char *line;
379 if (depend_missing_ok)
380 preproc->include_path(NULL); /* "assume generated" */
382 preproc->reset(inname, 0, &nasmlist, depend_ptr);
383 if (outname[0] == '\0')
384 ofmt->filename(inname, outname);
385 ofile = NULL;
386 while ((line = preproc->getline()))
387 nasm_free(line);
388 preproc->cleanup(0);
389 } else if (operating_mode & OP_PREPROCESS) {
390 char *line;
391 char *file_name = NULL;
392 int32_t prior_linnum = 0;
393 int lineinc = 0;
395 if (*outname) {
396 ofile = fopen(outname, "w");
397 if (!ofile)
398 nasm_error(ERR_FATAL | ERR_NOFILE,
399 "unable to open output file `%s'",
400 outname);
401 } else
402 ofile = NULL;
404 location.known = false;
406 /* pass = 1; */
407 preproc->reset(inname, 3, &nasmlist, depend_ptr);
408 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
410 while ((line = preproc->getline())) {
412 * We generate %line directives if needed for later programs
414 int32_t linnum = prior_linnum += lineinc;
415 int altline = src_get(&linnum, &file_name);
416 if (altline) {
417 if (altline == 1 && lineinc == 1)
418 nasm_fputs("", ofile);
419 else {
420 lineinc = (altline != -1 || lineinc != 1);
421 fprintf(ofile ? ofile : stdout,
422 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
423 file_name);
425 prior_linnum = linnum;
427 nasm_fputs(line, ofile);
428 nasm_free(line);
430 nasm_free(file_name);
431 preproc->cleanup(0);
432 if (ofile)
433 fclose(ofile);
434 if (ofile && terminate_after_phase)
435 remove(outname);
436 ofile = NULL;
439 if (operating_mode & OP_NORMAL) {
441 * We must call ofmt->filename _anyway_, even if the user
442 * has specified their own output file, because some
443 * formats (eg OBJ and COFF) use ofmt->filename to find out
444 * the name of the input file and then put that inside the
445 * file.
447 ofmt->filename(inname, outname);
449 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
450 if (!ofile)
451 nasm_error(ERR_FATAL | ERR_NOFILE,
452 "unable to open output file `%s'", outname);
455 * We must call init_labels() before ofmt->init() since
456 * some object formats will want to define labels in their
457 * init routines. (eg OS/2 defines the FLAT group)
459 init_labels();
461 ofmt->init();
462 dfmt = ofmt->current_dfmt;
463 dfmt->init();
465 assemble_file(inname, depend_ptr);
467 if (!terminate_after_phase) {
468 ofmt->cleanup(using_debug_info);
469 cleanup_labels();
470 fflush(ofile);
471 if (ferror(ofile))
472 nasm_error(ERR_NONFATAL|ERR_NOFILE,
473 "write error on output file `%s'", outname);
476 if (ofile) {
477 fclose(ofile);
478 if (terminate_after_phase)
479 remove(outname);
480 ofile = NULL;
484 if (depend_list && !terminate_after_phase)
485 emit_dependencies(depend_list);
487 if (want_usage)
488 usage();
490 raa_free(offsets);
491 saa_free(forwrefs);
492 eval_cleanup();
493 stdscan_cleanup();
495 return terminate_after_phase;
499 * Get a parameter for a command line option.
500 * First arg must be in the form of e.g. -f...
502 static char *get_param(char *p, char *q, bool *advance)
504 *advance = false;
505 if (p[2]) /* the parameter's in the option */
506 return nasm_skip_spaces(p + 2);
507 if (q && q[0]) {
508 *advance = true;
509 return q;
511 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
512 "option `-%c' requires an argument", p[1]);
513 return NULL;
517 * Copy a filename
519 static void copy_filename(char *dst, const char *src)
521 size_t len = strlen(src);
523 if (len >= (size_t)FILENAME_MAX) {
524 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
525 return;
527 strncpy(dst, src, FILENAME_MAX);
531 * Convert a string to Make-safe form
533 static char *quote_for_make(const char *str)
535 const char *p;
536 char *os, *q;
538 size_t n = 1; /* Terminating zero */
539 size_t nbs = 0;
541 if (!str)
542 return NULL;
544 for (p = str; *p; p++) {
545 switch (*p) {
546 case ' ':
547 case '\t':
548 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
549 n += nbs + 2;
550 nbs = 0;
551 break;
552 case '$':
553 case '#':
554 nbs = 0;
555 n += 2;
556 break;
557 case '\\':
558 nbs++;
559 n++;
560 break;
561 default:
562 nbs = 0;
563 n++;
564 break;
568 /* Convert N backslashes at the end of filename to 2N backslashes */
569 if (nbs)
570 n += nbs;
572 os = q = nasm_malloc(n);
574 nbs = 0;
575 for (p = str; *p; p++) {
576 switch (*p) {
577 case ' ':
578 case '\t':
579 while (nbs--)
580 *q++ = '\\';
581 *q++ = '\\';
582 *q++ = *p;
583 break;
584 case '$':
585 *q++ = *p;
586 *q++ = *p;
587 nbs = 0;
588 break;
589 case '#':
590 *q++ = '\\';
591 *q++ = *p;
592 nbs = 0;
593 break;
594 case '\\':
595 *q++ = *p;
596 nbs++;
597 break;
598 default:
599 *q++ = *p;
600 nbs = 0;
601 break;
604 while (nbs--)
605 *q++ = '\\';
607 *q = '\0';
609 return os;
612 struct textargs {
613 const char *label;
614 int value;
617 #define OPT_PREFIX 0
618 #define OPT_POSTFIX 1
619 struct textargs textopts[] = {
620 {"prefix", OPT_PREFIX},
621 {"postfix", OPT_POSTFIX},
622 {NULL, 0}
625 static void show_version(void)
627 printf("NASM version %s compiled on %s%s\n",
628 nasm_version, nasm_date, nasm_compile_options);
629 exit(0);
632 static bool stopoptions = false;
633 static bool process_arg(char *p, char *q)
635 char *param;
636 int i;
637 bool advance = false;
638 bool do_warn;
640 if (!p || !p[0])
641 return false;
643 if (p[0] == '-' && !stopoptions) {
644 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
645 /* These parameters take values */
646 if (!(param = get_param(p, q, &advance)))
647 return advance;
650 switch (p[1]) {
651 case 's':
652 error_file = stdout;
653 break;
655 case 'o': /* output file */
656 copy_filename(outname, param);
657 break;
659 case 'f': /* output format */
660 ofmt = ofmt_find(param, &ofmt_alias);
661 if (!ofmt) {
662 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
663 "unrecognised output format `%s' - "
664 "use -hf for a list", param);
666 break;
668 case 'O': /* Optimization level */
670 int opt;
672 if (!*param) {
673 /* Naked -O == -Ox */
674 optimizing = MAX_OPTIMIZE;
675 } else {
676 while (*param) {
677 switch (*param) {
678 case '0': case '1': case '2': case '3': case '4':
679 case '5': case '6': case '7': case '8': case '9':
680 opt = strtoul(param, &param, 10);
682 /* -O0 -> optimizing == -1, 0.98 behaviour */
683 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
684 if (opt < 2)
685 optimizing = opt - 1;
686 else
687 optimizing = opt;
688 break;
690 case 'v':
691 case '+':
692 param++;
693 opt_verbose_info = true;
694 break;
696 case 'x':
697 param++;
698 optimizing = MAX_OPTIMIZE;
699 break;
701 default:
702 nasm_error(ERR_FATAL,
703 "unknown optimization option -O%c\n",
704 *param);
705 break;
708 if (optimizing > MAX_OPTIMIZE)
709 optimizing = MAX_OPTIMIZE;
711 break;
714 case 'p': /* pre-include */
715 case 'P':
716 preproc->pre_include(param);
717 break;
719 case 'd': /* pre-define */
720 case 'D':
721 preproc->pre_define(param);
722 break;
724 case 'u': /* un-define */
725 case 'U':
726 preproc->pre_undefine(param);
727 break;
729 case 'i': /* include search path */
730 case 'I':
731 preproc->include_path(param);
732 break;
734 case 'l': /* listing file */
735 copy_filename(listname, param);
736 break;
738 case 'Z': /* error messages file */
739 copy_filename(errname, param);
740 break;
742 case 'F': /* specify debug format */
743 ofmt->current_dfmt = dfmt_find(ofmt, param);
744 if (!ofmt->current_dfmt) {
745 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
746 "unrecognized debug format `%s' for"
747 " output format `%s'",
748 param, ofmt->shortname);
750 using_debug_info = true;
751 break;
753 case 'X': /* specify error reporting format */
754 if (nasm_stricmp("vc", param) == 0)
755 nasm_set_verror(nasm_verror_vc);
756 else if (nasm_stricmp("gnu", param) == 0)
757 nasm_set_verror(nasm_verror_gnu);
758 else
759 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
760 "unrecognized error reporting format `%s'",
761 param);
762 break;
764 case 'g':
765 using_debug_info = true;
766 break;
768 case 'h':
769 printf
770 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
771 "[-l listfile]\n"
772 " [options...] [--] filename\n"
773 " or nasm -v (or --v) for version info\n\n"
774 " -t assemble in SciTech TASM compatible mode\n"
775 " -g generate debug information in selected format\n");
776 printf
777 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
778 " -a don't preprocess (assemble only)\n"
779 " -M generate Makefile dependencies on stdout\n"
780 " -MG d:o, missing files assumed generated\n"
781 " -MF <file> set Makefile dependency file\n"
782 " -MD <file> assemble and generate dependencies\n"
783 " -MT <file> dependency target name\n"
784 " -MQ <file> dependency target name (quoted)\n"
785 " -MP emit phony target\n\n"
786 " -Z<file> redirect error messages to file\n"
787 " -s redirect error messages to stdout\n\n"
788 " -F format select a debugging format\n\n"
789 " -o outfile write output to an outfile\n\n"
790 " -f format select an output format\n\n"
791 " -l listfile write listing to a listfile\n\n"
792 " -I<path> adds a pathname to the include file path\n");
793 printf
794 (" -O<digit> optimize branch offsets\n"
795 " -O0: No optimization\n"
796 " -O1: Minimal optimization\n"
797 " -Ox: Multipass optimization (default)\n\n"
798 " -P<file> pre-includes a file\n"
799 " -D<macro>[=<value>] pre-defines a macro\n"
800 " -U<macro> undefines a macro\n"
801 " -X<format> specifies error reporting format (gnu or vc)\n"
802 " -w+foo enables warning foo (equiv. -Wfoo)\n"
803 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
804 " -h show invocation summary and exit\n\n"
805 "--prefix,--postfix\n"
806 " this options prepend or append the given argument to all\n"
807 " extern and global variables\n\n"
808 "Warnings:\n");
809 for (i = 0; i <= ERR_WARN_MAX; i++)
810 printf(" %-23s %s (default %s)\n",
811 warnings[i].name, warnings[i].help,
812 warnings[i].enabled ? "on" : "off");
813 printf
814 ("\nresponse files should contain command line parameters"
815 ", one per line.\n");
816 if (p[2] == 'f') {
817 printf("\nvalid output formats for -f are"
818 " (`*' denotes default):\n");
819 ofmt_list(ofmt, stdout);
820 } else {
821 printf("\nFor a list of valid output formats, use -hf.\n");
822 printf("For a list of debug formats, use -f <form> -y.\n");
824 exit(0); /* never need usage message here */
825 break;
827 case 'y':
828 printf("\nvalid debug formats for '%s' output format are"
829 " ('*' denotes default):\n", ofmt->shortname);
830 dfmt_list(ofmt, stdout);
831 exit(0);
832 break;
834 case 't':
835 tasm_compatible_mode = true;
836 break;
838 case 'v':
839 show_version();
840 break;
842 case 'e': /* preprocess only */
843 case 'E':
844 operating_mode = OP_PREPROCESS;
845 break;
847 case 'a': /* assemble only - don't preprocess */
848 preproc = &preproc_nop;
849 break;
851 case 'W':
852 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
853 do_warn = false;
854 param += 3;
855 } else {
856 do_warn = true;
858 goto set_warning;
860 case 'w':
861 if (param[0] != '+' && param[0] != '-') {
862 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
863 "invalid option to `-w'");
864 break;
866 do_warn = (param[0] == '+');
867 param++;
869 set_warning:
870 for (i = 0; i <= ERR_WARN_MAX; i++) {
871 if (!nasm_stricmp(param, warnings[i].name))
872 break;
874 if (i <= ERR_WARN_MAX) {
875 warning_on_global[i] = do_warn;
876 } else if (!nasm_stricmp(param, "all")) {
877 for (i = 1; i <= ERR_WARN_MAX; i++)
878 warning_on_global[i] = do_warn;
879 } else if (!nasm_stricmp(param, "none")) {
880 for (i = 1; i <= ERR_WARN_MAX; i++)
881 warning_on_global[i] = !do_warn;
882 } else {
883 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
884 "invalid warning `%s'", param);
886 break;
888 case 'M':
889 switch (p[2]) {
890 case 0:
891 operating_mode = OP_DEPEND;
892 break;
893 case 'G':
894 operating_mode = OP_DEPEND;
895 depend_missing_ok = true;
896 break;
897 case 'P':
898 depend_emit_phony = true;
899 break;
900 case 'D':
901 operating_mode = OP_NORMAL;
902 depend_file = q;
903 advance = true;
904 break;
905 case 'F':
906 depend_file = q;
907 advance = true;
908 break;
909 case 'T':
910 depend_target = q;
911 advance = true;
912 break;
913 case 'Q':
914 depend_target = quote_for_make(q);
915 advance = true;
916 break;
917 default:
918 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
919 "unknown dependency option `-M%c'", p[2]);
920 break;
922 if (advance && (!q || !q[0])) {
923 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
924 "option `-M%c' requires a parameter", p[2]);
925 break;
927 break;
929 case '-':
931 int s;
933 if (p[2] == 0) { /* -- => stop processing options */
934 stopoptions = 1;
935 break;
938 if (!nasm_stricmp(p, "--v"))
939 show_version();
941 for (s = 0; textopts[s].label; s++) {
942 if (!nasm_stricmp(p + 2, textopts[s].label)) {
943 break;
947 switch (s) {
949 case OPT_PREFIX:
950 case OPT_POSTFIX:
952 if (!q) {
953 nasm_error(ERR_NONFATAL | ERR_NOFILE |
954 ERR_USAGE,
955 "option `--%s' requires an argument",
956 p + 2);
957 break;
958 } else {
959 advance = 1, param = q;
962 if (s == OPT_PREFIX) {
963 strncpy(lprefix, param, PREFIX_MAX - 1);
964 lprefix[PREFIX_MAX - 1] = 0;
965 break;
967 if (s == OPT_POSTFIX) {
968 strncpy(lpostfix, param, POSTFIX_MAX - 1);
969 lpostfix[POSTFIX_MAX - 1] = 0;
970 break;
972 break;
974 default:
976 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
977 "unrecognised option `--%s'", p + 2);
978 break;
981 break;
984 default:
985 if (!ofmt->setinfo(GI_SWITCH, &p))
986 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
987 "unrecognised option `-%c'", p[1]);
988 break;
990 } else {
991 if (*inname) {
992 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
993 "more than one input file specified");
994 } else {
995 copy_filename(inname, p);
999 return advance;
1002 #define ARG_BUF_DELTA 128
1004 static void process_respfile(FILE * rfile)
1006 char *buffer, *p, *q, *prevarg;
1007 int bufsize, prevargsize;
1009 bufsize = prevargsize = ARG_BUF_DELTA;
1010 buffer = nasm_malloc(ARG_BUF_DELTA);
1011 prevarg = nasm_malloc(ARG_BUF_DELTA);
1012 prevarg[0] = '\0';
1014 while (1) { /* Loop to handle all lines in file */
1015 p = buffer;
1016 while (1) { /* Loop to handle long lines */
1017 q = fgets(p, bufsize - (p - buffer), rfile);
1018 if (!q)
1019 break;
1020 p += strlen(p);
1021 if (p > buffer && p[-1] == '\n')
1022 break;
1023 if (p - buffer > bufsize - 10) {
1024 int offset;
1025 offset = p - buffer;
1026 bufsize += ARG_BUF_DELTA;
1027 buffer = nasm_realloc(buffer, bufsize);
1028 p = buffer + offset;
1032 if (!q && p == buffer) {
1033 if (prevarg[0])
1034 process_arg(prevarg, NULL);
1035 nasm_free(buffer);
1036 nasm_free(prevarg);
1037 return;
1041 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1042 * them are present at the end of the line.
1044 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1046 while (p > buffer && nasm_isspace(p[-1]))
1047 *--p = '\0';
1049 p = nasm_skip_spaces(buffer);
1051 if (process_arg(prevarg, p))
1052 *p = '\0';
1054 if ((int) strlen(p) > prevargsize - 10) {
1055 prevargsize += ARG_BUF_DELTA;
1056 prevarg = nasm_realloc(prevarg, prevargsize);
1058 strncpy(prevarg, p, prevargsize);
1062 /* Function to process args from a string of args, rather than the
1063 * argv array. Used by the environment variable and response file
1064 * processing.
1066 static void process_args(char *args)
1068 char *p, *q, *arg, *prevarg;
1069 char separator = ' ';
1071 p = args;
1072 if (*p && *p != '-')
1073 separator = *p++;
1074 arg = NULL;
1075 while (*p) {
1076 q = p;
1077 while (*p && *p != separator)
1078 p++;
1079 while (*p == separator)
1080 *p++ = '\0';
1081 prevarg = arg;
1082 arg = q;
1083 if (process_arg(prevarg, arg))
1084 arg = NULL;
1086 if (arg)
1087 process_arg(arg, NULL);
1090 static void process_response_file(const char *file)
1092 char str[2048];
1093 FILE *f = fopen(file, "r");
1094 if (!f) {
1095 perror(file);
1096 exit(-1);
1098 while (fgets(str, sizeof str, f)) {
1099 process_args(str);
1101 fclose(f);
1104 static void parse_cmdline(int argc, char **argv)
1106 FILE *rfile;
1107 char *envreal, *envcopy = NULL, *p;
1108 int i;
1110 *inname = *outname = *listname = *errname = '\0';
1112 for (i = 0; i <= ERR_WARN_MAX; i++)
1113 warning_on_global[i] = warnings[i].enabled;
1116 * First, process the NASMENV environment variable.
1118 envreal = getenv("NASMENV");
1119 if (envreal) {
1120 envcopy = nasm_strdup(envreal);
1121 process_args(envcopy);
1122 nasm_free(envcopy);
1126 * Now process the actual command line.
1128 while (--argc) {
1129 bool advance;
1130 argv++;
1131 if (argv[0][0] == '@') {
1133 * We have a response file, so process this as a set of
1134 * arguments like the environment variable. This allows us
1135 * to have multiple arguments on a single line, which is
1136 * different to the -@resp file processing below for regular
1137 * NASM.
1139 process_response_file(argv[0]+1);
1140 argc--;
1141 argv++;
1143 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1144 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1145 if (p) {
1146 rfile = fopen(p, "r");
1147 if (rfile) {
1148 process_respfile(rfile);
1149 fclose(rfile);
1150 } else
1151 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1152 "unable to open response file `%s'", p);
1154 } else
1155 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1156 argv += advance, argc -= advance;
1160 * Look for basic command line typos. This definitely doesn't
1161 * catch all errors, but it might help cases of fumbled fingers.
1163 if (!*inname)
1164 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1165 "no input file specified");
1166 else if (!strcmp(inname, errname) ||
1167 !strcmp(inname, outname) ||
1168 !strcmp(inname, listname) ||
1169 (depend_file && !strcmp(inname, depend_file)))
1170 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1171 "file `%s' is both input and output file",
1172 inname);
1174 if (*errname) {
1175 error_file = fopen(errname, "w");
1176 if (!error_file) {
1177 error_file = stderr; /* Revert to default! */
1178 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1179 "cannot open file `%s' for error messages",
1180 errname);
1185 static enum directives getkw(char **directive, char **value);
1187 static void assemble_file(char *fname, StrList **depend_ptr)
1189 char *directive, *value, *p, *q, *special, *line;
1190 insn output_ins;
1191 int i, validid;
1192 bool rn_error;
1193 int32_t seg;
1194 int64_t offs;
1195 struct tokenval tokval;
1196 expr *e;
1197 int pass_max;
1199 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1200 nasm_error(ERR_FATAL, "command line: "
1201 "32-bit segment size requires a higher cpu");
1203 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1204 for (passn = 1; pass0 <= 2; passn++) {
1205 int pass1, pass2;
1206 ldfunc def_label;
1208 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1209 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1210 /* pass0 0, 0, 0, ..., 1, 2 */
1212 def_label = passn > 1 ? redefine_label : define_label;
1214 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1215 cpu = cmd_cpu;
1216 if (pass0 == 2) {
1217 if (*listname)
1218 nasmlist.init(listname, nasm_error);
1220 in_abs_seg = false;
1221 global_offset_changed = 0; /* set by redefine_label */
1222 location.segment = ofmt->section(NULL, pass2, &sb);
1223 globalbits = sb;
1224 if (passn > 1) {
1225 saa_rewind(forwrefs);
1226 forwref = saa_rstruct(forwrefs);
1227 raa_free(offsets);
1228 offsets = raa_init();
1230 preproc->reset(fname, pass1, &nasmlist,
1231 pass1 == 2 ? depend_ptr : NULL);
1232 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1234 globallineno = 0;
1235 if (passn == 1)
1236 location.known = true;
1237 location.offset = offs = get_curr_offs();
1239 while ((line = preproc->getline())) {
1240 enum directives d;
1241 globallineno++;
1244 * Here we parse our directives; this is not handled by the
1245 * 'real' parser. This really should be a separate function.
1247 directive = line;
1248 d = getkw(&directive, &value);
1249 if (d) {
1250 int err = 0;
1252 switch (d) {
1253 case D_SEGMENT: /* [SEGMENT n] */
1254 case D_SECTION:
1255 seg = ofmt->section(value, pass2, &sb);
1256 if (seg == NO_SEG) {
1257 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1258 "segment name `%s' not recognized",
1259 value);
1260 } else {
1261 in_abs_seg = false;
1262 location.segment = seg;
1264 break;
1265 case D_SECTALIGN: /* [SECTALIGN n] */
1266 if (*value) {
1267 stdscan_reset();
1268 stdscan_set(value);
1269 tokval.t_type = TOKEN_INVALID;
1270 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1271 if (e) {
1272 unsigned int align = (unsigned int)e->value;
1273 if ((uint64_t)e->value > 0x7fffffff) {
1275 * FIXME: Please make some sane message here
1276 * ofmt should have some 'check' method which
1277 * would report segment alignment bounds.
1279 nasm_error(ERR_FATAL,
1280 "incorrect segment alignment `%s'", value);
1281 } else if (!is_power2(align)) {
1282 nasm_error(ERR_NONFATAL,
1283 "segment alignment `%s' is not power of two",
1284 value);
1286 /* callee should be able to handle all details */
1287 ofmt->sectalign(location.segment, align);
1290 break;
1291 case D_EXTERN: /* [EXTERN label:special] */
1292 if (*value == '$')
1293 value++; /* skip initial $ if present */
1294 if (pass0 == 2) {
1295 q = value;
1296 while (*q && *q != ':')
1297 q++;
1298 if (*q == ':') {
1299 *q++ = '\0';
1300 ofmt->symdef(value, 0L, 0L, 3, q);
1302 } else if (passn == 1) {
1303 q = value;
1304 validid = true;
1305 if (!isidstart(*q))
1306 validid = false;
1307 while (*q && *q != ':') {
1308 if (!isidchar(*q))
1309 validid = false;
1310 q++;
1312 if (!validid) {
1313 nasm_error(ERR_NONFATAL,
1314 "identifier expected after EXTERN");
1315 break;
1317 if (*q == ':') {
1318 *q++ = '\0';
1319 special = q;
1320 } else
1321 special = NULL;
1322 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1323 int temp = pass0;
1324 pass0 = 1; /* fake pass 1 in labels.c */
1325 declare_as_global(value, special);
1326 define_label(value, seg_alloc(), 0L, NULL,
1327 false, true);
1328 pass0 = temp;
1330 } /* else pass0 == 1 */
1331 break;
1332 case D_BITS: /* [BITS bits] */
1333 globalbits = sb = get_bits(value);
1334 break;
1335 case D_GLOBAL: /* [GLOBAL symbol:special] */
1336 if (*value == '$')
1337 value++; /* skip initial $ if present */
1338 if (pass0 == 2) { /* pass 2 */
1339 q = value;
1340 while (*q && *q != ':')
1341 q++;
1342 if (*q == ':') {
1343 *q++ = '\0';
1344 ofmt->symdef(value, 0L, 0L, 3, q);
1346 } else if (pass2 == 1) { /* pass == 1 */
1347 q = value;
1348 validid = true;
1349 if (!isidstart(*q))
1350 validid = false;
1351 while (*q && *q != ':') {
1352 if (!isidchar(*q))
1353 validid = false;
1354 q++;
1356 if (!validid) {
1357 nasm_error(ERR_NONFATAL,
1358 "identifier expected after GLOBAL");
1359 break;
1361 if (*q == ':') {
1362 *q++ = '\0';
1363 special = q;
1364 } else
1365 special = NULL;
1366 declare_as_global(value, special);
1367 } /* pass == 1 */
1368 break;
1369 case D_COMMON: /* [COMMON symbol size:special] */
1371 int64_t size;
1373 if (*value == '$')
1374 value++; /* skip initial $ if present */
1375 p = value;
1376 validid = true;
1377 if (!isidstart(*p))
1378 validid = false;
1379 while (*p && !nasm_isspace(*p)) {
1380 if (!isidchar(*p))
1381 validid = false;
1382 p++;
1384 if (!validid) {
1385 nasm_error(ERR_NONFATAL,
1386 "identifier expected after COMMON");
1387 break;
1389 if (*p) {
1390 p = nasm_zap_spaces_fwd(p);
1391 q = p;
1392 while (*q && *q != ':')
1393 q++;
1394 if (*q == ':') {
1395 *q++ = '\0';
1396 special = q;
1397 } else {
1398 special = NULL;
1400 size = readnum(p, &rn_error);
1401 if (rn_error) {
1402 nasm_error(ERR_NONFATAL,
1403 "invalid size specified"
1404 " in COMMON declaration");
1405 break;
1407 } else {
1408 nasm_error(ERR_NONFATAL,
1409 "no size specified in"
1410 " COMMON declaration");
1411 break;
1414 if (pass0 < 2) {
1415 define_common(value, seg_alloc(), size, special);
1416 } else if (pass0 == 2) {
1417 if (special)
1418 ofmt->symdef(value, 0L, 0L, 3, special);
1420 break;
1422 case D_ABSOLUTE: /* [ABSOLUTE address] */
1423 stdscan_reset();
1424 stdscan_set(value);
1425 tokval.t_type = TOKEN_INVALID;
1426 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1427 nasm_error, NULL);
1428 if (e) {
1429 if (!is_reloc(e))
1430 nasm_error(pass0 ==
1431 1 ? ERR_NONFATAL : ERR_PANIC,
1432 "cannot use non-relocatable expression as "
1433 "ABSOLUTE address");
1434 else {
1435 abs_seg = reloc_seg(e);
1436 abs_offset = reloc_value(e);
1438 } else if (passn == 1)
1439 abs_offset = 0x100; /* don't go near zero in case of / */
1440 else
1441 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1442 "in pass two");
1443 in_abs_seg = true;
1444 location.segment = NO_SEG;
1445 break;
1446 case D_DEBUG: /* [DEBUG] */
1448 char debugid[128];
1449 bool badid, overlong;
1451 p = value;
1452 q = debugid;
1453 badid = overlong = false;
1454 if (!isidstart(*p)) {
1455 badid = true;
1456 } else {
1457 while (*p && !nasm_isspace(*p)) {
1458 if (q >= debugid + sizeof debugid - 1) {
1459 overlong = true;
1460 break;
1462 if (!isidchar(*p))
1463 badid = true;
1464 *q++ = *p++;
1466 *q = 0;
1468 if (badid) {
1469 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1470 "identifier expected after DEBUG");
1471 break;
1473 if (overlong) {
1474 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1475 "DEBUG identifier too long");
1476 break;
1478 p = nasm_skip_spaces(p);
1479 if (pass0 == 2)
1480 dfmt->debug_directive(debugid, p);
1481 break;
1483 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1484 value = nasm_skip_spaces(value);
1485 switch(*value) {
1486 case '-': validid = 0; value++; break;
1487 case '+': validid = 1; value++; break;
1488 case '*': validid = 2; value++; break;
1489 default: validid = 1; break;
1492 for (i = 1; i <= ERR_WARN_MAX; i++)
1493 if (!nasm_stricmp(value, warnings[i].name))
1494 break;
1495 if (i <= ERR_WARN_MAX) {
1496 switch(validid) {
1497 case 0:
1498 warning_on[i] = false;
1499 break;
1500 case 1:
1501 warning_on[i] = true;
1502 break;
1503 case 2:
1504 warning_on[i] = warning_on_global[i];
1505 break;
1507 } else
1508 nasm_error(ERR_NONFATAL,
1509 "invalid warning id in WARNING directive");
1510 break;
1511 case D_CPU: /* [CPU] */
1512 cpu = get_cpu(value);
1513 break;
1514 case D_LIST: /* [LIST {+|-}] */
1515 value = nasm_skip_spaces(value);
1516 if (*value == '+') {
1517 user_nolist = 0;
1518 } else {
1519 if (*value == '-') {
1520 user_nolist = 1;
1521 } else {
1522 err = 1;
1525 break;
1526 case D_DEFAULT: /* [DEFAULT] */
1527 stdscan_reset();
1528 stdscan_set(value);
1529 tokval.t_type = TOKEN_INVALID;
1530 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1531 switch ((int)tokval.t_integer) {
1532 case S_REL:
1533 globalrel = 1;
1534 break;
1535 case S_ABS:
1536 globalrel = 0;
1537 break;
1538 case P_BND:
1539 globalbnd = 1;
1540 break;
1541 case P_NOBND:
1542 globalbnd = 0;
1543 break;
1544 default:
1545 err = 1;
1546 break;
1548 } else {
1549 err = 1;
1551 break;
1552 case D_FLOAT:
1553 if (float_option(value)) {
1554 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1555 "unknown 'float' directive: %s",
1556 value);
1558 break;
1559 default:
1560 if (ofmt->directive(d, value, pass2))
1561 break;
1562 /* else fall through */
1563 case D_unknown:
1564 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1565 "unrecognised directive [%s]",
1566 directive);
1567 break;
1569 if (err) {
1570 nasm_error(ERR_NONFATAL,
1571 "invalid parameter to [%s] directive",
1572 directive);
1574 } else { /* it isn't a directive */
1575 parse_line(pass1, line, &output_ins, def_label);
1577 if (optimizing > 0) {
1578 if (forwref != NULL && globallineno == forwref->lineno) {
1579 output_ins.forw_ref = true;
1580 do {
1581 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1582 forwref = saa_rstruct(forwrefs);
1583 } while (forwref != NULL
1584 && forwref->lineno == globallineno);
1585 } else
1586 output_ins.forw_ref = false;
1588 if (output_ins.forw_ref) {
1589 if (passn == 1) {
1590 for (i = 0; i < output_ins.operands; i++) {
1591 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1592 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1593 fwinf->lineno = globallineno;
1594 fwinf->operand = i;
1601 /* forw_ref */
1602 if (output_ins.opcode == I_EQU) {
1603 if (pass1 == 1) {
1605 * Special `..' EQUs get processed in pass two,
1606 * except `..@' macro-processor EQUs which are done
1607 * in the normal place.
1609 if (!output_ins.label)
1610 nasm_error(ERR_NONFATAL,
1611 "EQU not preceded by label");
1613 else if (output_ins.label[0] != '.' ||
1614 output_ins.label[1] != '.' ||
1615 output_ins.label[2] == '@') {
1616 if (output_ins.operands == 1 &&
1617 (output_ins.oprs[0].type & IMMEDIATE) &&
1618 output_ins.oprs[0].wrt == NO_SEG) {
1619 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1620 def_label(output_ins.label,
1621 output_ins.oprs[0].segment,
1622 output_ins.oprs[0].offset, NULL,
1623 false, isext);
1624 } else if (output_ins.operands == 2
1625 && (output_ins.oprs[0].type & IMMEDIATE)
1626 && (output_ins.oprs[0].type & COLON)
1627 && output_ins.oprs[0].segment == NO_SEG
1628 && output_ins.oprs[0].wrt == NO_SEG
1629 && (output_ins.oprs[1].type & IMMEDIATE)
1630 && output_ins.oprs[1].segment == NO_SEG
1631 && output_ins.oprs[1].wrt == NO_SEG) {
1632 def_label(output_ins.label,
1633 output_ins.oprs[0].offset | SEG_ABS,
1634 output_ins.oprs[1].offset,
1635 NULL, false, false);
1636 } else
1637 nasm_error(ERR_NONFATAL,
1638 "bad syntax for EQU");
1640 } else {
1642 * Special `..' EQUs get processed here, except
1643 * `..@' macro processor EQUs which are done above.
1645 if (output_ins.label[0] == '.' &&
1646 output_ins.label[1] == '.' &&
1647 output_ins.label[2] != '@') {
1648 if (output_ins.operands == 1 &&
1649 (output_ins.oprs[0].type & IMMEDIATE)) {
1650 define_label(output_ins.label,
1651 output_ins.oprs[0].segment,
1652 output_ins.oprs[0].offset,
1653 NULL, false, false);
1654 } else if (output_ins.operands == 2
1655 && (output_ins.oprs[0].type & IMMEDIATE)
1656 && (output_ins.oprs[0].type & COLON)
1657 && output_ins.oprs[0].segment == NO_SEG
1658 && (output_ins.oprs[1].type & IMMEDIATE)
1659 && output_ins.oprs[1].segment == NO_SEG) {
1660 define_label(output_ins.label,
1661 output_ins.oprs[0].offset | SEG_ABS,
1662 output_ins.oprs[1].offset,
1663 NULL, false, false);
1664 } else
1665 nasm_error(ERR_NONFATAL,
1666 "bad syntax for EQU");
1669 } else { /* instruction isn't an EQU */
1671 if (pass1 == 1) {
1673 int64_t l = insn_size(location.segment, offs, sb, cpu,
1674 &output_ins, nasm_error);
1676 /* if (using_debug_info) && output_ins.opcode != -1) */
1677 if (using_debug_info)
1678 { /* fbk 03/25/01 */
1679 /* this is done here so we can do debug type info */
1680 int32_t typeinfo =
1681 TYS_ELEMENTS(output_ins.operands);
1682 switch (output_ins.opcode) {
1683 case I_RESB:
1684 typeinfo =
1685 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1686 break;
1687 case I_RESW:
1688 typeinfo =
1689 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1690 break;
1691 case I_RESD:
1692 typeinfo =
1693 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1694 break;
1695 case I_RESQ:
1696 typeinfo =
1697 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1698 break;
1699 case I_REST:
1700 typeinfo =
1701 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1702 break;
1703 case I_RESO:
1704 typeinfo =
1705 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1706 break;
1707 case I_RESY:
1708 typeinfo =
1709 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1710 break;
1711 case I_DB:
1712 typeinfo |= TY_BYTE;
1713 break;
1714 case I_DW:
1715 typeinfo |= TY_WORD;
1716 break;
1717 case I_DD:
1718 if (output_ins.eops_float)
1719 typeinfo |= TY_FLOAT;
1720 else
1721 typeinfo |= TY_DWORD;
1722 break;
1723 case I_DQ:
1724 typeinfo |= TY_QWORD;
1725 break;
1726 case I_DT:
1727 typeinfo |= TY_TBYTE;
1728 break;
1729 case I_DO:
1730 typeinfo |= TY_OWORD;
1731 break;
1732 case I_DY:
1733 typeinfo |= TY_YWORD;
1734 break;
1735 default:
1736 typeinfo = TY_LABEL;
1740 dfmt->debug_typevalue(typeinfo);
1742 if (l != -1) {
1743 offs += l;
1744 set_curr_offs(offs);
1747 * else l == -1 => invalid instruction, which will be
1748 * flagged as an error on pass 2
1751 } else {
1752 offs += assemble(location.segment, offs, sb, cpu,
1753 &output_ins, ofmt, nasm_error,
1754 &nasmlist);
1755 set_curr_offs(offs);
1758 } /* not an EQU */
1759 cleanup_insn(&output_ins);
1761 nasm_free(line);
1762 location.offset = offs = get_curr_offs();
1763 } /* end while (line = preproc->getline... */
1765 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1766 nasm_error(ERR_NONFATAL,
1767 "phase error detected at end of assembly.");
1769 if (pass1 == 1)
1770 preproc->cleanup(1);
1772 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1773 pass0++;
1774 } else if (global_offset_changed &&
1775 global_offset_changed < prev_offset_changed) {
1776 prev_offset_changed = global_offset_changed;
1777 stall_count = 0;
1778 } else {
1779 stall_count++;
1782 if (terminate_after_phase)
1783 break;
1785 if ((stall_count > 997) || (passn >= pass_max)) {
1786 /* We get here if the labels don't converge
1787 * Example: FOO equ FOO + 1
1789 nasm_error(ERR_NONFATAL,
1790 "Can't find valid values for all labels "
1791 "after %d passes, giving up.", passn);
1792 nasm_error(ERR_NONFATAL,
1793 "Possible causes: recursive EQUs, macro abuse.");
1794 break;
1798 preproc->cleanup(0);
1799 nasmlist.cleanup();
1800 if (!terminate_after_phase && opt_verbose_info) {
1801 /* -On and -Ov switches */
1802 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1806 static enum directives getkw(char **directive, char **value)
1808 char *p, *q, *buf;
1810 buf = nasm_skip_spaces(*directive);
1812 /* it should be enclosed in [ ] */
1813 if (*buf != '[')
1814 return D_none;
1815 q = strchr(buf, ']');
1816 if (!q)
1817 return D_none;
1819 /* stip off the comments */
1820 p = strchr(buf, ';');
1821 if (p) {
1822 if (p < q) /* ouch! somwhere inside */
1823 return D_none;
1824 *p = '\0';
1827 /* no brace, no trailing spaces */
1828 *q = '\0';
1829 nasm_zap_spaces_rev(--q);
1831 /* directive */
1832 p = nasm_skip_spaces(++buf);
1833 q = nasm_skip_word(p);
1834 if (!q)
1835 return D_none; /* sigh... no value there */
1836 *q = '\0';
1837 *directive = p;
1839 /* and value finally */
1840 p = nasm_skip_spaces(++q);
1841 *value = p;
1843 return find_directive(*directive);
1847 * gnu style error reporting
1848 * This function prints an error message to error_file in the
1849 * style used by GNU. An example would be:
1850 * file.asm:50: error: blah blah blah
1851 * where file.asm is the name of the file, 50 is the line number on
1852 * which the error occurs (or is detected) and "error:" is one of
1853 * the possible optional diagnostics -- it can be "error" or "warning"
1854 * or something else. Finally the line terminates with the actual
1855 * error message.
1857 * @param severity the severity of the warning or error
1858 * @param fmt the printf style format string
1860 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1862 char *currentfile = NULL;
1863 int32_t lineno = 0;
1865 if (is_suppressed_warning(severity))
1866 return;
1868 if (!(severity & ERR_NOFILE))
1869 src_get(&lineno, &currentfile);
1871 if (currentfile) {
1872 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1873 nasm_free(currentfile);
1874 } else {
1875 fputs("nasm: ", error_file);
1878 nasm_verror_common(severity, fmt, ap);
1882 * MS style error reporting
1883 * This function prints an error message to error_file in the
1884 * style used by Visual C and some other Microsoft tools. An example
1885 * would be:
1886 * file.asm(50) : error: blah blah blah
1887 * where file.asm is the name of the file, 50 is the line number on
1888 * which the error occurs (or is detected) and "error:" is one of
1889 * the possible optional diagnostics -- it can be "error" or "warning"
1890 * or something else. Finally the line terminates with the actual
1891 * error message.
1893 * @param severity the severity of the warning or error
1894 * @param fmt the printf style format string
1896 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1898 char *currentfile = NULL;
1899 int32_t lineno = 0;
1901 if (is_suppressed_warning(severity))
1902 return;
1904 if (!(severity & ERR_NOFILE))
1905 src_get(&lineno, &currentfile);
1907 if (currentfile) {
1908 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1909 nasm_free(currentfile);
1910 } else {
1911 fputs("nasm: ", error_file);
1914 nasm_verror_common(severity, fmt, ap);
1918 * check for supressed warning
1919 * checks for suppressed warning or pass one only warning and we're
1920 * not in pass 1
1922 * @param severity the severity of the warning or error
1923 * @return true if we should abort error/warning printing
1925 static bool is_suppressed_warning(int severity)
1927 /* Not a warning at all */
1928 if ((severity & ERR_MASK) != ERR_WARNING)
1929 return false;
1931 /* See if it's a pass-one only warning and we're not in pass one. */
1932 if (((severity & ERR_PASS1) && pass0 != 1) ||
1933 ((severity & ERR_PASS2) && pass0 != 2))
1934 return true;
1936 /* Might be a warning but suppresed explicitly */
1937 if (severity & ERR_WARN_MASK)
1938 return !warning_on[WARN_IDX(severity)];
1939 else
1940 return false;
1944 * common error reporting
1945 * This is the common back end of the error reporting schemes currently
1946 * implemented. It prints the nature of the warning and then the
1947 * specific error message to error_file and may or may not return. It
1948 * doesn't return if the error severity is a "panic" or "debug" type.
1950 * @param severity the severity of the warning or error
1951 * @param fmt the printf style format string
1953 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1955 char msg[1024];
1956 const char *pfx;
1958 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1959 case ERR_WARNING:
1960 pfx = "warning: ";
1961 break;
1962 case ERR_NONFATAL:
1963 pfx = "error: ";
1964 break;
1965 case ERR_FATAL:
1966 pfx = "fatal: ";
1967 break;
1968 case ERR_PANIC:
1969 pfx = "panic: ";
1970 break;
1971 case ERR_DEBUG:
1972 pfx = "debug: ";
1973 break;
1974 default:
1975 pfx = "";
1976 break;
1979 vsnprintf(msg, sizeof msg, fmt, args);
1981 fprintf(error_file, "%s%s\n", pfx, msg);
1983 if (*listname)
1984 nasmlist.error(severity, pfx, msg);
1986 if (severity & ERR_USAGE)
1987 want_usage = true;
1989 switch (severity & ERR_MASK) {
1990 case ERR_DEBUG:
1991 /* no further action, by definition */
1992 break;
1993 case ERR_WARNING:
1994 /* Treat warnings as errors */
1995 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
1996 terminate_after_phase = true;
1997 break;
1998 case ERR_NONFATAL:
1999 terminate_after_phase = true;
2000 break;
2001 case ERR_FATAL:
2002 if (ofile) {
2003 fclose(ofile);
2004 remove(outname);
2005 ofile = NULL;
2007 if (want_usage)
2008 usage();
2009 exit(1); /* instantly die */
2010 break; /* placate silly compilers */
2011 case ERR_PANIC:
2012 fflush(NULL);
2013 /* abort(); */ /* halt, catch fire, and dump core */
2014 exit(3);
2015 break;
2019 static void usage(void)
2021 fputs("type `nasm -h' for help\n", error_file);
2024 static iflag_t get_cpu(char *value)
2026 iflag_t r;
2028 iflag_clear_all(&r);
2030 if (!strcmp(value, "8086"))
2031 iflag_set(&r, IF_8086);
2032 else if (!strcmp(value, "186"))
2033 iflag_set(&r, IF_186);
2034 else if (!strcmp(value, "286"))
2035 iflag_set(&r, IF_286);
2036 else if (!strcmp(value, "386"))
2037 iflag_set(&r, IF_386);
2038 else if (!strcmp(value, "486"))
2039 iflag_set(&r, IF_486);
2040 else if (!strcmp(value, "586") ||
2041 !nasm_stricmp(value, "pentium"))
2042 iflag_set(&r, IF_PENT);
2043 else if (!strcmp(value, "686") ||
2044 !nasm_stricmp(value, "ppro") ||
2045 !nasm_stricmp(value, "pentiumpro") ||
2046 !nasm_stricmp(value, "p2"))
2047 iflag_set(&r, IF_P6);
2048 else if (!nasm_stricmp(value, "p3") ||
2049 !nasm_stricmp(value, "katmai"))
2050 iflag_set(&r, IF_KATMAI);
2051 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2052 !nasm_stricmp(value, "willamette"))
2053 iflag_set(&r, IF_WILLAMETTE);
2054 else if (!nasm_stricmp(value, "prescott"))
2055 iflag_set(&r, IF_PRESCOTT);
2056 else if (!nasm_stricmp(value, "x64") ||
2057 !nasm_stricmp(value, "x86-64"))
2058 iflag_set(&r, IF_X86_64);
2059 else if (!nasm_stricmp(value, "ia64") ||
2060 !nasm_stricmp(value, "ia-64") ||
2061 !nasm_stricmp(value, "itanium")||
2062 !nasm_stricmp(value, "itanic") ||
2063 !nasm_stricmp(value, "merced"))
2064 iflag_set(&r, IF_IA64);
2065 else {
2066 iflag_set(&r, IF_PLEVEL);
2067 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2068 "unknown 'cpu' type");
2070 return r;
2073 static int get_bits(char *value)
2075 int i;
2077 if ((i = atoi(value)) == 16)
2078 return i; /* set for a 16-bit segment */
2079 else if (i == 32) {
2080 if (iflag_ffs(&cpu) < IF_386) {
2081 nasm_error(ERR_NONFATAL,
2082 "cannot specify 32-bit segment on processor below a 386");
2083 i = 16;
2085 } else if (i == 64) {
2086 if (iflag_ffs(&cpu) < IF_X86_64) {
2087 nasm_error(ERR_NONFATAL,
2088 "cannot specify 64-bit segment on processor below an x86-64");
2089 i = 16;
2091 if (i != maxbits) {
2092 nasm_error(ERR_NONFATAL,
2093 "%s output format does not support 64-bit code",
2094 ofmt->shortname);
2095 i = 16;
2097 } else {
2098 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2099 "`%s' is not a valid segment size; must be 16, 32 or 64",
2100 value);
2101 i = 16;
2103 return i;