headers/doc: copyright header for documentation files
[nasm/avx512.git] / nasm.c
blob3def14ebf3a37a2a3736f78b7ad8bfc739c7403b
1 /* ----------------------------------------------------------------------- *
2 *
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 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation, Inc.,
10 * 51 Franklin St, Fifth Floor, Boston MA 02110-1301, USA; version 2.1,
11 * or, at your option, any later version, incorporated herein by
12 * reference.
14 * Patches submitted to this file are required to be dual licensed
15 * under the LGPL 2.1+ and the 2-clause BSD license:
17 * Copyright 1996-2009 the NASM Authors - All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following
21 * conditions are met:
23 * * Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * * Redistributions in binary form must reproduce the above
26 * copyright notice, this list of conditions and the following
27 * disclaimer in the documentation and/or other materials provided
28 * with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
31 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
32 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
34 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
38 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
40 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
41 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
42 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 * ----------------------------------------------------------------------- */
46 /*
47 * The Netwide Assembler main program module
50 #include "compiler.h"
52 #include <stdio.h>
53 #include <stdarg.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <ctype.h>
57 #include <inttypes.h>
58 #include <limits.h>
59 #include <time.h>
61 #include "nasm.h"
62 #include "nasmlib.h"
63 #include "saa.h"
64 #include "raa.h"
65 #include "float.h"
66 #include "stdscan.h"
67 #include "insns.h"
68 #include "preproc.h"
69 #include "parser.h"
70 #include "eval.h"
71 #include "assemble.h"
72 #include "labels.h"
73 #include "output/outform.h"
74 #include "listing.h"
76 struct forwrefinfo { /* info held on forward refs. */
77 int lineno;
78 int operand;
81 static int get_bits(char *value);
82 static uint32_t get_cpu(char *cpu_str);
83 static void parse_cmdline(int, char **);
84 static void assemble_file(char *, StrList **);
85 static void register_output_formats(void);
86 static void report_error_gnu(int severity, const char *fmt, ...);
87 static void report_error_vc(int severity, const char *fmt, ...);
88 static void report_error_common(int severity, const char *fmt,
89 va_list args);
90 static bool is_suppressed_warning(int severity);
91 static void usage(void);
92 static efunc report_error;
94 static int using_debug_info, opt_verbose_info;
95 bool tasm_compatible_mode = false;
96 int pass0, passn;
97 int maxbits = 0;
98 int globalrel = 0;
100 time_t official_compile_time;
102 static char inname[FILENAME_MAX];
103 static char outname[FILENAME_MAX];
104 static char listname[FILENAME_MAX];
105 static char errname[FILENAME_MAX];
106 static int globallineno; /* for forward-reference tracking */
107 /* static int pass = 0; */
108 static struct ofmt *ofmt = NULL;
110 static FILE *error_file; /* Where to write error messages */
112 static FILE *ofile = NULL;
113 int optimizing = -1; /* number of optimization passes to take */
114 static int sb, cmd_sb = 16; /* by default */
115 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
116 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
117 int64_t global_offset_changed; /* referenced in labels.c */
118 int64_t prev_offset_changed;
119 int32_t stall_count;
121 static 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 Preproc *preproc;
132 enum op_type {
133 op_normal, /* Preprocess and assemble */
134 op_preprocess, /* Preprocess only */
135 op_depend, /* Generate dependencies */
137 static enum op_type operating_mode;
138 /* Dependency flags */
139 static bool depend_emit_phony = false;
140 static bool depend_missing_ok = false;
141 static const char *depend_target = NULL;
142 static const char *depend_file = NULL;
145 * Which of the suppressible warnings are suppressed. Entry zero
146 * isn't an actual warning, but it used for -w+error/-Werror.
149 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
150 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
152 static const struct warning {
153 const char *name;
154 const char *help;
155 bool enabled;
156 } warnings[ERR_WARN_MAX+1] = {
157 {"error", "treat warnings as errors", false},
158 {"macro-params", "macro calls with wrong parameter count", true},
159 {"macro-selfref", "cyclic macro references", false},
160 {"macro-defaults", "macros with more default than optional parameters", true},
161 {"orphan-labels", "labels alone on lines without trailing `:'", true},
162 {"number-overflow", "numeric constant does not fit", true},
163 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
164 {"float-overflow", "floating point overflow", true},
165 {"float-denorm", "floating point denormal", false},
166 {"float-underflow", "floating point underflow", false},
167 {"float-toolong", "too many digits in floating-point number", true},
168 {"user", "%warning directives", true},
172 * This is a null preprocessor which just copies lines from input
173 * to output. It's used when someone explicitly requests that NASM
174 * not preprocess their source file.
177 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
178 static char *no_pp_getline(void);
179 static void no_pp_cleanup(int);
180 static Preproc no_pp = {
181 no_pp_reset,
182 no_pp_getline,
183 no_pp_cleanup
187 * get/set current offset...
189 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
190 raa_read(offsets,location.segment))
191 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
192 (void)(offsets=raa_write(offsets,location.segment,(x))))
194 static bool want_usage;
195 static bool terminate_after_phase;
196 int user_nolist = 0; /* fbk 9/2/00 */
198 static void nasm_fputs(const char *line, FILE * outfile)
200 if (outfile) {
201 fputs(line, outfile);
202 putc('\n', outfile);
203 } else
204 puts(line);
207 /* Convert a struct tm to a POSIX-style time constant */
208 static int64_t posix_mktime(struct tm *tm)
210 int64_t t;
211 int64_t y = tm->tm_year;
213 /* See IEEE 1003.1:2004, section 4.14 */
215 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
216 t += tm->tm_yday;
217 t *= 24;
218 t += tm->tm_hour;
219 t *= 60;
220 t += tm->tm_min;
221 t *= 60;
222 t += tm->tm_sec;
224 return t;
227 static void define_macros_early(void)
229 char temp[128];
230 struct tm lt, *lt_p, gm, *gm_p;
231 int64_t posix_time;
233 lt_p = localtime(&official_compile_time);
234 if (lt_p) {
235 lt = *lt_p;
237 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", &lt);
238 pp_pre_define(temp);
239 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", &lt);
240 pp_pre_define(temp);
241 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", &lt);
242 pp_pre_define(temp);
243 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", &lt);
244 pp_pre_define(temp);
247 gm_p = gmtime(&official_compile_time);
248 if (gm_p) {
249 gm = *gm_p;
251 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
252 pp_pre_define(temp);
253 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
254 pp_pre_define(temp);
255 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
256 pp_pre_define(temp);
257 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
258 pp_pre_define(temp);
261 if (gm_p)
262 posix_time = posix_mktime(&gm);
263 else if (lt_p)
264 posix_time = posix_mktime(&lt);
265 else
266 posix_time = 0;
268 if (posix_time) {
269 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
270 pp_pre_define(temp);
274 static void define_macros_late(void)
276 char temp[128];
278 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
279 ofmt->shortname);
280 pp_pre_define(temp);
283 static void emit_dependencies(StrList *list)
285 FILE *deps;
286 int linepos, len;
287 StrList *l, *nl;
289 if (depend_file && strcmp(depend_file, "-")) {
290 deps = fopen(depend_file, "w");
291 if (!deps) {
292 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
293 "unable to write dependency file `%s'", depend_file);
294 return;
296 } else {
297 deps = stdout;
300 linepos = fprintf(deps, "%s:", depend_target);
301 for (l = list; l; l = l->next) {
302 len = strlen(l->str);
303 if (linepos + len > 62) {
304 fprintf(deps, " \\\n ");
305 linepos = 1;
307 fprintf(deps, " %s", l->str);
308 linepos += len+1;
310 fprintf(deps, "\n\n");
312 for (l = list; l; l = nl) {
313 if (depend_emit_phony)
314 fprintf(deps, "%s:\n\n", l->str);
316 nl = l->next;
317 nasm_free(l);
320 if (deps != stdout)
321 fclose(deps);
324 int main(int argc, char **argv)
326 StrList *depend_list = NULL, **depend_ptr;
328 time(&official_compile_time);
330 pass0 = 0;
331 want_usage = terminate_after_phase = false;
332 report_error = report_error_gnu;
334 error_file = stderr;
336 tolower_init();
338 nasm_set_malloc_error(report_error);
339 offsets = raa_init();
340 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
342 preproc = &nasmpp;
343 operating_mode = op_normal;
345 seg_init();
347 register_output_formats();
349 /* Define some macros dependent on the runtime, but not
350 on the command line. */
351 define_macros_early();
353 parse_cmdline(argc, argv);
355 if (terminate_after_phase) {
356 if (want_usage)
357 usage();
358 return 1;
361 /* If debugging info is disabled, suppress any debug calls */
362 if (!using_debug_info)
363 ofmt->current_dfmt = &null_debug_form;
365 if (ofmt->stdmac)
366 pp_extra_stdmac(ofmt->stdmac);
367 parser_global_info(ofmt, &location);
368 eval_global_info(ofmt, lookup_label, &location);
370 /* define some macros dependent of command-line */
371 define_macros_late();
373 depend_ptr = (depend_file || (operating_mode == op_depend))
374 ? &depend_list : NULL;
375 if (!depend_target)
376 depend_target = outname;
378 switch (operating_mode) {
379 case op_depend:
381 char *line;
383 if (depend_missing_ok)
384 pp_include_path(NULL); /* "assume generated" */
386 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
387 depend_ptr);
388 if (outname[0] == '\0')
389 ofmt->filename(inname, outname, report_error);
390 ofile = NULL;
391 while ((line = preproc->getline()))
392 nasm_free(line);
393 preproc->cleanup(0);
395 break;
397 case op_preprocess:
399 char *line;
400 char *file_name = NULL;
401 int32_t prior_linnum = 0;
402 int lineinc = 0;
404 if (*outname) {
405 ofile = fopen(outname, "w");
406 if (!ofile)
407 report_error(ERR_FATAL | ERR_NOFILE,
408 "unable to open output file `%s'",
409 outname);
410 } else
411 ofile = NULL;
413 location.known = false;
415 /* pass = 1; */
416 preproc->reset(inname, 3, report_error, evaluate, &nasmlist,
417 depend_ptr);
419 while ((line = preproc->getline())) {
421 * We generate %line directives if needed for later programs
423 int32_t linnum = prior_linnum += lineinc;
424 int altline = src_get(&linnum, &file_name);
425 if (altline) {
426 if (altline == 1 && lineinc == 1)
427 nasm_fputs("", ofile);
428 else {
429 lineinc = (altline != -1 || lineinc != 1);
430 fprintf(ofile ? ofile : stdout,
431 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
432 file_name);
434 prior_linnum = linnum;
436 nasm_fputs(line, ofile);
437 nasm_free(line);
439 nasm_free(file_name);
440 preproc->cleanup(0);
441 if (ofile)
442 fclose(ofile);
443 if (ofile && terminate_after_phase)
444 remove(outname);
446 break;
448 case op_normal:
451 * We must call ofmt->filename _anyway_, even if the user
452 * has specified their own output file, because some
453 * formats (eg OBJ and COFF) use ofmt->filename to find out
454 * the name of the input file and then put that inside the
455 * file.
457 ofmt->filename(inname, outname, report_error);
459 ofile = fopen(outname, "wb");
460 if (!ofile) {
461 report_error(ERR_FATAL | ERR_NOFILE,
462 "unable to open output file `%s'", outname);
466 * We must call init_labels() before ofmt->init() since
467 * some object formats will want to define labels in their
468 * init routines. (eg OS/2 defines the FLAT group)
470 init_labels();
472 ofmt->init(ofile, report_error, define_label, evaluate);
473 ofmt->current_dfmt->init(ofmt, NULL, ofile, report_error);
475 assemble_file(inname, depend_ptr);
477 if (!terminate_after_phase) {
478 ofmt->cleanup(using_debug_info);
479 cleanup_labels();
480 } else {
482 * Despite earlier comments, we need this fclose.
483 * The object output drivers only fclose on cleanup,
484 * and we just skipped that.
486 fclose (ofile);
488 remove(outname);
489 if (listname[0])
490 remove(listname);
493 break;
496 if (depend_list && !terminate_after_phase)
497 emit_dependencies(depend_list);
499 if (want_usage)
500 usage();
502 raa_free(offsets);
503 saa_free(forwrefs);
504 eval_cleanup();
505 stdscan_cleanup();
507 return terminate_after_phase;
511 * Get a parameter for a command line option.
512 * First arg must be in the form of e.g. -f...
514 static char *get_param(char *p, char *q, bool *advance)
516 *advance = false;
517 if (p[2]) { /* the parameter's in the option */
518 p += 2;
519 while (nasm_isspace(*p))
520 p++;
521 return p;
523 if (q && q[0]) {
524 *advance = true;
525 return q;
527 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
528 "option `-%c' requires an argument", p[1]);
529 return NULL;
533 * Copy a filename
535 static void copy_filename(char *dst, const char *src)
537 size_t len = strlen(src);
539 if (len >= (size_t)FILENAME_MAX) {
540 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
541 return;
543 strncpy(dst, src, FILENAME_MAX);
547 * Convert a string to Make-safe form
549 static char *quote_for_make(const char *str)
551 const char *p;
552 char *os, *q;
554 size_t n = 1; /* Terminating zero */
555 size_t nbs = 0;
557 if (!str)
558 return NULL;
560 for (p = str; *p; p++) {
561 switch (*p) {
562 case ' ':
563 case '\t':
564 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
565 n += nbs + 2;
566 nbs = 0;
567 break;
568 case '$':
569 case '#':
570 nbs = 0;
571 n += 2;
572 break;
573 case '\\':
574 nbs++;
575 n++;
576 break;
577 default:
578 nbs = 0;
579 n++;
580 break;
584 /* Convert N backslashes at the end of filename to 2N backslashes */
585 if (nbs)
586 n += nbs;
588 os = q = nasm_malloc(n);
590 nbs = 0;
591 for (p = str; *p; p++) {
592 switch (*p) {
593 case ' ':
594 case '\t':
595 while (nbs--)
596 *q++ = '\\';
597 *q++ = '\\';
598 *q++ = *p;
599 break;
600 case '$':
601 *q++ = *p;
602 *q++ = *p;
603 nbs = 0;
604 break;
605 case '#':
606 *q++ = '\\';
607 *q++ = *p;
608 nbs = 0;
609 break;
610 case '\\':
611 *q++ = *p;
612 nbs++;
613 break;
614 default:
615 *q++ = *p;
616 nbs = 0;
617 break;
620 while (nbs--)
621 *q++ = '\\';
623 *q = '\0';
625 return os;
628 struct textargs {
629 const char *label;
630 int value;
633 #define OPT_PREFIX 0
634 #define OPT_POSTFIX 1
635 struct textargs textopts[] = {
636 {"prefix", OPT_PREFIX},
637 {"postfix", OPT_POSTFIX},
638 {NULL, 0}
641 static bool stopoptions = false;
642 static bool process_arg(char *p, char *q)
644 char *param;
645 int i;
646 bool advance = false;
647 bool do_warn;
649 if (!p || !p[0])
650 return false;
652 if (p[0] == '-' && !stopoptions) {
653 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
654 /* These parameters take values */
655 if (!(param = get_param(p, q, &advance)))
656 return advance;
659 switch (p[1]) {
660 case 's':
661 error_file = stdout;
662 break;
664 case 'o': /* output file */
665 copy_filename(outname, param);
666 break;
668 case 'f': /* output format */
669 ofmt = ofmt_find(param);
670 if (!ofmt) {
671 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
672 "unrecognised output format `%s' - "
673 "use -hf for a list", param);
675 break;
677 case 'O': /* Optimization level */
679 int opt;
681 if (!*param) {
682 /* Naked -O == -Ox */
683 optimizing = INT_MAX >> 1; /* Almost unlimited */
684 } else {
685 while (*param) {
686 switch (*param) {
687 case '0': case '1': case '2': case '3': case '4':
688 case '5': case '6': case '7': case '8': case '9':
689 opt = strtoul(param, &param, 10);
691 /* -O0 -> optimizing == -1, 0.98 behaviour */
692 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
693 if (opt < 2)
694 optimizing = opt - 1;
695 else
696 optimizing = opt;
697 break;
699 case 'v':
700 case '+':
701 param++;
702 opt_verbose_info = true;
703 break;
705 case 'x':
706 param++;
707 optimizing = INT_MAX >> 1; /* Almost unlimited */
708 break;
710 default:
711 report_error(ERR_FATAL,
712 "unknown optimization option -O%c\n",
713 *param);
714 break;
718 break;
721 case 'p': /* pre-include */
722 case 'P':
723 pp_pre_include(param);
724 break;
726 case 'd': /* pre-define */
727 case 'D':
728 pp_pre_define(param);
729 break;
731 case 'u': /* un-define */
732 case 'U':
733 pp_pre_undefine(param);
734 break;
736 case 'i': /* include search path */
737 case 'I':
738 pp_include_path(param);
739 break;
741 case 'l': /* listing file */
742 copy_filename(listname, param);
743 break;
745 case 'Z': /* error messages file */
746 strcpy(errname, param);
747 break;
749 case 'F': /* specify debug format */
750 ofmt->current_dfmt = dfmt_find(ofmt, param);
751 if (!ofmt->current_dfmt) {
752 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
753 "unrecognized debug format `%s' for"
754 " output format `%s'",
755 param, ofmt->shortname);
757 using_debug_info = true;
758 break;
760 case 'X': /* specify error reporting format */
761 if (nasm_stricmp("vc", param) == 0)
762 report_error = report_error_vc;
763 else if (nasm_stricmp("gnu", param) == 0)
764 report_error = report_error_gnu;
765 else
766 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
767 "unrecognized error reporting format `%s'",
768 param);
769 break;
771 case 'g':
772 using_debug_info = true;
773 break;
775 case 'h':
776 printf
777 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
778 "[-l listfile]\n"
779 " [options...] [--] filename\n"
780 " or nasm -v for version info\n\n"
781 " -t assemble in SciTech TASM compatible mode\n"
782 " -g generate debug information in selected format.\n");
783 printf
784 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
785 " -a don't preprocess (assemble only)\n"
786 " -M generate Makefile dependencies on stdout\n"
787 " -MG d:o, missing files assumed generated\n\n"
788 " -Z<file> redirect error messages to file\n"
789 " -s redirect error messages to stdout\n\n"
790 " -F format select a debugging format\n\n"
791 " -I<path> adds a pathname to the include file path\n");
792 printf
793 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
794 " -P<file> pre-includes a file\n"
795 " -D<macro>[=<value>] pre-defines a macro\n"
796 " -U<macro> undefines a macro\n"
797 " -X<format> specifies error reporting format (gnu or vc)\n"
798 " -w+foo enables warning foo (equiv. -Wfoo)\n"
799 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
800 "Warnings:\n");
801 for (i = 0; i <= ERR_WARN_MAX; i++)
802 printf(" %-23s %s (default %s)\n",
803 warnings[i].name, warnings[i].help,
804 warnings[i].enabled ? "on" : "off");
805 printf
806 ("\nresponse files should contain command line parameters"
807 ", one per line.\n");
808 if (p[2] == 'f') {
809 printf("\nvalid output formats for -f are"
810 " (`*' denotes default):\n");
811 ofmt_list(ofmt, stdout);
812 } else {
813 printf("\nFor a list of valid output formats, use -hf.\n");
814 printf("For a list of debug formats, use -f <form> -y.\n");
816 exit(0); /* never need usage message here */
817 break;
819 case 'y':
820 printf("\nvalid debug formats for '%s' output format are"
821 " ('*' denotes default):\n", ofmt->shortname);
822 dfmt_list(ofmt, stdout);
823 exit(0);
824 break;
826 case 't':
827 tasm_compatible_mode = true;
828 break;
830 case 'v':
831 printf("NASM version %s compiled on %s%s\n",
832 nasm_version, nasm_date, nasm_compile_options);
833 exit(0); /* never need usage message here */
834 break;
836 case 'e': /* preprocess only */
837 case 'E':
838 operating_mode = op_preprocess;
839 break;
841 case 'a': /* assemble only - don't preprocess */
842 preproc = &no_pp;
843 break;
845 case 'W':
846 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
847 do_warn = false;
848 param += 3;
849 } else {
850 do_warn = true;
852 goto set_warning;
854 case 'w':
855 if (param[0] != '+' && param[0] != '-') {
856 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
857 "invalid option to `-w'");
858 break;
860 do_warn = (param[0] == '+');
861 param++;
862 goto set_warning;
863 set_warning:
864 for (i = 0; i <= ERR_WARN_MAX; i++)
865 if (!nasm_stricmp(param, warnings[i].name))
866 break;
867 if (i <= ERR_WARN_MAX)
868 warning_on_global[i] = do_warn;
869 else if (!nasm_stricmp(param, "all"))
870 for (i = 1; i <= ERR_WARN_MAX; i++)
871 warning_on_global[i] = do_warn;
872 else if (!nasm_stricmp(param, "none"))
873 for (i = 1; i <= ERR_WARN_MAX; i++)
874 warning_on_global[i] = !do_warn;
875 else
876 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
877 "invalid warning `%s'", param);
878 break;
880 case 'M':
881 switch (p[2]) {
882 case 0:
883 operating_mode = op_depend;
884 break;
885 case 'G':
886 operating_mode = op_depend;
887 depend_missing_ok = true;
888 break;
889 case 'P':
890 depend_emit_phony = true;
891 break;
892 case 'D':
893 depend_file = q;
894 advance = true;
895 break;
896 case 'T':
897 depend_target = q;
898 advance = true;
899 break;
900 case 'Q':
901 depend_target = quote_for_make(q);
902 advance = true;
903 break;
904 default:
905 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
906 "unknown dependency option `-M%c'", p[2]);
907 break;
909 if (advance && (!q || !q[0])) {
910 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
911 "option `-M%c' requires a parameter", p[2]);
912 break;
914 break;
916 case '-':
918 int s;
920 if (p[2] == 0) { /* -- => stop processing options */
921 stopoptions = 1;
922 break;
924 for (s = 0; textopts[s].label; s++) {
925 if (!nasm_stricmp(p + 2, textopts[s].label)) {
926 break;
930 switch (s) {
932 case OPT_PREFIX:
933 case OPT_POSTFIX:
935 if (!q) {
936 report_error(ERR_NONFATAL | ERR_NOFILE |
937 ERR_USAGE,
938 "option `--%s' requires an argument",
939 p + 2);
940 break;
941 } else {
942 advance = 1, param = q;
945 if (s == OPT_PREFIX) {
946 strncpy(lprefix, param, PREFIX_MAX - 1);
947 lprefix[PREFIX_MAX - 1] = 0;
948 break;
950 if (s == OPT_POSTFIX) {
951 strncpy(lpostfix, param, POSTFIX_MAX - 1);
952 lpostfix[POSTFIX_MAX - 1] = 0;
953 break;
955 break;
957 default:
959 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
960 "unrecognised option `--%s'", p + 2);
961 break;
964 break;
967 default:
968 if (!ofmt->setinfo(GI_SWITCH, &p))
969 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
970 "unrecognised option `-%c'", p[1]);
971 break;
973 } else {
974 if (*inname) {
975 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
976 "more than one input file specified");
977 } else {
978 copy_filename(inname, p);
982 return advance;
985 #define ARG_BUF_DELTA 128
987 static void process_respfile(FILE * rfile)
989 char *buffer, *p, *q, *prevarg;
990 int bufsize, prevargsize;
992 bufsize = prevargsize = ARG_BUF_DELTA;
993 buffer = nasm_malloc(ARG_BUF_DELTA);
994 prevarg = nasm_malloc(ARG_BUF_DELTA);
995 prevarg[0] = '\0';
997 while (1) { /* Loop to handle all lines in file */
998 p = buffer;
999 while (1) { /* Loop to handle long lines */
1000 q = fgets(p, bufsize - (p - buffer), rfile);
1001 if (!q)
1002 break;
1003 p += strlen(p);
1004 if (p > buffer && p[-1] == '\n')
1005 break;
1006 if (p - buffer > bufsize - 10) {
1007 int offset;
1008 offset = p - buffer;
1009 bufsize += ARG_BUF_DELTA;
1010 buffer = nasm_realloc(buffer, bufsize);
1011 p = buffer + offset;
1015 if (!q && p == buffer) {
1016 if (prevarg[0])
1017 process_arg(prevarg, NULL);
1018 nasm_free(buffer);
1019 nasm_free(prevarg);
1020 return;
1024 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1025 * them are present at the end of the line.
1027 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1029 while (p > buffer && nasm_isspace(p[-1]))
1030 *--p = '\0';
1032 p = buffer;
1033 while (nasm_isspace(*p))
1034 p++;
1036 if (process_arg(prevarg, p))
1037 *p = '\0';
1039 if ((int) strlen(p) > prevargsize - 10) {
1040 prevargsize += ARG_BUF_DELTA;
1041 prevarg = nasm_realloc(prevarg, prevargsize);
1043 strncpy(prevarg, p, prevargsize);
1047 /* Function to process args from a string of args, rather than the
1048 * argv array. Used by the environment variable and response file
1049 * processing.
1051 static void process_args(char *args)
1053 char *p, *q, *arg, *prevarg;
1054 char separator = ' ';
1056 p = args;
1057 if (*p && *p != '-')
1058 separator = *p++;
1059 arg = NULL;
1060 while (*p) {
1061 q = p;
1062 while (*p && *p != separator)
1063 p++;
1064 while (*p == separator)
1065 *p++ = '\0';
1066 prevarg = arg;
1067 arg = q;
1068 if (process_arg(prevarg, arg))
1069 arg = NULL;
1071 if (arg)
1072 process_arg(arg, NULL);
1075 static void process_response_file(const char *file)
1077 char str[2048];
1078 FILE *f = fopen(file, "r");
1079 if (!f) {
1080 perror(file);
1081 exit(-1);
1083 while (fgets(str, sizeof str, f)) {
1084 process_args(str);
1086 fclose(f);
1089 static void parse_cmdline(int argc, char **argv)
1091 FILE *rfile;
1092 char *envreal, *envcopy = NULL, *p, *arg;
1093 int i;
1095 *inname = *outname = *listname = *errname = '\0';
1096 for (i = 0; i <= ERR_WARN_MAX; i++)
1097 warning_on_global[i] = warnings[i].enabled;
1100 * First, process the NASMENV environment variable.
1102 envreal = getenv("NASMENV");
1103 arg = NULL;
1104 if (envreal) {
1105 envcopy = nasm_strdup(envreal);
1106 process_args(envcopy);
1107 nasm_free(envcopy);
1111 * Now process the actual command line.
1113 while (--argc) {
1114 bool advance;
1115 argv++;
1116 if (argv[0][0] == '@') {
1117 /* We have a response file, so process this as a set of
1118 * arguments like the environment variable. This allows us
1119 * to have multiple arguments on a single line, which is
1120 * different to the -@resp file processing below for regular
1121 * NASM.
1123 process_response_file(argv[0]+1);
1124 argc--;
1125 argv++;
1127 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1128 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1129 if (p) {
1130 rfile = fopen(p, "r");
1131 if (rfile) {
1132 process_respfile(rfile);
1133 fclose(rfile);
1134 } else
1135 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1136 "unable to open response file `%s'", p);
1138 } else
1139 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1140 argv += advance, argc -= advance;
1143 /* Look for basic command line typos. This definitely doesn't
1144 catch all errors, but it might help cases of fumbled fingers. */
1145 if (!*inname)
1146 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1147 "no input file specified");
1148 else if (!strcmp(inname, errname) ||
1149 !strcmp(inname, outname) ||
1150 !strcmp(inname, listname) ||
1151 (depend_file && !strcmp(inname, depend_file)))
1152 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1153 "file `%s' is both input and output file",
1154 inname);
1156 if (*errname) {
1157 error_file = fopen(errname, "w");
1158 if (!error_file) {
1159 error_file = stderr; /* Revert to default! */
1160 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1161 "cannot open file `%s' for error messages",
1162 errname);
1167 /* List of directives */
1168 enum directives {
1169 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1170 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1172 static const char *directives[] = {
1173 "", "absolute", "bits", "common", "cpu", "debug", "default",
1174 "extern", "float", "global", "list", "section", "segment", "warning"
1176 static enum directives getkw(char **directive, char **value);
1178 static void assemble_file(char *fname, StrList **depend_ptr)
1180 char *directive, *value, *p, *q, *special, *line, debugid[80];
1181 insn output_ins;
1182 int i, validid;
1183 bool rn_error;
1184 int32_t seg;
1185 int64_t offs;
1186 struct tokenval tokval;
1187 expr *e;
1188 int pass_max;
1190 if (cmd_sb == 32 && cmd_cpu < IF_386)
1191 report_error(ERR_FATAL, "command line: "
1192 "32-bit segment size requires a higher cpu");
1194 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1195 for (passn = 1; pass0 <= 2; passn++) {
1196 int pass1, pass2;
1197 ldfunc def_label;
1199 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1200 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1201 /* pass0 0, 0, 0, ..., 1, 2 */
1203 def_label = passn > 1 ? redefine_label : define_label;
1205 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1206 cpu = cmd_cpu;
1207 if (pass0 == 2) {
1208 if (*listname)
1209 nasmlist.init(listname, report_error);
1211 in_abs_seg = false;
1212 global_offset_changed = 0; /* set by redefine_label */
1213 location.segment = ofmt->section(NULL, pass2, &sb);
1214 globalbits = sb;
1215 if (passn > 1) {
1216 saa_rewind(forwrefs);
1217 forwref = saa_rstruct(forwrefs);
1218 raa_free(offsets);
1219 offsets = raa_init();
1221 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1222 pass1 == 2 ? depend_ptr : NULL);
1223 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1225 globallineno = 0;
1226 if (passn == 1)
1227 location.known = true;
1228 location.offset = offs = GET_CURR_OFFS;
1230 while ((line = preproc->getline())) {
1231 enum directives d;
1232 globallineno++;
1235 * Here we parse our directives; this is not handled by the
1236 * 'real' parser. This really should be a separate function.
1238 directive = line;
1239 d = getkw(&directive, &value);
1240 if (d) {
1241 int err = 0;
1243 switch (d) {
1244 case D_SEGMENT: /* [SEGMENT n] */
1245 case D_SECTION:
1246 seg = ofmt->section(value, pass2, &sb);
1247 if (seg == NO_SEG) {
1248 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1249 "segment name `%s' not recognized",
1250 value);
1251 } else {
1252 in_abs_seg = false;
1253 location.segment = seg;
1255 break;
1256 case D_EXTERN: /* [EXTERN label:special] */
1257 if (*value == '$')
1258 value++; /* skip initial $ if present */
1259 if (pass0 == 2) {
1260 q = value;
1261 while (*q && *q != ':')
1262 q++;
1263 if (*q == ':') {
1264 *q++ = '\0';
1265 ofmt->symdef(value, 0L, 0L, 3, q);
1267 } else if (passn == 1) {
1268 q = value;
1269 validid = true;
1270 if (!isidstart(*q))
1271 validid = false;
1272 while (*q && *q != ':') {
1273 if (!isidchar(*q))
1274 validid = false;
1275 q++;
1277 if (!validid) {
1278 report_error(ERR_NONFATAL,
1279 "identifier expected after EXTERN");
1280 break;
1282 if (*q == ':') {
1283 *q++ = '\0';
1284 special = q;
1285 } else
1286 special = NULL;
1287 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1288 int temp = pass0;
1289 pass0 = 1; /* fake pass 1 in labels.c */
1290 declare_as_global(value, special,
1291 report_error);
1292 define_label(value, seg_alloc(), 0L, NULL,
1293 false, true, ofmt, report_error);
1294 pass0 = temp;
1296 } /* else pass0 == 1 */
1297 break;
1298 case D_BITS: /* [BITS bits] */
1299 globalbits = sb = get_bits(value);
1300 break;
1301 case D_GLOBAL: /* [GLOBAL symbol:special] */
1302 if (*value == '$')
1303 value++; /* skip initial $ if present */
1304 if (pass0 == 2) { /* pass 2 */
1305 q = value;
1306 while (*q && *q != ':')
1307 q++;
1308 if (*q == ':') {
1309 *q++ = '\0';
1310 ofmt->symdef(value, 0L, 0L, 3, q);
1312 } else if (pass2 == 1) { /* pass == 1 */
1313 q = value;
1314 validid = true;
1315 if (!isidstart(*q))
1316 validid = false;
1317 while (*q && *q != ':') {
1318 if (!isidchar(*q))
1319 validid = false;
1320 q++;
1322 if (!validid) {
1323 report_error(ERR_NONFATAL,
1324 "identifier expected after GLOBAL");
1325 break;
1327 if (*q == ':') {
1328 *q++ = '\0';
1329 special = q;
1330 } else
1331 special = NULL;
1332 declare_as_global(value, special, report_error);
1333 } /* pass == 1 */
1334 break;
1335 case D_COMMON: /* [COMMON symbol size:special] */
1337 int64_t size;
1339 if (*value == '$')
1340 value++; /* skip initial $ if present */
1341 p = value;
1342 validid = true;
1343 if (!isidstart(*p))
1344 validid = false;
1345 while (*p && !nasm_isspace(*p)) {
1346 if (!isidchar(*p))
1347 validid = false;
1348 p++;
1350 if (!validid) {
1351 report_error(ERR_NONFATAL,
1352 "identifier expected after COMMON");
1353 break;
1355 if (*p) {
1356 while (*p && nasm_isspace(*p))
1357 *p++ = '\0';
1358 q = p;
1359 while (*q && *q != ':')
1360 q++;
1361 if (*q == ':') {
1362 *q++ = '\0';
1363 special = q;
1364 } else {
1365 special = NULL;
1367 size = readnum(p, &rn_error);
1368 if (rn_error) {
1369 report_error(ERR_NONFATAL,
1370 "invalid size specified"
1371 " in COMMON declaration");
1372 break;
1374 } else {
1375 report_error(ERR_NONFATAL,
1376 "no size specified in"
1377 " COMMON declaration");
1378 break;
1381 if (pass0 < 2) {
1382 define_common(value, seg_alloc(), size,
1383 special, ofmt, report_error);
1384 } else if (pass0 == 2) {
1385 ofmt->symdef(value, 0L, 0L, 3, special);
1387 break;
1389 case D_ABSOLUTE: /* [ABSOLUTE address] */
1390 stdscan_reset();
1391 stdscan_bufptr = value;
1392 tokval.t_type = TOKEN_INVALID;
1393 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1394 report_error, NULL);
1395 if (e) {
1396 if (!is_reloc(e))
1397 report_error(pass0 ==
1398 1 ? ERR_NONFATAL : ERR_PANIC,
1399 "cannot use non-relocatable expression as "
1400 "ABSOLUTE address");
1401 else {
1402 abs_seg = reloc_seg(e);
1403 abs_offset = reloc_value(e);
1405 } else if (passn == 1)
1406 abs_offset = 0x100; /* don't go near zero in case of / */
1407 else
1408 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1409 "in pass two");
1410 in_abs_seg = true;
1411 location.segment = NO_SEG;
1412 break;
1413 case D_DEBUG: /* [DEBUG] */
1414 p = value;
1415 q = debugid;
1416 validid = true;
1417 if (!isidstart(*p))
1418 validid = false;
1419 while (*p && !nasm_isspace(*p)) {
1420 if (!isidchar(*p))
1421 validid = false;
1422 *q++ = *p++;
1424 *q++ = 0;
1425 if (!validid) {
1426 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1427 "identifier expected after DEBUG");
1428 break;
1430 while (*p && nasm_isspace(*p))
1431 p++;
1432 if (pass0 == 2)
1433 ofmt->current_dfmt->debug_directive(debugid, p);
1434 break;
1435 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1436 while (*value && nasm_isspace(*value))
1437 value++;
1439 switch(*value) {
1440 case '-': validid = 0; value++; break;
1441 case '+': validid = 1; value++; break;
1442 case '*': validid = 2; value++; break;
1443 default: validid = 1; break;
1446 for (i = 1; i <= ERR_WARN_MAX; i++)
1447 if (!nasm_stricmp(value, warnings[i].name))
1448 break;
1449 if (i <= ERR_WARN_MAX) {
1450 switch(validid) {
1451 case 0:
1452 warning_on[i] = false;
1453 break;
1454 case 1:
1455 warning_on[i] = true;
1456 break;
1457 case 2:
1458 warning_on[i] = warning_on_global[i];
1459 break;
1462 else
1463 report_error(ERR_NONFATAL,
1464 "invalid warning id in WARNING directive");
1465 break;
1466 case D_CPU: /* [CPU] */
1467 cpu = get_cpu(value);
1468 break;
1469 case D_LIST: /* [LIST {+|-}] */
1470 while (*value && nasm_isspace(*value))
1471 value++;
1473 if (*value == '+') {
1474 user_nolist = 0;
1475 } else {
1476 if (*value == '-') {
1477 user_nolist = 1;
1478 } else {
1479 err = 1;
1482 break;
1483 case D_DEFAULT: /* [DEFAULT] */
1484 stdscan_reset();
1485 stdscan_bufptr = value;
1486 tokval.t_type = TOKEN_INVALID;
1487 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1488 switch ((int)tokval.t_integer) {
1489 case S_REL:
1490 globalrel = 1;
1491 break;
1492 case S_ABS:
1493 globalrel = 0;
1494 break;
1495 default:
1496 err = 1;
1497 break;
1499 } else {
1500 err = 1;
1502 break;
1503 case D_FLOAT:
1504 if (float_option(value)) {
1505 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1506 "unknown 'float' directive: %s",
1507 value);
1509 break;
1510 default:
1511 if (!ofmt->directive(directive, value, pass2))
1512 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1513 "unrecognised directive [%s]",
1514 directive);
1516 if (err) {
1517 report_error(ERR_NONFATAL,
1518 "invalid parameter to [%s] directive",
1519 directive);
1521 } else { /* it isn't a directive */
1523 parse_line(pass1, line, &output_ins,
1524 report_error, evaluate, def_label);
1526 if (optimizing > 0) {
1527 if (forwref != NULL && globallineno == forwref->lineno) {
1528 output_ins.forw_ref = true;
1529 do {
1530 output_ins.oprs[forwref->operand].opflags |=
1531 OPFLAG_FORWARD;
1532 forwref = saa_rstruct(forwrefs);
1533 } while (forwref != NULL
1534 && forwref->lineno == globallineno);
1535 } else
1536 output_ins.forw_ref = false;
1538 if (output_ins.forw_ref) {
1539 if (passn == 1) {
1540 for (i = 0; i < output_ins.operands; i++) {
1541 if (output_ins.oprs[i].
1542 opflags & OPFLAG_FORWARD) {
1543 struct forwrefinfo *fwinf =
1544 (struct forwrefinfo *)
1545 saa_wstruct(forwrefs);
1546 fwinf->lineno = globallineno;
1547 fwinf->operand = i;
1554 /* forw_ref */
1555 if (output_ins.opcode == I_EQU) {
1556 if (pass1 == 1) {
1558 * Special `..' EQUs get processed in pass two,
1559 * except `..@' macro-processor EQUs which are done
1560 * in the normal place.
1562 if (!output_ins.label)
1563 report_error(ERR_NONFATAL,
1564 "EQU not preceded by label");
1566 else if (output_ins.label[0] != '.' ||
1567 output_ins.label[1] != '.' ||
1568 output_ins.label[2] == '@') {
1569 if (output_ins.operands == 1 &&
1570 (output_ins.oprs[0].type & IMMEDIATE) &&
1571 output_ins.oprs[0].wrt == NO_SEG) {
1572 bool isext = !!(output_ins.oprs[0].opflags
1573 & OPFLAG_EXTERN);
1574 def_label(output_ins.label,
1575 output_ins.oprs[0].segment,
1576 output_ins.oprs[0].offset, NULL,
1577 false, isext, ofmt,
1578 report_error);
1579 } else if (output_ins.operands == 2
1580 && (output_ins.oprs[0].type & IMMEDIATE)
1581 && (output_ins.oprs[0].type & COLON)
1582 && output_ins.oprs[0].segment == NO_SEG
1583 && output_ins.oprs[0].wrt == NO_SEG
1584 && (output_ins.oprs[1].type & IMMEDIATE)
1585 && output_ins.oprs[1].segment == NO_SEG
1586 && output_ins.oprs[1].wrt == NO_SEG) {
1587 def_label(output_ins.label,
1588 output_ins.oprs[0].offset | SEG_ABS,
1589 output_ins.oprs[1].offset,
1590 NULL, false, false, ofmt,
1591 report_error);
1592 } else
1593 report_error(ERR_NONFATAL,
1594 "bad syntax for EQU");
1596 } else {
1598 * Special `..' EQUs get processed here, except
1599 * `..@' macro processor EQUs which are done above.
1601 if (output_ins.label[0] == '.' &&
1602 output_ins.label[1] == '.' &&
1603 output_ins.label[2] != '@') {
1604 if (output_ins.operands == 1 &&
1605 (output_ins.oprs[0].type & IMMEDIATE)) {
1606 define_label(output_ins.label,
1607 output_ins.oprs[0].segment,
1608 output_ins.oprs[0].offset,
1609 NULL, false, false, ofmt,
1610 report_error);
1611 } else if (output_ins.operands == 2
1612 && (output_ins.oprs[0].
1613 type & IMMEDIATE)
1614 && (output_ins.oprs[0].type & COLON)
1615 && output_ins.oprs[0].segment ==
1616 NO_SEG
1617 && (output_ins.oprs[1].
1618 type & IMMEDIATE)
1619 && output_ins.oprs[1].segment ==
1620 NO_SEG) {
1621 define_label(output_ins.label,
1622 output_ins.oprs[0].
1623 offset | SEG_ABS,
1624 output_ins.oprs[1].offset,
1625 NULL, false, false, ofmt,
1626 report_error);
1627 } else
1628 report_error(ERR_NONFATAL,
1629 "bad syntax for EQU");
1632 } else { /* instruction isn't an EQU */
1634 if (pass1 == 1) {
1636 int64_t l = insn_size(location.segment, offs, sb, cpu,
1637 &output_ins, report_error);
1639 /* if (using_debug_info) && output_ins.opcode != -1) */
1640 if (using_debug_info)
1641 { /* fbk 03/25/01 */
1642 /* this is done here so we can do debug type info */
1643 int32_t typeinfo =
1644 TYS_ELEMENTS(output_ins.operands);
1645 switch (output_ins.opcode) {
1646 case I_RESB:
1647 typeinfo =
1648 TYS_ELEMENTS(output_ins.oprs[0].
1649 offset) | TY_BYTE;
1650 break;
1651 case I_RESW:
1652 typeinfo =
1653 TYS_ELEMENTS(output_ins.oprs[0].
1654 offset) | TY_WORD;
1655 break;
1656 case I_RESD:
1657 typeinfo =
1658 TYS_ELEMENTS(output_ins.oprs[0].
1659 offset) | TY_DWORD;
1660 break;
1661 case I_RESQ:
1662 typeinfo =
1663 TYS_ELEMENTS(output_ins.oprs[0].
1664 offset) | TY_QWORD;
1665 break;
1666 case I_REST:
1667 typeinfo =
1668 TYS_ELEMENTS(output_ins.oprs[0].
1669 offset) | TY_TBYTE;
1670 break;
1671 case I_RESO:
1672 typeinfo =
1673 TYS_ELEMENTS(output_ins.oprs[0].
1674 offset) | TY_OWORD;
1675 break;
1676 case I_RESY:
1677 typeinfo =
1678 TYS_ELEMENTS(output_ins.oprs[0].
1679 offset) | TY_YWORD;
1680 break;
1681 case I_DB:
1682 typeinfo |= TY_BYTE;
1683 break;
1684 case I_DW:
1685 typeinfo |= TY_WORD;
1686 break;
1687 case I_DD:
1688 if (output_ins.eops_float)
1689 typeinfo |= TY_FLOAT;
1690 else
1691 typeinfo |= TY_DWORD;
1692 break;
1693 case I_DQ:
1694 typeinfo |= TY_QWORD;
1695 break;
1696 case I_DT:
1697 typeinfo |= TY_TBYTE;
1698 break;
1699 case I_DO:
1700 typeinfo |= TY_OWORD;
1701 break;
1702 case I_DY:
1703 typeinfo |= TY_YWORD;
1704 break;
1705 default:
1706 typeinfo = TY_LABEL;
1710 ofmt->current_dfmt->debug_typevalue(typeinfo);
1713 if (l != -1) {
1714 offs += l;
1715 SET_CURR_OFFS(offs);
1718 * else l == -1 => invalid instruction, which will be
1719 * flagged as an error on pass 2
1722 } else {
1723 offs += assemble(location.segment, offs, sb, cpu,
1724 &output_ins, ofmt, report_error,
1725 &nasmlist);
1726 SET_CURR_OFFS(offs);
1729 } /* not an EQU */
1730 cleanup_insn(&output_ins);
1732 nasm_free(line);
1733 location.offset = offs = GET_CURR_OFFS;
1734 } /* end while (line = preproc->getline... */
1736 if (pass0 && global_offset_changed)
1737 report_error(ERR_NONFATAL,
1738 "phase error detected at end of assembly.");
1740 if (pass1 == 1)
1741 preproc->cleanup(1);
1743 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1744 pass0++;
1745 } else if (global_offset_changed &&
1746 global_offset_changed < prev_offset_changed) {
1747 prev_offset_changed = global_offset_changed;
1748 stall_count = 0;
1749 } else {
1750 stall_count++;
1753 if (terminate_after_phase)
1754 break;
1756 if ((stall_count > 997) || (passn >= pass_max)) {
1757 /* We get here if the labels don't converge
1758 * Example: FOO equ FOO + 1
1760 report_error(ERR_NONFATAL,
1761 "Can't find valid values for all labels "
1762 "after %d passes, giving up.", passn);
1763 report_error(ERR_NONFATAL,
1764 "Possible causes: recursive EQUs, macro abuse.");
1765 terminate_after_phase = true;
1766 break;
1770 preproc->cleanup(0);
1771 nasmlist.cleanup();
1772 if (!terminate_after_phase && opt_verbose_info) {
1773 /* -On and -Ov switches */
1774 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1778 static enum directives getkw(char **directive, char **value)
1780 char *p, *q, *buf;
1782 buf = *directive;
1784 /* allow leading spaces or tabs */
1785 while (*buf == ' ' || *buf == '\t')
1786 buf++;
1788 if (*buf != '[')
1789 return 0;
1791 p = buf;
1793 while (*p && *p != ']')
1794 p++;
1796 if (!*p)
1797 return 0;
1799 q = p++;
1801 while (*p && *p != ';') {
1802 if (!nasm_isspace(*p))
1803 return 0;
1804 p++;
1806 q[1] = '\0';
1808 *directive = p = buf + 1;
1809 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1810 buf++;
1811 if (*buf == ']') {
1812 *buf = '\0';
1813 *value = buf;
1814 } else {
1815 *buf++ = '\0';
1816 while (nasm_isspace(*buf))
1817 buf++; /* beppu - skip leading whitespace */
1818 *value = buf;
1819 while (*buf != ']')
1820 buf++;
1821 *buf++ = '\0';
1824 return bsii(*directive, directives, elements(directives));
1828 * gnu style error reporting
1829 * This function prints an error message to error_file in the
1830 * style used by GNU. An example would be:
1831 * file.asm:50: error: blah blah blah
1832 * where file.asm is the name of the file, 50 is the line number on
1833 * which the error occurs (or is detected) and "error:" is one of
1834 * the possible optional diagnostics -- it can be "error" or "warning"
1835 * or something else. Finally the line terminates with the actual
1836 * error message.
1838 * @param severity the severity of the warning or error
1839 * @param fmt the printf style format string
1841 static void report_error_gnu(int severity, const char *fmt, ...)
1843 va_list ap;
1845 if (is_suppressed_warning(severity))
1846 return;
1848 if (severity & ERR_NOFILE)
1849 fputs("nasm: ", error_file);
1850 else {
1851 char *currentfile = NULL;
1852 int32_t lineno = 0;
1853 src_get(&lineno, &currentfile);
1854 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1855 nasm_free(currentfile);
1857 va_start(ap, fmt);
1858 report_error_common(severity, fmt, ap);
1859 va_end(ap);
1863 * MS style error reporting
1864 * This function prints an error message to error_file in the
1865 * style used by Visual C and some other Microsoft tools. An example
1866 * would be:
1867 * file.asm(50) : error: blah blah blah
1868 * where file.asm is the name of the file, 50 is the line number on
1869 * which the error occurs (or is detected) and "error:" is one of
1870 * the possible optional diagnostics -- it can be "error" or "warning"
1871 * or something else. Finally the line terminates with the actual
1872 * error message.
1874 * @param severity the severity of the warning or error
1875 * @param fmt the printf style format string
1877 static void report_error_vc(int severity, const char *fmt, ...)
1879 va_list ap;
1881 if (is_suppressed_warning(severity))
1882 return;
1884 if (severity & ERR_NOFILE)
1885 fputs("nasm: ", error_file);
1886 else {
1887 char *currentfile = NULL;
1888 int32_t lineno = 0;
1889 src_get(&lineno, &currentfile);
1890 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1891 nasm_free(currentfile);
1893 va_start(ap, fmt);
1894 report_error_common(severity, fmt, ap);
1895 va_end(ap);
1899 * check for supressed warning
1900 * checks for suppressed warning or pass one only warning and we're
1901 * not in pass 1
1903 * @param severity the severity of the warning or error
1904 * @return true if we should abort error/warning printing
1906 static bool is_suppressed_warning(int severity)
1909 * See if it's a suppressed warning.
1911 return (severity & ERR_MASK) == ERR_WARNING &&
1912 (((severity & ERR_WARN_MASK) != 0 &&
1913 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1914 /* See if it's a pass-one only warning and we're not in pass one. */
1915 ((severity & ERR_PASS1) && pass0 != 1) ||
1916 ((severity & ERR_PASS2) && pass0 != 2));
1920 * common error reporting
1921 * This is the common back end of the error reporting schemes currently
1922 * implemented. It prints the nature of the warning and then the
1923 * specific error message to error_file and may or may not return. It
1924 * doesn't return if the error severity is a "panic" or "debug" type.
1926 * @param severity the severity of the warning or error
1927 * @param fmt the printf style format string
1929 static void report_error_common(int severity, const char *fmt,
1930 va_list args)
1932 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1933 case ERR_WARNING:
1934 fputs("warning: ", error_file);
1935 break;
1936 case ERR_NONFATAL:
1937 fputs("error: ", error_file);
1938 break;
1939 case ERR_FATAL:
1940 fputs("fatal: ", error_file);
1941 break;
1942 case ERR_PANIC:
1943 fputs("panic: ", error_file);
1944 break;
1945 case ERR_DEBUG:
1946 fputs("debug: ", error_file);
1947 break;
1948 default:
1949 break;
1952 vfprintf(error_file, fmt, args);
1953 putc('\n', error_file);
1955 if (severity & ERR_USAGE)
1956 want_usage = true;
1958 switch (severity & ERR_MASK) {
1959 case ERR_DEBUG:
1960 /* no further action, by definition */
1961 break;
1962 case ERR_WARNING:
1963 if (warning_on[0]) /* Treat warnings as errors */
1964 terminate_after_phase = true;
1965 break;
1966 case ERR_NONFATAL:
1967 terminate_after_phase = true;
1968 break;
1969 case ERR_FATAL:
1970 if (ofile) {
1971 fclose(ofile);
1972 remove(outname);
1974 if (want_usage)
1975 usage();
1976 exit(1); /* instantly die */
1977 break; /* placate silly compilers */
1978 case ERR_PANIC:
1979 fflush(NULL);
1980 /* abort(); *//* halt, catch fire, and dump core */
1981 exit(3);
1982 break;
1986 static void usage(void)
1988 fputs("type `nasm -h' for help\n", error_file);
1991 static void register_output_formats(void)
1993 ofmt = ofmt_register(report_error);
1996 #define BUF_DELTA 512
1998 static FILE *no_pp_fp;
1999 static efunc no_pp_err;
2000 static ListGen *no_pp_list;
2001 static int32_t no_pp_lineinc;
2003 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
2004 ListGen * listgen, StrList **deplist)
2006 src_set_fname(nasm_strdup(file));
2007 src_set_linnum(0);
2008 no_pp_lineinc = 1;
2009 no_pp_err = error;
2010 no_pp_fp = fopen(file, "r");
2011 if (!no_pp_fp)
2012 no_pp_err(ERR_FATAL | ERR_NOFILE,
2013 "unable to open input file `%s'", file);
2014 no_pp_list = listgen;
2015 (void)pass; /* placate compilers */
2016 (void)eval; /* placate compilers */
2018 if (deplist) {
2019 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2020 sl->next = NULL;
2021 strcpy(sl->str, file);
2022 *deplist = sl;
2026 static char *no_pp_getline(void)
2028 char *buffer, *p, *q;
2029 int bufsize;
2031 bufsize = BUF_DELTA;
2032 buffer = nasm_malloc(BUF_DELTA);
2033 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2035 while (1) { /* Loop to handle %line */
2037 p = buffer;
2038 while (1) { /* Loop to handle long lines */
2039 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2040 if (!q)
2041 break;
2042 p += strlen(p);
2043 if (p > buffer && p[-1] == '\n')
2044 break;
2045 if (p - buffer > bufsize - 10) {
2046 int offset;
2047 offset = p - buffer;
2048 bufsize += BUF_DELTA;
2049 buffer = nasm_realloc(buffer, bufsize);
2050 p = buffer + offset;
2054 if (!q && p == buffer) {
2055 nasm_free(buffer);
2056 return NULL;
2060 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2061 * them are present at the end of the line.
2063 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2065 if (!nasm_strnicmp(buffer, "%line", 5)) {
2066 int32_t ln;
2067 int li;
2068 char *nm = nasm_malloc(strlen(buffer));
2069 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2070 nasm_free(src_set_fname(nm));
2071 src_set_linnum(ln);
2072 no_pp_lineinc = li;
2073 continue;
2075 nasm_free(nm);
2077 break;
2080 no_pp_list->line(LIST_READ, buffer);
2082 return buffer;
2085 static void no_pp_cleanup(int pass)
2087 (void)pass; /* placate GCC */
2088 fclose(no_pp_fp);
2091 static uint32_t get_cpu(char *value)
2093 if (!strcmp(value, "8086"))
2094 return IF_8086;
2095 if (!strcmp(value, "186"))
2096 return IF_186;
2097 if (!strcmp(value, "286"))
2098 return IF_286;
2099 if (!strcmp(value, "386"))
2100 return IF_386;
2101 if (!strcmp(value, "486"))
2102 return IF_486;
2103 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2104 return IF_PENT;
2105 if (!strcmp(value, "686") ||
2106 !nasm_stricmp(value, "ppro") ||
2107 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2108 return IF_P6;
2109 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2110 return IF_KATMAI;
2111 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2112 !nasm_stricmp(value, "willamette"))
2113 return IF_WILLAMETTE;
2114 if (!nasm_stricmp(value, "prescott"))
2115 return IF_PRESCOTT;
2116 if (!nasm_stricmp(value, "x64") ||
2117 !nasm_stricmp(value, "x86-64"))
2118 return IF_X86_64;
2119 if (!nasm_stricmp(value, "ia64") ||
2120 !nasm_stricmp(value, "ia-64") ||
2121 !nasm_stricmp(value, "itanium") ||
2122 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2123 return IF_IA64;
2125 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2126 "unknown 'cpu' type");
2128 return IF_PLEVEL; /* the maximum level */
2131 static int get_bits(char *value)
2133 int i;
2135 if ((i = atoi(value)) == 16)
2136 return i; /* set for a 16-bit segment */
2137 else if (i == 32) {
2138 if (cpu < IF_386) {
2139 report_error(ERR_NONFATAL,
2140 "cannot specify 32-bit segment on processor below a 386");
2141 i = 16;
2143 } else if (i == 64) {
2144 if (cpu < IF_X86_64) {
2145 report_error(ERR_NONFATAL,
2146 "cannot specify 64-bit segment on processor below an x86-64");
2147 i = 16;
2149 if (i != maxbits) {
2150 report_error(ERR_NONFATAL,
2151 "%s output format does not support 64-bit code",
2152 ofmt->shortname);
2153 i = 16;
2155 } else {
2156 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2157 "`%s' is not a valid segment size; must be 16, 32 or 64",
2158 value);
2159 i = 16;
2161 return i;
2164 /* end of nasm.c */