preproc: add plumbing for the %pragma directive
[nasm.git] / asm / nasm.c
blobfc6d7194ace6524aca80e709156311afdfe4ce69
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2016 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 <limits.h>
46 #include <time.h>
48 #include "nasm.h"
49 #include "nasmlib.h"
50 #include "saa.h"
51 #include "raa.h"
52 #include "float.h"
53 #include "stdscan.h"
54 #include "insns.h"
55 #include "preproc.h"
56 #include "parser.h"
57 #include "eval.h"
58 #include "assemble.h"
59 #include "labels.h"
60 #include "outform.h"
61 #include "listing.h"
62 #include "iflag.h"
63 #include "ver.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 **, int);
80 static void assemble_file(char *, StrList **);
81 static bool is_suppressed_warning(int severity);
82 static bool skip_this_pass(int severity);
83 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
84 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
85 static void nasm_verror_common(int severity, const char *fmt, va_list args);
86 static void usage(void);
88 static bool using_debug_info, opt_verbose_info;
89 static const char *debug_format;
91 bool tasm_compatible_mode = false;
92 int pass0, passn;
93 int globalrel = 0;
94 int globalbnd = 0;
96 static time_t official_compile_time;
98 static char inname[FILENAME_MAX];
99 static char outname[FILENAME_MAX];
100 static char listname[FILENAME_MAX];
101 static char errname[FILENAME_MAX];
102 static int globallineno; /* for forward-reference tracking */
103 /* static int pass = 0; */
104 const struct ofmt *ofmt = &OF_DEFAULT;
105 const struct ofmt_alias *ofmt_alias = NULL;
106 const struct dfmt *dfmt;
108 static FILE *error_file; /* Where to write error messages */
110 FILE *ofile = NULL;
111 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
112 static int sb, cmd_sb = 16; /* by default */
114 static iflag_t cpu;
115 static iflag_t cmd_cpu;
117 int64_t global_offset_changed; /* referenced in labels.c */
118 int64_t prev_offset_changed;
119 int32_t stall_count;
121 struct location location;
122 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
123 int32_t abs_seg; /* ABSOLUTE segment basis */
124 int32_t abs_offset; /* ABSOLUTE offset */
126 static struct RAA *offsets;
128 static struct SAA *forwrefs; /* keep track of forward references */
129 static const struct forwrefinfo *forwref;
131 static const struct preproc_ops *preproc;
133 #define OP_NORMAL (1u << 0)
134 #define OP_PREPROCESS (1u << 1)
135 #define OP_DEPEND (1u << 2)
137 static unsigned int operating_mode;
139 /* Dependency flags */
140 static bool depend_emit_phony = false;
141 static bool depend_missing_ok = false;
142 static const char *depend_target = NULL;
143 static const char *depend_file = NULL;
146 * Which of the suppressible warnings are suppressed. Entry zero
147 * isn't an actual warning, but it used for -w+error/-Werror.
150 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
151 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
153 static const struct warning {
154 const char *name;
155 const char *help;
156 bool enabled;
157 } warnings[ERR_WARN_MAX+1] = {
158 {"error", "treat warnings as errors", false},
159 {"macro-params", "macro calls with wrong parameter count", true},
160 {"macro-selfref", "cyclic macro references", false},
161 {"macro-defaults", "macros with more default than optional parameters", true},
162 {"orphan-labels", "labels alone on lines without trailing `:'", true},
163 {"number-overflow", "numeric constant does not fit", true},
164 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
165 {"float-overflow", "floating point overflow", true},
166 {"float-denorm", "floating point denormal", false},
167 {"float-underflow", "floating point underflow", false},
168 {"float-toolong", "too many digits in floating-point number", true},
169 {"user", "%warning directives", true},
170 {"lock", "lock prefix on unlockable instructions", true},
171 {"hle", "invalid hle prefixes", true},
172 {"bnd", "invalid bnd prefixes", true},
173 {"zext-reloc", "relocation zero-extended to match output format", true},
174 {"ptr", "non-NASM keyword used in other assemblers", true},
177 static bool want_usage;
178 static bool terminate_after_phase;
179 bool user_nolist = false;
181 static char *quote_for_make(const char *str);
183 static int64_t get_curr_offs(void)
185 return in_abs_seg ? abs_offset : raa_read(offsets, location.segment);
188 static void set_curr_offs(int64_t l_off)
190 if (in_abs_seg)
191 abs_offset = l_off;
192 else
193 offsets = raa_write(offsets, location.segment, l_off);
196 static void nasm_fputs(const char *line, FILE * outfile)
198 if (outfile) {
199 fputs(line, outfile);
200 putc('\n', outfile);
201 } else
202 puts(line);
205 /* Convert a struct tm to a POSIX-style time constant */
206 static int64_t make_posix_time(struct tm *tm)
208 int64_t t;
209 int64_t y = tm->tm_year;
211 /* See IEEE 1003.1:2004, section 4.14 */
213 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
214 t += tm->tm_yday;
215 t *= 24;
216 t += tm->tm_hour;
217 t *= 60;
218 t += tm->tm_min;
219 t *= 60;
220 t += tm->tm_sec;
222 return t;
225 static void define_macros_early(void)
227 char temp[128];
228 struct tm lt, *lt_p, gm, *gm_p;
229 int64_t posix_time;
231 lt_p = localtime(&official_compile_time);
232 if (lt_p) {
233 lt = *lt_p;
235 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
236 preproc->pre_define(temp);
237 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
238 preproc->pre_define(temp);
239 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
240 preproc->pre_define(temp);
241 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
242 preproc->pre_define(temp);
245 gm_p = gmtime(&official_compile_time);
246 if (gm_p) {
247 gm = *gm_p;
249 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
250 preproc->pre_define(temp);
251 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
252 preproc->pre_define(temp);
253 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
254 preproc->pre_define(temp);
255 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
256 preproc->pre_define(temp);
259 if (gm_p)
260 posix_time = make_posix_time(&gm);
261 else if (lt_p)
262 posix_time = make_posix_time(&lt);
263 else
264 posix_time = 0;
266 if (posix_time) {
267 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
268 preproc->pre_define(temp);
272 static void define_macros_late(void)
274 char temp[128];
277 * In case if output format is defined by alias
278 * we have to put shortname of the alias itself here
279 * otherwise ABI backward compatibility gets broken.
281 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
282 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
283 preproc->pre_define(temp);
286 static void emit_dependencies(StrList *list)
288 FILE *deps;
289 int linepos, len;
290 StrList *l, *nl;
292 if (depend_file && strcmp(depend_file, "-")) {
293 deps = nasm_open_write(depend_file, NF_TEXT);
294 if (!deps) {
295 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
296 "unable to write dependency file `%s'", depend_file);
297 return;
299 } else {
300 deps = stdout;
303 linepos = fprintf(deps, "%s:", depend_target);
304 list_for_each(l, list) {
305 char *file = quote_for_make(l->str);
306 len = strlen(file);
307 if (linepos + len > 62 && linepos > 1) {
308 fprintf(deps, " \\\n ");
309 linepos = 1;
311 fprintf(deps, " %s", file);
312 linepos += len+1;
313 nasm_free(file);
315 fprintf(deps, "\n\n");
317 list_for_each_safe(l, nl, list) {
318 if (depend_emit_phony)
319 fprintf(deps, "%s:\n\n", l->str);
320 nasm_free(l);
323 if (deps != stdout)
324 fclose(deps);
327 int main(int argc, char **argv)
329 StrList *depend_list = NULL, **depend_ptr;
331 time(&official_compile_time);
333 iflag_set(&cpu, IF_PLEVEL);
334 iflag_set(&cmd_cpu, IF_PLEVEL);
336 pass0 = 0;
337 want_usage = terminate_after_phase = false;
338 nasm_set_verror(nasm_verror_gnu);
340 error_file = stderr;
342 tolower_init();
343 src_init();
345 offsets = raa_init();
346 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
348 preproc = &nasmpp;
349 operating_mode = OP_NORMAL;
351 parse_cmdline(argc, argv, 1);
352 if (terminate_after_phase) {
353 if (want_usage)
354 usage();
355 return 1;
359 * Define some macros dependent on the runtime, but not
360 * on the command line (as those are scanned in cmdline pass 2.)
362 preproc->init();
363 define_macros_early();
365 parse_cmdline(argc, argv, 2);
366 if (terminate_after_phase) {
367 if (want_usage)
368 usage();
369 return 1;
372 if (!using_debug_info) {
373 /* No debug info, redirect to the null backend (empty stubs) */
374 dfmt = &null_debug_form;
375 } else if (!debug_format) {
376 /* Default debug format for this backend */
377 dfmt = ofmt->default_dfmt;
378 } else {
379 dfmt = dfmt_find(ofmt, debug_format);
380 if (!dfmt) {
381 nasm_fatal(ERR_NOFILE | ERR_USAGE,
382 "unrecognized debug format `%s' for"
383 " output format `%s'",
384 debug_format, ofmt->shortname);
388 if (ofmt->stdmac)
389 preproc->extra_stdmac(ofmt->stdmac);
391 /* define some macros dependent of command-line */
392 define_macros_late();
394 depend_ptr = (depend_file || (operating_mode & OP_DEPEND)) ? &depend_list : NULL;
395 if (!depend_target)
396 depend_target = quote_for_make(outname);
398 if (operating_mode & OP_DEPEND) {
399 char *line;
401 if (depend_missing_ok)
402 preproc->include_path(NULL); /* "assume generated" */
404 preproc->reset(inname, 0, depend_ptr);
405 if (outname[0] == '\0')
406 ofmt->filename(inname, outname);
407 ofile = NULL;
408 while ((line = preproc->getline()))
409 nasm_free(line);
410 preproc->cleanup(0);
411 } else if (operating_mode & OP_PREPROCESS) {
412 char *line;
413 const char *file_name = NULL;
414 int32_t prior_linnum = 0;
415 int lineinc = 0;
417 if (*outname) {
418 ofile = nasm_open_write(outname, NF_TEXT);
419 if (!ofile)
420 nasm_fatal(ERR_NOFILE,
421 "unable to open output file `%s'",
422 outname);
423 } else
424 ofile = NULL;
426 location.known = false;
428 /* pass = 1; */
429 preproc->reset(inname, 3, depend_ptr);
430 memcpy(warning_on, warning_on_global,
431 (ERR_WARN_MAX+1) * sizeof(bool));
433 while ((line = preproc->getline())) {
435 * We generate %line directives if needed for later programs
437 int32_t linnum = prior_linnum += lineinc;
438 int altline = src_get(&linnum, &file_name);
439 if (altline) {
440 if (altline == 1 && lineinc == 1)
441 nasm_fputs("", ofile);
442 else {
443 lineinc = (altline != -1 || lineinc != 1);
444 fprintf(ofile ? ofile : stdout,
445 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
446 file_name);
448 prior_linnum = linnum;
450 nasm_fputs(line, ofile);
451 nasm_free(line);
453 preproc->cleanup(0);
454 if (ofile)
455 fclose(ofile);
456 if (ofile && terminate_after_phase)
457 remove(outname);
458 ofile = NULL;
461 if (operating_mode & OP_NORMAL) {
463 * We must call ofmt->filename _anyway_, even if the user
464 * has specified their own output file, because some
465 * formats (eg OBJ and COFF) use ofmt->filename to find out
466 * the name of the input file and then put that inside the
467 * file.
469 ofmt->filename(inname, outname);
471 ofile = nasm_open_write(outname, (ofmt->flags & OFMT_TEXT) ? NF_TEXT : NF_BINARY);
472 if (!ofile)
473 nasm_fatal(ERR_NOFILE,
474 "unable to open output file `%s'", outname);
477 * We must call init_labels() before ofmt->init() since
478 * some object formats will want to define labels in their
479 * init routines. (eg OS/2 defines the FLAT group)
481 init_labels();
483 ofmt->init();
484 dfmt->init();
486 assemble_file(inname, depend_ptr);
488 if (!terminate_after_phase) {
489 ofmt->cleanup();
490 cleanup_labels();
491 fflush(ofile);
492 if (ferror(ofile)) {
493 nasm_error(ERR_NONFATAL|ERR_NOFILE,
494 "write error on output file `%s'", outname);
495 terminate_after_phase = true;
499 if (ofile) {
500 fclose(ofile);
501 if (terminate_after_phase)
502 remove(outname);
503 ofile = NULL;
507 if (depend_list && !terminate_after_phase)
508 emit_dependencies(depend_list);
510 if (want_usage)
511 usage();
513 raa_free(offsets);
514 saa_free(forwrefs);
515 eval_cleanup();
516 stdscan_cleanup();
517 src_free();
519 return terminate_after_phase;
523 * Get a parameter for a command line option.
524 * First arg must be in the form of e.g. -f...
526 static char *get_param(char *p, char *q, bool *advance)
528 *advance = false;
529 if (p[2]) /* the parameter's in the option */
530 return nasm_skip_spaces(p + 2);
531 if (q && q[0]) {
532 *advance = true;
533 return q;
535 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
536 "option `-%c' requires an argument", p[1]);
537 return NULL;
541 * Copy a filename
543 static void copy_filename(char *dst, const char *src)
545 size_t len = strlen(src);
547 if (len >= (size_t)FILENAME_MAX) {
548 nasm_fatal(ERR_NOFILE, "file name too long");
549 return;
551 strncpy(dst, src, FILENAME_MAX);
555 * Convert a string to Make-safe form
557 static char *quote_for_make(const char *str)
559 const char *p;
560 char *os, *q;
562 size_t n = 1; /* Terminating zero */
563 size_t nbs = 0;
565 if (!str)
566 return NULL;
568 for (p = str; *p; p++) {
569 switch (*p) {
570 case ' ':
571 case '\t':
572 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
573 n += nbs + 2;
574 nbs = 0;
575 break;
576 case '$':
577 case '#':
578 nbs = 0;
579 n += 2;
580 break;
581 case '\\':
582 nbs++;
583 n++;
584 break;
585 default:
586 nbs = 0;
587 n++;
588 break;
592 /* Convert N backslashes at the end of filename to 2N backslashes */
593 if (nbs)
594 n += nbs;
596 os = q = nasm_malloc(n);
598 nbs = 0;
599 for (p = str; *p; p++) {
600 switch (*p) {
601 case ' ':
602 case '\t':
603 while (nbs--)
604 *q++ = '\\';
605 *q++ = '\\';
606 *q++ = *p;
607 break;
608 case '$':
609 *q++ = *p;
610 *q++ = *p;
611 nbs = 0;
612 break;
613 case '#':
614 *q++ = '\\';
615 *q++ = *p;
616 nbs = 0;
617 break;
618 case '\\':
619 *q++ = *p;
620 nbs++;
621 break;
622 default:
623 *q++ = *p;
624 nbs = 0;
625 break;
628 while (nbs--)
629 *q++ = '\\';
631 *q = '\0';
633 return os;
636 struct textargs {
637 const char *label;
638 int value;
641 enum text_options {
642 OPT_PREFIX,
643 OPT_POSTFIX
645 static const struct textargs textopts[] = {
646 {"prefix", OPT_PREFIX},
647 {"postfix", OPT_POSTFIX},
648 {NULL, 0}
651 static void show_version(void)
653 printf("NASM version %s compiled on %s%s\n",
654 nasm_version, nasm_date, nasm_compile_options);
655 exit(0);
658 static bool stopoptions = false;
659 static bool process_arg(char *p, char *q, int pass)
661 char *param;
662 int i;
663 bool advance = false;
664 bool do_warn;
666 if (!p || !p[0])
667 return false;
669 if (p[0] == '-' && !stopoptions) {
670 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
671 /* These parameters take values */
672 if (!(param = get_param(p, q, &advance)))
673 return advance;
676 switch (p[1]) {
677 case 's':
678 if (pass == 1)
679 error_file = stdout;
680 break;
682 case 'o': /* output file */
683 if (pass == 2)
684 copy_filename(outname, param);
685 break;
687 case 'f': /* output format */
688 if (pass == 1) {
689 ofmt = ofmt_find(param, &ofmt_alias);
690 if (!ofmt) {
691 nasm_fatal(ERR_NOFILE | ERR_USAGE,
692 "unrecognised output format `%s' - "
693 "use -hf for a list", param);
696 break;
698 case 'O': /* Optimization level */
699 if (pass == 2) {
700 int opt;
702 if (!*param) {
703 /* Naked -O == -Ox */
704 optimizing = MAX_OPTIMIZE;
705 } else {
706 while (*param) {
707 switch (*param) {
708 case '0': case '1': case '2': case '3': case '4':
709 case '5': case '6': case '7': case '8': case '9':
710 opt = strtoul(param, &param, 10);
712 /* -O0 -> optimizing == -1, 0.98 behaviour */
713 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
714 if (opt < 2)
715 optimizing = opt - 1;
716 else
717 optimizing = opt;
718 break;
720 case 'v':
721 case '+':
722 param++;
723 opt_verbose_info = true;
724 break;
726 case 'x':
727 param++;
728 optimizing = MAX_OPTIMIZE;
729 break;
731 default:
732 nasm_fatal(0,
733 "unknown optimization option -O%c\n",
734 *param);
735 break;
738 if (optimizing > MAX_OPTIMIZE)
739 optimizing = MAX_OPTIMIZE;
742 break;
744 case 'p': /* pre-include */
745 case 'P':
746 if (pass == 2)
747 preproc->pre_include(param);
748 break;
750 case 'd': /* pre-define */
751 case 'D':
752 if (pass == 2)
753 preproc->pre_define(param);
754 break;
756 case 'u': /* un-define */
757 case 'U':
758 if (pass == 2)
759 preproc->pre_undefine(param);
760 break;
762 case 'i': /* include search path */
763 case 'I':
764 if (pass == 2)
765 preproc->include_path(param);
766 break;
768 case 'l': /* listing file */
769 if (pass == 2)
770 copy_filename(listname, param);
771 break;
773 case 'Z': /* error messages file */
774 if (pass == 1)
775 copy_filename(errname, param);
776 break;
778 case 'F': /* specify debug format */
779 if (pass == 2) {
780 using_debug_info = true;
781 debug_format = param;
783 break;
785 case 'X': /* specify error reporting format */
786 if (pass == 1) {
787 if (nasm_stricmp("vc", param) == 0)
788 nasm_set_verror(nasm_verror_vc);
789 else if (nasm_stricmp("gnu", param) == 0)
790 nasm_set_verror(nasm_verror_gnu);
791 else
792 nasm_fatal(ERR_NOFILE | ERR_USAGE,
793 "unrecognized error reporting format `%s'",
794 param);
796 break;
798 case 'g':
799 if (pass == 2) {
800 using_debug_info = true;
801 if (p[2])
802 debug_format = nasm_skip_spaces(p + 2);
804 break;
806 case 'h':
807 printf
808 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
809 "[-l listfile]\n"
810 " [options...] [--] filename\n"
811 " or nasm -v (or --v) for version info\n\n"
812 " -t assemble in SciTech TASM compatible mode\n");
813 printf
814 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
815 " -a don't preprocess (assemble only)\n"
816 " -M generate Makefile dependencies on stdout\n"
817 " -MG d:o, missing files assumed generated\n"
818 " -MF <file> set Makefile dependency file\n"
819 " -MD <file> assemble and generate dependencies\n"
820 " -MT <file> dependency target name\n"
821 " -MQ <file> dependency target name (quoted)\n"
822 " -MP emit phony target\n\n"
823 " -Z<file> redirect error messages to file\n"
824 " -s redirect error messages to stdout\n\n"
825 " -g generate debugging information\n\n"
826 " -F format select a debugging format\n\n"
827 " -gformat same as -g -F format\n\n"
828 " -o outfile write output to an outfile\n\n"
829 " -f format select an output format\n\n"
830 " -l listfile write listing to a listfile\n\n"
831 " -I<path> adds a pathname to the include file path\n");
832 printf
833 (" -O<digit> optimize branch offsets\n"
834 " -O0: No optimization\n"
835 " -O1: Minimal optimization\n"
836 " -Ox: Multipass optimization (default)\n\n"
837 " -P<file> pre-includes a file\n"
838 " -D<macro>[=<value>] pre-defines a macro\n"
839 " -U<macro> undefines a macro\n"
840 " -X<format> specifies error reporting format (gnu or vc)\n"
841 " -w+foo enables warning foo (equiv. -Wfoo)\n"
842 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
843 " -h show invocation summary and exit\n\n"
844 "--prefix,--postfix\n"
845 " this options prepend or append the given argument to all\n"
846 " extern and global variables\n"
847 "Warnings:\n");
848 for (i = 0; i <= ERR_WARN_MAX; i++)
849 printf(" %-23s %s (default %s)\n",
850 warnings[i].name, warnings[i].help,
851 warnings[i].enabled ? "on" : "off");
852 printf
853 ("\nresponse files should contain command line parameters"
854 ", one per line.\n");
855 if (p[2] == 'f') {
856 printf("\nvalid output formats for -f are"
857 " (`*' denotes default):\n");
858 ofmt_list(ofmt, stdout);
859 } else {
860 printf("\nFor a list of valid output formats, use -hf.\n");
861 printf("For a list of debug formats, use -f <form> -y.\n");
863 exit(0); /* never need usage message here */
864 break;
866 case 'y':
867 printf("\nvalid debug formats for '%s' output format are"
868 " ('*' denotes default):\n", ofmt->shortname);
869 dfmt_list(ofmt, stdout);
870 exit(0);
871 break;
873 case 't':
874 if (pass == 2)
875 tasm_compatible_mode = true;
876 break;
878 case 'v':
879 show_version();
880 break;
882 case 'e': /* preprocess only */
883 case 'E':
884 if (pass == 1)
885 operating_mode = OP_PREPROCESS;
886 break;
888 case 'a': /* assemble only - don't preprocess */
889 if (pass == 1)
890 preproc = &preproc_nop;
891 break;
893 case 'W':
894 if (pass == 2) {
895 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
896 do_warn = false;
897 param += 3;
898 } else {
899 do_warn = true;
901 goto set_warning;
903 break;
905 case 'w':
906 if (pass == 2) {
907 if (param[0] != '+' && param[0] != '-') {
908 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
909 "invalid option to `-w'");
910 break;
912 do_warn = (param[0] == '+');
913 param++;
914 goto set_warning;
916 break;
918 set_warning:
919 for (i = 0; i <= ERR_WARN_MAX; i++) {
920 if (!nasm_stricmp(param, warnings[i].name))
921 break;
923 if (i <= ERR_WARN_MAX) {
924 warning_on_global[i] = do_warn;
925 } else if (!nasm_stricmp(param, "all")) {
926 for (i = 1; i <= ERR_WARN_MAX; i++)
927 warning_on_global[i] = do_warn;
928 } else if (!nasm_stricmp(param, "none")) {
929 for (i = 1; i <= ERR_WARN_MAX; i++)
930 warning_on_global[i] = !do_warn;
931 } else {
932 /* Ignore invalid warning names; forward compatibility */
934 break;
936 case 'M':
937 if (pass == 2) {
938 switch (p[2]) {
939 case 0:
940 operating_mode = OP_DEPEND;
941 break;
942 case 'G':
943 operating_mode = OP_DEPEND;
944 depend_missing_ok = true;
945 break;
946 case 'P':
947 depend_emit_phony = true;
948 break;
949 case 'D':
950 operating_mode = OP_NORMAL;
951 depend_file = q;
952 advance = true;
953 break;
954 case 'F':
955 depend_file = q;
956 advance = true;
957 break;
958 case 'T':
959 depend_target = q;
960 advance = true;
961 break;
962 case 'Q':
963 depend_target = quote_for_make(q);
964 advance = true;
965 break;
966 default:
967 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
968 "unknown dependency option `-M%c'", p[2]);
969 break;
971 if (advance && (!q || !q[0])) {
972 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
973 "option `-M%c' requires a parameter", p[2]);
974 break;
977 break;
979 case '-':
981 int s;
983 if (p[2] == 0) { /* -- => stop processing options */
984 stopoptions = 1;
985 break;
988 if (!nasm_stricmp(p, "--v"))
989 show_version();
991 if (!nasm_stricmp(p, "--version"))
992 show_version();
994 for (s = 0; textopts[s].label; s++) {
995 if (!nasm_stricmp(p + 2, textopts[s].label)) {
996 break;
1000 switch (s) {
1002 case OPT_PREFIX:
1003 case OPT_POSTFIX:
1005 if (!q) {
1006 nasm_error(ERR_NONFATAL | ERR_NOFILE |
1007 ERR_USAGE,
1008 "option `--%s' requires an argument",
1009 p + 2);
1010 break;
1011 } else {
1012 advance = 1, param = q;
1015 switch (s) {
1016 case OPT_PREFIX:
1017 if (pass == 2)
1018 strlcpy(lprefix, param, PREFIX_MAX);
1019 break;
1020 case OPT_POSTFIX:
1021 if (pass == 2)
1022 strlcpy(lpostfix, param, POSTFIX_MAX);
1023 break;
1024 default:
1025 nasm_panic(ERR_NOFILE,
1026 "internal error");
1027 break;
1029 break;
1032 default:
1034 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1035 "unrecognised option `--%s'", p + 2);
1036 break;
1039 break;
1042 default:
1043 if (!ofmt->setinfo(GI_SWITCH, &p))
1044 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1045 "unrecognised option `-%c'", p[1]);
1046 break;
1048 } else if (pass == 2) {
1049 if (*inname) {
1050 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1051 "more than one input file specified");
1052 } else {
1053 copy_filename(inname, p);
1057 return advance;
1060 #define ARG_BUF_DELTA 128
1062 static void process_respfile(FILE * rfile, int pass)
1064 char *buffer, *p, *q, *prevarg;
1065 int bufsize, prevargsize;
1067 bufsize = prevargsize = ARG_BUF_DELTA;
1068 buffer = nasm_malloc(ARG_BUF_DELTA);
1069 prevarg = nasm_malloc(ARG_BUF_DELTA);
1070 prevarg[0] = '\0';
1072 while (1) { /* Loop to handle all lines in file */
1073 p = buffer;
1074 while (1) { /* Loop to handle long lines */
1075 q = fgets(p, bufsize - (p - buffer), rfile);
1076 if (!q)
1077 break;
1078 p += strlen(p);
1079 if (p > buffer && p[-1] == '\n')
1080 break;
1081 if (p - buffer > bufsize - 10) {
1082 int offset;
1083 offset = p - buffer;
1084 bufsize += ARG_BUF_DELTA;
1085 buffer = nasm_realloc(buffer, bufsize);
1086 p = buffer + offset;
1090 if (!q && p == buffer) {
1091 if (prevarg[0])
1092 process_arg(prevarg, NULL, pass);
1093 nasm_free(buffer);
1094 nasm_free(prevarg);
1095 return;
1099 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1100 * them are present at the end of the line.
1102 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1104 while (p > buffer && nasm_isspace(p[-1]))
1105 *--p = '\0';
1107 p = nasm_skip_spaces(buffer);
1109 if (process_arg(prevarg, p, pass))
1110 *p = '\0';
1112 if ((int) strlen(p) > prevargsize - 10) {
1113 prevargsize += ARG_BUF_DELTA;
1114 prevarg = nasm_realloc(prevarg, prevargsize);
1116 strncpy(prevarg, p, prevargsize);
1120 /* Function to process args from a string of args, rather than the
1121 * argv array. Used by the environment variable and response file
1122 * processing.
1124 static void process_args(char *args, int pass)
1126 char *p, *q, *arg, *prevarg;
1127 char separator = ' ';
1129 p = args;
1130 if (*p && *p != '-')
1131 separator = *p++;
1132 arg = NULL;
1133 while (*p) {
1134 q = p;
1135 while (*p && *p != separator)
1136 p++;
1137 while (*p == separator)
1138 *p++ = '\0';
1139 prevarg = arg;
1140 arg = q;
1141 if (process_arg(prevarg, arg, pass))
1142 arg = NULL;
1144 if (arg)
1145 process_arg(arg, NULL, pass);
1148 static void process_response_file(const char *file, int pass)
1150 char str[2048];
1151 FILE *f = nasm_open_read(file, NF_TEXT);
1152 if (!f) {
1153 perror(file);
1154 exit(-1);
1156 while (fgets(str, sizeof str, f)) {
1157 process_args(str, pass);
1159 fclose(f);
1162 static void parse_cmdline(int argc, char **argv, int pass)
1164 FILE *rfile;
1165 char *envreal, *envcopy = NULL, *p;
1166 int i;
1168 *inname = *outname = *listname = *errname = '\0';
1170 for (i = 0; i <= ERR_WARN_MAX; i++)
1171 warning_on_global[i] = warnings[i].enabled;
1174 * First, process the NASMENV environment variable.
1176 envreal = getenv("NASMENV");
1177 if (envreal) {
1178 envcopy = nasm_strdup(envreal);
1179 process_args(envcopy, pass);
1180 nasm_free(envcopy);
1184 * Now process the actual command line.
1186 while (--argc) {
1187 bool advance;
1188 argv++;
1189 if (argv[0][0] == '@') {
1191 * We have a response file, so process this as a set of
1192 * arguments like the environment variable. This allows us
1193 * to have multiple arguments on a single line, which is
1194 * different to the -@resp file processing below for regular
1195 * NASM.
1197 process_response_file(argv[0]+1, pass);
1198 argc--;
1199 argv++;
1201 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1202 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1203 if (p) {
1204 rfile = nasm_open_read(p, NF_TEXT);
1205 if (rfile) {
1206 process_respfile(rfile, pass);
1207 fclose(rfile);
1208 } else
1209 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1210 "unable to open response file `%s'", p);
1212 } else
1213 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL, pass);
1214 argv += advance, argc -= advance;
1218 * Look for basic command line typos. This definitely doesn't
1219 * catch all errors, but it might help cases of fumbled fingers.
1221 if (pass != 2)
1222 return;
1224 if (!*inname)
1225 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1226 "no input file specified");
1227 else if (!strcmp(inname, errname) ||
1228 !strcmp(inname, outname) ||
1229 !strcmp(inname, listname) ||
1230 (depend_file && !strcmp(inname, depend_file)))
1231 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1232 "file `%s' is both input and output file",
1233 inname);
1235 if (*errname) {
1236 error_file = nasm_open_write(errname, NF_TEXT);
1237 if (!error_file) {
1238 error_file = stderr; /* Revert to default! */
1239 nasm_fatal(ERR_NOFILE | ERR_USAGE,
1240 "cannot open file `%s' for error messages",
1241 errname);
1246 static enum directives getkw(char **directive, char **value);
1248 static void assemble_file(char *fname, StrList **depend_ptr)
1250 char *directive, *value, *p, *q, *special, *line;
1251 insn output_ins;
1252 int i, validid;
1253 bool rn_error;
1254 int32_t seg;
1255 int64_t offs;
1256 struct tokenval tokval;
1257 expr *e;
1258 int pass_max;
1260 if (cmd_sb == 32 && iflag_ffs(&cmd_cpu) < IF_386)
1261 nasm_fatal(0, "command line: 32-bit segment size requires a higher cpu");
1263 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1264 for (passn = 1; pass0 <= 2; passn++) {
1265 int pass1, pass2;
1266 ldfunc def_label;
1268 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1269 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1270 /* pass0 0, 0, 0, ..., 1, 2 */
1272 def_label = passn > 1 ? redefine_label : define_label;
1274 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1275 cpu = cmd_cpu;
1276 if (pass0 == 2) {
1277 lfmt->init(listname);
1279 in_abs_seg = false;
1280 global_offset_changed = 0; /* set by redefine_label */
1281 location.segment = ofmt->section(NULL, pass2, &sb);
1282 globalbits = sb;
1283 if (passn > 1) {
1284 saa_rewind(forwrefs);
1285 forwref = saa_rstruct(forwrefs);
1286 raa_free(offsets);
1287 offsets = raa_init();
1289 preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);
1290 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1292 globallineno = 0;
1293 if (passn == 1)
1294 location.known = true;
1295 location.offset = offs = get_curr_offs();
1297 while ((line = preproc->getline())) {
1298 enum directives d;
1299 globallineno++;
1302 * Here we parse our directives; this is not handled by the
1303 * 'real' parser. This really should be a separate function.
1305 directive = line;
1306 d = getkw(&directive, &value);
1307 if (d) {
1308 int err = 0;
1310 switch (d) {
1311 case D_SEGMENT: /* [SEGMENT n] */
1312 case D_SECTION:
1313 seg = ofmt->section(value, pass2, &sb);
1314 if (seg == NO_SEG) {
1315 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1316 "segment name `%s' not recognized",
1317 value);
1318 } else {
1319 in_abs_seg = false;
1320 location.segment = seg;
1322 break;
1323 case D_SECTALIGN: /* [SECTALIGN n] */
1324 if (*value) {
1325 stdscan_reset();
1326 stdscan_set(value);
1327 tokval.t_type = TOKEN_INVALID;
1328 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1329 if (e) {
1330 unsigned int align = (unsigned int)e->value;
1331 if ((uint64_t)e->value > 0x7fffffff) {
1333 * FIXME: Please make some sane message here
1334 * ofmt should have some 'check' method which
1335 * would report segment alignment bounds.
1337 nasm_fatal(0,
1338 "incorrect segment alignment `%s'", value);
1339 } else if (!is_power2(align)) {
1340 nasm_error(ERR_NONFATAL,
1341 "segment alignment `%s' is not power of two",
1342 value);
1345 /* callee should be able to handle all details */
1346 if (location.segment != NO_SEG)
1347 ofmt->sectalign(location.segment, align);
1350 break;
1351 case D_EXTERN: /* [EXTERN label:special] */
1352 if (*value == '$')
1353 value++; /* skip initial $ if present */
1354 if (pass0 == 2) {
1355 q = value;
1356 while (*q && *q != ':')
1357 q++;
1358 if (*q == ':') {
1359 *q++ = '\0';
1360 ofmt->symdef(value, 0L, 0L, 3, q);
1362 } else if (passn == 1) {
1363 q = value;
1364 validid = true;
1365 if (!isidstart(*q))
1366 validid = false;
1367 while (*q && *q != ':') {
1368 if (!isidchar(*q))
1369 validid = false;
1370 q++;
1372 if (!validid) {
1373 nasm_error(ERR_NONFATAL,
1374 "identifier expected after EXTERN");
1375 break;
1377 if (*q == ':') {
1378 *q++ = '\0';
1379 special = q;
1380 } else
1381 special = NULL;
1382 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1383 int temp = pass0;
1384 pass0 = 1; /* fake pass 1 in labels.c */
1385 declare_as_global(value, special);
1386 define_label(value, seg_alloc(), 0L, NULL,
1387 false, true);
1388 pass0 = temp;
1390 } /* else pass0 == 1 */
1391 break;
1392 case D_BITS: /* [BITS bits] */
1393 globalbits = sb = get_bits(value);
1394 break;
1395 case D_GLOBAL: /* [GLOBAL symbol:special] */
1396 if (*value == '$')
1397 value++; /* skip initial $ if present */
1398 if (pass0 == 2) { /* pass 2 */
1399 q = value;
1400 while (*q && *q != ':')
1401 q++;
1402 if (*q == ':') {
1403 *q++ = '\0';
1404 ofmt->symdef(value, 0L, 0L, 3, q);
1406 } else if (pass2 == 1) { /* pass == 1 */
1407 q = value;
1408 validid = true;
1409 if (!isidstart(*q))
1410 validid = false;
1411 while (*q && *q != ':') {
1412 if (!isidchar(*q))
1413 validid = false;
1414 q++;
1416 if (!validid) {
1417 nasm_error(ERR_NONFATAL,
1418 "identifier expected after GLOBAL");
1419 break;
1421 if (*q == ':') {
1422 *q++ = '\0';
1423 special = q;
1424 } else
1425 special = NULL;
1426 declare_as_global(value, special);
1427 } /* pass == 1 */
1428 break;
1429 case D_COMMON: /* [COMMON symbol size:special] */
1431 int64_t size;
1433 if (*value == '$')
1434 value++; /* skip initial $ if present */
1435 p = value;
1436 validid = true;
1437 if (!isidstart(*p))
1438 validid = false;
1439 while (*p && !nasm_isspace(*p)) {
1440 if (!isidchar(*p))
1441 validid = false;
1442 p++;
1444 if (!validid) {
1445 nasm_error(ERR_NONFATAL,
1446 "identifier expected after COMMON");
1447 break;
1449 if (*p) {
1450 p = nasm_zap_spaces_fwd(p);
1451 q = p;
1452 while (*q && *q != ':')
1453 q++;
1454 if (*q == ':') {
1455 *q++ = '\0';
1456 special = q;
1457 } else {
1458 special = NULL;
1460 size = readnum(p, &rn_error);
1461 if (rn_error) {
1462 nasm_error(ERR_NONFATAL,
1463 "invalid size specified"
1464 " in COMMON declaration");
1465 break;
1467 } else {
1468 nasm_error(ERR_NONFATAL,
1469 "no size specified in"
1470 " COMMON declaration");
1471 break;
1474 if (pass0 < 2) {
1475 define_common(value, seg_alloc(), size, special);
1476 } else if (pass0 == 2) {
1477 if (special)
1478 ofmt->symdef(value, 0L, 0L, 3, special);
1480 break;
1482 case D_ABSOLUTE: /* [ABSOLUTE address] */
1483 stdscan_reset();
1484 stdscan_set(value);
1485 tokval.t_type = TOKEN_INVALID;
1486 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, NULL);
1487 if (e) {
1488 if (!is_reloc(e))
1489 nasm_error(pass0 ==
1490 1 ? ERR_NONFATAL : ERR_PANIC,
1491 "cannot use non-relocatable expression as "
1492 "ABSOLUTE address");
1493 else {
1494 abs_seg = reloc_seg(e);
1495 abs_offset = reloc_value(e);
1497 } else if (passn == 1)
1498 abs_offset = 0x100; /* don't go near zero in case of / */
1499 else
1500 nasm_panic(0, "invalid ABSOLUTE address "
1501 "in pass two");
1502 in_abs_seg = true;
1503 location.segment = NO_SEG;
1504 break;
1505 case D_DEBUG: /* [DEBUG] */
1507 char debugid[128];
1508 bool badid, overlong;
1510 p = value;
1511 q = debugid;
1512 badid = overlong = false;
1513 if (!isidstart(*p)) {
1514 badid = true;
1515 } else {
1516 while (*p && !nasm_isspace(*p)) {
1517 if (q >= debugid + sizeof debugid - 1) {
1518 overlong = true;
1519 break;
1521 if (!isidchar(*p))
1522 badid = true;
1523 *q++ = *p++;
1525 *q = 0;
1527 if (badid) {
1528 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1529 "identifier expected after DEBUG");
1530 break;
1532 if (overlong) {
1533 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1534 "DEBUG identifier too long");
1535 break;
1537 p = nasm_skip_spaces(p);
1538 if (pass0 == 2)
1539 dfmt->debug_directive(debugid, p);
1540 break;
1542 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1543 value = nasm_skip_spaces(value);
1544 switch(*value) {
1545 case '-': validid = 0; value++; break;
1546 case '+': validid = 1; value++; break;
1547 case '*': validid = 2; value++; break;
1548 default: validid = 1; break;
1551 for (i = 1; i <= ERR_WARN_MAX; i++)
1552 if (!nasm_stricmp(value, warnings[i].name))
1553 break;
1554 if (i <= ERR_WARN_MAX) {
1555 switch(validid) {
1556 case 0:
1557 warning_on[i] = false;
1558 break;
1559 case 1:
1560 warning_on[i] = true;
1561 break;
1562 case 2:
1563 warning_on[i] = warning_on_global[i];
1564 break;
1567 break;
1568 case D_CPU: /* [CPU] */
1569 cpu = get_cpu(value);
1570 break;
1571 case D_LIST: /* [LIST {+|-}] */
1572 value = nasm_skip_spaces(value);
1573 if (*value == '+') {
1574 user_nolist = 0;
1575 } else {
1576 if (*value == '-') {
1577 user_nolist = 1;
1578 } else {
1579 err = 1;
1582 break;
1583 case D_DEFAULT: /* [DEFAULT] */
1584 stdscan_reset();
1585 stdscan_set(value);
1586 tokval.t_type = TOKEN_INVALID;
1587 if (stdscan(NULL, &tokval) != TOKEN_INVALID) {
1588 switch ((int)tokval.t_integer) {
1589 case S_REL:
1590 globalrel = 1;
1591 break;
1592 case S_ABS:
1593 globalrel = 0;
1594 break;
1595 case P_BND:
1596 globalbnd = 1;
1597 break;
1598 case P_NOBND:
1599 globalbnd = 0;
1600 break;
1601 default:
1602 err = 1;
1603 break;
1605 } else {
1606 err = 1;
1608 break;
1609 case D_FLOAT:
1610 if (float_option(value)) {
1611 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1612 "unknown 'float' directive: %s",
1613 value);
1615 break;
1616 case D_PRAGMA:
1617 /* Currently the pragma directive doesn't do anything */
1618 break;
1619 default:
1620 if (ofmt->directive(d, value, pass2))
1621 break;
1622 /* else fall through */
1623 case D_unknown:
1624 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1625 "unrecognised directive [%s]",
1626 directive);
1627 break;
1629 if (err) {
1630 nasm_error(ERR_NONFATAL,
1631 "invalid parameter to [%s] directive",
1632 directive);
1634 } else { /* it isn't a directive */
1635 parse_line(pass1, line, &output_ins, def_label);
1637 if (optimizing > 0) {
1638 if (forwref != NULL && globallineno == forwref->lineno) {
1639 output_ins.forw_ref = true;
1640 do {
1641 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1642 forwref = saa_rstruct(forwrefs);
1643 } while (forwref != NULL
1644 && forwref->lineno == globallineno);
1645 } else
1646 output_ins.forw_ref = false;
1648 if (output_ins.forw_ref) {
1649 if (passn == 1) {
1650 for (i = 0; i < output_ins.operands; i++) {
1651 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1652 struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);
1653 fwinf->lineno = globallineno;
1654 fwinf->operand = i;
1661 /* forw_ref */
1662 if (output_ins.opcode == I_EQU) {
1663 if (pass1 == 1) {
1665 * Special `..' EQUs get processed in pass two,
1666 * except `..@' macro-processor EQUs which are done
1667 * in the normal place.
1669 if (!output_ins.label)
1670 nasm_error(ERR_NONFATAL,
1671 "EQU not preceded by label");
1673 else if (output_ins.label[0] != '.' ||
1674 output_ins.label[1] != '.' ||
1675 output_ins.label[2] == '@') {
1676 if (output_ins.operands == 1 &&
1677 (output_ins.oprs[0].type & IMMEDIATE) &&
1678 output_ins.oprs[0].wrt == NO_SEG) {
1679 bool isext = !!(output_ins.oprs[0].opflags & OPFLAG_EXTERN);
1680 def_label(output_ins.label,
1681 output_ins.oprs[0].segment,
1682 output_ins.oprs[0].offset, NULL,
1683 false, isext);
1684 } else if (output_ins.operands == 2
1685 && (output_ins.oprs[0].type & IMMEDIATE)
1686 && (output_ins.oprs[0].type & COLON)
1687 && output_ins.oprs[0].segment == NO_SEG
1688 && output_ins.oprs[0].wrt == NO_SEG
1689 && (output_ins.oprs[1].type & IMMEDIATE)
1690 && output_ins.oprs[1].segment == NO_SEG
1691 && output_ins.oprs[1].wrt == NO_SEG) {
1692 def_label(output_ins.label,
1693 output_ins.oprs[0].offset | SEG_ABS,
1694 output_ins.oprs[1].offset,
1695 NULL, false, false);
1696 } else
1697 nasm_error(ERR_NONFATAL,
1698 "bad syntax for EQU");
1700 } else {
1702 * Special `..' EQUs get processed here, except
1703 * `..@' macro processor EQUs which are done above.
1705 if (output_ins.label[0] == '.' &&
1706 output_ins.label[1] == '.' &&
1707 output_ins.label[2] != '@') {
1708 if (output_ins.operands == 1 &&
1709 (output_ins.oprs[0].type & IMMEDIATE)) {
1710 define_label(output_ins.label,
1711 output_ins.oprs[0].segment,
1712 output_ins.oprs[0].offset,
1713 NULL, false, false);
1714 } else if (output_ins.operands == 2
1715 && (output_ins.oprs[0].type & IMMEDIATE)
1716 && (output_ins.oprs[0].type & COLON)
1717 && output_ins.oprs[0].segment == NO_SEG
1718 && (output_ins.oprs[1].type & IMMEDIATE)
1719 && output_ins.oprs[1].segment == NO_SEG) {
1720 define_label(output_ins.label,
1721 output_ins.oprs[0].offset | SEG_ABS,
1722 output_ins.oprs[1].offset,
1723 NULL, false, false);
1724 } else
1725 nasm_error(ERR_NONFATAL,
1726 "bad syntax for EQU");
1729 } else { /* instruction isn't an EQU */
1731 if (pass1 == 1) {
1733 int64_t l = insn_size(location.segment, offs, sb, cpu,
1734 &output_ins);
1735 l *= output_ins.times;
1737 /* if (using_debug_info) && output_ins.opcode != -1) */
1738 if (using_debug_info)
1739 { /* fbk 03/25/01 */
1740 /* this is done here so we can do debug type info */
1741 int32_t typeinfo =
1742 TYS_ELEMENTS(output_ins.operands);
1743 switch (output_ins.opcode) {
1744 case I_RESB:
1745 typeinfo =
1746 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1747 break;
1748 case I_RESW:
1749 typeinfo =
1750 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1751 break;
1752 case I_RESD:
1753 typeinfo =
1754 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1755 break;
1756 case I_RESQ:
1757 typeinfo =
1758 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1759 break;
1760 case I_REST:
1761 typeinfo =
1762 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1763 break;
1764 case I_RESO:
1765 typeinfo =
1766 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1767 break;
1768 case I_RESY:
1769 typeinfo =
1770 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1771 break;
1772 case I_DB:
1773 typeinfo |= TY_BYTE;
1774 break;
1775 case I_DW:
1776 typeinfo |= TY_WORD;
1777 break;
1778 case I_DD:
1779 if (output_ins.eops_float)
1780 typeinfo |= TY_FLOAT;
1781 else
1782 typeinfo |= TY_DWORD;
1783 break;
1784 case I_DQ:
1785 typeinfo |= TY_QWORD;
1786 break;
1787 case I_DT:
1788 typeinfo |= TY_TBYTE;
1789 break;
1790 case I_DO:
1791 typeinfo |= TY_OWORD;
1792 break;
1793 case I_DY:
1794 typeinfo |= TY_YWORD;
1795 break;
1796 default:
1797 typeinfo = TY_LABEL;
1801 dfmt->debug_typevalue(typeinfo);
1803 if (l != -1) {
1804 offs += l;
1805 set_curr_offs(offs);
1808 * else l == -1 => invalid instruction, which will be
1809 * flagged as an error on pass 2
1812 } else {
1813 offs += assemble(location.segment, offs, sb, cpu,
1814 &output_ins);
1815 set_curr_offs(offs);
1818 } /* not an EQU */
1819 cleanup_insn(&output_ins);
1821 nasm_free(line);
1822 location.offset = offs = get_curr_offs();
1823 } /* end while (line = preproc->getline... */
1825 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1826 nasm_error(ERR_NONFATAL,
1827 "phase error detected at end of assembly.");
1829 if (pass1 == 1)
1830 preproc->cleanup(1);
1832 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1833 pass0++;
1834 } else if (global_offset_changed &&
1835 global_offset_changed < prev_offset_changed) {
1836 prev_offset_changed = global_offset_changed;
1837 stall_count = 0;
1838 } else {
1839 stall_count++;
1842 if (terminate_after_phase)
1843 break;
1845 if ((stall_count > 997) || (passn >= pass_max)) {
1846 /* We get here if the labels don't converge
1847 * Example: FOO equ FOO + 1
1849 nasm_error(ERR_NONFATAL,
1850 "Can't find valid values for all labels "
1851 "after %d passes, giving up.", passn);
1852 nasm_error(ERR_NONFATAL,
1853 "Possible causes: recursive EQUs, macro abuse.");
1854 break;
1858 preproc->cleanup(0);
1859 lfmt->cleanup();
1860 if (!terminate_after_phase && opt_verbose_info) {
1861 /* -On and -Ov switches */
1862 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1866 static enum directives getkw(char **directive, char **value)
1868 char *p, *q, *buf;
1870 buf = nasm_skip_spaces(*directive);
1872 /* it should be enclosed in [ ] */
1873 if (*buf != '[')
1874 return D_none;
1875 q = strchr(buf, ']');
1876 if (!q)
1877 return D_none;
1879 /* stip off the comments */
1880 p = strchr(buf, ';');
1881 if (p) {
1882 if (p < q) /* ouch! somwhere inside */
1883 return D_none;
1884 *p = '\0';
1887 /* no brace, no trailing spaces */
1888 *q = '\0';
1889 nasm_zap_spaces_rev(--q);
1891 /* directive */
1892 p = nasm_skip_spaces(++buf);
1893 q = nasm_skip_word(p);
1894 if (!q)
1895 return D_none; /* sigh... no value there */
1896 *q = '\0';
1897 *directive = p;
1899 /* and value finally */
1900 p = nasm_skip_spaces(++q);
1901 *value = p;
1903 return find_directive(*directive);
1907 * gnu style error reporting
1908 * This function prints an error message to error_file in the
1909 * style used by GNU. An example would be:
1910 * file.asm:50: error: blah blah blah
1911 * where file.asm is the name of the file, 50 is the line number on
1912 * which the error occurs (or is detected) and "error:" is one of
1913 * the possible optional diagnostics -- it can be "error" or "warning"
1914 * or something else. Finally the line terminates with the actual
1915 * error message.
1917 * @param severity the severity of the warning or error
1918 * @param fmt the printf style format string
1920 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1922 const char *currentfile = NULL;
1923 int32_t lineno = 0;
1925 if (is_suppressed_warning(severity))
1926 return;
1928 if (!(severity & ERR_NOFILE))
1929 src_get(&lineno, &currentfile);
1931 if (!skip_this_pass(severity)) {
1932 if (currentfile) {
1933 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1934 } else {
1935 fputs("nasm: ", error_file);
1939 nasm_verror_common(severity, fmt, ap);
1943 * MS style error reporting
1944 * This function prints an error message to error_file in the
1945 * style used by Visual C and some other Microsoft tools. An example
1946 * would be:
1947 * file.asm(50) : error: blah blah blah
1948 * where file.asm is the name of the file, 50 is the line number on
1949 * which the error occurs (or is detected) and "error:" is one of
1950 * the possible optional diagnostics -- it can be "error" or "warning"
1951 * or something else. Finally the line terminates with the actual
1952 * error message.
1954 * @param severity the severity of the warning or error
1955 * @param fmt the printf style format string
1957 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1959 const char *currentfile = NULL;
1960 int32_t lineno = 0;
1962 if (is_suppressed_warning(severity))
1963 return;
1965 if (!(severity & ERR_NOFILE))
1966 src_get(&lineno, &currentfile);
1968 if (!skip_this_pass(severity)) {
1969 if (currentfile) {
1970 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1971 } else {
1972 fputs("nasm: ", error_file);
1976 nasm_verror_common(severity, fmt, ap);
1980 * check for supressed warning
1981 * checks for suppressed warning or pass one only warning and we're
1982 * not in pass 1
1984 * @param severity the severity of the warning or error
1985 * @return true if we should abort error/warning printing
1987 static bool is_suppressed_warning(int severity)
1989 /* Not a warning at all */
1990 if ((severity & ERR_MASK) != ERR_WARNING)
1991 return false;
1993 /* Might be a warning but suppresed explicitly */
1994 if (severity & ERR_WARN_MASK)
1995 return !warning_on[WARN_IDX(severity)];
1996 else
1997 return false;
2000 static bool skip_this_pass(int severity)
2002 /* See if it's a pass-specific warning which should be skipped. */
2004 if ((severity & ERR_MASK) > ERR_WARNING)
2005 return false;
2008 * passn is 1 on the very first pass only.
2009 * pass0 is 2 on the code-generation (final) pass only.
2010 * These are the passes we care about in this case.
2012 return (((severity & ERR_PASS1) && passn != 1) ||
2013 ((severity & ERR_PASS2) && pass0 != 2));
2017 * common error reporting
2018 * This is the common back end of the error reporting schemes currently
2019 * implemented. It prints the nature of the warning and then the
2020 * specific error message to error_file and may or may not return. It
2021 * doesn't return if the error severity is a "panic" or "debug" type.
2023 * @param severity the severity of the warning or error
2024 * @param fmt the printf style format string
2026 static void nasm_verror_common(int severity, const char *fmt, va_list args)
2028 char msg[1024];
2029 const char *pfx;
2031 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
2032 case ERR_WARNING:
2033 pfx = "warning: ";
2034 break;
2035 case ERR_NONFATAL:
2036 pfx = "error: ";
2037 break;
2038 case ERR_FATAL:
2039 pfx = "fatal: ";
2040 break;
2041 case ERR_PANIC:
2042 pfx = "panic: ";
2043 break;
2044 case ERR_DEBUG:
2045 pfx = "debug: ";
2046 break;
2047 default:
2048 pfx = "";
2049 break;
2052 vsnprintf(msg, sizeof msg - 64, fmt, args);
2053 if ((severity & (ERR_WARN_MASK|ERR_PP_LISTMACRO)) == ERR_WARN_MASK) {
2054 char *p = strchr(msg, '\0');
2055 snprintf(p, 64, " [-w+%s]", warnings[WARN_IDX(severity)].name);
2058 if (!skip_this_pass(severity))
2059 fprintf(error_file, "%s%s\n", pfx, msg);
2061 /* Are we recursing from error_list_macros? */
2062 if (severity & ERR_PP_LISTMACRO)
2063 return;
2066 * Don't suppress this with skip_this_pass(), or we don't get
2067 * pass1 or preprocessor warnings in the list file
2069 lfmt->error(severity, pfx, msg);
2071 if (severity & ERR_USAGE)
2072 want_usage = true;
2074 preproc->error_list_macros(severity);
2076 switch (severity & ERR_MASK) {
2077 case ERR_DEBUG:
2078 /* no further action, by definition */
2079 break;
2080 case ERR_WARNING:
2081 /* Treat warnings as errors */
2082 if (warning_on[WARN_IDX(ERR_WARN_TERM)])
2083 terminate_after_phase = true;
2084 break;
2085 case ERR_NONFATAL:
2086 terminate_after_phase = true;
2087 break;
2088 case ERR_FATAL:
2089 if (ofile) {
2090 fclose(ofile);
2091 remove(outname);
2092 ofile = NULL;
2094 if (want_usage)
2095 usage();
2096 exit(1); /* instantly die */
2097 break; /* placate silly compilers */
2098 case ERR_PANIC:
2099 fflush(NULL);
2100 /* abort(); */ /* halt, catch fire, and dump core */
2101 if (ofile) {
2102 fclose(ofile);
2103 remove(outname);
2104 ofile = NULL;
2106 exit(3);
2107 break;
2111 static void usage(void)
2113 fputs("type `nasm -h' for help\n", error_file);
2116 static iflag_t get_cpu(char *value)
2118 iflag_t r;
2120 iflag_clear_all(&r);
2122 if (!strcmp(value, "8086"))
2123 iflag_set(&r, IF_8086);
2124 else if (!strcmp(value, "186"))
2125 iflag_set(&r, IF_186);
2126 else if (!strcmp(value, "286"))
2127 iflag_set(&r, IF_286);
2128 else if (!strcmp(value, "386"))
2129 iflag_set(&r, IF_386);
2130 else if (!strcmp(value, "486"))
2131 iflag_set(&r, IF_486);
2132 else if (!strcmp(value, "586") ||
2133 !nasm_stricmp(value, "pentium"))
2134 iflag_set(&r, IF_PENT);
2135 else if (!strcmp(value, "686") ||
2136 !nasm_stricmp(value, "ppro") ||
2137 !nasm_stricmp(value, "pentiumpro") ||
2138 !nasm_stricmp(value, "p2"))
2139 iflag_set(&r, IF_P6);
2140 else if (!nasm_stricmp(value, "p3") ||
2141 !nasm_stricmp(value, "katmai"))
2142 iflag_set(&r, IF_KATMAI);
2143 else if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2144 !nasm_stricmp(value, "willamette"))
2145 iflag_set(&r, IF_WILLAMETTE);
2146 else if (!nasm_stricmp(value, "prescott"))
2147 iflag_set(&r, IF_PRESCOTT);
2148 else if (!nasm_stricmp(value, "x64") ||
2149 !nasm_stricmp(value, "x86-64"))
2150 iflag_set(&r, IF_X86_64);
2151 else if (!nasm_stricmp(value, "ia64") ||
2152 !nasm_stricmp(value, "ia-64") ||
2153 !nasm_stricmp(value, "itanium")||
2154 !nasm_stricmp(value, "itanic") ||
2155 !nasm_stricmp(value, "merced"))
2156 iflag_set(&r, IF_IA64);
2157 else {
2158 iflag_set(&r, IF_PLEVEL);
2159 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2160 "unknown 'cpu' type");
2162 return r;
2165 static int get_bits(char *value)
2167 int i;
2169 if ((i = atoi(value)) == 16)
2170 return i; /* set for a 16-bit segment */
2171 else if (i == 32) {
2172 if (iflag_ffs(&cpu) < IF_386) {
2173 nasm_error(ERR_NONFATAL,
2174 "cannot specify 32-bit segment on processor below a 386");
2175 i = 16;
2177 } else if (i == 64) {
2178 if (iflag_ffs(&cpu) < IF_X86_64) {
2179 nasm_error(ERR_NONFATAL,
2180 "cannot specify 64-bit segment on processor below an x86-64");
2181 i = 16;
2183 } else {
2184 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2185 "`%s' is not a valid segment size; must be 16, 32 or 64",
2186 value);
2187 i = 16;
2189 return i;