1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2011 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"
65 * This is the maximum number of optimization passes to do. If we ever
66 * find a case where the optimizer doesn't naturally converge, we might
67 * have to drop this value so the assembler doesn't appear to just hang.
69 #define MAX_OPTIMIZE (INT_MAX >> 1)
71 struct forwrefinfo { /* info held on forward refs. */
76 static int get_bits(char *value);
77 static uint32_t get_cpu(char *cpu_str);
78 static void parse_cmdline(int, char **);
79 static void assemble_file(char *, StrList **);
80 static void nasm_verror_gnu(int severity, const char *fmt, va_list args);
81 static void nasm_verror_vc(int severity, const char *fmt, va_list args);
82 static void nasm_verror_common(int severity, const char *fmt, va_list args);
83 static bool is_suppressed_warning(int severity);
84 static void usage(void);
86 static int using_debug_info, opt_verbose_info;
87 bool tasm_compatible_mode = false;
92 static time_t official_compile_time;
94 static char inname[FILENAME_MAX];
95 static char outname[FILENAME_MAX];
96 static char listname[FILENAME_MAX];
97 static char errname[FILENAME_MAX];
98 static int globallineno; /* for forward-reference tracking */
99 /* static int pass = 0; */
100 struct ofmt *ofmt = &OF_DEFAULT;
101 struct ofmt_alias *ofmt_alias = NULL;
102 const struct dfmt *dfmt;
104 static FILE *error_file; /* Where to write error messages */
107 int optimizing = MAX_OPTIMIZE; /* number of optimization passes to take */
108 static int sb, cmd_sb = 16; /* by default */
109 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
110 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
111 int64_t global_offset_changed; /* referenced in labels.c */
112 int64_t prev_offset_changed;
115 static struct location location;
116 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
117 int32_t abs_seg; /* ABSOLUTE segment basis */
118 int32_t abs_offset; /* ABSOLUTE offset */
120 static struct RAA *offsets;
122 static struct SAA *forwrefs; /* keep track of forward references */
123 static const struct forwrefinfo *forwref;
125 static Preproc *preproc;
127 op_normal, /* Preprocess and assemble */
128 op_preprocess, /* Preprocess only */
129 op_depend, /* Generate dependencies */
131 static enum op_type operating_mode;
132 /* Dependency flags */
133 static bool depend_emit_phony = false;
134 static bool depend_missing_ok = false;
135 static const char *depend_target = NULL;
136 static const char *depend_file = NULL;
139 * Which of the suppressible warnings are suppressed. Entry zero
140 * isn't an actual warning, but it used for -w+error/-Werror.
143 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
144 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
146 static const struct warning {
150 } warnings[ERR_WARN_MAX+1] = {
151 {"error", "treat warnings as errors", false},
152 {"macro-params", "macro calls with wrong parameter count", true},
153 {"macro-selfref", "cyclic macro references", false},
154 {"macro-defaults", "macros with more default than optional parameters", true},
155 {"orphan-labels", "labels alone on lines without trailing `:'", true},
156 {"number-overflow", "numeric constant does not fit", true},
157 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
158 {"float-overflow", "floating point overflow", true},
159 {"float-denorm", "floating point denormal", false},
160 {"float-underflow", "floating point underflow", false},
161 {"float-toolong", "too many digits in floating-point number", true},
162 {"user", "%warning directives", true},
166 * This is a null preprocessor which just copies lines from input
167 * to output. It's used when someone explicitly requests that NASM
168 * not preprocess their source file.
171 static void no_pp_reset(char *, int, ListGen *, StrList **);
172 static char *no_pp_getline(void);
173 static void no_pp_cleanup(int);
174 static Preproc no_pp = {
181 * get/set current offset...
183 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
184 raa_read(offsets,location.segment))
185 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
186 (void)(offsets=raa_write(offsets,location.segment,(x))))
188 static bool want_usage;
189 static bool terminate_after_phase;
190 int user_nolist = 0; /* fbk 9/2/00 */
192 static void nasm_fputs(const char *line, FILE * outfile)
195 fputs(line, outfile);
201 /* Convert a struct tm to a POSIX-style time constant */
202 static int64_t posix_mktime(struct tm *tm)
205 int64_t y = tm->tm_year;
207 /* See IEEE 1003.1:2004, section 4.14 */
209 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
221 static void define_macros_early(void)
224 struct tm lt, *lt_p, gm, *gm_p;
227 lt_p = localtime(&official_compile_time);
231 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", <);
233 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", <);
235 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", <);
237 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", <);
241 gm_p = gmtime(&official_compile_time);
245 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
247 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
249 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
251 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
256 posix_time = posix_mktime(&gm);
258 posix_time = posix_mktime(<);
263 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
268 static void define_macros_late(void)
273 * In case if output format is defined by alias
274 * we have to put shortname of the alias itself here
275 * otherwise ABI backward compatibility gets broken.
277 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s",
278 ofmt_alias ? ofmt_alias->shortname : ofmt->shortname);
282 static void emit_dependencies(StrList *list)
288 if (depend_file && strcmp(depend_file, "-")) {
289 deps = fopen(depend_file, "w");
291 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
292 "unable to write dependency file `%s'", depend_file);
299 linepos = fprintf(deps, "%s:", depend_target);
300 list_for_each(l, list) {
301 len = strlen(l->str);
302 if (linepos + len > 62) {
303 fprintf(deps, " \\\n ");
306 fprintf(deps, " %s", l->str);
309 fprintf(deps, "\n\n");
311 list_for_each_safe(l, nl, list) {
312 if (depend_emit_phony)
313 fprintf(deps, "%s:\n\n", l->str);
321 int main(int argc, char **argv)
323 StrList *depend_list = NULL, **depend_ptr;
325 time(&official_compile_time);
328 want_usage = terminate_after_phase = false;
329 nasm_set_verror(nasm_verror_gnu);
335 nasm_init_malloc_error();
336 offsets = raa_init();
337 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
340 operating_mode = op_normal;
344 /* Define some macros dependent on the runtime, but not
345 on the command line. */
346 define_macros_early();
348 parse_cmdline(argc, argv);
350 if (terminate_after_phase) {
356 /* If debugging info is disabled, suppress any debug calls */
357 if (!using_debug_info)
358 ofmt->current_dfmt = &null_debug_form;
361 pp_extra_stdmac(ofmt->stdmac);
362 parser_global_info(&location);
363 eval_global_info(ofmt, lookup_label, &location);
365 /* define some macros dependent of command-line */
366 define_macros_late();
368 depend_ptr = (depend_file || (operating_mode == op_depend))
369 ? &depend_list : NULL;
371 depend_target = outname;
373 switch (operating_mode) {
378 if (depend_missing_ok)
379 pp_include_path(NULL); /* "assume generated" */
381 preproc->reset(inname, 0, &nasmlist, depend_ptr);
382 if (outname[0] == '\0')
383 ofmt->filename(inname, outname);
385 while ((line = preproc->getline()))
394 char *file_name = NULL;
395 int32_t prior_linnum = 0;
399 ofile = fopen(outname, "w");
401 nasm_error(ERR_FATAL | ERR_NOFILE,
402 "unable to open output file `%s'",
407 location.known = false;
410 preproc->reset(inname, 3, &nasmlist, depend_ptr);
412 while ((line = preproc->getline())) {
414 * We generate %line directives if needed for later programs
416 int32_t linnum = prior_linnum += lineinc;
417 int altline = src_get(&linnum, &file_name);
419 if (altline == 1 && lineinc == 1)
420 nasm_fputs("", ofile);
422 lineinc = (altline != -1 || lineinc != 1);
423 fprintf(ofile ? ofile : stdout,
424 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
427 prior_linnum = linnum;
429 nasm_fputs(line, ofile);
432 nasm_free(file_name);
436 if (ofile && terminate_after_phase)
445 * We must call ofmt->filename _anyway_, even if the user
446 * has specified their own output file, because some
447 * formats (eg OBJ and COFF) use ofmt->filename to find out
448 * the name of the input file and then put that inside the
451 ofmt->filename(inname, outname);
453 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
455 nasm_error(ERR_FATAL | ERR_NOFILE,
456 "unable to open output file `%s'", outname);
460 * We must call init_labels() before ofmt->init() since
461 * some object formats will want to define labels in their
462 * init routines. (eg OS/2 defines the FLAT group)
467 dfmt = ofmt->current_dfmt;
470 assemble_file(inname, depend_ptr);
472 if (!terminate_after_phase) {
473 ofmt->cleanup(using_debug_info);
477 nasm_error(ERR_NONFATAL|ERR_NOFILE,
478 "write error on output file `%s'", outname);
484 if (terminate_after_phase)
492 if (depend_list && !terminate_after_phase)
493 emit_dependencies(depend_list);
503 return terminate_after_phase;
507 * Get a parameter for a command line option.
508 * First arg must be in the form of e.g. -f...
510 static char *get_param(char *p, char *q, bool *advance)
513 if (p[2]) /* the parameter's in the option */
514 return nasm_skip_spaces(p + 2);
519 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
520 "option `-%c' requires an argument", p[1]);
527 static void copy_filename(char *dst, const char *src)
529 size_t len = strlen(src);
531 if (len >= (size_t)FILENAME_MAX) {
532 nasm_error(ERR_FATAL | ERR_NOFILE, "file name too long");
535 strncpy(dst, src, FILENAME_MAX);
539 * Convert a string to Make-safe form
541 static char *quote_for_make(const char *str)
546 size_t n = 1; /* Terminating zero */
552 for (p = str; *p; p++) {
556 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
576 /* Convert N backslashes at the end of filename to 2N backslashes */
580 os = q = nasm_malloc(n);
583 for (p = str; *p; p++) {
626 #define OPT_POSTFIX 1
627 struct textargs textopts[] = {
628 {"prefix", OPT_PREFIX},
629 {"postfix", OPT_POSTFIX},
633 static bool stopoptions = false;
634 static bool process_arg(char *p, char *q)
638 bool advance = false;
644 if (p[0] == '-' && !stopoptions) {
645 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
646 /* These parameters take values */
647 if (!(param = get_param(p, q, &advance)))
656 case 'o': /* output file */
657 copy_filename(outname, param);
660 case 'f': /* output format */
661 ofmt = ofmt_find(param, &ofmt_alias);
663 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
664 "unrecognised output format `%s' - "
665 "use -hf for a list", param);
669 case 'O': /* Optimization level */
674 /* Naked -O == -Ox */
675 optimizing = MAX_OPTIMIZE;
679 case '0': case '1': case '2': case '3': case '4':
680 case '5': case '6': case '7': case '8': case '9':
681 opt = strtoul(param, ¶m, 10);
683 /* -O0 -> optimizing == -1, 0.98 behaviour */
684 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
686 optimizing = opt - 1;
694 opt_verbose_info = true;
699 optimizing = MAX_OPTIMIZE;
703 nasm_error(ERR_FATAL,
704 "unknown optimization option -O%c\n",
709 if (optimizing > MAX_OPTIMIZE)
710 optimizing = MAX_OPTIMIZE;
715 case 'p': /* pre-include */
717 pp_pre_include(param);
720 case 'd': /* pre-define */
722 pp_pre_define(param);
725 case 'u': /* un-define */
727 pp_pre_undefine(param);
730 case 'i': /* include search path */
732 pp_include_path(param);
735 case 'l': /* listing file */
736 copy_filename(listname, param);
739 case 'Z': /* error messages file */
740 copy_filename(errname, param);
743 case 'F': /* specify debug format */
744 ofmt->current_dfmt = dfmt_find(ofmt, param);
745 if (!ofmt->current_dfmt) {
746 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
747 "unrecognized debug format `%s' for"
748 " output format `%s'",
749 param, ofmt->shortname);
751 using_debug_info = true;
754 case 'X': /* specify error reporting format */
755 if (nasm_stricmp("vc", param) == 0)
756 nasm_set_verror(nasm_verror_vc);
757 else if (nasm_stricmp("gnu", param) == 0)
758 nasm_set_verror(nasm_verror_gnu);
760 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
761 "unrecognized error reporting format `%s'",
766 using_debug_info = true;
771 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
773 " [options...] [--] filename\n"
774 " or nasm -v for version info\n\n"
775 " -t assemble in SciTech TASM compatible mode\n"
776 " -g generate debug information in selected format\n");
778 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
779 " -a don't preprocess (assemble only)\n"
780 " -M generate Makefile dependencies on stdout\n"
781 " -MG d:o, missing files assumed generated\n"
782 " -MF <file> set Makefile dependency file\n"
783 " -MD <file> assemble and generate dependencies\n"
784 " -MT <file> dependency target name\n"
785 " -MQ <file> dependency target name (quoted)\n"
786 " -MP emit phony target\n\n"
787 " -Z<file> redirect error messages to file\n"
788 " -s redirect error messages to stdout\n\n"
789 " -F format select a debugging format\n\n"
790 " -I<path> adds a pathname to the include file path\n");
792 (" -O<digit> optimize branch offsets\n"
793 " -O0: No optimization (default)\n"
794 " -O1: Minimal optimization\n"
795 " -Ox: Multipass optimization (recommended)\n\n"
796 " -P<file> pre-includes a file\n"
797 " -D<macro>[=<value>] pre-defines a macro\n"
798 " -U<macro> undefines a macro\n"
799 " -X<format> specifies error reporting format (gnu or vc)\n"
800 " -w+foo enables warning foo (equiv. -Wfoo)\n"
801 " -w-foo disable warning foo (equiv. -Wno-foo)\n\n"
802 "--prefix,--postfix\n"
803 " this options prepend or append the given argument to all\n"
804 " extern and global variables\n\n"
806 for (i = 0; i <= ERR_WARN_MAX; i++)
807 printf(" %-23s %s (default %s)\n",
808 warnings[i].name, warnings[i].help,
809 warnings[i].enabled ? "on" : "off");
811 ("\nresponse files should contain command line parameters"
812 ", one per line.\n");
814 printf("\nvalid output formats for -f are"
815 " (`*' denotes default):\n");
816 ofmt_list(ofmt, stdout);
818 printf("\nFor a list of valid output formats, use -hf.\n");
819 printf("For a list of debug formats, use -f <form> -y.\n");
821 exit(0); /* never need usage message here */
825 printf("\nvalid debug formats for '%s' output format are"
826 " ('*' denotes default):\n", ofmt->shortname);
827 dfmt_list(ofmt, stdout);
832 tasm_compatible_mode = true;
836 printf("NASM version %s compiled on %s%s\n",
837 nasm_version, nasm_date, nasm_compile_options);
838 exit(0); /* never need usage message here */
841 case 'e': /* preprocess only */
843 operating_mode = op_preprocess;
846 case 'a': /* assemble only - don't preprocess */
851 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
860 if (param[0] != '+' && param[0] != '-') {
861 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
862 "invalid option to `-w'");
865 do_warn = (param[0] == '+');
869 for (i = 0; i <= ERR_WARN_MAX; i++)
870 if (!nasm_stricmp(param, warnings[i].name))
872 if (i <= ERR_WARN_MAX)
873 warning_on_global[i] = do_warn;
874 else if (!nasm_stricmp(param, "all"))
875 for (i = 1; i <= ERR_WARN_MAX; i++)
876 warning_on_global[i] = do_warn;
877 else if (!nasm_stricmp(param, "none"))
878 for (i = 1; i <= ERR_WARN_MAX; i++)
879 warning_on_global[i] = !do_warn;
881 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
882 "invalid warning `%s'", param);
888 operating_mode = op_depend;
891 operating_mode = op_depend;
892 depend_missing_ok = true;
895 depend_emit_phony = true;
906 depend_target = quote_for_make(q);
910 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
911 "unknown dependency option `-M%c'", p[2]);
914 if (advance && (!q || !q[0])) {
915 nasm_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
916 "option `-M%c' requires a parameter", p[2]);
925 if (p[2] == 0) { /* -- => stop processing options */
929 for (s = 0; textopts[s].label; s++) {
930 if (!nasm_stricmp(p + 2, textopts[s].label)) {
941 nasm_error(ERR_NONFATAL | ERR_NOFILE |
943 "option `--%s' requires an argument",
947 advance = 1, param = q;
950 if (s == OPT_PREFIX) {
951 strncpy(lprefix, param, PREFIX_MAX - 1);
952 lprefix[PREFIX_MAX - 1] = 0;
955 if (s == OPT_POSTFIX) {
956 strncpy(lpostfix, param, POSTFIX_MAX - 1);
957 lpostfix[POSTFIX_MAX - 1] = 0;
964 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
965 "unrecognised option `--%s'", p + 2);
973 if (!ofmt->setinfo(GI_SWITCH, &p))
974 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
975 "unrecognised option `-%c'", p[1]);
980 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
981 "more than one input file specified");
983 copy_filename(inname, p);
990 #define ARG_BUF_DELTA 128
992 static void process_respfile(FILE * rfile)
994 char *buffer, *p, *q, *prevarg;
995 int bufsize, prevargsize;
997 bufsize = prevargsize = ARG_BUF_DELTA;
998 buffer = nasm_malloc(ARG_BUF_DELTA);
999 prevarg = nasm_malloc(ARG_BUF_DELTA);
1002 while (1) { /* Loop to handle all lines in file */
1004 while (1) { /* Loop to handle long lines */
1005 q = fgets(p, bufsize - (p - buffer), rfile);
1009 if (p > buffer && p[-1] == '\n')
1011 if (p - buffer > bufsize - 10) {
1013 offset = p - buffer;
1014 bufsize += ARG_BUF_DELTA;
1015 buffer = nasm_realloc(buffer, bufsize);
1016 p = buffer + offset;
1020 if (!q && p == buffer) {
1022 process_arg(prevarg, NULL);
1029 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1030 * them are present at the end of the line.
1032 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1034 while (p > buffer && nasm_isspace(p[-1]))
1037 p = nasm_skip_spaces(buffer);
1039 if (process_arg(prevarg, p))
1042 if ((int) strlen(p) > prevargsize - 10) {
1043 prevargsize += ARG_BUF_DELTA;
1044 prevarg = nasm_realloc(prevarg, prevargsize);
1046 strncpy(prevarg, p, prevargsize);
1050 /* Function to process args from a string of args, rather than the
1051 * argv array. Used by the environment variable and response file
1054 static void process_args(char *args)
1056 char *p, *q, *arg, *prevarg;
1057 char separator = ' ';
1060 if (*p && *p != '-')
1065 while (*p && *p != separator)
1067 while (*p == separator)
1071 if (process_arg(prevarg, arg))
1075 process_arg(arg, NULL);
1078 static void process_response_file(const char *file)
1081 FILE *f = fopen(file, "r");
1086 while (fgets(str, sizeof str, f)) {
1092 static void parse_cmdline(int argc, char **argv)
1095 char *envreal, *envcopy = NULL, *p, *arg;
1098 *inname = *outname = *listname = *errname = '\0';
1099 for (i = 0; i <= ERR_WARN_MAX; i++)
1100 warning_on_global[i] = warnings[i].enabled;
1103 * First, process the NASMENV environment variable.
1105 envreal = getenv("NASMENV");
1108 envcopy = nasm_strdup(envreal);
1109 process_args(envcopy);
1114 * Now process the actual command line.
1119 if (argv[0][0] == '@') {
1120 /* We have a response file, so process this as a set of
1121 * arguments like the environment variable. This allows us
1122 * to have multiple arguments on a single line, which is
1123 * different to the -@resp file processing below for regular
1126 process_response_file(argv[0]+1);
1130 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1131 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1133 rfile = fopen(p, "r");
1135 process_respfile(rfile);
1138 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1139 "unable to open response file `%s'", p);
1142 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1143 argv += advance, argc -= advance;
1146 /* Look for basic command line typos. This definitely doesn't
1147 catch all errors, but it might help cases of fumbled fingers. */
1149 nasm_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1150 "no input file specified");
1151 else if (!strcmp(inname, errname) ||
1152 !strcmp(inname, outname) ||
1153 !strcmp(inname, listname) ||
1154 (depend_file && !strcmp(inname, depend_file)))
1155 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1156 "file `%s' is both input and output file",
1160 error_file = fopen(errname, "w");
1162 error_file = stderr; /* Revert to default! */
1163 nasm_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1164 "cannot open file `%s' for error messages",
1170 static enum directives getkw(char **directive, char **value);
1172 static void assemble_file(char *fname, StrList **depend_ptr)
1174 char *directive, *value, *p, *q, *special, *line;
1180 struct tokenval tokval;
1184 if (cmd_sb == 32 && cmd_cpu < IF_386)
1185 nasm_error(ERR_FATAL, "command line: "
1186 "32-bit segment size requires a higher cpu");
1188 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1189 for (passn = 1; pass0 <= 2; passn++) {
1193 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1194 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1195 /* pass0 0, 0, 0, ..., 1, 2 */
1197 def_label = passn > 1 ? redefine_label : define_label;
1199 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1203 nasmlist.init(listname, nasm_error);
1206 global_offset_changed = 0; /* set by redefine_label */
1207 location.segment = ofmt->section(NULL, pass2, &sb);
1210 saa_rewind(forwrefs);
1211 forwref = saa_rstruct(forwrefs);
1213 offsets = raa_init();
1215 preproc->reset(fname, pass1, &nasmlist,
1216 pass1 == 2 ? depend_ptr : NULL);
1217 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1221 location.known = true;
1222 location.offset = offs = GET_CURR_OFFS;
1224 while ((line = preproc->getline())) {
1229 * Here we parse our directives; this is not handled by the
1230 * 'real' parser. This really should be a separate function.
1233 d = getkw(&directive, &value);
1238 case D_SEGMENT: /* [SEGMENT n] */
1240 seg = ofmt->section(value, pass2, &sb);
1241 if (seg == NO_SEG) {
1242 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1243 "segment name `%s' not recognized",
1247 location.segment = seg;
1250 case D_SECTALIGN: /* [SECTALIGN n] */
1254 tokval.t_type = TOKEN_INVALID;
1255 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, nasm_error, NULL);
1257 unsigned int align = (unsigned int)e->value;
1258 if ((uint64_t)e->value > 0x7fffffff) {
1260 * FIXME: Please make some sane message here
1261 * ofmt should have some 'check' method which
1262 * would report segment alignment bounds.
1264 nasm_error(ERR_FATAL,
1265 "incorrect segment alignment `%s'", value);
1266 } else if (!is_power2(align)) {
1267 nasm_error(ERR_NONFATAL,
1268 "segment alignment `%s' is not power of two",
1271 /* callee should be able to handle all details */
1272 ofmt->sectalign(location.segment, align);
1276 case D_EXTERN: /* [EXTERN label:special] */
1278 value++; /* skip initial $ if present */
1281 while (*q && *q != ':')
1285 ofmt->symdef(value, 0L, 0L, 3, q);
1287 } else if (passn == 1) {
1292 while (*q && *q != ':') {
1298 nasm_error(ERR_NONFATAL,
1299 "identifier expected after EXTERN");
1307 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1309 pass0 = 1; /* fake pass 1 in labels.c */
1310 declare_as_global(value, special);
1311 define_label(value, seg_alloc(), 0L, NULL,
1315 } /* else pass0 == 1 */
1317 case D_BITS: /* [BITS bits] */
1318 globalbits = sb = get_bits(value);
1320 case D_GLOBAL: /* [GLOBAL symbol:special] */
1322 value++; /* skip initial $ if present */
1323 if (pass0 == 2) { /* pass 2 */
1325 while (*q && *q != ':')
1329 ofmt->symdef(value, 0L, 0L, 3, q);
1331 } else if (pass2 == 1) { /* pass == 1 */
1336 while (*q && *q != ':') {
1342 nasm_error(ERR_NONFATAL,
1343 "identifier expected after GLOBAL");
1351 declare_as_global(value, special);
1354 case D_COMMON: /* [COMMON symbol size:special] */
1359 value++; /* skip initial $ if present */
1364 while (*p && !nasm_isspace(*p)) {
1370 nasm_error(ERR_NONFATAL,
1371 "identifier expected after COMMON");
1375 p = nasm_zap_spaces_fwd(p);
1377 while (*q && *q != ':')
1385 size = readnum(p, &rn_error);
1387 nasm_error(ERR_NONFATAL,
1388 "invalid size specified"
1389 " in COMMON declaration");
1393 nasm_error(ERR_NONFATAL,
1394 "no size specified in"
1395 " COMMON declaration");
1400 define_common(value, seg_alloc(), size, special);
1401 } else if (pass0 == 2) {
1403 ofmt->symdef(value, 0L, 0L, 3, special);
1407 case D_ABSOLUTE: /* [ABSOLUTE address] */
1410 tokval.t_type = TOKEN_INVALID;
1411 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1416 1 ? ERR_NONFATAL : ERR_PANIC,
1417 "cannot use non-relocatable expression as "
1418 "ABSOLUTE address");
1420 abs_seg = reloc_seg(e);
1421 abs_offset = reloc_value(e);
1423 } else if (passn == 1)
1424 abs_offset = 0x100; /* don't go near zero in case of / */
1426 nasm_error(ERR_PANIC, "invalid ABSOLUTE address "
1429 location.segment = NO_SEG;
1431 case D_DEBUG: /* [DEBUG] */
1434 bool badid, overlong;
1438 badid = overlong = false;
1439 if (!isidstart(*p)) {
1442 while (*p && !nasm_isspace(*p)) {
1443 if (q >= debugid + sizeof debugid - 1) {
1454 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1455 "identifier expected after DEBUG");
1459 nasm_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1460 "DEBUG identifier too long");
1463 p = nasm_skip_spaces(p);
1465 dfmt->debug_directive(debugid, p);
1468 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1469 value = nasm_skip_spaces(value);
1471 case '-': validid = 0; value++; break;
1472 case '+': validid = 1; value++; break;
1473 case '*': validid = 2; value++; break;
1474 default: validid = 1; break;
1477 for (i = 1; i <= ERR_WARN_MAX; i++)
1478 if (!nasm_stricmp(value, warnings[i].name))
1480 if (i <= ERR_WARN_MAX) {
1483 warning_on[i] = false;
1486 warning_on[i] = true;
1489 warning_on[i] = warning_on_global[i];
1494 nasm_error(ERR_NONFATAL,
1495 "invalid warning id in WARNING directive");
1497 case D_CPU: /* [CPU] */
1498 cpu = get_cpu(value);
1500 case D_LIST: /* [LIST {+|-}] */
1501 value = nasm_skip_spaces(value);
1502 if (*value == '+') {
1505 if (*value == '-') {
1512 case D_DEFAULT: /* [DEFAULT] */
1515 tokval.t_type = TOKEN_INVALID;
1516 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1517 switch ((int)tokval.t_integer) {
1533 if (float_option(value)) {
1534 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1535 "unknown 'float' directive: %s",
1540 if (ofmt->directive(d, value, pass2))
1542 /* else fall through */
1544 nasm_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1545 "unrecognised directive [%s]",
1550 nasm_error(ERR_NONFATAL,
1551 "invalid parameter to [%s] directive",
1554 } else { /* it isn't a directive */
1555 parse_line(pass1, line, &output_ins, def_label);
1557 if (optimizing > 0) {
1558 if (forwref != NULL && globallineno == forwref->lineno) {
1559 output_ins.forw_ref = true;
1561 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1562 forwref = saa_rstruct(forwrefs);
1563 } while (forwref != NULL
1564 && forwref->lineno == globallineno);
1566 output_ins.forw_ref = false;
1568 if (output_ins.forw_ref) {
1570 for (i = 0; i < output_ins.operands; i++) {
1571 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {
1572 struct forwrefinfo *fwinf =
1573 (struct forwrefinfo *)
1574 saa_wstruct(forwrefs);
1575 fwinf->lineno = globallineno;
1584 if (output_ins.opcode == I_EQU) {
1587 * Special `..' EQUs get processed in pass two,
1588 * except `..@' macro-processor EQUs which are done
1589 * in the normal place.
1591 if (!output_ins.label)
1592 nasm_error(ERR_NONFATAL,
1593 "EQU not preceded by label");
1595 else if (output_ins.label[0] != '.' ||
1596 output_ins.label[1] != '.' ||
1597 output_ins.label[2] == '@') {
1598 if (output_ins.operands == 1 &&
1599 (output_ins.oprs[0].type & IMMEDIATE) &&
1600 output_ins.oprs[0].wrt == NO_SEG) {
1601 bool isext = !!(output_ins.oprs[0].opflags
1603 def_label(output_ins.label,
1604 output_ins.oprs[0].segment,
1605 output_ins.oprs[0].offset, NULL,
1607 } else if (output_ins.operands == 2
1608 && (output_ins.oprs[0].type & IMMEDIATE)
1609 && (output_ins.oprs[0].type & COLON)
1610 && output_ins.oprs[0].segment == NO_SEG
1611 && output_ins.oprs[0].wrt == NO_SEG
1612 && (output_ins.oprs[1].type & IMMEDIATE)
1613 && output_ins.oprs[1].segment == NO_SEG
1614 && output_ins.oprs[1].wrt == NO_SEG) {
1615 def_label(output_ins.label,
1616 output_ins.oprs[0].offset | SEG_ABS,
1617 output_ins.oprs[1].offset,
1618 NULL, false, false);
1620 nasm_error(ERR_NONFATAL,
1621 "bad syntax for EQU");
1625 * Special `..' EQUs get processed here, except
1626 * `..@' macro processor EQUs which are done above.
1628 if (output_ins.label[0] == '.' &&
1629 output_ins.label[1] == '.' &&
1630 output_ins.label[2] != '@') {
1631 if (output_ins.operands == 1 &&
1632 (output_ins.oprs[0].type & IMMEDIATE)) {
1633 define_label(output_ins.label,
1634 output_ins.oprs[0].segment,
1635 output_ins.oprs[0].offset,
1636 NULL, false, false);
1637 } else if (output_ins.operands == 2
1638 && (output_ins.oprs[0].type & IMMEDIATE)
1639 && (output_ins.oprs[0].type & COLON)
1640 && output_ins.oprs[0].segment == NO_SEG
1641 && (output_ins.oprs[1].type & IMMEDIATE)
1642 && output_ins.oprs[1].segment == NO_SEG) {
1643 define_label(output_ins.label,
1644 output_ins.oprs[0].offset | SEG_ABS,
1645 output_ins.oprs[1].offset,
1646 NULL, false, false);
1648 nasm_error(ERR_NONFATAL,
1649 "bad syntax for EQU");
1652 } else { /* instruction isn't an EQU */
1656 int64_t l = insn_size(location.segment, offs, sb, cpu,
1657 &output_ins, nasm_error);
1659 /* if (using_debug_info) && output_ins.opcode != -1) */
1660 if (using_debug_info)
1661 { /* fbk 03/25/01 */
1662 /* this is done here so we can do debug type info */
1664 TYS_ELEMENTS(output_ins.operands);
1665 switch (output_ins.opcode) {
1668 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1672 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1676 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1680 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1684 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1688 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;
1692 TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;
1695 typeinfo |= TY_BYTE;
1698 typeinfo |= TY_WORD;
1701 if (output_ins.eops_float)
1702 typeinfo |= TY_FLOAT;
1704 typeinfo |= TY_DWORD;
1707 typeinfo |= TY_QWORD;
1710 typeinfo |= TY_TBYTE;
1713 typeinfo |= TY_OWORD;
1716 typeinfo |= TY_YWORD;
1719 typeinfo = TY_LABEL;
1723 dfmt->debug_typevalue(typeinfo);
1727 SET_CURR_OFFS(offs);
1730 * else l == -1 => invalid instruction, which will be
1731 * flagged as an error on pass 2
1735 offs += assemble(location.segment, offs, sb, cpu,
1736 &output_ins, ofmt, nasm_error,
1738 SET_CURR_OFFS(offs);
1742 cleanup_insn(&output_ins);
1745 location.offset = offs = GET_CURR_OFFS;
1746 } /* end while (line = preproc->getline... */
1748 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1749 nasm_error(ERR_NONFATAL,
1750 "phase error detected at end of assembly.");
1753 preproc->cleanup(1);
1755 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1757 } else if (global_offset_changed &&
1758 global_offset_changed < prev_offset_changed) {
1759 prev_offset_changed = global_offset_changed;
1765 if (terminate_after_phase)
1768 if ((stall_count > 997) || (passn >= pass_max)) {
1769 /* We get here if the labels don't converge
1770 * Example: FOO equ FOO + 1
1772 nasm_error(ERR_NONFATAL,
1773 "Can't find valid values for all labels "
1774 "after %d passes, giving up.", passn);
1775 nasm_error(ERR_NONFATAL,
1776 "Possible causes: recursive EQUs, macro abuse.");
1781 preproc->cleanup(0);
1783 if (!terminate_after_phase && opt_verbose_info) {
1784 /* -On and -Ov switches */
1785 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1789 static enum directives getkw(char **directive, char **value)
1793 buf = nasm_skip_spaces(*directive);
1795 /* it should be enclosed in [ ] */
1798 q = strchr(buf, ']');
1802 /* stip off the comments */
1803 p = strchr(buf, ';');
1805 if (p < q) /* ouch! somwhere inside */
1810 /* no brace, no trailing spaces */
1812 nasm_zap_spaces_rev(--q);
1815 p = nasm_skip_spaces(++buf);
1816 q = nasm_skip_word(p);
1818 return D_none; /* sigh... no value there */
1822 /* and value finally */
1823 p = nasm_skip_spaces(++q);
1826 return find_directive(*directive);
1830 * gnu style error reporting
1831 * This function prints an error message to error_file in the
1832 * style used by GNU. An example would be:
1833 * file.asm:50: error: blah blah blah
1834 * where file.asm is the name of the file, 50 is the line number on
1835 * which the error occurs (or is detected) and "error:" is one of
1836 * the possible optional diagnostics -- it can be "error" or "warning"
1837 * or something else. Finally the line terminates with the actual
1840 * @param severity the severity of the warning or error
1841 * @param fmt the printf style format string
1843 static void nasm_verror_gnu(int severity, const char *fmt, va_list ap)
1845 char *currentfile = NULL;
1848 if (is_suppressed_warning(severity))
1851 if (!(severity & ERR_NOFILE))
1852 src_get(&lineno, ¤tfile);
1855 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1856 nasm_free(currentfile);
1858 fputs("nasm: ", error_file);
1861 nasm_verror_common(severity, fmt, ap);
1865 * MS style error reporting
1866 * This function prints an error message to error_file in the
1867 * style used by Visual C and some other Microsoft tools. An example
1869 * file.asm(50) : error: blah blah blah
1870 * where file.asm is the name of the file, 50 is the line number on
1871 * which the error occurs (or is detected) and "error:" is one of
1872 * the possible optional diagnostics -- it can be "error" or "warning"
1873 * or something else. Finally the line terminates with the actual
1876 * @param severity the severity of the warning or error
1877 * @param fmt the printf style format string
1879 static void nasm_verror_vc(int severity, const char *fmt, va_list ap)
1881 char *currentfile = NULL;
1884 if (is_suppressed_warning(severity))
1887 if (!(severity & ERR_NOFILE))
1888 src_get(&lineno, ¤tfile);
1891 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1892 nasm_free(currentfile);
1894 fputs("nasm: ", error_file);
1897 nasm_verror_common(severity, fmt, ap);
1901 * check for supressed warning
1902 * checks for suppressed warning or pass one only warning and we're
1905 * @param severity the severity of the warning or error
1906 * @return true if we should abort error/warning printing
1908 static bool is_suppressed_warning(int severity)
1911 * See if it's a suppressed warning.
1913 return (severity & ERR_MASK) == ERR_WARNING &&
1914 (((severity & ERR_WARN_MASK) != 0 &&
1915 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1916 /* See if it's a pass-one only warning and we're not in pass one. */
1917 ((severity & ERR_PASS1) && pass0 != 1) ||
1918 ((severity & ERR_PASS2) && pass0 != 2));
1922 * common error reporting
1923 * This is the common back end of the error reporting schemes currently
1924 * implemented. It prints the nature of the warning and then the
1925 * specific error message to error_file and may or may not return. It
1926 * doesn't return if the error severity is a "panic" or "debug" type.
1928 * @param severity the severity of the warning or error
1929 * @param fmt the printf style format string
1931 static void nasm_verror_common(int severity, const char *fmt, va_list args)
1936 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1957 vsnprintf(msg, sizeof msg, fmt, args);
1959 fprintf(error_file, "%s%s\n", pfx, msg);
1962 nasmlist.error(severity, pfx, msg);
1964 if (severity & ERR_USAGE)
1967 switch (severity & ERR_MASK) {
1969 /* no further action, by definition */
1972 if (warning_on[0]) /* Treat warnings as errors */
1973 terminate_after_phase = true;
1976 terminate_after_phase = true;
1986 exit(1); /* instantly die */
1987 break; /* placate silly compilers */
1990 /* abort(); *//* halt, catch fire, and dump core */
1996 static void usage(void)
1998 fputs("type `nasm -h' for help\n", error_file);
2001 #define BUF_DELTA 512
2003 static FILE *no_pp_fp;
2004 static ListGen *no_pp_list;
2005 static int32_t no_pp_lineinc;
2007 static void no_pp_reset(char *file, int pass, ListGen * listgen,
2010 src_set_fname(nasm_strdup(file));
2013 no_pp_fp = fopen(file, "r");
2015 nasm_error(ERR_FATAL | ERR_NOFILE,
2016 "unable to open input file `%s'", file);
2017 no_pp_list = listgen;
2018 (void)pass; /* placate compilers */
2021 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2023 strcpy(sl->str, file);
2028 static char *no_pp_getline(void)
2030 char *buffer, *p, *q;
2033 bufsize = BUF_DELTA;
2034 buffer = nasm_malloc(BUF_DELTA);
2035 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2037 while (1) { /* Loop to handle %line */
2040 while (1) { /* Loop to handle long lines */
2041 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2045 if (p > buffer && p[-1] == '\n')
2047 if (p - buffer > bufsize - 10) {
2049 offset = p - buffer;
2050 bufsize += BUF_DELTA;
2051 buffer = nasm_realloc(buffer, bufsize);
2052 p = buffer + offset;
2056 if (!q && p == buffer) {
2062 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2063 * them are present at the end of the line.
2065 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2067 if (!nasm_strnicmp(buffer, "%line", 5)) {
2070 char *nm = nasm_malloc(strlen(buffer));
2071 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2072 nasm_free(src_set_fname(nm));
2082 no_pp_list->line(LIST_READ, buffer);
2087 static void no_pp_cleanup(int pass)
2089 (void)pass; /* placate GCC */
2096 static uint32_t get_cpu(char *value)
2098 if (!strcmp(value, "8086"))
2100 if (!strcmp(value, "186"))
2102 if (!strcmp(value, "286"))
2104 if (!strcmp(value, "386"))
2106 if (!strcmp(value, "486"))
2108 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2110 if (!strcmp(value, "686") ||
2111 !nasm_stricmp(value, "ppro") ||
2112 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2114 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2116 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2117 !nasm_stricmp(value, "willamette"))
2118 return IF_WILLAMETTE;
2119 if (!nasm_stricmp(value, "prescott"))
2121 if (!nasm_stricmp(value, "x64") ||
2122 !nasm_stricmp(value, "x86-64"))
2124 if (!nasm_stricmp(value, "ia64") ||
2125 !nasm_stricmp(value, "ia-64") ||
2126 !nasm_stricmp(value, "itanium") ||
2127 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2130 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2131 "unknown 'cpu' type");
2133 return IF_PLEVEL; /* the maximum level */
2136 static int get_bits(char *value)
2140 if ((i = atoi(value)) == 16)
2141 return i; /* set for a 16-bit segment */
2144 nasm_error(ERR_NONFATAL,
2145 "cannot specify 32-bit segment on processor below a 386");
2148 } else if (i == 64) {
2149 if (cpu < IF_X86_64) {
2150 nasm_error(ERR_NONFATAL,
2151 "cannot specify 64-bit segment on processor below an x86-64");
2155 nasm_error(ERR_NONFATAL,
2156 "%s output format does not support 64-bit code",
2161 nasm_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2162 "`%s' is not a valid segment size; must be 16, 32 or 64",