0683739847ce7172b1562068545f393a5b969266
[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
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                 "  -p                Create an ST .prg (without symbols)\n"
136                 "  -ps               Create an ST .prg (with symbols)\n"
137                 "                    Forces -fa\n"
138                 "  -r[size]          Pad segments to boundary size specified\n"
139                 "                    w: word (2 bytes, default alignment)\n"
140                 "                    l: long (4 bytes)\n"
141                 "                    p: phrase (8 bytes)\n"
142                 "                    d: double phrase (16 bytes)\n"
143                 "                    q: quad phrase (32 bytes)\n"
144                 "  -s                Warn about possible short branches\n"
145                 "  -u                Force referenced and undefined symbols global\n"
146                 "  -v                Set verbose mode\n"
147                 "  -y[pagelen]       Set page line length (default: 61)\n"
148                 "\n", cmdlnexec);
149 }
150
151
152 //
153 // Display version information
154 //
155 void DisplayVersion(void)
156 {
157         printf("\n"
158                 " _ __ _ __ ___   __ _  ___ \n"
159                 "| '__| '_ ` _ \\ / _` |/ __|\n"
160                 "| |  | | | | | | (_| | (__ \n"
161                 "|_|  |_| |_| |_|\\__,_|\\___|\n"
162                 "\nReboot's Macro Assembler\n"
163                 "Copyright (C) 199x Landon Dyer, 2011-2015 Reboot\n"
164                 "V%01i.%01i.%01i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
165 }
166
167
168 // 
169 // Process command line arguments and do an assembly
170 //
171 int Process(int argc, char ** argv)
172 {
173         int argno;                                              // Argument number
174         SYM * sy;                                               // Pointer to a symbol record
175         char * s;                                               // String pointer
176         int fd;                                                 // File descriptor
177         char fnbuf[FNSIZ];                              // Filename buffer 
178         int i;                                                  // Iterator
179
180         errcnt = 0;                                             // Initialise error count
181         listing = 0;                                    // Initialise listing level
182         list_flag = 0;                                  // Initialise listing flag
183         verb_flag = perm_verb_flag;             // Initialise verbose flag
184         as68_flag = 0;                                  // Initialise as68 kludge mode
185         glob_flag = 0;                                  // Initialise .globl flag
186         sbra_flag = 0;                                  // Initialise short branch flag
187         debug = 0;                                              // Initialise debug flag
188         searchpath = NULL;                              // Initialise search path
189         objfname = NULL;                                // Initialise object filename
190         list_fname = NULL;                              // Initialise listing filename
191         err_fname = NULL;                               // Initialise error filename
192         obj_format = BSD;                               // Initialise object format
193         firstfname = NULL;                              // Initialise first filename
194         err_fd = ERROUT;                                // Initialise error file descriptor
195         err_flag = 0;                                   // Initialise error flag
196         rgpu = 0;                                               // Initialise GPU assembly flag
197         rdsp = 0;                                               // Initialise DSP assembly flag
198         lsym_flag = 1;                                  // Include local symbols in object file
199         regbank = BANK_N;                               // No RISC register bank specified
200         orgactive = 0;                                  // Not in RISC org section
201         orgwarning = 0;                                 // No ORG warning issued
202         segpadsize = 2;                                 // Initialise segment padding size
203
204         // Initialise modules
205         InitSymbolTable();                              // Symbol table
206         InitTokenizer();                                // Tokenizer
207         InitLineProcessor();                    // Line processor
208         InitExpression();                               // Expression analyzer
209         InitSection();                                  // Section manager / code generator
210         InitMark();                                             // Mark tape-recorder
211         InitMacro();                                    // Macro processor
212         InitListing();                                  // Listing generator
213
214         // Process command line arguments and assemble source files
215         for(argno=0; argno<argc; ++argno)
216         {
217                 if (*argv[argno] == '-')
218                 {
219                         switch (argv[argno][1])
220                         {
221                         case 'd':                               // Define symbol
222                         case 'D':
223                                 for(s=argv[argno]+2; *s!=EOS;)
224                                 {
225                                         if (*s++ == '=')
226                                         {
227                                                 s[-1] = EOS;
228                                                 break;
229                                         }
230                                 }
231
232                                 if (argv[argno][2] == EOS)
233                                 {
234                                         printf("-d: empty symbol\n");
235                                         errcnt++;
236                                         return errcnt;
237                                 }
238
239                                 sy = lookup(argv[argno] + 2, 0, 0);
240
241                                 if (sy == NULL)
242                                 {
243                                         sy = NewSymbol(argv[argno] + 2, LABEL, 0);
244                                         sy->svalue = 0;
245                                 }
246
247                                 sy->sattr = DEFINED | EQUATED | ABS;
248                                 sy->svalue = (*s ? (VALUE)atoi(s) : 0);
249                                 break;
250                         case 'e':                               // Redirect error message output
251                         case 'E':
252                                 err_fname = argv[argno] + 2;
253                                 break;
254                         case 'f':                               // -f<format>
255                         case 'F':
256                                 switch (argv[argno][2])
257                                 {
258                                 case EOS:
259                                 case 'a':                       // -fa = Alcyon [the default]
260                                 case 'A':
261                                         obj_format = ALCYON;
262                                         break;
263                                 case 'b':                       // -fb = BSD (Jaguar Recommended)
264                                 case 'B':
265                                         obj_format = BSD;
266                                         break;
267                                 default:
268                                         printf("-f: unknown object format specified\n");
269                                         errcnt++;
270                                         return errcnt;
271                                 }
272                                 break;
273                         case 'g':                               // Debugging flag
274                         case 'G':
275                                 printf("Debugging flag (-g) not yet implemented\n");
276                                 break;
277                         case 'i':                               // Set directory search path
278                         case 'I':
279                                 searchpath = argv[argno] + 2;
280                                 break;
281                         case 'l':                               // Produce listing file
282                         case 'L':
283                                 list_fname = argv[argno] + 2;
284                                 listing = 1;
285                                 list_flag = 1;
286                                 lnsave++;
287                                 break;
288                         case 'o':                               // Direct object file output
289                         case 'O':
290                                 if (argv[argno][2] != EOS)
291                                         objfname = argv[argno] + 2;
292                                 else
293                                 {
294                                         if (++argno >= argc)
295                                         {
296                                                 printf("Missing argument to -o");
297                                                 errcnt++;
298                                                 return errcnt;
299                                         }
300
301                                         objfname = argv[argno];
302                                 }
303
304                                 break;
305                         case 'p':               /* -p: generate ".PRG" executable output */
306                         case 'P':
307                                 /*
308                                  * -p           .PRG generation w/o symbols
309                                  * -ps  .PRG generation with symbols
310                                  */
311                                 switch (argv[argno][2])
312                                 {
313                                         case EOS:
314                                                 prg_flag = 1;
315                                                 break;
316
317                                         case 's':
318                                         case 'S':
319                                                 prg_flag = 2;
320                                                 break;
321
322                                         default:
323                                                 printf("-p: syntax error\n");
324                                                 ++errcnt;
325                                                 return errcnt;
326                                 }
327
328                                 // Enforce Alcyon object format - kind of silly
329                                 // to ask for .prg output without it!
330                                 obj_format = ALCYON;
331                                 break;
332                         case 'r':                               // Pad seg to requested boundary size
333                         case 'R':
334                                 switch(argv[argno][2])
335                                 {
336                                 case 'w': case 'W': segpadsize = 2;  break;  
337                                 case 'l': case 'L': segpadsize = 4;  break;
338                                 case 'p': case 'P': segpadsize = 8;  break;
339                                 case 'd': case 'D': segpadsize = 16; break;
340                                 case 'q': case 'Q': segpadsize = 32; break;
341                                 default: segpadsize = 2; break; // Effective autoeven();
342                                 }
343                                 break;
344                         case 's':                               // Warn about possible short branches
345                         case 'S':
346                                 sbra_flag = 1;
347                                 break;
348                         case 'u':                               // Make undefined symbols .globl
349                         case 'U':
350                                 glob_flag = 1;
351                                 break;
352                         case 'v':                               // Verbose flag
353                         case 'V':
354                                 verb_flag++;
355
356                                 if (verb_flag > 1)
357                                         DisplayVersion();
358
359                                 break;
360                         case 'x':                               // Turn on debugging
361                         case 'X':
362                                 debug = 1;
363                                 printf("~ Debugging ON\n");
364                                 break;
365                         case 'y':                               // -y<pagelen>
366                         case 'Y':
367                                 pagelen = atoi(argv[argno] + 2);
368
369                                 if (pagelen < 10)
370                                 {
371                                         printf("-y: bad page length\n");
372                                         ++errcnt;
373                                         return errcnt;
374                                 }
375
376                                 break;
377                         case EOS:                               // Input is stdin
378                                 if (firstfname == NULL) // Kludge first filename
379                                         firstfname = defname;
380
381                                 include(0, "(stdin)");
382                                 Assemble();
383                                 break;
384                         case 'h':                               // Display command line usage
385                         case 'H':
386                         case '?':
387                                 DisplayVersion();
388                                 DisplayHelp();
389                                 errcnt++;
390                                 break;
391                         case 'n':                               // Turn off legacy mode
392                         case 'N':
393                                 legacy_flag = 0;
394                                 printf("Legacy mode OFF\n");
395                                 break;
396                         default:
397                                 DisplayVersion();
398                                 printf("Unknown switch: %s\n\n", argv[argno]);
399                                 DisplayHelp();
400                                 errcnt++;
401                                 break;
402                         }
403                 }
404                 else
405                 {
406                         // Record first filename.
407                         if (firstfname == NULL)
408                                 firstfname = argv[argno];
409
410                         strcpy(fnbuf, argv[argno]);
411                         fext(fnbuf, ".s", 0);
412                         fd = open(fnbuf, 0);
413
414                         if (fd < 0)
415                         {
416                                 printf("Cannot open: %s\n", fnbuf);
417                                 errcnt++;
418                                 continue;
419                         }
420
421                         include(fd, fnbuf);
422                         Assemble();
423                 }
424         }
425
426         // Wind-up processing;
427         // o  save current section (no more code generation)
428         // o  do auto-even of all sections (or boundary alignment as requested
429         //    through '-r')
430         // o  determine name of object file:
431         //    -  "foo.o" for linkable output;
432         //    -  "foo.prg" for GEMDOS executable (-p flag).
433         SaveSection();
434
435         for(i=TEXT; i<=BSS; i<<=1)
436         {
437                 SwitchSection(i);
438
439                 switch(segpadsize)
440                 {
441                 case 2:  d_even();    break;
442                 case 4:  d_long();    break;
443                 case 8:  d_phrase();  break;
444                 case 16: d_dphrase(); break;
445                 case 32: d_qphrase(); break;
446                 }
447
448                 SaveSection();
449         }
450
451         if (objfname == NULL)
452         {
453                 if (firstfname == NULL)
454                         firstfname = defname;
455
456                 strcpy(fnbuf, firstfname);
457                 fext(fnbuf, (prg_flag ? ".prg" : ".o"), 1);
458                 objfname = fnbuf;
459         }
460
461         // With one pass finished, go back and:
462         // (1)   run through all the fixups and resolve forward references;
463         // (1.5) ensure that remaining fixups can be handled by the linker
464         //       (`lo68' format, extended (postfix) format....)
465         // (2)   generate the output file image and symbol table;
466         // (3)   generate relocation information from left-over fixups.
467         ResolveAllFixups();                                             // Do all fixups
468         StopMark();                                                             // Stop mark tape-recorder
469
470         if (errcnt == 0)
471         {
472                 if ((fd = open(objfname, _OPEN_FLAGS, _PERM_MODE)) < 0)
473                         cantcreat(objfname);
474
475                 if (verb_flag)
476                 {
477                         s = (prg_flag ? "executable" : "object");
478                         printf("[Writing %s file: %s]\n", s, objfname);
479                 }
480
481                 WriteObject(fd);
482                 close(fd);
483
484                 if (errcnt != 0)
485                         unlink(objfname);
486         }
487
488         if (list_flag)
489         {
490                 if (verb_flag)
491                         printf("[Wrapping-up listing file]\n");
492
493                 listing = 1;
494                 symtable();
495                 close(list_fd);
496         }
497
498         if (err_flag)
499                 close(err_fd);
500
501         DEBUG dump_everything();
502
503         return errcnt;
504 }
505
506
507 //
508 // Determine processor endianess
509 //
510 int GetEndianess(void)
511 {
512         int i = 1;
513         char * p = (char *)&i;
514
515         if (p[0] == 1)
516                 return 0;
517
518         return 1;
519 }
520
521
522 //
523 // Application entry point
524 //
525 int main(int argc, char ** argv)
526 {
527         perm_verb_flag = 0;                             // Clobber "permanent" verbose flag
528         legacy_flag = 1;                                // Default is legacy mode on (:-P)
529         cmdlnexec = argv[0];                    // Obtain executable name
530
531         endian = GetEndianess();                // Get processor endianess
532
533         // If commands were passed in, process them
534         if (argc > 1)
535                 return Process(argc - 1, argv + 1);              
536
537         DisplayVersion();
538         DisplayHelp();
539
540         return 0;
541 }
542