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