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 licence given in the file "Licence"
6 * distributed in the NASM archive.
30 struct forwrefinfo { /* info held on forward refs. */
35 static int get_bits(char *value);
36 static uint32_t get_cpu(char *cpu_str);
37 static void parse_cmdline(int, char **);
38 static void assemble_file(char *);
39 static int getkw(char **directive, char **value);
40 static void register_output_formats(void);
41 static void report_error_gnu(int severity, const char *fmt, ...);
42 static void report_error_vc(int severity, const char *fmt, ...);
43 static void report_error_common(int severity, const char *fmt,
45 static int is_suppressed_warning(int severity);
46 static void usage(void);
47 static efunc report_error;
49 static int using_debug_info, opt_verbose_info;
50 int tasm_compatible_mode = FALSE;
55 static char inname[FILENAME_MAX];
56 static char outname[FILENAME_MAX];
57 static char listname[FILENAME_MAX];
58 static char errname[FILENAME_MAX];
59 static int globallineno; /* for forward-reference tracking */
60 /* static int pass = 0; */
61 static struct ofmt *ofmt = NULL;
63 static FILE *error_file; /* Where to write error messages */
65 static FILE *ofile = NULL;
66 int optimizing = -1; /* number of optimization passes to take */
67 static int sb, cmd_sb = 16; /* by default */
68 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
69 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
70 int global_offset_changed; /* referenced in labels.c */
72 static struct location location;
73 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
74 int32_t abs_seg; /* ABSOLUTE segment basis */
75 int32_t abs_offset; /* ABSOLUTE offset */
77 static struct RAA *offsets;
79 static struct SAA *forwrefs; /* keep track of forward references */
80 static const struct forwrefinfo *forwref;
82 static Preproc *preproc;
84 op_normal, /* Preprocess and assemble */
85 op_preprocess, /* Preprocess only */
86 op_depend, /* Generate dependencies */
87 op_depend_missing_ok, /* Generate dependencies, missing OK */
89 static enum op_type operating_mode;
92 * Which of the suppressible warnings are suppressed. Entry zero
93 * doesn't do anything. Initial defaults are given here.
95 static char suppressed[1 + ERR_WARN_MAX] = {
96 0, TRUE, TRUE, TRUE, FALSE, TRUE
100 * The option names for the suppressible warnings. As before, entry
103 static const char *suppressed_names[1 + ERR_WARN_MAX] = {
104 NULL, "macro-params", "macro-selfref", "orphan-labels",
110 * The explanations for the suppressible warnings. As before, entry
113 static const char *suppressed_what[1 + ERR_WARN_MAX] = {
115 "macro calls with wrong no. of params",
116 "cyclic macro self-references",
117 "labels alone on lines without trailing `:'",
118 "numeric constants greater than 0xFFFFFFFF",
119 "using 8- or 16-bit relocation in ELF, a GNU extension"
123 * This is a null preprocessor which just copies lines from input
124 * to output. It's used when someone explicitly requests that NASM
125 * not preprocess their source file.
128 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *);
129 static char *no_pp_getline(void);
130 static void no_pp_cleanup(int);
131 static Preproc no_pp = {
138 * get/set current offset...
140 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
141 raa_read(offsets,location.segment))
142 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
143 (void)(offsets=raa_write(offsets,location.segment,(x))))
145 static int want_usage;
146 static int terminate_after_phase;
147 int user_nolist = 0; /* fbk 9/2/00 */
149 static void nasm_fputs(const char *line, FILE * outfile)
152 fputs(line, outfile);
153 fputc('\n', outfile);
158 int main(int argc, char **argv)
161 want_usage = terminate_after_phase = FALSE;
162 report_error = report_error_gnu;
166 nasm_set_malloc_error(report_error);
167 offsets = raa_init();
168 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
171 operating_mode = op_normal;
175 register_output_formats();
177 parse_cmdline(argc, argv);
179 if (terminate_after_phase) {
185 /* If debugging info is disabled, suppress any debug calls */
186 if (!using_debug_info)
187 ofmt->current_dfmt = &null_debug_form;
190 pp_extra_stdmac(ofmt->stdmac);
191 parser_global_info(ofmt, &location);
192 eval_global_info(ofmt, lookup_label, &location);
194 /* define some macros dependent of command-line */
197 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
202 switch (operating_mode) {
203 case op_depend_missing_ok:
204 pp_include_path(NULL); /* "assume generated" */
209 preproc->reset(inname, 0, report_error, evaluate, &nasmlist);
210 if (outname[0] == '\0')
211 ofmt->filename(inname, outname, report_error);
213 fprintf(stdout, "%s: %s", outname, inname);
214 while ((line = preproc->getline()))
224 char *file_name = NULL;
225 int32_t prior_linnum = 0;
229 ofile = fopen(outname, "w");
231 report_error(ERR_FATAL | ERR_NOFILE,
232 "unable to open output file `%s'",
237 location.known = FALSE;
240 preproc->reset(inname, 2, report_error, evaluate, &nasmlist);
241 while ((line = preproc->getline())) {
243 * We generate %line directives if needed for later programs
245 int32_t linnum = prior_linnum += lineinc;
246 int altline = src_get(&linnum, &file_name);
248 if (altline == 1 && lineinc == 1)
249 nasm_fputs("", ofile);
251 lineinc = (altline != -1 || lineinc != 1);
252 fprintf(ofile ? ofile : stdout,
253 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
256 prior_linnum = linnum;
258 nasm_fputs(line, ofile);
261 nasm_free(file_name);
265 if (ofile && terminate_after_phase)
273 * We must call ofmt->filename _anyway_, even if the user
274 * has specified their own output file, because some
275 * formats (eg OBJ and COFF) use ofmt->filename to find out
276 * the name of the input file and then put that inside the
279 ofmt->filename(inname, outname, report_error);
281 ofile = fopen(outname, "wb");
283 report_error(ERR_FATAL | ERR_NOFILE,
284 "unable to open output file `%s'", outname);
288 * We must call init_labels() before ofmt->init() since
289 * some object formats will want to define labels in their
290 * init routines. (eg OS/2 defines the FLAT group)
294 ofmt->init(ofile, report_error, define_label, evaluate);
296 assemble_file(inname);
298 if (!terminate_after_phase) {
299 ofmt->cleanup(using_debug_info);
303 * We had an fclose on the output file here, but we
304 * actually do that in all the object file drivers as well,
305 * so we're leaving out the one here.
324 if (terminate_after_phase)
331 * Get a parameter for a command line option.
332 * First arg must be in the form of e.g. -f...
334 static char *get_param(char *p, char *q, int *advance)
337 if (p[2]) { /* the parameter's in the option */
347 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
348 "option `-%c' requires an argument", p[1]);
358 #define OPT_POSTFIX 1
359 struct textargs textopts[] = {
360 {"prefix", OPT_PREFIX},
361 {"postfix", OPT_POSTFIX},
366 static int process_arg(char *p, char *q)
374 if (p[0] == '-' && !stopoptions) {
379 case 'o': /* these parameters take values */
394 if (!(param = get_param(p, q, &advance)))
396 if (p[1] == 'o') { /* output file */
397 strcpy(outname, param);
398 } else if (p[1] == 'f') { /* output format */
399 ofmt = ofmt_find(param);
401 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
402 "unrecognised output format `%s' - "
403 "use -hf for a list", param);
405 ofmt->current_dfmt = ofmt->debug_formats[0];
406 } else if (p[1] == 'O') { /* Optimization level */
410 if (isdigit(*param)) {
412 while (isdigit(*++param)) ;
414 optimizing = -1; /* 0.98 behaviour */
416 optimizing = 0; /* Two passes, 0.98.09 behavior */
418 /* The optimizer seems to have problems with
419 < 5 passes? Hidden bug? */
420 optimizing = 5; /* 5 passes */
422 optimizing = opt; /* More than 5 passes */
424 if (*param == 'v' || *param == '+') {
426 opt_verbose_info = TRUE;
428 } else { /* garbage */
433 } /* while (*param) */
435 report_error(ERR_FATAL,
436 "command line optimization level must be 'v', 0..3 or <nn>");
437 } else if (p[1] == 'P' || p[1] == 'p') { /* pre-include */
438 pp_pre_include(param);
439 } else if (p[1] == 'D' || p[1] == 'd') { /* pre-define */
440 pp_pre_define(param);
441 } else if (p[1] == 'U' || p[1] == 'u') { /* un-define */
442 pp_pre_undefine(param);
443 } else if (p[1] == 'I' || p[1] == 'i') { /* include search path */
444 pp_include_path(param);
445 } else if (p[1] == 'l') { /* listing file */
446 strcpy(listname, param);
447 } else if (p[1] == 'Z') { /* error messages file */
448 strcpy(errname, param);
449 } else if (p[1] == 'F') { /* specify debug format */
450 ofmt->current_dfmt = dfmt_find(ofmt, param);
451 if (!ofmt->current_dfmt) {
452 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
453 "unrecognized debug format `%s' for"
454 " output format `%s'",
455 param, ofmt->shortname);
457 } else if (p[1] == 'X') { /* specify error reporting format */
458 if (nasm_stricmp("vc", param) == 0)
459 report_error = report_error_vc;
460 else if (nasm_stricmp("gnu", param) == 0)
461 report_error = report_error_gnu;
463 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
464 "unrecognized error reporting format `%s'",
469 using_debug_info = TRUE;
473 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
475 " [options...] [--] filename\n"
476 " or nasm -v for version info\n\n"
477 " -t assemble in SciTech TASM compatible mode\n"
478 " -g generate debug information in selected format.\n");
480 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
481 " -a don't preprocess (assemble only)\n"
482 " -M generate Makefile dependencies on stdout\n"
483 " -MG d:o, missing files assumed generated\n\n"
484 " -Z<file> redirect error messages to file\n"
485 " -s redirect error messages to stdout\n\n"
486 " -F format select a debugging format\n\n"
487 " -I<path> adds a pathname to the include file path\n");
489 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
490 " -P<file> pre-includes a file\n"
491 " -D<macro>[=<value>] pre-defines a macro\n"
492 " -U<macro> undefines a macro\n"
493 " -X<format> specifies error reporting format (gnu or vc)\n"
494 " -w+foo enables warnings about foo; -w-foo disables them\n"
495 "where foo can be:\n");
496 for (i = 1; i <= ERR_WARN_MAX; i++)
497 printf(" %-23s %s (default %s)\n",
498 suppressed_names[i], suppressed_what[i],
499 suppressed[i] ? "off" : "on");
501 ("\nresponse files should contain command line parameters"
502 ", one per line.\n");
504 printf("\nvalid output formats for -f are"
505 " (`*' denotes default):\n");
506 ofmt_list(ofmt, stdout);
508 printf("\nFor a list of valid output formats, use -hf.\n");
509 printf("For a list of debug formats, use -f <form> -y.\n");
511 exit(0); /* never need usage message here */
514 printf("\nvalid debug formats for '%s' output format are"
515 " ('*' denotes default):\n", ofmt->shortname);
516 dfmt_list(ofmt, stdout);
520 tasm_compatible_mode = TRUE;
524 const char *nasm_version_string =
525 "NASM version " NASM_VER " compiled on " __DATE__
530 puts(nasm_version_string);
531 exit(0); /* never need usage message here */
534 case 'e': /* preprocess only */
536 operating_mode = op_preprocess;
538 case 'a': /* assemble only - don't preprocess */
542 if (p[2] != '+' && p[2] != '-') {
543 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
544 "invalid option to `-w'");
546 for (i = 1; i <= ERR_WARN_MAX; i++)
547 if (!nasm_stricmp(p + 3, suppressed_names[i]))
549 if (i <= ERR_WARN_MAX)
550 suppressed[i] = (p[2] == '-');
552 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
553 "invalid option to `-w'");
557 operating_mode = p[2] == 'G' ? op_depend_missing_ok : op_depend;
564 if (p[2] == 0) { /* -- => stop processing options */
568 for (s = 0; textopts[s].label; s++) {
569 if (!nasm_stricmp(p + 2, textopts[s].label)) {
580 report_error(ERR_NONFATAL | ERR_NOFILE |
582 "option `--%s' requires an argument",
586 advance = 1, param = q;
589 if (s == OPT_PREFIX) {
590 strncpy(lprefix, param, PREFIX_MAX - 1);
591 lprefix[PREFIX_MAX - 1] = 0;
594 if (s == OPT_POSTFIX) {
595 strncpy(lpostfix, param, POSTFIX_MAX - 1);
596 lpostfix[POSTFIX_MAX - 1] = 0;
603 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
604 "unrecognised option `--%s'", p + 2);
612 if (!ofmt->setinfo(GI_SWITCH, &p))
613 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
614 "unrecognised option `-%c'", p[1]);
619 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
620 "more than one input file specified");
628 #define ARG_BUF_DELTA 128
630 static void process_respfile(FILE * rfile)
632 char *buffer, *p, *q, *prevarg;
633 int bufsize, prevargsize;
635 bufsize = prevargsize = ARG_BUF_DELTA;
636 buffer = nasm_malloc(ARG_BUF_DELTA);
637 prevarg = nasm_malloc(ARG_BUF_DELTA);
640 while (1) { /* Loop to handle all lines in file */
643 while (1) { /* Loop to handle long lines */
644 q = fgets(p, bufsize - (p - buffer), rfile);
648 if (p > buffer && p[-1] == '\n')
650 if (p - buffer > bufsize - 10) {
653 bufsize += ARG_BUF_DELTA;
654 buffer = nasm_realloc(buffer, bufsize);
659 if (!q && p == buffer) {
661 process_arg(prevarg, NULL);
668 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
669 * them are present at the end of the line.
671 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
673 while (p > buffer && isspace(p[-1]))
680 if (process_arg(prevarg, p))
683 if (strlen(p) > prevargsize - 10) {
684 prevargsize += ARG_BUF_DELTA;
685 prevarg = nasm_realloc(prevarg, prevargsize);
691 /* Function to process args from a string of args, rather than the
692 * argv array. Used by the environment variable and response file
695 static void process_args(char *args)
697 char *p, *q, *arg, *prevarg;
698 char separator = ' ';
706 while (*p && *p != separator)
708 while (*p == separator)
712 if (process_arg(prevarg, arg))
716 process_arg(arg, NULL);
719 static void parse_cmdline(int argc, char **argv)
722 char *envreal, *envcopy = NULL, *p, *arg;
724 *inname = *outname = *listname = *errname = '\0';
727 * First, process the NASMENV environment variable.
729 envreal = getenv("NASMENV");
732 envcopy = nasm_strdup(envreal);
733 process_args(envcopy);
738 * Now process the actual command line.
743 if (argv[0][0] == '@') {
744 /* We have a response file, so process this as a set of
745 * arguments like the environment variable. This allows us
746 * to have multiple arguments on a single line, which is
747 * different to the -@resp file processing below for regular
750 char *str = malloc(2048);
751 FILE *f = fopen(&argv[0][1], "r");
753 printf("out of memory");
757 while (fgets(str, 2048, f)) {
766 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
767 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &i);
769 rfile = fopen(p, "r");
771 process_respfile(rfile);
774 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
775 "unable to open response file `%s'", p);
778 i = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
779 argv += i, argc -= i;
783 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
784 "no input file specified");
786 /* Look for basic command line typos. This definitely doesn't
787 catch all errors, but it might help cases of fumbled fingers. */
788 if (!strcmp(inname, errname) || !strcmp(inname, outname) ||
789 !strcmp(inname, listname))
790 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
791 "file `%s' is both input and output file",
795 error_file = fopen(errname, "w");
797 error_file = stderr; /* Revert to default! */
798 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
799 "cannot open file `%s' for error messages",
805 /* List of directives */
807 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
808 D_EXTERN, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
810 static const char *directives[] = {
811 "", "absolute", "bits", "common", "cpu", "debug", "default",
812 "extern", "global", "list", "section", "segment", "warning"
815 static void assemble_file(char *fname)
817 char *directive, *value, *p, *q, *special, *line, debugid[80];
819 int i, rn_error, validid;
821 struct tokenval tokval;
824 int pass_cnt = 0; /* count actual passes */
826 if (cmd_sb == 32 && cmd_cpu < IF_386)
827 report_error(ERR_FATAL, "command line: "
828 "32-bit segment size requires a higher cpu");
830 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
831 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
832 for (pass = 1; pass <= pass_max && pass0 <= 2; pass++) {
836 pass1 = pass < pass_max ? 1 : 2; /* seq is 1, 1, 1,..., 1, 2 */
837 pass2 = pass > 1 ? 2 : 1; /* seq is 1, 2, 2,..., 2, 2 */
838 /* pass0 seq is 0, 0, 0,..., 1, 2 */
840 def_label = pass > 1 ? redefine_label : define_label;
842 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
846 nasmlist.init(listname, report_error);
849 global_offset_changed = FALSE; /* set by redefine_label */
850 location.segment = ofmt->section(NULL, pass2, &sb);
853 saa_rewind(forwrefs);
854 forwref = saa_rstruct(forwrefs);
856 offsets = raa_init();
858 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
861 location.known = TRUE;
862 location.offset = offs = GET_CURR_OFFS;
864 while ((line = preproc->getline())) {
867 /* here we parse our directives; this is not handled by the 'real'
870 i = getkw(&directive, &value);
875 case D_SEGMENT: /* [SEGMENT n] */
877 seg = ofmt->section(value, pass2, &sb);
879 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
880 "segment name `%s' not recognized",
884 location.segment = seg;
887 case D_EXTERN: /* [EXTERN label:special] */
889 value++; /* skip initial $ if present */
892 while (*q && *q != ':')
896 ofmt->symdef(value, 0L, 0L, 3, q);
898 } else if (pass == 1) { /* pass == 1 */
903 while (*q && *q != ':') {
909 report_error(ERR_NONFATAL,
910 "identifier expected after EXTERN");
918 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
920 pass0 = 1; /* fake pass 1 in labels.c */
921 declare_as_global(value, special,
923 define_label(value, seg_alloc(), 0L, NULL,
924 FALSE, TRUE, ofmt, report_error);
927 } /* else pass0 == 1 */
929 case D_BITS: /* [BITS bits] */
930 globalbits = sb = get_bits(value);
932 case D_GLOBAL: /* [GLOBAL symbol:special] */
934 value++; /* skip initial $ if present */
935 if (pass0 == 2) { /* pass 2 */
937 while (*q && *q != ':')
941 ofmt->symdef(value, 0L, 0L, 3, q);
943 } else if (pass2 == 1) { /* pass == 1 */
948 while (*q && *q != ':') {
954 report_error(ERR_NONFATAL,
955 "identifier expected after GLOBAL");
963 declare_as_global(value, special, report_error);
966 case D_COMMON: /* [COMMON symbol size:special] */
968 value++; /* skip initial $ if present */
974 while (*p && !isspace(*p)) {
980 report_error(ERR_NONFATAL,
981 "identifier expected after COMMON");
987 while (*p && isspace(*p))
990 while (*q && *q != ':')
997 size = readnum(p, &rn_error);
999 report_error(ERR_NONFATAL,
1000 "invalid size specified"
1001 " in COMMON declaration");
1003 define_common(value, seg_alloc(), size,
1004 special, ofmt, report_error);
1006 report_error(ERR_NONFATAL,
1007 "no size specified in"
1008 " COMMON declaration");
1009 } else if (pass0 == 2) { /* pass == 2 */
1011 while (*q && *q != ':') {
1018 ofmt->symdef(value, 0L, 0L, 3, q);
1022 case D_ABSOLUTE: /* [ABSOLUTE address] */
1024 stdscan_bufptr = value;
1025 tokval.t_type = TOKEN_INVALID;
1026 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1027 report_error, NULL);
1030 report_error(pass0 ==
1031 1 ? ERR_NONFATAL : ERR_PANIC,
1032 "cannot use non-relocatable expression as "
1033 "ABSOLUTE address");
1035 abs_seg = reloc_seg(e);
1036 abs_offset = reloc_value(e);
1038 } else if (pass == 1)
1039 abs_offset = 0x100; /* don't go near zero in case of / */
1041 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1044 location.segment = NO_SEG;
1046 case D_DEBUG: /* [DEBUG] */
1052 while (*p && !isspace(*p)) {
1059 report_error(pass == 1 ? ERR_NONFATAL : ERR_PANIC,
1060 "identifier expected after DEBUG");
1063 while (*p && isspace(*p))
1065 if (pass == pass_max)
1066 ofmt->current_dfmt->debug_directive(debugid, p);
1068 case D_WARNING: /* [WARNING {+|-}warn-name] */
1070 while (*value && isspace(*value))
1073 if (*value == '+' || *value == '-') {
1074 validid = (*value == '-') ? TRUE : FALSE;
1079 for (i = 1; i <= ERR_WARN_MAX; i++)
1080 if (!nasm_stricmp(value, suppressed_names[i]))
1082 if (i <= ERR_WARN_MAX)
1083 suppressed[i] = validid;
1085 report_error(ERR_NONFATAL,
1086 "invalid warning id in WARNING directive");
1089 case D_CPU: /* [CPU] */
1090 cpu = get_cpu(value);
1092 case D_LIST: /* [LIST {+|-}] */
1093 while (*value && isspace(*value))
1096 if (*value == '+') {
1099 if (*value == '-') {
1106 case D_DEFAULT: /* [DEFAULT] */
1108 stdscan_bufptr = value;
1109 tokval.t_type = TOKEN_INVALID;
1110 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1111 switch ((int)tokval.t_integer) {
1127 if (!ofmt->directive(directive, value, pass2))
1128 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1129 "unrecognised directive [%s]",
1133 report_error(ERR_NONFATAL,
1134 "invalid parameter to [%s] directive",
1137 } else { /* it isn't a directive */
1139 parse_line(pass1, line, &output_ins,
1140 report_error, evaluate, def_label);
1142 if (!(optimizing > 0) && pass == 2) {
1143 if (forwref != NULL && globallineno == forwref->lineno) {
1144 output_ins.forw_ref = TRUE;
1146 output_ins.oprs[forwref->operand].opflags |=
1148 forwref = saa_rstruct(forwrefs);
1149 } while (forwref != NULL
1150 && forwref->lineno == globallineno);
1152 output_ins.forw_ref = FALSE;
1155 if (!(optimizing > 0) && output_ins.forw_ref) {
1157 for (i = 0; i < output_ins.operands; i++) {
1158 if (output_ins.oprs[i].
1159 opflags & OPFLAG_FORWARD) {
1160 struct forwrefinfo *fwinf =
1161 (struct forwrefinfo *)
1162 saa_wstruct(forwrefs);
1163 fwinf->lineno = globallineno;
1167 } else { /* pass == 2 */
1169 * Hack to prevent phase error in the code
1173 * If the second operand is a forward reference,
1174 * the UNITY property of the number 1 in that
1175 * operand is cancelled. Otherwise the above
1176 * sequence will cause a phase error.
1178 * This hack means that the above code will
1179 * generate 286+ code.
1181 * The forward reference will mean that the
1182 * operand will not have the UNITY property on
1183 * the first pass, so the pass behaviours will
1187 if (output_ins.operands >= 2 &&
1188 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1189 !(IMMEDIATE & ~output_ins.oprs[1].type))
1191 /* Remove special properties bits */
1192 output_ins.oprs[1].type &= ~REG_SMASK;
1200 if (output_ins.opcode == I_EQU) {
1203 * Special `..' EQUs get processed in pass two,
1204 * except `..@' macro-processor EQUs which are done
1205 * in the normal place.
1207 if (!output_ins.label)
1208 report_error(ERR_NONFATAL,
1209 "EQU not preceded by label");
1211 else if (output_ins.label[0] != '.' ||
1212 output_ins.label[1] != '.' ||
1213 output_ins.label[2] == '@') {
1214 if (output_ins.operands == 1 &&
1215 (output_ins.oprs[0].type & IMMEDIATE) &&
1216 output_ins.oprs[0].wrt == NO_SEG) {
1219 opflags & OPFLAG_EXTERN;
1220 def_label(output_ins.label,
1221 output_ins.oprs[0].segment,
1222 output_ins.oprs[0].offset, NULL,
1225 } else if (output_ins.operands == 2
1226 && (output_ins.oprs[0].
1228 && (output_ins.oprs[0].type & COLON)
1229 && output_ins.oprs[0].segment ==
1231 && output_ins.oprs[0].wrt == NO_SEG
1232 && (output_ins.oprs[1].
1234 && output_ins.oprs[1].segment ==
1236 && output_ins.oprs[1].wrt ==
1238 def_label(output_ins.label,
1241 output_ins.oprs[1].offset, NULL,
1245 report_error(ERR_NONFATAL,
1246 "bad syntax for EQU");
1248 } else { /* pass == 2 */
1250 * Special `..' EQUs get processed here, except
1251 * `..@' macro processor EQUs which are done above.
1253 if (output_ins.label[0] == '.' &&
1254 output_ins.label[1] == '.' &&
1255 output_ins.label[2] != '@') {
1256 if (output_ins.operands == 1 &&
1257 (output_ins.oprs[0].type & IMMEDIATE)) {
1258 define_label(output_ins.label,
1259 output_ins.oprs[0].segment,
1260 output_ins.oprs[0].offset,
1261 NULL, FALSE, FALSE, ofmt,
1263 } else if (output_ins.operands == 2
1264 && (output_ins.oprs[0].
1266 && (output_ins.oprs[0].type & COLON)
1267 && output_ins.oprs[0].segment ==
1269 && (output_ins.oprs[1].
1271 && output_ins.oprs[1].segment ==
1273 define_label(output_ins.label,
1276 output_ins.oprs[1].offset,
1277 NULL, FALSE, FALSE, ofmt,
1280 report_error(ERR_NONFATAL,
1281 "bad syntax for EQU");
1284 } else { /* instruction isn't an EQU */
1288 int32_t l = insn_size(location.segment, offs, sb, cpu,
1289 &output_ins, report_error);
1291 /* if (using_debug_info) && output_ins.opcode != -1) */
1292 if (using_debug_info)
1293 { /* fbk 03/25/01 */
1294 /* this is done here so we can do debug type info */
1296 TYS_ELEMENTS(output_ins.operands);
1297 switch (output_ins.opcode) {
1300 TYS_ELEMENTS(output_ins.oprs[0].
1305 TYS_ELEMENTS(output_ins.oprs[0].
1310 TYS_ELEMENTS(output_ins.oprs[0].
1315 TYS_ELEMENTS(output_ins.oprs[0].
1320 TYS_ELEMENTS(output_ins.oprs[0].
1324 typeinfo |= TY_BYTE;
1327 typeinfo |= TY_WORD;
1330 if (output_ins.eops_float)
1331 typeinfo |= TY_FLOAT;
1333 typeinfo |= TY_DWORD;
1336 typeinfo |= TY_QWORD;
1339 typeinfo |= TY_TBYTE;
1342 typeinfo |= TY_OWORD;
1345 typeinfo = TY_LABEL;
1349 ofmt->current_dfmt->debug_typevalue(typeinfo);
1354 SET_CURR_OFFS(offs);
1357 * else l == -1 => invalid instruction, which will be
1358 * flagged as an error on pass 2
1361 } else { /* pass == 2 */
1362 offs += assemble(location.segment, offs, sb, cpu,
1363 &output_ins, ofmt, report_error,
1365 SET_CURR_OFFS(offs);
1369 cleanup_insn(&output_ins);
1372 location.offset = offs = GET_CURR_OFFS;
1373 } /* end while (line = preproc->getline... */
1375 if (pass1 == 2 && global_offset_changed)
1376 report_error(ERR_NONFATAL,
1377 "phase error detected at end of assembly.");
1380 preproc->cleanup(1);
1382 if (pass1 == 1 && terminate_after_phase) {
1390 if (pass > 1 && !global_offset_changed) {
1393 pass = pass_max - 1;
1394 } else if (!(optimizing > 0))
1397 } /* for (pass=1; pass<=2; pass++) */
1399 preproc->cleanup(0);
1402 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1404 "info:: assembly required 1+%d+1 passes\n", pass_cnt - 2);
1406 } /* exit from assemble_file (...) */
1408 static int getkw(char **directive, char **value)
1414 /* allow leading spaces or tabs */
1415 while (*buf == ' ' || *buf == '\t')
1423 while (*p && *p != ']')
1431 while (*p && *p != ';') {
1438 *directive = p = buf + 1;
1439 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1446 while (isspace(*buf))
1447 buf++; /* beppu - skip leading whitespace */
1454 return bsii(*directive, directives, elements(directives));
1458 * gnu style error reporting
1459 * This function prints an error message to error_file in the
1460 * style used by GNU. An example would be:
1461 * file.asm:50: error: blah blah blah
1462 * where file.asm is the name of the file, 50 is the line number on
1463 * which the error occurs (or is detected) and "error:" is one of
1464 * the possible optional diagnostics -- it can be "error" or "warning"
1465 * or something else. Finally the line terminates with the actual
1468 * @param severity the severity of the warning or error
1469 * @param fmt the printf style format string
1471 static void report_error_gnu(int severity, const char *fmt, ...)
1475 if (is_suppressed_warning(severity))
1478 if (severity & ERR_NOFILE)
1479 fputs("nasm: ", error_file);
1481 char *currentfile = NULL;
1483 src_get(&lineno, ¤tfile);
1484 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1485 nasm_free(currentfile);
1488 report_error_common(severity, fmt, ap);
1493 * MS style error reporting
1494 * This function prints an error message to error_file in the
1495 * style used by Visual C and some other Microsoft tools. An example
1497 * file.asm(50) : error: blah blah blah
1498 * where file.asm is the name of the file, 50 is the line number on
1499 * which the error occurs (or is detected) and "error:" is one of
1500 * the possible optional diagnostics -- it can be "error" or "warning"
1501 * or something else. Finally the line terminates with the actual
1504 * @param severity the severity of the warning or error
1505 * @param fmt the printf style format string
1507 static void report_error_vc(int severity, const char *fmt, ...)
1511 if (is_suppressed_warning(severity))
1514 if (severity & ERR_NOFILE)
1515 fputs("nasm: ", error_file);
1517 char *currentfile = NULL;
1519 src_get(&lineno, ¤tfile);
1520 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1521 nasm_free(currentfile);
1524 report_error_common(severity, fmt, ap);
1529 * check for supressed warning
1530 * checks for suppressed warning or pass one only warning and we're
1533 * @param severity the severity of the warning or error
1534 * @return true if we should abort error/warning printing
1536 static int is_suppressed_warning(int severity)
1539 * See if it's a suppressed warning.
1541 return ((severity & ERR_MASK) == ERR_WARNING &&
1542 (severity & ERR_WARN_MASK) != 0 &&
1543 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1545 * See if it's a pass-one only warning and we're not in pass one.
1547 ((severity & ERR_PASS1) && pass0 == 2);
1551 * common error reporting
1552 * This is the common back end of the error reporting schemes currently
1553 * implemented. It prints the nature of the warning and then the
1554 * specific error message to error_file and may or may not return. It
1555 * doesn't return if the error severity is a "panic" or "debug" type.
1557 * @param severity the severity of the warning or error
1558 * @param fmt the printf style format string
1560 static void report_error_common(int severity, const char *fmt,
1563 switch (severity & ERR_MASK) {
1565 fputs("warning: ", error_file);
1568 fputs("error: ", error_file);
1571 fputs("fatal: ", error_file);
1574 fputs("panic: ", error_file);
1577 fputs("debug: ", error_file);
1581 vfprintf(error_file, fmt, args);
1582 fputc('\n', error_file);
1584 if (severity & ERR_USAGE)
1587 switch (severity & ERR_MASK) {
1590 /* no further action, by definition */
1593 /* hack enables listing(!) on errors */
1594 terminate_after_phase = TRUE;
1603 exit(1); /* instantly die */
1604 break; /* placate silly compilers */
1607 /* abort(); *//* halt, catch fire, and dump core */
1613 static void usage(void)
1615 fputs("type `nasm -h' for help\n", error_file);
1618 static void register_output_formats(void)
1620 ofmt = ofmt_register(report_error);
1623 #define BUF_DELTA 512
1625 static FILE *no_pp_fp;
1626 static efunc no_pp_err;
1627 static ListGen *no_pp_list;
1628 static int32_t no_pp_lineinc;
1630 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1633 src_set_fname(nasm_strdup(file));
1637 no_pp_fp = fopen(file, "r");
1639 no_pp_err(ERR_FATAL | ERR_NOFILE,
1640 "unable to open input file `%s'", file);
1641 no_pp_list = listgen;
1642 (void)pass; /* placate compilers */
1643 (void)eval; /* placate compilers */
1646 static char *no_pp_getline(void)
1648 char *buffer, *p, *q;
1651 bufsize = BUF_DELTA;
1652 buffer = nasm_malloc(BUF_DELTA);
1653 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1655 while (1) { /* Loop to handle %line */
1658 while (1) { /* Loop to handle long lines */
1659 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
1663 if (p > buffer && p[-1] == '\n')
1665 if (p - buffer > bufsize - 10) {
1667 offset = p - buffer;
1668 bufsize += BUF_DELTA;
1669 buffer = nasm_realloc(buffer, bufsize);
1670 p = buffer + offset;
1674 if (!q && p == buffer) {
1680 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1681 * them are present at the end of the line.
1683 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1685 if (!nasm_strnicmp(buffer, "%line", 5)) {
1688 char *nm = nasm_malloc(strlen(buffer));
1689 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
1690 nasm_free(src_set_fname(nm));
1700 no_pp_list->line(LIST_READ, buffer);
1705 static void no_pp_cleanup(int pass)
1707 (void)pass; /* placate GCC */
1711 static uint32_t get_cpu(char *value)
1714 if (!strcmp(value, "8086"))
1716 if (!strcmp(value, "186"))
1718 if (!strcmp(value, "286"))
1720 if (!strcmp(value, "386"))
1722 if (!strcmp(value, "486"))
1724 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
1726 if (!strcmp(value, "686") ||
1727 !nasm_stricmp(value, "ppro") ||
1728 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
1730 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
1732 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
1733 !nasm_stricmp(value, "willamette"))
1734 return IF_WILLAMETTE;
1735 if (!nasm_stricmp(value, "prescott"))
1737 if (!nasm_stricmp(value, "x64") ||
1738 !nasm_stricmp(value, "x86-64"))
1740 if (!nasm_stricmp(value, "ia64") ||
1741 !nasm_stricmp(value, "ia-64") ||
1742 !nasm_stricmp(value, "itanium") ||
1743 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
1746 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1747 "unknown 'cpu' type");
1749 return IF_PLEVEL; /* the maximum level */
1752 static int get_bits(char *value)
1756 if ((i = atoi(value)) == 16)
1757 return i; /* set for a 16-bit segment */
1760 report_error(ERR_NONFATAL,
1761 "cannot specify 32-bit segment on processor below a 386");
1764 } else if (i == 64) {
1765 if (cpu < IF_X86_64) {
1766 report_error(ERR_NONFATAL,
1767 "cannot specify 64-bit segment on processor below an x86-64");
1771 report_error(ERR_NONFATAL,
1772 "%s output format does not support 64-bit code",
1777 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1778 "`%s' is not a valid segment size; must be 16, 32 or 64",