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