Undo accidental checkin of old code
[nasm.git] / nasm.c
blob7666d0dd09d5e928665db6728dd496a28db0075d
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, opt_verbose_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 long abs_seg; /* ABSOLUTE segment basis */
63 long abs_offset; /* ABSOLUTE offset */
65 static struct RAA *offsets;
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 opt = -99;
392 while (*param) {
393 if (isdigit(*param)) {
394 opt = atoi(param);
395 while(isdigit(*++param)) ;
396 if (opt<=0) optimizing = -1; /* 0.98 behaviour */
397 else if (opt==1) optimizing = 0; /* Two passes, 0.98.09 behavior */
398 else if (opt<=3) optimizing = opt*5; /* Multiple passes */
399 else optimizing = opt; /* Multiple passes */
400 } else {
401 if (*param == 'v' || *param == '+') {
402 ++param;
403 opt_verbose_info = TRUE;
404 opt = 0;
407 } /* while (*param) */
408 if (opt == -99) report_error(ERR_FATAL,
409 "command line optimization level must be 'v', 0..3 or <nn>");
410 } else if (p[1]=='P' || p[1]=='p') { /* pre-include */
411 pp_pre_include (param);
412 } else if (p[1]=='D' || p[1]=='d') { /* pre-define */
413 pp_pre_define (param);
414 } else if (p[1]=='U' || p[1]=='u') { /* un-define */
415 pp_pre_undefine (param);
416 } else if (p[1]=='I' || p[1]=='i') { /* include search path */
417 pp_include_path (param);
418 } else if (p[1]=='l') { /* listing file */
419 strcpy (listname, param);
420 } else if (p[1]=='E') { /* error messages file */
421 error_file = fopen(param, "w");
422 if ( !error_file ) {
423 error_file = stderr; /* Revert to default! */
424 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
425 "cannot open file `%s' for error messages",
426 param);
428 } else if (p[1] == 'F') { /* specify debug format */
429 ofmt->current_dfmt = dfmt_find(ofmt, param);
430 if (!ofmt->current_dfmt) {
431 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
432 "unrecognized debug format `%s' for"
433 " output format `%s'",
434 param, ofmt->shortname);
437 break;
438 case 'g':
439 using_debug_info = TRUE;
440 break;
441 case 'h':
442 printf("usage: nasm [-@ response file] [-o outfile] [-f format] "
443 "[-l listfile]\n"
444 " [options...] [--] filename\n"
445 " or nasm -r for version info (obsolete)\n"
446 " or nasm -v for version info (preferred)\n\n"
447 " -t Assemble in SciTech TASM compatible mode\n"
448 " -g Generate debug information in selected format.\n");
449 printf(" -e preprocess only (writes output to stdout by default)\n"
450 " -a don't preprocess (assemble only)\n"
451 " -M generate Makefile dependencies on stdout\n\n"
452 " -E<file> redirect error messages to file\n"
453 " -s redirect error messages to stdout\n\n"
454 " -F format select a debugging format\n\n"
455 " -I<path> adds a pathname to the include file path\n");
456 printf(" -O<digit> optimize branch offsets (-O0 disables, default)\n"
457 " -P<file> pre-includes a file\n"
458 " -D<macro>[=<value>] pre-defines a macro\n"
459 " -U<macro> undefines a macro\n"
460 " -w+foo enables warnings about foo; -w-foo disables them\n"
461 "where foo can be:\n");
462 for (i=1; i<=ERR_WARN_MAX; i++)
463 printf(" %-23s %s (default %s)\n",
464 suppressed_names[i], suppressed_what[i],
465 suppressed[i] ? "off" : "on");
466 printf ("\nresponse files should contain command line parameters"
467 ", one per line.\n");
468 if (p[2] == 'f') {
469 printf("\nvalid output formats for -f are"
470 " (`*' denotes default):\n");
471 ofmt_list(ofmt, stdout);
473 else {
474 printf ("\nFor a list of valid output formats, use -hf.\n");
475 printf ("For a list of debug formats, use -f <form> -y.\n");
477 exit (0); /* never need usage message here */
478 break;
479 case 'y':
480 printf("\nvalid debug formats for '%s' output format are"
481 " ('*' denotes default):\n",
482 ofmt->shortname);
483 dfmt_list(ofmt, stdout);
484 exit(0);
485 break;
486 case 't':
487 tasm_compatible_mode = TRUE;
488 break;
489 case 'r':
490 case 'v':
491 printf("NASM version %s compiled "
492 #ifdef DEBUG
493 "with -DDEBUG "
494 #endif
495 "on " __DATE__ "\n", NASM_VER);
496 exit (0); /* never need usage message here */
497 break;
498 case 'e': /* preprocess only */
499 operating_mode = op_preprocess;
500 break;
501 case 'a': /* assemble only - don't preprocess */
502 preproc = &no_pp;
503 break;
504 case 'w':
505 if (p[2] != '+' && p[2] != '-') {
506 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
507 "invalid option to `-w'");
508 } else {
509 for (i=1; i<=ERR_WARN_MAX; i++)
510 if (!nasm_stricmp(p+3, suppressed_names[i]))
511 break;
512 if (i <= ERR_WARN_MAX)
513 suppressed[i] = (p[2] == '-');
514 else
515 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
516 "invalid option to `-w'");
518 break;
519 case 'M':
520 operating_mode = op_depend;
521 break;
523 case '-':
525 int s;
527 if (p[2]==0) { /* -- => stop processing options */
528 stopoptions = 1;
529 break;
531 for(s=0; textopts[s].label; s++)
533 if(!nasm_stricmp(p+2, textopts[s].label))
535 break;
539 switch(s)
542 case OPT_PREFIX:
543 case OPT_POSTFIX:
545 if (!q)
547 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
548 "option `--%s' requires an argument",
549 p+2);
550 break;
552 else
554 advance = 1, param = q;
557 if(s == OPT_PREFIX)
559 strncpy(lprefix,param,PREFIX_MAX-1);
560 lprefix[PREFIX_MAX-1]=0;
561 break;
563 if(s == OPT_POSTFIX)
565 strncpy(lpostfix,param,POSTFIX_MAX-1);
566 lpostfix[POSTFIX_MAX-1]=0;
567 break;
569 break;
571 default:
573 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
574 "unrecognised option `--%s'",
575 p+2);
576 break;
579 break;
582 default:
583 if (!ofmt->setinfo(GI_SWITCH,&p))
584 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
585 "unrecognised option `-%c'",
586 p[1]);
587 break;
590 else
592 if (*inname) {
593 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
594 "more than one input file specified");
595 } else
596 strcpy(inname, p);
599 return advance;
602 #define ARG_BUF_DELTA 128
604 static void process_respfile (FILE *rfile)
606 char *buffer, *p, *q, *prevarg;
607 int bufsize, prevargsize;
609 bufsize = prevargsize = ARG_BUF_DELTA;
610 buffer = nasm_malloc(ARG_BUF_DELTA);
611 prevarg = nasm_malloc(ARG_BUF_DELTA);
612 prevarg[0] = '\0';
614 while (1) { /* Loop to handle all lines in file */
616 p = buffer;
617 while (1) { /* Loop to handle long lines */
618 q = fgets(p, bufsize-(p-buffer), rfile);
619 if (!q)
620 break;
621 p += strlen(p);
622 if (p > buffer && p[-1] == '\n')
623 break;
624 if (p-buffer > bufsize-10) {
625 int offset;
626 offset = p - buffer;
627 bufsize += ARG_BUF_DELTA;
628 buffer = nasm_realloc(buffer, bufsize);
629 p = buffer + offset;
633 if (!q && p == buffer) {
634 if (prevarg[0])
635 process_arg (prevarg, NULL);
636 nasm_free (buffer);
637 nasm_free (prevarg);
638 return;
642 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
643 * them are present at the end of the line.
645 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
647 while (p > buffer && isspace(p[-1]))
648 *--p = '\0';
650 p = buffer;
651 while (isspace(*p))
652 p++;
654 if (process_arg (prevarg, p))
655 *p = '\0';
657 if (strlen(p) > prevargsize-10) {
658 prevargsize += ARG_BUF_DELTA;
659 prevarg = nasm_realloc(prevarg, prevargsize);
661 strcpy (prevarg, p);
665 /* Function to process args from a string of args, rather than the
666 * argv array. Used by the environment variable and response file
667 * processing.
669 static void process_args (char *args) {
670 char *p, *q, *arg, *prevarg;
671 char separator = ' ';
673 p = args;
674 if (*p && *p != '-')
675 separator = *p++;
676 arg = NULL;
677 while (*p) {
678 q = p;
679 while (*p && *p != separator) p++;
680 while (*p == separator) *p++ = '\0';
681 prevarg = arg;
682 arg = q;
683 if (process_arg (prevarg, arg))
684 arg = NULL;
686 if (arg)
687 process_arg (arg, NULL);
690 static void parse_cmdline(int argc, char **argv)
692 FILE *rfile;
693 char *envreal, *envcopy=NULL, *p, *arg;
695 *inname = *outname = *listname = '\0';
698 * First, process the NASMENV environment variable.
700 envreal = getenv("NASMENV");
701 arg = NULL;
702 if (envreal) {
703 envcopy = nasm_strdup(envreal);
704 process_args(envcopy);
705 nasm_free (envcopy);
709 * Now process the actual command line.
711 while (--argc)
713 int i;
714 argv++;
715 if (argv[0][0] == '@') {
716 /* We have a response file, so process this as a set of
717 * arguments like the environment variable. This allows us
718 * to have multiple arguments on a single line, which is
719 * different to the -@resp file processing below for regular
720 * NASM.
722 char *str = malloc(2048);
723 FILE *f = fopen(&argv[0][1],"r");
724 if (!str) {
725 printf("out of memory");
726 exit(-1);
728 if (f) {
729 while (fgets(str,2048,f)) {
730 process_args(str);
732 fclose(f);
734 free(str);
735 argc--;
736 argv++;
738 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
739 if ((p = get_param (argv[0], argc > 1 ? argv[1] : NULL, &i))) {
740 if ((rfile = fopen(p, "r"))) {
741 process_respfile (rfile);
742 fclose(rfile);
743 } else
744 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
745 "unable to open response file `%s'", p);
747 } else
748 i = process_arg (argv[0], argc > 1 ? argv[1] : NULL);
749 argv += i, argc -= i;
752 if (!*inname)
753 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
754 "no input file specified");
758 static void assemble_file (char *fname)
760 char * value, * p, * q, * special, * line, debugid[80];
761 insn output_ins;
762 int i, rn_error, validid;
763 long seg, offs;
764 struct tokenval tokval;
765 expr * e;
766 int pass, pass_max;
767 int pass_cnt = 0; /* count actual passes */
769 if (cmd_sb == 32 && cmd_cpu < IF_386)
770 report_error(ERR_FATAL, "command line: "
771 "32-bit segment size requires a higher cpu");
773 pass_max = (optimizing>0 ? optimizing : 0) + 2; /* passes 1, optimizing, then 2 */
774 pass0 = !(optimizing>0); /* start at 1 if not optimizing */
775 for (pass = 1; pass <= pass_max && pass0 <= 2; pass++) {
776 int pass1, pass2;
777 ldfunc def_label;
779 pass1 = pass < pass_max ? 1 : 2; /* seq is 1, 1, 1,..., 1, 2 */
780 pass2 = pass > 1 ? 2 : 1; /* seq is 1, 2, 2,..., 2, 2 */
781 /* pass0 seq is 0, 0, 0,..., 1, 2 */
783 def_label = pass > 1 ? redefine_label : define_label;
786 sb = cmd_sb; /* set 'bits' to command line default */
787 cpu = cmd_cpu;
788 if (pass0 == 2) {
789 if (*listname)
790 nasmlist.init(listname, report_error);
792 in_abs_seg = FALSE;
793 global_offset_changed = FALSE; /* set by redefine_label */
794 location.segment = ofmt->section(NULL, pass2, &sb);
795 if (pass > 1) {
796 saa_rewind (forwrefs);
797 forwref = saa_rstruct (forwrefs);
798 raa_free (offsets);
799 offsets = raa_init();
801 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
802 globallineno = 0;
803 if (pass == 1) location.known = TRUE;
804 location.offset = offs = GET_CURR_OFFS;
806 while ( (line = preproc->getline()) )
808 globallineno++;
810 /* here we parse our directives; this is not handled by the 'real'
811 * parser. */
812 if ( (i = getkw (line, &value)) )
814 switch (i) {
815 case 1: /* [SEGMENT n] */
816 seg = ofmt->section (value, pass2, &sb);
817 if (seg == NO_SEG) {
818 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
819 "segment name `%s' not recognised",
820 value);
821 } else {
822 in_abs_seg = FALSE;
823 location.segment = seg;
825 break;
826 case 2: /* [EXTERN label:special] */
827 if (*value == '$') value++; /* skip initial $ if present */
828 if (pass0 == 2) {
829 q = value;
830 while (*q && *q != ':')
831 q++;
832 if (*q == ':') {
833 *q++ = '\0';
834 ofmt->symdef(value, 0L, 0L, 3, q);
836 } else if (pass == 1) { /* pass == 1 */
837 q = value;
838 validid = TRUE;
839 if (!isidstart(*q))
840 validid = FALSE;
841 while (*q && *q != ':') {
842 if (!isidchar(*q))
843 validid = FALSE;
844 q++;
846 if (!validid) {
847 report_error (ERR_NONFATAL,
848 "identifier expected after EXTERN");
849 break;
851 if (*q == ':') {
852 *q++ = '\0';
853 special = q;
854 } else
855 special = NULL;
856 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
857 int temp = pass0;
858 pass0 = 1; /* fake pass 1 in labels.c */
859 declare_as_global (value, special, report_error);
860 define_label (value, seg_alloc(), 0L, NULL, FALSE, TRUE,
861 ofmt, report_error);
862 pass0 = temp;
864 } /* else pass0 == 1 */
865 break;
866 case 3: /* [BITS bits] */
867 sb = get_bits(value);
868 break;
869 case 4: /* [GLOBAL symbol:special] */
870 if (*value == '$') value++; /* skip initial $ if present */
871 if (pass0 == 2) { /* pass 2 */
872 q = value;
873 while (*q && *q != ':')
874 q++;
875 if (*q == ':') {
876 *q++ = '\0';
877 ofmt->symdef(value, 0L, 0L, 3, q);
879 } else if (pass2 == 1) { /* pass == 1 */
880 q = value;
881 validid = TRUE;
882 if (!isidstart(*q))
883 validid = FALSE;
884 while (*q && *q != ':') {
885 if (!isidchar(*q))
886 validid = FALSE;
887 q++;
889 if (!validid) {
890 report_error (ERR_NONFATAL,
891 "identifier expected after GLOBAL");
892 break;
894 if (*q == ':') {
895 *q++ = '\0';
896 special = q;
897 } else
898 special = NULL;
899 declare_as_global (value, special, report_error);
900 } /* pass == 1 */
901 break;
902 case 5: /* [COMMON symbol size:special] */
903 if (*value == '$') value++; /* skip initial $ if present */
904 if (pass0 == 1) {
905 p = value;
906 validid = TRUE;
907 if (!isidstart(*p))
908 validid = FALSE;
909 while (*p && !isspace(*p)) {
910 if (!isidchar(*p))
911 validid = FALSE;
912 p++;
914 if (!validid) {
915 report_error (ERR_NONFATAL,
916 "identifier expected after COMMON");
917 break;
919 if (*p) {
920 long size;
922 while (*p && isspace(*p))
923 *p++ = '\0';
924 q = p;
925 while (*q && *q != ':')
926 q++;
927 if (*q == ':') {
928 *q++ = '\0';
929 special = q;
930 } else
931 special = NULL;
932 size = readnum (p, &rn_error);
933 if (rn_error)
934 report_error (ERR_NONFATAL, "invalid size specified"
935 " in COMMON declaration");
936 else
937 define_common (value, seg_alloc(), size,
938 special, ofmt, report_error);
939 } else
940 report_error (ERR_NONFATAL, "no size specified in"
941 " COMMON declaration");
942 } else if (pass0 == 2) { /* pass == 2 */
943 q = value;
944 while (*q && *q != ':') {
945 if (isspace(*q))
946 *q = '\0';
947 q++;
949 if (*q == ':') {
950 *q++ = '\0';
951 ofmt->symdef(value, 0L, 0L, 3, q);
954 break;
955 case 6: /* [ABSOLUTE address] */
956 stdscan_reset();
957 stdscan_bufptr = value;
958 tokval.t_type = TOKEN_INVALID;
959 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, report_error,
960 NULL);
961 if (e) {
962 if (!is_reloc(e))
963 report_error (pass0==1 ? ERR_NONFATAL : ERR_PANIC,
964 "cannot use non-relocatable expression as "
965 "ABSOLUTE address");
966 else {
967 abs_seg = reloc_seg(e);
968 abs_offset = reloc_value(e);
970 } else
971 if (pass==1) abs_offset = 0x100;/* don't go near zero in case of / */
972 else report_error (ERR_PANIC, "invalid ABSOLUTE address "
973 "in pass two");
974 in_abs_seg = TRUE;
975 location.segment = NO_SEG;
976 break;
977 case 7: /* DEBUG */
978 p = value;
979 q = debugid;
980 validid = TRUE;
981 if (!isidstart(*p))
982 validid = FALSE;
983 while (*p && !isspace(*p)) {
984 if (!isidchar(*p))
985 validid = FALSE;
986 *q++ = *p++;
988 *q++ = 0;
989 if (!validid) {
990 report_error (pass==1 ? ERR_NONFATAL : ERR_PANIC,
991 "identifier expected after DEBUG");
992 break;
994 while (*p && isspace(*p)) p++;
995 if (pass==pass_max) ofmt->current_dfmt->debug_directive (debugid, p);
996 break;
997 case 8: /* [WARNING {+|-}warn-name] */
998 if (pass1 == 1) {
999 while (*value && isspace(*value))
1000 value++;
1002 if (*value == '+' || *value == '-') {
1003 validid = (*value == '-') ? TRUE : FALSE;
1004 value++;
1005 } else
1006 validid = FALSE;
1008 for (i=1; i<=ERR_WARN_MAX; i++)
1009 if (!nasm_stricmp(value, suppressed_names[i]))
1010 break;
1011 if (i <= ERR_WARN_MAX)
1012 suppressed[i] = validid;
1013 else
1014 report_error (ERR_NONFATAL, "invalid warning id in WARNING directive");
1016 break;
1017 case 9: /* cpu */
1018 cpu = get_cpu (value);
1019 break;
1020 case 10: /* fbk 9/2/00 */ /* [LIST {+|-}] */
1021 while (*value && isspace(*value))
1022 value++;
1024 if (*value == '+') {
1025 user_nolist = 0;
1027 else {
1028 if (*value == '-') {
1029 user_nolist = 1;
1031 else {
1032 report_error (ERR_NONFATAL, "invalid parameter to \"list\" directive");
1035 break;
1036 default:
1037 if (!ofmt->directive (line+1, value, pass2))
1038 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
1039 "unrecognised directive [%s]",
1040 line+1);
1043 else /* it isn't a directive */
1045 parse_line (pass1, line, &output_ins,
1046 report_error, evaluate,
1047 def_label);
1049 if (!(optimizing>0) && pass == 2) {
1050 if (forwref != NULL && globallineno == forwref->lineno) {
1051 output_ins.forw_ref = TRUE;
1052 do {
1053 output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;
1054 forwref = saa_rstruct (forwrefs);
1055 } while (forwref != NULL && forwref->lineno == globallineno);
1056 } else
1057 output_ins.forw_ref = FALSE;
1061 if (!(optimizing>0) && output_ins.forw_ref)
1063 if (pass == 1) {
1064 for(i = 0; i < output_ins.operands; i++)
1066 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD)
1068 struct forwrefinfo *fwinf =
1069 (struct forwrefinfo *)saa_wstruct(forwrefs);
1070 fwinf->lineno = globallineno;
1071 fwinf->operand = i;
1074 } else { /* pass == 2 */
1076 * Hack to prevent phase error in the code
1077 * rol ax,x
1078 * x equ 1
1080 * If the second operand is a forward reference,
1081 * the UNITY property of the number 1 in that
1082 * operand is cancelled. Otherwise the above
1083 * sequence will cause a phase error.
1085 * This hack means that the above code will
1086 * generate 286+ code.
1088 * The forward reference will mean that the
1089 * operand will not have the UNITY property on
1090 * the first pass, so the pass behaviours will
1091 * be consistent.
1094 if (output_ins.operands >= 2 &&
1095 (output_ins.oprs[1].opflags & OPFLAG_FORWARD))
1097 output_ins.oprs[1].type &= ~(ONENESS|BYTENESS);
1100 } /* pass == 2 */
1102 } /* forw_ref */
1105 if (output_ins.opcode == I_EQU) {
1106 if (pass1 == 1)
1109 * Special `..' EQUs get processed in pass two,
1110 * except `..@' macro-processor EQUs which are done
1111 * in the normal place.
1113 if (!output_ins.label)
1114 report_error (ERR_NONFATAL,
1115 "EQU not preceded by label");
1117 else if (output_ins.label[0] != '.' ||
1118 output_ins.label[1] != '.' ||
1119 output_ins.label[2] == '@')
1121 if (output_ins.operands == 1 &&
1122 (output_ins.oprs[0].type & IMMEDIATE) &&
1123 output_ins.oprs[0].wrt == NO_SEG)
1125 int isext = output_ins.oprs[0].opflags & OPFLAG_EXTERN;
1126 def_label (output_ins.label,
1127 output_ins.oprs[0].segment,
1128 output_ins.oprs[0].offset,
1129 NULL, FALSE, isext, ofmt, report_error);
1131 else if (output_ins.operands == 2 &&
1132 (output_ins.oprs[0].type & IMMEDIATE) &&
1133 (output_ins.oprs[0].type & COLON) &&
1134 output_ins.oprs[0].segment == NO_SEG &&
1135 output_ins.oprs[0].wrt == NO_SEG &&
1136 (output_ins.oprs[1].type & IMMEDIATE) &&
1137 output_ins.oprs[1].segment == NO_SEG &&
1138 output_ins.oprs[1].wrt == NO_SEG)
1140 def_label (output_ins.label,
1141 output_ins.oprs[0].offset | SEG_ABS,
1142 output_ins.oprs[1].offset,
1143 NULL, FALSE, FALSE, ofmt, report_error);
1145 else
1146 report_error(ERR_NONFATAL, "bad syntax for EQU");
1148 } else { /* pass == 2 */
1150 * Special `..' EQUs get processed here, except
1151 * `..@' macro processor EQUs which are done above.
1153 if (output_ins.label[0] == '.' &&
1154 output_ins.label[1] == '.' &&
1155 output_ins.label[2] != '@')
1157 if (output_ins.operands == 1 &&
1158 (output_ins.oprs[0].type & IMMEDIATE)) {
1159 define_label (output_ins.label,
1160 output_ins.oprs[0].segment,
1161 output_ins.oprs[0].offset,
1162 NULL, FALSE, FALSE, ofmt, report_error);
1164 else if (output_ins.operands == 2 &&
1165 (output_ins.oprs[0].type & IMMEDIATE) &&
1166 (output_ins.oprs[0].type & COLON) &&
1167 output_ins.oprs[0].segment == NO_SEG &&
1168 (output_ins.oprs[1].type & IMMEDIATE) &&
1169 output_ins.oprs[1].segment == NO_SEG)
1171 define_label (output_ins.label,
1172 output_ins.oprs[0].offset | SEG_ABS,
1173 output_ins.oprs[1].offset,
1174 NULL, FALSE, FALSE, ofmt, report_error);
1176 else
1177 report_error(ERR_NONFATAL, "bad syntax for EQU");
1179 } /* pass == 2 */
1180 } else { /* instruction isn't an EQU */
1182 if (pass1 == 1) {
1184 long l = insn_size (location.segment, offs, sb, cpu,
1185 &output_ins, report_error);
1187 /* if (using_debug_info) && output_ins.opcode != -1)*/
1188 if (using_debug_info) /* fbk 03/25/01 */
1191 /* this is done here so we can do debug type info */
1192 long typeinfo = TYS_ELEMENTS(output_ins.operands);
1193 switch (output_ins.opcode) {
1194 case I_RESB:
1195 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1196 break;
1197 case I_RESW:
1198 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1199 break;
1200 case I_RESD:
1201 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1202 break;
1203 case I_RESQ:
1204 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1205 break;
1206 case I_REST:
1207 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1208 break;
1209 case I_DB:
1210 typeinfo |= TY_BYTE;
1211 break;
1212 case I_DW:
1213 typeinfo |= TY_WORD;
1214 break;
1215 case I_DD:
1216 if (output_ins.eops_float)
1217 typeinfo |= TY_FLOAT;
1218 else
1219 typeinfo |= TY_DWORD;
1220 break;
1221 case I_DQ:
1222 typeinfo |= TY_QWORD;
1223 break;
1224 case I_DT:
1225 typeinfo |= TY_TBYTE;
1226 break;
1227 default:
1228 typeinfo = TY_LABEL;
1232 ofmt->current_dfmt->debug_typevalue(typeinfo);
1235 if (l != -1) {
1236 offs += l;
1237 SET_CURR_OFFS (offs);
1240 * else l == -1 => invalid instruction, which will be
1241 * flagged as an error on pass 2
1244 } else { /* pass == 2 */
1245 offs += assemble (location.segment, offs, sb, cpu,
1246 &output_ins, ofmt, report_error, &nasmlist);
1247 SET_CURR_OFFS (offs);
1250 } /* not an EQU */
1251 cleanup_insn (&output_ins);
1253 nasm_free (line);
1254 location.offset = offs = GET_CURR_OFFS;
1255 } /* end while (line = preproc->getline... */
1257 if (pass1==2 && global_offset_changed)
1258 report_error(ERR_NONFATAL, "phase error detected at end of assembly.");
1260 if (pass1 == 1) preproc->cleanup(1);
1262 if (pass1==1 && terminate_after_phase) {
1263 fclose(ofile);
1264 remove(outname);
1265 if (want_usage)
1266 usage();
1267 exit (1);
1269 pass_cnt++;
1270 if (pass>1 && !global_offset_changed) {
1271 pass0++;
1272 if (pass0==2) pass = pass_max - 1;
1273 } else if (!(optimizing>0)) pass0++;
1275 } /* for (pass=1; pass<=2; pass++) */
1277 preproc->cleanup(0);
1278 nasmlist.cleanup();
1279 #if 1
1280 if (optimizing>0 && opt_verbose_info) /* -On and -Ov switches */
1281 fprintf(stdout,
1282 "info:: assembly required 1+%d+1 passes\n", pass_cnt-2);
1283 #endif
1284 } /* exit from assemble_file (...) */
1287 static int getkw (char *buf, char **value)
1289 char *p, *q;
1291 /* allow leading spaces or tabs */
1292 while (*buf==' ' || *buf=='\t')
1293 buf++;
1295 if (*buf!='[')
1296 return 0;
1298 p = buf;
1300 while (*p && *p != ']') p++;
1302 if (!*p)
1303 return 0;
1305 q = p++;
1307 while (*p && *p != ';') {
1308 if (!isspace(*p))
1309 return 0;
1310 p++;
1312 q[1] = '\0';
1314 p = buf+1;
1315 while (*buf && *buf!=' ' && *buf!=']' && *buf!='\t')
1316 buf++;
1317 if (*buf==']') {
1318 *buf = '\0';
1319 *value = buf;
1320 } else {
1321 *buf++ = '\0';
1322 while (isspace(*buf)) buf++; /* beppu - skip leading whitespace */
1323 *value = buf;
1324 while (*buf!=']') buf++;
1325 *buf++ = '\0';
1327 #if 0
1328 for (q=p; *q; q++)
1329 *q = tolower(*q);
1330 #endif
1331 if (!nasm_stricmp(p, "segment") || !nasm_stricmp(p, "section"))
1332 return 1;
1333 if (!nasm_stricmp(p, "extern"))
1334 return 2;
1335 if (!nasm_stricmp(p, "bits"))
1336 return 3;
1337 if (!nasm_stricmp(p, "global"))
1338 return 4;
1339 if (!nasm_stricmp(p, "common"))
1340 return 5;
1341 if (!nasm_stricmp(p, "absolute"))
1342 return 6;
1343 if (!nasm_stricmp(p, "debug"))
1344 return 7;
1345 if (!nasm_stricmp(p, "warning"))
1346 return 8;
1347 if (!nasm_stricmp(p, "cpu"))
1348 return 9;
1349 if (!nasm_stricmp(p, "list")) /* fbk 9/2/00 */
1350 return 10;
1351 return -1;
1354 static void report_error (int severity, const char *fmt, ...)
1356 va_list ap;
1359 * See if it's a suppressed warning.
1361 if ((severity & ERR_MASK) == ERR_WARNING &&
1362 (severity & ERR_WARN_MASK) != 0 &&
1363 suppressed[ (severity & ERR_WARN_MASK) >> ERR_WARN_SHR ])
1364 return; /* and bail out if so */
1367 * See if it's a pass-one only warning and we're not in pass one.
1369 if ((severity & ERR_PASS1) && pass0 == 2)
1370 return;
1372 if (severity & ERR_NOFILE)
1373 fputs ("nasm: ", error_file);
1374 else {
1375 char * currentfile = NULL;
1376 long lineno = 0;
1377 src_get (&lineno, &currentfile);
1378 fprintf (error_file, "%s:%ld: ", currentfile, lineno);
1379 nasm_free (currentfile);
1382 switch (severity & ERR_MASK) {
1383 case ERR_WARNING:
1384 fputs ("warning: ", error_file); break;
1385 case ERR_NONFATAL:
1386 fputs ("error: ", error_file); break;
1387 case ERR_FATAL:
1388 fputs ("fatal: ", error_file); break;
1389 case ERR_PANIC:
1390 fputs ("panic: ", error_file); break;
1391 case ERR_DEBUG:
1392 fputs("debug: ", error_file); break;
1395 va_start (ap, fmt);
1396 vfprintf (error_file, fmt, ap);
1397 fputc ('\n', error_file);
1399 if (severity & ERR_USAGE)
1400 want_usage = TRUE;
1402 switch (severity & ERR_MASK) {
1403 case ERR_WARNING: case ERR_DEBUG:
1404 /* no further action, by definition */
1405 break;
1406 case ERR_NONFATAL:
1407 /* terminate_after_phase = TRUE; *//**//* hack enables listing(!) on errors */
1408 terminate_after_phase = TRUE;
1409 break;
1410 case ERR_FATAL:
1411 if (ofile) {
1412 fclose(ofile);
1413 remove(outname);
1415 if (want_usage)
1416 usage();
1417 exit(1); /* instantly die */
1418 break; /* placate silly compilers */
1419 case ERR_PANIC:
1420 fflush(NULL);
1421 /* abort(); */ /* halt, catch fire, and dump core */
1422 exit(3);
1423 break;
1427 static void usage(void)
1429 fputs("type `nasm -h' for help\n", error_file);
1432 static void register_output_formats(void)
1434 ofmt = ofmt_register (report_error);
1437 #define BUF_DELTA 512
1439 static FILE *no_pp_fp;
1440 static efunc no_pp_err;
1441 static ListGen *no_pp_list;
1442 static long no_pp_lineinc;
1444 static void no_pp_reset (char *file, int pass, efunc error, evalfunc eval,
1445 ListGen *listgen)
1447 src_set_fname(nasm_strdup(file));
1448 src_set_linnum(0);
1449 no_pp_lineinc = 1;
1450 no_pp_err = error;
1451 no_pp_fp = fopen(file, "r");
1452 if (!no_pp_fp)
1453 no_pp_err (ERR_FATAL | ERR_NOFILE,
1454 "unable to open input file `%s'", file);
1455 no_pp_list = listgen;
1456 (void) pass; /* placate compilers */
1457 (void) eval; /* placate compilers */
1460 static char *no_pp_getline (void)
1462 char *buffer, *p, *q;
1463 int bufsize;
1465 bufsize = BUF_DELTA;
1466 buffer = nasm_malloc(BUF_DELTA);
1467 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1469 while (1) { /* Loop to handle %line */
1471 p = buffer;
1472 while (1) { /* Loop to handle long lines */
1473 q = fgets(p, bufsize-(p-buffer), no_pp_fp);
1474 if (!q)
1475 break;
1476 p += strlen(p);
1477 if (p > buffer && p[-1] == '\n')
1478 break;
1479 if (p-buffer > bufsize-10) {
1480 int offset;
1481 offset = p - buffer;
1482 bufsize += BUF_DELTA;
1483 buffer = nasm_realloc(buffer, bufsize);
1484 p = buffer + offset;
1488 if (!q && p == buffer) {
1489 nasm_free (buffer);
1490 return NULL;
1494 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1495 * them are present at the end of the line.
1497 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1499 if (!strncmp(buffer, "%line", 5)) {
1500 long ln;
1501 int li;
1502 char *nm = nasm_malloc(strlen(buffer));
1503 if (sscanf(buffer+5, "%ld+%d %s", &ln, &li, nm) == 3) {
1504 nasm_free( src_set_fname(nm) );
1505 src_set_linnum(ln);
1506 no_pp_lineinc = li;
1507 continue;
1509 nasm_free(nm);
1511 break;
1514 no_pp_list->line (LIST_READ, buffer);
1516 return buffer;
1519 static void no_pp_cleanup (int pass)
1521 fclose(no_pp_fp);
1524 static unsigned long get_cpu (char *value)
1527 if (!strcmp(value, "8086")) return IF_8086;
1528 if (!strcmp(value, "186")) return IF_186;
1529 if (!strcmp(value, "286")) return IF_286;
1530 if (!strcmp(value, "386")) return IF_386;
1531 if (!strcmp(value, "486")) return IF_486;
1532 if (!strcmp(value, "586") ||
1533 !nasm_stricmp(value, "pentium") ) return IF_PENT;
1534 if (!strcmp(value, "686") ||
1535 !nasm_stricmp(value, "ppro") ||
1536 !nasm_stricmp(value, "p2") ) return IF_P6;
1537 if (!nasm_stricmp(value, "p3") ||
1538 !nasm_stricmp(value, "katmai") ) return IF_KATMAI;
1539 if (!nasm_stricmp(value, "p4") || /* is this right? -- jrc */
1540 !nasm_stricmp(value, "willamette") ) return IF_WILLAMETTE;
1542 report_error (pass0<2 ? ERR_NONFATAL : ERR_FATAL, "unknown 'cpu' type");
1544 return IF_PLEVEL; /* the maximum level */
1548 static int get_bits (char *value)
1550 int i;
1552 if ((i = atoi(value)) == 16) return i; /* set for a 16-bit segment */
1553 else if (i == 32) {
1554 if (cpu < IF_386) {
1555 report_error(ERR_NONFATAL,
1556 "cannot specify 32-bit segment on processor below a 386");
1557 i = 16;
1559 } else {
1560 report_error(pass0<2 ? ERR_NONFATAL : ERR_FATAL,
1561 "`%s' is not a valid segment size; must be 16 or 32",
1562 value);
1563 i = 16;
1565 return i;
1568 /* end of nasm.c */