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