* as/mcs51/asmain.c (search_path_append, search_path_fopen): new, added,
[fw/sdcc] / as / mcs51 / asmain.c
1 /* asmain.c */
2
3 /*
4  * (C) Copyright 1989-1995
5  * All Rights Reserved
6  *
7  * Alan R. Baldwin
8  * 721 Berkeley St.
9  * Kent, Ohio  44240
10  *
11  * 29-Oct-97 JLH pass ";!" comments to output file
12  */
13
14 #include <errno.h>
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <setjmp.h>
18 #include <string.h>
19
20 #include "asm.h"
21
22 /*)Module       asmain.c
23  *
24  *      The module asmain.c includes the command argument parser,
25  *      the three pass sequencer, and the machine independent
26  *      assembler parsing code.
27  *
28  *      asmain.c contains the following functions:
29  *              VOID    main(argc, argv)
30  *              VOID    asexit()
31  *              VOID    asmbl()
32  *              FILE *  afile(fn, ft, wf)
33  *              VOID    newdot(nap)
34  *              VOID    phase(ap, a)
35  *              VOID    usage()
36  *
37  *      asmain.c contains the array char *usetxt[] which
38  *      references the usage text strings printed by usage().
39  */
40
41 static const char *search_path[100];
42 static int search_path_length;
43
44 /**
45  * The search_path_append is used to append another directory to the end
46  * of the include file search path.
47  *
48  * @param dir
49  *     The directory to be added to the path.
50  */
51 void
52 search_path_append(const char *dir)
53 {
54         if (search_path_length < sizeof(search_path)/sizeof(char*))
55         {
56                 search_path[search_path_length++] = dir;
57         }
58 }
59
60 /**
61  * The search_path_fopen function is used to open the named file.  If
62  * the file isn't in the current directory, the search path is then used
63  * to build a series of possible file names, and attempts to open them.
64  * The first found is used.
65  *
66  * @param filename
67  *     The name of the file to be opened.
68  * @param mode
69  *     The mode of the file to be opened.
70  * @returns
71  *     what the fopen function would return on success, or NULL if the
72  *     file is not anywhere in the search path.
73  */
74 static FILE *
75 search_path_fopen(const char *filename, const char *mode)
76 {
77         FILE *fp;
78         int j;
79
80         fp = fopen(filename, mode);
81         if (fp != NULL || filename[0] == '/' || filename[0] == '\\')
82                 return fp;
83         for (j = 0; j < search_path_length; ++j)
84         {
85                 char path[2000];
86
87                 strncpy(path, search_path[j], sizeof(path));
88                 if ((path[strlen(path) - 1] != '/') &&
89                     (path[strlen(path) - 1] != DIR_SEPARATOR_CHAR))
90                 {
91                         strncat(path, DIR_SEPARATOR_STRING, sizeof(path));
92                 }
93                 strncat(path, filename, sizeof(path));
94                 fp = fopen(path, mode);
95                 if (fp != NULL)
96                         return fp;
97         }
98         errno = ENOENT;
99         return NULL;
100 }
101
102 /*)Function     VOID    main(argc, argv)
103  *
104  *              int     argc            argument count
105  *              char *  argv            array of pointers to argument strings
106  *
107  *      The function main() is the entry point to the assembler.
108  *      The purpose of main() is to (1) parse the command line
109  *      arguments for options and source file specifications and
110  *      (2) to process the source files through the 3 pass assembler.
111  *      Before each assembler pass various variables are initialized
112  *      and source files are rewound to their beginning.  During each
113  *      assembler pass each assembler-source text line is processed.
114  *      After each assembler pass the assembler information is flushed
115  *      to any opened output files and the if-else-endif processing
116  *      is checked for proper termination.
117  *
118  *      The function main() is also responsible for opening all
119  *      output files (REL, LST, and SYM), sequencing the global (-g)
120  *      and all-global (-a) variable definitions, and dumping the
121  *      REL file header information.
122  *
123  *      local variables:
124  *              char *  p               pointer to argument string
125  *              int     c               character from argument string
126  *              int     i               argument loop counter
127  *              area *  ap              pointer to area structure
128  *
129  *      global variables:
130  *              int     aflag           -a, make all symbols global flag
131  *              char    afn[]           afile() constructed filespec
132  *              area *  areap           pointer to an area structure
133  *              int     cb[]            array of assembler output values
134  *              int     cbt[]           array of assembler relocation types
135  *                                      describing the data in cb[]
136  *              int     cfile           current file handle index
137  *                                      of input assembly files
138  *              int *   cp              pointer to assembler output array cb[]
139  *              int *   cpt             pointer to assembler relocation type
140  *                                      output array cbt[]
141  *              char    eb[]            array of generated error codes
142  *              char *  ep              pointer into error list array eb[]
143  *              int     fflag           -f(f), relocations flagged flag
144  *              int     flevel          IF-ELSE-ENDIF flag will be non
145  *                                      zero for false conditional case
146  *              Addr_T  fuzz            tracks pass to pass changes in the
147  *                                      address of symbols caused by
148  *                                      variable length instruction formats
149  *              int     gflag           -g, make undefined symbols global flag
150  *              char    ib[]            assembler-source text line
151  *              int     inpfil          count of assembler
152  *                                      input files specified
153  *              int     ifcnd[]         array of IF statement condition
154  *                                      values (0 = FALSE) indexed by tlevel
155  *              int     iflvl[]         array of IF-ELSE-ENDIF flevel
156  *                                      values indexed by tlevel
157  *              int     incfil          current file handle index
158  *                                      for include files
159  *              char *  ip              pointer into the assembler-source
160  *                                      text line in ib[]
161  *              jmp_buf jump_env        compiler dependent structure
162  *                                      used by setjmp() and longjmp()
163  *              int     lflag           -l, generate listing flag
164  *              int     line            current assembler source
165  *                                      line number
166  *              int     lop             current line number on page
167  *              int     oflag           -o, generate relocatable output flag
168  *              int     jflag           -j, generate debug info flag
169  *              int     page            current page number
170  *              int     pflag           enable listing pagination
171  *              int     pass            assembler pass number
172  *              int     radix           current number conversion radix:
173  *                                      2 (binary), 8 (octal), 10 (decimal),
174  *                                      16 (hexadecimal)
175  *              int     sflag           -s, generate symbol table flag
176  *              char    srcfn[][]       array of source file names
177  *              int     srcline[]       current source file line
178  *              char    stb[]           Subtitle string buffer
179  *              sym *   symp            pointer to a symbol structure
180  *              int     tlevel          current conditional level
181  *              int     xflag           -x, listing radix flag
182  *              FILE *  lfp             list output file handle
183  *              FILE *  ofp             relocation output file handle
184  *              FILE *  tfp             symbol table output file handle
185  *              FILE *  sfp[]           array of assembler-source file handles
186  *
187  *      called functions:
188  *              FILE *  afile()         asmain.c
189  *              VOID    allglob()       assym.c
190  *              VOID    asexit()        asmain.c
191  *              VOID    diag()          assubr.c
192  *              VOID    err()           assubr.c
193  *              int     fprintf()       c-library
194  *              int     as_getline()    aslex.c
195  *              VOID    list()          aslist.c
196  *              VOID    lstsym()        aslist.c
197  *              VOID    minit()         ___mch.c
198  *              VOID    newdot()        asmain.c
199  *              VOID    outchk()        asout.c
200  *              VOID    outgsd()        asout.c
201  *              int     rewind()        c-library
202  *              int     setjmp()        c-library
203  *              VOID    symglob()       assym.c
204  *              VOID    syminit()       assym.c
205  *              VOID    usage()         asmain.c
206  *
207  *      side effects:
208  *              Completion of main() completes the assembly process.
209  *              REL, LST, and/or SYM files may be generated.
210  */
211
212 int fatalErrors=0;
213 char relFile[128];
214
215 int
216 main(argc, argv)
217 char *argv[];
218 {
219         register char *p;
220         register int c, i;
221         struct area *ap;
222
223         /*fprintf(stdout, "\n");*/
224         inpfil = -1;
225         pflag = 1;
226         for (i=1; i<argc; ++i) {
227                 p = argv[i];
228                 if (*p == '-') {
229                         if (inpfil >= 0)
230                                 usage();
231                         ++p;
232                         while ((c = *p++) != 0)
233                                 switch(c) {
234
235                                 case 'a':
236                                 case 'A':
237                                         ++aflag;
238                                         break;
239
240                                 case 'c':
241                                 case 'C':
242                                     ++cflag;
243                                     break;
244
245                                 case 'g':
246                                 case 'G':
247                                         ++gflag;
248                                         break;
249
250                                 case 'i':
251                                 case 'I':
252                                         search_path_append(p);
253                                         while (*p)
254                                                 ++p;
255                                         break;
256
257                                 case 'j':               /* JLH: debug info */
258                                 case 'J':
259                                         ++jflag;
260                                         ++oflag;        /* force object */
261                                         break;
262
263                                 case 'l':
264                                 case 'L':
265                                         ++lflag;
266                                         break;
267
268                                 case 'o':
269                                 case 'O':
270                                         ++oflag;
271                                         break;
272
273                                 case 's':
274                                 case 'S':
275                                         ++sflag;
276                                         break;
277
278                                 case 'p':
279                                 case 'P':
280                                         pflag = 0;
281                                         break;
282
283                                 case 'x':
284                                 case 'X':
285                                         xflag = 0;
286                                         break;
287
288                                 case 'q':
289                                 case 'Q':
290                                         xflag = 1;
291                                         break;
292
293                                 case 'd':
294                                 case 'D':
295                                         xflag = 2;
296                                         break;
297
298                                 case 'f':
299                                 case 'F':
300                                         ++fflag;
301                                         break;
302
303                                 default:
304                                         usage();
305                                 }
306                 } else {
307                         if (++inpfil == MAXFIL) {
308                                 fprintf(stderr, "too many input files\n");
309                                 asexit(1);
310                         }
311                         sfp[inpfil] = afile(p, "", 0);
312                         strcpy(srcfn[inpfil],afn);
313                         if (inpfil == 0) {
314                                 if (lflag)
315                                         lfp = afile(p, "lst", 1);
316                                 if (oflag) {
317                                   ofp = afile(p, "rel", 1);
318                                   // save the file name if we have to delete it on error
319                                   strcpy(relFile,afn);
320                                 }
321                                 if (sflag)
322                                         tfp = afile(p, "sym", 1);
323                         }
324                 }
325         }
326         if (inpfil < 0)
327                 usage();
328         syminit();
329         for (pass=0; pass<3; ++pass) {
330                 if (gflag && pass == 1)
331                         symglob();
332                 if (aflag && pass == 1)
333                         allglob();
334                 if (oflag && pass == 2)
335                         outgsd();
336                 flevel = 0;
337                 tlevel = 0;
338                 ifcnd[0] = 0;
339                 iflvl[0] = 0;
340                 radix = 10;
341                 srcline[0] = 0;
342                 page = 0;
343                 stb[0] = 0;
344                 lop  = NLPP;
345                 cfile = 0;
346                 incfil = -1;
347                 for (i = 0; i <= inpfil; i++)
348                         rewind(sfp[i]);
349                 ap = areap;
350                 while (ap) {
351                         ap->a_fuzz = 0;
352                         ap->a_size = 0;
353                         ap = ap->a_ap;
354                 }
355                 fuzz = 0;
356                 dot.s_addr = 0;
357                 dot.s_area = &dca;
358                 symp = &dot;
359                 minit();
360                 while (as_getline()) {
361                         cp = cb;
362                         cpt = cbt;
363                         ep = eb;
364                         ip = ib;
365
366                         /* JLH: if line begins with ";!", then
367                          * pass this comment on to the output file
368                          */
369                         if (oflag && (pass == 1) &&
370                             (ip[0] == ';') && (ip[1] == '!'))
371                         {
372                                 fprintf(ofp, "%s\n", ip );
373                         }
374
375                         if (setjmp(jump_env) == 0)
376                                 asmbl();
377
378                         if (pass == 2) {
379                                 diag();
380                                 list();
381                         }
382                 }
383                 newdot(dot.s_area); /* Flush area info */
384                 if (flevel || tlevel)
385                         err('i');
386         }
387         if (oflag)
388                 outchk(HUGE, HUGE);  /* Flush */
389         if (sflag) {
390                 lstsym(tfp);
391         } else
392         if (lflag) {
393                 lstsym(lfp);
394         }
395         //printf ("aserr: %d\n", aserr);
396         //printf ("fatalErrors: %d\n", fatalErrors);
397         asexit(fatalErrors);
398         return 0; // hush the compiler
399 }
400
401 /*)Function     VOID    asexit(i)
402  *
403  *                      int     i       exit code
404  *
405  *      The function asexit() explicitly closes all open
406  *      files and then terminates the program.
407  *
408  *      local variables:
409  *              int     j               loop counter
410  *
411  *      global variables:
412  *              FILE *  ifp[]           array of include-file file handles
413  *              FILE *  lfp             list output file handle
414  *              FILE *  ofp             relocation output file handle
415  *              FILE *  tfp             symbol table output file handle
416  *              FILE *  sfp[]           array of assembler-source file handles
417  *
418  *      functions called:
419  *              int     fclose()        c-library
420  *              VOID    exit()          c-library
421  *
422  *      side effects:
423  *              All files closed. Program terminates.
424  */
425
426 VOID
427 asexit(i)
428 int i;
429 {
430         int j;
431
432         if (lfp != NULL) fclose(lfp);
433         if (ofp != NULL) fclose(ofp);
434         if (tfp != NULL) fclose(tfp);
435
436         for (j=0; j<MAXFIL && sfp[j] != NULL; j++) {
437                 fclose(sfp[j]);
438         }
439
440         /*for (j=0; j<MAXINC && ifp[j] != NULL; j++) {
441                 fclose(ifp[j]);
442                 }*/
443         if (i) {
444           // remove output file
445           printf ("removing %s\n", relFile);
446           remove(relFile);
447         }
448         exit(i);
449 }
450
451 /*)Function     VOID    asmbl()
452  *
453  *      The function asmbl() scans the assembler-source text for
454  *      (1) labels, global labels, equates, global equates, and local
455  *      symbols, (2) .if, .else, .endif, and .page directives,
456  *      (3) machine independent assembler directives, and (4) machine
457  *      dependent mnemonics.
458  *
459  *      local variables:
460  *              mne *   mp              pointer to a mne structure
461  *              sym *   sp              pointer to a sym structure
462  *              tsym *  tp              pointer to a tsym structure
463  *              int     c               character from assembler-source
464  *                                      text line
465  *              area *  ap              pointer to an area structure
466  *              expr    e1              expression structure
467  *              char    id[]            id string
468  *              char    opt[]           options string
469  *              char    fn[]            filename string
470  *              char *  p               pointer into a string
471  *              int     d               temporary value
472  *              int     n               temporary value
473  *              int     uaf             user area options flag
474  *              int     uf              area options
475  *
476  *      global variables:
477  *              area *  areap           pointer to an area structure
478  *              char    ctype[]         array of character types, one per
479  *                                      ASCII character
480  *              int     flevel          IF-ELSE-ENDIF flag will be non
481  *                                      zero for false conditional case
482  *              Addr_T  fuzz            tracks pass to pass changes in the
483  *                                      address of symbols caused by
484  *                                      variable length instruction formats
485  *              int     ifcnd[]         array of IF statement condition
486  *                                      values (0 = FALSE) indexed by tlevel
487  *              int     iflvl[]         array of IF-ELSE-ENDIF flevel
488  *                                      values indexed by tlevel
489  *              FILE *  ifp[]           array of include-file file handles
490  *              char    incfn[][]       array of include file names
491  *              int     incline[]       current include file line
492  *              int     incfil          current file handle index
493  *                                      for include files
494  *              Addr_T  laddr           address of current assembler line
495  *                                      or value of .if argument
496  *              int     lmode           listing mode
497  *              int     lop             current line number on page
498  *              char    module[]        module name string
499  *              int     pass            assembler pass number
500  *              int     radix           current number conversion radix:
501  *                                      2 (binary), 8 (octal), 10 (decimal),
502  *                                      16 (hexadecimal)
503  *              char    stb[]           Subtitle string buffer
504  *              sym *   symp            pointer to a symbol structure
505  *              char    tb[]            Title string buffer
506  *              int     tlevel          current conditional level
507  *
508  *      functions called:
509  *              Addr_T  absexpr()       asexpr.c
510  *              area *  alookup()       assym.c
511  *              VOID    clrexpr()       asexpr.c
512  *              int     digit()         asexpr.c
513  *              char    endline()       aslex.c
514  *              VOID    err()           assubr.c
515  *              VOID    expr()          asexpr.c
516  *              FILE *  fopen()         c-library
517  *              char    get()           aslex.c
518  *              VOID    getid()         aslex.c
519  *              int     getmap()        aslex.c
520  *              char    getnb()         aslex.c
521  *              VOID    getst()         aslex.c
522  *              sym *   lookup()        assym.c
523  *              VOID    machine()       ___mch.c
524  *              mne *   mlookup()       assym.c
525  *              int     more()          aslex.c
526  *              VOID *  new()           assym.c
527  *              VOID    newdot()        asmain.c
528  *              VOID    outall()        asout.c
529  *              VOID    outab()         asout.c
530  *              VOID    outchk()        asout.c
531  *              VOID    outrb()         asout.c
532  *              VOID    outrw()         asout.c
533  *              VOID    phase()         asmain.c
534  *              VOID    qerr()          assubr.c
535  *              char *  strcpy()        c-library
536  *              char *  strncpy()       c-library
537  *              VOID    unget()         aslex.c
538  */
539
540 VOID
541 asmbl()
542 {
543         register struct mne *mp;
544         register struct sym *sp;
545         register struct tsym *tp;
546         register int c;
547         struct area  *ap;
548         struct expr e1;
549         char id[NCPS];
550         char opt[NCPS];
551         char fn[PATH_MAX];
552         char *p;
553         int d, n, uaf, uf;
554         static struct area *abs_ap; /* pointer to current absolute area structure */
555
556         laddr = dot.s_addr;
557         lmode = SLIST;
558 loop:
559         if ((c=endline()) == 0) { return; }
560         /*
561          * If the first character is a digit then assume
562          * a local symbol is being specified.  The symbol
563          * must end with $: to be valid.
564          *      pass 0:
565          *              Construct a tsym structure at the first
566          *              occurance of the symbol.  Flag the symbol
567          *              as multiply defined if not the first occurance.
568          *      pass 1:
569          *              Load area, address, and fuzz values
570          *              into structure tsym.
571          *      pass 2:
572          *              Check for assembler phase error and
573          *              multiply defined error.
574          */
575         if (ctype[c] & DIGIT) {
576                 if (flevel)
577                         return;
578                 n = 0;
579                 while ((d = digit(c, 10)) >= 0) {
580                         n = 10*n + d;
581                         c = get();
582                 }
583                 if (c != '$' || get() != ':')
584                         qerr();
585                 tp = symp->s_tsym;
586                 if (pass == 0) {
587                         while (tp) {
588                                 if (n == tp->t_num) {
589                                         tp->t_flg |= S_MDF;
590                                         break;
591                                 }
592                                 tp = tp->t_lnk;
593                         }
594                         if (tp == NULL) {
595                                 tp=(struct tsym *) new (sizeof(struct tsym));
596                                 tp->t_lnk = symp->s_tsym;
597                                 tp->t_num = n;
598                                 tp->t_flg = 0;
599                                 tp->t_area = dot.s_area;
600                                 tp->t_addr = dot.s_addr;
601                                 symp->s_tsym = tp;
602                         }
603                 } else {
604                         while (tp) {
605                                 if (n == tp->t_num) {
606                                         break;
607                                 }
608                                 tp = tp->t_lnk;
609                         }
610                         if (tp) {
611                                 if (pass == 1) {
612                                         fuzz = tp->t_addr - dot.s_addr;
613                                         tp->t_area = dot.s_area;
614                                         tp->t_addr = dot.s_addr;
615                                 } else {
616                                         phase(tp->t_area, tp->t_addr);
617                                         if (tp->t_flg & S_MDF)
618                                                 err('m');
619                                 }
620                         } else {
621                                 err('u');
622                         }
623                 }
624                 lmode = ALIST;
625                 goto loop;
626         }
627         /*
628          * If the first character is a letter then assume a label,
629          * symbol, assembler directive, or assembler mnemonic is
630          * being processed.
631          */
632         if ((ctype[c] & LETTER) == 0) {
633                 if (flevel) {
634                         return;
635                 } else {
636                         qerr();
637                 }
638         }
639         getid(id, c);
640         c = getnb();
641         /*
642          * If the next character is a : then a label is being processed.
643          * A double :: defines a global label.  If this is new label
644          * then create a symbol structure.
645          *      pass 0:
646          *              Flag multiply defined labels.
647          *      pass 1:
648          *              Load area, address, and fuzz values
649          *              into structure symp.
650          *      pass 2:
651          *              Check for assembler phase error and
652          *              multiply defined error.
653          */
654         if (c == ':') {
655                 if (flevel)
656                         return;
657                 if ((c = get()) != ':') {
658                         unget(c);
659                         c = 0;
660                 }
661                 symp = lookup(id);
662                 if (symp == &dot)
663                         err('.');
664                 if (pass == 0)
665                         if ((symp->s_type != S_NEW) &&
666                            ((symp->s_flag & S_ASG) == 0))
667                                 symp->s_flag |= S_MDF;
668                 if (pass != 2) {
669                         fuzz = symp->s_addr - dot.s_addr;
670                         symp->s_type = S_USER;
671                         symp->s_area = dot.s_area;
672                         symp->s_addr = dot.s_addr;
673                 } else {
674                         if (symp->s_flag & S_MDF)
675                                 err('m');
676                         phase(symp->s_area, symp->s_addr);
677                 }
678                 if (c) {
679                         symp->s_flag |= S_GBL;
680                 }
681                 lmode = ALIST;
682                 goto loop;
683         }
684         /*
685          * If the next character is a = then an equate is being processed.
686          * A double == defines a global equate.  If this is new variable
687          * then create a symbol structure.
688          */
689         if (c == '=') {
690                 if (flevel)
691                         return;
692                 if ((c = get()) != '=') {
693                         unget(c);
694                         c = 0;
695                 }
696                 clrexpr(&e1);
697                 expr(&e1, 0);
698                 sp = lookup(id);
699                 if (sp == &dot) {
700                         outall();
701                         if (e1.e_flag || e1.e_base.e_ap != dot.s_area)
702                                 err('.');
703                 } else
704                 if (sp->s_type != S_NEW && (sp->s_flag & S_ASG) == 0) {
705                         err('m');
706                 }
707                 sp->s_type = S_USER;
708                 sp->s_area = e1.e_base.e_ap;
709                 sp->s_addr = laddr = e1.e_addr;
710                 sp->s_flag |= S_ASG;
711                 if (c) {
712                         sp->s_flag |= S_GBL;
713                 }
714                 lmode = ELIST;
715                 goto loop;
716         }
717         unget(c);
718         lmode = flevel ? SLIST : CLIST;
719         if ((mp = mlookup(id)) == NULL) {
720                 if (!flevel)
721                         err('o');
722                 return;
723         }
724         /*
725          * If we have gotten this far then we have found an
726          * assembler directive or an assembler mnemonic.
727          *
728          * Check for .if, .else, .endif, and .page directives
729          * which are not controlled by the conditional flags
730          */
731         switch (mp->m_type) {
732
733         case S_IF:
734                 n = absexpr();
735                 if (tlevel < MAXIF) {
736                         ++tlevel;
737                         ifcnd[tlevel] = n;
738                         iflvl[tlevel] = flevel;
739                         if (n == 0) {
740                                 ++flevel;
741                         }
742                 } else {
743                         err('i');
744                 }
745                 lmode = ELIST;
746                 laddr = n;
747                 return;
748
749         case S_ELSE:
750                 if (ifcnd[tlevel]) {
751                         if (++flevel > (iflvl[tlevel]+1)) {
752                                 err('i');
753                         }
754                 } else {
755                         if (--flevel < iflvl[tlevel]) {
756                                 err('i');
757                         }
758                 }
759                 lmode = SLIST;
760                 return;
761
762         case S_ENDIF:
763                 if (tlevel) {
764                         flevel = iflvl[tlevel--];
765                 } else {
766                         err('i');
767                 }
768                 lmode = SLIST;
769                 return;
770
771         case S_PAGE:
772                 lop = NLPP;
773                 lmode = NLIST;
774                 return;
775
776         default:
777                 break;
778         }
779         if (flevel)
780                 return;
781         /*
782          * If we are not in a false state for .if/.else then
783          * process the assembler directives here.
784          */
785         switch (mp->m_type) {
786
787         case S_EVEN:
788                 outall();
789                 laddr = dot.s_addr = (dot.s_addr + 1) & ~1;
790                 lmode = ALIST;
791                 break;
792
793         case S_ODD:
794                 outall();
795                 laddr = dot.s_addr |= 1;
796                 lmode = ALIST;
797                 break;
798
799         case S_BYTE:
800         case S_WORD:
801                 do {
802                         clrexpr(&e1);
803                         expr(&e1, 0);
804                         if (mp->m_type == S_BYTE) {
805                                 outrb(&e1, R_NORM);
806                         } else {
807                                 outrw(&e1, R_NORM);
808                         }
809                 } while ((c = getnb()) == ',');
810                 unget(c);
811                 break;
812
813         case S_ASCII:
814         case S_ASCIZ:
815                 if ((d = getnb()) == '\0')
816                         qerr();
817                 while ((c = getmap(d)) >= 0)
818                         outab(c);
819                 if (mp->m_type == S_ASCIZ)
820                         outab(0);
821                 break;
822
823         case S_ASCIS:
824                 if ((d = getnb()) == '\0')
825                         qerr();
826                 c = getmap(d);
827                 while (c >= 0) {
828                         if ((n = getmap(d)) >= 0) {
829                                 outab(c);
830                         } else {
831                                 outab(c | 0x80);
832                         }
833                         c = n;
834                 }
835                 break;
836
837         case S_BLK:
838                 clrexpr(&e1);
839                 expr(&e1, 0);
840                 outchk(HUGE,HUGE);
841                 dot.s_addr += e1.e_addr*mp->m_valu;
842                 lmode = BLIST;
843                 break;
844
845         case S_TITLE:
846                 p = tb;
847                 if ((c = getnb()) != 0) {
848                         do {
849                                 if (p < &tb[NTITL-1])
850                                         *p++ = c;
851                         } while ((c = get()) != 0);
852                 }
853                 *p = 0;
854                 unget(c);
855                 lmode = SLIST;
856                 break;
857
858         case S_SBTL:
859                 p = stb;
860                 if ((c = getnb()) != 0) {
861                         do {
862                                 if (p < &stb[NSBTL-1])
863                                         *p++ = c;
864                         } while ((c = get()) != 0);
865                 }
866                 *p = 0;
867                 unget(c);
868                 lmode = SLIST;
869                 break;
870
871         case S_MODUL:
872                 getst(id, getnb()); // a module can start with a digit
873                 if (pass == 0) {
874                         if (module[0]) {
875                                 err('m');
876                         } else {
877                                 strncpy(module, id, NCPS);
878                         }
879                 }
880                 lmode = SLIST;
881                 break;
882
883         case S_OPTSDCC:
884                 p = optsdcc;
885                 if ((c = getnb()) != 0) {
886                         do {
887                                 if (p < &optsdcc[NINPUT-1])
888                                         *p++ = c;
889                         } while ((c = get()) != 0);
890                 }
891                 *p = 0;
892                 unget(c);
893                 lmode = SLIST;
894         /*if (pass == 0) printf("optsdcc=%s\n", optsdcc);*/
895         break;
896
897         case S_GLOBL:
898                 do {
899                         getid(id, -1);
900                         sp = lookup(id);
901                         sp->s_flag |= S_GBL;
902                 } while ((c = getnb()) == ',');
903                 unget(c);
904                 lmode = SLIST;
905                 break;
906
907         case S_DAREA:
908                 getid(id, -1);
909                 uaf = 0;
910                 uf  = A_CON|A_REL;
911                 if ((c = getnb()) == '(') {
912                         do {
913                                 getid(opt, -1);
914                                 mp = mlookup(opt);
915                                 if (mp && mp->m_type == S_ATYP) {
916                                         ++uaf;
917                                         uf |= mp->m_valu;
918                                 } else {
919                                         err('u');
920                                 }
921                         } while ((c = getnb()) == ',');
922                         if (c != ')')
923                                 qerr();
924                 } else {
925                         unget(c);
926                 }
927                 if ((ap = alookup(id)) != NULL) {
928                         if (uaf && uf != ap->a_flag)
929                                 err('m');
930                 } else {
931                         ap = (struct area *) new (sizeof(struct area));
932                         ap->a_ap = areap;
933                         strncpy(ap->a_id, id, NCPS);
934                         ap->a_ref = areap->a_ref + 1;
935                         ap->a_size = 0;
936                         ap->a_fuzz = 0;
937                         ap->a_flag = uaf ? uf : (A_CON|A_REL);
938                         areap = ap;
939                 }
940                 newdot(ap);
941                 lmode = SLIST;
942                 if (dot.s_area->a_flag & A_ABS)
943                         abs_ap = ap;
944                 break;
945
946         case S_ORG:
947                 if (dot.s_area->a_flag & A_ABS) {
948                         char buf[NCPS];
949                         laddr = absexpr();
950                         sprintf(buf, "%s%x", abs_ap->a_id, laddr);
951                         if ((ap = alookup(buf)) == NULL) {
952                                 ap = (struct area *) new (sizeof(struct area));
953                                 *ap = *areap;
954                                 ap->a_ap = areap;
955                                 strncpy(ap->a_id, buf, NCPS);
956                                 ap->a_ref = areap->a_ref + 1;
957                                 ap->a_size = 0;
958                                 ap->a_fuzz = 0;
959                                 areap = ap;
960                         }
961                         newdot(ap);
962                         lmode = ALIST;
963                         dot.s_addr = dot.s_org = laddr;
964                 } else {
965                         err('o');
966                 }
967                 break;
968
969         case S_RADIX:
970                 if (more()) {
971                         switch (getnb()) {
972                         case 'b':
973                         case 'B':
974                                 radix = 2;
975                                 break;
976                         case '@':
977                         case 'o':
978                         case 'O':
979                         case 'q':
980                         case 'Q':
981                                 radix = 8;
982                                 break;
983                         case 'd':
984                         case 'D':
985                                 radix = 10;
986                                 break;
987                         case 'h':
988                         case 'H':
989                         case 'x':
990                         case 'X':
991                                 radix = 16;
992                                 break;
993                         default:
994                                 radix = 10;
995                                 qerr();
996                                 break;
997                         }
998                 } else {
999                         radix = 10;
1000                 }
1001                 lmode = SLIST;
1002                 break;
1003
1004         case S_INCL:
1005                 d = getnb();
1006                 p = fn;
1007                 while ((c = get()) != d) {
1008                         if (p < &fn[PATH_MAX-1]) {
1009                                 *p++ = c;
1010                         } else {
1011                                 break;
1012                         }
1013                 }
1014                 *p = 0;
1015                 if ((++incfil == MAXINC) ||
1016                     (ifp[incfil] = search_path_fopen(fn, "r")) == NULL) {
1017                         --incfil;
1018                         err('i');
1019                 } else {
1020                         lop = NLPP;
1021                         incline[incfil] = 0;
1022                         strcpy(incfn[incfil],fn);
1023                 }
1024                 lmode = SLIST;
1025                 break;
1026
1027         case S_FLAT24:
1028                 if (more())
1029                 {
1030                     getst(id, -1);
1031
1032                     if (!as_strcmpi(id, "on"))
1033                     {
1034                         /* Quick sanity check: size of
1035                          * Addr_T must be at least 24 bits.
1036                          */
1037                         if (sizeof(Addr_T) < 3)
1038                         {
1039                             warnBanner();
1040                             fprintf(stderr,
1041                                     "Cannot enable Flat24 mode: "
1042                                     "host system must have 24 bit "
1043                                     "or greater integers.\n");
1044                         }
1045                         else
1046                         {
1047                             flat24Mode = 1;
1048                         }
1049                     }
1050                     else if (!as_strcmpi(id, "off"))
1051                     {
1052                         flat24Mode = 0;
1053                     }
1054                     else
1055                     {
1056                         qerr();
1057                     }
1058                 }
1059                 else
1060                 {
1061                     qerr();
1062                 }
1063                 lmode = SLIST;
1064                 #if 0
1065                 printf("as8051: ds390 flat mode %sabled.\n",
1066                         flat24Mode ? "en" : "dis");
1067                 #endif
1068                 break;
1069
1070
1071         /*
1072          * If not an assembler directive then go to
1073          * the machine dependent function which handles
1074          * all the assembler mnemonics.
1075          */
1076         default:
1077                 machine(mp);
1078                 /* if cdb information then generate the line info */
1079                 if (cflag && (pass == 1))
1080                     DefineCDB_Line();
1081
1082                 /* JLH: if -j, generate a line number symbol */
1083                 if (jflag && (pass == 1))
1084                 {
1085                    DefineNoICE_Line();
1086                 }
1087
1088         }
1089         goto loop;
1090 }
1091
1092 /*)Function     FILE *  afile(fn, ft, wf)
1093  *
1094  *              char *  fn              file specification string
1095  *              char *  ft              file type string
1096  *              int     wf              read(0)/write(1) flag
1097  *
1098  *      The function afile() opens a file for reading or writing.
1099  *              (1)     If the file type specification string ft
1100  *                      is not NULL then a file specification is
1101  *                      constructed with the file path\name in fn
1102  *                      and the extension in ft.
1103  *              (2)     If the file type specification string ft
1104  *                      is NULL then the file specification is
1105  *                      constructed from fn.  If fn does not have
1106  *                      a file type then the default source file
1107  *                      type dsft is appended to the file specification.
1108  *
1109  *      afile() returns a file handle for the opened file or aborts
1110  *      the assembler on an open error.
1111  *
1112  *      local variables:
1113  *              int     c               character value
1114  *              FILE *  fp              filehandle for opened file
1115  *              char *  p1              pointer to filespec string fn
1116  *              char *  p2              pointer to filespec string fb
1117  *              char *  p3              pointer to filetype string ft
1118  *
1119  *      global variables:
1120  *              char    afn[]           afile() constructed filespec
1121  *              char    dsft[]          default assembler file type string
1122  *              char    afn[]           constructed file specification string
1123  *
1124  *      functions called:
1125  *              VOID    asexit()        asmain.c
1126  *              FILE *  fopen()         c_library
1127  *              int     fprintf()       c_library
1128  *
1129  *      side effects:
1130  *              File is opened for read or write.
1131  */
1132
1133 FILE *
1134 afile(fn, ft, wf)
1135 char *fn;
1136 char *ft;
1137 int wf;
1138 {
1139         register char *p2, *p3;
1140         register int c;
1141         FILE *fp;
1142
1143         p2 = afn;
1144         p3 = ft;
1145
1146         strcpy (afn, fn);
1147         p2 = strrchr (afn, FSEPX);              // search last '.'
1148         if (!p2)
1149                 p2 = afn + strlen (afn);
1150         if (p2 > &afn[PATH_MAX-4])              // truncate filename, if it's too long
1151                 p2 = &afn[PATH_MAX-4];
1152         *p2++ = FSEPX;
1153
1154         // choose a file-extension
1155         if (*p3 == 0) {                                 // extension supplied?
1156                 p3 = strrchr (fn, FSEPX);       // no: extension in fn?
1157                 if (p3)
1158                         ++p3;
1159                 else
1160                         p3 = dsft;                                      // no: default extension
1161         }
1162
1163         while ((c = *p3++) != 0) {              // strncpy
1164                 if (p2 < &afn[PATH_MAX-1])
1165                         *p2++ = c;
1166         }
1167         *p2++ = 0;
1168
1169         if ((fp = fopen(afn, wf?"w":"r")) == NULL) {
1170                 fprintf(stderr, "%s: cannot %s.\n", afn, wf?"create":"open");
1171                 asexit(1);
1172         }
1173         return (fp);
1174 }
1175
1176 /*)Function     VOID    newdot(nap)
1177  *
1178  *              area *  nap             pointer to the new area structure
1179  *
1180  *      The function newdot():
1181  *              (1)     copies the current values of fuzz and the last
1182  *                      address into the current area referenced by dot
1183  *              (2)     loads dot with the pointer to the new area and
1184  *                      loads the fuzz and last address parameters
1185  *              (3)     outall() is called to flush any remaining
1186  *                      bufferred code from the old area to the output
1187  *
1188  *      local variables:
1189  *              area *  oap             pointer to old area
1190  *
1191  *      global variables:
1192  *              sym     dot             defined as sym[0]
1193  *              Addr_T  fuzz            tracks pass to pass changes in the
1194  *                                      address of symbols caused by
1195  *                                      variable length instruction formats
1196  *
1197  *      functions called:
1198  *              none
1199  *
1200  *      side effects:
1201  *              Current area saved, new area loaded, buffers flushed.
1202  */
1203
1204 VOID
1205 newdot(nap)
1206 register struct area *nap;
1207 {
1208         register struct area *oap;
1209
1210         oap = dot.s_area;
1211         /* fprintf (stderr, "%s dot.s_area->a_size: %d dot.s_addr: %d\n",
1212              oap->a_id, dot.s_area->a_size, dot.s_addr); */
1213         oap->a_fuzz = fuzz;
1214         if (oap->a_flag & A_OVR) {
1215           // the size of an overlay is the biggest size encountered
1216           if (oap->a_size < dot.s_addr) {
1217             oap->a_size = dot.s_addr;
1218           }
1219         } else if (oap->a_flag & A_ABS) {
1220           oap->a_addr = dot.s_org;
1221           oap->a_size += dot.s_addr - dot.s_org;
1222           dot.s_addr = dot.s_org = 0;
1223         } else {
1224           oap->a_addr = 0;
1225           oap->a_size = dot.s_addr;
1226         }
1227         if (nap->a_flag & A_OVR) {
1228           // a new overlay starts at 0, no fuzz
1229           dot.s_addr = 0;
1230           fuzz = 0;
1231         } else if (nap->a_flag & A_ABS) {
1232           // a new absolute starts at org, no fuzz
1233           dot.s_addr = dot.s_org;
1234           fuzz = 0;
1235         } else {
1236           dot.s_addr = nap->a_size;
1237           fuzz = nap->a_fuzz;
1238         }
1239         dot.s_area = nap;
1240         outall();
1241 }
1242
1243 /*)Function     VOID    phase(ap, a)
1244  *
1245  *              area *  ap              pointer to area
1246  *              Addr_T  a               address in area
1247  *
1248  *      Function phase() compares the area ap and address a
1249  *      with the current area dot.s_area and address dot.s_addr
1250  *      to determine if the position of the symbol has changed
1251  *      between assembler passes.
1252  *
1253  *      local variables:
1254  *              none
1255  *
1256  *      global varaibles:
1257  *              sym *   dot             defined as sym[0]
1258  *
1259  *      functions called:
1260  *              none
1261  *
1262  *      side effects:
1263  *              The p error is invoked if the area and/or address
1264  *              has changed.
1265  */
1266
1267 VOID
1268 phase(ap, a)
1269 struct area *ap;
1270 Addr_T a;
1271 {
1272         if (ap != dot.s_area || a != dot.s_addr)
1273                 err('p');
1274 }
1275
1276 char *usetxt[] = {
1277         "Usage: [-dqxjgalopsf][ -I<dir> ] file1 [file2 file3 ...]",
1278         "  d    decimal listing",
1279         "  q    octal   listing",
1280         "  x    hex     listing (default)",
1281         "  j    add line number and debug information to file", /* JLH */
1282         "  g    undefined symbols made global",
1283         "  a    all user symbols made global",
1284         "  l    create list   output file1[LST]",
1285         "  o    create object output file1[REL]",
1286         "  s    create symbol output file1[SYM]",
1287         "  p    disable listing pagination",
1288         "  f    flag relocatable references by `    in listing file",
1289         " ff    flag relocatable references by mode in listing file",
1290         "-I<dir>  Add the named directory to the include file",
1291         "       search path.  This option may be used more than once.",
1292         "       Directories are searched in the order given.",
1293         "",
1294         0
1295 };
1296
1297 /*)Function     VOID    usage()
1298  *
1299  *      The function usage() outputs to the stderr device the
1300  *      assembler name and version and a list of valid assembler options.
1301  *
1302  *      local variables:
1303  *              char ** dp              pointer to an array of
1304  *                                      text string pointers.
1305  *
1306  *      global variables:
1307  *              char    cpu[]           assembler type string
1308  *              char *  usetxt[]        array of string pointers
1309  *
1310  *      functions called:
1311  *              VOID    asexit()        asmain.c
1312  *              int     fprintf()       c_library
1313  *
1314  *      side effects:
1315  *              program is terminated
1316  */
1317
1318 VOID
1319 usage()
1320 {
1321         register char   **dp;
1322
1323         fprintf(stderr, "\nASxxxx Assembler %s  (%s)\n\n", VERSION, cpu);
1324         for (dp = usetxt; *dp; dp++)
1325                 fprintf(stderr, "%s\n", *dp);
1326         asexit(1);
1327 }