615d84d7cdec1eea5d9c013093e4c85d501ed9b5
[rmac] / rmac.c
1 //
2 // RMAC - Reboot's Macro Assembler for all Atari computers
3 // RMAC.C - Main Application Code
4 // Copyright (C) 199x Landon Dyer, 2011-2017 Reboot and Friends
5 // RMAC derived from MADMAC v1.07 Written by Landon Dyer, 1986
6 // Source utilised with the kind permission of Landon Dyer
7 //
8
9 #include "rmac.h"
10 #include "6502.h"
11 #include "debug.h"
12 #include "direct.h"
13 #include "error.h"
14 #include "expr.h"
15 #include "listing.h"
16 #include "mark.h"
17 #include "macro.h"
18 #include "object.h"
19 #include "procln.h"
20 #include "riscasm.h"
21 #include "sect.h"
22 #include "symbol.h"
23 #include "token.h"
24 #include "version.h"
25
26 int perm_verb_flag;                             // Permanently verbose, interactive mode
27 int list_flag;                                  // "-l" listing flag on command line
28 int list_pag = 1;                               // Enable listing pagination by default
29 int verb_flag;                                  // Be verbose about what's going on
30 int m6502;                                              // 1, assembling 6502 code
31 int as68_flag;                                  // as68 kludge mode
32 int glob_flag;                                  // Assume undefined symbols are global
33 int lsym_flag;                                  // Include local symbols in object file
34 int sbra_flag;                                  // Warn about possible short branches
35 int prg_flag;                                   // !=0, produce .PRG executable (2=symbols)
36 int legacy_flag;                                // Do stuff like insert code in RISC assembler
37 int obj_format;                                 // Object format flag
38 int debug;                                              // [1..9] Enable debugging levels
39 int err_flag;                                   // '-e' specified
40 int err_fd;                                             // File to write error messages to
41 int rgpu, rdsp;                                 // Assembling Jaguar GPU or DSP code
42 int dsp56001;                                   // Assembling DSP 56001 code
43 int list_fd;                                    // File to write listing to
44 int regbank;                                    // RISC register bank
45 int segpadsize;                                 // Segment padding size
46 int endian;                                             // Host processor endianess (0 = LE, 1 = BE)
47 char * objfname;                                // Object filename pointer
48 char * firstfname;                              // First source filename
49 char * cmdlnexec;                               // Executable name, pointer to ARGV[0]
50 char * searchpath;                              // Search path for include files
51 char defname[] = "noname.o";    // Default output filename
52 int optim_flags[OPT_COUNT];             // Specific optimisations on/off matrix
53 int activecpu = CPU_68000;              // Active 68k CPU (68000 by default)
54 int activefpu = FPU_NONE;               // Active FPU (none by default)
55
56
57 //
58 // Manipulate file extension.
59 //
60 // 'name' must be large enough to hold any possible filename. If 'stripp' is
61 // nonzero, any old extension is removed. If the file does not already have an
62 // extension, 'extension' is appended to the filename.
63 //
64 char * fext(char * name, char * extension, int stripp)
65 {
66         char * s;
67
68         // Find beginning of "real" name (strip off path)
69         char * beg = strrchr(name, SLASHCHAR);
70
71         if (beg == NULL)
72                 beg = name;
73
74         // Clobber any old extension, if requested
75         if (stripp)
76         {
77                 for(s=beg; *s && *s!='.'; ++s)
78                         ;
79
80                 *s = '\0';
81         }
82
83         if (strrchr(beg, '.') == NULL)
84                 strcat(beg, extension);
85
86         return name;
87 }
88
89
90 //
91 // Return 'item'nth element of semicolon-seperated pathnames specified in the
92 // enviroment string 's'. Copy the pathname to 'buf'.  Return 0 if the 'item'
93 // nth path doesn't exist.
94 //
95 // ['item' ranges from 0 to N-1, where N = #elements in search path]
96 //
97 int nthpath(char * env_var, int itemno, char * buf)
98 {
99         char * s = searchpath;
100
101         if (s == NULL)
102                 s = getenv(env_var);
103
104         if (s == NULL)
105                 return 0;
106
107         while (itemno--)
108                 while (*s != EOS && *s++ != ';')
109                         ;
110
111         if (*s == EOS)
112                 return 0;
113
114         while (*s != EOS && *s != ';')
115                 *buf++ = *s++;
116
117         *buf++ = EOS;
118
119         return 1;
120 }
121
122
123 //
124 // Display command line help
125 //
126 void DisplayHelp(void)
127 {
128         printf("Usage:\n"
129                 "    %s [options] srcfile\n"
130                 "\n"
131                 "Options:\n"
132                 "  -? or -h          Display usage information\n"
133                 "  -dsymbol[=value]  Define symbol (with optional value, default=0)\n"
134                 "  -e[errorfile]     Send error messages to file, not stdout\n"
135                 "  -f[format]        Output object file format\n"
136                 "                    a: ALCYON (use this for ST)\n"
137                 "                    b: BSD (use this for Jaguar)\n"
138                 "                    e: ELF\n"
139                 "                    x: com/exe/xex (Atari 800)\n"
140                 "  -i[path]          Directory to search for include files\n"
141                 "  -l[filename]      Create an output listing file\n"
142                 "  -l*[filename]     Create an output listing file without pagination\n"
143                 "  -m[cpu]           Select default CPU. Available options:\n"
144                 "                    68000\n"
145                 "                    68020\n"
146                 "                    68030\n"
147                 "                    68040\n"
148                 "                    68060\n"
149                 "                    6502\n"
150                 "                    tom\n"
151                 "                    jerry\n"
152                 "  -n                Don't do things behind your back in RISC assembler\n"
153                 "  -o file           Output file name\n"
154                 "  +o[value]         Turn a specific optimisation on\n"
155                 "                    Available optimisation values and default settings:\n"
156                 "                    o0: Absolute long adddresses to word        (on)\n"
157                 "                    o1: move.l #x,dn/an to moveq                (on)\n"
158                 "                    o2: Word branches to short                  (on)\n"
159                 "                    o3: Outer displacement 0(an) to (an)        (off)\n"
160                 "                    o4: lea size(An),An to addq #size,An        (off)\n"
161                 "                    o5: Absolute long base displacement to word (off)\n"
162                 "                    o6: Null branches to NOP                    (off)\n"
163                 "                    o7: clr.l Dx to moveq #0,Dx                 (off)\n"
164                 "                    o8: adda.w/l #x,Dy to addq.w/l #x,Dy        (off)\n"
165                 "                    o9: adda.w/l #x,Dy to lea x(Dy),Dy          (off)\n"
166                 "  ~o[value]         Turn a specific optimisation off\n"
167                 "  +oall             Turn all optimisations on\n"
168                 "  ~oall             Turn all optimisations off\n"
169                 "  -p                Create an ST .prg (without symbols)\n"
170                 "  -ps               Create an ST .prg (with symbols)\n"
171                 "                    Forces -fa\n"
172                 "  -r[size]          Pad segments to boundary size specified\n"
173                 "                    w: word (2 bytes, default alignment)\n"
174                 "                    l: long (4 bytes)\n"
175                 "                    p: phrase (8 bytes)\n"
176                 "                    d: double phrase (16 bytes)\n"
177                 "                    q: quad phrase (32 bytes)\n"
178                 "  -s                Warn about possible short branches\n"
179                 "                    and applied optimisations\n"
180                 "  -u                Force referenced and undefined symbols global\n"
181                 "  -v                Set verbose mode\n"
182                 "  -x                Turn on debugging mode\n"
183                 "  -y[pagelen]       Set page line length (default: 61)\n"
184                 "\n", cmdlnexec);
185 }
186
187
188 //
189 // Display version information
190 //
191 void DisplayVersion(void)
192 {
193         printf("\n"
194                 " _ __ _ __ ___   __ _  ___ \n"
195                 "| '__| '_ ` _ \\ / _` |/ __|\n"
196                 "| |  | | | | | | (_| | (__ \n"
197                 "|_|  |_| |_| |_|\\__,_|\\___|\n"
198                 "\nReboot's Macro Assembler\n"
199                 "Copyright (C) 199x Landon Dyer, 2011-2017 Reboot\n"
200                 "V%01i.%01i.%01i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
201 }
202
203
204 //
205 // Parse optimisation options
206 //
207 int ParseOptimization(char * optstring)
208 {
209         int onoff = 0;
210
211         if (*optstring == '+')
212                 onoff = 1;
213         else if (*optstring != '~')
214                 return ERROR;
215
216         if ((optstring[2] == 'a' || optstring[2] == 'A')
217                 && (optstring[3] == 'l' || optstring[3] == 'L')
218                 && (optstring[4] == 'l' || optstring[4] == 'L'))
219         {
220                 memset(optim_flags, onoff, OPT_COUNT * sizeof(int));
221                 return OK;
222         }
223         else if (optstring[1] == 'o' || optstring[1] == 'O') // Turn on specific optimisation
224         {
225                 int opt_no = atoi(&optstring[2]);
226
227                 if ((opt_no >= 0) && (opt_no < OPT_COUNT))
228                 {
229                         optim_flags[opt_no] = onoff;
230                         return OK;
231                 }
232                 else
233                         return ERROR;
234         }
235         else
236         {
237                 return ERROR;
238         }
239 }
240
241
242 //
243 // Process command line arguments and do an assembly
244 //
245 int Process(int argc, char ** argv)
246 {
247         int argno;                                              // Argument number
248         SYM * sy;                                               // Pointer to a symbol record
249         char * s;                                               // String pointer
250         int fd;                                                 // File descriptor
251         char fnbuf[FNSIZ];                              // Filename buffer
252         int i;                                                  // Iterator
253
254         errcnt = 0;                                             // Initialise error count
255         listing = 0;                                    // Initialise listing level
256         list_flag = 0;                                  // Initialise listing flag
257         verb_flag = perm_verb_flag;             // Initialise verbose flag
258         as68_flag = 0;                                  // Initialise as68 kludge mode
259         glob_flag = 0;                                  // Initialise .globl flag
260         sbra_flag = 0;                                  // Initialise short branch flag
261         debug = 0;                                              // Initialise debug flag
262         searchpath = NULL;                              // Initialise search path
263         objfname = NULL;                                // Initialise object filename
264         list_fname = NULL;                              // Initialise listing filename
265         err_fname = NULL;                               // Initialise error filename
266         obj_format = BSD;                               // Initialise object format
267         firstfname = NULL;                              // Initialise first filename
268         err_fd = ERROUT;                                // Initialise error file descriptor
269         err_flag = 0;                                   // Initialise error flag
270         rgpu = 0;                                               // Initialise GPU assembly flag
271         rdsp = 0;                                               // Initialise DSP assembly flag
272         lsym_flag = 1;                                  // Include local symbols in object file
273         regbank = BANK_N;                               // No RISC register bank specified
274         orgactive = 0;                                  // Not in RISC org section
275         orgwarning = 0;                                 // No ORG warning issued
276         segpadsize = 2;                                 // Initialise segment padding size
277         m6502 = 0;                                              // 6502 mode off by default
278
279         // Initialise modules
280         InitSymbolTable();                              // Symbol table
281         InitTokenizer();                                // Tokenizer
282         InitLineProcessor();                    // Line processor
283         InitExpression();                               // Expression analyzer
284         InitSection();                                  // Section manager / code generator
285         InitMark();                                             // Mark tape-recorder
286         InitMacro();                                    // Macro processor
287         InitListing();                                  // Listing generator
288         Init6502();                                             // 6502 assembler
289
290         // Process command line arguments and assemble source files
291         for(argno=0; argno<argc; argno++)
292         {
293                 if (*argv[argno] == '-')
294                 {
295                         switch (argv[argno][1])
296                         {
297                         case 'd':                               // Define symbol
298                         case 'D':
299                                 for(s=argv[argno]+2; *s!=EOS;)
300                                 {
301                                         if (*s++ == '=')
302                                         {
303                                                 s[-1] = EOS;
304                                                 break;
305                                         }
306                                 }
307
308                                 if (argv[argno][2] == EOS)
309                                 {
310                                         printf("-d: empty symbol\n");
311                                         errcnt++;
312                                         return errcnt;
313                                 }
314
315                                 sy = lookup(argv[argno] + 2, 0, 0);
316
317                                 if (sy == NULL)
318                                 {
319                                         sy = NewSymbol(argv[argno] + 2, LABEL, 0);
320                                         sy->svalue = 0;
321                                 }
322
323                                 sy->sattr = DEFINED | EQUATED | ABS;
324                                 sy->svalue = (*s ? (uint32_t)atoi(s) : 0);
325                                 break;
326                         case 'e':                               // Redirect error message output
327                         case 'E':
328                                 err_fname = argv[argno] + 2;
329                                 break;
330                         case 'f':                               // -f<format>
331                         case 'F':
332                                 switch (argv[argno][2])
333                                 {
334                                 case EOS:
335                                 case 'a':                       // -fa = Alcyon [the default]
336                                 case 'A':
337                                         obj_format = ALCYON;
338                                         break;
339                                 case 'b':                       // -fb = BSD (Jaguar Recommended: 3 out 4 jaguars recommend it!)
340                                 case 'B':
341                                         obj_format = BSD;
342                                         break;
343                                 case 'e':                       // -fe = ELF
344                                 case 'E':
345                                         obj_format = ELF;
346                                         break;
347                                 case 'x':                       // -fx = COM/EXE/XEX
348                                 case 'X':
349                                         obj_format = XEX;
350                                         break;
351                                 default:
352                                         printf("-f: unknown object format specified\n");
353                                         errcnt++;
354                                         return errcnt;
355                                 }
356                                 break;
357                         case 'g':                               // Debugging flag
358                         case 'G':
359                                 printf("Debugging flag (-g) not yet implemented\n");
360                                 break;
361                         case 'i':                               // Set directory search path
362                         case 'I':
363                                 searchpath = argv[argno] + 2;
364                                 break;
365                         case 'l':                               // Produce listing file
366                         case 'L':
367                                 if (*(argv[argno] + 2) == '*')
368                                 {
369                                         list_fname = argv[argno] + 3;
370                                         list_pag = 0;    // Special case - turn off pagination
371                                 }
372                                 else
373                                 {
374                                         list_fname = argv[argno] + 2;
375                                 }
376
377                                 listing = 1;
378                                 list_flag = 1;
379                                 lnsave++;
380                                 break;
381                         case 'm':
382                         case 'M':
383                                 if (strcmp(argv[argno] + 2, "68000") == 0)
384                                         d_68000();
385                                 else if (strcmp(argv[argno] + 2, "68020") == 0)
386                                         d_68020();
387                                 else if (strcmp(argv[argno] + 2, "68030") == 0)
388                                         d_68030();
389                                 else if (strcmp(argv[argno] + 2, "68040") == 0)
390                                         d_68040();
391                                 else if (strcmp(argv[argno] + 2, "68060") == 0)
392                                         d_68060();
393                                 else if (strcmp(argv[argno] + 2, "68881") == 0)
394                                         d_68881();
395                                 else if (strcmp(argv[argno] + 2, "68882") == 0)
396                                         d_68882();
397                                 else if (strcmp(argv[argno] + 2, "56001") == 0)
398                                         d_56001();
399                                 else if (strcmp(argv[argno] + 2, "6502") == 0)
400                                         d_6502();
401                                 else if (strcmp(argv[argno] + 2, "tom") == 0)
402                                         d_gpu();
403                                 else if (strcmp(argv[argno] + 2, "jerry") == 0)
404                                         d_dsp();
405                                 else
406                                 {
407                                         printf("Unrecognized CPU '%s'\n", argv[argno] + 2);
408                                         errcnt++;
409                                         return errcnt;
410                                 }
411                                 break;
412                         case 'o':                               // Direct object file output
413                         case 'O':
414                                 if (argv[argno][2] != EOS)
415                                         objfname = argv[argno] + 2;
416                                 else
417                                 {
418                                         if (++argno >= argc)
419                                         {
420                                                 printf("Missing argument to -o");
421                                                 errcnt++;
422                                                 return errcnt;
423                                         }
424
425                                         objfname = argv[argno];
426                                 }
427
428                                 break;
429                         case 'p':               /* -p: generate ".PRG" executable output */
430                         case 'P':
431                                 /*
432                                  * -p           .PRG generation w/o symbols
433                                  * -ps  .PRG generation with symbols
434                                  */
435                                 switch (argv[argno][2])
436                                 {
437                                         case EOS:
438                                                 prg_flag = 1;
439                                                 break;
440
441                                         case 's':
442                                         case 'S':
443                                                 prg_flag = 2;
444                                                 break;
445
446                                         default:
447                                                 printf("-p: syntax error\n");
448                                                 errcnt++;
449                                                 return errcnt;
450                                 }
451
452                                 // Enforce Alcyon object format - kind of silly
453                                 // to ask for .prg output without it!
454                                 obj_format = ALCYON;
455                                 break;
456                         case 'r':                               // Pad seg to requested boundary size
457                         case 'R':
458                                 switch(argv[argno][2])
459                                 {
460                                 case 'w': case 'W': segpadsize = 2;  break;
461                                 case 'l': case 'L': segpadsize = 4;  break;
462                                 case 'p': case 'P': segpadsize = 8;  break;
463                                 case 'd': case 'D': segpadsize = 16; break;
464                                 case 'q': case 'Q': segpadsize = 32; break;
465                                 default: segpadsize = 2; break; // Effective autoeven();
466                                 }
467                                 break;
468                         case 's':                               // Warn about possible short branches
469                         case 'S':
470                                 sbra_flag = 1;
471                                 break;
472                         case 'u':                               // Make undefined symbols .globl
473                         case 'U':
474                                 glob_flag = 1;
475                                 break;
476                         case 'v':                               // Verbose flag
477                         case 'V':
478                                 verb_flag++;
479
480                                 if (verb_flag > 1)
481                                         DisplayVersion();
482
483                                 break;
484                         case 'x':                               // Turn on debugging
485                         case 'X':
486                                 debug = 1;
487                                 printf("~ Debugging ON\n");
488                                 break;
489                         case 'y':                               // -y<pagelen>
490                         case 'Y':
491                                 pagelen = atoi(argv[argno] + 2);
492
493                                 if (pagelen < 10)
494                                 {
495                                         printf("-y: bad page length\n");
496                                         errcnt++;
497                                         return errcnt;
498                                 }
499
500                                 break;
501                         case EOS:                               // Input is stdin
502                                 if (firstfname == NULL) // Kludge first filename
503                                         firstfname = defname;
504
505                                 include(0, "(stdin)");
506                                 Assemble();
507                                 break;
508                         case 'h':                               // Display command line usage
509                         case 'H':
510                         case '?':
511                                 DisplayVersion();
512                                 DisplayHelp();
513                                 errcnt++;
514                                 break;
515                         case 'n':                               // Turn off legacy mode
516                         case 'N':
517                                 legacy_flag = 0;
518                                 printf("Legacy mode OFF\n");
519                                 break;
520                         default:
521                                 DisplayVersion();
522                                 printf("Unknown switch: %s\n\n", argv[argno]);
523                                 DisplayHelp();
524                                 errcnt++;
525                                 break;
526                         }
527                 }
528                 else if (*argv[argno] == '+' || *argv[argno] == '~')
529                 {
530                         if (ParseOptimization(argv[argno]) != OK)
531                         {
532                                 DisplayVersion();
533                                 printf("Unknown switch: %s\n\n", argv[argno]);
534                                 DisplayHelp();
535                                 errcnt++;
536                                 break;
537                         }
538                 }
539                 else
540                 {
541                         // Record first filename.
542                         if (firstfname == NULL)
543                                 firstfname = argv[argno];
544
545                         strcpy(fnbuf, argv[argno]);
546                         fext(fnbuf, ".s", 0);
547                         fd = open(fnbuf, 0);
548
549                         if (fd < 0)
550                         {
551                                 printf("Cannot open: %s\n", fnbuf);
552                                 errcnt++;
553                                 continue;
554                         }
555
556                         include(fd, fnbuf);
557                         Assemble();
558                 }
559         }
560
561         // Wind-up processing;
562         // o  save current section (no more code generation)
563         // o  do auto-even of all sections (or boundary alignment as requested
564         //    through '-r')
565     // o  save the last pc value for 6502 (if we used 6502 at all) and
566     //    detemine if the last section contains anything
567         // o  determine name of object file:
568         //    -  "foo.o" for linkable output;
569         //    -  "foo.prg" for GEMDOS executable (-p flag).
570         SaveSection();
571
572         for(i=TEXT; i<=BSS; i<<=1)
573         {
574                 SwitchSection(i);
575
576                 switch(segpadsize)
577                 {
578                 case 2:  d_even();    break;
579                 case 4:  d_long();    break;
580                 case 8:  d_phrase();  break;
581                 case 16: d_dphrase(); break;
582                 case 32: d_qphrase(); break;
583                 }
584
585                 SaveSection();
586         }
587
588         SwitchSection(M6502);
589
590         if (sloc != currentorg[0])
591         {
592                 currentorg[1] = sloc;
593                 currentorg += 2;
594         }
595
596         if (objfname == NULL)
597         {
598                 if (firstfname == NULL)
599                         firstfname = defname;
600
601                 strcpy(fnbuf, firstfname);
602                 fext(fnbuf, (prg_flag ? ".prg" : ".o"), 1);
603                 objfname = fnbuf;
604         }
605
606         // With one pass finished, go back and:
607         // (1)   run through all the fixups and resolve forward references;
608         // (1.5) ensure that remaining fixups can be handled by the linker
609         //       (`lo68' format, extended (postfix) format....)
610         // (2)   generate the output file image and symbol table;
611         // (3)   generate relocation information from left-over fixups.
612         ResolveAllFixups();                                             // Do all fixups
613         StopMark();                                                             // Stop mark tape-recorder
614
615         if (errcnt == 0)
616         {
617                 if ((fd = open(objfname, _OPEN_FLAGS, _PERM_MODE)) < 0)
618                         cantcreat(objfname);
619
620                 if (verb_flag)
621                 {
622                         s = (prg_flag ? "executable" : "object");
623                         printf("[Writing %s file: %s]\n", s, objfname);
624                 }
625
626                 WriteObject(fd);
627                 close(fd);
628
629                 if (errcnt != 0)
630                         unlink(objfname);
631         }
632
633         if (list_flag)
634         {
635                 if (verb_flag)
636                         printf("[Wrapping-up listing file]\n");
637
638                 listing = 1;
639                 symtable();
640                 close(list_fd);
641         }
642
643         if (err_flag)
644                 close(err_fd);
645
646         DEBUG dump_everything();
647
648         return errcnt;
649 }
650
651
652 //
653 // Determine processor endianess
654 //
655 int GetEndianess(void)
656 {
657         int i = 1;
658         char * p = (char *)&i;
659
660         if (p[0] == 1)
661                 return 0;
662
663         return 1;
664 }
665
666
667 //
668 // Application entry point
669 //
670 int main(int argc, char ** argv)
671 {
672         perm_verb_flag = 0;                             // Clobber "permanent" verbose flag
673         legacy_flag = 1;                                // Default is legacy mode on (:-P)
674
675         // Set legacy optimisation flags to on and everything else to off
676         memset(optim_flags, 0, OPT_COUNT * sizeof(int));
677         optim_flags[OPT_ABS_SHORT] =
678                 optim_flags[OPT_MOVEL_MOVEQ] =
679                 optim_flags[OPT_BSR_BCC_S] = 1;
680
681         cmdlnexec = argv[0];                    // Obtain executable name
682         endian = GetEndianess();                // Get processor endianess
683
684         // If commands were passed in, process them
685         if (argc > 1)
686                 return Process(argc - 1, argv + 1);
687
688         DisplayVersion();
689         DisplayHelp();
690
691         return 0;
692 }
693