NASM 0.98.09
[nasm.git] / nasm.c
blobcd7f7142ca086ec9f7fc288c59ab19fa2de0b280
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;
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 static int optimizing = 0; /* 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
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;
131 int user_nolist = 0; /* fbk 9/2/00 */
133 static void nasm_fputs(char *line, FILE *ofile)
135 if (ofile) {
136 fputs(line, ofile);
137 fputc('\n', ofile);
138 } else
139 puts(line);
142 int main(int argc, char **argv)
144 pass0 = 1;
145 want_usage = terminate_after_phase = FALSE;
147 nasm_set_malloc_error (report_error);
148 offsets = raa_init();
149 forwrefs = saa_init ((long)sizeof(struct forwrefinfo));
151 preproc = &nasmpp;
152 operating_mode = op_normal;
154 error_file = stderr;
156 seg_init();
158 register_output_formats();
160 parse_cmdline(argc, argv);
162 if (terminate_after_phase)
164 if (want_usage)
165 usage();
166 return 1;
169 if (ofmt->stdmac)
170 pp_extra_stdmac (ofmt->stdmac);
171 parser_global_info (ofmt, &location);
172 eval_global_info (ofmt, lookup_label, &location);
174 /* define some macros dependent of command-line */
176 char temp [64];
177 sprintf (temp, "__OUTPUT_FORMAT__=%s\n", ofmt->shortname);
178 pp_pre_define (temp);
181 switch ( operating_mode ) {
182 case op_depend:
184 char *line;
185 preproc->reset (inname, 0, report_error, evaluate, &nasmlist);
186 if (outname[0] == '\0')
187 ofmt->filename (inname, outname, report_error);
188 ofile = NULL;
189 fprintf(stdout, "%s: %s", outname, inname);
190 while ( (line = preproc->getline()) )
191 nasm_free (line);
192 preproc->cleanup();
193 putc('\n', stdout);
195 break;
197 case op_preprocess:
199 char *line;
200 char *file_name = NULL;
201 long prior_linnum=0;
202 int lineinc=0;
204 if (*outname) {
205 ofile = fopen(outname, "w");
206 if (!ofile)
207 report_error (ERR_FATAL | ERR_NOFILE,
208 "unable to open output file `%s'", outname);
209 } else
210 ofile = NULL;
212 location.known = FALSE;
214 /* pass = 1; */
215 preproc->reset (inname, 2, report_error, evaluate, &nasmlist);
216 while ( (line = preproc->getline()) ) {
218 * We generate %line directives if needed for later programs
220 long linnum = prior_linnum += lineinc;
221 int altline = src_get(&linnum, &file_name);
222 if (altline) {
223 if (altline==1 && lineinc==1)
224 nasm_fputs("", ofile);
225 else {
226 lineinc = (altline != -1 || lineinc!=1);
227 fprintf(ofile ? ofile : stdout, "%%line %ld+%d %s\n",
228 linnum, lineinc, file_name);
230 prior_linnum = linnum;
232 nasm_fputs(line, ofile);
233 nasm_free (line);
235 nasm_free(file_name);
236 preproc->cleanup();
237 if (ofile)
238 fclose(ofile);
239 if (ofile && terminate_after_phase)
240 remove(outname);
242 break;
244 case op_normal:
247 * We must call ofmt->filename _anyway_, even if the user
248 * has specified their own output file, because some
249 * formats (eg OBJ and COFF) use ofmt->filename to find out
250 * the name of the input file and then put that inside the
251 * file.
253 ofmt->filename (inname, outname, report_error);
255 ofile = fopen(outname, "wb");
256 if (!ofile) {
257 report_error (ERR_FATAL | ERR_NOFILE,
258 "unable to open output file `%s'", outname);
262 * We must call init_labels() before ofmt->init() since
263 * some object formats will want to define labels in their
264 * init routines. (eg OS/2 defines the FLAT group)
266 init_labels ();
268 ofmt->init (ofile, report_error, define_label, evaluate);
270 assemble_file (inname);
272 if (!terminate_after_phase) {
273 ofmt->cleanup (using_debug_info);
274 cleanup_labels ();
275 } else {
277 * We had an fclose on the output file here, but we
278 * actually do that in all the object file drivers as well,
279 * so we're leaving out the one here.
280 * fclose (ofile);
283 remove(outname);
284 if (listname[0])
285 remove(listname);
288 break;
291 if (want_usage)
292 usage();
294 raa_free (offsets);
295 saa_free (forwrefs);
296 eval_cleanup ();
297 nasmlib_cleanup ();
299 if (terminate_after_phase)
300 return 1;
301 else
302 return 0;
307 * Get a parameter for a command line option.
308 * First arg must be in the form of e.g. -f...
310 static char *get_param (char *p, char *q, int *advance)
312 *advance = 0;
313 if (p[2]) /* the parameter's in the option */
315 p += 2;
316 while (isspace(*p))
317 p++;
318 return p;
320 if (q && q[0])
322 *advance = 1;
323 return q;
325 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
326 "option `-%c' requires an argument",
327 p[1]);
328 return NULL;
331 struct textargs
333 char *label;
334 int value;
337 #define OPT_PREFIX 0
338 #define OPT_POSTFIX 1
339 struct textargs textopts[] =
341 {"prefix",OPT_PREFIX},
342 {"postfix",OPT_POSTFIX},
343 {NULL,0}
347 int stopoptions = 0;
348 static int process_arg (char *p, char *q)
350 char *param;
351 int i, advance = 0;
353 if (!p || !p[0])
354 return 0;
356 if (p[0]=='-' && ! stopoptions)
358 switch (p[1]) {
359 case 's':
360 error_file = stdout;
361 break;
362 case 'o': /* these parameters take values */
363 case 'O':
364 case 'f':
365 case 'p':
366 case 'P':
367 case 'd':
368 case 'D':
369 case 'i':
370 case 'I':
371 case 'l':
372 case 'E':
373 case 'F':
374 if ( !(param = get_param (p, q, &advance)) )
375 break;
376 if (p[1]=='o') { /* output file */
377 strcpy (outname, param);
378 } else if (p[1]=='f') { /* output format */
379 ofmt = ofmt_find(param);
380 if (!ofmt) {
381 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
382 "unrecognised output format `%s' - "
383 "use -hf for a list",
384 param);
386 else
387 ofmt->current_dfmt = ofmt->debug_formats[0];
388 } else if (p[1]=='O') { /* Optimization level */
389 if (!isdigit(*param)) report_error(ERR_FATAL,
390 "command line optimization level must be 0..3 or <nn>");
391 optimizing = atoi(param);
392 if (optimizing <= 0) optimizing = 0;
393 else if (optimizing <= 3) optimizing *= 5; /* 5 passes for each level */
394 } else if (p[1]=='P' || p[1]=='p') { /* pre-include */
395 pp_pre_include (param);
396 } else if (p[1]=='D' || p[1]=='d') { /* pre-define */
397 pp_pre_define (param);
398 } else if (p[1]=='U' || p[1]=='u') { /* un-define */
399 pp_pre_undefine (param);
400 } else if (p[1]=='I' || p[1]=='i') { /* include search path */
401 pp_include_path (param);
402 } else if (p[1]=='l') { /* listing file */
403 strcpy (listname, param);
404 } else if (p[1]=='E') { /* error messages file */
405 error_file = fopen(param, "w");
406 if ( !error_file ) {
407 error_file = stderr; /* Revert to default! */
408 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
409 "cannot open file `%s' for error messages",
410 param);
412 } else if (p[1] == 'F') { /* specify debug format */
413 ofmt->current_dfmt = dfmt_find(ofmt, param);
414 if (!ofmt->current_dfmt) {
415 report_error (ERR_FATAL | ERR_NOFILE | ERR_USAGE,
416 "unrecognized debug format `%s' for"
417 " output format `%s'",
418 param, ofmt->shortname);
421 break;
422 case 'g':
423 using_debug_info = TRUE;
424 break;
425 case 'h':
426 printf("usage: nasm [-@ response file] [-o outfile] [-f format] "
427 "[-l listfile]\n"
428 " [options...] [--] filename\n"
429 " or nasm -r for version info (obsolete)\n"
430 " or nasm -v for version info (preferred)\n\n"
431 " -t Assemble in SciTech TASM compatible mode\n"
432 " -g Generate debug information in selected format.\n"
433 " -e preprocess only (writes output to stdout by default)\n"
434 " -a don't preprocess (assemble only)\n"
435 " -M generate Makefile dependencies on stdout\n\n"
436 " -E<file> redirect error messages to file\n"
437 " -s redirect error messages to stdout\n\n"
438 " -F format select a debugging format\n\n"
439 " -I<path> adds a pathname to the include file path\n"
440 " -O<digit> optimize branch offsets (-O0 disables, default)\n"
441 " -P<file> pre-includes a file\n"
442 " -D<macro>[=<value>] pre-defines a macro\n"
443 " -U<macro> undefines a macro\n"
444 " -w+foo enables warnings about foo; -w-foo disables them\n"
445 "where foo can be:\n");
446 for (i=1; i<=ERR_WARN_MAX; i++)
447 printf(" %-16s%s (default %s)\n",
448 suppressed_names[i], suppressed_what[i],
449 suppressed[i] ? "off" : "on");
450 printf ("\nresponse files should contain command line parameters"
451 ", one per line.\n");
452 if (p[2] == 'f') {
453 printf("\nvalid output formats for -f are"
454 " (`*' denotes default):\n");
455 ofmt_list(ofmt, stdout);
457 else {
458 printf ("\nFor a list of valid output formats, use -hf.\n");
459 printf ("For a list of debug formats, use -f <form> -y.\n");
461 exit (0); /* never need usage message here */
462 break;
463 case 'y':
464 printf("\nvalid debug formats for '%s' output format are"
465 " ('*' denotes default):\n",
466 ofmt->shortname);
467 dfmt_list(ofmt, stdout);
468 exit(0);
469 break;
470 case 't':
471 tasm_compatible_mode = TRUE;
472 break;
473 case 'r':
474 case 'v':
475 printf("NASM version %s compiled "
476 #ifdef DEBUG
477 "with -DDEBUG "
478 #endif
479 "on " __DATE__ "\n", NASM_VER);
480 exit (0); /* never need usage message here */
481 break;
482 case 'e': /* preprocess only */
483 operating_mode = op_preprocess;
484 break;
485 case 'a': /* assemble only - don't preprocess */
486 preproc = &no_pp;
487 break;
488 case 'w':
489 if (p[2] != '+' && p[2] != '-') {
490 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
491 "invalid option to `-w'");
492 } else {
493 for (i=1; i<=ERR_WARN_MAX; i++)
494 if (!nasm_stricmp(p+3, suppressed_names[i]))
495 break;
496 if (i <= ERR_WARN_MAX)
497 suppressed[i] = (p[2] == '-');
498 else
499 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
500 "invalid option to `-w'");
502 break;
503 case 'M':
504 operating_mode = op_depend;
505 break;
507 case '-':
509 int s;
511 if (p[2]==0) { /* -- => stop processing options */
512 stopoptions = 1;
513 break;
515 for(s=0; textopts[s].label; s++)
517 if(!nasm_stricmp(p+2, textopts[s].label))
519 break;
523 switch(s)
526 case OPT_PREFIX:
527 case OPT_POSTFIX:
529 if (!q)
531 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
532 "option `--%s' requires an argument",
533 p+2);
534 break;
536 else
538 advance = 1, param = q;
541 if(s == OPT_PREFIX)
543 strncpy(lprefix,param,PREFIX_MAX-1);
544 lprefix[PREFIX_MAX-1]=0;
545 break;
547 if(s == OPT_POSTFIX)
549 strncpy(lpostfix,param,POSTFIX_MAX-1);
550 lpostfix[POSTFIX_MAX-1]=0;
551 break;
553 break;
555 default:
557 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
558 "unrecognised option `--%s'",
559 p+2);
560 break;
563 break;
566 default:
567 if (!ofmt->setinfo(GI_SWITCH,&p))
568 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
569 "unrecognised option `-%c'",
570 p[1]);
571 break;
574 else
576 if (*inname) {
577 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
578 "more than one input file specified");
579 } else
580 strcpy(inname, p);
583 return advance;
586 #define ARG_BUF_DELTA 128
588 static void process_respfile (FILE *rfile)
590 char *buffer, *p, *q, *prevarg;
591 int bufsize, prevargsize;
593 bufsize = prevargsize = ARG_BUF_DELTA;
594 buffer = nasm_malloc(ARG_BUF_DELTA);
595 prevarg = nasm_malloc(ARG_BUF_DELTA);
596 prevarg[0] = '\0';
598 while (1) { /* Loop to handle all lines in file */
600 p = buffer;
601 while (1) { /* Loop to handle long lines */
602 q = fgets(p, bufsize-(p-buffer), rfile);
603 if (!q)
604 break;
605 p += strlen(p);
606 if (p > buffer && p[-1] == '\n')
607 break;
608 if (p-buffer > bufsize-10) {
609 int offset;
610 offset = p - buffer;
611 bufsize += ARG_BUF_DELTA;
612 buffer = nasm_realloc(buffer, bufsize);
613 p = buffer + offset;
617 if (!q && p == buffer) {
618 if (prevarg[0])
619 process_arg (prevarg, NULL);
620 nasm_free (buffer);
621 nasm_free (prevarg);
622 return;
626 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
627 * them are present at the end of the line.
629 *(p = &buffer[strcspn(buffer, "\r\n\032")]) = '\0';
631 while (p > buffer && isspace(p[-1]))
632 *--p = '\0';
634 p = buffer;
635 while (isspace(*p))
636 p++;
638 if (process_arg (prevarg, p))
639 *p = '\0';
641 if (strlen(p) > prevargsize-10) {
642 prevargsize += ARG_BUF_DELTA;
643 prevarg = nasm_realloc(prevarg, prevargsize);
645 strcpy (prevarg, p);
649 /* Function to process args from a string of args, rather than the
650 * argv array. Used by the environment variable and response file
651 * processing.
653 static void process_args (char *args) {
654 char *p, *q, *arg, *prevarg;
655 char separator = ' ';
657 p = args;
658 if (*p && *p != '-')
659 separator = *p++;
660 arg = NULL;
661 while (*p) {
662 q = p;
663 while (*p && *p != separator) p++;
664 while (*p == separator) *p++ = '\0';
665 prevarg = arg;
666 arg = q;
667 if (process_arg (prevarg, arg))
668 arg = NULL;
670 if (arg)
671 process_arg (arg, NULL);
674 static void parse_cmdline(int argc, char **argv)
676 FILE *rfile;
677 char *envreal, *envcopy=NULL, *p, *arg;
679 *inname = *outname = *listname = '\0';
682 * First, process the NASM environment variable.
684 envreal = getenv("NASM");
685 arg = NULL;
686 if (envreal) {
687 envcopy = nasm_strdup(envreal);
688 process_args(envcopy);
689 nasm_free (envcopy);
693 * Now process the actual command line.
695 while (--argc)
697 int i;
698 argv++;
699 if (argv[0][0] == '@') {
700 /* We have a response file, so process this as a set of
701 * arguments like the environment variable. This allows us
702 * to have multiple arguments on a single line, which is
703 * different to the -@resp file processing below for regular
704 * NASM.
706 char *str = malloc(2048);
707 FILE *f = fopen(&argv[0][1],"r");
708 if (!str) {
709 printf("out of memory");
710 exit(-1);
712 if (f) {
713 while (fgets(str,2048,f)) {
714 process_args(str);
716 fclose(f);
718 free(str);
719 argc--;
720 argv++;
722 if (!stopoptions && argv[0][0] == '-' && argv[0][1] == '@') {
723 if ((p = get_param (argv[0], argc > 1 ? argv[1] : NULL, &i))) {
724 if ((rfile = fopen(p, "r"))) {
725 process_respfile (rfile);
726 fclose(rfile);
727 } else
728 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
729 "unable to open response file `%s'", p);
731 } else
732 i = process_arg (argv[0], argc > 1 ? argv[1] : NULL);
733 argv += i, argc -= i;
736 if (!*inname)
737 report_error (ERR_NONFATAL | ERR_NOFILE | ERR_USAGE,
738 "no input file specified");
742 static void assemble_file (char *fname)
744 char * value, * p, * q, * special, * line, debugid[80];
745 insn output_ins;
746 int i, rn_error, validid;
747 long seg, offs;
748 struct tokenval tokval;
749 expr * e;
750 int pass, pass_max;
751 int pass_cnt = 0; /* count actual passes */
753 if (cmd_sb == 32 && cmd_cpu < IF_386)
754 report_error(ERR_FATAL, "command line: "
755 "32-bit segment size requires a higher cpu");
757 pass_max = optimizing + 2; /* passes 1, optimizing, then 2 */
758 pass0 = !optimizing; /* start at 1 if not optimizing */
759 for (pass = 1; pass <= pass_max && pass0 <= 2; pass++) {
760 int pass1, pass2;
761 ldfunc def_label;
763 pass1 = pass < pass_max ? 1 : 2; /* seq is 1, 1, 1,..., 1, 2 */
764 pass2 = pass > 1 ? 2 : 1; /* seq is 1, 2, 2,..., 2, 2 */
765 /* pass0 seq is 0, 0, 0,..., 1, 2 */
767 def_label = pass > 1 ? redefine_label : define_label;
770 sb = cmd_sb; /* set 'bits' to command line default */
771 cpu = cmd_cpu;
772 if (pass0 == 2) {
773 if (*listname)
774 nasmlist.init(listname, report_error);
776 in_abs_seg = FALSE;
777 global_offset_changed = FALSE; /* set by redefine_label */
778 location.segment = ofmt->section(NULL, pass2, &sb);
779 if (pass > 1) {
780 saa_rewind (forwrefs);
781 forwref = saa_rstruct (forwrefs);
782 raa_free (offsets);
783 offsets = raa_init();
785 preproc->reset(fname, pass1, report_error, evaluate, &nasmlist);
786 globallineno = 0;
787 if (pass == 1) location.known = TRUE;
788 location.offset = offs = GET_CURR_OFFS;
790 while ( (line = preproc->getline()) )
792 globallineno++;
794 /* here we parse our directives; this is not handled by the 'real'
795 * parser. */
796 if ( (i = getkw (line, &value)) )
798 switch (i) {
799 case 1: /* [SEGMENT n] */
800 seg = ofmt->section (value, pass2, &sb);
801 if (seg == NO_SEG) {
802 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
803 "segment name `%s' not recognised",
804 value);
805 } else {
806 in_abs_seg = FALSE;
807 location.segment = seg;
809 break;
810 case 2: /* [EXTERN label:special] */
811 if (*value == '$') value++; /* skip initial $ if present */
812 if (pass0 == 2) {
813 q = value;
814 while (*q && *q != ':')
815 q++;
816 if (*q == ':') {
817 *q++ = '\0';
818 ofmt->symdef(value, 0L, 0L, 3, q);
820 } else if (pass0 == 1) { /* pass == 1 */
821 q = value;
822 validid = TRUE;
823 if (!isidstart(*q))
824 validid = FALSE;
825 while (*q && *q != ':') {
826 if (!isidchar(*q))
827 validid = FALSE;
828 q++;
830 if (!validid) {
831 report_error (ERR_NONFATAL,
832 "identifier expected after EXTERN");
833 break;
835 if (*q == ':') {
836 *q++ = '\0';
837 special = q;
838 } else
839 special = NULL;
840 if (!is_extern(value)) { /* allow re-EXTERN to be ignored */
841 declare_as_global (value, special, report_error);
842 define_label (value, seg_alloc(), 0L, NULL, FALSE, TRUE,
843 ofmt, report_error);
845 } /* else pass0 == 1 */
846 break;
847 case 3: /* [BITS bits] */
848 sb = get_bits(value);
849 break;
850 case 4: /* [GLOBAL symbol:special] */
851 if (*value == '$') value++; /* skip initial $ if present */
852 if (pass0 == 2) { /* pass 2 */
853 q = value;
854 while (*q && *q != ':')
855 q++;
856 if (*q == ':') {
857 *q++ = '\0';
858 ofmt->symdef(value, 0L, 0L, 3, q);
860 } else if (pass2 == 1) { /* pass == 1 */
861 q = value;
862 validid = TRUE;
863 if (!isidstart(*q))
864 validid = FALSE;
865 while (*q && *q != ':') {
866 if (!isidchar(*q))
867 validid = FALSE;
868 q++;
870 if (!validid) {
871 report_error (ERR_NONFATAL,
872 "identifier expected after GLOBAL");
873 break;
875 if (*q == ':') {
876 *q++ = '\0';
877 special = q;
878 } else
879 special = NULL;
880 declare_as_global (value, special, report_error);
881 } /* pass == 1 */
882 break;
883 case 5: /* [COMMON symbol size:special] */
884 if (*value == '$') value++; /* skip initial $ if present */
885 if (pass0 == 1) {
886 p = value;
887 validid = TRUE;
888 if (!isidstart(*p))
889 validid = FALSE;
890 while (*p && !isspace(*p)) {
891 if (!isidchar(*p))
892 validid = FALSE;
893 p++;
895 if (!validid) {
896 report_error (ERR_NONFATAL,
897 "identifier expected after COMMON");
898 break;
900 if (*p) {
901 long size;
903 while (*p && isspace(*p))
904 *p++ = '\0';
905 q = p;
906 while (*q && *q != ':')
907 q++;
908 if (*q == ':') {
909 *q++ = '\0';
910 special = q;
911 } else
912 special = NULL;
913 size = readnum (p, &rn_error);
914 if (rn_error)
915 report_error (ERR_NONFATAL, "invalid size specified"
916 " in COMMON declaration");
917 else
918 define_common (value, seg_alloc(), size,
919 special, ofmt, report_error);
920 } else
921 report_error (ERR_NONFATAL, "no size specified in"
922 " COMMON declaration");
923 } else if (pass0 == 2) { /* pass == 2 */
924 q = value;
925 while (*q && *q != ':') {
926 if (isspace(*q))
927 *q = '\0';
928 q++;
930 if (*q == ':') {
931 *q++ = '\0';
932 ofmt->symdef(value, 0L, 0L, 3, q);
935 break;
936 case 6: /* [ABSOLUTE address] */
937 stdscan_reset();
938 stdscan_bufptr = value;
939 tokval.t_type = TOKEN_INVALID;
940 e = evaluate(stdscan, NULL, &tokval, NULL, pass2, report_error,
941 NULL);
942 if (e) {
943 if (!is_reloc(e))
944 report_error (pass0==1 ? ERR_NONFATAL : ERR_PANIC,
945 "cannot use non-relocatable expression as "
946 "ABSOLUTE address");
947 else {
948 abs_seg = reloc_seg(e);
949 abs_offset = reloc_value(e);
951 } else
952 if (pass==1) abs_offset = 0x100;/* don't go near zero in case of / */
953 else report_error (ERR_PANIC, "invalid ABSOLUTE address "
954 "in pass two");
955 in_abs_seg = TRUE;
956 location.segment = abs_seg;
957 break;
958 case 7: /* DEBUG */
959 p = value;
960 q = debugid;
961 validid = TRUE;
962 if (!isidstart(*p))
963 validid = FALSE;
964 while (*p && !isspace(*p)) {
965 if (!isidchar(*p))
966 validid = FALSE;
967 *q++ = *p++;
969 *q++ = 0;
970 if (!validid) {
971 report_error (pass==1 ? ERR_NONFATAL : ERR_PANIC,
972 "identifier expected after DEBUG");
973 break;
975 while (*p && isspace(*p)) p++;
976 if (pass==pass_max) ofmt->current_dfmt->debug_directive (debugid, p);
977 break;
978 case 8: /* [WARNING {+|-}warn-name] */
979 if (pass1 == 1) {
980 while (*value && isspace(*value))
981 value++;
983 if (*value == '+' || *value == '-') {
984 validid = (*value == '-') ? TRUE : FALSE;
985 value++;
986 } else
987 validid = FALSE;
989 for (i=1; i<=ERR_WARN_MAX; i++)
990 if (!nasm_stricmp(value, suppressed_names[i]))
991 break;
992 if (i <= ERR_WARN_MAX)
993 suppressed[i] = validid;
994 else
995 report_error (ERR_NONFATAL, "invalid warning id in WARNING directive");
997 break;
998 case 9: /* cpu */
999 cpu = get_cpu (value);
1000 break;
1001 case 10: /* fbk 9/2/00 */ /* [LIST {+|-}] */
1002 while (*value && isspace(*value))
1003 value++;
1005 if (*value == '+') {
1006 user_nolist = 0;
1008 else {
1009 if (*value == '-') {
1010 user_nolist = 1;
1012 else {
1013 report_error (ERR_NONFATAL, "invalid parameter to \"list\" directive");
1016 break;
1017 default:
1018 if (!ofmt->directive (line+1, value, pass2))
1019 report_error (pass1==1 ? ERR_NONFATAL : ERR_PANIC,
1020 "unrecognised directive [%s]",
1021 line+1);
1024 else /* it isn't a directive */
1026 parse_line (pass1, line, &output_ins,
1027 report_error, evaluate,
1028 def_label);
1030 if (!optimizing && pass == 2) {
1031 if (forwref != NULL && globallineno == forwref->lineno) {
1032 output_ins.forw_ref = TRUE;
1033 do {
1034 output_ins.oprs[forwref->operand].opflags|= OPFLAG_FORWARD;
1035 forwref = saa_rstruct (forwrefs);
1036 } while (forwref != NULL && forwref->lineno == globallineno);
1037 } else
1038 output_ins.forw_ref = FALSE;
1042 if (!optimizing && output_ins.forw_ref)
1044 if (pass == 1) {
1045 for(i = 0; i < output_ins.operands; i++)
1047 if (output_ins.oprs[i].opflags & OPFLAG_FORWARD)
1049 struct forwrefinfo *fwinf =
1050 (struct forwrefinfo *)saa_wstruct(forwrefs);
1051 fwinf->lineno = globallineno;
1052 fwinf->operand = i;
1055 } else { /* pass == 2 */
1057 * Hack to prevent phase error in the code
1058 * rol ax,x
1059 * x equ 1
1061 * If the second operand is a forward reference,
1062 * the UNITY property of the number 1 in that
1063 * operand is cancelled. Otherwise the above
1064 * sequence will cause a phase error.
1066 * This hack means that the above code will
1067 * generate 286+ code.
1069 * The forward reference will mean that the
1070 * operand will not have the UNITY property on
1071 * the first pass, so the pass behaviours will
1072 * be consistent.
1075 if (output_ins.operands >= 2 &&
1076 (output_ins.oprs[1].opflags & OPFLAG_FORWARD))
1078 output_ins.oprs[1].type &= ~(ONENESS|BYTENESS);
1081 } /* pass == 2 */
1083 } /* forw_ref */
1086 if (output_ins.opcode == I_EQU) {
1087 if (pass1 == 1)
1090 * Special `..' EQUs get processed in pass two,
1091 * except `..@' macro-processor EQUs which are done
1092 * in the normal place.
1094 if (!output_ins.label)
1095 report_error (ERR_NONFATAL,
1096 "EQU not preceded by label");
1098 else if (output_ins.label[0] != '.' ||
1099 output_ins.label[1] != '.' ||
1100 output_ins.label[2] == '@')
1102 if (output_ins.operands == 1 &&
1103 (output_ins.oprs[0].type & IMMEDIATE) &&
1104 output_ins.oprs[0].wrt == NO_SEG)
1106 int isext = output_ins.oprs[0].opflags & OPFLAG_EXTERN;
1107 def_label (output_ins.label,
1108 output_ins.oprs[0].segment,
1109 output_ins.oprs[0].offset,
1110 NULL, FALSE, isext, ofmt, report_error);
1112 else if (output_ins.operands == 2 &&
1113 (output_ins.oprs[0].type & IMMEDIATE) &&
1114 (output_ins.oprs[0].type & COLON) &&
1115 output_ins.oprs[0].segment == NO_SEG &&
1116 output_ins.oprs[0].wrt == NO_SEG &&
1117 (output_ins.oprs[1].type & IMMEDIATE) &&
1118 output_ins.oprs[1].segment == NO_SEG &&
1119 output_ins.oprs[1].wrt == NO_SEG)
1121 def_label (output_ins.label,
1122 output_ins.oprs[0].offset | SEG_ABS,
1123 output_ins.oprs[1].offset,
1124 NULL, FALSE, FALSE, ofmt, report_error);
1126 else
1127 report_error(ERR_NONFATAL, "bad syntax for EQU");
1129 } else { /* pass == 2 */
1131 * Special `..' EQUs get processed here, except
1132 * `..@' macro processor EQUs which are done above.
1134 if (output_ins.label[0] == '.' &&
1135 output_ins.label[1] == '.' &&
1136 output_ins.label[2] != '@')
1138 if (output_ins.operands == 1 &&
1139 (output_ins.oprs[0].type & IMMEDIATE)) {
1140 define_label (output_ins.label,
1141 output_ins.oprs[0].segment,
1142 output_ins.oprs[0].offset,
1143 NULL, FALSE, FALSE, ofmt, report_error);
1145 else if (output_ins.operands == 2 &&
1146 (output_ins.oprs[0].type & IMMEDIATE) &&
1147 (output_ins.oprs[0].type & COLON) &&
1148 output_ins.oprs[0].segment == NO_SEG &&
1149 (output_ins.oprs[1].type & IMMEDIATE) &&
1150 output_ins.oprs[1].segment == NO_SEG)
1152 define_label (output_ins.label,
1153 output_ins.oprs[0].offset | SEG_ABS,
1154 output_ins.oprs[1].offset,
1155 NULL, FALSE, FALSE, ofmt, report_error);
1157 else
1158 report_error(ERR_NONFATAL, "bad syntax for EQU");
1160 } /* pass == 2 */
1161 } else { /* instruction isn't an EQU */
1163 if (pass1 == 1) {
1165 long l = insn_size (location.segment, offs, sb, cpu,
1166 &output_ins, report_error);
1168 /* if (using_debug_info) && output_ins.opcode != -1)*/
1169 if (using_debug_info) /* fbk 03/25/01 */
1172 /* this is done here so we can do debug type info */
1173 long typeinfo = TYS_ELEMENTS(output_ins.operands);
1174 switch (output_ins.opcode) {
1175 case I_RESB:
1176 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;
1177 break;
1178 case I_RESW:
1179 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;
1180 break;
1181 case I_RESD:
1182 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;
1183 break;
1184 case I_RESQ:
1185 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;
1186 break;
1187 case I_REST:
1188 typeinfo = TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;
1189 break;
1190 case I_DB:
1191 typeinfo |= TY_BYTE;
1192 break;
1193 case I_DW:
1194 typeinfo |= TY_WORD;
1195 break;
1196 case I_DD:
1197 if (output_ins.eops_float)
1198 typeinfo |= TY_FLOAT;
1199 else
1200 typeinfo |= TY_DWORD;
1201 break;
1202 case I_DQ:
1203 typeinfo |= TY_QWORD;
1204 break;
1205 case I_DT:
1206 typeinfo |= TY_TBYTE;
1207 break;
1208 default:
1209 typeinfo = TY_LABEL;
1213 ofmt->current_dfmt->debug_typevalue(typeinfo);
1216 if (l != -1) {
1217 offs += l;
1218 SET_CURR_OFFS (offs);
1221 * else l == -1 => invalid instruction, which will be
1222 * flagged as an error on pass 2
1225 } else { /* pass == 2 */
1226 offs += assemble (location.segment, offs, sb, cpu,
1227 &output_ins, ofmt, report_error, &nasmlist);
1228 SET_CURR_OFFS (offs);
1231 } /* not an EQU */
1232 cleanup_insn (&output_ins);
1234 nasm_free (line);
1235 location.offset = offs = GET_CURR_OFFS;
1236 } /* end while (line = preproc->getline... */
1238 if (pass1==2 && global_offset_changed)
1239 report_error(ERR_NONFATAL, "phase error detected at end of assembly.");
1241 if (pass1 == 1) preproc->cleanup();
1243 if (pass1==1 && terminate_after_phase) {
1244 fclose(ofile);
1245 remove(outname);
1246 if (want_usage)
1247 usage();
1248 exit (1);
1250 pass_cnt++;
1251 if (pass>1 && !global_offset_changed) {
1252 pass0++;
1253 if (pass0==2) pass = pass_max - 1;
1254 } else if (!optimizing) pass0++;
1256 } /* for (pass=1; pass<=2; pass++) */
1258 nasmlist.cleanup();
1259 #if 1
1260 if (optimizing && using_debug_info) /* -On and -g switches */
1261 fprintf(error_file,
1262 "info:: assembly required 1+%d+1 passes\n", pass_cnt-2);
1263 #endif
1264 } /* exit from assemble_file (...) */
1267 static int getkw (char *buf, char **value)
1269 char *p, *q;
1271 if (*buf!='[')
1272 return 0;
1274 p = buf;
1276 while (*p && *p != ']') p++;
1278 if (!*p)
1279 return 0;
1281 q = p++;
1283 while (*p && *p != ';') {
1284 if (!isspace(*p))
1285 return 0;
1286 p++;
1288 q[1] = '\0';
1290 p = buf+1;
1291 while (*buf && *buf!=' ' && *buf!=']' && *buf!='\t')
1292 buf++;
1293 if (*buf==']') {
1294 *buf = '\0';
1295 *value = buf;
1296 } else {
1297 *buf++ = '\0';
1298 while (isspace(*buf)) buf++; /* beppu - skip leading whitespace */
1299 *value = buf;
1300 while (*buf!=']') buf++;
1301 *buf++ = '\0';
1303 #if 0
1304 for (q=p; *q; q++)
1305 *q = tolower(*q);
1306 #endif
1307 if (!nasm_stricmp(p, "segment") || !nasm_stricmp(p, "section"))
1308 return 1;
1309 if (!nasm_stricmp(p, "extern"))
1310 return 2;
1311 if (!nasm_stricmp(p, "bits"))
1312 return 3;
1313 if (!nasm_stricmp(p, "global"))
1314 return 4;
1315 if (!nasm_stricmp(p, "common"))
1316 return 5;
1317 if (!nasm_stricmp(p, "absolute"))
1318 return 6;
1319 if (!nasm_stricmp(p, "debug"))
1320 return 7;
1321 if (!nasm_stricmp(p, "warning"))
1322 return 8;
1323 if (!nasm_stricmp(p, "cpu"))
1324 return 9;
1325 if (!nasm_stricmp(p, "list")) /* fbk 9/2/00 */
1326 return 10;
1327 return -1;
1330 static void report_error (int severity, char *fmt, ...)
1332 va_list ap;
1335 * See if it's a suppressed warning.
1337 if ((severity & ERR_MASK) == ERR_WARNING &&
1338 (severity & ERR_WARN_MASK) != 0 &&
1339 suppressed[ (severity & ERR_WARN_MASK) >> ERR_WARN_SHR ])
1340 return; /* and bail out if so */
1343 * See if it's a pass-one only warning and we're not in pass one.
1345 if ((severity & ERR_PASS1) && pass0 == 2)
1346 return;
1348 if (severity & ERR_NOFILE)
1349 fputs ("nasm: ", error_file);
1350 else {
1351 char * currentfile = NULL;
1352 long lineno = 0;
1353 src_get (&lineno, &currentfile);
1354 fprintf (error_file, "%s:%ld: ", currentfile, lineno);
1355 nasm_free (currentfile);
1358 switch (severity & ERR_MASK) {
1359 case ERR_WARNING:
1360 fputs ("warning: ", error_file); break;
1361 case ERR_NONFATAL:
1362 fputs ("error: ", error_file); break;
1363 case ERR_FATAL:
1364 fputs ("fatal: ", error_file); break;
1365 case ERR_PANIC:
1366 fputs ("panic: ", error_file); break;
1367 case ERR_DEBUG:
1368 fputs("debug: ", error_file); break;
1371 va_start (ap, fmt);
1372 vfprintf (error_file, fmt, ap);
1373 fputc ('\n', error_file);
1375 if (severity & ERR_USAGE)
1376 want_usage = TRUE;
1378 switch (severity & ERR_MASK) {
1379 case ERR_WARNING: case ERR_DEBUG:
1380 /* no further action, by definition */
1381 break;
1382 case ERR_NONFATAL:
1383 terminate_after_phase = TRUE;
1384 break;
1385 case ERR_FATAL:
1386 if (ofile) {
1387 fclose(ofile);
1388 remove(outname);
1390 if (want_usage)
1391 usage();
1392 exit(1); /* instantly die */
1393 break; /* placate silly compilers */
1394 case ERR_PANIC:
1395 fflush(NULL);
1396 /* abort(); */ /* halt, catch fire, and dump core */
1397 exit(3);
1398 break;
1402 static void usage(void)
1404 fputs("type `nasm -h' for help\n", error_file);
1407 static void register_output_formats(void)
1409 ofmt = ofmt_register (report_error);
1412 #define BUF_DELTA 512
1414 static FILE *no_pp_fp;
1415 static efunc no_pp_err;
1416 static ListGen *no_pp_list;
1417 static long no_pp_lineinc;
1419 static void no_pp_reset (char *file, int pass, efunc error, evalfunc eval,
1420 ListGen *listgen)
1422 src_set_fname(nasm_strdup(file));
1423 src_set_linnum(0);
1424 no_pp_lineinc = 1;
1425 no_pp_err = error;
1426 no_pp_fp = fopen(file, "r");
1427 if (!no_pp_fp)
1428 no_pp_err (ERR_FATAL | ERR_NOFILE,
1429 "unable to open input file `%s'", file);
1430 no_pp_list = listgen;
1431 (void) pass; /* placate compilers */
1432 (void) eval; /* placate compilers */
1435 static char *no_pp_getline (void)
1437 char *buffer, *p, *q;
1438 int bufsize;
1440 bufsize = BUF_DELTA;
1441 buffer = nasm_malloc(BUF_DELTA);
1442 src_set_linnum(src_get_linnum() + no_pp_lineinc);
1444 while (1) { /* Loop to handle %line */
1446 p = buffer;
1447 while (1) { /* Loop to handle long lines */
1448 q = fgets(p, bufsize-(p-buffer), no_pp_fp);
1449 if (!q)
1450 break;
1451 p += strlen(p);
1452 if (p > buffer && p[-1] == '\n')
1453 break;
1454 if (p-buffer > bufsize-10) {
1455 int offset;
1456 offset = p - buffer;
1457 bufsize += BUF_DELTA;
1458 buffer = nasm_realloc(buffer, bufsize);
1459 p = buffer + offset;
1463 if (!q && p == buffer) {
1464 nasm_free (buffer);
1465 return NULL;
1469 * Play safe: remove CRs, LFs and any spurious ^Zs, if any of
1470 * them are present at the end of the line.
1472 buffer[strcspn(buffer, "\r\n\032")] = '\0';
1474 if (!strncmp(buffer, "%line", 5)) {
1475 long ln;
1476 int li;
1477 char *nm = nasm_malloc(strlen(buffer));
1478 if (sscanf(buffer+5, "%ld+%d %s", &ln, &li, nm) == 3) {
1479 nasm_free( src_set_fname(nm) );
1480 src_set_linnum(ln);
1481 no_pp_lineinc = li;
1482 continue;
1484 nasm_free(nm);
1486 break;
1489 no_pp_list->line (LIST_READ, buffer);
1491 return buffer;
1494 static void no_pp_cleanup (void)
1496 fclose(no_pp_fp);
1499 static unsigned long get_cpu (char *value)
1502 if (!strcmp(value, "8086")) return IF_8086;
1503 if (!strcmp(value, "186")) return IF_186;
1504 if (!strcmp(value, "286")) return IF_286;
1505 if (!strcmp(value, "386")) return IF_386;
1506 if (!strcmp(value, "486")) return IF_486;
1507 if (!strcmp(value, "586") ||
1508 !nasm_stricmp(value, "pentium") ) return IF_PENT;
1509 if (!strcmp(value, "686") ||
1510 !nasm_stricmp(value, "ppro") ||
1511 !nasm_stricmp(value, "p2") ) return IF_P6;
1512 if (!nasm_stricmp(value, "p3") ||
1513 !nasm_stricmp(value, "katmai") ) return IF_KATMAI;
1515 report_error (pass0<2 ? ERR_NONFATAL : ERR_FATAL, "unknown 'cpu' type");
1517 return IF_PLEVEL; /* the maximum level */
1521 static int get_bits (char *value)
1523 int i;
1525 if ((i = atoi(value)) == 16) return i; /* set for a 16-bit segment */
1526 else if (i == 32) {
1527 if (cpu < IF_386) {
1528 report_error(ERR_NONFATAL,
1529 "cannot specify 32-bit segment on processor below a 386");
1530 i = 16;
1532 } else {
1533 report_error(pass0<2 ? ERR_NONFATAL : ERR_FATAL,
1534 "`%s' is not a valid segment size; must be 16 or 32",
1535 value);
1536 i = 16;
1538 return i;
1541 /* end of nasm.c */