NASM 0.98.03
[nasm.git] / nasm.c
blob841640cdd5e910172987f504e6f988e4143518e1
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 "insns.h"
18 #include "preproc.h"
19 #include "parser.h"
20 #include "eval.h"
21 #include "assemble.h"
22 #include "labels.h"
23 #include "outform.h"
24 #include "listing.h"
26 struct forwrefinfo { /* info held on forward refs. */
27 int lineno;
28 int operand;
31 static int get_bits (char *value);
32 static unsigned long get_cpu (char *cpu_str);
33 static void report_error (int, char *, ...);
34 static void parse_cmdline (int, char **);
35 static void assemble_file (char *);
36 static int getkw (char *buf, char **value);
37 static void register_output_formats(void);
38 static void usage(void);
40 static int using_debug_info;
42 static char inname[FILENAME_MAX];
43 static char outname[FILENAME_MAX];
44 static char listname[FILENAME_MAX];
45 static int globallineno; /* for forward-reference tracking */
46 static int pass = 0;
47 static struct ofmt *ofmt = NULL;
49 static FILE *error_file; /* Where to write error messages */
51 static FILE *ofile = NULL;
52 static int optimizing = 10; /* number of optimization passes to take */
53 static int sb, cmd_sb = 16; /* by default */
54 static unsigned long cmd_cpu = IF_PLEVEL; /* highest level by default */
55 static unsigned long cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
56 int global_offset_changed; /* referenced in labels.c */
58 static loc_t location;
59 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
60 static long abs_seg;
62 static struct RAA *offsets;
63 static long abs_offset;
65 static struct SAA *forwrefs; /* keep track of forward references */
66 static struct forwrefinfo *forwref;
68 static Preproc *preproc;
69 enum op_type {
70 op_normal, /* Preprocess and assemble */
71 op_preprocess, /* Preprocess only */
72 op_depend /* Generate dependencies */
74 static enum op_type operating_mode;
76 /* used by error function to report location */
79 * Which of the suppressible warnings are suppressed. Entry zero
80 * doesn't do anything. Initial defaults are given here.
82 static char suppressed[1+ERR_WARN_MAX] = {
83 0, TRUE, TRUE, TRUE, FALSE
87 * The option names for the suppressible warnings. As before, entry
88 * zero does nothing.
90 static char *suppressed_names[1+ERR_WARN_MAX] = {
91 NULL, "macro-params", "macro-selfref", "orphan-labels", "number-overflow",
95 * The explanations for the suppressible warnings. As before, entry
96 * zero does nothing.
98 static char *suppressed_what[1+ERR_WARN_MAX] = {
99 NULL,
100 "macro calls with wrong no. of params",
101 "cyclic macro self-references",
102 "labels alone on lines without trailing `:'",
103 "numeric constants greater than 0xFFFFFFFF"
107 * This is a null preprocessor which just copies lines from input
108 * to output. It's used when someone explicitly requests that NASM
109 * not preprocess their source file.
112 static void no_pp_reset (char *, int, efunc, evalfunc, ListGen *);
113 static char *no_pp_getline (void);
114 static void no_pp_cleanup (void);
115 static Preproc no_pp = {
116 no_pp_reset,
117 no_pp_getline,
118 no_pp_cleanup
122 * get/set current offset...
124 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
125 raa_read(offsets,location.segment))
126 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
127 (void)(offsets=raa_write(offsets,location.segment,(x))))
129 static int want_usage;
130 static int terminate_after_phase;
132 static void nasm_fputs(char *line, FILE *ofile)
134 if (ofile) {
135 fputs(line, ofile);
136 fputc('\n', ofile);
137 } else
138 puts(line);
141 int main(int argc, char **argv)
143 want_usage = terminate_after_phase = FALSE;
145 nasm_set_malloc_error (report_error);
146 offsets = raa_init();
147 forwrefs = saa_init ((long)sizeof(struct forwrefinfo));
149 preproc = &nasmpp;
150 operating_mode = op_normal;
152 error_file = stderr;
154 seg_init();
156 register_output_formats();
158 parse_cmdline(argc, argv);
160 if (terminate_after_phase)
162 if (want_usage)
163 usage();
164 return 1;
167 if (ofmt->stdmac)
168 pp_extra_stdmac (ofmt->stdmac);
169 parser_global_info (ofmt, &location);
170 eval_global_info (ofmt, lookup_label, &location);
172 /* define some macros dependent of command-line */
174 char temp [64];
175 sprintf (temp, "__OUTPUT_FORMAT__=%s\n", ofmt->shortname);
176 pp_pre_define (temp);
179 switch ( operating_mode ) {
180 case op_depend:
182 char *line;
183 preproc->reset (inname, 0, report_error, evaluate, &nasmlist);
184 if (outname[0] == '\0')
185 ofmt->filename (inname, outname, report_error);
186 ofile = NULL;
187 printf("%s: %s", outname, inname);
188 while ( (line = preproc->getline()) )
189 nasm_free (line);
190 preproc->cleanup();
191 putc('\n', stdout);
193 break;
195 case op_preprocess:
197 char *line;
198 char *file_name = NULL;
199 long prior_linnum=0;
200 int lineinc=0;
202 if (*outname) {
203 ofile = fopen(outname, "w");
204 if (!ofile)
205 report_error (ERR_FATAL | ERR_NOFILE,
206 "unable to open output file `%s'", outname);
207 } else
208 ofile = NULL;
210 location.known = FALSE;
212 pass = 1;
213 preproc->reset (inname, 2, report_error, evaluate, &nasmlist);
214 while ( (line = preproc->getline()) ) {
216 * We generate %line directives if needed for later programs
218 long linnum = prior_linnum += lineinc;
219 int altline = src_get(&linnum, &file_name);
220 if (altline) {
221 if (altline==1 && lineinc==1)
222 nasm_fputs("", ofile);
223 else {
224 lineinc = (altline != -1 || lineinc!=1);
225 fprintf(ofile ? ofile : stdout, "%%line %ld+%d %s\n",
226 linnum, lineinc, file_name);
228 prior_linnum = linnum;
230 nasm_fputs(line, ofile);
231 nasm_free (line);
233 nasm_free(file_name);
234 preproc->cleanup();
235 if (ofile)
236 fclose(ofile);
237 if (ofile && terminate_after_phase)
238 remove(outname);
240 break;
242 case op_normal:
245 * We must call ofmt->filename _anyway_, even if the user
246 * has specified their own output file, because some
247 * formats (eg OBJ and COFF) use ofmt->filename to find out
248 * the name of the input file and then put that inside the
249 * file.
251 ofmt->filename (inname, outname, report_error);
253 ofile = fopen(outname, "wb");
254 if (!ofile) {
255 report_error (ERR_FATAL | ERR_NOFILE,
256 "unable to open output file `%s'", outname);
260 * We must call init_labels() before ofmt->init() since
261 * some object formats will want to define labels in their
262 * init routines. (eg OS/2 defines the FLAT group)
264 init_labels ();
266 ofmt->init (ofile, report_error, define_label, evaluate);
268 assemble_file (inname);
270 if (!terminate_after_phase) {
271 ofmt->cleanup (using_debug_info);
272 cleanup_labels ();
273 } else {
275 * We had an fclose on the output file here, but we
276 * actually do that in all the object file drivers as well,
277 * so we're leaving out the one here.
278 * fclose (ofile);
281 remove(outname);
282 if (listname[0])
283 remove(listname);
286 break;
289 if (want_usage)
290 usage();
292 raa_free (offsets);
293 saa_free (forwrefs);
294 eval_cleanup ();
295 nasmlib_cleanup ();
297 if (terminate_after_phase)
298 return 1;
299 else
300 return 0;
305 * Get a parameter for a command line option.
306 * First arg must be in the form of e.g. -f...
308 static char *get_param (char *p, char *q, int *advance)
310 *advance = 0;
311 if (p[2]) /* the parameter's in the option */
313 p += 2;
314 while (isspace(*p))
315 p++;
316 return p;
318 if (q && q[0])
320 *advance = 1;
321 return q;
323 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
324 "option `-%c' requires an argument",
325 p[1]);
326 return NULL;
329 int stopoptions = 0;
330 static int process_arg (char *p, char *q)
332 char *param;
333 int i, advance = 0;
335 if (!p || !p[0])
336 return 0;
338 if (p[0]=='-' && ! stopoptions)
340 switch (p[1]) {
341 case '-': /* -- => stop processing options */
342 stopoptions = 1;
343 break;
344 case 's':
345 error_file = stdout;
346 break;
347 case 'o': /* these parameters take values */
348 case 'O':
349 case 'f':
350 case 'p':
351 case 'd':
352 case 'D':
353 case 'i':
354 case 'l':
355 case 'E':
356 case 'F':
357 if ( !(param = get_param (p, q, &advance)) )
358 break;
359 if (p[1]=='o') { /* output file */
360 strcpy (outname, param);
361 } else if (p[1]=='f') { /* output format */
362 ofmt = ofmt_find(param);
363 if (!ofmt) {
364 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
365 "unrecognised output format `%s' - "
366 "use -hf for a list",
367 param);
369 else
370 ofmt->current_dfmt = ofmt->debug_formats[0];
371 } else if (p[1]=='O') { /* Optimization level */
372 if (!isdigit(*param)) report_error(ERR_FATAL,
373 "command line optimization level must be 0..3");
374 optimizing = atoi(param);
375 if (optimizing <= 0) optimizing = 0;
376 else if (optimizing <= 3) optimizing *= 5; /* 5 passes for each level */
377 } else if (p[1]=='P' || p[1]=='p') { /* pre-include */
378 pp_pre_include (param);
379 } else if (p[1]=='D' || p[1]=='d') { /* pre-define */
380 pp_pre_define (param);
381 } else if (p[1]=='U' || p[1]=='u') { /* un-define */
382 pp_pre_undefine (param);
383 } else if (p[1]=='I' || p[1]=='i') { /* include search path */
384 pp_include_path (param);
385 } else if (p[1]=='l') { /* listing file */
386 strcpy (listname, param);
387 } else if (p[1]=='E') { /* error messages file */
388 error_file = fopen(param, "wt");
389 if ( !error_file ) {
390 error_file = stderr; /* Revert to default! */
391 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
392 "cannot open file `%s' for error messages",
393 param);
395 } else if (p[1] == 'F') { /* specify debug format */
396 ofmt->current_dfmt = dfmt_find(ofmt, param);
397 if (!ofmt->current_dfmt) {
398 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
399 "unrecognized debug format `%s' for"
400 " output format `%s'",
401 param, ofmt->shortname);
404 break;
405 case 'g':
406 using_debug_info = TRUE;
407 break;
408 case 'h':
409 printf("usage: nasm [-@ response file] [-o outfile] [-f format] "
410 "[-l listfile]\n"
411 " [options...] [--] filename\n"
412 " or nasm -r for version info\n\n"
413 " -e preprocess only (writes output to stdout by default)\n"
414 " -a don't preprocess (assemble only)\n"
415 " -M generate Makefile dependencies on stdout\n\n"
416 " -E<file> redirect error messages to file\n"
417 " -s redirect error messages to stdout\n\n"
418 " -g enable debug info\n"
419 " -F format select a debugging format\n\n"
420 " -I<path> adds a pathname to the include file path\n"
421 " -O<digit> optimize branch offsets -O0 disables, -O2 default\n"
422 " -P<file> pre-includes a file\n"
423 " -D<macro>[=<value>] pre-defines a macro\n"
424 " -U<macro> undefines a macro\n"
425 " -w+foo enables warnings about foo; -w-foo disables them\n"
426 "where foo can be:\n");
427 for (i=1; i<=ERR_WARN_MAX; i++)
428 printf(" %-16s%s (default %s)\n",
429 suppressed_names[i], suppressed_what[i],
430 suppressed[i] ? "off" : "on");
431 printf ("\nresponse files should contain command line parameters"
432 ", one per line.\n");
433 if (p[2] == 'f') {
434 printf("\nvalid output formats for -f are"
435 " (`*' denotes default):\n");
436 ofmt_list(ofmt, stdout);
438 else {
439 printf ("\nFor a list of valid output formats, use -hf.\n");
440 printf ("For a list of debug formats, use -f <form> -y.\n");
442 exit (0); /* never need usage message here */
443 break;
444 case 'y':
445 printf("\nvalid debug formats for '%s' output format are"
446 " ('*' denotes default):\n",
447 ofmt->shortname);
448 dfmt_list(ofmt, stdout);
449 exit(0);
450 break;
451 case 'r':
452 printf("NASM version %s\n", NASM_VER);
453 #ifdef DEBUG
454 printf("Compiled with -DDEBUG on " __DATE__ "\n");
455 #endif
456 exit (0); /* never need usage message here */
457 break;
458 case 'e': /* preprocess only */
459 operating_mode = op_preprocess;
460 break;
461 case 'a': /* assemble only - don't preprocess */
462 preproc = &no_pp;
463 break;
464 case 'w':
465 if (p[2] != '+' && p[2] != '-') {
466 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
467 "invalid option to `-w'");
468 } else {
469 for (i=1; i<=ERR_WARN_MAX; i++)
470 if (!nasm_stricmp(p+3, suppressed_names[i]))
471 break;
472 if (i <= ERR_WARN_MAX)
473 suppressed[i] = (p[2] == '-');
474 else
475 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
476 "invalid option to `-w'");
478 break;
479 case 'M':
480 operating_mode = op_depend;
481 break;
482 default:
483 if (!ofmt->setinfo(GI_SWITCH,&p))
484 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
485 "unrecognised option `-%c'",
486 p[1]);
487 break;
490 else
492 if (*inname) {
493 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
494 "more than one input file specified");
495 } else
496 strcpy(inname, p);
499 return advance;
502 #define ARG_BUF_DELTA 128
504 static void process_respfile (FILE *rfile)
506 char *buffer, *p, *q, *prevarg;
507 int bufsize, prevargsize;
509 bufsize = prevargsize = ARG_BUF_DELTA;
510 buffer = nasm_malloc(ARG_BUF_DELTA);
511 prevarg = nasm_malloc(ARG_BUF_DELTA);
512 prevarg[0] = '\0';
514 while (1) { /* Loop to handle all lines in file */
516 p = buffer;
517 while (1) { /* Loop to handle long lines */
518 q = fgets(p, bufsize-(p-buffer), rfile);
519 if (!q)
520 break;
521 p += strlen(p);
522 if (p > buffer && p[-1] == '\n')
523 break;
524 if (p-buffer > bufsize-10) {
525 int offset;
526 offset = p - buffer;
527 bufsize += ARG_BUF_DELTA;
528 buffer = nasm_realloc(buffer, bufsize);
529 p = buffer + offset;
533 if (!q && p == buffer) {
534 if (prevarg[0])
535 process_arg (prevarg, NULL);
536 nasm_free (buffer);
537 nasm_free (prevarg);
538 return;
542 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
543 * them are present at the end of the line.
545 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
547 while (p > buffer && isspace(p[-1]))
548 *--p = '\0';
550 p = buffer;
551 while (isspace(*p))
552 p++;
554 if (process_arg (prevarg, p))
555 *p = '\0';
557 if (strlen(p) > prevargsize-10) {
558 prevargsize += ARG_BUF_DELTA;
559 prevarg = nasm_realloc(prevarg, prevargsize);
561 strcpy (prevarg, p);
565 static void parse_cmdline(int argc, char **argv)
567 FILE *rfile;
568 char *envreal, *envcopy=NULL, *p, *q, *arg, *prevarg;
569 char separator = ' ';
571 *inname = *outname = *listname = '\0';
574 * First, process the NASM environment variable.
576 envreal = getenv("NASM");
577 arg = NULL;
578 if (envreal) {
579 envcopy = nasm_strdup(envreal);
580 p = envcopy;
581 if (*p && *p != '-')
582 separator = *p++;
583 while (*p) {
584 q = p;
585 while (*p && *p != separator) p++;
586 while (*p == separator) *p++ = '\0';
587 prevarg = arg;
588 arg = q;
589 if (process_arg (prevarg, arg))
590 arg = NULL;
592 if (arg)
593 process_arg (arg, NULL);
594 nasm_free (envcopy);
598 * Now process the actual command line.
600 while (--argc)
602 int i;
603 argv++;
604 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
605 if ((p = get_param (argv[0], argc > 1 ? argv[1] : NULL, &i))) {
606 if ((rfile = fopen(p, "r"))) {
607 process_respfile (rfile);
608 fclose(rfile);
609 } else
610 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
611 "unable to open response file `%s'", p);
613 } else
614 i = process_arg (argv[0], argc > 1 ? argv[1] : NULL);
615 argv += i, argc -= i;
618 if (!*inname)
619 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
620 "no input file specified");
624 static void assemble_file (char *fname)
626 char * value, * p, * q, * special, * line, debugid[80];
627 insn output_ins;
628 int i, rn_error, validid;
629 long seg, offs;
630 struct tokenval tokval;
631 expr * e;
632 int pass_max;
633 int pass_cnt = 0; /* count actual passes */
635 if (cmd_sb == 32 && cmd_cpu < IF_386)
636 report_error(ERR_FATAL, "command line: "
637 "32-bit segment size requires a higher cpu");
639 pass_max = optimizing + 2; /* passes 1, optimizing, then 2 */
640 for (pass = 1; pass <= pass_max; pass++) {
641 int pass1, pass2;
642 ldfunc def_label;
644 pass1 = pass < pass_max ? 1 : 2; /* seq is 1, 1, 1,..., 1, 2 */
645 pass2 = pass > 1 ? 2 : 1; /* seq is 1, 2, 2,..., 2, 2 */
646 def_label = pass > 1 ? redefine_label : define_label;
649 sb = cmd_sb; /* set 'bits' to command line default */
650 cpu = cmd_cpu;
651 if (pass == pass_max) {
652 if (*listname)
653 nasmlist.init(listname, report_error);
655 in_abs_seg = FALSE;
656 global_offset_changed = FALSE; /* set by redefine_label */
657 location.segment = ofmt->section(NULL, pass2, &sb);
658 if (pass > 1) {
659 saa_rewind (forwrefs);
660 forwref = saa_rstruct (forwrefs);
661 raa_free (offsets);
662 offsets = raa_init();
664 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
665 globallineno = 0;
666 if (pass == 1) location.known = TRUE;
667 location.offset = offs = GET_CURR_OFFS;
669 while ( (line = preproc->getline()) )
671 globallineno++;
673 /* here we parse our directives; this is not handled by the 'real'
674 * parser. */
675 if ( (i = getkw (line, &value)) )
677 switch (i) {
678 case 1: /* [SEGMENT n] */
679 seg = ofmt->section (value, pass2, &sb);
680 if (seg == NO_SEG) {
681 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
682 "segment name `%s' not recognised",
683 value);
684 } else {
685 in_abs_seg = FALSE;
686 location.segment = seg;
688 break;
689 case 2: /* [EXTERN label:special] */
690 if (pass == pass_max) {
691 q = value;
692 while (*q && *q != ':')
693 q++;
694 if (*q == ':') {
695 *q++ = '\0';
696 ofmt->symdef(value, 0L, 0L, 3, q);
698 } else if (pass == 1) { /* pass == 1 */
699 if (*value == '$')
700 value++; /* skip initial $ if present */
701 q = value;
702 validid = TRUE;
703 if (!isidstart(*q))
704 validid = FALSE;
705 while (*q && *q != ':') {
706 if (!isidchar(*q))
707 validid = FALSE;
708 q++;
710 if (!validid) {
711 report_error (ERR_NONFATAL,
712 "identifier expected after EXTERN");
713 break;
715 if (*q == ':') {
716 *q++ = '\0';
717 special = q;
718 } else
719 special = NULL;
720 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
721 declare_as_global (value, special, report_error);
722 define_label (value, seg_alloc(), 0L, NULL, FALSE, TRUE,
723 ofmt, report_error);
725 } /* else pass == 1 */
726 break;
727 case 3: /* [BITS bits] */
728 sb = get_bits(value);
729 break;
730 case 4: /* [GLOBAL symbol:special] */
731 if (pass == pass_max) { /* pass 2 */
732 q = value;
733 while (*q && *q != ':')
734 q++;
735 if (*q == ':') {
736 *q++ = '\0';
737 ofmt->symdef(value, 0L, 0L, 3, q);
739 } else if (pass == 1) { /* pass == 1 */
740 if (*value == '$')
741 value++; /* skip initial $ if present */
742 q = value;
743 validid = TRUE;
744 if (!isidstart(*q))
745 validid = FALSE;
746 while (*q && *q != ':') {
747 if (!isidchar(*q))
748 validid = FALSE;
749 q++;
751 if (!validid) {
752 report_error (ERR_NONFATAL,
753 "identifier expected after GLOBAL");
754 break;
756 if (*q == ':') {
757 *q++ = '\0';
758 special = q;
759 } else
760 special = NULL;
761 declare_as_global (value, special, report_error);
762 } /* pass == 1 */
763 break;
764 case 5: /* [COMMON symbol size:special] */
765 if (pass == 1) {
766 p = value;
767 validid = TRUE;
768 if (!isidstart(*p))
769 validid = FALSE;
770 while (*p && !isspace(*p)) {
771 if (!isidchar(*p))
772 validid = FALSE;
773 p++;
775 if (!validid) {
776 report_error (ERR_NONFATAL,
777 "identifier expected after COMMON");
778 break;
780 if (*p) {
781 long size;
783 while (*p && isspace(*p))
784 *p++ = '\0';
785 q = p;
786 while (*q && *q != ':')
787 q++;
788 if (*q == ':') {
789 *q++ = '\0';
790 special = q;
791 } else
792 special = NULL;
793 size = readnum (p, &rn_error);
794 if (rn_error)
795 report_error (ERR_NONFATAL, "invalid size specified"
796 " in COMMON declaration");
797 else
798 define_common (value, seg_alloc(), size,
799 special, ofmt, report_error);
800 } else
801 report_error (ERR_NONFATAL, "no size specified in"
802 " COMMON declaration");
803 } else if (pass == pass_max) { /* pass == 2 */
804 q = value;
805 while (*q && *q != ':') {
806 if (isspace(*q))
807 *q = '\0';
808 q++;
810 if (*q == ':') {
811 *q++ = '\0';
812 ofmt->symdef(value, 0L, 0L, 3, q);
815 break;
816 case 6: /* [ABSOLUTE address] */
817 stdscan_reset();
818 stdscan_bufptr = value;
819 tokval.t_type = TOKEN_INVALID;
820 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, report_error,
821 NULL);
822 if (e) {
823 if (!is_reloc(e))
824 report_error (pass==1 ? ERR_NONFATAL : ERR_PANIC,
825 "cannot use non-relocatable expression as "
826 "ABSOLUTE address");
827 else {
828 abs_seg = reloc_seg(e);
829 abs_offset = reloc_value(e);
831 } else
832 if (pass==1) abs_offset = 0x100;/* don't go near zero in case of / */
833 else report_error (ERR_PANIC, "invalid ABSOLUTE address "
834 "in pass two");
835 in_abs_seg = TRUE;
836 location.segment = abs_seg;
837 break;
838 case 7: /* DEBUG */
839 p = value;
840 q = debugid;
841 validid = TRUE;
842 if (!isidstart(*p))
843 validid = FALSE;
844 while (*p && !isspace(*p)) {
845 if (!isidchar(*p))
846 validid = FALSE;
847 *q++ = *p++;
849 *q++ = 0;
850 if (!validid) {
851 report_error (pass==1 ? ERR_NONFATAL : ERR_PANIC,
852 "identifier expected after DEBUG");
853 break;
855 while (*p && isspace(*p)) p++;
856 if (pass==pass_max) ofmt->current_dfmt->debug_directive (debugid, p);
857 break;
858 case 8: /* [WARNING {+|-}warn-name] */
859 if (pass1 == 1) {
860 while (*value && isspace(*value))
861 value++;
863 if (*value == '+' || *value == '-') {
864 validid = (*value == '-') ? TRUE : FALSE;
865 value++;
866 } else
867 validid = FALSE;
869 for (i=1; i<=ERR_WARN_MAX; i++)
870 if (!nasm_stricmp(value, suppressed_names[i]))
871 break;
872 if (i <= ERR_WARN_MAX)
873 suppressed[i] = validid;
874 else
875 report_error (ERR_NONFATAL, "invalid warning id in WARNING directive");
877 break;
878 case 9: /* cpu */
879 cpu = get_cpu (value);
880 break;
881 default:
882 if (!ofmt->directive (line+1, value, pass1))
883 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
884 "unrecognised directive [%s]",
885 line+1);
886 break;
889 else /* it isn't a directive */
891 parse_line (pass2, line, &output_ins,
892 report_error, evaluate,
893 def_label);
895 if (!optimizing && pass == 2) {
896 if (forwref != NULL && globallineno == forwref->lineno) {
897 output_ins.forw_ref = TRUE;
898 do {
899 output_ins.oprs[forwref->operand].opflags|= OPFLAG_FORWARD;
900 forwref = saa_rstruct (forwrefs);
901 } while (forwref != NULL && forwref->lineno == globallineno);
902 } else
903 output_ins.forw_ref = FALSE;
907 if (!optimizing && output_ins.forw_ref)
909 if (pass == 1) {
910 for(i = 0; i < output_ins.operands; i++)
912 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD)
914 struct forwrefinfo *fwinf =
915 (struct forwrefinfo *)saa_wstruct(forwrefs);
916 fwinf->lineno = globallineno;
917 fwinf->operand = i;
920 } else { /* pass == 2 */
922 * Hack to prevent phase error in the code
923 * rol ax,x
924 * x equ 1
926 * If the second operand is a forward reference,
927 * the UNITY property of the number 1 in that
928 * operand is cancelled. Otherwise the above
929 * sequence will cause a phase error.
931 * This hack means that the above code will
932 * generate 286+ code.
934 * The forward reference will mean that the
935 * operand will not have the UNITY property on
936 * the first pass, so the pass behaviours will
937 * be consistent.
940 if (output_ins.operands >= 2 &&
941 (output_ins.oprs[1].opflags & OPFLAG_FORWARD))
943 output_ins.oprs[1].type &= ~(ONENESS|BYTENESS);
946 } /* pass == 2 */
948 } /* forw_ref */
951 if (output_ins.opcode == I_EQU) {
952 if (pass1 == 1)
955 * Special `..' EQUs get processed in pass two,
956 * except `..@' macro-processor EQUs which are done
957 * in the normal place.
959 if (!output_ins.label)
960 report_error (ERR_NONFATAL,
961 "EQU not preceded by label");
963 else if (output_ins.label[0] != '.' ||
964 output_ins.label[1] != '.' ||
965 output_ins.label[2] == '@')
967 if (output_ins.operands == 1 &&
968 (output_ins.oprs[0].type & IMMEDIATE) &&
969 output_ins.oprs[0].wrt == NO_SEG)
971 int isext = output_ins.oprs[0].opflags & OPFLAG_EXTERN;
972 def_label (output_ins.label,
973 output_ins.oprs[0].segment,
974 output_ins.oprs[0].offset,
975 NULL, FALSE, isext, ofmt, report_error);
977 else if (output_ins.operands == 2 &&
978 (output_ins.oprs[0].type & IMMEDIATE) &&
979 (output_ins.oprs[0].type & COLON) &&
980 output_ins.oprs[0].segment == NO_SEG &&
981 output_ins.oprs[0].wrt == NO_SEG &&
982 (output_ins.oprs[1].type & IMMEDIATE) &&
983 output_ins.oprs[1].segment == NO_SEG &&
984 output_ins.oprs[1].wrt == NO_SEG)
986 def_label (output_ins.label,
987 output_ins.oprs[0].offset | SEG_ABS,
988 output_ins.oprs[1].offset,
989 NULL, FALSE, FALSE, ofmt, report_error);
991 else
992 report_error(ERR_NONFATAL, "bad syntax for EQU");
994 } else { /* pass == 2 */
996 * Special `..' EQUs get processed here, except
997 * `..@' macro processor EQUs which are done above.
999 if (output_ins.label[0] == '.' &&
1000 output_ins.label[1] == '.' &&
1001 output_ins.label[2] != '@')
1003 if (output_ins.operands == 1 &&
1004 (output_ins.oprs[0].type & IMMEDIATE)) {
1005 define_label (output_ins.label,
1006 output_ins.oprs[0].segment,
1007 output_ins.oprs[0].offset,
1008 NULL, FALSE, FALSE, ofmt, report_error);
1010 else if (output_ins.operands == 2 &&
1011 (output_ins.oprs[0].type & IMMEDIATE) &&
1012 (output_ins.oprs[0].type & COLON) &&
1013 output_ins.oprs[0].segment == NO_SEG &&
1014 (output_ins.oprs[1].type & IMMEDIATE) &&
1015 output_ins.oprs[1].segment == NO_SEG)
1017 define_label (output_ins.label,
1018 output_ins.oprs[0].offset | SEG_ABS,
1019 output_ins.oprs[1].offset,
1020 NULL, FALSE, FALSE, ofmt, report_error);
1022 else
1023 report_error(ERR_NONFATAL, "bad syntax for EQU");
1025 } /* pass == 2 */
1026 } else { /* instruction isn't an EQU */
1028 if (pass1 == 1) {
1029 long l = insn_size (location.segment, offs, sb, cpu,
1030 &output_ins, report_error);
1031 if (using_debug_info && output_ins.opcode != -1) {
1032 /* this is done here so we can do debug type info */
1033 long typeinfo = TYS_ELEMENTS(output_ins.operands);
1034 switch (output_ins.opcode) {
1035 case I_RESB:
1036 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1037 break;
1038 case I_RESW:
1039 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1040 break;
1041 case I_RESD:
1042 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1043 break;
1044 case I_RESQ:
1045 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1046 break;
1047 case I_REST:
1048 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1049 break;
1050 case I_DB:
1051 typeinfo |= TY_BYTE;
1052 break;
1053 case I_DW:
1054 typeinfo |= TY_WORD;
1055 break;
1056 case I_DD:
1057 if (output_ins.eops_float)
1058 typeinfo |= TY_FLOAT;
1059 else
1060 typeinfo |= TY_DWORD;
1061 break;
1062 case I_DQ:
1063 typeinfo |= TY_QWORD;
1064 break;
1065 case I_DT:
1066 typeinfo |= TY_TBYTE;
1067 break;
1068 default:
1069 typeinfo = TY_LABEL;
1071 ofmt->current_dfmt->debug_typevalue(typeinfo);
1073 if (l != -1) {
1074 offs += l;
1075 SET_CURR_OFFS (offs);
1078 * else l == -1 => invalid instruction, which will be
1079 * flagged as an error on pass 2
1082 } else { /* pass == 2 */
1083 offs += assemble (location.segment, offs, sb, cpu,
1084 &output_ins, ofmt, report_error, &nasmlist);
1085 SET_CURR_OFFS (offs);
1088 } /* not an EQU */
1089 cleanup_insn (&output_ins);
1091 nasm_free (line);
1092 location.offset = offs = GET_CURR_OFFS;
1093 } /* end while (line = preproc->getline... */
1095 if (pass1==2 && global_offset_changed)
1096 report_error(ERR_NONFATAL, "phase error detected at end of assembly.");
1098 if (pass1 == 1) preproc->cleanup();
1100 if (pass1==1 && terminate_after_phase) {
1101 fclose(ofile);
1102 remove(outname);
1103 if (want_usage)
1104 usage();
1105 exit (1);
1107 pass_cnt++;
1108 if (pass>1 && !global_offset_changed && pass<pass_max) pass = pass_max-1;
1109 } /* for (pass=1; pass<=2; pass++) */
1111 nasmlist.cleanup();
1112 #if 1
1113 if (optimizing)
1114 fprintf(error_file,
1115 "info:: assembly required 1+%d+1 passes\n", pass_cnt-2);
1116 #endif
1117 } /* exit from assemble_file (...) */
1120 static int getkw (char *buf, char **value)
1122 char *p, *q;
1124 if (*buf!='[')
1125 return 0;
1127 p = buf;
1129 while (*p && *p != ']') p++;
1131 if (!*p)
1132 return 0;
1134 q = p++;
1136 while (*p && *p != ';') {
1137 if (!isspace(*p))
1138 return 0;
1139 p++;
1141 q[1] = '\0';
1143 p = buf+1;
1144 while (*buf && *buf!=' ' && *buf!=']' && *buf!='\t')
1145 buf++;
1146 if (*buf==']') {
1147 *buf = '\0';
1148 *value = buf;
1149 } else {
1150 *buf++ = '\0';
1151 while (isspace(*buf)) buf++; /* beppu - skip leading whitespace */
1152 *value = buf;
1153 while (*buf!=']') buf++;
1154 *buf++ = '\0';
1156 #if 0
1157 for (q=p; *q; q++)
1158 *q = tolower(*q);
1159 #endif
1160 if (!nasm_stricmp(p, "segment") || !nasm_stricmp(p, "section"))
1161 return 1;
1162 if (!nasm_stricmp(p, "extern"))
1163 return 2;
1164 if (!nasm_stricmp(p, "bits"))
1165 return 3;
1166 if (!nasm_stricmp(p, "global"))
1167 return 4;
1168 if (!nasm_stricmp(p, "common"))
1169 return 5;
1170 if (!nasm_stricmp(p, "absolute"))
1171 return 6;
1172 if (!nasm_stricmp(p, "debug"))
1173 return 7;
1174 if (!nasm_stricmp(p, "warning"))
1175 return 8;
1176 if (!nasm_stricmp(p, "cpu"))
1177 return 9;
1178 return -1;
1181 static void report_error (int severity, char *fmt, ...)
1183 va_list ap;
1186 * See if it's a suppressed warning.
1188 if ((severity & ERR_MASK) == ERR_WARNING &&
1189 (severity & ERR_WARN_MASK) != 0 &&
1190 suppressed[ (severity & ERR_WARN_MASK) >> ERR_WARN_SHR ])
1191 return; /* and bail out if so */
1194 * See if it's a pass-one only warning and we're not in pass one.
1196 if ((severity & ERR_PASS1) && pass != 1)
1197 return;
1199 if (severity & ERR_NOFILE)
1200 fputs ("nasm: ", error_file);
1201 else {
1202 char * currentfile = NULL;
1203 long lineno = 0;
1204 src_get (&lineno, &currentfile);
1205 fprintf (error_file, "%s:%ld: ", currentfile, lineno);
1206 nasm_free (currentfile);
1209 switch (severity & ERR_MASK) {
1210 case ERR_WARNING:
1211 fputs ("warning: ", error_file); break;
1212 case ERR_NONFATAL:
1213 fputs ("error: ", error_file); break;
1214 case ERR_FATAL:
1215 fputs ("fatal: ", error_file); break;
1216 case ERR_PANIC:
1217 fputs ("panic: ", error_file); break;
1218 case ERR_DEBUG:
1219 fputs("debug: ", error_file); break;
1222 va_start (ap, fmt);
1223 vfprintf (error_file, fmt, ap);
1224 fputc ('\n', error_file);
1226 if (severity & ERR_USAGE)
1227 want_usage = TRUE;
1229 switch (severity & ERR_MASK) {
1230 case ERR_WARNING: case ERR_DEBUG:
1231 /* no further action, by definition */
1232 break;
1233 case ERR_NONFATAL:
1234 terminate_after_phase = TRUE;
1235 break;
1236 case ERR_FATAL:
1237 if (ofile) {
1238 fclose(ofile);
1239 remove(outname);
1241 if (want_usage)
1242 usage();
1243 exit(1); /* instantly die */
1244 break; /* placate silly compilers */
1245 case ERR_PANIC:
1246 fflush(NULL);
1247 /* abort(); */ /* halt, catch fire, and dump core */
1248 exit(3);
1249 break;
1253 static void usage(void)
1255 fputs("type `nasm -h' for help\n", error_file);
1258 static void register_output_formats(void)
1260 ofmt = ofmt_register (report_error);
1263 #define BUF_DELTA 512
1265 static FILE *no_pp_fp;
1266 static efunc no_pp_err;
1267 static ListGen *no_pp_list;
1268 static long no_pp_lineinc;
1270 static void no_pp_reset (char *file, int pass, efunc error, evalfunc eval,
1271 ListGen *listgen)
1273 src_set_fname(nasm_strdup(file));
1274 src_set_linnum(0);
1275 no_pp_lineinc = 1;
1276 no_pp_err = error;
1277 no_pp_fp = fopen(file, "r");
1278 if (!no_pp_fp)
1279 no_pp_err (ERR_FATAL | ERR_NOFILE,
1280 "unable to open input file `%s'", file);
1281 no_pp_list = listgen;
1282 (void) pass; /* placate compilers */
1283 (void) eval; /* placate compilers */
1286 static char *no_pp_getline (void)
1288 char *buffer, *p, *q;
1289 int bufsize;
1291 bufsize = BUF_DELTA;
1292 buffer = nasm_malloc(BUF_DELTA);
1293 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1295 while (1) { /* Loop to handle %line */
1297 p = buffer;
1298 while (1) { /* Loop to handle long lines */
1299 q = fgets(p, bufsize-(p-buffer), no_pp_fp);
1300 if (!q)
1301 break;
1302 p += strlen(p);
1303 if (p > buffer && p[-1] == '\n')
1304 break;
1305 if (p-buffer > bufsize-10) {
1306 int offset;
1307 offset = p - buffer;
1308 bufsize += BUF_DELTA;
1309 buffer = nasm_realloc(buffer, bufsize);
1310 p = buffer + offset;
1314 if (!q && p == buffer) {
1315 nasm_free (buffer);
1316 return NULL;
1320 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1321 * them are present at the end of the line.
1323 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1325 if (!strncmp(buffer, "%line", 5)) {
1326 long ln;
1327 int li;
1328 char *nm = nasm_malloc(strlen(buffer));
1329 if (sscanf(buffer+5, "%ld+%d %s", &ln, &li, nm) == 3) {
1330 nasm_free( src_set_fname(nm) );
1331 src_set_linnum(ln);
1332 no_pp_lineinc = li;
1333 continue;
1335 nasm_free(nm);
1337 break;
1340 no_pp_list->line (LIST_READ, buffer);
1342 return buffer;
1345 static void no_pp_cleanup (void)
1347 fclose(no_pp_fp);
1350 static unsigned long get_cpu (char *value)
1353 if (!strcmp(value, "8086")) return IF_8086;
1354 if (!strcmp(value, "186")) return IF_186;
1355 if (!strcmp(value, "286")) return IF_286;
1356 if (!strcmp(value, "386")) return IF_386;
1357 if (!strcmp(value, "486")) return IF_486;
1358 if (!strcmp(value, "586") ||
1359 !nasm_stricmp(value, "pentium") ) return IF_PENT;
1360 if (!strcmp(value, "686") ||
1361 !nasm_stricmp(value, "ppro") ||
1362 !nasm_stricmp(value, "p2") ) return IF_P6;
1363 if (!nasm_stricmp(value, "p3") ||
1364 !nasm_stricmp(value, "katmai") ) return IF_KATMAI;
1366 report_error (pass ? ERR_NONFATAL : ERR_FATAL, "unknown 'cpu' type");
1368 return IF_PLEVEL; /* the maximum level */
1372 static int get_bits (char *value)
1374 int i;
1376 if ((i = atoi(value)) == 16) return i; /* set for a 16-bit segment */
1377 else if (i == 32) {
1378 if (cpu < IF_386) {
1379 report_error(ERR_NONFATAL,
1380 "cannot specify 32-bit segment on processor below a 386");
1381 i = 16;
1383 } else {
1384 report_error(pass ? ERR_NONFATAL : ERR_FATAL,
1385 "`%s' is not a valid segment size; must be 16 or 32",
1386 value);
1387 i = 16;
1389 return i;
1392 /* end of nasm.c */