nasm.c: consistently use the 'murrican spelling "optimize"
[nasm.git] / nasm.c
blob8d7283550535eeefa7303d11371a29d6f9729506
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2009 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"
64 struct forwrefinfo { /* info held on forward refs. */
65 int lineno;
66 int operand;
69 static int get_bits(char *value);
70 static uint32_t get_cpu(char *cpu_str);
71 static void parse_cmdline(int, char **);
72 static void assemble_file(char *, StrList **);
73 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
74 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
75 static void nasm_verror_common(int severity, const char *fmt, va_list args);
76 static bool is_suppressed_warning(int severity);
77 static void usage(void);
79 static int using_debug_info, opt_verbose_info;
80 bool tasm_compatible_mode = false;
81 int pass0, passn;
82 int maxbits = 0;
83 int globalrel = 0;
85 static time_t official_compile_time;
87 static char inname[FILENAME_MAX];
88 static char outname[FILENAME_MAX];
89 static char listname[FILENAME_MAX];
90 static char errname[FILENAME_MAX];
91 static int globallineno; /* for forward-reference tracking */
92 /* static int pass = 0; */
93 struct ofmt *ofmt = &OF_DEFAULT;
94 const struct dfmt *dfmt;
96 static FILE *error_file; /* Where to write error messages */
98 FILE *ofile = NULL;
99 int optimizing = -1; /* number of optimization passes to take */
100 static int sb, cmd_sb = 16; /* by default */
101 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
102 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
103 int64_t global_offset_changed; /* referenced in labels.c */
104 int64_t prev_offset_changed;
105 int32_t stall_count;
107 static struct location location;
108 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
109 int32_t abs_seg; /* ABSOLUTE segment basis */
110 int32_t abs_offset; /* ABSOLUTE offset */
112 static struct RAA *offsets;
114 static struct SAA *forwrefs; /* keep track of forward references */
115 static const struct forwrefinfo *forwref;
117 static Preproc *preproc;
118 enum op_type {
119 op_normal, /* Preprocess and assemble */
120 op_preprocess, /* Preprocess only */
121 op_depend, /* Generate dependencies */
123 static enum op_type operating_mode;
124 /* Dependency flags */
125 static bool depend_emit_phony = false;
126 static bool depend_missing_ok = false;
127 static const char *depend_target = NULL;
128 static const char *depend_file = NULL;
131 * Which of the suppressible warnings are suppressed. Entry zero
132 * isn't an actual warning, but it used for -w+error/-Werror.
135 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
136 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
138 static const struct warning {
139 const char *name;
140 const char *help;
141 bool enabled;
142 } warnings[ERR_WARN_MAX+1] = {
143 {"error", "treat warnings as errors", false},
144 {"macro-params", "macro calls with wrong parameter count", true},
145 {"macro-selfref", "cyclic macro references", false},
146 {"macro-defaults", "macros with more default than optional parameters", true},
147 {"orphan-labels", "labels alone on lines without trailing `:'", true},
148 {"number-overflow", "numeric constant does not fit", true},
149 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
150 {"float-overflow", "floating point overflow", true},
151 {"float-denorm", "floating point denormal", false},
152 {"float-underflow", "floating point underflow", false},
153 {"float-toolong", "too many digits in floating-point number", true},
154 {"user", "%warning directives", true},
158 * This is a null preprocessor which just copies lines from input
159 * to output. It's used when someone explicitly requests that NASM
160 * not preprocess their source file.
163 static void no_pp_reset(char *, int, ListGen *, StrList **);
164 static char *no_pp_getline(void);
165 static void no_pp_cleanup(int);
166 static Preproc no_pp = {
167 no_pp_reset,
168 no_pp_getline,
169 no_pp_cleanup
173 * get/set current offset...
175 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
176 raa_read(offsets,location.segment))
177 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
178 (void)(offsets=raa_write(offsets,location.segment,(x))))
180 static bool want_usage;
181 static bool terminate_after_phase;
182 int user_nolist = 0; /* fbk 9/2/00 */
184 static void nasm_fputs(const char *line, FILE * outfile)
186 if (outfile) {
187 fputs(line, outfile);
188 putc('\n', outfile);
189 } else
190 puts(line);
193 /* Convert a struct tm to a POSIX-style time constant */
194 static int64_t posix_mktime(struct tm *tm)
196 int64_t t;
197 int64_t y = tm->tm_year;
199 /* See IEEE 1003.1:2004, section 4.14 */
201 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
202 t += tm->tm_yday;
203 t *= 24;
204 t += tm->tm_hour;
205 t *= 60;
206 t += tm->tm_min;
207 t *= 60;
208 t += tm->tm_sec;
210 return t;
213 static void define_macros_early(void)
215 char temp[128];
216 struct tm lt, *lt_p, gm, *gm_p;
217 int64_t posix_time;
219 lt_p = localtime(&official_compile_time);
220 if (lt_p) {
221 lt = *lt_p;
223 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
224 pp_pre_define(temp);
225 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
226 pp_pre_define(temp);
227 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
228 pp_pre_define(temp);
229 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
230 pp_pre_define(temp);
233 gm_p = gmtime(&official_compile_time);
234 if (gm_p) {
235 gm = *gm_p;
237 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
238 pp_pre_define(temp);
239 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
240 pp_pre_define(temp);
241 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
242 pp_pre_define(temp);
243 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
244 pp_pre_define(temp);
247 if (gm_p)
248 posix_time = posix_mktime(&gm);
249 else if (lt_p)
250 posix_time = posix_mktime(&lt);
251 else
252 posix_time = 0;
254 if (posix_time) {
255 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
256 pp_pre_define(temp);
260 static void define_macros_late(void)
262 char temp[128];
264 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
265 ofmt->shortname);
266 pp_pre_define(temp);
269 static void emit_dependencies(StrList *list)
271 FILE *deps;
272 int linepos, len;
273 StrList *l, *nl;
275 if (depend_file && strcmp(depend_file, "-")) {
276 deps = fopen(depend_file, "w");
277 if (!deps) {
278 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
279 "unable to write dependency file `%s'", depend_file);
280 return;
282 } else {
283 deps = stdout;
286 linepos = fprintf(deps, "%s:", depend_target);
287 list_for_each(l, list) {
288 len = strlen(l->str);
289 if (linepos + len > 62) {
290 fprintf(deps, " \\\n ");
291 linepos = 1;
293 fprintf(deps, " %s", l->str);
294 linepos += len+1;
296 fprintf(deps, "\n\n");
298 list_for_each_safe(l, nl, list) {
299 if (depend_emit_phony)
300 fprintf(deps, "%s:\n\n", l->str);
301 nasm_free(l);
304 if (deps != stdout)
305 fclose(deps);
308 int main(int argc, char **argv)
310 StrList *depend_list = NULL, **depend_ptr;
312 time(&official_compile_time);
314 pass0 = 0;
315 want_usage = terminate_after_phase = false;
316 nasm_set_verror(nasm_verror_gnu);
318 error_file = stderr;
320 tolower_init();
322 nasm_init_malloc_error();
323 offsets = raa_init();
324 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
326 preproc = &nasmpp;
327 operating_mode = op_normal;
329 seg_init();
331 /* Define some macros dependent on the runtime, but not
332 on the command line. */
333 define_macros_early();
335 parse_cmdline(argc, argv);
337 if (terminate_after_phase) {
338 if (want_usage)
339 usage();
340 return 1;
343 /* If debugging info is disabled, suppress any debug calls */
344 if (!using_debug_info)
345 ofmt->current_dfmt = &null_debug_form;
347 if (ofmt->stdmac)
348 pp_extra_stdmac(ofmt->stdmac);
349 parser_global_info(&location);
350 eval_global_info(ofmt, lookup_label, &location);
352 /* define some macros dependent of command-line */
353 define_macros_late();
355 depend_ptr = (depend_file || (operating_mode == op_depend))
356 ? &depend_list : NULL;
357 if (!depend_target)
358 depend_target = outname;
360 switch (operating_mode) {
361 case op_depend:
363 char *line;
365 if (depend_missing_ok)
366 pp_include_path(NULL); /* "assume generated" */
368 preproc->reset(inname, 0, &nasmlist, depend_ptr);
369 if (outname[0] == '\0')
370 ofmt->filename(inname, outname);
371 ofile = NULL;
372 while ((line = preproc->getline()))
373 nasm_free(line);
374 preproc->cleanup(0);
376 break;
378 case op_preprocess:
380 char *line;
381 char *file_name = NULL;
382 int32_t prior_linnum = 0;
383 int lineinc = 0;
385 if (*outname) {
386 ofile = fopen(outname, "w");
387 if (!ofile)
388 nasm_error(ERR_FATAL | ERR_NOFILE,
389 "unable to open output file `%s'",
390 outname);
391 } else
392 ofile = NULL;
394 location.known = false;
396 /* pass = 1; */
397 preproc->reset(inname, 3, &nasmlist, depend_ptr);
399 while ((line = preproc->getline())) {
401 * We generate %line directives if needed for later programs
403 int32_t linnum = prior_linnum += lineinc;
404 int altline = src_get(&linnum, &file_name);
405 if (altline) {
406 if (altline == 1 && lineinc == 1)
407 nasm_fputs("", ofile);
408 else {
409 lineinc = (altline != -1 || lineinc != 1);
410 fprintf(ofile ? ofile : stdout,
411 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
412 file_name);
414 prior_linnum = linnum;
416 nasm_fputs(line, ofile);
417 nasm_free(line);
419 nasm_free(file_name);
420 preproc->cleanup(0);
421 if (ofile)
422 fclose(ofile);
423 if (ofile && terminate_after_phase)
424 remove(outname);
425 ofile = NULL;
427 break;
429 case op_normal:
432 * We must call ofmt->filename _anyway_, even if the user
433 * has specified their own output file, because some
434 * formats (eg OBJ and COFF) use ofmt->filename to find out
435 * the name of the input file and then put that inside the
436 * file.
438 ofmt->filename(inname, outname);
440 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
441 if (!ofile) {
442 nasm_error(ERR_FATAL | ERR_NOFILE,
443 "unable to open output file `%s'", outname);
447 * We must call init_labels() before ofmt->init() since
448 * some object formats will want to define labels in their
449 * init routines. (eg OS/2 defines the FLAT group)
451 init_labels();
453 ofmt->init();
454 dfmt = ofmt->current_dfmt;
455 dfmt->init();
457 assemble_file(inname, depend_ptr);
459 if (!terminate_after_phase) {
460 ofmt->cleanup(using_debug_info);
461 cleanup_labels();
462 fflush(ofile);
463 if (ferror(ofile)) {
464 nasm_error(ERR_NONFATAL|ERR_NOFILE,
465 "write error on output file `%s'", outname);
469 if (ofile) {
470 fclose(ofile);
471 if (terminate_after_phase)
472 remove(outname);
473 ofile = NULL;
476 break;
479 if (depend_list && !terminate_after_phase)
480 emit_dependencies(depend_list);
482 if (want_usage)
483 usage();
485 raa_free(offsets);
486 saa_free(forwrefs);
487 eval_cleanup();
488 stdscan_cleanup();
490 return terminate_after_phase;
494 * Get a parameter for a command line option.
495 * First arg must be in the form of e.g. -f...
497 static char *get_param(char *p, char *q, bool *advance)
499 *advance = false;
500 if (p[2]) { /* the parameter's in the option */
501 p += 2;
502 while (nasm_isspace(*p))
503 p++;
504 return p;
506 if (q && q[0]) {
507 *advance = true;
508 return q;
510 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
511 "option `-%c' requires an argument", p[1]);
512 return NULL;
516 * Copy a filename
518 static void copy_filename(char *dst, const char *src)
520 size_t len = strlen(src);
522 if (len >= (size_t)FILENAME_MAX) {
523 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
524 return;
526 strncpy(dst, src, FILENAME_MAX);
530 * Convert a string to Make-safe form
532 static char *quote_for_make(const char *str)
534 const char *p;
535 char *os, *q;
537 size_t n = 1; /* Terminating zero */
538 size_t nbs = 0;
540 if (!str)
541 return NULL;
543 for (p = str; *p; p++) {
544 switch (*p) {
545 case ' ':
546 case '\t':
547 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
548 n += nbs + 2;
549 nbs = 0;
550 break;
551 case '$':
552 case '#':
553 nbs = 0;
554 n += 2;
555 break;
556 case '\\':
557 nbs++;
558 n++;
559 break;
560 default:
561 nbs = 0;
562 n++;
563 break;
567 /* Convert N backslashes at the end of filename to 2N backslashes */
568 if (nbs)
569 n += nbs;
571 os = q = nasm_malloc(n);
573 nbs = 0;
574 for (p = str; *p; p++) {
575 switch (*p) {
576 case ' ':
577 case '\t':
578 while (nbs--)
579 *q++ = '\\';
580 *q++ = '\\';
581 *q++ = *p;
582 break;
583 case '$':
584 *q++ = *p;
585 *q++ = *p;
586 nbs = 0;
587 break;
588 case '#':
589 *q++ = '\\';
590 *q++ = *p;
591 nbs = 0;
592 break;
593 case '\\':
594 *q++ = *p;
595 nbs++;
596 break;
597 default:
598 *q++ = *p;
599 nbs = 0;
600 break;
603 while (nbs--)
604 *q++ = '\\';
606 *q = '\0';
608 return os;
611 struct textargs {
612 const char *label;
613 int value;
616 #define OPT_PREFIX 0
617 #define OPT_POSTFIX 1
618 struct textargs textopts[] = {
619 {"prefix", OPT_PREFIX},
620 {"postfix", OPT_POSTFIX},
621 {NULL, 0}
624 static bool stopoptions = false;
625 static bool process_arg(char *p, char *q)
627 char *param;
628 int i;
629 bool advance = false;
630 bool do_warn;
632 if (!p || !p[0])
633 return false;
635 if (p[0] == '-' && !stopoptions) {
636 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
637 /* These parameters take values */
638 if (!(param = get_param(p, q, &advance)))
639 return advance;
642 switch (p[1]) {
643 case 's':
644 error_file = stdout;
645 break;
647 case 'o': /* output file */
648 copy_filename(outname, param);
649 break;
651 case 'f': /* output format */
652 ofmt = ofmt_find(param);
653 if (!ofmt) {
654 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
655 "unrecognised output format `%s' - "
656 "use -hf for a list", param);
658 break;
660 case 'O': /* Optimization level */
662 int opt;
664 if (!*param) {
665 /* Naked -O == -Ox */
666 optimizing = INT_MAX >> 1; /* Almost unlimited */
667 } else {
668 while (*param) {
669 switch (*param) {
670 case '0': case '1': case '2': case '3': case '4':
671 case '5': case '6': case '7': case '8': case '9':
672 opt = strtoul(param, &param, 10);
674 /* -O0 -> optimizing == -1, 0.98 behaviour */
675 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
676 if (opt < 2)
677 optimizing = opt - 1;
678 else
679 optimizing = opt;
680 break;
682 case 'v':
683 case '+':
684 param++;
685 opt_verbose_info = true;
686 break;
688 case 'x':
689 param++;
690 optimizing = INT_MAX >> 1; /* Almost unlimited */
691 break;
693 default:
694 nasm_error(ERR_FATAL,
695 "unknown optimization option -O%c\n",
696 *param);
697 break;
701 break;
704 case 'p': /* pre-include */
705 case 'P':
706 pp_pre_include(param);
707 break;
709 case 'd': /* pre-define */
710 case 'D':
711 pp_pre_define(param);
712 break;
714 case 'u': /* un-define */
715 case 'U':
716 pp_pre_undefine(param);
717 break;
719 case 'i': /* include search path */
720 case 'I':
721 pp_include_path(param);
722 break;
724 case 'l': /* listing file */
725 copy_filename(listname, param);
726 break;
728 case 'Z': /* error messages file */
729 strcpy(errname, param);
730 break;
732 case 'F': /* specify debug format */
733 ofmt->current_dfmt = dfmt_find(ofmt, param);
734 if (!ofmt->current_dfmt) {
735 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
736 "unrecognized debug format `%s' for"
737 " output format `%s'",
738 param, ofmt->shortname);
740 using_debug_info = true;
741 break;
743 case 'X': /* specify error reporting format */
744 if (nasm_stricmp("vc", param) == 0)
745 nasm_set_verror(nasm_verror_vc);
746 else if (nasm_stricmp("gnu", param) == 0)
747 nasm_set_verror(nasm_verror_gnu);
748 else
749 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
750 "unrecognized error reporting format `%s'",
751 param);
752 break;
754 case 'g':
755 using_debug_info = true;
756 break;
758 case 'h':
759 printf
760 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
761 "[-l listfile]\n"
762 " [options...] [--] filename\n"
763 " or nasm -v for version info\n\n"
764 " -t assemble in SciTech TASM compatible mode\n"
765 " -g generate debug information in selected format\n");
766 printf
767 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
768 " -a don't preprocess (assemble only)\n"
769 " -M generate Makefile dependencies on stdout\n"
770 " -MG d:o, missing files assumed generated\n"
771 " -MF <file> set Makefile dependency file\n"
772 " -MD <file> assemble and generate dependencies\n"
773 " -MT <file> dependency target name\n"
774 " -MQ <file> dependency target name (quoted)\n"
775 " -MP emit phony target\n\n"
776 " -Z<file> redirect error messages to file\n"
777 " -s redirect error messages to stdout\n\n"
778 " -F format select a debugging format\n\n"
779 " -I<path> adds a pathname to the include file path\n");
780 printf
781 (" -O<digit> optimize branch offsets\n"
782 " -O0: No optimization (default)\n"
783 " -O1: Minimal optimization\n"
784 " -Ox: Multipass optimization (recommended)\n\n"
785 " -P<file> pre-includes a file\n"
786 " -D<macro>[=<value>] pre-defines a macro\n"
787 " -U<macro> undefines a macro\n"
788 " -X<format> specifies error reporting format (gnu or vc)\n"
789 " -w+foo enables warning foo (equiv. -Wfoo)\n"
790 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
791 "--prefix,--postfix\n"
792 " this options prepend or append the given argument to all\n"
793 " extern and global variables\n\n"
794 "Warnings:\n");
795 for (i = 0; i <= ERR_WARN_MAX; i++)
796 printf(" %-23s %s (default %s)\n",
797 warnings[i].name, warnings[i].help,
798 warnings[i].enabled ? "on" : "off");
799 printf
800 ("\nresponse files should contain command line parameters"
801 ", one per line.\n");
802 if (p[2] == 'f') {
803 printf("\nvalid output formats for -f are"
804 " (`*' denotes default):\n");
805 ofmt_list(ofmt, stdout);
806 } else {
807 printf("\nFor a list of valid output formats, use -hf.\n");
808 printf("For a list of debug formats, use -f <form> -y.\n");
810 exit(0); /* never need usage message here */
811 break;
813 case 'y':
814 printf("\nvalid debug formats for '%s' output format are"
815 " ('*' denotes default):\n", ofmt->shortname);
816 dfmt_list(ofmt, stdout);
817 exit(0);
818 break;
820 case 't':
821 tasm_compatible_mode = true;
822 break;
824 case 'v':
825 printf("NASM version %s compiled on %s%s\n",
826 nasm_version, nasm_date, nasm_compile_options);
827 exit(0); /* never need usage message here */
828 break;
830 case 'e': /* preprocess only */
831 case 'E':
832 operating_mode = op_preprocess;
833 break;
835 case 'a': /* assemble only - don't preprocess */
836 preproc = &no_pp;
837 break;
839 case 'W':
840 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
841 do_warn = false;
842 param += 3;
843 } else {
844 do_warn = true;
846 goto set_warning;
848 case 'w':
849 if (param[0] != '+' && param[0] != '-') {
850 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
851 "invalid option to `-w'");
852 break;
854 do_warn = (param[0] == '+');
855 param++;
856 goto set_warning;
857 set_warning:
858 for (i = 0; i <= ERR_WARN_MAX; i++)
859 if (!nasm_stricmp(param, warnings[i].name))
860 break;
861 if (i <= ERR_WARN_MAX)
862 warning_on_global[i] = do_warn;
863 else if (!nasm_stricmp(param, "all"))
864 for (i = 1; i <= ERR_WARN_MAX; i++)
865 warning_on_global[i] = do_warn;
866 else if (!nasm_stricmp(param, "none"))
867 for (i = 1; i <= ERR_WARN_MAX; i++)
868 warning_on_global[i] = !do_warn;
869 else
870 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
871 "invalid warning `%s'", param);
872 break;
874 case 'M':
875 switch (p[2]) {
876 case 0:
877 operating_mode = op_depend;
878 break;
879 case 'G':
880 operating_mode = op_depend;
881 depend_missing_ok = true;
882 break;
883 case 'P':
884 depend_emit_phony = true;
885 break;
886 case 'D':
887 depend_file = q;
888 advance = true;
889 break;
890 case 'T':
891 depend_target = q;
892 advance = true;
893 break;
894 case 'Q':
895 depend_target = quote_for_make(q);
896 advance = true;
897 break;
898 default:
899 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
900 "unknown dependency option `-M%c'", p[2]);
901 break;
903 if (advance && (!q || !q[0])) {
904 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
905 "option `-M%c' requires a parameter", p[2]);
906 break;
908 break;
910 case '-':
912 int s;
914 if (p[2] == 0) { /* -- => stop processing options */
915 stopoptions = 1;
916 break;
918 for (s = 0; textopts[s].label; s++) {
919 if (!nasm_stricmp(p + 2, textopts[s].label)) {
920 break;
924 switch (s) {
926 case OPT_PREFIX:
927 case OPT_POSTFIX:
929 if (!q) {
930 nasm_error(ERR_NONFATAL | ERR_NOFILE |
931 ERR_USAGE,
932 "option `--%s' requires an argument",
933 p + 2);
934 break;
935 } else {
936 advance = 1, param = q;
939 if (s == OPT_PREFIX) {
940 strncpy(lprefix, param, PREFIX_MAX - 1);
941 lprefix[PREFIX_MAX - 1] = 0;
942 break;
944 if (s == OPT_POSTFIX) {
945 strncpy(lpostfix, param, POSTFIX_MAX - 1);
946 lpostfix[POSTFIX_MAX - 1] = 0;
947 break;
949 break;
951 default:
953 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
954 "unrecognised option `--%s'", p + 2);
955 break;
958 break;
961 default:
962 if (!ofmt->setinfo(GI_SWITCH, &p))
963 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
964 "unrecognised option `-%c'", p[1]);
965 break;
967 } else {
968 if (*inname) {
969 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
970 "more than one input file specified");
971 } else {
972 copy_filename(inname, p);
976 return advance;
979 #define ARG_BUF_DELTA 128
981 static void process_respfile(FILE * rfile)
983 char *buffer, *p, *q, *prevarg;
984 int bufsize, prevargsize;
986 bufsize = prevargsize = ARG_BUF_DELTA;
987 buffer = nasm_malloc(ARG_BUF_DELTA);
988 prevarg = nasm_malloc(ARG_BUF_DELTA);
989 prevarg[0] = '\0';
991 while (1) { /* Loop to handle all lines in file */
992 p = buffer;
993 while (1) { /* Loop to handle long lines */
994 q = fgets(p, bufsize - (p - buffer), rfile);
995 if (!q)
996 break;
997 p += strlen(p);
998 if (p > buffer && p[-1] == '\n')
999 break;
1000 if (p - buffer > bufsize - 10) {
1001 int offset;
1002 offset = p - buffer;
1003 bufsize += ARG_BUF_DELTA;
1004 buffer = nasm_realloc(buffer, bufsize);
1005 p = buffer + offset;
1009 if (!q && p == buffer) {
1010 if (prevarg[0])
1011 process_arg(prevarg, NULL);
1012 nasm_free(buffer);
1013 nasm_free(prevarg);
1014 return;
1018 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1019 * them are present at the end of the line.
1021 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1023 while (p > buffer && nasm_isspace(p[-1]))
1024 *--p = '\0';
1026 p = buffer;
1027 while (nasm_isspace(*p))
1028 p++;
1030 if (process_arg(prevarg, p))
1031 *p = '\0';
1033 if ((int) strlen(p) > prevargsize - 10) {
1034 prevargsize += ARG_BUF_DELTA;
1035 prevarg = nasm_realloc(prevarg, prevargsize);
1037 strncpy(prevarg, p, prevargsize);
1041 /* Function to process args from a string of args, rather than the
1042 * argv array. Used by the environment variable and response file
1043 * processing.
1045 static void process_args(char *args)
1047 char *p, *q, *arg, *prevarg;
1048 char separator = ' ';
1050 p = args;
1051 if (*p && *p != '-')
1052 separator = *p++;
1053 arg = NULL;
1054 while (*p) {
1055 q = p;
1056 while (*p && *p != separator)
1057 p++;
1058 while (*p == separator)
1059 *p++ = '\0';
1060 prevarg = arg;
1061 arg = q;
1062 if (process_arg(prevarg, arg))
1063 arg = NULL;
1065 if (arg)
1066 process_arg(arg, NULL);
1069 static void process_response_file(const char *file)
1071 char str[2048];
1072 FILE *f = fopen(file, "r");
1073 if (!f) {
1074 perror(file);
1075 exit(-1);
1077 while (fgets(str, sizeof str, f)) {
1078 process_args(str);
1080 fclose(f);
1083 static void parse_cmdline(int argc, char **argv)
1085 FILE *rfile;
1086 char *envreal, *envcopy = NULL, *p, *arg;
1087 int i;
1089 *inname = *outname = *listname = *errname = '\0';
1090 for (i = 0; i <= ERR_WARN_MAX; i++)
1091 warning_on_global[i] = warnings[i].enabled;
1094 * First, process the NASMENV environment variable.
1096 envreal = getenv("NASMENV");
1097 arg = NULL;
1098 if (envreal) {
1099 envcopy = nasm_strdup(envreal);
1100 process_args(envcopy);
1101 nasm_free(envcopy);
1105 * Now process the actual command line.
1107 while (--argc) {
1108 bool advance;
1109 argv++;
1110 if (argv[0][0] == '@') {
1111 /* We have a response file, so process this as a set of
1112 * arguments like the environment variable. This allows us
1113 * to have multiple arguments on a single line, which is
1114 * different to the -@resp file processing below for regular
1115 * NASM.
1117 process_response_file(argv[0]+1);
1118 argc--;
1119 argv++;
1121 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1122 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1123 if (p) {
1124 rfile = fopen(p, "r");
1125 if (rfile) {
1126 process_respfile(rfile);
1127 fclose(rfile);
1128 } else
1129 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1130 "unable to open response file `%s'", p);
1132 } else
1133 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1134 argv += advance, argc -= advance;
1137 /* Look for basic command line typos. This definitely doesn't
1138 catch all errors, but it might help cases of fumbled fingers. */
1139 if (!*inname)
1140 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1141 "no input file specified");
1142 else if (!strcmp(inname, errname) ||
1143 !strcmp(inname, outname) ||
1144 !strcmp(inname, listname) ||
1145 (depend_file && !strcmp(inname, depend_file)))
1146 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1147 "file `%s' is both input and output file",
1148 inname);
1150 if (*errname) {
1151 error_file = fopen(errname, "w");
1152 if (!error_file) {
1153 error_file = stderr; /* Revert to default! */
1154 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1155 "cannot open file `%s' for error messages",
1156 errname);
1161 static enum directives getkw(char **directive, char **value);
1163 static void assemble_file(char *fname, StrList **depend_ptr)
1165 char *directive, *value, *p, *q, *special, *line, debugid[80];
1166 insn output_ins;
1167 int i, validid;
1168 bool rn_error;
1169 int32_t seg;
1170 int64_t offs;
1171 struct tokenval tokval;
1172 expr *e;
1173 int pass_max;
1175 if (cmd_sb == 32 && cmd_cpu < IF_386)
1176 nasm_error(ERR_FATAL, "command line: "
1177 "32-bit segment size requires a higher cpu");
1179 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1180 for (passn = 1; pass0 <= 2; passn++) {
1181 int pass1, pass2;
1182 ldfunc def_label;
1184 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1185 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1186 /* pass0 0, 0, 0, ..., 1, 2 */
1188 def_label = passn > 1 ? redefine_label : define_label;
1190 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1191 cpu = cmd_cpu;
1192 if (pass0 == 2) {
1193 if (*listname)
1194 nasmlist.init(listname, nasm_error);
1196 in_abs_seg = false;
1197 global_offset_changed = 0; /* set by redefine_label */
1198 location.segment = ofmt->section(NULL, pass2, &sb);
1199 globalbits = sb;
1200 if (passn > 1) {
1201 saa_rewind(forwrefs);
1202 forwref = saa_rstruct(forwrefs);
1203 raa_free(offsets);
1204 offsets = raa_init();
1206 preproc->reset(fname, pass1, &nasmlist,
1207 pass1 == 2 ? depend_ptr : NULL);
1208 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1210 globallineno = 0;
1211 if (passn == 1)
1212 location.known = true;
1213 location.offset = offs = GET_CURR_OFFS;
1215 while ((line = preproc->getline())) {
1216 enum directives d;
1217 globallineno++;
1220 * Here we parse our directives; this is not handled by the
1221 * 'real' parser. This really should be a separate function.
1223 directive = line;
1224 d = getkw(&directive, &value);
1225 if (d) {
1226 int err = 0;
1228 switch (d) {
1229 case D_SEGMENT: /* [SEGMENT n] */
1230 case D_SECTION:
1231 seg = ofmt->section(value, pass2, &sb);
1232 if (seg == NO_SEG) {
1233 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1234 "segment name `%s' not recognized",
1235 value);
1236 } else {
1237 in_abs_seg = false;
1238 location.segment = seg;
1240 break;
1241 case D_EXTERN: /* [EXTERN label:special] */
1242 if (*value == '$')
1243 value++; /* skip initial $ if present */
1244 if (pass0 == 2) {
1245 q = value;
1246 while (*q && *q != ':')
1247 q++;
1248 if (*q == ':') {
1249 *q++ = '\0';
1250 ofmt->symdef(value, 0L, 0L, 3, q);
1252 } else if (passn == 1) {
1253 q = value;
1254 validid = true;
1255 if (!isidstart(*q))
1256 validid = false;
1257 while (*q && *q != ':') {
1258 if (!isidchar(*q))
1259 validid = false;
1260 q++;
1262 if (!validid) {
1263 nasm_error(ERR_NONFATAL,
1264 "identifier expected after EXTERN");
1265 break;
1267 if (*q == ':') {
1268 *q++ = '\0';
1269 special = q;
1270 } else
1271 special = NULL;
1272 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1273 int temp = pass0;
1274 pass0 = 1; /* fake pass 1 in labels.c */
1275 declare_as_global(value, special);
1276 define_label(value, seg_alloc(), 0L, NULL,
1277 false, true);
1278 pass0 = temp;
1280 } /* else pass0 == 1 */
1281 break;
1282 case D_BITS: /* [BITS bits] */
1283 globalbits = sb = get_bits(value);
1284 break;
1285 case D_GLOBAL: /* [GLOBAL symbol:special] */
1286 if (*value == '$')
1287 value++; /* skip initial $ if present */
1288 if (pass0 == 2) { /* pass 2 */
1289 q = value;
1290 while (*q && *q != ':')
1291 q++;
1292 if (*q == ':') {
1293 *q++ = '\0';
1294 ofmt->symdef(value, 0L, 0L, 3, q);
1296 } else if (pass2 == 1) { /* pass == 1 */
1297 q = value;
1298 validid = true;
1299 if (!isidstart(*q))
1300 validid = false;
1301 while (*q && *q != ':') {
1302 if (!isidchar(*q))
1303 validid = false;
1304 q++;
1306 if (!validid) {
1307 nasm_error(ERR_NONFATAL,
1308 "identifier expected after GLOBAL");
1309 break;
1311 if (*q == ':') {
1312 *q++ = '\0';
1313 special = q;
1314 } else
1315 special = NULL;
1316 declare_as_global(value, special);
1317 } /* pass == 1 */
1318 break;
1319 case D_COMMON: /* [COMMON symbol size:special] */
1321 int64_t size;
1323 if (*value == '$')
1324 value++; /* skip initial $ if present */
1325 p = value;
1326 validid = true;
1327 if (!isidstart(*p))
1328 validid = false;
1329 while (*p && !nasm_isspace(*p)) {
1330 if (!isidchar(*p))
1331 validid = false;
1332 p++;
1334 if (!validid) {
1335 nasm_error(ERR_NONFATAL,
1336 "identifier expected after COMMON");
1337 break;
1339 if (*p) {
1340 while (*p && nasm_isspace(*p))
1341 *p++ = '\0';
1342 q = p;
1343 while (*q && *q != ':')
1344 q++;
1345 if (*q == ':') {
1346 *q++ = '\0';
1347 special = q;
1348 } else {
1349 special = NULL;
1351 size = readnum(p, &rn_error);
1352 if (rn_error) {
1353 nasm_error(ERR_NONFATAL,
1354 "invalid size specified"
1355 " in COMMON declaration");
1356 break;
1358 } else {
1359 nasm_error(ERR_NONFATAL,
1360 "no size specified in"
1361 " COMMON declaration");
1362 break;
1365 if (pass0 < 2) {
1366 define_common(value, seg_alloc(), size, special);
1367 } else if (pass0 == 2) {
1368 if (special)
1369 ofmt->symdef(value, 0L, 0L, 3, special);
1371 break;
1373 case D_ABSOLUTE: /* [ABSOLUTE address] */
1374 stdscan_reset();
1375 stdscan_bufptr = value;
1376 tokval.t_type = TOKEN_INVALID;
1377 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1378 nasm_error, NULL);
1379 if (e) {
1380 if (!is_reloc(e))
1381 nasm_error(pass0 ==
1382 1 ? ERR_NONFATAL : ERR_PANIC,
1383 "cannot use non-relocatable expression as "
1384 "ABSOLUTE address");
1385 else {
1386 abs_seg = reloc_seg(e);
1387 abs_offset = reloc_value(e);
1389 } else if (passn == 1)
1390 abs_offset = 0x100; /* don't go near zero in case of / */
1391 else
1392 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1393 "in pass two");
1394 in_abs_seg = true;
1395 location.segment = NO_SEG;
1396 break;
1397 case D_DEBUG: /* [DEBUG] */
1398 p = value;
1399 q = debugid;
1400 validid = true;
1401 if (!isidstart(*p))
1402 validid = false;
1403 while (*p && !nasm_isspace(*p)) {
1404 if (!isidchar(*p))
1405 validid = false;
1406 *q++ = *p++;
1408 *q++ = 0;
1409 if (!validid) {
1410 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1411 "identifier expected after DEBUG");
1412 break;
1414 while (*p && nasm_isspace(*p))
1415 p++;
1416 if (pass0 == 2)
1417 dfmt->debug_directive(debugid, p);
1418 break;
1419 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1420 while (*value && nasm_isspace(*value))
1421 value++;
1423 switch(*value) {
1424 case '-': validid = 0; value++; break;
1425 case '+': validid = 1; value++; break;
1426 case '*': validid = 2; value++; break;
1427 default: validid = 1; break;
1430 for (i = 1; i <= ERR_WARN_MAX; i++)
1431 if (!nasm_stricmp(value, warnings[i].name))
1432 break;
1433 if (i <= ERR_WARN_MAX) {
1434 switch(validid) {
1435 case 0:
1436 warning_on[i] = false;
1437 break;
1438 case 1:
1439 warning_on[i] = true;
1440 break;
1441 case 2:
1442 warning_on[i] = warning_on_global[i];
1443 break;
1446 else
1447 nasm_error(ERR_NONFATAL,
1448 "invalid warning id in WARNING directive");
1449 break;
1450 case D_CPU: /* [CPU] */
1451 cpu = get_cpu(value);
1452 break;
1453 case D_LIST: /* [LIST {+|-}] */
1454 while (*value && nasm_isspace(*value))
1455 value++;
1457 if (*value == '+') {
1458 user_nolist = 0;
1459 } else {
1460 if (*value == '-') {
1461 user_nolist = 1;
1462 } else {
1463 err = 1;
1466 break;
1467 case D_DEFAULT: /* [DEFAULT] */
1468 stdscan_reset();
1469 stdscan_bufptr = value;
1470 tokval.t_type = TOKEN_INVALID;
1471 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1472 switch ((int)tokval.t_integer) {
1473 case S_REL:
1474 globalrel = 1;
1475 break;
1476 case S_ABS:
1477 globalrel = 0;
1478 break;
1479 default:
1480 err = 1;
1481 break;
1483 } else {
1484 err = 1;
1486 break;
1487 case D_FLOAT:
1488 if (float_option(value)) {
1489 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1490 "unknown 'float' directive: %s",
1491 value);
1493 break;
1494 default:
1495 if (!d || !ofmt->directive(d, value, pass2))
1496 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1497 "unrecognised directive [%s]",
1498 directive);
1499 break;
1501 if (err) {
1502 nasm_error(ERR_NONFATAL,
1503 "invalid parameter to [%s] directive",
1504 directive);
1506 } else { /* it isn't a directive */
1507 parse_line(pass1, line, &output_ins, def_label);
1509 if (optimizing > 0) {
1510 if (forwref != NULL && globallineno == forwref->lineno) {
1511 output_ins.forw_ref = true;
1512 do {
1513 output_ins.oprs[forwref->operand].opflags |=
1514 OPFLAG_FORWARD;
1515 forwref = saa_rstruct(forwrefs);
1516 } while (forwref != NULL
1517 && forwref->lineno == globallineno);
1518 } else
1519 output_ins.forw_ref = false;
1521 if (output_ins.forw_ref) {
1522 if (passn == 1) {
1523 for (i = 0; i < output_ins.operands; i++) {
1524 if (output_ins.oprs[i].
1525 opflags & OPFLAG_FORWARD) {
1526 struct forwrefinfo *fwinf =
1527 (struct forwrefinfo *)
1528 saa_wstruct(forwrefs);
1529 fwinf->lineno = globallineno;
1530 fwinf->operand = i;
1537 /* forw_ref */
1538 if (output_ins.opcode == I_EQU) {
1539 if (pass1 == 1) {
1541 * Special `..' EQUs get processed in pass two,
1542 * except `..@' macro-processor EQUs which are done
1543 * in the normal place.
1545 if (!output_ins.label)
1546 nasm_error(ERR_NONFATAL,
1547 "EQU not preceded by label");
1549 else if (output_ins.label[0] != '.' ||
1550 output_ins.label[1] != '.' ||
1551 output_ins.label[2] == '@') {
1552 if (output_ins.operands == 1 &&
1553 (output_ins.oprs[0].type & IMMEDIATE) &&
1554 output_ins.oprs[0].wrt == NO_SEG) {
1555 bool isext = !!(output_ins.oprs[0].opflags
1556 & OPFLAG_EXTERN);
1557 def_label(output_ins.label,
1558 output_ins.oprs[0].segment,
1559 output_ins.oprs[0].offset, NULL,
1560 false, isext);
1561 } else if (output_ins.operands == 2
1562 && (output_ins.oprs[0].type & IMMEDIATE)
1563 && (output_ins.oprs[0].type & COLON)
1564 && output_ins.oprs[0].segment == NO_SEG
1565 && output_ins.oprs[0].wrt == NO_SEG
1566 && (output_ins.oprs[1].type & IMMEDIATE)
1567 && output_ins.oprs[1].segment == NO_SEG
1568 && output_ins.oprs[1].wrt == NO_SEG) {
1569 def_label(output_ins.label,
1570 output_ins.oprs[0].offset | SEG_ABS,
1571 output_ins.oprs[1].offset,
1572 NULL, false, false);
1573 } else
1574 nasm_error(ERR_NONFATAL,
1575 "bad syntax for EQU");
1577 } else {
1579 * Special `..' EQUs get processed here, except
1580 * `..@' macro processor EQUs which are done above.
1582 if (output_ins.label[0] == '.' &&
1583 output_ins.label[1] == '.' &&
1584 output_ins.label[2] != '@') {
1585 if (output_ins.operands == 1 &&
1586 (output_ins.oprs[0].type & IMMEDIATE)) {
1587 define_label(output_ins.label,
1588 output_ins.oprs[0].segment,
1589 output_ins.oprs[0].offset,
1590 NULL, false, false);
1591 } else if (output_ins.operands == 2
1592 && (output_ins.oprs[0].
1593 type & IMMEDIATE)
1594 && (output_ins.oprs[0].type & COLON)
1595 && output_ins.oprs[0].segment ==
1596 NO_SEG
1597 && (output_ins.oprs[1].
1598 type & IMMEDIATE)
1599 && output_ins.oprs[1].segment ==
1600 NO_SEG) {
1601 define_label(output_ins.label,
1602 output_ins.oprs[0].
1603 offset | SEG_ABS,
1604 output_ins.oprs[1].offset,
1605 NULL, false, false);
1606 } else
1607 nasm_error(ERR_NONFATAL,
1608 "bad syntax for EQU");
1611 } else { /* instruction isn't an EQU */
1613 if (pass1 == 1) {
1615 int64_t l = insn_size(location.segment, offs, sb, cpu,
1616 &output_ins, nasm_error);
1618 /* if (using_debug_info) && output_ins.opcode != -1) */
1619 if (using_debug_info)
1620 { /* fbk 03/25/01 */
1621 /* this is done here so we can do debug type info */
1622 int32_t typeinfo =
1623 TYS_ELEMENTS(output_ins.operands);
1624 switch (output_ins.opcode) {
1625 case I_RESB:
1626 typeinfo =
1627 TYS_ELEMENTS(output_ins.oprs[0].
1628 offset) | TY_BYTE;
1629 break;
1630 case I_RESW:
1631 typeinfo =
1632 TYS_ELEMENTS(output_ins.oprs[0].
1633 offset) | TY_WORD;
1634 break;
1635 case I_RESD:
1636 typeinfo =
1637 TYS_ELEMENTS(output_ins.oprs[0].
1638 offset) | TY_DWORD;
1639 break;
1640 case I_RESQ:
1641 typeinfo =
1642 TYS_ELEMENTS(output_ins.oprs[0].
1643 offset) | TY_QWORD;
1644 break;
1645 case I_REST:
1646 typeinfo =
1647 TYS_ELEMENTS(output_ins.oprs[0].
1648 offset) | TY_TBYTE;
1649 break;
1650 case I_RESO:
1651 typeinfo =
1652 TYS_ELEMENTS(output_ins.oprs[0].
1653 offset) | TY_OWORD;
1654 break;
1655 case I_RESY:
1656 typeinfo =
1657 TYS_ELEMENTS(output_ins.oprs[0].
1658 offset) | TY_YWORD;
1659 break;
1660 case I_DB:
1661 typeinfo |= TY_BYTE;
1662 break;
1663 case I_DW:
1664 typeinfo |= TY_WORD;
1665 break;
1666 case I_DD:
1667 if (output_ins.eops_float)
1668 typeinfo |= TY_FLOAT;
1669 else
1670 typeinfo |= TY_DWORD;
1671 break;
1672 case I_DQ:
1673 typeinfo |= TY_QWORD;
1674 break;
1675 case I_DT:
1676 typeinfo |= TY_TBYTE;
1677 break;
1678 case I_DO:
1679 typeinfo |= TY_OWORD;
1680 break;
1681 case I_DY:
1682 typeinfo |= TY_YWORD;
1683 break;
1684 default:
1685 typeinfo = TY_LABEL;
1689 dfmt->debug_typevalue(typeinfo);
1691 if (l != -1) {
1692 offs += l;
1693 SET_CURR_OFFS(offs);
1696 * else l == -1 => invalid instruction, which will be
1697 * flagged as an error on pass 2
1700 } else {
1701 offs += assemble(location.segment, offs, sb, cpu,
1702 &output_ins, ofmt, nasm_error,
1703 &nasmlist);
1704 SET_CURR_OFFS(offs);
1707 } /* not an EQU */
1708 cleanup_insn(&output_ins);
1710 nasm_free(line);
1711 location.offset = offs = GET_CURR_OFFS;
1712 } /* end while (line = preproc->getline... */
1714 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1715 nasm_error(ERR_NONFATAL,
1716 "phase error detected at end of assembly.");
1718 if (pass1 == 1)
1719 preproc->cleanup(1);
1721 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1722 pass0++;
1723 } else if (global_offset_changed &&
1724 global_offset_changed < prev_offset_changed) {
1725 prev_offset_changed = global_offset_changed;
1726 stall_count = 0;
1727 } else {
1728 stall_count++;
1731 if (terminate_after_phase)
1732 break;
1734 if ((stall_count > 997) || (passn >= pass_max)) {
1735 /* We get here if the labels don't converge
1736 * Example: FOO equ FOO + 1
1738 nasm_error(ERR_NONFATAL,
1739 "Can't find valid values for all labels "
1740 "after %d passes, giving up.", passn);
1741 nasm_error(ERR_NONFATAL,
1742 "Possible causes: recursive EQUs, macro abuse.");
1743 break;
1747 preproc->cleanup(0);
1748 nasmlist.cleanup();
1749 if (!terminate_after_phase && opt_verbose_info) {
1750 /* -On and -Ov switches */
1751 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1755 static enum directives getkw(char **directive, char **value)
1757 char *p, *q, *buf;
1759 buf = *directive;
1761 /* allow leading spaces or tabs */
1762 while (*buf == ' ' || *buf == '\t')
1763 buf++;
1765 if (*buf != '[')
1766 return 0;
1768 p = buf;
1770 while (*p && *p != ']')
1771 p++;
1773 if (!*p)
1774 return 0;
1776 q = p++;
1778 while (*p && *p != ';') {
1779 if (!nasm_isspace(*p))
1780 return 0;
1781 p++;
1783 q[1] = '\0';
1785 *directive = p = buf + 1;
1786 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1787 buf++;
1788 if (*buf == ']') {
1789 *buf = '\0';
1790 *value = buf;
1791 } else {
1792 *buf++ = '\0';
1793 while (nasm_isspace(*buf))
1794 buf++; /* beppu - skip leading whitespace */
1795 *value = buf;
1796 while (*buf != ']')
1797 buf++;
1798 *buf++ = '\0';
1801 return find_directive(*directive);
1805 * gnu style error reporting
1806 * This function prints an error message to error_file in the
1807 * style used by GNU. An example would be:
1808 * file.asm:50: error: blah blah blah
1809 * where file.asm is the name of the file, 50 is the line number on
1810 * which the error occurs (or is detected) and "error:" is one of
1811 * the possible optional diagnostics -- it can be "error" or "warning"
1812 * or something else. Finally the line terminates with the actual
1813 * error message.
1815 * @param severity the severity of the warning or error
1816 * @param fmt the printf style format string
1818 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1820 char *currentfile = NULL;
1821 int32_t lineno = 0;
1823 if (is_suppressed_warning(severity))
1824 return;
1826 if (!(severity & ERR_NOFILE))
1827 src_get(&lineno, &currentfile);
1829 if (currentfile) {
1830 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1831 nasm_free(currentfile);
1832 } else {
1833 fputs("nasm: ", error_file);
1836 nasm_verror_common(severity, fmt, ap);
1840 * MS style error reporting
1841 * This function prints an error message to error_file in the
1842 * style used by Visual C and some other Microsoft tools. An example
1843 * would be:
1844 * file.asm(50) : error: blah blah blah
1845 * where file.asm is the name of the file, 50 is the line number on
1846 * which the error occurs (or is detected) and "error:" is one of
1847 * the possible optional diagnostics -- it can be "error" or "warning"
1848 * or something else. Finally the line terminates with the actual
1849 * error message.
1851 * @param severity the severity of the warning or error
1852 * @param fmt the printf style format string
1854 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1856 char *currentfile = NULL;
1857 int32_t lineno = 0;
1859 if (is_suppressed_warning(severity))
1860 return;
1862 if (!(severity & ERR_NOFILE))
1863 src_get(&lineno, &currentfile);
1865 if (currentfile) {
1866 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1867 nasm_free(currentfile);
1868 } else {
1869 fputs("nasm: ", error_file);
1872 nasm_verror_common(severity, fmt, ap);
1876 * check for supressed warning
1877 * checks for suppressed warning or pass one only warning and we're
1878 * not in pass 1
1880 * @param severity the severity of the warning or error
1881 * @return true if we should abort error/warning printing
1883 static bool is_suppressed_warning(int severity)
1886 * See if it's a suppressed warning.
1888 return (severity & ERR_MASK) == ERR_WARNING &&
1889 (((severity & ERR_WARN_MASK) != 0 &&
1890 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1891 /* See if it's a pass-one only warning and we're not in pass one. */
1892 ((severity & ERR_PASS1) && pass0 != 1) ||
1893 ((severity & ERR_PASS2) && pass0 != 2));
1897 * common error reporting
1898 * This is the common back end of the error reporting schemes currently
1899 * implemented. It prints the nature of the warning and then the
1900 * specific error message to error_file and may or may not return. It
1901 * doesn't return if the error severity is a "panic" or "debug" type.
1903 * @param severity the severity of the warning or error
1904 * @param fmt the printf style format string
1906 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1908 char msg[1024];
1909 const char *pfx;
1911 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1912 case ERR_WARNING:
1913 pfx = "warning: ";
1914 break;
1915 case ERR_NONFATAL:
1916 pfx = "error: ";
1917 break;
1918 case ERR_FATAL:
1919 pfx = "fatal: ";
1920 break;
1921 case ERR_PANIC:
1922 pfx = "panic: ";
1923 break;
1924 case ERR_DEBUG:
1925 pfx = "debug: ";
1926 break;
1927 default:
1928 pfx = "";
1929 break;
1932 vsnprintf(msg, sizeof msg, fmt, args);
1934 fprintf(error_file, "%s%s\n", pfx, msg);
1936 if (*listname)
1937 nasmlist.error(severity, pfx, msg);
1939 if (severity & ERR_USAGE)
1940 want_usage = true;
1942 switch (severity & ERR_MASK) {
1943 case ERR_DEBUG:
1944 /* no further action, by definition */
1945 break;
1946 case ERR_WARNING:
1947 if (warning_on[0]) /* Treat warnings as errors */
1948 terminate_after_phase = true;
1949 break;
1950 case ERR_NONFATAL:
1951 terminate_after_phase = true;
1952 break;
1953 case ERR_FATAL:
1954 if (ofile) {
1955 fclose(ofile);
1956 remove(outname);
1957 ofile = NULL;
1959 if (want_usage)
1960 usage();
1961 exit(1); /* instantly die */
1962 break; /* placate silly compilers */
1963 case ERR_PANIC:
1964 fflush(NULL);
1965 /* abort(); *//* halt, catch fire, and dump core */
1966 exit(3);
1967 break;
1971 static void usage(void)
1973 fputs("type `nasm -h' for help\n", error_file);
1976 #define BUF_DELTA 512
1978 static FILE *no_pp_fp;
1979 static ListGen *no_pp_list;
1980 static int32_t no_pp_lineinc;
1982 static void no_pp_reset(char *file, int pass, ListGen * listgen,
1983 StrList **deplist)
1985 src_set_fname(nasm_strdup(file));
1986 src_set_linnum(0);
1987 no_pp_lineinc = 1;
1988 no_pp_fp = fopen(file, "r");
1989 if (!no_pp_fp)
1990 nasm_error(ERR_FATAL | ERR_NOFILE,
1991 "unable to open input file `%s'", file);
1992 no_pp_list = listgen;
1993 (void)pass; /* placate compilers */
1995 if (deplist) {
1996 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1997 sl->next = NULL;
1998 strcpy(sl->str, file);
1999 *deplist = sl;
2003 static char *no_pp_getline(void)
2005 char *buffer, *p, *q;
2006 int bufsize;
2008 bufsize = BUF_DELTA;
2009 buffer = nasm_malloc(BUF_DELTA);
2010 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2012 while (1) { /* Loop to handle %line */
2014 p = buffer;
2015 while (1) { /* Loop to handle long lines */
2016 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2017 if (!q)
2018 break;
2019 p += strlen(p);
2020 if (p > buffer && p[-1] == '\n')
2021 break;
2022 if (p - buffer > bufsize - 10) {
2023 int offset;
2024 offset = p - buffer;
2025 bufsize += BUF_DELTA;
2026 buffer = nasm_realloc(buffer, bufsize);
2027 p = buffer + offset;
2031 if (!q && p == buffer) {
2032 nasm_free(buffer);
2033 return NULL;
2037 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2038 * them are present at the end of the line.
2040 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2042 if (!nasm_strnicmp(buffer, "%line", 5)) {
2043 int32_t ln;
2044 int li;
2045 char *nm = nasm_malloc(strlen(buffer));
2046 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2047 nasm_free(src_set_fname(nm));
2048 src_set_linnum(ln);
2049 no_pp_lineinc = li;
2050 continue;
2052 nasm_free(nm);
2054 break;
2057 no_pp_list->line(LIST_READ, buffer);
2059 return buffer;
2062 static void no_pp_cleanup(int pass)
2064 (void)pass; /* placate GCC */
2065 fclose(no_pp_fp);
2068 static uint32_t get_cpu(char *value)
2070 if (!strcmp(value, "8086"))
2071 return IF_8086;
2072 if (!strcmp(value, "186"))
2073 return IF_186;
2074 if (!strcmp(value, "286"))
2075 return IF_286;
2076 if (!strcmp(value, "386"))
2077 return IF_386;
2078 if (!strcmp(value, "486"))
2079 return IF_486;
2080 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2081 return IF_PENT;
2082 if (!strcmp(value, "686") ||
2083 !nasm_stricmp(value, "ppro") ||
2084 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2085 return IF_P6;
2086 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2087 return IF_KATMAI;
2088 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2089 !nasm_stricmp(value, "willamette"))
2090 return IF_WILLAMETTE;
2091 if (!nasm_stricmp(value, "prescott"))
2092 return IF_PRESCOTT;
2093 if (!nasm_stricmp(value, "x64") ||
2094 !nasm_stricmp(value, "x86-64"))
2095 return IF_X86_64;
2096 if (!nasm_stricmp(value, "ia64") ||
2097 !nasm_stricmp(value, "ia-64") ||
2098 !nasm_stricmp(value, "itanium") ||
2099 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2100 return IF_IA64;
2102 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2103 "unknown 'cpu' type");
2105 return IF_PLEVEL; /* the maximum level */
2108 static int get_bits(char *value)
2110 int i;
2112 if ((i = atoi(value)) == 16)
2113 return i; /* set for a 16-bit segment */
2114 else if (i == 32) {
2115 if (cpu < IF_386) {
2116 nasm_error(ERR_NONFATAL,
2117 "cannot specify 32-bit segment on processor below a 386");
2118 i = 16;
2120 } else if (i == 64) {
2121 if (cpu < IF_X86_64) {
2122 nasm_error(ERR_NONFATAL,
2123 "cannot specify 64-bit segment on processor below an x86-64");
2124 i = 16;
2126 if (i != maxbits) {
2127 nasm_error(ERR_NONFATAL,
2128 "%s output format does not support 64-bit code",
2129 ofmt->shortname);
2130 i = 16;
2132 } else {
2133 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2134 "`%s' is not a valid segment size; must be 16, 32 or 64",
2135 value);
2136 i = 16;
2138 return i;
2141 /* end of nasm.c */