NASM 0.98p7
[nasm/avx512.git] / nasm.c
blob74fcc08a684fb47c80f06f32407fe3bdbe5f062e
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.
7 */
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ctype.h>
15 #include "nasm.h"
16 #include "nasmlib.h"
17 #include "preproc.h"
18 #include "parser.h"
19 #include "eval.h"
20 #include "assemble.h"
21 #include "labels.h"
22 #include "outform.h"
23 #include "listing.h"
25 struct forwrefinfo { /* info held on forward refs. */
26 int lineno;
27 int operand;
30 static void report_error (int, char *, ...);
31 static void parse_cmdline (int, char **);
32 static void assemble_file (char *);
33 static int getkw (char *buf, char **value);
34 static void register_output_formats(void);
35 static void usage(void);
37 static int using_debug_info;
39 static char inname[FILENAME_MAX];
40 static char outname[FILENAME_MAX];
41 static char listname[FILENAME_MAX];
42 static int globallineno; /* for forward-reference tracking */
43 static int pass;
44 static struct ofmt *ofmt = NULL;
46 static FILE *error_file; /* Where to write error messages */
48 static FILE *ofile = NULL;
49 static int sb = 16; /* by default */
51 static loc_t location;
52 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
53 static long abs_seg;
55 static struct RAA *offsets;
56 static long abs_offset;
58 static struct SAA *forwrefs; /* keep track of forward references */
59 static struct forwrefinfo *forwref;
61 static Preproc *preproc;
62 enum op_type {
63 op_normal, /* Preprocess and assemble */
64 op_preprocess, /* Preprocess only */
65 op_depend /* Generate dependencies */
67 static enum op_type operating_mode;
69 /* used by error function to report location */
72 * Which of the suppressible warnings are suppressed. Entry zero
73 * doesn't do anything. Initial defaults are given here.
75 static char suppressed[1+ERR_WARN_MAX] = {
76 0, TRUE, TRUE, FALSE
80 * The option names for the suppressible warnings. As before, entry
81 * zero does nothing.
83 static char *suppressed_names[1+ERR_WARN_MAX] = {
84 NULL, "macro-params", "orphan-labels", "number-overflow"
88 * The explanations for the suppressible warnings. As before, entry
89 * zero does nothing.
91 static char *suppressed_what[1+ERR_WARN_MAX] = {
92 NULL, "macro calls with wrong no. of params",
93 "labels alone on lines without trailing `:'",
94 "numeric constants greater than 0xFFFFFFFF"
98 * This is a null preprocessor which just copies lines from input
99 * to output. It's used when someone explicitly requests that NASM
100 * not preprocess their source file.
103 static void no_pp_reset (char *, int, efunc, evalfunc, ListGen *);
104 static char *no_pp_getline (void);
105 static void no_pp_cleanup (void);
106 static Preproc no_pp = {
107 no_pp_reset,
108 no_pp_getline,
109 no_pp_cleanup
113 * get/set current offset...
115 #define get_curr_ofs (in_abs_seg?abs_offset:\
116 raa_read(offsets,location.segment))
117 #define set_curr_ofs(x) (in_abs_seg?(void)(abs_offset=(x)):\
118 (void)(offsets=raa_write(offsets,location.segment,(x))))
120 static int want_usage;
121 static int terminate_after_phase;
123 static void nasm_fputs(char *line, FILE *ofile)
125 if (ofile) {
126 fputs(line, ofile);
127 fputc('\n', ofile);
128 } else
129 puts(line);
132 int main(int argc, char **argv)
134 want_usage = terminate_after_phase = FALSE;
136 nasm_set_malloc_error (report_error);
137 offsets = raa_init();
138 forwrefs = saa_init ((long)sizeof(struct forwrefinfo));
140 preproc = &nasmpp;
141 operating_mode = op_normal;
143 error_file = stderr;
145 seg_init();
147 register_output_formats();
149 parse_cmdline(argc, argv);
151 if (terminate_after_phase)
153 if (want_usage)
154 usage();
155 return 1;
158 if (ofmt->stdmac)
159 pp_extra_stdmac (ofmt->stdmac);
160 parser_global_info (ofmt, &location);
161 eval_global_info (ofmt, lookup_label, &location);
163 switch ( operating_mode ) {
164 case op_depend:
166 char *line;
167 preproc->reset (inname, 0, report_error, evaluate, &nasmlist);
168 if (outname[0] == '\0')
169 ofmt->filename (inname, outname, report_error);
170 ofile = NULL;
171 printf("%s: %s", outname, inname);
172 while ( (line = preproc->getline()) )
173 nasm_free (line);
174 preproc->cleanup();
175 putc('\n', stdout);
177 break;
179 case op_preprocess:
181 char *line;
182 char *file_name = NULL;
183 long prior_linnum=0;
184 int lineinc=0;
186 if (*outname) {
187 ofile = fopen(outname, "w");
188 if (!ofile)
189 report_error (ERR_FATAL | ERR_NOFILE,
190 "unable to open output file `%s'", outname);
191 } else
192 ofile = NULL;
194 location.known = FALSE;
196 preproc->reset (inname, 2, report_error, evaluate, &nasmlist);
197 while ( (line = preproc->getline()) ) {
199 * We generate %line directives if needed for later programs
201 long linnum = prior_linnum += lineinc;
202 int altline = src_get(&linnum, &file_name);
203 if (altline) {
204 if (altline==1 && lineinc==1)
205 nasm_fputs("", ofile);
206 else {
207 lineinc = (altline != -1 || lineinc!=1);
208 fprintf(ofile ? ofile : stdout, "%%line %ld+%d %s\n",
209 linnum, lineinc, file_name);
211 prior_linnum = linnum;
213 nasm_fputs(line, ofile);
214 nasm_free (line);
216 nasm_free(file_name);
217 preproc->cleanup();
218 if (ofile)
219 fclose(ofile);
220 if (ofile && terminate_after_phase)
221 remove(outname);
223 break;
225 case op_normal:
228 * We must call ofmt->filename _anyway_, even if the user
229 * has specified their own output file, because some
230 * formats (eg OBJ and COFF) use ofmt->filename to find out
231 * the name of the input file and then put that inside the
232 * file.
234 ofmt->filename (inname, outname, report_error);
236 ofile = fopen(outname, "wb");
237 if (!ofile) {
238 report_error (ERR_FATAL | ERR_NOFILE,
239 "unable to open output file `%s'", outname);
243 * We must call init_labels() before ofmt->init() since
244 * some object formats will want to define labels in their
245 * init routines. (eg OS/2 defines the FLAT group)
247 init_labels ();
249 ofmt->init (ofile, report_error, define_label, evaluate);
251 assemble_file (inname);
253 if (!terminate_after_phase) {
254 ofmt->cleanup (using_debug_info);
255 cleanup_labels ();
257 else {
260 * We had an fclose on the output file here, but we
261 * actually do that in all the object file drivers as well,
262 * so we're leaving out the one here.
263 * fclose (ofile);
266 remove(outname);
267 if (listname[0])
268 remove(listname);
271 break;
274 if (want_usage)
275 usage();
277 raa_free (offsets);
278 saa_free (forwrefs);
279 eval_cleanup ();
280 nasmlib_cleanup ();
282 if (terminate_after_phase)
283 return 1;
284 else
285 return 0;
290 * Get a parameter for a command line option.
291 * First arg must be in the form of e.g. -f...
293 static char *get_param (char *p, char *q, int *advance)
295 *advance = 0;
296 if (p[2]) /* the parameter's in the option */
298 p += 2;
299 while (isspace(*p))
300 p++;
301 return p;
303 if (q && q[0])
305 *advance = 1;
306 return q;
308 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
309 "option `-%c' requires an argument",
310 p[1]);
311 return NULL;
314 int stopoptions = 0;
315 static int process_arg (char *p, char *q)
317 char *param;
318 int i, advance = 0;
320 if (!p || !p[0])
321 return 0;
323 if (p[0]=='-' && ! stopoptions)
325 switch (p[1]) {
326 case '-': /* -- => stop processing options */
327 stopoptions = 1;
328 break;
329 case 's': /* silently ignored for compatibility */
330 break;
331 case 'o': /* these parameters take values */
332 case 'f':
333 case 'p':
334 case 'd':
335 case 'D':
336 case 'i':
337 case 'l':
338 case 'E':
339 case 'F':
340 if ( !(param = get_param (p, q, &advance)) )
341 break;
342 if (p[1]=='o') { /* output file */
343 strcpy (outname, param);
344 } else if (p[1]=='f') { /* output format */
345 ofmt = ofmt_find(param);
346 if (!ofmt) {
347 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
348 "unrecognised output format `%s' - "
349 "use -hf for a list",
350 param);
352 else
353 ofmt->current_dfmt = ofmt->debug_formats[0];
354 } else if (p[1]=='P' || p[1]=='p') { /* pre-include */
355 pp_pre_include (param);
356 } else if (p[1]=='D' || p[1]=='d') { /* pre-define */
357 pp_pre_define (param);
358 } else if (p[1]=='U' || p[1]=='u') { /* un-define */
359 pp_pre_undefine (param);
360 } else if (p[1]=='I' || p[1]=='i') { /* include search path */
361 pp_include_path (param);
362 } else if (p[1]=='l') { /* listing file */
363 strcpy (listname, param);
364 } else if (p[1]=='E') { /* error messages file */
365 error_file = fopen(param, "wt");
366 if ( !error_file ) {
367 error_file = stderr; /* Revert to default! */
368 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
369 "cannot open file `%s' for error messages",
370 param);
372 } else if (p[1] == 'F') { /* specify debug format */
373 ofmt->current_dfmt = dfmt_find(ofmt, param);
374 if (!ofmt->current_dfmt) {
375 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
376 "unrecognized debug format `%s' for"
377 " output format `%s'",
378 param, ofmt->shortname);
381 break;
382 case 'g':
383 using_debug_info = TRUE;
384 break;
385 case 'h':
386 printf("usage: nasm [-@ response file] [-o outfile] [-f format] "
387 "[-l listfile]\n"
388 " [options...] [--] filename\n"
389 " or nasm -r for version info\n\n"
390 " -e preprocess only (writes output to stdout by default)\n"
391 " -a don't preprocess (assemble only)\n"
392 " -M generate Makefile dependencies on stdout\n\n"
393 " -E<file> redirect error messages to file\n\n"
394 " -g enable debug info\n"
395 " -F format select a debugging format\n\n"
396 " -I<path> adds a pathname to the include file path\n"
397 " -P<file> pre-includes a file\n"
398 " -D<macro>[=<value>] pre-defines a macro\n"
399 " -U<macro> undefines a macro\n"
400 " -w+foo enables warnings about foo; -w-foo disables them\n"
401 "where foo can be:\n");
402 for (i=1; i<=ERR_WARN_MAX; i++)
403 printf(" %-16s%s (default %s)\n",
404 suppressed_names[i], suppressed_what[i],
405 suppressed[i] ? "off" : "on");
406 printf ("\nresponse files should contain command line parameters"
407 ", one per line.\n");
408 if (p[2] == 'f') {
409 printf("\nvalid output formats for -f are"
410 " (`*' denotes default):\n");
411 ofmt_list(ofmt, stdout);
413 else {
414 printf ("\nFor a list of valid output formats, use -hf.\n");
415 printf ("For a list of debug formats, use -f <form> -y.\n");
417 exit (0); /* never need usage message here */
418 break;
419 case 'y':
420 printf("\nvalid debug formats for '%s' output format are"
421 " ('*' denotes default):\n",
422 ofmt->shortname);
423 dfmt_list(ofmt, stdout);
424 exit(0);
425 break;
426 case 'r':
427 printf("NASM version %s\n", NASM_VER);
428 #ifdef DEBUG
429 printf("Compiled with -DDEBUG on " __DATE__ "\n");
430 #endif
431 exit (0); /* never need usage message here */
432 break;
433 case 'e': /* preprocess only */
434 operating_mode = op_preprocess;
435 break;
436 case 'a': /* assemble only - don't preprocess */
437 preproc = &no_pp;
438 break;
439 case 'w':
440 if (p[2] != '+' && p[2] != '-') {
441 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
442 "invalid option to `-w'");
443 } else {
444 for (i=1; i<=ERR_WARN_MAX; i++)
445 if (!nasm_stricmp(p+3, suppressed_names[i]))
446 break;
447 if (i <= ERR_WARN_MAX)
448 suppressed[i] = (p[2] == '-');
449 else
450 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
451 "invalid option to `-w'");
453 break;
454 case 'M':
455 operating_mode = op_depend;
456 break;
457 default:
458 if (!ofmt->setinfo(GI_SWITCH,&p))
459 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
460 "unrecognised option `-%c'",
461 p[1]);
462 break;
465 else
467 if (*inname) {
468 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
469 "more than one input file specified");
470 } else
471 strcpy(inname, p);
474 return advance;
477 #define ARG_BUF_DELTA 128
479 static void process_respfile (FILE *rfile)
481 char *buffer, *p, *q, *prevarg;
482 int bufsize, prevargsize;
484 bufsize = prevargsize = ARG_BUF_DELTA;
485 buffer = nasm_malloc(ARG_BUF_DELTA);
486 prevarg = nasm_malloc(ARG_BUF_DELTA);
487 prevarg[0] = '\0';
489 while (1) { /* Loop to handle all lines in file */
491 p = buffer;
492 while (1) { /* Loop to handle long lines */
493 q = fgets(p, bufsize-(p-buffer), rfile);
494 if (!q)
495 break;
496 p += strlen(p);
497 if (p > buffer && p[-1] == '\n')
498 break;
499 if (p-buffer > bufsize-10) {
500 int offset;
501 offset = p - buffer;
502 bufsize += ARG_BUF_DELTA;
503 buffer = nasm_realloc(buffer, bufsize);
504 p = buffer + offset;
508 if (!q && p == buffer) {
509 if (prevarg[0])
510 process_arg (prevarg, NULL);
511 nasm_free (buffer);
512 nasm_free (prevarg);
513 return;
517 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
518 * them are present at the end of the line.
520 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
522 while (p > buffer && isspace(p[-1]))
523 *--p = '\0';
525 p = buffer;
526 while (isspace(*p))
527 p++;
529 if (process_arg (prevarg, p))
530 *p = '\0';
532 if (strlen(p) > prevargsize-10) {
533 prevargsize += ARG_BUF_DELTA;
534 prevarg = nasm_realloc(prevarg, prevargsize);
536 strcpy (prevarg, p);
540 static void parse_cmdline(int argc, char **argv)
542 FILE *rfile;
543 char *envreal, *envcopy=NULL, *p, *q, *arg, *prevarg;
544 char separator = ' ';
546 *inname = *outname = *listname = '\0';
549 * First, process the NASM environment variable.
551 envreal = getenv("NASM");
552 arg = NULL;
553 if (envreal) {
554 envcopy = nasm_strdup(envreal);
555 p = envcopy;
556 if (*p && *p != '-')
557 separator = *p++;
558 while (*p) {
559 q = p;
560 while (*p && *p != separator) p++;
561 while (*p == separator) *p++ = '\0';
562 prevarg = arg;
563 arg = q;
564 if (process_arg (prevarg, arg))
565 arg = NULL;
567 if (arg)
568 process_arg (arg, NULL);
569 nasm_free (envcopy);
573 * Now process the actual command line.
575 while (--argc)
577 int i;
578 argv++;
579 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
580 if ((p = get_param (argv[0], argc > 1 ? argv[1] : NULL, &i)))
581 if ((rfile = fopen(p, "r"))) {
582 process_respfile (rfile);
583 fclose(rfile);
584 } else
585 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
586 "unable to open response file `%s'", p);
587 } else
588 i = process_arg (argv[0], argc > 1 ? argv[1] : NULL);
589 argv += i, argc -= i;
592 if (!*inname)
593 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
594 "no input file specified");
597 static void assemble_file (char *fname)
599 char * value, * p, * q, * special, * line, debugid[80];
600 insn output_ins;
601 int i, rn_error, validid;
602 long seg, offs;
603 struct tokenval tokval;
604 expr * e;
607 * pass one
609 pass = 1;
610 in_abs_seg = FALSE;
611 location.segment = ofmt->section(NULL, pass, &sb);
612 preproc->reset(fname, 1, report_error, evaluate, &nasmlist);
613 globallineno = 0;
614 location.known = TRUE;
615 location.offset = offs = get_curr_ofs;
617 while ( (line = preproc->getline()) )
619 globallineno++;
621 /* here we parse our directives; this is not handled by the 'real'
622 * parser. */
623 if ( (i = getkw (line, &value)) )
625 switch (i) {
626 case 1: /* [SEGMENT n] */
627 seg = ofmt->section (value, pass, &sb);
628 if (seg == NO_SEG) {
629 report_error (ERR_NONFATAL,
630 "segment name `%s' not recognised",
631 value);
632 } else {
633 in_abs_seg = FALSE;
634 location.segment = seg;
636 break;
637 case 2: /* [EXTERN label:special] */
638 if (*value == '$')
639 value++; /* skip initial $ if present */
640 q = value;
641 validid = TRUE;
642 if (!isidstart(*q))
643 validid = FALSE;
644 while (*q && *q != ':') {
645 if (!isidchar(*q))
646 validid = FALSE;
647 q++;
649 if (!validid) {
650 report_error (ERR_NONFATAL,
651 "identifier expected after EXTERN");
652 break;
654 if (*q == ':') {
655 *q++ = '\0';
656 special = q;
657 } else
658 special = NULL;
659 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
660 declare_as_global (value, special, report_error);
661 define_label (value, seg_alloc(), 0L, NULL, FALSE, TRUE,
662 ofmt, report_error);
664 break;
665 case 3: /* [BITS bits] */
666 switch (atoi(value)) {
667 case 16:
668 case 32:
669 sb = atoi(value);
670 break;
671 default:
672 report_error(ERR_NONFATAL,
673 "`%s' is not a valid argument to [BITS]",
674 value);
675 break;
677 break;
678 case 4: /* [GLOBAL symbol:special] */
679 if (*value == '$')
680 value++; /* skip initial $ if present */
681 q = value;
682 validid = TRUE;
683 if (!isidstart(*q))
684 validid = FALSE;
685 while (*q && *q != ':') {
686 if (!isidchar(*q))
687 validid = FALSE;
688 q++;
690 if (!validid) {
691 report_error (ERR_NONFATAL,
692 "identifier expected after GLOBAL");
693 break;
695 if (*q == ':') {
696 *q++ = '\0';
697 special = q;
698 } else
699 special = NULL;
700 declare_as_global (value, special, report_error);
701 break;
702 case 5: /* [COMMON symbol size:special] */
703 p = value;
704 validid = TRUE;
705 if (!isidstart(*p))
706 validid = FALSE;
707 while (*p && !isspace(*p)) {
708 if (!isidchar(*p))
709 validid = FALSE;
710 p++;
712 if (!validid) {
713 report_error (ERR_NONFATAL,
714 "identifier expected after COMMON");
715 break;
717 if (*p) {
718 long size;
720 while (*p && isspace(*p))
721 *p++ = '\0';
722 q = p;
723 while (*q && *q != ':')
724 q++;
725 if (*q == ':') {
726 *q++ = '\0';
727 special = q;
728 } else
729 special = NULL;
730 size = readnum (p, &rn_error);
731 if (rn_error)
732 report_error (ERR_NONFATAL, "invalid size specified"
733 " in COMMON declaration");
734 else
735 define_common (value, seg_alloc(), size,
736 special, ofmt, report_error);
737 } else
738 report_error (ERR_NONFATAL, "no size specified in"
739 " COMMON declaration");
740 break;
741 case 6: /* [ABSOLUTE address] */
742 stdscan_reset();
743 stdscan_bufptr = value;
744 tokval.t_type = TOKEN_INVALID;
745 e = evaluate(stdscan, NULL, &tokval, NULL, 1, report_error,
746 NULL);
747 if (e) {
748 if (!is_reloc(e))
749 report_error (ERR_NONFATAL, "cannot use non-"
750 "relocatable expression as ABSOLUTE"
751 " address");
752 else {
753 abs_seg = reloc_seg(e);
754 abs_offset = reloc_value(e);
756 } else
757 abs_offset = 0x100;/* don't go near zero in case of / */
758 in_abs_seg = TRUE;
759 location.segment = abs_seg;
760 break;
761 case 7:
762 p = value;
763 validid = TRUE;
764 if (!isidstart(*p))
765 validid = FALSE;
766 while (*p && !isspace(*p)) {
767 if (!isidchar(*p))
768 validid = FALSE;
769 p++;
771 if (!validid) {
772 report_error (ERR_NONFATAL,
773 "identifier expected after DEBUG");
774 break;
776 while (*p && isspace(*p)) p++;
777 break;
778 default:
779 if (!ofmt->directive (line+1, value, 1))
780 report_error (ERR_NONFATAL, "unrecognised directive [%s]",
781 line+1);
782 break;
785 else /* it isn't a directive */
787 parse_line (1, line, &output_ins,
788 report_error, evaluate, define_label);
790 if (output_ins.forw_ref)
792 for(i = 0; i < output_ins.operands; i++)
794 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD)
796 struct forwrefinfo *fwinf =
797 (struct forwrefinfo *)saa_wstruct(forwrefs);
798 fwinf->lineno = globallineno;
799 fwinf->operand = i;
804 if (output_ins.opcode == I_EQU)
807 * Special `..' EQUs get processed in pass two,
808 * except `..@' macro-processor EQUs which are done
809 * in the normal place.
811 if (!output_ins.label)
812 report_error (ERR_NONFATAL,
813 "EQU not preceded by label");
816 * EQU cannot be used to declare a label relative to
817 * an external symbol.
819 else if ((output_ins.oprs[0].opflags & OPFLAG_EXTERN)
820 || (output_ins.operands > 1
821 && (output_ins.oprs[1].opflags & OPFLAG_EXTERN)))
823 report_error (ERR_NONFATAL,
824 "EQU used relative to external symbol");
827 else if (output_ins.label[0] != '.' ||
828 output_ins.label[1] != '.' ||
829 output_ins.label[2] == '@')
831 if (output_ins.operands == 1 &&
832 (output_ins.oprs[0].type & IMMEDIATE) &&
833 output_ins.oprs[0].wrt == NO_SEG)
835 define_label (output_ins.label,
836 output_ins.oprs[0].segment,
837 output_ins.oprs[0].offset,
838 NULL, FALSE, FALSE, ofmt, report_error);
840 else if (output_ins.operands == 2 &&
841 (output_ins.oprs[0].type & IMMEDIATE) &&
842 (output_ins.oprs[0].type & COLON) &&
843 output_ins.oprs[0].segment == NO_SEG &&
844 output_ins.oprs[0].wrt == NO_SEG &&
845 (output_ins.oprs[1].type & IMMEDIATE) &&
846 output_ins.oprs[1].segment == NO_SEG &&
847 output_ins.oprs[1].wrt == NO_SEG)
849 define_label (output_ins.label,
850 output_ins.oprs[0].offset | SEG_ABS,
851 output_ins.oprs[1].offset,
852 NULL, FALSE, FALSE, ofmt, report_error);
854 else
855 report_error(ERR_NONFATAL, "bad syntax for EQU");
858 else /* instruction isn't an EQU */
860 long l = insn_size (location.segment, offs, sb,
861 &output_ins, report_error);
862 if (using_debug_info && output_ins.opcode != -1) {
863 /* this is done here so we can do debug type info */
864 long typeinfo = TYS_ELEMENTS(output_ins.operands);
865 switch (output_ins.opcode) {
866 case I_RESB:
867 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
868 break;
869 case I_RESW:
870 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
871 break;
872 case I_RESD:
873 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
874 break;
875 case I_RESQ:
876 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
877 break;
878 case I_REST:
879 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
880 break;
881 case I_DB:
882 typeinfo |= TY_BYTE;
883 break;
884 case I_DW:
885 typeinfo |= TY_WORD;
886 break;
887 case I_DD:
888 if (output_ins.eops_float)
889 typeinfo |= TY_FLOAT;
890 else
891 typeinfo |= TY_DWORD;
892 break;
893 case I_DQ:
894 typeinfo |= TY_QWORD;
895 break;
896 case I_DT:
897 typeinfo |= TY_TBYTE;
898 break;
899 default:
900 typeinfo = TY_LABEL;
902 ofmt->current_dfmt->debug_typevalue(typeinfo);
904 if (l != -1) {
905 offs += l;
906 set_curr_ofs (offs);
909 * else l == -1 => invalid instruction, which will be
910 * flagged as an error on pass 2
913 cleanup_insn (&output_ins);
915 nasm_free (line);
916 location.offset = offs = get_curr_ofs;
919 preproc->cleanup();
921 if (terminate_after_phase) {
922 fclose(ofile);
923 remove(outname);
924 if (want_usage)
925 usage();
926 exit (1);
930 * pass two
933 pass = 2;
934 saa_rewind (forwrefs);
935 if (*listname)
936 nasmlist.init(listname, report_error);
937 forwref = saa_rstruct (forwrefs);
938 in_abs_seg = FALSE;
939 location.segment = ofmt->section(NULL, pass, &sb);
940 raa_free (offsets);
941 offsets = raa_init();
942 preproc->reset(fname, 2, report_error, evaluate, &nasmlist);
943 globallineno = 0;
944 location.offset = offs = get_curr_ofs;
946 while ( (line = preproc->getline()) )
948 globallineno++;
950 /* here we parse our directives; this is not handled by
951 * the 'real' parser. */
952 if ( (i = getkw (line, &value)) ) {
953 switch (i) {
954 case 1: /* [SEGMENT n] */
955 seg = ofmt->section (value, pass, &sb);
956 if (seg == NO_SEG) {
957 report_error (ERR_PANIC,
958 "invalid segment name on pass two");
959 } else
960 in_abs_seg = FALSE;
961 location.segment = seg;
962 break;
963 case 2: /* [EXTERN label] */
964 q = value;
965 while (*q && *q != ':')
966 q++;
967 if (*q == ':') {
968 *q++ = '\0';
969 ofmt->symdef(value, 0L, 0L, 3, q);
971 break;
972 case 3: /* [BITS bits] */
973 switch (atoi(value)) {
974 case 16:
975 case 32:
976 sb = atoi(value);
977 break;
978 default:
979 report_error(ERR_PANIC,
980 "invalid [BITS] value on pass two",
981 value);
982 break;
984 break;
985 case 4: /* [GLOBAL symbol] */
986 q = value;
987 while (*q && *q != ':')
988 q++;
989 if (*q == ':') {
990 *q++ = '\0';
991 ofmt->symdef(value, 0L, 0L, 3, q);
993 break;
994 case 5: /* [COMMON symbol size] */
995 q = value;
996 while (*q && *q != ':') {
997 if (isspace(*q))
998 *q = '\0';
999 q++;
1001 if (*q == ':') {
1002 *q++ = '\0';
1003 ofmt->symdef(value, 0L, 0L, 3, q);
1005 break;
1006 case 6: /* [ABSOLUTE addr] */
1007 stdscan_reset();
1008 stdscan_bufptr = value;
1009 tokval.t_type = TOKEN_INVALID;
1010 e = evaluate(stdscan, NULL, &tokval, NULL, 2, report_error,
1011 NULL);
1012 if (e) {
1013 if (!is_reloc(e))
1014 report_error (ERR_PANIC, "non-reloc ABSOLUTE address"
1015 " in pass two");
1016 else {
1017 abs_seg = reloc_seg(e);
1018 abs_offset = reloc_value(e);
1020 } else
1021 report_error (ERR_PANIC, "invalid ABSOLUTE address "
1022 "in pass two");
1023 in_abs_seg = TRUE;
1024 location.segment = abs_seg;
1025 break;
1026 case 7:
1027 p = value;
1028 q = debugid;
1029 validid = TRUE;
1030 if (!isidstart(*p))
1031 validid = FALSE;
1032 while (*p && !isspace(*p)) {
1033 if (!isidchar(*p))
1034 validid = FALSE;
1035 *q++ = *p++;
1037 *q++ = 0;
1038 if (!validid) {
1039 report_error (ERR_PANIC,
1040 "identifier expected after DEBUG in pass 2");
1041 break;
1043 while (*p && isspace(*p))
1044 p++;
1045 ofmt->current_dfmt->debug_directive (debugid, p);
1046 break;
1047 default:
1048 if (!ofmt->directive (line+1, value, 2))
1049 report_error (ERR_PANIC, "invalid directive on pass two");
1050 break;
1053 else /* not a directive */
1055 parse_line (2, line, &output_ins,
1056 report_error, evaluate, redefine_label);
1057 if (forwref != NULL && globallineno == forwref->lineno) {
1058 output_ins.forw_ref = TRUE;
1059 do {
1060 output_ins.oprs[forwref->operand].opflags|= OPFLAG_FORWARD;
1061 forwref = saa_rstruct (forwrefs);
1062 } while (forwref != NULL && forwref->lineno == globallineno);
1063 } else
1064 output_ins.forw_ref = FALSE;
1067 * Hack to prevent phase error in the code
1068 * rol ax,x
1069 * x equ 1
1071 * If the second operand is a forward reference,
1072 * the UNITY property of the number 1 in that
1073 * operand is cancelled. Otherwise the above
1074 * sequence will cause a phase error.
1076 * This hack means that the above code will
1077 * generate 286+ code.
1079 * The forward reference will mean that the
1080 * operand will not have the UNITY property on
1081 * the first pass, so the pass behaviours will
1082 * be consistent.
1085 if (output_ins.forw_ref &&
1086 output_ins.operands >= 2 &&
1087 (output_ins.oprs[1].opflags & OPFLAG_FORWARD))
1089 output_ins.oprs[1].type &= ~ONENESS;
1092 if (output_ins.opcode == I_EQU)
1095 * Special `..' EQUs get processed here, except
1096 * `..@' macro processor EQUs which are done above.
1098 if (output_ins.label[0] == '.' &&
1099 output_ins.label[1] == '.' &&
1100 output_ins.label[2] != '@')
1102 if (output_ins.operands == 1 &&
1103 (output_ins.oprs[0].type & IMMEDIATE)) {
1104 define_label (output_ins.label,
1105 output_ins.oprs[0].segment,
1106 output_ins.oprs[0].offset,
1107 NULL, FALSE, FALSE, ofmt, report_error);
1109 else if (output_ins.operands == 2 &&
1110 (output_ins.oprs[0].type & IMMEDIATE) &&
1111 (output_ins.oprs[0].type & COLON) &&
1112 output_ins.oprs[0].segment == NO_SEG &&
1113 (output_ins.oprs[1].type & IMMEDIATE) &&
1114 output_ins.oprs[1].segment == NO_SEG)
1116 define_label (output_ins.label,
1117 output_ins.oprs[0].offset | SEG_ABS,
1118 output_ins.oprs[1].offset,
1119 NULL, FALSE, FALSE, ofmt, report_error);
1121 else
1122 report_error(ERR_NONFATAL, "bad syntax for EQU");
1125 offs += assemble (location.segment, offs, sb,
1126 &output_ins, ofmt, report_error, &nasmlist);
1127 cleanup_insn (&output_ins);
1128 set_curr_ofs (offs);
1131 nasm_free (line);
1133 location.offset = offs = get_curr_ofs;
1136 preproc->cleanup();
1137 nasmlist.cleanup();
1140 static int getkw (char *buf, char **value)
1142 char *p, *q;
1144 if (*buf!='[')
1145 return 0;
1147 p = buf;
1149 while (*p && *p != ']') p++;
1151 if (!*p)
1152 return 0;
1154 q = p++;
1156 while (*p && *p != ';') {
1157 if (!isspace(*p))
1158 return 0;
1159 p++;
1161 q[1] = '\0';
1163 p = buf+1;
1164 while (*buf && *buf!=' ' && *buf!=']' && *buf!='\t')
1165 buf++;
1166 if (*buf==']') {
1167 *buf = '\0';
1168 *value = buf;
1169 } else {
1170 *buf++ = '\0';
1171 while (isspace(*buf)) buf++; /* beppu - skip leading whitespace */
1172 *value = buf;
1173 while (*buf!=']') buf++;
1174 *buf++ = '\0';
1176 for (q=p; *q; q++)
1177 *q = tolower(*q);
1178 if (!strcmp(p, "segment") || !strcmp(p, "section"))
1179 return 1;
1180 if (!strcmp(p, "extern"))
1181 return 2;
1182 if (!strcmp(p, "bits"))
1183 return 3;
1184 if (!strcmp(p, "global"))
1185 return 4;
1186 if (!strcmp(p, "common"))
1187 return 5;
1188 if (!strcmp(p, "absolute"))
1189 return 6;
1190 if (!strcmp(p, "debug"))
1191 return 7;
1192 return -1;
1195 static void report_error (int severity, char *fmt, ...)
1197 va_list ap;
1200 * See if it's a suppressed warning.
1202 if ((severity & ERR_MASK) == ERR_WARNING &&
1203 (severity & ERR_WARN_MASK) != 0 &&
1204 suppressed[ (severity & ERR_WARN_MASK) >> ERR_WARN_SHR ])
1205 return; /* and bail out if so */
1208 * See if it's a pass-one only warning and we're not in pass one.
1210 if ((severity & ERR_PASS1) && pass != 1)
1211 return;
1213 if (severity & ERR_NOFILE)
1214 fputs ("nasm: ", error_file);
1215 else {
1216 char * currentfile = NULL;
1217 long lineno = 0;
1218 src_get (&lineno, &currentfile);
1219 fprintf (error_file, "%s:%ld: ", currentfile, lineno);
1220 nasm_free (currentfile);
1223 if ( (severity & ERR_MASK) == ERR_WARNING)
1224 fputs ("warning: ", error_file);
1225 else if ( (severity & ERR_MASK) == ERR_PANIC)
1226 fputs ("panic: ", error_file);
1228 va_start (ap, fmt);
1229 vfprintf (error_file, fmt, ap);
1230 fputc ('\n', error_file);
1232 if (severity & ERR_USAGE)
1233 want_usage = TRUE;
1235 switch (severity & ERR_MASK) {
1236 case ERR_WARNING:
1237 /* no further action, by definition */
1238 break;
1239 case ERR_NONFATAL:
1240 terminate_after_phase = TRUE;
1241 break;
1242 case ERR_FATAL:
1243 if (ofile) {
1244 fclose(ofile);
1245 remove(outname);
1247 if (want_usage)
1248 usage();
1249 exit(1); /* instantly die */
1250 break; /* placate silly compilers */
1251 case ERR_PANIC:
1252 fflush(NULL);
1253 abort(); /* halt, catch fire, and dump core */
1254 break;
1258 static void usage(void)
1260 fputs("type `nasm -h' for help\n", error_file);
1263 static void register_output_formats(void)
1265 ofmt = ofmt_register (report_error);
1268 #define BUF_DELTA 512
1270 static FILE *no_pp_fp;
1271 static efunc no_pp_err;
1272 static ListGen *no_pp_list;
1273 static long no_pp_lineinc;
1275 static void no_pp_reset (char *file, int pass, efunc error, evalfunc eval,
1276 ListGen *listgen)
1278 src_set_fname(nasm_strdup(file));
1279 src_set_linnum(0);
1280 no_pp_lineinc = 1;
1281 no_pp_err = error;
1282 no_pp_fp = fopen(file, "r");
1283 if (!no_pp_fp)
1284 no_pp_err (ERR_FATAL | ERR_NOFILE,
1285 "unable to open input file `%s'", file);
1286 no_pp_list = listgen;
1287 (void) pass; /* placate compilers */
1288 (void) eval; /* placate compilers */
1291 static char *no_pp_getline (void)
1293 char *buffer, *p, *q;
1294 int bufsize;
1296 bufsize = BUF_DELTA;
1297 buffer = nasm_malloc(BUF_DELTA);
1298 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1300 while (1) { /* Loop to handle %line */
1302 p = buffer;
1303 while (1) { /* Loop to handle long lines */
1304 q = fgets(p, bufsize-(p-buffer), no_pp_fp);
1305 if (!q)
1306 break;
1307 p += strlen(p);
1308 if (p > buffer && p[-1] == '\n')
1309 break;
1310 if (p-buffer > bufsize-10) {
1311 int offset;
1312 offset = p - buffer;
1313 bufsize += BUF_DELTA;
1314 buffer = nasm_realloc(buffer, bufsize);
1315 p = buffer + offset;
1319 if (!q && p == buffer) {
1320 nasm_free (buffer);
1321 return NULL;
1325 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1326 * them are present at the end of the line.
1328 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1330 if (!strncmp(buffer, "%line", 5)) {
1331 long ln;
1332 int li;
1333 char *nm = nasm_malloc(strlen(buffer));
1334 if (sscanf(buffer+5, "%ld+%d %s", &ln, &li, nm) == 3) {
1335 nasm_free( src_set_fname(nm) );
1336 src_set_linnum(ln);
1337 no_pp_lineinc = li;
1338 continue;
1340 nasm_free(nm);
1342 break;
1345 no_pp_list->line (LIST_READ, buffer);
1347 return buffer;
1350 static void no_pp_cleanup (void)
1352 fclose(no_pp_fp);