34598db87de6b89d756467d00f330ddf75235299
[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(int argc, char *argv[])
217 {
218         register char *p;
219         register int c, i;
220         struct area *ap;
221
222         /*fprintf(stdout, "\n");*/
223         inpfil = -1;
224         pflag = 1;
225         for (i=1; i<argc; ++i) {
226                 p = argv[i];
227                 if (*p == '-') {
228                         if (inpfil >= 0)
229                                 usage();
230                         ++p;
231                         while ((c = *p++) != 0)
232                                 switch(c) {
233
234                                 case 'a':
235                                 case 'A':
236                                         ++aflag;
237                                         break;
238
239                                 case 'c':
240                                 case 'C':
241                                         ++cflag;
242                                         break;
243
244                                 case 'g':
245                                 case 'G':
246                                         ++gflag;
247                                         break;
248
249                                 case 'i':
250                                 case 'I':
251                                         search_path_append(p);
252                                         while (*p)
253                                                 ++p;
254                                         break;
255
256                                 case 'j':               /* JLH: debug info */
257                                 case 'J':
258                                         ++jflag;
259                                         ++oflag;        /* force object */
260                                         break;
261
262                                 case 'l':
263                                 case 'L':
264                                         ++lflag;
265                                         break;
266
267                                 case 'o':
268                                 case 'O':
269                                         ++oflag;
270                                         break;
271
272                                 case 's':
273                                 case 'S':
274                                         ++sflag;
275                                         break;
276
277                                 case 'p':
278                                 case 'P':
279                                         pflag = 0;
280                                         break;
281
282                                 case 'x':
283                                 case 'X':
284                                         xflag = 0;
285                                         break;
286
287                                 case 'q':
288                                 case 'Q':
289                                         xflag = 1;
290                                         break;
291
292                                 case 'd':
293                                 case 'D':
294                                         xflag = 2;
295                                         break;
296
297                                 case 'f':
298                                 case 'F':
299                                         ++fflag;
300                                         break;
301
302                                 default:
303                                         usage();
304                                 }
305                 } else {
306                         if (++inpfil == MAXFIL) {
307                                 fprintf(stderr, "too many input files\n");
308                                 asexit(1);
309                         }
310                         sfp[inpfil] = afile(p, "", 0);
311                         strcpy(srcfn[inpfil],afn);
312                         if (inpfil == 0) {
313                                 if (lflag)
314                                         lfp = afile(p, "lst", 1);
315                                 if (oflag) {
316                                         ofp = afile(p, "rel", 1);
317                                         // save the file name if we have to delete it on error
318                                         strcpy(relFile,afn);
319                                 }
320                                 if (sflag)
321                                         tfp = afile(p, "sym", 1);
322                         }
323                 }
324         }
325         if (inpfil < 0)
326                 usage();
327         syminit();
328         for (pass=0; pass<3; ++pass) {
329                 if (gflag && pass == 1)
330                         symglob();
331                 if (aflag && pass == 1)
332                         allglob();
333                 if (oflag && pass == 2)
334                         outgsd();
335                 flevel = 0;
336                 tlevel = 0;
337                 ifcnd[0] = 0;
338                 iflvl[0] = 0;
339                 radix = 10;
340                 srcline[0] = 0;
341                 page = 0;
342                 org_cnt = 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(int i)
428 {
429         int j;
430
431         if (lfp != NULL) fclose(lfp);
432         if (ofp != NULL) fclose(ofp);
433         if (tfp != NULL) fclose(tfp);
434
435         for (j=0; j<MAXFIL && sfp[j] != NULL; j++) {
436                 fclose(sfp[j]);
437         }
438
439         /*for (j=0; j<MAXINC && ifp[j] != NULL; j++) {
440                 fclose(ifp[j]);
441                 }*/
442         if (i) {
443           // remove output file
444           printf ("removing %s\n", relFile);
445           remove(relFile);
446         }
447         exit(i);
448 }
449
450 /*)Function     VOID    asmbl()
451  *
452  *      The function asmbl() scans the assembler-source text for
453  *      (1) labels, global labels, equates, global equates, and local
454  *      symbols, (2) .if, .else, .endif, and .page directives,
455  *      (3) machine independent assembler directives, and (4) machine
456  *      dependent mnemonics.
457  *
458  *      local variables:
459  *              mne *   mp              pointer to a mne structure
460  *              sym *   sp              pointer to a sym structure
461  *              tsym *  tp              pointer to a tsym structure
462  *              int     c               character from assembler-source
463  *                                      text line
464  *              area *  ap              pointer to an area structure
465  *              expr    e1              expression structure
466  *              char    id[]            id string
467  *              char    opt[]           options string
468  *              char    fn[]            filename string
469  *              char *  p               pointer into a string
470  *              int     d               temporary value
471  *              int     n               temporary value
472  *              int     uaf             user area options flag
473  *              int     uf              area options
474  *
475  *      global variables:
476  *              area *  areap           pointer to an area structure
477  *              char    ctype[]         array of character types, one per
478  *                                      ASCII character
479  *              int     flevel          IF-ELSE-ENDIF flag will be non
480  *                                      zero for false conditional case
481  *              Addr_T  fuzz            tracks pass to pass changes in the
482  *                                      address of symbols caused by
483  *                                      variable length instruction formats
484  *              int     ifcnd[]         array of IF statement condition
485  *                                      values (0 = FALSE) indexed by tlevel
486  *              int     iflvl[]         array of IF-ELSE-ENDIF flevel
487  *                                      values indexed by tlevel
488  *              FILE *  ifp[]           array of include-file file handles
489  *              char    incfn[][]       array of include file names
490  *              int     incline[]       current include file line
491  *              int     incfil          current file handle index
492  *                                      for include files
493  *              Addr_T  laddr           address of current assembler line
494  *                                      or value of .if argument
495  *              int     lmode           listing mode
496  *              int     lop             current line number on page
497  *              char    module[]        module name string
498  *              int     pass            assembler pass number
499  *              int     radix           current number conversion radix:
500  *                                      2 (binary), 8 (octal), 10 (decimal),
501  *                                      16 (hexadecimal)
502  *              char    stb[]           Subtitle string buffer
503  *              sym *   symp            pointer to a symbol structure
504  *              char    tb[]            Title string buffer
505  *              int     tlevel          current conditional level
506  *
507  *      functions called:
508  *              Addr_T  absexpr()       asexpr.c
509  *              area *  alookup()       assym.c
510  *              VOID    clrexpr()       asexpr.c
511  *              int     digit()         asexpr.c
512  *              char    endline()       aslex.c
513  *              VOID    err()           assubr.c
514  *              VOID    expr()          asexpr.c
515  *              FILE *  fopen()         c-library
516  *              char    get()           aslex.c
517  *              VOID    getid()         aslex.c
518  *              int     getmap()        aslex.c
519  *              char    getnb()         aslex.c
520  *              VOID    getst()         aslex.c
521  *              sym *   lookup()        assym.c
522  *              VOID    machine()       ___mch.c
523  *              mne *   mlookup()       assym.c
524  *              int     more()          aslex.c
525  *              VOID *  new()           assym.c
526  *              VOID    newdot()        asmain.c
527  *              VOID    outall()        asout.c
528  *              VOID    outab()         asout.c
529  *              VOID    outchk()        asout.c
530  *              VOID    outrb()         asout.c
531  *              VOID    outrw()         asout.c
532  *              VOID    phase()         asmain.c
533  *              VOID    qerr()          assubr.c
534  *              char *  strcpy()        c-library
535  *              char *  strncpy()       c-library
536  *              VOID    unget()         aslex.c
537  */
538
539 VOID
540 asmbl(void)
541 {
542         register struct mne *mp;
543         register struct sym *sp;
544         register struct tsym *tp;
545         register int c;
546         struct area  *ap;
547         struct expr e1;
548         char id[NCPS];
549         char opt[NCPS];
550         char fn[PATH_MAX];
551         char *p;
552         int d, n, uaf, uf;
553         static struct area *abs_ap; /* pointer to current absolute area structure */
554
555         laddr = dot.s_addr;
556         lmode = SLIST;
557 loop:
558         if ((c=endline()) == 0) { return; }
559         /*
560          * If the first character is a digit then assume
561          * a local symbol is being specified.  The symbol
562          * must end with $: to be valid.
563          *      pass 0:
564          *              Construct a tsym structure at the first
565          *              occurance of the symbol.  Flag the symbol
566          *              as multiply defined if not the first occurance.
567          *      pass 1:
568          *              Load area, address, and fuzz values
569          *              into structure tsym.
570          *      pass 2:
571          *              Check for assembler phase error and
572          *              multiply defined error.
573          */
574         if (ctype[c] & DIGIT) {
575                 if (flevel)
576                         return;
577                 n = 0;
578                 while ((d = digit(c, 10)) >= 0) {
579                         n = 10*n + d;
580                         c = get();
581                 }
582                 if (c != '$' || get() != ':')
583                         qerr();
584                 tp = symp->s_tsym;
585                 if (pass == 0) {
586                         while (tp) {
587                                 if (n == tp->t_num) {
588                                         tp->t_flg |= S_MDF;
589                                         break;
590                                 }
591                                 tp = tp->t_lnk;
592                         }
593                         if (tp == NULL) {
594                                 tp=(struct tsym *) new (sizeof(struct tsym));
595                                 tp->t_lnk = symp->s_tsym;
596                                 tp->t_num = n;
597                                 tp->t_flg = 0;
598                                 tp->t_area = dot.s_area;
599                                 tp->t_addr = dot.s_addr;
600                                 symp->s_tsym = tp;
601                         }
602                 } else {
603                         while (tp) {
604                                 if (n == tp->t_num) {
605                                         break;
606                                 }
607                                 tp = tp->t_lnk;
608                         }
609                         if (tp) {
610                                 if (pass == 1) {
611                                         fuzz = tp->t_addr - dot.s_addr;
612                                         tp->t_area = dot.s_area;
613                                         tp->t_addr = dot.s_addr;
614                                 } else {
615                                         phase(tp->t_area, tp->t_addr);
616                                         if (tp->t_flg & S_MDF)
617                                                 err('m');
618                                 }
619                         } else {
620                                 err('u');
621                         }
622                 }
623                 lmode = ALIST;
624                 goto loop;
625         }
626         /*
627          * If the first character is a letter then assume a label,
628          * symbol, assembler directive, or assembler mnemonic is
629          * being processed.
630          */
631         if ((ctype[c] & LETTER) == 0) {
632                 if (flevel) {
633                         return;
634                 } else {
635                         qerr();
636                 }
637         }
638         getid(id, c);
639         c = getnb();
640         /*
641          * If the next character is a : then a label is being processed.
642          * A double :: defines a global label.  If this is new label
643          * then create a symbol structure.
644          *      pass 0:
645          *              Flag multiply defined labels.
646          *      pass 1:
647          *              Load area, address, and fuzz values
648          *              into structure symp.
649          *      pass 2:
650          *              Check for assembler phase error and
651          *              multiply defined error.
652          */
653         if (c == ':') {
654                 if (flevel)
655                         return;
656                 if ((c = get()) != ':') {
657                         unget(c);
658                         c = 0;
659                 }
660                 symp = lookup(id);
661                 if (symp == &dot)
662                         err('.');
663                 if (pass == 0)
664                         if ((symp->s_type != S_NEW) &&
665                            ((symp->s_flag & S_ASG) == 0))
666                                 symp->s_flag |= S_MDF;
667                 if (pass != 2) {
668                         fuzz = symp->s_addr - dot.s_addr;
669                         symp->s_type = S_USER;
670                         symp->s_area = dot.s_area;
671                         symp->s_addr = dot.s_addr;
672                 } else {
673                         if (symp->s_flag & S_MDF)
674                                 err('m');
675                         phase(symp->s_area, symp->s_addr);
676                 }
677                 if (c) {
678                         symp->s_flag |= S_GBL;
679                 }
680                 lmode = ALIST;
681                 goto loop;
682         }
683         /*
684          * If the next character is a = then an equate is being processed.
685          * A double == defines a global equate.  If this is new variable
686          * then create a symbol structure.
687          */
688         if (c == '=') {
689                 if (flevel)
690                         return;
691                 if ((c = get()) != '=') {
692                         unget(c);
693                         c = 0;
694                 }
695                 clrexpr(&e1);
696                 expr(&e1, 0);
697                 sp = lookup(id);
698                 if (sp == &dot) {
699                         outall();
700                         if (e1.e_flag || e1.e_base.e_ap != dot.s_area)
701                                 err('.');
702                 } else
703                 if (sp->s_type != S_NEW && (sp->s_flag & S_ASG) == 0) {
704                         err('m');
705                 }
706                 sp->s_type = S_USER;
707                 sp->s_area = e1.e_base.e_ap;
708                 sp->s_addr = laddr = e1.e_addr;
709                 sp->s_flag |= S_ASG;
710                 if (c) {
711                         sp->s_flag |= S_GBL;
712                 }
713                 lmode = ELIST;
714                 goto loop;
715         }
716         unget(c);
717         lmode = flevel ? SLIST : CLIST;
718         if ((mp = mlookup(id)) == NULL) {
719                 if (!flevel)
720                         err('o');
721                 return;
722         }
723         /*
724          * If we have gotten this far then we have found an
725          * assembler directive or an assembler mnemonic.
726          *
727          * Check for .if, .else, .endif, and .page directives
728          * which are not controlled by the conditional flags
729          */
730         switch (mp->m_type) {
731
732         case S_IF:
733                 n = absexpr();
734                 if (tlevel < MAXIF) {
735                         ++tlevel;
736                         ifcnd[tlevel] = n;
737                         iflvl[tlevel] = flevel;
738                         if (n == 0) {
739                                 ++flevel;
740                         }
741                 } else {
742                         err('i');
743                 }
744                 lmode = ELIST;
745                 laddr = n;
746                 return;
747
748         case S_ELSE:
749                 if (ifcnd[tlevel]) {
750                         if (++flevel > (iflvl[tlevel]+1)) {
751                                 err('i');
752                         }
753                 } else {
754                         if (--flevel < iflvl[tlevel]) {
755                                 err('i');
756                         }
757                 }
758                 lmode = SLIST;
759                 return;
760
761         case S_ENDIF:
762                 if (tlevel) {
763                         flevel = iflvl[tlevel--];
764                 } else {
765                         err('i');
766                 }
767                 lmode = SLIST;
768                 return;
769
770         case S_PAGE:
771                 lop = NLPP;
772                 lmode = NLIST;
773                 return;
774
775         default:
776                 break;
777         }
778         if (flevel)
779                 return;
780         /*
781          * If we are not in a false state for .if/.else then
782          * process the assembler directives here.
783          */
784         switch (mp->m_type) {
785
786         case S_EVEN:
787                 outall();
788                 laddr = dot.s_addr = (dot.s_addr + 1) & ~1;
789                 lmode = ALIST;
790                 break;
791
792         case S_ODD:
793                 outall();
794                 laddr = dot.s_addr |= 1;
795                 lmode = ALIST;
796                 break;
797
798         case S_BYTE:
799         case S_WORD:
800                 do {
801                         clrexpr(&e1);
802                         expr(&e1, 0);
803                         if (mp->m_type == S_BYTE) {
804                                 outrb(&e1, R_NORM);
805                         } else {
806                                 outrw(&e1, R_NORM);
807                         }
808                 } while ((c = getnb()) == ',');
809                 unget(c);
810                 break;
811
812         case S_ASCII:
813         case S_ASCIZ:
814                 if ((d = getnb()) == '\0')
815                         qerr();
816                 while ((c = getmap(d)) >= 0)
817                         outab(c);
818                 if (mp->m_type == S_ASCIZ)
819                         outab(0);
820                 break;
821
822         case S_ASCIS:
823                 if ((d = getnb()) == '\0')
824                         qerr();
825                 c = getmap(d);
826                 while (c >= 0) {
827                         if ((n = getmap(d)) >= 0) {
828                                 outab(c);
829                         } else {
830                                 outab(c | 0x80);
831                         }
832                         c = n;
833                 }
834                 break;
835
836         case S_BLK:
837                 clrexpr(&e1);
838                 expr(&e1, 0);
839                 outchk(HUGE,HUGE);
840                 dot.s_addr += e1.e_addr*mp->m_valu;
841                 lmode = BLIST;
842                 break;
843
844         case S_TITLE:
845                 p = tb;
846                 if ((c = getnb()) != 0) {
847                         do {
848                                 if (p < &tb[NTITL-1])
849                                         *p++ = c;
850                         } while ((c = get()) != 0);
851                 }
852                 *p = 0;
853                 unget(c);
854                 lmode = SLIST;
855                 break;
856
857         case S_SBTL:
858                 p = stb;
859                 if ((c = getnb()) != 0) {
860                         do {
861                                 if (p < &stb[NSBTL-1])
862                                         *p++ = c;
863                         } while ((c = get()) != 0);
864                 }
865                 *p = 0;
866                 unget(c);
867                 lmode = SLIST;
868                 break;
869
870         case S_MODUL:
871                 getst(id, getnb()); // a module can start with a digit
872                 if (pass == 0) {
873                         if (module[0]) {
874                                 err('m');
875                         } else {
876                                 strncpy(module, id, NCPS);
877                         }
878                 }
879                 lmode = SLIST;
880                 break;
881
882         case S_OPTSDCC:
883                 p = optsdcc;
884                 if ((c = getnb()) != 0) {
885                         do {
886                                 if (p < &optsdcc[NINPUT-1])
887                                         *p++ = c;
888                         } while ((c = get()) != 0);
889                 }
890                 *p = 0;
891                 unget(c);
892                 lmode = SLIST;
893         /*if (pass == 0) printf("optsdcc=%s\n", optsdcc);*/
894         break;
895
896         case S_GLOBL:
897                 do {
898                         getid(id, -1);
899                         sp = lookup(id);
900                         sp->s_flag |= S_GBL;
901                 } while ((c = getnb()) == ',');
902                 unget(c);
903                 lmode = SLIST;
904                 break;
905
906         case S_DAREA:
907                 getid(id, -1);
908                 uaf = 0;
909                 uf  = A_CON|A_REL;
910                 if ((c = getnb()) == '(') {
911                         do {
912                                 getid(opt, -1);
913                                 mp = mlookup(opt);
914                                 if (mp && mp->m_type == S_ATYP) {
915                                         ++uaf;
916                                         uf |= mp->m_valu;
917                                 } else {
918                                         err('u');
919                                 }
920                         } while ((c = getnb()) == ',');
921                         if (c != ')')
922                                 qerr();
923                 } else {
924                         unget(c);
925                 }
926                 if ((ap = alookup(id)) != NULL) {
927                         if (uaf && uf != ap->a_flag)
928                                 err('m');
929                 } else {
930                         ap = (struct area *) new (sizeof(struct area));
931                         ap->a_ap = areap;
932                         strncpy(ap->a_id, id, NCPS);
933                         ap->a_ref = areap->a_ref + 1;
934                         ap->a_addr = 0;
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
950                         laddr = absexpr();
951                         sprintf(buf, "%s%x", abs_ap->a_id, org_cnt++);
952                         if ((ap = alookup(buf)) == NULL) {
953                                 ap = (struct area *) new (sizeof(struct area));
954                                 *ap = *areap;
955                                 ap->a_ap = areap;
956                                 strncpy(ap->a_id, buf, NCPS);
957                                 ap->a_ref = areap->a_ref + 1;
958                                 ap->a_size = 0;
959                                 ap->a_fuzz = 0;
960                                 areap = ap;
961                         }
962                         newdot(ap);
963                         lmode = ALIST;
964                         dot.s_addr = dot.s_org = laddr;
965                 } else {
966                         err('o');
967                 }
968                 break;
969
970         case S_RADIX:
971                 if (more()) {
972                         switch (getnb()) {
973                         case 'b':
974                         case 'B':
975                                 radix = 2;
976                                 break;
977                         case '@':
978                         case 'o':
979                         case 'O':
980                         case 'q':
981                         case 'Q':
982                                 radix = 8;
983                                 break;
984                         case 'd':
985                         case 'D':
986                                 radix = 10;
987                                 break;
988                         case 'h':
989                         case 'H':
990                         case 'x':
991                         case 'X':
992                                 radix = 16;
993                                 break;
994                         default:
995                                 radix = 10;
996                                 qerr();
997                                 break;
998                         }
999                 } else {
1000                         radix = 10;
1001                 }
1002                 lmode = SLIST;
1003                 break;
1004
1005         case S_INCL:
1006                 d = getnb();
1007                 p = fn;
1008                 while ((c = get()) != d) {
1009                         if (p < &fn[PATH_MAX-1]) {
1010                                 *p++ = c;
1011                         } else {
1012                                 break;
1013                         }
1014                 }
1015                 *p = 0;
1016                 if ((++incfil == MAXINC) ||
1017                     (ifp[incfil] = search_path_fopen(fn, "r")) == NULL) {
1018                         --incfil;
1019                         err('i');
1020                 } else {
1021                         lop = NLPP;
1022                         incline[incfil] = 0;
1023                         strcpy(incfn[incfil],fn);
1024                 }
1025                 lmode = SLIST;
1026                 break;
1027
1028         case S_FLAT24:
1029                 if (more())
1030                 {
1031                     getst(id, -1);
1032
1033                     if (!as_strcmpi(id, "on"))
1034                     {
1035                         /* Quick sanity check: size of
1036                          * Addr_T must be at least 24 bits.
1037                          */
1038                         if (sizeof(Addr_T) < 3)
1039                         {
1040                             warnBanner();
1041                             fprintf(stderr,
1042                                     "Cannot enable Flat24 mode: "
1043                                     "host system must have 24 bit "
1044                                     "or greater integers.\n");
1045                         }
1046                         else
1047                         {
1048                             flat24Mode = 1;
1049                         }
1050                     }
1051                     else if (!as_strcmpi(id, "off"))
1052                     {
1053                         flat24Mode = 0;
1054                     }
1055                     else
1056                     {
1057                         qerr();
1058                     }
1059                 }
1060                 else
1061                 {
1062                     qerr();
1063                 }
1064                 lmode = SLIST;
1065                 #if 0
1066                 printf("as8051: ds390 flat mode %sabled.\n",
1067                         flat24Mode ? "en" : "dis");
1068                 #endif
1069                 break;
1070
1071
1072         /*
1073          * If not an assembler directive then go to
1074          * the machine dependent function which handles
1075          * all the assembler mnemonics.
1076          */
1077         default:
1078                 machine(mp);
1079                 /* if cdb information then generate the line info */
1080                 if (cflag && (pass == 1))
1081                     DefineCDB_Line();
1082
1083                 /* JLH: if -j, generate a line number symbol */
1084                 if (jflag && (pass == 1))
1085                 {
1086                    DefineNoICE_Line();
1087                 }
1088
1089         }
1090         goto loop;
1091 }
1092
1093 /*)Function     FILE *  afile(fn, ft, wf)
1094  *
1095  *              char *  fn              file specification string
1096  *              char *  ft              file type string
1097  *              int     wf              read(0)/write(1) flag
1098  *
1099  *      The function afile() opens a file for reading or writing.
1100  *              (1)     If the file type specification string ft
1101  *                      is not NULL then a file specification is
1102  *                      constructed with the file path\name in fn
1103  *                      and the extension in ft.
1104  *              (2)     If the file type specification string ft
1105  *                      is NULL then the file specification is
1106  *                      constructed from fn.  If fn does not have
1107  *                      a file type then the default source file
1108  *                      type dsft is appended to the file specification.
1109  *
1110  *      afile() returns a file handle for the opened file or aborts
1111  *      the assembler on an open error.
1112  *
1113  *      local variables:
1114  *              int     c               character value
1115  *              FILE *  fp              filehandle for opened file
1116  *              char *  p1              pointer to filespec string fn
1117  *              char *  p2              pointer to filespec string fb
1118  *              char *  p3              pointer to filetype string ft
1119  *
1120  *      global variables:
1121  *              char    afn[]           afile() constructed filespec
1122  *              char    dsft[]          default assembler file type string
1123  *              char    afn[]           constructed file specification string
1124  *
1125  *      functions called:
1126  *              VOID    asexit()        asmain.c
1127  *              FILE *  fopen()         c_library
1128  *              int     fprintf()       c_library
1129  *
1130  *      side effects:
1131  *              File is opened for read or write.
1132  */
1133
1134 FILE *
1135 afile(char *fn, char *ft, int wf)
1136 {
1137         register char *p2, *p3;
1138         register int c;
1139         FILE *fp;
1140
1141         p2 = afn;
1142         p3 = ft;
1143
1144         strcpy (afn, fn);
1145         p2 = strrchr (afn, FSEPX);              // search last '.'
1146         if (!p2)
1147                 p2 = afn + strlen (afn);
1148         if (p2 > &afn[PATH_MAX-4])              // truncate filename, if it's too long
1149                 p2 = &afn[PATH_MAX-4];
1150         *p2++ = FSEPX;
1151
1152         // choose a file-extension
1153         if (*p3 == 0) {                                 // extension supplied?
1154                 p3 = strrchr (fn, FSEPX);       // no: extension in fn?
1155                 if (p3)
1156                         ++p3;
1157                 else
1158                         p3 = dsft;                                      // no: default extension
1159         }
1160
1161         while ((c = *p3++) != 0) {              // strncpy
1162                 if (p2 < &afn[PATH_MAX-1])
1163                         *p2++ = c;
1164         }
1165         *p2++ = 0;
1166
1167         if ((fp = fopen(afn, wf?"w":"r")) == NULL) {
1168                 fprintf(stderr, "%s: cannot %s.\n", afn, wf?"create":"open");
1169                 asexit(1);
1170         }
1171         return (fp);
1172 }
1173
1174 /*)Function     VOID    newdot(nap)
1175  *
1176  *              area *  nap             pointer to the new area structure
1177  *
1178  *      The function newdot():
1179  *              (1)     copies the current values of fuzz and the last
1180  *                      address into the current area referenced by dot
1181  *              (2)     loads dot with the pointer to the new area and
1182  *                      loads the fuzz and last address parameters
1183  *              (3)     outall() is called to flush any remaining
1184  *                      bufferred code from the old area to the output
1185  *
1186  *      local variables:
1187  *              area *  oap             pointer to old area
1188  *
1189  *      global variables:
1190  *              sym     dot             defined as sym[0]
1191  *              Addr_T  fuzz            tracks pass to pass changes in the
1192  *                                      address of symbols caused by
1193  *                                      variable length instruction formats
1194  *
1195  *      functions called:
1196  *              none
1197  *
1198  *      side effects:
1199  *              Current area saved, new area loaded, buffers flushed.
1200  */
1201
1202 VOID
1203 newdot(register struct area *nap)
1204 {
1205         register struct area *oap;
1206
1207         oap = dot.s_area;
1208         /* fprintf (stderr, "%s dot.s_area->a_size: %d dot.s_addr: %d\n",
1209              oap->a_id, dot.s_area->a_size, dot.s_addr); */
1210         oap->a_fuzz = fuzz;
1211         if (oap->a_flag & A_OVR) {
1212           // the size of an overlay is the biggest size encountered
1213           if (oap->a_size < dot.s_addr) {
1214             oap->a_size = dot.s_addr;
1215           }
1216         } else if (oap->a_flag & A_ABS) {
1217           oap->a_addr = dot.s_org;
1218           oap->a_size += dot.s_addr - dot.s_org;
1219           dot.s_addr = dot.s_org = 0;
1220         } else {
1221           oap->a_addr = 0;
1222           oap->a_size = dot.s_addr;
1223         }
1224         if (nap->a_flag & A_OVR) {
1225           // a new overlay starts at 0, no fuzz
1226           dot.s_addr = 0;
1227           fuzz = 0;
1228         } else if (nap->a_flag & A_ABS) {
1229           // a new absolute starts at org, no fuzz
1230           dot.s_addr = dot.s_org;
1231           fuzz = 0;
1232         } else {
1233           dot.s_addr = nap->a_size;
1234           fuzz = nap->a_fuzz;
1235         }
1236         dot.s_area = nap;
1237         outall();
1238 }
1239
1240 /*)Function     VOID    phase(ap, a)
1241  *
1242  *              area *  ap              pointer to area
1243  *              Addr_T  a               address in area
1244  *
1245  *      Function phase() compares the area ap and address a
1246  *      with the current area dot.s_area and address dot.s_addr
1247  *      to determine if the position of the symbol has changed
1248  *      between assembler passes.
1249  *
1250  *      local variables:
1251  *              none
1252  *
1253  *      global varaibles:
1254  *              sym *   dot             defined as sym[0]
1255  *
1256  *      functions called:
1257  *              none
1258  *
1259  *      side effects:
1260  *              The p error is invoked if the area and/or address
1261  *              has changed.
1262  */
1263
1264 VOID
1265 phase(struct area *ap, Addr_T a)
1266 {
1267         if (ap != dot.s_area || a != dot.s_addr)
1268                 err('p');
1269 }
1270
1271 char *usetxt[] = {
1272         "Usage: [-dqxjgalopsf][ -I<dir> ] file1 [file2 file3 ...]",
1273         "  d    decimal listing",
1274         "  q    octal   listing",
1275         "  x    hex     listing (default)",
1276         "  j    add line number and debug information to file", /* JLH */
1277         "  g    undefined symbols made global",
1278         "  a    all user symbols made global",
1279         "  l    create list   output file1[LST]",
1280         "  o    create object output file1[REL]",
1281         "  s    create symbol output file1[SYM]",
1282         "  c    generate sdcdb debug information",
1283         "  p    disable listing pagination",
1284         "  f    flag relocatable references by `    in listing file",
1285         " ff    flag relocatable references by mode in listing file",
1286         "-I<dir>  Add the named directory to the include file",
1287         "       search path.  This option may be used more than once.",
1288         "       Directories are searched in the order given.",
1289         "",
1290         0
1291 };
1292
1293 /*)Function     VOID    usage()
1294  *
1295  *      The function usage() outputs to the stderr device the
1296  *      assembler name and version and a list of valid assembler options.
1297  *
1298  *      local variables:
1299  *              char ** dp              pointer to an array of
1300  *                                      text string pointers.
1301  *
1302  *      global variables:
1303  *              char    cpu[]           assembler type string
1304  *              char *  usetxt[]        array of string pointers
1305  *
1306  *      functions called:
1307  *              VOID    asexit()        asmain.c
1308  *              int     fprintf()       c_library
1309  *
1310  *      side effects:
1311  *              program is terminated
1312  */
1313
1314 VOID
1315 usage(void)
1316 {
1317         register char   **dp;
1318
1319         fprintf(stderr, "\nASxxxx Assembler %s  (%s)\n\n", VERSION, cpu);
1320         for (dp = usetxt; *dp; dp++)
1321                 fprintf(stderr, "%s\n", *dp);
1322         asexit(1);
1323 }