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 register_output_formats(void);
74 static void report_error_gnu(int severity, const char *fmt, ...);
75 static void report_error_vc(int severity, const char *fmt, ...);
76 static void report_error_common(int severity, const char *fmt,
78 static bool is_suppressed_warning(int severity);
79 static void usage(void);
80 static efunc report_error;
82 static int using_debug_info, opt_verbose_info;
83 bool tasm_compatible_mode = false;
88 time_t official_compile_time;
90 static char inname[FILENAME_MAX];
91 static char outname[FILENAME_MAX];
92 static char listname[FILENAME_MAX];
93 static char errname[FILENAME_MAX];
94 static int globallineno; /* for forward-reference tracking */
95 /* static int pass = 0; */
96 static struct ofmt *ofmt = NULL;
98 static FILE *error_file; /* Where to write error messages */
100 static FILE *ofile = NULL;
101 int optimizing = -1; /* number of optimization passes to take */
102 static int sb, cmd_sb = 16; /* by default */
103 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
104 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
105 int64_t global_offset_changed; /* referenced in labels.c */
106 int64_t prev_offset_changed;
109 static struct location location;
110 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
111 int32_t abs_seg; /* ABSOLUTE segment basis */
112 int32_t abs_offset; /* ABSOLUTE offset */
114 static struct RAA *offsets;
116 static struct SAA *forwrefs; /* keep track of forward references */
117 static const struct forwrefinfo *forwref;
119 static Preproc *preproc;
121 op_normal, /* Preprocess and assemble */
122 op_preprocess, /* Preprocess only */
123 op_depend, /* Generate dependencies */
125 static enum op_type operating_mode;
126 /* Dependency flags */
127 static bool depend_emit_phony = false;
128 static bool depend_missing_ok = false;
129 static const char *depend_target = NULL;
130 static const char *depend_file = NULL;
133 * Which of the suppressible warnings are suppressed. Entry zero
134 * isn't an actual warning, but it used for -w+error/-Werror.
137 static bool warning_on[ERR_WARN_MAX+1]; /* Current state */
138 static bool warning_on_global[ERR_WARN_MAX+1]; /* Command-line state */
140 static const struct warning {
144 } warnings[ERR_WARN_MAX+1] = {
145 {"error", "treat warnings as errors", false},
146 {"macro-params", "macro calls with wrong parameter count", true},
147 {"macro-selfref", "cyclic macro references", false},
148 {"macro-defaults", "macros with more default than optional parameters", true},
149 {"orphan-labels", "labels alone on lines without trailing `:'", true},
150 {"number-overflow", "numeric constant does not fit", true},
151 {"gnu-elf-extensions", "using 8- or 16-bit relocation in ELF32, a GNU extension", false},
152 {"float-overflow", "floating point overflow", true},
153 {"float-denorm", "floating point denormal", false},
154 {"float-underflow", "floating point underflow", false},
155 {"float-toolong", "too many digits in floating-point number", true},
156 {"user", "%warning directives", true},
160 * This is a null preprocessor which just copies lines from input
161 * to output. It's used when someone explicitly requests that NASM
162 * not preprocess their source file.
165 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
166 static char *no_pp_getline(void);
167 static void no_pp_cleanup(int);
168 static Preproc no_pp = {
175 * get/set current offset...
177 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
178 raa_read(offsets,location.segment))
179 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
180 (void)(offsets=raa_write(offsets,location.segment,(x))))
182 static bool want_usage;
183 static bool terminate_after_phase;
184 int user_nolist = 0; /* fbk 9/2/00 */
186 static void nasm_fputs(const char *line, FILE * outfile)
189 fputs(line, outfile);
195 /* Convert a struct tm to a POSIX-style time constant */
196 static int64_t posix_mktime(struct tm *tm)
199 int64_t y = tm->tm_year;
201 /* See IEEE 1003.1:2004, section 4.14 */
203 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
215 static void define_macros_early(void)
218 struct tm lt, *lt_p, gm, *gm_p;
221 lt_p = localtime(&official_compile_time);
225 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", <);
227 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", <);
229 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", <);
231 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", <);
235 gm_p = gmtime(&official_compile_time);
239 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
241 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
243 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
245 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
250 posix_time = posix_mktime(&gm);
252 posix_time = posix_mktime(<);
257 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
262 static void define_macros_late(void)
266 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
271 static void emit_dependencies(StrList *list)
277 if (depend_file && strcmp(depend_file, "-")) {
278 deps = fopen(depend_file, "w");
280 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
281 "unable to write dependency file `%s'", depend_file);
288 linepos = fprintf(deps, "%s:", depend_target);
289 for (l = list; l; l = l->next) {
290 len = strlen(l->str);
291 if (linepos + len > 62) {
292 fprintf(deps, " \\\n ");
295 fprintf(deps, " %s", l->str);
298 fprintf(deps, "\n\n");
300 for (l = list; l; l = nl) {
301 if (depend_emit_phony)
302 fprintf(deps, "%s:\n\n", l->str);
312 int main(int argc, char **argv)
314 StrList *depend_list = NULL, **depend_ptr;
316 time(&official_compile_time);
319 want_usage = terminate_after_phase = false;
320 report_error = report_error_gnu;
326 nasm_set_malloc_error(report_error);
327 offsets = raa_init();
328 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
331 operating_mode = op_normal;
335 register_output_formats();
337 /* Define some macros dependent on the runtime, but not
338 on the command line. */
339 define_macros_early();
341 parse_cmdline(argc, argv);
343 if (terminate_after_phase) {
349 /* If debugging info is disabled, suppress any debug calls */
350 if (!using_debug_info)
351 ofmt->current_dfmt = &null_debug_form;
354 pp_extra_stdmac(ofmt->stdmac);
355 parser_global_info(ofmt, &location);
356 eval_global_info(ofmt, lookup_label, &location);
358 /* define some macros dependent of command-line */
359 define_macros_late();
361 depend_ptr = (depend_file || (operating_mode == op_depend))
362 ? &depend_list : NULL;
364 depend_target = outname;
366 switch (operating_mode) {
371 if (depend_missing_ok)
372 pp_include_path(NULL); /* "assume generated" */
374 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
376 if (outname[0] == '\0')
377 ofmt->filename(inname, outname, report_error);
379 while ((line = preproc->getline()))
388 char *file_name = NULL;
389 int32_t prior_linnum = 0;
393 ofile = fopen(outname, "w");
395 report_error(ERR_FATAL | ERR_NOFILE,
396 "unable to open output file `%s'",
401 location.known = false;
404 preproc->reset(inname, 3, report_error, evaluate, &nasmlist,
407 while ((line = preproc->getline())) {
409 * We generate %line directives if needed for later programs
411 int32_t linnum = prior_linnum += lineinc;
412 int altline = src_get(&linnum, &file_name);
414 if (altline == 1 && lineinc == 1)
415 nasm_fputs("", ofile);
417 lineinc = (altline != -1 || lineinc != 1);
418 fprintf(ofile ? ofile : stdout,
419 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
422 prior_linnum = linnum;
424 nasm_fputs(line, ofile);
427 nasm_free(file_name);
431 if (ofile && terminate_after_phase)
439 * We must call ofmt->filename _anyway_, even if the user
440 * has specified their own output file, because some
441 * formats (eg OBJ and COFF) use ofmt->filename to find out
442 * the name of the input file and then put that inside the
445 ofmt->filename(inname, outname, report_error);
447 ofile = fopen(outname, (ofmt->flags & OFMT_TEXT) ? "w" : "wb");
449 report_error(ERR_FATAL | ERR_NOFILE,
450 "unable to open output file `%s'", outname);
454 * We must call init_labels() before ofmt->init() since
455 * some object formats will want to define labels in their
456 * init routines. (eg OS/2 defines the FLAT group)
460 ofmt->init(ofile, report_error, define_label, evaluate);
461 ofmt->current_dfmt->init(ofmt, NULL, ofile, report_error);
463 assemble_file(inname, depend_ptr);
465 if (!terminate_after_phase) {
466 ofmt->cleanup(using_debug_info);
470 * Despite earlier comments, we need this fclose.
471 * The object output drivers only fclose on cleanup,
472 * and we just skipped that.
484 if (depend_list && !terminate_after_phase)
485 emit_dependencies(depend_list);
495 return terminate_after_phase;
499 * Get a parameter for a command line option.
500 * First arg must be in the form of e.g. -f...
502 static char *get_param(char *p, char *q, bool *advance)
505 if (p[2]) { /* the parameter's in the option */
507 while (nasm_isspace(*p))
515 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
516 "option `-%c' requires an argument", p[1]);
523 static void copy_filename(char *dst, const char *src)
525 size_t len = strlen(src);
527 if (len >= (size_t)FILENAME_MAX) {
528 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
531 strncpy(dst, src, FILENAME_MAX);
535 * Convert a string to Make-safe form
537 static char *quote_for_make(const char *str)
542 size_t n = 1; /* Terminating zero */
548 for (p = str; *p; p++) {
552 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
572 /* Convert N backslashes at the end of filename to 2N backslashes */
576 os = q = nasm_malloc(n);
579 for (p = str; *p; p++) {
622 #define OPT_POSTFIX 1
623 struct textargs textopts[] = {
624 {"prefix", OPT_PREFIX},
625 {"postfix", OPT_POSTFIX},
629 static bool stopoptions = false;
630 static bool process_arg(char *p, char *q)
634 bool advance = false;
640 if (p[0] == '-' && !stopoptions) {
641 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
642 /* These parameters take values */
643 if (!(param = get_param(p, q, &advance)))
652 case 'o': /* output file */
653 copy_filename(outname, param);
656 case 'f': /* output format */
657 ofmt = ofmt_find(param);
659 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
660 "unrecognised output format `%s' - "
661 "use -hf for a list", param);
665 case 'O': /* Optimization level */
670 /* Naked -O == -Ox */
671 optimizing = INT_MAX >> 1; /* Almost unlimited */
675 case '0': case '1': case '2': case '3': case '4':
676 case '5': case '6': case '7': case '8': case '9':
677 opt = strtoul(param, ¶m, 10);
679 /* -O0 -> optimizing == -1, 0.98 behaviour */
680 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
682 optimizing = opt - 1;
690 opt_verbose_info = true;
695 optimizing = INT_MAX >> 1; /* Almost unlimited */
699 report_error(ERR_FATAL,
700 "unknown optimization option -O%c\n",
709 case 'p': /* pre-include */
711 pp_pre_include(param);
714 case 'd': /* pre-define */
716 pp_pre_define(param);
719 case 'u': /* un-define */
721 pp_pre_undefine(param);
724 case 'i': /* include search path */
726 pp_include_path(param);
729 case 'l': /* listing file */
730 copy_filename(listname, param);
733 case 'Z': /* error messages file */
734 strcpy(errname, param);
737 case 'F': /* specify debug format */
738 ofmt->current_dfmt = dfmt_find(ofmt, param);
739 if (!ofmt->current_dfmt) {
740 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
741 "unrecognized debug format `%s' for"
742 " output format `%s'",
743 param, ofmt->shortname);
745 using_debug_info = true;
748 case 'X': /* specify error reporting format */
749 if (nasm_stricmp("vc", param) == 0)
750 report_error = report_error_vc;
751 else if (nasm_stricmp("gnu", param) == 0)
752 report_error = report_error_gnu;
754 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
755 "unrecognized error reporting format `%s'",
760 using_debug_info = true;
765 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
767 " [options...] [--] filename\n"
768 " or nasm -v for version info\n\n"
769 " -t assemble in SciTech TASM compatible mode\n"
770 " -g generate debug information in selected format.\n");
772 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
773 " -a don't preprocess (assemble only)\n"
774 " -M generate Makefile dependencies on stdout\n"
775 " -MG d:o, missing files assumed generated\n\n"
776 " -Z<file> redirect error messages to file\n"
777 " -s redirect error messages to stdout\n\n"
778 " -F format select a debugging format\n\n"
779 " -I<path> adds a pathname to the include file path\n");
781 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
782 " -P<file> pre-includes a file\n"
783 " -D<macro>[=<value>] pre-defines a macro\n"
784 " -U<macro> undefines a macro\n"
785 " -X<format> specifies error reporting format (gnu or vc)\n"
786 " -w+foo enables warning foo (equiv. -Wfoo)\n"
787 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
789 for (i = 0; i <= ERR_WARN_MAX; i++)
790 printf(" %-23s %s (default %s)\n",
791 warnings[i].name, warnings[i].help,
792 warnings[i].enabled ? "on" : "off");
794 ("\nresponse files should contain command line parameters"
795 ", one per line.\n");
797 printf("\nvalid output formats for -f are"
798 " (`*' denotes default):\n");
799 ofmt_list(ofmt, stdout);
801 printf("\nFor a list of valid output formats, use -hf.\n");
802 printf("For a list of debug formats, use -f <form> -y.\n");
804 exit(0); /* never need usage message here */
808 printf("\nvalid debug formats for '%s' output format are"
809 " ('*' denotes default):\n", ofmt->shortname);
810 dfmt_list(ofmt, stdout);
815 tasm_compatible_mode = true;
819 printf("NASM version %s compiled on %s%s\n",
820 nasm_version, nasm_date, nasm_compile_options);
821 exit(0); /* never need usage message here */
824 case 'e': /* preprocess only */
826 operating_mode = op_preprocess;
829 case 'a': /* assemble only - don't preprocess */
834 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
843 if (param[0] != '+' && param[0] != '-') {
844 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
845 "invalid option to `-w'");
848 do_warn = (param[0] == '+');
852 for (i = 0; i <= ERR_WARN_MAX; i++)
853 if (!nasm_stricmp(param, warnings[i].name))
855 if (i <= ERR_WARN_MAX)
856 warning_on_global[i] = do_warn;
857 else if (!nasm_stricmp(param, "all"))
858 for (i = 1; i <= ERR_WARN_MAX; i++)
859 warning_on_global[i] = do_warn;
860 else if (!nasm_stricmp(param, "none"))
861 for (i = 1; i <= ERR_WARN_MAX; i++)
862 warning_on_global[i] = !do_warn;
864 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
865 "invalid warning `%s'", param);
871 operating_mode = op_depend;
874 operating_mode = op_depend;
875 depend_missing_ok = true;
878 depend_emit_phony = true;
889 depend_target = quote_for_make(q);
893 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
894 "unknown dependency option `-M%c'", p[2]);
897 if (advance && (!q || !q[0])) {
898 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
899 "option `-M%c' requires a parameter", p[2]);
908 if (p[2] == 0) { /* -- => stop processing options */
912 for (s = 0; textopts[s].label; s++) {
913 if (!nasm_stricmp(p + 2, textopts[s].label)) {
924 report_error(ERR_NONFATAL | ERR_NOFILE |
926 "option `--%s' requires an argument",
930 advance = 1, param = q;
933 if (s == OPT_PREFIX) {
934 strncpy(lprefix, param, PREFIX_MAX - 1);
935 lprefix[PREFIX_MAX - 1] = 0;
938 if (s == OPT_POSTFIX) {
939 strncpy(lpostfix, param, POSTFIX_MAX - 1);
940 lpostfix[POSTFIX_MAX - 1] = 0;
947 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
948 "unrecognised option `--%s'", p + 2);
956 if (!ofmt->setinfo(GI_SWITCH, &p))
957 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
958 "unrecognised option `-%c'", p[1]);
963 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
964 "more than one input file specified");
966 copy_filename(inname, p);
973 #define ARG_BUF_DELTA 128
975 static void process_respfile(FILE * rfile)
977 char *buffer, *p, *q, *prevarg;
978 int bufsize, prevargsize;
980 bufsize = prevargsize = ARG_BUF_DELTA;
981 buffer = nasm_malloc(ARG_BUF_DELTA);
982 prevarg = nasm_malloc(ARG_BUF_DELTA);
985 while (1) { /* Loop to handle all lines in file */
987 while (1) { /* Loop to handle long lines */
988 q = fgets(p, bufsize - (p - buffer), rfile);
992 if (p > buffer && p[-1] == '\n')
994 if (p - buffer > bufsize - 10) {
997 bufsize += ARG_BUF_DELTA;
998 buffer = nasm_realloc(buffer, bufsize);
1003 if (!q && p == buffer) {
1005 process_arg(prevarg, NULL);
1012 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1013 * them are present at the end of the line.
1015 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1017 while (p > buffer && nasm_isspace(p[-1]))
1021 while (nasm_isspace(*p))
1024 if (process_arg(prevarg, p))
1027 if ((int) strlen(p) > prevargsize - 10) {
1028 prevargsize += ARG_BUF_DELTA;
1029 prevarg = nasm_realloc(prevarg, prevargsize);
1031 strncpy(prevarg, p, prevargsize);
1035 /* Function to process args from a string of args, rather than the
1036 * argv array. Used by the environment variable and response file
1039 static void process_args(char *args)
1041 char *p, *q, *arg, *prevarg;
1042 char separator = ' ';
1045 if (*p && *p != '-')
1050 while (*p && *p != separator)
1052 while (*p == separator)
1056 if (process_arg(prevarg, arg))
1060 process_arg(arg, NULL);
1063 static void process_response_file(const char *file)
1066 FILE *f = fopen(file, "r");
1071 while (fgets(str, sizeof str, f)) {
1077 static void parse_cmdline(int argc, char **argv)
1080 char *envreal, *envcopy = NULL, *p, *arg;
1083 *inname = *outname = *listname = *errname = '\0';
1084 for (i = 0; i <= ERR_WARN_MAX; i++)
1085 warning_on_global[i] = warnings[i].enabled;
1088 * First, process the NASMENV environment variable.
1090 envreal = getenv("NASMENV");
1093 envcopy = nasm_strdup(envreal);
1094 process_args(envcopy);
1099 * Now process the actual command line.
1104 if (argv[0][0] == '@') {
1105 /* We have a response file, so process this as a set of
1106 * arguments like the environment variable. This allows us
1107 * to have multiple arguments on a single line, which is
1108 * different to the -@resp file processing below for regular
1111 process_response_file(argv[0]+1);
1115 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1116 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1118 rfile = fopen(p, "r");
1120 process_respfile(rfile);
1123 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1124 "unable to open response file `%s'", p);
1127 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1128 argv += advance, argc -= advance;
1131 /* Look for basic command line typos. This definitely doesn't
1132 catch all errors, but it might help cases of fumbled fingers. */
1134 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1135 "no input file specified");
1136 else if (!strcmp(inname, errname) ||
1137 !strcmp(inname, outname) ||
1138 !strcmp(inname, listname) ||
1139 (depend_file && !strcmp(inname, depend_file)))
1140 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1141 "file `%s' is both input and output file",
1145 error_file = fopen(errname, "w");
1147 error_file = stderr; /* Revert to default! */
1148 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1149 "cannot open file `%s' for error messages",
1155 /* List of directives */
1157 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1158 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1160 static const char *directives[] = {
1161 "", "absolute", "bits", "common", "cpu", "debug", "default",
1162 "extern", "float", "global", "list", "section", "segment", "warning"
1164 static enum directives getkw(char **directive, char **value);
1166 static void assemble_file(char *fname, StrList **depend_ptr)
1168 char *directive, *value, *p, *q, *special, *line, debugid[80];
1174 struct tokenval tokval;
1178 if (cmd_sb == 32 && cmd_cpu < IF_386)
1179 report_error(ERR_FATAL, "command line: "
1180 "32-bit segment size requires a higher cpu");
1182 pass_max = prev_offset_changed = (INT_MAX >> 1) + 2; /* Almost unlimited */
1183 for (passn = 1; pass0 <= 2; passn++) {
1187 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1188 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1189 /* pass0 0, 0, 0, ..., 1, 2 */
1191 def_label = passn > 1 ? redefine_label : define_label;
1193 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1197 nasmlist.init(listname, report_error);
1200 global_offset_changed = 0; /* set by redefine_label */
1201 location.segment = ofmt->section(NULL, pass2, &sb);
1204 saa_rewind(forwrefs);
1205 forwref = saa_rstruct(forwrefs);
1207 offsets = raa_init();
1209 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1210 pass1 == 2 ? depend_ptr : NULL);
1211 memcpy(warning_on, warning_on_global, (ERR_WARN_MAX+1) * sizeof(bool));
1215 location.known = true;
1216 location.offset = offs = GET_CURR_OFFS;
1218 while ((line = preproc->getline())) {
1223 * Here we parse our directives; this is not handled by the
1224 * 'real' parser. This really should be a separate function.
1227 d = getkw(&directive, &value);
1232 case D_SEGMENT: /* [SEGMENT n] */
1234 seg = ofmt->section(value, pass2, &sb);
1235 if (seg == NO_SEG) {
1236 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1237 "segment name `%s' not recognized",
1241 location.segment = seg;
1244 case D_EXTERN: /* [EXTERN label:special] */
1246 value++; /* skip initial $ if present */
1249 while (*q && *q != ':')
1253 ofmt->symdef(value, 0L, 0L, 3, q);
1255 } else if (passn == 1) {
1260 while (*q && *q != ':') {
1266 report_error(ERR_NONFATAL,
1267 "identifier expected after EXTERN");
1275 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1277 pass0 = 1; /* fake pass 1 in labels.c */
1278 declare_as_global(value, special,
1280 define_label(value, seg_alloc(), 0L, NULL,
1281 false, true, ofmt, report_error);
1284 } /* else pass0 == 1 */
1286 case D_BITS: /* [BITS bits] */
1287 globalbits = sb = get_bits(value);
1289 case D_GLOBAL: /* [GLOBAL symbol:special] */
1291 value++; /* skip initial $ if present */
1292 if (pass0 == 2) { /* pass 2 */
1294 while (*q && *q != ':')
1298 ofmt->symdef(value, 0L, 0L, 3, q);
1300 } else if (pass2 == 1) { /* pass == 1 */
1305 while (*q && *q != ':') {
1311 report_error(ERR_NONFATAL,
1312 "identifier expected after GLOBAL");
1320 declare_as_global(value, special, report_error);
1323 case D_COMMON: /* [COMMON symbol size:special] */
1328 value++; /* skip initial $ if present */
1333 while (*p && !nasm_isspace(*p)) {
1339 report_error(ERR_NONFATAL,
1340 "identifier expected after COMMON");
1344 while (*p && nasm_isspace(*p))
1347 while (*q && *q != ':')
1355 size = readnum(p, &rn_error);
1357 report_error(ERR_NONFATAL,
1358 "invalid size specified"
1359 " in COMMON declaration");
1363 report_error(ERR_NONFATAL,
1364 "no size specified in"
1365 " COMMON declaration");
1370 define_common(value, seg_alloc(), size,
1371 special, ofmt, report_error);
1372 } else if (pass0 == 2) {
1373 ofmt->symdef(value, 0L, 0L, 3, special);
1377 case D_ABSOLUTE: /* [ABSOLUTE address] */
1379 stdscan_bufptr = value;
1380 tokval.t_type = TOKEN_INVALID;
1381 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1382 report_error, NULL);
1385 report_error(pass0 ==
1386 1 ? ERR_NONFATAL : ERR_PANIC,
1387 "cannot use non-relocatable expression as "
1388 "ABSOLUTE address");
1390 abs_seg = reloc_seg(e);
1391 abs_offset = reloc_value(e);
1393 } else if (passn == 1)
1394 abs_offset = 0x100; /* don't go near zero in case of / */
1396 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1399 location.segment = NO_SEG;
1401 case D_DEBUG: /* [DEBUG] */
1407 while (*p && !nasm_isspace(*p)) {
1414 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1415 "identifier expected after DEBUG");
1418 while (*p && nasm_isspace(*p))
1421 ofmt->current_dfmt->debug_directive(debugid, p);
1423 case D_WARNING: /* [WARNING {+|-|*}warn-name] */
1424 while (*value && nasm_isspace(*value))
1428 case '-': validid = 0; value++; break;
1429 case '+': validid = 1; value++; break;
1430 case '*': validid = 2; value++; break;
1431 default: validid = 1; break;
1434 for (i = 1; i <= ERR_WARN_MAX; i++)
1435 if (!nasm_stricmp(value, warnings[i].name))
1437 if (i <= ERR_WARN_MAX) {
1440 warning_on[i] = false;
1443 warning_on[i] = true;
1446 warning_on[i] = warning_on_global[i];
1451 report_error(ERR_NONFATAL,
1452 "invalid warning id in WARNING directive");
1454 case D_CPU: /* [CPU] */
1455 cpu = get_cpu(value);
1457 case D_LIST: /* [LIST {+|-}] */
1458 while (*value && nasm_isspace(*value))
1461 if (*value == '+') {
1464 if (*value == '-') {
1471 case D_DEFAULT: /* [DEFAULT] */
1473 stdscan_bufptr = value;
1474 tokval.t_type = TOKEN_INVALID;
1475 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1476 switch ((int)tokval.t_integer) {
1492 if (float_option(value)) {
1493 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1494 "unknown 'float' directive: %s",
1499 if (!ofmt->directive(directive, value, pass2))
1500 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1501 "unrecognised directive [%s]",
1505 report_error(ERR_NONFATAL,
1506 "invalid parameter to [%s] directive",
1509 } else { /* it isn't a directive */
1511 parse_line(pass1, line, &output_ins,
1512 report_error, evaluate, def_label);
1514 if (optimizing > 0) {
1515 if (forwref != NULL && globallineno == forwref->lineno) {
1516 output_ins.forw_ref = true;
1518 output_ins.oprs[forwref->operand].opflags |=
1520 forwref = saa_rstruct(forwrefs);
1521 } while (forwref != NULL
1522 && forwref->lineno == globallineno);
1524 output_ins.forw_ref = false;
1526 if (output_ins.forw_ref) {
1528 for (i = 0; i < output_ins.operands; i++) {
1529 if (output_ins.oprs[i].
1530 opflags & OPFLAG_FORWARD) {
1531 struct forwrefinfo *fwinf =
1532 (struct forwrefinfo *)
1533 saa_wstruct(forwrefs);
1534 fwinf->lineno = globallineno;
1543 if (output_ins.opcode == I_EQU) {
1546 * Special `..' EQUs get processed in pass two,
1547 * except `..@' macro-processor EQUs which are done
1548 * in the normal place.
1550 if (!output_ins.label)
1551 report_error(ERR_NONFATAL,
1552 "EQU not preceded by label");
1554 else if (output_ins.label[0] != '.' ||
1555 output_ins.label[1] != '.' ||
1556 output_ins.label[2] == '@') {
1557 if (output_ins.operands == 1 &&
1558 (output_ins.oprs[0].type & IMMEDIATE) &&
1559 output_ins.oprs[0].wrt == NO_SEG) {
1560 bool isext = !!(output_ins.oprs[0].opflags
1562 def_label(output_ins.label,
1563 output_ins.oprs[0].segment,
1564 output_ins.oprs[0].offset, NULL,
1567 } else if (output_ins.operands == 2
1568 && (output_ins.oprs[0].type & IMMEDIATE)
1569 && (output_ins.oprs[0].type & COLON)
1570 && output_ins.oprs[0].segment == NO_SEG
1571 && output_ins.oprs[0].wrt == NO_SEG
1572 && (output_ins.oprs[1].type & IMMEDIATE)
1573 && output_ins.oprs[1].segment == NO_SEG
1574 && output_ins.oprs[1].wrt == NO_SEG) {
1575 def_label(output_ins.label,
1576 output_ins.oprs[0].offset | SEG_ABS,
1577 output_ins.oprs[1].offset,
1578 NULL, false, false, ofmt,
1581 report_error(ERR_NONFATAL,
1582 "bad syntax for EQU");
1586 * Special `..' EQUs get processed here, except
1587 * `..@' macro processor EQUs which are done above.
1589 if (output_ins.label[0] == '.' &&
1590 output_ins.label[1] == '.' &&
1591 output_ins.label[2] != '@') {
1592 if (output_ins.operands == 1 &&
1593 (output_ins.oprs[0].type & IMMEDIATE)) {
1594 define_label(output_ins.label,
1595 output_ins.oprs[0].segment,
1596 output_ins.oprs[0].offset,
1597 NULL, false, false, ofmt,
1599 } else if (output_ins.operands == 2
1600 && (output_ins.oprs[0].
1602 && (output_ins.oprs[0].type & COLON)
1603 && output_ins.oprs[0].segment ==
1605 && (output_ins.oprs[1].
1607 && output_ins.oprs[1].segment ==
1609 define_label(output_ins.label,
1612 output_ins.oprs[1].offset,
1613 NULL, false, false, ofmt,
1616 report_error(ERR_NONFATAL,
1617 "bad syntax for EQU");
1620 } else { /* instruction isn't an EQU */
1624 int64_t l = insn_size(location.segment, offs, sb, cpu,
1625 &output_ins, report_error);
1627 /* if (using_debug_info) && output_ins.opcode != -1) */
1628 if (using_debug_info)
1629 { /* fbk 03/25/01 */
1630 /* this is done here so we can do debug type info */
1632 TYS_ELEMENTS(output_ins.operands);
1633 switch (output_ins.opcode) {
1636 TYS_ELEMENTS(output_ins.oprs[0].
1641 TYS_ELEMENTS(output_ins.oprs[0].
1646 TYS_ELEMENTS(output_ins.oprs[0].
1651 TYS_ELEMENTS(output_ins.oprs[0].
1656 TYS_ELEMENTS(output_ins.oprs[0].
1661 TYS_ELEMENTS(output_ins.oprs[0].
1666 TYS_ELEMENTS(output_ins.oprs[0].
1670 typeinfo |= TY_BYTE;
1673 typeinfo |= TY_WORD;
1676 if (output_ins.eops_float)
1677 typeinfo |= TY_FLOAT;
1679 typeinfo |= TY_DWORD;
1682 typeinfo |= TY_QWORD;
1685 typeinfo |= TY_TBYTE;
1688 typeinfo |= TY_OWORD;
1691 typeinfo |= TY_YWORD;
1694 typeinfo = TY_LABEL;
1698 ofmt->current_dfmt->debug_typevalue(typeinfo);
1703 SET_CURR_OFFS(offs);
1706 * else l == -1 => invalid instruction, which will be
1707 * flagged as an error on pass 2
1711 offs += assemble(location.segment, offs, sb, cpu,
1712 &output_ins, ofmt, report_error,
1714 SET_CURR_OFFS(offs);
1718 cleanup_insn(&output_ins);
1721 location.offset = offs = GET_CURR_OFFS;
1722 } /* end while (line = preproc->getline... */
1724 if (pass0 == 2 && global_offset_changed && !terminate_after_phase)
1725 report_error(ERR_NONFATAL,
1726 "phase error detected at end of assembly.");
1729 preproc->cleanup(1);
1731 if ((passn > 1 && !global_offset_changed) || pass0 == 2) {
1733 } else if (global_offset_changed &&
1734 global_offset_changed < prev_offset_changed) {
1735 prev_offset_changed = global_offset_changed;
1741 if (terminate_after_phase)
1744 if ((stall_count > 997) || (passn >= pass_max)) {
1745 /* We get here if the labels don't converge
1746 * Example: FOO equ FOO + 1
1748 report_error(ERR_NONFATAL,
1749 "Can't find valid values for all labels "
1750 "after %d passes, giving up.", passn);
1751 report_error(ERR_NONFATAL,
1752 "Possible causes: recursive EQUs, macro abuse.");
1757 preproc->cleanup(0);
1759 if (!terminate_after_phase && opt_verbose_info) {
1760 /* -On and -Ov switches */
1761 fprintf(stdout, "info: assembly required 1+%d+1 passes\n", passn-3);
1765 static enum directives getkw(char **directive, char **value)
1771 /* allow leading spaces or tabs */
1772 while (*buf == ' ' || *buf == '\t')
1780 while (*p && *p != ']')
1788 while (*p && *p != ';') {
1789 if (!nasm_isspace(*p))
1795 *directive = p = buf + 1;
1796 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1803 while (nasm_isspace(*buf))
1804 buf++; /* beppu - skip leading whitespace */
1811 return bsii(*directive, directives, elements(directives));
1815 * gnu style error reporting
1816 * This function prints an error message to error_file in the
1817 * style used by GNU. An example would be:
1818 * file.asm:50: error: blah blah blah
1819 * where file.asm is the name of the file, 50 is the line number on
1820 * which the error occurs (or is detected) and "error:" is one of
1821 * the possible optional diagnostics -- it can be "error" or "warning"
1822 * or something else. Finally the line terminates with the actual
1825 * @param severity the severity of the warning or error
1826 * @param fmt the printf style format string
1828 static void report_error_gnu(int severity, const char *fmt, ...)
1831 char *currentfile = NULL;
1834 if (is_suppressed_warning(severity))
1837 if (!(severity & ERR_NOFILE))
1838 src_get(&lineno, ¤tfile);
1841 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1842 nasm_free(currentfile);
1844 fputs("nasm: ", error_file);
1848 report_error_common(severity, fmt, ap);
1853 * MS style error reporting
1854 * This function prints an error message to error_file in the
1855 * style used by Visual C and some other Microsoft tools. An example
1857 * file.asm(50) : error: blah blah blah
1858 * where file.asm is the name of the file, 50 is the line number on
1859 * which the error occurs (or is detected) and "error:" is one of
1860 * the possible optional diagnostics -- it can be "error" or "warning"
1861 * or something else. Finally the line terminates with the actual
1864 * @param severity the severity of the warning or error
1865 * @param fmt the printf style format string
1867 static void report_error_vc(int severity, const char *fmt, ...)
1870 char *currentfile = NULL;
1873 if (is_suppressed_warning(severity))
1876 if (!(severity & ERR_NOFILE))
1877 src_get(&lineno, ¤tfile);
1880 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1881 nasm_free(currentfile);
1883 fputs("nasm: ", error_file);
1887 report_error_common(severity, fmt, ap);
1892 * check for supressed warning
1893 * checks for suppressed warning or pass one only warning and we're
1896 * @param severity the severity of the warning or error
1897 * @return true if we should abort error/warning printing
1899 static bool is_suppressed_warning(int severity)
1902 * See if it's a suppressed warning.
1904 return (severity & ERR_MASK) == ERR_WARNING &&
1905 (((severity & ERR_WARN_MASK) != 0 &&
1906 !warning_on[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1907 /* See if it's a pass-one only warning and we're not in pass one. */
1908 ((severity & ERR_PASS1) && pass0 != 1) ||
1909 ((severity & ERR_PASS2) && pass0 != 2));
1913 * common error reporting
1914 * This is the common back end of the error reporting schemes currently
1915 * implemented. It prints the nature of the warning and then the
1916 * specific error message to error_file and may or may not return. It
1917 * doesn't return if the error severity is a "panic" or "debug" type.
1919 * @param severity the severity of the warning or error
1920 * @param fmt the printf style format string
1922 static void report_error_common(int severity, const char *fmt,
1925 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1927 fputs("warning: ", error_file);
1930 fputs("error: ", error_file);
1933 fputs("fatal: ", error_file);
1936 fputs("panic: ", error_file);
1939 fputs("debug: ", error_file);
1945 vfprintf(error_file, fmt, args);
1946 putc('\n', error_file);
1948 if (severity & ERR_USAGE)
1951 switch (severity & ERR_MASK) {
1953 /* no further action, by definition */
1956 if (warning_on[0]) /* Treat warnings as errors */
1957 terminate_after_phase = true;
1960 terminate_after_phase = true;
1969 exit(1); /* instantly die */
1970 break; /* placate silly compilers */
1973 /* abort(); *//* halt, catch fire, and dump core */
1979 static void usage(void)
1981 fputs("type `nasm -h' for help\n", error_file);
1984 static void register_output_formats(void)
1986 ofmt = ofmt_register(report_error);
1989 #define BUF_DELTA 512
1991 static FILE *no_pp_fp;
1992 static efunc no_pp_err;
1993 static ListGen *no_pp_list;
1994 static int32_t no_pp_lineinc;
1996 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1997 ListGen * listgen, StrList **deplist)
1999 src_set_fname(nasm_strdup(file));
2003 no_pp_fp = fopen(file, "r");
2005 no_pp_err(ERR_FATAL | ERR_NOFILE,
2006 "unable to open input file `%s'", file);
2007 no_pp_list = listgen;
2008 (void)pass; /* placate compilers */
2009 (void)eval; /* placate compilers */
2012 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2014 strcpy(sl->str, file);
2019 static char *no_pp_getline(void)
2021 char *buffer, *p, *q;
2024 bufsize = BUF_DELTA;
2025 buffer = nasm_malloc(BUF_DELTA);
2026 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2028 while (1) { /* Loop to handle %line */
2031 while (1) { /* Loop to handle long lines */
2032 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2036 if (p > buffer && p[-1] == '\n')
2038 if (p - buffer > bufsize - 10) {
2040 offset = p - buffer;
2041 bufsize += BUF_DELTA;
2042 buffer = nasm_realloc(buffer, bufsize);
2043 p = buffer + offset;
2047 if (!q && p == buffer) {
2053 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2054 * them are present at the end of the line.
2056 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2058 if (!nasm_strnicmp(buffer, "%line", 5)) {
2061 char *nm = nasm_malloc(strlen(buffer));
2062 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2063 nasm_free(src_set_fname(nm));
2073 no_pp_list->line(LIST_READ, buffer);
2078 static void no_pp_cleanup(int pass)
2080 (void)pass; /* placate GCC */
2084 static uint32_t get_cpu(char *value)
2086 if (!strcmp(value, "8086"))
2088 if (!strcmp(value, "186"))
2090 if (!strcmp(value, "286"))
2092 if (!strcmp(value, "386"))
2094 if (!strcmp(value, "486"))
2096 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2098 if (!strcmp(value, "686") ||
2099 !nasm_stricmp(value, "ppro") ||
2100 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2102 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2104 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2105 !nasm_stricmp(value, "willamette"))
2106 return IF_WILLAMETTE;
2107 if (!nasm_stricmp(value, "prescott"))
2109 if (!nasm_stricmp(value, "x64") ||
2110 !nasm_stricmp(value, "x86-64"))
2112 if (!nasm_stricmp(value, "ia64") ||
2113 !nasm_stricmp(value, "ia-64") ||
2114 !nasm_stricmp(value, "itanium") ||
2115 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2118 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2119 "unknown 'cpu' type");
2121 return IF_PLEVEL; /* the maximum level */
2124 static int get_bits(char *value)
2128 if ((i = atoi(value)) == 16)
2129 return i; /* set for a 16-bit segment */
2132 report_error(ERR_NONFATAL,
2133 "cannot specify 32-bit segment on processor below a 386");
2136 } else if (i == 64) {
2137 if (cpu < IF_X86_64) {
2138 report_error(ERR_NONFATAL,
2139 "cannot specify 64-bit segment on processor below an x86-64");
2143 report_error(ERR_NONFATAL,
2144 "%s output format does not support 64-bit code",
2149 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2150 "`%s' is not a valid segment size; must be 16, 32 or 64",