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