Change the index term for "overloading multi-line macros" to match
[nasm/autotest.git] / nasm.c
blobc0b4d4682a68d4105c275423a6b6cb9373ade03e
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 parse_cmdline (int, char **);
34 static void assemble_file (char *);
35 static int getkw (char *buf, char **value);
36 static void register_output_formats(void);
37 static void report_error (int severity, const char *fmt, ...);
38 static void usage(void);
40 static int using_debug_info;
41 int tasm_compatible_mode = FALSE;
42 int pass0;
44 static char inname[FILENAME_MAX];
45 static char outname[FILENAME_MAX];
46 static char listname[FILENAME_MAX];
47 static int globallineno; /* for forward-reference tracking */
48 /* static int pass = 0; */
49 static struct ofmt *ofmt = NULL;
51 static FILE *error_file; /* Where to write error messages */
53 static FILE *ofile = NULL;
54 int optimizing = -1; /* number of optimization passes to take */
55 static int sb, cmd_sb = 16; /* by default */
56 static unsigned long cmd_cpu = IF_PLEVEL; /* highest level by default */
57 static unsigned long cpu = IF_PLEVEL; /* passed to insn_size & assemble.c */
58 int global_offset_changed; /* referenced in labels.c */
60 static loc_t location;
61 int in_abs_seg; /* Flag we are in ABSOLUTE seg */
62 static long abs_seg;
64 static struct RAA *offsets;
65 static long abs_offset;
67 static struct SAA *forwrefs; /* keep track of forward references */
68 static struct forwrefinfo *forwref;
70 static Preproc *preproc;
71 enum op_type {
72 op_normal, /* Preprocess and assemble */
73 op_preprocess, /* Preprocess only */
74 op_depend /* Generate dependencies */
76 static enum op_type operating_mode;
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, TRUE
87 * The option names for the suppressible warnings. As before, entry
88 * zero does nothing.
90 static const char *suppressed_names[1+ERR_WARN_MAX] = {
91 NULL, "macro-params", "macro-selfref", "orphan-labels", "number-overflow",
92 "gnu-elf-extensions"
96 * The explanations for the suppressible warnings. As before, entry
97 * zero does nothing.
99 static const char *suppressed_what[1+ERR_WARN_MAX] = {
100 NULL,
101 "macro calls with wrong no. of params",
102 "cyclic macro self-references",
103 "labels alone on lines without trailing `:'",
104 "numeric constants greater than 0xFFFFFFFF",
105 "using 8- or 16-bit relocation in ELF, a GNU extension"
109 * This is a null preprocessor which just copies lines from input
110 * to output. It's used when someone explicitly requests that NASM
111 * not preprocess their source file.
114 static void no_pp_reset (char *, int, efunc, evalfunc, ListGen *);
115 static char *no_pp_getline (void);
116 static void no_pp_cleanup (int);
117 static Preproc no_pp = {
118 no_pp_reset,
119 no_pp_getline,
120 no_pp_cleanup
124 * get/set current offset...
126 #define GET_CURR_OFFS (in_abs_seg?abs_offset:\
127 raa_read(offsets,location.segment))
128 #define SET_CURR_OFFS(x) (in_abs_seg?(void)(abs_offset=(x)):\
129 (void)(offsets=raa_write(offsets,location.segment,(x))))
131 static int want_usage;
132 static int terminate_after_phase;
133 int user_nolist = 0; /* fbk 9/2/00 */
135 static void nasm_fputs(const char *line, FILE *outfile)
137 if (outfile) {
138 fputs(line, outfile);
139 fputc('\n', outfile);
140 } else
141 puts(line);
144 int main(int argc, char **argv)
146 pass0 = 1;
147 want_usage = terminate_after_phase = FALSE;
149 nasm_set_malloc_error (report_error);
150 offsets = raa_init();
151 forwrefs = saa_init ((long)sizeof(struct forwrefinfo));
153 preproc = &nasmpp;
154 operating_mode = op_normal;
156 error_file = stderr;
158 seg_init();
160 register_output_formats();
162 parse_cmdline(argc, argv);
164 if (terminate_after_phase)
166 if (want_usage)
167 usage();
168 return 1;
171 if (ofmt->stdmac)
172 pp_extra_stdmac (ofmt->stdmac);
173 parser_global_info (ofmt, &location);
174 eval_global_info (ofmt, lookup_label, &location);
176 /* define some macros dependent of command-line */
178 char temp [64];
179 sprintf (temp, "__OUTPUT_FORMAT__=%s\n", ofmt->shortname);
180 pp_pre_define (temp);
183 switch ( operating_mode ) {
184 case op_depend:
186 char *line;
187 preproc->reset (inname, 0, report_error, evaluate, &nasmlist);
188 if (outname[0] == '\0')
189 ofmt->filename (inname, outname, report_error);
190 ofile = NULL;
191 fprintf(stdout, "%s: %s", outname, inname);
192 while ( (line = preproc->getline()) )
193 nasm_free (line);
194 preproc->cleanup(0);
195 putc('\n', stdout);
197 break;
199 case op_preprocess:
201 char *line;
202 char *file_name = NULL;
203 long prior_linnum=0;
204 int lineinc=0;
206 if (*outname) {
207 ofile = fopen(outname, "w");
208 if (!ofile)
209 report_error (ERR_FATAL | ERR_NOFILE,
210 "unable to open output file `%s'", outname);
211 } else
212 ofile = NULL;
214 location.known = FALSE;
216 /* pass = 1; */
217 preproc->reset (inname, 2, report_error, evaluate, &nasmlist);
218 while ( (line = preproc->getline()) ) {
220 * We generate %line directives if needed for later programs
222 long linnum = prior_linnum += lineinc;
223 int altline = src_get(&linnum, &file_name);
224 if (altline) {
225 if (altline==1 && lineinc==1)
226 nasm_fputs("", ofile);
227 else {
228 lineinc = (altline != -1 || lineinc!=1);
229 fprintf(ofile ? ofile : stdout, "%%line %ld+%d %s\n",
230 linnum, lineinc, file_name);
232 prior_linnum = linnum;
234 nasm_fputs(line, ofile);
235 nasm_free (line);
237 nasm_free(file_name);
238 preproc->cleanup(0);
239 if (ofile)
240 fclose(ofile);
241 if (ofile && terminate_after_phase)
242 remove(outname);
244 break;
246 case op_normal:
249 * We must call ofmt->filename _anyway_, even if the user
250 * has specified their own output file, because some
251 * formats (eg OBJ and COFF) use ofmt->filename to find out
252 * the name of the input file and then put that inside the
253 * file.
255 ofmt->filename (inname, outname, report_error);
257 ofile = fopen(outname, "wb");
258 if (!ofile) {
259 report_error (ERR_FATAL | ERR_NOFILE,
260 "unable to open output file `%s'", outname);
264 * We must call init_labels() before ofmt->init() since
265 * some object formats will want to define labels in their
266 * init routines. (eg OS/2 defines the FLAT group)
268 init_labels ();
270 ofmt->init (ofile, report_error, define_label, evaluate);
272 assemble_file (inname);
274 if (!terminate_after_phase) {
275 ofmt->cleanup (using_debug_info);
276 cleanup_labels ();
277 } else {
279 * We had an fclose on the output file here, but we
280 * actually do that in all the object file drivers as well,
281 * so we're leaving out the one here.
282 * fclose (ofile);
284 remove(outname);
285 if (listname[0])
286 remove(listname);
289 break;
292 if (want_usage)
293 usage();
295 raa_free (offsets);
296 saa_free (forwrefs);
297 eval_cleanup ();
298 nasmlib_cleanup ();
300 if (terminate_after_phase)
301 return 1;
302 else
303 return 0;
308 * Get a parameter for a command line option.
309 * First arg must be in the form of e.g. -f...
311 static char *get_param (char *p, char *q, int *advance)
313 *advance = 0;
314 if (p[2]) /* the parameter's in the option */
316 p += 2;
317 while (isspace(*p))
318 p++;
319 return p;
321 if (q && q[0])
323 *advance = 1;
324 return q;
326 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
327 "option `-%c' requires an argument",
328 p[1]);
329 return NULL;
332 struct textargs
334 const char *label;
335 int value;
338 #define OPT_PREFIX 0
339 #define OPT_POSTFIX 1
340 struct textargs textopts[] =
342 {"prefix",OPT_PREFIX},
343 {"postfix",OPT_POSTFIX},
344 {NULL,0}
348 int stopoptions = 0;
349 static int process_arg (char *p, char *q)
351 char *param;
352 int i, advance = 0;
354 if (!p || !p[0])
355 return 0;
357 if (p[0]=='-' && ! stopoptions)
359 switch (p[1]) {
360 case 's':
361 error_file = stdout;
362 break;
363 case 'o': /* these parameters take values */
364 case 'O':
365 case 'f':
366 case 'p':
367 case 'P':
368 case 'd':
369 case 'D':
370 case 'i':
371 case 'I':
372 case 'l':
373 case 'E':
374 case 'F':
375 if ( !(param = get_param (p, q, &advance)) )
376 break;
377 if (p[1]=='o') { /* output file */
378 strcpy (outname, param);
379 } else if (p[1]=='f') { /* output format */
380 ofmt = ofmt_find(param);
381 if (!ofmt) {
382 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
383 "unrecognised output format `%s' - "
384 "use -hf for a list",
385 param);
387 else
388 ofmt->current_dfmt = ofmt->debug_formats[0];
389 } else if (p[1]=='O') { /* Optimization level */
390 int opt;
391 if (!isdigit(*param)) report_error(ERR_FATAL,
392 "command line optimization level must be 0..3 or <nn>");
393 opt = atoi(param);
394 if (opt<=0) optimizing = -1; /* 0.98 behaviour */
395 else if (opt==1) optimizing = 0; /* Two passes, 0.98.09 behavior */
396 else if (opt<=3) optimizing = opt*5; /* Multiple passes */
397 else optimizing = opt; /* Multiple passes */
398 } else if (p[1]=='P' || p[1]=='p') { /* pre-include */
399 pp_pre_include (param);
400 } else if (p[1]=='D' || p[1]=='d') { /* pre-define */
401 pp_pre_define (param);
402 } else if (p[1]=='U' || p[1]=='u') { /* un-define */
403 pp_pre_undefine (param);
404 } else if (p[1]=='I' || p[1]=='i') { /* include search path */
405 pp_include_path (param);
406 } else if (p[1]=='l') { /* listing file */
407 strcpy (listname, param);
408 } else if (p[1]=='E') { /* error messages file */
409 error_file = fopen(param, "w");
410 if ( !error_file ) {
411 error_file = stderr; /* Revert to default! */
412 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
413 "cannot open file `%s' for error messages",
414 param);
416 } else if (p[1] == 'F') { /* specify debug format */
417 ofmt->current_dfmt = dfmt_find(ofmt, param);
418 if (!ofmt->current_dfmt) {
419 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
420 "unrecognized debug format `%s' for"
421 " output format `%s'",
422 param, ofmt->shortname);
425 break;
426 case 'g':
427 using_debug_info = TRUE;
428 break;
429 case 'h':
430 printf("usage: nasm [-@ response file] [-o outfile] [-f format] "
431 "[-l listfile]\n"
432 " [options...] [--] filename\n"
433 " or nasm -r for version info (obsolete)\n"
434 " or nasm -v for version info (preferred)\n\n"
435 " -t Assemble in SciTech TASM compatible mode\n"
436 " -g Generate debug information in selected format.\n");
437 printf(" -e preprocess only (writes output to stdout by default)\n"
438 " -a don't preprocess (assemble only)\n"
439 " -M generate Makefile dependencies on stdout\n\n"
440 " -E<file> redirect error messages to file\n"
441 " -s redirect error messages to stdout\n\n"
442 " -F format select a debugging format\n\n"
443 " -I<path> adds a pathname to the include file path\n");
444 printf(" -O<digit> optimize branch offsets (-O0 disables, default)\n"
445 " -P<file> pre-includes a file\n"
446 " -D<macro>[=<value>] pre-defines a macro\n"
447 " -U<macro> undefines a macro\n"
448 " -w+foo enables warnings about foo; -w-foo disables them\n"
449 "where foo can be:\n");
450 for (i=1; i<=ERR_WARN_MAX; i++)
451 printf(" %-23s %s (default %s)\n",
452 suppressed_names[i], suppressed_what[i],
453 suppressed[i] ? "off" : "on");
454 printf ("\nresponse files should contain command line parameters"
455 ", one per line.\n");
456 if (p[2] == 'f') {
457 printf("\nvalid output formats for -f are"
458 " (`*' denotes default):\n");
459 ofmt_list(ofmt, stdout);
461 else {
462 printf ("\nFor a list of valid output formats, use -hf.\n");
463 printf ("For a list of debug formats, use -f <form> -y.\n");
465 exit (0); /* never need usage message here */
466 break;
467 case 'y':
468 printf("\nvalid debug formats for '%s' output format are"
469 " ('*' denotes default):\n",
470 ofmt->shortname);
471 dfmt_list(ofmt, stdout);
472 exit(0);
473 break;
474 case 't':
475 tasm_compatible_mode = TRUE;
476 break;
477 case 'r':
478 case 'v':
479 printf("NASM version %s compiled "
480 #ifdef DEBUG
481 "with -DDEBUG "
482 #endif
483 "on " __DATE__ "\n", NASM_VER);
484 exit (0); /* never need usage message here */
485 break;
486 case 'e': /* preprocess only */
487 operating_mode = op_preprocess;
488 break;
489 case 'a': /* assemble only - don't preprocess */
490 preproc = &no_pp;
491 break;
492 case 'w':
493 if (p[2] != '+' && p[2] != '-') {
494 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
495 "invalid option to `-w'");
496 } else {
497 for (i=1; i<=ERR_WARN_MAX; i++)
498 if (!nasm_stricmp(p+3, suppressed_names[i]))
499 break;
500 if (i <= ERR_WARN_MAX)
501 suppressed[i] = (p[2] == '-');
502 else
503 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
504 "invalid option to `-w'");
506 break;
507 case 'M':
508 operating_mode = op_depend;
509 break;
511 case '-':
513 int s;
515 if (p[2]==0) { /* -- => stop processing options */
516 stopoptions = 1;
517 break;
519 for(s=0; textopts[s].label; s++)
521 if(!nasm_stricmp(p+2, textopts[s].label))
523 break;
527 switch(s)
530 case OPT_PREFIX:
531 case OPT_POSTFIX:
533 if (!q)
535 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
536 "option `--%s' requires an argument",
537 p+2);
538 break;
540 else
542 advance = 1, param = q;
545 if(s == OPT_PREFIX)
547 strncpy(lprefix,param,PREFIX_MAX-1);
548 lprefix[PREFIX_MAX-1]=0;
549 break;
551 if(s == OPT_POSTFIX)
553 strncpy(lpostfix,param,POSTFIX_MAX-1);
554 lpostfix[POSTFIX_MAX-1]=0;
555 break;
557 break;
559 default:
561 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
562 "unrecognised option `--%s'",
563 p+2);
564 break;
567 break;
570 default:
571 if (!ofmt->setinfo(GI_SWITCH,&p))
572 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
573 "unrecognised option `-%c'",
574 p[1]);
575 break;
578 else
580 if (*inname) {
581 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
582 "more than one input file specified");
583 } else
584 strcpy(inname, p);
587 return advance;
590 #define ARG_BUF_DELTA 128
592 static void process_respfile (FILE *rfile)
594 char *buffer, *p, *q, *prevarg;
595 int bufsize, prevargsize;
597 bufsize = prevargsize = ARG_BUF_DELTA;
598 buffer = nasm_malloc(ARG_BUF_DELTA);
599 prevarg = nasm_malloc(ARG_BUF_DELTA);
600 prevarg[0] = '\0';
602 while (1) { /* Loop to handle all lines in file */
604 p = buffer;
605 while (1) { /* Loop to handle long lines */
606 q = fgets(p, bufsize-(p-buffer), rfile);
607 if (!q)
608 break;
609 p += strlen(p);
610 if (p > buffer && p[-1] == '\n')
611 break;
612 if (p-buffer > bufsize-10) {
613 int offset;
614 offset = p - buffer;
615 bufsize += ARG_BUF_DELTA;
616 buffer = nasm_realloc(buffer, bufsize);
617 p = buffer + offset;
621 if (!q && p == buffer) {
622 if (prevarg[0])
623 process_arg (prevarg, NULL);
624 nasm_free (buffer);
625 nasm_free (prevarg);
626 return;
630 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
631 * them are present at the end of the line.
633 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
635 while (p > buffer && isspace(p[-1]))
636 *--p = '\0';
638 p = buffer;
639 while (isspace(*p))
640 p++;
642 if (process_arg (prevarg, p))
643 *p = '\0';
645 if (strlen(p) > prevargsize-10) {
646 prevargsize += ARG_BUF_DELTA;
647 prevarg = nasm_realloc(prevarg, prevargsize);
649 strcpy (prevarg, p);
653 /* Function to process args from a string of args, rather than the
654 * argv array. Used by the environment variable and response file
655 * processing.
657 static void process_args (char *args) {
658 char *p, *q, *arg, *prevarg;
659 char separator = ' ';
661 p = args;
662 if (*p && *p != '-')
663 separator = *p++;
664 arg = NULL;
665 while (*p) {
666 q = p;
667 while (*p && *p != separator) p++;
668 while (*p == separator) *p++ = '\0';
669 prevarg = arg;
670 arg = q;
671 if (process_arg (prevarg, arg))
672 arg = NULL;
674 if (arg)
675 process_arg (arg, NULL);
678 static void parse_cmdline(int argc, char **argv)
680 FILE *rfile;
681 char *envreal, *envcopy=NULL, *p, *arg;
683 *inname = *outname = *listname = '\0';
686 * First, process the NASMENV environment variable.
688 envreal = getenv("NASMENV");
689 arg = NULL;
690 if (envreal) {
691 envcopy = nasm_strdup(envreal);
692 process_args(envcopy);
693 nasm_free (envcopy);
697 * Now process the actual command line.
699 while (--argc)
701 int i;
702 argv++;
703 if (argv[0][0] == '@') {
704 /* We have a response file, so process this as a set of
705 * arguments like the environment variable. This allows us
706 * to have multiple arguments on a single line, which is
707 * different to the -@resp file processing below for regular
708 * NASM.
710 char *str = malloc(2048);
711 FILE *f = fopen(&argv[0][1],"r");
712 if (!str) {
713 printf("out of memory");
714 exit(-1);
716 if (f) {
717 while (fgets(str,2048,f)) {
718 process_args(str);
720 fclose(f);
722 free(str);
723 argc--;
724 argv++;
726 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
727 if ((p = get_param (argv[0], argc > 1 ? argv[1] : NULL, &i))) {
728 if ((rfile = fopen(p, "r"))) {
729 process_respfile (rfile);
730 fclose(rfile);
731 } else
732 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
733 "unable to open response file `%s'", p);
735 } else
736 i = process_arg (argv[0], argc > 1 ? argv[1] : NULL);
737 argv += i, argc -= i;
740 if (!*inname)
741 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
742 "no input file specified");
746 static void assemble_file (char *fname)
748 char * value, * p, * q, * special, * line, debugid[80];
749 insn output_ins;
750 int i, rn_error, validid;
751 long seg, offs;
752 struct tokenval tokval;
753 expr * e;
754 int pass, pass_max;
755 int pass_cnt = 0; /* count actual passes */
757 if (cmd_sb == 32 && cmd_cpu < IF_386)
758 report_error(ERR_FATAL, "command line: "
759 "32-bit segment size requires a higher cpu");
761 pass_max = (optimizing>0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
762 pass0 = !(optimizing>0); /* start at 1 if not optimizing */
763 for (pass = 1; pass <= pass_max && pass0 <= 2; pass++) {
764 int pass1, pass2;
765 ldfunc def_label;
767 pass1 = pass < pass_max ? 1 : 2; /* seq is 1, 1, 1,..., 1, 2 */
768 pass2 = pass > 1 ? 2 : 1; /* seq is 1, 2, 2,..., 2, 2 */
769 /* pass0 seq is 0, 0, 0,..., 1, 2 */
771 def_label = pass > 1 ? redefine_label : define_label;
774 sb = cmd_sb; /* set 'bits' to command line default */
775 cpu = cmd_cpu;
776 if (pass0 == 2) {
777 if (*listname)
778 nasmlist.init(listname, report_error);
780 in_abs_seg = FALSE;
781 global_offset_changed = FALSE; /* set by redefine_label */
782 location.segment = ofmt->section(NULL, pass2, &sb);
783 if (pass > 1) {
784 saa_rewind (forwrefs);
785 forwref = saa_rstruct (forwrefs);
786 raa_free (offsets);
787 offsets = raa_init();
789 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
790 globallineno = 0;
791 if (pass == 1) location.known = TRUE;
792 location.offset = offs = GET_CURR_OFFS;
794 while ( (line = preproc->getline()) )
796 globallineno++;
798 /* here we parse our directives; this is not handled by the 'real'
799 * parser. */
800 if ( (i = getkw (line, &value)) )
802 switch (i) {
803 case 1: /* [SEGMENT n] */
804 seg = ofmt->section (value, pass2, &sb);
805 if (seg == NO_SEG) {
806 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
807 "segment name `%s' not recognised",
808 value);
809 } else {
810 in_abs_seg = FALSE;
811 location.segment = seg;
813 break;
814 case 2: /* [EXTERN label:special] */
815 if (*value == '$') value++; /* skip initial $ if present */
816 if (pass0 == 2) {
817 q = value;
818 while (*q && *q != ':')
819 q++;
820 if (*q == ':') {
821 *q++ = '\0';
822 ofmt->symdef(value, 0L, 0L, 3, q);
824 } else if (pass == 1) { /* pass == 1 */
825 q = value;
826 validid = TRUE;
827 if (!isidstart(*q))
828 validid = FALSE;
829 while (*q && *q != ':') {
830 if (!isidchar(*q))
831 validid = FALSE;
832 q++;
834 if (!validid) {
835 report_error (ERR_NONFATAL,
836 "identifier expected after EXTERN");
837 break;
839 if (*q == ':') {
840 *q++ = '\0';
841 special = q;
842 } else
843 special = NULL;
844 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
845 int temp = pass0;
846 pass0 = 1; /* fake pass 1 in labels.c */
847 declare_as_global (value, special, report_error);
848 define_label (value, seg_alloc(), 0L, NULL, FALSE, TRUE,
849 ofmt, report_error);
850 pass0 = temp;
852 } /* else pass0 == 1 */
853 break;
854 case 3: /* [BITS bits] */
855 sb = get_bits(value);
856 break;
857 case 4: /* [GLOBAL symbol:special] */
858 if (*value == '$') value++; /* skip initial $ if present */
859 if (pass0 == 2) { /* pass 2 */
860 q = value;
861 while (*q && *q != ':')
862 q++;
863 if (*q == ':') {
864 *q++ = '\0';
865 ofmt->symdef(value, 0L, 0L, 3, q);
867 } else if (pass2 == 1) { /* pass == 1 */
868 q = value;
869 validid = TRUE;
870 if (!isidstart(*q))
871 validid = FALSE;
872 while (*q && *q != ':') {
873 if (!isidchar(*q))
874 validid = FALSE;
875 q++;
877 if (!validid) {
878 report_error (ERR_NONFATAL,
879 "identifier expected after GLOBAL");
880 break;
882 if (*q == ':') {
883 *q++ = '\0';
884 special = q;
885 } else
886 special = NULL;
887 declare_as_global (value, special, report_error);
888 } /* pass == 1 */
889 break;
890 case 5: /* [COMMON symbol size:special] */
891 if (*value == '$') value++; /* skip initial $ if present */
892 if (pass0 == 1) {
893 p = value;
894 validid = TRUE;
895 if (!isidstart(*p))
896 validid = FALSE;
897 while (*p && !isspace(*p)) {
898 if (!isidchar(*p))
899 validid = FALSE;
900 p++;
902 if (!validid) {
903 report_error (ERR_NONFATAL,
904 "identifier expected after COMMON");
905 break;
907 if (*p) {
908 long size;
910 while (*p && isspace(*p))
911 *p++ = '\0';
912 q = p;
913 while (*q && *q != ':')
914 q++;
915 if (*q == ':') {
916 *q++ = '\0';
917 special = q;
918 } else
919 special = NULL;
920 size = readnum (p, &rn_error);
921 if (rn_error)
922 report_error (ERR_NONFATAL, "invalid size specified"
923 " in COMMON declaration");
924 else
925 define_common (value, seg_alloc(), size,
926 special, ofmt, report_error);
927 } else
928 report_error (ERR_NONFATAL, "no size specified in"
929 " COMMON declaration");
930 } else if (pass0 == 2) { /* pass == 2 */
931 q = value;
932 while (*q && *q != ':') {
933 if (isspace(*q))
934 *q = '\0';
935 q++;
937 if (*q == ':') {
938 *q++ = '\0';
939 ofmt->symdef(value, 0L, 0L, 3, q);
942 break;
943 case 6: /* [ABSOLUTE address] */
944 stdscan_reset();
945 stdscan_bufptr = value;
946 tokval.t_type = TOKEN_INVALID;
947 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, report_error,
948 NULL);
949 if (e) {
950 if (!is_reloc(e))
951 report_error (pass0==1 ? ERR_NONFATAL : ERR_PANIC,
952 "cannot use non-relocatable expression as "
953 "ABSOLUTE address");
954 else {
955 abs_seg = reloc_seg(e);
956 abs_offset = reloc_value(e);
958 } else
959 if (pass==1) abs_offset = 0x100;/* don't go near zero in case of / */
960 else report_error (ERR_PANIC, "invalid ABSOLUTE address "
961 "in pass two");
962 in_abs_seg = TRUE;
963 location.segment = abs_seg;
964 break;
965 case 7: /* DEBUG */
966 p = value;
967 q = debugid;
968 validid = TRUE;
969 if (!isidstart(*p))
970 validid = FALSE;
971 while (*p && !isspace(*p)) {
972 if (!isidchar(*p))
973 validid = FALSE;
974 *q++ = *p++;
976 *q++ = 0;
977 if (!validid) {
978 report_error (pass==1 ? ERR_NONFATAL : ERR_PANIC,
979 "identifier expected after DEBUG");
980 break;
982 while (*p && isspace(*p)) p++;
983 if (pass==pass_max) ofmt->current_dfmt->debug_directive (debugid, p);
984 break;
985 case 8: /* [WARNING {+|-}warn-name] */
986 if (pass1 == 1) {
987 while (*value && isspace(*value))
988 value++;
990 if (*value == '+' || *value == '-') {
991 validid = (*value == '-') ? TRUE : FALSE;
992 value++;
993 } else
994 validid = FALSE;
996 for (i=1; i<=ERR_WARN_MAX; i++)
997 if (!nasm_stricmp(value, suppressed_names[i]))
998 break;
999 if (i <= ERR_WARN_MAX)
1000 suppressed[i] = validid;
1001 else
1002 report_error (ERR_NONFATAL, "invalid warning id in WARNING directive");
1004 break;
1005 case 9: /* cpu */
1006 cpu = get_cpu (value);
1007 break;
1008 case 10: /* fbk 9/2/00 */ /* [LIST {+|-}] */
1009 while (*value && isspace(*value))
1010 value++;
1012 if (*value == '+') {
1013 user_nolist = 0;
1015 else {
1016 if (*value == '-') {
1017 user_nolist = 1;
1019 else {
1020 report_error (ERR_NONFATAL, "invalid parameter to \"list\" directive");
1023 break;
1024 default:
1025 if (!ofmt->directive (line+1, value, pass2))
1026 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
1027 "unrecognised directive [%s]",
1028 line+1);
1031 else /* it isn't a directive */
1033 parse_line (pass1, line, &output_ins,
1034 report_error, evaluate,
1035 def_label);
1037 if (!(optimizing>0) && pass == 2) {
1038 if (forwref != NULL && globallineno == forwref->lineno) {
1039 output_ins.forw_ref = TRUE;
1040 do {
1041 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1042 forwref = saa_rstruct (forwrefs);
1043 } while (forwref != NULL && forwref->lineno == globallineno);
1044 } else
1045 output_ins.forw_ref = FALSE;
1049 if (!(optimizing>0) && output_ins.forw_ref)
1051 if (pass == 1) {
1052 for(i = 0; i < output_ins.operands; i++)
1054 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD)
1056 struct forwrefinfo *fwinf =
1057 (struct forwrefinfo *)saa_wstruct(forwrefs);
1058 fwinf->lineno = globallineno;
1059 fwinf->operand = i;
1062 } else { /* pass == 2 */
1064 * Hack to prevent phase error in the code
1065 * rol ax,x
1066 * x equ 1
1068 * If the second operand is a forward reference,
1069 * the UNITY property of the number 1 in that
1070 * operand is cancelled. Otherwise the above
1071 * sequence will cause a phase error.
1073 * This hack means that the above code will
1074 * generate 286+ code.
1076 * The forward reference will mean that the
1077 * operand will not have the UNITY property on
1078 * the first pass, so the pass behaviours will
1079 * be consistent.
1082 if (output_ins.operands >= 2 &&
1083 (output_ins.oprs[1].opflags & OPFLAG_FORWARD))
1085 output_ins.oprs[1].type &= ~(ONENESS|BYTENESS);
1088 } /* pass == 2 */
1090 } /* forw_ref */
1093 if (output_ins.opcode == I_EQU) {
1094 if (pass1 == 1)
1097 * Special `..' EQUs get processed in pass two,
1098 * except `..@' macro-processor EQUs which are done
1099 * in the normal place.
1101 if (!output_ins.label)
1102 report_error (ERR_NONFATAL,
1103 "EQU not preceded by label");
1105 else if (output_ins.label[0] != '.' ||
1106 output_ins.label[1] != '.' ||
1107 output_ins.label[2] == '@')
1109 if (output_ins.operands == 1 &&
1110 (output_ins.oprs[0].type & IMMEDIATE) &&
1111 output_ins.oprs[0].wrt == NO_SEG)
1113 int isext = output_ins.oprs[0].opflags & OPFLAG_EXTERN;
1114 def_label (output_ins.label,
1115 output_ins.oprs[0].segment,
1116 output_ins.oprs[0].offset,
1117 NULL, FALSE, isext, ofmt, report_error);
1119 else if (output_ins.operands == 2 &&
1120 (output_ins.oprs[0].type & IMMEDIATE) &&
1121 (output_ins.oprs[0].type & COLON) &&
1122 output_ins.oprs[0].segment == NO_SEG &&
1123 output_ins.oprs[0].wrt == NO_SEG &&
1124 (output_ins.oprs[1].type & IMMEDIATE) &&
1125 output_ins.oprs[1].segment == NO_SEG &&
1126 output_ins.oprs[1].wrt == NO_SEG)
1128 def_label (output_ins.label,
1129 output_ins.oprs[0].offset | SEG_ABS,
1130 output_ins.oprs[1].offset,
1131 NULL, FALSE, FALSE, ofmt, report_error);
1133 else
1134 report_error(ERR_NONFATAL, "bad syntax for EQU");
1136 } else { /* pass == 2 */
1138 * Special `..' EQUs get processed here, except
1139 * `..@' macro processor EQUs which are done above.
1141 if (output_ins.label[0] == '.' &&
1142 output_ins.label[1] == '.' &&
1143 output_ins.label[2] != '@')
1145 if (output_ins.operands == 1 &&
1146 (output_ins.oprs[0].type & IMMEDIATE)) {
1147 define_label (output_ins.label,
1148 output_ins.oprs[0].segment,
1149 output_ins.oprs[0].offset,
1150 NULL, FALSE, FALSE, ofmt, report_error);
1152 else if (output_ins.operands == 2 &&
1153 (output_ins.oprs[0].type & IMMEDIATE) &&
1154 (output_ins.oprs[0].type & COLON) &&
1155 output_ins.oprs[0].segment == NO_SEG &&
1156 (output_ins.oprs[1].type & IMMEDIATE) &&
1157 output_ins.oprs[1].segment == NO_SEG)
1159 define_label (output_ins.label,
1160 output_ins.oprs[0].offset | SEG_ABS,
1161 output_ins.oprs[1].offset,
1162 NULL, FALSE, FALSE, ofmt, report_error);
1164 else
1165 report_error(ERR_NONFATAL, "bad syntax for EQU");
1167 } /* pass == 2 */
1168 } else { /* instruction isn't an EQU */
1170 if (pass1 == 1) {
1172 long l = insn_size (location.segment, offs, sb, cpu,
1173 &output_ins, report_error);
1175 /* if (using_debug_info) && output_ins.opcode != -1)*/
1176 if (using_debug_info) /* fbk 03/25/01 */
1179 /* this is done here so we can do debug type info */
1180 long typeinfo = TYS_ELEMENTS(output_ins.operands);
1181 switch (output_ins.opcode) {
1182 case I_RESB:
1183 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1184 break;
1185 case I_RESW:
1186 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1187 break;
1188 case I_RESD:
1189 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1190 break;
1191 case I_RESQ:
1192 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1193 break;
1194 case I_REST:
1195 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1196 break;
1197 case I_DB:
1198 typeinfo |= TY_BYTE;
1199 break;
1200 case I_DW:
1201 typeinfo |= TY_WORD;
1202 break;
1203 case I_DD:
1204 if (output_ins.eops_float)
1205 typeinfo |= TY_FLOAT;
1206 else
1207 typeinfo |= TY_DWORD;
1208 break;
1209 case I_DQ:
1210 typeinfo |= TY_QWORD;
1211 break;
1212 case I_DT:
1213 typeinfo |= TY_TBYTE;
1214 break;
1215 default:
1216 typeinfo = TY_LABEL;
1220 ofmt->current_dfmt->debug_typevalue(typeinfo);
1223 if (l != -1) {
1224 offs += l;
1225 SET_CURR_OFFS (offs);
1228 * else l == -1 => invalid instruction, which will be
1229 * flagged as an error on pass 2
1232 } else { /* pass == 2 */
1233 offs += assemble (location.segment, offs, sb, cpu,
1234 &output_ins, ofmt, report_error, &nasmlist);
1235 SET_CURR_OFFS (offs);
1238 } /* not an EQU */
1239 cleanup_insn (&output_ins);
1241 nasm_free (line);
1242 location.offset = offs = GET_CURR_OFFS;
1243 } /* end while (line = preproc->getline... */
1245 if (pass1==2 && global_offset_changed)
1246 report_error(ERR_NONFATAL, "phase error detected at end of assembly.");
1248 if (pass1 == 1) preproc->cleanup(1);
1250 if (pass1==1 && terminate_after_phase) {
1251 fclose(ofile);
1252 remove(outname);
1253 if (want_usage)
1254 usage();
1255 exit (1);
1257 pass_cnt++;
1258 if (pass>1 && !global_offset_changed) {
1259 pass0++;
1260 if (pass0==2) pass = pass_max - 1;
1261 } else if (!(optimizing>0)) pass0++;
1263 } /* for (pass=1; pass<=2; pass++) */
1265 preproc->cleanup(0);
1266 nasmlist.cleanup();
1267 #if 1
1268 if (optimizing>0 && using_debug_info) /* -On and -g switches */
1269 fprintf(stdout,
1270 "info:: assembly required 1+%d+1 passes\n", pass_cnt-2);
1271 #endif
1272 } /* exit from assemble_file (...) */
1275 static int getkw (char *buf, char **value)
1277 char *p, *q;
1279 /* allow leading spaces or tabs */
1280 while (*buf==' ' || *buf=='\t')
1281 buf++;
1283 if (*buf!='[')
1284 return 0;
1286 p = buf;
1288 while (*p && *p != ']') p++;
1290 if (!*p)
1291 return 0;
1293 q = p++;
1295 while (*p && *p != ';') {
1296 if (!isspace(*p))
1297 return 0;
1298 p++;
1300 q[1] = '\0';
1302 p = buf+1;
1303 while (*buf && *buf!=' ' && *buf!=']' && *buf!='\t')
1304 buf++;
1305 if (*buf==']') {
1306 *buf = '\0';
1307 *value = buf;
1308 } else {
1309 *buf++ = '\0';
1310 while (isspace(*buf)) buf++; /* beppu - skip leading whitespace */
1311 *value = buf;
1312 while (*buf!=']') buf++;
1313 *buf++ = '\0';
1315 #if 0
1316 for (q=p; *q; q++)
1317 *q = tolower(*q);
1318 #endif
1319 if (!nasm_stricmp(p, "segment") || !nasm_stricmp(p, "section"))
1320 return 1;
1321 if (!nasm_stricmp(p, "extern"))
1322 return 2;
1323 if (!nasm_stricmp(p, "bits"))
1324 return 3;
1325 if (!nasm_stricmp(p, "global"))
1326 return 4;
1327 if (!nasm_stricmp(p, "common"))
1328 return 5;
1329 if (!nasm_stricmp(p, "absolute"))
1330 return 6;
1331 if (!nasm_stricmp(p, "debug"))
1332 return 7;
1333 if (!nasm_stricmp(p, "warning"))
1334 return 8;
1335 if (!nasm_stricmp(p, "cpu"))
1336 return 9;
1337 if (!nasm_stricmp(p, "list")) /* fbk 9/2/00 */
1338 return 10;
1339 return -1;
1342 static void report_error (int severity, const char *fmt, ...)
1344 va_list ap;
1347 * See if it's a suppressed warning.
1349 if ((severity & ERR_MASK) == ERR_WARNING &&
1350 (severity & ERR_WARN_MASK) != 0 &&
1351 suppressed[ (severity & ERR_WARN_MASK) >> ERR_WARN_SHR ])
1352 return; /* and bail out if so */
1355 * See if it's a pass-one only warning and we're not in pass one.
1357 if ((severity & ERR_PASS1) && pass0 == 2)
1358 return;
1360 if (severity & ERR_NOFILE)
1361 fputs ("nasm: ", error_file);
1362 else {
1363 char * currentfile = NULL;
1364 long lineno = 0;
1365 src_get (&lineno, &currentfile);
1366 fprintf (error_file, "%s:%ld: ", currentfile, lineno);
1367 nasm_free (currentfile);
1370 switch (severity & ERR_MASK) {
1371 case ERR_WARNING:
1372 fputs ("warning: ", error_file); break;
1373 case ERR_NONFATAL:
1374 fputs ("error: ", error_file); break;
1375 case ERR_FATAL:
1376 fputs ("fatal: ", error_file); break;
1377 case ERR_PANIC:
1378 fputs ("panic: ", error_file); break;
1379 case ERR_DEBUG:
1380 fputs("debug: ", error_file); break;
1383 va_start (ap, fmt);
1384 vfprintf (error_file, fmt, ap);
1385 fputc ('\n', error_file);
1387 if (severity & ERR_USAGE)
1388 want_usage = TRUE;
1390 switch (severity & ERR_MASK) {
1391 case ERR_WARNING: case ERR_DEBUG:
1392 /* no further action, by definition */
1393 break;
1394 case ERR_NONFATAL:
1395 /* terminate_after_phase = TRUE; *//**//* hack enables listing(!) on errors */
1396 terminate_after_phase = TRUE;
1397 break;
1398 case ERR_FATAL:
1399 if (ofile) {
1400 fclose(ofile);
1401 remove(outname);
1403 if (want_usage)
1404 usage();
1405 exit(1); /* instantly die */
1406 break; /* placate silly compilers */
1407 case ERR_PANIC:
1408 fflush(NULL);
1409 /* abort(); */ /* halt, catch fire, and dump core */
1410 exit(3);
1411 break;
1415 static void usage(void)
1417 fputs("type `nasm -h' for help\n", error_file);
1420 static void register_output_formats(void)
1422 ofmt = ofmt_register (report_error);
1425 #define BUF_DELTA 512
1427 static FILE *no_pp_fp;
1428 static efunc no_pp_err;
1429 static ListGen *no_pp_list;
1430 static long no_pp_lineinc;
1432 static void no_pp_reset (char *file, int pass, efunc error, evalfunc eval,
1433 ListGen *listgen)
1435 src_set_fname(nasm_strdup(file));
1436 src_set_linnum(0);
1437 no_pp_lineinc = 1;
1438 no_pp_err = error;
1439 no_pp_fp = fopen(file, "r");
1440 if (!no_pp_fp)
1441 no_pp_err (ERR_FATAL | ERR_NOFILE,
1442 "unable to open input file `%s'", file);
1443 no_pp_list = listgen;
1444 (void) pass; /* placate compilers */
1445 (void) eval; /* placate compilers */
1448 static char *no_pp_getline (void)
1450 char *buffer, *p, *q;
1451 int bufsize;
1453 bufsize = BUF_DELTA;
1454 buffer = nasm_malloc(BUF_DELTA);
1455 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1457 while (1) { /* Loop to handle %line */
1459 p = buffer;
1460 while (1) { /* Loop to handle long lines */
1461 q = fgets(p, bufsize-(p-buffer), no_pp_fp);
1462 if (!q)
1463 break;
1464 p += strlen(p);
1465 if (p > buffer && p[-1] == '\n')
1466 break;
1467 if (p-buffer > bufsize-10) {
1468 int offset;
1469 offset = p - buffer;
1470 bufsize += BUF_DELTA;
1471 buffer = nasm_realloc(buffer, bufsize);
1472 p = buffer + offset;
1476 if (!q && p == buffer) {
1477 nasm_free (buffer);
1478 return NULL;
1482 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1483 * them are present at the end of the line.
1485 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1487 if (!strncmp(buffer, "%line", 5)) {
1488 long ln;
1489 int li;
1490 char *nm = nasm_malloc(strlen(buffer));
1491 if (sscanf(buffer+5, "%ld+%d %s", &ln, &li, nm) == 3) {
1492 nasm_free( src_set_fname(nm) );
1493 src_set_linnum(ln);
1494 no_pp_lineinc = li;
1495 continue;
1497 nasm_free(nm);
1499 break;
1502 no_pp_list->line (LIST_READ, buffer);
1504 return buffer;
1507 static void no_pp_cleanup (int pass)
1509 fclose(no_pp_fp);
1512 static unsigned long get_cpu (char *value)
1515 if (!strcmp(value, "8086")) return IF_8086;
1516 if (!strcmp(value, "186")) return IF_186;
1517 if (!strcmp(value, "286")) return IF_286;
1518 if (!strcmp(value, "386")) return IF_386;
1519 if (!strcmp(value, "486")) return IF_486;
1520 if (!strcmp(value, "586") ||
1521 !nasm_stricmp(value, "pentium") ) return IF_PENT;
1522 if (!strcmp(value, "686") ||
1523 !nasm_stricmp(value, "ppro") ||
1524 !nasm_stricmp(value, "p2") ) return IF_P6;
1525 if (!nasm_stricmp(value, "p3") ||
1526 !nasm_stricmp(value, "katmai") ) return IF_KATMAI;
1527 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
1528 !nasm_stricmp(value, "willamette") ) return IF_WILLAMETTE;
1530 report_error (pass0<2 ? ERR_NONFATAL : ERR_FATAL, "unknown 'cpu' type");
1532 return IF_PLEVEL; /* the maximum level */
1536 static int get_bits (char *value)
1538 int i;
1540 if ((i = atoi(value)) == 16) return i; /* set for a 16-bit segment */
1541 else if (i == 32) {
1542 if (cpu < IF_386) {
1543 report_error(ERR_NONFATAL,
1544 "cannot specify 32-bit segment on processor below a 386");
1545 i = 16;
1547 } else {
1548 report_error(pass0<2 ? ERR_NONFATAL : ERR_FATAL,
1549 "`%s' is not a valid segment size; must be 16 or 32",
1550 value);
1551 i = 16;
1553 return i;
1556 /* end of nasm.c */