work in progress
[fw/sdcc] / as / xa51 / xa_main.c
1 /* Paul's XA51 Assembler, Copyright 1997,2002 Paul Stoffregen (paul@pjrc.com)
2  *
3  * Paul's XA51 Assembler is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation; version 2.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /* adapted from the osu8asm project, 1995 */
18 /* http://www.pjrc.com/tech/osu8/index.html */
19
20 #define D(x) x
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <limits.h>
26
27 #define printf(x...) fprintf(stderr,x)
28
29 #include "xa_main.h"
30 #include "xa_version.h"
31 extern void yyrestart(FILE *new_file);
32 extern int yyparse();
33
34
35 char modulename[PATH_MAX];
36 char infilename[PATH_MAX];
37 char outfilename[PATH_MAX];
38 char listfilename[PATH_MAX];
39 char symfilename[PATH_MAX];
40
41 /* global variables */
42
43 FILE *frel, *fmem, *list_fp, *sym_fp;
44 extern FILE *yyin;
45 extern char *yytext;
46 extern char last_line_text[];
47 struct symbol *sym_list=NULL;
48 struct target *targ_list=NULL;
49 int lineno=1;
50 int p1=0, p2=0, p3=0;
51 int expr_result, expr_ok, jump_dest, inst;
52 int opcode, operand;
53 char symbol_name[1000];
54 struct area_struct area[NUM_AREAS];
55 int current_area=0;
56
57 char rel_line[2][132];
58
59 char *areaToString (int area) {
60   switch (area) 
61     {
62     case AREA_CSEG: return "CSEG";
63     case AREA_DSEG: return "DSEG";
64       //case AREA_OSEG: return "OSEG";
65       //case AREA_ISEG: return "ISEG";
66     case AREA_BSEG: return "BSEG";
67     case AREA_XSEG: return "XSEG";
68     case AREA_XISEG: return "XISEG";
69     case AREA_XINIT: return "XINIT";
70     case AREA_GSINIT: return "GSINIT";
71     case AREA_GSFINAL: return "GSFINAL";
72     case AREA_HOME: return "HOME";
73     case AREA_SSEG: return "SSEG";
74     }
75   return ("UNKNOW");
76 }
77
78 /* "mem" is replaced by area[current_area].alloc_position */
79 /* int mem=0; */   /* mem is location in memory */
80
81 /* add symbols to list when we find their definition in pass #1 */
82 /* we will evaluate their values in pass #2, and figure out if */
83 /* they are branch targets betweem passes 1 and 2.  Every symbol */
84 /* should appear exactly once in this list, since it can't be redefined */
85
86 struct symbol * build_sym_list(char *thename)
87 {
88         struct symbol *new, *p;
89
90         if ((p=findSymbol(thename))) {
91           p->area=current_area;
92           //fprintf (stderr, "warning, symbol %s already defined\n", thename);
93           return p;
94         }
95
96         //printf("  Symbol: %s  Line: %d\n", thename, lineno);
97         new = (struct symbol *) malloc(sizeof(struct symbol));
98         new->name = (char *) malloc(strlen(thename)+1);
99         strcpy(new->name, thename);
100         new->value = 0;
101         new->istarget = 0;
102         new->isdef = 0;
103         new->isbit = 0;
104         new->isreg = 0;
105         new->line_def = lineno - 1;
106         new->area = current_area;
107         new->mode = 'X'; // start with an external
108         new->next = NULL;
109         if (sym_list == NULL) return (sym_list = new);
110         p = sym_list;
111         while (p->next != NULL) p = p->next;
112         p->next = new;
113         return (new);
114 }
115
116 struct symbol *findSymbol (char *thename) {
117   struct symbol *p;
118   for (p=sym_list; p; p=p->next) {
119     if (strcasecmp(thename, p->name)==0) {
120       return p;
121     }
122   }
123   return NULL;
124 }
125
126 int assign_value(char *thename, int thevalue, char mode)
127 {
128         struct symbol *p;
129
130         p = sym_list;
131         while (p != NULL) {
132                 if (!(strcasecmp(thename, p->name))) {
133                         p->value = thevalue;
134                         p->isdef = 1;
135                         p->mode = mode;
136                         return (0);
137                 }
138                 p = p->next;
139         }
140         fprintf(stderr, "Internal Error!  Couldn't find symbol\n");
141         exit(1);
142 }
143
144 int mk_bit(char *thename, int area)
145 {
146         struct symbol *p;
147
148         p = sym_list;
149         while (p != NULL) {
150                 if (!(strcasecmp(thename, p->name))) {
151                         p->isbit = 1;
152                         p->area = area;
153                         return (0);
154                 }
155                 p = p->next;
156         }
157         fprintf(stderr, "Internal Error!  Couldn't find symbol\n");
158         exit(1);
159 }
160
161 int mk_sfr(char *thename)
162 {
163         struct symbol *p;
164
165         p = sym_list;
166         while (p != NULL) {
167                 if (!(strcasecmp(thename, p->name))) {
168                         p->issfr = 1;
169                         p->area = 0;
170                         return (0);
171                 }
172                 p = p->next;
173         }
174         fprintf(stderr, "Internal Error!  Couldn't find symbol\n");
175         exit(1);
176 }
177
178
179 int mk_reg(char *thename)
180 {
181         struct symbol *p;
182
183         p = sym_list;
184         while (p != NULL) {
185                 if (!(strcasecmp(thename, p->name))) {
186                         p->isreg = 1;
187                         return (0);
188                 }
189                 p = p->next;
190         }
191         fprintf(stderr, "Internal Error!  Couldn't find symbol\n");
192         exit(1);
193 }
194
195
196
197 int get_value(char *thename)
198 {
199         struct symbol *p;
200         p = sym_list;
201         while (p != NULL) {
202                 if (!(strcasecmp(thename, p->name)))
203                         return (p->value);
204                 p = p->next;
205         }
206         fprintf(stderr, "Internal Error!  Couldn't find symbol value\n");
207         exit(1);
208 }
209                 
210
211
212 /* add every branch target to this list as we find them */
213 /* ok if multiple entries of same symbol name in this list */
214
215 struct target * build_target_list(char *thename)
216 {
217         struct target *new, *p;
218         new = (struct target *) malloc(sizeof(struct target));
219         new->name = (char *) malloc(strlen(thename)+1);
220         strcpy(new->name, thename);
221         new->next = NULL;
222         if (targ_list == NULL) return (targ_list = new);
223         p = targ_list;
224         while (p->next != NULL) p = p->next;
225         p->next = new;
226         return (new);
227 }
228
229 /* figure out which symbols are branch targets */
230
231 void flag_targets()
232 {
233         struct symbol *p_sym;
234         struct target *p_targ;
235         p_targ = targ_list;
236         while (p_targ != NULL) {
237                 p_sym = sym_list;
238                 while (p_sym != NULL) {
239                         if (!strcasecmp(p_sym->name, p_targ->name))
240                                 p_sym->istarget = 1;
241                         p_sym = p_sym->next;
242                 }
243                 p_targ = p_targ->next;
244         }
245 }
246
247 void print_symbol_table()
248 {
249   struct symbol *p;
250   p = sym_list;
251   while (p != NULL) {
252 #if 0
253     fprintf(sym_fp, "Sym in %-5s: %s\n", areaToString(p->area), p->name);
254     fprintf(sym_fp, "  at: 0x%04X (%5d)", p->value, p->value);
255     fprintf(sym_fp, " Def:%s", p->isdef ? "Yes" : "No ");
256     fprintf(sym_fp, " Bit:%s", p->isbit ? "Yes" : "No ");
257     fprintf(sym_fp, " Target:%s", p->istarget ? "Yes" : "No ");
258     fprintf(sym_fp, " Line %d\n", p->line_def);
259 #else
260     if (p->issfr) {
261       fprintf (sym_fp, "%-5s", "SFR");
262     } else if (p->isbit && !p->area) {
263       fprintf (sym_fp, "%-5s", "SBIT");
264     } else if (!p->isdef) {
265       fprintf (sym_fp,"EXTRN");
266     } else {
267       fprintf (sym_fp, "%-5s", areaToString(p->area));
268     }
269     fprintf (sym_fp, " 0x%04x (%5d)", p->value, p->value);
270     fprintf (sym_fp, " %s", p->isdef ? "D" : "-");
271     fprintf (sym_fp, "%s", p->isbit ? "B" : "-");
272     fprintf (sym_fp, "%s", p->istarget ? "T" : "-");
273     fprintf (sym_fp, " %s\n", p->name);
274 #endif
275     p = p->next;
276   }
277 }
278
279 /* check that every symbol is in the table only once */
280
281 void check_redefine()
282 {
283   struct symbol *p1, *p2;
284   p1 = sym_list;
285   while (p1 != NULL) {
286     p2 = p1->next;
287     while (p2 != NULL) {
288       if (!strcasecmp(p1->name, p2->name)) {
289         fprintf(stderr, "Error: symbol '%s' redefined on line %d", 
290                 p1->name, p2->line_def);
291         fprintf(stderr, ", first defined on line %d\n", p1->line_def);
292         exit(1);
293       }
294       p2 = p2->next;
295     }
296     p1 = p1->next;
297   }
298 }
299
300 int is_target(char *thename)
301 {
302         struct symbol *p;
303         p = sym_list;
304         while (p != NULL) {
305                 if (!strcasecmp(thename, p->name)) return (p->istarget);
306                 p = p->next;
307         }
308         return (0);
309 }
310
311 int is_bit(char *thename)
312 {
313         struct symbol *p;
314         p = sym_list;
315         while (p != NULL) {
316                 if (!strcasecmp(thename, p->name)) return (p->isbit);
317                 p = p->next;
318         }
319         return (0);
320 }
321
322 int is_reg(char *thename)
323 {
324         struct symbol *p;
325         p = sym_list;
326         while (p != NULL) {
327                 if (!strcasecmp(thename, p->name)) return (p->isreg);
328                 p = p->next;
329         }
330         return (0);
331 }
332
333
334 struct symbol *is_def(char *thename)
335 {
336   struct symbol *p;
337   p = sym_list;
338   while (p != NULL) {
339     if (!strcasecmp(thename, p->name) && p->isdef) 
340       return p;
341     p = p->next;
342   }
343   return NULL;
344 }
345
346 struct symbol *is_ref(char *thename) {
347   struct symbol *p;
348   p = sym_list;
349   while (p != NULL) {
350     if (strcasecmp(thename, p->name)==0) 
351       return p;
352     p = p->next;
353   }
354   return NULL;
355 }
356
357 /* this routine is used to dump a group of bytes to the output */
358 /* it is responsible for generating the list file and sending */
359 /* the bytes one at a time to the object code generator */
360 /* this routine is also responsible for generatine the list file */
361 /* though is it expected that the lexer has placed all the actual */
362 /* original text from the line in "last_line_text" */
363
364 static short last_area=-1;
365
366 int debug=0;
367
368 void out(int *byte_list, int num) {
369   struct symbol *p;
370   int i, first=1;
371   
372   if (num > 0) fprintf(list_fp, "%06X: ", MEM_POS);
373   else fprintf(list_fp, "\t");
374   
375   if (last_area!=current_area) {
376     // emit area information
377     fprintf (frel, "A %s size %d flags 0\n", 
378              areaToString(current_area),
379              area[current_area].size);
380     area[current_area].defsEmitted=1;
381     if  (!area[current_area].defsEmitted) {
382       for (p=sym_list; p; p=p->next) {
383         if (p->isdef && p->area==current_area) {
384           if (debug || p->name[strlen(p->name)-1]!='$') {
385             fprintf (frel, "S %s Def%04x\n", p->name, p->value);
386           }
387         }
388       }
389     }
390     last_area=current_area;
391   }
392   if (current_area==AREA_CSEG ||
393       current_area==AREA_GSFINAL ||
394       current_area==AREA_XINIT) {
395     if (num) {
396       fprintf (frel, "T %02x %02x", (MEM_POS>>16)&0xff, MEM_POS&0xff);
397       for (i=0; i<num; i++) {
398         fprintf (frel, " %02x", byte_list[i]);
399       }
400       fprintf (frel, "\n");
401       if (rel_line[0][0]) {
402         fprintf (frel, "%s\n", rel_line[0]);
403         if (rel_line[1][0]) {
404           fprintf (frel, "%s\n", rel_line[1]);
405         }
406       }
407     }
408     for (i=0; i<num; i++) {
409       if (!first && (i % 4) == 0) fprintf(list_fp, "\t");
410       fprintf(list_fp, "%02X", byte_list[i]);
411       if ((i+1) % 4 == 0) {
412         if (first) fprintf(list_fp, "\t%s\n", last_line_text);
413         else fprintf(list_fp, "\n");
414         first = 0;
415       } else {
416         if (i<num-1) fprintf(list_fp, " ");
417       }
418     }
419   }
420   if (first) {
421     if (num < 3) fprintf(list_fp, "\t");
422     fprintf(list_fp, "\t%s\n", last_line_text);
423   } else {
424     if (num % 4) fprintf(list_fp, "\n");
425   }
426   expr_var[0][0]='\0';
427   expr_var[1][0]='\0';
428   rel_line[0][0]='\0';
429   rel_line[1][0]='\0';
430 }
431
432
433 /* add NOPs to align memory location on a valid branch target address */
434
435 void pad_with_nop()
436 {
437         static int nops[] = {NOP_OPCODE, NOP_OPCODE, NOP_OPCODE, NOP_OPCODE};
438         int num;
439
440         last_line_text[0] = '\0';
441
442         for(num=0; (MEM_POS + num) % BRANCH_SPACING; num++) ;
443         if (p3) out(nops, num);
444         MEM_POS += num;
445 }
446
447 /* print branch out of bounds error */
448
449 void boob_error()
450 {
451         fprintf(stderr, "Error: branch out of bounds");
452         fprintf(stderr, " in line %d\n", lineno);
453         exit(1);
454 }
455
456 /* output the jump either direction on carry */
457 /* jump_dest and MEM_POS must have the proper values */
458
459 /* 
460 void do_jump_on_carry()
461 {
462         if (p3) {
463                 operand = REL4(jump_dest, MEM_POS);
464                 if (operand < 0) {
465                         operand *= -1;
466                         operand -= 1;
467                         if (operand > 15) boob_error();
468                         out(0x20 + (operand & 15));
469                 } else {
470                         if (operand > 15) boob_error();
471                         out(0x30 + (operand & 15));
472                 }
473         }
474 }
475 */ 
476
477 /* turn a string like "10010110b" into an int */
478
479 int binary2int(char *str)
480 {
481         register int i, j=1, sum=0;
482         
483         for (i=strlen(str)-2; i >= 0; i--) {
484                 sum += j * (str[i] == '1');
485                 j *= 2;
486         }
487         return (sum);
488 }
489
490 void print_usage(int);
491
492
493 /* todo: someday this will allow the user to control where the */
494 /* various memory areas go, and it will take care of assigning */
495 /* positions to area which follow others (such as OSEG getting */
496 /* set just after DSEG on the 2nd and 3rd passes when we have */
497 /* leared the size needed for each segment */
498
499 void init_areas(void)
500 {
501   area[AREA_CSEG].start=area[AREA_CSEG].alloc_position = 0;
502   area[AREA_DSEG].start=area[AREA_DSEG].alloc_position = 0x30;
503   area[AREA_BSEG].start=area[AREA_BSEG].alloc_position = 0;
504   area[AREA_XSEG].start=area[AREA_XSEG].alloc_position = 0;
505   area[AREA_XISEG].start=area[AREA_XISEG].alloc_position = 0;
506   area[AREA_XINIT].start=area[AREA_XINIT].alloc_position = 0;
507   area[AREA_GSINIT].start=area[AREA_GSINIT].alloc_position = 0;
508   area[AREA_GSFINAL].start=area[AREA_GSFINAL].alloc_position = 0;
509   area[AREA_HOME].start=area[AREA_HOME].alloc_position = 0;
510 }
511
512 void relPrelude() {
513   //char buffer[132];
514   int i, areas=0, globals=0;
515   struct symbol *p;
516
517   fprintf (frel, "SDCCXA rel, version %1.1f\n", version);
518   for (i=0; i<NUM_AREAS; i++) {
519     if ((area[i].size=area[i].alloc_position-area[i].start)) {
520       areas++;
521     }
522 #if 0
523     current_area=i;
524     sprintf (buffer, "s_%s", areaToString(i));
525     build_sym_list (buffer);
526     buffer[0]='l';
527     build_sym_list (buffer);
528 #endif
529   }
530   for (p=sym_list; p; p=p->next) {
531     if (p->isdef) {
532       if (debug || p->name[strlen(p->name)-1]!='$') {
533         globals++;
534       }
535     }
536   }
537   fprintf (frel, "H %d areas %d global symbols\n", areas, globals);
538   fprintf (frel, "M %s\n", modulename);
539   for (p=sym_list; p; p=p->next) {
540     if (!p->isdef) {
541       fprintf (frel, "S %s Ref0000\n", p->name);
542     }
543   }
544 }
545
546 void printVersion() {
547   printf("\nPaul's XA51 Assembler\n");
548   printf("Copyright 1997,2002 Paul Stoffregen\n\n");
549   printf("This program is free software; you can redistribute it\n");
550   printf("and/or modify it under the terms of the GNU General Public\n");
551   printf("License, Version 2, published by the Free Software Foundation\n\n");
552   printf("This program is distributed in the hope that it will be useful,\n");
553   printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
554   printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n");
555 }
556
557 int verbose=0, createSymbolFile=0;
558
559 void process_args(int argc, char **argv) 
560 {
561   int i=0;
562
563   if (argc < 2) print_usage(1);
564   
565   while (++i<argc && *argv[i]=='-') {
566     if (strcmp(argv[i], "--version")==0) {
567       printVersion();
568       exit (0);
569     }
570     if (strcmp(argv[i], "--help")==0) {
571       print_usage(0);
572     }
573     if (strcmp(argv[i], "-v")==0) {
574       verbose++;
575       continue;
576     }
577     if (strcmp(argv[i], "-s")==0) {
578       createSymbolFile++;
579       continue;
580     }
581     print_usage(1);
582   }
583
584   if (i!=argc-1) {
585     // only 1 source file for now
586     print_usage(1);
587   }
588
589   strcpy(infilename, argv[i]);
590
591   if (strncasecmp(infilename+strlen(infilename)-3, ".xa", 3)) {
592     fprintf (stderr, "unrecognized input file: \"%s\"\n", argv[i]);
593     print_usage(1);
594   }
595
596   strcpy(modulename, infilename);
597   modulename[strlen(modulename)-3] = '\0';
598   sprintf (outfilename, "%s.rel", modulename);
599   sprintf (listfilename, "%s.lst", modulename);
600   if (createSymbolFile) {
601     sprintf (symfilename, "%s.sym", modulename);
602   }
603 }
604
605 /* pass #1 (p1=1) find all symbol defs and branch target names */
606 /* pass #2 (p2=1) align branch targets, evaluate all symbols */
607 /* pass #3 (p3=1) produce object code */
608
609 int main(int argc, char **argv)
610 {
611         process_args (argc, argv);
612
613         yyin = fopen(infilename, "r");
614         if (yyin == NULL) {
615                 fprintf(stderr, "Can't open file '%s'.\n", infilename);
616                 exit(1);
617         }
618         frel = fopen(outfilename, "w");
619         if (frel == NULL) {
620                 fprintf(stderr, "Can't write file '%s'.\n", outfilename);
621                 exit(1);
622         }
623         list_fp = fopen(listfilename, "w");
624         if (list_fp == NULL) {
625                 fprintf(stderr, "Can't write file '%s'.\n", listfilename);
626                 exit(1);
627         }
628         if (createSymbolFile) {
629           sym_fp = fopen(symfilename, "w");
630           if (sym_fp == NULL) {
631             fprintf(stderr, "Can't write file '%s'.\n", symfilename);
632             exit(1);
633           }
634         }
635
636         if (verbose) printf("Pass 1: Building Symbol Table:\n");
637         p1 = 1;
638         init_areas();
639         yyparse();
640         flag_targets();
641         check_redefine();
642
643         if (verbose) printf("Pass 2: Aligning Branch Targets:\n");
644         p1 = 0;
645         p2 = 1;
646         rewind(yyin);
647         yyrestart(yyin);
648         lineno = 1;
649         init_areas();
650         yyparse();
651
652         relPrelude();
653         if (createSymbolFile) print_symbol_table();
654
655         if (verbose) printf("Pass 3: Generating Object Code:\n");
656         p2 = 0;
657         p3 = 1;
658         rewind(yyin);
659         yyrestart(yyin);
660         lineno = 1;
661         init_areas();
662         yyparse();
663
664         fclose(yyin);
665         return 0;
666 }
667
668
669 void print_usage(int fatal)
670 {
671   FILE *out = fatal ? stderr : stdout;
672
673   fprintf (out, "Usage: xa_asm [-s] [-v] file.xa\n");
674   fprintf (out, "  -v            verbose: show progress\n");
675   fprintf (out, "  -s            create symbol file\n");
676   fprintf (out, "  --version     show version/copyright info and exit\n");
677   fprintf (out, "  --help        show this and exit\n");
678 #if 0
679   // some usefull options I can think of.
680   fprintf (out, "  -m            create map file\n");
681   fprintf (out, "  -ss           create symbol file sorted by symbol\n");
682   fprintf (out, "  -sa           create symbol file sorted by segment/address\n");
683   fprintf (out, "  --no-temps    supress temp symbols in map and sym file\n");
684   fprintf (out, "  --code-loc=#  sets the start address of the code\n");
685   fprintf (out, "  --xdata-loc=# sets the start address of the external data\n");
686   fprintf (out, "  --stack-loc=# sets the start address of the stack\n");
687 #endif
688   exit(fatal);
689 }
690