1 /* The Netwide Assembler main program module
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the license given in the file "LICENSE"
6 * distributed in the NASM archive.
35 struct forwrefinfo { /* info held on forward refs. */
40 static int get_bits(char *value);
41 static uint32_t get_cpu(char *cpu_str);
42 static void parse_cmdline(int, char **);
43 static void assemble_file(char *, StrList **);
44 static void register_output_formats(void);
45 static void report_error_gnu(int severity, const char *fmt, ...);
46 static void report_error_vc(int severity, const char *fmt, ...);
47 static void report_error_common(int severity, const char *fmt,
49 static bool is_suppressed_warning(int severity);
50 static void usage(void);
51 static efunc report_error;
53 static int using_debug_info, opt_verbose_info;
54 bool tasm_compatible_mode = false;
59 time_t official_compile_time;
61 static char inname[FILENAME_MAX];
62 static char outname[FILENAME_MAX];
63 static char listname[FILENAME_MAX];
64 static char errname[FILENAME_MAX];
65 static int globallineno; /* for forward-reference tracking */
66 /* static int pass = 0; */
67 static struct ofmt *ofmt = NULL;
69 static FILE *error_file; /* Where to write error messages */
71 static FILE *ofile = NULL;
72 int optimizing = -1; /* number of optimization passes to take */
73 static int sb, cmd_sb = 16; /* by default */
74 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
75 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
76 bool global_offset_changed; /* referenced in labels.c */
78 static struct location location;
79 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
80 int32_t abs_seg; /* ABSOLUTE segment basis */
81 int32_t abs_offset; /* ABSOLUTE offset */
83 static struct RAA *offsets;
85 static struct SAA *forwrefs; /* keep track of forward references */
86 static const struct forwrefinfo *forwref;
88 static Preproc *preproc;
90 op_normal, /* Preprocess and assemble */
91 op_preprocess, /* Preprocess only */
92 op_depend, /* Generate dependencies */
94 static enum op_type operating_mode;
95 /* Dependency flags */
96 static bool depend_emit_phony = false;
97 static bool depend_missing_ok = false;
98 static const char *depend_target = NULL;
99 static const char *depend_file = NULL;
102 * Which of the suppressible warnings are suppressed. Entry zero
103 * isn't an actual warning, but it used for -w+error/-Werror.
105 static bool suppressed[ERR_WARN_MAX+1] = {
106 true, false, true, false, false, true, false, true, true, false
110 * The option names for the suppressible warnings. As before, entry
113 static const char *suppressed_names[ERR_WARN_MAX+1] = {
114 "error", "macro-params", "macro-selfref", "orphan-labels",
115 "number-overflow", "gnu-elf-extensions", "float-overflow",
116 "float-denorm", "float-underflow", "float-toolong"
120 * The explanations for the suppressible warnings. As before, entry
123 static const char *suppressed_what[ERR_WARN_MAX+1] = {
124 "treat warnings as errors",
125 "macro calls with wrong parameter count",
126 "cyclic macro references",
127 "labels alone on lines without trailing `:'",
128 "numeric constants does not fit in 64 bits",
129 "using 8- or 16-bit relocation in ELF32, a GNU extension",
130 "floating point overflow",
131 "floating point denormal",
132 "floating point underflow",
133 "too many digits in floating-point number"
137 * This is a null preprocessor which just copies lines from input
138 * to output. It's used when someone explicitly requests that NASM
139 * not preprocess their source file.
142 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *, StrList **);
143 static char *no_pp_getline(void);
144 static void no_pp_cleanup(int);
145 static Preproc no_pp = {
152 * get/set current offset...
154 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
155 raa_read(offsets,location.segment))
156 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
157 (void)(offsets=raa_write(offsets,location.segment,(x))))
159 static int want_usage;
160 static int terminate_after_phase;
161 int user_nolist = 0; /* fbk 9/2/00 */
163 static void nasm_fputs(const char *line, FILE * outfile)
166 fputs(line, outfile);
172 /* Convert a struct tm to a POSIX-style time constant */
173 static int64_t posix_mktime(struct tm *tm)
176 int64_t y = tm->tm_year;
178 /* See IEEE 1003.1:2004, section 4.14 */
180 t = (y-70)*365 + (y-69)/4 - (y-1)/100 + (y+299)/400;
192 static void define_macros_early(void)
195 struct tm lt, *lt_p, gm, *gm_p;
198 lt_p = localtime(&official_compile_time);
202 strftime(temp, sizeof temp, "__DATE__=\"%Y-%m-%d\"", <);
204 strftime(temp, sizeof temp, "__DATE_NUM__=%Y%m%d", <);
206 strftime(temp, sizeof temp, "__TIME__=\"%H:%M:%S\"", <);
208 strftime(temp, sizeof temp, "__TIME_NUM__=%H%M%S", <);
212 gm_p = gmtime(&official_compile_time);
216 strftime(temp, sizeof temp, "__UTC_DATE__=\"%Y-%m-%d\"", &gm);
218 strftime(temp, sizeof temp, "__UTC_DATE_NUM__=%Y%m%d", &gm);
220 strftime(temp, sizeof temp, "__UTC_TIME__=\"%H:%M:%S\"", &gm);
222 strftime(temp, sizeof temp, "__UTC_TIME_NUM__=%H%M%S", &gm);
227 posix_time = posix_mktime(&gm);
229 posix_time = posix_mktime(<);
234 snprintf(temp, sizeof temp, "__POSIX_TIME__=%"PRId64, posix_time);
239 static void define_macros_late(void)
243 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
248 static void emit_dependencies(StrList *list)
254 if (depend_file && strcmp(depend_file, "-")) {
255 deps = fopen(depend_file, "w");
257 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
258 "unable to write dependency file `%s'", depend_file);
265 linepos = fprintf(deps, "%s:", depend_target);
266 for (l = list; l; l = l->next) {
267 len = strlen(l->str);
268 if (linepos + len > 62) {
269 fprintf(deps, " \\\n ");
272 fprintf(deps, " %s", l->str);
275 fprintf(deps, "\n\n");
277 for (l = list; l; l = nl) {
278 if (depend_emit_phony)
279 fprintf(deps, "%s:\n\n", l->str);
289 int main(int argc, char **argv)
291 StrList *depend_list = NULL, **depend_ptr;
293 time(&official_compile_time);
296 want_usage = terminate_after_phase = false;
297 report_error = report_error_gnu;
303 nasm_set_malloc_error(report_error);
304 offsets = raa_init();
305 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
308 operating_mode = op_normal;
312 register_output_formats();
314 /* Define some macros dependent on the runtime, but not
315 on the command line. */
316 define_macros_early();
318 parse_cmdline(argc, argv);
320 if (terminate_after_phase) {
326 /* If debugging info is disabled, suppress any debug calls */
327 if (!using_debug_info)
328 ofmt->current_dfmt = &null_debug_form;
331 pp_extra_stdmac(ofmt->stdmac);
332 parser_global_info(ofmt, &location);
333 eval_global_info(ofmt, lookup_label, &location);
335 /* define some macros dependent of command-line */
336 define_macros_late();
338 depend_ptr = (depend_file || (operating_mode == op_depend))
339 ? &depend_list : NULL;
341 depend_target = outname;
343 switch (operating_mode) {
348 if (depend_missing_ok)
349 pp_include_path(NULL); /* "assume generated" */
351 preproc->reset(inname, 0, report_error, evaluate, &nasmlist,
353 if (outname[0] == '\0')
354 ofmt->filename(inname, outname, report_error);
356 while ((line = preproc->getline()))
365 char *file_name = NULL;
366 int32_t prior_linnum = 0;
370 ofile = fopen(outname, "w");
372 report_error(ERR_FATAL | ERR_NOFILE,
373 "unable to open output file `%s'",
378 location.known = false;
381 preproc->reset(inname, 2, report_error, evaluate, &nasmlist,
384 while ((line = preproc->getline())) {
386 * We generate %line directives if needed for later programs
388 int32_t linnum = prior_linnum += lineinc;
389 int altline = src_get(&linnum, &file_name);
391 if (altline == 1 && lineinc == 1)
392 nasm_fputs("", ofile);
394 lineinc = (altline != -1 || lineinc != 1);
395 fprintf(ofile ? ofile : stdout,
396 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
399 prior_linnum = linnum;
401 nasm_fputs(line, ofile);
404 nasm_free(file_name);
408 if (ofile && terminate_after_phase)
416 * We must call ofmt->filename _anyway_, even if the user
417 * has specified their own output file, because some
418 * formats (eg OBJ and COFF) use ofmt->filename to find out
419 * the name of the input file and then put that inside the
422 ofmt->filename(inname, outname, report_error);
424 ofile = fopen(outname, "wb");
426 report_error(ERR_FATAL | ERR_NOFILE,
427 "unable to open output file `%s'", outname);
431 * We must call init_labels() before ofmt->init() since
432 * some object formats will want to define labels in their
433 * init routines. (eg OS/2 defines the FLAT group)
437 ofmt->init(ofile, report_error, define_label, evaluate);
439 assemble_file(inname, depend_ptr);
441 if (!terminate_after_phase) {
442 ofmt->cleanup(using_debug_info);
446 * We had an fclose on the output file here, but we
447 * actually do that in all the object file drivers as well,
448 * so we're leaving out the one here.
460 emit_dependencies(depend_list);
470 if (terminate_after_phase)
477 * Get a parameter for a command line option.
478 * First arg must be in the form of e.g. -f...
480 static char *get_param(char *p, char *q, bool *advance)
483 if (p[2]) { /* the parameter's in the option */
493 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
494 "option `-%c' requires an argument", p[1]);
501 static void copy_filename(char *dst, const char *src)
503 size_t len = strlen(src);
505 if (len >= (size_t)FILENAME_MAX) {
506 report_error(ERR_FATAL | ERR_NOFILE, "file name too long");
509 strncpy(dst, src, FILENAME_MAX);
513 * Convert a string to Make-safe form
515 static char *quote_for_make(const char *str)
520 size_t n = 1; /* Terminating zero */
526 for (p = str; *p; p++) {
530 /* Convert N backslashes + ws -> 2N+1 backslashes + ws */
550 /* Convert N backslashes at the end of filename to 2N backslashes */
554 os = q = nasm_malloc(n);
557 for (p = str; *p; p++) {
600 #define OPT_POSTFIX 1
601 struct textargs textopts[] = {
602 {"prefix", OPT_PREFIX},
603 {"postfix", OPT_POSTFIX},
607 static bool stopoptions = false;
608 static bool process_arg(char *p, char *q)
612 bool advance = false;
618 if (p[0] == '-' && !stopoptions) {
619 if (strchr("oOfpPdDiIlFXuUZwW", p[1])) {
620 /* These parameters take values */
621 if (!(param = get_param(p, q, &advance)))
630 case 'o': /* output file */
631 copy_filename(outname, param);
634 case 'f': /* output format */
635 ofmt = ofmt_find(param);
637 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
638 "unrecognised output format `%s' - "
639 "use -hf for a list", param);
641 ofmt->current_dfmt = ofmt->debug_formats[0];
645 case 'O': /* Optimization level */
650 /* Naked -O == -Ox */
651 optimizing = INT_MAX >> 1; /* Almost unlimited */
655 case '0': case '1': case '2': case '3': case '4':
656 case '5': case '6': case '7': case '8': case '9':
657 opt = strtoul(param, ¶m, 10);
659 /* -O0 -> optimizing == -1, 0.98 behaviour */
660 /* -O1 -> optimizing == 0, 0.98.09 behaviour */
662 optimizing = opt - 1;
670 opt_verbose_info = true;
675 optimizing = INT_MAX >> 1; /* Almost unlimited */
679 report_error(ERR_FATAL,
680 "unknown optimization option -O%c\n",
689 case 'p': /* pre-include */
691 pp_pre_include(param);
694 case 'd': /* pre-define */
696 pp_pre_define(param);
699 case 'u': /* un-define */
701 pp_pre_undefine(param);
704 case 'i': /* include search path */
706 pp_include_path(param);
709 case 'l': /* listing file */
710 copy_filename(listname, param);
713 case 'Z': /* error messages file */
714 strcpy(errname, param);
717 case 'F': /* specify debug format */
718 ofmt->current_dfmt = dfmt_find(ofmt, param);
719 if (!ofmt->current_dfmt) {
720 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
721 "unrecognized debug format `%s' for"
722 " output format `%s'",
723 param, ofmt->shortname);
725 using_debug_info = true;
728 case 'X': /* specify error reporting format */
729 if (nasm_stricmp("vc", param) == 0)
730 report_error = report_error_vc;
731 else if (nasm_stricmp("gnu", param) == 0)
732 report_error = report_error_gnu;
734 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
735 "unrecognized error reporting format `%s'",
740 using_debug_info = true;
745 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
747 " [options...] [--] filename\n"
748 " or nasm -v for version info\n\n"
749 " -t assemble in SciTech TASM compatible mode\n"
750 " -g generate debug information in selected format.\n");
752 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
753 " -a don't preprocess (assemble only)\n"
754 " -M generate Makefile dependencies on stdout\n"
755 " -MG d:o, missing files assumed generated\n\n"
756 " -Z<file> redirect error messages to file\n"
757 " -s redirect error messages to stdout\n\n"
758 " -F format select a debugging format\n\n"
759 " -I<path> adds a pathname to the include file path\n");
761 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
762 " -P<file> pre-includes a file\n"
763 " -D<macro>[=<value>] pre-defines a macro\n"
764 " -U<macro> undefines a macro\n"
765 " -X<format> specifies error reporting format (gnu or vc)\n"
766 " -w+foo enables warning foo (equiv. -Wfoo)\n"
767 " -w-foo disable warning foo (equiv. -Wno-foo)\n"
769 for (i = 0; i <= ERR_WARN_MAX; i++)
770 printf(" %-23s %s (default %s)\n",
771 suppressed_names[i], suppressed_what[i],
772 suppressed[i] ? "off" : "on");
774 ("\nresponse files should contain command line parameters"
775 ", one per line.\n");
777 printf("\nvalid output formats for -f are"
778 " (`*' denotes default):\n");
779 ofmt_list(ofmt, stdout);
781 printf("\nFor a list of valid output formats, use -hf.\n");
782 printf("For a list of debug formats, use -f <form> -y.\n");
784 exit(0); /* never need usage message here */
788 printf("\nvalid debug formats for '%s' output format are"
789 " ('*' denotes default):\n", ofmt->shortname);
790 dfmt_list(ofmt, stdout);
795 tasm_compatible_mode = true;
800 const char *nasm_version_string =
801 "NASM version " NASM_VER " compiled on " __DATE__
806 puts(nasm_version_string);
807 exit(0); /* never need usage message here */
811 case 'e': /* preprocess only */
813 operating_mode = op_preprocess;
816 case 'a': /* assemble only - don't preprocess */
821 if (param[0] == 'n' && param[1] == 'o' && param[2] == '-') {
830 if (param[0] != '+' && param[0] != '-') {
831 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
832 "invalid option to `-w'");
835 suppress = (param[0] == '-');
839 for (i = 0; i <= ERR_WARN_MAX; i++)
840 if (!nasm_stricmp(param, suppressed_names[i]))
842 if (i <= ERR_WARN_MAX)
843 suppressed[i] = suppress;
844 else if (!nasm_stricmp(param, "all"))
845 for (i = 1; i <= ERR_WARN_MAX; i++)
846 suppressed[i] = suppress;
847 else if (!nasm_stricmp(param, "none"))
848 for (i = 1; i <= ERR_WARN_MAX; i++)
849 suppressed[i] = !suppress;
851 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
852 "invalid warning `%s'", param);
858 operating_mode = op_depend;
861 operating_mode = op_depend;
862 depend_missing_ok = true;
865 depend_emit_phony = true;
876 depend_target = quote_for_make(q);
880 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
881 "unknown dependency option `-M%c'", p[2]);
884 if (advance && (!q || !q[0])) {
885 report_error(ERR_NONFATAL|ERR_NOFILE|ERR_USAGE,
886 "option `-M%c' requires a parameter", p[2]);
895 if (p[2] == 0) { /* -- => stop processing options */
899 for (s = 0; textopts[s].label; s++) {
900 if (!nasm_stricmp(p + 2, textopts[s].label)) {
911 report_error(ERR_NONFATAL | ERR_NOFILE |
913 "option `--%s' requires an argument",
917 advance = 1, param = q;
920 if (s == OPT_PREFIX) {
921 strncpy(lprefix, param, PREFIX_MAX - 1);
922 lprefix[PREFIX_MAX - 1] = 0;
925 if (s == OPT_POSTFIX) {
926 strncpy(lpostfix, param, POSTFIX_MAX - 1);
927 lpostfix[POSTFIX_MAX - 1] = 0;
934 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
935 "unrecognised option `--%s'", p + 2);
943 if (!ofmt->setinfo(GI_SWITCH, &p))
944 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
945 "unrecognised option `-%c'", p[1]);
950 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
951 "more than one input file specified");
953 copy_filename(inname, p);
960 #define ARG_BUF_DELTA 128
962 static void process_respfile(FILE * rfile)
964 char *buffer, *p, *q, *prevarg;
965 int bufsize, prevargsize;
967 bufsize = prevargsize = ARG_BUF_DELTA;
968 buffer = nasm_malloc(ARG_BUF_DELTA);
969 prevarg = nasm_malloc(ARG_BUF_DELTA);
972 while (1) { /* Loop to handle all lines in file */
974 while (1) { /* Loop to handle long lines */
975 q = fgets(p, bufsize - (p - buffer), rfile);
979 if (p > buffer && p[-1] == '\n')
981 if (p - buffer > bufsize - 10) {
984 bufsize += ARG_BUF_DELTA;
985 buffer = nasm_realloc(buffer, bufsize);
990 if (!q && p == buffer) {
992 process_arg(prevarg, NULL);
999 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1000 * them are present at the end of the line.
1002 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
1004 while (p > buffer && isspace(p[-1]))
1011 if (process_arg(prevarg, p))
1014 if ((int) strlen(p) > prevargsize - 10) {
1015 prevargsize += ARG_BUF_DELTA;
1016 prevarg = nasm_realloc(prevarg, prevargsize);
1018 strncpy(prevarg, p, prevargsize);
1022 /* Function to process args from a string of args, rather than the
1023 * argv array. Used by the environment variable and response file
1026 static void process_args(char *args)
1028 char *p, *q, *arg, *prevarg;
1029 char separator = ' ';
1032 if (*p && *p != '-')
1037 while (*p && *p != separator)
1039 while (*p == separator)
1043 if (process_arg(prevarg, arg))
1047 process_arg(arg, NULL);
1050 static void process_response_file(const char *file)
1053 FILE *f = fopen(file, "r");
1058 while (fgets(str, sizeof str, f)) {
1064 static void parse_cmdline(int argc, char **argv)
1067 char *envreal, *envcopy = NULL, *p, *arg;
1069 *inname = *outname = *listname = *errname = '\0';
1072 * First, process the NASMENV environment variable.
1074 envreal = getenv("NASMENV");
1077 envcopy = nasm_strdup(envreal);
1078 process_args(envcopy);
1083 * Now process the actual command line.
1088 if (argv[0][0] == '@') {
1089 /* We have a response file, so process this as a set of
1090 * arguments like the environment variable. This allows us
1091 * to have multiple arguments on a single line, which is
1092 * different to the -@resp file processing below for regular
1095 process_response_file(argv[0]+1);
1099 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
1100 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &advance);
1102 rfile = fopen(p, "r");
1104 process_respfile(rfile);
1107 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1108 "unable to open response file `%s'", p);
1111 advance = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
1112 argv += advance, argc -= advance;
1115 /* Look for basic command line typos. This definitely doesn't
1116 catch all errors, but it might help cases of fumbled fingers. */
1118 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
1119 "no input file specified");
1120 else if (!strcmp(inname, errname) ||
1121 !strcmp(inname, outname) ||
1122 !strcmp(inname, listname) ||
1123 (depend_file && !strcmp(inname, depend_file)))
1124 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1125 "file `%s' is both input and output file",
1129 error_file = fopen(errname, "w");
1131 error_file = stderr; /* Revert to default! */
1132 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
1133 "cannot open file `%s' for error messages",
1139 /* List of directives */
1141 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
1142 D_EXTERN, D_FLOAT, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
1144 static const char *directives[] = {
1145 "", "absolute", "bits", "common", "cpu", "debug", "default",
1146 "extern", "float", "global", "list", "section", "segment", "warning"
1148 static enum directives getkw(char **directive, char **value);
1150 static void assemble_file(char *fname, StrList **depend_ptr)
1152 char *directive, *value, *p, *q, *special, *line, debugid[80];
1158 struct tokenval tokval;
1162 if (cmd_sb == 32 && cmd_cpu < IF_386)
1163 report_error(ERR_FATAL, "command line: "
1164 "32-bit segment size requires a higher cpu");
1166 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
1167 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
1168 for (passn = 1; pass0 <= 2; passn++) {
1172 pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */
1173 pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */
1174 /* pass0 0, 0, 0, ..., 1, 2 */
1176 def_label = passn > 1 ? redefine_label : define_label;
1178 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
1182 nasmlist.init(listname, report_error);
1185 global_offset_changed = false; /* set by redefine_label */
1186 location.segment = ofmt->section(NULL, pass2, &sb);
1189 saa_rewind(forwrefs);
1190 forwref = saa_rstruct(forwrefs);
1192 offsets = raa_init();
1194 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist,
1195 pass1 == 2 ? depend_ptr : NULL);
1199 location.known = true;
1200 location.offset = offs = GET_CURR_OFFS;
1202 while ((line = preproc->getline())) {
1206 /* here we parse our directives; this is not handled by the 'real'
1209 d = getkw(&directive, &value);
1214 case D_SEGMENT: /* [SEGMENT n] */
1216 seg = ofmt->section(value, pass2, &sb);
1217 if (seg == NO_SEG) {
1218 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1219 "segment name `%s' not recognized",
1223 location.segment = seg;
1226 case D_EXTERN: /* [EXTERN label:special] */
1228 value++; /* skip initial $ if present */
1231 while (*q && *q != ':')
1235 ofmt->symdef(value, 0L, 0L, 3, q);
1237 } else if (passn == 1) {
1242 while (*q && *q != ':') {
1248 report_error(ERR_NONFATAL,
1249 "identifier expected after EXTERN");
1257 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
1259 pass0 = 1; /* fake pass 1 in labels.c */
1260 declare_as_global(value, special,
1262 define_label(value, seg_alloc(), 0L, NULL,
1263 false, true, ofmt, report_error);
1266 } /* else pass0 == 1 */
1268 case D_BITS: /* [BITS bits] */
1269 globalbits = sb = get_bits(value);
1271 case D_GLOBAL: /* [GLOBAL symbol:special] */
1273 value++; /* skip initial $ if present */
1274 if (pass0 == 2) { /* pass 2 */
1276 while (*q && *q != ':')
1280 ofmt->symdef(value, 0L, 0L, 3, q);
1282 } else if (pass2 == 1) { /* pass == 1 */
1287 while (*q && *q != ':') {
1293 report_error(ERR_NONFATAL,
1294 "identifier expected after GLOBAL");
1302 declare_as_global(value, special, report_error);
1305 case D_COMMON: /* [COMMON symbol size:special] */
1307 value++; /* skip initial $ if present */
1313 while (*p && !isspace(*p)) {
1319 report_error(ERR_NONFATAL,
1320 "identifier expected after COMMON");
1326 while (*p && isspace(*p))
1329 while (*q && *q != ':')
1336 size = readnum(p, &rn_error);
1338 report_error(ERR_NONFATAL,
1339 "invalid size specified"
1340 " in COMMON declaration");
1342 define_common(value, seg_alloc(), size,
1343 special, ofmt, report_error);
1345 report_error(ERR_NONFATAL,
1346 "no size specified in"
1347 " COMMON declaration");
1348 } else if (pass0 == 2) { /* pass == 2 */
1350 while (*q && *q != ':') {
1357 ofmt->symdef(value, 0L, 0L, 3, q);
1361 case D_ABSOLUTE: /* [ABSOLUTE address] */
1363 stdscan_bufptr = value;
1364 tokval.t_type = TOKEN_INVALID;
1365 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1366 report_error, NULL);
1369 report_error(pass0 ==
1370 1 ? ERR_NONFATAL : ERR_PANIC,
1371 "cannot use non-relocatable expression as "
1372 "ABSOLUTE address");
1374 abs_seg = reloc_seg(e);
1375 abs_offset = reloc_value(e);
1377 } else if (passn == 1)
1378 abs_offset = 0x100; /* don't go near zero in case of / */
1380 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1383 location.segment = NO_SEG;
1385 case D_DEBUG: /* [DEBUG] */
1391 while (*p && !isspace(*p)) {
1398 report_error(passn == 1 ? ERR_NONFATAL : ERR_PANIC,
1399 "identifier expected after DEBUG");
1402 while (*p && isspace(*p))
1405 ofmt->current_dfmt->debug_directive(debugid, p);
1407 case D_WARNING: /* [WARNING {+|-}warn-name] */
1409 while (*value && isspace(*value))
1412 if (*value == '+' || *value == '-') {
1413 validid = (*value == '-') ? true : false;
1418 for (i = 1; i <= ERR_WARN_MAX; i++)
1419 if (!nasm_stricmp(value, suppressed_names[i]))
1421 if (i <= ERR_WARN_MAX)
1422 suppressed[i] = validid;
1424 report_error(ERR_NONFATAL,
1425 "invalid warning id in WARNING directive");
1428 case D_CPU: /* [CPU] */
1429 cpu = get_cpu(value);
1431 case D_LIST: /* [LIST {+|-}] */
1432 while (*value && isspace(*value))
1435 if (*value == '+') {
1438 if (*value == '-') {
1445 case D_DEFAULT: /* [DEFAULT] */
1447 stdscan_bufptr = value;
1448 tokval.t_type = TOKEN_INVALID;
1449 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1450 switch ((int)tokval.t_integer) {
1466 if (float_option(value)) {
1467 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1468 "unknown 'float' directive: %s",
1473 if (!ofmt->directive(directive, value, pass2))
1474 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1475 "unrecognised directive [%s]",
1479 report_error(ERR_NONFATAL,
1480 "invalid parameter to [%s] directive",
1483 } else { /* it isn't a directive */
1485 parse_line(pass1, line, &output_ins,
1486 report_error, evaluate, def_label);
1488 if (!(optimizing > 0) && pass0 == 2) {
1489 if (forwref != NULL && globallineno == forwref->lineno) {
1490 output_ins.forw_ref = true;
1492 output_ins.oprs[forwref->operand].opflags |=
1494 forwref = saa_rstruct(forwrefs);
1495 } while (forwref != NULL
1496 && forwref->lineno == globallineno);
1498 output_ins.forw_ref = false;
1501 if (!(optimizing > 0) && output_ins.forw_ref) {
1503 for (i = 0; i < output_ins.operands; i++) {
1504 if (output_ins.oprs[i].
1505 opflags & OPFLAG_FORWARD) {
1506 struct forwrefinfo *fwinf =
1507 (struct forwrefinfo *)
1508 saa_wstruct(forwrefs);
1509 fwinf->lineno = globallineno;
1513 } else { /* passn > 1 */
1515 * Hack to prevent phase error in the code
1519 * If the second operand is a forward reference,
1520 * the UNITY property of the number 1 in that
1521 * operand is cancelled. Otherwise the above
1522 * sequence will cause a phase error.
1524 * This hack means that the above code will
1525 * generate 286+ code.
1527 * The forward reference will mean that the
1528 * operand will not have the UNITY property on
1529 * the first pass, so the pass behaviours will
1533 if (output_ins.operands >= 2 &&
1534 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1535 !(IMMEDIATE & ~output_ins.oprs[1].type))
1537 /* Remove special properties bits */
1538 output_ins.oprs[1].type &= ~REG_SMASK;
1546 if (output_ins.opcode == I_EQU) {
1549 * Special `..' EQUs get processed in pass two,
1550 * except `..@' macro-processor EQUs which are done
1551 * in the normal place.
1553 if (!output_ins.label)
1554 report_error(ERR_NONFATAL,
1555 "EQU not preceded by label");
1557 else if (output_ins.label[0] != '.' ||
1558 output_ins.label[1] != '.' ||
1559 output_ins.label[2] == '@') {
1560 if (output_ins.operands == 1 &&
1561 (output_ins.oprs[0].type & IMMEDIATE) &&
1562 output_ins.oprs[0].wrt == NO_SEG) {
1565 opflags & OPFLAG_EXTERN;
1566 def_label(output_ins.label,
1567 output_ins.oprs[0].segment,
1568 output_ins.oprs[0].offset, NULL,
1571 } else if (output_ins.operands == 2
1572 && (output_ins.oprs[0].
1574 && (output_ins.oprs[0].type & COLON)
1575 && output_ins.oprs[0].segment ==
1577 && output_ins.oprs[0].wrt == NO_SEG
1578 && (output_ins.oprs[1].
1580 && output_ins.oprs[1].segment ==
1582 && output_ins.oprs[1].wrt ==
1584 def_label(output_ins.label,
1587 output_ins.oprs[1].offset, NULL,
1591 report_error(ERR_NONFATAL,
1592 "bad syntax for EQU");
1596 * Special `..' EQUs get processed here, except
1597 * `..@' macro processor EQUs which are done above.
1599 if (output_ins.label[0] == '.' &&
1600 output_ins.label[1] == '.' &&
1601 output_ins.label[2] != '@') {
1602 if (output_ins.operands == 1 &&
1603 (output_ins.oprs[0].type & IMMEDIATE)) {
1604 define_label(output_ins.label,
1605 output_ins.oprs[0].segment,
1606 output_ins.oprs[0].offset,
1607 NULL, false, false, ofmt,
1609 } else if (output_ins.operands == 2
1610 && (output_ins.oprs[0].
1612 && (output_ins.oprs[0].type & COLON)
1613 && output_ins.oprs[0].segment ==
1615 && (output_ins.oprs[1].
1617 && output_ins.oprs[1].segment ==
1619 define_label(output_ins.label,
1622 output_ins.oprs[1].offset,
1623 NULL, false, false, ofmt,
1626 report_error(ERR_NONFATAL,
1627 "bad syntax for EQU");
1630 } else { /* instruction isn't an EQU */
1634 int64_t l = insn_size(location.segment, offs, sb, cpu,
1635 &output_ins, report_error);
1637 /* if (using_debug_info) && output_ins.opcode != -1) */
1638 if (using_debug_info)
1639 { /* fbk 03/25/01 */
1640 /* this is done here so we can do debug type info */
1642 TYS_ELEMENTS(output_ins.operands);
1643 switch (output_ins.opcode) {
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].
1671 TYS_ELEMENTS(output_ins.oprs[0].
1676 TYS_ELEMENTS(output_ins.oprs[0].
1680 typeinfo |= TY_BYTE;
1683 typeinfo |= TY_WORD;
1686 if (output_ins.eops_float)
1687 typeinfo |= TY_FLOAT;
1689 typeinfo |= TY_DWORD;
1692 typeinfo |= TY_QWORD;
1695 typeinfo |= TY_TBYTE;
1698 typeinfo |= TY_OWORD;
1701 typeinfo |= TY_YWORD;
1704 typeinfo = TY_LABEL;
1708 ofmt->current_dfmt->debug_typevalue(typeinfo);
1713 SET_CURR_OFFS(offs);
1716 * else l == -1 => invalid instruction, which will be
1717 * flagged as an error on pass 2
1721 offs += assemble(location.segment, offs, sb, cpu,
1722 &output_ins, ofmt, report_error,
1724 SET_CURR_OFFS(offs);
1728 cleanup_insn(&output_ins);
1731 location.offset = offs = GET_CURR_OFFS;
1732 } /* end while (line = preproc->getline... */
1734 if (pass1 == 2 && global_offset_changed)
1735 report_error(ERR_NONFATAL,
1736 "phase error detected at end of assembly.");
1739 preproc->cleanup(1);
1741 if (pass1 == 1 && terminate_after_phase) {
1748 if (passn >= pass_max - 2 ||
1749 (passn > 1 && !global_offset_changed))
1753 preproc->cleanup(0);
1756 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1758 "info:: assembly required 1+%d+1 passes\n", passn-3);
1760 } /* exit from assemble_file (...) */
1762 static enum directives getkw(char **directive, char **value)
1768 /* allow leading spaces or tabs */
1769 while (*buf == ' ' || *buf == '\t')
1777 while (*p && *p != ']')
1785 while (*p && *p != ';') {
1792 *directive = p = buf + 1;
1793 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1800 while (isspace(*buf))
1801 buf++; /* beppu - skip leading whitespace */
1808 return bsii(*directive, directives, elements(directives));
1812 * gnu style error reporting
1813 * This function prints an error message to error_file in the
1814 * style used by GNU. An example would be:
1815 * file.asm:50: error: blah blah blah
1816 * where file.asm is the name of the file, 50 is the line number on
1817 * which the error occurs (or is detected) and "error:" is one of
1818 * the possible optional diagnostics -- it can be "error" or "warning"
1819 * or something else. Finally the line terminates with the actual
1822 * @param severity the severity of the warning or error
1823 * @param fmt the printf style format string
1825 static void report_error_gnu(int severity, const char *fmt, ...)
1829 if (is_suppressed_warning(severity))
1832 if (severity & ERR_NOFILE)
1833 fputs("nasm: ", error_file);
1835 char *currentfile = NULL;
1837 src_get(&lineno, ¤tfile);
1838 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1839 nasm_free(currentfile);
1842 report_error_common(severity, fmt, ap);
1847 * MS style error reporting
1848 * This function prints an error message to error_file in the
1849 * style used by Visual C and some other Microsoft tools. An example
1851 * file.asm(50) : error: blah blah blah
1852 * where file.asm is the name of the file, 50 is the line number on
1853 * which the error occurs (or is detected) and "error:" is one of
1854 * the possible optional diagnostics -- it can be "error" or "warning"
1855 * or something else. Finally the line terminates with the actual
1858 * @param severity the severity of the warning or error
1859 * @param fmt the printf style format string
1861 static void report_error_vc(int severity, const char *fmt, ...)
1865 if (is_suppressed_warning(severity))
1868 if (severity & ERR_NOFILE)
1869 fputs("nasm: ", error_file);
1871 char *currentfile = NULL;
1873 src_get(&lineno, ¤tfile);
1874 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1875 nasm_free(currentfile);
1878 report_error_common(severity, fmt, ap);
1883 * check for supressed warning
1884 * checks for suppressed warning or pass one only warning and we're
1887 * @param severity the severity of the warning or error
1888 * @return true if we should abort error/warning printing
1890 static bool is_suppressed_warning(int severity)
1893 * See if it's a suppressed warning.
1895 return (severity & ERR_MASK) == ERR_WARNING &&
1896 (((severity & ERR_WARN_MASK) != 0 &&
1897 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1898 /* See if it's a pass-one only warning and we're not in pass one. */
1899 ((severity & ERR_PASS1) && pass0 != 1));
1903 * common error reporting
1904 * This is the common back end of the error reporting schemes currently
1905 * implemented. It prints the nature of the warning and then the
1906 * specific error message to error_file and may or may not return. It
1907 * doesn't return if the error severity is a "panic" or "debug" type.
1909 * @param severity the severity of the warning or error
1910 * @param fmt the printf style format string
1912 static void report_error_common(int severity, const char *fmt,
1915 switch (severity & (ERR_MASK|ERR_NO_SEVERITY)) {
1917 fputs("warning: ", error_file);
1920 fputs("error: ", error_file);
1923 fputs("fatal: ", error_file);
1926 fputs("panic: ", error_file);
1929 fputs("debug: ", error_file);
1935 vfprintf(error_file, fmt, args);
1936 putc('\n', error_file);
1938 if (severity & ERR_USAGE)
1941 switch (severity & ERR_MASK) {
1943 /* no further action, by definition */
1946 if (!suppressed[0]) /* Treat warnings as errors */
1947 terminate_after_phase = true;
1950 terminate_after_phase = true;
1959 exit(1); /* instantly die */
1960 break; /* placate silly compilers */
1963 /* abort(); *//* halt, catch fire, and dump core */
1969 static void usage(void)
1971 fputs("type `nasm -h' for help\n", error_file);
1974 static void register_output_formats(void)
1976 ofmt = ofmt_register(report_error);
1979 #define BUF_DELTA 512
1981 static FILE *no_pp_fp;
1982 static efunc no_pp_err;
1983 static ListGen *no_pp_list;
1984 static int32_t no_pp_lineinc;
1986 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1987 ListGen * listgen, StrList **deplist)
1989 src_set_fname(nasm_strdup(file));
1993 no_pp_fp = fopen(file, "r");
1995 no_pp_err(ERR_FATAL | ERR_NOFILE,
1996 "unable to open input file `%s'", file);
1997 no_pp_list = listgen;
1998 (void)pass; /* placate compilers */
1999 (void)eval; /* placate compilers */
2002 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
2004 strcpy(sl->str, file);
2009 static char *no_pp_getline(void)
2011 char *buffer, *p, *q;
2014 bufsize = BUF_DELTA;
2015 buffer = nasm_malloc(BUF_DELTA);
2016 src_set_linnum(src_get_linnum() + no_pp_lineinc);
2018 while (1) { /* Loop to handle %line */
2021 while (1) { /* Loop to handle long lines */
2022 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
2026 if (p > buffer && p[-1] == '\n')
2028 if (p - buffer > bufsize - 10) {
2030 offset = p - buffer;
2031 bufsize += BUF_DELTA;
2032 buffer = nasm_realloc(buffer, bufsize);
2033 p = buffer + offset;
2037 if (!q && p == buffer) {
2043 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
2044 * them are present at the end of the line.
2046 buffer[strcspn(buffer, "\r\n\032")] = '\0';
2048 if (!nasm_strnicmp(buffer, "%line", 5)) {
2051 char *nm = nasm_malloc(strlen(buffer));
2052 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
2053 nasm_free(src_set_fname(nm));
2063 no_pp_list->line(LIST_READ, buffer);
2068 static void no_pp_cleanup(int pass)
2070 (void)pass; /* placate GCC */
2074 static uint32_t get_cpu(char *value)
2076 if (!strcmp(value, "8086"))
2078 if (!strcmp(value, "186"))
2080 if (!strcmp(value, "286"))
2082 if (!strcmp(value, "386"))
2084 if (!strcmp(value, "486"))
2086 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
2088 if (!strcmp(value, "686") ||
2089 !nasm_stricmp(value, "ppro") ||
2090 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
2092 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
2094 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
2095 !nasm_stricmp(value, "willamette"))
2096 return IF_WILLAMETTE;
2097 if (!nasm_stricmp(value, "prescott"))
2099 if (!nasm_stricmp(value, "x64") ||
2100 !nasm_stricmp(value, "x86-64"))
2102 if (!nasm_stricmp(value, "ia64") ||
2103 !nasm_stricmp(value, "ia-64") ||
2104 !nasm_stricmp(value, "itanium") ||
2105 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
2108 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2109 "unknown 'cpu' type");
2111 return IF_PLEVEL; /* the maximum level */
2114 static int get_bits(char *value)
2118 if ((i = atoi(value)) == 16)
2119 return i; /* set for a 16-bit segment */
2122 report_error(ERR_NONFATAL,
2123 "cannot specify 32-bit segment on processor below a 386");
2126 } else if (i == 64) {
2127 if (cpu < IF_X86_64) {
2128 report_error(ERR_NONFATAL,
2129 "cannot specify 64-bit segment on processor below an x86-64");
2133 report_error(ERR_NONFATAL,
2134 "%s output format does not support 64-bit code",
2139 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
2140 "`%s' is not a valid segment size; must be 16, 32 or 64",