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.
28 struct forwrefinfo { /* info held on forward refs. */
33 static int get_bits(char *value);
34 static uint32_t get_cpu(char *cpu_str);
35 static void parse_cmdline(int, char **);
36 static void assemble_file(char *);
37 static int getkw(char **directive, char **value);
38 static void register_output_formats(void);
39 static void report_error_gnu(int severity, const char *fmt, ...);
40 static void report_error_vc(int severity, const char *fmt, ...);
41 static void report_error_common(int severity, const char *fmt,
43 static int is_suppressed_warning(int severity);
44 static void usage(void);
45 static efunc report_error;
47 static int using_debug_info, opt_verbose_info;
48 int tasm_compatible_mode = FALSE;
53 static char inname[FILENAME_MAX];
54 static char outname[FILENAME_MAX];
55 static char listname[FILENAME_MAX];
56 static char errname[FILENAME_MAX];
57 static int globallineno; /* for forward-reference tracking */
58 /* static int pass = 0; */
59 static struct ofmt *ofmt = NULL;
61 static FILE *error_file; /* Where to write error messages */
63 static FILE *ofile = NULL;
64 int optimizing = -1; /* number of optimization passes to take */
65 static int sb, cmd_sb = 16; /* by default */
66 static uint32_t cmd_cpu = IF_PLEVEL; /* highest level by default */
67 static uint32_t cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
68 int global_offset_changed; /* referenced in labels.c */
70 static loc_t location;
71 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
72 int32_t abs_seg; /* ABSOLUTE segment basis */
73 int32_t abs_offset; /* ABSOLUTE offset */
75 static struct RAA *offsets;
77 static struct SAA *forwrefs; /* keep track of forward references */
78 static struct forwrefinfo *forwref;
80 static Preproc *preproc;
82 op_normal, /* Preprocess and assemble */
83 op_preprocess, /* Preprocess only */
84 op_depend, /* Generate dependencies */
85 op_depend_missing_ok, /* Generate dependencies, missing OK */
87 static enum op_type operating_mode;
90 * Which of the suppressible warnings are suppressed. Entry zero
91 * doesn't do anything. Initial defaults are given here.
93 static char suppressed[1 + ERR_WARN_MAX] = {
94 0, TRUE, TRUE, TRUE, FALSE, TRUE
98 * The option names for the suppressible warnings. As before, entry
101 static const char *suppressed_names[1 + ERR_WARN_MAX] = {
102 NULL, "macro-params", "macro-selfref", "orphan-labels",
108 * The explanations for the suppressible warnings. As before, entry
111 static const char *suppressed_what[1 + ERR_WARN_MAX] = {
113 "macro calls with wrong no. of params",
114 "cyclic macro self-references",
115 "labels alone on lines without trailing `:'",
116 "numeric constants greater than 0xFFFFFFFF",
117 "using 8- or 16-bit relocation in ELF, a GNU extension"
121 * This is a null preprocessor which just copies lines from input
122 * to output. It's used when someone explicitly requests that NASM
123 * not preprocess their source file.
126 static void no_pp_reset(char *, int, efunc, evalfunc, ListGen *);
127 static char *no_pp_getline(void);
128 static void no_pp_cleanup(int);
129 static Preproc no_pp = {
136 * get/set current offset...
138 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
139 raa_read(offsets,location.segment))
140 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
141 (void)(offsets=raa_write(offsets,location.segment,(x))))
143 static int want_usage;
144 static int terminate_after_phase;
145 int user_nolist = 0; /* fbk 9/2/00 */
147 static void nasm_fputs(const char *line, FILE * outfile)
150 fputs(line, outfile);
151 fputc('\n', outfile);
156 int main(int argc, char **argv)
159 want_usage = terminate_after_phase = FALSE;
160 report_error = report_error_gnu;
164 nasm_set_malloc_error(report_error);
165 offsets = raa_init();
166 forwrefs = saa_init((int32_t)sizeof(struct forwrefinfo));
169 operating_mode = op_normal;
173 register_output_formats();
175 parse_cmdline(argc, argv);
177 if (terminate_after_phase) {
183 /* If debugging info is disabled, suppress any debug calls */
184 if (!using_debug_info)
185 ofmt->current_dfmt = &null_debug_form;
188 pp_extra_stdmac(ofmt->stdmac);
189 parser_global_info(ofmt, &location);
190 eval_global_info(ofmt, lookup_label, &location);
192 /* define some macros dependent of command-line */
195 snprintf(temp, sizeof(temp), "__OUTPUT_FORMAT__=%s\n",
200 switch (operating_mode) {
201 case op_depend_missing_ok:
202 pp_include_path(NULL); /* "assume generated" */
207 preproc->reset(inname, 0, report_error, evaluate, &nasmlist);
208 if (outname[0] == '\0')
209 ofmt->filename(inname, outname, report_error);
211 fprintf(stdout, "%s: %s", outname, inname);
212 while ((line = preproc->getline()))
222 char *file_name = NULL;
223 int32_t prior_linnum = 0;
227 ofile = fopen(outname, "w");
229 report_error(ERR_FATAL | ERR_NOFILE,
230 "unable to open output file `%s'",
235 location.known = FALSE;
238 preproc->reset(inname, 2, report_error, evaluate, &nasmlist);
239 while ((line = preproc->getline())) {
241 * We generate %line directives if needed for later programs
243 int32_t linnum = prior_linnum += lineinc;
244 int altline = src_get(&linnum, &file_name);
246 if (altline == 1 && lineinc == 1)
247 nasm_fputs("", ofile);
249 lineinc = (altline != -1 || lineinc != 1);
250 fprintf(ofile ? ofile : stdout,
251 "%%line %"PRId32"+%d %s\n", linnum, lineinc,
254 prior_linnum = linnum;
256 nasm_fputs(line, ofile);
259 nasm_free(file_name);
263 if (ofile && terminate_after_phase)
271 * We must call ofmt->filename _anyway_, even if the user
272 * has specified their own output file, because some
273 * formats (eg OBJ and COFF) use ofmt->filename to find out
274 * the name of the input file and then put that inside the
277 ofmt->filename(inname, outname, report_error);
279 ofile = fopen(outname, "wb");
281 report_error(ERR_FATAL | ERR_NOFILE,
282 "unable to open output file `%s'", outname);
286 * We must call init_labels() before ofmt->init() since
287 * some object formats will want to define labels in their
288 * init routines. (eg OS/2 defines the FLAT group)
292 ofmt->init(ofile, report_error, define_label, evaluate);
294 assemble_file(inname);
296 if (!terminate_after_phase) {
297 ofmt->cleanup(using_debug_info);
301 * We had an fclose on the output file here, but we
302 * actually do that in all the object file drivers as well,
303 * so we're leaving out the one here.
322 if (terminate_after_phase)
329 * Get a parameter for a command line option.
330 * First arg must be in the form of e.g. -f...
332 static char *get_param(char *p, char *q, int *advance)
335 if (p[2]) { /* the parameter's in the option */
345 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
346 "option `-%c' requires an argument", p[1]);
356 #define OPT_POSTFIX 1
357 struct textargs textopts[] = {
358 {"prefix", OPT_PREFIX},
359 {"postfix", OPT_POSTFIX},
364 static int process_arg(char *p, char *q)
372 if (p[0] == '-' && !stopoptions) {
377 case 'o': /* these parameters take values */
392 if (!(param = get_param(p, q, &advance)))
394 if (p[1] == 'o') { /* output file */
395 strcpy(outname, param);
396 } else if (p[1] == 'f') { /* output format */
397 ofmt = ofmt_find(param);
399 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
400 "unrecognised output format `%s' - "
401 "use -hf for a list", param);
403 ofmt->current_dfmt = ofmt->debug_formats[0];
404 } else if (p[1] == 'O') { /* Optimization level */
408 if (isdigit(*param)) {
410 while (isdigit(*++param)) ;
412 optimizing = -1; /* 0.98 behaviour */
414 optimizing = 0; /* Two passes, 0.98.09 behavior */
416 /* The optimizer seems to have problems with
417 < 5 passes? Hidden bug? */
418 optimizing = 5; /* 5 passes */
420 optimizing = opt; /* More than 5 passes */
422 if (*param == 'v' || *param == '+') {
424 opt_verbose_info = TRUE;
426 } else { /* garbage */
431 } /* while (*param) */
433 report_error(ERR_FATAL,
434 "command line optimization level must be 'v', 0..3 or <nn>");
435 } else if (p[1] == 'P' || p[1] == 'p') { /* pre-include */
436 pp_pre_include(param);
437 } else if (p[1] == 'D' || p[1] == 'd') { /* pre-define */
438 pp_pre_define(param);
439 } else if (p[1] == 'U' || p[1] == 'u') { /* un-define */
440 pp_pre_undefine(param);
441 } else if (p[1] == 'I' || p[1] == 'i') { /* include search path */
442 pp_include_path(param);
443 } else if (p[1] == 'l') { /* listing file */
444 strcpy(listname, param);
445 } else if (p[1] == 'Z') { /* error messages file */
446 strcpy(errname, param);
447 } else if (p[1] == 'F') { /* specify debug format */
448 ofmt->current_dfmt = dfmt_find(ofmt, param);
449 if (!ofmt->current_dfmt) {
450 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
451 "unrecognized debug format `%s' for"
452 " output format `%s'",
453 param, ofmt->shortname);
455 } else if (p[1] == 'X') { /* specify error reporting format */
456 if (nasm_stricmp("vc", param) == 0)
457 report_error = report_error_vc;
458 else if (nasm_stricmp("gnu", param) == 0)
459 report_error = report_error_gnu;
461 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
462 "unrecognized error reporting format `%s'",
467 using_debug_info = TRUE;
471 ("usage: nasm [-@ response file] [-o outfile] [-f format] "
473 " [options...] [--] filename\n"
474 " or nasm -v for version info\n\n"
475 " -t assemble in SciTech TASM compatible mode\n"
476 " -g generate debug information in selected format.\n");
478 (" -E (or -e) preprocess only (writes output to stdout by default)\n"
479 " -a don't preprocess (assemble only)\n"
480 " -M generate Makefile dependencies on stdout\n"
481 " -MG d:o, missing files assumed generated\n\n"
482 " -Z<file> redirect error messages to file\n"
483 " -s redirect error messages to stdout\n\n"
484 " -F format select a debugging format\n\n"
485 " -I<path> adds a pathname to the include file path\n");
487 (" -O<digit> optimize branch offsets (-O0 disables, default)\n"
488 " -P<file> pre-includes a file\n"
489 " -D<macro>[=<value>] pre-defines a macro\n"
490 " -U<macro> undefines a macro\n"
491 " -X<format> specifies error reporting format (gnu or vc)\n"
492 " -w+foo enables warnings about foo; -w-foo disables them\n"
493 "where foo can be:\n");
494 for (i = 1; i <= ERR_WARN_MAX; i++)
495 printf(" %-23s %s (default %s)\n",
496 suppressed_names[i], suppressed_what[i],
497 suppressed[i] ? "off" : "on");
499 ("\nresponse files should contain command line parameters"
500 ", one per line.\n");
502 printf("\nvalid output formats for -f are"
503 " (`*' denotes default):\n");
504 ofmt_list(ofmt, stdout);
506 printf("\nFor a list of valid output formats, use -hf.\n");
507 printf("For a list of debug formats, use -f <form> -y.\n");
509 exit(0); /* never need usage message here */
512 printf("\nvalid debug formats for '%s' output format are"
513 " ('*' denotes default):\n", ofmt->shortname);
514 dfmt_list(ofmt, stdout);
518 tasm_compatible_mode = TRUE;
522 const char *nasm_version_string =
523 "NASM version " NASM_VER " compiled on " __DATE__
528 puts(nasm_version_string);
529 exit(0); /* never need usage message here */
532 case 'e': /* preprocess only */
534 operating_mode = op_preprocess;
536 case 'a': /* assemble only - don't preprocess */
540 if (p[2] != '+' && p[2] != '-') {
541 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
542 "invalid option to `-w'");
544 for (i = 1; i <= ERR_WARN_MAX; i++)
545 if (!nasm_stricmp(p + 3, suppressed_names[i]))
547 if (i <= ERR_WARN_MAX)
548 suppressed[i] = (p[2] == '-');
550 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
551 "invalid option to `-w'");
555 operating_mode = p[2] == 'G' ? op_depend_missing_ok : op_depend;
562 if (p[2] == 0) { /* -- => stop processing options */
566 for (s = 0; textopts[s].label; s++) {
567 if (!nasm_stricmp(p + 2, textopts[s].label)) {
578 report_error(ERR_NONFATAL | ERR_NOFILE |
580 "option `--%s' requires an argument",
584 advance = 1, param = q;
587 if (s == OPT_PREFIX) {
588 strncpy(lprefix, param, PREFIX_MAX - 1);
589 lprefix[PREFIX_MAX - 1] = 0;
592 if (s == OPT_POSTFIX) {
593 strncpy(lpostfix, param, POSTFIX_MAX - 1);
594 lpostfix[POSTFIX_MAX - 1] = 0;
601 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
602 "unrecognised option `--%s'", p + 2);
610 if (!ofmt->setinfo(GI_SWITCH, &p))
611 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
612 "unrecognised option `-%c'", p[1]);
617 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
618 "more than one input file specified");
626 #define ARG_BUF_DELTA 128
628 static void process_respfile(FILE * rfile)
630 char *buffer, *p, *q, *prevarg;
631 int bufsize, prevargsize;
633 bufsize = prevargsize = ARG_BUF_DELTA;
634 buffer = nasm_malloc(ARG_BUF_DELTA);
635 prevarg = nasm_malloc(ARG_BUF_DELTA);
638 while (1) { /* Loop to handle all lines in file */
641 while (1) { /* Loop to handle long lines */
642 q = fgets(p, bufsize - (p - buffer), rfile);
646 if (p > buffer && p[-1] == '\n')
648 if (p - buffer > bufsize - 10) {
651 bufsize += ARG_BUF_DELTA;
652 buffer = nasm_realloc(buffer, bufsize);
657 if (!q && p == buffer) {
659 process_arg(prevarg, NULL);
666 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
667 * them are present at the end of the line.
669 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
671 while (p > buffer && isspace(p[-1]))
678 if (process_arg(prevarg, p))
681 if (strlen(p) > prevargsize - 10) {
682 prevargsize += ARG_BUF_DELTA;
683 prevarg = nasm_realloc(prevarg, prevargsize);
689 /* Function to process args from a string of args, rather than the
690 * argv array. Used by the environment variable and response file
693 static void process_args(char *args)
695 char *p, *q, *arg, *prevarg;
696 char separator = ' ';
704 while (*p && *p != separator)
706 while (*p == separator)
710 if (process_arg(prevarg, arg))
714 process_arg(arg, NULL);
717 static void parse_cmdline(int argc, char **argv)
720 char *envreal, *envcopy = NULL, *p, *arg;
722 *inname = *outname = *listname = *errname = '\0';
725 * First, process the NASMENV environment variable.
727 envreal = getenv("NASMENV");
730 envcopy = nasm_strdup(envreal);
731 process_args(envcopy);
736 * Now process the actual command line.
741 if (argv[0][0] == '@') {
742 /* We have a response file, so process this as a set of
743 * arguments like the environment variable. This allows us
744 * to have multiple arguments on a single line, which is
745 * different to the -@resp file processing below for regular
748 char *str = malloc(2048);
749 FILE *f = fopen(&argv[0][1], "r");
751 printf("out of memory");
755 while (fgets(str, 2048, f)) {
764 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
765 p = get_param(argv[0], argc > 1 ? argv[1] : NULL, &i);
767 rfile = fopen(p, "r");
769 process_respfile(rfile);
772 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
773 "unable to open response file `%s'", p);
776 i = process_arg(argv[0], argc > 1 ? argv[1] : NULL);
777 argv += i, argc -= i;
781 report_error(ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
782 "no input file specified");
785 error_file = fopen(errname, "w");
787 error_file = stderr; /* Revert to default! */
788 report_error(ERR_FATAL | ERR_NOFILE | ERR_USAGE,
789 "cannot open file `%s' for error messages",
796 /* List of directives */
798 D_NONE, D_ABSOLUTE, D_BITS, D_COMMON, D_CPU, D_DEBUG, D_DEFAULT,
799 D_EXTERN, D_GLOBAL, D_LIST, D_SECTION, D_SEGMENT, D_WARNING
801 static const char *directives[] = {
802 "", "absolute", "bits", "common", "cpu", "debug", "default",
803 "extern", "global", "list", "section", "segment", "warning"
806 static void assemble_file(char *fname)
808 char *directive, *value, *p, *q, *special, *line, debugid[80];
810 int i, rn_error, validid;
812 struct tokenval tokval;
815 int pass_cnt = 0; /* count actual passes */
817 if (cmd_sb == 32 && cmd_cpu < IF_386)
818 report_error(ERR_FATAL, "command line: "
819 "32-bit segment size requires a higher cpu");
821 pass_max = (optimizing > 0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
822 pass0 = !(optimizing > 0); /* start at 1 if not optimizing */
823 for (pass = 1; pass <= pass_max && pass0 <= 2; pass++) {
827 pass1 = pass < pass_max ? 1 : 2; /* seq is 1, 1, 1,..., 1, 2 */
828 pass2 = pass > 1 ? 2 : 1; /* seq is 1, 2, 2,..., 2, 2 */
829 /* pass0 seq is 0, 0, 0,..., 1, 2 */
831 def_label = pass > 1 ? redefine_label : define_label;
833 globalbits = sb = cmd_sb; /* set 'bits' to command line default */
837 nasmlist.init(listname, report_error);
840 global_offset_changed = FALSE; /* set by redefine_label */
841 location.segment = ofmt->section(NULL, pass2, &sb);
844 saa_rewind(forwrefs);
845 forwref = saa_rstruct(forwrefs);
847 offsets = raa_init();
849 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
852 location.known = TRUE;
853 location.offset = offs = GET_CURR_OFFS;
855 while ((line = preproc->getline())) {
858 /* here we parse our directives; this is not handled by the 'real'
861 i = getkw(&directive, &value);
866 case D_SEGMENT: /* [SEGMENT n] */
868 seg = ofmt->section(value, pass2, &sb);
870 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
871 "segment name `%s' not recognized",
875 location.segment = seg;
878 case D_EXTERN: /* [EXTERN label:special] */
880 value++; /* skip initial $ if present */
883 while (*q && *q != ':')
887 ofmt->symdef(value, 0L, 0L, 3, q);
889 } else if (pass == 1) { /* pass == 1 */
894 while (*q && *q != ':') {
900 report_error(ERR_NONFATAL,
901 "identifier expected after EXTERN");
909 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
911 pass0 = 1; /* fake pass 1 in labels.c */
912 declare_as_global(value, special,
914 define_label(value, seg_alloc(), 0L, NULL,
915 FALSE, TRUE, ofmt, report_error);
918 } /* else pass0 == 1 */
920 case D_BITS: /* [BITS bits] */
921 globalbits = sb = get_bits(value);
923 case D_GLOBAL: /* [GLOBAL symbol:special] */
925 value++; /* skip initial $ if present */
926 if (pass0 == 2) { /* pass 2 */
928 while (*q && *q != ':')
932 ofmt->symdef(value, 0L, 0L, 3, q);
934 } else if (pass2 == 1) { /* pass == 1 */
939 while (*q && *q != ':') {
945 report_error(ERR_NONFATAL,
946 "identifier expected after GLOBAL");
954 declare_as_global(value, special, report_error);
957 case D_COMMON: /* [COMMON symbol size:special] */
959 value++; /* skip initial $ if present */
965 while (*p && !isspace(*p)) {
971 report_error(ERR_NONFATAL,
972 "identifier expected after COMMON");
978 while (*p && isspace(*p))
981 while (*q && *q != ':')
988 size = readnum(p, &rn_error);
990 report_error(ERR_NONFATAL,
991 "invalid size specified"
992 " in COMMON declaration");
994 define_common(value, seg_alloc(), size,
995 special, ofmt, report_error);
997 report_error(ERR_NONFATAL,
998 "no size specified in"
999 " COMMON declaration");
1000 } else if (pass0 == 2) { /* pass == 2 */
1002 while (*q && *q != ':') {
1009 ofmt->symdef(value, 0L, 0L, 3, q);
1013 case D_ABSOLUTE: /* [ABSOLUTE address] */
1015 stdscan_bufptr = value;
1016 tokval.t_type = TOKEN_INVALID;
1017 e = evaluate(stdscan, NULL, &tokval, NULL, pass2,
1018 report_error, NULL);
1021 report_error(pass0 ==
1022 1 ? ERR_NONFATAL : ERR_PANIC,
1023 "cannot use non-relocatable expression as "
1024 "ABSOLUTE address");
1026 abs_seg = reloc_seg(e);
1027 abs_offset = reloc_value(e);
1029 } else if (pass == 1)
1030 abs_offset = 0x100; /* don't go near zero in case of / */
1032 report_error(ERR_PANIC, "invalid ABSOLUTE address "
1035 location.segment = NO_SEG;
1037 case D_DEBUG: /* [DEBUG] */
1043 while (*p && !isspace(*p)) {
1050 report_error(pass == 1 ? ERR_NONFATAL : ERR_PANIC,
1051 "identifier expected after DEBUG");
1054 while (*p && isspace(*p))
1056 if (pass == pass_max)
1057 ofmt->current_dfmt->debug_directive(debugid, p);
1059 case D_WARNING: /* [WARNING {+|-}warn-name] */
1061 while (*value && isspace(*value))
1064 if (*value == '+' || *value == '-') {
1065 validid = (*value == '-') ? TRUE : FALSE;
1070 for (i = 1; i <= ERR_WARN_MAX; i++)
1071 if (!nasm_stricmp(value, suppressed_names[i]))
1073 if (i <= ERR_WARN_MAX)
1074 suppressed[i] = validid;
1076 report_error(ERR_NONFATAL,
1077 "invalid warning id in WARNING directive");
1080 case D_CPU: /* [CPU] */
1081 cpu = get_cpu(value);
1083 case D_LIST: /* [LIST {+|-}] */
1084 while (*value && isspace(*value))
1087 if (*value == '+') {
1090 if (*value == '-') {
1097 case D_DEFAULT: /* [DEFAULT] */
1099 stdscan_bufptr = value;
1100 tokval.t_type = TOKEN_INVALID;
1101 if (stdscan(NULL, &tokval) == TOKEN_SPECIAL) {
1102 switch ((int)tokval.t_integer) {
1118 if (!ofmt->directive(directive, value, pass2))
1119 report_error(pass1 == 1 ? ERR_NONFATAL : ERR_PANIC,
1120 "unrecognised directive [%s]",
1124 report_error(ERR_NONFATAL,
1125 "invalid parameter to [%s] directive",
1128 } else { /* it isn't a directive */
1130 parse_line(pass1, line, &output_ins,
1131 report_error, evaluate, def_label);
1133 if (!(optimizing > 0) && pass == 2) {
1134 if (forwref != NULL && globallineno == forwref->lineno) {
1135 output_ins.forw_ref = TRUE;
1137 output_ins.oprs[forwref->operand].opflags |=
1139 forwref = saa_rstruct(forwrefs);
1140 } while (forwref != NULL
1141 && forwref->lineno == globallineno);
1143 output_ins.forw_ref = FALSE;
1146 if (!(optimizing > 0) && output_ins.forw_ref) {
1148 for (i = 0; i < output_ins.operands; i++) {
1149 if (output_ins.oprs[i].
1150 opflags & OPFLAG_FORWARD) {
1151 struct forwrefinfo *fwinf =
1152 (struct forwrefinfo *)
1153 saa_wstruct(forwrefs);
1154 fwinf->lineno = globallineno;
1158 } else { /* pass == 2 */
1160 * Hack to prevent phase error in the code
1164 * If the second operand is a forward reference,
1165 * the UNITY property of the number 1 in that
1166 * operand is cancelled. Otherwise the above
1167 * sequence will cause a phase error.
1169 * This hack means that the above code will
1170 * generate 286+ code.
1172 * The forward reference will mean that the
1173 * operand will not have the UNITY property on
1174 * the first pass, so the pass behaviours will
1178 if (output_ins.operands >= 2 &&
1179 (output_ins.oprs[1].opflags & OPFLAG_FORWARD) &&
1180 !(IMMEDIATE & ~output_ins.oprs[1].type))
1182 /* Remove special properties bits */
1183 output_ins.oprs[1].type &= ~REG_SMASK;
1191 if (output_ins.opcode == I_EQU) {
1194 * Special `..' EQUs get processed in pass two,
1195 * except `..@' macro-processor EQUs which are done
1196 * in the normal place.
1198 if (!output_ins.label)
1199 report_error(ERR_NONFATAL,
1200 "EQU not preceded by label");
1202 else if (output_ins.label[0] != '.' ||
1203 output_ins.label[1] != '.' ||
1204 output_ins.label[2] == '@') {
1205 if (output_ins.operands == 1 &&
1206 (output_ins.oprs[0].type & IMMEDIATE) &&
1207 output_ins.oprs[0].wrt == NO_SEG) {
1210 opflags & OPFLAG_EXTERN;
1211 def_label(output_ins.label,
1212 output_ins.oprs[0].segment,
1213 output_ins.oprs[0].offset, NULL,
1216 } else if (output_ins.operands == 2
1217 && (output_ins.oprs[0].
1219 && (output_ins.oprs[0].type & COLON)
1220 && output_ins.oprs[0].segment ==
1222 && output_ins.oprs[0].wrt == NO_SEG
1223 && (output_ins.oprs[1].
1225 && output_ins.oprs[1].segment ==
1227 && output_ins.oprs[1].wrt ==
1229 def_label(output_ins.label,
1232 output_ins.oprs[1].offset, NULL,
1236 report_error(ERR_NONFATAL,
1237 "bad syntax for EQU");
1239 } else { /* pass == 2 */
1241 * Special `..' EQUs get processed here, except
1242 * `..@' macro processor EQUs which are done above.
1244 if (output_ins.label[0] == '.' &&
1245 output_ins.label[1] == '.' &&
1246 output_ins.label[2] != '@') {
1247 if (output_ins.operands == 1 &&
1248 (output_ins.oprs[0].type & IMMEDIATE)) {
1249 define_label(output_ins.label,
1250 output_ins.oprs[0].segment,
1251 output_ins.oprs[0].offset,
1252 NULL, FALSE, FALSE, ofmt,
1254 } else if (output_ins.operands == 2
1255 && (output_ins.oprs[0].
1257 && (output_ins.oprs[0].type & COLON)
1258 && output_ins.oprs[0].segment ==
1260 && (output_ins.oprs[1].
1262 && output_ins.oprs[1].segment ==
1264 define_label(output_ins.label,
1267 output_ins.oprs[1].offset,
1268 NULL, FALSE, FALSE, ofmt,
1271 report_error(ERR_NONFATAL,
1272 "bad syntax for EQU");
1275 } else { /* instruction isn't an EQU */
1279 int32_t l = insn_size(location.segment, offs, sb, cpu,
1280 &output_ins, report_error);
1282 /* if (using_debug_info) && output_ins.opcode != -1) */
1283 if (using_debug_info)
1284 { /* fbk 03/25/01 */
1285 /* this is done here so we can do debug type info */
1287 TYS_ELEMENTS(output_ins.operands);
1288 switch (output_ins.opcode) {
1291 TYS_ELEMENTS(output_ins.oprs[0].
1296 TYS_ELEMENTS(output_ins.oprs[0].
1301 TYS_ELEMENTS(output_ins.oprs[0].
1306 TYS_ELEMENTS(output_ins.oprs[0].
1311 TYS_ELEMENTS(output_ins.oprs[0].
1315 typeinfo |= TY_BYTE;
1318 typeinfo |= TY_WORD;
1321 if (output_ins.eops_float)
1322 typeinfo |= TY_FLOAT;
1324 typeinfo |= TY_DWORD;
1327 typeinfo |= TY_QWORD;
1330 typeinfo |= TY_TBYTE;
1333 typeinfo |= TY_OWORD;
1336 typeinfo = TY_LABEL;
1340 ofmt->current_dfmt->debug_typevalue(typeinfo);
1345 SET_CURR_OFFS(offs);
1348 * else l == -1 => invalid instruction, which will be
1349 * flagged as an error on pass 2
1352 } else { /* pass == 2 */
1353 offs += assemble(location.segment, offs, sb, cpu,
1354 &output_ins, ofmt, report_error,
1356 SET_CURR_OFFS(offs);
1360 cleanup_insn(&output_ins);
1363 location.offset = offs = GET_CURR_OFFS;
1364 } /* end while (line = preproc->getline... */
1366 if (pass1 == 2 && global_offset_changed)
1367 report_error(ERR_NONFATAL,
1368 "phase error detected at end of assembly.");
1371 preproc->cleanup(1);
1373 if (pass1 == 1 && terminate_after_phase) {
1381 if (pass > 1 && !global_offset_changed) {
1384 pass = pass_max - 1;
1385 } else if (!(optimizing > 0))
1388 } /* for (pass=1; pass<=2; pass++) */
1390 preproc->cleanup(0);
1393 if (optimizing > 0 && opt_verbose_info) /* -On and -Ov switches */
1395 "info:: assembly required 1+%d+1 passes\n", pass_cnt - 2);
1397 } /* exit from assemble_file (...) */
1399 static int getkw(char **directive, char **value)
1405 /* allow leading spaces or tabs */
1406 while (*buf == ' ' || *buf == '\t')
1414 while (*p && *p != ']')
1422 while (*p && *p != ';') {
1429 *directive = p = buf + 1;
1430 while (*buf && *buf != ' ' && *buf != ']' && *buf != '\t')
1437 while (isspace(*buf))
1438 buf++; /* beppu - skip leading whitespace */
1445 return bsii(*directive, directives, elements(directives));
1449 * gnu style error reporting
1450 * This function prints an error message to error_file in the
1451 * style used by GNU. An example would be:
1452 * file.asm:50: error: blah blah blah
1453 * where file.asm is the name of the file, 50 is the line number on
1454 * which the error occurs (or is detected) and "error:" is one of
1455 * the possible optional diagnostics -- it can be "error" or "warning"
1456 * or something else. Finally the line terminates with the actual
1459 * @param severity the severity of the warning or error
1460 * @param fmt the printf style format string
1462 static void report_error_gnu(int severity, const char *fmt, ...)
1466 if (is_suppressed_warning(severity))
1469 if (severity & ERR_NOFILE)
1470 fputs("nasm: ", error_file);
1472 char *currentfile = NULL;
1474 src_get(&lineno, ¤tfile);
1475 fprintf(error_file, "%s:%"PRId32": ", currentfile, lineno);
1476 nasm_free(currentfile);
1479 report_error_common(severity, fmt, ap);
1484 * MS style error reporting
1485 * This function prints an error message to error_file in the
1486 * style used by Visual C and some other Microsoft tools. An example
1488 * file.asm(50) : error: blah blah blah
1489 * where file.asm is the name of the file, 50 is the line number on
1490 * which the error occurs (or is detected) and "error:" is one of
1491 * the possible optional diagnostics -- it can be "error" or "warning"
1492 * or something else. Finally the line terminates with the actual
1495 * @param severity the severity of the warning or error
1496 * @param fmt the printf style format string
1498 static void report_error_vc(int severity, const char *fmt, ...)
1502 if (is_suppressed_warning(severity))
1505 if (severity & ERR_NOFILE)
1506 fputs("nasm: ", error_file);
1508 char *currentfile = NULL;
1510 src_get(&lineno, ¤tfile);
1511 fprintf(error_file, "%s(%"PRId32") : ", currentfile, lineno);
1512 nasm_free(currentfile);
1515 report_error_common(severity, fmt, ap);
1520 * check for supressed warning
1521 * checks for suppressed warning or pass one only warning and we're
1524 * @param severity the severity of the warning or error
1525 * @return true if we should abort error/warning printing
1527 static int is_suppressed_warning(int severity)
1530 * See if it's a suppressed warning.
1532 return ((severity & ERR_MASK) == ERR_WARNING &&
1533 (severity & ERR_WARN_MASK) != 0 &&
1534 suppressed[(severity & ERR_WARN_MASK) >> ERR_WARN_SHR]) ||
1536 * See if it's a pass-one only warning and we're not in pass one.
1538 ((severity & ERR_PASS1) && pass0 == 2);
1542 * common error reporting
1543 * This is the common back end of the error reporting schemes currently
1544 * implemented. It prints the nature of the warning and then the
1545 * specific error message to error_file and may or may not return. It
1546 * doesn't return if the error severity is a "panic" or "debug" type.
1548 * @param severity the severity of the warning or error
1549 * @param fmt the printf style format string
1551 static void report_error_common(int severity, const char *fmt,
1554 switch (severity & ERR_MASK) {
1556 fputs("warning: ", error_file);
1559 fputs("error: ", error_file);
1562 fputs("fatal: ", error_file);
1565 fputs("panic: ", error_file);
1568 fputs("debug: ", error_file);
1572 vfprintf(error_file, fmt, args);
1573 fputc('\n', error_file);
1575 if (severity & ERR_USAGE)
1578 switch (severity & ERR_MASK) {
1581 /* no further action, by definition */
1584 /* hack enables listing(!) on errors */
1585 terminate_after_phase = TRUE;
1594 exit(1); /* instantly die */
1595 break; /* placate silly compilers */
1598 /* abort(); *//* halt, catch fire, and dump core */
1604 static void usage(void)
1606 fputs("type `nasm -h' for help\n", error_file);
1609 static void register_output_formats(void)
1611 ofmt = ofmt_register(report_error);
1614 #define BUF_DELTA 512
1616 static FILE *no_pp_fp;
1617 static efunc no_pp_err;
1618 static ListGen *no_pp_list;
1619 static int32_t no_pp_lineinc;
1621 static void no_pp_reset(char *file, int pass, efunc error, evalfunc eval,
1624 src_set_fname(nasm_strdup(file));
1628 no_pp_fp = fopen(file, "r");
1630 no_pp_err(ERR_FATAL | ERR_NOFILE,
1631 "unable to open input file `%s'", file);
1632 no_pp_list = listgen;
1633 (void)pass; /* placate compilers */
1634 (void)eval; /* placate compilers */
1637 static char *no_pp_getline(void)
1639 char *buffer, *p, *q;
1642 bufsize = BUF_DELTA;
1643 buffer = nasm_malloc(BUF_DELTA);
1644 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1646 while (1) { /* Loop to handle %line */
1649 while (1) { /* Loop to handle long lines */
1650 q = fgets(p, bufsize - (p - buffer), no_pp_fp);
1654 if (p > buffer && p[-1] == '\n')
1656 if (p - buffer > bufsize - 10) {
1658 offset = p - buffer;
1659 bufsize += BUF_DELTA;
1660 buffer = nasm_realloc(buffer, bufsize);
1661 p = buffer + offset;
1665 if (!q && p == buffer) {
1671 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1672 * them are present at the end of the line.
1674 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1676 if (!strncmp(buffer, "%line", 5)) {
1679 char *nm = nasm_malloc(strlen(buffer));
1680 if (sscanf(buffer + 5, "%"PRId32"+%d %s", &ln, &li, nm) == 3) {
1681 nasm_free(src_set_fname(nm));
1691 no_pp_list->line(LIST_READ, buffer);
1696 static void no_pp_cleanup(int pass)
1698 (void)pass; /* placate GCC */
1702 static uint32_t get_cpu(char *value)
1705 if (!strcmp(value, "8086"))
1707 if (!strcmp(value, "186"))
1709 if (!strcmp(value, "286"))
1711 if (!strcmp(value, "386"))
1713 if (!strcmp(value, "486"))
1715 if (!strcmp(value, "586") || !nasm_stricmp(value, "pentium"))
1717 if (!strcmp(value, "686") ||
1718 !nasm_stricmp(value, "ppro") ||
1719 !nasm_stricmp(value, "pentiumpro") || !nasm_stricmp(value, "p2"))
1721 if (!nasm_stricmp(value, "p3") || !nasm_stricmp(value, "katmai"))
1723 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
1724 !nasm_stricmp(value, "willamette"))
1725 return IF_WILLAMETTE;
1726 if (!nasm_stricmp(value, "prescott"))
1728 if (!nasm_stricmp(value, "x64") ||
1729 !nasm_stricmp(value, "x86-64"))
1731 if (!nasm_stricmp(value, "ia64") ||
1732 !nasm_stricmp(value, "ia-64") ||
1733 !nasm_stricmp(value, "itanium") ||
1734 !nasm_stricmp(value, "itanic") || !nasm_stricmp(value, "merced"))
1737 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1738 "unknown 'cpu' type");
1740 return IF_PLEVEL; /* the maximum level */
1743 static int get_bits(char *value)
1747 if ((i = atoi(value)) == 16)
1748 return i; /* set for a 16-bit segment */
1751 report_error(ERR_NONFATAL,
1752 "cannot specify 32-bit segment on processor below a 386");
1755 } else if (i == 64) {
1756 if (cpu < IF_X86_64) {
1757 report_error(ERR_NONFATAL,
1758 "cannot specify 64-bit segment on processor below an x86-64");
1762 report_error(ERR_NONFATAL,
1763 "%s output format does not support 64-bit code",
1768 report_error(pass0 < 2 ? ERR_NONFATAL : ERR_FATAL,
1769 "`%s' is not a valid segment size; must be 16, 32 or 64",