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
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
61 #include "output/outform.h"
64 struct forwrefinfo { /* info held on forward refs. */
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;
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 */
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;
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;
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 {
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 = {
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)
187 fputs(line, outfile);
193 /* Convert a struct tm to a POSIX-style time constant */
194 static int64_t posix_mktime(struct tm *tm)
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;
213 static void define_macros_early(void)
216 struct tm lt, *lt_p, gm, *gm_p;
219 lt_p = localtime(&official_compile_time);
223 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", <);
225 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", <);
227 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", <);
229 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", <);
233 gm_p = gmtime(&official_compile_time);
237 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
239 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
241 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
243 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
248 posix_time = posix_mktime(&gm);
250 posix_time = posix_mktime(<);
255 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
260 static void define_macros_late(void)
264 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
269 static void emit_dependencies(StrList *list)
275 if (depend_file && strcmp(depend_file, "-")) {
276 deps = fopen(depend_file, "w");
278 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
279 "unable to write dependency file `%s'", depend_file);
286 linepos = fprintf(deps, "%s:", depend_target);
287 for (l = list; l; l = l->next) {
288 len = strlen(l->str);
289 if (linepos + len > 62) {
290 fprintf(deps, " \\\n ");
293 fprintf(deps, " %s", l->str);
296 fprintf(deps, "\n\n");
298 for (l = list; l; l = nl) {
299 if (depend_emit_phony)
300 fprintf(deps, "%s:\n\n", l->str);
310 int main(int argc, char **argv)
312 StrList *depend_list = NULL, **depend_ptr;
314 time(&official_compile_time);
317 want_usage = terminate_after_phase = false;
318 nasm_set_verror(nasm_verror_gnu);
324 nasm_init_malloc_error();
325 offsets = raa_init();
326 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
329 operating_mode = op_normal;
333 /* Define some macros dependent on the runtime, but not
334 on the command line. */
335 define_macros_early();
337 parse_cmdline(argc, argv);
339 if (terminate_after_phase) {
345 /* If debugging info is disabled, suppress any debug calls */
346 if (!using_debug_info)
347 ofmt->current_dfmt = &null_debug_form;
350 pp_extra_stdmac(ofmt->stdmac);
351 parser_global_info(&location);
352 eval_global_info(ofmt, lookup_label, &location);
354 /* define some macros dependent of command-line */
355 define_macros_late();
357 depend_ptr = (depend_file || (operating_mode == op_depend))
358 ? &depend_list : NULL;
360 depend_target = outname;
362 switch (operating_mode) {
367 if (depend_missing_ok)
368 pp_include_path(NULL); /* "assume generated" */
370 preproc->reset(inname, 0, &nasmlist, depend_ptr);
371 if (outname[0] == '\0')
372 ofmt->filename(inname, outname);
374 while ((line = preproc->getline()))
383 char *file_name = NULL;
384 int32_t prior_linnum = 0;
388 ofile = fopen(outname, "w");
390 nasm_error(ERR_FATAL | ERR_NOFILE,
391 "unable to open output file `%s'",
396 location.known = false;
399 preproc->reset(inname, 3, &nasmlist, depend_ptr);
401 while ((line = preproc->getline())) {
403 * We generate %line directives if needed for later programs
405 int32_t linnum = prior_linnum += lineinc;
406 int altline = src_get(&linnum, &file_name);
408 if (altline == 1 && lineinc == 1)
409 nasm_fputs("", ofile);
411 lineinc = (altline != -1 || lineinc != 1);
412 fprintf(ofile ? ofile : stdout,
413 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
416 prior_linnum = linnum;
418 nasm_fputs(line, ofile);
421 nasm_free(file_name);
425 if (ofile && terminate_after_phase)
434 * We must call ofmt->filename _anyway_, even if the user
435 * has specified their own output file, because some
436 * formats (eg OBJ and COFF) use ofmt->filename to find out
437 * the name of the input file and then put that inside the
440 ofmt->filename(inname, outname);
442 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
444 nasm_error(ERR_FATAL | ERR_NOFILE,
445 "unable to open output file `%s'", outname);
449 * We must call init_labels() before ofmt->init() since
450 * some object formats will want to define labels in their
451 * init routines. (eg OS/2 defines the FLAT group)
456 dfmt = ofmt->current_dfmt;
459 assemble_file(inname, depend_ptr);
461 if (!terminate_after_phase) {
462 ofmt->cleanup(using_debug_info);
466 nasm_error(ERR_NONFATAL|ERR_NOFILE,
467 "write error on output file `%s'", outname);
473 if (terminate_after_phase)
481 if (depend_list && !terminate_after_phase)
482 emit_dependencies(depend_list);
492 return terminate_after_phase;
496 * Get a parameter for a command line option.
497 * First arg must be in the form of e.g. -f...
499 static char *get_param(char *p, char *q, bool *advance)
502 if (p[2]) { /* the parameter's in the option */
504 while (nasm_isspace(*p))
512 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
513 "option `-%c' requires an argument", p[1]);
520 static void copy_filename(char *dst, const char *src)
522 size_t len = strlen(src);
524 if (len >= (size_t)FILENAME_MAX) {
525 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
528 strncpy(dst, src, FILENAME_MAX);
532 * Convert a string to Make-safe form
534 static char *quote_for_make(const char *str)
539 size_t n = 1; /* Terminating zero */
545 for (p = str; *p; p++) {
549 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
569 /* Convert N backslashes at the end of filename to 2N backslashes */
573 os = q = nasm_malloc(n);
576 for (p = str; *p; p++) {
619 #define OPT_POSTFIX 1
620 struct textargs textopts[] = {
621 {"prefix", OPT_PREFIX},
622 {"postfix", OPT_POSTFIX},
626 static bool stopoptions = false;
627 static bool process_arg(char *p, char *q)
631 bool advance = false;
637 if (p[0] == '-' && !stopoptions) {
638 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
639 /* These parameters take values */
640 if (!(param = get_param(p, q, &advance)))
649 case 'o': /* output file */
650 copy_filename(outname, param);
653 case 'f': /* output format */
654 ofmt = ofmt_find(param);
656 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
657 "unrecognised output format `%s' - "
658 "use -hf for a list", param);
662 case 'O': /* Optimization level */
667 /* Naked -O == -Ox */
668 optimizing = INT_MAX >> 1; /* Almost unlimited */
672 case '0': case '1': case '2': case '3': case '4':
673 case '5': case '6': case '7': case '8': case '9':
674 opt = strtoul(param, ¶m, 10);
676 /* -O0 -> optimizing == -1, 0.98 behaviour */
677 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
679 optimizing = opt - 1;
687 opt_verbose_info = true;
692 optimizing = INT_MAX >> 1; /* Almost unlimited */
696 nasm_error(ERR_FATAL,
697 "unknown optimization option -O%c\n",
706 case 'p': /* pre-include */
708 pp_pre_include(param);
711 case 'd': /* pre-define */
713 pp_pre_define(param);
716 case 'u': /* un-define */
718 pp_pre_undefine(param);
721 case 'i': /* include search path */
723 pp_include_path(param);
726 case 'l': /* listing file */
727 copy_filename(listname, param);
730 case 'Z': /* error messages file */
731 strcpy(errname, param);
734 case 'F': /* specify debug format */
735 ofmt->current_dfmt = dfmt_find(ofmt, param);
736 if (!ofmt->current_dfmt) {
737 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
738 "unrecognized debug format `%s' for"
739 " output format `%s'",
740 param, ofmt->shortname);
742 using_debug_info = true;
745 case 'X': /* specify error reporting format */
746 if (nasm_stricmp("vc", param) == 0)
747 nasm_set_verror(nasm_verror_vc);
748 else if (nasm_stricmp("gnu", param) == 0)
749 nasm_set_verror(nasm_verror_gnu);
751 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
752 "unrecognized error reporting format `%s'",
757 using_debug_info = true;
762 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
764 " [options...] [--] filename\n"
765 " or nasm -v for version info\n\n"
766 " -t assemble in SciTech TASM compatible mode\n"
767 " -g generate debug information in selected format.\n");
769 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
770 " -a don't preprocess (assemble only)\n"
771 " -M generate Makefile dependencies on stdout\n"
772 " -MG d:o, missing files assumed generated\n\n"
773 " -Z<file> redirect error messages to file\n"
774 " -s redirect error messages to stdout\n\n"
775 " -F format select a debugging format\n\n"
776 " -I<path> adds a pathname to the include file path\n");
778 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
779 " -P<file> pre-includes a file\n"
780 " -D<macro>[=<value>] pre-defines a macro\n"
781 " -U<macro> undefines a macro\n"
782 " -X<format> specifies error reporting format (gnu or vc)\n"
783 " -w+foo enables warning foo (equiv. -Wfoo)\n"
784 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
786 for (i = 0; i <= ERR_WARN_MAX; i++)
787 printf(" %-23s %s (default %s)\n",
788 warnings[i].name, warnings[i].help,
789 warnings[i].enabled ? "on" : "off");
791 ("\nresponse files should contain command line parameters"
792 ", one per line.\n");
794 printf("\nvalid output formats for -f are"
795 " (`*' denotes default):\n");
796 ofmt_list(ofmt, stdout);
798 printf("\nFor a list of valid output formats, use -hf.\n");
799 printf("For a list of debug formats, use -f <form> -y.\n");
801 exit(0); /* never need usage message here */
805 printf("\nvalid debug formats for '%s' output format are"
806 " ('*' denotes default):\n", ofmt->shortname);
807 dfmt_list(ofmt, stdout);
812 tasm_compatible_mode = true;
816 printf("NASM version %s compiled on %s%s\n",
817 nasm_version, nasm_date, nasm_compile_options);
818 exit(0); /* never need usage message here */
821 case 'e': /* preprocess only */
823 operating_mode = op_preprocess;
826 case 'a': /* assemble only - don't preprocess */
831 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
840 if (param[0] != '+' && param[0] != '-') {
841 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
842 "invalid option to `-w'");
845 do_warn = (param[0] == '+');
849 for (i = 0; i <= ERR_WARN_MAX; i++)
850 if (!nasm_stricmp(param, warnings[i].name))
852 if (i <= ERR_WARN_MAX)
853 warning_on_global[i] = do_warn;
854 else if (!nasm_stricmp(param, "all"))
855 for (i = 1; i <= ERR_WARN_MAX; i++)
856 warning_on_global[i] = do_warn;
857 else if (!nasm_stricmp(param, "none"))
858 for (i = 1; i <= ERR_WARN_MAX; i++)
859 warning_on_global[i] = !do_warn;
861 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
862 "invalid warning `%s'", param);
868 operating_mode = op_depend;
871 operating_mode = op_depend;
872 depend_missing_ok = true;
875 depend_emit_phony = true;
886 depend_target = quote_for_make(q);
890 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
891 "unknown dependency option `-M%c'", p[2]);
894 if (advance && (!q || !q[0])) {
895 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
896 "option `-M%c' requires a parameter", p[2]);
905 if (p[2] == 0) { /* -- => stop processing options */
909 for (s = 0; textopts[s].label; s++) {
910 if (!nasm_stricmp(p + 2, textopts[s].label)) {
921 nasm_error(ERR_NONFATAL | ERR_NOFILE |
923 "option `--%s' requires an argument",
927 advance = 1, param = q;
930 if (s == OPT_PREFIX) {
931 strncpy(lprefix, param, PREFIX_MAX - 1);
932 lprefix[PREFIX_MAX - 1] = 0;
935 if (s == OPT_POSTFIX) {
936 strncpy(lpostfix, param, POSTFIX_MAX - 1);
937 lpostfix[POSTFIX_MAX - 1] = 0;
944 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
945 "unrecognised option `--%s'", p + 2);
953 if (!ofmt->setinfo(GI_SWITCH, &p))
954 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
955 "unrecognised option `-%c'", p[1]);
960 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
961 "more than one input file specified");
963 copy_filename(inname, p);
970 #define ARG_BUF_DELTA 128
972 static void process_respfile(FILE * rfile)
974 char *buffer, *p, *q, *prevarg;
975 int bufsize, prevargsize;
977 bufsize = prevargsize = ARG_BUF_DELTA;
978 buffer = nasm_malloc(ARG_BUF_DELTA);
979 prevarg = nasm_malloc(ARG_BUF_DELTA);
982 while (1) { /* Loop to handle all lines in file */
984 while (1) { /* Loop to handle long lines */
985 q = fgets(p, bufsize - (p - buffer), rfile);
989 if (p > buffer && p[-1] == '\n')
991 if (p - buffer > bufsize - 10) {
994 bufsize += ARG_BUF_DELTA;
995 buffer = nasm_realloc(buffer, bufsize);
1000 if (!q && p == buffer) {
1002 process_arg(prevarg, NULL);
1009 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1010 * them are present at the end of the line.
1012 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1014 while (p > buffer && nasm_isspace(p[-1]))
1018 while (nasm_isspace(*p))
1021 if (process_arg(prevarg, p))
1024 if ((int) strlen(p) > prevargsize - 10) {
1025 prevargsize += ARG_BUF_DELTA;
1026 prevarg = nasm_realloc(prevarg, prevargsize);
1028 strncpy(prevarg, p, prevargsize);
1032 /* Function to process args from a string of args, rather than the
1033 * argv array. Used by the environment variable and response file
1036 static void process_args(char *args)
1038 char *p, *q, *arg, *prevarg;
1039 char separator = ' ';
1042 if (*p && *p != '-')
1047 while (*p && *p != separator)
1049 while (*p == separator)
1053 if (process_arg(prevarg, arg))
1057 process_arg(arg, NULL);
1060 static void process_response_file(const char *file)
1063 FILE *f = fopen(file, "r");
1068 while (fgets(str, sizeof str, f)) {
1074 static void parse_cmdline(int argc, char **argv)
1077 char *envreal, *envcopy = NULL, *p, *arg;
1080 *inname = *outname = *listname = *errname = '\0';
1081 for (i = 0; i <= ERR_WARN_MAX; i++)
1082 warning_on_global[i] = warnings[i].enabled;
1085 * First, process the NASMENV environment variable.
1087 envreal = getenv("NASMENV");
1090 envcopy = nasm_strdup(envreal);
1091 process_args(envcopy);
1096 * Now process the actual command line.
1101 if (argv[0][0] == '@') {
1102 /* We have a response file, so process this as a set of
1103 * arguments like the environment variable. This allows us
1104 * to have multiple arguments on a single line, which is
1105 * different to the -@resp file processing below for regular
1108 process_response_file(argv[0]+1);
1112 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1113 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1115 rfile = fopen(p, "r");
1117 process_respfile(rfile);
1120 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1121 "unable to open response file `%s'", p);
1124 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1125 argv += advance, argc -= advance;
1128 /* Look for basic command line typos. This definitely doesn't
1129 catch all errors, but it might help cases of fumbled fingers. */
1131 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1132 "no input file specified");
1133 else if (!strcmp(inname, errname) ||
1134 !strcmp(inname, outname) ||
1135 !strcmp(inname, listname) ||
1136 (depend_file && !strcmp(inname, depend_file)))
1137 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1138 "file `%s' is both input and output file",
1142 error_file = fopen(errname, "w");
1144 error_file = stderr; /* Revert to default! */
1145 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1146 "cannot open file `%s' for error messages",
1152 static enum directives getkw(char **directive, char **value);
1154 static void assemble_file(char *fname, StrList **depend_ptr)
1156 char *directive, *value, *p, *q, *special, *line, debugid[80];
1162 struct tokenval tokval;
1166 if (cmd_sb == 32 && cmd_cpu < IF_386)
1167 nasm_error(ERR_FATAL, "command line: "
1168 "32-bit segment size requires a higher cpu");
1170 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1171 for (passn = 1; pass0 <= 2; passn++) {
1175 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1176 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1177 /* pass0 0, 0, 0, ..., 1, 2 */
1179 def_label = passn > 1 ? redefine_label : define_label;
1181 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1185 nasmlist.init(listname, nasm_error);
1188 global_offset_changed = 0; /* set by redefine_label */
1189 location.segment = ofmt->section(NULL, pass2, &sb);
1192 saa_rewind(forwrefs);
1193 forwref = saa_rstruct(forwrefs);
1195 offsets = raa_init();
1197 preproc->reset(fname, pass1, &nasmlist,
1198 pass1 == 2 ? depend_ptr : NULL);
1199 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1203 location.known = true;
1204 location.offset = offs = GET_CURR_OFFS;
1206 while ((line = preproc->getline())) {
1211 * Here we parse our directives; this is not handled by the
1212 * 'real' parser. This really should be a separate function.
1215 d = getkw(&directive, &value);
1220 case D_SEGMENT: /* [SEGMENT n] */
1222 seg = ofmt->section(value, pass2, &sb);
1223 if (seg == NO_SEG) {
1224 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1225 "segment name `%s' not recognized",
1229 location.segment = seg;
1232 case D_EXTERN: /* [EXTERN label:special] */
1234 value++; /* skip initial $ if present */
1237 while (*q && *q != ':')
1241 ofmt->symdef(value, 0L, 0L, 3, q);
1243 } else if (passn == 1) {
1248 while (*q && *q != ':') {
1254 nasm_error(ERR_NONFATAL,
1255 "identifier expected after EXTERN");
1263 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1265 pass0 = 1; /* fake pass 1 in labels.c */
1266 declare_as_global(value, special);
1267 define_label(value, seg_alloc(), 0L, NULL,
1271 } /* else pass0 == 1 */
1273 case D_BITS: /* [BITS bits] */
1274 globalbits = sb = get_bits(value);
1276 case D_GLOBAL: /* [GLOBAL symbol:special] */
1278 value++; /* skip initial $ if present */
1279 if (pass0 == 2) { /* pass 2 */
1281 while (*q && *q != ':')
1285 ofmt->symdef(value, 0L, 0L, 3, q);
1287 } else if (pass2 == 1) { /* pass == 1 */
1292 while (*q && *q != ':') {
1298 nasm_error(ERR_NONFATAL,
1299 "identifier expected after GLOBAL");
1307 declare_as_global(value, special);
1310 case D_COMMON: /* [COMMON symbol size:special] */
1315 value++; /* skip initial $ if present */
1320 while (*p && !nasm_isspace(*p)) {
1326 nasm_error(ERR_NONFATAL,
1327 "identifier expected after COMMON");
1331 while (*p && nasm_isspace(*p))
1334 while (*q && *q != ':')
1342 size = readnum(p, &rn_error);
1344 nasm_error(ERR_NONFATAL,
1345 "invalid size specified"
1346 " in COMMON declaration");
1350 nasm_error(ERR_NONFATAL,
1351 "no size specified in"
1352 " COMMON declaration");
1357 define_common(value, seg_alloc(), size, special);
1358 } else if (pass0 == 2) {
1360 ofmt->symdef(value, 0L, 0L, 3, special);
1364 case D_ABSOLUTE: /* [ABSOLUTE address] */
1366 stdscan_bufptr = value;
1367 tokval.t_type = TOKEN_INVALID;
1368 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1373 1 ? ERR_NONFATAL : ERR_PANIC,
1374 "cannot use non-relocatable expression as "
1375 "ABSOLUTE address");
1377 abs_seg = reloc_seg(e);
1378 abs_offset = reloc_value(e);
1380 } else if (passn == 1)
1381 abs_offset = 0x100; /* don't go near zero in case of / */
1383 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1386 location.segment = NO_SEG;
1388 case D_DEBUG: /* [DEBUG] */
1394 while (*p && !nasm_isspace(*p)) {
1401 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1402 "identifier expected after DEBUG");
1405 while (*p && nasm_isspace(*p))
1408 dfmt->debug_directive(debugid, p);
1410 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1411 while (*value && nasm_isspace(*value))
1415 case '-': validid = 0; value++; break;
1416 case '+': validid = 1; value++; break;
1417 case '*': validid = 2; value++; break;
1418 default: validid = 1; break;
1421 for (i = 1; i <= ERR_WARN_MAX; i++)
1422 if (!nasm_stricmp(value, warnings[i].name))
1424 if (i <= ERR_WARN_MAX) {
1427 warning_on[i] = false;
1430 warning_on[i] = true;
1433 warning_on[i] = warning_on_global[i];
1438 nasm_error(ERR_NONFATAL,
1439 "invalid warning id in WARNING directive");
1441 case D_CPU: /* [CPU] */
1442 cpu = get_cpu(value);
1444 case D_LIST: /* [LIST {+|-}] */
1445 while (*value && nasm_isspace(*value))
1448 if (*value == '+') {
1451 if (*value == '-') {
1458 case D_DEFAULT: /* [DEFAULT] */
1460 stdscan_bufptr = value;
1461 tokval.t_type = TOKEN_INVALID;
1462 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1463 switch ((int)tokval.t_integer) {
1479 if (float_option(value)) {
1480 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1481 "unknown 'float' directive: %s",
1486 if (!d || !ofmt->directive(d, value, pass2))
1487 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1488 "unrecognised directive [%s]",
1493 nasm_error(ERR_NONFATAL,
1494 "invalid parameter to [%s] directive",
1497 } else { /* it isn't a directive */
1498 parse_line(pass1, line, &output_ins, def_label);
1500 if (optimizing > 0) {
1501 if (forwref != NULL && globallineno == forwref->lineno) {
1502 output_ins.forw_ref = true;
1504 output_ins.oprs[forwref->operand].opflags |=
1506 forwref = saa_rstruct(forwrefs);
1507 } while (forwref != NULL
1508 && forwref->lineno == globallineno);
1510 output_ins.forw_ref = false;
1512 if (output_ins.forw_ref) {
1514 for (i = 0; i < output_ins.operands; i++) {
1515 if (output_ins.oprs[i].
1516 opflags & OPFLAG_FORWARD) {
1517 struct forwrefinfo *fwinf =
1518 (struct forwrefinfo *)
1519 saa_wstruct(forwrefs);
1520 fwinf->lineno = globallineno;
1529 if (output_ins.opcode == I_EQU) {
1532 * Special `..' EQUs get processed in pass two,
1533 * except `..@' macro-processor EQUs which are done
1534 * in the normal place.
1536 if (!output_ins.label)
1537 nasm_error(ERR_NONFATAL,
1538 "EQU not preceded by label");
1540 else if (output_ins.label[0] != '.' ||
1541 output_ins.label[1] != '.' ||
1542 output_ins.label[2] == '@') {
1543 if (output_ins.operands == 1 &&
1544 (output_ins.oprs[0].type & IMMEDIATE) &&
1545 output_ins.oprs[0].wrt == NO_SEG) {
1546 bool isext = !!(output_ins.oprs[0].opflags
1548 def_label(output_ins.label,
1549 output_ins.oprs[0].segment,
1550 output_ins.oprs[0].offset, NULL,
1552 } else if (output_ins.operands == 2
1553 && (output_ins.oprs[0].type & IMMEDIATE)
1554 && (output_ins.oprs[0].type & COLON)
1555 && output_ins.oprs[0].segment == NO_SEG
1556 && output_ins.oprs[0].wrt == NO_SEG
1557 && (output_ins.oprs[1].type & IMMEDIATE)
1558 && output_ins.oprs[1].segment == NO_SEG
1559 && output_ins.oprs[1].wrt == NO_SEG) {
1560 def_label(output_ins.label,
1561 output_ins.oprs[0].offset | SEG_ABS,
1562 output_ins.oprs[1].offset,
1563 NULL, false, false);
1565 nasm_error(ERR_NONFATAL,
1566 "bad syntax for EQU");
1570 * Special `..' EQUs get processed here, except
1571 * `..@' macro processor EQUs which are done above.
1573 if (output_ins.label[0] == '.' &&
1574 output_ins.label[1] == '.' &&
1575 output_ins.label[2] != '@') {
1576 if (output_ins.operands == 1 &&
1577 (output_ins.oprs[0].type & IMMEDIATE)) {
1578 define_label(output_ins.label,
1579 output_ins.oprs[0].segment,
1580 output_ins.oprs[0].offset,
1581 NULL, false, false);
1582 } else if (output_ins.operands == 2
1583 && (output_ins.oprs[0].
1585 && (output_ins.oprs[0].type & COLON)
1586 && output_ins.oprs[0].segment ==
1588 && (output_ins.oprs[1].
1590 && output_ins.oprs[1].segment ==
1592 define_label(output_ins.label,
1595 output_ins.oprs[1].offset,
1596 NULL, false, false);
1598 nasm_error(ERR_NONFATAL,
1599 "bad syntax for EQU");
1602 } else { /* instruction isn't an EQU */
1606 int64_t l = insn_size(location.segment, offs, sb, cpu,
1607 &output_ins, nasm_error);
1609 /* if (using_debug_info) && output_ins.opcode != -1) */
1610 if (using_debug_info)
1611 { /* fbk 03/25/01 */
1612 /* this is done here so we can do debug type info */
1614 TYS_ELEMENTS(output_ins.operands);
1615 switch (output_ins.opcode) {
1618 TYS_ELEMENTS(output_ins.oprs[0].
1623 TYS_ELEMENTS(output_ins.oprs[0].
1628 TYS_ELEMENTS(output_ins.oprs[0].
1633 TYS_ELEMENTS(output_ins.oprs[0].
1638 TYS_ELEMENTS(output_ins.oprs[0].
1643 TYS_ELEMENTS(output_ins.oprs[0].
1648 TYS_ELEMENTS(output_ins.oprs[0].
1652 typeinfo |= TY_BYTE;
1655 typeinfo |= TY_WORD;
1658 if (output_ins.eops_float)
1659 typeinfo |= TY_FLOAT;
1661 typeinfo |= TY_DWORD;
1664 typeinfo |= TY_QWORD;
1667 typeinfo |= TY_TBYTE;
1670 typeinfo |= TY_OWORD;
1673 typeinfo |= TY_YWORD;
1676 typeinfo = TY_LABEL;
1680 dfmt->debug_typevalue(typeinfo);
1684 SET_CURR_OFFS(offs);
1687 * else l == -1 => invalid instruction, which will be
1688 * flagged as an error on pass 2
1692 offs += assemble(location.segment, offs, sb, cpu,
1693 &output_ins, ofmt, nasm_error,
1695 SET_CURR_OFFS(offs);
1699 cleanup_insn(&output_ins);
1702 location.offset = offs = GET_CURR_OFFS;
1703 } /* end while (line = preproc->getline... */
1705 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1706 nasm_error(ERR_NONFATAL,
1707 "phase error detected at end of assembly.");
1710 preproc->cleanup(1);
1712 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1714 } else if (global_offset_changed &&
1715 global_offset_changed < prev_offset_changed) {
1716 prev_offset_changed = global_offset_changed;
1722 if (terminate_after_phase)
1725 if ((stall_count > 997) || (passn >= pass_max)) {
1726 /* We get here if the labels don't converge
1727 * Example: FOO equ FOO + 1
1729 nasm_error(ERR_NONFATAL,
1730 "Can't find valid values for all labels "
1731 "after %d passes, giving up.", passn);
1732 nasm_error(ERR_NONFATAL,
1733 "Possible causes: recursive EQUs, macro abuse.");
1738 preproc->cleanup(0);
1740 if (!terminate_after_phase && opt_verbose_info) {
1741 /* -On and -Ov switches */
1742 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1746 static enum directives getkw(char **directive, char **value)
1752 /* allow leading spaces or tabs */
1753 while (*buf == ' ' || *buf == '\t')
1761 while (*p && *p != ']')
1769 while (*p && *p != ';') {
1770 if (!nasm_isspace(*p))
1776 *directive = p = buf + 1;
1777 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1784 while (nasm_isspace(*buf))
1785 buf++; /* beppu - skip leading whitespace */
1792 return find_directive(*directive);
1796 * gnu style error reporting
1797 * This function prints an error message to error_file in the
1798 * style used by GNU. An example would be:
1799 * file.asm:50: error: blah blah blah
1800 * where file.asm is the name of the file, 50 is the line number on
1801 * which the error occurs (or is detected) and "error:" is one of
1802 * the possible optional diagnostics -- it can be "error" or "warning"
1803 * or something else. Finally the line terminates with the actual
1806 * @param severity the severity of the warning or error
1807 * @param fmt the printf style format string
1809 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1811 char *currentfile = NULL;
1814 if (is_suppressed_warning(severity))
1817 if (!(severity & ERR_NOFILE))
1818 src_get(&lineno, ¤tfile);
1821 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1822 nasm_free(currentfile);
1824 fputs("nasm: ", error_file);
1827 nasm_verror_common(severity, fmt, ap);
1831 * MS style error reporting
1832 * This function prints an error message to error_file in the
1833 * style used by Visual C and some other Microsoft tools. An example
1835 * file.asm(50) : error: blah blah blah
1836 * where file.asm is the name of the file, 50 is the line number on
1837 * which the error occurs (or is detected) and "error:" is one of
1838 * the possible optional diagnostics -- it can be "error" or "warning"
1839 * or something else. Finally the line terminates with the actual
1842 * @param severity the severity of the warning or error
1843 * @param fmt the printf style format string
1845 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1847 char *currentfile = NULL;
1850 if (is_suppressed_warning(severity))
1853 if (!(severity & ERR_NOFILE))
1854 src_get(&lineno, ¤tfile);
1857 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1858 nasm_free(currentfile);
1860 fputs("nasm: ", error_file);
1863 nasm_verror_common(severity, fmt, ap);
1867 * check for supressed warning
1868 * checks for suppressed warning or pass one only warning and we're
1871 * @param severity the severity of the warning or error
1872 * @return true if we should abort error/warning printing
1874 static bool is_suppressed_warning(int severity)
1877 * See if it's a suppressed warning.
1879 return (severity & ERR_MASK) == ERR_WARNING &&
1880 (((severity & ERR_WARN_MASK) != 0 &&
1881 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1882 /* See if it's a pass-one only warning and we're not in pass one. */
1883 ((severity & ERR_PASS1) && pass0 != 1) ||
1884 ((severity & ERR_PASS2) && pass0 != 2));
1888 * common error reporting
1889 * This is the common back end of the error reporting schemes currently
1890 * implemented. It prints the nature of the warning and then the
1891 * specific error message to error_file and may or may not return. It
1892 * doesn't return if the error severity is a "panic" or "debug" type.
1894 * @param severity the severity of the warning or error
1895 * @param fmt the printf style format string
1897 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1902 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1923 vsnprintf(msg, sizeof msg, fmt, args);
1925 fprintf(error_file, "%s%s\n", pfx, msg);
1928 nasmlist.error(severity, pfx, msg);
1930 if (severity & ERR_USAGE)
1933 switch (severity & ERR_MASK) {
1935 /* no further action, by definition */
1938 if (warning_on[0]) /* Treat warnings as errors */
1939 terminate_after_phase = true;
1942 terminate_after_phase = true;
1952 exit(1); /* instantly die */
1953 break; /* placate silly compilers */
1956 /* abort(); *//* halt, catch fire, and dump core */
1962 static void usage(void)
1964 fputs("type `nasm -h' for help\n", error_file);
1967 #define BUF_DELTA 512
1969 static FILE *no_pp_fp;
1970 static ListGen *no_pp_list;
1971 static int32_t no_pp_lineinc;
1973 static void no_pp_reset(char *file, int pass, ListGen * listgen,
1976 src_set_fname(nasm_strdup(file));
1979 no_pp_fp = fopen(file, "r");
1981 nasm_error(ERR_FATAL | ERR_NOFILE,
1982 "unable to open input file `%s'", file);
1983 no_pp_list = listgen;
1984 (void)pass; /* placate compilers */
1987 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
1989 strcpy(sl->str, file);
1994 static char *no_pp_getline(void)
1996 char *buffer, *p, *q;
1999 bufsize = BUF_DELTA;
2000 buffer = nasm_malloc(BUF_DELTA);
2001 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2003 while (1) { /* Loop to handle %line */
2006 while (1) { /* Loop to handle long lines */
2007 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2011 if (p > buffer && p[-1] == '\n')
2013 if (p - buffer > bufsize - 10) {
2015 offset = p - buffer;
2016 bufsize += BUF_DELTA;
2017 buffer = nasm_realloc(buffer, bufsize);
2018 p = buffer + offset;
2022 if (!q && p == buffer) {
2028 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2029 * them are present at the end of the line.
2031 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2033 if (!nasm_strnicmp(buffer, "%line", 5)) {
2036 char *nm = nasm_malloc(strlen(buffer));
2037 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2038 nasm_free(src_set_fname(nm));
2048 no_pp_list->line(LIST_READ, buffer);
2053 static void no_pp_cleanup(int pass)
2055 (void)pass; /* placate GCC */
2059 static uint32_t get_cpu(char *value)
2061 if (!strcmp(value, "8086"))
2063 if (!strcmp(value, "186"))
2065 if (!strcmp(value, "286"))
2067 if (!strcmp(value, "386"))
2069 if (!strcmp(value, "486"))
2071 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2073 if (!strcmp(value, "686") ||
2074 !nasm_stricmp(value, "ppro") ||
2075 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2077 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2079 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2080 !nasm_stricmp(value, "willamette"))
2081 return IF_WILLAMETTE;
2082 if (!nasm_stricmp(value, "prescott"))
2084 if (!nasm_stricmp(value, "x64") ||
2085 !nasm_stricmp(value, "x86-64"))
2087 if (!nasm_stricmp(value, "ia64") ||
2088 !nasm_stricmp(value, "ia-64") ||
2089 !nasm_stricmp(value, "itanium") ||
2090 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2093 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2094 "unknown 'cpu' type");
2096 return IF_PLEVEL; /* the maximum level */
2099 static int get_bits(char *value)
2103 if ((i = atoi(value)) == 16)
2104 return i; /* set for a 16-bit segment */
2107 nasm_error(ERR_NONFATAL,
2108 "cannot specify 32-bit segment on processor below a 386");
2111 } else if (i == 64) {
2112 if (cpu < IF_X86_64) {
2113 nasm_error(ERR_NONFATAL,
2114 "cannot specify 64-bit segment on processor below an x86-64");
2118 nasm_error(ERR_NONFATAL,
2119 "%s output format does not support 64-bit code",
2124 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2125 "`%s' is not a valid segment size; must be 16, 32 or 64",