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
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 obj_format; // Object format flag
33 int debug; // [1..9] Enable debugging levels
34 int err_flag; // '-e' specified
35 int err_fd; // File to write error messages to
36 int rgpu, rdsp; // Assembling Jaguar GPU or DSP code
37 int list_fd; // File to write listing to
38 int regbank; // RISC register bank
39 int segpadsize; // Segment padding size
40 int in_main; // In main memory flag for GPUMAIN
41 int endian; // Host processor endianess
42 char * objfname; // Object filename pointer
43 char * firstfname; // First source filename
44 char * cmdlnexec; // Executable name, pointer to ARGV[0]
45 char * searchpath; // Search path for include files
46 char defname[] = "noname.o"; // Default output filename
48 // Under Windows and UNIX malloc() is an expensive call, so for small amounts
49 // of memory we allocate from a previously allocated buffer.
51 #define A_AMOUNT 4096 // Amount to malloc() at a time
52 #define A_THRESH 64 // Use malloc() for amounts >= A_THRESH
54 static LONG a_amount; // Amount left at a_ptr
55 static char * a_ptr; // Next free chunk
56 LONG amemtot; // amem() total of requests
58 // Qsort; The THRESHold below is the insertion sort threshold, and has been adjusted
59 // for records of size 48 bytes.The MTHREShold is where we stop finding a better median.
61 #define THRESH 4 // Threshold for insertion
62 #define MTHRESH 6 // Threshold for median
64 static int (*qcmp)(); // The comparison routine
65 static int qsz; // Size of each record
66 static int thresh; // THRESHold in chars
67 static int mthresh; // MTHRESHold in chars
71 // qst: Do a quicksort. First, find the median element, and put that one in the
72 // first place as the discriminator. (This "median" is just the median of the
73 // first, last and middle elements). (Using this median instead of the first
74 // element is a big win). Then, the usual partitioning/swapping, followed by
75 // moving the discriminator into the right place. Then, figure out the sizes of
76 // the two partions, do the smaller one recursively and the larger one via a
77 // repeat of this code. Stopping when there are less than THRESH elements in a
78 // partition and cleaning up with an insertion sort (in our caller) is a huge
79 // win. All data swaps are done in-line, which is space-losing but time-saving.
80 // (And there are only three places where this is done).
82 static int qst(char * base, char * max)
84 char c, * i, * j, * jj;
90 * At the top here, lo is the number of characters of elements in the
91 * current partition. (Which should be max - base).
92 * Find the median of the first, last, and middle element and make
93 * that the middle element. Set j to largest of first and middle.
94 * If max is larger than that guy, then it's that guy, else compare
95 * max with loser of first and take larger. Things are set up to
96 * prefer the middle, then the first in case of ties.
98 lo = max - base; /* number of elements as chars */
102 mid = i = base + qsz * ((lo / qsz) >> 1);
106 j = (qcmp((jj = base), i) > 0 ? jj : i);
108 if (qcmp(j, (tmp = max - qsz)) > 0)
110 /* switch to first loser */
111 j = (j == jj ? i : jj);
113 if (qcmp(j, tmp) < 0)
132 * Semi-standard quicksort partitioning/swapping
134 for(i=base, j=max-qsz; ;)
136 while (i < mid && qcmp(i, mid) <= 0)
141 if (qcmp(mid, j) <= 0)
147 tmp = i + qsz; /* value of i after swap */
151 /* j <-> mid, new mid is j */
170 /* i <-> mid, new mid is i */
172 tmp = mid = i; /* value of i after swap */
190 * Look at sizes of the two partitions, do the smaller
191 * one first by recursion, then do the larger one by
192 * making sure lo is its size, base and max are update
193 * correctly, and branching back. But only repeat
194 * (recursively or by branching) if the partition is
195 * of at least size THRESH.
199 if ((lo = j - base) <= (hi = max - i))
215 while (lo >= thresh);
223 * First, set up some global parameters for qst to share. Then, quicksort
224 * with qst(), and then a cleanup insertion sort ourselves. Sound simple?
227 int rmac_qsort(char * base, int n, int size, int (*compar)())
229 register char c, * i, * j, * lo, * hi;
237 thresh = qsz * THRESH;
238 mthresh = qsz * MTHRESH;
239 max = base + n * qsz;
252 * First put smallest element, which must be in the first THRESH, in
253 * the first position as a sentinel. This is done just by searching
254 * the first THRESH elements (or the first n if n < THRESH), finding
255 * the min, and swapping it into the first position.
257 for(j=lo=base; (lo+=qsz)<hi;)
265 /* swap j into place */
266 for(i=base, hi=base+qsz; i<hi;)
275 * With our sentinel in place, we now run the following hyper-fast
276 * insertion sort. For each remaining element, min, from [1] to [n-1],
277 * set hi to the index of the element AFTER which this one goes.
278 * Then, do the standard insertion sort shift on a character at a time
279 * basis for each element in the frob.
281 for(min=base; (hi=min+=qsz)<max;)
283 while (qcmp(hi -= qsz, min) > 0)
286 if ((hi += qsz) != min)
288 for(lo=min+qsz; --lo>=min;)
292 for(i=j=lo; (j-=qsz)>=hi; i=j)
305 // Allocate memory; Panic and Quit if we Run Out
307 char * amem(LONG amount)
311 // if (amount & 1) // Keep word alignment
313 amount = (amount + 1) & ~(0x01); // Keep word alignment
315 // Honor *small* request (< 64 bytes)
316 if (amount < A_THRESH)
318 if (a_amount < amount)
320 a_ptr = amem(A_AMOUNT); // Allocate 4K bytes
330 amemtot += amount; // Bump total alloc
331 p = (char *)malloc(amount); // Get memory from malloc
334 fatal("Memory exhausted!");
336 memset(p, 0, amount);
344 // Copy stuff around, return pointer to dest+count+1 (doesn't handle overlap)
346 char * copy(char * dest, char * src, LONG count)
356 // Clear a region of memory
358 void clear(char * dest, LONG count)
366 // Check to see if the string is a keyword. Returns -1, or a value from the
369 int kmatch(char * p, int * base, int * check, int * tab, int * accept)
374 for(state=0; state>=0;)
376 j = base[state] + (int)tolowertab[*p];
378 if (check[j] != state)
379 { // Reject, character doesn't match
380 state = -1; // No match
385 { // Must accept or reject at EOS
386 state = accept[j]; // (-1 on no terminal match)
398 // Auto-even a section
400 void autoeven(int sect)
409 // Manipulate file extension.
410 // `name' must be large enough to hold any possible filename.
411 // If `stripp' is nonzero, any old extension is removed.
412 // Then, if the file does not already have an extension,
413 // `extension' is appended to the filename.
415 char * fext(char * name, char * extension, int stripp)
417 char * s, * beg; // String pointers
419 // Find beginning of "real" name
420 beg = name + strlen(name) - 1;
422 for(; beg>name; --beg)
424 if (*beg == SLASHCHAR)
432 { // Clobber any old extension
433 for(s=beg; *s && *s!='.'; ++s)
439 for(s=beg; *s!='.'; ++s)
442 { // Append the new extension
443 strcat(beg, extension);
453 // Return `item'nth element of semicolon-seperated pathnames specified in the
454 // enviroment string `s'. Copy the pathname to `buf'. Return 0 if the `item'
455 // nth path doesn't exist.
457 // [`item' ranges from 0 to N-1, where N = #elements in search path]
459 int nthpath(char * env_var, int itemno, char * buf)
461 char * s = searchpath;
470 while (*s != EOS && *s++ != ';')
476 while (*s != EOS && *s != ';')
486 // Display Command Line Help
488 void display_help(void)
491 printf(" %s [options] srcfile\n", cmdlnexec);
493 printf("Options:\n");
494 printf(" -? or -h display usage information\n");
495 printf(" -dsymbol[=value] define symbol\n");
496 printf(" -e[errorfile] send error messages to file, not stdout\n");
497 printf(" -f[format] output object file format\n");
498 printf(" b: BSD (use this for Jaguar)\n");
499 printf(" -i[path] directory to search for include files\n");
500 printf(" -l[filename] create an output listing file\n");
501 printf(" -o file output file name\n");
502 printf(" -r[size] pad segments to boundary size specified\n");
503 printf(" w: word (2 bytes, default alignment)\n");
504 printf(" l: long (4 bytes)\n");
505 printf(" p: phrase (8 bytes)\n");
506 printf(" d: double phrase (16 bytes)\n");
507 printf(" q: quad phrase (32 bytes)\n");
508 printf(" -s warn about possible short branches\n");
509 printf(" -u force referenced and undefined symbols global\n");
510 printf(" -v set verbose mode\n");
511 printf(" -y[pagelen] set page line length (default: 61)\n");
517 // Display Version Information
519 void display_version(void)
521 printf("\nReboot's Macro Assembler for Atari Jaguar\n");
522 printf("Copyright (C) 199x Landon Dyer, 2011 Reboot\n");
523 printf("V%01i.%01i.%01i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
528 // Process Command Line Arguments and do an Assembly
530 int process(int argc, char ** argv)
532 int argno; // Argument number
533 SYM * sy; // Pointer to a symbol record
534 char * s; // String pointer
535 int fd; // File descriptor
536 char fnbuf[FNSIZ]; // Filename buffer
539 errcnt = 0; // Initialise error count
540 listing = 0; // Initialise listing level
541 list_flag = 0; // Initialise listing flag
542 verb_flag = perm_verb_flag; // Initialise verbose flag
543 as68_flag = 0; // Initialise as68 kludge mode
544 glob_flag = 0; // Initialise .globl flag
545 sbra_flag = 0; // Initialise short branch flag
546 debug = 0; // Initialise debug flag
547 searchpath = NULL; // Initialise search path
548 objfname = NULL; // Initialise object filename
549 list_fname = NULL; // Initialise listing filename
550 err_fname = NULL; // Initialise error filename
551 obj_format = BSD; // Initialise object format
552 firstfname = NULL; // Initialise first filename
553 err_fd = ERROUT; // Initialise error file descriptor
554 err_flag = 0; // Initialise error flag
555 rgpu = 0; // Initialise GPU assembly flag
556 rdsp = 0; // Initialise DSP assembly flag
557 lsym_flag = 1; // Include local symbols in object file
558 regbank = BANK_N; // No RISC register bank specified
559 orgactive = 0; // Not in RISC org section
560 orgwarning = 0; // No ORG warning issued
562 segpadsize = 2; // Initialise segment padding size
565 // Initialise modules
566 InitSymbolTable(); // Symbol table
567 init_token(); // Tokenizer
568 init_procln(); // Line processor
569 init_expr(); // Expression analyzer
570 init_sect(); // Section manager / code generator
571 init_mark(); // Mark tape-recorder
572 InitMacro(); // Macro processor
573 init_list(); // Listing generator
575 // Process command line arguments and assemble source files
576 for(argno = 0; argno < argc; ++argno)
578 if (*argv[argno] == '-')
580 switch (argv[argno][1])
582 case 'd': // Define symbol
584 for(s=argv[argno]+2; *s!=EOS;)
593 if (argv[argno][2] == EOS)
595 printf("-d: empty symbol\n");
600 sy = lookup(argv[argno] + 2, 0, 0);
604 sy = NewSymbol(argv[argno] + 2, LABEL, 0);
608 sy->sattr = DEFINED | EQUATED | ABS;
611 sy->svalue = (VALUE)atoi(s);
616 case 'e': // Redirect error message output
618 err_fname = argv[argno] + 2;
620 case 'f': // -f<format>
622 switch (argv[argno][2])
625 case 'b': // -fb = BSD (Jaguar Recommended)
630 printf("-f: unknown object format specified\n");
635 case 'g': // Debugging flag
637 printf("Debugging flag (-g) not yet implemented\n");
639 case 'i': // Set directory search path
641 searchpath = argv[argno] + 2;
643 case 'l': // Produce listing file
645 list_fname = argv[argno] + 2;
650 case 'o': // Direct object file output
652 if (argv[argno][2] != EOS)
653 objfname = argv[argno] + 2;
658 printf("Missing argument to -o");
662 objfname = argv[argno];
666 case 'r': // Pad seg to requested boundary size
668 switch(argv[argno][2])
670 case 'w': case 'W': segpadsize = 2; break;
671 case 'l': case 'L': segpadsize = 4; break;
672 case 'p': case 'P': segpadsize = 8; break;
673 case 'd': case 'D': segpadsize = 16; break;
674 case 'q': case 'Q': segpadsize = 32; break;
675 default: segpadsize = 2; break; // Effective autoeven();
678 case 's': // Warn about possible short branches
682 case 'u': // Make undefined symbols .globl
686 case 'v': // Verbose flag
694 case 'x': // Turn on debugging
697 printf("~ Debugging ON\n");
699 case 'y': // -y<pagelen>
701 pagelen = atoi(argv[argno] + 2);
705 printf("-y: bad page length\n");
711 case EOS: // Input is stdin
712 if (firstfname == NULL) // Kludge first filename
713 firstfname = defname;
715 include(0, "(stdin)");
718 case 'h': // Display command line usage
727 printf("Unknown switch: %s\n\n", argv[argno]);
735 // Record first filename.
736 if (firstfname == NULL)
737 firstfname = argv[argno];
739 strcpy(fnbuf, argv[argno]);
740 fext(fnbuf, ".s", 0);
745 printf("Cannot open: %s\n", fnbuf);
755 // Wind-up processing;
756 // o save current section (no more code generation)
757 // o do auto-even of all sections (or boundary alignment as requested through '-r')
758 // o determine name of object file:
759 // - "foo.o" for linkable output;
760 // - "foo.prg" for GEMDOS executable (-p flag).
763 for(i=TEXT; i<=BSS; i<<=1)
769 case 2: d_even(); break;
770 case 4: d_long(); break;
771 case 8: d_phrase(); break;
772 case 16: d_dphrase(); break;
773 case 32: d_qphrase(); break;
779 if (objfname == NULL)
781 if (firstfname == NULL)
782 firstfname = defname;
784 strcpy(fnbuf, firstfname);
785 //fext(fnbuf, prg_flag ? ".prg" : ".o", 1);
786 fext(fnbuf, ".o", 1);
790 // With one pass finished, go back and:
791 // (1) run through all the fixups and resolve forward references;
792 // (1.5) ensure that remaining fixups can be handled by the linker
793 // (`lo68' format, extended (postfix) format....)
794 // (2) generate the output file image and symbol table;
795 // (3) generate relocation information from left-over fixups.
796 ResolveAllFixups(); // Do all fixups
797 stopmark(); // Stop mark tape-recorder
801 if ((fd = open(objfname, _OPEN_FLAGS, _PERM_MODE)) < 0)
807 printf("[Writing %s file: %s]\n", s, objfname);
820 printf("[Wrapping-up listing file]\n");
830 DEBUG dump_everything();
837 // Determine Processor Endianess
839 int get_endianess(void)
842 char * p = (char *)&i;
852 // Application Entry Point; Handle the Command Line
854 int main(int argc, char ** argv)
859 perm_verb_flag = 0; // Clobber "permanent" verbose flag
860 cmdlnexec = argv[0]; // Obtain executable name
862 endian = get_endianess(); // Get processor endianess
864 for(i=0; i<MAXFWDJUMPS; i++)
867 // Full command line passed
870 status = process(argc - 1, argv + 1);