2 // RMAC - Renamed Macro Assembler for all Atari computers
3 // RMAC.C - Main Application Code
4 // Copyright (C) 199x Landon Dyer, 2011-2022 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
27 int perm_verb_flag; // Permanently verbose, interactive mode
28 int list_flag; // "-l" listing flag on command line
29 int list_pag = 1; // Enable listing pagination by default
30 int verb_flag; // Be verbose about what's going on
31 int m6502; // 1, assembling 6502 code
32 int glob_flag; // Assume undefined symbols are global
33 int lsym_flag; // Include local symbols in object file (ALWAYS true)
34 int optim_warn_flag; // Warn about possible short branches
35 int prg_flag; // !=0, produce .PRG executable (2=symbols)
36 int prg_extend; // !=0, output extended .PRG symbols
37 int legacy_flag; // Do stuff like insert code in RISC assembler
38 int obj_format; // Object format flag
39 int debug; // [1..9] Enable debugging levels
40 int err_flag; // '-e' specified
41 int err_fd; // File to write error messages to
42 int rgpu, rdsp; // Assembling Jaguar GPU or DSP code
43 int robjproc; // Assembling Jaguar Object Processor code
44 int dsp56001; // Assembling DSP 56001 code
45 int list_fd; // File to write listing to
46 int segpadsize; // Segment padding size
47 int endian; // Host processor endianess (0 = LE, 1 = BE)
48 int *regbase; // Points to current DFA register table (base)
49 int *regtab; // Points to current DFA register table (tab)
50 int *regcheck; // Points to current DFA register table (check)
51 int *regaccept; // Points to current DFA register table (accept)
52 char * objfname; // Object filename pointer
53 char * firstfname; // First source filename
54 char * cmdlnexec; // Executable name, pointer to ARGV[0]
55 char searchpatha[512] = { 0 }; // Buffer to hold searchpath when specified
56 char * searchpath = NULL; // Search path for include files
57 char defname[] = "noname.o"; // Default output filename
58 int optim_flags[OPT_COUNT_ALL] = { 0 }; // Specific optimisations on/off matrix
59 int activecpu = CPU_68000; // Active 68k CPU (68000 by default)
60 int activefpu = FPU_NONE; // Active FPU (none by default)
61 int org68k_active = 0; // .org switch for 68k (only with RAW output format)
62 uint32_t org68k_address; // .org for 68k
63 int correctMathRules; // 1, use C operator precedence in expressions
66 // Convert a string to uppercase
68 void strtoupper(char * s)
75 // Manipulate file extension.
77 // 'name' must be large enough to hold any possible filename. If 'stripp' is
78 // nonzero, any old extension is removed. If the file does not already have an
79 // extension, 'extension' is appended to the filename.
81 char * fext(char * name, char * extension, int stripp)
85 // Find beginning of "real" name (strip off path)
86 char * beg = strrchr(name, SLASHCHAR);
91 // Clobber any old extension, if requested
94 for(s=beg; *s && *s!='.'; ++s)
100 if (strrchr(beg, '.') == NULL)
101 strcat(beg, extension);
106 static int is_sep(char c)
108 const char *seps = PATH_SEPS;
110 for (seps = PATH_SEPS; *seps; seps++) {
119 // Return 'item'nth element of semicolon-seperated pathnames specified in the
120 // enviroment string 's'. Copy the pathname to 'buf'. Return 0 if the 'item'
121 // nth path doesn't exist.
123 // ['item' ranges from 0 to N-1, where N = #elements in search path]
125 int nthpath(char * env_var, int itemno, char * buf)
127 char * s = searchpath;
136 while (*s != EOS && !is_sep(*s++))
142 while (*s != EOS && !is_sep(*s))
151 // Display command line help
153 void DisplayHelp(void)
156 " %s [options] srcfile\n"
159 " -? or -h Display usage information\n"
160 " -dsymbol[=value] Define symbol (with optional value, default=0)\n"
161 " -e[errorfile] Send error messages to file, not stdout\n"
162 " -f[format] Output object file format\n"
164 " b: BSD (use this for Jaguar)\n"
166 " p: P56 (use this for DSP56001 only)\n"
167 " l: LOD (use this for DSP56001 only)\n"
168 " x: com/exe/xex (Atari 800)\n"
169 " r: absolute address\n"
170 " -i[path] Directory to search for include files\n"
171 " -l[filename] Create an output listing file\n"
172 " -l*[filename] Create an output listing file without pagination\n"
173 " -m[cpu] Select default CPU. Available options:\n"
174 " 68000, 68020, 68030, 68040, 68060, 6502, tom, jerry, 56001\n"
175 " -n Don't do things behind your back in RISC assembler\n"
176 " -o file Output file name\n"
177 " +o[value] Turn a specific optimisation on\n"
178 " Available optimisation switches:\n"
179 " o0: Absolute long addresses to word\n"
180 " o1: move.l #x,dn/an to moveq\n"
181 " o2: Word branches to short\n"
182 " o3: Outer displacement 0(an) to (an)\n"
183 " o4: lea size(An),An to addq #size,An\n"
184 " o5: 68020+ Absolute long base/outer disp. to word\n"
185 " o6: Null branches to NOP\n"
186 " o7: clr.l Dx to moveq #0,Dx\n"
187 " o8: adda.w/l #x,Dy to addq.w/l #x,Dy\n"
188 " o9: adda.w/l #x,Ay to lea x(Dy),Ay\n"
189 " o10: 56001 Use short format for immediate values if possible\n"
190 " o11: 56001 Auto convert short addressing mode to long (default: on)\n"
191 " o30: Enforce PC relative (alternative name: op)\n"
192 " ~o[value] Turn a specific optimisation off\n"
193 " +oall Turn all optimisations on\n"
194 " ~oall Turn all optimisations off\n"
195 " -p Create an ST .prg (without symbols). Forces -fa\n"
196 " -ps Create an ST .prg (with symbols). Forces -fa\n"
197 " -px Create an ST .prg (with exsymbols). Forces -fa\n"
198 " -r[size] Pad segments to boundary size specified\n"
199 " w: word (2 bytes, default alignment)\n"
200 " l: long (4 bytes)\n"
201 " p: phrase (8 bytes)\n"
202 " d: double phrase (16 bytes)\n"
203 " q: quad phrase (32 bytes)\n"
204 " -s Warn about possible short branches\n"
205 " and applied optimisations\n"
206 " -u Force referenced and undefined symbols global\n"
207 " -v Set verbose mode\n"
208 " -x Turn on debugging mode\n"
209 " -y[pagelen] Set page line length (default: 61)\n"
210 " -4 Use C style operator precedence\n"
216 // Display version information
218 void DisplayVersion(void)
221 " _ __ _ __ ___ __ _ ___ \n"
222 "| '__| '_ ` _ \\ / _` |/ __|\n"
223 "| | | | | | | | (_| | (__ \n"
224 "|_| |_| |_| |_|\\__,_|\\___|\n"
225 "\nRenamed Macro Assembler\n"
226 "Copyright (C) 199x Landon Dyer, 2011-2022 Reboot and Friends\n"
227 "V%01i.%01i.%01i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
231 // Parse optimisation options
233 int ParseOptimization(char * optstring)
239 if (*optstring == '+')
241 else if (*optstring != '~')
244 if (optstring[2] == 0)
245 return error(".opt called with zero arguments");
247 if ((optstring[2] == 'a' || optstring[2] == 'A')
248 && (optstring[3] == 'l' || optstring[3] == 'L')
249 && (optstring[4] == 'l' || optstring[4] == 'L'))
251 memset(optim_flags, onoff, OPT_COUNT * sizeof(int));
254 else if (optstring[1] == 'o' || optstring[1] == 'O') // Turn on specific optimisation
256 if (optstring[2] == 'p' || optstring[2] == 'P')
258 optim_flags[OPT_PC_RELATIVE] = onoff;
263 int opt_no = atoi(&optstring[2]);
265 if ((opt_no >= 0) && (opt_no < OPT_COUNT))
267 optim_flags[opt_no] = onoff;
270 // If opt_no is 2 digits then consume an extra character.
271 // Sounds a bit sleazy but we know we're not going to hit
272 // more than 100 optimisation switches so this should be
273 // fine. If we do hit that number then it'll probably be
274 // time to burn the whole codebase and start from scratch.
287 if (*optstring == ',')
293 extern int reg68base[53];
294 extern int reg68tab[222];
295 extern int reg68check[222];
296 extern int reg68accept[222];
299 // Process command line arguments and do an assembly
301 int Process(int argc, char ** argv)
303 int argno; // Argument number
304 SYM * sy; // Pointer to a symbol record
305 char * s; // String pointer
306 int fd; // File descriptor
307 char fnbuf[FNSIZ]; // Filename buffer
309 int current_path_index = 0; // Iterator for search paths
311 errcnt = 0; // Initialize error count
312 listing = 0; // Initialize listing level
313 list_flag = 0; // Initialize listing flag
314 verb_flag = perm_verb_flag; // Initialize verbose flag
315 glob_flag = 0; // Initialize .globl flag
316 optim_warn_flag = 0; // Initialize short branch flag
317 debug = 0; // Initialize debug flag
318 objfname = NULL; // Initialize object filename
319 list_fname = NULL; // Initialize listing filename
320 err_fname = NULL; // Initialize error filename
321 obj_format = BSD; // Initialize object format
322 firstfname = NULL; // Initialize first filename
323 err_fd = ERROUT; // Initialize error file descriptor
324 err_flag = 0; // Initialize error flag
325 rgpu = 0; // Initialize GPU assembly flag
326 rdsp = 0; // Initialize DSP assembly flag
327 robjproc = 0; // Initialize OP assembly flag
328 lsym_flag = 1; // Include local symbols in object file
329 orgactive = 0; // Not in RISC org section
330 orgwarning = 0; // No ORG warning issued
331 segpadsize = 2; // Initialize segment padding size
332 dsp_orgmap[0].start = 0; // Initialize 56001 org initial address
333 dsp_orgmap[0].memtype = ORG_P; // Initialize 56001 org start segment
334 m6502 = 0; // 6502 mode off by default
335 regbase = reg68base; // Initialise DFA register tables
336 regtab = reg68tab; // Idem
337 regcheck = reg68check; // Idem
338 regaccept = reg68accept; // Idem
339 correctMathRules = 0; // respect operator precedence
340 // Initialize modules
341 InitSymbolTable(); // Symbol table
342 InitTokenizer(); // Tokenizer
343 InitLineProcessor(); // Line processor
344 InitExpression(); // Expression analyzer
345 InitSection(); // Section manager / code generator
346 InitMark(); // Mark tape-recorder
347 InitMacro(); // Macro processor
348 InitListing(); // Listing generator
349 Init6502(); // 6502 assembler
351 // Process command line arguments and assemble source files
352 for(argno=0; argno<argc; argno++)
354 if (*argv[argno] == '-')
356 switch (argv[argno][1])
359 correctMathRules = 1;
361 case 'd': // Define symbol
363 for(s=argv[argno]+2; *s!=EOS;)
372 if (argv[argno][2] == EOS)
374 printf("-d: empty symbol\n");
379 sy = lookup(argv[argno] + 2, 0, 0);
383 sy = NewSymbol(argv[argno] + 2, LABEL, 0);
387 sy->sattr = DEFINED | EQUATED | ABS;
388 sy->svalue = (*s ? (uint64_t)atoi(s) : 0);
390 case 'e': // Redirect error message output
392 err_fname = argv[argno] + 2;
394 case 'f': // -f<format>
396 switch (argv[argno][2])
399 case 'a': // -fa = Alcyon [the default]
403 case 'b': // -fb = BSD (Jaguar Recommended: 3 out 4 jaguars recommend it!)
407 case 'e': // -fe = ELF
411 case 'l': // -fl = LOD
415 case 'p': // -fp = P56
419 case 'x': // -fx = COM/EXE/XEX
423 case 'r': // -fr = Absolute address
428 printf("-f: unknown object format specified\n");
433 case 'g': // Debugging flag
435 printf("Debugging flag (-g) not yet implemented\n");
437 case 'i': // Set directory search path
440 strcat(searchpatha, argv[argno] + 2);
441 strcat(searchpatha, ";");
442 searchpath = searchpatha;
444 // Check to see if include paths actually exist
445 char current_path[256];
447 for(i=current_path_index; nthpath("RMACPATH", i, current_path)!=0; i++)
449 if (strlen(current_path) > 0)
451 DIR * test = opendir(current_path);
455 printf("Invalid include path: %s\n", current_path);
464 current_path_index = i - 1;
467 case 'l': // Produce listing file
469 if (*(argv[argno] + 2) == '*')
471 list_fname = argv[argno] + 3;
472 list_pag = 0; // Special case - turn off pagination
476 list_fname = argv[argno] + 2;
485 if (strcmp(argv[argno] + 2, "68000") == 0)
487 else if (strcmp(argv[argno] + 2, "68020") == 0)
489 else if (strcmp(argv[argno] + 2, "68030") == 0)
491 else if (strcmp(argv[argno] + 2, "68040") == 0)
493 else if (strcmp(argv[argno] + 2, "68060") == 0)
495 else if (strcmp(argv[argno] + 2, "68881") == 0)
497 else if (strcmp(argv[argno] + 2, "68882") == 0)
499 else if (strcmp(argv[argno] + 2, "56001") == 0)
501 else if (strcmp(argv[argno] + 2, "6502") == 0)
503 else if (strcmp(argv[argno] + 2, "tom") == 0)
505 else if (strcmp(argv[argno] + 2, "jerry") == 0)
509 printf("Unrecognized CPU '%s'\n", argv[argno] + 2);
514 case 'o': // Direct object file output
516 if (argv[argno][2] != EOS)
517 objfname = argv[argno] + 2;
522 printf("Missing argument to -o");
527 objfname = argv[argno];
531 case 'p': /* -p: generate ".PRG" executable output */
534 * -p .PRG generation w/o symbols
535 * -ps .PRG generation with symbols
536 * -px .PRG generation with extended symbols
538 switch (argv[argno][2])
555 printf("-p: syntax error\n");
560 // Enforce Alcyon object format - kind of silly
561 // to ask for .prg output without it!
564 case 'r': // Pad seg to requested boundary size
566 switch(argv[argno][2])
568 case 'w': case 'W': segpadsize = 2; break;
569 case 'l': case 'L': segpadsize = 4; break;
570 case 'p': case 'P': segpadsize = 8; break;
571 case 'd': case 'D': segpadsize = 16; break;
572 case 'q': case 'Q': segpadsize = 32; break;
573 default: segpadsize = 2; break; // Effective autoeven();
576 case 's': // Warn about possible short branches and applied optimisations
580 case 'u': // Make undefined symbols .globl
584 case 'v': // Verbose flag
592 case 'x': // Turn on debugging
595 printf("~ Debugging ON\n");
597 case 'y': // -y<pagelen>
599 pagelen = atoi(argv[argno] + 2);
603 printf("-y: bad page length\n");
609 case EOS: // Input is stdin
610 if (firstfname == NULL) // Kludge first filename
611 firstfname = defname;
613 include(0, "(stdin)");
616 case 'h': // Display command line usage
623 case 'n': // Turn off legacy mode
626 printf("Legacy mode OFF\n");
630 printf("Unknown switch: %s\n\n", argv[argno]);
636 else if (*argv[argno] == '+' || *argv[argno] == '~')
638 if (ParseOptimization(argv[argno]) != OK)
641 printf("Unknown switch: %s\n\n", argv[argno]);
649 // Record first filename.
650 if (firstfname == NULL)
651 firstfname = argv[argno];
653 strcpy(fnbuf, argv[argno]);
654 fext(fnbuf, ".s", 0);
659 printf("Cannot open: %s\n", fnbuf);
669 // Wind-up processing;
670 // o save current section (no more code generation)
671 // o do auto-even of all sections (or boundary alignment as requested
673 // o save the last pc value for 6502 (if we used 6502 at all) and
674 // detemine if the last section contains anything
675 // o determine name of object file:
676 // - "foo.o" for linkable output;
677 // - "foo.prg" for GEMDOS executable (-p flag).
679 int temp_section = cursect;
681 for(i=TEXT; i<=BSS; i<<=1)
687 case 2: d_even(); break;
688 case 4: d_long(); break;
689 case 8: d_phrase(); break;
690 case 16: d_dphrase(); break;
691 case 32: d_qphrase(); break;
697 SwitchSection(M6502);
699 if (sloc != currentorg[0])
701 currentorg[1] = sloc;
705 // This looks like an awful kludge... !!! FIX !!!
706 if (temp_section & (M56001P | M56001X | M56001Y))
708 SwitchSection(temp_section);
710 if (chptr != dsp_currentorg->start)
712 dsp_currentorg->end = chptr;
719 if (objfname == NULL)
721 if (firstfname == NULL)
722 firstfname = defname;
724 strcpy(fnbuf, firstfname);
725 fext(fnbuf, (prg_flag ? ".prg" : ".o"), 1);
729 // With one pass finished, go back and:
730 // (1) run through all the fixups and resolve forward references;
731 // (1.5) ensure that remaining fixups can be handled by the linker
732 // (`lo68' format, extended (postfix) format....)
733 // (2) generate the output file image and symbol table;
734 // (3) generate relocation information from left-over fixups.
735 ResolveAllFixups(); // Do all fixups
736 StopMark(); // Stop mark tape-recorder
740 if ((fd = open(objfname, _OPEN_FLAGS, _PERM_MODE)) < 0)
741 CantCreateFile(objfname);
745 s = (prg_flag ? "executable" : "object");
746 printf("[Writing %s file: %s]\n", s, objfname);
759 printf("[Wrapping-up listing file]\n");
769 DEBUG dump_everything();
775 // Determine processor endianess
777 int GetEndianess(void)
780 char * p = (char *)&i;
789 // Application entry point
791 int main(int argc, char ** argv)
793 perm_verb_flag = 0; // Clobber "permanent" verbose flag
794 legacy_flag = 1; // Default is legacy mode on (:-P)
795 optim_flags[OPT_56K_SHORT] = 1; // This ensures compatibilty with Motorola's 56k assembler
797 cmdlnexec = argv[0]; // Obtain executable name
798 endian = GetEndianess(); // Get processor endianess
800 // If commands were passed in, process them
802 return Process(argc - 1, argv + 1);